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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(voice): add experimental ChatGPT subscription realtime
Ruben Lütke41afbdc6a484
diff --git a/docs/codex-subscription-realtime-voice.md b/docs/codex-subscription-realtime-voice.mdnew file mode 100644index 0000000000..adbdfe39f3--- /dev/null+++ b/docs/codex-subscription-realtime-voice.md@@ -0,0 +1,153 @@+# ChatGPT-plan realtime voice through Codex++Status: experimental, opt-in, and pinned to Codex CLI 0.146.0+Last verified: 2026-07-31++## Bottom line++ChatGPT Voice is not exposed as a general-purpose subscription API. Codex does,+however, expose an official experimental realtime surface through+`codex app-server`. It can create a WebRTC voice session while authenticated+with a ChatGPT account. That gives Jarvis a legitimate subscription-routed+transport without automating chatgpt.com, borrowing browser cookies, copying+tokens from another Codex profile, or pretending that an API key is covered by+a ChatGPT subscription.++This is not a promise of unlimited or zero-cost voice. OpenAI controls the plan+allowance and describes Codex and connected Voice as drawing from plan-specific+usage pools. The important billing boundary in Jarvis is simpler: this provider+uses the dedicated ChatGPT login only, while the existing OpenAI Realtime+provider continues to use metered API billing. Jarvis never crosses between the+two silently.++## Why this path is acceptable++The implementation uses documented Codex app-server operations:++- `account/read` confirms that the live process is using ChatGPT authentication+ and reports the plan type.+- `thread/start` creates an ephemeral transport-only thread.+- `thread/realtime/start` accepts a browser-created WebRTC offer and returns the+ answer through a realtime notification.+- `thread/realtime/appendSpeech`, `appendText`, `stop`, and the realtime event+ stream carry Jarvis responses, transcripts, and lifecycle signals.++OpenAI marks the realtime methods as experimental and gives them no backwards-+compatibility guarantee. Jarvis therefore treats the integration as a+versioned adapter, not as a stable protocol that can float with any installed+Codex release.++## Runtime design++```mermaid+flowchart LR+ UI["Jarvis desktop WebView\nmic + playback"]+ Broker["Loopback offer broker\none-time desktop capability"]+ Provider["Codex subscription\nRealtimeProvider"]+ AppServer["Pinned codex app-server\ndedicated profile"]+ Voice["OpenAI realtime voice\nthrough ChatGPT plan"]+ Brain["Jarvis brain + tools\nnormal safety boundary"]++ UI <-->|"one-time WebRTC SDP"| Broker+ Broker <-->|"offer lease + answer"| Provider+ Provider <-->|"JSONL control + sideband PCM"| AppServer+ AppServer <-->|"authenticated session + WebRTC signaling"| Voice+ Voice -.->|"negotiated RTP track (detached)"| UI+ Provider <-->|"client-managed handoffs"| Brain+```++The browser/WebView owns the peer connection, while scrubbed sideband PCM stays+on Jarvis's low-latency playback path. Codex uses client-managed handoffs: the+realtime model can answer direct conversational turns, but it is not allowed to+act as a second action-capable assistant. Requests that need memory or tools+return to the ordinary Jarvis brain and ToolExecutor; the resulting safe,+scrubbed text is sent back for speech.++## Billing and fallback rules++| Selection | Authentication | Charging authority | Failure behavior |+|---|---|---|---|+| ChatGPT subscription (Codex) | Dedicated ChatGPT login | ChatGPT/Codex plan limits and any connected-Voice rules set by OpenAI | Stop honestly; never inject an API key |+| OpenAI Realtime | Dedicated or compatible OpenAI API key | OpenAI API usage billing | Follow the user's explicit realtime fallback configuration |+| Other realtime provider | That provider's credential | That provider's billing model | Follow the user's explicit realtime fallback configuration |++Selecting the subscription provider is explicit and requires an experimental-+feature acknowledgement. API Realtime remains a separate selectable provider.+An API provider can be an explicit fallback, but it is never an implicit billing+escape hatch.++This selection covers the realtime voice session and its direct conversational+replies. If a request is handed to Jarvis's separately configured brain or a+tool provider, that provider keeps its own authentication, limits, and billing.+The subscription transport never relabels those calls as ChatGPT-plan usage.++## Credential and process boundaries++The dedicated login lives under Jarvis's data directory in+`codex-subscription-voice`. It is not the user's normal Codex profile. Jarvis+allows only its marker plus the exact files the pinned Codex binary owns:+`auth.json`, a persistent UUID in `installation_id`, and the bounded+`tmp/arg0` process-launch tree. Codex sends that UUID as a pseudonymous+installation identifier. Jarvis never copies or links credentials into a+second runtime profile. Unexpected config, session, agent, or model files make+startup fail closed, and unsafe linked, reparse-point, or multiply-linked+entries are rejected.++At process launch Jarvis:++1. Requires the exact official Codex 0.146.0 native executable and verifies its+ SHA-256. The first experimental release is enabled on Windows only because+ its Job Object provides kernel-enforced kill-on-parent-exit containment.+2. Forces file-backed auth and strips inherited OpenAI/API billing credentials,+ proxy/provider variables, and keyring-session variables.+3. Supplies isolated temporary home, app-data, log, database, model-catalog,+ prompt, and working directories.+4. Starts app-server with strict configuration and a Jarvis-owned loopback sink+ as the unusable normal model provider.+5. Audits effective config layers, origins, managed requirements, the live+ ChatGPT account, and the returned ephemeral thread before enabling realtime.+6. Starts the thread with no tools, no writable workspace, no roots, no web+ search, no provider fallback, and no startup context.+7. Reaps the whole child process tree and validates Codex's exact+ runtime-artifact layout before and after use. On graceful exit, Codex's own+ locked guard removes the per-process `tmp/arg0` directory; after a crash,+ Codex's next-start lock-aware janitor removes stale directories. Jarvis does+ not race that lock by deleting the tree itself. The non-secret+ `installation_id` remains stable for stock Codex compatibility.++Only personal ChatGPT plan types accepted by the audited protocol are enabled.+Managed workspace accounts are refused because their policy and compliance+requirements cannot safely be inferred by this experimental client.++## Setup and platform behavior++The user installs the supported Codex CLI, opens Providers in Jarvis, and uses+the subscription voice card's Connect action. That launches a fresh interactive+ChatGPT login for this feature only. No API key is requested through chat or+voice.++Windows supports the experimental subscription transport. macOS and Linux+receive an explicit unavailable result until Jarvis has a verified+kill-on-parent-exit supervisor for those systems; a hard crash must never leave+an orphan Codex process holding the private profile indefinitely. This+limitation does not affect API-backed realtime providers or standard voice.++## Upgrade policy++Do not broaden the CLI version range just because a newer Codex binary starts.+For every supported upgrade:++1. Inspect the exact tagged app-server schema and implementation.+2. Re-run the live strict-config audit with an isolated profile.+3. Verify the official native hashes on all six OS/architecture targets.+4. Re-test account type, managed requirements, config origins, thread+ isolation, WebRTC negotiation, handoffs, teardown, and billing fail-closed+ behavior.+5. Update the user-facing experimental warning if OpenAI changes plan or+ connected-Voice accounting.++## Primary sources++- [Using Codex with your ChatGPT plan](https://help.openai.com/en/articles/11369540-using-codex-with-your-chatgpt-plan)+- [Codex 0.146.0 app-server protocol](https://github.com/openai/codex/blob/rust-v0.146.0/codex-rs/app-server/README.md)+- [OpenAI Realtime API guide](https://developers.openai.com/api/docs/guides/realtime)diff --git a/docs/commands-reference.md b/docs/commands-reference.mdindex 2d317e328a..82db551ff1 100644--- a/docs/commands-reference.md+++ b/docs/commands-reference.md@@ -43,10 +43,10 @@ Switch the speech-to-text provider. Takes effect on the next voice-pipeline star## `realtime-switch` — Switch realtime voice provider-Switch which realtime voice engine (speech-to-speech) is active, e.g. openai-realtime or gemini-live.+Switch which realtime voice engine (speech-to-speech) is active, including subscription- and API-backed providers. Experimental transports require explicit acknowledgement.- **Endpoint:** `POST /api/realtime/switch`-- **Arguments:** `provider` (one of: gemini-live, openai-realtime; required); `persist` (boolean; optional)+- **Arguments:** `provider` (one of: codex-subscription-realtime, gemini-live, openai-realtime; required); `persist` (boolean; optional); `accept_experimental` (boolean; optional)- **Requires confirmation:** no- **Desktop UI section:** `apikeys`- **Voice example (EN):** "switch the realtime model to gemini"@@ -86,7 +86,7 @@ List all configured providers and which ones are active.Test connectivity and authentication for one provider.- **Endpoint:** `POST /api/providers/{provider_id}/test`-- **Arguments:** `provider_id` (one of: antigravity, cartesia, claude-api, claude-cli, codex, elevenlabs, faster-whisper, gemini, gemini-flash-tts, gemini-live, gemini-polish, grok, grok-voice, groq-api, groq-polish, inworld, local-openai, nemotron-local, nvidia, ollama, ollama-polish, openai, openai-api, openai-polish, openai-realtime, openrouter, openrouter-polish, openrouter-stt, openrouter-tts, piper-local; required)+- **Arguments:** `provider_id` (one of: antigravity, cartesia, claude-api, claude-cli, codex, codex-subscription-realtime, elevenlabs, faster-whisper, gemini, gemini-flash-tts, gemini-live, gemini-polish, grok, grok-voice, groq-api, groq-polish, inworld, local-openai, nemotron-local, nvidia, ollama, ollama-polish, openai, openai-api, openai-polish, openai-realtime, openrouter, openrouter-polish, openrouter-stt, openrouter-tts, piper-local; required)- **Requires confirmation:** no- **Desktop UI section:** `apikeys`- **Voice example (EN):** "test the openai provider"diff --git a/docs/os-parity.md b/docs/os-parity.mdindex f846fc4e00..058252526a 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -49,6 +49,7 @@ experiences today.| # | Impact | Area | Gap | Evidence | Behavior off-Windows ||---|---|---|---|---|---|+| P-28 | Medium | Codex subscription voice | The pinned experimental Codex app-server transport requires kernel-enforced kill-on-parent-exit containment. Windows has a kill-on-close Job Object; macOS and Linux are gated until an equally reliable supervisor is implemented and crash-tested. | `jarvis/codex_app_server.py::_trusted_native_codex_binary`, `docs/codex-subscription-realtime-voice.md` | macOS and Linux show an explicit unavailable status for subscription voice. API Realtime, Pipeline voice, and the rest of Jarvis continue to work normally. || P-24 | Medium | Dictation shortcut | The global dictation/call shortcut needs `pynput` on Linux/X11, and `pynput` hard-requires `evdev` — which is published **source-only** (verified on PyPI 2026-07-28: evdev 1.9.3 ships an sdist and no wheels) and compiles against the kernel headers. Putting it in `[full]` would break the one advertised install path on a stock `python:3.11-slim`, so it is the opt-in `[desktop-linux]` extra instead. Wayland is a separate, unfixable-by-install case: the compositor owns global shortcuts by design (the XDG `GlobalShortcuts` portal lets the *compositor* assign the keys, and no wlroots compositor implements it at all) | `pyproject.toml` (`desktop-linux`), `jarvis/platform/probes.py::has_hotkey`, `jarvis/trigger/backends/noop.py::explain_unavailable` | X11 without the extra: no global shortcut, and the log/UI now names the actual cause and the exact `pip install` that fixes it (it used to blame Wayland unconditionally). Wayland: no global shortcut at all — bind a compositor shortcut to `jarvis api dictation start`. On both, dictation still works from the Jarvis Bar, the Dictation view and the CLI, and voice still works via the wake word || P-25 | Medium | Dictation insertion | Pasting the transcript into another application is blocked, silently, in three OS-specific situations: Windows UIPI when the foreground window is elevated and Jarvis is not (`SendInput` reports success and the input is discarded), macOS Secure Input while a password field is focused, and Wayland outright (no synthetic input). Detection exists for the first two; Wayland is refused up front | `jarvis/dictation/insert.py::describe_target`, `jarvis/platform/input_isolation.py::windows_foreground_window_is_elevated`, `macos_secure_input_enabled` | All three degrade to the SAME honest outcome instead of silence: the transcript is left on the clipboard, the result is reported as `clipboard_only`, and the bar plus the Dictation view say why and that Ctrl+V will paste it. macOS Secure Input detection is implemented but has not been verified on real hardware from this machine || P-02 | Low | Awareness | Idle detection has no Wayland backend (Windows GetLastInputInfo, macOS Quartz, Linux X11 `xprintidle` all exist since 2026-07-16); Wayland exposes no global idle time without portal support | `jarvis/awareness/watchers/idle.py` | Wayland: one honest log line, watcher does not start |diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.pyindex 5352abf08e..d1680c8ece 100644--- a/jarvis/brain/model_catalog.py+++ b/jarvis/brain/model_catalog.py@@ -466,7 +466,8 @@ TTS_CATALOG: dict[str, tuple[str, list[ModelInfo]]] = {}# Realtime catalogs — REALTIME_MODELS + REALTIME_VOICES, keyed by realtime-# provider id (``openai-realtime`` / ``gemini-live``).+# provider id (``codex-subscription-realtime`` / ``openai-realtime`` /+# ``gemini-live``).# Realtime needs BOTH a# model AND a voice selection per provider (unlike every other picker, which# serves ONE selection), so these two dicts are looked up directly by the@@ -487,6 +488,12 @@ TTS_CATALOG: dict[str, tuple[str, list[ModelInfo]]] = {# they target dedicated translation/transcription sessions, not the general# duplex voice-agent protocol implemented by this adapter.REALTIME_MODELS: dict[str, list[ModelInfo]] = {+ # Codex 0.146's experimental v1 subscription transport has its own fixed+ # model/voice contract. Keep it separate from the metered OpenAI Realtime+ # API catalog: their accepted voice sets are not interchangeable.+ "codex-subscription-realtime": _curated(+ [("gpt-realtime-1.5", "GPT Realtime 1.5 (Codex default)")]+ ),"openai-realtime": _curated([("gpt-realtime", "GPT Realtime (default)"),@@ -529,6 +536,22 @@ REALTIME_MODELS: dict[str, list[ModelInfo]] = {# gemini-live: verified 2026-07-10 against the Live API capabilities guide,# which now permits the complete 30-voice Gemini prebuilt roster.REALTIME_VOICES: dict[str, list[ModelInfo]] = {+ # Codex app-server realtime v1 voices. ``cove`` is the v1 default, so it+ # leads the picker just as each realtime model catalog leads with its+ # adapter default.+ "codex-subscription-realtime": _ids(+ [+ "cove",+ "juniper",+ "maple",+ "spruce",+ "ember",+ "vale",+ "breeze",+ "arbor",+ "sol",+ ]+ ),"openai-realtime": _ids(["alloy",diff --git a/jarvis/browser_voice/route.py b/jarvis/browser_voice/route.pyindex 0f89334b06..2ceda91e41 100644--- a/jarvis/browser_voice/route.py+++ b/jarvis/browser_voice/route.py@@ -11,8 +11,10 @@ unclean disconnect is terminal — ``break``, never ``continue``.from __future__ import annotationsimport asyncio+import ipaddressimport jsonimport logging+import secretsfrom typing import Anyfrom uuid import uuid4@@ -34,11 +36,17 @@ router = APIRouter()_AUDIO_QUEUE_MAX_FRAMES = 32_TRANSPORT_SEND_TIMEOUT_S = 2.0_AUDIO_DRAIN_TIMEOUT_S = 2.0+_BROKER_AUTH_TIMEOUT_S = 3.0_UNSAFE_FALLBACK_DETAIL = ("Realtime provider failed after this turn was accepted. The session was ""closed without replaying audio through the classic pipeline to avoid ""duplicate actions.")+_USAGE_FALLBACK_DISABLED_DETAIL = (+ "Selected realtime access failed. Automatic usage-billed API fallback is "+ "disabled for this provider; configure an explicit realtime fallback or "+ "restore its subscription access."+)# BCP-47 from the canonical per-turn resolver (de/en/es)._LANG_MAP = {"de": "de-DE", "en": "en-US", "es": "es-ES"}@@ -72,6 +80,28 @@ def _browser_voice_authorized(ws: WebSocket) -> bool:return credentials_valid(ws.scope)+def _socket_peer_is_loopback(ws: WebSocket) -> bool:+ """Trust only the ASGI socket peer for the local SDP broker boundary.++ Forwarded headers and Origin are deliberately ignored: either can be+ supplied by a remote authenticated browser. IPv4-mapped IPv6 loopback is+ accepted so desktop networking behaves consistently across operating+ systems and embedded WebView implementations.+ """+ client = ws.scope.get("client")+ if not isinstance(client, (tuple, list)) or not client:+ return False+ host = str(client[0] or "").strip().strip("[]")+ if "%" in host:+ host = host.split("%", 1)[0]+ try:+ address = ipaddress.ip_address(host)+ except ValueError: # A non-IP host is a normal failed loopback capability check.+ return False+ mapped = getattr(address, "ipv4_mapped", None)+ return bool((mapped or address).is_loopback)++def _json_commits_semantic_turn(message: dict[str, Any]) -> bool:"""Whether an outbound status proves Realtime has accepted the turn.@@ -96,6 +126,20 @@ def _json_commits_semantic_turn(message: dict[str, Any]) -> bool:}+def _automatic_usage_fallback_allowed(cfg: Any) -> bool:+ """Read the selected provider's neutral billing-fallback capability."""+ if getattr(getattr(cfg, "voice", None), "mode", "pipeline") != "realtime":+ return True+ try:+ from jarvis.realtime.factory import (+ realtime_implicit_usage_fallback_allowed,+ )++ return realtime_implicit_usage_fallback_allowed(cfg)+ except Exception: # noqa: BLE001 - configured realtime fails closed on ambiguity+ return False++def _enqueue_audio_frame(queue: asyncio.Queue[bytes | None], data: bytes) -> bool:"""Queue one mic frame without blocking; drop the oldest on overflow."""dropped = False@@ -110,6 +154,16 @@ def _enqueue_audio_frame(queue: asyncio.Queue[bytes | None], data: bytes) -> booreturn dropped+async def _cancel_socket_task(task: asyncio.Task[Any]) -> None:+ """Cancel and reap one temporary WebSocket receive/wait task."""+ if not task.done():+ task.cancel()+ try:+ await task+ except (asyncio.CancelledError, WebSocketDisconnect, RuntimeError): # Expected teardown.+ pass++def _build_browser_session(*, state: Any, cfg: Any, bus: Any, session_id: str, send_binary: Any, send_json: Any) -> Any:@@ -141,6 +195,9 @@ def _build_browser_session(if rt is not None:return rt+ if not _automatic_usage_fallback_allowed(cfg):+ return None+return _build_classic_browser_session(state=state,cfg=cfg,@@ -183,6 +240,165 @@ def _build_classic_browser_session()[email protected]("/ws/realtime-transport")+async def realtime_transport_ws(ws: WebSocket) -> None:+ """Broker a local desktop WebRTC offer for subscription voice.++ Audio remains on Jarvis's existing native or ``/ws/audio`` path. This+ socket carries only one-shot SDP offers and answers. Because an answered+ offer can receive native-call audio, this broker is additionally restricted+ to the actual loopback socket peer; authentication alone is insufficient.+ """+ await ws.accept()+ if not _socket_peer_is_loopback(ws):+ await ws.close(code=4403, reason="local desktop transport required")+ return+ if not _browser_voice_authorized(ws):+ await ws.close(code=4401, reason="unauthorized")+ return++ app = ws.scope.get("app")+ state = app.state if app is not None else None+ cfg = getattr(state, "config", None) or getattr(state, "cfg", None)+ if cfg is None:+ try:+ cfg = cfg_mod.load_config()+ except Exception: # noqa: BLE001 - route still fails closed below+ log.warning("realtime transport config could not be loaded", exc_info=True)+ cfg = None+ if cfg is None or getattr(getattr(cfg, "voice", None), "mode", "pipeline") != (+ "realtime"+ ):+ await ws.close(code=1008, reason="realtime voice disabled")+ return++ from jarvis.realtime.offer_broker import (+ get_realtime_transport_offer_broker,+ )++ broker = get_realtime_transport_offer_broker()+ registration: Any = None+ queued_message: dict[str, Any] | None = None+ socket_closed = False+ try:+ desktop_capability = str(+ getattr(state, "realtime_transport_broker_token", "") or ""+ )+ if not desktop_capability:+ await ws.close(code=4401, reason="desktop capability unavailable")+ return+ try:+ auth_message = await asyncio.wait_for(+ ws.receive(), timeout=_BROKER_AUTH_TIMEOUT_S+ )+ except (TimeoutError, WebSocketDisconnect, RuntimeError): # Reject failed capability proof.+ await ws.close(code=4401, reason="desktop capability required")+ return+ auth_text = auth_message.get("text")+ try:+ auth_payload = json.loads(auth_text) if auth_text is not None else None+ except (TypeError, ValueError): # Malformed authentication is handled as absent.+ auth_payload = None+ supplied_capability = (+ str(auth_payload.get("desktop_capability", "") or "")+ if isinstance(auth_payload, dict)+ and auth_payload.get("type") == "authenticate"+ else ""+ )+ if not supplied_capability or not secrets.compare_digest(+ supplied_capability, desktop_capability+ ):+ await ws.close(code=4401, reason="invalid desktop capability")+ return+ owner_id = f"broker-ws-{id(ws):x}"+ while not socket_closed:+ if queued_message is None:+ try:+ message = await ws.receive()+ except (WebSocketDisconnect, RuntimeError): # Socket teardown ends this receiver.+ break+ else:+ message = queued_message+ queued_message = None+ if message.get("type") == "websocket.disconnect":+ break+ text = message.get("text")+ if text is None:+ continue+ try:+ payload = json.loads(text)+ except (TypeError, ValueError):+ log.debug("realtime transport dropped malformed JSON")+ continue+ if not isinstance(payload, dict) or payload.get("type") != "offer":+ if isinstance(payload, dict) and payload.get("type") == "authenticate":+ await ws.close(code=4401, reason="desktop capability replay")+ socket_closed = True+ continue++ offer_id = str(payload.get("offer_id", "") or "").strip()+ offer_sdp = str(payload.get("webrtc_offer_sdp", "") or "")+ try:+ registration = await broker.register(+ offer_id, offer_sdp, owner_id=owner_id+ )+ except ValueError as exc:+ log.warning("realtime transport rejected offer: %s", exc)+ await ws.send_json({"type": "release", "offer_id": offer_id})+ continue++ while registration is not None:+ result_task = asyncio.create_task(+ registration.wait(), name=f"realtime-offer-{offer_id}"+ )+ receive_task = asyncio.create_task(+ ws.receive(), name=f"realtime-offer-receive-{offer_id}"+ )+ done, _pending = await asyncio.wait(+ {result_task, receive_task},+ return_when=asyncio.FIRST_COMPLETED,+ )+ if result_task in done:+ await _cancel_socket_task(receive_task)+ result = result_task.result()+ if result.type == "answer":+ await ws.send_json(+ {+ "type": "answer",+ "offer_id": result.offer_id,+ "webrtc_answer_sdp": result.answer_sdp,+ }+ )+ # Keep the registration alive until provider close so+ # the UI knows when to recycle its PeerConnection and+ # publish a fresh offer for the next native call.+ continue+ await ws.send_json(+ {"type": "release", "offer_id": result.offer_id}+ )+ registration = None+ break++ await _cancel_socket_task(result_task)+ await registration.cancel()+ registration = None+ try:+ next_message = receive_task.result()+ except (WebSocketDisconnect, RuntimeError): # Socket teardown ends this offer.+ socket_closed = True+ break+ if next_message.get("type") == "websocket.disconnect":+ socket_closed = True+ break+ # A refreshed offer can replace an abandoned one on the same+ # socket. Process that already-read frame in the outer loop.+ queued_message = next_message+ break+ finally:+ if registration is not None:+ await registration.cancel()++@router.websocket("/ws/audio")async def browser_voice_ws(ws: WebSocket) -> None:"""Browser-microphone voice socket: run the per-connection turn loop."""@@ -199,7 +415,7 @@ async def browser_voice_ws(ws: WebSocket) -> None:if cfg is None:try:cfg = cfg_mod.load_config()- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001 - Config failure degrades to unavailable voice.cfg = Noneif cfg is not None and not _browser_voice_enabled(cfg):@@ -234,7 +450,12 @@ async def browser_voice_ws(ws: WebSocket) -> None:send_json=_send_json,)if session is None:- await ws.close(code=1011, reason="speech stack unavailable")+ reason = (+ "realtime access unavailable"+ if not _automatic_usage_fallback_allowed(cfg)+ else "speech stack unavailable"+ )+ await ws.close(code=1011, reason=reason)returnaudio_start_control: dict[str, Any] | None = None@@ -248,6 +469,27 @@ async def browser_voice_ws(ws: WebSocket) -> None:nonlocal sessionif not bool(getattr(session, "is_realtime", False)):return False+ if not bool(getattr(session, "allow_classic_fallback", True)):+ log.warning(+ "browser_voice: selected realtime provider failed; automatic "+ "usage-billed fallback is disabled: %s",+ reason,+ )+ await session.end(reason=HANGUP_ERROR)+ try:+ await _send_json(+ {+ "type": "provider_error",+ "error": _USAGE_FALLBACK_DISABLED_DETAIL,+ }+ )+ except Exception: # noqa: BLE001 - surface may already be gone+ log.debug(+ "browser_voice: subscription failure status could not be sent",+ exc_info=True,+ )+ await ws.close(code=1011, reason="automatic API fallback disabled")+ return Falseif semantic_turn_committed:log.warning("browser_voice: realtime failed after a committed turn; "@@ -338,7 +580,7 @@ async def browser_voice_ws(ws: WebSocket) -> None:while True:try:msg = await ws.receive()- except WebSocketDisconnect:+ except WebSocketDisconnect: # A peer disconnect normally terminates the receive loop.breakexcept RuntimeError:# AP-20: an unclean disconnect raises RuntimeError (not@@ -362,6 +604,23 @@ async def browser_voice_ws(ws: WebSocket) -> None:continueif isinstance(control, dict):if control.get("type") == "audio_start":+ raw_offer = control.get("webrtc_offer_sdp")+ if raw_offer is not None:+ try:+ from jarvis.realtime.offer_broker import (+ validate_webrtc_offer_sdp,+ )++ control["webrtc_offer_sdp"] = (+ validate_webrtc_offer_sdp(raw_offer)+ )+ except ValueError as exc:+ log.warning(+ "browser_voice: rejected invalid WebRTC offer: %s",+ exc,+ )+ await ws.close(code=1008, reason="invalid WebRTC offer")+ breakaudio_start_control = dict(control)try:await session.handle_control(control)@@ -388,13 +647,14 @@ async def browser_voice_ws(ws: WebSocket) -> None:if not audio_sender_task.done():try:audio_queue.put_nowait(None)- except asyncio.QueueFull:+ except asyncio.QueueFull: # Cancellation already makes the terminal sentinel redundant.audio_sender_task.cancel()try:await asyncio.wait_for(audio_sender_task, timeout=_TRANSPORT_SEND_TIMEOUT_S)except (TimeoutError, asyncio.CancelledError):+ # Bounded teardown cancels a stuck sender.audio_sender_task.cancel()if dropped_audio_frames:log.warning(diff --git a/jarvis/codex_app_server.py b/jarvis/codex_app_server.pynew file mode 100644index 0000000000..53d48859d1--- /dev/null+++ b/jarvis/codex_app_server.py@@ -0,0 +1,3177 @@+"""Persistent, subscription-only transport for ``codex app-server``.++This module owns the local JSONL protocol, process lifecycle, and the dedicated+Codex identity used by subscription voice. The user signs in directly inside a+Jarvis-owned ``CODEX_HOME``; OAuth tokens are never copied, hard-linked, or+borrowed from an ordinary Codex/IDE profile. Credentials are forced into that+profile's file store, and live ``account/read`` is the authoritative account and+plan check.+API-key environment variables are removed so a subscription request cannot+silently become usage-billed API traffic.++The process is lazy and shared by callers. A dead process fails every pending+request and thread subscription, then the next request starts a fresh process.+Requests wait on independent futures, while the write lock covers only one+JSONL frame and its drain. This keeps high-frequency realtime audio appends+from serialising behind unrelated response waits.+"""++from __future__ import annotations++import asyncio+import hashlib+import json+import logging+import os+import platform+import re+import secrets+import shutil+import stat+import subprocess+import sys+import tempfile+import threading+import uuid+from collections.abc import AsyncIterator, Mapping, Sequence+from contextlib import suppress+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Final, Literal++from jarvis import __version__+from jarvis.core.process_tree import ProcessTree, make_process_tree+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++log = logging.getLogger(__name__)++_DEFAULT_REQUEST_TIMEOUT_S: Final = 20.0+_SHUTDOWN_TIMEOUT_S: Final = 2.0+_DEFAULT_SDP_TIMEOUT_S: Final = 15.0+_DEFAULT_NOTIFICATION_QUEUE_SIZE: Final = 512+_SUPPORTED_CODEX_VERSION: Final = "codex-cli 0.146.0"++# SHA-256 of the native executables in OpenAI's six official npm artifacts for+# @openai/codex 0.146.0. The app-server protocol used below is experimental;+# an unknown build is refused instead of assuming its safety semantics match.+_TRUSTED_CODEX_TARGETS: Final = {+ ("darwin", "arm64"): (+ "darwin-arm64",+ "aarch64-apple-darwin",+ "codex",+ "ae1d3ffe6d48aec6a4dc3f50e7eb8e0d11962485a6a9406c5a7012139383da02",+ ),+ ("darwin", "x86_64"): (+ "darwin-x64",+ "x86_64-apple-darwin",+ "codex",+ "544e2df9e6f09b3f1ceb0405879c83dd099ec015aeed942bb091ff0f29f60dc2",+ ),+ ("linux", "arm64"): (+ "linux-arm64",+ "aarch64-unknown-linux-musl",+ "codex",+ "cb5e8cb8a333a408ce6adbe0d4fad1845c69772c2216af7c1f88c98a11460dc6",+ ),+ ("linux", "x86_64"): (+ "linux-x64",+ "x86_64-unknown-linux-musl",+ "codex",+ "2e863156ed35ecc5253b1e2f907a9143077b9f7cb51942070c61996471ff6e04",+ ),+ ("win32", "arm64"): (+ "win32-arm64",+ "aarch64-pc-windows-msvc",+ "codex.exe",+ "d52efa1d816b305c84c525335f451aafc56398a7e8515b6c6db095c4e4fb0d1d",+ ),+ ("win32", "x86_64"): (+ "win32-x64",+ "x86_64-pc-windows-msvc",+ "codex.exe",+ "bc343ba420dc2e2e9f59e6fc5e5bf0aae1cd8c771fc319665241fc9c0271fddb",+ ),+}+_SUBSCRIPTION_HOME_DIRNAME: Final = "codex-subscription-voice"+_SUBSCRIPTION_LOCK_DIRNAME: Final = ".codex-subscription-voice-lock"+_SUBSCRIPTION_LOCK_FILENAME: Final = "owner.lock"+_SUBSCRIPTION_PROFILE_MARKER: Final = ".jarvis-realtime-transport.json"+_SUBSCRIPTION_PROFILE_SCHEMA: Final = 1+_ALLOWED_SUBSCRIPTION_HOME_ENTRIES: Final = frozenset(+ {+ "auth.json",+ "installation_id",+ "tmp",+ _SUBSCRIPTION_PROFILE_MARKER,+ }+)+_ARG0_RUNTIME_DIR_RE: Final = re.compile(r"^codex-arg0[A-Za-z0-9]{6}$")+_MAX_ARG0_RUNTIME_DIRS: Final = 32+_PERSONAL_CHATGPT_PLANS: Final = frozenset(+ {"free", "go", "plus", "pro", "prolite"}+)++_SUBSCRIPTION_ENV_ALLOWLIST: Final = frozenset(+ {+ # Executable/runtime discovery.+ "PATH",+ "PATHEXT",+ "COMSPEC",+ "SYSTEMROOT",+ "WINDIR",+ # Temporary storage used by the CLI/runtime.+ "TEMP",+ "TMP",+ "TMPDIR",+ # Portable account/home selection. No provider or cloud variables are+ # inherited merely because they happen to exist in Jarvis's process.+ "HOME",+ "USERPROFILE",+ "HOMEDRIVE",+ "HOMEPATH",+ "APPDATA",+ "LOCALAPPDATA",+ "CODEX_HOME",+ }+)++_DISABLED_APP_SERVER_FEATURES: Final = (+ "shell_tool",+ "apps",+ "browser_use",+ "computer_use",+ "hooks",+ "image_generation",+ "memories",+ "multi_agent",+ "multi_agent_v2",+ "plugins",+ "network_proxy",+ "remote_plugin",+ "remote_control",+ "respect_system_proxy",+ "skill_search",+ "workspace_dependencies",+ "web_search_request",+ "external_agent_memory_import",+ "chronicle",+)++_TRANSPORT_BASE_INSTRUCTIONS: Final = (+ "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."+)+_TRANSPORT_DEVELOPER_INSTRUCTIONS: Final = (+ "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."+)++_OFFICIAL_OPENAI_API_BASE: Final = "https://api.openai.com/v1"+_OFFICIAL_OPENAI_REALTIME_BASE: Final = "https://api.openai.com/v1"+_OFFICIAL_CHATGPT_BASE: Final = "https://chatgpt.com/backend-api/"+_OFFICIAL_CHATGPT_CODEX_BASE: Final = "https://chatgpt.com/backend-api/codex"+_MISSING = object()++# A ChatGPT-authenticated Codex process must not inherit any OpenAI key that+# could make the CLI select a usage-billed path. Include Jarvis's per-feature+# aliases as well as historical Codex aliases seen in existing installations.+_OPENAI_BILLING_ENV_NAMES: Final = frozenset(+ {+ "CODEX_API_KEY",+ "CODEX_OPENAI_API_KEY",+ "JARVIS_AGENT_OPENAI_API_KEY",+ "JARVIS_REALTIME_OPENAI_API_KEY",+ "LOCAL_OPENAI_API_KEY",+ "OPENAI_API_KEY",+ }+)++_DECLINE_REQUEST_METHODS: Final = frozenset(+ {+ "item/commandExecution/requestApproval",+ "item/fileChange/requestApproval",+ }+)+_DYNAMIC_TOOL_REQUEST_METHODS: Final = frozenset({"item/tool/call"})+++class CodexAppServerError(RuntimeError):+ """Base error for the local app-server transport."""+++class CodexSubscriptionUnavailable(CodexAppServerError):+ """The Codex CLI cannot currently use a ChatGPT subscription login."""+++class CodexSubscriptionContainmentUnavailable(CodexSubscriptionUnavailable):+ """The host cannot safely bind the experimental child to Jarvis lifetime."""+++class CodexSubscriptionProfileMissing(CodexSubscriptionUnavailable):+ """The dedicated subscription-voice profile does not exist yet."""+++class CodexAppServerDisconnected(CodexAppServerError):+ """The app-server process exited or its JSONL stream broke."""+++class CodexAppServerTimeout(CodexAppServerError):+ """A bounded app-server request or notification wait expired."""+++class CodexNotificationOverflow(CodexAppServerError):+ """A subscriber stopped consuming realtime notifications fast enough."""+++class CodexAppServerRPCError(CodexAppServerError):+ """A redacted JSON-RPC error returned by app-server."""++ def __init__(self, method: str, code: int | None) -> None:+ self.method = method+ self.code = code+ suffix = f" (code {code})" if code is not None else ""+ super().__init__(f"Codex app-server rejected {method}{suffix}.")+++@dataclass(frozen=True, slots=True)+class CodexAppServerCapability:+ """PII-free snapshot of whether the subscription transport may start."""++ available: bool+ chatgpt_authenticated: bool+ binary_path: str | None+ version: str | None+ reason: str+ reason_code: Literal[+ "ready",+ "login_required",+ "lifecycle_unavailable",+ "not_installed",+ "setup_invalid",+ ] = "setup_invalid"+++@dataclass(frozen=True, slots=True)+class CodexAppServerNotification:+ """One thread-scoped app-server notification."""++ method: str+ params: dict[str, Any]+++@dataclass(frozen=True, slots=True)+class CodexRealtimeStartResult:+ """Realtime start acknowledgement plus an optional WebRTC answer SDP."""++ response: dict[str, Any]+ answer_sdp: str | None+++_SUBSCRIPTION_END = object()+_SubscriptionItem = CodexAppServerNotification | BaseException | object+++@dataclass(frozen=True, slots=True)+class _SafeTransportWorkspace:+ root: Path+ instructions: Path+ compact_prompt: Path+ model_catalog: Path+ sqlite_home: Path+ log_dir: Path+ child_home: Path+ child_appdata: Path+ child_local_appdata: Path+ child_tmp: Path+++def codex_subscription_home() -> Path:+ """Jarvis-owned Codex identity used only by realtime subscription voice."""+ from jarvis.core.paths import user_data_dir++ return user_data_dir() / _SUBSCRIPTION_HOME_DIRNAME+++def _subscription_process_lock_path() -> Path:+ """Return an owner-only lock path outside the allowlisted CODEX_HOME."""+ from jarvis.core.paths import user_data_dir+ from jarvis.core.private_directory import ensure_owner_only_directory++ root = user_data_dir()+ root.mkdir(parents=True, exist_ok=True)+ try:+ canonical_root = root.resolve(strict=True)+ lock_directory = canonical_root / _SUBSCRIPTION_LOCK_DIRNAME+ ensure_owner_only_directory(lock_directory, create=True)+ canonical_lock_directory = lock_directory.resolve(strict=True)+ except (OSError, RuntimeError) as exc:+ raise CodexSubscriptionUnavailable(+ "The subscription-voice process lock could not be secured."+ ) from exc+ if canonical_lock_directory.parent != canonical_root:+ raise CodexSubscriptionUnavailable(+ "The subscription-voice process lock could not be secured."+ )+ return canonical_lock_directory / _SUBSCRIPTION_LOCK_FILENAME+++def _acquire_subscription_process_lock():+ """Acquire the cross-process profile owner or fail without path disclosure."""+ from jarvis.core.exclusive_process_lock import (+ ExclusiveProcessLock,+ ExclusiveProcessLockError,+ )++ try:+ return ExclusiveProcessLock.acquire(+ _subscription_process_lock_path(),+ protected_directory=codex_subscription_home(),+ )+ except ExclusiveProcessLockError as exc:+ if exc.reason == "busy":+ message = "Another Jarvis process is using subscription voice."+ else:+ message = "The subscription-voice process lock could not be secured."+ raise CodexSubscriptionUnavailable(message) from exc+++def _is_link_or_reparse(path: Path) -> bool:+ metadata = path.lstat()+ if stat.S_ISLNK(metadata.st_mode):+ return True+ reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)+ return bool(getattr(metadata, "st_file_attributes", 0) & reparse_flag)+++def _validate_current_owner(metadata: os.stat_result) -> None:+ geteuid = getattr(os, "geteuid", None)+ if callable(geteuid) and metadata.st_uid != geteuid():+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile belongs to another user."+ )+++def _validate_regular_private_file(path: Path) -> None:+ metadata = path.lstat()+ if _is_link_or_reparse(path) or not stat.S_ISREG(metadata.st_mode):+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains an unsafe filesystem entry."+ )+ if getattr(metadata, "st_nlink", 1) != 1:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains a linked credential file."+ )+ _validate_current_owner(metadata)+ if sys.platform == "win32":+ from jarvis.core.exclusive_process_lock import ( # noqa: PLC0415+ ExclusiveProcessLockError,+ _validate_windows_file_security,+ )++ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)+ flags |= getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)+ descriptor = -1+ try:+ descriptor = os.open(path, flags)+ opened = os.fstat(descriptor)+ current = path.lstat()+ reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)+ if (+ stat.S_ISLNK(current.st_mode)+ or bool(getattr(current, "st_file_attributes", 0) & reparse_flag)+ or not stat.S_ISREG(opened.st_mode)+ or (opened.st_dev, opened.st_ino) != (current.st_dev, current.st_ino)+ ):+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains an unsafe filesystem entry."+ )+ _validate_windows_file_security(descriptor)+ except CodexSubscriptionUnavailable:+ raise+ except (ExclusiveProcessLockError, OSError, ValueError) as exc:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains a file that is not owner-only."+ ) from exc+ finally:+ if descriptor >= 0:+ os.close(descriptor)+++def _validate_private_directory(+ path: Path,+ *,+ exact_posix_mode: int | None = None,+ require_owner_only: bool = False,+) -> None:+ metadata = path.lstat()+ if _is_link_or_reparse(path) or not stat.S_ISDIR(metadata.st_mode):+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains an unsafe directory."+ )+ _validate_current_owner(metadata)+ if os.name == "posix":+ mode = stat.S_IMODE(metadata.st_mode)+ if exact_posix_mode is not None and mode != exact_posix_mode:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile has unsafe directory permissions."+ )+ if require_owner_only and exact_posix_mode is None and mode & 0o077:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile is not owner-only."+ )+++def _is_trusted_codex_runtime_binary(+ path: Path,+ *,+ trusted_binary_path: str | None = None,+) -> bool:+ try:+ canonical = path.resolve(strict=True)+ if _is_link_or_reparse(canonical) or not canonical.is_file():+ return False+ if trusted_binary_path is not None:+ trusted = Path(trusted_binary_path).resolve(strict=True)+ return (+ not _is_link_or_reparse(trusted)+ and trusted.is_file()+ and os.path.normcase(str(canonical))+ == os.path.normcase(str(trusted))+ )+ target = _TRUSTED_CODEX_TARGETS.get(+ (sys.platform, _normalized_machine())+ )+ return target is not None and _sha256_file(canonical) == target[3]+ except OSError: # An unreadable binary is reported as an unavailable capability.+ return False+++def _validate_windows_arg0_wrapper(+ path: Path,+ *,+ trusted_binary_path: str | None = None,+) -> None:+ _validate_regular_private_file(path)+ try:+ if path.stat().st_size > 4096:+ raise ValueError("wrapper is too large")+ body = path.read_text(encoding="utf-8")+ except (OSError, UnicodeError, ValueError) as exc:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains an invalid runtime wrapper."+ ) from exc+ match = re.fullmatch(+ r'@echo off\r?\n"([^"\r\n]+)" --codex-run-as-apply-patch %\*\r?\n',+ body,+ )+ if match is None or not _is_trusted_codex_runtime_binary(+ Path(match.group(1)),+ trusted_binary_path=trusted_binary_path,+ ):+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains an untrusted runtime wrapper."+ )+++def _validate_unix_arg0_alias(+ path: Path,+ *,+ trusted_binary_path: str | None = None,+) -> None:+ metadata = path.lstat()+ if not stat.S_ISLNK(metadata.st_mode):+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains an invalid runtime alias."+ )+ _validate_current_owner(metadata)+ try:+ raw_target = Path(os.readlink(path))+ target = raw_target if raw_target.is_absolute() else path.parent / raw_target+ except OSError as exc:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains an unreadable runtime alias."+ ) from exc+ if not _is_trusted_codex_runtime_binary(+ target,+ trusted_binary_path=trusted_binary_path,+ ):+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains an untrusted runtime alias."+ )+++def _validate_arg0_runtime_dir(+ path: Path,+ *,+ trusted_binary_path: str | None = None,+) -> None:+ _validate_private_directory(path)+ try:+ children = {entry.name: entry for entry in path.iterdir()}+ except OSError as exc:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile runtime could not be inspected."+ ) from exc+ expected = {".lock"}+ if sys.platform == "win32":+ expected.update({"apply_patch.bat", "applypatch.bat"})+ elif sys.platform == "darwin":+ expected.update({"apply_patch", "applypatch", "codex-execve-wrapper"})+ elif sys.platform.startswith("linux"):+ expected.update(+ {+ "apply_patch",+ "applypatch",+ "codex-execve-wrapper",+ "codex-linux-sandbox",+ }+ )+ else:+ raise CodexSubscriptionUnavailable(+ "This platform's Codex runtime layout is not approved."+ )+ if set(children) != expected:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains unexpected runtime files."+ )+ lock_file = children[".lock"]+ _validate_regular_private_file(lock_file)+ if lock_file.stat().st_size != 0:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains an invalid runtime lock."+ )+ for name, child in children.items():+ if name == ".lock":+ continue+ if sys.platform == "win32":+ _validate_windows_arg0_wrapper(+ child,+ trusted_binary_path=trusted_binary_path,+ )+ else:+ _validate_unix_arg0_alias(+ child,+ trusted_binary_path=trusted_binary_path,+ )+++def _validate_codex_runtime_state(+ home: Path,+ *,+ trusted_binary_path: str | None = None,+) -> None:+ installation_id = home / "installation_id"+ if installation_id.exists() or installation_id.is_symlink():+ _validate_regular_private_file(installation_id)+ try:+ raw_installation_id = installation_id.read_text(encoding="utf-8")+ parsed = uuid.UUID(raw_installation_id)+ except (OSError, UnicodeError, ValueError) as exc:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile has an invalid installation id."+ ) from exc+ if raw_installation_id != str(parsed) or len(raw_installation_id) != 36:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile has a non-canonical installation id."+ )+ if os.name == "posix":+ mode = stat.S_IMODE(installation_id.stat().st_mode)+ if mode not in {0o600, 0o640, 0o644}:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice installation id has unsafe permissions."+ )++ runtime_root = home / "tmp"+ if not runtime_root.exists() and not runtime_root.is_symlink():+ return+ trusted_runtime_binary: Path | None = None+ if trusted_binary_path is not None:+ try:+ trusted_runtime_binary = Path(trusted_binary_path).resolve(strict=True)+ except OSError as exc:+ raise CodexSubscriptionUnavailable(+ "The approved Codex runtime binary is unavailable."+ ) from exc+ _validate_private_directory(runtime_root)+ try:+ runtime_children = {entry.name: entry for entry in runtime_root.iterdir()}+ except OSError as exc:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice runtime could not be inspected."+ ) from exc+ if set(runtime_children) != {"arg0"}:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains unexpected runtime state."+ )+ arg0_root = runtime_children["arg0"]+ _validate_private_directory(+ arg0_root,+ exact_posix_mode=0o700 if os.name == "posix" else None,+ )+ try:+ process_dirs = tuple(arg0_root.iterdir())+ except OSError as exc:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice runtime could not be inspected."+ ) from exc+ if len(process_dirs) > _MAX_ARG0_RUNTIME_DIRS:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains excessive runtime state."+ )+ for process_dir in process_dirs:+ if _ARG0_RUNTIME_DIR_RE.fullmatch(process_dir.name) is None:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains an unknown runtime directory."+ )+ _validate_arg0_runtime_dir(+ process_dir,+ trusted_binary_path=(+ str(trusted_runtime_binary)+ if trusted_runtime_binary is not None+ else None+ ),+ )+ if trusted_runtime_binary is not None and not _is_trusted_codex_runtime_binary(+ trusted_runtime_binary+ ):+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile references an untrusted runtime binary."+ )+++def _validated_subscription_home(+ *,+ create: bool,+ require_marker: bool,+ trusted_binary_path: str | None = None,+) -> Path:+ """Resolve the isolated profile and reject every non-login artifact."""+ from jarvis.core.paths import user_data_dir+ from jarvis.core.private_directory import ensure_owner_only_directory++ root = user_data_dir()+ if create:+ root.mkdir(parents=True, exist_ok=True)+ elif not root.exists() and not root.is_symlink():+ raise CodexSubscriptionProfileMissing(+ "The dedicated Codex voice profile has not been created yet."+ )+ try:+ canonical_root = root.resolve(strict=True)+ except OSError as exc:+ raise CodexSubscriptionUnavailable(+ "Jarvis's private data directory could not be verified."+ ) from exc+ candidate = canonical_root / _SUBSCRIPTION_HOME_DIRNAME+ if not create and not candidate.exists() and not candidate.is_symlink():+ raise CodexSubscriptionProfileMissing(+ "The dedicated Codex voice profile has not been created yet."+ )+ try:+ ensure_owner_only_directory(candidate, create=create)+ except RuntimeError as exc:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile is not owner-only."+ ) from exc+ try:+ canonical_home = candidate.resolve(strict=True)+ except OSError as exc:+ raise CodexSubscriptionProfileMissing(+ "The dedicated Codex voice profile has not been created yet."+ ) from exc+ if canonical_home.parent != canonical_root:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile escaped Jarvis's private data directory."+ )+ _validate_private_directory(canonical_home, require_owner_only=True)++ try:+ entries = tuple(canonical_home.iterdir())+ except OSError as exc:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile could not be inspected."+ ) from exc+ unexpected = [+ entry.name+ for entry in entries+ if entry.name not in _ALLOWED_SUBSCRIPTION_HOME_ENTRIES+ ]+ if unexpected:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains configuration or runtime state. "+ "Create a fresh voice-only login."+ )+ for entry in entries:+ if entry.name in {"auth.json", _SUBSCRIPTION_PROFILE_MARKER}:+ _validate_regular_private_file(entry)++ _validate_codex_runtime_state(+ canonical_home,+ trusted_binary_path=trusted_binary_path,+ )++ marker = canonical_home / _SUBSCRIPTION_PROFILE_MARKER+ if require_marker:+ try:+ marker_data = json.loads(marker.read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ raise CodexSubscriptionUnavailable(+ "Use Jarvis's subscription-voice login before starting voice mode."+ ) from exc+ if marker_data != {+ "schema": _SUBSCRIPTION_PROFILE_SCHEMA,+ "purpose": "realtime_transport",+ }:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile marker is invalid."+ )+ return canonical_home+++def _prepare_subscription_login_home() -> Path:+ home = _validated_subscription_home(create=True, require_marker=False)+ marker = home / _SUBSCRIPTION_PROFILE_MARKER+ auth_file = home / "auth.json"+ if not marker.exists() and auth_file.exists():+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile already contains credentials that were "+ "not created by Jarvis's direct login flow."+ )+ if not marker.exists():+ payload = json.dumps(+ {+ "schema": _SUBSCRIPTION_PROFILE_SCHEMA,+ "purpose": "realtime_transport",+ },+ separators=(",", ":"),+ )+ temporary = home / f"{_SUBSCRIPTION_PROFILE_MARKER}.{secrets.token_hex(4)}.tmp"+ try:+ temporary.write_text(payload, encoding="utf-8")+ os.chmod(temporary, 0o600)+ os.replace(temporary, marker)+ except BaseException:+ with suppress(OSError):+ temporary.unlink()+ raise+ return _validated_subscription_home(create=False, require_marker=True)+++def _normalized_machine() -> str:+ machine = platform.machine().strip().lower()+ return {+ "aarch64": "arm64",+ "amd64": "x86_64",+ "x64": "x86_64",+ }.get(machine, machine)+++def _sha256_file(path: Path) -> str:+ digest = hashlib.sha256()+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0)+ descriptor = os.open(path, flags)+ with os.fdopen(descriptor, "rb") as handle:+ opened = os.fstat(handle.fileno())+ if not stat.S_ISREG(opened.st_mode):+ raise OSError("Codex executable is not a regular file.")+ while chunk := handle.read(1024 * 1024):+ digest.update(chunk)+ completed = os.fstat(handle.fileno())+ final = path.stat()+ stable_fields = ("st_dev", "st_ino", "st_size", "st_mtime_ns", "st_ctime_ns")+ if any(+ getattr(opened, field, None) != getattr(completed, field, None)+ or getattr(opened, field, None) != getattr(final, field, None)+ for field in stable_fields+ ):+ raise OSError("Codex executable changed while it was being verified.")+ return digest.hexdigest()+++def _trusted_native_codex_binary(resolved_binary: str, version: str | None) -> str:+ if version != _SUPPORTED_CODEX_VERSION:+ raise CodexSubscriptionUnavailable(+ f"Subscription voice requires Codex CLI {_SUPPORTED_CODEX_VERSION}."+ )+ if sys.platform != "win32":+ raise CodexSubscriptionContainmentUnavailable(+ "Experimental Codex subscription voice is unavailable on this platform "+ "until kill-on-parent-exit process containment is available."+ )+ target = _TRUSTED_CODEX_TARGETS.get((sys.platform, _normalized_machine()))+ if target is None:+ raise CodexSubscriptionUnavailable(+ "This operating-system architecture is not approved for the experimental "+ "Codex subscription voice transport."+ )+ variant, triple, executable_name, expected_hash = target+ try:+ launcher = Path(resolved_binary).resolve(strict=True)+ except OSError as exc:+ raise CodexSubscriptionUnavailable("The Codex CLI binary is unavailable.") from exc++ candidates: list[Path] = [launcher]+ roots = [launcher.parent, *list(launcher.parents)[:8]]+ package_roots: list[Path] = []+ for root in roots:+ if root.name == "codex" and root.parent.name == "@openai":+ package_roots.append(root)+ package_roots.append(root / "node_modules" / "@openai" / "codex")+ for package_root in package_roots:+ candidates.extend(+ (+ package_root+ / "node_modules"+ / "@openai"+ / f"codex-{variant}"+ / "vendor"+ / triple+ / "bin"+ / executable_name,+ package_root.parent+ / f"codex-{variant}"+ / "vendor"+ / triple+ / "bin"+ / executable_name,+ )+ )++ seen: set[str] = set()+ for candidate in candidates:+ try:+ canonical = candidate.resolve(strict=True)+ key = os.path.normcase(str(canonical))+ if key in seen:+ continue+ seen.add(key)+ if _is_link_or_reparse(canonical) or not canonical.is_file():+ continue+ if _sha256_file(canonical) == expected_hash:+ return str(canonical)+ except OSError: # Unreadable installation candidates are skipped during discovery.+ continue+ raise CodexSubscriptionUnavailable(+ "The installed Codex 0.146 executable does not match an official approved build."+ )+++def _read_codex_capability(binary_path: str | None) -> CodexAppServerCapability:+ """Resolve the CLI; app-server itself authoritatively reads its auth store.++ Discovery uses ``codex login status``, whose exact 0.146 output reports only+ the mode and never token contents or account PII. Billing authority comes+ only from the live ``account/read`` RPC below.+ """+ from jarvis.codex_auth import CodexAuthService # lazy: off the boot path++ service = CodexAuthService(+ binary_path,+ codex_home=codex_subscription_home(),+ force_file_auth_store=True,+ isolate_openai_environment=True,+ )+ resolved = service._resolve_binary()+ if resolved is None:+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=None,+ version=None,+ reason="Codex CLI is not installed.",+ reason_code="not_installed",+ )+ version = service._probe_version(resolved)+ try:+ resolved_binary = _trusted_native_codex_binary(+ resolved,+ version,+ )+ except CodexSubscriptionContainmentUnavailable as exc: # Expected platform gate becomes status.+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=None,+ version=version,+ reason=str(exc),+ reason_code="lifecycle_unavailable",+ )+ except CodexSubscriptionUnavailable as exc:+ # Convert setup failure into a safe status snapshot.+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=None,+ version=version,+ reason=str(exc),+ reason_code="setup_invalid",+ )+ try:+ home = _validated_subscription_home(+ create=False,+ require_marker=True,+ trusted_binary_path=resolved_binary,+ )+ except CodexSubscriptionProfileMissing as exc: # Missing login becomes an actionable snapshot.+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=resolved_binary,+ version=version,+ reason=str(exc),+ reason_code="login_required",+ )+ except CodexSubscriptionUnavailable as exc: # Unsafe profile state becomes a status snapshot.+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=resolved_binary,+ version=version,+ reason=str(exc),+ reason_code="setup_invalid",+ )+ status_log_dir = Path(tempfile.mkdtemp(prefix="jarvis-codex-status-"))+ try:+ logged_in, login_mode = CodexAuthService(+ resolved_binary,+ codex_home=home,+ force_file_auth_store=True,+ isolate_openai_environment=True,+ log_dir=status_log_dir,+ ).login_status()+ finally:+ shutil.rmtree(status_log_dir, ignore_errors=True)+ # Codex 0.146 creates only a persistent installation UUID plus its locked+ # tmp/arg0 aliases before parsing config. Validate that exact runtime+ # footprint after every status probe; any other state remains fail-closed.+ try:+ _validated_subscription_home(+ create=False,+ require_marker=True,+ trusted_binary_path=resolved_binary,+ )+ except CodexSubscriptionProfileMissing as exc:+ # Missing login remains a normal not-ready state.+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=resolved_binary,+ version=version,+ reason=str(exc),+ reason_code="login_required",+ )+ except CodexSubscriptionUnavailable as exc: # Profile validation failure is returned to the UI.+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=resolved_binary,+ version=version,+ reason=str(exc),+ reason_code="setup_invalid",+ )+ chatgpt_login = logged_in and login_mode == "chatgpt"+ return CodexAppServerCapability(+ available=True,+ # Advisory only: the CLI emits a fixed PII-free mode string. The live+ # account/read RPC below proves ChatGPT mode and the plan.+ chatgpt_authenticated=chatgpt_login,+ binary_path=resolved_binary,+ version=version,+ reason=(+ "Dedicated ChatGPT login is available."+ if chatgpt_login+ else "Use Jarvis's subscription-voice login to connect ChatGPT."+ ),+ reason_code="ready" if chatgpt_login else "login_required",+ )+++def _subscription_environment(+ codex_home: Path,+ workspace: _SafeTransportWorkspace,+) -> dict[str, str]:+ """Minimal child environment containing no inherited provider tokens.++ ``CODEX_HOME`` is the fixed Jarvis-owned identity. Provider, cloud, proxy,+ keyring-session, and billing-token environment variables are not inherited.+ """+ environment = {+ name: value+ for name, value in os.environ.items()+ if name.upper() in _SUBSCRIPTION_ENV_ALLOWLIST+ }+ environment.update(+ {+ "APPDATA": str(workspace.child_appdata),+ "CODEX_HOME": str(codex_home),+ "HOME": str(workspace.child_home),+ "LOCALAPPDATA": str(workspace.child_local_appdata),+ "RUST_BACKTRACE": "0",+ "RUST_LOG": "warn",+ "TEMP": str(workspace.child_tmp),+ "TMP": str(workspace.child_tmp),+ "TMPDIR": str(workspace.child_tmp),+ "USERPROFILE": str(workspace.child_home),+ }+ )+ environment.pop("HOMEDRIVE", None)+ environment.pop("HOMEPATH", None)+ # Persisted Remote Control is resolved before initialize/config audit in+ # Codex 0.146. This one documented process guard disables that startup+ # path before app-server can make any outbound connection.+ environment["CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED"] = "1"+ return environment+++def _create_safe_transport_workspace() -> _SafeTransportWorkspace:+ from jarvis.core.private_directory import ( # noqa: PLC0415+ ensure_owner_only_directory,+ )++ try:+ temporary_root = Path(tempfile.gettempdir()).resolve(strict=True)+ root = temporary_root / f"jarvis-codex-voice-{secrets.token_hex(16)}"+ ensure_owner_only_directory(root, create=True)+ root = root.resolve(strict=True)+ if root.parent != temporary_root:+ raise RuntimeError("The private workspace escaped its temporary root.")+ except (OSError, RuntimeError) as exc:+ raise CodexSubscriptionUnavailable(+ "The private Codex transport workspace could not be secured."+ ) from exc+ instructions = root / "transport-instructions.md"+ compact_prompt = root / "transport-compact-prompt.md"+ model_catalog = root / "model-catalog.json"+ sqlite_home = root / "sqlite"+ log_dir = root / "logs"+ child_home = root / "home"+ child_appdata = root / "appdata"+ child_local_appdata = root / "local-appdata"+ child_tmp = root / "tmp"+ try:+ instructions.write_text(_TRANSPORT_BASE_INSTRUCTIONS, encoding="utf-8")+ compact_prompt.write_text(_TRANSPORT_BASE_INSTRUCTIONS, encoding="utf-8")+ for directory in (+ sqlite_home,+ log_dir,+ child_home,+ child_appdata,+ child_local_appdata,+ child_tmp,+ ):+ directory.mkdir()+ model_catalog.write_text(+ json.dumps(+ {+ "models": [+ {+ "slug": "gpt-5.1-codex",+ "display_name": "Jarvis transport boundary",+ "description": None,+ "supported_reasoning_levels": [],+ "shell_type": "disabled",+ "visibility": "hide",+ "supported_in_api": True,+ "priority": 0,+ "availability_nux": None,+ "upgrade": None,+ "base_instructions": _TRANSPORT_BASE_INSTRUCTIONS,+ "model_messages": None,+ "support_verbosity": False,+ "default_verbosity": None,+ "apply_patch_tool_type": None,+ "truncation_policy": {"mode": "tokens", "limit": 10_000},+ "supports_parallel_tool_calls": False,+ "experimental_supported_tools": [],+ }+ ]+ },+ separators=(",", ":"),+ ),+ encoding="utf-8",+ )+ except BaseException:+ shutil.rmtree(root, ignore_errors=True)+ raise+ return _SafeTransportWorkspace(+ root=root,+ instructions=instructions,+ compact_prompt=compact_prompt,+ model_catalog=model_catalog,+ sqlite_home=sqlite_home,+ log_dir=log_dir,+ child_home=child_home,+ child_appdata=child_appdata,+ child_local_appdata=child_local_appdata,+ child_tmp=child_tmp,+ )+++def _windows_creationflags(*, allow_breakaway: bool) -> int:+ flags = NO_WINDOW_CREATIONFLAGS+ if sys.platform == "win32" and allow_breakaway:+ flags |= getattr(subprocess, "CREATE_BREAKAWAY_FROM_JOB", 0x01000000)+ return flags+++def _thread_id_from_params(params: Mapping[str, Any]) -> str | None:+ direct = params.get("threadId")+ if isinstance(direct, str) and direct:+ return direct+ for key in ("thread", "turn", "item"):+ nested = params.get(key)+ if not isinstance(nested, Mapping):+ continue+ value = nested.get("threadId")+ if isinstance(value, str) and value:+ return value+ if key == "thread":+ value = nested.get("id")+ if isinstance(value, str) and value:+ return value+ return None+++def _result_dict(method: str, result: Any) -> dict[str, Any]:+ if isinstance(result, dict):+ return result+ raise CodexAppServerError(f"Codex app-server returned an invalid {method} result.")+++def _config_layers(result: Mapping[str, Any]) -> tuple[Mapping[str, Any], ...]:+ raw_layers = result.get("layers")+ if not isinstance(raw_layers, list):+ raise CodexSubscriptionUnavailable(+ "Codex effective configuration could not be verified."+ )+ layers: list[Mapping[str, Any]] = []+ for layer in raw_layers:+ if not isinstance(layer, Mapping):+ raise CodexSubscriptionUnavailable(+ "Codex effective configuration contained an invalid layer."+ )+ config = layer.get("config")+ if not isinstance(config, Mapping):+ raise CodexSubscriptionUnavailable(+ "Codex effective configuration contained an unreadable layer."+ )+ layers.append(config)+ return tuple(layers)+++def _config_layer_entries(+ result: Mapping[str, Any],+) -> tuple[tuple[str, Mapping[str, Any]], ...]:+ raw_layers = result.get("layers")+ if not isinstance(raw_layers, list):+ raise CodexSubscriptionUnavailable(+ "Codex effective configuration could not be verified."+ )+ entries: list[tuple[str, Mapping[str, Any]]] = []+ for layer in raw_layers:+ if not isinstance(layer, Mapping):+ raise CodexSubscriptionUnavailable(+ "Codex effective configuration contained an invalid layer."+ )+ raw_name = layer.get("name")+ if isinstance(raw_name, Mapping):+ raw_name = raw_name.get("type")+ if not isinstance(raw_name, str) or not raw_name:+ raise CodexSubscriptionUnavailable(+ "Codex effective configuration contained an unnamed layer."+ )+ config = layer.get("config")+ if not isinstance(config, Mapping):+ raise CodexSubscriptionUnavailable(+ "Codex effective configuration contained an unreadable layer."+ )+ entries.append((raw_name, config))+ return tuple(entries)+++def _layer_value(+ layers: Sequence[Mapping[str, Any]], path: Sequence[str]+) -> Any:+ """Return the highest-precedence explicitly configured value for a path."""+ for layer in layers: # config/read returns highest precedence first.+ value: Any = layer+ for part in path:+ if not isinstance(value, Mapping) or part not in value:+ value = _MISSING+ break+ value = value[part]+ if value is not _MISSING:+ return value+ return _MISSING+++def _mcp_server_ids(layers: Sequence[Mapping[str, Any]]) -> tuple[str, ...]:+ names: set[str] = set()+ for layer in layers:+ servers = layer.get("mcp_servers")+ if isinstance(servers, Mapping):+ names.update(str(name) for name in servers if str(name))+ return tuple(sorted(names))+++class CodexNotificationSubscription:+ """A notification queue bound to exactly one app-server thread."""++ def __init__(+ self,+ client: CodexAppServerClient,+ thread_id: str,+ max_queue_size: int,+ ) -> None:+ self._client = client+ self.thread_id = thread_id+ self._queue: asyncio.Queue[_SubscriptionItem] = asyncio.Queue(maxsize=max_queue_size)+ self._closed = False++ async def get(self, timeout_s: float | None = None) -> CodexAppServerNotification:+ """Return the next notification, with an optional bounded wait."""+ try:+ if timeout_s is None:+ item = await self._queue.get()+ else:+ item = await asyncio.wait_for(self._queue.get(), timeout=timeout_s)+ except TimeoutError as exc:+ raise CodexAppServerTimeout(+ f"Timed out waiting for a Codex notification on {self.thread_id}."+ ) from exc+ if item is _SUBSCRIPTION_END:+ raise CodexAppServerDisconnected("Codex notification subscription closed.")+ if isinstance(item, BaseException):+ raise item+ if not isinstance(item, CodexAppServerNotification):+ raise CodexAppServerDisconnected("Codex notification stream is invalid.")+ return item++ async def wait_for(+ self, method: str, timeout_s: float | None = None+ ) -> CodexAppServerNotification:+ """Wait for one method on this subscription.++ Non-matching items are consumed only from this subscription. Callers+ that need the complete stream should keep their own parallel+ subscription; notifications are broadcast to every subscriber.+ """+ deadline = None+ if timeout_s is not None:+ deadline = asyncio.get_running_loop().time() + timeout_s+ while True:+ remaining = None+ if deadline is not None:+ remaining = deadline - asyncio.get_running_loop().time()+ if remaining <= 0:+ raise CodexAppServerTimeout(+ f"Timed out waiting for Codex notification {method}."+ )+ notification = await self.get(remaining)+ if notification.method == method:+ return notification++ def close(self) -> None:+ """Unregister this local subscriber. Safe to call more than once."""+ if self._closed:+ return+ self._closed = True+ self._client._remove_subscription(self)+ self._replace_queue_with(_SUBSCRIPTION_END)++ def _publish(self, item: _SubscriptionItem) -> None:+ if self._closed:+ return+ try:+ self._queue.put_nowait(item)+ except asyncio.QueueFull:+ # Continuing with missing audio/transcript frames would corrupt the+ # session invisibly. Terminate this subscriber and replace every+ # queued frame with one explicit overflow error instead.+ self._closed = True+ self._client._remove_subscription(self)+ self._replace_queue_with(+ CodexNotificationOverflow(+ "Codex realtime notification buffer overflowed; session closed."+ )+ )++ def _fail(self, error: BaseException) -> None:+ if self._closed:+ return+ self._closed = True+ self._client._remove_subscription(self)+ self._replace_queue_with(error)++ def _replace_queue_with(self, item: _SubscriptionItem) -> None:+ while True:+ try:+ self._queue.get_nowait()+ except asyncio.QueueEmpty: # The terminal item can now fit without a drop.+ break+ self._queue.put_nowait(item)++ async def __aenter__(self) -> CodexNotificationSubscription:+ return self++ async def __aexit__(self, *_exc: object) -> None:+ self.close()++ def __aiter__(self) -> AsyncIterator[CodexAppServerNotification]:+ return self++ async def __anext__(self) -> CodexAppServerNotification:+ try:+ return await self.get()+ except CodexAppServerDisconnected:+ raise StopAsyncIteration from None+++class CodexAppServerClient:+ """Lazy JSONL client for one persistent ``codex app-server`` process."""++ def __init__(+ self,+ binary_path: str | None = None,+ request_timeout_s: float = _DEFAULT_REQUEST_TIMEOUT_S,+ ) -> None:+ self._binary_path = (binary_path or "").strip() or None+ self._request_timeout_s = max(0.1, float(request_timeout_s))+ self._child_environment: dict[str, str] = {}+ self._process: asyncio.subprocess.Process | None = None+ self._process_tree: ProcessTree | None = None+ self._reader_task: asyncio.Task[None] | None = None+ self._stderr_task: asyncio.Task[None] | None = None+ self._start_lock = asyncio.Lock()+ self._thread_start_lock = asyncio.Lock()+ self._write_lock = asyncio.Lock()+ self._pending: dict[int, tuple[str, asyncio.Future[Any]]] = {}+ self._subscriptions: dict[str, set[CodexNotificationSubscription]] = {}+ self._next_request_id = 1+ self._workspace: _SafeTransportWorkspace | None = None+ self._sink_server: asyncio.Server | None = None+ self._sink_base_url: str | None = None+ self._trusted_binary_path: str | None = None+ self._profile_transport_reserved = False+ self._owner_loop: asyncio.AbstractEventLoop | None = None+ self._transport_provider_id = f"jarvis_voice_{secrets.token_hex(16)}"+ self._ready = False++ def _assert_owner_loop(self) -> asyncio.AbstractEventLoop:+ loop = asyncio.get_running_loop()+ if self._owner_loop is None:+ self._owner_loop = loop+ elif self._owner_loop is not loop:+ raise CodexSubscriptionUnavailable(+ "Codex app-server client ownership cannot cross event loops."+ )+ return loop++ async def capability_status(self) -> CodexAppServerCapability:+ """Return a bounded, PII-free ChatGPT-login capability snapshot."""+ try:+ # The subprocesses inside this synchronous probe each have their own+ # hard timeout. Do not wrap ``to_thread`` in ``wait_for``: cancelling+ # that await leaves the worker thread running against CODEX_HOME and+ # would release the profile mutation gate too early.+ return await asyncio.to_thread(_read_codex_capability, self._binary_path)+ except TimeoutError: # The returned status reports this bounded probe failure.+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=None,+ version=None,+ reason="Codex login status timed out.",+ reason_code="setup_invalid",+ )+ except Exception as exc: # noqa: BLE001 - status must degrade honestly+ log.warning(+ "Codex subscription status failed (%s); app-server stays disabled",+ type(exc).__name__,+ )+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=None,+ version=None,+ reason="Codex login status could not be verified.",+ reason_code="setup_invalid",+ )++ @property+ def running(self) -> bool:+ process = self._process+ return process is not None and process.returncode is None++ @property+ def ready(self) -> bool:+ """Whether handshake and live ChatGPT account verification completed."""+ return self.running and self._ready++ async def ensure_started(self) -> None:+ """Start and initialize app-server once, only when first needed."""+ self._assert_owner_loop()+ if self.ready:+ return+ async with self._start_lock:+ if self.ready:+ return+ if self._process is not None:+ await self._close_process(+ CodexAppServerDisconnected("Codex app-server exited."),+ expected=False,+ )++ _reserve_subscription_transport(self)+ self._profile_transport_reserved = True++ try:+ capability = await self.capability_status()+ except BaseException:+ _release_subscription_transport(self)+ self._profile_transport_reserved = False+ raise+ if not capability.available:+ _release_subscription_transport(self)+ self._profile_transport_reserved = False+ raise CodexSubscriptionUnavailable(capability.reason)+ if not capability.binary_path:+ _release_subscription_transport(self)+ self._profile_transport_reserved = False+ raise CodexSubscriptionUnavailable("Codex CLI binary is unavailable.")+ try:+ self._trusted_binary_path = capability.binary_path+ codex_home = await asyncio.to_thread(+ _validated_subscription_home,+ create=False,+ require_marker=True,+ trusted_binary_path=self._trusted_binary_path,+ )+ if self._workspace is None:+ self._workspace = await asyncio.to_thread(+ _create_safe_transport_workspace+ )+ self._child_environment = _subscription_environment(+ codex_home,+ self._workspace,+ )+ await self._ensure_sink_started()+ await self._spawn(capability.binary_path)+ await self._initialize_live_process()+ await self._verify_live_chatgpt_account()+ self._audit_config_requirements(+ await self._read_config_requirements()+ )+ final_config = await self._read_effective_config()+ self._audit_effective_config(final_config)+ await asyncio.to_thread(+ _validated_subscription_home,+ create=False,+ require_marker=True,+ trusted_binary_path=self._trusted_binary_path,+ )+ self._ready = True+ except BaseException:+ await self._close_process(+ CodexAppServerDisconnected("Codex app-server initialization failed."),+ expected=False,+ )+ raise++ async def _initialize_live_process(self) -> None:+ await self._request_live(+ "initialize",+ {+ "clientInfo": {+ "name": "personal_jarvis",+ "title": "Personal Jarvis",+ "version": __version__,+ },+ "capabilities": {+ "experimentalApi": True,+ "mcpServerOpenaiFormElicitation": False,+ "requestAttestation": False,+ },+ },+ timeout_s=self._request_timeout_s,+ )+ await self._notify_live("initialized", None)++ async def _verify_live_chatgpt_account(self) -> None:+ account_result = _result_dict(+ "account/read",+ await self._request_live(+ "account/read",+ {"refreshToken": False},+ timeout_s=self._request_timeout_s,+ ),+ )+ account = account_result.get("account")+ account_type = account.get("type") if isinstance(account, Mapping) else None+ if account_type != "chatgpt" or account_result.get("requiresOpenaiAuth") is not True:+ raise CodexSubscriptionUnavailable(+ "Codex app-server is not using ChatGPT authentication."+ )+ plan_type = account.get("planType") if isinstance(account, Mapping) else None+ if plan_type not in _PERSONAL_CHATGPT_PLANS:+ raise CodexSubscriptionUnavailable(+ "Subscription voice permits only personal ChatGPT accounts; workspace, "+ "enterprise, education, and unknown plans are refused."+ )++ async def require_chatgpt_login(self) -> None:+ """Verify the current app-server account through Codex's real store."""+ await self.ensure_started()+ try:+ await self._verify_live_chatgpt_account()+ except CodexSubscriptionUnavailable:+ await self._close_process(+ CodexAppServerDisconnected(+ "Codex app-server authentication is not ChatGPT."+ ),+ expected=False,+ )+ raise++ async def _read_effective_config(self) -> dict[str, Any]:+ return _result_dict(+ "config/read",+ await self._request_live(+ "config/read",+ {"cwd": self._safe_thread_cwd(), "includeLayers": True},+ timeout_s=self._request_timeout_s,+ ),+ )++ async def _read_config_requirements(self) -> dict[str, Any]:+ return _result_dict(+ "configRequirements/read",+ await self._request_live(+ "configRequirements/read",+ {},+ timeout_s=self._request_timeout_s,+ ),+ )++ @staticmethod+ def _audit_config_requirements(result: Mapping[str, Any]) -> None:+ if set(result) != {"requirements"} or result.get("requirements") is not None:+ raise CodexSubscriptionUnavailable(+ "Codex subscription voice refuses managed configuration requirements."+ )++ async def _ensure_sink_started(self) -> None:+ if self._sink_server is not None:+ return++ async def reject_connection(+ _reader: asyncio.StreamReader,+ writer: asyncio.StreamWriter,+ ) -> None:+ try:+ writer.write(+ b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n"+ b"Connection: close\r\n\r\n"+ )+ await writer.drain()+ except (ConnectionError, OSError):+ # The diagnostic sink peer may close before its reply.+ pass+ finally:+ writer.close()+ with suppress(Exception):+ await writer.wait_closed()++ try:+ server = await asyncio.start_server(reject_connection, "127.0.0.1", 0)+ except OSError as exc:+ raise CodexSubscriptionUnavailable(+ "The local Codex billing-isolation sink could not be started."+ ) from exc+ sockets = server.sockets or ()+ if len(sockets) != 1:+ server.close()+ await server.wait_closed()+ raise CodexSubscriptionUnavailable(+ "The local Codex billing-isolation sink is unavailable."+ )+ address = sockets[0].getsockname()+ if not isinstance(address, tuple) or len(address) < 2:+ server.close()+ await server.wait_closed()+ raise CodexSubscriptionUnavailable(+ "The local Codex billing-isolation sink returned an invalid address."+ )+ self._sink_server = server+ self._sink_base_url = f"http://127.0.0.1:{int(address[1])}/v1"++ def _audit_effective_config(+ self,+ result: Mapping[str, Any],+ ) -> None:+ entries = _config_layer_entries(result)+ layers = tuple(config for _name, config in entries)+ session_layers = [config for name, config in entries if name == "sessionFlags"]+ if len(session_layers) != 1:+ raise CodexSubscriptionUnavailable(+ "Codex session configuration provenance could not be verified."+ )+ for name, config in entries:+ if name != "sessionFlags" and config:+ raise CodexSubscriptionUnavailable(+ "Codex subscription voice refuses non-empty user, project, system, "+ "MDM, enterprise, profile, or legacy configuration layers."+ )++ expected_paths: dict[tuple[str, ...], Any] = {+ ("analytics", "enabled"): False,+ ("approval_policy",): "never",+ ("cli_auth_credentials_store",): "file",+ ("chatgpt_base_url",): _OFFICIAL_CHATGPT_BASE,+ ("experimental_realtime_webrtc_call_base_url",): (+ _OFFICIAL_CHATGPT_CODEX_BASE+ ),+ ("experimental_realtime_start_instructions",): "",+ ("experimental_realtime_ws_backend_prompt",): (+ ""+ ),+ ("experimental_realtime_ws_base_url",): (+ _OFFICIAL_OPENAI_REALTIME_BASE+ ),+ ("history", "persistence"): "none",+ ("include_apps_instructions",): False,+ ("include_collaboration_mode_instructions",): False,+ ("include_environment_context",): False,+ ("include_permissions_instructions",): False,+ ("memories", "dedicated_tools"): False,+ ("memories", "generate_memories"): False,+ ("memories", "use_memories"): False,+ ("model_provider",): self._transport_provider_id,+ ("experimental_compact_prompt_file",): self._compact_prompt_file(),+ ("log_dir",): self._log_dir(),+ ("model_catalog_json",): self._model_catalog_file(),+ ("model_instructions_file",): self._safe_instructions_file(),+ ("notify",): [],+ ("openai_base_url",): _OFFICIAL_OPENAI_API_BASE,+ ("orchestrator", "mcp", "enabled"): False,+ ("orchestrator", "skills", "enabled"): False,+ ("otel", "exporter"): "none",+ ("otel", "log_user_prompt"): False,+ ("otel", "metrics_exporter"): "none",+ ("otel", "trace_exporter"): "none",+ ("project_doc_max_bytes",): 0,+ ("sandbox_mode",): "read-only",+ ("sqlite_home",): self._sqlite_home(),+ ("skills", "bundled", "enabled"): False,+ ("skills", "include_instructions"): False,+ ("tools", "web_search"): False,+ }+ for feature in _DISABLED_APP_SERVER_FEATURES:+ expected_paths[("features", feature)] = False+ expected_paths[("features", "realtime_conversation")] = True+ provider_prefix = ("model_providers", self._transport_provider_id)+ expected_paths.update(+ {+ (*provider_prefix, "base_url"): self._provider_sink_base_url(),+ (*provider_prefix, "name"): "OpenAI ChatGPT subscription voice",+ (*provider_prefix, "requires_openai_auth"): True,+ (*provider_prefix, "request_max_retries"): 0,+ (*provider_prefix, "supports_standalone_web_search"): False,+ (*provider_prefix, "supports_websockets"): False,+ (*provider_prefix, "stream_max_retries"): 0,+ (*provider_prefix, "wire_api"): "responses",+ }+ )+ if sys.platform == "win32":+ expected_paths[("windows", "sandbox")] = "unelevated"+ for path, expected in expected_paths.items():+ if _layer_value(layers, path) != expected:+ raise CodexSubscriptionUnavailable(+ "Codex effective configuration failed the transport safety audit."+ )++ allowed_paths = set(expected_paths)++ def walk(value: Any, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]:+ if isinstance(value, Mapping):+ leaves: list[tuple[str, ...]] = []+ for key, child in value.items():+ leaves.extend(walk(child, (*prefix, str(key))))+ return leaves+ return [prefix]++ if any(path not in allowed_paths for path in walk(session_layers[0])):+ raise CodexSubscriptionUnavailable(+ "Codex session flags exposed an unapproved configuration surface."+ )++ raw_layers = result.get("layers")+ if not isinstance(raw_layers, list):+ raise CodexSubscriptionUnavailable(+ "Codex configuration provenance could not be verified."+ )+ session_metadata = [+ layer+ for layer in raw_layers+ if isinstance(layer, Mapping)+ and isinstance(layer.get("name"), Mapping)+ and layer["name"].get("type") == "sessionFlags"+ ]+ if len(session_metadata) != 1:+ raise CodexSubscriptionUnavailable(+ "Codex session configuration provenance could not be verified."+ )+ session_version = session_metadata[0].get("version")+ if not isinstance(session_version, str) or not session_version:+ raise CodexSubscriptionUnavailable(+ "Codex session configuration version could not be verified."+ )+ origins = result.get("origins")+ expected_origin_keys = {+ ".".join(path)+ for path, expected in expected_paths.items()+ if expected not in ([], {})+ }+ if not isinstance(origins, Mapping) or set(origins) != expected_origin_keys:+ raise CodexSubscriptionUnavailable(+ "Codex configuration origins failed the transport safety audit."+ )+ for metadata in origins.values():+ source = metadata.get("name") if isinstance(metadata, Mapping) else None+ if (+ not isinstance(source, Mapping)+ or source.get("type") != "sessionFlags"+ or metadata.get("version") != session_version+ ):+ raise CodexSubscriptionUnavailable(+ "A Codex safety setting came from an unapproved configuration layer."+ )++ public_config = result.get("config")+ if not isinstance(public_config, Mapping):+ raise CodexSubscriptionUnavailable(+ "Codex effective configuration could not be verified."+ )+ public_expected = {+ "analytics": {"enabled": False},+ "approval_policy": "never",+ "model_provider": self._transport_provider_id,+ "sandbox_mode": "read-only",+ }+ for key, expected in public_expected.items():+ if public_config.get(key) != expected:+ raise CodexSubscriptionUnavailable(+ "Codex managed configuration overrode a required safety setting."+ )++ async def _spawn(+ self,+ binary_path: str,+ ) -> None:+ command = [+ binary_path,+ "app-server",+ "--strict-config",+ "--enable",+ "realtime_conversation",+ ]+ for feature in _DISABLED_APP_SERVER_FEATURES:+ command.extend(("--disable", feature))+ command.extend(+ (+ "-c",+ "notify=[]",+ "-c",+ 'openai_base_url="https://api.openai.com/v1"',+ "-c",+ 'chatgpt_base_url="https://chatgpt.com/backend-api/"',+ "-c",+ (+ 'experimental_realtime_ws_base_url='+ '"https://api.openai.com/v1"'+ ),+ "-c",+ (+ 'experimental_realtime_webrtc_call_base_url='+ '"https://chatgpt.com/backend-api/codex"'+ ),+ "-c",+ 'experimental_realtime_start_instructions=""',+ "-c",+ (+ "experimental_realtime_ws_backend_prompt="+ '""'+ ),+ "-c",+ "tools.web_search=false",+ "-c",+ 'history.persistence="none"',+ "-c",+ "include_apps_instructions=false",+ "-c",+ "include_collaboration_mode_instructions=false",+ "-c",+ "include_environment_context=false",+ "-c",+ "include_permissions_instructions=false",+ "-c",+ "memories.dedicated_tools=false",+ "-c",+ "memories.generate_memories=false",+ "-c",+ "memories.use_memories=false",+ "-c",+ "orchestrator.mcp.enabled=false",+ "-c",+ "orchestrator.skills.enabled=false",+ "-c",+ "skills.bundled.enabled=false",+ "-c",+ "skills.include_instructions=false",+ "-c",+ (+ "model_instructions_file="+ f"{json.dumps(self._safe_instructions_file())}"+ ),+ "-c",+ (+ "experimental_compact_prompt_file="+ f"{json.dumps(self._compact_prompt_file())}"+ ),+ "-c",+ f"log_dir={json.dumps(self._log_dir())}",+ "-c",+ f"model_catalog_json={json.dumps(self._model_catalog_file())}",+ "-c",+ f"sqlite_home={json.dumps(self._sqlite_home())}",+ "-c",+ "analytics.enabled=false",+ "-c",+ 'cli_auth_credentials_store="file"',+ "-c",+ "project_doc_max_bytes=0",+ "-c",+ 'otel.exporter="none"',+ "-c",+ 'otel.trace_exporter="none"',+ "-c",+ 'otel.metrics_exporter="none"',+ "-c",+ "otel.log_user_prompt=false",+ "-c",+ 'approval_policy="never"',+ "-c",+ 'sandbox_mode="read-only"',+ )+ )+ provider = f"model_providers.{self._transport_provider_id}"+ command.extend(+ (+ "-c",+ f'{provider}.name="OpenAI ChatGPT subscription voice"',+ "-c",+ f"{provider}.base_url={json.dumps(self._provider_sink_base_url())}",+ "-c",+ f'{provider}.wire_api="responses"',+ "-c",+ f"{provider}.requires_openai_auth=true",+ "-c",+ f"{provider}.supports_websockets=false",+ "-c",+ f"{provider}.supports_standalone_web_search=false",+ "-c",+ f"{provider}.request_max_retries=0",+ "-c",+ f"{provider}.stream_max_retries=0",+ "-c",+ f'model_provider="{self._transport_provider_id}"',+ )+ )+ if sys.platform == "win32":+ command.extend(("-c", 'windows.sandbox="unelevated"'))+ kwargs: dict[str, Any] = {+ "env": dict(self._child_environment),+ "stdin": asyncio.subprocess.PIPE,+ "stdout": asyncio.subprocess.PIPE,+ "stderr": asyncio.subprocess.PIPE,+ "cwd": self._safe_thread_cwd(),+ }+ if sys.platform != "win32":+ kwargs["start_new_session"] = True+ kwargs["pass_fds"] = _subscription_transport_pass_fds(self)++ tree = make_process_tree("codex-app-server")+ if not bool(getattr(tree, "supports_containment", False)):+ tree.close()+ raise CodexSubscriptionUnavailable(+ "Codex app-server process-tree containment is unavailable."+ )+ try:+ process = await asyncio.create_subprocess_exec(+ *command,+ creationflags=_windows_creationflags(allow_breakaway=True),+ **kwargs,+ )+ except PermissionError:+ if sys.platform != "win32":+ tree.close()+ raise+ log.warning(+ "Codex app-server breakaway was denied; retrying with no-window process flags"+ )+ try:+ process = await asyncio.create_subprocess_exec(+ *command,+ creationflags=_windows_creationflags(allow_breakaway=False),+ **kwargs,+ )+ except BaseException:+ tree.close()+ raise+ except BaseException:+ tree.close()+ raise++ self._process = process+ self._process_tree = tree+ try:+ tree.assign(process.pid)+ except Exception as exc: # noqa: BLE001 - containment is mandatory+ self._process = None+ self._process_tree = None+ with suppress(ProcessLookupError, OSError):+ process.kill()+ with suppress(Exception):+ await asyncio.wait_for(process.wait(), timeout=_SHUTDOWN_TIMEOUT_S)+ tree.close()+ raise CodexSubscriptionUnavailable(+ "Codex app-server process containment could not be established."+ ) from exc+ self._reader_task = asyncio.create_task(+ self._reader_loop(process), name="codex-app-server-stdout"+ )+ self._stderr_task = asyncio.create_task(+ self._stderr_loop(process), name="codex-app-server-stderr"+ )+ log.info("Codex app-server process started; account verification pending")++ async def request(+ self,+ method: str,+ params: Mapping[str, Any] | None = None,+ *,+ timeout_s: float | None = None,+ ) -> Any:+ """Send one request and await only its own response future."""+ await self.ensure_started()+ return await self._request_live(method, params, timeout_s=timeout_s)++ async def notify(self, method: str, params: Mapping[str, Any] | None = None) -> None:+ """Send a client notification after lazily starting the process."""+ await self.ensure_started()+ await self._notify_live(method, params)++ async def _request_live(+ self,+ method: str,+ params: Mapping[str, Any] | None,+ *,+ timeout_s: float | None,+ ) -> Any:+ process = self._require_live_process()+ request_id = self._next_request_id+ self._next_request_id += 1+ future: asyncio.Future[Any] = asyncio.get_running_loop().create_future()+ self._pending[request_id] = (method, future)+ message: dict[str, Any] = {"id": request_id, "method": method}+ if params is not None:+ message["params"] = dict(params)+ try:+ await self._write_frame(process, message)+ budget = self._request_timeout_s if timeout_s is None else timeout_s+ try:+ return await asyncio.wait_for(asyncio.shield(future), timeout=budget)+ except TimeoutError as exc:+ raise CodexAppServerTimeout(+ f"Codex app-server request {method} timed out."+ ) from exc+ finally:+ self._pending.pop(request_id, None)+ if not future.done():+ future.cancel()++ async def _notify_live(self, method: str, params: Mapping[str, Any] | None) -> None:+ process = self._require_live_process()+ message: dict[str, Any] = {"method": method}+ if params is not None:+ message["params"] = dict(params)+ await self._write_frame(process, message)++ def _require_live_process(self) -> asyncio.subprocess.Process:+ process = self._process+ if process is None or process.returncode is not None:+ raise CodexAppServerDisconnected("Codex app-server is not running.")+ return process++ async def _write_frame(+ self, process: asyncio.subprocess.Process, message: Mapping[str, Any]+ ) -> None:+ try:+ payload = (+ json.dumps(message, ensure_ascii=False, separators=(",", ":")).encode("utf-8")+ + b"\n"+ )+ except (TypeError, ValueError) as exc:+ raise CodexAppServerError("Codex app-server request is not JSON-safe.") from exc++ async with self._write_lock:+ if process is not self._process or process.returncode is not None:+ raise CodexAppServerDisconnected("Codex app-server exited.")+ stdin = process.stdin+ if stdin is None:+ raise CodexAppServerDisconnected("Codex app-server stdin is unavailable.")+ try:+ stdin.write(payload)+ await stdin.drain()+ except (BrokenPipeError, ConnectionError, OSError) as exc:+ await self._close_process(+ CodexAppServerDisconnected("Codex app-server input closed."),+ expected=False,+ )+ raise CodexAppServerDisconnected("Codex app-server input closed.") from exc++ async def _reader_loop(self, process: asyncio.subprocess.Process) -> None:+ stream = process.stdout+ if stream is None:+ await self._close_process(+ CodexAppServerDisconnected("Codex app-server stdout is unavailable."),+ expected=False,+ )+ return+ try:+ while True:+ line = await stream.readline()+ if not line:+ break+ try:+ message = json.loads(line.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError):+ log.warning(+ "Codex app-server emitted an invalid JSONL frame (%d bytes; "+ "content redacted)",+ len(line),+ )+ continue+ if not isinstance(message, dict):+ log.warning("Codex app-server emitted a non-object JSONL frame")+ continue+ await self._handle_message(process, message)+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 - convert transport failure+ log.warning("Codex app-server stdout reader failed (%s)", type(exc).__name__)+ finally:+ if process is self._process:+ await self._close_process(+ CodexAppServerDisconnected("Codex app-server output closed."),+ expected=False,+ )++ async def _stderr_loop(self, process: asyncio.subprocess.Process) -> None:+ stream = process.stderr+ if stream is None:+ return+ try:+ while True:+ line = await stream.readline()+ if not line:+ return+ # Stderr can contain prompts, paths, account labels, or upstream+ # request details. Record that diagnostics exist without+ # copying their contents into Jarvis's world-readable logs.+ log.debug(+ "Codex app-server diagnostic received (%d bytes; content redacted)",+ len(line),+ )+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 - stderr is diagnostic only+ log.warning("Codex app-server stderr reader failed (%s)", type(exc).__name__)++ async def _handle_message(+ self, process: asyncio.subprocess.Process, message: dict[str, Any]+ ) -> None:+ if process is not self._process:+ return+ request_id = message.get("id")+ method = message.get("method")+ if request_id is not None and isinstance(method, str):+ await self._deny_server_request(process, request_id, method)+ return+ if request_id is not None and ("result" in message or "error" in message):+ if not isinstance(request_id, int):+ return+ pending = self._pending.get(request_id)+ if pending is None:+ log.debug("Codex app-server returned an unknown request id")+ return+ pending_method, future = pending+ if future.done():+ return+ if "error" in message:+ error = message.get("error")+ code = error.get("code") if isinstance(error, Mapping) else None+ future.set_exception(+ CodexAppServerRPCError(pending_method, code if isinstance(code, int) else None)+ )+ else:+ future.set_result(message.get("result"))+ return+ if isinstance(method, str):+ params = message.get("params")+ safe_params = dict(params) if isinstance(params, Mapping) else {}+ thread_id = _thread_id_from_params(safe_params)+ if thread_id is None:+ return+ notification = CodexAppServerNotification(method, safe_params)+ for subscription in tuple(self._subscriptions.get(thread_id, ())):+ subscription._publish(notification)++ async def _deny_server_request(+ self, process: asyncio.subprocess.Process, request_id: Any, method: str+ ) -> None:+ """Fail closed for every server-initiated action request."""+ if method in _DECLINE_REQUEST_METHODS:+ response: dict[str, Any] = {+ "id": request_id,+ "result": {"decision": "decline"},+ }+ elif method in _DYNAMIC_TOOL_REQUEST_METHODS:+ response = {+ "id": request_id,+ "result": {"contentItems": [], "success": False},+ }+ else:+ response = {+ "id": request_id,+ "error": {+ "code": -32000,+ "message": "Personal Jarvis does not permit server-initiated actions.",+ },+ }+ log.warning("Denied Codex app-server request method %s", method)+ await self._write_frame(process, response)++ def subscribe(+ self,+ thread_id: str,+ *,+ max_queue_size: int = _DEFAULT_NOTIFICATION_QUEUE_SIZE,+ ) -> CodexNotificationSubscription:+ """Register a local broadcast subscription before starting a session."""+ self._assert_owner_loop()+ if not isinstance(thread_id, str) or not thread_id.strip():+ raise ValueError("thread_id must be a non-empty string")+ if max_queue_size < 1:+ raise ValueError("max_queue_size must be at least one")+ subscription = CodexNotificationSubscription(self, thread_id, max_queue_size=max_queue_size)+ self._subscriptions.setdefault(thread_id, set()).add(subscription)+ return subscription++ def _remove_subscription(self, subscription: CodexNotificationSubscription) -> None:+ subscribers = self._subscriptions.get(subscription.thread_id)+ if not subscribers:+ return+ subscribers.discard(subscription)+ if not subscribers:+ self._subscriptions.pop(subscription.thread_id, None)++ def _safe_thread_cwd(self) -> str:+ if self._workspace is None:+ raise CodexSubscriptionUnavailable(+ "Codex transport workspace is unavailable."+ )+ return str(self._workspace.root)++ def _safe_instructions_file(self) -> str:+ """Return the isolated transport-only model instructions file."""+ if self._workspace is None:+ raise CodexSubscriptionUnavailable(+ "Codex transport instruction boundary is unavailable."+ )+ return str(self._workspace.instructions)++ def _compact_prompt_file(self) -> str:+ if self._workspace is None:+ raise CodexSubscriptionUnavailable(+ "Codex transport compact-prompt boundary is unavailable."+ )+ return str(self._workspace.compact_prompt)++ def _model_catalog_file(self) -> str:+ if self._workspace is None:+ raise CodexSubscriptionUnavailable(+ "Codex transport model catalog is unavailable."+ )+ return str(self._workspace.model_catalog)++ def _sqlite_home(self) -> str:+ if self._workspace is None:+ raise CodexSubscriptionUnavailable(+ "Codex transport SQLite boundary is unavailable."+ )+ return str(self._workspace.sqlite_home)++ def _log_dir(self) -> str:+ if self._workspace is None:+ raise CodexSubscriptionUnavailable(+ "Codex transport log boundary is unavailable."+ )+ return str(self._workspace.log_dir)++ def _provider_sink_base_url(self) -> str:+ if not self._sink_base_url:+ raise CodexSubscriptionUnavailable(+ "Codex billing-isolation sink is unavailable."+ )+ return self._sink_base_url++ def _audit_thread_start_response(self, result: Mapping[str, Any]) -> None:+ thread = result.get("thread")+ sandbox = result.get("sandbox")+ expected_cwd = os.path.normcase(os.path.abspath(self._safe_thread_cwd()))+ response_cwd = result.get("cwd")+ thread_cwd = thread.get("cwd") if isinstance(thread, Mapping) else None+ instruction_sources = result.get("instructionSources", [])+ if (+ not isinstance(thread, Mapping)+ or not isinstance(thread.get("id"), str)+ or not thread["id"]+ or thread.get("ephemeral") is not True+ or thread.get("modelProvider") != self._transport_provider_id+ or not isinstance(response_cwd, str)+ or os.path.normcase(os.path.abspath(response_cwd)) != expected_cwd+ or not isinstance(thread_cwd, str)+ or os.path.normcase(os.path.abspath(thread_cwd)) != expected_cwd+ or result.get("approvalPolicy") != "never"+ or result.get("model") != "gpt-5.1-codex"+ or result.get("modelProvider") != self._transport_provider_id+ or sandbox != {"type": "readOnly", "networkAccess": False}+ or instruction_sources != []+ ):+ raise CodexSubscriptionUnavailable(+ "Codex returned an unsafe or unverifiable voice thread boundary."+ )++ async def thread_start(+ self,+ *,+ base_instructions: str | None = None,+ developer_instructions: str | None = None,+ cwd: str | Path | None = None,+ model: str | None = None,+ ephemeral: bool = True,+ extra: Mapping[str, Any] | None = None,+ ) -> dict[str, Any]:+ """Start a verified ChatGPT-only transport thread outside the workspace."""+ del base_instructions, developer_instructions, cwd, model, ephemeral+ await self.ensure_started()+ if extra:+ raise CodexSubscriptionUnavailable(+ "Custom Codex thread/start fields are disabled for subscription voice."+ )+ params: dict[str, Any] = {}+ params.update(+ {+ "allowProviderModelFallback": False,+ "approvalPolicy": "never",+ "baseInstructions": _TRANSPORT_BASE_INSTRUCTIONS,+ "config": {+ "analytics": {"enabled": False},+ "cli_auth_credentials_store": "file",+ "chatgpt_base_url": _OFFICIAL_CHATGPT_BASE,+ "experimental_realtime_webrtc_call_base_url": (+ _OFFICIAL_CHATGPT_CODEX_BASE+ ),+ "experimental_realtime_start_instructions": "",+ "experimental_realtime_ws_backend_prompt": (+ ""+ ),+ "experimental_realtime_ws_base_url": (+ _OFFICIAL_OPENAI_REALTIME_BASE+ ),+ "features": {+ **{+ feature: False+ for feature in _DISABLED_APP_SERVER_FEATURES+ },+ "realtime_conversation": True,+ },+ "history": {"persistence": "none"},+ "include_apps_instructions": False,+ "include_collaboration_mode_instructions": False,+ "include_environment_context": False,+ "include_permissions_instructions": False,+ "memories": {+ "dedicated_tools": False,+ "generate_memories": False,+ "use_memories": False,+ },+ "experimental_compact_prompt_file": self._compact_prompt_file(),+ "log_dir": self._log_dir(),+ "model_catalog_json": self._model_catalog_file(),+ "model_instructions_file": self._safe_instructions_file(),+ "model_provider": self._transport_provider_id,+ "model_providers": {+ self._transport_provider_id: {+ "base_url": self._provider_sink_base_url(),+ "name": "OpenAI ChatGPT subscription voice",+ "request_max_retries": 0,+ "requires_openai_auth": True,+ "stream_max_retries": 0,+ "supports_standalone_web_search": False,+ "supports_websockets": False,+ "wire_api": "responses",+ }+ },+ "notify": [],+ "openai_base_url": _OFFICIAL_OPENAI_API_BASE,+ "orchestrator": {+ "mcp": {"enabled": False},+ "skills": {"enabled": False},+ },+ "otel": {+ "exporter": "none",+ "log_user_prompt": False,+ "metrics_exporter": "none",+ "trace_exporter": "none",+ },+ "project_doc_max_bytes": 0,+ "sandbox_mode": "read-only",+ "sqlite_home": self._sqlite_home(),+ "skills": {+ "bundled": {"enabled": False},+ "include_instructions": False,+ },+ "tools": {"web_search": False},+ },+ "cwd": self._safe_thread_cwd(),+ "developerInstructions": _TRANSPORT_DEVELOPER_INSTRUCTIONS,+ "dynamicTools": None,+ "environments": [],+ "ephemeral": True,+ "model": "gpt-5.1-codex",+ "modelProvider": self._transport_provider_id,+ "runtimeWorkspaceRoots": [],+ "sandbox": "read-only",+ "selectedCapabilityRoots": [],+ }+ )+ # account/read at process initialization is not durable: `codex login+ # --with-api-key` may switch the shared process while it remains alive.+ # Re-read immediately before EVERY subscription thread and serialize+ # this check with its thread/start frame.+ async with self._thread_start_lock:+ await self.ensure_started()+ try:+ await asyncio.to_thread(+ _validated_subscription_home,+ create=False,+ require_marker=True,+ trusted_binary_path=self._trusted_binary_path,+ )+ await self._verify_live_chatgpt_account()+ self._audit_config_requirements(+ await self._read_config_requirements()+ )+ self._audit_effective_config(await self._read_effective_config())+ except CodexSubscriptionUnavailable as exc:+ error = CodexSubscriptionUnavailable(str(exc))+ await self._close_process(+ CodexAppServerDisconnected(+ "Codex app-server safety state changed."+ ),+ expected=False,+ )+ raise error from None+ result = _result_dict(+ "thread/start",+ await self._request_live(+ "thread/start", params, timeout_s=self._request_timeout_s+ ),+ )+ try:+ self._audit_thread_start_response(result)+ except CodexSubscriptionUnavailable:+ await self._close_process(+ CodexAppServerDisconnected(+ "Codex app-server returned an unsafe thread boundary."+ ),+ expected=False,+ )+ raise+ return result++ async def turn_start(+ self,+ thread_id: str,+ input_items: Sequence[Mapping[str, Any]] | str,+ *,+ extra: Mapping[str, Any] | None = None,+ ) -> dict[str, Any]:+ """Start a future text turn while retaining the thread safety floor."""+ if isinstance(input_items, str):+ rendered_input: list[dict[str, Any]] = [{"type": "text", "text": input_items}]+ else:+ rendered_input = [dict(item) for item in input_items]+ params = dict(extra or {})+ params.update(+ {+ "approvalPolicy": "never",+ "environments": [],+ "input": rendered_input,+ "threadId": thread_id,+ }+ )+ return _result_dict("turn/start", await self.request("turn/start", params))++ async def turn_interrupt(self, thread_id: str, turn_id: str) -> dict[str, Any]:+ """Interrupt one exact app-server turn by its schema-defined ids."""+ return _result_dict(+ "turn/interrupt",+ await self.request(+ "turn/interrupt",+ {"threadId": thread_id, "turnId": turn_id},+ ),+ )++ async def thread_unsubscribe(self, thread_id: str) -> dict[str, Any]:+ """Unload a completed ephemeral voice thread from app-server."""+ return _result_dict(+ "thread/unsubscribe",+ await self.request("thread/unsubscribe", {"threadId": thread_id}),+ )++ async def realtime_start(+ self,+ thread_id: str,+ *,+ output_modality: str = "audio",+ offer_sdp: str | None = None,+ prompt: str | None = None,+ voice: str | None = None,+ version: str | None = None,+ model: str | None = None,+ include_startup_context: bool | None = None,+ client_managed_handoffs: bool | None = None,+ extra: Mapping[str, Any] | None = None,+ sdp_timeout_s: float = _DEFAULT_SDP_TIMEOUT_S,+ ) -> CodexRealtimeStartResult:+ """Start realtime and capture WebRTC SDP without a notification race."""+ if extra:+ raise CodexSubscriptionUnavailable(+ "Custom Codex realtime fields are disabled for subscription voice."+ )+ del prompt, include_startup_context, client_managed_handoffs+ params = {+ "clientManagedHandoffs": True,+ "includeStartupContext": False,+ "outputModality": output_modality,+ "prompt": "",+ "threadId": thread_id,+ }+ optional: dict[str, Any] = {+ "version": version,+ "voice": voice,+ }+ for key, value in optional.items():+ if value is not None:+ params[key] = value+ if model is not None and model.strip():+ params["model"] = model.strip()+ if offer_sdp is not None:+ params["transport"] = {"type": "webrtc", "sdp": offer_sdp}++ sdp_subscription = self.subscribe(thread_id) if offer_sdp is not None else None+ try:+ response = _result_dict(+ "thread/realtime/start",+ await self.request("thread/realtime/start", params),+ )+ answer_sdp: str | None = None+ if sdp_subscription is not None:+ notification = await sdp_subscription.wait_for(+ "thread/realtime/sdp", timeout_s=sdp_timeout_s+ )+ candidate = notification.params.get("sdp")+ if not isinstance(candidate, str) or not candidate:+ raise CodexAppServerError("Codex app-server returned an invalid WebRTC answer.")+ answer_sdp = candidate+ return CodexRealtimeStartResult(response=response, answer_sdp=answer_sdp)+ finally:+ if sdp_subscription is not None:+ sdp_subscription.close()++ async def realtime_append_audio(+ self,+ thread_id: str,+ *,+ data: str,+ sample_rate: int,+ num_channels: int,+ samples_per_channel: int | None = None,+ item_id: str | None = None,+ ) -> dict[str, Any]:+ audio: dict[str, Any] = {+ "data": data,+ "sampleRate": int(sample_rate),+ "numChannels": int(num_channels),+ }+ if samples_per_channel is not None:+ audio["samplesPerChannel"] = int(samples_per_channel)+ if item_id is not None:+ audio["itemId"] = item_id+ return _result_dict(+ "thread/realtime/appendAudio",+ await self.request(+ "thread/realtime/appendAudio",+ {"threadId": thread_id, "audio": audio},+ ),+ )++ async def realtime_append_text(+ self, thread_id: str, text: str, *, role: str = "user"+ ) -> dict[str, Any]:+ return _result_dict(+ "thread/realtime/appendText",+ await self.request(+ "thread/realtime/appendText",+ {"threadId": thread_id, "text": text, "role": role},+ ),+ )++ async def realtime_append_speech(self, thread_id: str, text: str) -> dict[str, Any]:+ return _result_dict(+ "thread/realtime/appendSpeech",+ await self.request(+ "thread/realtime/appendSpeech",+ {"threadId": thread_id, "text": text},+ ),+ )++ async def realtime_stop(self, thread_id: str) -> dict[str, Any]:+ return _result_dict(+ "thread/realtime/stop",+ await self.request("thread/realtime/stop", {"threadId": thread_id}),+ )++ async def _close_process(self, error: CodexAppServerDisconnected, *, expected: bool) -> None:+ process = self._process+ if process is None:+ self._ready = False+ if self._profile_transport_reserved:+ _release_subscription_transport(self)+ self._profile_transport_reserved = False+ return+ self._process = None+ self._ready = False+ tree = self._process_tree+ self._process_tree = None+ reader_task = self._reader_task+ stderr_task = self._stderr_task+ self._reader_task = None+ self._stderr_task = None++ for _method, future in tuple(self._pending.values()):+ if not future.done():+ future.set_exception(error)+ self._pending.clear()+ for subscriptions in tuple(self._subscriptions.values()):+ for subscription in tuple(subscriptions):+ subscription._fail(error)+ self._subscriptions.clear()++ stdin = process.stdin+ if stdin is not None:+ with suppress(Exception):+ stdin.close()++ current = asyncio.current_task()+ tasks = [+ task+ for task in (reader_task, stderr_task)+ if task is not None and task is not current and not task.done()+ ]+ for task in tasks:+ task.cancel()+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)++ if process.returncode is None:+ # EOF is Codex's graceful app-server shutdown path. Give its+ # Arg0PathEntryGuard time to remove the locked tmp/arg0 directory+ # before terminating the contained tree.+ with suppress(TimeoutError):+ await asyncio.wait_for(+ process.wait(), timeout=_SHUTDOWN_TIMEOUT_S+ )+ if process.returncode is None:+ with suppress(ProcessLookupError, OSError):+ process.terminate()+ try:+ await asyncio.wait_for(process.wait(), timeout=_SHUTDOWN_TIMEOUT_S)+ except TimeoutError: # The grace expired, so hard-kill the contained tree.+ with suppress(ProcessLookupError, OSError):+ process.kill()+ with suppress(Exception):+ await asyncio.wait_for(process.wait(), timeout=_SHUTDOWN_TIMEOUT_S)+ if tree is not None:+ tree.close()+ if self._profile_transport_reserved:+ _release_subscription_transport(self)+ self._profile_transport_reserved = False+ if not expected:+ log.warning("Codex app-server connection reset")++ async def close(self) -> None:+ """Reap the app-server tree and release local temporary state."""+ self._assert_owner_loop()+ async with self._start_lock:+ await self._close_process(+ CodexAppServerDisconnected("Codex app-server client closed."),+ expected=True,+ )+ workspace = self._workspace+ self._workspace = None+ self._child_environment = {}+ sink_server = self._sink_server+ self._sink_server = None+ self._sink_base_url = None+ if sink_server is not None:+ sink_server.close()+ with suppress(Exception):+ await sink_server.wait_closed()+ if workspace is not None:+ with suppress(OSError):+ await asyncio.to_thread(shutil.rmtree, workspace.root)++ async def poison(self) -> None:+ """Fail closed after an uncertain remote cleanup."""+ await self.close()+++_shared_clients: dict[+ tuple[str, asyncio.AbstractEventLoop], CodexAppServerClient+] = {}+_shared_clients_lock = threading.Lock()+_subscription_login_lock = threading.Lock()+_subscription_login_in_flight = False+_subscription_login_process: Any | None = None+_subscription_profile_mutating = False+_subscription_active_transports: set[int] = set()+_subscription_transport_process_lock: Any | None = None+_subscription_mutation_process_lock: Any | None = None+++def _subscription_transport_pass_fds(+ client: CodexAppServerClient,+) -> tuple[int, ...]:+ """Return the owner lock FD inherited by a POSIX app-server child."""+ with _subscription_login_lock:+ if _subscription_active_transports != {id(client)}:+ raise CodexSubscriptionUnavailable(+ "The subscription-voice process lock has no unique owner."+ )+ process_lock = _subscription_transport_process_lock+ if process_lock is None:+ raise CodexSubscriptionUnavailable(+ "The subscription-voice process lock is unavailable."+ )+ try:+ descriptor = int(process_lock.fileno())+ except (AttributeError, OSError, TypeError, ValueError) as exc:+ raise CodexSubscriptionUnavailable(+ "The subscription-voice process lock cannot be inherited."+ ) from exc+ if descriptor < 0:+ raise CodexSubscriptionUnavailable(+ "The subscription-voice process lock cannot be inherited."+ )+ return (descriptor,)+++def _reserve_subscription_transport(client: CodexAppServerClient) -> None:+ global _subscription_transport_process_lock++ with _subscription_login_lock:+ if _subscription_profile_mutating:+ raise CodexSubscriptionUnavailable(+ "The subscription-voice profile is being changed."+ )+ client_id = id(client)+ if _subscription_active_transports:+ if (+ _subscription_active_transports == {client_id}+ and _subscription_transport_process_lock is not None+ ):+ return+ raise CodexSubscriptionUnavailable(+ "Subscription voice is already owned by another client or event loop."+ )+ _subscription_transport_process_lock = _acquire_subscription_process_lock()+ _subscription_active_transports.add(client_id)+++def _release_subscription_transport(client: CodexAppServerClient) -> None:+ global _subscription_transport_process_lock++ with _subscription_login_lock:+ _subscription_active_transports.discard(id(client))+ if not _subscription_active_transports:+ process_lock = _subscription_transport_process_lock+ _subscription_transport_process_lock = None+ if process_lock is not None:+ process_lock.close()+++def _release_subscription_mutation_process_lock_locked() -> None:+ """Release the mutation owner while ``_subscription_login_lock`` is held."""+ global _subscription_mutation_process_lock++ process_lock = _subscription_mutation_process_lock+ _subscription_mutation_process_lock = None+ if process_lock is not None:+ process_lock.close()+++def _handoff_subscription_mutation_lock_to_login_guard() -> None:+ """Release the parent lock only after the guardian has signalled waiting."""+ global _subscription_mutation_process_lock++ with _subscription_login_lock:+ process_lock = _subscription_mutation_process_lock+ if not _subscription_profile_mutating or process_lock is None:+ raise CodexSubscriptionUnavailable(+ "The subscription-login lock handoff is unavailable."+ )+ _subscription_mutation_process_lock = None+ process_lock.close()+++def _launch_subscription_login_reaper(target: Any) -> None:+ threading.Thread(+ target=target,+ name="codex-subscription-login-reaper",+ daemon=True,+ ).start()+++def get_shared_codex_app_server(+ binary_path: str | None = None,+) -> CodexAppServerClient:+ """Return the shared client for Jarvis's fixed subscription-voice identity."""+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError as exc:+ raise CodexSubscriptionUnavailable(+ "The shared Codex app-server must be acquired from its owning event loop."+ ) from exc+ binary_key = (binary_path or "").strip() or "<default>"+ key = (binary_key, loop)+ with _shared_clients_lock:+ client = _shared_clients.get(key)+ if client is None:+ client = CodexAppServerClient(binary_path=binary_path)+ client._owner_loop = loop+ _shared_clients[key] = client+ return client+++def _local_subscription_auth_snapshot_locked() -> CodexAppServerCapability | None:+ """Return an in-memory status while the dedicated profile is already owned.++ The caller holds ``_subscription_login_lock``. Starting another Codex CLI+ against the same profile during login, logout, startup, or a live transport+ can race its auth and runtime files, so these states must never be probed.+ """+ if _subscription_login_in_flight:+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=None,+ version=None,+ reason="Dedicated ChatGPT subscription login is in progress.",+ reason_code="login_required",+ )+ if _subscription_active_transports:+ with _shared_clients_lock:+ active_clients = tuple(+ client+ for client in _shared_clients.values()+ if id(client) in _subscription_active_transports+ )+ ready_client = next((client for client in active_clients if client.ready), None)+ if ready_client is not None:+ return CodexAppServerCapability(+ available=True,+ chatgpt_authenticated=True,+ binary_path=(+ ready_client._trusted_binary_path or ready_client._binary_path+ ),+ version=None,+ reason="Dedicated ChatGPT subscription voice is active.",+ reason_code="ready",+ )+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=None,+ version=None,+ reason="Dedicated ChatGPT subscription voice is starting.",+ reason_code="setup_invalid",+ )+ if _subscription_profile_mutating:+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=None,+ version=None,+ reason="Dedicated subscription voice status is being checked or changed.",+ reason_code="setup_invalid",+ )+ return None+++def codex_subscription_auth_snapshot(+ binary_path: str | None = None,+) -> CodexAppServerCapability:+ """Return a lightweight snapshot without starting ``codex app-server``."""+ global _subscription_mutation_process_lock, _subscription_profile_mutating++ with _subscription_login_lock:+ local_snapshot = _local_subscription_auth_snapshot_locked()+ if local_snapshot is not None:+ return local_snapshot+ try:+ _subscription_mutation_process_lock = (+ _acquire_subscription_process_lock()+ )+ except CodexSubscriptionUnavailable as exc: # Expected lock failure becomes status.+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=None,+ version=None,+ reason=str(exc),+ reason_code="setup_invalid",+ )+ _subscription_profile_mutating = True+ try:+ return _read_codex_capability(binary_path)+ finally:+ with _subscription_login_lock:+ _release_subscription_mutation_process_lock_locked()+ _subscription_profile_mutating = False+++def start_codex_subscription_login(+ binary_path: str | None = None,+) -> subprocess.Popen[bytes]:+ """Start a fresh direct ChatGPT login in the dedicated voice profile."""+ global _subscription_login_in_flight, _subscription_login_process+ global _subscription_mutation_process_lock, _subscription_profile_mutating++ from jarvis.codex_auth import CodexAuthService++ if (+ sys.platform.startswith("linux")+ and not os.environ.get("DISPLAY")+ and not os.environ.get("WAYLAND_DISPLAY")+ ):+ raise CodexSubscriptionUnavailable(+ "Interactive subscription-voice login is unavailable on headless Linux. "+ "Run Jarvis on a desktop to connect this dedicated profile."+ )+ with _subscription_login_lock:+ if _subscription_profile_mutating or _subscription_login_in_flight:+ raise CodexSubscriptionUnavailable(+ "A subscription-voice login is already in progress."+ )+ if _subscription_active_transports:+ raise CodexSubscriptionUnavailable(+ "Disconnect active subscription voice before starting login."+ )+ _subscription_mutation_process_lock = (+ _acquire_subscription_process_lock()+ )+ _subscription_profile_mutating = True+ _subscription_login_in_flight = True++ log_dir: Path | None = None+ try:+ home = _prepare_subscription_login_home()+ capability = _read_codex_capability(binary_path)+ if not capability.available or not capability.binary_path:+ raise CodexSubscriptionUnavailable(capability.reason)+ target = _TRUSTED_CODEX_TARGETS.get(+ (sys.platform, _normalized_machine())+ )+ if target is None:+ raise CodexSubscriptionUnavailable(+ "This platform has no approved Codex subscription runtime."+ )+ lock_path = _subscription_process_lock_path()+ from jarvis.core.private_directory import ( # noqa: PLC0415+ ensure_owner_only_directory,+ )++ log_dir = lock_path.parent / f"login-{secrets.token_hex(16)}"+ ensure_owner_only_directory(log_dir, create=True)+ process = CodexAuthService(+ capability.binary_path,+ codex_home=home,+ force_file_auth_store=True,+ isolate_openai_environment=True,+ log_dir=log_dir,+ visible_login=True,+ lifetime_lock_path=lock_path,+ login_guard_directory=log_dir,+ login_guard_handoff=(+ _handoff_subscription_mutation_lock_to_login_guard+ ),+ trusted_binary_sha256=target[3],+ ).start_login()+ except RuntimeError as exc:+ if log_dir is not None:+ shutil.rmtree(log_dir, ignore_errors=True)+ with _subscription_login_lock:+ _release_subscription_mutation_process_lock_locked()+ _subscription_profile_mutating = False+ _subscription_login_in_flight = False+ raise CodexSubscriptionUnavailable(str(exc)) from exc+ except BaseException:+ if log_dir is not None:+ shutil.rmtree(log_dir, ignore_errors=True)+ with _subscription_login_lock:+ _release_subscription_mutation_process_lock_locked()+ _subscription_profile_mutating = False+ _subscription_login_in_flight = False+ raise++ with _subscription_login_lock:+ _subscription_login_process = process++ def cleanup_login() -> None:+ global _subscription_login_in_flight, _subscription_login_process+ global _subscription_profile_mutating++ try:+ process.wait()+ try:+ post_login = _read_codex_capability(capability.binary_path)+ if not (+ post_login.available+ and post_login.chatgpt_authenticated+ and post_login.reason_code == "ready"+ ):+ log.warning(+ "Dedicated subscription login did not produce a verified "+ "ChatGPT login (%s)",+ post_login.reason_code,+ )+ except (CodexAppServerError, OSError) as exc:+ log.warning(+ "Dedicated subscription login post-check failed (%s)",+ type(exc).__name__,+ )+ finally:+ release_guard = getattr(process, "release_profile_lock", None)+ if callable(release_guard):+ try:+ release_guard()+ except (OSError, RuntimeError) as exc:+ log.warning(+ "Dedicated subscription login guard release failed (%s)",+ type(exc).__name__,+ )+ if log_dir is not None:+ shutil.rmtree(log_dir, ignore_errors=True)+ with _subscription_login_lock:+ if _subscription_login_process is process:+ _subscription_login_process = None+ _subscription_login_in_flight = False+ _subscription_profile_mutating = False+ _release_subscription_mutation_process_lock_locked()++ _launch_subscription_login_reaper(cleanup_login)+ return process+++def _delete_codex_subscription_auth_locked() -> tuple[bool, str | None]:+ """Delete the dedicated auth file while the caller owns the mutation lock."""+ try:+ home = _validated_subscription_home(create=False, require_marker=True)+ except CodexSubscriptionProfileMissing: # Logging out an absent profile is idempotent success.+ return True, None+ auth_file = home / "auth.json"+ if not auth_file.exists() and not auth_file.is_symlink():+ return True, None+ _validate_regular_private_file(auth_file)+ try:+ auth_file.unlink()+ except OSError as exc: # Return a path-free deletion error to the authenticated caller.+ return (+ False,+ "Dedicated subscription credentials could not be removed "+ f"({type(exc).__name__}).",+ )+ _validated_subscription_home(create=False, require_marker=True)+ return True, None+++def logout_codex_subscription(+ binary_path: str | None = None,+) -> tuple[bool, str | None]:+ """Delete only the dedicated file-backed login; missing is success."""+ global _subscription_mutation_process_lock, _subscription_profile_mutating++ del binary_path # Kept for the stable route/helper signature.++ with _subscription_login_lock:+ if _subscription_profile_mutating or _subscription_login_in_flight:+ raise CodexSubscriptionUnavailable(+ "Subscription voice cannot log out while login is in progress."+ )+ if _subscription_active_transports:+ raise CodexSubscriptionUnavailable(+ "Subscription voice is still active; disconnect it before logout."+ )+ _subscription_mutation_process_lock = (+ _acquire_subscription_process_lock()+ )+ _subscription_profile_mutating = True+ try:+ return _delete_codex_subscription_auth_locked()+ finally:+ with _subscription_login_lock:+ _release_subscription_mutation_process_lock_locked()+ _subscription_profile_mutating = False+++async def disconnect_and_logout_codex_subscription(+ binary_path: str | None = None,+) -> tuple[bool, str | None]:+ """Atomically block starts, close the transport, and delete its login."""+ global _subscription_mutation_process_lock, _subscription_profile_mutating+ global _subscription_transport_process_lock++ del binary_path # Kept for the stable route/helper signature.++ with _subscription_login_lock:+ if _subscription_profile_mutating or _subscription_login_in_flight:+ raise CodexSubscriptionUnavailable(+ "Subscription voice cannot log out while login is in progress."+ )+ if _subscription_active_transports:+ process_lock = _subscription_transport_process_lock+ if process_lock is None:+ raise CodexSubscriptionUnavailable(+ "The active subscription-voice process lock is unavailable."+ )+ _subscription_mutation_process_lock = process_lock+ _subscription_transport_process_lock = None+ else:+ _subscription_mutation_process_lock = (+ _acquire_subscription_process_lock()+ )+ _subscription_profile_mutating = True+ try:+ await close_shared_codex_app_servers()+ return await asyncio.to_thread(_delete_codex_subscription_auth_locked)+ finally:+ with _subscription_login_lock:+ if _subscription_active_transports:+ if _subscription_transport_process_lock is not None:+ log.error(+ "Subscription voice has two process-lock owners during logout"+ )+ _release_subscription_mutation_process_lock_locked()+ else:+ _subscription_transport_process_lock = (+ _subscription_mutation_process_lock+ )+ _subscription_mutation_process_lock = None+ else:+ _release_subscription_mutation_process_lock_locked()+ _subscription_profile_mutating = False+++async def codex_subscription_login_ready(binary_path: str | None = None) -> bool:+ """Return the lightweight dedicated-profile login snapshot."""+ try:+ snapshot = await asyncio.to_thread(+ codex_subscription_auth_snapshot,+ binary_path,+ )+ except (CodexAppServerError, OSError):+ # Readiness probes fail closed without starting transport.+ return False+ return bool(snapshot.available and snapshot.chatgpt_authenticated)+++async def close_shared_codex_app_servers() -> None:+ """Close all shared transports, primarily for application shutdown/tests."""+ current_loop = asyncio.get_running_loop()+ with _shared_clients_lock:+ entries = tuple(_shared_clients.items())+ failures: list[BaseException] = []+ for key, client in entries:+ owner_loop = key[1]+ try:+ if owner_loop is current_loop:+ await client.close()+ elif owner_loop.is_running():+ future = asyncio.run_coroutine_threadsafe(client.close(), owner_loop)+ await asyncio.wrap_future(future)+ else:+ raise CodexSubscriptionUnavailable(+ "A Codex app-server owner loop is unavailable for safe shutdown."+ )+ except BaseException as exc: # noqa: BLE001 - collect every owner-loop failure+ failures.append(exc)+ continue+ with _shared_clients_lock:+ if _shared_clients.get(key) is client:+ _shared_clients.pop(key, None)+ if failures:+ raise CodexSubscriptionUnavailable(+ "Not every Codex app-server could be closed on its owning event loop."+ ) from failures[0]+++__all__ = [+ "CodexAppServerCapability",+ "CodexAppServerClient",+ "CodexAppServerDisconnected",+ "CodexAppServerError",+ "CodexAppServerNotification",+ "CodexAppServerRPCError",+ "CodexAppServerTimeout",+ "CodexNotificationOverflow",+ "CodexNotificationSubscription",+ "CodexRealtimeStartResult",+ "CodexSubscriptionProfileMissing",+ "CodexSubscriptionContainmentUnavailable",+ "CodexSubscriptionUnavailable",+ "codex_subscription_auth_snapshot",+ "codex_subscription_home",+ "codex_subscription_login_ready",+ "close_shared_codex_app_servers",+ "disconnect_and_logout_codex_subscription",+ "get_shared_codex_app_server",+ "logout_codex_subscription",+ "start_codex_subscription_login",+]diff --git a/jarvis/codex_auth.py b/jarvis/codex_auth.pyindex 58e6692e28..d6e2a80852 100644--- a/jarvis/codex_auth.py+++ b/jarvis/codex_auth.py@@ -28,8 +28,16 @@ import binasciiimport jsonimport loggingimport os+import secrets+import shlex+import shutil+import statimport subprocessimport sys+import tempfile+import threading+import time+from collections.abc import Callablefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any@@ -53,6 +61,43 @@ _BINARY_CANDIDATES: tuple[str, ...] = ("codex", "codex.cmd", "codex.exe")# probe is cached too, so a hanging/absent codex never re-pays the 4 s timeout._VERSION_CACHE: dict[str, str | None] = {}+# A dedicated subscription login must not inherit provider, cloud, proxy,+# dynamic-loader, keyring, or agent-session state. Keep this list deliberately+# small: these are OS process essentials, not a denylist that has to predict the+# next credential variable name.+_ISOLATED_CODEX_ENV_ALLOWLIST: frozenset[str] = frozenset(+ {+ "COMSPEC",+ "HOME",+ "LANG",+ "LOCALAPPDATA",+ "NO_COLOR",+ "PATH",+ "PATHEXT",+ "SHELL",+ "SYSTEMDRIVE",+ "SYSTEMROOT",+ "TEMP",+ "TERM",+ "TMP",+ "TMPDIR",+ "USERPROFILE",+ "WINDIR",+ }+)+_DESKTOP_LAUNCHER_ENV_ALLOWLIST: frozenset[str] = frozenset(+ {+ "DBUS_SESSION_BUS_ADDRESS",+ "DESKTOP_SESSION",+ "DISPLAY",+ "WAYLAND_DISPLAY",+ "XAUTHORITY",+ "XDG_CURRENT_DESKTOP",+ "XDG_RUNTIME_DIR",+ "XDG_SESSION_TYPE",+ }+)+def clear_version_cache() -> None:"""Drop all cached ``codex --version`` results.@@ -70,6 +115,11 @@ if sys.platform == "win32":_NEW_CONSOLE_FLAGS: int = getattr(subprocess, "CREATE_NEW_CONSOLE", 0x00000010)else:_NEW_CONSOLE_FLAGS = 0+_CREATE_BREAKAWAY_FROM_JOB = getattr(+ subprocess,+ "CREATE_BREAKAWAY_FROM_JOB",+ 0x01000000,+)# ----------------------------------------------------------------------@@ -119,7 +169,7 @@ def _email_from_id_token(tokens: dict[str, Any] | None) -> str | None:payload_b64 += "=" * (-len(payload_b64) % 4) # restore base64 paddingtry:payload = json.loads(base64.urlsafe_b64decode(payload_b64))- except (binascii.Error, ValueError, json.JSONDecodeError):+ except (binascii.Error, ValueError, json.JSONDecodeError): # Display-only claim is optional.return Noneemail = payload.get("email") if isinstance(payload, dict) else Nonereturn email if isinstance(email, str) and email else None@@ -137,11 +187,11 @@ def codex_login_in(codex_home: Path) -> tuple[bool, str, str | None]:"""try:raw = (codex_home / "auth.json").read_text(encoding="utf-8")- except (OSError, ValueError):+ except (OSError, ValueError): # An absent auth file is the normal disconnected state.return False, "unknown", Nonetry:data = json.loads(raw)- except (ValueError, json.JSONDecodeError):+ except (ValueError, json.JSONDecodeError): # Invalid auth data fails closed as disconnected.return False, "unknown", Noneauth = data if isinstance(data, dict) else Noneconnected, mode = _derive_auth(auth)@@ -186,6 +236,191 @@ class CodexAuthStatus:}+class _GuardedCodexLoginProcess:+ """Popen-like handle whose wait boundary precedes guardian lock release."""++ def __init__(+ self,+ process: subprocess.Popen[bytes],+ acknowledgement: Path,+ release: Path,+ process_tree: Any | None = None,+ ) -> None:+ self._process = process+ self._acknowledgement = acknowledgement+ self._release = release+ self._process_tree = process_tree+ self._process_tree_lock = threading.Lock()+ self.pid = process.pid+ if process_tree is not None:+ monitor = threading.Thread(+ target=self._monitor_guardian_exit,+ name="codex-subscription-login-guardian",+ daemon=True,+ )+ try:+ monitor.start()+ except RuntimeError:+ self._close_process_tree()+ raise++ def _close_process_tree(self) -> None:+ with self._process_tree_lock:+ process_tree = self._process_tree+ self._process_tree = None+ if process_tree is not None:+ process_tree.close()++ def _monitor_guardian_exit(self) -> None:+ try:+ self._process.wait()+ finally:+ self._close_process_tree()++ @staticmethod+ def _read_status(path: Path) -> str | None:+ try:+ metadata = path.lstat()+ reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)+ if (+ stat.S_ISLNK(metadata.st_mode)+ or bool(getattr(metadata, "st_file_attributes", 0) & reparse)+ or not stat.S_ISREG(metadata.st_mode)+ or metadata.st_size > 16+ or getattr(metadata, "st_nlink", 1) != 1+ ):+ return None+ if os.name == "posix":+ geteuid = getattr(os, "geteuid", None)+ if (+ not callable(geteuid)+ or metadata.st_uid != geteuid()+ or stat.S_IMODE(metadata.st_mode) != 0o600+ ):+ return None+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)+ flags |= getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)+ descriptor = os.open(path, flags)+ try:+ opened = os.fstat(descriptor)+ if (opened.st_dev, opened.st_ino) != (+ metadata.st_dev,+ metadata.st_ino,+ ):+ return None+ if sys.platform == "win32":+ from jarvis.core.exclusive_process_lock import ( # noqa: PLC0415+ _validate_windows_file_security,+ )++ _validate_windows_file_security(descriptor)+ return os.read(descriptor, 17).decode("ascii")+ finally:+ os.close(descriptor)+ except (OSError, RuntimeError, UnicodeError, ValueError): # Unsafe path is unavailable.+ return None++ @staticmethod+ def _publish_control(path: Path, status: str) -> None:+ if status not in {"acquire", "release"}:+ raise ValueError("Unknown subscription-login control state.")+ parent = path.parent.resolve(strict=True)+ descriptor, temporary_name = tempfile.mkstemp(+ prefix=f".{path.name}.",+ suffix=".tmp",+ dir=parent,+ )+ temporary = Path(temporary_name)+ try:+ os.chmod(temporary, 0o600)+ with os.fdopen(descriptor, "w", encoding="ascii", newline="") as stream:+ descriptor = -1+ stream.write(status)+ stream.flush()+ os.fsync(stream.fileno())+ os.replace(temporary, path)+ finally:+ if descriptor >= 0:+ os.close(descriptor)+ try:+ temporary.unlink()+ except FileNotFoundError:+ # Another cleanup may already have removed the temporary file.+ pass++ @classmethod+ def establish_handoff(+ cls,+ process: subprocess.Popen[bytes],+ acknowledgement: Path,+ release: Path,+ release_parent_lock: Callable[[], None],+ *,+ timeout_s: float = 8.0,+ ) -> None:+ deadline = time.monotonic() + timeout_s+ while time.monotonic() < deadline:+ status = cls._read_status(acknowledgement)+ if status == "waiting":+ break+ if process.poll() is not None:+ raise RuntimeError(+ "The subscription-login guardian exited before lock handoff."+ )+ time.sleep(0.05)+ else:+ raise RuntimeError(+ "The subscription-login guardian did not request lock handoff."+ )++ release_parent_lock()+ cls._publish_control(release, "acquire")+ deadline = time.monotonic() + timeout_s+ while time.monotonic() < deadline:+ status = cls._read_status(acknowledgement)+ if status == "ready":+ return+ if status == "busy":+ raise RuntimeError(+ "Another Jarvis process is using subscription voice."+ )+ if process.poll() is not None:+ raise RuntimeError(+ "The subscription-login guardian exited before taking ownership."+ )+ time.sleep(0.05)+ raise RuntimeError(+ "The subscription-login guardian did not confirm profile ownership."+ )++ def wait(self) -> int:+ """Wait until Codex login exits while the guardian still owns the lock."""+ while True:+ if self._read_status(self._acknowledgement) == "finished":+ return 0+ return_code = self._process.poll()+ if return_code is not None:+ self._close_process_tree()+ return return_code+ time.sleep(0.05)++ def release_profile_lock(self) -> None:+ """Publish post-check completion, then reap the guardian."""+ try:+ self._publish_control(self._release, "release")+ try:+ self._process.wait(timeout=35.0)+ except subprocess.TimeoutExpired:+ log.warning("Subscription-login guardian release timed out")+ finally:+ self._close_process_tree()+ for path in (self._acknowledgement, self._release):+ try:+ path.unlink()+ except FileNotFoundError: # Coordination cleanup is intentionally idempotent.+ pass++class CodexAuthService:"""Status / login / logout for the ``codex`` CLI.@@ -194,15 +429,41 @@ class CodexAuthService:``auth.json`` parsing against a temp ``$CODEX_HOME``."""- def __init__(self, binary_path: str | None = None) -> None:+ def __init__(+ self,+ binary_path: str | None = None,+ *,+ codex_home: Path | None = None,+ force_file_auth_store: bool = False,+ isolate_openai_environment: bool = False,+ log_dir: Path | None = None,+ visible_login: bool = False,+ lifetime_lock_path: Path | None = None,+ login_guard_directory: Path | None = None,+ login_guard_handoff: Callable[[], None] | None = None,+ trusted_binary_sha256: str | None = None,+ ) -> None:self._binary_path = (binary_path or "").strip() or "codex"+ self._codex_home = Path(codex_home) if codex_home is not None else None+ self._force_file_auth_store = bool(force_file_auth_store)+ self._isolate_openai_environment = bool(isolate_openai_environment)+ self._log_dir = Path(log_dir) if log_dir is not None else None+ self._visible_login = bool(visible_login)+ self._lifetime_lock_path = (+ Path(lifetime_lock_path) if lifetime_lock_path is not None else None+ )+ self._login_guard_directory = (+ Path(login_guard_directory)+ if login_guard_directory is not None+ else None+ )+ self._login_guard_handoff = login_guard_handoff+ self._trusted_binary_sha256 = trusted_binary_sha256# -- seams -----------------------------------------------------------def _resolve_binary(self) -> str | None:"""Full path to the ``codex`` binary, or ``None`` when absent."""- import shutil-# A CLI installed AFTER app start (or into a dir the GUI PATH never# had) must still be found — idempotent stat probes, no subprocess.try:@@ -210,7 +471,7 @@ class CodexAuthService:ensure_cli_paths()except Exception: # noqa: BLE001 — a probe helper must never break status- pass+ log.debug("Codex CLI path augmentation failed", exc_info=True)candidates = (self._binary_path, *_BINARY_CANDIDATES)for name in candidates:@@ -238,6 +499,7 @@ class CodexAuthService:timeout=4.0,text=True,creationflags=NO_WINDOW_CREATIONFLAGS,+ env=self._subprocess_environment(),)except (FileNotFoundError, subprocess.TimeoutExpired, OSError):_VERSION_CACHE[binary] = None@@ -250,15 +512,142 @@ class CodexAuthService:# -- auth file -------------------------------------------------------def _auth_home(self) -> Path:+ if self._codex_home is not None:+ return self._codex_homeoverride = os.environ.get("CODEX_HOME")return Path(override) if override else (Path.home() / ".codex")+ def _command(self, binary: str, *subcommand: str) -> list[str]:+ command = [binary]+ if self._force_file_auth_store:+ command.extend(("-c", 'cli_auth_credentials_store="file"'))+ if self._log_dir is not None:+ command.extend(("-c", f"log_dir={json.dumps(str(self._log_dir))}"))+ command.extend(subcommand)+ return command++ def _subprocess_environment(self) -> dict[str, str] | None:+ if (+ self._codex_home is None+ and not self._force_file_auth_store+ and not self._isolate_openai_environment+ ):+ return None+ if self._isolate_openai_environment:+ environment = {+ name: value+ for name, value in os.environ.items()+ if name.upper() in _ISOLATED_CODEX_ENV_ALLOWLIST+ or name.upper().startswith("LC_")+ }+ else:+ environment = dict(os.environ)+ if self._codex_home is not None:+ environment["CODEX_HOME"] = str(self._codex_home)+ if self._force_file_auth_store:+ environment.pop("DBUS_SESSION_BUS_ADDRESS", None)+ environment.pop("XDG_RUNTIME_DIR", None)+ return environment++ def _desktop_launcher_environment(self) -> dict[str, str]:+ """Minimal launcher environment with only graphical-session handles."""+ if not self._isolate_openai_environment:+ return self._subprocess_environment() or dict(os.environ)+ environment = self._subprocess_environment() or {}+ for name, value in os.environ.items():+ if name.upper() in _DESKTOP_LAUNCHER_ENV_ALLOWLIST:+ environment[name] = value+ return environment++ def _isolated_exec_command(self, command: list[str]) -> list[str]:+ """Wrap a terminal child so Codex receives only the strict environment."""+ environment = self._subprocess_environment()+ if environment is None:+ return command+ helper = (+ "import json,os,sys;"+ "environment=json.loads(sys.argv[1]);"+ "os.execve(sys.argv[2],sys.argv[2:],environment)"+ )+ return [+ str(Path(sys.executable).resolve()),+ "-I",+ "-S",+ "-c",+ helper,+ json.dumps(environment, separators=(",", ":"), sort_keys=True),+ *command,+ ]++ def _guarded_login_command(+ self,+ binary: str,+ ) -> tuple[list[str], Path, Path]:+ """Build the fixed guardian argv for one dedicated profile login."""+ if (+ self._lifetime_lock_path is None+ or self._login_guard_directory is None+ or self._log_dir is None+ or self._codex_home is None+ or not self._force_file_auth_store+ or not self._isolate_openai_environment+ or self._trusted_binary_sha256 is None+ ):+ raise RuntimeError("The subscription-login guardian is not fully configured.")+ if (+ len(self._trusted_binary_sha256) != 64+ or any(+ character not in "0123456789abcdef"+ for character in self._trusted_binary_sha256+ )+ ):+ raise RuntimeError("The subscription-login binary digest is invalid.")+ from jarvis.core.private_directory import ( # noqa: PLC0415+ ensure_owner_only_directory,+ )++ try:+ ensure_owner_only_directory(self._login_guard_directory, create=False)+ guard_directory = self._login_guard_directory.resolve(strict=True)+ lock_path = self._lifetime_lock_path.resolve(strict=False)+ binary_path = Path(binary).resolve(strict=True)+ log_dir = self._log_dir.resolve(strict=True)+ guardian = Path(__file__).with_name("codex_login_guard.py").resolve(+ strict=True+ )+ except (OSError, RuntimeError) as exc:+ raise RuntimeError(+ "The subscription-login guardian paths are unavailable."+ ) from exc+ nonce = secrets.token_hex(16)+ acknowledgement = guard_directory / f"login-{nonce}.ack"+ release = guard_directory / f"login-{nonce}.release"+ if acknowledgement.exists() or release.exists():+ raise RuntimeError("The subscription-login coordination state is not fresh.")+ environment = self._subprocess_environment()+ if environment is None:+ raise RuntimeError("The subscription-login environment is not isolated.")+ command = [+ str(Path(sys.executable).resolve()),+ "-I",+ "-S",+ str(guardian),+ str(lock_path),+ str(acknowledgement),+ str(release),+ str(binary_path),+ self._trusted_binary_sha256,+ str(log_dir),+ json.dumps(environment, separators=(",", ":"), sort_keys=True),+ ]+ return command, acknowledgement, release+def _read_auth(self) -> dict[str, Any] | None:"""Parse ``<codex-home>/auth.json``; ``None`` if absent/unreadable."""path = self._auth_home() / "auth.json"try:raw = path.read_text(encoding="utf-8")- except (FileNotFoundError, OSError):+ except (FileNotFoundError, OSError): # A missing control file means no handoff state yet.return Nonetry:data = json.loads(raw)@@ -316,7 +705,9 @@ class CodexAuthService:binary_path=binary,)- def start_login(self) -> subprocess.Popen[bytes]:+ def start_login(+ self,+ ) -> subprocess.Popen[bytes] | _GuardedCodexLoginProcess:"""Spawn ``codex login`` in a visible console. Raises if not installed.``codex login`` opens the browser for the OAuth/device flow and runs a@@ -329,11 +720,90 @@ class CodexAuthService:"Codex CLI is not installed (run: npm i -g @openai/codex).")log.info("Starting 'codex login' (interactive)")+ command = self._command(binary, "login")+ guard_paths: tuple[Path, Path] | None = None+ if self._lifetime_lock_path is not None:+ command, acknowledgement, release = self._guarded_login_command(binary)+ guard_paths = (acknowledgement, release)if sys.platform == "win32":# Fresh visible console so the device/OAuth URL is reachable under# pythonw.exe. Do NOT redirect stdio — the output belongs in that# console (the new console replaces the absent parent one).kwargs: dict[str, Any] = {"creationflags": _NEW_CONSOLE_FLAGS}+ elif self._visible_login:+ environment = self._desktop_launcher_environment()+ terminal_command = (+ command+ if guard_paths is not None+ else self._isolated_exec_command(command)+ if self._isolate_openai_environment+ else command+ )+ if sys.platform == "darwin":+ shell_command = "exec " + shlex.join(terminal_command)+ escaped = shell_command.replace("\\", "\\\\").replace('"', '\\"')+ script = (+ 'tell application "Terminal"\n'+ "activate\n"+ f'set loginTab to do script "{escaped}"\n'+ "repeat while busy of loginTab\n"+ "delay 1\n"+ "end repeat\n"+ "end tell"+ )+ command = ["/usr/bin/osascript", "-e", script]+ else:+ terminal = next(+ (+ candidate+ for candidate in (+ shutil.which("gnome-terminal"),+ shutil.which("konsole"),+ shutil.which("xterm"),+ )+ if candidate+ ),+ None,+ )+ if terminal is None:+ terminal = shutil.which("x-terminal-emulator")+ if terminal is None:+ raise RuntimeError(+ "No supported desktop terminal is available for Codex login."+ )+ # Resolve Debian's x-terminal-emulator alternative before+ # choosing flags. Generic terminal launchers may return as+ # soon as they hand work to a terminal server, which would+ # release the profile login guard while Codex still writes+ # auth.json. Only backends with a documented wait/no-fork+ # form are accepted.+ resolved_terminal = str(Path(terminal).resolve())+ terminal_name = Path(resolved_terminal).name.lower()+ if terminal_name.startswith("gnome-terminal"):+ command = [+ resolved_terminal,+ "--wait",+ "--",+ *terminal_command,+ ]+ elif terminal_name.startswith("konsole"):+ command = [+ resolved_terminal,+ "--nofork",+ "-e",+ *terminal_command,+ ]+ elif terminal_name == "xterm":+ command = [resolved_terminal, "-e", *terminal_command]+ else:+ raise RuntimeError(+ "The configured desktop terminal cannot provide a bounded "+ "Codex login lifetime."+ )+ kwargs = {+ "env": environment,+ "start_new_session": True,+ }else:# Headless-safe (CLOUD.md Rule #1): detach into a new session and# never inherit the server's stdio — otherwise a VPS would see codex@@ -345,7 +815,113 @@ class CodexAuthService:"stdin": subprocess.DEVNULL,"start_new_session": True,}- return subprocess.Popen([binary, "login"], **kwargs) # noqa: S603 — fixed argv, shell=False+ environment = self._subprocess_environment()+ if environment is not None and "env" not in kwargs:+ kwargs["env"] = environment+ process_tree: Any | None = None+ if guard_paths is not None and sys.platform == "win32":+ from jarvis.core.process_tree import make_process_tree # noqa: PLC0415++ process_tree = make_process_tree("codex-subscription-login")+ if not bool(getattr(process_tree, "supports_containment", False)):+ process_tree.close()+ raise RuntimeError(+ "Windows process-tree containment is unavailable for Codex login."+ )+ kwargs["creationflags"] = int(kwargs.get("creationflags", 0)) | (+ _CREATE_BREAKAWAY_FROM_JOB+ )+ try:+ try:+ process = subprocess.Popen( # noqa: S603 — fixed argv, shell=False+ command,+ **kwargs,+ )+ except PermissionError:+ if process_tree is None:+ raise+ kwargs["creationflags"] = int(kwargs.get("creationflags", 0)) & (+ ~_CREATE_BREAKAWAY_FROM_JOB+ )+ process = subprocess.Popen( # noqa: S603 — fixed argv, shell=False+ command,+ **kwargs,+ )+ except BaseException:+ if process_tree is not None:+ process_tree.close()+ raise++ if process_tree is not None:+ try:+ process_tree.assign(process.pid)+ except Exception as exc: # noqa: BLE001 - containment is mandatory+ process_tree.close()+ try:+ process.terminate()+ except OSError:+ pass+ raise RuntimeError(+ "Windows process-tree containment could not be established for Codex login."+ ) from exc+ if guard_paths is None:+ return process+ if self._login_guard_handoff is None:+ if process_tree is not None:+ process_tree.close()+ else:+ try:+ process.terminate()+ except OSError:+ pass+ raise RuntimeError("The subscription-login lock handoff is unavailable.")+ acknowledgement, release = guard_paths+ try:+ _GuardedCodexLoginProcess.establish_handoff(+ process,+ acknowledgement,+ release,+ self._login_guard_handoff,+ )+ return _GuardedCodexLoginProcess(+ process,+ acknowledgement,+ release,+ process_tree,+ )+ except BaseException:+ if process_tree is not None:+ process_tree.close()+ else:+ try:+ process.terminate()+ except OSError:+ pass+ raise++ def login_status(self) -> tuple[bool, str]:+ """Return the CLI's PII-free login mode for this exact profile."""+ binary = self._resolve_binary()+ if binary is None:+ return False, "unknown"+ try:+ proc = subprocess.run(+ self._command(binary, "login", "status"),+ capture_output=True,+ timeout=4.0,+ text=True,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ env=self._subprocess_environment(),+ )+ except (FileNotFoundError, subprocess.TimeoutExpired, OSError):+ # The status probe is unavailable and therefore fails closed.+ return False, "unknown"+ output = (proc.stdout or proc.stderr or "").strip()+ if proc.returncode == 0 and output == "Logged in using ChatGPT":+ return True, "chatgpt"+ if proc.returncode == 0 and output == "Logged in using an API key":+ return True, "api_key"+ return False, "unknown"def logout_blocking(self) -> tuple[bool, str | None]:"""Run ``codex logout``; fall back to deleting ``auth.json``.@@ -358,16 +934,18 @@ class CodexAuthService:return False, "Codex CLI is not installed."try:proc = subprocess.run(- [binary, "logout"],+ self._command(binary, "logout"),capture_output=True,timeout=15.0,text=True,creationflags=NO_WINDOW_CREATIONFLAGS,+ env=self._subprocess_environment(),)if proc.returncode == 0:return True, Nonecli_error = (proc.stderr or proc.stdout or "").strip() or Noneexcept (subprocess.TimeoutExpired, OSError) as exc:+ # Preserve failure for the deletion fallback.cli_error = str(exc)# Fallback: remove the auth file directly. Log the CLI failure first so a@@ -377,5 +955,5 @@ class CodexAuthService:try:auth_file.unlink(missing_ok=True)return True, None- except OSError as exc:+ except OSError as exc: # Return the recoverable logout failure to the caller.return False, cli_error or f"could not remove auth.json: {exc}"diff --git a/jarvis/codex_login_guard.py b/jarvis/codex_login_guard.pynew file mode 100644index 0000000000..10163c8a8d--- /dev/null+++ b/jarvis/codex_login_guard.py@@ -0,0 +1,376 @@+"""Isolated lifetime guardian for the subscription-voice Codex login.++This script is an internal executable, not a user-facing CLI. Invoke it as a+trusted absolute path under ``python -I -S`` with exactly seven positional+arguments after the script path: lock path, acknowledgement path, release path,+Codex binary, expected binary SHA-256, log directory, and a strict JSON child+environment. It never reads profile credentials.+"""++from __future__ import annotations++import hashlib+import hmac+import importlib.util+import json+import os+import signal+import stat+import subprocess+import sys+import tempfile+import time+from collections.abc import Sequence+from pathlib import Path+from types import ModuleType++EXIT_INVALID = 2+EXIT_UNSAFE = 74+EXIT_BUSY = 75+EXIT_LAUNCH_FAILED = 127+RELEASE_TIMEOUT_SECONDS = 30.0++_MAX_ENVIRONMENT_BYTES = 32_768+_ALLOWED_ENVIRONMENT_NAMES = frozenset(+ {+ "APPDATA",+ "CODEX_HOME",+ "CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED",+ "COMSPEC",+ "HOME",+ "LANG",+ "LOCALAPPDATA",+ "NO_COLOR",+ "PATH",+ "PATHEXT",+ "RUST_BACKTRACE",+ "RUST_LOG",+ "SHELL",+ "SYSTEMDRIVE",+ "SYSTEMROOT",+ "TEMP",+ "TERM",+ "TMP",+ "TMPDIR",+ "USERPROFILE",+ "WINDIR",+ }+)+++def _load_lock_module() -> ModuleType:+ """Load the exact sibling implementation without trusting import paths."""+ source = Path(__file__).resolve().parent / "core" / "exclusive_process_lock.py"+ spec = importlib.util.spec_from_file_location("_jarvis_exclusive_process_lock", source)+ if spec is None or spec.loader is None:+ raise RuntimeError("lock module unavailable")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _strict_environment(raw: str) -> dict[str, str]:+ if len(raw.encode("utf-8")) > _MAX_ENVIRONMENT_BYTES:+ raise ValueError("environment is too large")++ def reject_duplicates(pairs: list[tuple[str, object]]) -> dict[str, object]:+ result: dict[str, object] = {}+ seen: set[str] = set()+ for name, value in pairs:+ identity = name.upper() if os.name == "nt" else name+ if identity in seen:+ raise ValueError("duplicate environment name")+ seen.add(identity)+ result[name] = value+ return result++ data = json.loads(raw, object_pairs_hook=reject_duplicates)+ if not isinstance(data, dict) or not data:+ raise ValueError("environment must be an object")+ environment: dict[str, str] = {}+ for name, value in data.items():+ normalized_name = name.upper() if os.name == "nt" else name+ if (+ not isinstance(name, str)+ or not isinstance(value, str)+ or (+ normalized_name not in _ALLOWED_ENVIRONMENT_NAMES+ and not normalized_name.startswith("LC_")+ )+ or not name+ or "\0" in name+ or "=" in name+ or "\0" in value+ ):+ raise ValueError("environment is not approved")+ environment[normalized_name] = value+ if "CODEX_HOME" not in environment:+ raise ValueError("profile home is missing")+ return environment+++def _resolved_absolute_directory(raw: str) -> Path:+ path = Path(raw)+ if not path.is_absolute():+ raise ValueError("directory is not absolute")+ resolved = path.resolve(strict=True)+ metadata = resolved.lstat()+ reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)+ if not stat.S_ISDIR(metadata.st_mode) or bool(+ getattr(metadata, "st_file_attributes", 0) & reparse+ ):+ raise ValueError("directory is unsafe")+ return resolved+++def _open_verified_binary(raw: str, expected_sha256: str) -> tuple[Path, int]:+ path = Path(raw)+ if (+ not path.is_absolute()+ or len(expected_sha256) != 64+ or any(character not in "0123456789abcdef" for character in expected_sha256)+ ):+ raise ValueError("binary is not absolute")+ resolved = path.resolve(strict=True)+ path_metadata = resolved.lstat()+ reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)+ if (+ stat.S_ISLNK(path_metadata.st_mode)+ or bool(getattr(path_metadata, "st_file_attributes", 0) & reparse)+ or not stat.S_ISREG(path_metadata.st_mode)+ ):+ raise ValueError("binary is not regular")+ fd = os.open(+ resolved,+ os.O_RDONLY+ | getattr(os, "O_BINARY", 0)+ | getattr(os, "O_CLOEXEC", 0)+ | getattr(os, "O_NOFOLLOW", 0),+ )+ try:+ opened_before = os.fstat(fd)+ if not stat.S_ISREG(opened_before.st_mode):+ raise ValueError("binary is not regular")+ digest = hashlib.sha256()+ while chunk := os.read(fd, 1024 * 1024):+ digest.update(chunk)+ opened_after = os.fstat(fd)+ current = resolved.lstat()+ identity = (opened_before.st_dev, opened_before.st_ino)+ if (+ identity != (opened_after.st_dev, opened_after.st_ino)+ or identity != (current.st_dev, current.st_ino)+ or opened_before.st_size != opened_after.st_size+ or opened_before.st_mtime_ns != opened_after.st_mtime_ns+ or not hmac.compare_digest(digest.hexdigest(), expected_sha256)+ ):+ raise ValueError("binary verification failed")+ return resolved, fd+ except BaseException:+ os.close(fd)+ raise+++def _require_outside(path: Path, protected_directory: Path) -> None:+ try:+ path.relative_to(protected_directory)+ except ValueError: # Failure means the path is safely outside the protected directory.+ return+ raise ValueError("runtime path is inside the profile")+++def _atomic_acknowledgement(path: Path, status: str) -> None:+ if status not in {"waiting", "ready", "busy", "finished"} or not path.is_absolute():+ raise ValueError("invalid acknowledgement")+ parent = _resolved_absolute_directory(str(path.parent))+ temporary_fd, temporary_name = tempfile.mkstemp(+ prefix=f".{path.name}.", suffix=".tmp", dir=parent+ )+ temporary = Path(temporary_name)+ try:+ os.chmod(temporary, 0o600)+ with os.fdopen(temporary_fd, "w", encoding="ascii", newline="") as stream:+ temporary_fd = -1+ stream.write(status)+ stream.flush()+ os.fsync(stream.fileno())+ os.replace(temporary, path)+ finally:+ if temporary_fd >= 0:+ os.close(temporary_fd)+ try:+ temporary.unlink()+ except FileNotFoundError: # Atomic replacement or cleanup may already remove this file.+ pass+++def _control_requested(+ path: Path,+ expected: bytes,+ lock_module: ModuleType,+) -> bool:+ try:+ metadata = path.lstat()+ reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)+ if (+ stat.S_ISLNK(metadata.st_mode)+ or bool(getattr(metadata, "st_file_attributes", 0) & reparse)+ or not stat.S_ISREG(metadata.st_mode)+ or metadata.st_size != len(expected)+ or getattr(metadata, "st_nlink", 1) != 1+ ):+ return False+ if os.name == "posix":+ geteuid = getattr(os, "geteuid", None)+ if (+ not callable(geteuid)+ or metadata.st_uid != geteuid()+ or stat.S_IMODE(metadata.st_mode) != 0o600+ ):+ return False+ fd = os.open(+ path,+ os.O_RDONLY+ | getattr(os, "O_BINARY", 0)+ | getattr(os, "O_CLOEXEC", 0)+ | getattr(os, "O_NOFOLLOW", 0),+ )+ try:+ opened = os.fstat(fd)+ if (opened.st_dev, opened.st_ino) != (metadata.st_dev, metadata.st_ino):+ return False+ lock_module._validate_windows_file_security(fd)+ return os.read(fd, len(expected) + 1) == expected+ finally:+ os.close(fd)+ except (OSError, ValueError, lock_module.ExclusiveProcessLockError):+ # Invalid control content is a false result.+ return False+++def _wait_for_control(+ path: Path,+ expected: bytes,+ lock_module: ModuleType,+) -> bool:+ deadline = time.monotonic() + RELEASE_TIMEOUT_SECONDS+ while time.monotonic() < deadline:+ if _control_requested(path, expected, lock_module):+ return True+ time.sleep(0.05)+ return False+++def _wait_for_child(process: subprocess.Popen[bytes]) -> int:+ def forward(signum: int, _frame: object) -> None:+ try:+ process.send_signal(signum)+ except OSError: # A child that already exited no longer needs the forwarded signal.+ pass++ handled = [signal.SIGINT, signal.SIGTERM]+ previous = {signum: signal.signal(signum, forward) for signum in handled}+ try:+ return process.wait()+ finally:+ for signum, handler in previous.items():+ signal.signal(signum, handler)+++def main(argv: Sequence[str] | None = None) -> int:+ arguments = tuple(sys.argv[1:] if argv is None else argv)+ if len(arguments) != 7:+ return EXIT_INVALID+ (+ lock_raw,+ acknowledgement_raw,+ release_raw,+ binary_raw,+ binary_sha256,+ log_dir_raw,+ environment_raw,+ ) = arguments+ try:+ environment = _strict_environment(environment_raw)+ protected_directory = _resolved_absolute_directory(environment["CODEX_HOME"])+ log_dir = _resolved_absolute_directory(log_dir_raw)+ acknowledgement = Path(acknowledgement_raw)+ release = Path(release_raw)+ if not acknowledgement.is_absolute() or not release.is_absolute():+ raise ValueError("coordination path is not absolute")+ if release.exists() or release.is_symlink():+ raise ValueError("release path is not fresh")+ _require_outside(log_dir, protected_directory)+ _require_outside(acknowledgement.parent.resolve(strict=True), protected_directory)+ _require_outside(release.parent.resolve(strict=True), protected_directory)+ lock_module = _load_lock_module()+ except (ImportError, OSError, RuntimeError, ValueError, json.JSONDecodeError):+ # Invalid guardian input maps to the stable invalid exit.+ return EXIT_INVALID++ lock = None+ try:+ try:+ _atomic_acknowledgement(acknowledgement, "waiting")+ except (OSError, ValueError): # Unsafe coordination state maps to the stable unsafe exit.+ return EXIT_UNSAFE+ if not _wait_for_control(release, b"acquire", lock_module):+ return EXIT_UNSAFE+ try:+ lock = lock_module.ExclusiveProcessLock.acquire(+ lock_raw,+ protected_directory=protected_directory,+ )+ except lock_module.ExclusiveProcessLockError as exc:+ # Contention maps to a stable exit code.+ try:+ _atomic_acknowledgement(acknowledgement, "busy")+ except (OSError, ValueError): # Failure to publish contention must fail closed.+ return EXIT_UNSAFE+ return EXIT_BUSY if exc.reason == "busy" else EXIT_UNSAFE++ try:+ _atomic_acknowledgement(acknowledgement, "ready")+ except (OSError, ValueError): # Failure to confirm ownership must fail closed.+ return EXIT_UNSAFE++ command = [+ binary_raw,+ "-c",+ 'cli_auth_credentials_store="file"',+ "-c",+ f"log_dir={json.dumps(str(log_dir))}",+ "login",+ ]+ binary_fd = -1+ try:+ binary, binary_fd = _open_verified_binary(binary_raw, binary_sha256)+ command[0] = str(binary)+ try:+ process = subprocess.Popen( # noqa: S603 - fixed argv, verified binary+ command,+ env=environment,+ shell=False,+ )+ finally:+ os.close(binary_fd)+ binary_fd = -1+ except (OSError, ValueError): # A verified launch failure maps to the fixed exit code.+ return EXIT_LAUNCH_FAILED+ child_return_code = _wait_for_child(process)+ try:+ _atomic_acknowledgement(acknowledgement, "finished")+ except (OSError, ValueError):+ # The parent cannot perform its post-check without this signal. Hold+ # ownership for the same bounded crash timeout before releasing.+ time.sleep(RELEASE_TIMEOUT_SECONDS)+ return child_return_code+ _wait_for_control(release, b"release", lock_module)+ return child_return_code+ finally:+ if lock is not None:+ lock.close()+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.pyindex 642b25bd34..dcd6692594 100644--- a/jarvis/commands/registry.py+++ b/jarvis/commands/registry.py@@ -128,21 +128,32 @@ def _str_param(description: str, *, enum: list[str] | None = None,return schema-def _provider_switch_params(tier: str, *, brain_switchable_only: bool = False,- ) -> dict[str, Any]:+def _provider_switch_params(+ tier: str,+ *,+ brain_switchable_only: bool = False,+ allow_experimental_ack: bool = False,+) -> dict[str, Any]:enum = _provider_ids(tier, brain_switchable_only=brain_switchable_only)+ properties: dict[str, Any] = {+ "provider": _str_param(+ f"Target {tier} provider id.", enum=enum or None, min_length=1+ ),+ "persist": {+ "type": "boolean",+ "default": True,+ "description": "Persist the choice to jarvis.toml (survives restart).",+ },+ }+ if allow_experimental_ack:+ properties["accept_experimental"] = {+ "type": "boolean",+ "default": False,+ "description": "Explicitly acknowledge an experimental provider transport.",+ }return {"type": "object",- "properties": {- "provider": _str_param(- f"Target {tier} provider id.", enum=enum or None, min_length=1- ),- "persist": {- "type": "boolean",- "default": True,- "description": "Persist the choice to jarvis.toml (survives restart).",- },- },+ "properties": properties,"required": ["provider"],}@@ -206,11 +217,15 @@ def _build_registry() -> tuple[AppCommand, ...]:title="Switch realtime voice provider",description=("Switch which realtime voice engine (speech-to-speech) is "- "active, e.g. openai-realtime or gemini-live."+ "active, including subscription- and API-backed providers. "+ "Experimental transports require explicit acknowledgement."),method="POST",path="/api/realtime/switch",- params=_provider_switch_params("realtime"),+ params=_provider_switch_params(+ "realtime",+ allow_experimental_ack=True,+ ),ui_section="apikeys",voice_aliases={"de": ("wechsle das realtime-modell zu gemini",), # i18n-allow: input vocabdiff --git a/jarvis/core/exclusive_process_lock.py b/jarvis/core/exclusive_process_lock.pynew file mode 100644index 0000000000..c54f0e3855--- /dev/null+++ b/jarvis/core/exclusive_process_lock.py@@ -0,0 +1,488 @@+"""Strict non-blocking file lock for coordinating separate processes.++The lock file is permanent and contains one NUL byte. Ownership belongs to+the open file descriptor: closing it, or process exit, releases the OS lock.+The file is never removed because unlinking a live lock creates two unrelated+lock identities and defeats mutual exclusion.+"""++from __future__ import annotations++import errno+import os+import stat+import sys+from pathlib import Path+from types import TracebackType+from typing import Any, Literal, NoReturn, Self++LockFailureReason = Literal["busy", "unsafe", "unavailable"]++_MESSAGES: dict[LockFailureReason, str] = {+ "busy": "The protected profile is already in use.",+ "unsafe": "The profile process lock is unsafe.",+ "unavailable": "The profile process lock is unavailable.",+}+_REPARSE_POINT = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)+++class ExclusiveProcessLockError(RuntimeError):+ """Stable, path-free failure raised when an exclusive lock cannot be held."""++ def __init__(self, reason: LockFailureReason) -> None:+ self.reason = reason+ super().__init__(_MESSAGES[reason])+++def _raise(reason: LockFailureReason, cause: BaseException | None = None) -> NoReturn:+ error = ExclusiveProcessLockError(reason)+ if cause is None:+ raise error+ raise error from cause+++def _is_link_or_reparse(metadata: os.stat_result) -> bool:+ return stat.S_ISLNK(metadata.st_mode) or bool(+ getattr(metadata, "st_file_attributes", 0) & _REPARSE_POINT+ )+++def _validate_metadata(metadata: os.stat_result) -> None:+ if _is_link_or_reparse(metadata) or not stat.S_ISREG(metadata.st_mode):+ _raise("unsafe")+ if getattr(metadata, "st_nlink", 1) != 1:+ _raise("unsafe")+ if metadata.st_size != 1:+ _raise("unsafe")+ if os.name == "posix":+ geteuid = getattr(os, "geteuid", None)+ if not callable(geteuid) or metadata.st_uid != geteuid():+ _raise("unsafe")+ if stat.S_IMODE(metadata.st_mode) != 0o600:+ _raise("unsafe")+++def _validate_windows_handle_security(handle: int, *, directory: bool) -> None:+ """Require an exact current-user-only Windows owner and DACL."""+ if sys.platform != "win32":+ return+ try:+ import ctypes # noqa: PLC0415 - Windows-only, off the import floor+ from ctypes import wintypes # noqa: PLC0415 - Windows-only++ token_query = 0x0008+ token_user_class = 1+ security_file_object = 1+ owner_security_information = 0x00000001+ dacl_security_information = 0x00000004+ sddl_revision = 1+ error_insufficient_buffer = 122++ class SidAndAttributes(ctypes.Structure):+ _fields_ = [("Sid", ctypes.c_void_p), ("Attributes", wintypes.DWORD)]++ class TokenUser(ctypes.Structure):+ _fields_ = [("User", SidAndAttributes)]++ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)+ kernel32.GetCurrentProcess.restype = wintypes.HANDLE+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]+ kernel32.CloseHandle.restype = wintypes.BOOL+ kernel32.LocalFree.argtypes = [wintypes.HLOCAL]+ kernel32.LocalFree.restype = wintypes.HLOCAL+ advapi32.OpenProcessToken.argtypes = [+ wintypes.HANDLE,+ wintypes.DWORD,+ ctypes.POINTER(wintypes.HANDLE),+ ]+ advapi32.OpenProcessToken.restype = wintypes.BOOL+ advapi32.GetTokenInformation.argtypes = [+ wintypes.HANDLE,+ ctypes.c_uint,+ ctypes.c_void_p,+ wintypes.DWORD,+ ctypes.POINTER(wintypes.DWORD),+ ]+ advapi32.GetTokenInformation.restype = wintypes.BOOL+ advapi32.GetSecurityInfo.argtypes = [+ wintypes.HANDLE,+ ctypes.c_uint,+ wintypes.DWORD,+ ctypes.POINTER(ctypes.c_void_p),+ ctypes.POINTER(ctypes.c_void_p),+ ctypes.c_void_p,+ ctypes.c_void_p,+ ctypes.POINTER(wintypes.HLOCAL),+ ]+ advapi32.GetSecurityInfo.restype = wintypes.DWORD+ advapi32.EqualSid.argtypes = [ctypes.c_void_p, ctypes.c_void_p]+ advapi32.EqualSid.restype = wintypes.BOOL+ advapi32.ConvertSidToStringSidW.argtypes = [+ ctypes.c_void_p,+ ctypes.POINTER(wintypes.LPWSTR),+ ]+ advapi32.ConvertSidToStringSidW.restype = wintypes.BOOL+ advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [+ wintypes.LPCWSTR,+ wintypes.DWORD,+ ctypes.POINTER(ctypes.c_void_p),+ ctypes.POINTER(wintypes.DWORD),+ ]+ advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wintypes.BOOL+ advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW.argtypes = [+ ctypes.c_void_p,+ wintypes.DWORD,+ wintypes.DWORD,+ ctypes.POINTER(wintypes.LPWSTR),+ ctypes.POINTER(wintypes.DWORD),+ ]+ advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW.restype = wintypes.BOOL++ security_information = owner_security_information | dacl_security_information++ def local_free(pointer: Any) -> None:+ if pointer:+ kernel32.LocalFree(ctypes.cast(pointer, wintypes.HLOCAL))++ def canonical_sddl(descriptor_pointer: object) -> str:+ rendered = wintypes.LPWSTR()+ rendered_length = wintypes.DWORD()+ if not advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW(+ descriptor_pointer,+ sddl_revision,+ security_information,+ ctypes.byref(rendered),+ ctypes.byref(rendered_length),+ ):+ _raise("unavailable")+ try:+ value = rendered.value+ if not value:+ _raise("unavailable")+ return value+ finally:+ local_free(rendered)++ def canonical_expected(sddl: str) -> str:+ pointer = ctypes.c_void_p()+ size = wintypes.DWORD()+ if not advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW(+ sddl,+ sddl_revision,+ ctypes.byref(pointer),+ ctypes.byref(size),+ ):+ _raise("unavailable")+ try:+ return canonical_sddl(pointer)+ finally:+ local_free(pointer)++ token = wintypes.HANDLE()+ descriptor = wintypes.HLOCAL()+ try:+ if not advapi32.OpenProcessToken(+ kernel32.GetCurrentProcess(), token_query, ctypes.byref(token)+ ):+ _raise("unavailable")+ required = wintypes.DWORD()+ if advapi32.GetTokenInformation(+ token, token_user_class, None, 0, ctypes.byref(required)+ ):+ _raise("unavailable")+ if ctypes.get_last_error() != error_insufficient_buffer or not required.value:+ _raise("unavailable")+ token_buffer = ctypes.create_string_buffer(required.value)+ if not advapi32.GetTokenInformation(+ token,+ token_user_class,+ token_buffer,+ required.value,+ ctypes.byref(required),+ ):+ _raise("unavailable")+ token_user = ctypes.cast(token_buffer, ctypes.POINTER(TokenUser)).contents+ sid_text = wintypes.LPWSTR()+ if not advapi32.ConvertSidToStringSidW(token_user.User.Sid, ctypes.byref(sid_text)):+ _raise("unavailable")+ try:+ sid = sid_text.value+ if not sid:+ _raise("unavailable")+ finally:+ local_free(sid_text)++ owner = ctypes.c_void_p()+ dacl = ctypes.c_void_p()+ result = advapi32.GetSecurityInfo(+ wintypes.HANDLE(handle),+ security_file_object,+ security_information,+ ctypes.byref(owner),+ None,+ ctypes.byref(dacl),+ None,+ ctypes.byref(descriptor),+ )+ if result != 0 or not owner.value or not dacl.value or not descriptor:+ _raise("unavailable")+ if not advapi32.EqualSid(owner, token_user.User.Sid):+ _raise("unsafe")+ actual_sddl = canonical_sddl(descriptor)+ if directory:+ expected = {canonical_expected(f"O:{sid}D:P(A;OICI;FA;;;{sid})")}+ else:+ expected = {+ canonical_expected(f"O:{sid}D:P(A;;FA;;;{sid})"),+ canonical_expected(f"O:{sid}D:(A;ID;FA;;;{sid})"),+ }+ if actual_sddl not in expected:+ _raise("unsafe")+ finally:+ if descriptor:+ kernel32.LocalFree(descriptor)+ if token:+ kernel32.CloseHandle(token)+ except ExclusiveProcessLockError:+ raise+ except (ImportError, OSError, ValueError) as exc:+ # Translate platform failure to a stable error.+ _raise("unavailable", exc)+++def _validate_windows_file_security(fd: int) -> None:+ if sys.platform != "win32":+ return+ try:+ import msvcrt # noqa: PLC0415 - Windows-only, off the import floor++ _validate_windows_handle_security(msvcrt.get_osfhandle(fd), directory=False)+ except ExclusiveProcessLockError:+ raise+ except (ImportError, OSError, ValueError) as exc: # Translate handle failure to a stable error.+ _raise("unavailable", exc)+++def _validate_windows_directory_security(path: Path) -> None:+ if sys.platform != "win32":+ return+ try:+ import ctypes # noqa: PLC0415 - Windows-only, off the import floor+ from ctypes import wintypes # noqa: PLC0415 - Windows-only++ read_control = 0x00020000+ share_read = 0x00000001+ share_write = 0x00000002+ open_existing = 3+ open_reparse = 0x00200000+ backup_semantics = 0x02000000+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.CreateFileW.argtypes = [+ wintypes.LPCWSTR,+ wintypes.DWORD,+ wintypes.DWORD,+ wintypes.LPVOID,+ wintypes.DWORD,+ wintypes.DWORD,+ wintypes.HANDLE,+ ]+ kernel32.CreateFileW.restype = wintypes.HANDLE+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]+ kernel32.CloseHandle.restype = wintypes.BOOL+ handle = kernel32.CreateFileW(+ os.fspath(path),+ read_control,+ share_read | share_write,+ None,+ open_existing,+ open_reparse | backup_semantics,+ None,+ )+ invalid = ctypes.c_void_p(-1).value+ if not handle or handle == invalid:+ _raise("unavailable")+ try:+ _validate_windows_handle_security(handle, directory=True)+ finally:+ kernel32.CloseHandle(handle)+ except ExclusiveProcessLockError:+ raise+ except (ImportError, OSError, ValueError) as exc:+ # Translate directory failure to a stable error.+ _raise("unavailable", exc)+++def _canonical_lock_path(lock_path: Path, protected_directory: Path) -> Path:+ if not lock_path.is_absolute() or not protected_directory.is_absolute():+ _raise("unsafe")+ try:+ parent_metadata = lock_path.parent.lstat()+ if _is_link_or_reparse(parent_metadata) or not stat.S_ISDIR(parent_metadata.st_mode):+ _raise("unsafe")+ if os.name == "posix":+ geteuid = getattr(os, "geteuid", None)+ if (+ not callable(geteuid)+ or parent_metadata.st_uid != geteuid()+ or stat.S_IMODE(parent_metadata.st_mode) != 0o700+ ):+ _raise("unsafe")+ _validate_windows_directory_security(lock_path.parent)+ parent = lock_path.parent.resolve(strict=True)+ if protected_directory.exists() or protected_directory.is_symlink():+ protected_metadata = protected_directory.lstat()+ if _is_link_or_reparse(protected_metadata):+ _raise("unsafe")+ protected = protected_directory.resolve(strict=True)+ else:+ protected_parent = protected_directory.parent.resolve(strict=True)+ protected = protected_parent / protected_directory.name+ except ExclusiveProcessLockError:+ raise+ except OSError as exc: # Canonicalization failure is reported as unavailable.+ _raise("unavailable", exc)+ candidate = parent / lock_path.name+ try:+ candidate.relative_to(protected)+ except ValueError: # Failure means the lock is safely outside the protected directory.+ return candidate+ _raise("unsafe")+++def _open_lock_file(path: Path) -> int:+ flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_BINARY", 0)+ flags |= getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)+ existed = path.exists() or path.is_symlink()+ if existed:+ try:+ _validate_metadata(path.lstat())+ except OSError as exc: # Metadata failure is translated to the stable lock error.+ _raise("unavailable", exc)+ else:+ flags |= os.O_EXCL+ try:+ fd = os.open(path, flags, 0o600)+ except FileExistsError:+ # A concurrent creator won. Validate and open the file it published.+ try:+ _validate_metadata(path.lstat())+ fd = os.open(+ path,+ os.O_RDWR+ | getattr(os, "O_BINARY", 0)+ | getattr(os, "O_CLOEXEC", 0)+ | getattr(os, "O_NOFOLLOW", 0),+ )+ except ExclusiveProcessLockError:+ raise+ except OSError as exc: # Concurrent-open failure is translated to the stable lock error.+ _raise("unavailable", exc)+ existed = True+ except OSError as exc: # Open failure is translated without exposing a filesystem path.+ _raise("unsafe" if exc.errno == errno.ELOOP else "unavailable", exc)++ try:+ if not existed:+ os.write(fd, b"\0")+ os.fsync(fd)+ opened = os.fstat(fd)+ _validate_metadata(opened)+ _validate_windows_file_security(fd)+ current = path.lstat()+ _validate_metadata(current)+ if (opened.st_dev, opened.st_ino) != (current.st_dev, current.st_ino):+ _raise("unsafe")+ return fd+ except BaseException:+ os.close(fd)+ raise+++def _acquire_fd(fd: int) -> None:+ try:+ os.lseek(fd, 0, os.SEEK_SET)+ if sys.platform == "win32":+ import msvcrt # noqa: PLC0415 - Windows-only, off import floor++ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)+ else:+ import fcntl # noqa: PLC0415 - POSIX-only, off import floor++ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except (BlockingIOError, PermissionError) as exc: # Expected contention becomes the busy state.+ _raise("busy", exc)+ except OSError as exc: # Platform lock errors become stable busy or unavailable states.+ busy_errors = {errno.EACCES, errno.EAGAIN, errno.EDEADLK}+ if exc.errno in busy_errors or getattr(exc, "winerror", None) in {32, 33, 36}:+ _raise("busy", exc)+ _raise("unavailable", exc)+++def _release_fd(fd: int) -> None:+ try:+ os.lseek(fd, 0, os.SEEK_SET)+ if sys.platform == "win32":+ import msvcrt # noqa: PLC0415 - Windows-only, off import floor++ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)+ else:+ import fcntl # noqa: PLC0415 - POSIX-only, off import floor++ fcntl.flock(fd, fcntl.LOCK_UN)+ finally:+ os.close(fd)+++class ExclusiveProcessLock:+ """An acquired cross-process lock, released by :meth:`close`."""++ def __init__(self, fd: int) -> None:+ self._fd = fd++ @classmethod+ def acquire(+ cls,+ lock_path: str | os.PathLike[str],+ *,+ protected_directory: str | os.PathLike[str],+ ) -> Self:+ """Acquire immediately or raise :class:`ExclusiveProcessLockError`."""+ path = _canonical_lock_path(Path(lock_path), Path(protected_directory))+ fd = _open_lock_file(path)+ try:+ _acquire_fd(fd)+ except BaseException:+ os.close(fd)+ raise+ return cls(fd)++ @property+ def closed(self) -> bool:+ return self._fd < 0++ def fileno(self) -> int:+ """Return the held descriptor for safe POSIX child inheritance."""+ if self._fd < 0:+ raise ValueError("The profile process lock is closed.")+ return self._fd++ def close(self) -> None:+ if self._fd < 0:+ return+ fd, self._fd = self._fd, -1+ _release_fd(fd)++ def __enter__(self) -> Self:+ return self++ def __exit__(+ self,+ exc_type: type[BaseException] | None,+ exc_value: BaseException | None,+ traceback: TracebackType | None,+ ) -> None:+ self.close()+++__all__ = ["ExclusiveProcessLock", "ExclusiveProcessLockError", "LockFailureReason"]diff --git a/jarvis/core/private_directory.py b/jarvis/core/private_directory.pyindex 8d177e286a..36c8491bc2 100644--- a/jarvis/core/private_directory.py+++ b/jarvis/core/private_directory.py@@ -48,12 +48,12 @@ def _ensure_posix_owner_only_directory(path: Path, *, create: bool) -> None:# An existing path is accepted only after the independent lstat# checks below; this must never become an implicit permission repair.pass- except OSError:+ except OSError: # Platform security setup failure is translated by the fail-closed helper._fail()try:metadata = path.lstat()- except OSError:+ except OSError: # Metadata failure is translated by the fail-closed helper._fail()if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISDIR(metadata.st_mode):diff --git a/jarvis/core/process_tree.py b/jarvis/core/process_tree.pyindex 19ac294a4c..a1f924526e 100644--- a/jarvis/core/process_tree.py+++ b/jarvis/core/process_tree.py@@ -78,6 +78,11 @@ _SIGKILL = getattr(signal, "SIGKILL", signal.SIGTERM)class ProcessTree(Protocol):"""One spawned process and everything it goes on to start."""+ @property+ def supports_containment(self) -> bool:+ """Whether this live container can enforce tree termination."""+ ...+def assign(self, pid: int) -> None:"""Put a freshly spawned process under this container's control."""@@ -94,6 +99,10 @@ class _NoContainment:__slots__ = ("_name",)+ @property+ def supports_containment(self) -> bool:+ return False+def __init__(self, name: str) -> None:self._name = namelogger.debug(@@ -114,6 +123,10 @@ class _WindowsJob:__slots__ = ("_kernel32", "_handle", "_closed", "_name")+ @property+ def supports_containment(self) -> bool:+ return not self._closed+def __init__(self, name: str) -> None:kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]@@ -233,6 +246,10 @@ class _PosixProcessGroup:__slots__ = ("_pgids", "_closed", "_name")+ @property+ def supports_containment(self) -> bool:+ return not self._closed+def __init__(self, name: str) -> None:self._pgids: set[int] = set()self._closed = Falsediff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.pynew file mode 100644index 0000000000..23818cea21--- /dev/null+++ b/jarvis/plugins/realtime/codex_subscription.py@@ -0,0 +1,871 @@+"""Realtime voice through a user's authenticated ChatGPT Codex session.++The adapter intentionally contains no platform API key path. It talks only to+the local Codex app-server, which owns ChatGPT authentication, and keeps all+imports from ``jarvis.*`` lazy so plugin discovery stays off the startup path.+The app-server realtime surface is experimental. Failures may cross only to+realtime fallbacks the user configured explicitly; otherwise the session+closes honestly instead of silently entering usage-billed API voice.+"""++from __future__ import annotations++import asyncio+import base64+import importlib+import inspect+import logging+from collections.abc import AsyncIterator+from contextlib import suppress+from dataclasses import dataclass+from typing import Any++log = logging.getLogger(__name__)++_INPUT_RATE = 24_000+_OUTPUT_RATE = 24_000+_BROKER_OFFER_WAIT_S = 3.0+_OUTPUT_QUIESCENCE_S = 0.5+_NORMALIZATION_QUEUE_MAX = 128+_REMOTE_CLEANUP_TIMEOUT_S = 1.5+_TURN_INTERRUPT_TIMEOUT_S = 1.5+_V1_MODEL = "gpt-realtime-1.5"+_V1_DEFAULT_VOICE = "cove"+_V1_VOICES = frozenset(+ {+ "arbor",+ "breeze",+ "cove",+ "ember",+ "juniper",+ "maple",+ "sol",+ "spruce",+ "vale",+ }+)++_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."+)+_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."+)+_LANGUAGE_UPDATE_TEXT = {+ "de": (+ "For every following assistant audio and text response, reply only in "+ "German. This is a voice-rendering instruction, not a request to use "+ "tools or perform an action."+ ),+ "en": (+ "For every following assistant audio and text response, reply only in "+ "English. This is a voice-rendering instruction, not a request to use "+ "tools or perform an action."+ ),+ "es": (+ "For every following assistant audio and text response, reply only in "+ "Spanish. This is a voice-rendering instruction, not a request to use "+ "tools or perform an action."+ ),+}+++@dataclass(frozen=True, slots=True)+class _PcmChunk:+ pcm: bytes+ sample_rate: int+ timestamp_ns: int = 0+ channels: int = 1+++@dataclass(frozen=True, slots=True)+class _ProviderEvent:+ type: str+ audio: _PcmChunk | None = None+ text: str | None = None+ is_final: bool = False+ ms_played: int | None = None+ error: str | None = None+ recoverable: bool = False+ reconnect_advised: bool = False+ item_id: str | None = None+ call_id: str | None = None+ tool_name: str | None = None+ tool_args: dict[str, Any] | None = None+ handoff_id: str | None = None+ provider_turn_id: str | None = None+++def _notification_parts(notification: Any) -> tuple[str, dict[str, Any]]:+ """Accept the production notification record and lightweight test fakes."""+ if isinstance(notification, dict):+ method = str(notification.get("method", "") or "")+ params = notification.get("params", {})+ else:+ method = str(getattr(notification, "method", "") or "")+ params = getattr(notification, "params", {})+ return method, params if isinstance(params, dict) else {}+++def _thread_id_from_result(result: Any) -> str:+ if not isinstance(result, dict):+ return ""+ thread = result.get("thread")+ if not isinstance(thread, dict):+ return ""+ return str(thread.get("id", "") or "").strip()+++def _safe_error(exc: BaseException, *, max_chars: int = 500) -> str:+ text = " ".join(str(exc).split())+ return (text or type(exc).__name__)[:max_chars]+++def _handoff_text(item: dict[str, Any]) -> str:+ direct = str(+ item.get("input_transcript", "")+ or item.get("inputTranscript", "")+ or ""+ ).strip()+ if direct:+ return direct+ active = item.get("active_transcript", item.get("activeTranscript", []))+ if not isinstance(active, list):+ return ""+ for entry in reversed(active):+ if not isinstance(entry, dict):+ continue+ if str(entry.get("role", "") or "").strip().lower() != "user":+ continue+ text = str(entry.get("text", "") or "").strip()+ if text:+ return text+ return ""+++async def _close_subscription(subscription: Any) -> None:+ close = getattr(subscription, "close", None)+ if not callable(close):+ return+ result = close()+ if inspect.isawaitable(result):+ await result+++def _consume_cleanup_task(task: asyncio.Task[Any]) -> None:+ with suppress(asyncio.CancelledError, Exception):+ task.result()+++async def _bounded_remote_call(+ client: Any,+ method_name: str,+ thread_id: str,+ *args: str,+) -> bool:+ """Run one cleanup/control RPC without letting it hold session teardown."""+ method = getattr(client, method_name, None)+ if not callable(method):+ log.warning("Codex app-server client lacks required %s cleanup", method_name)+ return False+ task = asyncio.create_task(method(thread_id, *args))+ done, _pending = await asyncio.wait(+ {task}, timeout=_REMOTE_CLEANUP_TIMEOUT_S+ )+ if not done:+ task.cancel()+ # Reap the canceled coroutine within a small second bound so it cannot+ # leak an unobserved exception into loop shutdown. A cleanup RPC that+ # suppresses cancellation still cannot hold session teardown open.+ reaped, _still_pending = await asyncio.wait({task}, timeout=0.1)+ if reaped:+ _consume_cleanup_task(task)+ else:+ task.add_done_callback(_consume_cleanup_task)+ log.warning(+ "Codex subscription %s timed out after %.1fs",+ method_name,+ _REMOTE_CLEANUP_TIMEOUT_S,+ )+ return False+ try:+ task.result()+ except Exception: # noqa: BLE001 - cleanup continues to the next boundary+ log.warning("Codex subscription %s failed", method_name, exc_info=True)+ return False+ return True+++async def _poison_client(client: Any) -> None:+ method = getattr(client, "poison", None) or getattr(client, "close", None)+ if not callable(method):+ log.error("Codex app-server cleanup failed and the client cannot be poisoned")+ return+ try:+ result = method()+ if inspect.isawaitable(result):+ await result+ except Exception: # noqa: BLE001 - containment attempt is logged explicitly+ log.error("Codex app-server poison failed", exc_info=True)+++async def _cleanup_remote_thread(client: Any, thread_id: str) -> bool:+ """Stop realtime and unload its ephemeral app-server thread, in order."""+ if not thread_id:+ return True+ stopped = await _bounded_remote_call(client, "realtime_stop", thread_id)+ unsubscribed = await _bounded_remote_call(+ client,+ "thread_unsubscribe",+ thread_id,+ )+ clean = stopped and unsubscribed+ if not clean:+ await _poison_client(client)+ return clean+++class _CodexSubscriptionRealtimeSession:+ supports_tool_updates = False+ creates_responses_automatically = True+ isolates_response_generations = True+ rebuild_on_transport_death = False+ direct_speech_is_authoritative = True++ def __init__(+ self,+ *,+ client: Any,+ subscription: Any,+ thread_id: str,+ answer_sdp: str,+ offer_lease: Any = None,+ language: str = "en",+ ) -> None:+ self._client = client+ self._subscription = subscription+ self._thread_id = thread_id+ self.session_id = thread_id+ self.answer_sdp = answer_sdp+ self.realtime_version = ""+ self._offer_lease = offer_lease+ self._closed = False+ self._last_input_item_id = ""+ self._assistant_delta_text = ""+ self._language = str(language or "en").strip().lower()+ self._active_codex_turn_id = ""+ self._handoff_interrupt_pending = False++ async def _interrupt_active_codex_turn(self) -> None:+ turn_id = self._active_codex_turn_id+ if not turn_id:+ return+ self._active_codex_turn_id = ""+ self._handoff_interrupt_pending = False+ method = getattr(self._client, "turn_interrupt", None)+ if not callable(method):+ log.warning("Codex app-server client cannot interrupt handoff turn")+ return+ try:+ await asyncio.wait_for(+ method(self._thread_id, turn_id),+ timeout=_TURN_INTERRUPT_TIMEOUT_S,+ )+ except Exception: # noqa: BLE001 - containment flags remain the backstop+ log.warning(+ "Codex subscription handoff turn interrupt failed",+ exc_info=True,+ )++ async def send_audio(self, chunk: Any) -> None:+ if self._closed:+ raise RuntimeError("Codex subscription realtime session is closed")+ sample_rate = int(getattr(chunk, "sample_rate", 0) or 0)+ channels = int(getattr(chunk, "channels", 1) or 1)+ if sample_rate <= 0:+ raise ValueError("Codex subscription realtime audio needs a sample rate")+ if channels != 1:+ raise ValueError("Codex subscription realtime accepts mono PCM only")+ pcm = bytes(getattr(chunk, "pcm", b"") or b"")+ if not pcm:+ return+ await self._client.realtime_append_audio(+ self._thread_id,+ data=base64.b64encode(pcm).decode("ascii"),+ sample_rate=sample_rate,+ num_channels=channels,+ samples_per_channel=len(pcm) // 2,+ )++ async def receive(self) -> AsyncIterator[_ProviderEvent]:+ # Stay below app-server's bounded subscription queue so a stalled+ # consumer propagates backpressure instead of silently buffering an+ # unbounded amount of audio in a second layer.+ queue: asyncio.Queue[tuple[str, Any]] = asyncio.Queue(+ maxsize=_NORMALIZATION_QUEUE_MAX+ )+ timer_tasks: set[asyncio.Task[None]] = set()+ completion_task: asyncio.Task[None] | None = None+ completion_generation = 0+ completion_emitted = False+ stream_ended = False+ version = self.realtime_version.lower().removeprefix("v")+ authoritative_done = version == "3"++ async def _pump_notifications() -> None:+ try:+ async for notification in self._subscription:+ await queue.put(("notification", notification))+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 - normalized by consumer+ await queue.put(("stream_error", exc))+ else:+ await queue.put(("stream_end", None))++ async def _emit_after_idle(generation: int) -> None:+ await asyncio.sleep(_OUTPUT_QUIESCENCE_S)+ await queue.put(("completion", generation))++ def _cancel_completion() -> None:+ nonlocal completion_task, completion_generation+ completion_generation += 1+ if completion_task is not None and not completion_task.done():+ completion_task.cancel()+ completion_task = None++ def _arm_completion() -> None:+ nonlocal completion_task, completion_generation+ _cancel_completion()+ generation = completion_generation+ completion_task = asyncio.create_task(+ _emit_after_idle(generation),+ name=f"codex-realtime-quiescence-{self._thread_id}",+ )+ timer_tasks.add(completion_task)+ completion_task.add_done_callback(timer_tasks.discard)++ pump_task = asyncio.create_task(+ _pump_notifications(),+ name=f"codex-realtime-notifications-{self._thread_id}",+ )+ try:+ while True:+ queue_kind, payload = await queue.get()+ if queue_kind == "completion":+ if payload != completion_generation:+ continue+ completion_task = None+ if not completion_emitted:+ completion_emitted = True+ yield _ProviderEvent(type="turn_complete")+ if stream_ended:+ if not self._closed:+ yield _ProviderEvent(+ type="error",+ error=(+ "Codex app-server notification stream ended "+ "unexpectedly"+ ),+ )+ return+ continue++ if queue_kind == "stream_error":+ _cancel_completion()+ exc = payload+ yield _ProviderEvent(+ type="error",+ error=(+ "Codex app-server notification stream failed: "+ f"{type(exc).__name__}: {_safe_error(exc)}"+ ),+ )+ return++ if queue_kind == "stream_end":+ stream_ended = True+ if completion_task is not None:+ continue+ if not self._closed:+ yield _ProviderEvent(+ type="error",+ error=(+ "Codex app-server notification stream ended "+ "unexpectedly"+ ),+ )+ return++ notification = payload+ method, params = _notification_parts(notification)+ event_thread = str(params.get("threadId", "") or "")+ if event_thread and event_thread != self._thread_id:+ continue++ if method == "turn/started":+ turn = params.get("turn")+ if isinstance(turn, dict):+ self._active_codex_turn_id = str(+ turn.get("id", "") or ""+ ).strip()+ if self._handoff_interrupt_pending:+ await self._interrupt_active_codex_turn()+ continue++ if method in {"turn/completed", "turn/failed"}:+ turn = params.get("turn")+ completed_id = (+ str(turn.get("id", "") or "").strip()+ if isinstance(turn, dict)+ else ""+ )+ if not completed_id or completed_id == self._active_codex_turn_id:+ self._active_codex_turn_id = ""+ continue++ if method == "thread/realtime/started":+ # The start RPC result is empty in exact-0.146; the live+ # protocol version exists only on this notification.+ self.realtime_version = str(params.get("version", "") or "").strip()+ authoritative_done = (+ self.realtime_version.lower().removeprefix("v") == "3"+ )+ continue++ if method == "thread/realtime/transcript/delta":+ role = str(params.get("role", "") or "").lower()+ delta = str(params.get("delta", "") or "")+ if not delta:+ continue+ if role == "user":+ _cancel_completion()+ completion_emitted = False+ yield _ProviderEvent(+ type="input_transcript",+ text=delta,+ is_final=False,+ item_id=self._last_input_item_id or None,+ )+ elif role == "assistant":+ # A later transcript delta proves the previous+ # transcript-part ``done`` was not a turn boundary.+ _cancel_completion()+ completion_emitted = False+ self._assistant_delta_text += delta+ yield _ProviderEvent(+ type="output_transcript_delta",+ text=delta,+ is_final=False,+ )+ continue++ if method == "thread/realtime/transcript/done":+ role = str(params.get("role", "") or "").lower()+ text = str(params.get("text", "") or "")+ if role == "user":+ _cancel_completion()+ completion_emitted = False+ yield _ProviderEvent(+ type="input_transcript",+ text=text,+ is_final=True,+ item_id=self._last_input_item_id or None,+ )+ elif role == "assistant":+ # Emit only a missing suffix so transcript consumers do+ # not see the final text twice.+ suffix = text+ if text.startswith(self._assistant_delta_text):+ suffix = text[len(self._assistant_delta_text) :]+ if suffix:+ yield _ProviderEvent(+ type="output_transcript_delta",+ text=suffix,+ is_final=True,+ )+ self._assistant_delta_text = ""+ if authoritative_done:+ _cancel_completion()+ if not completion_emitted:+ completion_emitted = True+ yield _ProviderEvent(type="turn_complete")+ elif not completion_emitted:+ _arm_completion()+ continue++ if method == "thread/realtime/outputAudio/delta":+ # The sideband PCM is authoritative for Jarvis playback:+ # it passes through the existing scrub, barge-in, and+ # persistence gates. The browser peer intentionally does+ # not play the duplicate RTP track.+ audio = params.get("audio")+ if not isinstance(audio, dict):+ _cancel_completion()+ yield _ProviderEvent(+ type="error",+ error="Codex app-server emitted an invalid audio payload",+ )+ return+ try:+ pcm = base64.b64decode(+ str(audio.get("data", "") or ""), validate=True+ )+ sample_rate = int(audio.get("sampleRate", 0) or 0)+ channels = int(audio.get("numChannels", 1) or 1)+ except (ValueError, TypeError) as exc:+ _cancel_completion()+ yield _ProviderEvent(+ type="error",+ error=(+ "Codex app-server emitted malformed realtime audio: "+ f"{_safe_error(exc)}"+ ),+ )+ return+ if not pcm or sample_rate <= 0 or channels != 1:+ _cancel_completion()+ yield _ProviderEvent(+ type="error",+ error=(+ "Codex app-server emitted unsupported realtime audio "+ f"(sample_rate={sample_rate}, channels={channels})"+ ),+ )+ return+ if completion_task is not None:+ _arm_completion()+ yield _ProviderEvent(+ type="audio_delta",+ audio=_PcmChunk(+ pcm=pcm,+ sample_rate=sample_rate,+ channels=channels,+ ),+ )+ continue++ if method == "thread/realtime/itemAdded":+ item = params.get("item")+ if not isinstance(item, dict):+ continue+ item_type = str(item.get("type", "") or "")+ if item_type == "input_audio_buffer.speech_started":+ _cancel_completion()+ completion_emitted = False+ self._assistant_delta_text = ""+ self._last_input_item_id = str(+ item.get("item_id", "") or ""+ )+ yield _ProviderEvent(+ type="speech_started",+ item_id=self._last_input_item_id or None,+ )+ elif item_type == "response.cancelled":+ _cancel_completion()+ completion_emitted = False+ self._assistant_delta_text = ""+ yield _ProviderEvent(type="interrupted")+ elif item_type == "handoff_request":+ # Exact Codex 0.146 routes this item into a normal Codex+ # turn even with clientManagedHandoffs enabled; that flag+ # suppresses only automatic output delivery. Interrupt+ # the turn as soon as its id is visible and hand control+ # to Jarvis's deterministic supervisor.+ _cancel_completion()+ self._handoff_interrupt_pending = True+ direct_turn_id = str(+ item.get("turn_id", "")+ or item.get("turnId", "")+ or ""+ ).strip()+ if direct_turn_id:+ self._active_codex_turn_id = direct_turn_id+ await self._interrupt_active_codex_turn()+ yield _ProviderEvent(+ type="handoff_requested",+ text=_handoff_text(item) or None,+ handoff_id=str(+ item.get("handoff_id", "")+ or item.get("handoffId", "")+ or ""+ ).strip()+ or None,+ provider_turn_id=(direct_turn_id or None),+ )+ continue++ if method == "thread/realtime/error":+ _cancel_completion()+ message = str(params.get("message", "") or "").strip()+ yield _ProviderEvent(+ type="error",+ error=message or "Codex subscription realtime transport failed",+ )+ return++ if method == "thread/realtime/closed":+ _cancel_completion()+ if self._closed:+ return+ reason = str(params.get("reason", "") or "").strip()+ yield _ProviderEvent(+ type="error",+ error=(+ "Codex subscription realtime transport closed"+ + (f": {reason}" if reason else "")+ ),+ )+ return+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 - normalize adapter failures+ yield _ProviderEvent(+ type="error",+ error=(+ "Codex app-server notification handling failed: "+ f"{type(exc).__name__}: {_safe_error(exc)}"+ ),+ )+ finally:+ _cancel_completion()+ if not pump_task.done():+ pump_task.cancel()+ for task in tuple(timer_tasks):+ if not task.done():+ task.cancel()+ await asyncio.gather(+ pump_task,+ *tuple(timer_tasks),+ return_exceptions=True,+ )++ async def update_session(+ self,+ *,+ instructions: str | None = None,+ 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+ normalized = str(language or "").strip().lower()+ if normalized not in _LANGUAGE_UPDATE_TEXT or normalized == self._language:+ return+ await self._client.realtime_append_text(+ self._thread_id,+ _LANGUAGE_UPDATE_TEXT[normalized],+ role="developer",+ )+ self._language = normalized++ 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+ # app-server action.+ del required_tool++ async def send_text(self, text: str) -> None:+ await self._client.realtime_append_text(+ self._thread_id, str(text), role="developer"+ )++ async def send_speech(self, text: str) -> None:+ """Queue trusted verbatim speech without starting a Codex model turn."""+ await self._client.realtime_append_speech(self._thread_id, str(text))++ async def truncate(self, audio_end_ms: int) -> None:+ del audio_end_ms++ async def interrupt(self) -> None:+ await self._interrupt_active_codex_turn()++ async def send_tool_result(self, call_id: str, name: str, result: dict[str, Any]) -> None:+ del call_id, name, result+ raise RuntimeError("Codex subscription realtime does not execute tools directly")++ async def close(self) -> None:+ if self._closed:+ return+ self._closed = True+ try:+ await _cleanup_remote_thread(self._client, self._thread_id)+ finally:+ try:+ await _close_subscription(self._subscription)+ finally:+ if self._offer_lease is not None:+ await self._offer_lease.release()+++class CodexSubscriptionRealtimeProvider:+ """Structural provider entry point backed by ChatGPT-managed Codex auth."""++ name = "codex-subscription-realtime"+ credential_family = "openai-chatgpt-subscription"+ supports_realtime = True+ implicit_usage_fallback_allowed = False++ @classmethod+ async def verify_activation(cls, cfg: Any) -> None:+ """Run the provider's authoritative account/config activation gate."""+ app_server_module = importlib.import_module("jarvis.codex_app_server")+ codex_cfg = getattr(cfg, "codex", None)+ binary_path = str(getattr(codex_cfg, "binary_path", "") or "").strip() or None+ client = app_server_module.get_shared_codex_app_server(binary_path)+ await client.require_chatgpt_login()+ requires_webrtc_offer = True+ input_sample_rate = _INPUT_RATE+ output_sample_rate = _OUTPUT_RATE+ credential_candidates: tuple[tuple[str, str | None], ...] = ()++ def __init__(+ self,+ *,+ client: Any = None,+ offer_broker: Any = None,+ binary_path: str | None = None,+ ) -> None:+ self._client = client+ self._offer_broker = offer_broker+ self._binary_path = str(binary_path or "").strip() or None++ @classmethod+ def from_runtime_config(cls, cfg: Any) -> CodexSubscriptionRealtimeProvider:+ binary_path = str(+ getattr(getattr(cfg, "codex", None), "binary_path", "") or ""+ ).strip()+ return cls(binary_path=binary_path or None)++ @classmethod+ def external_login_ready(cls, cfg: Any = None) -> bool:+ """Return the dedicated-profile snapshot; app-server verifies it live."""+ try:+ # Dynamic import preserves the plugin boundary: discovery imports+ # no ``jarvis.*`` module until this explicit capability probe.+ app_server_module = importlib.import_module("jarvis.codex_app_server")+ binary_path = str(+ getattr(getattr(cfg, "codex", None), "binary_path", "") or ""+ ).strip()+ status = app_server_module.codex_subscription_auth_snapshot(+ binary_path or None+ )+ return bool(+ getattr(status, "available", False)+ and getattr(status, "chatgpt_authenticated", False)+ )+ except Exception: # noqa: BLE001 - discovery degrades to other providers+ log.warning("Codex ChatGPT login status probe failed", exc_info=True)+ return False++ async def can_open_duplex_session(self) -> bool:+ # The factory already performed the bounded external-login probe. The+ # authoritative handshake below starts app-server, which independently+ # verifies the live ChatGPT account. Repeating the CLI probe here costs+ # seconds on a cold call without strengthening the trust boundary.+ return True++ async def open_session(self, cfg: Any) -> _CodexSubscriptionRealtimeSession:+ offer_sdp = str(getattr(cfg, "transport_offer_sdp", "") or "").strip()+ offer_lease: Any = None+ if not offer_sdp:+ broker = self._offer_broker+ if broker is None:+ broker_module = importlib.import_module(+ "jarvis.realtime.offer_broker"+ )+ broker = broker_module.get_realtime_transport_offer_broker()+ offer_lease = await broker.acquire(timeout_s=_BROKER_OFFER_WAIT_S)+ if offer_lease is None:+ raise RuntimeError(+ "Codex subscription realtime needs a connected UI WebRTC "+ "offer, so this session cannot start"+ )+ offer_sdp = offer_lease.offer_sdp++ broker_module = importlib.import_module("jarvis.realtime.offer_broker")+ offer_sdp = broker_module.validate_webrtc_offer_sdp(offer_sdp)++ client = self._client+ if client is None:+ app_server_module = importlib.import_module("jarvis.codex_app_server")+ client = app_server_module.get_shared_codex_app_server(self._binary_path)++ subscription: Any = None+ thread_id = ""+ try:+ # ``thread_start`` lazily calls app-server ``ensure_started``. That+ # performs the authoritative capability probe plus live+ # ``account/read`` verification before accepting this thread.+ thread_result = await client.thread_start(+ base_instructions=_THREAD_BASE_INSTRUCTIONS,+ developer_instructions=_THREAD_DEVELOPER_INSTRUCTIONS,+ ephemeral=True,+ )+ thread_id = _thread_id_from_result(thread_result)+ if not thread_id:+ raise RuntimeError("Codex app-server did not return a thread id")+ subscription = client.subscribe(thread_id)++ model = str(getattr(cfg, "model", "") or "").strip() or _V1_MODEL+ voice = (+ str(getattr(cfg, "voice", "") or "").strip().lower()+ or _V1_DEFAULT_VOICE+ )+ if model != _V1_MODEL:+ raise RuntimeError(+ "Codex subscription realtime has an unsupported V1 model configured"+ )+ if voice not in _V1_VOICES:+ raise RuntimeError(+ "Codex subscription realtime has an unsupported V1 voice configured"+ )+ start = await client.realtime_start(+ thread_id,+ output_modality="audio",+ offer_sdp=offer_sdp,+ prompt="",+ model=model,+ voice=voice,+ # Codex 0.146 deliberately ignores the configured voice for a+ # WebRTC start whose version is omitted. V1 is the current+ # supported protocol and preserves the selected voice.+ version="v1",+ include_startup_context=False,+ client_managed_handoffs=True,+ )+ answer_sdp = str(getattr(start, "answer_sdp", "") or "").strip()+ if not answer_sdp:+ raise RuntimeError("Codex app-server did not return a WebRTC answer SDP")+ if offer_lease is not None and not await offer_lease.answer(answer_sdp):+ raise RuntimeError("The UI WebRTC offer disconnected before Codex answered")+ return _CodexSubscriptionRealtimeSession(+ client=client,+ subscription=subscription,+ thread_id=thread_id,+ answer_sdp=answer_sdp,+ offer_lease=offer_lease,+ language=str(getattr(cfg, "language", "en") or "en"),+ )+ except BaseException:+ try:+ await _cleanup_remote_thread(client, thread_id)+ finally:+ try:+ if subscription is not None:+ await _close_subscription(subscription)+ finally:+ if offer_lease is not None:+ await offer_lease.release()+ raise+++__all__ = ["CodexSubscriptionRealtimeProvider"]diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.pyindex 526c31d9b6..c8f1b594ac 100644--- a/jarvis/plugins/realtime/gemini_live.py+++ b/jarvis/plugins/realtime/gemini_live.py@@ -533,6 +533,7 @@ class GeminiLiveProvider:# alias backed by the very same credential family (AP-22).credential_family = "gemini"supports_realtime = True+ implicit_usage_fallback_allowed = Trueinput_sample_rate = _INPUT_RATEoutput_sample_rate = _OUTPUT_RATEcredential_candidates = (diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex d2b0901b41..f86587823f 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -1082,6 +1082,7 @@ class OpenAIRealtimeProvider:# This is account/quota metadata, not a provider-name feature gate.credential_family = "openai"supports_realtime = True+ implicit_usage_fallback_allowed = Trueinput_sample_rate = _INPUT_RATEoutput_sample_rate = _OUTPUT_RATEcredential_candidates = (diff --git a/jarvis/realtime/factory.py b/jarvis/realtime/factory.pyindex 365b86e1e9..eda3ae4991 100644--- a/jarvis/realtime/factory.py+++ b/jarvis/realtime/factory.py@@ -2,8 +2,9 @@Realtime plugins are discovered through the ``jarvis.realtime`` entry-pointgroup. The configured provider and its explicit fallbacks are tried first,-then every other installed provider with a usable credential. No provider name-or model id controls whether the feature is available (AP-21/AP-22).+then every other installed provider with a usable credential when the selected+provider permits implicit usage fallback. No provider name or model id controls+whether the feature is available (AP-21/AP-22)."""from __future__ import annotations@@ -20,26 +21,70 @@ log = logging.getLogger(__name__)_GROUP = "jarvis.realtime"-def _configured_provider_ids(cfg: Any) -> list[str]:- tier = getattr(getattr(getattr(cfg, "brain", None), "realtime", None), "provider", None)+def _explicit_provider_ids(cfg: Any) -> list[str]:+ """Configured primary/fallback ids, without ambient installed plugins."""realtime = getattr(getattr(cfg, "brain", None), "realtime", None)- preferred = [- tier,+ installed = set(list_plugins(_GROUP))+ ordered: list[str] = []+ for configured in (+ getattr(realtime, "provider", None),getattr(realtime, "fallback_provider", None),getattr(realtime, "fallback_provider_2", None),- ]+ ):+ provider_id = str(configured or "").strip()+ if provider_id and provider_id in installed and provider_id not in ordered:+ ordered.append(provider_id)+ return ordered+++def _configured_provider_ids(cfg: Any) -> list[str]:+ preferred = _explicit_provider_ids(cfg)installed = list_plugins(_GROUP)+ allow_ambient = realtime_implicit_usage_fallback_allowed(cfg)ordered: list[str] = []- for provider_id in [*preferred, *installed]:+ provider_ids = [*preferred, *(installed if allow_ambient else [])]+ for provider_id in provider_ids:value = str(provider_id or "").strip()if value and value in installed and value not in ordered:ordered.append(value)return ordered-def _provider_candidates(cfg: Any) -> list[Any]:- """Instantiate every keyed realtime plugin in effective fallback order."""+def realtime_implicit_usage_fallback_allowed(cfg: Any) -> bool:+ """Whether the selected primary permits ambient usage-billed fallback.++ This reads a provider capability, never a provider id. An absent selection+ and successfully loaded API-backed providers retain the historical+ permissive behavior. A configured but missing/broken primary is+ fail-closed: it cannot silently spend unrelated ambient credentials.+ """+ realtime = getattr(getattr(cfg, "brain", None), "realtime", None)+ primary_id = str(getattr(realtime, "provider", "") or "").strip()+ if not primary_id:+ return True+ installed = list_plugins(_GROUP)+ if primary_id not in installed:+ return False+ try:+ provider_cls = load(_GROUP, primary_id, protocol=RealtimeProvider)+ except Exception as exc: # noqa: BLE001 - availability still degrades normally+ log.warning("Realtime primary capability probe failed for %s: %s", primary_id, exc)+ return False+ return bool(getattr(provider_cls, "implicit_usage_fallback_allowed", True))+++def _provider_candidates(+ cfg: Any, *, defer_external_login_probe: bool = False+) -> list[Any]:+ """Instantiate every credential-ready plugin in effective fallback order.++ API providers declare ``credential_candidates`` and receive the resolved+ key. Providers backed by an external application login may instead expose+ a synchronous ``external_login_ready`` capability probe and a no-argument+ constructor. The factory never infers either path from a provider name.+ """candidates: list[Any] = []+ explicit_ids = set(_explicit_provider_ids(cfg))for provider_id in _configured_provider_ids(cfg):try:provider_cls = load(_GROUP, provider_id, protocol=RealtimeProvider)@@ -48,10 +93,42 @@ def _provider_candidates(cfg: Any) -> list[Any]:credential_candidates = tuple(getattr(provider_cls, "credential_candidates", ()) or ())- api_key = get_secret_any(credential_candidates)- if not api_key:- continue- provider = provider_cls(api_key=api_key)+ api_key = (+ get_secret_any(credential_candidates)+ if credential_candidates+ else None+ )+ if api_key:+ provider = provider_cls(api_key=api_key)+ else:+ external_login_ready = getattr(+ provider_cls, "external_login_ready", None+ )+ if not callable(external_login_ready):+ continue+ if provider_id not in explicit_ids:+ continue+ # Session construction can happen on an audio/WebSocket loop.+ # The adapter's async can_open_duplex_session/open_session+ # performs the authoritative probe without blocking that loop,+ # but only for providers the user explicitly selected. An+ # ambient installed subscription must not become a candidate+ # merely because its synchronous login probe was deferred.+ if not defer_external_login_probe:+ try:+ ready = external_login_ready(cfg)+ except TypeError:+ ready = external_login_ready()+ if not bool(ready):+ continue+ from_runtime_config = getattr(+ provider_cls, "from_runtime_config", None+ )+ provider = (+ from_runtime_config(cfg)+ if callable(from_runtime_config)+ else provider_cls()+ )if not isinstance(provider, RealtimeProvider):log.warning("Realtime plugin %s does not satisfy the provider contract.",@@ -76,6 +153,29 @@ def realtime_available_provider(cfg: Any) -> str | None:return str(getattr(provider, "name", "") or "") or None+def realtime_requires_webrtc_offer(cfg: Any) -> bool:+ """Whether any eligible realtime fallback needs browser SDP signaling.++ This is an adapter capability, never a provider-id check. The offer must be+ prepared before audio starts because an API primary can fail into an+ explicitly configured subscription fallback during the same handshake.+ """+ # Browser SDP preparation is allowed only for an explicitly selected+ # primary/fallback. Installed-but-unselected external-login plugins are+ # neither a billing fallback nor a reason to negotiate WebRTC.+ for provider_id in _explicit_provider_ids(cfg):+ try:+ provider_cls = load(_GROUP, provider_id, protocol=RealtimeProvider)+ except Exception as exc: # noqa: BLE001 - one broken plugin is skipped+ log.warning("Realtime WebRTC capability probe failed for %s: %s", provider_id, exc)+ continue+ if bool(getattr(provider_cls, "supports_realtime", False)) and bool(+ getattr(provider_cls, "requires_webrtc_offer", False)+ ):+ return True+ return False++def _provider_family(provider_id: str) -> str:"""Credential/quota family of a provider id (AP-22 diagnostics only)."""pid = (provider_id or "").strip().lower()@@ -92,7 +192,12 @@ def _provider_family(provider_id: str) -> str:return aliases.get(pid, pid.split("-")[0])-def _warn_on_same_family_delegate_chain(cfg: Any, realtime_provider: str) -> None:+def _warn_on_same_family_delegate_chain(+ cfg: Any,+ realtime_provider: str,+ *,+ credential_family: str | None = None,+) -> None:"""AP-22 visibility: one quota hit must not kill realtime AND the brain.When every configured brain provider resolves to the realtime provider's@@ -103,7 +208,9 @@ def _warn_on_same_family_delegate_chain(cfg: Any, realtime_provider: str) -> Nonanother family, added in-app."""try:- realtime_family = _provider_family(realtime_provider)+ realtime_family = str(credential_family or "").strip().lower()+ if not realtime_family:+ realtime_family = _provider_family(realtime_provider)brain_cfg = getattr(cfg, "brain", None)chain = [entry@@ -131,8 +238,8 @@ def _warn_on_same_family_delegate_chain(cfg: Any, realtime_provider: str) -> Non", ".join(sorted(set(chain))),realtime_family,)- except Exception: # noqa: BLE001, S110 — diagnostics must never block the build- pass+ except Exception: # noqa: BLE001 - diagnostics must never block the build+ log.debug("Realtime credential-family diagnostics failed.", exc_info=True)def build_realtime_session(@@ -156,12 +263,17 @@ def build_realtime_session(if mode != "realtime":return Nonetry:- providers = _provider_candidates(cfg)+ providers = _provider_candidates(cfg, defer_external_login_probe=True)if not providers:log.info("Realtime voice has no credential-ready provider; using pipeline mode.")return None+ primary_provider = providers[0]_warn_on_same_family_delegate_chain(- cfg, str(getattr(providers[0], "name", "") or "")+ cfg,+ str(getattr(primary_provider, "name", "") or ""),+ credential_family=str(+ getattr(primary_provider, "credential_family", "") or ""+ ),)from jarvis.realtime.session import RealtimeVoiceSession@@ -176,6 +288,7 @@ def build_realtime_session(half_duplex=half_duplex,surface=surface,brain=brain,+ allow_classic_fallback=realtime_implicit_usage_fallback_allowed(cfg),)except Exception as exc: # noqa: BLE001 — unbuildable stack => classic pathlog.warning("Realtime session build failed: %s", exc)@@ -185,4 +298,6 @@ def build_realtime_session(__all__ = ["build_realtime_session","realtime_available_provider",+ "realtime_implicit_usage_fallback_allowed",+ "realtime_requires_webrtc_offer",]diff --git a/jarvis/realtime/offer_broker.py b/jarvis/realtime/offer_broker.pynew file mode 100644index 0000000000..7f4245ccb2--- /dev/null+++ b/jarvis/realtime/offer_broker.py@@ -0,0 +1,259 @@+"""In-process WebRTC offer handoff between UI and native voice surfaces.++Some externally authenticated realtime transports need a genuine browser SDP+offer even when the microphone owner is the native desktop voice loop. The UI+keeps a recv-only peer ready and registers its offer here; a provider leases it+exactly once and returns the answer through the same registration. No audio,+credentials, or model content passes through this broker.+"""++from __future__ import annotations++import asyncio+import time+from collections import deque+from dataclasses import dataclass+from typing import Literal++_MAX_SDP_CHARS = 256_000+_MAX_OFFER_ID_CHARS = 128+_DEFAULT_OFFER_TTL_S = 20.0+_DEFAULT_MAX_OFFERS = 32+_DEFAULT_MAX_OFFERS_PER_OWNER = 2+++def validate_webrtc_offer_sdp(offer_sdp: object) -> str:+ """Validate one browser WebRTC offer at every ingress boundary."""+ if not isinstance(offer_sdp, str):+ raise ValueError("WebRTC offer SDP must be text")+ normalized = offer_sdp.strip()+ if not normalized or len(normalized) > _MAX_SDP_CHARS:+ raise ValueError("WebRTC offer SDP is empty or too large")+ if not normalized.startswith("v=0"):+ raise ValueError("WebRTC offer SDP must be generated by RTCPeerConnection")+ return normalized+++@dataclass(frozen=True, slots=True)+class TransportOfferResult:+ """One terminal result delivered to the UI registration."""++ type: Literal["answer", "release"]+ offer_id: str+ answer_sdp: str = ""+++@dataclass(slots=True)+class _OfferEntry:+ offer_id: str+ offer_sdp: str+ created_at: float+ results: asyncio.Queue[TransportOfferResult]+ owner_id: str = "anonymous"+ claimed: bool = False+ answered: bool = False+++class TransportOfferRegistration:+ """UI-owned handle for one registered offer."""++ def __init__(self, broker: RealtimeTransportOfferBroker, entry: _OfferEntry) -> None:+ self._broker = broker+ self._entry = entry++ @property+ def offer_id(self) -> str:+ return self._entry.offer_id++ async def wait(self) -> TransportOfferResult:+ return await self._entry.results.get()++ async def cancel(self) -> None:+ await self._broker.cancel(self._entry.offer_id)+++class TransportOfferLease:+ """Provider-owned single-use lease of a genuine browser SDP offer."""++ def __init__(self, broker: RealtimeTransportOfferBroker, entry: _OfferEntry) -> None:+ self._broker = broker+ self._entry = entry++ @property+ def offer_id(self) -> str:+ return self._entry.offer_id++ @property+ def offer_sdp(self) -> str:+ return self._entry.offer_sdp++ async def answer(self, answer_sdp: str) -> bool:+ """Deliver an answer, returning false if the UI disconnected first."""+ return await self._broker.answer(self._entry.offer_id, answer_sdp)++ async def release(self) -> None:+ """Return an unusable/abandoned lease so the UI creates a fresh offer."""+ await self._broker.release(self._entry.offer_id)+++class RealtimeTransportOfferBroker:+ """Concurrency-safe one-shot offer queue shared inside the web process."""++ def __init__(+ self,+ *,+ offer_ttl_s: float = _DEFAULT_OFFER_TTL_S,+ max_offers: int = _DEFAULT_MAX_OFFERS,+ max_offers_per_owner: int = _DEFAULT_MAX_OFFERS_PER_OWNER,+ ) -> None:+ self._lock = asyncio.Lock()+ self._available = asyncio.Event()+ self._entries: dict[str, _OfferEntry] = {}+ self._pending: deque[str] = deque()+ self._offer_ttl_s = max(0.1, float(offer_ttl_s))+ self._max_offers = max(1, int(max_offers))+ self._max_offers_per_owner = max(1, int(max_offers_per_owner))++ def _sync_available_locked(self) -> None:+ if self._pending:+ self._available.set()+ else:+ self._available.clear()++ def _remove_pending_locked(self, offer_id: str) -> None:+ if offer_id in self._pending:+ self._pending = deque(+ pending_id+ for pending_id in self._pending+ if pending_id != offer_id+ )++ def _release_entry_locked(self, offer_id: str) -> None:+ entry = self._entries.pop(offer_id, None)+ self._remove_pending_locked(offer_id)+ if entry is not None and not entry.results.full():+ entry.results.put_nowait(+ TransportOfferResult(type="release", offer_id=entry.offer_id)+ )+ self._sync_available_locked()++ def _sweep_stale_locked(self, now: float) -> None:+ expired = [+ offer_id+ for offer_id, entry in self._entries.items()+ if not entry.claimed and now - entry.created_at >= self._offer_ttl_s+ ]+ for offer_id in expired:+ self._release_entry_locked(offer_id)++ async def register(+ self,+ offer_id: str,+ offer_sdp: str,+ *,+ owner_id: str = "anonymous",+ ) -> TransportOfferRegistration:+ normalized_id = str(offer_id or "").strip()+ normalized_sdp = validate_webrtc_offer_sdp(offer_sdp)+ normalized_owner = str(owner_id or "anonymous").strip() or "anonymous"+ if not normalized_id or len(normalized_id) > _MAX_OFFER_ID_CHARS:+ raise ValueError("offer_id must contain 1 to 128 characters")+ async with self._lock:+ now = time.monotonic()+ self._sweep_stale_locked(now)+ if normalized_id in self._entries:+ raise ValueError("offer_id is already registered")+ if len(self._entries) >= self._max_offers:+ raise ValueError("too many WebRTC offers are already pending")+ owner_count = sum(+ 1+ for entry in self._entries.values()+ if entry.owner_id == normalized_owner+ )+ if owner_count >= self._max_offers_per_owner:+ raise ValueError("too many WebRTC offers are pending for this client")+ entry = _OfferEntry(+ offer_id=normalized_id,+ offer_sdp=normalized_sdp,+ created_at=now,+ results=asyncio.Queue(maxsize=2),+ owner_id=normalized_owner,+ )+ self._entries[normalized_id] = entry+ self._pending.append(normalized_id)+ self._sync_available_locked()+ return TransportOfferRegistration(self, entry)++ async def acquire(self, *, timeout_s: float = 0.0) -> TransportOfferLease | None:+ """Lease the oldest live offer, optionally waiting for UI readiness."""+ timeout = max(0.0, float(timeout_s))+ deadline = asyncio.get_running_loop().time() + timeout+ while True:+ async with self._lock:+ self._sweep_stale_locked(time.monotonic())+ while self._pending:+ offer_id = self._pending.popleft()+ entry = self._entries.get(offer_id)+ if entry is None or entry.claimed:+ continue+ entry.claimed = True+ self._sync_available_locked()+ return TransportOfferLease(self, entry)+ self._sync_available_locked()++ remaining = deadline - asyncio.get_running_loop().time()+ if remaining <= 0:+ return None+ try:+ await asyncio.wait_for(self._available.wait(), timeout=remaining)+ except TimeoutError: # A bounded wait normally reports that no offer became available.+ return None++ async def answer(self, offer_id: str, answer_sdp: str) -> bool:+ normalized_sdp = str(answer_sdp or "").strip()+ if not normalized_sdp or len(normalized_sdp) > _MAX_SDP_CHARS:+ raise ValueError("WebRTC answer SDP is empty or too large")+ async with self._lock:+ entry = self._entries.get(str(offer_id))+ if entry is None or not entry.claimed or entry.answered:+ return False+ entry.answered = True+ entry.results.put_nowait(+ TransportOfferResult(+ type="answer",+ offer_id=entry.offer_id,+ answer_sdp=normalized_sdp,+ )+ )+ return True++ async def release(self, offer_id: str) -> None:+ async with self._lock:+ self._release_entry_locked(str(offer_id))++ async def cancel(self, offer_id: str) -> None:+ """Remove an offer whose owning UI socket disconnected."""+ await self.release(offer_id)++ async def pending_count(self) -> int:+ """Return live unclaimed offers for diagnostics and focused tests."""+ async with self._lock:+ return sum(1 for entry in self._entries.values() if not entry.claimed)+++_SHARED_BROKER = RealtimeTransportOfferBroker()+++def get_realtime_transport_offer_broker() -> RealtimeTransportOfferBroker:+ """Return the process-local provider/UI handoff broker."""+ return _SHARED_BROKER+++__all__ = [+ "RealtimeTransportOfferBroker",+ "TransportOfferLease",+ "TransportOfferRegistration",+ "TransportOfferResult",+ "get_realtime_transport_offer_broker",+ "validate_webrtc_offer_sdp",+]diff --git a/jarvis/realtime/protocol.py b/jarvis/realtime/protocol.pyindex 9e412c2458..da9bda0128 100644--- a/jarvis/realtime/protocol.py+++ b/jarvis/realtime/protocol.py@@ -18,6 +18,7 @@ RealtimeEventType = Literal["audio_delta","output_transcript_delta","input_transcript",+ "handoff_requested","tool_call","speech_started","interrupted",@@ -49,6 +50,10 @@ class RealtimeEvent:call_id: str | None = Nonetool_name: str | None = Nonetool_args: dict[str, Any] | None = None+ # Client-managed provider handoff metadata. A handoff is control flow for+ # the Jarvis supervisor, never a provider tool call or response boundary.+ handoff_id: str | None = None+ provider_turn_id: str | None = None@dataclass(frozen=True, slots=True)@@ -85,6 +90,11 @@ class RealtimeSessionConfig:# needs to understand follow-up turns (BUG-088). Empty at the first open# of a call. Providers that cannot inject history ignore it.history: tuple[dict[str, str], ...] = ()+ # A browser-created WebRTC offer used only by providers whose upstream+ # authentication handshake requires a browser media transport. Most+ # providers ignore it and continue to use their native WebSocket SDK.+ # The offer is deliberately transport data rather than a credential.+ transport_offer_sdp: str = ""@runtime_checkablediff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 354531fbd4..6b6d2f89f2 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -950,6 +950,7 @@ class RealtimeVoiceSession:surface: str = "browser",brain: Any = None,tool_bridge: Any = None,+ allow_classic_fallback: bool = True,) -> None:self.session_id = session_idself._send_binary = send_binary@@ -969,6 +970,11 @@ class RealtimeVoiceSession:)self._half_duplex = bool(half_duplex)self._surface = str(surface or "unknown")+ # Billing boundary advertised to browser/desktop owners. A provider+ # backed by an interactive subscription can forbid falling through to+ # unrelated ambient API credentials and the classic usage pipeline.+ self.allow_classic_fallback = bool(allow_classic_fallback)+ self._transport_offer_sdp = ""self._output_active = Falsebrain_config = getattr(self._config, "brain", None)@@ -1440,22 +1446,35 @@ class RealtimeVoiceSession:rate = int(msg.get("sample_rate", self.browser_sample_rate) or self.browser_sample_rate)if rate != self.browser_sample_rate:self.browser_sample_rate = rate+ offer_sdp = str(+ msg.get("webrtc_offer_sdp")+ or msg.get("webrtc_sdp")+ or msg.get("sdp")+ or ""+ )+ if offer_sdp:+ self._transport_offer_sdp = offer_sdpif self._session is None:await self._open()self._in_resampler = StreamingPcm16Resampler(self.browser_sample_rate, self._input_sample_rate)- await self._send_json(- {- "type": "audio_ready",- "provider": self.active_provider,- "model": self._active_model,- "input_sample_rate": self._input_sample_rate,- "output_sample_rate": int(- getattr(self._provider, "output_sample_rate", 24_000) or 24_000- ),- }- )+ ready = {+ "type": "audio_ready",+ "provider": self.active_provider,+ "model": self._active_model,+ "requires_webrtc_answer": bool(+ getattr(self._provider, "requires_webrtc_offer", False)+ ),+ "input_sample_rate": self._input_sample_rate,+ "output_sample_rate": int(+ getattr(self._provider, "output_sample_rate", 24_000) or 24_000+ ),+ }+ answer_sdp = str(getattr(self._session, "answer_sdp", "") or "")+ if answer_sdp:+ ready["webrtc_answer_sdp"] = answer_sdp+ await self._send_json(ready)if self._surface == "browser" and not self._browser_session_started:await self._publish_browser_session_started()self._browser_session_started = True@@ -1592,6 +1611,7 @@ class RealtimeVoiceSession:if self._suppress_history_seedelse self._history_seed()),+ transport_offer_sdp=self._transport_offer_sdp,)try:providers_left = sum(@@ -2336,6 +2356,63 @@ class RealtimeVoiceSession:self._response_requested_for_turn = Trueif input_item_id:self._response_requested_input_ids.add(input_item_id)+ elif event.type == "handoff_requested":+ # Client-managed handoffs are a provider control boundary,+ # never a public response boundary and never a direct tool+ # call. Keep execution inside the existing deterministic+ # Jarvis supervisor path, then render its trusted result+ # through the provider's appendText/appendSpeech boundary.+ handoff_text = _dictionary_corrected(+ str(getattr(event, "text", "") or "").strip()+ )+ if handoff_text and not self._last_user_text:+ self._last_user_text = handoff_text+ self._input_turn_observed = True+ await self._publish_transcription(+ handoff_text,+ is_final=True,+ )+ await self._ensure_turn_started()+ if not self._delegate_enabled or not self._last_user_text:+ await self._fail_terminally(+ "Realtime provider requested a supervised handoff, "+ "but no deterministic Jarvis delegate is available."+ )+ break+ self._delegate_required_for_turn = True+ self._response_requested_for_turn = True+ self._drop_provider_output_until_new_response = True+ turn_state = self._delegate_turns.setdefault(+ self._turn_id,+ _DelegateTurnState(deterministic=True),+ )+ turn_state.deterministic = True+ turn_state.wait_for_provider_boundary = True+ turn_state.input_final = True+ # The realtime model explicitly yielded control. The+ # app-server adapter interrupts any normal Codex turn that+ # core may already have started before this event arrived.+ try:+ await self._session.interrupt()+ except Exception: # noqa: BLE001 - the adapter also interrupts on receipt+ log.warning(+ "realtime[%s] provider handoff interrupt failed",+ self.session_id,+ exc_info=True,+ )+ turn_state.input_boundary_ready.set()+ turn_state.provider_boundary_seen = True+ turn_state.provider_ready.set()+ log.info(+ "realtime[%s] supervised provider handoff%s",+ self.session_id,+ (+ f" ({getattr(event, 'handoff_id', '')})"+ if getattr(event, "handoff_id", None)+ else ""+ ),+ )+ self._start_deterministic_delegate(self._last_user_text)elif event.type == "output_transcript_delta" and event.text:delegate_state = self._delegate_turns.get(self._turn_id)if (@@ -3145,18 +3222,23 @@ class RealtimeVoiceSession:# The fresh transport may resolve to a different provider, model, or# sample rates — re-announce so playback and surface labels follow.try:- await self._send_json(- {- "type": "audio_ready",- "provider": self.active_provider,- "model": self._active_model,- "input_sample_rate": self._input_sample_rate,- "output_sample_rate": int(- getattr(self._provider, "output_sample_rate", 24_000)- or 24_000- ),- }- )+ ready = {+ "type": "audio_ready",+ "provider": self.active_provider,+ "model": self._active_model,+ "requires_webrtc_answer": bool(+ getattr(self._provider, "requires_webrtc_offer", False)+ ),+ "input_sample_rate": self._input_sample_rate,+ "output_sample_rate": int(+ getattr(self._provider, "output_sample_rate", 24_000)+ or 24_000+ ),+ }+ answer_sdp = str(getattr(self._session, "answer_sdp", "") or "")+ if answer_sdp:+ ready["webrtc_answer_sdp"] = answer_sdp+ await self._send_json(ready)except Exception: # noqa: BLE001, S110 — surface refresh is best-effortpassreturn True@@ -5056,10 +5138,22 @@ class RealtimeVoiceSession:self._queue_late_delegate_result(turn_state)returnturn_state.delivery_started = True+ trusted_reply = self._scrubbed_trusted_reply(turn_state)+ if not trusted_reply:+ from jarvis.voice.action_phrases import action_phrase++ trusted_reply = action_phrase(+ "cu_done" if succeeded else "action_failed_generic",+ self._language,+ )+ # From this point onward every speech and persistence fallback must use+ # the regex-scrubbed value (ADR-0010). The raw Brain answer must never+ # reach appendSpeech, which synthesizes before our audio gate can help.+ turn_state.last_reply = trusted_reply# Belt-and-braces echo reference: the exact reply text, independent# of the provider's (possibly lagging/garbled) readback# transcription (BUG-089).- self._register_spoken_reference(str(turn_state.last_reply or ""))+ self._register_spoken_reference(trusted_reply)drop_before_delivery = self._drop_provider_output_until_new_responseself._drop_provider_output_until_new_response = Falsetry:@@ -5072,13 +5166,17 @@ class RealtimeVoiceSession:)turn_state.pending_tool_calls.clear()else:- await self._session.send_text(- _delegate_result_prompt(- turn_state.last_reply,- language=self._language,- success=succeeded,+ send_speech = getattr(self._session, "send_speech", None)+ if callable(send_speech):+ await send_speech(trusted_reply)+ else:+ await self._session.send_text(+ _delegate_result_prompt(+ trusted_reply,+ language=self._language,+ success=succeeded,+ ))- )except Exception: # noqa: BLE001 — preserve an honest surface fallbackturn_state.delivery_started = Falseself._drop_provider_output_until_new_response = drop_before_delivery@@ -5137,7 +5235,7 @@ class RealtimeVoiceSession:if time.monotonic() >= deadline:breakawait asyncio.sleep(_DELEGATE_READBACK_POLL_S)- reply = str(turn_state.last_reply or "").strip()+ reply = self._scrubbed_trusted_reply(turn_state)# One reply, one voice: the turn-complete no-audio fallback may have# spoken it already through the same surface TTS, which never touches# the realtime sample counters this loop watches (live forensicdiff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 4b92923264..97045eecea 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -7648,12 +7648,19 @@ class SpeechPipeline:echo cancellation. The browser surface provides full duplex with WebAudio echo cancellation."""+ allow_classic_fallback = Truetry:from jarvis.realtime.desktop import (DesktopRealtimeBargeInDetector,DesktopRealtimePlayback,)- from jarvis.realtime.factory import build_realtime_session+ from jarvis.realtime.factory import (+ build_realtime_session,+ realtime_implicit_usage_fallback_allowed,+ )+ allow_classic_fallback = realtime_implicit_usage_fallback_allowed(+ self._config+ )except ImportError as exc:log.warning("Realtime desktop stack is unavailable: %s", exc)return None@@ -8112,7 +8119,11 @@ class SpeechPipeline:# pipeline. Every genuine hangup path below overwrites it. The marker# keeps ``RealtimeVoiceSession.end`` from announcing a session end that# never happened — the pipeline's own teardown owns that.- reason = HANGUP_DESKTOP_FALLBACK+ reason = (+ HANGUP_DESKTOP_FALLBACK+ if allow_classic_fallback+ else HANGUP_ERROR+ )session: Any | None = Nonemicrophone_task: asyncio.Task[Any] | None = Nonetry:@@ -8249,7 +8260,17 @@ class SpeechPipeline:build_ms = (time.monotonic() - build_started_at) * 1000.0log.info("Realtime desktop session assembled in %.0f ms.", build_ms)if session is None:- return None+ if allow_classic_fallback:+ return None+ log.warning(+ "Selected realtime access is unavailable; automatic "+ "usage-billed classic fallback is disabled."+ )+ reason = HANGUP_ERROR+ return HANGUP_ERROR+ allow_classic_fallback = bool(+ getattr(session, "allow_classic_fallback", True)+ )handshake_started_at = time.monotonic()handshake_task = asyncio.create_task(session.handle_control(@@ -8336,7 +8357,14 @@ class SpeechPipeline:return HANGUP_ERROR# A startup/early provider failure has committed no semantic# user turn, so classic may safely replay the retained opening.- return None+ if allow_classic_fallback:+ return None+ reason = HANGUP_ERROR+ log.warning(+ "Realtime provider failed before a committed turn; "+ "automatic usage-billed classic fallback is disabled."+ )+ return HANGUP_ERRORexcept asyncio.CancelledError:reason = "shutdown"raise@@ -8349,7 +8377,14 @@ class SpeechPipeline:"audio replay through classic voice.")return HANGUP_ERROR- return None+ if allow_classic_fallback:+ return None+ reason = HANGUP_ERROR+ log.warning(+ "Realtime startup failed; automatic usage-billed classic "+ "fallback is disabled."+ )+ return HANGUP_ERRORfinally:if getattr(self, "_active_realtime_handle", None) is session:self._active_realtime_handle = Nonediff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 19fe04c7da..43ed7eebec 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -865,7 +865,11 @@ class DesktopApp:"""def __init__(- self, cfg: JarvisConfig | None = None, *, session_token: str | None = None+ self,+ cfg: JarvisConfig | None = None,+ *,+ session_token: str | None = None,+ realtime_transport_broker_token: str | None = None,) -> None:self.cfg = cfg or load_config()# The fast-boot launcher generates the token up front (on the main@@ -873,6 +877,13 @@ class DesktopApp:# used for both the server's TokenAuth env (below) and the window's# _inject_token. When not injected, generate our own (classic path).self.session_token = session_token or _generate_session_token()+ # Separate, process-local capability for the invisible WebRTC+ # signalling peer used by native subscription voice. Normal browser+ # sessions may legitimately hold ``session_token`` too, so that token+ # must never authorize a peer which can receive provider media.+ self.realtime_transport_broker_token = (+ realtime_transport_broker_token or _generate_session_token()+ )# The ENV must be set _before_ the backend starts: the uvicorn thread# reads it during the FastAPI app build to prime the TokenAuth guard.os.environ[self.cfg.ui.auth_token_env] = self.session_token@@ -1225,6 +1236,9 @@ class DesktopApp:# _focus_handler fetches the value dynamically.server.app.state.shell = Noneserver.app.state.desktop_app = self+ server.app.state.realtime_transport_broker_token = (+ getattr(self, "realtime_transport_broker_token", "")+ )# Local desktop run: the user IS at this machine, so reveal/open-with-# default-app target their own desktop. Enable the native file actions.server.app.state.native_file_actions = True@@ -3478,8 +3492,13 @@ class DesktopApp:single-instance lock)."""token_literal = json.dumps(self.session_token)+ broker_token_literal = json.dumps(self.realtime_transport_broker_token)js = (f"window.__JARVIS_TOKEN = {token_literal};"+ "window.__JARVIS_EMBEDDED_DESKTOP = true;"+ "Object.defineProperty(window, '__JARVIS_REALTIME_BROKER_TOKEN', {"+ f"value: {broker_token_literal}, configurable: true, writable: false"+ "});""window.dispatchEvent(new Event('jarvis-token-ready'));")try:diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsxindex aaada94f09..f362c2bb4d 100644--- a/jarvis/ui/web/frontend/src/App.tsx+++ b/jarvis/ui/web/frontend/src/App.tsx@@ -23,6 +23,7 @@ import { JarvisDock } from "@/components/JarvisDock";import { CliConnectPoller } from "@/components/CliConnectPoller";import { OnboardingGate } from "@/components/onboarding/OnboardingGate";import { installDictationFocusTracker } from "@/lib/dictationTarget";+import { SubscriptionRealtimeTransportBroker } from "@/components/voice/SubscriptionRealtimeTransportBroker";export default function App() {useWebSocket();@@ -66,6 +67,7 @@ export default function App() {return (<div className="relative flex h-screen w-screen overflow-hidden bg-background text-foreground">+ <SubscriptionRealtimeTransportBroker /><div className="pointer-events-none fixed inset-0 jarvis-grid opacity-40" aria-hidden /><divclassName="pointer-events-none fixed right-[-10%] top-[-20%] h-[600px] w-[600px] jarvis-glow"diff --git a/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.test.tsx b/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.test.tsxindex f6a8b202a9..8fd46ab3ee 100644--- a/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.test.tsx+++ b/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.test.tsx@@ -1,9 +1,30 @@-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { cleanup, render, screen } from "@testing-library/react";+const i18n = vi.hoisted(() => ({ language: "en" }));+vi.mock("@/i18n", () => ({+ useT: () => (key: string) => {+ const values: Record<string, Record<string, string>> = {+ en: {+ "provider_billing.api": "API, billed per token",+ "provider_billing.subscription": "Subscription login",+ "provider_billing.subscription_or_api": "Subscription login or API key",+ "provider_billing.local": "Local, no key needed",+ },+ de: {+ "provider_billing.subscription": "Subscription-Login",+ },+ };+ return values[i18n.language]?.[key] ?? key;+ },+}));+import { ProviderBillingBadge } from "@/components/ProviderBillingBadge";afterEach(cleanup);+beforeEach(() => {+ i18n.language = "en";+});describe("ProviderBillingBadge", () => {it("labels an API provider as pay-per-token", () => {@@ -18,11 +39,17 @@ describe("ProviderBillingBadge", () => {it("labels the dual codex path as subscription or API key", () => {render(<ProviderBillingBadge billing="subscription_or_api" />);- expect(screen.getByText(/subscription or api/i)).toBeTruthy();+ expect(screen.getByText(/subscription login or api key/i)).toBeTruthy();});it("labels a local provider", () => {render(<ProviderBillingBadge billing="local" />);expect(screen.getByText(/local/i)).toBeTruthy();});++ it("uses the active UI language instead of a hardcoded badge", () => {+ i18n.language = "de";+ render(<ProviderBillingBadge billing="subscription" />);+ expect(screen.getByText("Subscription-Login")).toBeTruthy();+ });});diff --git a/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.tsx b/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.tsxindex 2774881357..512a6d1a8b 100644--- a/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.tsx+++ b/jarvis/ui/web/frontend/src/components/ProviderBillingBadge.tsx@@ -1,5 +1,6 @@import { CreditCard, Laptop, Sparkles } from "lucide-react";import type { Billing } from "@/hooks/useProviders";+import { useT } from "@/i18n";import { cn } from "@/lib/utils";/**@@ -7,30 +8,31 @@ import { cn } from "@/lib/utils";* API-key-vs-subscription distinction they asked for. Driven by the backend's* `billing` field (derived from auth_mode), never by a provider name.*/-const META: Record<Billing, { label: string; icon: typeof CreditCard; className: string }> = {+const META: Record<Billing, { labelKey: string; icon: typeof CreditCard; className: string }> = {api: {- label: "API · billed per token",+ labelKey: "provider_billing.api",icon: CreditCard,className: "border-sky-500/30 bg-sky-500/10 text-sky-600 dark:text-sky-400",},subscription: {- label: "Subscription login",+ labelKey: "provider_billing.subscription",icon: Sparkles,className: "border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400",},subscription_or_api: {- label: "Subscription or API key",+ labelKey: "provider_billing.subscription_or_api",icon: Sparkles,className: "border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400",},local: {- label: "Local · no key needed",+ labelKey: "provider_billing.local",icon: Laptop,className: "border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",},};export function ProviderBillingBadge({ billing, className }: { billing: Billing; className?: string }) {+ const t = useT();const meta = META[billing];if (!meta) return null;const Icon = meta.icon;@@ -42,8 +44,8 @@ export function ProviderBillingBadge({ billing, className }: { billing: Billing;className,)}>- <Icon className="h-3 w-3" />- {meta.label}+ <Icon aria-hidden="true" className="h-3 w-3" />+ {t(meta.labelKey)}</span>);}diff --git a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.test.tsx b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.test.tsxindex 314e5c039d..6eed6da3ab 100644--- a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.test.tsx+++ b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.test.tsx@@ -38,6 +38,7 @@ const OPTIONS = {],current_model: "",current_voice: "",+ preview_available: true,};// jsdom implements neither media playback nor object URLs — stub the pieces@@ -262,4 +263,39 @@ describe("RealtimeOptionsControl", () => {}),);});++ it("keeps subscription voices selectable without rendering a broken preview", async () => {+ getRealtimeOptions.mockResolvedValue({+ provider: "codex-subscription-realtime",+ models: [{ id: "gpt-realtime-1.5", label: "GPT Realtime 1.5" }],+ voices: [+ { id: "cove", label: "Cove" },+ { id: "juniper", label: "Juniper" },+ ],+ current_model: "gpt-realtime-1.5",+ current_voice: "cove",+ preview_available: false,+ });+ saveRealtimeOptions.mockResolvedValue({+ ok: true,+ provider: "codex-subscription-realtime",+ model: "gpt-realtime-1.5",+ voice: "juniper",+ restart_required: false,+ });++ render(<RealtimeOptionsControl providerId="codex-subscription-realtime" />);+ await openVoicePanel();++ expect(screen.queryByLabelText("apikeys_voice.preview")).toBeNull();+ expect(screen.queryByText("de")).toBeNull();+ fireEvent.click(screen.getByText("Juniper"));+ await waitFor(() =>+ expect(saveRealtimeOptions).toHaveBeenCalledWith(+ "codex-subscription-realtime",+ { voice: "juniper" },+ ),+ );+ expect(fetchRealtimeVoicePreview).not.toHaveBeenCalled();+ });});diff --git a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsx b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsxindex 60aeb002d6..e25794859b 100644--- a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsx+++ b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsx@@ -25,10 +25,9 @@ const PROVIDER_DEFAULT = "";* than the shared search-heavy `BrainModelSelector`.** The model stays a plain `<select>` (a handful of curated entries). The- * voice is a richer expanding picker with a per-voice audio preview- * (`POST /api/providers/{id}/realtime-voice-preview`) so a voice can be- * HEARD before it is pinned — auditioning must not write config or restart a- * live realtime session; only clicking a name saves.+ * voice is a richer expanding picker. Providers with a standalone sampler+ * expose per-voice audio previews; offer-only transports remain selectable+ * without showing a preview button that cannot work.** Renders only inside a realtime provider card (`tier === "realtime"`), gated* on the card already having a stored credential — see `ApiKeysView.tsx`.@@ -47,6 +46,7 @@ export function RealtimeOptionsControl({const [voices, setVoices] = useState<RealtimeOptionInfo[]>([]);const [model, setModel] = useState<string>(PROVIDER_DEFAULT);const [voice, setVoice] = useState<string>(PROVIDER_DEFAULT);+ const [previewAvailable, setPreviewAvailable] = useState(false);const [loading, setLoading] = useState(true);const [savingField, setSavingField] = useState<"model" | "voice" | null>(null);@@ -63,6 +63,7 @@ export function RealtimeOptionsControl({setVoices(Array.isArray(r?.voices) ? r.voices : []);setModel(r?.current_model || PROVIDER_DEFAULT);setVoice(r?.current_voice || PROVIDER_DEFAULT);+ setPreviewAvailable(r?.preview_available === true);}).catch(() => {// Best-effort — the row degrades to empty dropdowns rather than@@ -141,6 +142,7 @@ export function RealtimeOptionsControl({model={model}options={voices}saving={savingField === "voice"}+ previewAvailable={previewAvailable}onChange={(next) => void handleChange("voice", next)}/></div>@@ -190,10 +192,9 @@ function RealtimeSelectRow({}/**- * Voice row: current pick + preview button, expanding into the full voice- * list where EVERY voice can be auditioned (play/stop) without saving —- * clicking a name is what saves. The sample language is switchable DE/EN/ES,- * seeded from the UI language (mirrors the TTS VoicePicker).+ * Voice row: current pick, expanding into the full selectable voice list.+ * When the backend advertises a sampler, every voice can be auditioned without+ * saving and the sample language follows the same DE/EN/ES control as TTS.*/function RealtimeVoiceRow({providerId,@@ -202,6 +203,7 @@ function RealtimeVoiceRow({model,options,saving,+ previewAvailable,onChange,}: {providerId: string;@@ -210,6 +212,7 @@ function RealtimeVoiceRow({model: string;options: RealtimeOptionInfo[];saving: boolean;+ previewAvailable: boolean;onChange: (value: string) => void;}) {const t = useT();@@ -336,7 +339,7 @@ function RealtimeVoiceRow({{/* The provider-default pick ("") resolves server-side — there is nosingle voice to honestly sample, so the trigger-row preview onlyrenders for a concrete voice. */}- {value && (+ {previewAvailable && value && (<PreviewButtonactive={previewingId === value}loading={loadingId === value}@@ -349,31 +352,33 @@ function RealtimeVoiceRow({{/* Inline-expanding voice list with per-voice audition. */}{open && (<div className="overflow-hidden rounded-md border border-border bg-popover">- <div- className="flex items-center justify-end gap-1 border-b border-border px-2.5 py-1"- role="group"- aria-label={t("apikeys_voice.preview_language")}- >- <span className="text-[10px] text-muted-foreground">- {t("apikeys_voice.preview_in")}- </span>- {(["de", "en", "es"] as const).map((lng) => (- <button- key={lng}- type="button"- onClick={() => setPreviewLang(lng)}- aria-pressed={previewLang === lng}- className={cn(- "rounded-full border px-1.5 py-0.5 text-[10px] uppercase tracking-wide transition-colors",- previewLang === lng- ? "border-primary/40 bg-primary/20 text-primary"- : "border-border bg-muted text-muted-foreground hover:text-foreground",- )}- >- {lng}- </button>- ))}- </div>+ {previewAvailable && (+ <div+ className="flex items-center justify-end gap-1 border-b border-border px-2.5 py-1"+ role="group"+ aria-label={t("apikeys_voice.preview_language")}+ >+ <span className="text-[10px] text-muted-foreground">+ {t("apikeys_voice.preview_in")}+ </span>+ {(["de", "en", "es"] as const).map((lng) => (+ <button+ key={lng}+ type="button"+ onClick={() => setPreviewLang(lng)}+ aria-pressed={previewLang === lng}+ className={cn(+ "rounded-full border px-1.5 py-0.5 text-[10px] uppercase tracking-wide transition-colors",+ previewLang === lng+ ? "border-primary/40 bg-primary/20 text-primary"+ : "border-border bg-muted text-muted-foreground hover:text-foreground",+ )}+ >+ {lng}+ </button>+ ))}+ </div>+ )}<ul className="max-h-56 overflow-y-auto p-1 scrollbar-jarvis"><li><div@@ -409,13 +414,15 @@ function RealtimeVoiceRow({isPinned && "bg-primary/20",)}>- <PreviewButton- active={previewingId === v.id}- loading={loadingId === v.id}- onClick={() => void preview(v.id)}- label={t("apikeys_voice.preview")}- className="ml-1"- />+ {previewAvailable && (+ <PreviewButton+ active={previewingId === v.id}+ loading={loadingId === v.id}+ onClick={() => void preview(v.id)}+ label={t("apikeys_voice.preview")}+ className="ml-1"+ />+ )}<buttontype="button"onClick={() => pick(v.id)}diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsxindex ade0c9c9cf..78cac31abe 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx@@ -19,6 +19,7 @@ import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/reimport { ProviderCard } from "@/components/providers/ProviderTierSection";import type { ProviderDescriptor, ProviderTestResult } from "@/hooks/useProviders";+import { useI18nStore, type UiLanguage } from "@/i18n";import { useEventStore } from "@/store/events";interface Call {@@ -92,6 +93,38 @@ function dictationCard(over: Partial<ProviderDescriptor> = {}): ProviderDescript};}+function codexRealtimeCard(+ over: Partial<ProviderDescriptor> = {},+): ProviderDescriptor {+ return {+ id: "codex-subscription-realtime",+ label: "ChatGPT subscription (Codex)",+ tier: "realtime",+ auth_mode: "codex",+ secret_keys: [],+ secrets_set: {},+ dashboard_url: null,+ login_cli: ["codex", "login"],+ install_hint: "npm i -g @openai/codex",+ credential_path_hint: null,+ configured: true,+ active: false,+ cli_installed: true,+ credential_help: "Uses the ChatGPT plan signed in through Codex.",+ signup_url: "https://chatgpt.com",+ billing: "subscription",+ experimental: true,+ alt_credential: null,+ codex_status: {+ installed: true,+ connected: true,+ mode: "chatgpt",+ message: "Connected with ChatGPT.",+ },+ ...over,+ };+}+function renderCard(descriptor: ProviderDescriptor) {return render(<ProviderCard@@ -175,6 +208,7 @@ describe("ProviderCard — dictation polish activation", () => {describe("ProviderCard — a switched-to polish provider proves it works", () => {beforeEach(() => {vi.restoreAllMocks();+ useI18nStore.getState().setUi("en", { push: false });useEventStore.setState({ toasts: [] });});@@ -270,3 +304,193 @@ describe("ProviderCard — a switched-to polish provider proves it works", () =>expect(toastsOf("warning")).toEqual([]);});});++describe("ProviderCard: ChatGPT subscription Realtime", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ useEventStore.setState({ toasts: [] });+ useI18nStore.getState().setUi("en", { push: false });+ });++ afterEach(() => cleanup());++ it("shows login setup without rendering an API key field", () => {+ installFetchMock();+ renderCard(+ codexRealtimeCard({+ configured: false,+ codex_status: {+ installed: true,+ connected: false,+ mode: "not_connected",+ message: "Sign in required.",+ },+ }),+ );++ expect(screen.getByRole("button", { name: "Connect with ChatGPT" })).toBeTruthy();+ expect(document.querySelector('input[type="password"]')).toBeNull();+ expect(+ screen.getByTestId("provider-experimental-codex-subscription-realtime"),+ ).toBeTruthy();+ expect(+ screen.getByTestId("provider-experimental-note-codex-subscription-realtime"),+ ).toBeTruthy();+ });++ it("uses the isolated subscription login instead of the normal Codex profile", async () => {+ const calls = installFetchMock();+ renderCard(+ codexRealtimeCard({+ configured: false,+ codex_status: {+ installed: true,+ connected: false,+ mode: "not_connected",+ message: "Sign in required.",+ },+ }),+ );++ fireEvent.click(screen.getByRole("button", { name: "Connect with ChatGPT" }));++ await waitFor(() =>+ expect(+ calls.some(+ (candidate) =>+ candidate.method === "POST" &&+ candidate.url === "/api/codex/subscription-voice/login",+ ),+ ).toBe(true),+ );+ });++ it("disconnects only the isolated subscription voice login", async () => {+ const calls = installFetchMock();+ renderCard(codexRealtimeCard());++ fireEvent.click(screen.getByRole("button", { name: "Disconnect" }));++ await waitFor(() =>+ expect(+ calls.some(+ (candidate) =>+ candidate.method === "POST" &&+ candidate.url === "/api/codex/subscription-voice/logout",+ ),+ ).toBe(true),+ );+ });++ it.each([+ ["de", "Über dein ChatGPT-Abo verbunden.", "Trennen"], // i18n-allow: German UI fixture.+ ["es", "Conectado mediante tu suscripción de ChatGPT.", "Desconectar"],+ ] as const)(+ "localizes the connected subscription controls in %s",+ async (language, connectedLabel, disconnectLabel) => {+ installFetchMock();+ useI18nStore.getState().setUi(language as UiLanguage, { push: false });+ renderCard(+ codexRealtimeCard({+ codex_status: {+ installed: true,+ connected: true,+ mode: "chatgpt",+ message: "Backend English must stay hidden.",+ reason_code: "ready",+ },+ }),+ );++ await waitFor(() => expect(screen.getByText(connectedLabel)).toBeTruthy());+ expect(screen.getByRole("button", { name: disconnectLabel })).toBeTruthy();+ expect(screen.queryByText("Backend English must stay hidden.")).toBeNull();+ },+ );++ it("asks for a ChatGPT subscription login without suggesting an API key", () => {+ installFetchMock();+ renderCard(+ codexRealtimeCard({+ configured: false,+ codex_status: {+ installed: true,+ connected: false,+ mode: "not_connected",+ message: "Sign in required.",+ },+ }),+ );++ fireEvent.click(screen.getByText("ChatGPT subscription (Codex)"));++ expect(toastsOf("warning")).toEqual([+ "This voice provider needs a ChatGPT subscription login. Connect with ChatGPT below.",+ ]);+ expect(toastsOf("warning")[0]).not.toContain("API key");+ });++ it.each([+ [+ "de",+ "Nutzt den über Codex verbundenen ChatGPT-Tarif. Ein API-Key ist nicht nötig.", // i18n-allow: German UI fixture.+ ],+ [+ "es",+ "Usa el plan de ChatGPT conectado mediante Codex. No necesita una clave API.",+ ],+ ] as const)(+ "uses localized setup guidance in %s instead of backend English",+ async (language, expected) => {+ installFetchMock();+ useI18nStore.getState().setUi(language as UiLanguage, { push: false });+ renderCard(+ codexRealtimeCard({+ credential_help: "Backend English credential help must stay hidden.",+ }),+ );++ await waitFor(() => expect(screen.getByText(expected)).toBeTruthy());+ expect(+ screen.queryByText("Backend English credential help must stay hidden."),+ ).toBeNull();+ },+ );++ it("activates through the Realtime switch without the Brain API-key guard", async () => {+ const calls = installFetchMock();+ vi.spyOn(window, "confirm").mockReturnValue(true);+ renderCard(codexRealtimeCard());++ fireEvent.click(screen.getByText("ChatGPT subscription (Codex)"));++ await waitFor(() => {+ const call = calls.find(+ (candidate) =>+ candidate.method === "POST" && candidate.url === "/api/realtime/switch",+ );+ expect(call).toBeTruthy();+ expect(JSON.parse(call?.body ?? "{}")).toMatchObject({+ provider: "codex-subscription-realtime",+ persist: true,+ accept_experimental: true,+ });+ });+ });++ it("does not activate until the user accepts the experimental boundary", async () => {+ const calls = installFetchMock();+ vi.spyOn(window, "confirm").mockReturnValue(false);+ renderCard(codexRealtimeCard());++ fireEvent.click(screen.getByText("ChatGPT subscription (Codex)"));++ await waitFor(() => expect(window.confirm).toHaveBeenCalledOnce());+ expect(+ calls.some(+ (candidate) =>+ candidate.method === "POST" && candidate.url === "/api/realtime/switch",+ ),+ ).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxindex 6e6f9919af..02816dc263 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx@@ -174,7 +174,7 @@ export function useTierHealth(* The Pipeline|Realtime segmented switch. Feature A (supersedes D1): clicking* a segment still switches the local view (`onSelect`), and ALSO persists* `[voice].mode` — Pipeline unconditionally (always reachable), Realtime only- * when `realtimeAvailable` (a key is present for some realtime family);+ * when `realtimeAvailable` (subscription login or API access is ready);* otherwise the click just switches the view so the user can add a key from* the Realtime tab without silently pinning the boot default to a dead* engine.@@ -186,7 +186,7 @@ export function useTierHealth(* only rolls back if the persist fails.* - The segment currently being VIEWED but not live gets a subtle outline* only (no fill) — it's a transient look, not "on".- * - Realtime with no key configured anywhere (`!realtimeAvailable`) reads+ * - Realtime with no provider access (`!realtimeAvailable`) reads* muted; it stays clickable (opens the Realtime tab so the user can add one)* but never gets the fill.* - The explanatory copy lives in `VoiceEngineContext` inside the provider@@ -202,7 +202,7 @@ export function EngineModeSwitch({mode: VoiceEngineMode;/** The live `[voice].mode` value — determines the filled/active segment. */liveMode: string;- /** Whether SOME realtime family (OpenAI/Gemini) has a key configured. */+ /** Whether some realtime provider has usable subscription or API access. */realtimeAvailable: boolean;onSelect: (mode: VoiceEngineMode) => void;/** Persists `[voice].mode` — gated per the rule above. */@@ -353,7 +353,7 @@ export function VoiceEngineContext({mode === "realtime" && !realtimeAvailable? t(statusKnown- ? "apikeys_view.mode_needs_key"+ ? "apikeys_view.mode_needs_credentials": "apikeys_view.mode_status_unknown",): mode === "realtime"@@ -709,10 +709,15 @@ export function ProviderCard({// provider + cause, so it answers "what is wrong" without a second lookup.const cardErrorDetail = health?.detail?.trim() || "";- // Codex is filtered out of the Brain tier (`brain_switchable=false`) and is- // selected from the Subagent section. This branch stays for older payloads or- // tests that still mount a Codex descriptor directly.- const isCodex = descriptor.auth_mode === "codex";+ // The legacy Codex Brain card has stricter readiness rules than other+ // Codex-auth surfaces. Subscription Realtime uses the same login widget but+ // must remain activatable without an API key.+ const isCodexAuth = descriptor.auth_mode === "codex";+ const isCodexBrain = isCodexAuth && descriptor.tier === "brain";+ const isSubscriptionLoginOnly =+ isCodexAuth &&+ descriptor.billing === "subscription" &&+ descriptor.secret_keys.length === 0;const isBrainSwitchable =descriptor.tier !== "brain" || descriptor.brain_switchable !== false;@@ -759,7 +764,7 @@ export function ProviderCard({);return;}- if (isCodex && !descriptor.codex_brain_ready) {+ if (isCodexBrain && !descriptor.codex_brain_ready) {// The card is "connected" via OAuth, but a chat brain needs an OpenAI key.// Guide honestly instead of switching and failing on the first turn.pushToast("warning", t("apikeys_codex.brain_needs_openai_key"));@@ -769,7 +774,9 @@ export function ProviderCard({pushToast("warning",descriptor.auth_mode === "codex"- ? t("apikeys_codex.needs_codex_full").replace("{0}", descriptor.label)+ ? isSubscriptionLoginOnly+ ? t("apikeys_codex.subscription_login_required")+ : t("apikeys_codex.needs_codex_full").replace("{0}", descriptor.label): descriptor.auth_mode === "antigravity"? t("apikeys_antigravity.needs_login_full").replace("{0}", descriptor.label): t("apikeys_codex.needs_key_full").replace("{0}", descriptor.label),@@ -831,7 +838,16 @@ export function ProviderCard({// cheap here (a handful of tokens) and the only honest signal.void verifyPolishProvider();} else {- const result = await switchRealtimeProvider(descriptor.id);+ if (+ descriptor.experimental &&+ !window.confirm(t("apikeys_view.experimental_subscription_consent"))+ ) {+ return;+ }+ const result = await switchRealtimeProvider(+ descriptor.id,+ descriptor.experimental === true,+ );const note = result.restart_required? " (active from next voice start)": "";@@ -861,7 +877,7 @@ export function ProviderCard({// (belt and suspenders).function handleCardActivate(e: React.MouseEvent<HTMLDivElement>) {// Codex is connection-only — a card click must never trigger a brain switch.- if (isCodex) return;+ if (isCodexBrain) return;if (!isBrainSwitchable) return;const target = e.target as HTMLElement | null;if (@@ -941,6 +957,14 @@ export function ProviderCard({{t("apikeys_view.recommended")}</span>)}+ {descriptor.experimental && (+ <span+ data-testid={`provider-experimental-${descriptor.id}`}+ className="rounded-full border border-violet-500/40 bg-violet-500/10 px-2 py-0.5 text-[10px] font-medium text-violet-600 dark:text-violet-300"+ >+ {t("apikeys_view.experimental")}+ </span>+ )}{descriptor.caution && (<spanclassName="rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-600 dark:text-amber-400"@@ -976,17 +1000,19 @@ export function ProviderCard({<ActiveControldescriptor={- isCodex+ isCodexBrain? { ...descriptor, configured: Boolean(descriptor.codex_brain_ready) }: descriptor}activating={activating}onActivate={activate}- disabled={!isBrainSwitchable || (isCodex && !descriptor.codex_brain_ready)}+ disabled={+ !isBrainSwitchable || (isCodexBrain && !descriptor.codex_brain_ready)+ }disabledReason={!isBrainSwitchable? `Available for ${agentsBrand(assistantName)} only`- : isCodex && !descriptor.codex_brain_ready+ : isCodexBrain && !descriptor.codex_brain_ready? t("apikeys_codex.brain_needs_openai_key"): undefined}@@ -1268,13 +1294,14 @@ export function ActiveControl({disabled?: boolean;disabledReason?: string;}) {+ const t = useT();const labelTitle = descriptor.active? "This provider is active": disabled? disabledReason ?? "Provider cannot be activated": descriptor.configured? "Activate this provider"- : "Set an API key first";+ : t("apikeys_view.needs_credentials");return (<label@@ -1497,9 +1524,21 @@ export function AuthWidget({onChanged: () => void;onSavedActivate?: () => void;}) {+ const t = useT();return (<div className="space-y-2"><ProviderBillingBadge billing={descriptor.billing} />+ {descriptor.experimental && (+ <div+ data-testid={`provider-experimental-note-${descriptor.id}`}+ className="rounded-md border border-violet-500/30 bg-violet-500/[0.06] px-3 py-2 text-xs leading-relaxed text-muted-foreground"+ >+ <p>{t("apikeys_view.subscription_realtime_description")}</p>+ <p className="mt-1">+ {t("apikeys_view.experimental_subscription_fallback")}+ </p>+ </div>+ )}<LocalRuntimePanel descriptor={descriptor} onChanged={onChanged} />{descriptor.supports_base_url && (<BaseUrlField descriptor={descriptor} onChanged={onChanged} />@@ -1568,12 +1607,30 @@ function CodexAuthWidget({const pushToast = useEventStore((s) => s.pushToast);const status = descriptor.codex_status;const installCommand = descriptor.install_hint ?? "npm i -g @openai/codex";+ const subscriptionOnly = descriptor.secret_keys.length === 0;+ const loginReady = Boolean(+ status?.connected && (!subscriptionOnly || status.mode === "chatgpt"),+ );+ const subscriptionStatusKey = !status+ ? "apikeys_codex.status_loading"+ : status.reason_code === "ready"+ ? "apikeys_codex.status_ready"+ : status.reason_code === "lifecycle_unavailable"+ ? "apikeys_codex.status_lifecycle_unavailable"+ : status.reason_code === "setup_invalid"+ ? "apikeys_codex.status_setup_invalid"+ : status.reason_code === "not_installed" || !status.installed+ ? "apikeys_codex.status_not_installed"+ : "apikeys_codex.status_login_required";async function handleCopy() {setPending("copy");try {const copied = await robustCopy(installCommand);- pushToast(copied ? "success" : "warning", copied ? "Install command copied" : installCommand);+ pushToast(+ copied ? "success" : "warning",+ copied ? t("apikeys_codex.install_command_copied") : installCommand,+ );} finally {setPending(null);}@@ -1582,7 +1639,7 @@ function CodexAuthWidget({async function handleLogin() {setPending("login");try {- await startCodexLogin();+ await startCodexLogin(subscriptionOnly);pushToast("info", t("apikeys_codex.login_started"));// `codex login` opens the browser OAuth flow; it only completes once the// user clicks through (seconds later). Poll a few times so the card flips@@ -1601,7 +1658,7 @@ function CodexAuthWidget({async function handleLogout() {setPending("logout");try {- await codexLogout();+ await codexLogout(subscriptionOnly);pushToast("info", t("apikeys_codex.disconnected"));onChanged();} catch (e) {@@ -1615,7 +1672,7 @@ function CodexAuthWidget({// No connect button (no second invitation), no API-key field (the key lives on// the separate "OpenAI" provider). Activation as the worker happens in the// Subagent list below.- if (status?.connected) {+ if (loginReady && status) {return (<div className="space-y-3"><div@@ -1624,7 +1681,9 @@ function CodexAuthWidget({><Check className="h-3.5 w-3.5 shrink-0 text-emerald-500" /><span className="min-w-0 break-words text-foreground">- {status.message ?? "Connected via ChatGPT."}+ {subscriptionOnly+ ? t("apikeys_codex.connected_chatgpt")+ : status.message ?? t("apikeys_codex.connected_chatgpt")}</span>{status.version && (<code className="rounded bg-muted px-1.5 py-0.5 font-mono">{status.version}</code>@@ -1638,7 +1697,7 @@ function CodexAuthWidget({className="ml-auto"><LogOut className="h-3.5 w-3.5" />- Disconnect+ {t("apikeys_codex.disconnect")}</Button></div></div>@@ -1650,7 +1709,11 @@ function CodexAuthWidget({<div className="space-y-3"><div className="rounded-md border border-border bg-background/40 p-3 text-xs text-muted-foreground"><div className="flex flex-wrap items-center gap-2">- <span>{status?.message ?? t("apikeys_codex.status_loading")}</span>+ <span>+ {subscriptionOnly+ ? t(subscriptionStatusKey)+ : status?.message ?? t("apikeys_codex.status_loading")}+ </span>{status?.version && (<code className="rounded bg-muted px-1.5 py-0.5 font-mono">{status.version}</code>)}@@ -1664,7 +1727,7 @@ function CodexAuthWidget({</code><Button size="sm" variant="outline" onClick={handleCopy} disabled={pending === "copy"}>{pending === "copy" ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}- Copy command+ {t("apikeys_codex.copy_command")}</Button></div>)}@@ -1672,12 +1735,12 @@ function CodexAuthWidget({<div className="flex flex-wrap gap-2"><Button size="sm" onClick={handleLogin} disabled={pending !== null || !status?.installed}><LogIn className="h-3.5 w-3.5" />- Connect with ChatGPT+ {t("apikeys_codex.connect_chatgpt")}</Button><Button size="sm" variant="outline" asChild><a href="https://help.openai.com/en/articles/11381614" target="_blank" rel="noreferrer"><Terminal className="h-3.5 w-3.5" />- Install Codex+ {t("apikeys_codex.install_codex")}</a></Button></div>diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsxindex 7f5f8f811a..23a6a9c8b3 100644--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx@@ -9,6 +9,7 @@ const fakes = vi.hoisted(() => ({native: false,mode: "realtime",available: true,+ requiresWebRtcOffer: false,connect: vi.fn(async () => undefined),disconnect: vi.fn(async () => undefined),supportIssue: null as@@ -20,6 +21,7 @@ const fakes = vi.hoisted(() => ({onAudio?: () => void;onStatus?: (status: string, payload: Record<string, unknown>) => void;},+ options: null as null | { requiresWebRtcOffer?: boolean },}));vi.mock("@/hooks/useCapabilities", () => ({@@ -30,6 +32,7 @@ vi.mock("@/hooks/useVoiceMode", () => ({useVoiceMode: () => ({mode: fakes.mode,realtimeAvailable: fakes.available,+ requiresWebRtcOffer: fakes.requiresWebRtcOffer,setMode: vi.fn(),isLoading: false,isSaving: false,@@ -42,8 +45,12 @@ vi.mock("@/lib/realtimeAudio", () => ({browserRealtimeSupportIssue: () => fakes.supportIssue,RealtimeAudioSupportError: class extends Error {},RealtimeAudioClient: class {- constructor(callbacks: NonNullable<typeof fakes.callbacks>) {+ constructor(+ callbacks: NonNullable<typeof fakes.callbacks>,+ options: NonNullable<typeof fakes.options>,+ ) {fakes.callbacks = callbacks;+ fakes.options = options;}connect = fakes.connect;@@ -56,10 +63,13 @@ describe("BrowserRealtimeControl", () => {fakes.native = false;fakes.mode = "realtime";fakes.available = true;+ fakes.requiresWebRtcOffer = false;fakes.connect.mockClear();fakes.disconnect.mockClear();fakes.supportIssue = null;fakes.callbacks = null;+ fakes.options = null;+ delete (window as unknown as { pywebview?: unknown }).pywebview;useEventStore.setState({voiceState: "idle",transcription: "",@@ -69,10 +79,18 @@ describe("BrowserRealtimeControl", () => {it("is hidden in the desktop shell to prevent a second microphone", () => {fakes.native = true;+ (window as unknown as { pywebview?: unknown }).pywebview = { api: {} };render(<BrowserRealtimeControl />);expect(screen.queryByRole("button")).toBeNull();});+ it("stays visible in external Chrome connected to the desktop backend", () => {+ fakes.native = true;+ render(<BrowserRealtimeControl />);++ expect(screen.getByRole("button", { name: "sidebar.realtime_start" })).toBeTruthy();+ });+it("is hidden while the classic pipeline is selected", () => {fakes.mode = "pipeline";render(<BrowserRealtimeControl />);@@ -92,6 +110,15 @@ describe("BrowserRealtimeControl", () => {).toBe("true");});+ it("requests WebRTC signalling only for a provider that declares it", async () => {+ fakes.requiresWebRtcOffer = true;+ render(<BrowserRealtimeControl />);+ fireEvent.click(screen.getByRole("button", { name: "sidebar.realtime_start" }));++ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));+ expect(fakes.options).toEqual({ requiresWebRtcOffer: true });+ });+it("returns to thinking after an interim realtime sentence", async () => {render(<BrowserRealtimeControl />);fireEvent.click(screen.getByRole("button", { name: "sidebar.realtime_start" }));@@ -104,7 +131,7 @@ describe("BrowserRealtimeControl", () => {expect(useEventStore.getState().voiceState).toBe("thinking");});- it("explains that a key is required instead of opening the microphone", () => {+ it("requires a configured Realtime provider before opening the microphone", () => {fakes.available = false;render(<BrowserRealtimeControl />);diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsxindex 1c2bde2e65..2e04fe866d 100644--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx@@ -16,6 +16,28 @@ import { cn } from "@/lib/utils";type ConnectionState = "idle" | "connecting" | "connected" | "error";+/** True only inside a pywebview host, never from the backend's machine flag.+ *+ * A normal Chrome window can connect to the same local desktop backend, where+ * `native_file_actions` is also true. Checking the client bridge keeps browser+ * microphone control visible there without enabling a second microphone in the+ * embedded desktop window.+ */+export function hasEmbeddedDesktopBridge(): boolean {+ const host = window as unknown as {+ __JARVIS_EMBEDDED_DESKTOP?: boolean;+ pywebview?: { api?: unknown };+ chrome?: { webview?: { postMessage?: unknown } };+ webkit?: { messageHandlers?: Record<string, unknown> };+ };+ return Boolean(+ host.__JARVIS_EMBEDDED_DESKTOP ||+ host.pywebview?.api ||+ typeof host.chrome?.webview?.postMessage === "function" ||+ host.webkit?.messageHandlers?.jarvisFileDrag,+ );+}+/** Map the socket state plus the shared voice state onto one visualizer look.** Kept as a pure function so the mapping is testable and lives in exactly one@@ -48,7 +70,7 @@ export function waveformPhase(export function BrowserRealtimeControl() {const t = useT();const capabilities = useCapabilities();- const { mode, realtimeAvailable } = useVoiceMode();+ const { mode, realtimeAvailable, requiresWebRtcOffer } = useVoiceMode();const setVoice = useEventStore((store) => store.setVoice);const setTranscription = useEventStore((store) => store.setTranscription);const voiceState = useEventStore((store) => store.voiceState);@@ -63,7 +85,10 @@ export function BrowserRealtimeControl() {// repaint a five-segment meter.const levelRef = useRef(0);const clientRef = useRef<RealtimeAudioClient | null>(null);- const browserSurface = capabilities.data?.native_file_actions === false;+ const browserSurface = Boolean(+ capabilities.data &&+ (capabilities.data.native_file_actions === false || !hasEmbeddedDesktopBridge()),+ );const visible = browserSurface && mode === "realtime";const supportIssue = visible ? browserRealtimeSupportIssue() : null;@@ -97,46 +122,53 @@ export function BrowserRealtimeControl() {setError("");setEffectiveProvider("");- const client = new RealtimeAudioClient({- onTranscript: (text, isFinal, role) => {- if (role === "user") setTranscription(text, isFinal);- if (role === "user" && isFinal) setVoice("thinking");- },- onAudio: () => {- setError("");- setVoice("speaking");- },- onInputLevel: (value) => {- levelRef.current = value;- },- onStatus: (status, payload) => {- if (status === "audio_ready") {- const provider = typeof payload.provider === "string" ? payload.provider : "";- if (provider) setEffectiveProvider(provider);- setState("connected");- setVoice("listening");- } else if (status === "mode_fallback") {- setEffectiveProvider(t("sidebar.realtime_pipeline_fallback"));- } else if (status === "hangup") {- // The session ended the call by voice ("auflegen" / end_call) —- // release the microphone and return to idle.- void stop();- } else if (status === "thinking") {- setVoice("thinking");- } else if (status === "turn_complete" || status === "tts_end") {- setVoice("listening");- } else if (status === "tts_cancel") {- setVoice("listening");- } else if (status === "tts_browser_unavailable" || status === "tts_browser_error") {- setError(t("sidebar.realtime_browser_tts_unavailable"));- setVoice("listening");- } else if (status === "provider_error" || status === "disconnected") {- setState("error");- setError(t("sidebar.realtime_error"));- setVoice("error");- }+ const client = new RealtimeAudioClient(+ {+ onTranscript: (text, isFinal, role) => {+ if (role === "user") setTranscription(text, isFinal);+ if (role === "user" && isFinal) setVoice("thinking");+ },+ onAudio: () => {+ setError("");+ setVoice("speaking");+ },+ onInputLevel: (value) => {+ levelRef.current = value;+ },+ onStatus: (status, payload) => {+ if (status === "audio_ready") {+ const provider =+ typeof payload.provider === "string" ? payload.provider : "";+ if (provider) setEffectiveProvider(provider);+ setState("connected");+ setVoice("listening");+ } else if (status === "mode_fallback") {+ setEffectiveProvider(t("sidebar.realtime_pipeline_fallback"));+ } else if (status === "hangup") {+ // The session ended through a voice hang-up command or end_call.+ // Release the microphone and return to idle.+ void stop();+ } else if (status === "thinking") {+ setVoice("thinking");+ } else if (status === "turn_complete" || status === "tts_end") {+ setVoice("listening");+ } else if (status === "tts_cancel") {+ setVoice("listening");+ } else if (+ status === "tts_browser_unavailable" ||+ status === "tts_browser_error"+ ) {+ setError(t("sidebar.realtime_browser_tts_unavailable"));+ setVoice("listening");+ } else if (status === "provider_error" || status === "disconnected") {+ setState("error");+ setError(t("sidebar.realtime_error"));+ setVoice("error");+ }+ },},- });+ { requiresWebRtcOffer },+ );clientRef.current = client;try {await client.connect();@@ -153,7 +185,16 @@ export function BrowserRealtimeControl() {);setVoice("error");}- }, [realtimeAvailable, setTranscription, setVoice, state, stop, supportMessage, t]);+ }, [+ realtimeAvailable,+ requiresWebRtcOffer,+ setTranscription,+ setVoice,+ state,+ stop,+ supportMessage,+ t,+ ]);useEffect(() => {if (visible) return;diff --git a/jarvis/ui/web/frontend/src/components/voice/SubscriptionRealtimeTransportBroker.test.tsx b/jarvis/ui/web/frontend/src/components/voice/SubscriptionRealtimeTransportBroker.test.tsxnew file mode 100644index 0000000000..dd8cc1764c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/voice/SubscriptionRealtimeTransportBroker.test.tsx@@ -0,0 +1,111 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, render } from "@testing-library/react";++const fakes = vi.hoisted(() => ({+ mode: "pipeline",+ realtimeAvailable: false,+ requiresWebRtcOffer: false,+ constructed: 0,+ start: vi.fn(),+ stop: vi.fn(),+}));++vi.mock("@/hooks/useVoiceMode", () => ({+ useVoiceMode: () => ({+ mode: fakes.mode,+ realtimeAvailable: fakes.realtimeAvailable,+ requiresWebRtcOffer: fakes.requiresWebRtcOffer,+ }),+}));++vi.mock("@/lib/realtimeTransportBroker", () => ({+ RealtimeTransportBroker: class {+ constructor() {+ fakes.constructed += 1;+ }++ start() {+ fakes.start();+ }++ stop() {+ fakes.stop();+ }+ },+}));++import { SubscriptionRealtimeTransportBroker } from "./SubscriptionRealtimeTransportBroker";++beforeEach(() => {+ fakes.mode = "pipeline";+ fakes.realtimeAvailable = false;+ fakes.requiresWebRtcOffer = false;+ fakes.constructed = 0;+ fakes.start.mockClear();+ fakes.stop.mockClear();+ (window as unknown as { pywebview?: unknown }).pywebview = { api: {} };+ window.__JARVIS_REALTIME_BROKER_TOKEN = "desktop-capability";+});++afterEach(() => {+ cleanup();+ delete (window as unknown as { pywebview?: unknown }).pywebview;+ delete window.__JARVIS_REALTIME_BROKER_TOKEN;+});++describe("SubscriptionRealtimeTransportBroker", () => {+ it.each([+ ["pipeline", true, true],+ ["realtime", false, true],+ ["realtime", true, false],+ ])(+ "does not start for mode %s, availability %s, offer requirement %s",+ (mode, available, requiresOffer) => {+ fakes.mode = mode;+ fakes.realtimeAvailable = available;+ fakes.requiresWebRtcOffer = requiresOffer;++ render(<SubscriptionRealtimeTransportBroker />);++ expect(fakes.constructed).toBe(0);+ expect(fakes.start).not.toHaveBeenCalled();+ },+ );++ it("runs only while subscription Realtime needs an offer", () => {+ fakes.mode = "realtime";+ fakes.realtimeAvailable = true;+ fakes.requiresWebRtcOffer = true;+ const view = render(<SubscriptionRealtimeTransportBroker />);++ expect(fakes.constructed).toBe(1);+ expect(fakes.start).toHaveBeenCalledOnce();++ fakes.requiresWebRtcOffer = false;+ view.rerender(<SubscriptionRealtimeTransportBroker />);+ expect(fakes.stop).toHaveBeenCalledOnce();+ expect(fakes.constructed).toBe(1);+ });++ it("does not expose the passive peer to a normal authenticated browser", () => {+ fakes.mode = "realtime";+ fakes.realtimeAvailable = true;+ fakes.requiresWebRtcOffer = true;+ delete (window as unknown as { pywebview?: unknown }).pywebview;++ render(<SubscriptionRealtimeTransportBroker />);++ expect(fakes.constructed).toBe(0);+ });++ it("requires the desktop-only process capability", () => {+ fakes.mode = "realtime";+ fakes.realtimeAvailable = true;+ fakes.requiresWebRtcOffer = true;+ delete window.__JARVIS_REALTIME_BROKER_TOKEN;++ render(<SubscriptionRealtimeTransportBroker />);++ expect(fakes.constructed).toBe(0);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/voice/SubscriptionRealtimeTransportBroker.tsx b/jarvis/ui/web/frontend/src/components/voice/SubscriptionRealtimeTransportBroker.tsxnew file mode 100644index 0000000000..3eddde2703--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/voice/SubscriptionRealtimeTransportBroker.tsx@@ -0,0 +1,26 @@+import { useEffect } from "react";++import { useVoiceMode } from "@/hooks/useVoiceMode";+import { RealtimeTransportBroker } from "@/lib/realtimeTransportBroker";+import { hasEmbeddedDesktopBridge } from "./BrowserRealtimeControl";++/** Authenticated, invisible WebRTC offer broker for native voice sessions. */+export function SubscriptionRealtimeTransportBroker() {+ const { mode, realtimeAvailable, requiresWebRtcOffer } = useVoiceMode();++ useEffect(() => {+ if (+ mode !== "realtime" ||+ !realtimeAvailable ||+ !requiresWebRtcOffer ||+ !hasEmbeddedDesktopBridge() ||+ !window.__JARVIS_REALTIME_BROKER_TOKEN?.trim()+ ) {+ return;+ }+ const broker = new RealtimeTransportBroker();+ broker.start();+ return () => broker.stop();+ }, [mode, realtimeAvailable, requiresWebRtcOffer]);+ return null;+}diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex ca40b27da6..029a5a4e45 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -97,6 +97,8 @@ export interface ProviderDescriptor {* without it. Absent on older payloads, which read as "required".*/optional?: boolean;+ /** Unstable provider protocol. The card shows a clear fallback notice. */+ experimental?: boolean;/*** Dictation-polish cards only: the value `[dictation].polish_provider`* actually stores ("groq"), which is NOT this card's `id` ("groq-polish") —@@ -146,6 +148,12 @@ export interface CodexStatus {connected: boolean;mode: "missing" | "not_connected" | "chatgpt" | "api_key" | "unknown";message: string;+ reason_code?:+ | "ready"+ | "login_required"+ | "lifecycle_unavailable"+ | "not_installed"+ | "setup_invalid";version?: string | null;accountLabel?: string | null;account_label?: string | null;@@ -510,8 +518,11 @@ export async function saveProviderBaseUrl(return data.base_url ?? null;}-export async function startCodexLogin(): Promise<void> {- const res = await fetch("/api/codex/login", { method: "POST" });+export async function startCodexLogin(subscriptionVoice = false): Promise<void> {+ const path = subscriptionVoice+ ? "/api/codex/subscription-voice/login"+ : "/api/codex/login";+ const res = await fetch(path, { method: "POST" });const body = await res.json().catch(() => ({}));if (!res.ok) {const detail = body.detail;@@ -523,8 +534,11 @@ export async function startCodexLogin(): Promise<void> {}}-export async function codexLogout(): Promise<void> {- const res = await fetch("/api/codex/logout", { method: "POST" });+export async function codexLogout(subscriptionVoice = false): Promise<void> {+ const path = subscriptionVoice+ ? "/api/codex/subscription-voice/logout"+ : "/api/codex/logout";+ const res = await fetch(path, { method: "POST" });const body = await res.json().catch(() => ({}));if (!res.ok) {throw new Error(body.detail ?? `HTTP ${res.status}`);@@ -748,11 +762,16 @@ export async function switchSttProvider(*/export async function switchRealtimeProvider(providerId: string,+ acceptExperimental = false,): Promise<PipelineSwitchResult> {const res = await fetch("/api/realtime/switch", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ provider: providerId, persist: true }),+ body: JSON.stringify({+ provider: providerId,+ persist: true,+ accept_experimental: acceptExperimental,+ }),});const body = await res.json().catch(() => ({}));if (!res.ok) {@@ -1175,6 +1194,7 @@ export interface RealtimeOptionsResult {voices: RealtimeOptionInfo[];current_model: string;current_voice: string;+ preview_available: boolean;}/**@@ -1232,7 +1252,8 @@ export async function saveRealtimeOptions(* POST /api/providers/{id}/realtime-voice-preview. `model` matters only where* the sampler runs through a realtime session (openai-realtime); `""` uses* the adapter default. Throws with the backend's message on any failure- * (no key / quota / transport).+ * (no key / quota / transport). Callers only render this action when the+ * realtime-options response advertises `preview_available`.*/export async function fetchRealtimeVoicePreview(opts: {providerId: string;diff --git a/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts b/jarvis/ui/web/frontend/src/hooks/useVoiceMode.tsindex 865da145e3..0467a6de3e 100644--- a/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts+++ b/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts@@ -6,6 +6,7 @@ import { useEventStore } from "@/store/events";type VoiceModeResp = {mode: string;realtime_available: boolean;+ requires_webrtc_offer: boolean;active_provider: string | null;// Sidebar-footer display fields: pretty provider name + the model an idle// realtime session would use (configured pin or catalog default).@@ -87,9 +88,10 @@ export function useVoiceMode() {return {mode: q.data?.mode ?? "pipeline",realtimeAvailable: q.data?.realtime_available ?? false,+ requiresWebRtcOffer: q.data?.requires_webrtc_offer ?? false,// Distinguishes "the server SAID no realtime key" from "we never heard// back" (timeout/loading). Without it a failed status fetch showed the- // false claim "Realtime needs an API key" and looked like a locked+ // false claim "Realtime needs provider setup" and looked like a locked// toggle on a machine that merely had a slow/broken backend moment.statusKnown: q.isSuccess,activeProvider: q.data?.active_provider ?? null,diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 71354a428d..dc0d1c1789 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -414,9 +414,15 @@"realtime_microphone_denied": "Der Mikrofonzugriff wurde verweigert. Erlaube ihn in den Website-Einstellungen des Browsers und versuche es erneut.","realtime_browser_tts_unavailable": "Dieser Browser hat keine nutzbare Systemstimme. Die Antwort bleibt als Text verfügbar; verbinde für Audio einen TTS-Anbieter.","realtime_pipeline_fallback": "Klassische Pipeline als Fallback",- "realtime_unavailable": "Realtime-API-Key einrichten",+ "realtime_unavailable": "Realtime-Anbieter verbinden oder einrichten","realtime_error": "Die Sprachverbindung konnte nicht gestartet werden. Teste den aktiven Realtime-Anbieter unter API Keys und versuche es erneut."},+ "provider_billing": {+ "api": "API, Abrechnung pro Token",+ "subscription": "Subscription-Login",+ "subscription_or_api": "Subscription-Login oder API-Key",+ "local": "Lokal, kein Key nötig"+ },"chats_view": {"title": "Chat","subtitle": "Rede mit deinem Assistenten oder schreibe — beides landet im selben Event-Bus.",@@ -1155,11 +1161,11 @@"mode_recommended": "Empfohlen","voice_engine_label": "Sprach-Engine","voice_engine_desc": "Wie {name} zuhört und spricht — die klassische Pipeline oder ein einzelnes Realtime-Modell.",- "mode_needs_key": "Realtime braucht einen API-Key — unten einen hinzufügen, dann umschalten.",+ "mode_needs_credentials": "Verbinde oder konfiguriere unten einen Realtime-Anbieter, um umzuschalten.","mode_desc_pipeline": "Drei Schritte: Sprache zu Text, das Brain denkt, Text zu Sprache.","mode_desc_realtime": "Ein Modell hört zu und antwortet im selben Live-Audiostrom.",- "mode_pick_one_hint": "Du brauchst nur für einen Modus API-Keys.",- "mode_keys_hint": "Realtime braucht einen einzigen realtime-fähigen Key; die Pipeline braucht ihre eigenen Keys für Spracheingabe, Sprachausgabe und Brain. Tool Model und {name}-Agents gelten für beide Modi.",+ "mode_pick_one_hint": "Du musst nur einen Sprachmodus einrichten.",+ "mode_keys_hint": "Realtime braucht einen aktiven Anbieter mit Subscription-Login oder API-Key. Die Pipeline braucht eigene Zugangsdaten für Spracheingabe, Sprachausgabe und Brain. Tool Model und {name}-Agents gelten für beide Modi.","mode_realtime_preview": "Research-Preview – noch nicht fertig. Viele Tools und Funktionen laufen im Realtime-Modus noch nicht.","runtime_switching": "Die aktuelle Sprach-Session wird mit der ausgewählten Engine neu gestartet…","runtime_idle": "Keine Sprach-Session ist aktiv. Die Auswahl gilt für die nächste Session.",@@ -1183,11 +1189,16 @@"needs_codex": "Erst Codex verbinden oder API-Key speichern","needs_login": "Erst mit Google anmelden, dann aktivierbar","needs_key": "Erst API-Key speichern, dann aktivierbar",+ "needs_credentials": "Verbinde oder konfiguriere zuerst diesen Anbieter","recommended": "Empfohlen","recommended_tooltip": "Empfohlenes Modell: {0}","not_recommended": "Nicht empfohlen","optional": "Optional","optional_tooltip": "Schön zu haben, aber nicht nötig. Ohne läuft alles andere genau wie vorher.",+ "experimental": "Experimentell",+ "subscription_realtime_description": "Nutzt den über Codex verbundenen ChatGPT-Tarif. Ein API-Key ist nicht nötig.",+ "experimental_subscription_fallback": "Dieser Weg nutzt das experimentelle Realtime-Protokoll von Codex. Die App wechselt nicht still zu einer nutzungsbasiert abgerechneten API. Falls die Subscription nicht startet, endet das Gespräch; für Usage-Billing wählst du einen API-Realtime-Anbieter aus.",+ "experimental_subscription_consent": "Bevor du das einschaltest: Dein Live-Audio und Transkript laufen über deinen ChatGPT-Tarif und einen experimentellen Codex-Weg. Das gilt für die Realtime-Sprachsitzung samt direkten Gesprächsantworten. Wird eine Aufgabe an einen separat konfigurierten Brain- oder Tool-Anbieter übergeben, behält dieser seine eigene Abrechnung. Nutze den Weg nur auf einem privaten, nicht verwalteten Computer. Er kann sich jederzeit ändern. Falls er ausfällt, endet das Gespräch; die App wechselt nie von selbst zu kostenpflichtiger API-Sprache. Fortfahren?","health_needs_setup": "Einrichtung nötig","health_error": "Funktioniert nicht","health_ok": "Funktioniert",@@ -1439,9 +1450,9 @@},"app_settings_group_title": "App-Einstellungen","realtime_voice": {- "title": "Echtzeit-Sprache (Browser)",- "description": "Vollduplex-Sprachdialog direkt im Browser (OpenAI). Standardmäßig aus.",- "unavailable": "Benötigt einen OpenAI-Schlüssel. Es wird die Standard-Sprachausgabe verwendet."+ "title": "Realtime-Sprache",+ "description": "Vollduplex-Sprachdialog über den ausgewählten Realtime-Anbieter. Standardmäßig aus.",+ "unavailable": "Verbinde oder konfiguriere einen Realtime-Anbieter. Die Standardsprache bleibt verfügbar."},"jarvis_api": {"title": "Control Key",@@ -1893,6 +1904,18 @@"login_started": "codex login wurde im Terminal gestartet","disconnected": "Codex wurde getrennt","status_loading": "Codex-Status wird geladen",+ "status_ready": "Dein getrenntes ChatGPT-Abo-Login für Sprache ist bereit.",+ "status_login_required": "Verbinde dein ChatGPT-Abo, um diesen Sprachanbieter zu nutzen.",+ "status_not_installed": "Installiere zuerst die unterstützte Codex-Version und verbinde danach ChatGPT.",+ "status_lifecycle_unavailable": "Subscription Voice ist auf diesem Betriebssystem noch nicht verfügbar. API Realtime und Standard-Voice funktionieren weiterhin.",+ "status_setup_invalid": "Das geschützte Codex-Sprachprofil braucht Aufmerksamkeit. Prüfe die Anleitung und verbinde es danach neu.",+ "install_command_copied": "Installationsbefehl kopiert",+ "connected_chatgpt": "Über dein ChatGPT-Abo verbunden.",+ "disconnect": "Trennen",+ "copy_command": "Befehl kopieren",+ "connect_chatgpt": "Mit ChatGPT verbinden",+ "install_codex": "Codex installieren",+ "subscription_login_required": "Dieser Sprachanbieter braucht ein ChatGPT-Subscription-Login. Verbinde dich unten mit ChatGPT.","needs_codex_full": "{0}: erst Codex verbinden oder API-Key speichern, dann aktivieren.","needs_key_full": "{0}: erst API-Key speichern, dann aktivieren.","runs_as_subagent_hint": "Mit deinem ChatGPT-Login arbeitet Codex als {name}-Agent (Hintergrund-Arbeiter). Nach dem Verbinden unten in der {name}-Agent-Liste aktivieren. Ein denkendes Hirn braucht den separaten OpenAI-API-Key-Provider.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex ef46b01143..d8c85b79c1 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -414,9 +414,15 @@"realtime_microphone_denied": "Microphone access was denied. Allow it in the browser's site settings, then retry.","realtime_browser_tts_unavailable": "This browser has no usable system voice. The answer is still available as text; connect a TTS provider for audio.","realtime_pipeline_fallback": "Classic pipeline fallback",- "realtime_unavailable": "Configure a Realtime API Key",+ "realtime_unavailable": "Connect or configure a Realtime provider","realtime_error": "Couldn’t start voice. Test the active Realtime provider under API Keys, then retry."},+ "provider_billing": {+ "api": "API, billed per token",+ "subscription": "Subscription login",+ "subscription_or_api": "Subscription login or API key",+ "local": "Local, no key needed"+ },"chats_view": {"title": "Chat","subtitle": "Talk to your assistant or type — both go through the same event bus.",@@ -1155,11 +1161,11 @@"mode_recommended": "Recommended","voice_engine_label": "Voice engine","voice_engine_desc": "How {name} listens and talks — the classic pipeline, or a single realtime model.",- "mode_needs_key": "Realtime needs an API key — add one below to switch.",+ "mode_needs_credentials": "Connect or configure a Realtime provider below to switch.","mode_desc_pipeline": "Three steps: speech-to-text, the Brain thinks, text-to-speech.","mode_desc_realtime": "One model listens and answers in the same live audio stream.",- "mode_pick_one_hint": "You only need API keys for one mode.",- "mode_keys_hint": "Realtime needs one realtime-capable key; Pipeline needs its own Voice Input, Voice Output and Brain keys. Tool Model and {name}-Agents apply to both modes.",+ "mode_pick_one_hint": "You only need to set up one voice mode.",+ "mode_keys_hint": "Realtime needs one live provider, using either a subscription login or an API key. Pipeline needs its own Voice Input, Voice Output and Brain credentials. Tool Model and {name}-Agents apply to both modes.","mode_realtime_preview": "Research preview — not finished yet. Many tools and features don't work in realtime mode.","runtime_switching": "Restarting the current voice session with the selected engine…","runtime_idle": "No voice session is active. This selection applies to the next one.",@@ -1183,11 +1189,16 @@"needs_codex": "First connect Codex or save API key, then activate","needs_login": "First sign in with Google, then activate","needs_key": "First save API key, then activate",+ "needs_credentials": "Connect or configure this provider first","recommended": "Recommended","recommended_tooltip": "Recommended model: {0}","not_recommended": "Not recommended","optional": "Optional","optional_tooltip": "Nice to have, not required. Without it everything else keeps working exactly as before.",+ "experimental": "Experimental",+ "subscription_realtime_description": "Uses the ChatGPT plan connected through Codex. No API key is needed.",+ "experimental_subscription_fallback": "This path uses Codex's experimental Realtime protocol. The app won't silently switch to metered API voice. If it cannot start, the call stops; select an API Realtime provider if you want usage billing.",+ "experimental_subscription_consent": "Before you turn this on: your live audio and transcript go through your ChatGPT plan using an experimental Codex route. That covers the realtime voice session and its direct conversational replies. If work is handed to a separately configured Brain or tool provider, that provider keeps its own billing. Use this only on a personal, unmanaged computer. The route can change without notice. If it breaks, the call stops; the app never switches to paid API voice on its own. Continue?","health_needs_setup": "Setup needed","health_error": "Not working","health_ok": "Working",@@ -1440,9 +1451,9 @@},"app_settings_group_title": "App settings","realtime_voice": {- "title": "Realtime voice (browser)",- "description": "Full-duplex speech-to-speech in the browser (OpenAI). Off by default.",- "unavailable": "Needs an OpenAI key. Using standard voice."+ "title": "Realtime voice",+ "description": "Full-duplex speech-to-speech through your selected Realtime provider. Off by default.",+ "unavailable": "Connect or configure a Realtime provider. Standard voice remains available."},"jarvis_api": {"title": "Control Key",@@ -1894,6 +1905,18 @@"login_started": "codex login started in terminal","disconnected": "Codex disconnected","status_loading": "Loading Codex status",+ "status_ready": "Your dedicated ChatGPT subscription voice login is ready.",+ "status_login_required": "Connect your ChatGPT subscription to use this voice provider.",+ "status_not_installed": "Install the supported Codex version before connecting ChatGPT.",+ "status_lifecycle_unavailable": "Subscription voice is not yet available on this operating system. API Realtime and standard voice still work.",+ "status_setup_invalid": "The protected Codex voice profile needs attention. Review the setup guide, then reconnect.",+ "install_command_copied": "Install command copied",+ "connected_chatgpt": "Connected through your ChatGPT subscription.",+ "disconnect": "Disconnect",+ "copy_command": "Copy command",+ "connect_chatgpt": "Connect with ChatGPT",+ "install_codex": "Install Codex",+ "subscription_login_required": "This voice provider needs a ChatGPT subscription login. Connect with ChatGPT below.","needs_codex_full": "{0}: first connect Codex or save API key, then activate.","needs_key_full": "{0}: first save API key, then activate.","runs_as_subagent_hint": "Codex works as a {name}-Agent (background worker) on your ChatGPT login. After connecting, activate it in the {name}-Agent list below. A thinking brain needs the separate OpenAI API-key provider.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 1401e8e6db..7cae4b331b 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -414,9 +414,15 @@"realtime_microphone_denied": "Se denegó el acceso al micrófono. Permítelo en la configuración del sitio del navegador y vuelve a intentarlo.","realtime_browser_tts_unavailable": "Este navegador no tiene una voz del sistema utilizable. La respuesta sigue disponible como texto; conecta un proveedor de TTS para oírla.","realtime_pipeline_fallback": "Sistema de voz clásico como alternativa",- "realtime_unavailable": "Configura una clave API de tiempo real",+ "realtime_unavailable": "Conecta o configura un proveedor de tiempo real","realtime_error": "No se pudo iniciar la voz. Prueba el proveedor activo en API Keys y vuelve a intentarlo."},+ "provider_billing": {+ "api": "API, facturación por token",+ "subscription": "Inicio de sesión con suscripción",+ "subscription_or_api": "Inicio de sesión con suscripción o clave API",+ "local": "Local, no necesita clave"+ },"chats_view": {"title": "Chat","subtitle": "Habla con tu asistente o escribe — ambos pasan por el mismo bus de eventos.",@@ -1155,11 +1161,11 @@"mode_recommended": "Recomendado","voice_engine_label": "Motor de voz","voice_engine_desc": "Cómo escucha y habla {name}: la pipeline clásica o un único modelo en tiempo real.",- "mode_needs_key": "Tiempo real necesita una clave API — añade una abajo para cambiar.",+ "mode_needs_credentials": "Conecta o configura un proveedor de tiempo real abajo para cambiar.","mode_desc_pipeline": "Tres pasos: voz a texto, el Brain piensa, texto a voz.","mode_desc_realtime": "Un solo modelo escucha y responde en el mismo flujo de audio en vivo.",- "mode_pick_one_hint": "Solo necesitas claves API para un modo.",- "mode_keys_hint": "Tiempo real necesita una única clave compatible; la pipeline necesita sus propias claves de Entrada de voz, Salida de voz e IA. Tool Model y {name}-Agents valen para ambos modos.",+ "mode_pick_one_hint": "Solo necesitas configurar un modo de voz.",+ "mode_keys_hint": "Tiempo real necesita un proveedor activo, con una suscripción o una clave API. La pipeline necesita sus propias credenciales de Entrada de voz, Salida de voz e IA. Tool Model y {name}-Agents valen para ambos modos.","mode_realtime_preview": "Research preview: aún sin terminar. Muchas herramientas y funciones todavía no funcionan en modo realtime.","runtime_switching": "Reiniciando la sesión de voz actual con el motor seleccionado…","runtime_idle": "No hay ninguna sesión de voz activa. Esta selección se aplicará a la siguiente.",@@ -1183,11 +1189,16 @@"needs_codex": "Primero conecta Codex o guarda la clave API","needs_login": "Primero inicia sesión con Google, luego se puede activar","needs_key": "Primero guarda la clave API, luego se puede activar",+ "needs_credentials": "Conecta o configura primero este proveedor","recommended": "Recomendado","recommended_tooltip": "Modelo recomendado: {0}","not_recommended": "No recomendado","optional": "Opcional","optional_tooltip": "Está bien tenerlo, pero no hace falta. Sin él todo lo demás sigue funcionando igual.",+ "experimental": "Experimental",+ "subscription_realtime_description": "Usa el plan de ChatGPT conectado mediante Codex. No necesita una clave API.",+ "experimental_subscription_fallback": "Esta opción usa el protocolo experimental Realtime de Codex. La aplicación no cambia en silencio a una API de pago por uso. Si la suscripción no puede iniciarse, la llamada termina; selecciona un proveedor Realtime por API si quieres facturación por uso.",+ "experimental_subscription_consent": "Antes de activarlo: el audio en directo y la transcripción pasan por tu plan de ChatGPT mediante una ruta experimental de Codex. Esto cubre la sesión de voz en tiempo real y sus respuestas conversacionales directas. Si una tarea se entrega a un proveedor de Brain o herramientas configurado por separado, ese proveedor conserva su propia facturación. Úsala solo en un ordenador personal no administrado. La ruta puede cambiar sin aviso. Si falla, la llamada termina; la aplicación nunca cambia por su cuenta a voz de API de pago. ¿Continuar?","health_needs_setup": "Falta configurar","health_error": "No funciona","health_ok": "Funciona",@@ -1439,9 +1450,9 @@},"app_settings_group_title": "Ajustes de la app","realtime_voice": {- "title": "Voz en tiempo real (navegador)",- "description": "Conversación de voz dúplex completo directamente en el navegador (OpenAI). Desactivado de forma predeterminada.",- "unavailable": "Necesita una clave de OpenAI. Se usa la voz estándar."+ "title": "Voz en tiempo real",+ "description": "Conversación de voz dúplex completo mediante el proveedor de tiempo real seleccionado. Desactivado de forma predeterminada.",+ "unavailable": "Conecta o configura un proveedor de tiempo real. La voz estándar sigue disponible."},"jarvis_api": {"title": "Clave de control",@@ -1893,6 +1904,18 @@"login_started": "inicio de sesión de codex iniciado en el terminal","disconnected": "Codex desconectado","status_loading": "Cargando estado de Codex",+ "status_ready": "Tu inicio de sesión de voz independiente con la suscripción de ChatGPT está listo.",+ "status_login_required": "Conecta tu suscripción de ChatGPT para usar este proveedor de voz.",+ "status_not_installed": "Instala la versión compatible de Codex antes de conectar ChatGPT.",+ "status_lifecycle_unavailable": "La voz por suscripción aún no está disponible en este sistema operativo. API Realtime y la voz estándar siguen funcionando.",+ "status_setup_invalid": "El perfil protegido de voz de Codex necesita atención. Revisa la guía de configuración y vuelve a conectarlo.",+ "install_command_copied": "Comando de instalación copiado",+ "connected_chatgpt": "Conectado mediante tu suscripción de ChatGPT.",+ "disconnect": "Desconectar",+ "copy_command": "Copiar comando",+ "connect_chatgpt": "Conectar con ChatGPT",+ "install_codex": "Instalar Codex",+ "subscription_login_required": "Este proveedor de voz necesita iniciar sesión con una suscripción de ChatGPT. Conecta con ChatGPT abajo.","needs_codex_full": "{0}: primero conecta Codex o guarda la clave API, luego activa.","needs_key_full": "{0}: primero guarda la clave API, luego activa.","runs_as_subagent_hint": "Con tu inicio de sesión de ChatGPT, Codex funciona como {name}-Agent (trabajador en segundo plano). Tras conectar, actívalo en la lista de {name}-Agents de abajo. Un cerebro pensante necesita el proveedor de clave API de OpenAI por separado.",diff --git a/jarvis/ui/web/frontend/src/i18n/voice-i18n-parity.test.ts b/jarvis/ui/web/frontend/src/i18n/voice-i18n-parity.test.tsindex 20474c29f3..e09fa38793 100644--- a/jarvis/ui/web/frontend/src/i18n/voice-i18n-parity.test.ts+++ b/jarvis/ui/web/frontend/src/i18n/voice-i18n-parity.test.ts@@ -110,3 +110,50 @@ describe("voice section tab labels", () => {});}});++describe("subscription Realtime voice copy", () => {+ const KEYS = [+ "sidebar.realtime_unavailable",+ "apikeys_view.mode_needs_credentials",+ "apikeys_view.needs_credentials",+ "apikeys_view.experimental",+ "apikeys_view.subscription_realtime_description",+ "apikeys_view.experimental_subscription_fallback",+ "apikeys_view.experimental_subscription_consent",+ "provider_billing.api",+ "provider_billing.subscription",+ "provider_billing.subscription_or_api",+ "provider_billing.local",+ "settings_view.realtime_voice.title",+ "settings_view.realtime_voice.description",+ "settings_view.realtime_voice.unavailable",+ "apikeys_codex.status_ready",+ "apikeys_codex.status_login_required",+ "apikeys_codex.status_not_installed",+ "apikeys_codex.status_lifecycle_unavailable",+ "apikeys_codex.status_setup_invalid",+ "apikeys_codex.install_command_copied",+ "apikeys_codex.connected_chatgpt",+ "apikeys_codex.disconnect",+ "apikeys_codex.copy_command",+ "apikeys_codex.connect_chatgpt",+ "apikeys_codex.install_codex",+ "apikeys_codex.subscription_login_required",+ ] as const;++ function valueAt(loc: Loc, path: string): unknown {+ let current: unknown = loc;+ for (const part of path.split(".")) current = (current as Loc)[part];+ return current;+ }++ for (const [lang, loc] of [["en", en], ...LOCALES] as const) {+ it(`${lang}: has complete subscription Realtime guidance`, () => {+ for (const key of KEYS) {+ const value = valueAt(loc as Loc, key);+ expect(typeof value, key).toBe("string");+ expect((value as string).trim().length, key).toBeGreaterThan(0);+ }+ });+ }+});diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.tsindex 2b390be8b7..3980d1f134 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts@@ -1,17 +1,124 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+const wsFakes = vi.hoisted(() => ({ mintWsTicket: vi.fn(async () => null) }));+vi.mock("./ws", () => ({ mintWsTicket: wsFakes.mintWsTicket }));+import {BrowserSpeechFallback,browserRealtimeSupportIssue,buildAudioSocketUrl,+ RealtimeAudioClient,StreamingPcm16Resampler,} from "./realtimeAudio";+class FakePort {+ onmessage: ((event: MessageEvent) => void) | null = null;+ postMessage = vi.fn();+}++class FakeAudioNode {+ port = new FakePort();+ connect = vi.fn(() => this);+ disconnect = vi.fn();+}++class FakeAudioContext {+ sampleRate = 48_000;+ destination = {} as AudioDestinationNode;+ audioWorklet = { addModule: vi.fn(async () => undefined) };+ resume = vi.fn(async () => undefined);+ close = vi.fn(async () => undefined);+ createMediaStreamSource = vi.fn(() => new FakeAudioNode());+ createGain = vi.fn(() => Object.assign(new FakeAudioNode(), { gain: { value: 1 } }));+}++class FakePeerConnection {+ static instances: FakePeerConnection[] = [];+ iceGatheringState: RTCIceGatheringState = "complete";+ localDescription: RTCSessionDescription | null = null;+ remoteDescriptions: RTCSessionDescriptionInit[] = [];+ addTransceiver = vi.fn();+ createDataChannel = vi.fn();+ close = vi.fn();+ addEventListener = vi.fn();+ removeEventListener = vi.fn();+ ontrack: ((event: RTCTrackEvent) => void) | null = null;++ constructor() {+ FakePeerConnection.instances.push(this);+ }++ createOffer = vi.fn(async () => ({ type: "offer" as const, sdp: "offer-sdp" }));+ setLocalDescription = vi.fn(async (description: RTCSessionDescriptionInit) => {+ this.localDescription = description as RTCSessionDescription;+ });+ setRemoteDescription = vi.fn(async (description: RTCSessionDescriptionInit) => {+ this.remoteDescriptions.push(description);+ });+}++class FakeWebSocket {+ static OPEN = 1;+ static instances: FakeWebSocket[] = [];+ readyState = 0;+ binaryType = "";+ sent: unknown[] = [];+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onclose: ((event: CloseEvent) => void) | null = null;+ onmessage: ((event: MessageEvent) => void) | null = null;++ constructor(readonly url: string) {+ FakeWebSocket.instances.push(this);+ }++ send(data: unknown) {+ this.sent.push(data);+ }++ open() {+ this.readyState = FakeWebSocket.OPEN;+ this.onopen?.();+ }++ receive(message: Record<string, unknown>) {+ this.onmessage?.({ data: JSON.stringify(message) } as MessageEvent);+ }++ receiveBinary(data: ArrayBuffer) {+ this.onmessage?.({ data } as MessageEvent);+ }++ close = vi.fn(() => {+ if (this.readyState === 3) return;+ this.readyState = 3;+ this.onclose?.({ code: 1000, reason: "" } as CloseEvent);+ });+}++function installVoiceBrowserFakes() {+ const track = { stop: vi.fn() };+ vi.stubGlobal("navigator", {+ mediaDevices: { getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })) },+ });+ vi.stubGlobal("AudioContext", FakeAudioContext);+ vi.stubGlobal("AudioWorkletNode", FakeAudioNode);+ vi.stubGlobal("RTCPeerConnection", FakePeerConnection);+ vi.stubGlobal("WebSocket", FakeWebSocket);+ return { track };+}+describe("realtime audio client", () => {beforeEach(() => {vi.stubGlobal("window", {location: { protocol: "https:", host: "app.example", hostname: "app.example" },__JARVIS_TOKEN: "tok",+ isSecureContext: true,+ setTimeout: globalThis.setTimeout,+ clearTimeout: globalThis.clearTimeout,});+ FakePeerConnection.instances = [];+ FakeWebSocket.instances = [];+ wsFakes.mintWsTicket.mockClear();});afterEach(() => vi.unstubAllGlobals());@@ -79,6 +186,215 @@ describe("realtime audio client", () => {expect([...first, ...second]).toEqual([...whole]);});+ it("sends a WebRTC offer and applies the matching answer while PCM stays active", async () => {+ const { track } = installVoiceBrowserFakes();+ const client = new RealtimeAudioClient({}, { requiresWebRtcOffer: true });+ const connecting = client.connect();++ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));+ const socket = FakeWebSocket.instances[0];+ socket.open();+ const start = JSON.parse(String(socket.sent[0])) as Record<string, unknown>;+ expect(start).toMatchObject({+ type: "audio_start",+ sample_rate: 48_000,+ webrtc_offer_sdp: "offer-sdp",+ });+ expect(FakePeerConnection.instances[0].addTransceiver).toHaveBeenCalledWith(+ "audio",+ { direction: "recvonly" },+ );+ expect(FakePeerConnection.instances[0].createDataChannel).toHaveBeenCalledWith(+ "oai-events",+ );++ socket.receive({+ type: "audio_ready",+ output_sample_rate: 24_000,+ webrtc_answer_sdp: "answer-sdp",+ });+ await connecting;+ expect(FakePeerConnection.instances[0].remoteDescriptions).toEqual([+ { type: "answer", sdp: "answer-sdp" },+ ]);++ await client.disconnect();+ expect(FakePeerConnection.instances[0].close).toHaveBeenCalledOnce();+ expect(track.stop).toHaveBeenCalledOnce();+ });++ it("keeps RTP detached and plays scrubbed subscription sideband PCM", async () => {+ const createAudio = vi.fn();+ vi.stubGlobal("Audio", createAudio);+ installVoiceBrowserFakes();+ const onAudio = vi.fn();+ const client = new RealtimeAudioClient({ onAudio }, { requiresWebRtcOffer: true });+ const connecting = client.connect();++ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));+ const socket = FakeWebSocket.instances[0];+ socket.open();+ socket.receive({+ type: "audio_ready",+ output_sample_rate: 24_000,+ webrtc_answer_sdp: "answer-sdp",+ });+ await connecting;++ expect(FakePeerConnection.instances[0].ontrack).toBeNull();+ expect(createAudio).not.toHaveBeenCalled();+ socket.receiveBinary(new Int16Array([1, 2, 3]).buffer);+ expect(onAudio).toHaveBeenCalledOnce();++ await client.disconnect();+ });++ it("gathers subscription ICE in parallel with microphone setup", async () => {+ installVoiceBrowserFakes();+ const track = { stop: vi.fn() };+ let releaseCapture: ((stream: MediaStream) => void) | undefined;+ vi.stubGlobal("navigator", {+ mediaDevices: {+ getUserMedia: vi.fn(+ () =>+ new Promise<MediaStream>((resolve) => {+ releaseCapture = resolve;+ }),+ ),+ },+ });+ const client = new RealtimeAudioClient({}, { requiresWebRtcOffer: true });+ const connecting = client.connect();++ await vi.waitFor(() => expect(FakePeerConnection.instances).toHaveLength(1));+ await vi.waitFor(() => expect(releaseCapture).toBeTypeOf("function"));+ expect(FakeWebSocket.instances).toHaveLength(0);+ releaseCapture?.({ getTracks: () => [track] } as unknown as MediaStream);+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));+ const socket = FakeWebSocket.instances[0];+ socket.open();+ socket.receive({+ type: "audio_ready",+ output_sample_rate: 24_000,+ webrtc_answer_sdp: "answer-sdp",+ });++ await connecting;+ await client.disconnect();+ });++ it("fails closed before opening a socket when subscription WebRTC is missing", async () => {+ const { track } = installVoiceBrowserFakes();+ vi.stubGlobal("RTCPeerConnection", undefined);+ const client = new RealtimeAudioClient({}, { requiresWebRtcOffer: true });++ await expect(client.connect()).rejects.toThrow(+ "Subscription Realtime requires WebRTC support",+ );+ expect(FakeWebSocket.instances).toHaveLength(0);+ expect(track.stop).toHaveBeenCalledOnce();+ });++ it("rejects subscription readiness when the provider omits its WebRTC answer", async () => {+ installVoiceBrowserFakes();+ const client = new RealtimeAudioClient({}, { requiresWebRtcOffer: true });+ const outcome = client.connect().catch((error: unknown) => error);++ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));+ const socket = FakeWebSocket.instances[0];+ socket.open();+ socket.receive({ type: "audio_ready", output_sample_rate: 24_000 });++ await expect(outcome).resolves.toMatchObject({+ message: "Subscription Realtime did not return a WebRTC answer",+ });+ expect(socket.close).toHaveBeenCalled();+ expect(FakePeerConnection.instances[0].close).toHaveBeenCalled();+ });++ it("rejects subscription readiness when the provider answer is invalid", async () => {+ installVoiceBrowserFakes();+ const client = new RealtimeAudioClient({}, { requiresWebRtcOffer: true });+ const outcome = client.connect().catch((error: unknown) => error);++ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));+ const socket = FakeWebSocket.instances[0];+ socket.open();+ FakePeerConnection.instances[0].setRemoteDescription.mockRejectedValueOnce(+ new Error("invalid SDP"),+ );+ socket.receive({+ type: "audio_ready",+ output_sample_rate: 24_000,+ webrtc_answer_sdp: "bad-answer",+ });++ await expect(outcome).resolves.toMatchObject({+ message: "Subscription Realtime returned an invalid WebRTC answer",+ });+ expect(socket.close).toHaveBeenCalled();+ expect(FakePeerConnection.instances[0].close).toHaveBeenCalled();+ });++ it("keeps an API primary active when WebRTC was prepared only for a fallback", async () => {+ installVoiceBrowserFakes();+ const client = new RealtimeAudioClient({}, { requiresWebRtcOffer: true });+ const connecting = client.connect();++ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));+ const socket = FakeWebSocket.instances[0];+ socket.open();+ expect(JSON.parse(String(socket.sent[0])).webrtc_offer_sdp).toBe("offer-sdp");+ socket.receive({+ type: "audio_ready",+ provider: "api-primary",+ output_sample_rate: 24_000,+ requires_webrtc_answer: false,+ });++ await connecting;+ expect(FakePeerConnection.instances[0].remoteDescriptions).toEqual([]);+ expect(FakePeerConnection.instances[0].close).toHaveBeenCalledOnce();+ await client.disconnect();+ });++ it("adds no WebRTC handshake work for API Realtime providers", async () => {+ installVoiceBrowserFakes();+ const client = new RealtimeAudioClient();+ const connecting = client.connect();++ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));+ expect(FakePeerConnection.instances).toHaveLength(0);+ const socket = FakeWebSocket.instances[0];+ socket.open();+ expect(JSON.parse(String(socket.sent[0])).webrtc_offer_sdp).toBeUndefined();+ socket.receive({ type: "audio_ready", output_sample_rate: 24_000 });+ await connecting;+ await client.disconnect();+ });++ it("keeps API-backed PCM voice available when an unsolicited answer is invalid", async () => {+ installVoiceBrowserFakes();+ const statuses: string[] = [];+ const client = new RealtimeAudioClient({+ onStatus: (status) => statuses.push(status),+ });+ const connecting = client.connect();++ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));+ const socket = FakeWebSocket.instances[0];+ socket.open();+ socket.receive({+ type: "audio_ready",+ output_sample_rate: 24_000,+ webrtc_answer_sdp: "unsolicited-answer",+ });++ await connecting;+ expect(statuses).toContain("webrtc_transport_unavailable");+ await client.disconnect();+ });+it("speaks a server-approved fallback with language and volume", () => {const utterances: SpeechSynthesisUtterance[] = [];const synthesis = {diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.tsindex 00f1e34d88..f53d31b4b4 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts@@ -22,6 +22,11 @@ export type RealtimeCallbacks = {onInputLevel?: (level: number) => void;};+export type RealtimeAudioOptions = {+ /** The active provider needs a WebRTC offer to open its subscription transport. */+ requiresWebRtcOffer?: boolean;+};+export type BrowserSpeechOutcome = "ended" | "error" | "unavailable";export type BrowserRealtimeSupportIssue =@@ -29,6 +34,66 @@ export type BrowserRealtimeSupportIssue =| "microphone_unavailable"| "audio_worklet_unavailable";+const ICE_GATHER_TIMEOUT_MS = 1_500;++/** One offer-only WebRTC transport for Codex subscription signalling.+ *+ * Audio capture and playback stay on Jarvis's PCM WebSocket. The peer exists+ * only to establish the provider transport: it receives no microphone track,+ * and its remote RTP track is deliberately not attached to an output element.+ * Codex mirrors output through `thread/realtime/outputAudio/delta`, allowing the+ * existing transcript scrub gate to approve PCM before it reaches speakers.+ */+export class RealtimeWebRtcTransport {+ private peer: RTCPeerConnection | null = null;++ async createOffer(): Promise<string | null> {+ this.close();+ if (typeof RTCPeerConnection !== "function") return null;++ const peer = new RTCPeerConnection();+ this.peer = peer;+ peer.addTransceiver("audio", { direction: "recvonly" });+ peer.createDataChannel("oai-events");+ const offer = await peer.createOffer();+ await peer.setLocalDescription(offer);+ await waitForIceGathering(peer);+ if (this.peer !== peer) return null;+ const sdp = peer.localDescription?.sdp ?? offer.sdp ?? "";+ return sdp.trim() || null;+ }++ async applyAnswer(sdp: string): Promise<void> {+ if (!this.peer) throw new Error("WebRTC answer arrived without an active offer");+ await this.peer.setRemoteDescription({ type: "answer", sdp });+ }++ close(): void {+ const peer = this.peer;+ this.peer = null;+ peer?.close();+ }+}++async function waitForIceGathering(peer: RTCPeerConnection): Promise<void> {+ if (peer.iceGatheringState === "complete") return;+ await new Promise<void>((resolve) => {+ let settled = false;+ const finish = () => {+ if (settled) return;+ settled = true;+ globalThis.clearTimeout(timeout);+ peer.removeEventListener("icegatheringstatechange", onChange);+ resolve();+ };+ const onChange = () => {+ if (peer.iceGatheringState === "complete") finish();+ };+ const timeout = globalThis.setTimeout(finish, ICE_GATHER_TIMEOUT_MS);+ peer.addEventListener("icegatheringstatechange", onChange);+ });+}+export class RealtimeAudioSupportError extends Error {constructor(readonly issue: BrowserRealtimeSupportIssue) {super(`Browser Realtime Voice is unavailable: ${issue}`);@@ -209,8 +274,15 @@ export class RealtimeAudioClient {private intentionalClose = false;private inputMeter = new LevelMeter();private browserSpeech = new BrowserSpeechFallback();+ private webRtcTransport: RealtimeWebRtcTransport;+ private webRtcOfferSdp: string | null = null;- constructor(private cb: RealtimeCallbacks = {}) {}+ constructor(+ private cb: RealtimeCallbacks = {},+ private options: RealtimeAudioOptions = {},+ ) {+ this.webRtcTransport = new RealtimeWebRtcTransport();+ }connect(): Promise<void> {if (this.ready) return Promise.resolve();@@ -226,6 +298,19 @@ export class RealtimeAudioClient {try {const supportIssue = browserRealtimeSupportIssue();if (supportIssue) throw new RealtimeAudioSupportError(supportIssue);+ // Start ICE gathering before microphone/worklet setup. This hides nearly+ // all subscription signalling latency behind work the call already has+ // to do, including when subscription voice is an explicit fallback for+ // an API-first provider chain. Capture and scrubbed playback remain PCM.+ const webRtcOffer: Promise<{+ sdp: string | null;+ error: unknown | null;+ }> | null = this.options.requiresWebRtcOffer+ ? this.webRtcTransport.createOffer().then(+ (sdp) => ({ sdp, error: null }),+ (error: unknown) => ({ sdp: null, error }),+ )+ : null;this.ctx = new AudioContext({ latencyHint: "interactive" });if (!this.ctx.audioWorklet) {throw new RealtimeAudioSupportError("audio_worklet_unavailable");@@ -254,6 +339,26 @@ export class RealtimeAudioClient {this.captureSink.connect(this.ctx.destination);this.playbackNode.connect(this.ctx.destination);+ // Required transport bootstrap for subscription-backed Realtime. API+ // providers do not set this option and continue to use the PCM socket+ // alone. A subscription session cannot be opened or billed correctly+ // without its WebRTC peer, so this path fails closed.+ if (this.options.requiresWebRtcOffer) {+ const result = await webRtcOffer;+ if (result?.error) {+ this.webRtcTransport.close();+ this.webRtcOfferSdp = null;+ throw new Error("Subscription Realtime WebRTC signalling is unavailable", {+ cause: result.error,+ });+ }+ this.webRtcOfferSdp = result?.sdp ?? null;+ if (!this.webRtcOfferSdp) {+ this.webRtcTransport.close();+ throw new Error("Subscription Realtime requires WebRTC support");+ }+ }+// Proactive one-time ticket: WebKit engines do not attach the HttpOnly// session cookie to a WS handshake (BUG-065). Minting over plain HTTP// first works on every engine; on a mint failure (e.g. older backend)@@ -300,7 +405,13 @@ export class RealtimeAudioClient {socket.onopen = () => {socket.send(- JSON.stringify({ type: "audio_start", sample_rate: this.ctx?.sampleRate ?? 48_000 }),+ JSON.stringify({+ type: "audio_start",+ sample_rate: this.ctx?.sampleRate ?? 48_000,+ ...(this.webRtcOfferSdp+ ? { webrtc_offer_sdp: this.webRtcOfferSdp }+ : {}),+ }),);};socket.onerror = () => fail(new Error("Realtime voice socket failed"));@@ -335,12 +446,24 @@ export class RealtimeAudioClient {this.playbackNode?.port.postMessage({ type: "flush" });} else if (type === "audio_ready") {this.setOutputRate(message.output_sample_rate);- this.ready = true;- if (!settled) {- settled = true;- window.clearTimeout(timeout);- resolve();- }+ void this.finishAudioReady(message)+ .then(() => {+ this.ready = true;+ if (!settled) {+ settled = true;+ window.clearTimeout(timeout);+ resolve();+ }+ this.cb.onStatus?.(type, message);+ })+ .catch((error: unknown) => {+ const failure =+ error instanceof Error ? error : new Error(String(error));+ this.ready = false;+ fail(failure);+ socket.close();+ });+ return;} else if (type === "tts_start") {this.browserSpeech.cancel();this.setOutputRate(message.sample_rate);@@ -354,6 +477,37 @@ export class RealtimeAudioClient {});}+ private async finishAudioReady(message: RealtimeStatusPayload): Promise<void> {+ const answer = message.webrtc_answer_sdp;+ const answerRequired =+ message.requires_webrtc_answer === true ||+ (message.requires_webrtc_answer === undefined &&+ this.options.requiresWebRtcOffer === true);+ if (typeof answer !== "string" || !answer.trim()) {+ this.webRtcTransport.close();+ if (answerRequired) {+ throw new Error("Subscription Realtime did not return a WebRTC answer");+ }+ return;+ }+ try {+ await this.webRtcTransport.applyAnswer(answer);+ } catch (error) {+ this.webRtcTransport.close();+ if (answerRequired) {+ throw new Error("Subscription Realtime returned an invalid WebRTC answer", {+ cause: error,+ });+ }+ // PCM remains authoritative. A broken or unsupported WebRTC answer must+ // not take API-backed browser voice down with it.+ console.warn("WebRTC answer could not be applied; continuing with PCM voice.", error);+ this.cb.onStatus?.("webrtc_transport_unavailable", {+ type: "webrtc_transport_unavailable",+ });+ }+ }+private setOutputRate(value: unknown): void {const providerRate = typeof value === "number" && value > 0 ? value : 24_000;const contextRate = this.ctx?.sampleRate ?? 48_000;@@ -361,6 +515,9 @@ export class RealtimeAudioClient {}private handleAudio(pcm: ArrayBuffer): void {+ // This is authoritative for both API and subscription providers. The+ // subscription WebRTC peer intentionally does not play remote RTP; Codex's+ // documented sideband PCM therefore keeps Jarvis's scrub gate in the path.this.browserSpeech.cancel();if (!this.playbackResampler) this.setOutputRate(24_000);const converted = this.playbackResampler?.process(pcm) ?? pcm;@@ -422,6 +579,8 @@ export class RealtimeAudioClient {this.captureSink = null;this.playbackNode = null;this.playbackResampler = null;+ this.webRtcTransport.close();+ this.webRtcOfferSdp = null;this.stream = null;this.ctx = null;this.inputMeter.reset();diff --git a/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.test.ts b/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.test.tsnew file mode 100644index 0000000000..7b2b60111a--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.test.ts@@ -0,0 +1,131 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ buildRealtimeTransportSocketUrl,+ RealtimeTransportBroker,+} from "./realtimeTransportBroker";++class FakeTransport {+ answers: string[] = [];+ close = vi.fn();++ constructor(readonly offer: string) {}++ createOffer = vi.fn(async () => this.offer);+ applyAnswer = vi.fn(async (answer: string) => {+ this.answers.push(answer);+ });++}++class FakeSocket {+ readyState = 0;+ sent: string[] = [];+ onopen: (() => void) | null = null;+ onmessage: ((event: MessageEvent) => void) | null = null;+ onerror: (() => void) | null = null;+ onclose: (() => void) | null = null;+ close = vi.fn(() => {+ if (this.readyState === 3) return;+ this.readyState = 3;+ this.onclose?.();+ });++ constructor(readonly url: string) {}++ open() {+ this.readyState = 1;+ this.onopen?.();+ }++ send(data: string) {+ this.sent.push(data);+ }++ receive(message: Record<string, unknown>) {+ this.onmessage?.({ data: JSON.stringify(message) } as MessageEvent);+ }+}++afterEach(() => vi.unstubAllGlobals());++describe("realtime transport broker", () => {+ it("builds the authenticated socket URL without exposing a session token", () => {+ vi.stubGlobal("window", {+ location: { protocol: "https:", host: "app.example" },+ });+ expect(buildRealtimeTransportSocketUrl("single-use")).toBe(+ "wss://app.example/ws/realtime-transport?ticket=single-use",+ );+ });++ it("keeps an answered peer alive, then publishes a fresh offer after release", async () => {+ vi.stubGlobal("window", {+ location: { protocol: "https:", host: "app.example" },+ });+ const sockets: FakeSocket[] = [];+ const transports: FakeTransport[] = [];+ let nextOffer = 0;+ let nextId = 0;+ const broker = new RealtimeTransportBroker({+ mintTicket: vi.fn(async () => "ticket-1"),+ readDesktopCapability: () => "desktop-only",+ createSocket: (url) => {+ const socket = new FakeSocket(url);+ sockets.push(socket);+ return socket as unknown as WebSocket;+ },+ createTransport: () => {+ const transport = new FakeTransport(`offer-sdp-${++nextOffer}`);+ transports.push(transport);+ return transport;+ },+ createOfferId: () => `offer-${++nextId}`,+ });++ broker.start();+ await vi.waitFor(() => expect(sockets).toHaveLength(1));+ const socket = sockets[0];+ socket.open();+ await vi.waitFor(() => expect(socket.sent).toHaveLength(2));+ expect(JSON.parse(socket.sent[0])).toEqual({+ type: "authenticate",+ desktop_capability: "desktop-only",+ });+ expect(JSON.parse(socket.sent[1])).toEqual({+ type: "offer",+ offer_id: "offer-1",+ webrtc_offer_sdp: "offer-sdp-1",+ });++ socket.receive({+ type: "answer",+ offer_id: "offer-1",+ webrtc_answer_sdp: "answer-sdp-1",+ });+ await vi.waitFor(() => expect(transports[0].answers).toEqual(["answer-sdp-1"]));+ expect(transports[0].close).not.toHaveBeenCalled();++ socket.receive({ type: "release", offer_id: "offer-1" });+ await vi.waitFor(() => expect(socket.sent).toHaveLength(3));+ expect(transports[0].close).toHaveBeenCalledOnce();+ expect(transports).toHaveLength(2);+ expect(JSON.parse(socket.sent[2])).toEqual({+ type: "offer",+ offer_id: "offer-2",+ webrtc_offer_sdp: "offer-sdp-2",+ });++ socket.receive({+ type: "answer",+ offer_id: "offer-2",+ webrtc_answer_sdp: "answer-sdp-2",+ });+ await vi.waitFor(() => expect(transports[1].answers).toEqual(["answer-sdp-2"]));+ expect(transports[1].close).not.toHaveBeenCalled();++ broker.stop();+ expect(transports[1].close).toHaveBeenCalledOnce();+ expect(socket.close).toHaveBeenCalledOnce();+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.ts b/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.tsnew file mode 100644index 0000000000..e322918a19--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.ts@@ -0,0 +1,203 @@+import { RealtimeWebRtcTransport } from "./realtimeAudio";+import { mintWsTicket } from "./ws";++declare global {+ interface Window {+ __JARVIS_REALTIME_BROKER_TOKEN?: string;+ }+}++const RECONNECT_DELAY_MS = 1_500;+const WS_OPEN = 1;++type OfferTransport = Pick<+ RealtimeWebRtcTransport,+ "createOffer" | "applyAnswer" | "close"+>;++type BrokerDeps = {+ createTransport: () => OfferTransport;+ createSocket: (url: string) => WebSocket;+ mintTicket: () => Promise<string | null>;+ readDesktopCapability: () => string;+ createOfferId: () => string;+ schedule: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;+ cancelSchedule: (timer: ReturnType<typeof setTimeout>) => void;+};++function defaultOfferId(): string {+ if (typeof globalThis.crypto?.randomUUID === "function") {+ return globalThis.crypto.randomUUID();+ }+ return `rtc-${Date.now()}-${Math.random().toString(36).slice(2)}`;+}++export function buildRealtimeTransportSocketUrl(ticket?: string | null): string {+ const protocol = window.location.protocol === "https:" ? "wss" : "ws";+ const base = `${protocol}://${window.location.host}/ws/realtime-transport`;+ return ticket ? `${base}?ticket=${encodeURIComponent(ticket)}` : base;+}++const DEFAULT_DEPS: BrokerDeps = {+ createTransport: () => new RealtimeWebRtcTransport(),+ createSocket: (url) => new WebSocket(url),+ mintTicket: mintWsTicket,+ readDesktopCapability: () =>+ window.__JARVIS_REALTIME_BROKER_TOKEN?.trim() ?? "",+ createOfferId: defaultOfferId,+ schedule: (callback, delayMs) => globalThis.setTimeout(callback, delayMs),+ cancelSchedule: (timer) => globalThis.clearTimeout(timer),+};++/** Keeps one offer registered for native subscription voice sessions.+ *+ * The broker runs only in the embedded desktop WebView after UI+ * authentication. It does not request a microphone or play the provider's RTP+ * media; Codex's sideband PCM remains authoritative so Jarvis can scrub it+ * before playback. A native voice session consumes the registered offer, then+ * releases it so the broker can publish a fresh one on the same socket.+ */+export class RealtimeTransportBroker {+ private readonly deps: BrokerDeps;+ private socket: WebSocket | null = null;+ private transport: OfferTransport | null = null;+ private offerId: string | null = null;+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;+ private stopped = true;+ private generation = 0;++ constructor(deps: Partial<BrokerDeps> = {}) {+ this.deps = { ...DEFAULT_DEPS, ...deps };+ }++ start(): void {+ if (!this.stopped) return;+ this.stopped = false;+ void this.connect();+ }++ stop(): void {+ this.stopped = true;+ this.generation += 1;+ if (this.reconnectTimer !== null) {+ this.deps.cancelSchedule(this.reconnectTimer);+ this.reconnectTimer = null;+ }+ this.releaseTransport();+ const socket = this.socket;+ this.socket = null;+ socket?.close();+ }++ private async connect(): Promise<void> {+ const generation = ++this.generation;+ try {+ const desktopCapability = this.deps.readDesktopCapability();+ if (!desktopCapability) return;+ const ticket = await this.deps.mintTicket();+ if (this.stopped || generation !== this.generation) return;+ const socket = this.deps.createSocket(buildRealtimeTransportSocketUrl(ticket));+ this.socket = socket;+ socket.onopen = () => {+ if (this.stopped || this.socket !== socket) return;+ // The normal UI session is deliberately insufficient here. Only the+ // embedded desktop WebView receives this separate process capability.+ socket.send(+ JSON.stringify({+ type: "authenticate",+ desktop_capability: desktopCapability,+ }),+ );+ void this.publishOffer(socket);+ };+ socket.onmessage = (event) => this.handleMessage(socket, event);+ socket.onerror = () => socket.close();+ socket.onclose = () => {+ if (this.socket !== socket) return;+ this.socket = null;+ this.releaseTransport();+ this.scheduleReconnect();+ };+ } catch (error) {+ console.info("Realtime transport broker could not connect.", error);+ this.scheduleReconnect();+ }+ }++ private async publishOffer(socket: WebSocket): Promise<void> {+ const generation = ++this.generation;+ this.releaseTransport();+ const transport = this.deps.createTransport();+ this.transport = transport;+ try {+ const sdp = await transport.createOffer();+ if (+ !sdp ||+ this.stopped ||+ this.socket !== socket ||+ generation !== this.generation ||+ socket.readyState !== WS_OPEN+ ) {+ if (!sdp) {+ console.info("This browser cannot broker a WebRTC subscription transport.");+ }+ if (this.transport === transport) this.releaseTransport();+ return;+ }+ const offerId = this.deps.createOfferId();+ this.offerId = offerId;+ socket.send(+ JSON.stringify({+ type: "offer",+ offer_id: offerId,+ webrtc_offer_sdp: sdp,+ }),+ );+ } catch (error) {+ console.info("Realtime transport broker could not create an offer.", error);+ if (this.transport === transport) this.releaseTransport();+ socket.close();+ }+ }++ private handleMessage(socket: WebSocket, event: MessageEvent): void {+ if (typeof event.data !== "string") return;+ let message: Record<string, unknown>;+ try {+ message = JSON.parse(event.data) as Record<string, unknown>;+ } catch {+ // A malformed control frame cannot identify an offer and is safe to ignore.+ return;+ }+ if (message.offer_id !== this.offerId) return;+ if (message.type === "release") {+ void this.publishOffer(socket);+ return;+ }+ const answer = message.webrtc_answer_sdp;+ if (message.type !== "answer" || typeof answer !== "string" || !answer.trim()) {+ return;+ }+ const transport = this.transport;+ if (!transport) return;+ void transport.applyAnswer(answer).catch((error) => {+ console.warn("Realtime transport broker rejected the provider answer.", error);+ socket.close();+ });+ }++ private releaseTransport(): void {+ this.offerId = null;+ const transport = this.transport;+ this.transport = null;+ transport?.close();+ }++ private scheduleReconnect(): void {+ if (this.stopped || this.reconnectTimer !== null) return;+ this.reconnectTimer = this.deps.schedule(() => {+ this.reconnectTimer = null;+ void this.connect();+ }, RECONNECT_DELAY_MS);+ }+}diff --git a/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.test.tsx b/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.test.tsxindex 13c10e581d..2b55ee5df8 100644--- a/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.test.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.test.tsx@@ -34,7 +34,7 @@ afterEach(() => {});describe("RealtimeVoiceGroup", () => {- it("blocks enabling Realtime when no provider key is available", () => {+ it("blocks enabling Realtime when no provider access is available", () => {render(<RealtimeVoiceGroup />);expect((screen.getByRole("switch") as HTMLButtonElement).disabled).toBe(true);diff --git a/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsxindex 0572a69f34..066742c638 100644--- a/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx@@ -7,7 +7,7 @@ import { useT } from "@/i18n";/*** Provider-neutral Realtime voice toggle inside the Settings view. It flips* ``mode`` between the classic wake-word/STT/TTS pipeline and full-duplex- * Realtime voice. A missing Realtime key blocks turning the mode on, but never+ * Realtime voice. Missing provider access blocks turning the mode on, but never* traps a stale Realtime setting: users can always switch back to Pipeline.** Uses the in-house `useT()` i18n hook (see src/i18n/index.ts) rather thandiff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 605e762fa4..21d94ecea2 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -18,8 +18,10 @@ Mounted by the WebServer in ``_build_app()``:from __future__ import annotationsimport asyncio+import inspectimport loggingimport time+from collections.abc import Mappingfrom typing import Any, Literal, get_argsfrom fastapi import APIRouter, HTTPException, Request, Response@@ -87,6 +89,10 @@ class SecretBody(BaseModel):class SwitchBody(BaseModel):provider: str = Field(..., min_length=1)persist: bool = Field(default=True, description="Write the selection to jarvis.toml")+ accept_experimental: bool = Field(+ default=False,+ description="Acknowledge an explicitly selected experimental provider",+ )class CodexBinaryPathBody(BaseModel):@@ -224,6 +230,7 @@ class RealtimeOptionsResponse(BaseModel):voices: list[RealtimeOptionInfo]current_model: strcurrent_voice: str+ preview_available: boolclass RealtimeOptionsBody(BaseModel):@@ -268,14 +275,10 @@ def _is_credential_present(spec: ProviderSpec, binary_path: str | None = None) -use the *same* check — anti-drift, BUG-008 class. Name/signature preservedfor the rest of this module.- ONE local addition: a dictation-polish card answers through its polish- FAMILY instead. Such a card renders a single key field, but the pass itself- accepts any slot in the family's candidate list — a Google user holding only- ``google_api_key`` has a perfectly working polish pass, and the single-slot- check would call that card "no key set" and offer a fix for a problem that- does not exist. The shared implementation is untouched because it never sees- these specs: ``apply_provider_switch`` rejects a dictation spec on its tier- long before the credential check.+ Local additions cover two capabilities the shared Brain switch never sees:+ a dictation-polish card answers through its polish family, while keyless+ Codex auth requires a ChatGPT login rather than Codex API-key mode. The+ shared implementation remains responsible for every other provider path."""family = _polish_family(spec)if family is not None:@@ -283,13 +286,21 @@ def _is_credential_present(spec: ProviderSpec, binary_path: str | None = None) -return family_has_key(family)+ # A keyless Codex-auth surface explicitly spends a ChatGPT subscription.+ # A connected Codex CLI running in API-key mode is a different billing+ # capability and must not unlock it. Specs that declare key slots retain+ # their existing subscription-or-API behavior through app_control below.+ if spec.auth_mode == "codex" and not spec.secret_keys:+ status = CodexAuthService(binary_path or _codex_binary_path()).status()+ return bool(status.connected and status.mode == "chatgpt")+from jarvis.brain.app_control import is_credential_presentreturn is_credential_present(spec, binary_path)def _cli_installed(spec: ProviderSpec) -> bool | None:- if spec.id == "codex":+ if spec.auth_mode == "codex":return CodexAuthService().status().installedreturn None@@ -414,6 +425,8 @@ def _spec_to_payload(active_computer_use: str | None = None,active_dictation: str | None = None,local_model_override: str | None = None,+ codex_subscription_ready: bool | None = None,+ codex_subscription_status: Mapping[str, Any] | None = None,) -> dict[str, Any]:if spec.tier == "brain":active = spec.id == active_brain@@ -461,8 +474,27 @@ def _spec_to_payload(for k in spec.secret_keys}codex_status = None- if spec.id == "codex":- codex_status = CodexAuthService(_codex_binary_path()).status().to_dict()+ if spec.auth_mode == "codex":+ codex_status = (+ dict(codex_subscription_status)+ if spec.id == "codex-subscription-realtime"+ and codex_subscription_status is not None+ else CodexAuthService(_codex_binary_path()).status().to_dict()+ )+ if (+ spec.id == "codex-subscription-realtime"+ and codex_subscription_ready is not None+ ):+ codex_status["connected"] = codex_subscription_ready+ if codex_subscription_ready:+ codex_status["mode"] = "chatgpt"+ codex_status["message"] = "Connected via ChatGPT."+ else:+ codex_status["mode"] = "not_connected"+ codex_status["message"] = (+ "ChatGPT subscription voice is not ready. "+ "Reconnect with ChatGPT and review the setup status."+ )antigravity_status = Noneif spec.id == "antigravity":from jarvis.google_cli.auth_service import GoogleCliAuthService@@ -509,6 +541,9 @@ def _spec_to_payload(# instead of raising a permanent "needs setup" dot. Presentation +# nag-suppression only — never a behavior gate (AP-21)."optional": spec.optional,+ # Unstable provider protocol: the card explains the fallback before a+ # user activates it. Presentation only, never a runtime provider gate.+ "experimental": spec.experimental,# Dictation-polish cards only: the value ``[dictation].polish_provider``# actually stores. The card id and the polish FAMILY id differ ("groq"# is already the brain card), so a client pinning this tier must send@@ -537,13 +572,24 @@ def _spec_to_payload("configured": (bool(antigravity_status["connected"])if antigravity_status is not None+ else codex_subscription_ready+ if spec.id == "codex-subscription-realtime"+ and codex_subscription_ready is not None+ else bool(+ codex_status["connected"] and codex_status["mode"] == "chatgpt"+ )+ if codex_status is not None and not spec.secret_keyselse _is_credential_present(spec,- _codex_binary_path() if spec.id == "codex" else None,+ _codex_binary_path() if spec.auth_mode == "codex" else None,)),"active": active,- "cli_installed": _cli_installed(spec),+ "cli_installed": (+ bool(codex_status["installed"])+ if codex_status is not None+ else _cli_installed(spec)+ ),# Overlay, not a new tier (see the CU-own-provider plan): a brain# provider can be BOTH the main Brain ("active") AND/OR the dedicated# Computer-Use planner ("computer_use_active") — the two selections@@ -556,9 +602,11 @@ def _spec_to_payload(payload["antigravity_status"] = antigravity_statusif codex_status is not None:payload["codex_status"] = codex_status- # Back-compat only. Codex is not rendered as a switchable Brain anymore;- # the Subagent section owns its ChatGPT login and activation.- payload["codex_brain_ready"] = _codex_brain_usable()+ if spec.tier == "brain":+ # Back-compat only. The Brain-tier Codex card is owned by the+ # Jarvis-Agents section. Other Codex-auth surfaces must not inherit+ # its API-key readiness rule.+ payload["codex_brain_ready"] = _codex_brain_usable()return payload@@ -814,6 +862,60 @@ def _codex_binary_path(request: Request | None = None) -> str | None:return getattr(getattr(cfg, "codex", None), "binary_path", "") or None+def _codex_subscription_status_payload(binary_path: str | None) -> dict[str, Any]:+ """Lightweight status for the isolated voice-only Codex identity.++ This never starts app-server and never consults the normal Codex profile.+ The live account and plan are verified when the user explicitly activates+ the experimental provider or starts a call.+ """+ from jarvis.codex_app_server import codex_subscription_auth_snapshot++ snapshot = codex_subscription_auth_snapshot(binary_path)+ installed = bool(snapshot.available or snapshot.version)+ connected = bool(snapshot.available and snapshot.chatgpt_authenticated)+ if connected:+ message = "Dedicated ChatGPT subscription voice login is ready."+ elif snapshot.available:+ message = "Connect the dedicated ChatGPT subscription voice login."+ else:+ message = snapshot.reason+ return {+ "installed": installed,+ "connected": connected,+ "mode": "chatgpt" if connected else "not_connected",+ "message": message,+ "reason_code": "ready" if connected else snapshot.reason_code,+ "version": snapshot.version,+ "accountLabel": "ChatGPT subscription voice" if connected else None,+ "user_email": None,+ "binary_path": snapshot.binary_path,+ "isolated": True,+ }+++async def _provider_credential_present_for_binary_async(+ spec: ProviderSpec,+ binary_path: str | None,+) -> bool:+ """Probe sync keyrings and Codex's authoritative auth store off-loop."""+ if spec.id == "codex-subscription-realtime":+ from jarvis.codex_app_server import codex_subscription_login_ready++ return await codex_subscription_login_ready(binary_path)+ return await asyncio.to_thread(_is_credential_present, spec, binary_path)+++async def _provider_credential_present_async(+ spec: ProviderSpec,+ request: Request,+) -> bool:+ return await _provider_credential_present_for_binary_async(+ spec,+ _codex_binary_path(request),+ )++def _apply_worker_model_in_memory(request: Request, model: str) -> None:"""Best-effort in-memory update of ``cfg.brain.worker.model``.@@ -865,12 +967,20 @@ async def list_providers(request: Request) -> dict[str, Any]:active_brain = _active_brain(request)active_tts = _active_tts(request)active_stt = _active_stt(request)- active_realtime = _active_realtime(request)+ # Subscription discovery can invoke the Codex CLI. Keep that synchronous+ # login probe off FastAPI's event loop just like the credential payload+ # build below.+ active_realtime = await asyncio.to_thread(_active_realtime, request)active_computer_use = _active_computer_use(request)# Resolved in a worker thread first (keyring + config file); the read that# follows is then a memo hit. See ``_warm_active_polish``.await _warm_active_polish(request)active_dictation = _active_polish(request)+ codex_subscription_status = await asyncio.to_thread(+ _codex_subscription_status_payload,+ _codex_binary_path(request),+ )+ codex_subscription_ready = bool(codex_subscription_status["connected"])# When a local STT provider is ALREADY the active one, its card must report# on the checkpoint the config names — not the catalog default. Otherwise a# user who pinned a different Whisper size in jarvis.toml would read a@@ -899,6 +1009,8 @@ async def list_providers(request: Request) -> dict[str, Any]:active_computer_use=active_computer_use,active_dictation=active_dictation,local_model_override=local_model_override,+ codex_subscription_ready=codex_subscription_ready,+ codex_subscription_status=codex_subscription_status,)for spec in PROVIDERS]@@ -1049,6 +1161,7 @@ async def _tier_section_health(model: str | None = None,optional: bool = False,probe: bool = True,+ binary_path: str | None = None,) -> SectionHealth:"""Health of one provider tier, derived from its ACTIVE provider only.@@ -1112,8 +1225,9 @@ async def _tier_section_health(subject_id=spec.id,)try:- configured = _is_credential_present(- spec, _codex_binary_path() if spec.id == "codex" else None+ configured = await _provider_credential_present_for_binary_async(+ spec,+ binary_path,)except Exception: # noqa: BLE001 — a probe failure is "not set up", not a crashconfigured = False@@ -1122,20 +1236,20 @@ async def _tier_section_health(return SectionHealth(status=_section_health.OK,reason="not_configured_optional",- detail=f"{spec.label}: optional, no key set",+ detail=f"{spec.label}: optional, not connected or configured",subject_id=spec.id,)return SectionHealth(status=_section_health.NEEDS_SETUP,reason="not_configured",- detail=f"{spec.label}: no key set",+ detail=f"{spec.label}: not connected or configured",subject_id=spec.id,)if not probe:return SectionHealth(status=_section_health.OK,reason="configured",- detail=f"{spec.label}: key set",+ detail=f"{spec.label}: connected or configured",subject_id=spec.id,)try:@@ -1323,14 +1437,19 @@ def _jarvis_agent_section_health(cfg: Any) -> SectionHealth:)-async def _realtime_section_health(cfg: Any, spec: ProviderSpec | None) -> SectionHealth:+async def _realtime_section_health(+ cfg: Any,+ spec: ProviderSpec | None,+ *,+ binary_path: str | None = None,+) -> SectionHealth:"""Test the active provider's actual duplex handshake.Credential presence alone previously painted a depleted or schema-brokenprovider green. Reuse the standard tier health mapping so the Realtime tabreports the same honest account/integration states as every other tier."""- return await _tier_section_health(cfg, spec)+ return await _tier_section_health(cfg, spec, binary_path=binary_path)async def _dictation_section_health(@@ -1601,8 +1720,13 @@ async def _compute_section_health(subject_id=subjects.get(section),)+ binary_path = _codex_binary_path(request)checks = {- "brain": _tier_section_health(cfg, get_spec(subjects["brain"] or "")),+ "brain": _tier_section_health(+ cfg,+ get_spec(subjects["brain"] or ""),+ binary_path=binary_path,+ ),# The Tool Model tier has its own model pin (tool_model → cu_model);# probe THAT model, not the general brain model. An unset pin falls# through to run_provider_test's own resolution (model → tier default).@@ -1610,11 +1734,18 @@ async def _compute_section_health(cfg,get_spec(subjects["computer-use"] or ""),model=_provider_cu_model(cfg, subjects["computer-use"] or "") or None,+ binary_path=binary_path,+ ),+ "tts": _tier_section_health(+ cfg, get_spec(subjects["tts"] or ""), binary_path=binary_path+ ),+ "stt": _tier_section_health(+ cfg, get_spec(subjects["stt"] or ""), binary_path=binary_path),- "tts": _tier_section_health(cfg, get_spec(subjects["tts"] or "")),- "stt": _tier_section_health(cfg, get_spec(subjects["stt"] or "")),"realtime": _realtime_section_health(- cfg, get_spec(subjects["realtime"] or "")+ cfg,+ get_spec(subjects["realtime"] or ""),+ binary_path=binary_path,),# Optional tier: silent without a key, never amber (see the function)."dictation": _dictation_section_health(@@ -2333,6 +2464,7 @@ async def get_realtime_options(provider_id: str, request: Request) -> RealtimeOp],current_model=current_model,current_voice=current_voice,+ preview_available=provider_id in _REALTIME_PREVIEW_SAMPLERS,)@@ -2342,7 +2474,8 @@ async def set_realtime_options() -> RealtimeOptionsSaveResponse:"""Pin the model and/or voice for a realtime provider.- Persists to ``[brain.providers.<id>].model`` / ``.voice`` (+ drift-soll) # i18n-allow: config-soll filename+ Persists to ``[brain.providers.<id>].model`` / ``.voice`` and the drift+ baseline, then updates the in-memory config.and updates the in-memory config. If this provider owns the active realtimecall, that call is closed and reopened immediately; otherwise the selectionapplies to the next session. No process restart is required. Only fields@@ -2366,12 +2499,12 @@ async def set_realtime_options(value=voice,allowed={option.id for option in REALTIME_VOICES.get(provider_id, ())},)- if not _is_credential_present(spec):+ if not await _provider_credential_present_async(spec, request):raise HTTPException(status_code=409,detail=(f"Provider '{provider_id}' has no configured credentials. "- "Add its API key first."+ "Connect or configure this provider first."),)@@ -2570,8 +2703,9 @@ async def _openai_realtime_voice_sample(return bytes(pcm), output_rate-# Keyed like REALTIME_MODELS/REALTIME_VOICES: adding a realtime provider means-# adding its catalog entries AND its sampler here (the parity test guards it).+# Only providers whose preview transport can run without an interactive media+# offer appear here. A cataloged provider may intentionally omit a sampler;+# ``preview_available`` keeps the UI from rendering a button that cannot work._REALTIME_PREVIEW_SAMPLERS: dict[str, Any] = {"gemini-live": _gemini_live_voice_sample,"openai-realtime": _openai_realtime_voice_sample,@@ -2689,6 +2823,15 @@ async def codex_status(request: Request) -> dict[str, Any]:return status.to_dict()[email protected]("/codex/subscription-voice/status")+async def codex_subscription_voice_status(request: Request) -> dict[str, Any]:+ """Status of the isolated, voice-only ChatGPT subscription login."""+ return await asyncio.to_thread(+ _codex_subscription_status_payload,+ _codex_binary_path(request),+ )++@router.post("/codex/test")async def codex_test(request: Request) -> dict[str, Any]:"""Live CLI test: cache-busting binary + version + login probe.@@ -2749,6 +2892,36 @@ async def codex_login(request: Request) -> dict[str, Any]:return {"ok": True, "pid": proc.pid, "message": "codex login was started in a terminal"}[email protected]("/codex/subscription-voice/login")+async def codex_subscription_voice_login(request: Request) -> dict[str, Any]:+ """Start Codex's own login in Jarvis's isolated voice profile."""+ from jarvis.codex_app_server import (+ CodexSubscriptionUnavailable,+ start_codex_subscription_login,+ )++ try:+ proc = await asyncio.to_thread(+ start_codex_subscription_login,+ _codex_binary_path(request),+ )+ except (CodexSubscriptionUnavailable, FileNotFoundError, OSError) as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ except Exception as exc: # noqa: BLE001 - terminal backends vary by OS+ raise HTTPException(+ status_code=500,+ detail=(+ "The dedicated ChatGPT subscription login could not be started: "+ f"{type(exc).__name__}: {exc}"+ ),+ ) from exc+ return {+ "ok": True,+ "pid": proc.pid,+ "message": "The dedicated ChatGPT subscription login was started.",+ }++@router.post("/codex/logout")async def codex_logout(request: Request) -> dict[str, Any]:service = CodexAuthService(_codex_binary_path(request))@@ -2761,6 +2934,31 @@ async def codex_logout(request: Request) -> dict[str, Any]:return {"ok": True, "message": "Codex was disconnected"}+ "/codex/subscription-voice/logout",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def codex_subscription_voice_logout(request: Request) -> dict[str, Any]:+ """Disconnect only the isolated subscription-voice identity."""+ from jarvis.codex_app_server import (+ CodexSubscriptionUnavailable,+ disconnect_and_logout_codex_subscription,+ )++ try:+ ok, error = await disconnect_and_logout_codex_subscription(+ _codex_binary_path(request),+ )+ except CodexSubscriptionUnavailable as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ if not ok:+ raise HTTPException(+ status_code=500,+ detail=error or "Subscription voice logout failed.",+ )+ return {"ok": True, "message": "Subscription voice was disconnected."}++# M6: STT/TTS engines build ONCE at voice-pipeline bootstrap, so a key feeding them# is unused until the next voice start. Surface restart_required so the UI shows the# "active from next voice start" hint instead of implying the new key is live now.@@ -3046,8 +3244,7 @@ _VOICE_PICKER_PROVIDER = "openrouter-tts"_TTS_PREVIEW_SAMPLES: dict[str, str] = {# The German sentence is deliberately NOT a literal translation of the# English one: Gemini's AI-Studio TTS safety filter deterministically- # blocked the former mirror-translation ("So klingt meine Stimme, wenn- # ich für dich spreche und dir zuhöre") as PROHIBITED_CONTENT — 0/2 runs # i18n-allow: forensic quote of the blocked German sample+ # blocked the former mirrored sentence as PROHIBITED_CONTENT — 0/2 runs# passed, voice-independent, while EN/ES passed (probe 2026-07-17). This# wording passed 4/4 runs across three voices."de": (@@ -3199,7 +3396,7 @@ async def set_tts_voice_selection("""Persist + live-apply the global TTS voice (``[tts] voice_de``/``voice_en``).A TTS model ships several voices; this pins the chosen one. Reuses the shared- ``_apply_tts_selection`` path (config-soll-synced write + a live rebuild of # i18n-allow: config-soll filename+ ``_apply_tts_selection`` path (drift-synced write plus a live rebuild ofthe running SpeechPipeline's TTS) so the next spoken turn uses it without arestart when voice is active."""@@ -3437,14 +3634,39 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:f"(tier={spec.tier})"),)- if not _is_credential_present(spec):+ if spec.experimental and not body.accept_experimental:+ raise HTTPException(+ status_code=409,+ detail=(+ f"Provider '{body.provider}' is experimental. Explicitly acknowledge "+ "the experimental transport before activating it."+ ),+ )+ credential_present = await _provider_credential_present_async(spec, request)+ if not credential_present:raise HTTPException(status_code=409,detail=(f"Provider '{body.provider}' has no configured credentials. "- "Add its API key first."+ "Connect or configure this provider first."),)+ try:+ from jarvis.core.registry import load+ from jarvis.realtime.protocol import RealtimeProvider++ provider_cls = load(+ "jarvis.realtime",+ body.provider,+ protocol=RealtimeProvider,+ )+ verify_activation = getattr(provider_cls, "verify_activation", None)+ if callable(verify_activation):+ result = verify_activation(_resolve_cfg(request))+ if inspect.isawaitable(result):+ await result+ except Exception as exc: # noqa: BLE001 - provider gate returns a safe 409+ raise HTTPException(status_code=409, detail=str(exc)) from excvoice_mode_write_ok = Trueif body.persist:diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.pyindex 1d4fc4ff3f..11de51b037 100644--- a/jarvis/ui/web/provider_spec.py+++ b/jarvis/ui/web/provider_spec.py@@ -101,6 +101,10 @@ class ProviderSpec:# no guessable default port).supports_base_url: bool = Falsedefault_base_url: str | None = None+ # The integration uses a provider protocol that is not yet stable. The UI+ # shows a clear badge and fallback note, while runtime selection remains+ # capability-driven. This is presentation only and never gates behavior.+ experimental: bool = Falsedef provider_billing(spec: ProviderSpec) -> Billing:@@ -738,8 +742,27 @@ PROVIDERS: tuple[ProviderSpec, ...] = (# missing one leaves dictation behaving exactly as it did before.*_DICTATION_PROVIDERS,# ── Realtime ──────────────────────────────────────────────────────────- # Realtime voice spans independently selectable OpenAI, Gemini, and xAI- # plugins behind the provider-neutral RealtimeProvider contract.+ # Realtime voice providers share the provider-neutral RealtimeProvider+ # contract. Subscription and API billing remain independently selectable.+ ProviderSpec(+ id="codex-subscription-realtime",+ label="ChatGPT subscription (Codex)",+ tier="realtime",+ auth_mode="codex",+ secret_keys=(),+ dashboard_url=None,+ login_cli=("codex", "login"),+ install_hint="npm i -g @openai/[email protected]",+ signup_url="https://chatgpt.com",+ credential_help=(+ "Uses the ChatGPT plan signed in through Codex. This experimental "+ "realtime path does not need an API key. The app never switches it "+ "silently to metered API voice. If it cannot start, the call stops; "+ "select an API Realtime provider if you want usage billing. Brain "+ "and tool providers keep their separately configured billing."+ ),+ experimental=True,+ ),ProviderSpec(id="openai-realtime",label="OpenAI Realtime",diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 9d1634b60f..28df6ff8dc 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -3385,18 +3385,30 @@ class WebServer:self.app.state.channel_manager = Noneself.app.state.friend_registry = None- if self._server is None:- return- self._server.should_exit = True- if self._serve_task is not None:- try:- await asyncio.wait_for(self._serve_task, timeout=5.0)- except TimeoutError:- logger.warning("uvicorn shutdown timeout — force-cancel")- self._serve_task.cancel()+ if self._server is not None:+ self._server.should_exit = True+ if self._serve_task is not None:+ try:+ await asyncio.wait_for(self._serve_task, timeout=5.0)+ except TimeoutError:+ logger.warning("uvicorn shutdown timeout — force-cancel")+ self._serve_task.cancel()self._server = Noneself._serve_task = None+ # Browser/desktop realtime owners must release their ephemeral threads+ # before their shared process is reaped. Keep this unconditional: a+ # failed startup can complete the Codex handshake before uvicorn marks+ # itself running, and that process still needs bounded teardown.+ try:+ from jarvis.codex_app_server import close_shared_codex_app_servers++ await close_shared_codex_app_servers()+ except Exception as exc: # noqa: BLE001 - shutdown continues best-effort+ logger.opt(exception=exc).warning(+ "Codex subscription app-server cleanup failed"+ )+@propertydef running(self) -> bool:return self._server is not None and self._server.starteddiff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex 3df11c977c..5af75646cf 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -50,21 +50,27 @@ router = APIRouter(prefix="/api/settings", tags=["settings"])def _realtime_available_provider(cfg: object) -> str | None:"""Reachable realtime provider name for ``cfg``, or ``None``.- The realtime voice engine (``jarvis.realtime``) is an optional module that is- stripped from public distribution snapshots (distribution-denylist) while it- is still internal. Import it lazily and treat its absence as "no realtime- available", so the settings router still IMPORTS (the server boots) and the- ``/voice-mode`` endpoint degrades honestly instead of taking the whole app- down. When the module is present (the full/local build) this delegates to it- unchanged.+ Realtime ships as a public optional capability. Import it lazily so a+ minimal or headless install without the module still boots and reports the+ feature as unavailable instead of taking the settings API down. When the+ module is installed, delegate provider resolution unchanged."""try:from jarvis.realtime.factory import realtime_available_provider- except ImportError:+ except ImportError: # Optional realtime support degrades to no available provider.return Nonereturn realtime_available_provider(cfg)+def _realtime_requires_webrtc_offer(cfg: object) -> bool:+ """Whether the resolved adapter needs browser SDP, or false when absent."""+ try:+ from jarvis.realtime.factory import realtime_requires_webrtc_offer+ except ImportError: # Optional subscription transport degrades to no WebRTC requirement.+ return False+ return realtime_requires_webrtc_offer(cfg)++class ReplyLanguageBody(BaseModel):language: str = Field(..., min_length=1)persist: bool = Field(default=True, description="Persist as boot default in jarvis.toml")@@ -142,9 +148,9 @@ async def put_reply_language(body: ReplyLanguageBody, request: Request) -> dict[# ----------------------------------------------------------------------------# Voice mode: pipeline (the classic STT→Brain→TTS pipeline) vs realtime (the-# browser-based OpenAI/Gemini full-duplex realtime engine). GET current mode +-# whether realtime is actually reachable (needs an OpenAI key); PUT to switch.+# Voice mode: pipeline (the classic STT→Brain→TTS pipeline) vs realtime (a+# full-duplex provider transport, including subscription-authenticated Codex).+# GET reports the current mode and provider readiness; PUT switches it.# Persisted to jarvis.toml [voice].mode via config_writer.set_voice_mode# (Task 1); the persist is best-effort so a locked/read-only toml never blocks# the live in-memory switch that already succeeded. See@@ -204,7 +210,13 @@ async def get_voice_mode(request: Request) -> dict[str, object]:# session factory uses, so this never disagrees with what a realtime# session would actually build (Gemini-only users now get `true` too,# not just OpenAI — Feature A2).- prov = _realtime_available_provider(cfg)+ # External-login adapters may need a bounded CLI status probe. Keep that+ # subprocess off the event loop so a settings poll cannot punch a hole in+ # live Realtime audio playback.+ prov = await asyncio.to_thread(_realtime_available_provider, cfg)+ requires_webrtc_offer = await asyncio.to_thread(+ _realtime_requires_webrtc_offer, cfg+ )prov_label, prov_model = _realtime_provider_display(cfg, prov)from jarvis.ui.web.voice_runtime import voice_engine_status@@ -212,6 +224,7 @@ async def get_voice_mode(request: Request) -> dict[str, object]:return {"mode": mode,"realtime_available": prov is not None,+ "requires_webrtc_offer": requires_webrtc_offer,"active_provider": prov,# Sidebar-footer display fields: the pretty provider name + the model# an idle realtime session would use (configured pin or catalog@@ -236,10 +249,16 @@ async def put_voice_mode(body: VoiceModeBody, request: Request) -> dict[str, objcfg = getattr(request.app.state, "config", None) or getattr(request.app.state, "cfg", None)- # A3: never pin the boot default to an unreachable engine — selecting- # realtime with no key in ANY family is a 400, not a silent dead switch.- if body.mode == "realtime" and _realtime_available_provider(cfg) is None:- raise HTTPException(status_code=400, detail="no realtime provider key configured")+ # A3: never pin the boot default to an unreachable engine. A provider may+ # use an API key or an external subscription login, so readiness — not a+ # particular credential shape — is the boundary.+ if body.mode == "realtime" and await asyncio.to_thread(+ _realtime_available_provider, cfg+ ) is None:+ raise HTTPException(+ status_code=400,+ detail="no realtime provider is configured and ready",+ )if cfg is not None and getattr(cfg, "voice", None) is not None:try:diff --git a/pyproject.toml b/pyproject.tomlindex f4a4c71c09..3cada43bf7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -537,6 +537,7 @@ discord = "jarvis.channels.discord:DiscordChannel"[project.entry-points."jarvis.realtime"]# Provider-neutral speech-to-speech plugins. Every adapter loads lazily; the# orchestrator chooses a credential-ready family and crosses families on failure.+codex-subscription-realtime = "jarvis.plugins.realtime.codex_subscription:CodexSubscriptionRealtimeProvider"openai-realtime = "jarvis.plugins.realtime.openai_realtime:OpenAIRealtimeProvider"gemini-live = "jarvis.plugins.realtime.gemini_live:GeminiLiveProvider"diff --git a/tests/contract/test_realtime_provider_contract.py b/tests/contract/test_realtime_provider_contract.pyindex 6176205f2d..91dfa1c799 100644--- a/tests/contract/test_realtime_provider_contract.py+++ b/tests/contract/test_realtime_provider_contract.py@@ -5,6 +5,9 @@ from pathlib import Pathimport pytest+from jarvis.plugins.realtime.codex_subscription import (+ CodexSubscriptionRealtimeProvider,+)from jarvis.plugins.realtime.gemini_live import GeminiLiveProviderfrom jarvis.plugins.realtime.openai_realtime import OpenAIRealtimeProviderfrom jarvis.realtime.protocol import RealtimeProvider@@ -27,6 +30,18 @@ def test_provider_is_structurally_conformant(provider_cls, provider_id, input_raassert provider.credential_candidates+def test_subscription_provider_is_structurally_conformant_without_api_key() -> None:+ provider = CodexSubscriptionRealtimeProvider()++ assert isinstance(provider, RealtimeProvider)+ assert provider.supports_realtime is True+ assert provider.name == "codex-subscription-realtime"+ assert provider.input_sample_rate == 24_000+ assert provider.output_sample_rate == 24_000+ assert provider.credential_candidates == ()+ assert provider.requires_webrtc_offer is True++@pytest.mark.asyncio@pytest.mark.parametrize("provider_cls",@@ -41,6 +56,7 @@ async def test_keyless_capability_probe_is_false(provider_cls):[Path("jarvis/plugins/realtime/openai_realtime.py"),Path("jarvis/plugins/realtime/gemini_live.py"),+ Path("jarvis/plugins/realtime/codex_subscription.py"),],)def test_plugin_module_imports_no_jarvis_modules(path: Path):diff --git a/tests/unit/brain/test_current_model_catalogs.py b/tests/unit/brain/test_current_model_catalogs.pyindex bea06a18d3..b04ff19ffa 100644--- a/tests/unit/brain/test_current_model_catalogs.py+++ b/tests/unit/brain/test_current_model_catalogs.py@@ -126,6 +126,20 @@ def test_current_stt_and_cartesia_model_rosters() -> None:def test_current_realtime_models_and_voices() -> None:+ assert _ids(REALTIME_MODELS["codex-subscription-realtime"]) == {+ "gpt-realtime-1.5"+ }+ assert _ids(REALTIME_VOICES["codex-subscription-realtime"]) == {+ "cove",+ "juniper",+ "maple",+ "spruce",+ "ember",+ "vale",+ "breeze",+ "arbor",+ "sol",+ }assert {"gpt-realtime","gpt-realtime-mini",diff --git a/tests/unit/brain/test_model_catalog.py b/tests/unit/brain/test_model_catalog.pyindex 2c34822a20..01034dcf3d 100644--- a/tests/unit/brain/test_model_catalog.py+++ b/tests/unit/brain/test_model_catalog.py@@ -754,6 +754,24 @@ class TestModelClassification:class TestRealtimeCatalog:+ def test_codex_subscription_catalog_matches_app_server_v1(self) -> None:+ from jarvis.brain.model_catalog import REALTIME_MODELS, REALTIME_VOICES++ assert [m.id for m in REALTIME_MODELS["codex-subscription-realtime"]] == [+ "gpt-realtime-1.5"+ ]+ assert [v.id for v in REALTIME_VOICES["codex-subscription-realtime"]] == [+ "cove",+ "juniper",+ "maple",+ "spruce",+ "ember",+ "vale",+ "breeze",+ "arbor",+ "sol",+ ]+def test_openai_realtime_models_lead_with_the_hardcoded_default(self) -> None:from jarvis.brain.model_catalog import REALTIME_MODELS@@ -813,3 +831,4 @@ class TestRealtimeCatalog:# single-selection response that can't express model+voice together).assert catalog_spec("openai-realtime") is Noneassert catalog_spec("gemini-live") is None+ assert catalog_spec("codex-subscription-realtime") is Nonediff --git a/tests/unit/brain/test_section_health.py b/tests/unit/brain/test_section_health.pyindex 2aae65d00c..d8648f5c5d 100644--- a/tests/unit/brain/test_section_health.py+++ b/tests/unit/brain/test_section_health.py@@ -89,10 +89,20 @@ async def test_every_catalog_provider_health_is_bound_to_its_exact_id(reached a real provider instead would make this a connectivity test of themachine it runs on."""+ from jarvis import codex_app_serverfrom jarvis.dictation import polish_probefrom jarvis.ui.web import provider_routesmonkeypatch.setattr(provider_routes, "_is_credential_present", lambda *args: True)++ async def _subscription_ready(_binary_path=None):+ return True++ monkeypatch.setattr(+ codex_app_server,+ "codex_subscription_login_ready",+ _subscription_ready,+ )# On-device cards ask the disk whether engine + weights are really there.# On a machine that never installed them that is an honest "needs setup" —# true, and not what this test is about.diff --git a/tests/unit/browser_voice/test_route.py b/tests/unit/browser_voice/test_route.pyindex 9316a1d7e7..c155478eec 100644--- a/tests/unit/browser_voice/test_route.py+++ b/tests/unit/browser_voice/test_route.py@@ -14,8 +14,10 @@ import pytestfrom fastapi import WebSocketDisconnectimport jarvis.browser_voice.route as route_mod-from jarvis.browser_voice.route import browser_voice_ws+import jarvis.realtime.offer_broker as offer_broker_mod+from jarvis.browser_voice.route import browser_voice_ws, realtime_transport_wsfrom jarvis.core.bus import EventBus+from jarvis.realtime.offer_broker import RealtimeTransportOfferBrokerfrom jarvis.realtime.protocol import RealtimeEventfrom jarvis.realtime.session import RealtimeVoiceSessionfrom jarvis.sessions.recorder import SessionRecorder@@ -28,6 +30,7 @@ from tests.fakes.fake_realtime import (_VALID_TOKEN = "registered-session-token" # noqa: S105 -- synthetic test token_INVALID_TOKEN = "invalid-token" # noqa: S105 -- synthetic test token+_BROKER_TOKEN = "desktop-broker-capability" # noqa: S105 -- synthetic test token@pytest.fixture(autouse=True)@@ -98,6 +101,37 @@ class _FakeWS:self.closed = (code, reason)+class _QueueWS(_FakeWS):+ """Fake socket that can stay connected while the provider answers."""++ def __init__(self, incoming, *, state, **kwargs) -> None:+ super().__init__([], state=state, **kwargs)+ self._queue: asyncio.Queue[dict] = asyncio.Queue()+ for message in incoming:+ self._queue.put_nowait(message)++ async def receive(self) -> dict:+ return await self._queue.get()++ def feed(self, message: dict) -> None:+ self._queue.put_nowait(message)+++async def _wait_for_json(+ ws: _FakeWS, message_type: str, *, offer_id: str | None = None+) -> dict:+ async def _wait() -> dict:+ while True:+ for message in ws.sent_json:+ if message.get("type") == message_type and (+ offer_id is None or message.get("offer_id") == offer_id+ ):+ return message+ await asyncio.sleep(0)++ return await asyncio.wait_for(_wait(), timeout=1.0)++def _state(session, cfg=None):# Default cfg explicitly opts into the classic bridge (Task 7 inverted the# gate to default-OFF; these tests exercise the classic dispatch/session@@ -108,9 +142,20 @@ def _state(session, cfg=None):config=cfg if cfg is not None else default_cfg,bus=None,browser_voice_session_factory=lambda **kw: session,+ realtime_transport_broker_token=_BROKER_TOKEN,)+def _broker_auth_message() -> dict[str, str]:+ return {+ "type": "websocket.receive",+ "text": (+ '{"type":"authenticate","desktop_capability":'+ f'"{_BROKER_TOKEN}"}}'+ ),+ }++def test_classic_fallback_language_uses_canonical_default_and_pin() -> None:auto_cfg = SimpleNamespace(brain=SimpleNamespace(reply_language="auto"))spanish_cfg = SimpleNamespace(brain=SimpleNamespace(reply_language="es"))@@ -212,6 +257,189 @@ async def test_loopback_route_rejects_supplied_invalid_token() -> None:assert rec.ended is False+async def test_realtime_transport_rejects_missing_token_before_offer_registration(+ monkeypatch,+) -> None:+ broker = RealtimeTransportOfferBroker()+ monkeypatch.setattr(+ offer_broker_mod,+ "get_realtime_transport_offer_broker",+ lambda: broker,+ )+ cfg = SimpleNamespace(voice=SimpleNamespace(mode="realtime"))+ ws = _FakeWS([], state=_state(_RecSession(), cfg=cfg), token="")++ await realtime_transport_ws(ws)++ assert ws.closed == (4401, "unauthorized")+ assert await broker.pending_count() == 0+++async def test_realtime_transport_rejects_invalid_desktop_capability(+ monkeypatch,+) -> None:+ broker = RealtimeTransportOfferBroker()+ monkeypatch.setattr(+ offer_broker_mod,+ "get_realtime_transport_offer_broker",+ lambda: broker,+ )+ cfg = SimpleNamespace(voice=SimpleNamespace(mode="realtime"))+ ws = _FakeWS(+ [+ {+ "type": "websocket.receive",+ "text": (+ '{"type":"authenticate",'+ '"desktop_capability":"wrong-capability"}'+ ),+ }+ ],+ state=_state(_RecSession(), cfg=cfg),+ )++ await realtime_transport_ws(ws)++ assert ws.closed == (4401, "invalid desktop capability")+ assert await broker.pending_count() == 0+++async def test_realtime_transport_rejects_remote_offer_hijack_even_with_valid_token(+ monkeypatch,+) -> None:+ broker = RealtimeTransportOfferBroker()+ monkeypatch.setattr(+ offer_broker_mod,+ "get_realtime_transport_offer_broker",+ lambda: broker,+ )+ cfg = SimpleNamespace(voice=SimpleNamespace(mode="realtime"))+ ws = _FakeWS(+ [+ {+ "type": "websocket.receive",+ "text": (+ '{"type":"offer","offer_id":"remote-hijack",'+ '"webrtc_offer_sdp":"v=0\\r\\no=remote"}'+ ),+ }+ ],+ state=_state(_RecSession(), cfg=cfg),+ client_host="203.0.113.8",+ token=_VALID_TOKEN,+ )+ # Neither forwarded headers nor Origin can override the actual ASGI peer.+ ws.scope["headers"].extend(+ [+ (b"x-forwarded-for", b"127.0.0.1"),+ (b"origin", b"http://127.0.0.1"),+ ]+ )++ await realtime_transport_ws(ws)++ assert ws.closed == (4403, "local desktop transport required")+ assert await broker.pending_count() == 0++[email protected]("client_host", ["127.0.0.1", "::1"])+async def test_realtime_transport_keeps_answer_live_then_releases_fresh_offers(+ monkeypatch,+ client_host: str,+) -> None:+ broker = RealtimeTransportOfferBroker()+ monkeypatch.setattr(+ offer_broker_mod,+ "get_realtime_transport_offer_broker",+ lambda: broker,+ )+ cfg = SimpleNamespace(voice=SimpleNamespace(mode="realtime"))+ ws = _QueueWS(+ [+ _broker_auth_message(),+ {+ "type": "websocket.receive",+ "text": (+ '{"type":"offer","offer_id":"offer-1",'+ '"webrtc_offer_sdp":"v=0\\r\\no=first"}'+ ),+ }+ ],+ state=_state(_RecSession(), cfg=cfg),+ client_host=client_host,+ )+ route_task = asyncio.create_task(realtime_transport_ws(ws))++ first_lease = await broker.acquire(timeout_s=1.0)+ assert first_lease is not None+ assert await first_lease.answer("v=0\r\no=first-answer") is True+ assert await _wait_for_json(ws, "answer", offer_id="offer-1") == {+ "type": "answer",+ "offer_id": "offer-1",+ "webrtc_answer_sdp": "v=0\r\no=first-answer",+ }+ await first_lease.release()+ await _wait_for_json(ws, "release", offer_id="offer-1")++ ws.feed(+ {+ "type": "websocket.receive",+ "text": (+ '{"type":"offer","offer_id":"offer-2",'+ '"webrtc_offer_sdp":"v=0\\r\\no=second"}'+ ),+ }+ )+ second_lease = await broker.acquire(timeout_s=1.0)+ assert second_lease is not None+ assert second_lease.offer_sdp == "v=0\r\no=second"+ assert await second_lease.answer("v=0\r\no=second-answer") is True+ await second_lease.release()+ await _wait_for_json(ws, "release", offer_id="offer-2")++ ws.feed({"type": "websocket.disconnect", "code": 1000})+ await asyncio.wait_for(route_task, timeout=1.0)++ assert ws.accepted is True+ assert await broker.pending_count() == 0+++async def test_realtime_transport_disconnect_after_answer_cancels_live_lease(+ monkeypatch,+) -> None:+ broker = RealtimeTransportOfferBroker()+ monkeypatch.setattr(+ offer_broker_mod,+ "get_realtime_transport_offer_broker",+ lambda: broker,+ )+ cfg = SimpleNamespace(voice=SimpleNamespace(mode="realtime"))+ ws = _QueueWS(+ [+ _broker_auth_message(),+ {+ "type": "websocket.receive",+ "text": (+ '{"type":"offer","offer_id":"offer-1",'+ '"webrtc_offer_sdp":"v=0\\r\\no=first"}'+ ),+ }+ ],+ state=_state(_RecSession(), cfg=cfg),+ )+ route_task = asyncio.create_task(realtime_transport_ws(ws))+ lease = await broker.acquire(timeout_s=1.0)+ assert lease is not None+ assert await lease.answer("v=0\r\no=answer") is True+ await _wait_for_json(ws, "answer", offer_id="offer-1")++ ws.feed({"type": "websocket.disconnect", "code": 1000})+ await asyncio.wait_for(route_task, timeout=1.0)++ assert await lease.answer("v=0\r\no=late") is False+ assert await broker.pending_count() == 0++async def test_route_drops_stale_frames_when_provider_is_backpressured(monkeypatch,) -> None:diff --git a/tests/unit/codex_app_server/test_transport.py b/tests/unit/codex_app_server/test_transport.pynew file mode 100644index 0000000000..ee58db8ac1--- /dev/null+++ b/tests/unit/codex_app_server/test_transport.py@@ -0,0 +1,2113 @@+"""Unit tests for the persistent Codex app-server JSONL transport.++Every subprocess, pipe, auth result, and process-tree container is a local fake.+The suite never reads a Codex auth file, starts the CLI, or touches the network.+"""++from __future__ import annotations++import asyncio+import json+import os+import shutil+import sys+import threading+from collections.abc import Callable+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++import jarvis.codex_app_server as transport+from jarvis.codex_app_server import (+ CodexAppServerCapability,+ CodexAppServerClient,+ CodexAppServerDisconnected,+ CodexAppServerRPCError,+ CodexAppServerTimeout,+ CodexNotificationOverflow,+ CodexSubscriptionUnavailable,+)+++class FakeProcessTree:+ supports_containment = True++ def __init__(self) -> None:+ self.assigned: list[int] = []+ self.closed = False++ def assign(self, pid: int) -> None:+ self.assigned.append(pid)++ def close(self) -> None:+ self.closed = True+++class FakeProfileProcessLock:+ def __init__(self) -> None:+ self.closed = False++ def close(self) -> None:+ self.closed = True++ def fileno(self) -> int:+ if self.closed:+ raise ValueError("closed")+ return 91++[email protected](autouse=True)+def isolated_profile_lifecycle(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ transport,+ "_acquire_subscription_process_lock",+ FakeProfileProcessLock,+ )+ monkeypatch.setattr(transport, "_subscription_login_in_flight", False)+ monkeypatch.setattr(transport, "_subscription_login_process", None)+ monkeypatch.setattr(transport, "_subscription_profile_mutating", False)+ monkeypatch.setattr(transport, "_subscription_active_transports", set())+ monkeypatch.setattr(transport, "_subscription_transport_process_lock", None)+ monkeypatch.setattr(transport, "_subscription_mutation_process_lock", None)+++class FakeStdin:+ def __init__(self, process: FakeProcess) -> None:+ self.process = process+ self.messages: list[dict[str, Any]] = []+ self.closed = False+ self.drain_calls = 0++ def write(self, payload: bytes) -> None:+ assert payload.endswith(b"\n")+ for line in payload.splitlines():+ message = json.loads(line.decode("utf-8"))+ self.messages.append(message)+ self.process.on_client_message(message)++ async def drain(self) -> None:+ self.drain_calls += 1+ await asyncio.sleep(0)++ def close(self) -> None:+ self.closed = True+ self.process.finish(0)+++class FakeProcess:+ _next_pid = 4100++ def __init__(+ self,+ responder: Callable[[FakeProcess, dict[str, Any]], None] | None = None,+ config_result: dict[str, Any] | None = None,+ ) -> None:+ type(self)._next_pid += 1+ self.pid = type(self)._next_pid+ self.returncode: int | None = None+ self.stdout = asyncio.StreamReader()+ self.stderr = asyncio.StreamReader()+ self.stdin = FakeStdin(self)+ self._waited = asyncio.Event()+ self._responder = responder or _default_responder+ self._config_result = config_result or {+ "config": {},+ "layers": [{"name": "sessionFlags", "config": {}}],+ }++ def on_client_message(self, message: dict[str, Any]) -> None:+ if message.get("method") == "config/read" and isinstance(+ message.get("id"), int+ ):+ _respond(self, message["id"], self._config_result)+ return+ if message.get("method") == "configRequirements/read" and isinstance(+ message.get("id"), int+ ):+ _respond(self, message["id"], {"requirements": None})+ return+ self._responder(self, message)++ def emit(self, message: dict[str, Any]) -> None:+ self.stdout.feed_data(json.dumps(message, separators=(",", ":")).encode("utf-8") + b"\n")++ def emit_stderr(self, text: str) -> None:+ self.stderr.feed_data(text.encode("utf-8") + b"\n")++ def finish(self, returncode: int) -> None:+ if self.returncode is not None:+ return+ self.returncode = returncode+ self.stdout.feed_eof()+ self.stderr.feed_eof()+ self._waited.set()++ def terminate(self) -> None:+ self.finish(-15)++ def kill(self) -> None:+ self.finish(-9)++ async def wait(self) -> int:+ await self._waited.wait()+ assert self.returncode is not None+ return self.returncode+++def _respond(process: FakeProcess, request_id: int, result: Any) -> None:+ asyncio.get_running_loop().call_soon(process.emit, {"id": request_id, "result": result})+++def _respond_handshake(process: FakeProcess, message: dict[str, Any]) -> bool:+ request_id = message.get("id")+ if not isinstance(request_id, int):+ return False+ if message.get("method") == "initialize":+ _respond(process, request_id, {"userAgent": "fake"})+ return True+ if message.get("method") == "account/read":+ _respond(+ process,+ request_id,+ {+ "account": {+ "type": "chatgpt",+ "email": "[email protected]",+ "planType": "plus",+ },+ "requiresOpenaiAuth": True,+ },+ )+ return True+ return False+++def _default_responder(process: FakeProcess, message: dict[str, Any]) -> None:+ if _respond_handshake(process, message):+ return+ request_id = message.get("id")+ if not isinstance(request_id, int):+ return+ method = message.get("method")+ if method == "thread/start":+ _respond(process, request_id, {"thread": {"id": "thread-1"}})+ else:+ _respond(process, request_id, {})+++class SpawnHarness:+ def __init__(+ self,+ monkeypatch: pytest.MonkeyPatch,+ responders: list[Callable[[FakeProcess, dict[str, Any]], None] | None] | None = None,+ probe_responders: list[+ Callable[[FakeProcess, dict[str, Any]], None] | None+ ]+ | None = None,+ *,+ audit_effective_config: bool = False,+ mcp_ids: tuple[str, ...] = (),+ ) -> None:+ self.all_calls: list[tuple[tuple[Any, ...], dict[str, Any]]] = []+ self.calls: list[tuple[tuple[Any, ...], dict[str, Any]]] = []+ self.all_processes: list[FakeProcess] = []+ self.processes: list[FakeProcess] = []+ self.probe_processes: list[FakeProcess] = []+ self.all_trees: list[FakeProcessTree] = []+ self.trees: list[FakeProcessTree] = []+ self.probe_trees: list[FakeProcessTree] = []+ self._responders = list(responders or [])+ self._probe_responders = list(probe_responders or [])+ self._pending_tree: FakeProcessTree | None = None+ self._spawn_count = 0+ self.codex_home = Path("C:/isolated-jarvis-codex-voice-test")++ capability = CodexAppServerCapability(+ available=True,+ chatgpt_authenticated=True,+ binary_path="codex-test",+ version="codex-test 1.0",+ reason="ready",+ )+ monkeypatch.setattr(transport, "_read_codex_capability", lambda _binary: capability)++ def make_tree(_name: str) -> FakeProcessTree:+ tree = FakeProcessTree()+ self.all_trees.append(tree)+ self._pending_tree = tree+ return tree++ async def spawn(*args: Any, **kwargs: Any) -> FakeProcess:+ self._spawn_count += 1+ self.all_calls.append((args, kwargs))+ responder = self._responders.pop(0) if self._responders else None+ session_config: dict[str, Any] = {}+ user_config = {+ "mcp_servers": {+ server_id: {"enabled": True} for server_id in mcp_ids+ }+ }+ process = FakeProcess(+ responder,+ config_result={+ "config": {},+ "layers": [+ {"name": "sessionFlags", "config": session_config},+ {"name": "user", "config": user_config},+ ],+ },+ )+ self.all_processes.append(process)+ tree = self._pending_tree+ assert tree is not None+ self._pending_tree = None+ self.calls.append((args, kwargs))+ self.processes.append(process)+ self.trees.append(tree)+ return process++ monkeypatch.setattr(transport, "make_process_tree", make_tree)+ monkeypatch.setattr(transport.asyncio, "create_subprocess_exec", spawn)+ monkeypatch.setattr(+ transport,+ "_validated_subscription_home",+ lambda **_kwargs: self.codex_home,+ )+ if not audit_effective_config:+ monkeypatch.setattr(+ CodexAppServerClient,+ "_audit_effective_config",+ lambda *_args, **_kwargs: None,+ )+ monkeypatch.setattr(+ CodexAppServerClient,+ "_audit_thread_start_response",+ lambda *_args, **_kwargs: None,+ )+++async def test_lazy_start_handshake_scrubs_api_billing_environment_and_reaps_tree(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ selected_home = tmp_path / "selected-codex-account"+ monkeypatch.setenv("CODEX_HOME", str(selected_home))+ monkeypatch.setenv("OPENAI_API_KEY", "must-not-reach-child")+ monkeypatch.setenv("CODEX_API_KEY", "must-not-reach-child")+ monkeypatch.setenv("CODEX_OPENAI_API_KEY", "must-not-reach-child")+ monkeypatch.setenv("JARVIS_REALTIME_OPENAI_API_KEY", "must-not-reach-child")+ monkeypatch.setenv("JARVIS_AGENT_OPENAI_API_KEY", "must-not-reach-child")+ monkeypatch.setenv("ANTHROPIC_API_KEY", "must-not-reach-child")+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "must-not-reach-child")+ monkeypatch.setenv("HTTPS_PROXY", "http://must-not-reach-child.invalid")+ monkeypatch.setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/test/bus")+ monkeypatch.setenv("XDG_RUNTIME_DIR", "/run/user/test")+ harness = SpawnHarness(monkeypatch)+ client = CodexAppServerClient()++ assert harness.calls == []+ assert client.running is False++ await client.ensure_started()++ assert len(harness.calls) == 1+ assert client.ready is True+ argv, kwargs = harness.calls[0]+ assert argv[:5] == (+ "codex-test",+ "app-server",+ "--strict-config",+ "--enable",+ "realtime_conversation",+ )+ argv_text = "\n".join(str(value) for value in argv)+ assert "skills.include_instructions=false" in argv_text+ assert "skills.bundled.enabled=false" in argv_text+ disabled_features = {+ argv[index + 1]+ for index, value in enumerate(argv[:-1])+ if value == "--disable"+ }+ assert "memories" in disabled_features+ assert "memories.use_memories=false" in argv_text+ assert 'cli_auth_credentials_store="file"' in argv+ assert 'experimental_realtime_ws_base_url="https://api.openai.com/v1"' in argv+ assert (+ 'experimental_realtime_webrtc_call_base_url='+ '"https://chatgpt.com/backend-api/codex"'+ ) in argv+ child_env = kwargs["env"]+ for name in transport._OPENAI_BILLING_ENV_NAMES:+ assert name not in child_env+ for name in ("ANTHROPIC_API_KEY", "AWS_SECRET_ACCESS_KEY", "HTTPS_PROXY"):+ assert name not in child_env+ assert child_env["CODEX_HOME"] == str(harness.codex_home)+ assert child_env["CODEX_HOME"] != str(selected_home)+ assert "DBUS_SESSION_BUS_ADDRESS" not in child_env+ assert "XDG_RUNTIME_DIR" not in child_env+ assert child_env["RUST_LOG"] == "warn"+ assert child_env["RUST_BACKTRACE"] == "0"+ assert child_env["CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED"] == "1"+ assert kwargs["creationflags"] & transport.NO_WINDOW_CREATIONFLAGS++ process = harness.processes[0]+ assert process.stdin.messages[0]["method"] == "initialize"+ assert process.stdin.messages[0]["params"]["capabilities"] == {+ "experimentalApi": True,+ "mcpServerOpenaiFormElicitation": False,+ "requestAttestation": False,+ }+ assert process.stdin.messages[1] == {"method": "initialized"}+ assert process.stdin.messages[2]["method"] == "account/read"+ assert process.stdin.messages[2]["params"] == {"refreshToken": False}+ assert process.stdin.messages[3]["method"] == "configRequirements/read"+ assert process.stdin.messages[4]["method"] == "config/read"+ assert harness.probe_processes == []+ assert harness.trees[0].assigned == [process.pid]++ await client.close()++ assert harness.trees[0].closed is True+ assert process.returncode is not None+++async def test_posix_child_inherits_the_profile_lock_descriptor(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(transport.sys, "platform", "linux")+ harness = SpawnHarness(monkeypatch)+ client = CodexAppServerClient()++ await client.ensure_started()++ assert harness.calls[0][1]["pass_fds"] == (91,)+ await client.close()+++async def test_start_refuses_missing_process_containment_before_spawn(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ harness = SpawnHarness(monkeypatch)+ tree = FakeProcessTree()+ tree.supports_containment = False+ monkeypatch.setattr(transport, "make_process_tree", lambda _name: tree)++ async def unexpected_spawn(*_args: Any, **_kwargs: Any) -> FakeProcess:+ pytest.fail("an uncontained Codex process must never be spawned")++ monkeypatch.setattr(+ transport.asyncio,+ "create_subprocess_exec",+ unexpected_spawn,+ )+ client = CodexAppServerClient()++ with pytest.raises(CodexSubscriptionUnavailable, match="containment is unavailable"):+ await client.ensure_started()++ assert harness.all_calls == []+ assert tree.closed is True+ assert client.running is False+++async def test_containment_assignment_failure_kills_child_and_closes_tree(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ harness = SpawnHarness(monkeypatch)++ class FailingAssignmentTree(FakeProcessTree):+ def assign(self, pid: int) -> None:+ super().assign(pid)+ raise OSError("job assignment failed")++ tree = FailingAssignmentTree()++ def make_tree(_name: str) -> FakeProcessTree:+ harness.all_trees.append(tree)+ harness._pending_tree = tree+ return tree++ monkeypatch.setattr(transport, "make_process_tree", make_tree)+ client = CodexAppServerClient()++ with pytest.raises(+ CodexSubscriptionUnavailable,+ match="containment could not be established",+ ):+ await client.ensure_started()++ assert len(harness.all_processes) == 1+ assert tree.assigned == [harness.all_processes[0].pid]+ assert tree.closed is True+ assert harness.all_processes[0].returncode == -9+ assert client.running is False+++async def test_server_reported_api_key_account_fails_before_any_work_request(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def responder(process: FakeProcess, message: dict[str, Any]) -> None:+ request_id = message.get("id")+ if not isinstance(request_id, int):+ return+ if message.get("method") == "initialize":+ _respond(process, request_id, {})+ elif message.get("method") == "account/read":+ _respond(+ process,+ request_id,+ {+ "account": {"type": "apiKey"},+ "requiresOpenaiAuth": True,+ },+ )++ harness = SpawnHarness(monkeypatch, [responder])+ client = CodexAppServerClient()++ with pytest.raises(CodexSubscriptionUnavailable):+ await client.request("thread/start", {})++ methods = [item.get("method") for item in harness.processes[0].stdin.messages]+ assert methods == ["initialize", "initialized", "account/read"]+ assert harness.trees[0].closed is True+ assert client.running is False+++async def test_simultaneous_first_requests_wait_for_one_complete_handshake(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ initialize_seen = asyncio.Event()+ initialize_request: list[tuple[FakeProcess, int]] = []++ def responder(process: FakeProcess, message: dict[str, Any]) -> None:+ request_id = message.get("id")+ if not isinstance(request_id, int):+ return+ method = message.get("method")+ if method == "initialize":+ initialize_request.append((process, request_id))+ initialize_seen.set()+ elif method == "account/read":+ _respond(+ process,+ request_id,+ {+ "account": {"type": "chatgpt", "email": None, "planType": "plus"},+ "requiresOpenaiAuth": True,+ },+ )+ elif method in {"test/first", "test/second"}:+ _respond(process, request_id, {"method": method})++ harness = SpawnHarness(monkeypatch, [responder])+ client = CodexAppServerClient()+ first = asyncio.create_task(client.request("test/first"))+ second = asyncio.create_task(client.request("test/second"))++ await asyncio.wait_for(initialize_seen.wait(), timeout=1.0)+ await asyncio.sleep(0)+ process = harness.processes[0]+ assert client.running is True+ assert client.ready is False+ assert [item["method"] for item in process.stdin.messages] == ["initialize"]++ init_process, init_id = initialize_request[0]+ init_process.emit({"id": init_id, "result": {}})+ first_result, second_result = await asyncio.gather(first, second)++ assert first_result == {"method": "test/first"}+ assert second_result == {"method": "test/second"}+ methods = [item["method"] for item in process.stdin.messages]+ assert methods.count("initialize") == 1+ assert methods[:3] == ["initialize", "initialized", "account/read"]+ assert methods[3:5] == ["configRequirements/read", "config/read"]+ assert set(methods[5:]) == {"test/first", "test/second"}+ assert len(harness.processes) == 1+ assert client.ready is True+ await client.close()+++async def test_concurrent_requests_route_out_of_order_responses_independently(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ held_requests: list[tuple[FakeProcess, dict[str, Any]]] = []+ requests_ready = asyncio.Event()++ def responder(process: FakeProcess, message: dict[str, Any]) -> None:+ if _respond_handshake(process, message):+ return+ if "id" in message:+ held_requests.append((process, message))+ if len(held_requests) >= 2:+ requests_ready.set()++ SpawnHarness(monkeypatch, [responder])+ client = CodexAppServerClient()+ await client.ensure_started()++ first = asyncio.create_task(client.request("test/first"))+ second = asyncio.create_task(client.request("test/second"))+ await asyncio.wait_for(requests_ready.wait(), timeout=1.0)++ second_process, second_message = held_requests[1]+ first_process, first_message = held_requests[0]+ second_process.emit({"id": second_message["id"], "result": {"order": 2}})+ first_process.emit({"id": first_message["id"], "result": {"order": 1}})++ assert await first == {"order": 1}+ assert await second == {"order": 2}+ await client.close()+++async def test_realtime_start_subscribes_before_request_and_returns_answer_sdp(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def responder(process: FakeProcess, message: dict[str, Any]) -> None:+ if _respond_handshake(process, message):+ return+ request_id = message.get("id")+ if not isinstance(request_id, int):+ return+ method = message.get("method")+ if method == "thread/start":+ _respond(process, request_id, {"thread": {"id": "voice-thread"}})+ elif method == "thread/realtime/start":+ # Notifications deliberately arrive before the request response.+ process.emit(+ {+ "method": "thread/realtime/started",+ "params": {+ "threadId": "voice-thread",+ "realtimeSessionId": "rt-1",+ },+ }+ )+ process.emit(+ {+ "method": "thread/realtime/sdp",+ "params": {"threadId": "voice-thread", "sdp": "answer-sdp"},+ }+ )+ _respond(process, request_id, {})++ harness = SpawnHarness(monkeypatch, [responder])+ client = CodexAppServerClient()+ thread = await client.thread_start(base_instructions="Answer directly.")+ assert thread == {"thread": {"id": "voice-thread"}}++ full_stream = client.subscribe("voice-thread")+ result = await client.realtime_start(+ "voice-thread",+ offer_sdp="offer-sdp",+ model="explicit-realtime-model",+ include_startup_context=False,+ client_managed_handoffs=True,+ )++ assert result.response == {}+ assert result.answer_sdp == "answer-sdp"+ assert (await full_stream.get(0.1)).method == "thread/realtime/started"+ assert (await full_stream.get(0.1)).method == "thread/realtime/sdp"++ messages = harness.processes[0].stdin.messages+ thread_params = next(+ item["params"] for item in messages if item.get("method") == "thread/start"+ )+ assert thread_params["approvalPolicy"] == "never"+ assert thread_params["sandbox"] == "read-only"+ assert thread_params["environments"] == []+ assert thread_params["dynamicTools"] is None+ assert thread_params["ephemeral"] is True+ assert Path(thread_params["cwd"]).name.startswith("jarvis-codex-voice-")++ realtime_params = next(+ item["params"] for item in messages if item.get("method") == "thread/realtime/start"+ )+ assert realtime_params["transport"] == {"type": "webrtc", "sdp": "offer-sdp"}+ assert realtime_params["model"] == "explicit-realtime-model"+ assert realtime_params["includeStartupContext"] is False+ assert realtime_params["clientManagedHandoffs"] is True++ full_stream.close()+ await client.close()+++async def test_audio_append_uses_protocol_chunk_shape(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ harness = SpawnHarness(monkeypatch)+ client = CodexAppServerClient()++ await client.realtime_append_audio(+ "thread-a",+ data="AAEC",+ sample_rate=24_000,+ num_channels=1,+ samples_per_channel=2,+ item_id="audio-1",+ )++ message = next(+ item+ for item in harness.processes[0].stdin.messages+ if item.get("method") == "thread/realtime/appendAudio"+ )+ assert message["params"] == {+ "threadId": "thread-a",+ "audio": {+ "data": "AAEC",+ "sampleRate": 24_000,+ "numChannels": 1,+ "samplesPerChannel": 2,+ "itemId": "audio-1",+ },+ }+ await client.close()+++async def test_notification_queue_overflow_fails_fast_without_silent_audio_drop(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ harness = SpawnHarness(monkeypatch)+ client = CodexAppServerClient()+ await client.ensure_started()+ subscription = client.subscribe("audio-thread", max_queue_size=1)+ process = harness.processes[0]++ process.emit(+ {+ "method": "thread/realtime/outputAudio/delta",+ "params": {"threadId": "audio-thread", "delta": "first"},+ }+ )+ process.emit(+ {+ "method": "thread/realtime/outputAudio/delta",+ "params": {"threadId": "audio-thread", "delta": "second"},+ }+ )++ with pytest.raises(CodexNotificationOverflow):+ await subscription.get(timeout_s=0.2)+ assert "audio-thread" not in client._subscriptions+ await client.close()+++async def test_server_initiated_actions_are_denied_without_logging_params(+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ harness = SpawnHarness(monkeypatch)+ client = CodexAppServerClient()+ await client.ensure_started()+ process = harness.processes[0]+ caplog.set_level("DEBUG", logger=transport.__name__)++ process.emit(+ {+ "id": "approval-1",+ "method": "item/commandExecution/requestApproval",+ "params": {"command": "contains-private-prompt"},+ }+ )+ process.emit(+ {+ "id": "tool-1",+ "method": "item/tool/call",+ "params": {"arguments": {"secret": "contains-private-prompt"}},+ }+ )+ process.emit(+ {+ "id": "unknown-1",+ "method": "unknown/request",+ "params": {"private": "contains-private-prompt"},+ }+ )+ process.emit_stderr("[email protected] bearer-secret contains-private-prompt")+ await asyncio.sleep(0.02)++ responses = {item.get("id"): item for item in process.stdin.messages}+ assert responses["approval-1"]["result"] == {"decision": "decline"}+ assert responses["tool-1"]["result"] == {"contentItems": [], "success": False}+ assert responses["unknown-1"]["error"]["code"] == -32000+ assert "contains-private-prompt" not in caplog.text+ assert "[email protected]" not in caplog.text+ assert "content redacted" in caplog.text+ await client.close()+++async def test_timeout_is_bounded_and_rpc_error_message_is_redacted(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ held: list[tuple[FakeProcess, dict[str, Any]]] = []+ second_request_ready = asyncio.Event()++ def responder(process: FakeProcess, message: dict[str, Any]) -> None:+ if _respond_handshake(process, message):+ return+ if "id" in message:+ held.append((process, message))+ if len(held) >= 2:+ second_request_ready.set()++ SpawnHarness(monkeypatch, [responder])+ client = CodexAppServerClient(request_timeout_s=0.01)+ await client.ensure_started()++ with pytest.raises(CodexAppServerTimeout):+ await client.request("test/timeout")+ assert client._pending == {}++ error_task = asyncio.create_task(client.request("test/error", timeout_s=1.0))+ await asyncio.wait_for(second_request_ready.wait(), timeout=1.0)+ process, message = held[-1]+ process.emit(+ {+ "id": message["id"],+ "error": {"code": 418, "message": "[email protected] bearer-secret"},+ }+ )+ with pytest.raises(CodexAppServerRPCError) as exc_info:+ await error_task+ assert exc_info.value.code == 418+ assert "[email protected]" not in str(exc_info.value)+ assert "bearer-secret" not in str(exc_info.value)+ await client.close()+++async def test_process_death_fails_pending_and_subscribers_then_next_request_restarts(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ held: list[tuple[FakeProcess, dict[str, Any]]] = []+ request_ready = asyncio.Event()++ def first_responder(process: FakeProcess, message: dict[str, Any]) -> None:+ if _respond_handshake(process, message):+ return+ if "id" in message:+ held.append((process, message))+ request_ready.set()++ harness = SpawnHarness(monkeypatch, [first_responder, None])+ client = CodexAppServerClient()+ await client.ensure_started()+ subscription = client.subscribe("thread-death")+ pending = asyncio.create_task(client.request("test/pending", timeout_s=1.0))+ await asyncio.wait_for(request_ready.wait(), timeout=1.0)++ harness.processes[0].finish(9)+ with pytest.raises(CodexAppServerDisconnected):+ await pending+ with pytest.raises(CodexAppServerDisconnected):+ await subscription.get(0.1)++ assert await client.request("test/after-restart") == {}+ assert len(harness.processes) == 2+ assert harness.trees[0].closed is True+ await client.close()+++def test_capability_reads_only_the_dedicated_file_backed_profile(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.codex_auth as auth_module++ class FakeAuthService:+ constructor: tuple[object, dict[str, object]] | None = None+ login_result = (False, "unknown")++ def __init__(self, binary: str | None, **kwargs: object) -> None:+ type(self).constructor = (binary, kwargs)++ def _resolve_binary(self) -> str:+ return "codex-test"++ def _probe_version(self, _binary: str) -> str:+ return "codex-test 1.0"++ def login_status(self) -> tuple[bool, str]:+ return type(self).login_result++ home = tmp_path / "dedicated-profile"+ home.mkdir()+ monkeypatch.setattr(auth_module, "CodexAuthService", FakeAuthService)+ monkeypatch.setattr(transport, "codex_subscription_home", lambda: home)+ monkeypatch.setattr(+ transport,+ "_trusted_native_codex_binary",+ lambda binary, _version: binary,+ )+ monkeypatch.setattr(+ transport,+ "_validated_subscription_home",+ lambda **_kwargs: home,+ )+ capability = transport._read_codex_capability(None)+ assert capability.available is True+ assert capability.chatgpt_authenticated is False+ assert "subscription-voice login" in capability.reason+ assert FakeAuthService.constructor is not None+ _binary, kwargs = FakeAuthService.constructor+ assert kwargs["codex_home"] == home+ assert kwargs["force_file_auth_store"] is True+ assert kwargs["isolate_openai_environment"] is True++ # Opaque invalid bytes deliberately prove the snapshot checks only safe+ # CLI status and never parses or decodes token contents itself.+ (home / "auth.json").write_bytes(b"not-json-and-never-read")+ FakeAuthService.login_result = (True, "chatgpt")+ capability = transport._read_codex_capability(None)+ assert capability.available is True+ assert capability.chatgpt_authenticated is True+++def test_capability_revalidates_profile_after_login_status_probe(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.codex_auth as auth_module++ class FakeAuthService:+ def __init__(self, *_args: object, **_kwargs: object) -> None:+ pass++ def _resolve_binary(self) -> str:+ return "codex-test"++ def _probe_version(self, _binary: str) -> str:+ return "codex-cli 0.146.0"++ def login_status(self) -> tuple[bool, str]:+ return True, "chatgpt"++ validations = 0++ def validate_home(**_kwargs: object) -> Path:+ nonlocal validations+ validations += 1+ if validations == 2:+ raise CodexSubscriptionUnavailable("profile changed during status")+ return tmp_path++ monkeypatch.setattr(auth_module, "CodexAuthService", FakeAuthService)+ monkeypatch.setattr(+ transport,+ "_trusted_native_codex_binary",+ lambda binary, _version: binary,+ )+ monkeypatch.setattr(transport, "_validated_subscription_home", validate_home)++ capability = transport._read_codex_capability(None)++ assert validations == 2+ assert capability.available is False+ assert capability.chatgpt_authenticated is False+ assert capability.reason == "profile changed during status"+++def test_missing_dedicated_profile_is_a_login_required_capability(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import jarvis.codex_auth as auth_module++ class FakeAuthService:+ def __init__(self, *_args: object, **_kwargs: object) -> None:+ pass++ def _resolve_binary(self) -> str:+ return "codex-test"++ def _probe_version(self, _binary: str) -> str:+ return "codex-cli 0.146.0"++ monkeypatch.setattr(auth_module, "CodexAuthService", FakeAuthService)+ monkeypatch.setattr(+ transport,+ "_trusted_native_codex_binary",+ lambda binary, _version: binary,+ )++ def missing_profile(**_kwargs: object) -> Path:+ raise transport.CodexSubscriptionProfileMissing("profile missing")++ monkeypatch.setattr(+ transport,+ "_validated_subscription_home",+ missing_profile,+ )++ capability = transport._read_codex_capability(None)++ assert capability.available is False+ assert capability.version == "codex-cli 0.146.0"+ assert capability.reason_code == "login_required"+++def test_public_auth_snapshot_uses_live_state_without_cli_probe(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ client = CodexAppServerClient("codex-test")+ client._process = SimpleNamespace(returncode=None) # type: ignore[assignment]+ client._ready = True+ client._trusted_binary_path = "trusted-codex-test"+ owner_loop = asyncio.new_event_loop()+ monkeypatch.setattr(+ transport,+ "_shared_clients",+ {("codex-test", owner_loop): client},+ )+ monkeypatch.setattr(transport, "_subscription_active_transports", {id(client)})+ monkeypatch.setattr(+ transport,+ "_read_codex_capability",+ lambda _binary: pytest.fail("live status must not spawn a Codex CLI probe"),+ )++ capability = transport.codex_subscription_auth_snapshot(None)+ owner_loop.close()++ assert capability.available is True+ assert capability.chatgpt_authenticated is True+ assert capability.binary_path == "trusted-codex-test"+ assert capability.reason_code == "ready"+++def test_public_auth_snapshot_holds_profile_owner_for_entire_probe(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ started = threading.Event()+ release = threading.Event()+ process_lock = FakeProfileProcessLock()+ reads: list[str | None] = []+ results: list[CodexAppServerCapability] = []++ monkeypatch.setattr(+ transport,+ "_acquire_subscription_process_lock",+ lambda: process_lock,+ )++ def slow_probe(binary: str | None) -> CodexAppServerCapability:+ reads.append(binary)+ assert transport._subscription_profile_mutating is True+ assert transport._subscription_mutation_process_lock is process_lock+ assert process_lock.closed is False+ started.set()+ assert release.wait(timeout=2.0)+ return CodexAppServerCapability(+ available=True,+ chatgpt_authenticated=True,+ binary_path="codex-test",+ version="codex-cli 0.146.0",+ reason="ready",+ reason_code="ready",+ )++ monkeypatch.setattr(transport, "_read_codex_capability", slow_probe)+ worker = threading.Thread(+ target=lambda: results.append(+ transport.codex_subscription_auth_snapshot("codex-test")+ )+ )+ worker.start()+ assert started.wait(timeout=1.0)++ concurrent = transport.codex_subscription_auth_snapshot("codex-test")++ assert concurrent.reason_code == "setup_invalid"+ assert reads == ["codex-test"]+ assert process_lock.closed is False+ release.set()+ worker.join(timeout=2.0)++ assert worker.is_alive() is False+ assert results[0].reason_code == "ready"+ assert process_lock.closed is True+ assert transport._subscription_profile_mutating is False+ assert transport._subscription_mutation_process_lock is None+++async def test_capability_worker_keeps_profile_reserved_until_it_finishes(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ started = threading.Event()+ release = threading.Event()++ def slow_probe(_binary: str | None) -> CodexAppServerCapability:+ started.set()+ assert release.wait(timeout=2.0)+ return CodexAppServerCapability(+ available=False,+ chatgpt_authenticated=False,+ binary_path=None,+ version=None,+ reason="not connected",+ )++ monkeypatch.setattr(transport, "_read_codex_capability", slow_probe)+ monkeypatch.setattr(transport, "_subscription_profile_mutating", False)+ monkeypatch.setattr(transport, "_subscription_active_transports", set())+ client = CodexAppServerClient()+ start_task = asyncio.create_task(client.ensure_started())++ assert await asyncio.to_thread(started.wait, 1.0)+ await asyncio.sleep(0.05)+ assert start_task.done() is False+ assert id(client) in transport._subscription_active_transports++ release.set()+ with pytest.raises(CodexSubscriptionUnavailable, match="not connected"):+ await asyncio.wait_for(start_task, timeout=1.0)+ assert id(client) not in transport._subscription_active_transports+++async def test_advisory_file_status_still_reaches_live_account_read(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ harness = SpawnHarness(monkeypatch)+ monkeypatch.setattr(+ transport,+ "_read_codex_capability",+ lambda _binary: CodexAppServerCapability(+ available=True,+ chatgpt_authenticated=False,+ binary_path="codex-test",+ version="codex-test 1.0",+ reason="auth file absent",+ ),+ )+ client = CodexAppServerClient()++ await client.ensure_started()++ assert client.ready is True+ assert any(+ message.get("method") == "account/read"+ for process in harness.all_processes+ for message in process.stdin.messages+ )+ await client.close()+++async def test_shared_client_ignores_active_codex_account_profiles(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.agent_accounts as accounts++ monkeypatch.setattr(+ accounts,+ "active_account",+ lambda _platform: pytest.fail("active Codex accounts must not be read"),+ )+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / "ambient-profile"))+ await transport.close_shared_codex_app_servers()++ client = transport.get_shared_codex_app_server("codex-test")++ assert client._binary_path == "codex-test"+ assert client._child_environment == {}+ await transport.close_shared_codex_app_servers()+++async def test_shared_clients_are_scoped_to_their_event_loop(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ SpawnHarness(monkeypatch)+ await transport.close_shared_codex_app_servers()+ current = transport.get_shared_codex_app_server("codex-test")++ async def acquire_on_foreign_loop() -> int:+ loop = asyncio.get_running_loop()+ client = transport.get_shared_codex_app_server("codex-test")+ identifier = id(client)+ await client.close()+ with transport._shared_clients_lock:+ transport._shared_clients.pop(("codex-test", loop), None)+ return identifier++ foreign_identifier = await asyncio.to_thread(+ lambda: asyncio.run(acquire_on_foreign_loop())+ )++ assert foreign_identifier != id(current)+ await transport.close_shared_codex_app_servers()+++async def test_client_rejects_use_from_a_foreign_event_loop() -> None:+ client = CodexAppServerClient()+ client._owner_loop = asyncio.get_running_loop()++ async def close_on_foreign_loop() -> BaseException | None:+ try:+ await client.close()+ except BaseException as exc: # noqa: BLE001 - return for parent assertion+ return exc+ return None++ error = await asyncio.to_thread(lambda: asyncio.run(close_on_foreign_loop()))++ assert isinstance(error, CodexSubscriptionUnavailable)+ assert "cannot cross event loops" in str(error)+ await client.close()+++async def test_second_client_cannot_share_the_subscription_profile(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ harness = SpawnHarness(monkeypatch)+ first = CodexAppServerClient()+ second = CodexAppServerClient()++ await first.ensure_started()+ with pytest.raises(CodexSubscriptionUnavailable, match="another client"):+ await second.ensure_started()++ assert len(harness.processes) == 1+ await first.close()+ await second.ensure_started()+ assert len(harness.processes) == 2+ await second.close()+++async def test_transport_holds_process_lock_until_close_and_blocks_logout(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ SpawnHarness(monkeypatch)+ profile_lock = FakeProfileProcessLock()+ monkeypatch.setattr(+ transport,+ "_acquire_subscription_process_lock",+ lambda: profile_lock,+ )+ client = CodexAppServerClient()++ await client.ensure_started()+ assert profile_lock.closed is False+ with pytest.raises(CodexSubscriptionUnavailable, match="still active"):+ transport.logout_codex_subscription()++ await client.close()+ assert profile_lock.closed is True+++def test_dedicated_profile_rejects_agents_and_other_artifacts(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.core.paths as paths++ monkeypatch.setattr(paths, "user_data_dir", lambda: tmp_path)+ home = transport._prepare_subscription_login_home()+ (home / "AGENTS.md").write_text("Hostile instructions", encoding="utf-8")++ with pytest.raises(CodexSubscriptionUnavailable, match="configuration"):+ transport._validated_subscription_home(create=False, require_marker=True)+++async def test_startup_refuses_nonempty_user_mcp_layer(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ harness = SpawnHarness(+ monkeypatch,+ mcp_ids=("hostile.server", "second"),+ audit_effective_config=True,+ )+ client = CodexAppServerClient()++ with pytest.raises(CodexSubscriptionUnavailable, match="non-empty"):+ await client.ensure_started()++ assert len(harness.all_calls) == 1+ assert harness.processes[0].returncode is not None+ await client.close()+++def _safe_audit_result(+ client: CodexAppServerClient,+) -> dict[str, Any]:+ provider_id = client._transport_provider_id+ version = "sha256:test-session-flags"+ session = {+ "analytics": {"enabled": False},+ "approval_policy": "never",+ "cli_auth_credentials_store": "file",+ "chatgpt_base_url": transport._OFFICIAL_CHATGPT_BASE,+ "experimental_compact_prompt_file": client._compact_prompt_file(),+ "experimental_realtime_start_instructions": "",+ "experimental_realtime_webrtc_call_base_url": (+ transport._OFFICIAL_CHATGPT_CODEX_BASE+ ),+ "experimental_realtime_ws_backend_prompt": "",+ "experimental_realtime_ws_base_url": (+ transport._OFFICIAL_OPENAI_REALTIME_BASE+ ),+ "features": {+ **{+ feature: False+ for feature in transport._DISABLED_APP_SERVER_FEATURES+ },+ "realtime_conversation": True,+ },+ "history": {"persistence": "none"},+ "include_apps_instructions": False,+ "include_collaboration_mode_instructions": False,+ "include_environment_context": False,+ "include_permissions_instructions": False,+ "log_dir": client._log_dir(),+ "memories": {+ "dedicated_tools": False,+ "generate_memories": False,+ "use_memories": False,+ },+ "model_catalog_json": client._model_catalog_file(),+ "model_instructions_file": client._safe_instructions_file(),+ "model_provider": provider_id,+ "model_providers": {+ provider_id: {+ "base_url": client._provider_sink_base_url(),+ "name": "OpenAI ChatGPT subscription voice",+ "request_max_retries": 0,+ "requires_openai_auth": True,+ "stream_max_retries": 0,+ "supports_standalone_web_search": False,+ "supports_websockets": False,+ "wire_api": "responses",+ }+ },+ "notify": [],+ "openai_base_url": transport._OFFICIAL_OPENAI_API_BASE,+ "orchestrator": {+ "mcp": {"enabled": False},+ "skills": {"enabled": False},+ },+ "otel": {+ "exporter": "none",+ "log_user_prompt": False,+ "metrics_exporter": "none",+ "trace_exporter": "none",+ },+ "project_doc_max_bytes": 0,+ "sandbox_mode": "read-only",+ "sqlite_home": client._sqlite_home(),+ "skills": {+ "bundled": {"enabled": False},+ "include_instructions": False,+ },+ "tools": {"web_search": False},+ }+ if sys.platform == "win32":+ session["windows"] = {"sandbox": "unelevated"}++ def leaf_paths(value: Any, prefix: tuple[str, ...] = ()) -> list[str]:+ if isinstance(value, dict):+ paths: list[str] = []+ for key, child in value.items():+ paths.extend(leaf_paths(child, (*prefix, str(key))))+ return paths+ if value == []:+ return []+ return [".".join(prefix)]++ origin = {+ "name": {"type": "sessionFlags"},+ "version": version,+ }+ return {+ "config": {+ "analytics": {"enabled": False},+ "approval_policy": "never",+ "model_provider": provider_id,+ "sandbox_mode": "read-only",+ },+ "layers": [+ {+ "name": {"type": "sessionFlags"},+ "version": version,+ "config": session,+ },+ {+ "name": {"type": "user", "file": "C:/isolated/config.toml"},+ "version": "sha256:empty",+ "config": {},+ },+ ],+ "origins": {path: dict(origin) for path in leaf_paths(session)},+ }+++def test_effective_config_audit_requires_empty_host_layers_and_session_origins() -> None:+ client = CodexAppServerClient()+ client._workspace = transport._create_safe_transport_workspace()+ client._sink_base_url = "http://127.0.0.1:43123/v1"+ try:+ result = _safe_audit_result(client)+ client._audit_effective_config(result)++ result["layers"][1]["config"] = {"mcp_servers": {"hostile": {}}}+ with pytest.raises(CodexSubscriptionUnavailable, match="non-empty"):+ client._audit_effective_config(result)++ result["layers"][1]["config"] = {}+ result["origins"]["approval_policy"] = {+ "name": {"type": "user", "file": "C:/hostile/config.toml"},+ "version": "sha256:hostile",+ }+ with pytest.raises(CodexSubscriptionUnavailable, match="unapproved"):+ client._audit_effective_config(result)+ finally:+ shutil.rmtree(client._workspace.root, ignore_errors=True)+++async def test_dedicated_home_is_revalidated_before_thread_start(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ harness = SpawnHarness(monkeypatch)+ validations = 0++ def validate_home(**_kwargs: object) -> Path:+ nonlocal validations+ validations += 1+ if validations >= 3:+ raise CodexSubscriptionUnavailable(+ "The dedicated Codex voice profile contains configuration."+ )+ return harness.codex_home++ monkeypatch.setattr(transport, "_validated_subscription_home", validate_home)+ client = CodexAppServerClient()++ with pytest.raises(CodexSubscriptionUnavailable, match="configuration"):+ await client.thread_start()++ assert not any(+ message.get("method") == "thread/start"+ for message in harness.processes[0].stdin.messages+ )+ await client.close()+++async def test_account_is_rechecked_immediately_before_every_thread_start(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ account_reads = 0++ def responder(process: FakeProcess, message: dict[str, Any]) -> None:+ nonlocal account_reads+ request_id = message.get("id")+ if not isinstance(request_id, int):+ return+ method = message.get("method")+ if method == "initialize":+ _respond(process, request_id, {})+ elif method == "account/read":+ account_reads += 1+ account_type = "chatgpt" if account_reads <= 2 else "apiKey"+ _respond(+ process,+ request_id,+ {+ "account": {+ "type": account_type,+ "planType": "plus" if account_type == "chatgpt" else None,+ },+ "requiresOpenaiAuth": True,+ },+ )+ elif method == "thread/start":+ _respond(process, request_id, {"thread": {"id": "thread-1"}})++ harness = SpawnHarness(monkeypatch, [responder])+ client = CodexAppServerClient()++ await client.thread_start()+ with pytest.raises(CodexSubscriptionUnavailable):+ await client.thread_start()++ methods = [item.get("method") for item in harness.processes[0].stdin.messages]+ assert methods.count("account/read") == 3+ assert methods.count("thread/start") == 1+++def test_config_requirements_must_be_absent() -> None:+ CodexAppServerClient._audit_config_requirements({"requirements": None})++ with pytest.raises(CodexSubscriptionUnavailable, match="managed"):+ CodexAppServerClient._audit_config_requirements(+ {"requirements": {"network": {"enabled": True}}}+ )+++def test_thread_start_response_is_audited_as_read_only_and_ephemeral() -> None:+ client = CodexAppServerClient()+ client._workspace = transport._create_safe_transport_workspace()+ try:+ cwd = client._safe_thread_cwd()+ result = {+ "approvalPolicy": "never",+ "cwd": cwd,+ "instructionSources": [],+ "model": "gpt-5.1-codex",+ "modelProvider": client._transport_provider_id,+ "sandbox": {"type": "readOnly", "networkAccess": False},+ "thread": {+ "cwd": cwd,+ "ephemeral": True,+ "id": "thread-safe",+ "modelProvider": client._transport_provider_id,+ },+ }+ client._audit_thread_start_response(result)++ result["instructionSources"] = ["C:/hostile/AGENTS.md"]+ with pytest.raises(CodexSubscriptionUnavailable, match="unsafe"):+ client._audit_thread_start_response(result)++ result["instructionSources"] = []+ result["sandbox"] = {"type": "readOnly", "networkAccess": True}+ with pytest.raises(CodexSubscriptionUnavailable, match="unsafe"):+ client._audit_thread_start_response(result)+ finally:+ shutil.rmtree(client._workspace.root, ignore_errors=True)++[email protected]("plan", ["free", "go", "plus", "pro", "prolite"])+async def test_personal_chatgpt_plan_is_accepted(plan: str) -> None:+ client = CodexAppServerClient()++ async def account_read(*_args: object, **_kwargs: object) -> dict[str, Any]:+ return {+ "account": {"type": "chatgpt", "planType": plan},+ "requiresOpenaiAuth": True,+ }++ client._request_live = account_read # type: ignore[method-assign]+ await client._verify_live_chatgpt_account()++[email protected]("plan", [None, "team", "business", "enterprise", "edu"])+async def test_managed_or_unknown_chatgpt_plan_is_refused(plan: str | None) -> None:+ client = CodexAppServerClient()++ async def account_read(*_args: object, **_kwargs: object) -> dict[str, Any]:+ return {+ "account": {"type": "chatgpt", "planType": plan},+ "requiresOpenaiAuth": True,+ }++ client._request_live = account_read # type: ignore[method-assign]+ with pytest.raises(CodexSubscriptionUnavailable, match="personal"):+ await client._verify_live_chatgpt_account()+++async def test_account_requires_the_openai_authenticated_provider() -> None:+ client = CodexAppServerClient()++ async def account_read(*_args: object, **_kwargs: object) -> dict[str, Any]:+ return {+ "account": {"type": "chatgpt", "planType": "plus"},+ "requiresOpenaiAuth": False,+ }++ client._request_live = account_read # type: ignore[method-assign]+ with pytest.raises(CodexSubscriptionUnavailable, match="authentication"):+ await client._verify_live_chatgpt_account()+++async def test_realtime_start_forces_handoff_and_startup_context_boundaries(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ harness = SpawnHarness(monkeypatch)+ client = CodexAppServerClient()+ await client.ensure_started()++ await client.realtime_start(+ "thread-1",+ prompt="hostile prompt",+ include_startup_context=True,+ client_managed_handoffs=False,+ )+ params = next(+ frame["params"]+ for frame in harness.processes[0].stdin.messages+ if frame.get("method") == "thread/realtime/start"+ )+ assert params["prompt"] == ""+ assert params["includeStartupContext"] is False+ assert params["clientManagedHandoffs"] is True++ with pytest.raises(CodexSubscriptionUnavailable, match="Custom"):+ await client.realtime_start("thread-1", extra={"unsafe": True})+ await client.close()+++def test_native_codex_version_and_hash_are_both_required(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ binary = tmp_path / "codex.exe"+ binary.write_bytes(b"official-test-binary")+ monkeypatch.setattr(transport.sys, "platform", "win32")+ monkeypatch.setattr(transport, "_normalized_machine", lambda: "x86_64")+ monkeypatch.setattr(+ transport,+ "_TRUSTED_CODEX_TARGETS",+ {+ ("win32", "x86_64"): (+ "win32-x64",+ "x86_64-pc-windows-msvc",+ "codex.exe",+ "approved-hash",+ )+ },+ )+ monkeypatch.setattr(transport, "_sha256_file", lambda _path: "approved-hash")++ assert (+ transport._trusted_native_codex_binary(+ str(binary), transport._SUPPORTED_CODEX_VERSION+ )+ == str(binary.resolve())+ )+ with pytest.raises(CodexSubscriptionUnavailable, match="requires Codex"):+ transport._trusted_native_codex_binary(str(binary), "codex-cli 0.147.0")++ monkeypatch.setattr(transport, "_sha256_file", lambda _path: "wrong-hash")+ with pytest.raises(CodexSubscriptionUnavailable, match="approved build"):+ transport._trusted_native_codex_binary(+ str(binary), transport._SUPPORTED_CODEX_VERSION+ )++[email protected]("platform", ["darwin", "linux"])+def test_subscription_transport_refuses_posix_without_parent_death_containment(+ monkeypatch: pytest.MonkeyPatch,+ platform: str,+) -> None:+ monkeypatch.setattr(transport.sys, "platform", platform)++ with pytest.raises(+ transport.CodexSubscriptionContainmentUnavailable,+ match="kill-on-parent-exit",+ ):+ transport._trusted_native_codex_binary(+ "/unused/codex",+ transport._SUPPORTED_CODEX_VERSION,+ )+++def test_dedicated_profile_rejects_hardlinked_auth_file(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.core.paths as paths++ monkeypatch.setattr(paths, "user_data_dir", lambda: tmp_path / "data")+ home = transport._prepare_subscription_login_home()+ outside = tmp_path / "outside-auth.json"+ outside.write_text("{}", encoding="utf-8")+ os.link(outside, home / "auth.json")++ with pytest.raises(CodexSubscriptionUnavailable, match="linked credential"):+ transport._validated_subscription_home(create=False, require_marker=True)++[email protected](os.name != "nt", reason="Windows credential DACL contract")+def test_dedicated_profile_rejects_permissive_windows_auth_acl(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import ntsecuritycon+ import win32api+ import win32con+ import win32security++ import jarvis.core.paths as paths++ monkeypatch.setattr(paths, "user_data_dir", lambda: tmp_path / "data")+ home = transport._prepare_subscription_login_home()+ auth = home / "auth.json"+ auth.write_text("{}", encoding="utf-8")++ token = win32security.OpenProcessToken(+ win32api.GetCurrentProcess(),+ win32con.TOKEN_QUERY,+ )+ current_user = win32security.GetTokenInformation(+ token,+ win32security.TokenUser,+ )[0]+ everyone = win32security.CreateWellKnownSid(win32security.WinWorldSid, None)+ dacl = win32security.ACL()+ dacl.AddAccessAllowedAce(+ win32security.ACL_REVISION,+ ntsecuritycon.FILE_ALL_ACCESS,+ current_user,+ )+ dacl.AddAccessAllowedAce(+ win32security.ACL_REVISION,+ ntsecuritycon.FILE_GENERIC_READ,+ everyone,+ )+ win32security.SetNamedSecurityInfo(+ str(auth),+ win32security.SE_FILE_OBJECT,+ win32security.DACL_SECURITY_INFORMATION+ | win32security.PROTECTED_DACL_SECURITY_INFORMATION,+ None,+ None,+ dacl,+ None,+ )++ with pytest.raises(CodexSubscriptionUnavailable, match="not owner-only"):+ transport._validated_subscription_home(create=False, require_marker=True)++[email protected](os.name != "nt", reason="Windows workspace DACL contract")+def test_transport_workspace_has_exact_owner_only_windows_dacl() -> None:+ import ntsecuritycon+ import win32api+ import win32con+ import win32security++ workspace = transport._create_safe_transport_workspace()+ try:+ descriptor = win32security.GetNamedSecurityInfo(+ str(workspace.root),+ win32security.SE_FILE_OBJECT,+ win32security.OWNER_SECURITY_INFORMATION+ | win32security.DACL_SECURITY_INFORMATION,+ )+ token = win32security.OpenProcessToken(+ win32api.GetCurrentProcess(),+ win32con.TOKEN_QUERY,+ )+ current_user = win32security.GetTokenInformation(+ token,+ win32security.TokenUser,+ )[0]+ owner = descriptor.GetSecurityDescriptorOwner()+ dacl = descriptor.GetSecurityDescriptorDacl()+ control, _revision = descriptor.GetSecurityDescriptorControl()++ assert win32security.ConvertSidToStringSid(owner) == (+ win32security.ConvertSidToStringSid(current_user)+ )+ assert control & win32security.SE_DACL_PROTECTED+ assert dacl is not None and dacl.GetAceCount() == 1+ ace_type, ace_flags = dacl.GetAce(0)[0]+ access_mask = dacl.GetAce(0)[1]+ trustee = dacl.GetAce(0)[2]+ assert (ace_type, ace_flags) == (+ win32security.ACCESS_ALLOWED_ACE_TYPE,+ win32security.OBJECT_INHERIT_ACE+ | win32security.CONTAINER_INHERIT_ACE,+ )+ assert access_mask == ntsecuritycon.FILE_ALL_ACCESS+ assert win32security.ConvertSidToStringSid(trustee) == (+ win32security.ConvertSidToStringSid(current_user)+ )+ finally:+ shutil.rmtree(workspace.root, ignore_errors=True)++[email protected](os.name != "posix", reason="POSIX workspace mode contract")+def test_transport_workspace_has_owner_only_posix_mode() -> None:+ workspace = transport._create_safe_transport_workspace()+ try:+ metadata = workspace.root.stat()+ assert metadata.st_uid == os.geteuid()+ assert metadata.st_mode & 0o777 == 0o700+ finally:+ shutil.rmtree(workspace.root, ignore_errors=True)+++def test_headless_linux_login_degrades_honestly(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(transport.sys, "platform", "linux")+ monkeypatch.delenv("DISPLAY", raising=False)+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)++ with pytest.raises(CodexSubscriptionUnavailable, match="headless Linux"):+ transport.start_codex_subscription_login()+++def test_exact_windows_codex_runtime_state_is_allowed_and_tampering_is_refused(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.core.paths as paths++ monkeypatch.setattr(paths, "user_data_dir", lambda: tmp_path / "data")+ monkeypatch.setattr(transport.sys, "platform", "win32")+ monkeypatch.setattr(transport, "_normalized_machine", lambda: "x86_64")+ monkeypatch.setattr(+ transport,+ "_TRUSTED_CODEX_TARGETS",+ {+ ("win32", "x86_64"): (+ "win32-x64",+ "x86_64-pc-windows-msvc",+ "codex.exe",+ "approved",+ )+ },+ )+ binary = tmp_path / "codex.exe"+ binary.write_bytes(b"official binary")+ hash_calls: list[Path] = []++ def hash_binary(path: Path) -> str:+ canonical = Path(path).resolve()+ hash_calls.append(canonical)+ return "approved" if canonical == binary.resolve() else "wrong"++ monkeypatch.setattr(transport, "_sha256_file", hash_binary)+ home = transport._prepare_subscription_login_home()+ (home / "installation_id").write_text(+ "8fd4ce9f-0c3d-4502-8ff7-c22a79a11833",+ encoding="utf-8",+ )+ runtime = home / "tmp" / "arg0" / "codex-arg0Ab12Cd"+ runtime.mkdir(parents=True)+ if os.name == "posix":+ os.chmod(runtime.parent, 0o700)+ (runtime / ".lock").write_bytes(b"")+ wrapper = f'@echo off\n"{binary}" --codex-run-as-apply-patch %*\n'+ (runtime / "apply_patch.bat").write_text(wrapper, encoding="utf-8")+ (runtime / "applypatch.bat").write_text(wrapper, encoding="utf-8")++ assert (+ transport._validated_subscription_home(+ create=False,+ require_marker=True,+ trusted_binary_path=str(binary.resolve()),+ )+ == home+ )+ assert hash_calls == [binary.resolve()]++ (runtime / "apply_patch.bat").write_text(+ '@echo off\n"C:\\untrusted.exe" --codex-run-as-apply-patch %*\n',+ encoding="utf-8",+ )+ with pytest.raises(CodexSubscriptionUnavailable, match="untrusted runtime"):+ transport._validated_subscription_home(+ create=False,+ require_marker=True,+ trusted_binary_path=str(binary.resolve()),+ )++[email protected](os.name != "posix", reason="POSIX umask semantics")+def test_installation_id_created_under_umask_077_is_accepted(tmp_path: Path) -> None:+ home = tmp_path / "profile"+ home.mkdir(mode=0o700)+ installation_id = home / "installation_id"+ installation_id.write_text(+ "8fd4ce9f-0c3d-4502-8ff7-c22a79a11833",+ encoding="utf-8",+ )+ installation_id.chmod(0o600)++ transport._validate_codex_runtime_state(home)+++def test_exact_unix_codex_runtime_aliases_must_target_trusted_binary(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.core.paths as paths++ monkeypatch.setattr(paths, "user_data_dir", lambda: tmp_path / "data")+ monkeypatch.setattr(transport.sys, "platform", "linux")+ monkeypatch.setattr(transport, "_normalized_machine", lambda: "x86_64")+ monkeypatch.setattr(+ transport,+ "_TRUSTED_CODEX_TARGETS",+ {+ ("linux", "x86_64"): (+ "linux-x64",+ "x86_64-unknown-linux-musl",+ "codex",+ "approved",+ )+ },+ )+ binary = tmp_path / "codex"+ binary.write_bytes(b"official binary")+ monkeypatch.setattr(+ transport,+ "_sha256_file",+ lambda path: "approved" if Path(path).resolve() == binary.resolve() else "wrong",+ )+ home = transport._prepare_subscription_login_home()+ (home / "installation_id").write_text(+ "8fd4ce9f-0c3d-4502-8ff7-c22a79a11833",+ encoding="utf-8",+ )+ if os.name == "posix":+ os.chmod(home / "installation_id", 0o644)+ runtime = home / "tmp" / "arg0" / "codex-arg0Ab12Cd"+ runtime.mkdir(parents=True)+ if os.name == "posix":+ os.chmod(runtime.parent, 0o700)+ (runtime / ".lock").write_bytes(b"")+ aliases = {+ "apply_patch",+ "applypatch",+ "codex-execve-wrapper",+ "codex-linux-sandbox",+ }+ try:+ for alias in aliases:+ os.symlink(binary, runtime / alias)+ except OSError as exc:+ pytest.skip(f"symlink creation is unavailable: {type(exc).__name__}")++ assert (+ transport._validated_subscription_home(+ create=False,+ require_marker=True,+ trusted_binary_path=str(binary.resolve()),+ )+ == home+ )+ (runtime / "unexpected").write_text("unsafe", encoding="utf-8")+ with pytest.raises(CodexSubscriptionUnavailable, match="unexpected runtime"):+ transport._validated_subscription_home(+ create=False,+ require_marker=True,+ trusted_binary_path=str(binary.resolve()),+ )+++def test_subscription_login_guard_covers_process_and_reaper(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.codex_auth as auth_module++ cleanup_targets: list[Callable[[], None]] = []+ processes: list[object] = []++ class FakeProcess:+ pid = 731++ def wait(self) -> int:+ return 0++ class FakeAuthService:+ def __init__(self, *_args: object, **_kwargs: object) -> None:+ pass++ def start_login(self) -> FakeProcess:+ process = FakeProcess()+ processes.append(process)+ return process++ home = tmp_path / "profile"+ home.mkdir()+ profile_lock = FakeProfileProcessLock()+ monkeypatch.setattr(+ transport,+ "_acquire_subscription_process_lock",+ lambda: profile_lock,+ )+ monkeypatch.setattr(auth_module, "CodexAuthService", FakeAuthService)+ monkeypatch.setattr(+ transport,+ "_launch_subscription_login_reaper",+ cleanup_targets.append,+ )+ monkeypatch.setattr(transport, "_prepare_subscription_login_home", lambda: home)+ capability_reads: list[str | None] = []++ def read_capability(binary: str | None) -> CodexAppServerCapability:+ capability_reads.append(binary)+ authenticated = len(capability_reads) > 1+ return CodexAppServerCapability(+ available=True,+ chatgpt_authenticated=authenticated,+ binary_path="codex-test",+ version="codex-cli 0.146.0",+ reason="ready",+ reason_code="ready" if authenticated else "login_required",+ )++ monkeypatch.setattr(+ transport,+ "_read_codex_capability",+ read_capability,+ )+ monkeypatch.setattr(+ transport,+ "_validated_subscription_home",+ lambda **_kwargs: home,+ )+ monkeypatch.setattr(transport, "_subscription_login_in_flight", False)+ monkeypatch.setattr(transport, "_subscription_login_process", None)+ monkeypatch.setattr(transport, "_subscription_profile_mutating", False)+ monkeypatch.setattr(transport, "_subscription_active_transports", set())++ first = transport.start_codex_subscription_login()+ assert first is processes[0]+ assert capability_reads == [None]+ assert profile_lock.closed is False+ with pytest.raises(CodexSubscriptionUnavailable, match="already in progress"):+ transport.start_codex_subscription_login()+ with pytest.raises(CodexSubscriptionUnavailable, match="login is in progress"):+ transport.logout_codex_subscription()++ cleanup_targets[0]()+ assert capability_reads == [None, "codex-test"]+ assert profile_lock.closed is True+ assert transport._subscription_login_in_flight is False+ assert transport._subscription_login_process is None+++def test_subscription_login_spawn_failure_releases_guard(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.codex_auth as auth_module++ class FakeAuthService:+ def __init__(self, *_args: object, **_kwargs: object) -> None:+ pass++ def start_login(self) -> None:+ raise RuntimeError("terminal unavailable")++ monkeypatch.setattr(auth_module, "CodexAuthService", FakeAuthService)+ monkeypatch.setattr(+ transport,+ "_prepare_subscription_login_home",+ lambda: tmp_path,+ )+ monkeypatch.setattr(+ transport,+ "_read_codex_capability",+ lambda _binary: CodexAppServerCapability(+ True,+ False,+ "codex-test",+ "codex-cli 0.146.0",+ "ready",+ ),+ )+ monkeypatch.setattr(transport, "_subscription_login_in_flight", False)+ monkeypatch.setattr(transport, "_subscription_login_process", None)+ monkeypatch.setattr(transport, "_subscription_profile_mutating", False)+ monkeypatch.setattr(transport, "_subscription_active_transports", set())++ with pytest.raises(CodexSubscriptionUnavailable, match="terminal unavailable"):+ transport.start_codex_subscription_login()+ assert transport._subscription_login_in_flight is False+++def test_subscription_logout_is_idempotent_and_deletes_only_dedicated_auth(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.core.paths as paths++ monkeypatch.setattr(paths, "user_data_dir", lambda: tmp_path / "data")+ monkeypatch.setattr(transport, "_subscription_login_in_flight", False)+ monkeypatch.setattr(transport, "_subscription_profile_mutating", False)+ monkeypatch.setattr(transport, "_subscription_active_transports", set())+ profile_locks: list[FakeProfileProcessLock] = []++ def acquire_lock() -> FakeProfileProcessLock:+ lock = FakeProfileProcessLock()+ profile_locks.append(lock)+ return lock++ monkeypatch.setattr(+ transport,+ "_acquire_subscription_process_lock",+ acquire_lock,+ )++ assert transport.logout_codex_subscription() == (True, None)+ assert profile_locks[-1].closed is True++ home = transport._prepare_subscription_login_home()+ auth = home / "auth.json"+ auth.write_text("opaque credentials", encoding="utf-8")+ assert transport.logout_codex_subscription("missing-codex") == (True, None)+ assert profile_locks[-1].closed is True+ assert not auth.exists()+ assert (home / transport._SUBSCRIPTION_PROFILE_MARKER).exists()+++async def test_atomic_logout_transfers_live_transport_lock_without_a_gap(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ SpawnHarness(monkeypatch)+ await transport.close_shared_codex_app_servers()+ profile_lock = FakeProfileProcessLock()+ monkeypatch.setattr(+ transport,+ "_acquire_subscription_process_lock",+ lambda: profile_lock,+ )+ client = transport.get_shared_codex_app_server("codex-test")+ await client.ensure_started()+ observations: list[str] = []++ def delete_auth() -> tuple[bool, None]:+ assert transport._subscription_profile_mutating is True+ assert transport._subscription_active_transports == set()+ assert transport._subscription_mutation_process_lock is profile_lock+ assert profile_lock.closed is False+ observations.append("deleted")+ return True, None++ monkeypatch.setattr(+ transport,+ "_delete_codex_subscription_auth_locked",+ delete_auth,+ )++ result = await transport.disconnect_and_logout_codex_subscription()++ assert result == (True, None)+ assert observations == ["deleted"]+ assert profile_lock.closed is True+ assert transport._subscription_profile_mutating is Falsediff --git a/tests/unit/commands/test_registry_parity.py b/tests/unit/commands/test_registry_parity.pyindex a5be81624c..39cda085a0 100644--- a/tests/unit/commands/test_registry_parity.py+++ b/tests/unit/commands/test_registry_parity.py@@ -137,6 +137,19 @@ def test_brain_switch_enum_excludes_subagent_only_providers() -> None:assert "antigravity" not in enum+def test_realtime_switch_exposes_experimental_acknowledgement() -> None:+ """Curated CLI/voice schema must match the REST activation contract."""+ command = get_command("realtime-switch")+ assert command is not None+ properties = command.params["properties"]+ assert "codex-subscription-realtime" in properties["provider"]["enum"]+ assert properties["accept_experimental"] == {+ "type": "boolean",+ "default": False,+ "description": "Explicitly acknowledge an experimental provider transport.",+ }++def test_spawn_agent_enum_follows_the_agent_registry() -> None:"""A newly registered coding CLI must be spawnable by voice the same day.diff --git a/tests/unit/core/test_exclusive_process_lock.py b/tests/unit/core/test_exclusive_process_lock.pynew file mode 100644index 0000000000..f628c4d5de--- /dev/null+++ b/tests/unit/core/test_exclusive_process_lock.py@@ -0,0 +1,178 @@+from __future__ import annotations++import os+import subprocess+import sys+from pathlib import Path++import pytest++from jarvis.core import exclusive_process_lock as process_lock+from jarvis.core.exclusive_process_lock import (+ ExclusiveProcessLock,+ ExclusiveProcessLockError,+)+from jarvis.core.private_directory import ensure_owner_only_directory+++def _paths(tmp_path: Path) -> tuple[Path, Path]:+ protected = tmp_path / "profile"+ protected.mkdir()+ coordination = tmp_path / "coordination"+ ensure_owner_only_directory(coordination, create=True)+ return coordination / "profile-process.lock", protected+++def test_lock_releases_on_close_and_keeps_strict_file(tmp_path: Path) -> None:+ path, protected = _paths(tmp_path)++ first = ExclusiveProcessLock.acquire(path, protected_directory=protected)+ assert path.stat().st_size == 1+ assert not first.closed+ first.close()+ assert path.read_bytes() == b"\0"+ assert first.closed++ with ExclusiveProcessLock.acquire(path, protected_directory=protected) as second:+ assert not second.closed+ assert second.closed+++def test_lock_rejects_location_inside_protected_directory(tmp_path: Path) -> None:+ _, protected = _paths(tmp_path)++ with pytest.raises(ExclusiveProcessLockError) as caught:+ ExclusiveProcessLock.acquire(+ protected / "process.lock",+ protected_directory=protected,+ )++ assert caught.value.reason == "unsafe"+++def test_lock_accepts_a_protected_directory_that_does_not_exist_yet(+ tmp_path: Path,+) -> None:+ coordination = tmp_path / "coordination"+ ensure_owner_only_directory(coordination, create=True)+ protected = tmp_path / "future-profile"++ with ExclusiveProcessLock.acquire(+ coordination / "profile-process.lock",+ protected_directory=protected,+ ):+ assert not protected.exists()++[email protected](os.name != "nt", reason="Windows DACL contract")+def test_lock_rejects_permissive_windows_dacl(tmp_path: Path) -> None:+ win32api = pytest.importorskip("win32api")+ win32con = pytest.importorskip("win32con")+ win32security = pytest.importorskip("win32security")+ path, protected = _paths(tmp_path)+ ExclusiveProcessLock.acquire(path, protected_directory=protected).close()+ token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)+ user_sid = win32security.GetTokenInformation(token, win32security.TokenUser)[0]+ everyone_sid = win32security.CreateWellKnownSid(win32security.WinWorldSid, None)+ dacl = win32security.ACL()+ dacl.AddAccessAllowedAce(win32security.ACL_REVISION, 0x001F01FF, user_sid)+ dacl.AddAccessAllowedAce(win32security.ACL_REVISION, win32con.GENERIC_READ, everyone_sid)+ win32security.SetNamedSecurityInfo(+ str(path),+ win32security.SE_FILE_OBJECT,+ win32security.DACL_SECURITY_INFORMATION | win32security.PROTECTED_DACL_SECURITY_INFORMATION,+ None,+ None,+ dacl,+ None,+ )++ with pytest.raises(ExclusiveProcessLockError) as caught:+ ExclusiveProcessLock.acquire(path, protected_directory=protected)++ assert caught.value.reason == "unsafe"+ assert str(caught.value) == "The profile process lock is unsafe."++[email protected](os.name != "posix", reason="POSIX parent permission contract")+def test_lock_rejects_unsafe_posix_parent(tmp_path: Path) -> None:+ protected = tmp_path / "profile"+ protected.mkdir()+ coordination = tmp_path / "coordination"+ coordination.mkdir(mode=0o755)+ coordination.chmod(0o755)++ with pytest.raises(ExclusiveProcessLockError) as caught:+ ExclusiveProcessLock.acquire(+ coordination / "profile-process.lock",+ protected_directory=protected,+ )++ assert caught.value.reason == "unsafe"++[email protected]("kind", ["empty", "directory", "multi_link"])+def test_lock_rejects_non_strict_existing_entry(tmp_path: Path, kind: str) -> None:+ path, protected = _paths(tmp_path)+ if kind == "empty":+ path.touch()+ elif kind == "directory":+ path.mkdir()+ else:+ original = tmp_path / "original"+ original.write_bytes(b"\0")+ try:+ os.link(original, path)+ except OSError:+ pytest.skip("hard links are unavailable")++ with pytest.raises(ExclusiveProcessLockError) as caught:+ ExclusiveProcessLock.acquire(path, protected_directory=protected)++ assert caught.value.reason == "unsafe"++[email protected](os.name != "posix", reason="POSIX permission contract")+def test_lock_rejects_unsafe_posix_mode_without_repair(tmp_path: Path) -> None:+ path, protected = _paths(tmp_path)+ path.write_bytes(b"\0")+ path.chmod(0o640)++ with pytest.raises(ExclusiveProcessLockError) as caught:+ ExclusiveProcessLock.acquire(path, protected_directory=protected)++ assert caught.value.reason == "unsafe"+ assert path.stat().st_mode & 0o777 == 0o640++[email protected](os.name != "posix", reason="POSIX ownership contract")+def test_lock_rejects_wrong_posix_owner(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ path, protected = _paths(tmp_path)+ path.write_bytes(b"\0")+ path.chmod(0o600)+ actual_uid = os.geteuid()+ monkeypatch.setattr(process_lock.os, "geteuid", lambda: actual_uid + 1)++ with pytest.raises(ExclusiveProcessLockError) as caught:+ ExclusiveProcessLock.acquire(path, protected_directory=protected)++ assert caught.value.reason == "unsafe"++[email protected](os.name != "posix", reason="POSIX inherited flock contract")+def test_inherited_descriptor_holds_lock_after_parent_close(tmp_path: Path) -> None:+ path, protected = _paths(tmp_path)+ parent_lock = ExclusiveProcessLock.acquire(path, protected_directory=protected)+ child = subprocess.Popen(+ [sys.executable, "-I", "-S", "-c", "import time; time.sleep(0.5)"],+ pass_fds=(parent_lock.fileno(),),+ )+ try:+ parent_lock.close()+ with pytest.raises(ExclusiveProcessLockError) as caught:+ ExclusiveProcessLock.acquire(path, protected_directory=protected)+ assert caught.value.reason == "busy"+ finally:+ child.wait(timeout=5)++ ExclusiveProcessLock.acquire(path, protected_directory=protected).close()diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.pynew file mode 100644index 0000000000..7bf133a42e--- /dev/null+++ b/tests/unit/realtime/test_codex_subscription.py@@ -0,0 +1,817 @@+"""Codex ChatGPT-subscription realtime adapter and SDP broker tests."""++from __future__ import annotations++import asyncio+import base64+from types import SimpleNamespace++import pytest++import jarvis.plugins.realtime.codex_subscription as codex_subscription_mod+from jarvis.plugins.realtime.codex_subscription import (+ CodexSubscriptionRealtimeProvider,+)+from jarvis.realtime.offer_broker import RealtimeTransportOfferBroker+from jarvis.realtime.protocol import RealtimeSessionConfig+++class _Notification:+ def __init__(self, method: str, params: dict) -> None:+ self.method = method+ self.params = params+++class _Subscription:+ def __init__(self, events=(), *, failure: BaseException | None = None) -> None:+ self.events = list(events)+ self.failure = failure+ self.closed = False++ def __aiter__(self):+ return self++ async def __anext__(self):+ if self.failure is not None:+ failure = self.failure+ self.failure = None+ raise failure+ if not self.events:+ raise StopAsyncIteration+ return self.events.pop(0)++ def close(self) -> None:+ self.closed = True+++class _ScheduledSubscription(_Subscription):+ def __init__(self, scheduled_events) -> None:+ super().__init__()+ self.scheduled_events = list(scheduled_events)++ async def __anext__(self):+ if not self.scheduled_events:+ raise StopAsyncIteration+ delay_s, event = self.scheduled_events.pop(0)+ if delay_s:+ await asyncio.sleep(delay_s)+ return event+++class _CountingSubscription(_Subscription):+ def __init__(self) -> None:+ super().__init__()+ self.yielded = 0++ async def __anext__(self):+ self.yielded += 1+ return _Notification(+ "thread/realtime/transcript/delta",+ {+ "threadId": "thread-1",+ "role": "user",+ "delta": str(self.yielded),+ },+ )+++class _Client:+ def __init__(+ self,+ events=(),+ *,+ failure: BaseException | None = None,+ start_response: dict | None = None,+ ) -> None:+ self.subscription = _Subscription(events, failure=failure)+ self.thread_starts: list[dict] = []+ self.realtime_starts: list[tuple[str, dict]] = []+ self.audio_appends: list[tuple[str, dict]] = []+ self.text_appends: list[tuple[str, str, str]] = []+ self.speech_appends: list[tuple[str, str]] = []+ self.stops: list[str] = []+ self.interrupts: list[tuple[str, str]] = []+ self.unsubscribes: list[str] = []+ self.poison_calls = 0+ self.capability_calls = 0+ self._thread_number = 0+ self.start_response = dict(start_response or {})++ async def capability_status(self):+ self.capability_calls += 1+ return SimpleNamespace(+ available=True,+ chatgpt_authenticated=True,+ reason="",+ )++ async def thread_start(self, **kwargs):+ self.thread_starts.append(kwargs)+ self._thread_number += 1+ return {"thread": {"id": f"thread-{self._thread_number}"}}++ def subscribe(self, thread_id: str):+ del thread_id+ return self.subscription++ async def realtime_start(self, thread_id: str, **kwargs):+ self.realtime_starts.append((thread_id, kwargs))+ return SimpleNamespace(+ response=self.start_response,+ answer_sdp="v=0\r\nanswer",+ )++ async def realtime_append_audio(self, thread_id: str, **kwargs):+ self.audio_appends.append((thread_id, kwargs))+ return {}++ async def realtime_append_text(+ self, thread_id: str, text: str, *, role: str = "user"+ ):+ self.text_appends.append((thread_id, text, role))+ return {}++ async def realtime_append_speech(self, thread_id: str, text: str):+ self.speech_appends.append((thread_id, text))+ return {}++ async def turn_interrupt(self, thread_id: str, turn_id: str):+ self.interrupts.append((thread_id, turn_id))+ return {}++ async def realtime_stop(self, thread_id: str):+ self.stops.append(thread_id)+ return {}++ async def thread_unsubscribe(self, thread_id: str):+ self.unsubscribes.append(thread_id)+ return {}++ async def poison(self) -> None:+ self.poison_calls += 1+++class _NoOfferBroker:+ async def acquire(self, *, timeout_s: float):+ del timeout_s+ return None+++class _UnauthenticatedClient(_Client):+ async def thread_start(self, **kwargs):+ self.thread_starts.append(kwargs)+ raise RuntimeError("Codex app-server rejected the unauthenticated account")+++class _FailedCleanupClient(_Client):+ async def realtime_stop(self, thread_id: str):+ self.stops.append(thread_id)+ raise RuntimeError("stop failed")+++class _TimedOutCleanupClient(_Client):+ async def realtime_stop(self, thread_id: str):+ self.stops.append(thread_id)+ await asyncio.sleep(60)+++async def test_direct_sdp_open_uses_safe_experimental_transport_contract() -> None:+ client = _Client()+ provider = CodexSubscriptionRealtimeProvider(client=client)++ session = await provider.open_session(+ RealtimeSessionConfig(+ instructions="Speak concise English.",+ transport_offer_sdp="v=0\r\no=browser-offer",+ )+ )++ assert session.answer_sdp == "v=0\r\nanswer"+ assert client.capability_calls == 0+ assert len(client.thread_starts) == 1+ 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()+ _thread_id, start = client.realtime_starts[0]+ assert start == {+ "output_modality": "audio",+ "offer_sdp": "v=0\r\no=browser-offer",+ "prompt": "",+ "model": "gpt-realtime-1.5",+ "voice": "cove",+ "version": "v1",+ "include_startup_context": False,+ "client_managed_handoffs": True,+ }+ await session.close()+ assert client.unsubscribes == ["thread-1"]+++async def test_failed_remote_cleanup_poisons_the_entire_app_server_client() -> None:+ client = _FailedCleanupClient()+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ await session.close()++ assert client.stops == ["thread-1"]+ assert client.unsubscribes == ["thread-1"]+ assert client.poison_calls == 1+++async def test_timed_out_remote_cleanup_poisons_the_entire_client(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(codex_subscription_mod, "_REMOTE_CLEANUP_TIMEOUT_S", 0.01)+ client = _TimedOutCleanupClient()+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ await session.close()++ assert client.unsubscribes == ["thread-1"]+ assert client.poison_calls == 1+++ ("field", "value"),+ [("model", "gpt-4o-realtime-preview"), ("voice", "marin")],+)+async def test_stale_api_v2_selection_fails_before_subscription_realtime_start(+ field: str,+ value: str,+) -> None:+ client = _Client()+ provider = CodexSubscriptionRealtimeProvider(client=client)+ config = RealtimeSessionConfig(+ transport_offer_sdp="v=0\r\no=browser-offer",+ **{field: value},+ )++ with pytest.raises(RuntimeError, match="unsupported V1"):+ await provider.open_session(config)++ assert client.realtime_starts == []+ assert client.stops == ["thread-1"]+ assert client.unsubscribes == ["thread-1"]+++async def test_language_update_is_developer_context_and_speech_is_authoritative() -> None:+ client = _Client()+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ await session.update_session(language="es")+ await session.send_speech("Trusted answer")++ assert client.text_appends == [+ (+ "thread-1",+ codex_subscription_mod._LANGUAGE_UPDATE_TEXT["es"],+ "developer",+ )+ ]+ assert client.speech_appends == [("thread-1", "Trusted answer")]+ await session.close()+++async def test_open_relies_on_authoritative_app_server_auth_without_pre_probe() -> None:+ client = _UnauthenticatedClient()+ provider = CodexSubscriptionRealtimeProvider(client=client)++ with pytest.raises(RuntimeError, match="unauthenticated account"):+ await provider.open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ assert client.capability_calls == 0+ assert len(client.thread_starts) == 1+ assert client.realtime_starts == []+++async def test_orchestrator_capability_check_does_not_repeat_cli_auth_probe(+ monkeypatch,+) -> None:+ provider = CodexSubscriptionRealtimeProvider(client=_Client())++ def _unexpected_probe(_cls):+ raise AssertionError("factory login probe must not repeat during handshake")++ monkeypatch.setattr(+ CodexSubscriptionRealtimeProvider,+ "external_login_ready",+ classmethod(_unexpected_probe),+ )++ assert await provider.can_open_duplex_session() is True+++async def test_send_audio_uses_sideband_pcm_without_api_usage_accounting() -> None:+ client = _Client()+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ await session.send_audio(+ SimpleNamespace(pcm=b"\x01\x00\x02\x00", sample_rate=24_000, channels=1)+ )++ assert client.audio_appends == [+ (+ "thread-1",+ {+ "data": base64.b64encode(b"\x01\x00\x02\x00").decode("ascii"),+ "sample_rate": 24_000,+ "num_channels": 1,+ "samples_per_channel": 2,+ },+ )+ ]+ await session.close()+++async def test_notifications_normalize_audio_transcripts_and_boundaries() -> None:+ encoded = base64.b64encode(b"\x01\x00\x02\x00").decode("ascii")+ client = _Client(+ [+ _Notification(+ "thread/realtime/itemAdded",+ {+ "threadId": "thread-1",+ "item": {+ "type": "input_audio_buffer.speech_started",+ "item_id": "input-1",+ },+ },+ ),+ _Notification(+ "thread/realtime/transcript/delta",+ {"threadId": "thread-1", "role": "user", "delta": "hello"},+ ),+ _Notification(+ "thread/realtime/transcript/done",+ {"threadId": "thread-1", "role": "user", "text": "hello"},+ ),+ _Notification(+ "thread/realtime/outputAudio/delta",+ {+ "threadId": "thread-1",+ "audio": {+ "data": encoded,+ "sampleRate": 24_000,+ "numChannels": 1,+ "samplesPerChannel": 2,+ },+ },+ ),+ _Notification(+ "thread/realtime/transcript/delta",+ {"threadId": "thread-1", "role": "assistant", "delta": "hi"},+ ),+ _Notification(+ "thread/realtime/transcript/done",+ {"threadId": "thread-1", "role": "assistant", "text": "hi"},+ ),+ ]+ )+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ events = [event async for event in session.receive()]++ assert [event.type for event in events] == [+ "speech_started",+ "input_transcript",+ "input_transcript",+ "audio_delta",+ "output_transcript_delta",+ "turn_complete",+ "error",+ ]+ assert events[2].is_final is True+ assert events[2].item_id == "input-1"+ assert events[3].audio is not None+ assert events[3].audio.pcm == b"\x01\x00\x02\x00"+ # A cleanly exhausted fake stream is still an unexpected transport death.+ assert "ended unexpectedly" in str(events[-1].error)+ await session.close()+++async def test_default_done_waits_for_all_late_audio_before_one_completion(+ monkeypatch,+) -> None:+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.03)+ encoded = base64.b64encode(b"\x01\x00").decode("ascii")+ audio = _Notification(+ "thread/realtime/outputAudio/delta",+ {+ "threadId": "thread-1",+ "audio": {+ "data": encoded,+ "sampleRate": 24_000,+ "numChannels": 1,+ },+ },+ )+ client = _Client()+ client.subscription = _ScheduledSubscription(+ [+ (+ 0,+ _Notification(+ "thread/realtime/transcript/done",+ {"threadId": "thread-1", "role": "assistant", "text": "hi"},+ ),+ ),+ (0.015, audio),+ (0.015, audio),+ ]+ )+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ events = [event async for event in session.receive()]+ event_types = [event.type for event in events]++ assert event_types.count("audio_delta") == 2+ assert event_types.count("turn_complete") == 1+ assert max(+ index for index, event_type in enumerate(event_types) if event_type == "audio_delta"+ ) < event_types.index("turn_complete")+ await session.close()+++async def test_later_assistant_delta_cancels_pending_completion_until_next_done(+ monkeypatch,+) -> None:+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.02)+ client = _Client()+ client.subscription = _ScheduledSubscription(+ [+ (+ 0,+ _Notification(+ "thread/realtime/transcript/done",+ {"threadId": "thread-1", "role": "assistant", "text": "part"},+ ),+ ),+ (+ 0.01,+ _Notification(+ "thread/realtime/transcript/delta",+ {"threadId": "thread-1", "role": "assistant", "delta": "more"},+ ),+ ),+ ]+ )+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ events = [event async for event in session.receive()]++ assert not [event for event in events if event.type == "turn_complete"]+ await session.close()+++ ("method", "params"),+ [+ (+ "thread/realtime/itemAdded",+ {"item": {"type": "input_audio_buffer.speech_started"}},+ ),+ (+ "thread/realtime/itemAdded",+ {"item": {"type": "response.cancelled"}},+ ),+ ("thread/realtime/error", {"message": "transport failed"}),+ ("thread/realtime/closed", {"reason": "closed"}),+ ],+)+async def test_terminal_or_interruption_event_cancels_pending_completion(+ monkeypatch,+ method: str,+ params: dict,+) -> None:+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.01)+ done = _Notification(+ "thread/realtime/transcript/done",+ {"threadId": "thread-1", "role": "assistant", "text": "partial"},+ )+ cancelling = _Notification(method, {"threadId": "thread-1", **params})+ client = _Client([done, cancelling])+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ events = [event async for event in session.receive()]++ assert not [event for event in events if event.type == "turn_complete"]+ await session.close()+++async def test_duplicate_transcript_done_emits_one_completion(monkeypatch) -> None:+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.01)+ done = _Notification(+ "thread/realtime/transcript/done",+ {"threadId": "thread-1", "role": "assistant", "text": "done"},+ )+ client = _Client([done, done])+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ events = [event async for event in session.receive()]++ assert len([event for event in events if event.type == "turn_complete"]) == 1+ await session.close()+++async def test_handoff_without_transcript_preserves_neutral_boundary() -> None:+ client = _Client(+ [+ _Notification(+ "thread/realtime/itemAdded",+ {+ "threadId": "thread-1",+ "item": {"type": "handoff_request", "handoff_id": "handoff-1"},+ },+ )+ ]+ )+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ events = [event async for event in session.receive()]++ assert not [event for event in events if event.type == "turn_complete"]+ handoff = next(event for event in events if event.type == "handoff_requested")+ assert handoff.handoff_id == "handoff-1"+ assert handoff.text is None+ await session.close()+++async def test_handoff_preserves_item_transcript_and_interrupts_late_codex_turn() -> None:+ client = _Client(+ [+ _Notification(+ "thread/realtime/itemAdded",+ {+ "threadId": "thread-1",+ "item": {+ "type": "handoff_request",+ "handoff_id": "handoff-1",+ "input_transcript": "Please check the calendar",+ "active_transcript": [+ {"role": "user", "text": "older question"}+ ],+ },+ },+ ),+ _Notification(+ "turn/started",+ {+ "threadId": "thread-1",+ "turn": {"id": "codex-turn-1"},+ },+ ),+ ]+ )+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ events = [event async for event in session.receive()]++ handoff = next(event for event in events if event.type == "handoff_requested")+ assert handoff.text == "Please check the calendar"+ assert handoff.handoff_id == "handoff-1"+ assert client.interrupts == [("thread-1", "codex-turn-1")]+ await session.close()+++async def test_done_then_handoff_cancels_synthetic_completion(monkeypatch) -> None:+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.01)+ client = _Client(+ [+ _Notification(+ "thread/realtime/transcript/done",+ {"threadId": "thread-1", "role": "assistant", "text": "partial"},+ ),+ _Notification(+ "thread/realtime/itemAdded",+ {+ "threadId": "thread-1",+ "item": {"type": "handoff_request", "handoff_id": "handoff-1"},+ },+ ),+ ]+ )+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ events = [event async for event in session.receive()]++ assert not [event for event in events if event.type == "turn_complete"]+ assert any(event.type == "handoff_requested" for event in events)+ await session.close()+++async def test_v3_authoritative_done_completes_without_idle_debounce(monkeypatch) -> None:+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 10.0)+ client = _Client(+ [+ _Notification(+ "thread/realtime/started",+ {"threadId": "thread-1", "version": 3},+ ),+ _Notification(+ "thread/realtime/transcript/done",+ {"threadId": "thread-1", "role": "assistant", "text": "done"},+ )+ ]+ )+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ async with asyncio.timeout(0.2):+ events = [event async for event in session.receive()]++ assert len([event for event in events if event.type == "turn_complete"]) == 1+ assert session.realtime_version == "3"+ await session.close()+++async def test_normalization_queue_backpressures_and_pump_cleans_up() -> None:+ client = _Client()+ subscription = _CountingSubscription()+ client.subscription = subscription+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )+ stream = session.receive()++ first = await anext(stream)+ assert first.type == "input_transcript"+ await asyncio.sleep(0.01)++ assert subscription.yielded <= codex_subscription_mod._NORMALIZATION_QUEUE_MAX + 2+ yielded_before_close = subscription.yielded+ await stream.aclose()+ await asyncio.sleep(0)+ assert subscription.yielded == yielded_before_close+ await session.close()+++async def test_handoff_request_never_becomes_a_direct_tool_call() -> None:+ client = _Client(+ [+ _Notification(+ "thread/realtime/itemAdded",+ {+ "threadId": "thread-1",+ "item": {+ "type": "handoff_request",+ "handoff_id": "handoff-1",+ },+ },+ ),+ _Notification(+ "thread/realtime/transcript/done",+ {"threadId": "thread-1", "role": "assistant", "text": "Working"},+ ),+ ]+ )+ session = await CodexSubscriptionRealtimeProvider(client=client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )++ events = [event async for event in session.receive()]++ assert not [event for event in events if event.type == "tool_call"]+ await session.close()+++async def test_provider_error_and_app_server_death_are_normalized() -> None:+ provider_error_client = _Client(+ [+ _Notification(+ "thread/realtime/error",+ {"threadId": "thread-1", "message": "experimental transport failed"},+ )+ ]+ )+ provider_session = await CodexSubscriptionRealtimeProvider(+ client=provider_error_client+ ).open_session(RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer"))+ provider_events = [event async for event in provider_session.receive()]+ assert provider_events[0].type == "error"+ assert provider_events[0].recoverable is False++ dead_client = _Client(failure=RuntimeError("process exited"))+ dead_session = await CodexSubscriptionRealtimeProvider(client=dead_client).open_session(+ RealtimeSessionConfig(transport_offer_sdp="v=0\r\no=offer")+ )+ dead_events = [event async for event in dead_session.receive()]+ assert dead_events[0].type == "error"+ assert "notification stream failed" in str(dead_events[0].error)+ await provider_session.close()+ await dead_session.close()+++async def test_missing_browser_offer_fails_before_app_server_launch() -> None:+ client = _Client()+ provider = CodexSubscriptionRealtimeProvider(client=client, offer_broker=_NoOfferBroker())++ with pytest.raises(RuntimeError, match="connected UI WebRTC offer"):+ await provider.open_session(RealtimeSessionConfig())++ assert client.capability_calls == 0+++async def test_broker_keeps_answered_lease_until_provider_release() -> None:+ broker = RealtimeTransportOfferBroker()+ registration = await broker.register("offer-1", "v=0\r\no=one")+ lease = await broker.acquire()+ assert lease is not None++ assert await lease.answer("v=0\r\no=answer") is True+ answer = await registration.wait()+ assert answer.type == "answer"+ assert answer.answer_sdp == "v=0\r\no=answer"++ await lease.release()+ released = await registration.wait()+ assert released.type == "release"+ assert await broker.pending_count() == 0+++async def test_two_consecutive_native_sessions_each_consume_a_fresh_offer() -> None:+ broker = RealtimeTransportOfferBroker()+ client = _Client()+ provider = CodexSubscriptionRealtimeProvider(client=client, offer_broker=broker)++ for number in (1, 2):+ offer_id = f"offer-{number}"+ registration = await broker.register(offer_id, f"v=0\r\no=native-{number}")+ session = await provider.open_session(RealtimeSessionConfig())+ answer = await registration.wait()+ assert answer.type == "answer"+ await session.close()+ released = await registration.wait()+ assert released.type == "release"++ assert [kwargs["offer_sdp"] for _thread, kwargs in client.realtime_starts] == [+ "v=0\r\no=native-1",+ "v=0\r\no=native-2",+ ]+++async def test_ui_disconnect_after_answer_removes_answered_lease() -> None:+ broker = RealtimeTransportOfferBroker()+ registration = await broker.register("offer-1", "v=0\r\no=one")+ lease = await broker.acquire()+ assert lease is not None+ assert await lease.answer("v=0\r\no=answer") is True+ assert (await registration.wait()).type == "answer"++ await registration.cancel()++ assert (await registration.wait()).type == "release"+ assert await broker.pending_count() == 0+ assert await lease.answer("v=0\r\no=late-answer") is Falsediff --git a/tests/unit/realtime/test_factory.py b/tests/unit/realtime/test_factory.pyindex c4e086d0ed..7a49a58dbc 100644--- a/tests/unit/realtime/test_factory.py+++ b/tests/unit/realtime/test_factory.py@@ -12,6 +12,7 @@ from jarvis.realtime.factory import (_resolve_realtime_provider,build_realtime_session,realtime_available_provider,+ realtime_requires_webrtc_offer,)@@ -32,6 +33,7 @@ class _BaseProvider:class _OpenAIProvider(_BaseProvider):name = "openai-realtime"+ credential_family = "openai"credential_candidates = (("openai_api_key", "OPENAI_API_KEY"),)@@ -45,10 +47,27 @@ class _AcmeProvider(_BaseProvider):credential_candidates = (("acme_api_key", "ACME_API_KEY"),)+class _SubscriptionProvider(_BaseProvider):+ name = "codex-subscription-realtime"+ credential_family = "openai-chatgpt-subscription"+ credential_candidates = ()+ requires_webrtc_offer = True+ implicit_usage_fallback_allowed = False+ login_ready = False++ def __init__(self):+ super().__init__(api_key="external-login")++ @classmethod+ def external_login_ready(cls):+ return cls.login_ready++_PLUGINS = {"openai-realtime": _OpenAIProvider,"gemini-live": _GeminiProvider,"acme-realtime": _AcmeProvider,+ "codex-subscription-realtime": _SubscriptionProvider,}@@ -67,11 +86,14 @@ def _cfg(mode: str = "realtime", provider: str = "openai-realtime") -> SimpleNam)-def _fake_registry(monkeypatch, keys: set[str]) -> None:+def _fake_registry(+ monkeypatch, keys: set[str], *, subscription_login: bool = False+) -> None:import jarvis.realtime.factory as factorymonkeypatch.setattr(factory, "list_plugins", lambda _group: list(_PLUGINS))monkeypatch.setattr(factory, "load", lambda _group, name, protocol=None: _PLUGINS[name])+ _SubscriptionProvider.login_ready = subscription_logindef _get_secret(candidates):slot = candidates[0][0]@@ -119,6 +141,60 @@ def test_explicit_fallback_order_precedes_other_installed_plugins(monkeypatch):]+def test_external_login_provider_is_candidate_without_a_fake_api_key(monkeypatch):+ _fake_registry(monkeypatch, set(), subscription_login=True)+ config = _cfg(provider="codex-subscription-realtime")++ providers = _provider_candidates(config)++ assert [provider.name for provider in providers] == [+ "codex-subscription-realtime"+ ]+ assert providers[0].credential_family == "openai-chatgpt-subscription"+++def test_subscription_primary_never_uses_ambient_api_fallback(+ monkeypatch,+):+ _fake_registry(monkeypatch, {"openai"}, subscription_login=False)+ config = _cfg(provider="codex-subscription-realtime")++ assert _provider_candidates(config) == []+++def test_subscription_and_api_credentials_remain_distinct_fallbacks(monkeypatch):+ _fake_registry(monkeypatch, {"openai"}, subscription_login=True)+ config = _cfg(provider="codex-subscription-realtime")+ config.brain.realtime.fallback_provider = "openai-realtime"++ providers = _provider_candidates(config)++ assert [provider.name for provider in providers] == [+ "codex-subscription-realtime",+ "openai-realtime",+ ]+ assert [provider.credential_family for provider in providers] == [+ "openai-chatgpt-subscription",+ "openai",+ ]+ assert realtime_requires_webrtc_offer(config) is True+++def test_api_provider_does_not_request_unneeded_browser_sdp(monkeypatch):+ _fake_registry(monkeypatch, {"openai"}, subscription_login=True)+ config = _cfg(provider="openai-realtime")++ assert realtime_requires_webrtc_offer(config) is False+++def test_logged_in_subscription_is_never_an_ambient_candidate(monkeypatch):+ _fake_registry(monkeypatch, set(), subscription_login=True)+ config = _cfg(provider="openai-realtime")++ assert _provider_candidates(config) == []+ assert realtime_available_provider(config) is None++def test_pipeline_mode_never_builds_realtime_session(monkeypatch):_fake_registry(monkeypatch, {"openai"})assert (diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 900a1edcb6..42cdac865c 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -2,6 +2,7 @@ import asyncioimport pytest+from jarvis.brain.output_filter import scrub_for_voicefrom jarvis.brain.tool_gateway import BrainSupervisorToolGatewayfrom jarvis.core import runtime_refsfrom jarvis.core.events import (@@ -328,6 +329,43 @@ async def test_open_injects_active_providers_model_and_voice():assert ready["model"] == "gpt-realtime-2.1"+async def test_browser_webrtc_offer_reaches_provider_and_answer_returns_in_ready():+ class AnswerProvider(FakeProvider):+ requires_webrtc_offer = True++ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = FakeSession(self._events)+ self.session.answer_sdp = "v=0\r\no=provider-answer"+ return self.session++ messages = []+ provider = AnswerProvider([])+ sess = RealtimeVoiceSession(+ session_id="s-webrtc-sdp",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda message: messages.append(message) or asyncio.sleep(0),+ provider=provider,+ config=_cfg(),+ bus=None,+ )++ await sess.handle_control(+ {+ "type": "audio_start",+ "sample_rate": 48_000,+ "webrtc_offer_sdp": "v=0\r\no=browser-offer",+ }+ )++ assert provider.opened_with.transport_offer_sdp == "v=0\r\no=browser-offer"+ ready = next(message for message in messages if message["type"] == "audio_ready")+ assert ready["webrtc_answer_sdp"] == "v=0\r\no=provider-answer"+ assert ready["requires_webrtc_answer"] is True+ await sess.end(reason="test")++@pytest.mark.asyncioasync def test_open_defaults_to_empty_model_and_voice_when_unset():"""No [brain.providers.<id>] entry -> "" / "" so the adapter falls back@@ -2332,7 +2370,7 @@ async def test_generative_voice_provider_mute_still_falls_back_to_surface_tts():elapsed = asyncio.get_event_loop().time() - startassert elapsed >= 2.0, "surface TTS claimed the reply before the wait window"spoken = [m for m in jsons if m.get("type") == "error_spoken"]- assert [m["text"] for m in spoken] == [reply]+ assert [m["text"] for m in spoken] == [scrub_for_voice(reply).cleaned]assert binaries == []provider.session.release.set()await sess.end(reason="test")@@ -3734,7 +3772,7 @@ async def test_gate_miss_lets_the_model_reach_the_wiki_through_jarvis_action():"""A vague follow-up the planner cannot classify must still reach the brain."""from jarvis.brain.turn_planner import plan_turn- utterance = "Was steht da drin?" # i18n-allow: German speech-input fixture+ utterance = "Und was ist damit?" # i18n-allow: German speech-input fixtureassert plan_turn(utterance).requires_orchestrator is Falsebrain = FakeBrain(replies=("Your wiki holds pages about you and Lukas.",))diff --git a/tests/unit/test_codex_auth.py b/tests/unit/test_codex_auth.pyindex 92156f1a4a..740ce4328d 100644--- a/tests/unit/test_codex_auth.py+++ b/tests/unit/test_codex_auth.py@@ -11,7 +11,11 @@ version probe are seams that the tests stub; the auth file is a real temp file.from __future__ import annotationsimport base64+import hashlibimport json+import subprocess+import sys+import threadingfrom pathlib import Pathimport pytest@@ -242,6 +246,169 @@ def test_start_login_raises_when_binary_missing(monkeypatch: pytest.MonkeyPatch)svc.start_login()+def test_guarded_login_handoff_runs_real_guardian(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ """The service and guardian transfer one real cross-process profile lock."""+ import jarvis.codex_auth as codex_mod+ from jarvis.core.exclusive_process_lock import (+ ExclusiveProcessLock,+ ExclusiveProcessLockError,+ )+ from jarvis.core.private_directory import ensure_owner_only_directory++ profile = tmp_path / "profile"+ coordination = tmp_path / "coordination"+ guard_directory = coordination / "login"+ ensure_owner_only_directory(profile, create=True)+ ensure_owner_only_directory(coordination, create=True)+ ensure_owner_only_directory(guard_directory, create=True)+ lock_path = coordination / "owner.lock"+ parent_lock = ExclusiveProcessLock.acquire(+ lock_path,+ protected_directory=profile,+ )+ binary = Path(sys.executable).resolve(strict=True)+ service = CodexAuthService(+ str(binary),+ codex_home=profile,+ force_file_auth_store=True,+ isolate_openai_environment=True,+ log_dir=guard_directory,+ visible_login=False,+ lifetime_lock_path=lock_path,+ login_guard_directory=guard_directory,+ login_guard_handoff=parent_lock.close,+ trusted_binary_sha256=hashlib.sha256(binary.read_bytes()).hexdigest(),+ )+ monkeypatch.setattr(service, "_resolve_binary", lambda: str(binary))+ if sys.platform == "win32":+ monkeypatch.setattr(+ codex_mod,+ "_NEW_CONSOLE_FLAGS",+ codex_mod.NO_WINDOW_CREATIONFLAGS,+ )++ process = None+ try:+ process = service.start_login()+ assert parent_lock.closed is True+ assert process.wait() == 0+ with pytest.raises(ExclusiveProcessLockError) as caught:+ ExclusiveProcessLock.acquire(+ lock_path,+ protected_directory=profile,+ )+ assert caught.value.reason == "busy"+ finally:+ if process is not None:+ process.release_profile_lock()+ elif not parent_lock.closed:+ parent_lock.close()++ reacquired = ExclusiveProcessLock.acquire(+ lock_path,+ protected_directory=profile,+ )+ reacquired.close()+++def test_guarded_windows_login_closes_job_when_guardian_exits(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.codex_auth as codex_mod+ import jarvis.core.process_tree as process_tree_module++ guardian_exited = threading.Event()+ job_closed = threading.Event()+ events: list[str] = []++ class FakeProcess:+ pid = 9321++ def poll(self) -> int | None:+ return 74 if guardian_exited.is_set() else None++ def wait(self, timeout: float | None = None) -> int:+ if not guardian_exited.wait(timeout):+ raise subprocess.TimeoutExpired(["guardian"], timeout)+ return 74++ def terminate(self) -> None:+ guardian_exited.set()++ class FakeProcessTree:+ supports_containment = True++ def __init__(self) -> None:+ self.assigned: list[int] = []+ self.close_calls = 0++ def assign(self, pid: int) -> None:+ events.append("assign")+ self.assigned.append(pid)++ def close(self) -> None:+ self.close_calls += 1+ job_closed.set()++ process = FakeProcess()+ process_tree = FakeProcessTree()+ captured: dict[str, object] = {}++ def spawn(command: list[str], **kwargs: object) -> FakeProcess:+ events.append("spawn")+ captured["command"] = command+ captured["kwargs"] = kwargs+ return process++ def handoff(*_args: object, **_kwargs: object) -> None:+ events.append("handoff")++ monkeypatch.setattr(codex_mod.sys, "platform", "win32")+ monkeypatch.setattr(codex_mod.subprocess, "Popen", spawn)+ monkeypatch.setattr(+ process_tree_module,+ "make_process_tree",+ lambda _name: process_tree,+ )+ monkeypatch.setattr(+ codex_mod._GuardedCodexLoginProcess,+ "establish_handoff",+ staticmethod(handoff),+ )+ service = CodexAuthService(+ "codex.exe",+ lifetime_lock_path=tmp_path / "owner.lock",+ login_guard_handoff=lambda: None,+ )+ monkeypatch.setattr(service, "_resolve_binary", lambda: "codex.exe")+ monkeypatch.setattr(+ service,+ "_guarded_login_command",+ lambda _binary: (+ ["guardian.exe"],+ tmp_path / "login.ack",+ tmp_path / "login.release",+ ),+ )++ wrapper = service.start_login()+ assert isinstance(wrapper, codex_mod._GuardedCodexLoginProcess)+ assert events == ["spawn", "assign", "handoff"]+ assert process_tree.assigned == [process.pid]+ kwargs = captured["kwargs"]+ assert isinstance(kwargs, dict)+ assert int(kwargs["creationflags"]) & codex_mod._CREATE_BREAKAWAY_FROM_JOB++ guardian_exited.set()+ assert job_closed.wait(1.0)+ assert wrapper.wait() == 74+ assert process_tree.close_calls == 1++def test_start_login_posix_detaches_and_redirects_stdio(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -297,6 +464,281 @@ def test_start_login_windows_uses_visible_console(assert captured["kwargs"].get("stdout") is not sp.DEVNULL+def test_dedicated_login_pins_file_store_log_dir_and_scrubs_api_keys(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.codex_auth as codex_mod++ captured: dict = {}++ class _FakeProc:+ pid = 10++ def _fake_popen(cmd, **kwargs): # noqa: ANN001, ANN002, ANN003+ captured["cmd"] = cmd+ captured["kwargs"] = kwargs+ return _FakeProc()++ monkeypatch.setattr(codex_mod.sys, "platform", "win32")+ monkeypatch.setenv("OPENAI_API_KEY", "must-not-reach-login")+ monkeypatch.setenv("OPENAI_BASE_URL", "https://billing-sink.invalid")+ monkeypatch.setenv("AZURE_OPENAI_API_KEY", "must-not-reach-login")+ monkeypatch.setenv("HTTPS_PROXY", "http://credential-proxy.invalid")+ monkeypatch.setenv("AWS_SESSION_TOKEN", "must-not-reach-login")+ monkeypatch.setenv("LD_PRELOAD", "must-not-reach-login")+ monkeypatch.setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/host/keyring")+ monkeypatch.setattr(codex_mod.subprocess, "Popen", _fake_popen)+ home = tmp_path / "dedicated-home"+ log_dir = tmp_path / "isolated-logs"+ service = CodexAuthService(+ "codex",+ codex_home=home,+ force_file_auth_store=True,+ isolate_openai_environment=True,+ log_dir=log_dir,+ )+ monkeypatch.setattr(service, "_resolve_binary", lambda: "codex")++ service.start_login()++ assert captured["cmd"] == [+ "codex",+ "-c",+ 'cli_auth_credentials_store="file"',+ "-c",+ f"log_dir={json.dumps(str(log_dir))}",+ "login",+ ]+ environment = captured["kwargs"]["env"]+ assert environment["CODEX_HOME"] == str(home)+ for name in (+ "OPENAI_API_KEY",+ "OPENAI_BASE_URL",+ "AZURE_OPENAI_API_KEY",+ "HTTPS_PROXY",+ "AWS_SESSION_TOKEN",+ "LD_PRELOAD",+ "DBUS_SESSION_BUS_ADDRESS",+ ):+ assert name not in environment+++def test_visible_linux_login_uses_a_waiting_desktop_terminal(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.codex_auth as codex_mod++ captured: dict = {}++ class _FakeProc:+ pid = 11++ def _fake_popen(cmd, **kwargs): # noqa: ANN001, ANN002, ANN003+ captured["cmd"] = cmd+ captured["kwargs"] = kwargs+ return _FakeProc()++ monkeypatch.setattr(codex_mod.sys, "platform", "linux")+ monkeypatch.setenv("DISPLAY", ":9")+ monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-9")+ monkeypatch.setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/9/bus")+ monkeypatch.setenv("XDG_RUNTIME_DIR", "/run/user/9")+ monkeypatch.setenv("OPENAI_API_KEY", "must-not-reach-codex")+ monkeypatch.setenv("OPENAI_BASE_URL", "https://must-not-reach-codex.invalid")+ monkeypatch.setenv("HTTPS_PROXY", "http://must-not-reach-codex.invalid")+ monkeypatch.setattr(+ codex_mod.shutil,+ "which",+ lambda name: "/usr/bin/gnome-terminal" if name == "gnome-terminal" else None,+ )+ monkeypatch.setattr(codex_mod.subprocess, "Popen", _fake_popen)+ service = CodexAuthService(+ "codex",+ codex_home=tmp_path / "home",+ force_file_auth_store=True,+ isolate_openai_environment=True,+ visible_login=True,+ )+ monkeypatch.setattr(service, "_resolve_binary", lambda: "/usr/bin/codex")++ service.start_login()++ assert captured["cmd"][:3] == [+ str(Path("/usr/bin/gnome-terminal").resolve()),+ "--wait",+ "--",+ ]+ wrapper = captured["cmd"][3:]+ assert wrapper[0] == str(Path(codex_mod.sys.executable).resolve())+ assert wrapper[1:4] == ["-I", "-S", "-c"]+ child_environment = json.loads(wrapper[5])+ assert wrapper[6:] == [+ "/usr/bin/codex",+ "-c",+ 'cli_auth_credentials_store="file"',+ "login",+ ]+ assert child_environment["CODEX_HOME"] == str(tmp_path / "home")+ for name in (+ "DBUS_SESSION_BUS_ADDRESS",+ "XDG_RUNTIME_DIR",+ "OPENAI_API_KEY",+ "OPENAI_BASE_URL",+ "HTTPS_PROXY",+ ):+ assert name not in child_environment+ assert captured["kwargs"]["start_new_session"] is True+ assert captured["kwargs"].get("stdout") is not codex_mod.subprocess.DEVNULL+ launcher_environment = captured["kwargs"]["env"]+ assert launcher_environment["DISPLAY"] == ":9"+ assert launcher_environment["WAYLAND_DISPLAY"] == "wayland-9"+ assert launcher_environment["DBUS_SESSION_BUS_ADDRESS"].endswith("/bus")+ assert launcher_environment["XDG_RUNTIME_DIR"] == "/run/user/9"+ assert "OPENAI_API_KEY" not in launcher_environment+ assert "HTTPS_PROXY" not in launcher_environment+++def test_visible_linux_login_resolves_waiting_terminal_alternative(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.codex_auth as codex_mod++ terminal = tmp_path / "gnome-terminal"+ alternative = tmp_path / "x-terminal-emulator"+ terminal.write_bytes(b"")+ alternative.write_bytes(b"")+ original_resolve = Path.resolve++ def resolve(path: Path, *args, **kwargs): # noqa: ANN002, ANN003+ if path == alternative:+ return terminal+ return original_resolve(path, *args, **kwargs)++ captured: dict[str, object] = {}++ class _FakeProc:+ pid = 13++ monkeypatch.setattr(Path, "resolve", resolve)+ monkeypatch.setattr(codex_mod.sys, "platform", "linux")+ monkeypatch.setattr(+ codex_mod.shutil,+ "which",+ lambda name: str(alternative) if name == "x-terminal-emulator" else None,+ )+ monkeypatch.setattr(+ codex_mod.subprocess,+ "Popen",+ lambda command, **kwargs: (+ captured.update(command=command, kwargs=kwargs) or _FakeProc()+ ),+ )+ service = CodexAuthService(+ "/usr/bin/codex",+ codex_home=tmp_path / "home",+ force_file_auth_store=True,+ isolate_openai_environment=True,+ visible_login=True,+ )+ monkeypatch.setattr(service, "_resolve_binary", lambda: "/usr/bin/codex")++ service.start_login()++ command = captured["command"]+ assert isinstance(command, list)+ assert command[:3] == [str(terminal), "--wait", "--"]+++def test_visible_macos_login_opens_terminal_and_scrubs_shell_api_keys(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ import jarvis.codex_auth as codex_mod++ captured: dict = {}++ class _FakeProc:+ pid = 12++ def _fake_popen(cmd, **kwargs): # noqa: ANN001, ANN002, ANN003+ captured["cmd"] = cmd+ captured["kwargs"] = kwargs+ return _FakeProc()++ monkeypatch.setattr(codex_mod.sys, "platform", "darwin")+ monkeypatch.setenv("OPENAI_API_KEY", "must-not-reach-codex")+ monkeypatch.setenv("HTTPS_PROXY", "http://must-not-reach-codex.invalid")+ monkeypatch.setattr(codex_mod.subprocess, "Popen", _fake_popen)+ home = tmp_path / "dedicated home"+ service = CodexAuthService(+ "/usr/local/bin/codex",+ codex_home=home,+ force_file_auth_store=True,+ isolate_openai_environment=True,+ visible_login=True,+ )+ monkeypatch.setattr(service, "_resolve_binary", lambda: "/usr/local/bin/codex")++ service.start_login()++ assert captured["cmd"][:2] == ["/usr/bin/osascript", "-e"]+ script = captured["cmd"][2]+ assert 'tell application "Terminal"' in script+ assert "repeat while busy of loginTab" in script+ assert "os.execve" in script+ assert "OPENAI_API_KEY" not in script+ assert "HTTPS_PROXY" not in script+ assert "CODEX_HOME" in script+ assert home.name in script+ assert "OPENAI_API_KEY" not in captured["kwargs"]["env"]+++ ("output", "expected"),+ [+ ("Logged in using ChatGPT\n", (True, "chatgpt")),+ ("Logged in using an API key\n", (True, "api_key")),+ ("[email protected]\n", (False, "unknown")),+ ],+)+def test_login_status_accepts_only_exact_pii_free_mode_strings(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ output: str,+ expected: tuple[bool, str],+) -> None:+ import jarvis.codex_auth as codex_mod++ captured: dict = {}++ class _Result:+ returncode = 0+ stdout = output+ stderr = ""++ def _fake_run(argv, **kwargs): # noqa: ANN001, ANN002, ANN003+ captured["argv"] = argv+ captured["kwargs"] = kwargs+ return _Result()++ monkeypatch.setattr(codex_mod.subprocess, "run", _fake_run)+ service = CodexAuthService(+ "codex",+ codex_home=tmp_path / "home",+ force_file_auth_store=True,+ isolate_openai_environment=True,+ log_dir=tmp_path / "logs",+ )+ monkeypatch.setattr(service, "_resolve_binary", lambda: "codex")++ assert service.login_status() == expected+ assert captured["argv"][-2:] == ["login", "status"]+ assert 'cli_auth_credentials_store="file"' in captured["argv"]++def test_logout_returns_false_when_binary_missing(monkeypatch: pytest.MonkeyPatch) -> None:svc = CodexAuthService()monkeypatch.setattr(svc, "_resolve_binary", lambda: None)diff --git a/tests/unit/test_codex_login_guard.py b/tests/unit/test_codex_login_guard.pynew file mode 100644index 0000000000..a305e6cf4e--- /dev/null+++ b/tests/unit/test_codex_login_guard.py@@ -0,0 +1,216 @@+from __future__ import annotations++import hashlib+import json+import os+import subprocess+import sys+import time+from pathlib import Path++import pytest++from jarvis import codex_login_guard+from jarvis.core.exclusive_process_lock import ExclusiveProcessLock+from jarvis.core.private_directory import ensure_owner_only_directory+++def _guardian_path() -> Path:+ return Path(codex_login_guard.__file__).resolve()+++def _environment(profile: Path) -> dict[str, str]:+ safe_names = {+ "COMSPEC",+ "PATH",+ "PATHEXT",+ "SYSTEMROOT",+ "TEMP",+ "TMP",+ "TMPDIR",+ "WINDIR",+ }+ environment = {name: value for name, value in os.environ.items() if name in safe_names}+ environment["CODEX_HOME"] = str(profile)+ return environment+++def _start_guardian(+ *,+ lock_path: Path,+ acknowledgement: Path,+ release: Path,+ profile: Path,+ log_dir: Path,+) -> subprocess.Popen[bytes]:+ return subprocess.Popen(+ [+ sys.executable,+ "-I",+ "-S",+ str(_guardian_path()),+ str(lock_path),+ str(acknowledgement),+ str(release),+ str(Path(sys.executable).resolve()),+ hashlib.sha256(Path(sys.executable).read_bytes()).hexdigest(),+ str(log_dir),+ json.dumps(_environment(profile), separators=(",", ":")),+ ],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )+++def _wait_for_status(path: Path, wanted: str) -> None:+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ try:+ if path.read_text(encoding="ascii") == wanted:+ return+ except OSError:+ pass+ time.sleep(0.02)+ raise AssertionError(f"guardian did not publish {wanted!r}")+++def _publish_control(path: Path, status: str) -> None:+ temporary = path.with_suffix(".tmp")+ temporary.write_text(status, encoding="ascii")+ temporary.chmod(0o600)+ os.replace(temporary, path)+++def _coordination_directory(tmp_path: Path) -> Path:+ coordination = tmp_path / "coordination"+ ensure_owner_only_directory(coordination, create=True)+ return coordination+++def test_guardian_runs_isolated_launches_fixed_child_and_acknowledges_ready(+ tmp_path: Path,+) -> None:+ profile = tmp_path / "profile"+ profile.mkdir()+ log_dir = tmp_path / "logs"+ log_dir.mkdir()+ coordination = _coordination_directory(tmp_path)+ acknowledgement = coordination / "ack"+ release = coordination / "release"+ lock_path = coordination / "profile-process.lock"++ process = _start_guardian(+ lock_path=lock_path,+ acknowledgement=acknowledgement,+ release=release,+ profile=profile,+ log_dir=log_dir,+ )+ _wait_for_status(acknowledgement, "waiting")+ _publish_control(release, "acquire")+ _wait_for_status(acknowledgement, "finished")+ assert process.poll() is None+ _publish_control(release, "release")+ stdout, stderr = process.communicate(timeout=10)++ assert process.returncode == 0+ assert stdout == b""+ assert stderr == b""+ assert acknowledgement.read_text(encoding="ascii") == "finished"+ assert not (profile / "profile-process.lock").exists()+++def test_guardian_reports_cross_process_contention_without_launching_child(+ tmp_path: Path,+) -> None:+ profile = tmp_path / "profile"+ profile.mkdir()+ log_dir = tmp_path / "logs"+ log_dir.mkdir()+ coordination = _coordination_directory(tmp_path)+ acknowledgement = coordination / "ack"+ release = coordination / "release"+ lock_path = coordination / "profile-process.lock"++ with ExclusiveProcessLock.acquire(lock_path, protected_directory=profile):+ process = _start_guardian(+ lock_path=lock_path,+ acknowledgement=acknowledgement,+ release=release,+ profile=profile,+ log_dir=log_dir,+ )+ _wait_for_status(acknowledgement, "waiting")+ _publish_control(release, "acquire")+ stdout, stderr = process.communicate(timeout=10)++ assert process.returncode == codex_login_guard.EXIT_BUSY+ assert stdout == b""+ assert stderr == b""+ assert acknowledgement.read_text(encoding="ascii") == "busy"+++def test_guardian_rejects_non_allowlisted_environment_without_acknowledging(+ tmp_path: Path,+) -> None:+ profile = tmp_path / "profile"+ profile.mkdir()+ log_dir = tmp_path / "logs"+ log_dir.mkdir()+ coordination = _coordination_directory(tmp_path)+ acknowledgement = coordination / "ack"+ environment = {+ "CODEX_HOME": str(profile),+ "UNAPPROVED_SECRET": "must-not-be-forwarded",+ }++ result = codex_login_guard.main(+ (+ str(coordination / "profile-process.lock"),+ str(acknowledgement),+ str(coordination / "release"),+ str(Path(sys.executable).resolve()),+ hashlib.sha256(Path(sys.executable).read_bytes()).hexdigest(),+ str(log_dir),+ json.dumps(environment),+ )+ )++ assert result == codex_login_guard.EXIT_INVALID+ assert not acknowledgement.exists()+++def test_guardian_rejects_desktop_session_variables_from_child_environment(+ tmp_path: Path,+) -> None:+ profile = tmp_path / "profile"+ profile.mkdir()++ with pytest.raises(ValueError, match="not approved"):+ codex_login_guard._strict_environment(+ json.dumps({"CODEX_HOME": str(profile), "DISPLAY": ":0"})+ )+++def test_guardian_rejects_a_binary_hash_mismatch() -> None:+ with pytest.raises(ValueError, match="verification failed"):+ codex_login_guard._open_verified_binary(+ str(Path(sys.executable).resolve()),+ "0" * 64,+ )++[email protected](os.name != "nt", reason="Windows environment names are caseless")+def test_guardian_normalizes_windows_environment_names_and_rejects_aliases(+ tmp_path: Path,+) -> None:+ profile = tmp_path / "profile"+ profile.mkdir()++ parsed = codex_login_guard._strict_environment(+ json.dumps({"Codex_Home": str(profile), "Path": "safe"})+ )+ assert parsed == {"CODEX_HOME": str(profile), "PATH": "safe"}++ with pytest.raises(ValueError, match="duplicate environment"):+ codex_login_guard._strict_environment('{"CODEX_HOME":"safe","Path":"one","PATH":"two"}')diff --git a/tests/unit/ui/test_desktop_realtime_broker_capability.py b/tests/unit/ui/test_desktop_realtime_broker_capability.pynew file mode 100644index 0000000000..f0ab4dd1d4--- /dev/null+++ b/tests/unit/ui/test_desktop_realtime_broker_capability.py@@ -0,0 +1,35 @@+"""Desktop-only capability injection for subscription Realtime signalling."""++from __future__ import annotations++import sys+from types import SimpleNamespace++from jarvis.ui.desktop_app import DesktopApp+++def test_desktop_injects_distinct_realtime_broker_capability(monkeypatch) -> None:+ scripts: list[str] = []+ window = SimpleNamespace(evaluate_js=scripts.append)+ app = DesktopApp.__new__(DesktopApp)+ app.session_token = "ordinary-ui-session" # noqa: S105 - synthetic test token+ app.realtime_transport_broker_token = (+ "desktop-broker-capability" # noqa: S105 - synthetic test token+ )+ monkeypatch.setattr(app, "_start_desktop_integration_repair", lambda: None)+ monkeypatch.setitem(+ sys.modules,+ "jarvis.ui.icon_utils",+ SimpleNamespace(+ project_icon_path=lambda: "unused",+ set_window_icon_by_title=lambda *_args: None,+ ),+ )++ app._inject_token(window)++ assert len(scripts) == 1+ assert "ordinary-ui-session" in scripts[0]+ assert "desktop-broker-capability" in scripts[0]+ assert "__JARVIS_EMBEDDED_DESKTOP" in scripts[0]+ assert "__JARVIS_REALTIME_BROKER_TOKEN" in scripts[0]diff --git a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.pynew file mode 100644index 0000000000..a78881b622--- /dev/null+++ b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py@@ -0,0 +1,397 @@+from __future__ import annotations++from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from jarvis.ui.web import provider_routes as routes+from jarvis.ui.web.provider_spec import get_spec, provider_billing+++class _Status:+ def __init__(self, *, connected: bool, mode: str) -> None:+ self.connected = connected+ self.mode = mode++ def to_dict(self) -> dict[str, object]:+ return {+ "installed": True,+ "connected": self.connected,+ "mode": self.mode,+ "message": "Codex status",+ "version": "1.0",+ }+++def test_codex_subscription_realtime_spec_has_no_api_key_path() -> None:+ spec = get_spec("codex-subscription-realtime")++ assert spec is not None+ assert spec.tier == "realtime"+ assert spec.auth_mode == "codex"+ assert spec.secret_keys == ()+ assert provider_billing(spec) == "subscription"+ assert spec.experimental is True+++ ("connected", "mode", "configured"),+ [+ (True, "chatgpt", True),+ (True, "api_key", False),+ (False, "not_connected", False),+ ],+)+def test_keyless_codex_readiness_requires_chatgpt_login(+ monkeypatch: pytest.MonkeyPatch,+ connected: bool,+ mode: str,+ configured: bool,+) -> None:+ spec = get_spec("codex-subscription-realtime")+ assert spec is not None++ class _Service:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ def status(self) -> _Status:+ return _Status(connected=connected, mode=mode)++ monkeypatch.setattr(routes, "CodexAuthService", _Service)+ monkeypatch.setattr(routes, "_codex_binary_path", lambda *_args: "codex")+ monkeypatch.setattr(routes.cfg_mod, "get_secret", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(+ routes,+ "_is_credential_present",+ lambda *_args, **_kwargs: pytest.fail("keyless Codex must use login status"),+ )++ payload = routes._spec_to_payload(+ spec,+ active_brain=None,+ active_tts=None,+ active_stt=None,+ active_realtime=spec.id if configured else None,+ )++ assert payload["configured"] is configured+ assert payload["billing"] == "subscription"+ assert payload["codex_status"]["mode"] == mode+ assert payload["cli_installed"] is True+ assert "codex_brain_ready" not in payload+++def test_authoritative_subscription_probe_overrides_stale_chatgpt_status(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ spec = get_spec("codex-subscription-realtime")+ assert spec is not None++ class _Service:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ def status(self) -> _Status:+ return _Status(connected=True, mode="chatgpt")++ monkeypatch.setattr(routes, "CodexAuthService", _Service)+ monkeypatch.setattr(routes, "_codex_binary_path", lambda *_args: "codex")+ monkeypatch.setattr(routes.cfg_mod, "get_secret", lambda *_args, **_kwargs: None)++ payload = routes._spec_to_payload(+ spec,+ active_brain=None,+ active_tts=None,+ active_stt=None,+ active_realtime=None,+ codex_subscription_ready=False,+ )++ assert payload["configured"] is False+ assert payload["codex_status"]["connected"] is False+ assert payload["codex_status"]["mode"] == "not_connected"+ assert "not ready" in payload["codex_status"]["message"]+++async def test_section_health_accepts_keyring_only_chatgpt_login(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jarvis import codex_app_server++ spec = get_spec("codex-subscription-realtime")+ assert spec is not None++ async def ready(_binary_path: str | None = None) -> bool:+ return True++ async def healthy_probe(*_args, **_kwargs):+ return SimpleNamespace(status="ok", detail="subscription reachable")++ monkeypatch.setattr(codex_app_server, "codex_subscription_login_ready", ready)+ monkeypatch.setattr(routes, "_run_tier_test", healthy_probe)+ monkeypatch.setattr(+ routes,+ "_is_credential_present",+ lambda *_args, **_kwargs: pytest.fail(+ "section health must use the authoritative app-server auth probe"+ ),+ )++ health = await routes._realtime_section_health(+ SimpleNamespace(),+ spec,+ binary_path="codex-custom",+ )++ assert health.status == "ok"+ assert health.reason == "ok"+ assert health.subject_id == "codex-subscription-realtime"+++async def test_realtime_activation_rejects_codex_api_key_mode(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class _Service:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ def status(self) -> _Status:+ return _Status(connected=True, mode="api_key")++ monkeypatch.setattr(routes, "CodexAuthService", _Service)+ monkeypatch.setattr(routes, "_codex_binary_path", lambda *_args: "codex")++ with pytest.raises(HTTPException) as caught:+ await routes.realtime_switch(+ routes.SwitchBody(+ provider="codex-subscription-realtime",+ persist=False,+ accept_experimental=True,+ ),+ object(),+ )++ assert caught.value.status_code == 409+ assert "Connect or configure this provider first" in str(caught.value.detail)+++async def test_realtime_activation_requires_experimental_acknowledgement(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def unexpected_probe(*_args, **_kwargs) -> bool:+ pytest.fail("the experimental acknowledgement must be checked first")++ monkeypatch.setattr(+ routes,+ "_provider_credential_present_async",+ unexpected_probe,+ )++ with pytest.raises(HTTPException) as caught:+ await routes.realtime_switch(+ routes.SwitchBody(+ provider="codex-subscription-realtime",+ persist=False,+ ),+ object(),+ )++ assert caught.value.status_code == 409+ assert "Explicitly acknowledge" in str(caught.value.detail)+++async def test_realtime_activation_uses_provider_capability_not_provider_id(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import jarvis.core.registry as registry++ config = SimpleNamespace(marker="active-config")+ request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=config)))+ spec = SimpleNamespace(+ id="arbitrary-subscription-transport",+ tier="realtime",+ experimental=False,+ )+ verified: list[object] = []++ class Provider:+ @classmethod+ async def verify_activation(cls, cfg: object) -> None:+ verified.append(cfg)+ raise RuntimeError("provider capability rejected activation")++ async def credential_present(*_args, **_kwargs) -> bool:+ return True++ monkeypatch.setattr(routes, "get_spec", lambda _provider: spec)+ monkeypatch.setattr(+ routes,+ "_provider_credential_present_async",+ credential_present,+ )+ monkeypatch.setattr(registry, "load", lambda *_args, **_kwargs: Provider)++ with pytest.raises(HTTPException) as caught:+ await routes.realtime_switch(+ routes.SwitchBody(+ provider=spec.id,+ persist=False,+ ),+ request,+ )++ assert caught.value.status_code == 409+ assert "capability rejected" in str(caught.value.detail)+ assert verified == [config]+++def _request_with_codex_path() -> SimpleNamespace:+ return SimpleNamespace(+ app=SimpleNamespace(+ state=SimpleNamespace(+ config=SimpleNamespace(codex=SimpleNamespace(binary_path="codex-custom"))+ )+ )+ )+++async def test_subscription_voice_status_uses_isolated_snapshot(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ expected = {+ "installed": True,+ "connected": True,+ "mode": "chatgpt",+ "message": "ready",+ }+ monkeypatch.setattr(+ routes,+ "_codex_subscription_status_payload",+ lambda binary_path: expected | {"binary_path": binary_path},+ )++ result = await routes.codex_subscription_voice_status(_request_with_codex_path())++ assert result["connected"] is True+ assert result["binary_path"] == "codex-custom"+++ ("available", "authenticated", "version", "reason_code"),+ [+ (True, True, "codex-cli 0.146.0", "ready"),+ (True, False, "codex-cli 0.146.0", "login_required"),+ (False, False, "codex-cli 0.146.0", "login_required"),+ (False, False, None, "not_installed"),+ (False, False, "codex-cli 0.147.0", "setup_invalid"),+ ],+)+def test_subscription_status_has_stable_reason_codes(+ monkeypatch: pytest.MonkeyPatch,+ available: bool,+ authenticated: bool,+ version: str | None,+ reason_code: str,+) -> None:+ from jarvis import codex_app_server++ snapshot = codex_app_server.CodexAppServerCapability(+ available=available,+ chatgpt_authenticated=authenticated,+ binary_path="codex" if version is not None else None,+ version=version,+ reason="setup result",+ reason_code=reason_code,+ )+ monkeypatch.setattr(+ codex_app_server,+ "codex_subscription_auth_snapshot",+ lambda _binary_path: snapshot,+ )++ payload = routes._codex_subscription_status_payload(None)++ assert payload["reason_code"] == reason_code+++async def test_subscription_voice_login_uses_dedicated_helper(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jarvis import codex_app_server++ calls: list[str | None] = []+ monkeypatch.setattr(+ codex_app_server,+ "start_codex_subscription_login",+ lambda binary_path=None: calls.append(binary_path) or SimpleNamespace(pid=731),+ )++ result = await routes.codex_subscription_voice_login(_request_with_codex_path())++ assert calls == ["codex-custom"]+ assert result["pid"] == 731+++async def test_subscription_voice_logout_uses_atomic_backend_helper(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jarvis import codex_app_server++ calls: list[str | None] = []++ async def disconnect_and_logout(binary_path=None):+ calls.append(binary_path)+ return True, None++ monkeypatch.setattr(+ codex_app_server,+ "disconnect_and_logout_codex_subscription",+ disconnect_and_logout,+ )++ result = await routes.codex_subscription_voice_logout(_request_with_codex_path())++ assert calls == ["codex-custom"]+ assert result["ok"] is True+++async def test_subscription_voice_logout_does_not_parse_exception_prose(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jarvis import codex_app_server++ async def malformed_profile(_binary_path=None):+ raise codex_app_server.CodexSubscriptionUnavailable(+ "The profile has not been created but is also malformed."+ )++ monkeypatch.setattr(+ codex_app_server,+ "disconnect_and_logout_codex_subscription",+ malformed_profile,+ )++ with pytest.raises(HTTPException) as caught:+ await routes.codex_subscription_voice_logout(_request_with_codex_path())++ assert caught.value.status_code == 409+++def test_subscription_voice_logout_is_marked_dangerous_in_openapi() -> None:+ route = next(+ route+ for route in routes.router.routes+ if getattr(route, "path", None) == "/api/codex/subscription-voice/logout"+ )++ assert route.openapi_extra == {"x-jarvis-dangerous": True}diff --git a/tests/unit/ui/web/test_settings_realtime_optional.py b/tests/unit/ui/web/test_settings_realtime_optional.pyindex 71005d049a..594651976f 100644--- a/tests/unit/ui/web/test_settings_realtime_optional.py+++ b/tests/unit/ui/web/test_settings_realtime_optional.py@@ -29,5 +29,13 @@ def test_realtime_available_helper_resolves_when_module_present(monkeypatch) ->stub = types.ModuleType("jarvis.realtime.factory")stub.realtime_available_provider = lambda cfg: "openai-realtime" # type: ignore[attr-defined]+ stub.realtime_requires_webrtc_offer = lambda cfg: True # type: ignore[attr-defined]monkeypatch.setitem(sys.modules, "jarvis.realtime.factory", stub)assert settings_routes._realtime_available_provider(object()) == "openai-realtime"+ assert settings_routes._realtime_requires_webrtc_offer(object()) is True+++def test_realtime_webrtc_helper_degrades_when_module_stripped(monkeypatch) -> None:+ monkeypatch.setitem(sys.modules, "jarvis.realtime.factory", None)+ monkeypatch.setitem(sys.modules, "jarvis.realtime", None)+ assert settings_routes._realtime_requires_webrtc_offer(object()) is Falsediff --git a/tests/unit/web/test_realtime_option_validation.py b/tests/unit/web/test_realtime_option_validation.pyindex 9657e28941..fa6876955d 100644--- a/tests/unit/web/test_realtime_option_validation.py+++ b/tests/unit/web/test_realtime_option_validation.py@@ -99,3 +99,24 @@ def test_put_realtime_options_keeps_explicit_clear_contract(assert response.status_code == 200assert writes == [("", "")]+++def test_get_realtime_options_reports_preview_capability(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *args, **kwargs: "sk-test")+ client = TestClient(_app())++ api_response = client.get(+ "/api/providers/openai-realtime/realtime-options"+ )+ subscription_response = client.get(+ "/api/providers/codex-subscription-realtime/realtime-options"+ )++ assert api_response.status_code == 200+ assert api_response.json()["preview_available"] is True+ assert subscription_response.status_code == 200+ body = subscription_response.json()+ assert body["preview_available"] is False+ assert [voice["id"] for voice in body["voices"]][0] == "cove"diff --git a/tests/unit/web/test_realtime_voice_preview.py b/tests/unit/web/test_realtime_voice_preview.pyindex e2b8ce067c..79bd204dca 100644--- a/tests/unit/web/test_realtime_voice_preview.py+++ b/tests/unit/web/test_realtime_voice_preview.py@@ -38,11 +38,12 @@ async def _silent_sampler(*_args, **_kwargs) -> tuple[bytes, int]:return b"\x01\x02" * 240, 24_000-def test_every_cataloged_realtime_provider_has_a_preview_sampler() -> None:- """Adding a realtime provider means adding its sampler too (parity)."""+def test_every_preview_sampler_has_a_cataloged_realtime_provider() -> None:+ """A sampler may not exist without a catalog; offer-only providers may omit one."""from jarvis.brain.model_catalog import REALTIME_VOICES- assert set(REALTIME_VOICES) == set(provider_routes._REALTIME_PREVIEW_SAMPLERS)+ assert set(provider_routes._REALTIME_PREVIEW_SAMPLERS) <= set(REALTIME_VOICES)+ assert "codex-subscription-realtime" not in provider_routes._REALTIME_PREVIEW_SAMPLERSdef test_unknown_provider_is_404() -> None:diff --git a/tests/unit/web/test_voice_mode_route.py b/tests/unit/web/test_voice_mode_route.pyindex e8a5ce9133..6a239f727a 100644--- a/tests/unit/web/test_voice_mode_route.py+++ b/tests/unit/web/test_voice_mode_route.py@@ -13,6 +13,7 @@ from __future__ import annotationsfrom types import SimpleNamespace+import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -20,6 +21,20 @@ from jarvis.browser_voice.route import _browser_voice_enabledfrom jarvis.ui.web.settings_routes import router[email protected](autouse=True)+def _disable_machine_codex_subscription_login(monkeypatch):+ """Keep API-key route tests independent of the host's Codex login."""+ from jarvis.plugins.realtime.codex_subscription import (+ CodexSubscriptionRealtimeProvider,+ )++ monkeypatch.setattr(+ CodexSubscriptionRealtimeProvider,+ "external_login_ready",+ classmethod(lambda _cls: False),+ )++def test_gate_default_off_when_pipeline_and_no_browser_voice():cfg = SimpleNamespace(voice=SimpleNamespace(mode="pipeline"))assert _browser_voice_enabled(cfg) is False@@ -63,6 +78,7 @@ def test_get_voice_mode(monkeypatch):body = r.json()assert body["mode"] == "realtime"assert body["realtime_available"] is True+ assert body["requires_webrtc_offer"] is Falseassert body["active_provider"] == "openai-realtime"# Sidebar display fields: registry label + the catalog-default model (no# pin configured in this app fixture).@@ -72,6 +88,26 @@ def test_get_voice_mode(monkeypatch):assert body["active_session_mode"] is None+def test_get_voice_mode_reports_browser_offer_capability(monkeypatch):+ from jarvis.ui.web import settings_routes++ monkeypatch.setattr(+ settings_routes,+ "_realtime_available_provider",+ lambda _cfg: "codex-subscription-realtime",+ )+ monkeypatch.setattr(+ settings_routes,+ "_realtime_requires_webrtc_offer",+ lambda _cfg: True,+ )++ body = TestClient(_app(mode="realtime")).get("/api/settings/voice-mode").json()++ assert body["active_provider"] == "codex-subscription-realtime"+ assert body["requires_webrtc_offer"] is True++def test_get_voice_mode_cross_family_gemini_only(monkeypatch):"""Feature A2: realtime_available must NOT be OpenAI-only — a user withonly a Gemini key gets realtime_available=true, active_provider=gemini-live."""