Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat: improve realtime voice and assistant workflows

rubenluetke10-beep44f994a3eaa1
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 3d7c60a6ba..4d115061c5 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -210,6 +210,7 @@ experiences today.
| P-28 | Low | Local realtime | The one-click managed install AND the 2026-08-08 supervisor (prewarm, pidfile ownership, start/stop routes, Ollama keep-alive warm ping) are built cross-platform — pathlib, `os.name` venv layout with a POSIX `lib/python*/site-packages` glob, per-hardware torch flavor, `start_new_session` + `killpg` SIGTERM→SIGKILL escalation on POSIX, `HF_HUB_DISABLE_SYMLINKS` Windows-only — but have only been RUN on the Windows dev box. The preflight's accelerator probe knows two sources: NVIDIA VRAM (nvidia-smi) and Apple-Silicon unified memory (total RAM); the derived launch command maps them to `cuda`/`mps`; an AMD/Intel/no-nvidia-smi host gets the honest "no supported accelerator" blocker (unit-tested) | `jarvis/realtime/local_server/{preflight,install,supervisor}.py` | Any host under 12 GB usable accelerator memory (including every GPU-less/headless box) gets the honest blocker with a cloud pointer instead of an install — verified by unit tests. macOS Apple-Silicon: preflight and install should work but the smoke boot (`--qwen3_tts_device mps`) is UNVERIFIED on real hardware; a failure is honest (install ends in an error state naming the smoke log, readiness stays fail-closed). Linux+NVIDIA: expected to work via the same cu130 wheel index, unverified; the supervisor's POSIX kill/spawn branches are unit-tested but not live-run. The bring-your-own-server URL socket keeps full parity everywhere |
+| P-32 | Low | Local models | The in-app Ollama runtime install (the plug-and-go path for local models: detect → install → start → pull, no terminal) has one silent path per OS and an honest refusal elsewhere: Windows uses winget or the official per-user OllamaSetup.exe (built, not yet live-run on a machine WITHOUT Ollama); macOS automates only Homebrew — a dmg drag cannot be scripted honestly, so brew-less Macs get the download pointer; Linux runs the official install.sh only when non-interactive sudo exists (the script escalates internally; without it the refusal names the one terminal command instead of hanging on an invisible password prompt). Detection and start are cross-platform | `jarvis/brain/ollama_runtime.py`, `jarvis/ui/web/provider_routes.py` (ollama-runtime routes), `jarvis/realtime/local_server/install.py::_setup_local_brain` | Every OS gets the same three-state truth (not installed / stopped / running) and the same buttons; only the INSTALL leg differs. Refusals are one honest sentence with the exact fixing action. All install legs are unit-tested with fakes; no leg has been live-run on a machine without Ollama yet — the cold-machine drill is the recorded release gate |
| P-31 | Low | Detached views | The "own window" detach (Agentic IDE / Voice into a second pywebview window) creates the window at RUNTIME, after `webview.start()`. pywebview documents runtime multi-window, and the code path is OS-neutral (worker-thread create, distinct title, shared backend), but it has only been RUN against the Windows/WebView2 backend; whether the cocoa and GTK backends accept a runtime `create_window` is unverified from this machine. Browser-lock auth in the second window additionally relies on a shared cookie jar, which is verified for WebView2 only | `jarvis/ui/desktop_app.py::open_detached_window`, `jarvis/platform/probes.py::webview_backend_available`, `jarvis/ui/web/desktop_routes.py` | Every failure is honest and keeps the feature usable: a shell whose backend refuses the runtime create answers `ok: false` with the solo URL and the frontend opens it in the user's real browser tab (via open-external); plain-browser clients open the tab directly; headless answers `no_desktop_shell` the same way. macOS/Linux desktop live check pending: detach, close main, reattach, tray-reopen — on success this row shrinks to the cookie-jar note or disappears |
## Maintenance
diff --git a/docs/reports/jarvis-mcp-deep-dive-2026-08-08.md b/docs/reports/jarvis-mcp-deep-dive-2026-08-08.md
new file mode 100644
index 0000000000..9ef4794100
--- /dev/null
+++ b/docs/reports/jarvis-mcp-deep-dive-2026-08-08.md
@@ -0,0 +1,193 @@
+# Jarvis MCP Deep Dive
+
+**Audit date:** 2026-08-08
+**Scope:** MCP client, Marketplace connectors, mission worker broker, standalone Jarvis MCP server, management surfaces, tests, documentation, and parity with the Jarvis CLI.
+
+## Executive verdict
+
+"Jarvis MCP" is not one product. It is four related systems with different maturity levels:
+
+| Plane | Purpose | Current maturity | Verdict |
+|---|---|---:|---|
+| Custom MCP client | Connect user-defined stdio or remote MCP servers and expose their tools to the brain | Beta | Useful core with incomplete lifecycle and safety semantics |
+| Marketplace MCP runtime | Turn packaged connectors and OAuth/PAT grants into live MCP tools | Production-oriented | Strongest MCP plane; bounded startup and reauthentication logic are present |
+| Mission worker broker | Give isolated CLI/API workers a mission-scoped tool surface without handing them connector secrets | Production-oriented | Sound security architecture; SDK v2 migration is the immediate compatibility blocker |
+| Jarvis as an MCP server | Let external MCP clients access Jarvis memory and skills | Prototype | Four tools and two resources, no CLI-level parity, no tests, and unsafe HTTP claims |
+
+The repository has a credible MCP foundation, but it does **not** yet have a cohesive "Jarvis MCP" product comparable to the Jarvis CLI. The right end state is a thin, authenticated MCP facade over the same live control plane, policy engine, event bus, and command catalog used by the CLI. The standalone server must not continue as a second, direct writer to Jarvis data.
+
+## 1. What exists today
+
+### 1.1 Jarvis as an MCP client
+
+The custom-server path begins with `mcp.json`, loaded through the portable precedence rules in [`state.py`](../../jarvis/mcp/state.py#L62). The registry intentionally ships no preconfigured servers (`BOOTSTRAP_SERVERS` is empty) and starts enabled entries in parallel ([`registry.py`](../../jarvis/mcp/registry.py#L52)).
+
+The v1 SDK client in [`client.py`](../../jarvis/mcp/client.py#L101) supports:
+
+- local stdio subprocesses;
+- legacy HTTP+SSE;
+- Streamable HTTP with protected header references;
+- a 20-second default call timeout;
+- a three-failure, 60-second circuit breaker;
+- cached tool discovery and bounded shutdown.
+
+Each discovered tool becomes a Jarvis tool named `<server>/<tool>`. The adapter also registers voice-language capability phrases so tools can be selected through normal brain routing ([`adapter.py`](../../jarvis/mcp/adapter.py#L207)). Desktop and headless startup both create the registry, start enabled servers, register adapters, and publish a `BrainToolsChanged` signal. A per-turn tool-surface fingerprint provides a second reconciliation path ([`tool_surface.py`](../../jarvis/brain/tool_surface.py#L25)).
+
+This means a trusted MCP server can already become available to conversation routing and delegated missions without a Jarvis restart.
+
+### 1.2 Marketplace-backed MCP connectors
+
+The Marketplace has 21 seeded plugins, 14 of which currently declare an HTTP MCP server: GitHub, Supabase, Notion, Slack, Linear, Stripe, Cloudflare, Asana, Todoist, ClickUp, Dropbox, Canva, Airtable, and Cal.com ([`seed_catalog.json`](../../jarvis/marketplace/seed_catalog.json)).
+
+[`plugin_mcp.py`](../../jarvis/marketplace/plugin_mcp.py#L17) converts a connected plugin and its protected token record into an in-process MCP client specification. [`plugin_registry.py`](../../jarvis/marketplace/plugin_registry.py#L169) adds bounded handshake/tool discovery, per-plugin refresh, auth-failure classification, token refresh and retry, `needs_reauth`, and bounded disconnect. The Marketplace also supports PAT, PKCE, device, and hosted MCP discovery/DCR flows.
+
+This is materially more complete than arbitrary `mcp.json`: credentials have a product flow, refresh behavior, liveness state, and recovery UX.
+
+### 1.3 MCP as the worker tool transport
+
+Mission startup assembles the relevant connected Marketplace and custom MCP server IDs, using the same relevance concept as brain routing ([`missions/init.py`](../../jarvis/missions/init.py#L249)). A `WorkerCapabilityInventory` deliberately retains identity, not resolved connector credentials ([`capabilities.py`](../../jarvis/missions/workers/capabilities.py#L38)).
+
+At execution time, the supervisor issues a short-lived grant to an authenticated loopback broker. CLI workers see only a local stdio MCP adapter; API workers call the same binding directly. The broker applies a tool denylist, exact/family grants, payload and TTL limits, cancellation, revocation, approval policy, and outcome-integrity reporting before execution reaches the supervisor gateway ([`worker_tool_broker.py`](../../jarvis/missions/workers/worker_tool_broker.py#L654)).
+
+This is the correct architectural direction: credentials and policy remain in the supervisor, while MCP is only the worker-facing protocol.
+
+### 1.4 Jarvis as an MCP server
+
+The standalone entry point is `python -m jarvis.mcp.server`. It currently exposes:
+
+- `memory_search(query, k)`;
+- `memory_recent(limit, role)`;
+- `memory_add_fact(fact, category)`;
+- `skills_list()`;
+- resources `jarvis://core-memory/persona` and `jarvis://core-memory/all`.
+
+The module documentation and server instructions also advertise `skills_run`, but no such tool exists ([`server.py`](../../jarvis/mcp/server.py#L7)). It has no first-class `jarvis mcp serve` command, no dedicated product documentation, no discovery/catalog parity, and no tests.
+
+## 2. Critical findings
+
+### P0 — Secure or suspend standalone HTTP
+
+[`server.py`](../../jarvis/mcp/server.py#L26) says that `JARVIS_MCP_TOKEN` requires bearer authentication, and [`MCPServerConfig`](../../jarvis/core/config.py#L1474) declares an auth-token setting. The implementation never reads or enforces it. HTTP can expose personal memory, including the mutating `memory_add_fact`, with no Jarvis authorization middleware, scope enforcement, rate limiting, or Origin validation. The CLI accepts a host override, so the risk is not limited to localhost.
+
+The current MCP transport specification requires Origin validation, recommends localhost binding for local servers, and recommends authentication for all Streamable HTTP connections. Protected HTTP resources use OAuth 2.1 discovery, per-request bearer tokens, audience validation, and 401/403 semantics ([Streamable HTTP security](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http), [authorization](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization)).
+
+Until those properties exist, HTTP mode should be disabled or explicitly experimental and localhost-only. Stdio can remain the local development surface.
+
+### P0 — Stop bypassing Jarvis ownership and safety
+
+The standalone server opens the recall database and `CoreMemory` directly rather than calling the running Jarvis service. `CoreMemory` explicitly assumes a single process and writes its JSON file directly ([`core_memory.py`](../../jarvis/memory/core_memory.py#L36)). Running desktop Jarvis and the MCP server together can create stale reads, lost updates, or file corruption. Calls also bypass the REST boundary, `ToolExecutor`, safety tiers, audit trail, event bus, and live brain state.
+
+The MCP server must become an adapter to the running control plane. It must never be an independent data owner.
+
+### P0 — Apply conservative per-tool policy
+
+All arbitrary MCP tools currently inherit one default risk tier, normally `monitor` ([`adapter.py`](../../jarvis/mcp/adapter.py#L313)). A remote server can therefore advertise `delete`, `send`, `publish`, or payment-like operations without a per-tool confirmation requirement.
+
+Modern MCP annotations include read-only, destructive, idempotent, and open-world hints, but the specification says clients must treat them as untrusted unless the server is trusted ([tool specification](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)). Jarvis should combine server trust, annotations, local name/schema heuristics, explicit user overrides, and existing blacklist/whitelist policy. Unknown or destructive-looking tools should default to `ask`, never gain authority from an annotation alone, and always execute through `ToolExecutor`.
+
+## 3. Correctness and lifecycle gaps
+
+1. The chat/voice `manage-mcp-server` tool calls the nonexistent `MCPRegistry.active_names()` method. Disable does not stop a live client, remove can leave a running client and registered tools behind, and enable persists state before proving the connection ([`manage_mcp_server.py`](../../jarvis/plugins/tool/manage_mcp_server.py#L250)). Existing tests cover only unknown-name responses.
+2. Raw REST config reload overwrites/adds registry specs but does not reconcile removed or changed entries. Delete removes the client/spec without removing tool adapters or publishing `BrainToolsChanged`; capability entries have no deregistration path ([`mcp_routes.py`](../../jarvis/ui/web/mcp_routes.py#L472)).
+3. `/config/info` reads the project-root constant while saves use the resolved active path. With `JARVIS_MCP_CONFIG`, `JARVIS_DATA_DIR`, or per-user fallback, the UI can display a different file than it edits ([`mcp_routes.py`](../../jarvis/ui/web/mcp_routes.py#L453)).
+4. Start failures are represented inside a nominally successful response because the registry swallows connection failures. Fresh `check` has no route-level timeout. Headless autostart silently discards startup, adapter, and event errors ([`launcher.py`](../../jarvis/ui/web/launcher.py#L695)).
+5. URL-only SSE entries are accepted by the management schema but are not reliably loaded by the registry. Legacy HTTP+SSE is deprecated; new work should target stdio and current Streamable HTTP.
+
+These should be fixed with one idempotent registry operation: **reconcile desired config to live state**, returning per-server outcomes and one atomic tool/capability/event delta.
+
+## 4. Protocol and SDK gap
+
+The project pins `mcp>=1.28.1,<2` ([`pyproject.toml`](../../pyproject.toml#L190)). That was a valid security-floor stabilization, but SDK v2 is now the stable line and v1 is maintenance-only. The current protocol revision is 2026-07-28 ([Python SDK v2 changes](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/whats-new.md), [current MCP specification](https://modelcontextprotocol.io/specification/2026-07-28)).
+
+The immediate blocker is [`broker_stdio.py`](../../jarvis/missions/workers/broker_stdio.py#L65), which uses the rebuilt low-level v1 `Server` decorator API. Migration also affects the client lifecycle, `FastMCP` rename, snake_case SDK fields, Streamable HTTP streams, validation behavior, errors, and result types.
+
+Even before v2, Jarvis currently discards or omits important protocol data:
+
+- only the first `tools/list` response is cached; there is no pagination or cache TTL handling;
+- no `tools/list_changed` subscription refreshes the live surface;
+- tool title, icons, output schema, annotations, and metadata are dropped;
+- structured content, resource links, embedded resources, and output validation are flattened;
+- modern `input_required` user interaction is not bridged into Jarvis approvals/forms.
+
+The v2 migration needs a contract matrix across stdio, Streamable HTTP, Marketplace OAuth refresh, worker broker, Windows, macOS, Linux, and headless `python:3.11-slim`; it should not be a dependency-only bump.
+
+## 5. Management UX versus Jarvis CLI
+
+The curated CLI group currently offers `list`, `enable`, `disable`, `check`, `import-claude-desktop`, and `delete` ([`mcps.py`](../../jarvis/cli_ctl/commands/mcps.py#L12)). Remaining REST operations are technically reachable through the generated `jarvis api` group. The MCP view offers switches, Claude Desktop import, and a raw JSON editor, but it does not surface the returned tool list, tool risk, scopes, server trust, a visible check action, safe add/delete flows, or generic credential onboarding ([`McpsView.tsx`](../../jarvis/ui/web/frontend/src/views/McpsView.tsx#L22)). Import is Windows-only.
+
+The more important parity gap is opposite-facing: the Jarvis CLI exposes the live REST/OpenAPI control plane, while the Jarvis MCP server hand-writes four memory/skill tools. It therefore has neither the breadth nor the architectural guarantees of the CLI.
+
+### Target parity model
+
+Build one `JarvisMCPFacade` over the same command registry and authenticated REST/service layer used by the CLI:
+
+```text
+MCP client
+ -> stdio or authenticated Streamable HTTP
+ -> scope-filtered MCP facade
+ -> command catalog / REST application services
+ -> ToolExecutor + safety + audit + EventBus
+ -> Jarvis state and integrations
+```
+
+Expose a small stable core rather than flooding every model context with hundreds of operations:
+
+- `commands_search(query, risk, capability)`;
+- `command_describe(command_id)` with exact input/output schema and danger metadata;
+- `command_execute(command_id, arguments)` routed through the existing control plane;
+- curated high-frequency read/status tools;
+- scoped resources for documentation, health, command catalog, and explicitly authorized memory views.
+
+Dangerous execution must return `input_required` when approval is needed. `tools/list` should be filtered by granted scope and feature availability, deterministic, paginated/cacheable, and emit `list_changed` when the live surface changes. This gives functional CLI parity without duplicating business logic or expanding every operation into the model prompt.
+
+## 6. Recommended delivery plan
+
+### Wave 0 — Safety containment
+
+- Disable unauthenticated standalone HTTP; keep stdio development-only.
+- Remove direct writable memory ownership from the MCP process.
+- Add server auth, Origin, scope, rate-limit, audit, and unauthorized/forbidden tests before HTTP returns.
+- Remove the nonexistent `skills_run` claim and label the current server experimental.
+
+### Wave 1 — SDK v2 compatibility
+
+- Migrate `broker_stdio.py` first, then the shared client and high-level server.
+- Preserve the `mcp>=1.28.1,<2` release line until the full contract matrix passes.
+- Lift the cap in the same change as cross-platform and malformed-server compatibility tests.
+- Implement modern result preservation, pagination, subscriptions, and `input_required` bridging.
+
+### Wave 2 — One live lifecycle
+
+- Add public registry introspection and a single reconcile API; stop using private `_specs`.
+- Atomically synchronize clients, tool adapters, capabilities, state, and one brain-change event.
+- Fix active config-path reporting, failure HTTP semantics, timeouts, and headless logging.
+- Add safe per-tool risk derivation and explicit server trust/override storage.
+
+### Wave 3 — CLI-level Jarvis MCP facade
+
+- Mount an authenticated MCP facade into the existing application, with stdio proxy support.
+- Generate discovery/describe/execute behavior from the command/OpenAPI registry.
+- Route every action through existing safety, approval, audit, language, and event ownership.
+- Add CLI commands for `mcp serve/status/doctor` and protocol/version diagnostics.
+
+### Wave 4 — Productization and cleanup
+
+- Replace raw-JSON-first setup with add/check/edit/delete, tool previews, risk/scope review, and protected credentials.
+- Make import capability-based and cross-platform or state the unsupported path honestly.
+- Delete or formally retire the broken, unregistered `mcp-remote` harness, obsolete bootstrap/setup selector, stale worker-secret comments/probes, and the unreachable "First MCP Connection" achievement trigger.
+- Add a single product document distinguishing custom MCPs, Marketplace MCPs, worker brokerage, and Jarvis-as-server.
+
+## 7. Verified current state
+
+The focused MCP suite passed **126 tests** with two deprecation warnings. The CLI coverage and danger-metadata guards passed. Coverage is strongest for the shared client, registry, adapter, Marketplace bridge, and worker broker. There are no tests for `jarvis.mcp.server`, and the live management lifecycle, config reconciliation, capability deregistration, HTTP authentication, Origin defense, and modern protocol features are not covered.
+
+### Definition of done
+
+Jarvis MCP reaches CLI-level maturity when:
+
+1. no MCP process directly owns mutable Jarvis data;
+2. every HTTP call is authenticated, origin-checked, scoped, rate-limited, and audited;
+3. every action uses the same safety/execution boundary as UI, voice, REST, and CLI;
+4. config changes cannot leave stale clients, tools, capabilities, or brain prompts;
+5. the stable SDK v2 and 2026 protocol contract pass on all supported OS/headless paths;
+6. external clients can discover and safely execute the live command surface without a parallel hand-maintained API.
diff --git a/jarvis/brain/turn_planner.py b/jarvis/brain/turn_planner.py
index 3df96e9a9c..e3911d4a6e 100644
--- a/jarvis/brain/turn_planner.py
+++ b/jarvis/brain/turn_planner.py
@@ -36,12 +36,23 @@ class TurnReason(StrEnum):
LOCAL_STATE = "local_state"
MISSION = "mission"
PRIVATE_DATA = "private_data"
+ PUBLIC_FACT = "public_fact"
SCREEN_CONTEXT = "screen_context"
SKILL = "skill"
UNCERTAIN = "uncertain"
WORKSPACE = "workspace"
+class GroundingFailurePolicy(StrEnum):
+ """Required behavior when public-fact evidence cannot be obtained."""
+
+ HONEST_UNCERTAINTY = "honest_uncertainty"
+
+
+PUBLIC_FACT_GROUNDING_CAPABILITY = "search_web"
+PUBLIC_FACT_GROUNDING_TIMEOUT_S = 2.5
+
+
@dataclass(frozen=True)
class TurnPlan:
"""Provider-neutral plan consumed by Pipeline and Realtime."""
@@ -50,6 +61,10 @@ class TurnPlan:
reasons: frozenset[TurnReason] = frozenset()
required_capabilities: tuple[str, ...] = ()
requires_evidence: bool = False
+ requires_public_fact_grounding: bool = False
+ public_fact_grounding_timeout_s: float | None = None
+ public_fact_grounding_attempt_limit: int = 0
+ grounding_failure_policy: GroundingFailurePolicy | None = None
@property
def requires_orchestrator(self) -> bool:
@@ -133,6 +148,32 @@ _CURRENT_RE = re.compile(
r"actual\w*|ultimo\w*|hoy|manana|ahora|reciente\w*|noticias|"
r"clima|tiempo|estado|disponible)\b" # i18n-allow: multilingual speech-input matching data
)
+
+# Factual question/request shapes are deliberately narrower than the general
+# lookup vocabulary. This boundary is used only when a provider declares that
+# its unaided public-fact recall is not a trustworthy source. It must not turn
+# advice, how-to requests, private data, or connected data into web searches.
+_PUBLIC_FACT_QUESTION_RE = re.compile(
+ r"^\s*(?:(?:hey|hello|hi|hallo|hola|okay|ok|jarvis|please|bitte|"
+ r"por favor)[\s,]+){0,3}(?:"
+ r"who\b|where\b|when\b|which\b|"
+ r"what\s+(?:is|are|was|were|did|does|has|have)\b|"
+ r"how\s+(?:many|much|old|long|large|big|tall|far)\b|"
+ r"wer\b|wo\b|wann\b|welch\w*\b|"
+ r"was\s+(?:ist|sind|war|waren|hat|haben|macht|machte)\b|" # i18n-allow
+ r"wie\s+(?:viel|viele|alt|lang|gross|weit)\b|" # i18n-allow: speech input
+ r"quien\b|donde\b|cuando\b|cual\w*\b|cuant\w*\b|"
+ r"que\s+(?:es|son|fue|eran|hizo|hace|tiene|tienen)\b"
+ r")" # i18n-allow: multilingual speech-input matching data
+)
+_PUBLIC_FACT_REQUEST_RE = re.compile(
+ r"^\s*(?:(?:hey|hello|hi|hallo|hola|okay|ok|jarvis|please|bitte|"
+ r"por favor)[\s,]+){0,3}(?:"
+ r"tell me|give me|look up|search(?: for)?|check|find|"
+ r"sag mir|nenne mir|such\w*|pruef\w*|find\w*|"
+ r"dime|busca|revisa|encuentra"
+ r")\b" # i18n-allow: multilingual speech-input matching data
+)
_LOCAL_STATE_RE = re.compile(
r"\b(?:wiki|mcp\w*|cli\w*|tool\w*|plugin\w*|connector\w*|"
r"integration\w*|setting\w*|configuration\w*|api[\s-]?key\w*|"
@@ -523,6 +564,22 @@ def is_contextual_follow_up(text: str, context: Sequence[str]) -> bool:
)
+def is_public_fact_question(text: str) -> bool:
+ """Return whether ``text`` asks for a concrete public-world fact.
+
+ This is a form classifier, not a freshness or provider decision. Callers
+ must still exclude private, connected, local-state, and action evidence.
+ Keeping it deterministic makes it safe on the voice hot path.
+ """
+ normalized = _normalize(text).strip()
+ if not normalized or _INSTRUCTIONAL_RE.search(normalized):
+ return False
+ return bool(
+ _PUBLIC_FACT_QUESTION_RE.search(normalized)
+ or _PUBLIC_FACT_REQUEST_RE.search(normalized)
+ )
+
+
def plan_turn(
text: str,
*,
@@ -532,6 +589,7 @@ def plan_turn(
context: Sequence[str] = (),
skill_index: Any | None = None,
workspace_names: Sequence[str] = (),
+ requires_public_fact_grounding: bool = False,
) -> TurnPlan:
"""Return the conservative shared execution plan for ``text``.
@@ -557,6 +615,12 @@ def plan_turn(
passed IN rather than looked up, so this module keeps holding no registry
reference; see ``_is_workspace_turn`` for why a runtime-chosen name can
never be covered by the static vocabularies.
+
+ ``requires_public_fact_grounding`` is a provider capability, never a
+ provider-name check. When true, concrete public-fact turns take the same
+ one-shot ``search_web`` evidence path used for explicitly fresh facts.
+ Hosted providers keep the default false and retain the native evergreen
+ fast path.
""" # i18n-allow: names the German trigger words the static branch matches
normalized = _normalize(text).strip()
if not normalized:
@@ -792,6 +856,47 @@ def plan_turn(
):
reasons.add(TurnReason.UNCERTAIN)
+ # Public fact grounding is an evidence contract, not another research
+ # router. Explicitly fresh public facts always ground. Evergreen facts do
+ # so only when the active model declares that requirement. Connected and
+ # private lookups retain their own tools and must never leak into web
+ # search. Set de-duplication gives the execution layer exactly one required
+ # search capability even if the live tool catalog matched it too.
+ non_public_evidence = reasons & {
+ TurnReason.LOCAL_STATE,
+ TurnReason.MISSION,
+ TurnReason.PRIVATE_DATA,
+ TurnReason.SCREEN_CONTEXT,
+ TurnReason.SKILL,
+ TurnReason.WORKSPACE,
+ }
+ required_without_public_search = {
+ item for item in required if item != PUBLIC_FACT_GROUNDING_CAPABILITY
+ }
+ if TurnReason.CAPABILITY in reasons and required_without_public_search:
+ non_public_evidence.add(TurnReason.CAPABILITY)
+ if TurnReason.CONNECTED_DATA in reasons and (
+ required_without_public_search
+ or _CONNECTED_DOMAIN_RE.search(normalized)
+ or _CONTACT_DETAIL_RE.search(normalized)
+ or private
+ ):
+ non_public_evidence.add(TurnReason.CONNECTED_DATA)
+ public_fact_shape = is_public_fact_question(text)
+ fresh_public_fact = (
+ TurnReason.CURRENT_DATA in reasons
+ and (public_fact_shape or lookup)
+ and not non_public_evidence
+ )
+ ground_public_fact = fresh_public_fact or (
+ bool(requires_public_fact_grounding)
+ and public_fact_shape
+ and not non_public_evidence
+ )
+ if ground_public_fact:
+ reasons.add(TurnReason.PUBLIC_FACT)
+ required = tuple(sorted({*required, PUBLIC_FACT_GROUNDING_CAPABILITY}))
+
if not reasons:
return TurnPlan(path=TurnPath.NATIVE_REALTIME)
return TurnPlan(
@@ -806,6 +911,7 @@ def plan_turn(
TurnReason.CURRENT_DATA,
TurnReason.LOCAL_STATE,
TurnReason.PRIVATE_DATA,
+ TurnReason.PUBLIC_FACT,
TurnReason.SCREEN_CONTEXT,
# What the pane actually printed is evidence the live model
# never holds; answering "what has Dana done" without it is
@@ -813,13 +919,27 @@ def plan_turn(
TurnReason.WORKSPACE,
}
),
+ requires_public_fact_grounding=ground_public_fact,
+ public_fact_grounding_timeout_s=(
+ PUBLIC_FACT_GROUNDING_TIMEOUT_S if ground_public_fact else None
+ ),
+ public_fact_grounding_attempt_limit=1 if ground_public_fact else 0,
+ grounding_failure_policy=(
+ GroundingFailurePolicy.HONEST_UNCERTAINTY
+ if ground_public_fact
+ else None
+ ),
)
__all__ = [
+ "GroundingFailurePolicy",
+ "PUBLIC_FACT_GROUNDING_CAPABILITY",
+ "PUBLIC_FACT_GROUNDING_TIMEOUT_S",
"TurnPath",
"TurnPlan",
"TurnReason",
"is_contextual_follow_up",
+ "is_public_fact_question",
"plan_turn",
]
diff --git a/jarvis/codex_app_server.py b/jarvis/codex_app_server.py
index 724414a38a..2842e24862 100644
--- a/jarvis/codex_app_server.py
+++ b/jarvis/codex_app_server.py
@@ -52,8 +52,13 @@ log = logging.getLogger(__name__)
_DEFAULT_REQUEST_TIMEOUT_S: Final = 20.0
# How long a passed cold-start audit may be ridden by a SECOND thread_start on
# the same process (the STUN media-path retry). Short on purpose: warm starts
-# minutes later must re-audit in full.
+# minutes later must re-audit in full. ``prime_startup_audit`` mints a wake
+# ride under the same TTL — always from an audit that actually completed.
_STARTUP_AUDIT_TTL_S: Final = 10.0
+# How long a per-host STUN media-path memory stays valid. Long enough to span
+# a working session on one network, short enough that a laptop moving networks
+# gets a fresh host-candidate attempt within the hour.
+_STUN_MEDIA_PATH_TTL_S: Final = 3600.0
_SHUTDOWN_TIMEOUT_S: Final = 2.0
_DEFAULT_SDP_TIMEOUT_S: Final = 15.0
_DEFAULT_NOTIFICATION_QUEUE_SIZE: Final = 512
@@ -336,6 +341,58 @@ _DECLINE_REQUEST_METHODS: Final = frozenset(
)
_DYNAMIC_TOOL_REQUEST_METHODS: Final = frozenset({"item/tool/call"})
+# Per-host memory of the WebRTC media path the LAST successful connect needed.
+# In-process only and TTL-bounded on purpose: network topology is a property
+# of this machine on this network right now, so persisting it would replay a
+# stale environment. A host recorded here needed a server-reflexive (STUN)
+# candidate, which means a host-candidates-only first attempt is known to be
+# doomed and would cost a full second open (thread_start bundle included).
+# Guarded by a lock because callers may record from executor threads.
+_stun_media_path_lock = threading.Lock()
+_stun_media_path_memory: dict[str, float] = {}
+
+
+def _stun_media_path_key(host: str) -> str:
+ return str(host or "").strip().lower()
+
+
+def record_media_path_outcome(host: str, *, needed_stun: bool) -> None:
+ """Remember whether the last successful connect to ``host`` needed STUN.
+
+ Call this only after a connect actually succeeded: a successful
+ host-candidate path clears the memory, a successful STUN path arms it so
+ the next open for the same host starts with STUN directly instead of
+ paying a doomed host-only attempt first.
+ """
+ key = _stun_media_path_key(host)
+ if not key:
+ return
+ with _stun_media_path_lock:
+ if needed_stun:
+ _stun_media_path_memory[key] = time.monotonic()
+ else:
+ _stun_media_path_memory.pop(key, None)
+
+
+def media_path_prefers_stun(host: str) -> bool:
+ """Whether the last successful connect to ``host`` needed a STUN candidate.
+
+ Returns ``False`` for unknown hosts and for stale entries — the memory is
+ an optimization, never a gate, so forgetting only restores today's
+ host-candidates-first behavior.
+ """
+ key = _stun_media_path_key(host)
+ if not key:
+ return False
+ with _stun_media_path_lock:
+ recorded_at = _stun_media_path_memory.get(key)
+ if recorded_at is None:
+ return False
+ if time.monotonic() - recorded_at > _STUN_MEDIA_PATH_TTL_S:
+ del _stun_media_path_memory[key]
+ return False
+ return True
+
class CodexAppServerError(RuntimeError):
"""Base error for the local app-server transport."""
@@ -1967,6 +2024,73 @@ def _validated_realtime_initial_items(
return validated
+def _validated_realtime_audited_optional(
+ *,
+ realtime_start_instructions: str | None,
+ realtime_end_instructions: str | None,
+ codex_responses_as_items: bool | None,
+ codex_response_item_prefix: str | None,
+ codex_response_handoff_mode: str | None,
+ codex_response_handoff_channel_prefixes: Sequence[str] | None,
+) -> dict[str, Any]:
+ """Validate the optional 0.147-audited realtime start fields.
+
+ Field names mirror the upstream ``ThreadRealtimeStartParams`` schema
+ byte-for-byte (verified against the codex-cli 0.147.0 binary's serde name
+ table): ``realtimeStartInstructions``, ``realtimeEndInstructions``,
+ ``codexResponsesAsItems``, ``codexResponseItemPrefix``,
+ ``codexResponseHandoffMode``, ``codexResponseHandoffChannelPrefixes``.
+ Only fields the caller actually provided are returned; empty strings and
+ empty sequences count as not provided.
+ """
+ audited: dict[str, Any] = {}
+ instruction_fields = (
+ ("realtimeStartInstructions", realtime_start_instructions),
+ ("realtimeEndInstructions", realtime_end_instructions),
+ )
+ for field_name, value in instruction_fields:
+ if value is None:
+ continue
+ if not isinstance(value, str):
+ raise CodexSubscriptionUnavailable("Codex realtime session instructions are invalid.")
+ clean = value.strip()
+ if len(clean.encode("utf-8")) > _MAX_REALTIME_START_PROMPT_BYTES:
+ raise CodexSubscriptionUnavailable("Codex realtime session instructions are too large.")
+ if clean:
+ audited[field_name] = clean
+ if codex_responses_as_items is not None:
+ if not isinstance(codex_responses_as_items, bool):
+ raise CodexSubscriptionUnavailable("Codex realtime handoff routing fields are invalid.")
+ audited["codexResponsesAsItems"] = codex_responses_as_items
+ string_fields = (
+ ("codexResponseItemPrefix", codex_response_item_prefix),
+ ("codexResponseHandoffMode", codex_response_handoff_mode),
+ )
+ for field_name, value in string_fields:
+ if value is None:
+ continue
+ if not isinstance(value, str):
+ raise CodexSubscriptionUnavailable("Codex realtime handoff routing fields are invalid.")
+ clean = value.strip()
+ if clean:
+ audited[field_name] = clean
+ if codex_response_handoff_channel_prefixes is not None:
+ if isinstance(codex_response_handoff_channel_prefixes, (str, bytes)) or not isinstance(
+ codex_response_handoff_channel_prefixes, Sequence
+ ):
+ raise CodexSubscriptionUnavailable("Codex realtime handoff routing fields are invalid.")
+ prefixes: list[str] = []
+ for prefix in codex_response_handoff_channel_prefixes:
+ if not isinstance(prefix, str) or not prefix.strip():
+ raise CodexSubscriptionUnavailable(
+ "Codex realtime handoff routing fields are invalid."
+ )
+ prefixes.append(prefix.strip())
+ if prefixes:
+ audited["codexResponseHandoffChannelPrefixes"] = prefixes
+ return audited
+
+
def _config_layers(result: Mapping[str, Any]) -> tuple[Mapping[str, Any], ...]:
raw_layers = result.get("layers")
if not isinstance(raw_layers, list):
@@ -2205,10 +2329,20 @@ class CodexAppServerClient:
# retry rides the same audit instead of re-running three RPCs and a
# profile walk. Warm starts minutes later still re-audit in full, so
# "re-read immediately before EVERY subscription thread" keeps its
- # meaning.
+ # meaning (the wake ride below is the one TTL-bounded exception, and
+ # it too exists only because a full audit just passed).
self._startup_audit_process: asyncio.subprocess.Process | None = None
self._audited_process: asyncio.subprocess.Process | None = None
self._startup_audit_at = 0.0
+ # Wake ride minted by ``prime_startup_audit``: a warm/verify pass that
+ # just COMPLETED the full startup audit stamps this (process, time)
+ # pair so one wake-word thread start arriving within the same short
+ # TTL can ride that audit instead of repeating it on the identical
+ # process. One-shot — thread_start consumes it on first read — and
+ # never minted without a full audit actually passing, so the audit
+ # itself is not weakened, only de-duplicated.
+ self._warm_audit_process: asyncio.subprocess.Process | None = None
+ self._warm_audit_at = 0.0
def _assert_owner_loop(self) -> asyncio.AbstractEventLoop:
loop = asyncio.get_running_loop()
@@ -2565,6 +2699,69 @@ class CodexAppServerClient:
expected=False,
)
raise
+ # The verify pass just proved the account; completing the FULL startup
+ # audit here (off the wake critical path) lets one wake word inside
+ # the ride TTL skip the byte-identical re-audit in ``thread_start``.
+ await self.prime_startup_audit()
+
+ async def prime_startup_audit(self) -> None:
+ """Complete the full startup audit now and mint the one-shot wake ride.
+
+ Runs the byte-identical audit ``thread_start`` performs (profile walk,
+ live ``account/read``, config requirements, effective config) under the
+ same lock that serializes thread starts, then stamps the short-TTL
+ one-shot ride token. A wake word arriving within the TTL rides this
+ just-passed audit instead of paying it again on the same process; a
+ wake word arriving later re-audits in full, so "re-read immediately
+ before EVERY subscription thread" keeps its meaning. The token is only
+ ever minted from an audit that actually completed — this method never
+ skips or weakens any check, it only moves the identical work off the
+ wake critical path.
+ """
+ await self.ensure_started()
+ async with self._thread_start_lock:
+ live_process = self._process
+ if live_process is None or live_process.returncode is not None:
+ raise CodexAppServerDisconnected("Codex app-server is not running.")
+ if (
+ self._audited_process is live_process
+ and time.monotonic() - self._startup_audit_at <= _STARTUP_AUDIT_TTL_S
+ ):
+ # A full audit of this very process passed within the TTL
+ # (cold start or a warm thread_start re-audit). Re-mint the
+ # wake ride from that stamp — its TTL still counts from the
+ # moment the audit actually passed.
+ self._warm_audit_process = live_process
+ self._warm_audit_at = self._startup_audit_at
+ return
+ 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:
+ if isinstance(exc, CodexSubscriptionPlanUnsupported):
+ # Same recording rule as the cold-start and warm-call
+ # paths: the sticky diagnosis is written where the truth
+ # is discovered.
+ await asyncio.shield(
+ asyncio.to_thread(set_codex_subscription_activation_block, str(exc))
+ )
+ error = type(exc)(str(exc))
+ await self._close_process(
+ CodexAppServerDisconnected("Codex app-server safety state changed."),
+ expected=False,
+ )
+ raise error from None
+ self._audited_process = live_process
+ self._startup_audit_at = time.monotonic()
+ self._warm_audit_process = live_process
+ self._warm_audit_at = self._startup_audit_at
async def _read_effective_config(self) -> dict[str, Any]:
return _result_dict(
@@ -3506,8 +3703,19 @@ class CodexAppServerClient:
# thread/start frame, so exactly one thread start can ride it and
# every WARM start still re-audits.
live_process = self._process
+ # The wake ride minted by ``prime_startup_audit`` is one-shot:
+ # reading it here consumes it whether or not it is still fresh,
+ # so a second wake on the same warm process always re-audits.
+ warm_ride_process = self._warm_audit_process
+ warm_ride_at = self._warm_audit_at
+ self._warm_audit_process = None
+ self._warm_audit_at = 0.0
audit_is_fresh = live_process is not None and (
self._startup_audit_process is live_process
+ or (
+ warm_ride_process is live_process
+ and time.monotonic() - warm_ride_at <= _STARTUP_AUDIT_TTL_S
+ )
or (
ride_recent_audit
and getattr(self, "_audited_process", None) is live_process
@@ -3648,6 +3856,12 @@ class CodexAppServerClient:
model: str | None = None,
include_startup_context: bool | None = None,
client_managed_handoffs: bool | None = None,
+ realtime_start_instructions: str | None = None,
+ realtime_end_instructions: str | None = None,
+ codex_responses_as_items: bool | None = None,
+ codex_response_item_prefix: str | None = None,
+ codex_response_handoff_mode: str | None = None,
+ codex_response_handoff_channel_prefixes: Sequence[str] | None = None,
extra: Mapping[str, Any] | None = None,
sdp_timeout_s: float = _DEFAULT_SDP_TIMEOUT_S,
) -> CodexRealtimeStartResult:
@@ -3671,6 +3885,14 @@ class CodexAppServerClient:
raise CodexSubscriptionUnavailable(
"Codex realtime startup history requires the audited v3 protocol."
)
+ audited_optional = _validated_realtime_audited_optional(
+ realtime_start_instructions=realtime_start_instructions,
+ realtime_end_instructions=realtime_end_instructions,
+ codex_responses_as_items=codex_responses_as_items,
+ codex_response_item_prefix=codex_response_item_prefix,
+ codex_response_handoff_mode=codex_response_handoff_mode,
+ codex_response_handoff_channel_prefixes=codex_response_handoff_channel_prefixes,
+ )
params = {
"clientManagedHandoffs": True,
"includeStartupContext": False,
@@ -3688,6 +3910,17 @@ class CodexAppServerClient:
and self._trusted_binary_version == _SUPPORTED_CODEX_VERSION
):
params["delegationAckFiller"] = False
+ # Same 0.147/v3 gate for the caller-provided audited fields: the
+ # start/end instruction slots and the codexResponse* handoff
+ # routing controls. Outside the gate they are omitted (and named
+ # in the log) rather than sent — an older approved binary must
+ # never receive unknown fields.
+ params.update(audited_optional)
+ elif audited_optional:
+ log.info(
+ "Codex realtime start omitted 0.147-audited fields for this binary/protocol: %s",
+ ", ".join(sorted(audited_optional)),
+ )
optional: dict[str, Any] = {
"version": version,
"voice": voice,
@@ -3800,6 +4033,19 @@ class CodexAppServerClient:
),
)
+ async def realtime_list_voices(self, thread_id: str) -> dict[str, Any]:
+ """Read the server's realtime voice roster (``RealtimeVoicesList``).
+
+ Same JSON-RPC plumbing as the other realtime methods. A server build
+ without ``thread/realtime/listVoices`` answers with a JSON-RPC error
+ that surfaces as :class:`CodexAppServerRPCError`, so callers can fall
+ back to their audited static roster instead of failing the session.
+ """
+ return _result_dict(
+ "thread/realtime/listVoices",
+ await self.request("thread/realtime/listVoices", {"threadId": thread_id}),
+ )
+
async def realtime_stop(self, thread_id: str) -> dict[str, Any]:
return await self._teardown_request(
"thread/realtime/stop", {"threadId": thread_id}
@@ -3812,6 +4058,8 @@ class CodexAppServerClient:
self._startup_audit_process = None
self._audited_process = None
self._startup_audit_at = 0.0
+ self._warm_audit_process = None
+ self._warm_audit_at = 0.0
self._close_lifeline()
if self._profile_transport_epoch is not None:
# Epoch first, release off-loop and shielded: a cancellation
@@ -3829,6 +4077,8 @@ class CodexAppServerClient:
self._startup_audit_process = None
self._audited_process = None
self._startup_audit_at = 0.0
+ self._warm_audit_process = None
+ self._warm_audit_at = 0.0
tree = self._process_tree
self._process_tree = None
reader_task = self._reader_task
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index 171e8da828..11c28db52c 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -1652,6 +1652,13 @@ class RealtimeSessionPostmortem(Event):
ready_ms: int = 0
#: audio_start → first provider audio frame emitted to the surface.
first_audio_ms: int = 0
+ #: First user FINAL of the call → first AUDIBLE provider frame after it.
+ #: This is the user-perceived answer wait; ``first_audio_ms`` stays for
+ #: continuity but counts from session start and therefore includes the
+ #: user's own listening/speaking time (a codex call measured 8 311 ms
+ #: from start while the wait after the utterance was 923 ms, 2026-08-08).
+ #: 0 means "never measured" (no final, or no audible audio after one).
+ first_final_to_first_audio_ms: int = 0
turns_completed: int = 0
#: In-place transport rebuilds this session survived (BUG-071 machinery).
rebuilds: int = 0
@@ -1671,6 +1678,22 @@ class RealtimeSessionPostmortem(Event):
response_splices: int = 0
#: Splices converted into clean local boundaries by the sequencing drain.
sequenced_boundaries: int = 0
+ #: Bounded local-STT passes started before a provider transcript arrived.
+ output_shadow_recovery_attempts: int = 0
+ #: Early local-STT passes that produced gate-only vetting text.
+ output_shadow_recovery_successes: int = 0
+ #: Responses that exhausted their bounded early local-STT attempts.
+ output_shadow_recovery_exhausted: int = 0
+ #: Authoritative local-STT passes started at a response boundary.
+ output_terminal_recovery_attempts: int = 0
+ #: Terminal passes that recovered the missing provider transcript.
+ output_terminal_recovery_successes: int = 0
+ #: Local-STT output recovery attempts that failed or produced no text.
+ output_transcript_recovery_failures: int = 0
+ #: Late/mismatched response events dropped before text could clear PCM.
+ response_identity_drops: int = 0
+ #: Provider responses cancelled by the fail-closed output gate.
+ unsafe_output_cancellations: int = 0
#: Opening responses cut at the cap because no user question existed yet.
opening_responses_bounded: int = 0
#: Self-dialogue verdicts that forced a transport replacement (BUG-124).
@@ -1685,6 +1708,12 @@ class RealtimeSessionPostmortem(Event):
handoff_declines: int = 0
#: Action turns where the provider omitted its required handoff event.
handoff_obligation_misses: int = 0
+ #: Delegate-by-default dispatches on a tool-less transport: finals the
+ #: planner routed natively but whose assistant-tasking shape made the
+ #: session delegate anyway rather than let the far end answer unaided.
+ #: Distinct from ``handoff_delegate_dispatches`` (all deterministic
+ #: dispatches) and ``handoff_requests`` (model-initiated handoffs).
+ handoff_ambiguous_delegations: int = 0
#: Half-duplex mutes released by the emergency timer, not a turn boundary.
mute_emergency_releases: int = 0
#: Microphone sender wall-clock resyncs (mic audio lost to a stall).
diff --git a/jarvis/core/turn_language.py b/jarvis/core/turn_language.py
index fd9e5e1638..e9b0551df1 100644
--- a/jarvis/core/turn_language.py
+++ b/jarvis/core/turn_language.py
@@ -25,18 +25,24 @@ This module is the single source of truth for the language of a turn:
Pure regex / set lookups — no LLM, no IO. Safe on the voice critical path
(AP-9 / AP-11).
"""
+
from __future__ import annotations
import re
+import unicodedata
+from dataclasses import dataclass
+from typing import Literal
__all__ = [
"DEFAULT_LOCALE",
+ "OutputLanguageValidation",
"detect_text_language",
"is_substantive_turn",
"normalize_language_tag",
"resolve_output_language",
"resolve_transcript_language",
"resolve_turn_language",
+ "validate_output_language",
]
#: The fallback spoken/written language for a turn whose language cannot be
@@ -60,9 +66,64 @@ _THIN_TURN_MAX_TOKENS = 2
_TOKEN_RE = re.compile(r"\b[\w']+\b", re.UNICODE)
-# Strong script signals: umlauts/ß occur in German only; inverted punctuation # i18n-allow: English comment; literal umlaut/ß characters named for illustration only
-# and accented vowels (minus the pan-European é) point to Spanish.
-_DE_SCRIPT_RE = re.compile(r"[äöüÄÖÜß]") # i18n-allow: German-script detection regex, matched in logic (core of the language resolver)
+# Output validation deliberately ignores code and links. They frequently carry
+# English keywords or non-Latin identifiers regardless of the language of the
+# surrounding answer, so treating them as prose would create false positives.
+_CODE_FENCE_RE = re.compile(r"```.*?```", re.DOTALL)
+_INLINE_CODE_RE = re.compile(r"`[^`\r\n]*`")
+_URL_RE = re.compile(r"\b(?:https?://|www\.)\S+", re.IGNORECASE)
+
+# Han text has a unique script signal. A ratio is still required so a German,
+# English, or Spanish sentence containing a Chinese name remains valid.
+_HAN_RE = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]")
+_LATIN_LETTER_RE = re.compile(r"[A-Za-z\u00c0-\u024f]")
+
+# Vietnamese uses Latin script, so script alone is insufficient. The validator
+# combines its characteristic letters/tones with a vocabulary signal and only
+# returns a verdict when both make a gross mismatch unambiguous.
+_VI_DISTINCTIVE_CHAR_RE = re.compile(
+ r"[\u0103\u00e2\u0111\u00ea\u00f4\u01a1\u01b0"
+ r"\u1ea3\u1ea1\u1eb1\u1eaf\u1eb3\u1eb5\u1eb7"
+ r"\u1ea7\u1ea5\u1ea9\u1eab\u1ead\u1ebb\u1ebd\u1eb9"
+ r"\u1ec1\u1ebf\u1ec3\u1ec5\u1ec7\u1ec9\u1ecb"
+ r"\u1ecf\u1ecd\u1ed3\u1ed1\u1ed5\u1ed7\u1ed9"
+ r"\u1edd\u1edb\u1edf\u1ee1\u1ee3\u1ee7\u1ee5"
+ r"\u1eeb\u1ee9\u1eed\u1eef\u1ef1\u1ef3\u1ef7\u1ef9\u1ef5]",
+ re.IGNORECASE,
+)
+_VI_TOKENS: frozenset[str] = frozenset(
+ """
+ bạn bằng các chào chúng có của đã được giúp hãy không là một này người
+ những sẽ thể tiếng tôi việt với
+ """.split()
+)
+
+OutputLanguageStatus = Literal["match", "mismatch", "indeterminate"]
+
+
+@dataclass(frozen=True, slots=True)
+class OutputLanguageValidation:
+ """Deterministic verdict for text checked against a resolved turn language.
+
+ ``indeterminate`` is intentionally fail-open: short replies, code, names,
+ numbers, and ambiguous prose do not provide enough evidence to suppress
+ user-facing output. Only ``mismatch`` is safe to block before text/audio
+ release.
+ """
+
+ status: OutputLanguageStatus
+ resolved_language: str
+ detected_language: str
+
+ @property
+ def should_block(self) -> bool:
+ """Whether the caller should suppress this output and retry/fallback."""
+ return self.status == "mismatch"
+
+
+# Strong script signals: German-specific letters and Spanish punctuation or
+# accented vowels (minus the pan-European acute-e) are useful hints.
+_DE_SCRIPT_RE = re.compile(r"[äöüÄÖÜß]") # i18n-allow: German-script regex
_ES_SCRIPT_RE = re.compile(r"[áíóúñÁÍÓÚÑ¿¡]")
# Function-word sets, kept mutually disjoint. Words common to more than one of
@@ -146,6 +207,89 @@ def detect_text_language(text: str) -> str:
return best_code
+def _prose_for_output_validation(text: str) -> str:
+ """Remove content whose syntax is not evidence of the reply language."""
+ prose = unicodedata.normalize("NFC", text or "")
+ prose = _CODE_FENCE_RE.sub(" ", prose)
+ prose = _INLINE_CODE_RE.sub(" ", prose)
+ return _URL_RE.sub(" ", prose).strip()
+
+
+def _detect_gross_han_output(text: str) -> bool:
+ han_count = len(_HAN_RE.findall(text))
+ if han_count < 4:
+ return False
+ latin_count = len(_LATIN_LETTER_RE.findall(text))
+ script_ratio = han_count / max(1, han_count + latin_count)
+ return script_ratio >= 0.55
+
+
+def _detect_gross_vietnamese_output(text: str, tokens: list[str]) -> bool:
+ if len(tokens) < 5:
+ return False
+ characteristic_chars = len(_VI_DISTINCTIVE_CHAR_RE.findall(text))
+ distinct_vocabulary_hits = len(set(tokens) & _VI_TOKENS)
+ return characteristic_chars >= 2 and distinct_vocabulary_hits >= 2
+
+
+def _detect_strong_supported_output(text: str, tokens: list[str]) -> str:
+ """Return de/en/es only when multiple independent prose signals agree."""
+ if len(tokens) < 4:
+ return "unknown"
+ scores = {
+ code: sum(token in vocabulary for token in tokens)
+ for code, vocabulary in _SETS
+ }
+ if _DE_SCRIPT_RE.search(text):
+ scores["de"] += 2
+ if _ES_SCRIPT_RE.search(text):
+ scores["es"] += 2
+ ranked = sorted(scores.items(), key=lambda item: item[1], reverse=True)
+ (best_code, best_score), (_, second_score) = ranked[:2]
+ if best_score < 3 or best_score == second_score:
+ return "unknown"
+ return best_code
+
+
+def validate_output_language(
+ text: str,
+ *,
+ resolved_language: object,
+) -> OutputLanguageValidation:
+ """Validate reply *text* against an already-resolved ``de``/``en``/``es``.
+
+ The target MUST come from :func:`resolve_output_language`; this function
+ never derives or changes the turn language. It only detects high-confidence
+ output corruption before text or audio is released. Detection is regex/set
+ based, has no IO or model call, and treats uncertain content as
+ ``indeterminate`` (non-blocking).
+ """
+ target = normalize_language_tag(resolved_language)
+ if target not in _REPLY_PINS:
+ return OutputLanguageValidation("indeterminate", target, "unknown")
+
+ prose = _prose_for_output_validation(text)
+ if not prose:
+ return OutputLanguageValidation("indeterminate", target, "unknown")
+
+ if _detect_gross_han_output(prose):
+ detected = "zh"
+ else:
+ tokens = [token.lower() for token in _TOKEN_RE.findall(prose)]
+ if _detect_gross_vietnamese_output(prose, tokens):
+ detected = "vi"
+ else:
+ detected = _detect_strong_supported_output(prose, tokens)
+
+ if detected == "unknown":
+ status: OutputLanguageStatus = "indeterminate"
+ elif detected == target:
+ status = "match"
+ else:
+ status = "mismatch"
+ return OutputLanguageValidation(status, target, detected)
+
+
def resolve_turn_language(
stt_language: object, text: str, *, default: str = "en"
) -> str:
diff --git a/jarvis/diagnostics/realtime_forensics.py b/jarvis/diagnostics/realtime_forensics.py
index 67d5fb044a..3880325f4a 100644
--- a/jarvis/diagnostics/realtime_forensics.py
+++ b/jarvis/diagnostics/realtime_forensics.py
@@ -21,6 +21,14 @@ from typing import Any
#: Spawn budgets. The forensics report treats an overrun as a WARN; the live
#: probe starts at WARN too and flips to FAIL once the latency phase lands
#: (that flip lives in the probe, deliberately not here).
+#:
+#: The first-audio budget judges ``first_final_to_first_audio_ms`` — the wait
+#: the USER experiences between finishing an utterance and hearing the answer.
+#: It deliberately does NOT judge ``first_audio_ms``: that metric counts from
+#: session start and therefore includes the user's own speaking/listening
+#: time, so a healthy codex call (8 311 ms from start, 923 ms after the
+#: final, live 2026-08-08) read as a budget breach. ``first_audio_ms`` stays
+#: in the payload and the detail line for continuity with old recordings.
SPAWN_READY_BUDGET_MS = 4_000
SPAWN_FIRST_AUDIO_BUDGET_MS = 6_000
@@ -62,6 +70,39 @@ def evaluate_postmortem(pm: Mapping[str, Any]) -> list[RealtimeFinding]:
)
)
+ identity_drops = _count(pm, "response_identity_drops")
+ if identity_drops:
+ add(
+ RealtimeFinding(
+ "high",
+ "response-identity-mismatch",
+ f"{identity_drops} late or mismatched provider response "
+ "event(s) were dropped before transcript could clear PCM",
+ )
+ )
+
+ unsafe_cancellations = _count(pm, "unsafe_output_cancellations")
+ recovery_failures = _count(pm, "output_transcript_recovery_failures")
+ if unsafe_cancellations or recovery_failures:
+ add(
+ RealtimeFinding(
+ "high",
+ "output-transcript-recovery-failed",
+ f"{recovery_failures} local transcript recovery attempt(s) "
+ f"failed and {unsafe_cancellations} provider response(s) "
+ "were cancelled fail-closed",
+ )
+ )
+ elif _count(pm, "output_shadow_recovery_exhausted"):
+ add(
+ RealtimeFinding(
+ "warn",
+ "output-shadow-recovery-exhausted",
+ "bounded early output-transcript recovery was exhausted; "
+ "the provider transcript or terminal pass still completed",
+ )
+ )
+
quiescence = _count(pm, "quiescence_boundary_turns")
if quiescence:
add(
@@ -202,16 +243,21 @@ def evaluate_postmortem(pm: Mapping[str, Any]) -> list[RealtimeFinding]:
ready_ms = _count(pm, "ready_ms")
first_audio_ms = _count(pm, "first_audio_ms")
+ response_ms = _count(pm, "first_final_to_first_audio_ms")
over_ready = ready_ms > SPAWN_READY_BUDGET_MS
- over_first = bool(first_audio_ms) and first_audio_ms > SPAWN_FIRST_AUDIO_BUDGET_MS
+ # 0 means "never measured" (pre-metric recording, no final, or no audible
+ # audio after one) — silence there is reported by other counters, and an
+ # absent metric must not fabricate a budget breach.
+ over_first = bool(response_ms) and response_ms > SPAWN_FIRST_AUDIO_BUDGET_MS
if over_ready or over_first:
add(
RealtimeFinding(
"warn",
"spawn-over-budget",
f"ready {ready_ms} ms (budget {SPAWN_READY_BUDGET_MS}), "
- f"first audio {first_audio_ms} ms "
- f"(budget {SPAWN_FIRST_AUDIO_BUDGET_MS})",
+ f"first audio {response_ms} ms after the first user final "
+ f"(budget {SPAWN_FIRST_AUDIO_BUDGET_MS}; "
+ f"{first_audio_ms} ms from session start)",
)
)
diff --git a/jarvis/dictation/polish_guards.py b/jarvis/dictation/polish_guards.py
index 6a0e6d7bbb..48d1d6257e 100644
--- a/jarvis/dictation/polish_guards.py
+++ b/jarvis/dictation/polish_guards.py
@@ -352,10 +352,61 @@ _NUMBER_WORDS: Final[dict[str, frozenset[str]]] = {
}),
}
+# i18n-allow: the tables below are speech-input command vocabulary (§1 list
+# #3) — the literal German/Spanish words a dictation speaks to command a mark.
+#
+# The spoken FORMATTING commands, per language: the punctuation the prompt
+# turns into the mark itself ("comma" -> ","), and the layout commands behind
+# paragraphs and bullet lists ("new paragraph", "bullet point", and their
+# input-language equivalents). Two guards read this table:
+#
+# * the rare-token filter treats these words as common, because the licensed
+# conversion DELETES them — a spoken bullet command has no repaired spelling
+# in the answer, only the "- " that replaced it, and mourning it rejected
+# every commanded list;
+# * the word-count band counts them out of both sides of the ratio
+# (:func:`_ratio_word_count`), because a command becomes a mark and not a
+# word — a dictation that leans on commands hardest halves its word count
+# when formatted CORRECTLY, which an unadjusted band reads as a summariser
+# at work.
+#
+# Carrier words of multi-word commands ride along ("neuer" in "neuer Absatz", # i18n-allow
+# "nueva" in "nueva linea"): the command vanishes whole, so every word of it # i18n-allow
+# must be licensed. The cost of listing a homonym here ("Punkt" the content # i18n-allow
+# word, "mark", "dash") is that the guard no longer mourns it when a model
+# wrongly drops it — accepted, because the words are short, common in speech,
+# and the alternative rejects every dictation that uses the command.
+_FORMAT_COMMAND_WORDS: Final[dict[str, frozenset[str]]] = {
+ "en": frozenset({
+ "period", "comma", "colon", "semicolon", "hyphen", "dash",
+ "quote", "unquote", "quotes", "question", "exclamation", "mark",
+ "bullet", "bullets", "paragraph", "newline", "ellipsis",
+ "parenthesis", "parentheses", "bracket", "brackets", "slash",
+ }),
+ "de": frozenset({ # i18n-allow: German spoken commands (§1 list #3)
+ "punkt", "komma", "doppelpunkt", "semikolon", "strichpunkt", # i18n-allow
+ "fragezeichen", "ausrufezeichen", "bindestrich", "gedankenstrich", # i18n-allow
+ "anführungszeichen", "klammer", "klammern", "schrägstrich", # i18n-allow
+ "absatz", "zeile", "zeilenumbruch", "auslassungspunkte", # i18n-allow
+ "stichpunkt", "stichpunkte", "spiegelstrich", "aufzählungszeichen", # i18n-allow
+ "aufzählungspunkt", "neue", "neuer", "neues", "nächste", "nächster", # i18n-allow
+ }),
+ "es": frozenset({ # i18n-allow: Spanish spoken commands (§1 list #3)
+ "punto", "puntos", "coma", "aparte", "seguido", "interrogación", # i18n-allow
+ "interrogacion", "exclamación", "exclamacion", "guion", "guión", # i18n-allow
+ "raya", "comillas", "paréntesis", "parentesis", "párrafo", "parrafo", # i18n-allow
+ "línea", "linea", "viñeta", "vineta", "salto", "nueva", "nuevo", # i18n-allow
+ "siguiente", # i18n-allow
+ }),
+}
+
#: The lookup the rarity filter actually uses: ordinary vocabulary plus the
-#: number words, per language. Anything absent from here is "rare".
+#: number words and the spoken formatting commands, per language. Anything
+#: absent from here is "rare".
_COMMON_WORDS: Final[dict[str, frozenset[str]]] = {
- code: base | _NUMBER_WORDS.get(code, frozenset())
+ code: base
+ | _NUMBER_WORDS.get(code, frozenset())
+ | _FORMAT_COMMAND_WORDS.get(code, frozenset())
for code, base in _COMMON_WORDS_BASE.items()
}
diff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.py
index 39d20047c4..d23794527a 100644
--- a/jarvis/plugins/realtime/codex_subscription.py
+++ b/jarvis/plugins/realtime/codex_subscription.py
@@ -27,20 +27,35 @@ log = logging.getLogger(__name__)
_INPUT_RATE = 24_000
_OUTPUT_RATE = 24_000
-_BROKER_OFFER_WAIT_S = 3.0
# No audible frame for this long ends the turn. It is a BACKSTOP, not the
# boundary: the terminal response item ends a turn immediately. Measured
# in-reply pauses on ChatGPT-Live reach ~720 ms, so a shorter window would
# split a single answer at every breath.
_OUTPUT_QUIESCENCE_S = 1.2
-# Cap on a recognizer-LESS host's first (failopen) response. On grounded
-# hosts nothing unsolicited plays before the call's first user final at all
-# (maintainer live test 2026-08-08 killed the bounded-greeting compromise:
-# the opener's remainder re-earned grants and the first final adopted the
-# model's own echo-monologue as "the answer"). A host without any local
-# recognizer cannot ground anything, so its opening keeps only this coarse
-# bound against the 13.9 s demo-monologue class (live 2026-08-06 17:03).
+# Cap on EVERY response granted "failopen", i.e. while no local grounding
+# exists. On grounded hosts nothing unsolicited plays before the call's first
+# user final at all (maintainer live test 2026-08-08 killed the
+# bounded-greeting compromise: the opener's remainder re-earned grants and
+# the first final adopted the model's own echo-monologue as "the answer").
+# An ungrounded host cannot refuse anything, so this coarse bound is the
+# ONLY opposition it has — first observed against the 13.9 s demo-monologue
+# class (live 2026-08-06 17:03). Bounding only the opening response left
+# every later ungrounded response unbounded, and that unbounded regime is
+# why the two-AIs self-talk loop survived every grounded-path fix: a build
+# failure or a mid-call recognizer death handed the far end unlimited
+# responses for the rest of the call. A real answer fits comfortably under
+# the bound; a monologue is cut and the far end re-earns nothing by it.
_OPENING_RESPONSE_MAX_S = 6.0
+# A dead local recognizer STREAM is rebuilt at most this many times per call
+# before the session accepts the (bounded) ungrounded regime above. The
+# rebuild is cheap by design: the STT backend is cached process-wide in
+# ``jarvis.realtime.input_transcription``, so a rebuild re-attaches to the
+# live engine instead of paying a model load. Two attempts cover a transient
+# stream death without letting a crash-looping engine spin forever.
+_RECOGNIZER_REBUILDS_MAX = 2
+# Backoff before rebuild attempt N (linear in N), so an engine that dies the
+# moment it starts cannot hot-loop build/die inside one call.
+_RECOGNIZER_REBUILD_BACKOFF_S = 0.5
# A locally DISCARDED utterance (under the endpointer's minimum voiced
# length) keeps its response window this long. The far end heard the sound
# regardless of the local verdict and often answers it; consuming the
@@ -150,6 +165,10 @@ _REFUSAL_STORM_WINDOW_S = 10.0
# non-blocking lock makes a busy engine a skip, never a wedge).
_OUTPUT_EARLY_RECOVERY_AFTER_S = 1.2
_OUTPUT_EARLY_RECOVERY_RETRY_S = 1.0
+# The early pass is a latency rescue, not an unbounded retry loop. Two
+# single-flight attempts cover a recognizer that was briefly busy with the
+# microphone; the response boundary owns the one authoritative terminal pass.
+_OUTPUT_EARLY_RECOVERY_MAX_ATTEMPTS = 2
# The shadow attempt transcribes only this much of the response head: the
# gate needs SOME clean text, not the whole reply, and the recognizer's own
# time bound scales with the audio handed in — an uncapped, still-growing
@@ -180,7 +199,10 @@ _SPEECH_DISCARDED = "speech_discarded"
_LEGACY_V1_MODEL = "gpt-realtime-1.5"
_DEFAULT_VOICE = "cove"
# Server-confirmed v3 roster (the refusal for an unknown voice lists exactly
-# these nine, verified live 2026-08-01).
+# these nine, verified live 2026-08-01). Since codex-cli 0.147.0 the server
+# publishes its live roster through ``thread/realtime/listVoices``; this
+# frozenset is the explicit FALLBACK for a client or server build without
+# that method (see ``_live_voice_roster``), never the primary source.
_V3_VOICES = frozenset(
{
"arbor",
@@ -451,9 +473,7 @@ def _history_initial_items(history: Any) -> list[dict[str, str]]:
if role not in {"user", "assistant"} or not text:
continue
records.append({"role": role, "text": text[:2_000]})
- while sum(len(record["text"]) for record in records) > _HISTORY_MAX_CHARS and len(
- records
- ) > 1:
+ while sum(len(record["text"]) for record in records) > _HISTORY_MAX_CHARS and len(records) > 1:
records.pop(0)
return records
@@ -463,6 +483,91 @@ def _safe_error(exc: BaseException, *, max_chars: int = 500) -> str:
return (text or type(exc).__name__)[:max_chars]
+# One process-wide WARNING when the local recognizer's constructor rejects
+# the ``language`` keyword, DEBUG afterwards. The in-tree recognizer accepts
+# it since 2026-08-08, so this fires only against an older out-of-tree
+# module — but a swallowed capability probe at DEBUG is exactly how the
+# un-pinned session language survived unreported for days (AP-30).
+_language_kwarg_rejected_warned = False
+
+
+def _roster_voice_names(result: Any) -> frozenset[str]:
+ """Every voice name found in a ``RealtimeVoicesList`` result.
+
+ The result carries per-protocol lists (``v1``/``v2`` today) plus default
+ fields; which list feeds the live v3 surface is not documented, so every
+ list-valued entry contributes. Validation stays a membership check — an
+ over-broad union can only accept a voice the server itself announced.
+ """
+ if not isinstance(result, dict):
+ return frozenset()
+ names: set[str] = set()
+ for value in result.values():
+ if not isinstance(value, (list, tuple)):
+ continue
+ for entry in value:
+ if isinstance(entry, dict):
+ entry = entry.get("id", "") or entry.get("name", "")
+ name = str(entry or "").strip().lower()
+ if name:
+ names.add(name)
+ return frozenset(names)
+
+
+async def _live_voice_roster(client: Any, thread_id: str) -> frozenset[str]:
+ """The server's own realtime voice roster, or the audited static one.
+
+ Probed as a capability, never a version string (AP-21/AP-22): a client
+ without ``realtime_list_voices``, a server build that rejects the method
+ (a JSON-RPC refusal surfaces with a ``code`` attribute), or an unusable
+ result all degrade to ``_V3_VOICES`` — the roster the server itself
+ confirmed live 2026-08-01. A failure WITHOUT an RPC error code is a
+ transport failure, not a roster verdict, and propagates so the open
+ fails honestly instead of validating against a guess.
+ """
+ lister = getattr(client, "realtime_list_voices", None)
+ if not callable(lister):
+ return _V3_VOICES
+ try:
+ result = await lister(thread_id)
+ except Exception as exc:
+ if getattr(exc, "code", None) is None:
+ raise
+ log.info(
+ "Codex app-server rejected thread/realtime/listVoices (%s); "
+ "using the audited static voice roster",
+ _safe_error(exc),
+ )
+ return _V3_VOICES
+ names = _roster_voice_names(result)
+ if not names:
+ log.info(
+ "Codex app-server returned no usable realtime voice roster; "
+ "using the audited static one"
+ )
+ return _V3_VOICES
+ return names
+
+
+def _client_realtime_start_accepts(client: Any, parameter: str) -> bool:
+ """Whether the client's ``realtime_start`` declares ``parameter`` by name.
+
+ A NAMED-parameter probe rather than the file's usual TypeError probe, and
+ the difference is load-bearing: a client that merely takes ``**kwargs``
+ would swallow the field without ever sending it, and a silently lost
+ startup contract is exactly the failure a capability probe exists to
+ prevent (AP-21/AP-30). Only an explicit declaration counts as support.
+ """
+ method = getattr(client, "realtime_start", None)
+ if not callable(method):
+ return False
+ try:
+ parameters = inspect.signature(method).parameters
+ except (TypeError, ValueError):
+ return False
+ return parameter in parameters
+
+
def _handoff_text(item: dict[str, Any]) -> str:
direct = str(item.get("input_transcript", "") or item.get("inputTranscript", "") or "").strip()
if direct:
@@ -601,6 +706,8 @@ class _CodexSubscriptionRealtimeSession:
answer_sdp: str,
audio_endpoint: Any = None,
input_transcriber: Any = None,
+ input_transcriber_factory: Any = None,
+ grounding_unavailable_reason: str = "",
language: str = "en",
voice: str = "",
initial_context: str = "",
@@ -618,6 +725,19 @@ class _CodexSubscriptionRealtimeSession:
# from silence or speaker echo. Local energy-gated STT is authoritative
# for the bar and every transcript-driven Jarvis integration.
self._input_transcriber = input_transcriber
+ # Zero-arg callable producing a replacement recognizer (or ``None``)
+ # for the bounded mid-call rebuild. The build itself is cheap — the
+ # STT backend is cached process-wide — so a dead stream no longer has
+ # to end grounding for the rest of the call.
+ self._input_transcriber_factory = (
+ input_transcriber_factory if callable(input_transcriber_factory) else None
+ )
+ # Why the recognizer BUILD failed, when it did. Non-empty means the
+ # whole call runs ungrounded from the first frame and the receive
+ # loop owes the user one honest surface notice for it — a WARNING in
+ # the log was the only trace before, and a silently disarmed
+ # grounding gate is how the self-talk loop kept coming back (AP-30).
+ self._grounding_unavailable_reason = str(grounding_unavailable_reason or "").strip()
self._closed = False
self._last_input_item_id = ""
self._assistant_delta_text = ""
@@ -662,10 +782,12 @@ class _CodexSubscriptionRealtimeSession:
self._delivered_turn_directive = ""
# One INFO line per session for the discarded tool declarations.
self._tools_discard_noted = False
- # False once the local recognizer stream DIED. It is the only grounding
- # source this transport has, so losing it must degrade to the same
- # fail-open behaviour as a host that never had one — otherwise the gate
- # refuses and interrupts every remaining answer of the call.
+ # False while the local recognizer stream is DEAD. It is the only
+ # grounding source this transport has, so losing it must degrade to
+ # the same fail-open (now bounded) behaviour as a host that never had
+ # one — otherwise the gate refuses and interrupts every remaining
+ # answer of the call. No longer a one-way latch: a successful bounded
+ # rebuild (see ``_RECOGNIZER_REBUILDS_MAX``) sets it back to True.
self._local_grounding_ok = True
# Session-lifetime counters for the end-of-session postmortem event.
# Bumped at the same sites that already log the condition; the session
@@ -688,9 +810,7 @@ class _CodexSubscriptionRealtimeSession:
endpoint_diag = getattr(self._audio_endpoint, "diagnostics", None)
if callable(endpoint_diag):
try:
- merged.update(
- {k: int(v) for k, v in endpoint_diag().items()}
- )
+ merged.update({k: int(v) for k, v in endpoint_diag().items()})
except Exception: # noqa: BLE001 — diagnostics never break teardown
log.debug("audio endpoint diagnostics unavailable", exc_info=True)
return merged
@@ -837,9 +957,21 @@ class _CodexSubscriptionRealtimeSession:
# (``_begin_response`` is not a generator and cannot yield).
self_dialogue_detected = False
grounding_loss_reported = False
+ # Bounded mid-call recognizer rebuild (see _RECOGNIZER_REBUILDS_MAX):
+ # attempts started so far, and the in-flight background build. The
+ # build runs off this loop — its backoff sleep inside the receive
+ # loop would stall audio pumping for its whole duration.
+ recognizer_rebuilds_started = 0
+ rebuild_task: asyncio.Task[None] | None = None
assistant_audio = bytearray()
assistant_audio_active = False
assistant_transcript_seen = False
+ # Exactly one terminal STT pass is allowed per provider response. A
+ # failed pass must not be repeated by each competing local boundary
+ # (quiescence, sequence drain, terminal item): native inference may
+ # still be finishing in a worker thread, and retrying it here is the
+ # AP-24 wedge class.
+ terminal_recovery_attempted = False
# Early shadow recovery (see _OUTPUT_EARLY_RECOVERY_AFTER_S): when the
# response's first audible frame arrived, when recovery last finished,
# and whether this response already produced its one shadow delta.
@@ -850,6 +982,7 @@ class _CodexSubscriptionRealtimeSession:
first_audible_at = 0.0
early_recovery_at = 0.0
early_shadow_done = False
+ shadow_attempts = 0
shadow_task: asyncio.Task[None] | None = None
# True between the local endpointer's speech-start and its final (or
# failed/discarded) transcript: while the user is mid-utterance the
@@ -878,6 +1011,13 @@ class _CodexSubscriptionRealtimeSession:
# answer was then refused as ungrounded).
first_user_final_seen = False
call_response_index = 0
+ # Local, monotone response identity. ChatGPT-Live media can precede
+ # its sideband turn/started id, so the remote turn id cannot safely
+ # pair early PCM with later transcript. This identity is allocated at
+ # the first observed response evidence and rides audio, transcript and
+ # the terminal boundary together.
+ response_identity = ""
+ sequence_boundary_response_id = ""
# A discarded utterance's still-open response window (see
# _DISCARDED_UTTERANCE_GRACE_S): the generation it covers and when
# the discard happened.
@@ -941,8 +1081,9 @@ class _CodexSubscriptionRealtimeSession:
# source, so simply returning left the gate refusing and
# interrupting every remaining answer of the call — a silent
# mute that looked like the provider had stopped talking
- # (AP-30). The consumer degrades to the same fail-open path a
- # host without any recognizer takes, and says so out loud.
+ # (AP-30). The consumer attempts a bounded rebuild first and
+ # only then degrades to the bounded fail-open path a host
+ # without any recognizer takes, saying so out loud.
await queue.put(("local_input_failed", exc))
async def _pump_media_audio() -> None:
@@ -970,13 +1111,15 @@ class _CodexSubscriptionRealtimeSession:
def _reset_assistant_capture() -> None:
nonlocal assistant_audio_active, assistant_transcript_seen
nonlocal first_audible_at, early_recovery_at, early_shadow_done
- nonlocal shadow_task
+ nonlocal shadow_attempts, shadow_task, terminal_recovery_attempted
assistant_audio.clear()
assistant_audio_active = False
assistant_transcript_seen = False
first_audible_at = 0.0
early_recovery_at = 0.0
early_shadow_done = False
+ shadow_attempts = 0
+ terminal_recovery_attempted = False
# A still-running attempt belongs to the response that just
# ended; letting it run would only suppress the NEXT response's
# attempt through the single-flight handle until it delivered a
@@ -993,12 +1136,9 @@ class _CodexSubscriptionRealtimeSession:
return
if (
discarded_generation
- and asyncio.get_running_loop().time() - discarded_at
- > _DISCARDED_UTTERANCE_GRACE_S
+ and asyncio.get_running_loop().time() - discarded_at > _DISCARDED_UTTERANCE_GRACE_S
):
- consumed_input_generation = max(
- consumed_input_generation, discarded_generation
- )
+ consumed_input_generation = max(consumed_input_generation, discarded_generation)
discarded_generation = 0
def _fresh_local_input_exists() -> bool:
@@ -1067,6 +1207,7 @@ class _CodexSubscriptionRealtimeSession:
nonlocal sequence_boundary_pending
nonlocal response_grant, call_response_index
nonlocal silent_line_noted
+ nonlocal response_identity, sequence_boundary_response_id
_expire_discarded_grace()
if response_open:
if response_allowed or not _rejected_response_is_stale():
@@ -1093,6 +1234,7 @@ class _CodexSubscriptionRealtimeSession:
self._diag["response_splices"] += 1
if not completion_emitted:
sequence_boundary_pending = True
+ sequence_boundary_response_id = response_identity
log.info(
"Codex subscription realtime opened a new response "
"%d ms after the previous response's audio "
@@ -1108,14 +1250,12 @@ class _CodexSubscriptionRealtimeSession:
response_rejected_at = 0.0
active_response_generation = 0
call_response_index += 1
+ response_identity = f"{self._thread_id}:response:{call_response_index}"
response_grant = ""
if not self._local_grounding_active():
response_allowed = True
response_grant = "failopen"
- elif (
- local_input_generation > consumed_input_generation
- and first_user_final_seen
- ):
+ elif local_input_generation > consumed_input_generation and first_user_final_seen:
# NOTHING unsolicited ever plays before the call's first user
# FINAL. The bounded-greeting compromise this replaces lost
# its live test (maintainer, 2026-08-08): the greeting's
@@ -1295,14 +1435,19 @@ class _CodexSubscriptionRealtimeSession:
response start clean.
"""
nonlocal sequence_boundary_pending, completion_emitted
+ nonlocal sequence_boundary_response_id
if not sequence_boundary_pending:
return []
sequence_boundary_pending = False
+ boundary_response_id = sequence_boundary_response_id
+ sequence_boundary_response_id = ""
events: list[_ProviderEvent] = []
missing_input = _missing_input_boundary()
if missing_input is not None:
events.append(missing_input)
- recovered = await _recover_output_transcript()
+ recovered = await _recover_output_transcript(
+ response_id=boundary_response_id
+ )
if recovered is not None:
events.append(recovered)
self._diag["sequenced_boundaries"] += 1
@@ -1310,7 +1455,12 @@ class _CodexSubscriptionRealtimeSession:
"Codex subscription realtime sequenced a back-to-back "
"response behind a local turn boundary"
)
- events.append(_ProviderEvent(type="turn_complete"))
+ events.append(
+ _ProviderEvent(
+ type="turn_complete",
+ provider_turn_id=boundary_response_id or None,
+ )
+ )
_reset_assistant_capture()
self._assistant_delta_text = ""
# The boundary belongs to the OLD response; the one just opened
@@ -1354,13 +1504,22 @@ class _CodexSubscriptionRealtimeSession:
< _UNGROUNDED_RESPONSE_GRACE_S
)
- async def _recover_output_transcript() -> _ProviderEvent | None:
- """Recover text for provider audio whose transcript went missing."""
- nonlocal assistant_transcript_seen
- if assistant_transcript_seen or not assistant_audio:
+ async def _recover_output_transcript(
+ *, response_id: str = ""
+ ) -> _ProviderEvent | None:
+ """Run the one terminal STT pass for a missing transcript."""
+ nonlocal assistant_transcript_seen, terminal_recovery_attempted
+ if (
+ assistant_transcript_seen
+ or terminal_recovery_attempted
+ or not assistant_audio
+ ):
return None
+ terminal_recovery_attempted = True
+ self._diag["output_terminal_recovery_attempts"] += 1
recover = getattr(self._input_transcriber, "transcribe_audio", None)
if not callable(recover):
+ self._diag["output_transcript_recovery_failures"] += 1
return None
try:
# No outer wait_for: the recognizer bounds itself in proportion
@@ -1373,15 +1532,18 @@ class _CodexSubscriptionRealtimeSession:
await recover(bytes(assistant_audio), sample_rate=_OUTPUT_RATE) or ""
).strip()
except Exception: # noqa: BLE001 - the fail-closed gate remains active
+ self._diag["output_transcript_recovery_failures"] += 1
log.warning(
"Codex subscription output transcript recovery failed",
exc_info=True,
)
return None
if not text:
+ self._diag["output_transcript_recovery_failures"] += 1
log.warning("Codex subscription output transcript recovery returned no text")
return None
assistant_transcript_seen = True
+ self._diag["output_terminal_recovery_successes"] += 1
log.info(
"Recovered a missing Codex subscription output transcript "
"from %d bytes of provider audio",
@@ -1391,6 +1553,7 @@ class _CodexSubscriptionRealtimeSession:
type="output_transcript_delta",
text=text,
is_final=True,
+ provider_turn_id=response_id or response_identity or None,
)
async def _recover_shadow_transcript(head: bytes) -> str:
@@ -1411,9 +1574,7 @@ class _CodexSubscriptionRealtimeSession:
if not callable(recover):
return ""
try:
- return str(
- await recover(head, sample_rate=_OUTPUT_RATE) or ""
- ).strip()
+ return str(await recover(head, sample_rate=_OUTPUT_RATE) or "").strip()
except Exception: # noqa: BLE001 - the fail-closed hold simply continues
log.debug(
"Codex subscription early shadow recovery skipped",
@@ -1421,7 +1582,11 @@ class _CodexSubscriptionRealtimeSession:
)
return ""
- async def _run_shadow_recovery(anchor: float, head: bytes) -> None:
+ async def _run_shadow_recovery(
+ anchor: float,
+ response_id: str,
+ head: bytes,
+ ) -> None:
"""Background shadow attempt; the result rides the ordinary queue.
The anchor is the response's ``first_audible_at`` at task start:
@@ -1429,7 +1594,59 @@ class _CodexSubscriptionRealtimeSession:
that has since closed and must never vet a different one's audio.
"""
text = await _recover_shadow_transcript(head)
- await queue.put(("shadow_transcript", (anchor, text)))
+ await queue.put(("shadow_transcript", (anchor, response_id, text)))
+
+ async def _run_recognizer_rebuild(attempt: int) -> None:
+ """Build a replacement recognizer off the receive loop.
+
+ The linear backoff spaces attempts so an engine that dies on
+ start cannot hot-loop; the result rides the ordinary queue
+ because this loop owns every piece of grounding state. A failed
+ build delivers ``None`` — a counted verdict, never a crash.
+ """
+ await asyncio.sleep(_RECOGNIZER_REBUILD_BACKOFF_S * attempt)
+ # Read once: the scheduler only starts this task with a factory
+ # present, and the local name keeps that invariant checkable.
+ factory = self._input_transcriber_factory
+ replacement: Any = None
+ try:
+ replacement = factory() if factory is not None else None
+ if replacement is not None:
+ await _warm_input_transcriber(replacement)
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 - the exhaustion path reports it
+ if replacement is not None:
+ with suppress(Exception):
+ await replacement.close()
+ replacement = None
+ log.warning(
+ "Codex subscription recognizer rebuild attempt %d failed",
+ attempt,
+ exc_info=True,
+ )
+ await queue.put(("recognizer_rebuilt", replacement))
+
+ def _grounding_unavailable_notice(detail: str) -> _ProviderEvent:
+ """The ONE honest surface notice for an ungrounded call (AP-30).
+
+ Same shape as every other user-facing degradation this adapter
+ reports: a recoverable error event the session surfaces without
+ ending the call. The caller guards it with
+ ``grounding_loss_reported`` so a call degrades out loud exactly
+ once, whichever path got it there.
+ """
+ self._diag["grounding_unavailable_notices"] += 1
+ return _ProviderEvent(
+ type="error",
+ error=(
+ f"Local speech recognition is unavailable: {detail} "
+ "The assistant keeps answering, but every automatic "
+ f"response is bounded to {_OPENING_RESPONSE_MAX_S:.0f}s "
+ "and Jarvis-side transcript features stay idle."
+ ),
+ recoverable=True,
+ )
def _missing_input_boundary() -> _ProviderEvent | None:
"""One placeholder per turn when neither source produced text.
@@ -1509,6 +1726,16 @@ class _CodexSubscriptionRealtimeSession:
name=f"codex-realtime-media-{self._thread_id}",
)
try:
+ if self._input_transcriber is None and self._grounding_unavailable_reason:
+ # The recognizer BUILD failed, so the whole call runs in the
+ # bounded ungrounded regime and there is nothing to rebuild.
+ # Degradation is announced at session start, not buried in a
+ # build-time log line: a silently disarmed grounding gate is
+ # THE reason past self-talk fixes did not stick (AP-30). An
+ # injected recognizer of None without a reason is a caller's
+ # explicit choice and stays silent, exactly as before.
+ grounding_loss_reported = True
+ yield _grounding_unavailable_notice(f"{self._grounding_unavailable_reason}.")
while True:
queue_kind, payload = await queue.get()
if self_dialogue_detected:
@@ -1523,7 +1750,10 @@ class _CodexSubscriptionRealtimeSession:
recoverable=True,
reconnect_advised=True,
)
- yield _ProviderEvent(type="turn_complete")
+ yield _ProviderEvent(
+ type="turn_complete",
+ provider_turn_id=response_identity or None,
+ )
return
if _interrupt_barrier_moved():
# Barge-in. ChatGPT-Live keeps streaming the rest of the
@@ -1563,16 +1793,18 @@ class _CodexSubscriptionRealtimeSession:
if queue_kind == "shadow_transcript":
shadow_task = None
early_recovery_at = asyncio.get_running_loop().time()
- anchor, shadow_text = payload
+ anchor, shadow_response_id, shadow_text = payload
if (
shadow_text
and anchor == first_audible_at
+ and shadow_response_id == response_identity
and not early_shadow_done
and not assistant_transcript_seen
and response_open
and response_allowed
):
early_shadow_done = True
+ self._diag["output_shadow_recovery_successes"] += 1
log.info(
"Codex subscription realtime released the opening "
"hold with a locally recovered shadow transcript "
@@ -1584,18 +1816,20 @@ class _CodexSubscriptionRealtimeSession:
text=shadow_text,
is_final=False,
shadow=True,
+ provider_turn_id=shadow_response_id or None,
)
elif shadow_text:
- log.debug(
- "Discarding a stale or superseded shadow transcript"
- )
+ log.debug("Discarding a stale or superseded shadow transcript")
+ elif shadow_attempts >= _OUTPUT_EARLY_RECOVERY_MAX_ATTEMPTS:
+ self._diag["output_shadow_recovery_exhausted"] += 1
continue
if queue_kind == "local_input_failed":
- # The ONLY grounding source died mid-call. Degrade to the
- # same fail-open behaviour a host without any recognizer
- # has (``_local_grounding_active``), or the gate would
- # refuse and interrupt every remaining answer — a mute the
- # user cannot distinguish from a dead provider.
+ # The ONLY grounding source died mid-call. Until a
+ # rebuild lands, degrade to the same bounded fail-open
+ # behaviour a host without any recognizer has
+ # (``_local_grounding_active``), or the gate would refuse
+ # and interrupt every remaining answer — a mute the user
+ # cannot distinguish from a dead provider.
if not self._local_grounding_ok:
continue
self._local_grounding_ok = False
@@ -1605,25 +1839,102 @@ class _CodexSubscriptionRealtimeSession:
# work even when the event stream died).
user_utterance_open = False
_close_response(spent=False)
+ if (
+ self._input_transcriber_factory is not None
+ and recognizer_rebuilds_started < _RECOGNIZER_REBUILDS_MAX
+ and rebuild_task is None
+ ):
+ # Not the one-way latch this used to be: the process-
+ # wide STT cache makes a rebuild cheap, so a transient
+ # stream death costs seconds of bounded fail-open
+ # instead of the whole call's grounding.
+ recognizer_rebuilds_started += 1
+ self._diag["recognizer_rebuild_attempts"] += 1
+ log.warning(
+ "Local input transcription stream failed; "
+ "rebuilding the recognizer (attempt %d of %d) — "
+ "the grounding gate fails OPEN, bounded, until "
+ "it returns",
+ recognizer_rebuilds_started,
+ _RECOGNIZER_REBUILDS_MAX,
+ exc_info=payload if isinstance(payload, BaseException) else None,
+ )
+ rebuild_task = asyncio.create_task(
+ _run_recognizer_rebuild(recognizer_rebuilds_started),
+ name=f"codex-recognizer-rebuild-{self._thread_id}",
+ )
+ continue
log.warning(
- "Local input transcription stream failed; the Codex "
- "subscription grounding gate now fails OPEN for the "
- "rest of this call",
+ "Local input transcription stream failed with no "
+ "rebuild left; the Codex subscription grounding gate "
+ "now fails OPEN (bounded) for the rest of this call",
exc_info=payload if isinstance(payload, BaseException) else None,
)
if not grounding_loss_reported:
grounding_loss_reported = True
- yield _ProviderEvent(
- type="error",
- error=(
- "Local speech recognition stopped during this call: "
- f"{type(payload).__name__}: {_safe_error(payload)}. "
- "The assistant keeps answering, but Jarvis-side "
- "transcript features stay idle."
- ),
- recoverable=True,
+ yield _grounding_unavailable_notice(
+ "local speech recognition stopped during this "
+ f"call: {type(payload).__name__}: "
+ f"{_safe_error(payload)}."
)
continue
+ if queue_kind == "recognizer_rebuilt":
+ rebuild_task = None
+ replacement = payload
+ if self._closed and replacement is not None:
+ with suppress(Exception):
+ await replacement.close()
+ continue
+ if replacement is None:
+ if (
+ self._input_transcriber_factory is not None
+ and recognizer_rebuilds_started < _RECOGNIZER_REBUILDS_MAX
+ ):
+ # The dead pump delivers no further failure event,
+ # so the next attempt starts here, not in the
+ # failure handler.
+ recognizer_rebuilds_started += 1
+ self._diag["recognizer_rebuild_attempts"] += 1
+ rebuild_task = asyncio.create_task(
+ _run_recognizer_rebuild(recognizer_rebuilds_started),
+ name=(f"codex-recognizer-rebuild-{self._thread_id}"),
+ )
+ continue
+ log.warning(
+ "Codex subscription exhausted its %d recognizer "
+ "rebuild(s); the grounding gate stays OPEN "
+ "(bounded) for the rest of this call",
+ _RECOGNIZER_REBUILDS_MAX,
+ )
+ if not grounding_loss_reported:
+ grounding_loss_reported = True
+ yield _grounding_unavailable_notice(
+ "local speech recognition could not be "
+ "rebuilt after it stopped mid-call."
+ )
+ continue
+ # Success: the new recognizer takes over grounding and
+ # the local-input pump restarts on it. The old instance
+ # is closed best-effort — its stream is already dead and
+ # the shared STT backend outlives any one instance.
+ retired = self._input_transcriber
+ self._input_transcriber = replacement
+ self._local_grounding_ok = True
+ self._diag["recognizer_rebuilds_restored"] += 1
+ if retired is not None:
+ with suppress(Exception):
+ await retired.close()
+ input_task = asyncio.create_task(
+ _pump_local_input(),
+ name=f"codex-realtime-local-input-{self._thread_id}",
+ )
+ log.info(
+ "Codex subscription restored local grounding with a "
+ "rebuilt recognizer (attempt %d of %d)",
+ recognizer_rebuilds_started,
+ _RECOGNIZER_REBUILDS_MAX,
+ )
+ continue
if queue_kind == "local_input":
if payload.kind == _SPEECH_STARTED:
local_input_generation += 1
@@ -1675,7 +1986,10 @@ class _CodexSubscriptionRealtimeSession:
)
if not response_open and not completion_emitted:
completion_emitted = True
- yield _ProviderEvent(type="turn_complete")
+ yield _ProviderEvent(
+ type="turn_complete",
+ provider_turn_id=response_identity or None,
+ )
elif payload.kind == _TRANSCRIPT_FAILED:
# The local recognizer could not deliver this
# utterance. A turn the user really spoke must not
@@ -1737,9 +2051,7 @@ class _CodexSubscriptionRealtimeSession:
type="input_transcript",
text=payload.text,
is_final=payload.is_final,
- voiced_ms=int(
- getattr(payload, "voiced_ms", 0) or 0
- ),
+ voiced_ms=int(getattr(payload, "voiced_ms", 0) or 0),
)
continue
if queue_kind == "media_audio":
@@ -1796,33 +2108,36 @@ class _CodexSubscriptionRealtimeSession:
assistant_audio.extend(pcm[:remaining])
if audible and assistant_audio_active and not first_audible_at:
first_audible_at = asyncio.get_running_loop().time()
- if (
- response_allowed
- and first_audible_at
- and not first_user_final_seen
- and response_grant == "failopen"
- and call_response_index == 1
- ):
- # A recognizer-less host cannot refuse its opener (no
- # grounding exists), so its FIRST response keeps a
- # coarse cap against the demo-monologue class. On
- # grounded hosts the opener never plays at all.
- opening_age = (
- asyncio.get_running_loop().time() - first_audible_at
- )
+ if response_allowed and first_audible_at and response_grant == "failopen":
+ # An ungrounded host cannot refuse ANY response (no
+ # grounding exists), so EVERY failopen response keeps
+ # the coarse cap — not just the opener. Bounding only
+ # response #1 left the far end unbounded from response
+ # #2 on, which is where the echo-driven two-AIs loop
+ # ran unopposed whenever the recognizer was absent or
+ # dead (see _OPENING_RESPONSE_MAX_S). On grounded
+ # hosts no failopen grant exists at all.
+ opening_age = asyncio.get_running_loop().time() - first_audible_at
if opening_age > _OPENING_RESPONSE_MAX_S:
- self._diag["opening_responses_bounded"] += 1
+ if call_response_index == 1 and not first_user_final_seen:
+ # Keep the opener's dedicated postmortem key:
+ # a bounded OPENING still means "monologue
+ # before any question", a different diagnosis
+ # than a bounded mid-call response.
+ self._diag["opening_responses_bounded"] += 1
+ else:
+ self._diag["ungrounded_responses_bounded"] += 1
log.warning(
- "Codex subscription bounded an opening "
- "response at %.1fs - no user question exists "
- "yet (grant=%s)",
+ "Codex subscription bounded an ungrounded "
+ "response at %.1fs - no local grounding "
+ "exists to judge it (grant=%s, response=%d)",
opening_age,
response_grant,
+ call_response_index,
)
await self._interrupt_active_codex_turn()
interrupt_grace_until = (
- asyncio.get_running_loop().time()
- + _POST_INTERRUPT_GRACE_S
+ asyncio.get_running_loop().time() + _POST_INTERRUPT_GRACE_S
)
_cancel_completion()
completion_emitted = True
@@ -1840,6 +2155,8 @@ class _CodexSubscriptionRealtimeSession:
and assistant_audio
and shadow_task is None
and not user_utterance_open
+ and shadow_attempts
+ < _OUTPUT_EARLY_RECOVERY_MAX_ATTEMPTS
):
# The session's scrub gate is holding every one of
# these chunks fail-closed until SOME transcript
@@ -1853,14 +2170,17 @@ class _CodexSubscriptionRealtimeSession:
now = asyncio.get_running_loop().time()
if (
now - first_audible_at >= _OUTPUT_EARLY_RECOVERY_AFTER_S
- and now - early_recovery_at
- >= _OUTPUT_EARLY_RECOVERY_RETRY_S
+ and now - early_recovery_at >= _OUTPUT_EARLY_RECOVERY_RETRY_S
):
- head = bytes(
- assistant_audio[:_SHADOW_RECOVERY_MAX_BYTES]
- )
+ head = bytes(assistant_audio[:_SHADOW_RECOVERY_MAX_BYTES])
+ shadow_attempts += 1
+ self._diag["output_shadow_recovery_attempts"] += 1
shadow_task = asyncio.create_task(
- _run_shadow_recovery(first_audible_at, head),
+ _run_shadow_recovery(
+ first_audible_at,
+ response_identity,
+ head,
+ ),
name=f"codex-shadow-recovery-{self._thread_id}",
)
yield _ProviderEvent(
@@ -1870,6 +2190,7 @@ class _CodexSubscriptionRealtimeSession:
sample_rate=_OUTPUT_RATE,
channels=1,
),
+ provider_turn_id=response_identity or None,
)
continue
if queue_kind == "completion":
@@ -1880,12 +2201,17 @@ class _CodexSubscriptionRealtimeSession:
missing_input = _missing_input_boundary()
if missing_input is not None:
yield missing_input
- recovered = await _recover_output_transcript()
+ recovered = await _recover_output_transcript(
+ response_id=response_identity
+ )
if recovered is not None:
yield recovered
completion_emitted = True
self._diag["quiescence_boundary_turns"] += 1
- yield _ProviderEvent(type="turn_complete")
+ yield _ProviderEvent(
+ type="turn_complete",
+ provider_turn_id=response_identity or None,
+ )
_reset_assistant_capture()
_finish_response()
if stream_ended:
@@ -2050,6 +2376,7 @@ class _CodexSubscriptionRealtimeSession:
type="output_transcript_delta",
text=delta,
is_final=False,
+ provider_turn_id=response_identity or None,
)
continue
@@ -2104,10 +2431,7 @@ class _CodexSubscriptionRealtimeSession:
_close_response(spent=True)
continue
ungrounded_final_captions += 1
- if (
- ungrounded_final_captions
- >= _UNGROUNDED_CAPTIONS_BEFORE_REBUILD
- ):
+ if ungrounded_final_captions >= _UNGROUNDED_CAPTIONS_BEFORE_REBUILD:
diagnostic = (
"Codex subscription detected %d consecutive "
"automatic server turns without locally "
@@ -2127,7 +2451,10 @@ class _CodexSubscriptionRealtimeSession:
recoverable=True,
reconnect_advised=True,
)
- yield _ProviderEvent(type="turn_complete")
+ yield _ProviderEvent(
+ type="turn_complete",
+ provider_turn_id=response_identity or None,
+ )
return
self._diag["ungrounded_captions_dropped"] += 1
log.info(
@@ -2181,6 +2508,7 @@ class _CodexSubscriptionRealtimeSession:
type="output_transcript_delta",
text=suffix,
is_final=True,
+ provider_turn_id=response_identity or None,
)
self._assistant_delta_text = ""
# ChatGPT-Live emits this per transcript PART, not per
@@ -2243,6 +2571,7 @@ class _CodexSubscriptionRealtimeSession:
sample_rate=sample_rate,
channels=channels,
),
+ provider_turn_id=response_identity or None,
)
continue
@@ -2322,7 +2651,9 @@ class _CodexSubscriptionRealtimeSession:
missing_input = _missing_input_boundary()
if missing_input is not None:
yield missing_input
- recovered = await _recover_output_transcript()
+ recovered = await _recover_output_transcript(
+ response_id=response_identity
+ )
if recovered is not None:
yield recovered
completion_emitted = True
@@ -2332,7 +2663,10 @@ class _CodexSubscriptionRealtimeSession:
item_type,
self.realtime_version or "unknown",
)
- yield _ProviderEvent(type="turn_complete")
+ yield _ProviderEvent(
+ type="turn_complete",
+ provider_turn_id=response_identity or None,
+ )
_reset_assistant_capture()
# Protocol proof that the response ended: the strongest
# boundary there is, so the entitlement retires here.
@@ -2401,11 +2735,14 @@ class _CodexSubscriptionRealtimeSession:
task.cancel()
if shadow_task is not None and not shadow_task.done():
shadow_task.cancel()
+ if rebuild_task is not None and not rebuild_task.done():
+ rebuild_task.cancel()
await asyncio.gather(
pump_task,
media_task,
input_task,
*((shadow_task,) if shadow_task is not None else ()),
+ *((rebuild_task,) if rebuild_task is not None else ()),
*tuple(timer_tasks),
return_exceptions=True,
)
@@ -2518,8 +2855,7 @@ class _CodexSubscriptionRealtimeSession:
sections.append(
"Current-turn instructions — these REPLACE every earlier "
"instruction about how to handle the current turn; apply "
- "them silently, never acknowledge them aloud:\n"
- + directive
+ "them silently, never acknowledge them aloud:\n" + directive
)
if standing:
# Re-asserted EVERY delivery, unchanged or not: three live calls
@@ -2686,6 +3022,15 @@ class CodexSubscriptionRealtimeProvider:
# WebRTC — measured 15-25s on a mid-range desktop. The shared 12s ceiling
# beheaded every cold call into a pipeline fallback (log 2026-08-01).
handshake_budget_s = 45.0
+ # A delegate readback on this transport is spoken by ChatGPT-Live, whose
+ # audio measurably lags its own start: the session's scrub gate held a
+ # response's first audible frame 7.4 s (live 2026-08-05 20:42), while the
+ # shared delegate-readback floor is 2.5 s. Undeclared, the watchdog fired
+ # first every time the far end was slow — the surface TTS took the turn
+ # in the wrong voice, or (with no realtime-scoped surface TTS) the real
+ # audio answer was withheld outright and the user heard nothing. Declared
+ # budget, same AP-21 doctrine as handshake_budget_s.
+ readback_render_budget_s = 12.0
input_sample_rate = _INPUT_RATE
output_sample_rate = _OUTPUT_RATE
credential_candidates: tuple[tuple[str, str | None], ...] = ()
@@ -2805,7 +3150,7 @@ class CodexSubscriptionRealtimeProvider:
# Built and primed ONCE for both attempts: the recognizer is pure
# local state, and rebuilding + re-warming it on the STUN retry paid
# seconds for nothing.
- input_transcriber = self._build_input_transcriber(cfg)
+ input_transcriber, grounding_unavailable_reason = self._build_input_transcriber_outcome(cfg)
warm_task: asyncio.Task[Any] | None = None
if callable(getattr(input_transcriber, "warm", None)):
warm_task = asyncio.create_task(
@@ -2820,6 +3165,7 @@ class CodexSubscriptionRealtimeProvider:
None if ice_factory is None else ice_factory(),
input_transcriber=input_transcriber,
input_transcriber_warm_task=warm_task,
+ grounding_unavailable_reason=grounding_unavailable_reason,
# The STUN retry may ride the audit that passed seconds
# ago on this very open; a first attempt never does.
ride_recent_audit=index > 0,
@@ -2847,20 +3193,31 @@ class CodexSubscriptionRealtimeProvider:
await _cancel_background_task(warm_task)
def _build_input_transcriber(self, cfg: Any = None) -> Any:
- """Local user-speech recognition, or ``None`` when unavailable.
+ """Local user-speech recognition, or ``None`` when unavailable."""
+ transcriber, _reason = self._build_input_transcriber_outcome(cfg)
+ return transcriber
+
+ def _build_input_transcriber_outcome(self, cfg: Any = None) -> tuple[Any, str]:
+ """(recognizer or ``None``, non-empty degradation reason on failure).
ChatGPT-Live also guesses at user speech, but local energy-gated STT is
authoritative. Without it silence/echo captions could become commands,
while transcript-driven Jarvis integrations would have no grounded text.
+ A BUILD failure therefore returns its reason alongside the ``None`` so
+ the session can announce the degraded (bounded fail-open) call on the
+ surface instead of only in this log (AP-30). An injected factory owns
+ its own construction and degradation story — a ``None`` from it is the
+ caller's explicit choice, never a failure to report.
The session's recognition language is handed over when the recognizer
accepts it. Probed rather than assumed (AP-21): an older recognizer
without the parameter keeps working on its own configured language
instead of the whole call losing its only grounding source over a
- keyword argument.
+ keyword argument. The in-tree recognizer accepts ``language`` since
+ 2026-08-08, so the probe protects out-of-tree modules only.
"""
if self._input_transcriber_factory is not None:
- return self._input_transcriber_factory()
+ return self._input_transcriber_factory(), ""
input_language = _normalized_locale(getattr(cfg, "input_language", ""))
if input_language == "auto":
input_language = ""
@@ -2868,22 +3225,36 @@ class CodexSubscriptionRealtimeProvider:
module = importlib.import_module("jarvis.realtime.input_transcription")
if input_language:
try:
- return module.LocalInputTranscriber(
- sample_rate=_INPUT_RATE, language=input_language
+ return (
+ module.LocalInputTranscriber(
+ sample_rate=_INPUT_RATE, language=input_language
+ ),
+ "",
)
except TypeError:
- log.debug(
- "Local input transcription does not accept a language "
- "yet; using its configured one"
+ # One WARNING per process, DEBUG afterwards: the dropped
+ # capability repeats on every call, but swallowing it at
+ # DEBUG is how the un-pinned session language went
+ # unnoticed while the recognizer heard the wrong
+ # language (AP-30).
+ global _language_kwarg_rejected_warned
+ already_warned = _language_kwarg_rejected_warned
+ _language_kwarg_rejected_warned = True
+ log.log(
+ logging.DEBUG if already_warned else logging.WARNING,
+ "Local input transcription does not accept a session "
+ "language; the call keeps the recognizer's configured "
+ "language instead of %r",
+ input_language,
)
- return module.LocalInputTranscriber(sample_rate=_INPUT_RATE)
- except Exception: # noqa: BLE001 - the call still works, just deaf
+ return module.LocalInputTranscriber(sample_rate=_INPUT_RATE), ""
+ except Exception as exc: # noqa: BLE001 - the call still works, just deaf
log.warning(
"Local input transcription could not be started; the voice "
"answers but Jarvis-side transcript features stay idle",
exc_info=True,
)
- return None
+ return None, f"{type(exc).__name__}: {_safe_error(exc)}"
async def _open_session_once(
self,
@@ -2892,6 +3263,7 @@ class CodexSubscriptionRealtimeProvider:
*,
input_transcriber: Any = None,
input_transcriber_warm_task: asyncio.Task[Any] | None = None,
+ grounding_unavailable_reason: str = "",
ride_recent_audit: bool = False,
) -> _CodexSubscriptionRealtimeSession:
# Jarvis owns the media path in-process. The UI could only ever broker
@@ -2915,12 +3287,8 @@ class CodexSubscriptionRealtimeProvider:
if self._audio_endpoint_factory is not None:
audio_endpoint = self._audio_endpoint_factory(ice_servers)
else:
- transport_module = importlib.import_module(
- "jarvis.realtime.webrtc_transport"
- )
- audio_endpoint = transport_module.RealtimeWebRtcAudioEndpoint(
- ice_servers
- )
+ transport_module = importlib.import_module("jarvis.realtime.webrtc_transport")
+ audio_endpoint = transport_module.RealtimeWebRtcAudioEndpoint(ice_servers)
offer_started_at = time.monotonic()
offer_task = asyncio.create_task(
audio_endpoint.create_offer(), name="codex-realtime-create-offer"
@@ -2928,9 +3296,7 @@ class CodexSubscriptionRealtimeProvider:
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
- )
+ client = app_server_module.get_shared_codex_app_server(self._binary_path)
# ``thread_start`` lazily calls app-server ``ensure_started``. That
# performs the authoritative capability probe plus live
# ``account/read`` verification before accepting this thread.
@@ -2961,7 +3327,12 @@ class CodexSubscriptionRealtimeProvider:
configured_model,
)
voice = str(getattr(cfg, "voice", "") or "").strip().lower() or _DEFAULT_VOICE
- if voice not in _V3_VOICES:
+ # The server's live roster is authoritative when it can be read
+ # (thread/realtime/listVoices, codex-cli 0.147.0); the audited
+ # static frozenset stays the fallback for a client or server
+ # without the method. Capability-probed, never version-gated
+ # here (AP-21/AP-22) — the app-server client owns the wire.
+ if voice not in await _live_voice_roster(client, thread_id):
raise RuntimeError(
"Codex subscription realtime has an unsupported voice configured"
)
@@ -2969,29 +3340,39 @@ class CodexSubscriptionRealtimeProvider:
start_prompt = _startup_prompt(
initial_context,
language=getattr(cfg, "language", ""),
- language_is_pinned=bool(
- getattr(cfg, "language_is_pinned", False)
- ),
+ language_is_pinned=bool(getattr(cfg, "language_is_pinned", False)),
)
initial_items = _history_initial_items(getattr(cfg, "history", ()))
realtime_started_at = time.monotonic()
- start = await client.realtime_start(
- thread_id,
- output_modality="audio",
- offer_sdp=offer_sdp,
- prompt="",
- trusted_prompt=start_prompt,
- initial_items=initial_items,
+ start_kwargs: dict[str, Any] = {
+ "output_modality": "audio",
+ "offer_sdp": offer_sdp,
+ "prompt": "",
+ "trusted_prompt": start_prompt,
+ "initial_items": initial_items,
# v3 (ChatGPT-Live): the server chooses the model; sending a
# client model is rejected with "Field `session.model` is not
# allowed" (verified live 2026-08-01). The dead v1 protocol
# answered every start with 403 since the ChatGPT-Live launch.
- model=None,
- voice=voice,
- version="v3",
- include_startup_context=False,
- client_managed_handoffs=True,
- )
+ "model": None,
+ "voice": voice,
+ "version": "v3",
+ "include_startup_context": False,
+ "client_managed_handoffs": True,
+ }
+ if _client_realtime_start_accepts(client, "realtime_start_instructions"):
+ # codex-cli 0.147.0's realtimeStartInstructions slot carries
+ # the startup contract as SESSION instructions instead of a
+ # trusted first prompt — injected prompt context is what the
+ # model audibly acknowledged mid-open. The client owns the
+ # wire gate and omits the field (naming it in its own log)
+ # for an older approved binary; the thread-level base and
+ # developer instructions from thread_start still hold there
+ # and the persona re-arrives with the first update_session
+ # delivery, so that degradation is honest, never silent.
+ start_kwargs["realtime_start_instructions"] = start_prompt
+ start_kwargs["trusted_prompt"] = ""
+ start = await client.realtime_start(thread_id, **start_kwargs)
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")
@@ -3013,6 +3394,11 @@ class CodexSubscriptionRealtimeProvider:
if input_transcriber is not None
else self._build_input_transcriber(cfg)
),
+ # The bounded mid-call rebuild reuses the ordinary build path,
+ # which reattaches to the process-wide STT cache — so a
+ # rebuild costs a stream restart, not a model load.
+ input_transcriber_factory=lambda: self._build_input_transcriber(cfg),
+ grounding_unavailable_reason=grounding_unavailable_reason,
language=str(getattr(cfg, "language", "en") or "en"),
voice=voice,
initial_context=initial_context,
diff --git a/jarvis/realtime/factory.py b/jarvis/realtime/factory.py
index ed364ec695..684012fd76 100644
--- a/jarvis/realtime/factory.py
+++ b/jarvis/realtime/factory.py
@@ -73,17 +73,21 @@ def realtime_implicit_usage_fallback_allowed(cfg: Any) -> bool:
return bool(getattr(provider_cls, "implicit_usage_fallback_allowed", True))
-def _provider_candidates(
+def _identified_provider_candidates(
cfg: Any, *, defer_external_login_probe: bool = False
-) -> list[Any]:
+) -> list[tuple[str, 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.
+
+ Each candidate is paired with the entry-point id it was loaded from, which
+ a caller cannot recover from the instance: ``name`` is a provider-chosen
+ label and may differ from the id the registry knows.
"""
- candidates: list[Any] = []
+ candidates: list[tuple[str, Any]] = []
explicit_ids = set(_explicit_provider_ids(cfg))
for provider_id in _configured_provider_ids(cfg):
try:
@@ -135,12 +139,22 @@ def _provider_candidates(
provider_id,
)
continue
- candidates.append(provider)
+ candidates.append((provider_id, provider))
except Exception as exc: # noqa: BLE001 — one plugin must not brick others
log.warning("Realtime plugin %s is unavailable: %s", provider_id, exc)
return candidates
+def _provider_candidates(cfg: Any, *, defer_external_login_probe: bool = False) -> list[Any]:
+ """Credential-ready provider instances in effective fallback order."""
+ return [
+ provider
+ for _provider_id, provider in _identified_provider_candidates(
+ cfg, defer_external_login_probe=defer_external_login_probe
+ )
+ ]
+
+
def _resolve_realtime_provider(cfg: Any) -> Any:
"""Compatibility helper returning the first credential-ready provider."""
candidates = _provider_candidates(cfg)
@@ -188,21 +202,35 @@ def realtime_handshake_budget_s(cfg: Any) -> float:
Returns the effective ceiling — never below the shared default — so a
caller can use the value directly as a timeout budget.
+
+ The budget is read off the INSTANCE the factory would actually open with
+ whenever there is one, because a provider may declare it as a ``property``
+ whose value depends on its own configuration (a self-hosted card asks for
+ more time when it is allowed to revive its server). Reading such a
+ declaration off the class yields the descriptor object, not a number.
+ Every read stays inside the per-provider guard: one plugin that raises
+ must cost only its own budget, never the whole probe — a probe that dies
+ leaves the surface on its historical floor while the transport is still
+ legitimately negotiating.
"""
from jarvis.realtime.session import _PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S
declared = [float(_PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S)]
+ instances: dict[str, Any] = {}
+ try:
+ instances = dict(_identified_provider_candidates(cfg, defer_external_login_probe=True))
+ except Exception as exc: # noqa: BLE001 - class-level reads still work
+ log.warning("Realtime handshake-budget candidate build failed: %s", exc)
for provider_id in _configured_provider_ids(cfg):
try:
- provider_cls = load(_GROUP, provider_id, protocol=RealtimeProvider)
+ source = instances.get(provider_id)
+ if source is None:
+ source = load(_GROUP, provider_id, protocol=RealtimeProvider)
+ if not bool(getattr(source, "supports_realtime", False)):
+ continue
+ declared.append(float(getattr(source, "handshake_budget_s", 0.0) or 0.0))
except Exception as exc: # noqa: BLE001 - one broken plugin is skipped
- log.warning(
- "Realtime handshake-budget probe failed for %s: %s", provider_id, exc
- )
- continue
- if not bool(getattr(provider_cls, "supports_realtime", False)):
- continue
- declared.append(float(getattr(provider_cls, "handshake_budget_s", 0.0) or 0.0))
+ log.warning("Realtime handshake-budget probe failed for %s: %s", provider_id, exc)
return max(declared)
diff --git a/jarvis/realtime/input_transcription.py b/jarvis/realtime/input_transcription.py
index 03acb9680a..8e7a810aff 100644
--- a/jarvis/realtime/input_transcription.py
+++ b/jarvis/realtime/input_transcription.py
@@ -29,8 +29,9 @@ from __future__ import annotations
import asyncio
import logging
+import threading
import time
-from collections import deque
+from collections import OrderedDict, deque
from dataclasses import dataclass
from typing import Any
@@ -249,6 +250,99 @@ class _NoiseFloor:
return min(configured, max(k * self._floor, abs_min))
+@dataclass(slots=True)
+class _SharedRecognizer:
+ """One process-wide recognizer plus the in-flight guard that follows it.
+
+ The guard belongs to the ENGINE rather than to the transcriber holding it:
+ once two sessions can share one cached backend, a per-object flag cannot see
+ the other caller, and entering a native engine twice at once is what wedges
+ it permanently (AP-24).
+ """
+
+ backend: Any
+ busy: bool = False
+
+
+# Building the recognizer is the expensive half of opening a realtime call — a
+# local engine costs seconds and loads weights that are identical for every
+# session asking for the same configuration, so a per-transcriber engine made
+# every call re-pay that inside its own handshake. Keyed by the CONSTRUCTION
+# parameters (the effective STT config, session language pin included), so a
+# config change or a different session language still builds a fresh engine.
+# Bounded, because every retained entry can pin a model in memory.
+_STT_CACHE_MAX = 4
+_stt_cache: OrderedDict[str, _SharedRecognizer] = OrderedDict()
+_stt_cache_lock = threading.Lock()
+
+
+def _shared_recognizer(key: str, build: Any) -> _SharedRecognizer:
+ """The cached recognizer for ``key``, constructed at most once per process.
+
+ ``build`` runs UNDER the lock deliberately: a second concurrent build of the
+ same configuration is precisely the duplicated model load this cache exists
+ to remove, and two DIFFERENT configurations racing on the voice path is not
+ a case worth trading that guarantee for.
+ """
+ with _stt_cache_lock:
+ cached = _stt_cache.get(key)
+ if cached is not None:
+ _stt_cache.move_to_end(key)
+ return cached
+ entry = _SharedRecognizer(backend=build())
+ _stt_cache[key] = entry
+ while len(_stt_cache) > _STT_CACHE_MAX:
+ _stt_cache.popitem(last=False)
+ return entry
+
+
+def _forget_shared_recognizer(entry: _SharedRecognizer) -> None:
+ """Retire a wedged engine so the next session is not handed it back."""
+ with _stt_cache_lock:
+ for key, cached in tuple(_stt_cache.items()):
+ if cached is entry:
+ del _stt_cache[key]
+
+
+def _reset_for_tests() -> None:
+ """Drop the process-wide recognizer cache."""
+ with _stt_cache_lock:
+ _stt_cache.clear()
+
+
+def _language_pinned_stt_config(stt_cfg: Any, language: str | None) -> Any:
+ """``stt_cfg`` with the session's recognition language pinned onto it.
+
+ The configured recognizer takes its language from the STT config, so this is
+ where a session language has to land: from here the value flows through the
+ per-provider gates the STT factory already owns, instead of every backend
+ being probed for a keyword it may not have. A config object that cannot
+ carry a language (a stand-in, an older shape) is returned untouched — the
+ call keeps its configured language rather than losing its recognizer over an
+ attribute.
+ """
+ if not language:
+ return stt_cfg
+ copy = getattr(stt_cfg, "model_copy", None)
+ if not callable(copy) or not hasattr(stt_cfg, "language"):
+ log.debug(
+ "The STT configuration carries no language field, so the local "
+ "input recognizer keeps its configured language instead of %r",
+ language,
+ )
+ return stt_cfg
+ return copy(update={"language": language})
+
+
+def _build_default_stt(language: str | None) -> _SharedRecognizer:
+ """Build (or reuse) the configured recognizer. Blocking — call in a thread."""
+ from jarvis.core.config import load_config # noqa: PLC0415
+ from jarvis.plugins.stt import build_stt_from_config # noqa: PLC0415
+
+ stt_cfg = _language_pinned_stt_config(load_config().stt, language)
+ return _shared_recognizer(repr(stt_cfg), lambda: build_stt_from_config(stt_cfg))
+
+
class LocalInputTranscriber:
"""Turn microphone PCM into ``input_transcript`` events."""
@@ -258,14 +352,24 @@ class LocalInputTranscriber:
sample_rate: int = 24_000,
stt_factory: Any = None,
recognizer_sample_rate: int | None = None,
+ language: str | None = None,
) -> None:
self._sample_rate = sample_rate
self._stt_factory = stt_factory
+ # The session's recognition language. Empty means "whatever the STT
+ # configuration says", which is exactly what callers got before this
+ # parameter existed. Pinning it matters because an ``auto`` recognizer
+ # is the configuration that answers near-silence with caption-style
+ # boilerplate in the wrong language — text this transport would then
+ # treat as something the user said.
+ self._language = (language or "").strip() or None
+ self._factory_language_logged = False
self._recognizer_rate_override = (
int(recognizer_sample_rate) if recognizer_sample_rate else None
)
self._recognizer_rate: int | None = None
self._stt: Any = None
+ self._shared: _SharedRecognizer | None = None
# Control events must survive a stalled consumer, so this is a deque
# evicted by policy rather than an asyncio.Queue that refuses whatever
# arrives last (see ``_emit``). Everything here runs on one event loop,
@@ -288,7 +392,9 @@ class LocalInputTranscriber:
# transcript recovery can overlap the tail of input recognition. The
# guard is a non-blocking flag, NOT a lock: a second caller skips, so a
# call that has hung can never make every later call hang behind it.
- self._recognition_busy = False
+ # Held here only while this transcriber owns its engine alone; a cached
+ # engine carries the flag itself (see ``_recognition_busy``).
+ self._local_recognition_busy = False
# Serializes only the CONSTRUCTION of the recognizer, so two utterances
# racing at session start cannot load the model twice. Never held across
# an inference: a model load inside the inference guard made the first
@@ -472,6 +578,25 @@ class LocalInputTranscriber:
task.add_done_callback(self._tasks.discard)
# -- recognition ---------------------------------------------------
+ @property
+ def _recognition_busy(self) -> bool:
+ """Whether the recognizer behind this transcriber is inside a call.
+
+ Resolved through the shared cache entry whenever there is one: the
+ ENGINE is what a second concurrent entry wedges, so two sessions on one
+ cached backend have to read and write the same flag.
+ """
+ shared = self._shared
+ return shared.busy if shared is not None else self._local_recognition_busy
+
+ @_recognition_busy.setter
+ def _recognition_busy(self, value: bool) -> None:
+ shared = self._shared
+ if shared is not None:
+ shared.busy = bool(value)
+ else:
+ self._local_recognition_busy = bool(value)
+
async def warm(self) -> bool:
"""Build (and prime) the recognizer off the first utterance's path.
@@ -521,18 +646,24 @@ class LocalInputTranscriber:
if self._stt is not None:
return self._stt
factory = self._stt_factory
- if factory is None:
-
- def factory() -> Any: # noqa: ANN202 - local default wiring
- from jarvis.core.config import load_config # noqa: PLC0415
- from jarvis.plugins.stt import ( # noqa: PLC0415
- build_stt_from_config,
+ if factory is not None:
+ # An injected factory owns its own construction, so there is
+ # nothing here that could pin a language onto it. Say so rather
+ # than let a dropped language look like an applied one (AP-30).
+ if self._language and not self._factory_language_logged:
+ self._factory_language_logged = True
+ log.debug(
+ "An injected recognizer factory configures itself, so "
+ "the session language %r is not applied",
+ self._language,
)
-
- return build_stt_from_config(load_config().stt)
-
- stt = await asyncio.to_thread(factory)
+ shared = None
+ stt = await asyncio.to_thread(factory)
+ else:
+ shared = await asyncio.to_thread(_build_default_stt, self._language)
+ stt = shared.backend
self._recognizer_rate = self._resolve_recognizer_rate(stt)
+ self._shared = shared
self._stt = stt
return self._stt
@@ -600,7 +731,15 @@ class LocalInputTranscriber:
utterance constructs a fresh one.
"""
stt = self._stt
+ shared = self._shared
+ if shared is not None:
+ # Dropping only this reference would leave the wedged engine in the
+ # process-wide cache, and the next session would be handed it as if
+ # it were healthy — the "deaf for the rest of the call" signature,
+ # now inherited across calls.
+ _forget_shared_recognizer(shared)
self._stt = None
+ self._shared = None
self._recognizer_rate = None
self._consecutive_failures = 0
self._consecutive_busy = 0
diff --git a/jarvis/realtime/scrub_gate.py b/jarvis/realtime/scrub_gate.py
index 345055cc41..65b3630f03 100644
--- a/jarvis/realtime/scrub_gate.py
+++ b/jarvis/realtime/scrub_gate.py
@@ -32,6 +32,7 @@ import time
from jarvis.brain.output_filter import FALLBACK_PHRASES, ScrubResult, scrub_for_voice
from jarvis.core.protocols import AudioChunk
+from jarvis.core.turn_language import validate_output_language
from jarvis.speech.hangup import END_CALL_SIGNAL
log = logging.getLogger(__name__)
@@ -42,12 +43,13 @@ _HARD_LEAK_ACTIONS = frozenset(
"replaced_stacktrace",
"replaced_raw_repr",
"replaced_shell_command",
+ "output_language_mismatch",
}
)
_RESIDUE_ACTION = "replaced_with_fallback_residue"
_NON_BLOCKING_SCRUB_ACTIONS = frozenset(
{
- "removed_anrede_drift", # i18n-allow: established telemetry action-name identifier (ADR-0010), not prose
+ "removed_anrede_drift", # i18n-allow
"removed_background_action_narration",
"removed_em_dash",
"removed_engineering_jargon",
@@ -96,6 +98,14 @@ class ScrubHoldGate:
del lookahead_ms
self._pending: list[AudioChunk] = []
self._pending_audio_ms = 0.0
+ # Provider-neutral identity of the response whose PCM/transcript this
+ # gate currently holds. Empty means the adapter cannot expose an id
+ # and preserves the legacy ordered-stream contract. Once an adapter
+ # does expose one, a different id can never clear or release this
+ # response's audio: that would pair text from answer B with PCM from
+ # answer A, the exact synchronization failure this gate exists to
+ # prevent.
+ self._response_id = ""
self._cleared = False
self._hard_leak = False
self._transcript_seen = False
@@ -182,13 +192,42 @@ class ScrubHoldGate:
def fallback_phrase(self) -> str:
return FALLBACK_PHRASES.get(self._language, FALLBACK_PHRASES["en"])
- async def feed_transcript(self, text: str) -> str:
+ def begin_response(self, response_id: str = "") -> bool:
+ """Bind this gate to one provider response.
+
+ Adapters that cannot identify responses pass the default empty value
+ and keep the existing ordered-stream behaviour. A non-empty mismatch
+ fails closed and drops every held chunk; callers then cancel the
+ provider response and speak the ordinary safe fallback.
+ """
+ identity = str(response_id or "").strip()
+ if not identity:
+ return True
+ if not self._response_id:
+ self._response_id = identity
+ return True
+ if identity == self._response_id:
+ return True
+ self._hard_leak = True
+ self._hard_leak_actions = ("response_identity_mismatch",)
+ self._cleared = False
+ self._pending.clear()
+ self._pending_audio_ms = 0.0
+ self._pending_since = None
+ return False
+
+ @property
+ def response_id(self) -> str:
+ """The non-empty provider response currently owned by this gate."""
+ return self._response_id
+
+ async def feed_transcript(self, text: str, *, response_id: str = "") -> str:
"""Scrub a transcript boundary. Returns display-safe text.
Sets the clear flag (audio may flow) on clean text; sets the hard-leak
flag (audio dropped) on a hard leak.
"""
- if self._hard_leak:
+ if not self.begin_response(response_id) or self._hard_leak:
return self.fallback_phrase()
text = self._strip_stream_controls(str(text or ""))
@@ -202,6 +241,18 @@ class ScrubHoldGate:
self._transcript_seen = True
aggregate = scrub_for_voice(self._transcript_tail, language=self._language)
result = scrub_for_voice(text, language=self._language)
+ language_verdict = validate_output_language(
+ aggregate.cleaned,
+ resolved_language=self._language,
+ )
+ if language_verdict.should_block:
+ self._hard_leak = True
+ self._hard_leak_actions = ("output_language_mismatch",)
+ self._cleared = False
+ self._pending.clear()
+ self._pending_audio_ms = 0.0
+ self._pending_since = None
+ return self.fallback_phrase()
aggregate_is_hard = _is_hard_scrub_result(aggregate)
result_is_hard = _is_hard_scrub_result(result)
if aggregate_is_hard or result_is_hard:
@@ -257,7 +308,12 @@ class ScrubHoldGate:
break
return combined
- async def push_audio(self, chunk: AudioChunk) -> list[AudioChunk]:
+ async def push_audio(
+ self,
+ chunk: AudioChunk,
+ *,
+ response_id: str = "",
+ ) -> list[AudioChunk]:
"""Buffer or release an audio delta. Returns chunks safe to play now.
Two states only (maintainer mandate 2026-07-18, BUG-080 follow-up —
@@ -273,7 +329,7 @@ class ScrubHoldGate:
hard leak in a later delta drops all unplayed audio and cancels
the response.
"""
- if self._hard_leak:
+ if not self.begin_response(response_id) or self._hard_leak:
return []
self._expire_direct_speech_budget()
if not self._cleared and not self._coverage_active:
@@ -383,7 +439,7 @@ class ScrubHoldGate:
self._hard_leak_actions = ("transcript_stalled",)
return True
- def finalize(self) -> list[AudioChunk]:
+ def finalize(self, *, response_id: str = "") -> list[AudioChunk]:
"""Release the clean transcript-covered tail at the response boundary.
Trust basis: at a genuine response boundary every transcript delta of
@@ -394,6 +450,8 @@ class ScrubHoldGate:
beyond the estimate means transcription lagged or died mid-turn;
log it so the next incident names this producer (BUG-069 review).
"""
+ if not self.begin_response(response_id):
+ return []
self._expire_direct_speech_budget()
if self.fail_closed() or self._hard_leak:
return []
@@ -446,6 +504,7 @@ class ScrubHoldGate:
self._transcript_tail = ""
self._control_tail = ""
self._hard_leak_actions = ()
+ self._response_id = ""
self._pending_since = None
self.last_hold_ms = 0.0
self._released_ms = 0.0
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 0168edca30..c16cb370fb 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -16,11 +16,17 @@ import random
import re
import time
from collections import Counter, deque
+from collections.abc import Callable
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Any
from uuid import uuid4
+# The planner module itself is also imported: the delegate-by-default
+# ambiguity test for tool-less transports reuses the planner's suppressor
+# vocabulary in place instead of keeping a second copy here that would
+# silently drift.
+from jarvis.brain import turn_planner as _planner_vocab
from jarvis.brain.action_honesty import (
action_not_started_phrase,
has_deferred_action_claim,
@@ -83,6 +89,17 @@ _HALF_DUPLEX_MUTE_REPEAT_S = 10.0
# reply that is merely pausing keeps its mute, and far below the alert. No
# audio playing means no echo risk — reopening matches barge-in semantics.
_HALF_DUPLEX_SILENT_RELEASE_S = 2.0
+# Provider-frame silence says the provider stopped SENDING, not that the room
+# stopped HEARING: the desktop surface still holds ~180 ms of jitter reserve
+# plus the device's output latency in flight (DEFAULT_PREBUFFER_MS in
+# jarvis.realtime.desktop; 0.410 s device latency measured live 2026-08-08,
+# 0.869 s worst field report, BUG-100). Where the surface exposes a PHYSICAL
+# playback probe (``set_playback_probe``) the release consults it directly;
+# where it does not, this margin is added to the silence window so the mic
+# does not reopen into the reply's still-audible tail (self-talk fuel on open
+# speakers). The probe's veto is bounded by the alert threshold below — a
+# latched probe must never create a new stuck-mute class.
+_HALF_DUPLEX_NO_PROBE_DRAIN_MARGIN_S = 1.0
# Before the conversation's language is ESTABLISHED, a final this short is
# too little audio to trust its words for the language decision ("Was geht
# ab?" misheard as "Vaskit up" flipped a whole German call to English).
@@ -107,6 +124,11 @@ _OUTPUT_DROP_LOG_INTERVAL_S = 2.0
# (cleared on rebuild) and bounded, so a long call cannot grow one entry per
# utterance forever.
_ANSWERED_INPUT_ID_MAX = 64
+# Provider response ids retained after a boundary. This suppresses audio or
+# transcript frames that arrive late from a completed response instead of
+# letting them open and clear the next response's scrub gate. Per session and
+# bounded, like the input-item duplicate guard above.
+_COMPLETED_RESPONSE_ID_MAX = 64
_TOOL_TRANSCRIPT_WAIT_S = 3.0
# Grace window for the model to finish its goodbye after an end_call tool
# call; if the provider never sends turn_complete, hang up anyway.
@@ -623,6 +645,61 @@ def _requires_jarvis_action(text: str) -> bool:
return plan_turn(text).requires_orchestrator
+# Delegate-by-default floor: a tasking phrase alone ("bitte", "please") is an
+# interjection, not a request — it must carry at least this many words before
+# an ambiguous final is worth a delegation round trip.
+_TOOLLESS_AMBIGUITY_MIN_WORDS = 3
+# Hear-me probes phrased AS a task ("Kannst du mich hoeren?"): the closed
+# presence vocabulary above covers only the bare idioms, and a hearing check
+# routed through a 12-34 s delegation reads as a dead call. Matched on the
+# planner-normalized text (ae/oe/ue form).
+# i18n-allow: multilingual speech-input matching data
+_TOOLLESS_HEARING_PROBE_RE = re.compile(
+ r"\bmich\s+(?:noch\s+|gut\s+|jetzt\s+)?(?:hoeren|verstehen)\b"
+ r"|\bhear\s+me\b|\bunderstand\s+me\b"
+ r"|\bme\s+(?:oyes|escuchas|entiendes)\b"
+)
+
+
+def _toolless_ambiguous_action(text: str) -> bool:
+ """Whether an action-shaped-but-ambiguous final should delegate anyway.
+
+ Only consulted for providers that declare ``supports_direct_tools=False``
+ (capability read, AP-21): on such a transport the session-side planner is
+ the ONLY action path — there is no native tool declaration the model
+ could fall back to, and the model-initiated handoff item has never been
+ observed on the live wire. A final the planner routes natively is
+ therefore answered unaided by the far end, and any action in it is lost
+ with only the ``handoff_obligation_misses`` audit as a trace.
+
+ So the tie-break flips for these transports: a final that TASKS the
+ assistant ("kannst du …", "please …") but matches none of the planner's
+ action vocabulary prefers DELEGATION over a native answer. Over-matching
+ costs latency only — the orchestrator still answers conversationally —
+ while under-matching loses the user's action (the planner module states
+ the same doctrine for its own action vocabulary). Deterministic regex on
+ the final's shape, reusing the planner's vocabulary verbatim; no LLM, no
+ I/O. Explanation shapes (definition / how-to / opinion) and bare
+ presence probes stay native — they are conversation, not lost actions.
+ """ # i18n-allow: quotes the German tasking idiom the vocabulary matches
+ normalized = _planner_vocab._normalize(text).strip()
+ if not normalized:
+ return False
+ if len(normalized.split()) < _TOOLLESS_AMBIGUITY_MIN_WORDS:
+ return False
+ if not _planner_vocab._ASSISTANT_TASKING_RE.search(normalized):
+ return False
+ if (
+ _planner_vocab._DEFINITION_RE.search(normalized)
+ or _planner_vocab._INSTRUCTIONAL_RE.search(normalized)
+ or _planner_vocab._OPINION_RE.search(normalized)
+ ):
+ return False
+ if _TOOLLESS_HEARING_PROBE_RE.search(normalized):
+ return False
+ return not _is_presence_check(text)
+
+
# Ceiling for a delegate reply injected into the provider context. ~4 000
# characters is roughly three spoken minutes — far beyond any real voice
# answer, small enough to stop a runaway tool result from riding along in
@@ -1313,6 +1390,13 @@ class RealtimeVoiceSession:
# the condition is visible instead of invisible (AP-30).
self._half_duplex_muted_since: float | None = None
self._half_duplex_mute_reported = 0.0
+ # Physical playback probe, installed by the owning surface via
+ # ``set_playback_probe`` when provider PCM plays through a device this
+ # process can observe (the desktop pipeline's AudioPlayer window).
+ # Capability injection, never a surface-id check (AP-21): a surface
+ # that plays elsewhere (browser) simply never installs one and the
+ # provider-frame heuristic plus drain margin governs the mute release.
+ self._playback_active_probe: Callable[[], bool] | None = None
# When provider audio last actually reached the surface. A reply that
# is still playing must never be cut short by the mute release below,
# and "is it still playing" is a question only this timestamp answers:
@@ -1338,6 +1422,15 @@ class RealtimeVoiceSession:
self._audio_start_monotonic = 0.0
self._ready_monotonic = 0.0
self._first_audio_emit_monotonic = 0.0
+ # First user FINAL of the call and the answer latency measured from
+ # it to the first AUDIBLE provider frame that follows. This is the
+ # user-perceived wait; ``first_audio_ms`` (from session start) also
+ # counts the user's own speaking time and read as a budget breach on
+ # a call whose real wait was under a second (8 311 ms vs 923 ms,
+ # codex live 2026-08-08). 0 = never measured, so a captured sub-ms
+ # value is floored to 1.
+ self._first_final_monotonic = 0.0
+ self._first_final_to_first_audio_ms = 0
self._rebuild_count = 0
self._mute_emergency_releases = 0
self._language_flips = 0
@@ -1351,6 +1444,12 @@ class RealtimeVoiceSession:
self._handoff_requests = 0
self._handoff_delegate_dispatches = 0
self._handoff_declines = 0
+ # Delegate-by-default dispatches on a tool-less transport (finals the
+ # planner routed natively but whose tasking shape delegated anyway).
+ # Kept apart from the planner-confirmed action counters so the audit
+ # can tell planner dispatches, ambiguity dispatches and
+ # model-initiated handoffs from one another.
+ self._handoff_ambiguous_delegations = 0
self._handoff_action_seen_for_turn = False
brain_config = getattr(self._config, "brain", None)
@@ -1543,6 +1642,12 @@ class RealtimeVoiceSession:
self._tool_transcript_task: asyncio.Task[None] | None = None
self._response_requested_for_turn = False
self._response_requested_input_ids: set[str] = set()
+ self._active_provider_response_id = ""
+ self._completed_provider_response_ids: deque[str] = deque(
+ maxlen=_COMPLETED_RESPONSE_ID_MAX
+ )
+ self._response_identity_drops = 0
+ self._unsafe_output_cancellations = 0
# True once the surface TTS spoke anything in THIS turn, so the turn is
# answered and the no-audio rescue must not speak over it.
self._surface_spoke_this_turn = False
@@ -1615,6 +1720,12 @@ class RealtimeVoiceSession:
).strip()
# The turn has real text now; the live caption served its purpose.
self._last_user_text_preview = ""
+ if not self._first_final_monotonic:
+ # Anchor of the user-perceived answer wait: the first audible
+ # provider frame emitted from here on closes the measurement
+ # (``first_final_to_first_audio_ms``). A greeting still draining
+ # can only SHORTEN the reading, never lengthen it.
+ self._first_final_monotonic = time.monotonic()
def _resolve_lang(self, *, text: str, voiced_ms: int = 0) -> str:
brain = getattr(self._config, "brain", None)
@@ -2330,6 +2441,43 @@ class RealtimeVoiceSession:
self._pump(), name=f"rt-pump-{self.session_id}"
)
+ def set_playback_probe(self, probe: Callable[[], bool] | None) -> None:
+ """Install the surface's PHYSICAL playback probe (capability, AP-21).
+
+ The probe answers "is provider audio audible on the output device
+ right now" — e.g. the desktop pipeline's ``level_tap.playback_active``
+ window, stamped by the AudioPlayer at block-write time. The mute
+ release consults it because provider-frame silence only proves the
+ provider stopped SENDING while the surface's jitter reserve and the
+ device drain are still audibly playing; reopening the microphone into
+ that tail feeds the reply's remainder back in as user speech on open
+ speakers. Surfaces whose playback this process cannot observe simply
+ never call this and keep the heuristic release with a drain margin.
+ """
+ self._playback_active_probe = probe if callable(probe) else None
+
+ def _playback_physically_active(self) -> bool | None:
+ """The probe's verdict, or ``None`` when no working probe exists.
+
+ A probe that raises is disabled for the rest of the call (reported,
+ AP-30): the heuristic drain margin then governs, which can only make
+ the release LATER, never a new stuck-mute class.
+ """
+ probe = self._playback_active_probe
+ if probe is None:
+ return None
+ try:
+ return bool(probe())
+ except Exception: # noqa: BLE001 — degrade to the heuristic release
+ self._playback_active_probe = None
+ log.warning(
+ "realtime[%s] physical playback probe failed — falling back "
+ "to the provider-frame release heuristic for this call",
+ self.session_id,
+ exc_info=True,
+ )
+ return None
+
def _note_half_duplex_mute(self) -> None:
"""Release, or failing that report, a microphone held shut too long.
@@ -2345,6 +2493,14 @@ class RealtimeVoiceSession:
mute time alone: a long reply that is still playing keeps its
microphone shut, exactly as half-duplex intends. Only a turn that is
both overdue AND no longer producing audio is treated as over.
+
+ "No longer producing audio" is judged PHYSICALLY where the surface
+ installed a playback probe: provider-frame silence leaves ~180 ms of
+ jitter reserve plus the device drain still audible, and releasing
+ into that tail re-entered the reply's remainder through the open
+ microphone. The probe's veto is bounded by the alert threshold so a
+ latched probe can only delay the release, never remove it — the
+ emergency exit semantics stay exactly as before.
"""
now = time.monotonic()
if self._half_duplex_muted_since is None:
@@ -2355,7 +2511,18 @@ class RealtimeVoiceSession:
return
silent_since = self._last_output_audio_at or self._half_duplex_muted_since
silent_s = now - silent_since
- if silent_s >= _HALF_DUPLEX_SILENT_RELEASE_S:
+ physically_active = self._playback_physically_active()
+ required_silent_s = _HALF_DUPLEX_SILENT_RELEASE_S
+ if physically_active is None:
+ # No physical probe: the provider-frame heuristic cannot see the
+ # surface's prebuffer/device drain, so cover it with the margin.
+ required_silent_s += _HALF_DUPLEX_NO_PROBE_DRAIN_MARGIN_S
+ elif physically_active and muted_s < _HALF_DUPLEX_MUTE_ALERT_S:
+ # The reply is still audibly on the device — reopening now would
+ # feed its remainder back into the microphone. Bounded veto: past
+ # the alert threshold the release below runs regardless.
+ return
+ if silent_s >= required_silent_s:
self._mute_emergency_releases += 1
log.log(
# The fast release is the DESIGNED boundary-of-last-resort on
@@ -2366,11 +2533,19 @@ class RealtimeVoiceSession:
if muted_s >= _HALF_DUPLEX_MUTE_ALERT_S
else logging.INFO,
"realtime[%s] releasing a half-duplex mute held %.1fs with no "
- "provider audio for %.1fs - the turn ended without a boundary, "
- "so the microphone is reopened rather than left deaf",
+ "provider audio for %.1fs (physical playback: %s) - the turn "
+ "ended without a boundary, so the microphone is reopened "
+ "rather than left deaf",
self.session_id,
muted_s,
silent_s,
+ (
+ "no probe"
+ if physically_active is None
+ else "still active, alert threshold overrides"
+ if physically_active
+ else "drained"
+ ),
)
self._reset_output_state(reason="half-duplex mute outlived its turn")
self._half_duplex_muted_since = None
@@ -2758,6 +2933,8 @@ class RealtimeVoiceSession:
# the per-turn stall watchdog measures exactly one thing: total
# provider silence inside an open turn.
self._note_turn_activity()
+ if not await self._accept_provider_response_event(event):
+ continue
if event.type == "input_transcript":
transcript = _dictionary_corrected(str(event.text or "").strip())
transcription_failed = bool(event.error)
@@ -2968,6 +3145,30 @@ class RealtimeVoiceSession:
):
self._handoff_action_turns += 1
self._handoff_action_seen_for_turn = True
+ # Delegate-by-default on ambiguity, tool-less
+ # transports ONLY (capability read, AP-21): the
+ # planner is their one action path, so a final that
+ # tasks the assistant but matches no planner category
+ # prefers delegation over the far end answering
+ # unaided — the miss would otherwise only surface as
+ # a handoff_obligation_misses count after the call.
+ # Providers with native tools keep today's routing:
+ # their model can still call the declared function.
+ ambiguous_action_default = bool(
+ not turn_plan.requires_orchestrator
+ and not self._active_provider_supports_direct_tools()
+ and self._delegate_enabled
+ and self._last_user_text
+ and _toolless_ambiguous_action(self._last_user_text)
+ )
+ if ambiguous_action_default:
+ self._handoff_ambiguous_delegations += 1
+ log.info(
+ "realtime[%s] tool-less transport: final is "
+ "action-shaped but ambiguous — delegating by "
+ "default instead of a native answer",
+ self.session_id,
+ )
reasons = ",".join(
sorted(reason.value for reason in turn_plan.reasons)
) or "none"
@@ -2989,6 +3190,7 @@ class RealtimeVoiceSession:
self._delegate_required_for_turn = (
self._delegate_required_for_turn
or turn_plan.requires_orchestrator
+ or ambiguous_action_default
or self._brain_awaits_voice_confirm()
or self._answers_open_delegate_question()
)
@@ -3005,6 +3207,7 @@ class RealtimeVoiceSession:
),
delegate_discouraged=(
not turn_plan.requires_orchestrator
+ and not ambiguous_action_default
),
)
update_kwargs: dict[str, Any] = {
@@ -3289,7 +3492,12 @@ class RealtimeVoiceSession:
self._note_output_withheld("transcript")
continue
await self._ensure_turn_started()
- await self._gate.feed_transcript(event.text)
+ await self._gate.feed_transcript(
+ event.text,
+ response_id=str(
+ getattr(event, "provider_turn_id", "") or ""
+ ),
+ )
if self._gate.hard_leak_pending():
_actions = ", ".join(self._gate.hard_leak_actions())
await self._cancel_unsafe_output(
@@ -3326,7 +3534,12 @@ class RealtimeVoiceSession:
if await self._recover_unbacked_action_claim():
continue
self._mark_latency_named("REALTIME_FIRST_TRANSCRIPT")
- display = await self._gate.feed_transcript(event.text)
+ display = await self._gate.feed_transcript(
+ event.text,
+ response_id=str(
+ getattr(event, "provider_turn_id", "") or ""
+ ),
+ )
if self._gate.hard_leak_pending():
# Name the tripped detectors (safe metadata, never the
# flagged content) so a false-positive abort is
@@ -3436,7 +3649,12 @@ class RealtimeVoiceSession:
await self._ensure_turn_started()
self._mark_latency_named("REALTIME_FIRST_AUDIO")
self._output_active = True
- released = await self._gate.push_audio(event.audio)
+ released = await self._gate.push_audio(
+ event.audio,
+ response_id=str(
+ getattr(event, "provider_turn_id", "") or ""
+ ),
+ )
for chunk in released:
await self._emit_audio(chunk)
if self._gate.fail_if_pending_exceeds(
@@ -3733,7 +3951,11 @@ class RealtimeVoiceSession:
await self._send_json(
self._surface_speech_message(fallback_text)
)
- final_chunks = self._gate.finalize()
+ final_chunks = self._gate.finalize(
+ response_id=str(
+ getattr(event, "provider_turn_id", "") or ""
+ )
+ )
if self._gate.hard_leak_pending():
# Same rendering-failure contract as the pending-buffer
# trip above: a delegate readback whose transcription
@@ -3834,7 +4056,9 @@ class RealtimeVoiceSession:
# chopped harder than the transport failure requires;
# audio without a cleared transcript stays withheld
# (fail-closed).
- final_chunks = self._gate.finalize()
+ final_chunks = self._gate.finalize(
+ response_id=self._active_provider_response_id
+ )
if self._gate.hard_leak_pending():
await self._cancel_unsafe_output(
reason="output transcript missing at provider error",
@@ -3929,7 +4153,9 @@ class RealtimeVoiceSession:
self._output_transcript.append(trusted_reply)
await self._complete_surface_turn()
elif self._output_active or self._response_requested_for_turn:
- final_chunks = self._gate.finalize()
+ final_chunks = self._gate.finalize(
+ response_id=self._active_provider_response_id
+ )
if self._gate.hard_leak_pending():
await self._cancel_unsafe_output(
reason="output transcript missing at provider stream end",
@@ -4401,6 +4627,8 @@ class RealtimeVoiceSession:
)
return
self._scrub_cancelled_for_turn = True
+ self._unsafe_output_cancellations += 1
+ self._retire_active_provider_response()
self._drop_provider_output_until_new_response = True
self._mark_latency_named(
"REALTIME_SCRUB_CANCEL",
@@ -4775,6 +5003,84 @@ class RealtimeVoiceSession:
)
return None
+ async def _accept_provider_response_event(self, event: Any) -> bool:
+ """Pair provider audio, transcript and boundary by response identity.
+
+ Empty ids preserve compatibility with adapters that expose only an
+ ordered event stream. Once a non-empty id is present, late events from
+ completed responses are dropped and an unsequenced id change fails
+ closed: transcript from response B can never authorize PCM from A.
+ """
+ if event.type not in {
+ "audio_delta",
+ "output_transcript_delta",
+ "turn_complete",
+ }:
+ return True
+ response_id = str(getattr(event, "provider_turn_id", "") or "").strip()
+ active_id = self._active_provider_response_id
+ if response_id and response_id in self._completed_provider_response_ids:
+ self._response_identity_drops += 1
+ log.warning(
+ "realtime[%s] dropped a late %s event for completed provider "
+ "response %s",
+ self.session_id,
+ event.type,
+ response_id,
+ )
+ return False
+
+ if event.type == "turn_complete":
+ boundary_id = response_id or active_id
+ if response_id and active_id and response_id != active_id:
+ self._response_identity_drops += 1
+ log.warning(
+ "realtime[%s] dropped a terminal boundary for provider "
+ "response %s while response %s is active",
+ self.session_id,
+ response_id,
+ active_id,
+ )
+ return False
+ if boundary_id:
+ self._completed_provider_response_ids.append(boundary_id)
+ self._active_provider_response_id = ""
+ return True
+
+ if not response_id:
+ return True
+ if not active_id:
+ self._active_provider_response_id = response_id
+ self._gate.begin_response(response_id)
+ return True
+ if response_id == active_id:
+ return True
+
+ # A new response arrived without a boundary for the one whose PCM is
+ # still in the scrub gate. Drop both the held PCM and this first
+ # mismatched event, cancel the unsafe generation once, then allow
+ # subsequent events of the new identity to start cleanly.
+ self._response_identity_drops += 1
+ await self._cancel_unsafe_output(
+ reason=(
+ "provider response identity changed before the previous "
+ "response boundary"
+ )
+ )
+ if active_id not in self._completed_provider_response_ids:
+ self._completed_provider_response_ids.append(active_id)
+ self._gate.drain()
+ self._active_provider_response_id = response_id
+ self._gate.begin_response(response_id)
+ return False
+
+ def _retire_active_provider_response(self) -> None:
+ """Remember the active response id as closed and clear its owner."""
+ response_id = self._active_provider_response_id
+ if response_id and response_id not in self._completed_provider_response_ids:
+ self._completed_provider_response_ids.append(response_id)
+ self._active_provider_response_id = ""
+
def _latency_detail(self, detail: str = "") -> str:
fields = [
f"session_id={self.session_id}",
@@ -5330,6 +5636,7 @@ class RealtimeVoiceSession:
log.debug(
"realtime[%s] output state reset (%s)", self.session_id, reason
)
+ self._retire_active_provider_response()
self._output_active = False
self._output_samples_sent = 0
self._response_requested_for_turn = False
@@ -7037,6 +7344,27 @@ class RealtimeVoiceSession:
audible = _pcm16_peak(pcm) >= _EMBEDDED_SILENCE_PEAK
if audible:
self._last_output_audio_at = time.monotonic()
+ if (
+ self._first_final_monotonic
+ and not self._first_final_to_first_audio_ms
+ ):
+ # User-perceived answer wait: first user FINAL → this first
+ # AUDIBLE frame. Floored to 1 ms so a captured value can
+ # never read as the 0 "never measured" sentinel.
+ self._first_final_to_first_audio_ms = max(
+ 1,
+ int(
+ (time.monotonic() - self._first_final_monotonic)
+ * 1000.0
+ ),
+ )
+ log.info(
+ "RT-SPAWN span=first_final_to_first_audio ms=%d "
+ "session=%s provider=%s",
+ self._first_final_to_first_audio_ms,
+ self.session_id,
+ self.active_provider,
+ )
self._output_samples_sent += len(pcm) // 2
rate = max(1, int(getattr(chunk, "sample_rate", 0) or 24_000))
if audible:
@@ -7178,19 +7506,31 @@ class RealtimeVoiceSession:
return bool(getattr(self._provider, "supports_direct_tools", True))
def _log_handoff_observability(self) -> None:
- """Emit one content-free summary when handoffs mattered this call."""
- if self._handoff_action_turns <= 0:
+ """Emit one content-free summary when handoffs mattered this call.
+
+ The counters keep the three action origins apart: ``handoff_requests``
+ are model-initiated, ``delegate_dispatches`` are deterministic
+ planner/session dispatches, and ``ambiguous_delegations`` are the
+ delegate-by-default subset among them (finals the planner routed
+ natively but whose tasking shape delegated anyway).
+ """
+ if (
+ self._handoff_action_turns <= 0
+ and self._handoff_ambiguous_delegations <= 0
+ ):
return
misses = max(0, self._handoff_action_turns - self._handoff_requests)
logger = log.warning if misses else log.info
logger(
"realtime[%s] capability-limited action audit: action_turns=%d "
- "handoff_requests=%d delegate_dispatches=%d declines=%d "
+ "handoff_requests=%d delegate_dispatches=%d "
+ "ambiguous_delegations=%d declines=%d "
"handoff_obligation_misses=%d",
self.session_id,
self._handoff_action_turns,
self._handoff_requests,
self._handoff_delegate_dispatches,
+ self._handoff_ambiguous_delegations,
self._handoff_declines,
misses,
)
@@ -7217,6 +7557,7 @@ class RealtimeVoiceSession:
duration_ms=int((now - start) * 1000.0),
ready_ms=_since_start_ms(self._ready_monotonic),
first_audio_ms=_since_start_ms(self._first_audio_emit_monotonic),
+ first_final_to_first_audio_ms=self._first_final_to_first_audio_ms,
turns_completed=self._turn_index,
rebuilds=self._rebuild_count,
stun_retries=diag.get("stun_retries", 0),
@@ -7231,6 +7572,26 @@ class RealtimeVoiceSession:
terminal_item_turns=diag.get("terminal_item_turns", 0),
response_splices=diag.get("response_splices", 0),
sequenced_boundaries=diag.get("sequenced_boundaries", 0),
+ output_shadow_recovery_attempts=diag.get(
+ "output_shadow_recovery_attempts", 0
+ ),
+ output_shadow_recovery_successes=diag.get(
+ "output_shadow_recovery_successes", 0
+ ),
+ output_shadow_recovery_exhausted=diag.get(
+ "output_shadow_recovery_exhausted", 0
+ ),
+ output_terminal_recovery_attempts=diag.get(
+ "output_terminal_recovery_attempts", 0
+ ),
+ output_terminal_recovery_successes=diag.get(
+ "output_terminal_recovery_successes", 0
+ ),
+ output_transcript_recovery_failures=diag.get(
+ "output_transcript_recovery_failures", 0
+ ),
+ response_identity_drops=self._response_identity_drops,
+ unsafe_output_cancellations=self._unsafe_output_cancellations,
opening_responses_bounded=diag.get("opening_responses_bounded", 0),
self_dialogue_rebuilds=diag.get("self_dialogue_rebuilds", 0),
handoff_action_turns=self._handoff_action_turns,
@@ -7240,6 +7601,7 @@ class RealtimeVoiceSession:
handoff_obligation_misses=max(
0, self._handoff_action_turns - self._handoff_requests
),
+ handoff_ambiguous_delegations=self._handoff_ambiguous_delegations,
mute_emergency_releases=self._mute_emergency_releases,
sender_pacing_resyncs=diag.get("sender_pacing_resyncs", 0),
sender_shed_frames=diag.get("sender_shed_frames", 0),
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 6c02920065..79a1bc1587 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -8511,6 +8511,19 @@ class SpeechPipeline:
allow_classic_fallback = bool(
getattr(session, "allow_classic_fallback", True)
)
+ # Desktop plays provider PCM through the process-local
+ # AudioPlayer, whose write path stamps level_tap's playback
+ # window — a PHYSICAL "audio is audible right now" probe. The
+ # session's half-duplex mute release uses it so the mic stays
+ # shut while the prebuffered/device-drained reply tail is
+ # still audible (provider-frame silence alone reopened into
+ # that tail and fed the reply back in on open speakers).
+ # Capability injection: only this surface owns the player, so
+ # only this surface installs the probe (getattr keeps older
+ # session objects working).
+ probe_setter = getattr(session, "set_playback_probe", None)
+ if callable(probe_setter):
+ probe_setter(level_tap.playback_active)
handshake_started_at = time.monotonic()
handshake_task = asyncio.create_task(
session.handle_control(
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
index 2b1b03b46d..36af928190 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
@@ -2613,8 +2613,9 @@ describe("chat view", () => {
expect(title.textContent).toBe("Fix provider selection priority");
// The mark LEADS the row and the title follows it, the way a list of
// conversations reads: the title is the subject, the mark says which CLI
- // is having it.
- const mark = title.previousElementSibling;
+ // is having it. The title sits inside its tooltip anchor, so the mark is
+ // the ANCHOR's previous sibling.
+ const mark = title.parentElement?.previousElementSibling;
expect(mark?.getAttribute("data-testid")).toBe("agent-mark-codex");
expect(mark?.querySelector("img")?.getAttribute("src")).toBe(
"/provider-logos/openai.svg",
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
index 7e48c220e8..8345447b90 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -45,6 +45,7 @@ import { useThemeValue } from "@/hooks/useTheme";
import { useDocumentVisible } from "@/hooks/useDocumentVisible";
import { useResizablePane } from "@/hooks/useResizablePane";
import { PaneResizer } from "@/components/layout/PaneResizer";
+import { QuickTooltip } from "@/components/ui/tooltip";
import { useEventStore, type VoiceState } from "@/store/events";
import { AgenticTerminal, type PaneStatus, type SplitDirection } from "./AgenticTerminal";
import { AgentMark } from "./AgentMark";
@@ -2550,16 +2551,25 @@ export function AgenticGrid({
size="sm"
variant="plain"
/>
- <span
- data-testid={`chat-rail-title-${term.name}`}
- className={cn(
- "min-w-0 flex-1 truncate text-[12px]",
- active ? "text-foreground" : "text-foreground/75",
- )}
- title={title}
+ {/* The app's own bubble, not `title=`: the native
+ tooltip takes over a second to appear and is drawn
+ in the OS's grey box — a foreign artifact over a
+ rail whose whole point is the title. */}
+ <QuickTooltip
+ content={title}
+ side="right"
+ className="min-w-0 flex-1"
>
- {title}
- </span>
+ <span
+ data-testid={`chat-rail-title-${term.name}`}
+ className={cn(
+ "block truncate text-[12px]",
+ active ? "text-foreground" : "text-foreground/75",
+ )}
+ >
+ {title}
+ </span>
+ </QuickTooltip>
</span>
{/* Not "live". Every pane in this list is live, all day —
what the user is scanning for is which of them still
diff --git a/jarvis/ui/web/frontend/src/components/ui/tooltip.tsx b/jarvis/ui/web/frontend/src/components/ui/tooltip.tsx
new file mode 100644
index 0000000000..57b8036a29
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ui/tooltip.tsx
@@ -0,0 +1,151 @@
+/**
+ * A fast, app-styled replacement for the native `title` attribute.
+ *
+ * The native tooltip is the wrong tool for a truncated label: it waits a
+ * second and a half before appearing, and it is drawn by the OS in whatever
+ * grey box the platform ships — a foreign artifact on top of the app's own
+ * surfaces. This one appears quickly, wears the same card surface as every
+ * other floating panel here, and is rendered in a portal so a clipping
+ * ancestor (a scrolling rail, an `overflow: hidden` pane) cannot cut it off.
+ *
+ * Deliberately NOT interactive, unlike the recap card: a tooltip repeats text
+ * that is already on screen but truncated. Anything that needs hovering,
+ * clicking or copying belongs in a real popover, not here.
+ */
+import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
+import { createPortal } from "react-dom";
+import { cn } from "@/lib/utils";
+
+/** Quick enough to feel immediate, long enough that sweeping the cursor
+ * across a list does not flash a tooltip per row. */
+const SHOW_DELAY_MS = 180;
+const MAX_WIDTH = 320;
+/** Gap between the anchor and the bubble. */
+const GAP = 8;
+const VIEWPORT_MARGIN = 8;
+
+type Side = "right" | "top" | "bottom";
+
+interface Position {
+ left: number;
+ top: number;
+}
+
+function place(anchor: DOMRect, bubble: DOMRect, side: Side): Position {
+ let left: number;
+ let top: number;
+ if (side === "right") {
+ left = anchor.right + GAP;
+ top = anchor.top + anchor.height / 2 - bubble.height / 2;
+ // A rail sits at the screen edge; if the bubble cannot fit to the right,
+ // fall through to "below" rather than covering the anchor.
+ if (left + bubble.width > window.innerWidth - VIEWPORT_MARGIN) {
+ left = anchor.left;
+ top = anchor.bottom + GAP;
+ }
+ } else if (side === "top") {
+ left = anchor.left + anchor.width / 2 - bubble.width / 2;
+ top = anchor.top - GAP - bubble.height;
+ } else {
+ left = anchor.left + anchor.width / 2 - bubble.width / 2;
+ top = anchor.bottom + GAP;
+ }
+ left = Math.min(Math.max(left, VIEWPORT_MARGIN), window.innerWidth - bubble.width - VIEWPORT_MARGIN);
+ top = Math.min(Math.max(top, VIEWPORT_MARGIN), window.innerHeight - bubble.height - VIEWPORT_MARGIN);
+ return { left, top };
+}
+
+/**
+ * Wraps its children in a span that shows `content` in an app-styled bubble on
+ * hover or keyboard focus. Replaces `title=` — never add both, or the native
+ * box will race this one.
+ */
+export function QuickTooltip({
+ content,
+ side = "right",
+ disabled = false,
+ className,
+ children,
+}: {
+ /** What the bubble says. An empty string never opens. */
+ content: string;
+ side?: Side;
+ /** Suppress entirely — for rows whose text is not truncated, say. */
+ disabled?: boolean;
+ /** Classes for the anchor span, so this can slot into an existing layout. */
+ className?: string;
+ children: ReactNode;
+}) {
+ const anchorRef = useRef<HTMLSpanElement | null>(null);
+ const bubbleRef = useRef<HTMLDivElement | null>(null);
+ const timerRef = useRef<number | null>(null);
+ const [open, setOpen] = useState(false);
+ const [position, setPosition] = useState<Position | null>(null);
+
+ const cancel = useCallback(() => {
+ if (timerRef.current !== null) {
+ window.clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }
+ setOpen(false);
+ setPosition(null);
+ }, []);
+
+ const schedule = useCallback(() => {
+ if (disabled || !content.trim()) return;
+ if (timerRef.current !== null) window.clearTimeout(timerRef.current);
+ timerRef.current = window.setTimeout(() => {
+ timerRef.current = null;
+ setOpen(true);
+ }, SHOW_DELAY_MS);
+ }, [disabled, content]);
+
+ useEffect(() => cancel, [cancel]);
+
+ // Two-pass placement: the bubble has to exist to be measured, so it mounts
+ // invisible, is measured, and only then receives its coordinates.
+ useEffect(() => {
+ if (!open) return;
+ const anchor = anchorRef.current?.getBoundingClientRect();
+ const bubble = bubbleRef.current?.getBoundingClientRect();
+ if (!anchor || !bubble) return;
+ setPosition(place(anchor, bubble, side));
+ }, [open, side]);
+
+ return (
+ <span
+ ref={anchorRef}
+ className={className}
+ onMouseEnter={schedule}
+ onMouseLeave={cancel}
+ onFocus={schedule}
+ onBlur={cancel}
+ // Selecting the row is the moment the tooltip stops being news.
+ onClick={cancel}
+ >
+ {children}
+ {open &&
+ createPortal(
+ <div
+ ref={bubbleRef}
+ role="tooltip"
+ style={{
+ position: "fixed",
+ left: position?.left ?? 0,
+ top: position?.top ?? 0,
+ maxWidth: MAX_WIDTH,
+ visibility: position ? "visible" : "hidden",
+ }}
+ className={cn(
+ "pointer-events-none z-[70] rounded-lg border border-border/90 bg-card px-2.5 py-1.5",
+ "text-[11.5px] leading-snug text-foreground shadow-[0_10px_28px_-14px_rgba(0,0,0,0.85)]",
+ position && "animate-in fade-in-0 zoom-in-95 duration-100",
+ )}
+ >
+ {content}
+ </div>,
+ document.body,
+ )}
+ </span>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/lib/pcm-worklet.ts b/jarvis/ui/web/frontend/src/lib/pcm-worklet.ts
index 1388153f20..93be08933c 100644
--- a/jarvis/ui/web/frontend/src/lib/pcm-worklet.ts
+++ b/jarvis/ui/web/frontend/src/lib/pcm-worklet.ts
@@ -4,11 +4,7 @@
// to it (isolatedModules requires every file to be a module or a script; as a
// script these ambient declarations would otherwise leak into the rest of the
// app's type-check).
-import {
- BoundedPcm16Queue,
- Pcm16Packetizer,
- playbackBufferSampleCount,
-} from "./pcmWorkletBuffer";
+import { JitterBufferedPcm16Queue, Pcm16Packetizer } from "./pcmWorkletBuffer";
export {};
@@ -53,9 +49,7 @@ class PcmCapture extends AudioWorkletProcessor {
}
class PcmPlayback extends AudioWorkletProcessor {
- private readonly queue = new BoundedPcm16Queue(
- playbackBufferSampleCount(sampleRate),
- );
+ private readonly queue = new JitterBufferedPcm16Queue(sampleRate);
constructor() {
super();
@@ -74,7 +68,10 @@ class PcmPlayback extends AudioWorkletProcessor {
process(_inputs: Float32Array[][], outputs: Float32Array[][]): boolean {
const out = outputs[0]?.[0];
if (!out) return true;
- this.queue.dequeueInto(out);
+ // Banks a jitter reserve at a burst start and after an underrun, then
+ // streams at wall clock. Zero-filling a starved quantum instead is what
+ // chopped the voice on this surface.
+ this.queue.render(out);
return true;
}
}
diff --git a/jarvis/ui/web/frontend/src/lib/pcmPlaybackJitterBuffer.test.ts b/jarvis/ui/web/frontend/src/lib/pcmPlaybackJitterBuffer.test.ts
new file mode 100644
index 0000000000..a097e7e6f5
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/pcmPlaybackJitterBuffer.test.ts
@@ -0,0 +1,132 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ JitterBufferedPcm16Queue,
+ PLAYBACK_PREBUFFER_SECONDS,
+ PLAYBACK_PREBUFFER_TIMEOUT_SECONDS,
+ playbackPrebufferSampleCount,
+} from "./pcmWorkletBuffer";
+
+const RATE = 48_000;
+const QUANTUM = 128;
+
+/** One render quantum, as the AudioWorklet hands it to the processor. */
+function quantum(): Float32Array {
+ return new Float32Array(QUANTUM);
+}
+
+/** Constant-amplitude PCM16, so a rendered sample is trivially recognisable. */
+function tone(count: number, value = 0x4000): Int16Array {
+ return new Int16Array(count).fill(value);
+}
+
+function renderQuanta(
+ queue: JitterBufferedPcm16Queue,
+ count: number,
+): Float32Array[] {
+ const frames: Float32Array[] = [];
+ for (let i = 0; i < count; i++) {
+ const out = quantum();
+ queue.render(out);
+ frames.push(out);
+ }
+ return frames;
+}
+
+describe("playback jitter buffer", () => {
+ it("holds the opening burst silent until the reserve is banked", () => {
+ const queue = new JitterBufferedPcm16Queue(RATE);
+ const reserve = playbackPrebufferSampleCount(RATE);
+ expect(reserve).toBe(Math.round(RATE * PLAYBACK_PREBUFFER_SECONDS));
+
+ queue.enqueue(tone(reserve - QUANTUM));
+ const held = renderQuanta(queue, 3);
+ for (const frame of held) expect(frame.every((s) => s === 0)).toBe(true);
+ expect(queue.isPriming).toBe(true);
+ // Nothing was consumed while priming — the reserve is delayed, not dropped.
+ expect(queue.length).toBe(reserve - QUANTUM);
+
+ queue.enqueue(tone(QUANTUM));
+ const out = quantum();
+ expect(queue.render(out)).toBe(QUANTUM);
+ expect(queue.isPriming).toBe(false);
+ expect(out[QUANTUM - 1]).toBeGreaterThan(0);
+ });
+
+ it("starts a short reply anyway once the prebuffer timeout elapses", () => {
+ const queue = new JitterBufferedPcm16Queue(RATE);
+ // A whole burst far below the reserve: waiting for a reserve that will
+ // never arrive would swallow the reply entirely.
+ queue.enqueue(tone(QUANTUM * 2));
+ const timeoutQuanta = Math.ceil(
+ (RATE * PLAYBACK_PREBUFFER_TIMEOUT_SECONDS) / QUANTUM,
+ );
+
+ let rendered = 0;
+ for (let i = 0; i < timeoutQuanta + 2 && rendered === 0; i++) {
+ rendered = queue.render(quantum());
+ }
+ expect(rendered).toBeGreaterThan(0);
+ });
+
+ it("streams without added latency once playing", () => {
+ const queue = new JitterBufferedPcm16Queue(RATE);
+ queue.enqueue(tone(playbackPrebufferSampleCount(RATE) + QUANTUM * 4));
+ // Leave priming.
+ expect(queue.render(quantum())).toBe(QUANTUM);
+
+ const before = queue.length;
+ expect(queue.render(quantum())).toBe(QUANTUM);
+ expect(queue.length).toBe(before - QUANTUM);
+ expect(queue.isPriming).toBe(false);
+ });
+
+ it("re-banks the reserve after a true underrun instead of chopping on", () => {
+ const queue = new JitterBufferedPcm16Queue(RATE);
+ queue.enqueue(tone(playbackPrebufferSampleCount(RATE)));
+ while (queue.length >= QUANTUM) queue.render(quantum());
+
+ // The starved quantum: partial data, then the buffer returns to priming.
+ const starved = quantum();
+ const rendered = queue.render(starved);
+ expect(rendered).toBeLessThan(QUANTUM);
+ expect(queue.isPriming).toBe(true);
+
+ // A trickle that stays below the reserve must not be dribbled out.
+ queue.enqueue(tone(QUANTUM));
+ expect(queue.render(quantum())).toBe(0);
+ });
+
+ it("ramps both edges so a gap is not also a click", () => {
+ const queue = new JitterBufferedPcm16Queue(RATE);
+ const reserve = playbackPrebufferSampleCount(RATE);
+ queue.enqueue(tone(reserve));
+
+ const first = quantum();
+ queue.render(first);
+ // Resume edge: the ramp lifts the first samples out of silence.
+ expect(first[0]).toBeGreaterThan(0);
+ expect(first[0]).toBeLessThan(first[QUANTUM - 1]);
+
+ while (queue.length >= QUANTUM) queue.render(quantum());
+ const starved = quantum();
+ const rendered = queue.render(starved);
+ if (rendered > 0 && rendered < QUANTUM) {
+ // Underrun edge: the tail decays instead of stepping to zero.
+ expect(starved[rendered]).toBeGreaterThan(0);
+ expect(starved[rendered]).toBeLessThan(starved[rendered - 1]);
+ }
+ });
+
+ it("returns to priming on flush", () => {
+ const queue = new JitterBufferedPcm16Queue(RATE);
+ queue.enqueue(tone(playbackPrebufferSampleCount(RATE)));
+ expect(queue.render(quantum())).toBe(QUANTUM);
+
+ queue.clear();
+ expect(queue.length).toBe(0);
+ expect(queue.isPriming).toBe(true);
+ queue.enqueue(tone(QUANTUM));
+ expect(queue.render(quantum())).toBe(0);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/pcmWorkletBuffer.ts b/jarvis/ui/web/frontend/src/lib/pcmWorkletBuffer.ts
index c242abe639..8de1144f02 100644
--- a/jarvis/ui/web/frontend/src/lib/pcmWorkletBuffer.ts
+++ b/jarvis/ui/web/frontend/src/lib/pcmWorkletBuffer.ts
@@ -11,6 +11,30 @@ export const CAPTURE_PACKET_SECONDS = 0.02;
*/
export const MAX_PLAYBACK_BUFFER_SECONDS = 10;
+/**
+ * Jitter reserve banked before playback starts and after a true underrun.
+ *
+ * Provider PCM arrives over a WebSocket in bursts, is resampled on the main
+ * thread and is then read by the render thread once per 128-sample quantum
+ * (~2.7 ms at 48 kHz). Without a reserve, any scheduling or network gap shorter
+ * than one packet is rendered as digital silence mid-waveform — a hard
+ * discontinuity, audible as a chop plus a click. Mirrors the desktop surface's
+ * proven 180 ms reserve (`jarvis/realtime/desktop.py::DEFAULT_PREBUFFER_MS`).
+ */
+export const PLAYBACK_PREBUFFER_SECONDS = 0.15;
+
+/**
+ * Longest the reserve is allowed to hold audio back.
+ *
+ * A short reply ("yes.") can be the whole burst, so waiting for a full reserve
+ * that will never arrive would swallow it. Once audio has been queued for this
+ * long, playback starts under-filled rather than never.
+ */
+export const PLAYBACK_PREBUFFER_TIMEOUT_SECONDS = 0.24;
+
+/** Ramp length applied at a resume edge and at an underrun edge. */
+const PLAYBACK_DECLICK_SECONDS = 0.001;
+
function validatedSampleCount(sampleRate: number, seconds: number): number {
if (!Number.isFinite(sampleRate) || sampleRate <= 0) {
throw new RangeError("sampleRate must be a positive finite number");
@@ -31,6 +55,10 @@ export function playbackBufferSampleCount(sampleRate: number): number {
return validatedSampleCount(sampleRate, MAX_PLAYBACK_BUFFER_SECONDS);
}
+export function playbackPrebufferSampleCount(sampleRate: number): number {
+ return validatedSampleCount(sampleRate, PLAYBACK_PREBUFFER_SECONDS);
+}
+
function floatToPcm16(sample: number): number {
const clamped = Math.max(-1, Math.min(1, sample));
return clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff;
@@ -148,3 +176,108 @@ export class BoundedPcm16Queue {
return readCount;
}
}
+
+/**
+ * Playback ring with a jitter reserve — the browser surface's equivalent of
+ * `DesktopRealtimePlayback`'s prebuffer.
+ *
+ * The reserve is banked in exactly two places and nowhere else, so it never
+ * becomes permanently added latency: at the start of a burst, and after a true
+ * underrun (the render thread asked for more than the ring held). While
+ * playing, samples are handed out at wall clock with no delay whatsoever.
+ * Both edges are ramped, because jumping between a non-zero sample and silence
+ * is itself an audible click even when the gap is later filled.
+ */
+export class JitterBufferedPcm16Queue {
+ private readonly queue: BoundedPcm16Queue;
+ private readonly prebufferSamples: number;
+ private readonly prebufferTimeoutSamples: number;
+ private readonly declickSamples: number;
+ private priming = true;
+ private primingSamples = 0;
+ private resuming = false;
+
+ constructor(sampleRate: number) {
+ this.queue = new BoundedPcm16Queue(playbackBufferSampleCount(sampleRate));
+ this.prebufferSamples = playbackPrebufferSampleCount(sampleRate);
+ this.prebufferTimeoutSamples = validatedSampleCount(
+ sampleRate,
+ PLAYBACK_PREBUFFER_TIMEOUT_SECONDS,
+ );
+ this.declickSamples = validatedSampleCount(sampleRate, PLAYBACK_DECLICK_SECONDS);
+ }
+
+ /** Samples currently banked, whether or not playback has started. */
+ get length(): number {
+ return this.queue.length;
+ }
+
+ /** True while the reserve is still being banked. */
+ get isPriming(): boolean {
+ return this.priming;
+ }
+
+ clear(): void {
+ this.queue.clear();
+ this.priming = true;
+ this.primingSamples = 0;
+ this.resuming = false;
+ }
+
+ enqueue(input: Int16Array): number {
+ return this.queue.enqueue(input);
+ }
+
+ /** Fill one render quantum. Returns the number of real samples written. */
+ render(output: Float32Array): number {
+ if (this.priming) {
+ if (this.queue.length === 0) {
+ // Silence between turns must not burn the timeout: the clock starts
+ // when audio actually exists to be held back.
+ this.primingSamples = 0;
+ output.fill(0);
+ return 0;
+ }
+ if (
+ this.queue.length < this.prebufferSamples &&
+ this.primingSamples < this.prebufferTimeoutSamples
+ ) {
+ this.primingSamples += output.length;
+ output.fill(0);
+ return 0;
+ }
+ this.priming = false;
+ this.primingSamples = 0;
+ this.resuming = true;
+ }
+
+ const rendered = this.queue.dequeueInto(output);
+ if (this.resuming) {
+ this.resuming = false;
+ this.rampIn(output, rendered);
+ }
+ if (rendered < output.length) {
+ this.rampOut(output, rendered);
+ this.priming = true;
+ this.primingSamples = 0;
+ }
+ return rendered;
+ }
+
+ private rampIn(output: Float32Array, rendered: number): void {
+ const ramp = Math.min(rendered, this.declickSamples);
+ for (let i = 0; i < ramp; i++) output[i] *= (i + 1) / (ramp + 1);
+ }
+
+ private rampOut(output: Float32Array, rendered: number): void {
+ if (rendered === 0) return;
+ const last = output[rendered - 1];
+ if (last === 0) return;
+ // `dequeueInto` already zeroed the tail; overwrite the first slice of it
+ // with a ramp down from the last real sample.
+ const ramp = Math.min(output.length - rendered, this.declickSamples);
+ for (let i = 0; i < ramp; i++) {
+ output[rendered + i] = last * (1 - (i + 1) / (ramp + 1));
+ }
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.ts b/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.ts
index 359890dd14..ccf7dacdb9 100644
--- a/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.ts
+++ b/jarvis/ui/web/frontend/src/lib/realtimeTransportBroker.ts
@@ -3,6 +3,7 @@ import {
publishRealtimeTransportIssue,
type RealtimeTransportIssue,
} from "./realtimeTransportIssue";
+import { fetchRealtimeOfferRequirement } from "./voiceApi";
import { mintWsTicket } from "./ws";
declare global {
@@ -35,6 +36,7 @@ type BrokerDeps = {
createSocket: (url: string) => WebSocket;
mintTicket: () => Promise<string | null>;
readDesktopCapability: () => string;
+ readOfferRequirement: () => Promise<boolean | null>;
createOfferId: () => string;
schedule: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
cancelSchedule: (timer: ReturnType<typeof setTimeout>) => void;
@@ -59,6 +61,7 @@ const DEFAULT_DEPS: BrokerDeps = {
mintTicket: mintWsTicket,
readDesktopCapability: () =>
window.__JARVIS_REALTIME_BROKER_TOKEN?.trim() ?? "",
+ readOfferRequirement: fetchRealtimeOfferRequirement,
createOfferId: defaultOfferId,
schedule: (callback, delayMs) => globalThis.setTimeout(callback, delayMs),
cancelSchedule: (timer) => globalThis.clearTimeout(timer),
@@ -114,6 +117,31 @@ export class RealtimeTransportBroker {
this.reconnectTimer = null;
}
console.warn(`Realtime transport broker unavailable (${issue}): ${detail}`);
+ void this.publishFailure(issue);
+ }
+
+ /**
+ * Surface a terminal issue only when an offer is genuinely wanted.
+ *
+ * The broker is also mounted during the switch "prepare" window, before this
+ * client can know whether the transport it is switching TO needs a browser
+ * offer — and no built-in provider currently does. A failure published there
+ * accuses a capability nothing uses and sends the reader after the wrong bug.
+ * The backend capability decides (AP-21); an UNKNOWN answer still publishes,
+ * because a hidden real blocker is the worse outcome.
+ */
+ private async publishFailure(issue: RealtimeTransportIssue): Promise<void> {
+ const generation = this.generation;
+ const required = await this.deps.readOfferRequirement();
+ // Any restart or reconnect bumps the generation, so a failure that has
+ // already been superseded must not land on the status row.
+ if (generation !== this.generation) return;
+ if (required === false) {
+ console.info(
+ `Realtime transport broker issue withheld (${issue}): no configured provider needs a browser WebRTC offer.`,
+ );
+ return;
+ }
publishRealtimeTransportIssue(issue);
}
diff --git a/jarvis/ui/web/frontend/src/lib/realtimeTransportOfferGate.test.ts b/jarvis/ui/web/frontend/src/lib/realtimeTransportOfferGate.test.ts
new file mode 100644
index 0000000000..bb8e0f6e5e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/realtimeTransportOfferGate.test.ts
@@ -0,0 +1,83 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { RealtimeTransportBroker } from "./realtimeTransportBroker";
+import {
+ REALTIME_TRANSPORT_ISSUE_EVENT,
+ type RealtimeTransportIssueDetail,
+} from "./realtimeTransportIssue";
+
+type PublishedIssue = RealtimeTransportIssueDetail["issue"];
+
+/**
+ * Drives a broker to its terminal state and reports what it published.
+ *
+ * Refusing the desktop capability on every attempt is the cheapest path to
+ * `fail()`: six consecutive failures exhaust the retry budget.
+ */
+async function runUntilTerminal(
+ requirement: boolean | null,
+): Promise<{ issues: PublishedIssue[]; asked: number }> {
+ const issues: PublishedIssue[] = [];
+ vi.stubGlobal("window", {
+ location: { protocol: "https:", host: "app.example" },
+ dispatchEvent: (event: Event) => {
+ if (event.type === REALTIME_TRANSPORT_ISSUE_EVENT) {
+ issues.push((event as CustomEvent<RealtimeTransportIssueDetail>).detail.issue);
+ }
+ return true;
+ },
+ });
+
+ let asked = 0;
+ const pending: Array<() => void> = [];
+ const broker = new RealtimeTransportBroker({
+ mintTicket: vi.fn(async () => "ticket-1"),
+ readDesktopCapability: () => "",
+ readOfferRequirement: async () => {
+ asked += 1;
+ return requirement;
+ },
+ createSocket: () => {
+ throw new Error("the broker must never reach the socket in this test");
+ },
+ createTransport: () => {
+ throw new Error("the broker must never build a transport in this test");
+ },
+ schedule: (callback) => {
+ pending.push(callback);
+ return 1 as unknown as ReturnType<typeof setTimeout>;
+ },
+ cancelSchedule: () => undefined,
+ });
+
+ broker.start();
+ while (pending.length > 0) pending.shift()?.();
+ await vi.waitFor(() => expect(asked).toBe(1));
+ // Let `publishFailure` resume past its await before the assertions read the
+ // published list.
+ await Promise.resolve();
+ await Promise.resolve();
+ return { issues, asked };
+}
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe("realtime transport issue gate", () => {
+ it("withholds the accusation when no provider needs a browser offer", async () => {
+ const { issues, asked } = await runUntilTerminal(false);
+ expect(asked).toBe(1);
+ expect(issues).toEqual([]);
+ });
+
+ it("publishes the blocker when a provider does need the offer", async () => {
+ const { issues } = await runUntilTerminal(true);
+ expect(issues).toEqual(["capability_missing"]);
+ });
+
+ it("publishes when the capability cannot be read, rather than hiding it", async () => {
+ // `null` is "unknown", not "not required": a hidden real blocker is worse
+ // than a noisy one.
+ const { issues } = await runUntilTerminal(null);
+ expect(issues).toEqual(["capability_missing"]);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/voiceApi.ts b/jarvis/ui/web/frontend/src/lib/voiceApi.ts
index 363faa3c7a..2766494172 100644
--- a/jarvis/ui/web/frontend/src/lib/voiceApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/voiceApi.ts
@@ -36,6 +36,30 @@ export function requestVoiceHangup(): Promise<VoiceHangupAnswer> {
return post<VoiceHangupAnswer>("/api/voice/hangup");
}
+/**
+ * Whether the configured realtime transport needs a browser-supplied WebRTC
+ * offer at all (`requires_webrtc_offer` from GET /api/settings/voice-mode).
+ *
+ * A capability, never a provider id (AP-21). `null` means the backend could not
+ * be asked and is NOT the same as `false`: an unknown answer must keep every
+ * genuine failure visible, because hiding a real blocker is the worse failure.
+ */
+export async function fetchRealtimeOfferRequirement(): Promise<boolean | null> {
+ try {
+ const res = await fetch("/api/settings/voice-mode", { cache: "no-store" });
+ if (!res.ok) return null;
+ const body = (await res.json()) as { requires_webrtc_offer?: unknown };
+ return typeof body.requires_webrtc_offer === "boolean"
+ ? body.requires_webrtc_offer
+ : null;
+ } catch (error) {
+ // Deliberately degraded to "unknown" rather than swallowed: the caller
+ // treats null as "cannot rule the requirement out" and still reports.
+ console.info("Realtime offer requirement could not be read.", error);
+ return null;
+ }
+}
+
export interface TtsVolumeState {
volume: number;
}
diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.py
index 84e2bb1a06..4eb6dfffaa 100644
--- a/jarvis/ui/web/provider_spec.py
+++ b/jarvis/ui/web/provider_spec.py
@@ -105,6 +105,12 @@ class ProviderSpec:
# shows a clear badge and fallback note, while runtime selection remains
# capability-driven. This is presentation only and never gates behavior.
experimental: bool = False
+ # The provider/model class cannot be trusted to answer concrete public
+ # facts from unaided recall. The shared turn planner uses this capability
+ # to require one bounded search_web evidence attempt. Consumers branch on
+ # this field, never on a provider id; hosted evergreen turns keep the
+ # default False fast path.
+ requires_public_fact_grounding: bool = False
def provider_billing(spec: ProviderSpec) -> Billing:
@@ -540,6 +546,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
signup_url="https://ollama.com/download",
supports_base_url=True,
default_base_url="http://localhost:11434",
+ requires_public_fact_grounding=True,
credential_help=(
"Runs models fully local through an Ollama server — no API key, "
"no cloud account, nothing leaves this machine. Install Ollama, "
@@ -565,6 +572,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
"The API key is optional; most local servers ignore it."
),
supports_base_url=True,
+ requires_public_fact_grounding=True,
),
# ── TTS ───────────────────────────────────────────────────────────────
# Voice-Output cards render in this tuple order. OpenRouter leads (one key
@@ -815,6 +823,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
dashboard_url=None,
signup_url="https://platform.openai.com/docs/guides/realtime",
supports_base_url=True,
+ requires_public_fact_grounding=True,
credential_help=(
"Fully local voice calls, no cloud account. Easiest path: the "
"install panel below checks this machine (12 GB of GPU/unified "
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 124ca55067..e7ad6476a7 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -88,6 +88,18 @@ _WS_LEVEL_SEND_TIMEOUT_S = 0.25
# inside the window cancels the wait rather than delaying it.
ULTRAWIKI_PIPELINE_GRACE_S = 20.0
+# How long the realtime transport warm is held back after boot. Warming can
+# spawn a provider's app-server and verify a live account, so it must not
+# compete with the wake-model load and the brain/MCP build for CPU and disk
+# (AP-26). A few seconds still lands it long before a realistic first wake
+# word, which is the entire point of warming.
+REALTIME_WARM_BOOT_DELAY_S = 5.0
+
+# Shared with the desktop shell's warm worker (``jarvis/ui/desktop_app.py``).
+# Both surfaces schedule onto ONE event loop in a desktop boot, so the task
+# name is what keeps that boot from warming the same transports twice.
+REALTIME_WARM_TASK_NAME = "realtime-transport-warm"
+
class WebServer:
"""In-process uvicorn + FastAPI, run by the orchestrator loop."""
@@ -127,6 +139,10 @@ class WebServer:
self._refresh_scheduler_start_handle: asyncio.Handle | None = None
self._refresh_registry_tasks: set[asyncio.Task[Any]] = set()
self._refresh_scheduler_stopping = False
+ # Realtime transport pre-warm — scheduled at the end of start() so the
+ # headless/browser-only boot path gets the same warm the desktop shell
+ # runs. Cancelled in stop().
+ self._realtime_warm_task: asyncio.Task[None] | None = None
# Board stack is populated in _setup_board() (in the _build_app path).
self._board_aggregator: Any | None = None
self._board_aggregator_task: asyncio.Task[None] | None = None
@@ -2129,6 +2145,65 @@ class WebServer:
"will be renewed in the background."
)
+ def _schedule_realtime_transport_warm(self) -> None:
+ """Pre-open the selected realtime transports off the boot path.
+
+ ``run.bat --headless`` and every browser-only install boot through this
+ server and never through the desktop shell, so without this hook they
+ paid the realtime provider's whole cold start inside the user's first
+ call — for a subscription transport a spawned app-server plus a live
+ account check. Every OS reaches it the same way; nothing here is
+ desktop- or Windows-specific.
+
+ Exactly-once by construction: the desktop shell starts its own warm
+ worker under :data:`REALTIME_WARM_TASK_NAME` before it awaits
+ :meth:`start`, and both run on the same loop, so an already-live task
+ of that name means this boot is already covered. Whether warming is
+ appropriate at all stays the factory's decision — it skips itself when
+ realtime is not the configured voice mode and warms only explicitly
+ selected providers.
+ """
+ existing = self._realtime_warm_task
+ if existing is not None and not existing.done():
+ return
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ # No loop (a synchronous start in a test harness): nothing to warm
+ # onto, and boot must not care.
+ logger.debug("Realtime transport warm not scheduled — no running event loop.")
+ return
+ for task in asyncio.all_tasks(loop):
+ if task.get_name() == REALTIME_WARM_TASK_NAME and not task.done():
+ logger.debug(
+ "Realtime transport warm already running on this loop — "
+ "not scheduling a second one."
+ )
+ return
+ self._realtime_warm_task = loop.create_task(
+ self._warm_realtime_transports(), name=REALTIME_WARM_TASK_NAME
+ )
+
+ async def _warm_realtime_transports(self) -> None:
+ """Warm the explicitly selected realtime transports once, after boot.
+
+ Advisory by contract and never silent (AP-30): a failure here changes
+ nothing except that the first call pays the cold start it pays today,
+ and it says so at warning level.
+ """
+ try:
+ await asyncio.sleep(REALTIME_WARM_BOOT_DELAY_S)
+ from jarvis.realtime.factory import realtime_warm_selected_transports
+
+ await realtime_warm_selected_transports(self.cfg)
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001 -- warming is advisory, never fatal
+ logger.opt(exception=exc).warning(
+ "Realtime transport warm failed — the first realtime call will "
+ "pay the provider's cold start."
+ )
+
async def _stop_marketplace_refresh_scheduler(self) -> None:
"""Cancel a pending start and stop the live refresh task, if any."""
self._refresh_scheduler_stopping = True
@@ -2493,6 +2568,10 @@ class WebServer:
# catalog/keyring reads or refresh network calls can begin. This shared
# hook covers normal desktop, headless, and direct WebServer starts.
self._schedule_marketplace_refresh_scheduler()
+ # Same reasoning, and the same three boot paths: a headless or
+ # browser-only install has no desktop shell to warm the realtime
+ # transport for it.
+ self._schedule_realtime_transport_warm()
async def _init_screenshot_retention(self) -> None:
"""Auto-delete captured screenshot blobs older than the configured
@@ -3335,6 +3414,18 @@ class WebServer:
except Exception as exc: # noqa: BLE001
logger.opt(exception=exc).debug("voice-ready watchdog shutdown: {}", exc)
self._voice_ready_watchdog_task = None
+ # Realtime transport warm: usually finished long before a shutdown, but
+ # a stop inside its boot delay must not orphan it at loop close.
+ _warm_task = self._realtime_warm_task
+ self._realtime_warm_task = None
+ if _warm_task is not None and not _warm_task.done():
+ _warm_task.cancel()
+ try:
+ await asyncio.wait_for(_warm_task, timeout=2.0)
+ except (TimeoutError, asyncio.CancelledError):
+ pass
+ except Exception as exc: # noqa: BLE001 -- shutdown stays best-effort
+ logger.opt(exception=exc).debug("Realtime transport warm shutdown: {}", exc)
if self._bio_scheduler is not None:
try:
await self._bio_scheduler.stop()
diff --git a/scripts/config-soll.json b/scripts/config-soll.json
index e884d63231..59e920ab03 100644
--- a/scripts/config-soll.json
+++ b/scripts/config-soll.json
@@ -33,7 +33,7 @@
"allow_sapi5_fallback": false
},
"brain": {
- "primary": "openai",
+ "primary": "openrouter",
"fallback": "openrouter",
"deep_brain": "claude-cli",
"routing_provider": "grok",
@@ -113,7 +113,7 @@
"provider": "grok"
},
"brain.computer_use": {
- "provider": "grok"
+ "provider": "ollama"
},
"brain.providers.grok-realtime": {
"voice": "lux"
diff --git a/skillbook/CLAUDE.md b/skillbook/CLAUDE.md
index 98623be5e1..c6a43f8e95 100644
--- a/skillbook/CLAUDE.md
+++ b/skillbook/CLAUDE.md
@@ -73,41 +73,6 @@ Concrete data models live in `skillbook.{module}.models` modules (pydantic v2).
| Guardrails taxonomy | Enum-driven AgentDoG (Source/FailureMode/Consequence) | ADR-0008 |
| Survey deviations | See ADR-0009 | ADR-0009 |
-## Repo Layout
-
-```
-skillbook/
-├── CLAUDE.md ← this file (binding)
-├── CHANGELOG.md ← per-commit log
-├── pyproject.toml ← uv-managed deps + pytest config
-├── conftest.py ← --seeds option, src on path, shared fixtures
-├── README.md ← short orientation
-├── docs/
-│ └── adr/ ← architecture decision records
-│ ├── 0001-repo-layout-and-toolchain.md
-│ ├── 0002-sqlite-storage.md
-│ ├── 0003-embeddings-strategy.md
-│ ├── 0004-llm-provider-strategy.md
-│ ├── 0005-mqtt-stack.md
-│ ├── 0006-p2p-transport.md
-│ ├── 0007-reflector-sandbox.md
-│ ├── 0008-guardrails-taxonomy.md
-│ └── 0009-survey-deviations.md
-├── src/
-│ └── skillbook/
-│ ├── __init__.py
-│ ├── ace_core/ ← Generator, RecursiveReflector, Curator
-│ ├── symcon_bridge/ ← async MQTT + JSON-RPC client
-│ ├── memory_layer/ ← temporal facts + KG + skillbook persistence
-│ ├── guardrails/ ← AgentDoG + LATS
-│ └── p2p_sync/ ← CRDT OR-Set + Merkle-tree gossip
-├── tests/
-│ ├── unit/ ← module-level unit tests
-│ ├── integration/ ← cross-module
-│ └── test_capstone.py ← end-to-end ACE loop oracle
-└── data/ ← per-instance SQLite files (gitignored)
-```
-
## Test Pyramid
- **Unit tests** (`tests/unit/{module}/`): one behavior per file, mock at module boundary.
diff --git a/tests/unit/brain/test_turn_planner.py b/tests/unit/brain/test_turn_planner.py
index 9a944f6214..f121f64c09 100644
--- a/tests/unit/brain/test_turn_planner.py
+++ b/tests/unit/brain/test_turn_planner.py
@@ -4,7 +4,14 @@ from __future__ import annotations
import pytest
-from jarvis.brain.turn_planner import TurnPath, TurnReason, plan_turn
+from jarvis.brain.turn_planner import (
+ PUBLIC_FACT_GROUNDING_CAPABILITY,
+ PUBLIC_FACT_GROUNDING_TIMEOUT_S,
+ GroundingFailurePolicy,
+ TurnPath,
+ TurnReason,
+ plan_turn,
+)
from jarvis.core.capabilities import Capability, CapabilityRegistry
@@ -137,7 +144,76 @@ def test_temporal_filler_world_knowledge_stays_native(utterance: str) -> None:
],
)
def test_strong_current_markers_still_use_orchestrator(utterance: str) -> None:
- assert plan_turn(utterance).path is TurnPath.ORCHESTRATOR
+ plan = plan_turn(utterance)
+
+ assert plan.path is TurnPath.ORCHESTRATOR
+ assert plan.requires_public_fact_grounding is True
+ assert plan.required_capabilities.count(PUBLIC_FACT_GROUNDING_CAPABILITY) == 1
+ assert plan.public_fact_grounding_timeout_s == PUBLIC_FACT_GROUNDING_TIMEOUT_S
+ assert plan.public_fact_grounding_attempt_limit == 1
+ assert plan.grounding_failure_policy is GroundingFailurePolicy.HONEST_UNCERTAINTY
+
+
+ "utterance",
+ [
+ "How long did Muhammad Ali live?",
+ "Wer ist der Praesident des WBC?", # i18n-allow: German speech fixture
+ "Quien fundo la NASA?", # i18n-allow: Spanish speech fixture
+ ],
+)
+def test_declared_small_model_public_facts_ground_once(utterance: str) -> None:
+ plan = plan_turn(
+ utterance,
+ tool_names=(PUBLIC_FACT_GROUNDING_CAPABILITY,),
+ requires_public_fact_grounding=True,
+ )
+
+ assert plan.path is TurnPath.ORCHESTRATOR
+ assert TurnReason.PUBLIC_FACT in plan.reasons
+ assert plan.required_capabilities.count(PUBLIC_FACT_GROUNDING_CAPABILITY) == 1
+ assert plan.requires_evidence is True
+ assert plan.requires_public_fact_grounding is True
+ assert plan.public_fact_grounding_attempt_limit == 1
+
+
+def test_hosted_evergreen_public_fact_keeps_native_fast_path() -> None:
+ plan = plan_turn("Who wrote Hamlet?")
+
+ assert plan.path is TurnPath.NATIVE_REALTIME
+ assert plan.requires_public_fact_grounding is False
+ assert plan.required_capabilities == ()
+ assert plan.public_fact_grounding_timeout_s is None
+ assert plan.public_fact_grounding_attempt_limit == 0
+ assert plan.grounding_failure_policy is None
+
+
+def test_public_search_capability_is_deduplicated() -> None:
+ plan = plan_turn(
+ "Search for the latest Python release.",
+ tool_names=(PUBLIC_FACT_GROUNDING_CAPABILITY,),
+ requires_public_fact_grounding=True,
+ )
+
+ assert plan.required_capabilities.count(PUBLIC_FACT_GROUNDING_CAPABILITY) == 1
+ assert plan.public_fact_grounding_attempt_limit == 1
+
+
+ "utterance",
+ [
+ "What is in my Gmail inbox?",
+ "Which meetings are in my calendar today?",
+ "What is on my screen?",
+ ],
+)
+def test_private_or_connected_facts_never_leak_to_public_search(
+ utterance: str,
+) -> None:
+ plan = plan_turn(utterance, requires_public_fact_grounding=True)
+
+ assert plan.requires_public_fact_grounding is False
+ assert PUBLIC_FACT_GROUNDING_CAPABILITY not in plan.required_capabilities
def test_read_only_dynamic_connector_matches_live_capability(
diff --git a/tests/unit/codex_app_server/test_transport.py b/tests/unit/codex_app_server/test_transport.py
index dea1080b12..0624543e35 100644
--- a/tests/unit/codex_app_server/test_transport.py
+++ b/tests/unit/codex_app_server/test_transport.py
@@ -1381,7 +1381,7 @@ def _ready_capability(binary_path: str = "codex-test") -> CodexAppServerCapabili
available=True,
chatgpt_authenticated=True,
binary_path=binary_path,
- version="codex-cli 0.146.0",
+ version="codex-cli 0.147.0",
reason="ready",
reason_code="ready",
)
@@ -1664,6 +1664,16 @@ def test_reaper_launch_failure_releases_guard_and_state(
"_read_codex_capability",
lambda _binary: _ready_capability(binary_path="codex-test"),
)
+ monkeypatch.setattr(
+ transport,
+ "_trusted_codex_targets_for_platform",
+ lambda: (
+ (
+ "codex-cli 0.147.0",
+ ("test", "test", "codex-test", "trusted-test-digest"),
+ ),
+ ),
+ )
monkeypatch.setattr(
transport,
"_subscription_process_lock_path",
@@ -3472,7 +3482,7 @@ def test_subscription_login_guard_covers_process_and_reaper(
available=True,
chatgpt_authenticated=authenticated,
binary_path="codex-test",
- version="codex-cli 0.146.0",
+ version="codex-cli 0.147.0",
reason="ready",
reason_code="ready" if authenticated else "login_required",
)
@@ -3482,6 +3492,16 @@ def test_subscription_login_guard_covers_process_and_reaper(
"_read_codex_capability",
read_capability,
)
+ monkeypatch.setattr(
+ transport,
+ "_trusted_codex_targets_for_platform",
+ lambda: (
+ (
+ "codex-cli 0.147.0",
+ ("test", "test", "codex-test", "trusted-test-digest"),
+ ),
+ ),
+ )
monkeypatch.setattr(
transport,
"_validated_subscription_home",
@@ -3534,10 +3554,20 @@ def test_subscription_login_spawn_failure_releases_guard(
True,
False,
"codex-test",
- "codex-cli 0.146.0",
+ "codex-cli 0.147.0",
"ready",
),
)
+ monkeypatch.setattr(
+ transport,
+ "_trusted_codex_targets_for_platform",
+ lambda: (
+ (
+ "codex-cli 0.147.0",
+ ("test", "test", "codex-test", "trusted-test-digest"),
+ ),
+ ),
+ )
monkeypatch.setattr(transport, "_subscription_login_in_flight", False)
monkeypatch.setattr(transport, "_subscription_login_process", None)
monkeypatch.setattr(transport, "_subscription_profile_mutating", False)
diff --git a/tests/unit/core/test_turn_language.py b/tests/unit/core/test_turn_language.py
index bfad7c723e..f53841c8fe 100644
--- a/tests/unit/core/test_turn_language.py
+++ b/tests/unit/core/test_turn_language.py
@@ -24,6 +24,7 @@ from jarvis.core.turn_language import (
resolve_output_language,
resolve_transcript_language,
resolve_turn_language,
+ validate_output_language,
)
# ---------------------------------------------------------------------------
@@ -266,3 +267,134 @@ def test_no_tag_at_all_is_answered_from_the_text() -> None:
def test_no_text_at_all_falls_back_to_the_tag() -> None:
assert resolve_transcript_language("German", "") == "de"
assert resolve_transcript_language("", "") == "unknown"
+
+
+# ---------------------------------------------------------------------------
+# Deterministic output-language validation. The caller passes the result of
+# resolve_output_language; the validator never chooses a target language.
+# ---------------------------------------------------------------------------
+
+
+ ("resolved_language", "text", "detected_language"),
+ [
+ (
+ "de",
+ "Das Wetter ist heute gut und wir sind bereit.", # i18n-allow: German output fixture
+ "de",
+ ),
+ ("en", "The weather is good today and we are ready.", "en"),
+ ("es", "El tiempo está muy bien hoy y quiero saber más.", "es"),
+ ("es", "Hoy hay información útil para mí, y está muy bien así.", "es"),
+ ],
+)
+def test_output_language_validator_accepts_supported_languages(
+ resolved_language: str,
+ text: str,
+ detected_language: str,
+) -> None:
+ result = validate_output_language(text, resolved_language=resolved_language)
+
+ assert result.status == "match"
+ assert result.detected_language == detected_language
+ assert result.should_block is False
+
+
+ ("resolved_language", "text", "detected_language"),
+ [
+ ("de", "Xin chào, tôi có thể giúp bạn bằng tiếng Việt.", "vi"),
+ ("en", "这是一个完全错误的中文回答,需要立即阻止。", "zh"),
+ ("es", "The answer is in the wrong language and should not be spoken.", "en"),
+ ],
+)
+def test_output_language_validator_blocks_high_confidence_mismatches(
+ resolved_language: str,
+ text: str,
+ detected_language: str,
+) -> None:
+ result = validate_output_language(text, resolved_language=resolved_language)
+
+ assert result.status == "mismatch"
+ assert result.detected_language == detected_language
+ assert result.should_block is True
+
+
+ "text",
+ [
+ "",
+ "Okay.",
+ "Danke.", # i18n-allow: short German output fixture
+ "HTTP 500, CPU 95%, API v2.1.",
+ "OpenAI GitHub Spotify HTTP Berlin",
+ "```python\nfor item in items:\n return item\n```",
+ "Use `response.status_code == 500`.",
+ ],
+)
+def test_output_language_validator_keeps_ambiguous_content_non_blocking(
+ text: str,
+) -> None:
+ result = validate_output_language(text, resolved_language="de")
+
+ assert result.status == "indeterminate"
+ assert result.should_block is False
+
+
+def test_output_language_validator_does_not_reject_a_chinese_name() -> None:
+ result = validate_output_language(
+ "The Beijing office uses 北京 for its local label.",
+ resolved_language="en",
+ )
+
+ assert result.should_block is False
+ assert result.detected_language != "zh"
+
+
+def test_output_language_validator_does_not_reject_a_vietnamese_name() -> None:
+ result = validate_output_language(
+ "The meeting with Nguyễn Văn Bình is today.",
+ resolved_language="en",
+ )
+
+ assert result.status == "match"
+ assert result.detected_language == "en"
+ assert result.should_block is False
+
+
+def test_output_language_validator_does_not_misread_repeated_the_as_vietnamese() -> None:
+ text = "The answer is the same as the question, and the result is clear."
+
+ result = validate_output_language(text, resolved_language="en")
+
+ assert result.status == "match"
+ assert result.detected_language == "en"
+ assert result.should_block is False
+
+
+ "text",
+ [
+ "the the the the the",
+ "ban ban ban ban ban",
+ "bạn bạn bạn bạn bạn",
+ ],
+)
+def test_output_language_validator_does_not_count_repeated_tokens_as_vietnamese(
+ text: str,
+) -> None:
+ result = validate_output_language(text, resolved_language="en")
+
+ assert result.detected_language != "vi"
+ assert result.should_block is False
+
+
+def test_output_language_validator_keeps_unknown_target_non_blocking() -> None:
+ result = validate_output_language(
+ "这是一个很长的中文回答,应当保持安全。",
+ resolved_language="fr",
+ )
+
+ assert result.status == "indeterminate"
+ assert result.resolved_language == "unknown"
+ assert result.should_block is False
diff --git a/tests/unit/diagnostics/test_realtime_forensics_first_final_budget.py b/tests/unit/diagnostics/test_realtime_forensics_first_final_budget.py
new file mode 100644
index 0000000000..4453275fbf
--- /dev/null
+++ b/tests/unit/diagnostics/test_realtime_forensics_first_final_budget.py
@@ -0,0 +1,80 @@
+"""The first-audio budget judges the USER-perceived wait, not session age.
+
+``first_audio_ms`` counts from session start and therefore includes the
+user's own speaking/listening time: a live codex call measured 8 311 ms from
+start while the wait after the user's final was 923 ms, and the old
+assertion flagged that healthy call as a budget breach. The budget now
+judges ``first_final_to_first_audio_ms`` (first user FINAL → first audible
+provider frame); ``first_audio_ms`` stays in the payload and the detail
+line for continuity with old recordings but is never asserted against the
+budget anymore.
+"""
+
+from __future__ import annotations
+
+from jarvis.diagnostics.realtime_forensics import (
+ SPAWN_FIRST_AUDIO_BUDGET_MS,
+ SPAWN_READY_BUDGET_MS,
+ evaluate_postmortem,
+)
+
+
+def _healthy() -> dict[str, object]:
+ return {
+ "session_id": "first-final-budget",
+ "provider": "codex-subscription-realtime",
+ "turns_completed": 2,
+ "ready_ms": 2400,
+ "first_audio_ms": 4100,
+ "close_clean": True,
+ }
+
+
+def _kinds(pm: dict[str, object]) -> set[str]:
+ return {finding.kind for finding in evaluate_postmortem(pm)}
+
+
+def test_response_latency_over_budget_is_the_spawn_finding() -> None:
+ over = _healthy() | {
+ "first_final_to_first_audio_ms": SPAWN_FIRST_AUDIO_BUDGET_MS + 1
+ }
+ findings = evaluate_postmortem(over)
+ assert [(f.severity, f.kind) for f in findings] == [
+ ("warn", "spawn-over-budget")
+ ]
+
+
+def test_the_codex_8311ms_case_no_longer_reads_as_a_breach() -> None:
+ # The measured live shape: first audio 8.3 s from session start, but only
+ # 923 ms after the user's final — a healthy call, not a slow spawn.
+ healthy_codex = _healthy() | {
+ "first_audio_ms": 8_311,
+ "first_final_to_first_audio_ms": 923,
+ }
+ assert _kinds(healthy_codex) == set()
+
+
+def test_legacy_first_audio_alone_never_breaches_the_budget() -> None:
+ # An old recording without the new metric must not fabricate a breach
+ # from the misleading session-start measurement.
+ legacy = _healthy() | {"first_audio_ms": SPAWN_FIRST_AUDIO_BUDGET_MS + 1}
+ assert _kinds(legacy) == set()
+
+
+def test_zero_means_never_measured_and_stays_quiet() -> None:
+ assert _kinds(_healthy() | {"first_final_to_first_audio_ms": 0}) == set()
+
+
+def test_ready_budget_is_untouched() -> None:
+ slow_ready = _healthy() | {"ready_ms": SPAWN_READY_BUDGET_MS + 1}
+ assert _kinds(slow_ready) == {"spawn-over-budget"}
+
+
+def test_detail_line_carries_both_measurements_for_continuity() -> None:
+ over = _healthy() | {
+ "first_audio_ms": 8_311,
+ "first_final_to_first_audio_ms": SPAWN_FIRST_AUDIO_BUDGET_MS + 500,
+ }
+ (finding,) = evaluate_postmortem(over)
+ assert "after the first user final" in finding.detail
+ assert "8311 ms from session start" in finding.detail
diff --git a/tests/unit/realtime/test_codex_subscription.py b/tests/unit/realtime/test_codex_subscription.py
index ac9ca452fa..576ca76e1d 100644
--- a/tests/unit/realtime/test_codex_subscription.py
+++ b/tests/unit/realtime/test_codex_subscription.py
@@ -859,7 +859,11 @@ async def test_media_track_forwards_provider_silence_verbatim() -> None:
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)
+ # The last chunk must land WELL inside the quiescence window: Windows
+ # timer granularity (~15.6 ms) makes two sequential sleeps overshoot a
+ # same-length single sleep, so a schedule that races the deadline exactly
+ # loses deterministically there while passing elsewhere.
+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 0.25)
client = _Client()
client.subscription = _ScheduledSubscription(
[
@@ -872,12 +876,12 @@ async def test_default_done_waits_for_all_late_audio_before_one_completion(
),
# Keeps the notification stream open while the late media audio
# arrives, as a live transport does.
- (0.2, _Notification("thread/realtime/keepalive", {"threadId": "thread-1"})),
+ (0.6, _Notification("thread/realtime/keepalive", {"threadId": "thread-1"})),
]
)
- # Late RTP audio must keep re-arming the quiescence timer so one turn ends
- # exactly once, after the last audible chunk.
- endpoint = _FakeAudioEndpoint(output_schedule=((0.015, b"\x01\x00"), (0.015, b"\x01\x00")))
+ # Late RTP audio must arrive inside the quiescence window so one turn ends
+ # exactly once, after the last chunk.
+ endpoint = _FakeAudioEndpoint(output_schedule=((0.05, b"\x01\x00"), (0.05, b"\x01\x00")))
session = await _provider(client, endpoint=endpoint).open_session(RealtimeSessionConfig())
events = [event async for event in session.receive()]
@@ -1292,9 +1296,7 @@ async def test_offer_thread_and_transcriber_warm_overlap() -> None:
input_transcriber_factory=_GatedTranscriber,
)
- session = await asyncio.wait_for(
- provider.open_session(RealtimeSessionConfig()), timeout=1.0
- )
+ session = await asyncio.wait_for(provider.open_session(RealtimeSessionConfig()), timeout=1.0)
assert offer_started.is_set()
assert warm_started.is_set()
@@ -1435,9 +1437,7 @@ class _RecoveringEndpointer(_StubEndpointer):
# Under the no-unsolicited-opening policy an answer only plays
# once a user final exists.
self._events.put_nowait(
- InputTranscriptEvent(
- kind="transcript", text="Hi.", is_final=True
- )
+ InputTranscriptEvent(kind="transcript", text="Hi.", is_final=True)
)
async def next_event(self): # noqa: ANN202 - test protocol
@@ -1713,9 +1713,7 @@ async def test_ungrounded_server_turn_aborts_an_open_response_without_a_boundary
events = [event async for event in session.receive()]
- assert [event.text for event in events if event.type == "output_transcript_delta"] == [
- "Hi."
- ]
+ assert [event.text for event in events if event.type == "output_transcript_delta"] == ["Hi."]
assert [event.type for event in events].count("turn_complete") == 1
errors = [event for event in events if event.type == "error"]
assert len(errors) == 1
@@ -2200,15 +2198,15 @@ async def test_a_refused_response_does_not_deafen_the_next_real_turn() -> None:
),
]
)
- session = await _provider(
- client, input_transcriber_factory=lambda: transcriber
- ).open_session(RealtimeSessionConfig())
+ session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
+ RealtimeSessionConfig()
+ )
events = [event async for event in session.receive()]
- assert [
- event.text for event in events if event.type == "output_transcript_delta"
- ] == ["The real answer."]
+ assert [event.text for event in events if event.type == "output_transcript_delta"] == [
+ "The real answer."
+ ]
await session.close()
@@ -2268,9 +2266,7 @@ async def test_a_pause_inside_one_reply_does_not_cut_off_its_remainder(
# Grounded call: the first answer needs a user final now.
(
0.0,
- InputTranscriptEvent(
- kind="transcript", text="Hello there.", is_final=True
- ),
+ InputTranscriptEvent(kind="transcript", text="Hello there.", is_final=True),
),
]
)
@@ -2282,9 +2278,7 @@ async def test_a_pause_inside_one_reply_does_not_cut_off_its_remainder(
input_transcriber_factory=lambda: transcriber,
).open_session(RealtimeSessionConfig())
- events = await _collect_until(
- session, stop_after=2, kind="audio_delta", timeout_s=1.5
- )
+ events = await _collect_until(session, stop_after=2, kind="audio_delta", timeout_s=1.5)
assert [event.type for event in events].count("audio_delta") == 2
# The backstop still delivered its boundary between the two halves.
@@ -2305,9 +2299,7 @@ async def test_a_completed_turn_still_refuses_the_next_ungrounded_response() ->
[
InputTranscriptEvent(kind="speech_started"),
# Grounded call: the first answer needs a user final now.
- InputTranscriptEvent(
- kind="transcript", text="Hello there.", is_final=True
- ),
+ InputTranscriptEvent(kind="transcript", text="Hello there.", is_final=True),
]
)
client = _Client(
@@ -2330,15 +2322,15 @@ async def test_a_completed_turn_still_refuses_the_next_ungrounded_response() ->
),
]
)
- session = await _provider(
- client, input_transcriber_factory=lambda: transcriber
- ).open_session(RealtimeSessionConfig())
+ session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
+ RealtimeSessionConfig()
+ )
events = [event async for event in session.receive()]
- assert [
- event.text for event in events if event.type == "output_transcript_delta"
- ] == ["Answer one."]
+ assert [event.text for event in events if event.type == "output_transcript_delta"] == [
+ "Answer one."
+ ]
assert [event.type for event in events].count("turn_complete") == 1
await session.close()
@@ -2356,9 +2348,7 @@ async def test_an_invented_user_caption_retires_the_entitlement() -> None:
[
InputTranscriptEvent(kind="speech_started"),
# Grounded call: the first answer needs a user final now.
- InputTranscriptEvent(
- kind="transcript", text="Hello there.", is_final=True
- ),
+ InputTranscriptEvent(kind="transcript", text="Hello there.", is_final=True),
]
)
transcriber._speaking = False # the microphone is quiet from here on
@@ -2382,15 +2372,15 @@ async def test_an_invented_user_caption_retires_the_entitlement() -> None:
),
]
)
- session = await _provider(
- client, input_transcriber_factory=lambda: transcriber
- ).open_session(RealtimeSessionConfig())
+ session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
+ RealtimeSessionConfig()
+ )
events = [event async for event in session.receive()]
- assert [
- event.text for event in events if event.type == "output_transcript_delta"
- ] == ["Answer one."]
+ assert [event.text for event in events if event.type == "output_transcript_delta"] == [
+ "Answer one."
+ ]
await session.close()
@@ -2407,18 +2397,14 @@ async def test_interrupt_drops_the_remainder_without_any_codex_turn_id(
"""
monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_QUIESCENCE_S", 5.0)
speech = (1000).to_bytes(2, "little", signed=True) * 480
- endpoint = _FakeAudioEndpoint(
- output_schedule=((0.02, speech), (0.15, speech), (0.05, speech))
- )
+ endpoint = _FakeAudioEndpoint(output_schedule=((0.02, speech), (0.15, speech), (0.05, speech)))
transcriber = _ScheduledInputTranscriber(
[
(0.0, InputTranscriptEvent(kind="speech_started")),
# Grounded call: the first answer needs a user final now.
(
0.0,
- InputTranscriptEvent(
- kind="transcript", text="Hello there.", is_final=True
- ),
+ InputTranscriptEvent(kind="transcript", text="Hello there.", is_final=True),
),
]
)
@@ -2463,12 +2449,8 @@ async def test_late_provider_transcript_is_shadow_recovered_for_the_gate(
hold). The local recognizer recovers vetting text early; the shadow flag
keeps it out of the user-visible transcript.
"""
- monkeypatch.setattr(
- codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_AFTER_S", 0.05
- )
- monkeypatch.setattr(
- codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_RETRY_S", 0.01
- )
+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_AFTER_S", 0.05)
+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_RETRY_S", 0.01)
speech = (1000).to_bytes(2, "little", signed=True) * 480
endpoint = _FakeAudioEndpoint(
output_schedule=(
@@ -2497,9 +2479,7 @@ async def test_late_provider_transcript_is_shadow_recovered_for_the_gate(
with contextlib.suppress(TimeoutError):
async with asyncio.timeout(1.5):
async for event in session.receive():
- if event.type == "output_transcript_delta" and getattr(
- event, "shadow", False
- ):
+ if event.type == "output_transcript_delta" and getattr(event, "shadow", False):
shadow = event
break
@@ -2519,12 +2499,8 @@ async def test_slow_shadow_recovery_never_stalls_the_receive_pump(
recognizer's own time bound — audio stalled and the user's speech edge
arrived seconds late. The recovery now runs as a background task.
"""
- monkeypatch.setattr(
- codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_AFTER_S", 0.05
- )
- monkeypatch.setattr(
- codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_RETRY_S", 0.01
- )
+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_AFTER_S", 0.05)
+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_RETRY_S", 0.01)
class _SlowRecoveringEndpointer(_RecoveringEndpointer):
async def transcribe_audio(self, pcm: bytes, *, sample_rate: int) -> str:
@@ -2532,9 +2508,7 @@ async def test_slow_shadow_recovery_never_stalls_the_receive_pump(
return await super().transcribe_audio(pcm, sample_rate=sample_rate)
speech = (1000).to_bytes(2, "little", signed=True) * 480
- endpoint = _FakeAudioEndpoint(
- output_schedule=tuple((0.04, speech) for _ in range(14))
- )
+ endpoint = _FakeAudioEndpoint(output_schedule=tuple((0.04, speech) for _ in range(14)))
transcriber = _SlowRecoveringEndpointer("Here is the answer.")
transcriber._events.put_nowait(
InputTranscriptEvent(kind="transcript", text="Hi", is_final=True)
@@ -2554,9 +2528,7 @@ async def test_slow_shadow_recovery_never_stalls_the_receive_pump(
async for event in session.receive():
if event.type == "audio_delta" and not shadow_seen:
audio_before_shadow += 1
- if event.type == "output_transcript_delta" and getattr(
- event, "shadow", False
- ):
+ if event.type == "output_transcript_delta" and getattr(event, "shadow", False):
shadow_seen = True
break
@@ -2573,16 +2545,10 @@ async def test_shadow_recovery_yields_to_an_open_user_utterance(
monkeypatch,
) -> None:
"""The microphone owns the shared recognizer mid-utterance (review R2)."""
- monkeypatch.setattr(
- codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_AFTER_S", 0.05
- )
- monkeypatch.setattr(
- codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_RETRY_S", 0.01
- )
+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_AFTER_S", 0.05)
+ monkeypatch.setattr(codex_subscription_mod, "_OUTPUT_EARLY_RECOVERY_RETRY_S", 0.01)
speech = (1000).to_bytes(2, "little", signed=True) * 480
- endpoint = _FakeAudioEndpoint(
- output_schedule=tuple((0.04, speech) for _ in range(8))
- )
+ endpoint = _FakeAudioEndpoint(output_schedule=tuple((0.04, speech) for _ in range(8)))
# speech_started with no final: the utterance stays open for the whole
# window, so no shadow attempt may run (and under the
# no-unsolicited-opening policy the response never plays either).
@@ -2599,8 +2565,7 @@ async def test_shadow_recovery_yields_to_an_open_user_utterance(
async with asyncio.timeout(0.8):
async for event in session.receive():
assert not (
- event.type == "output_transcript_delta"
- and getattr(event, "shadow", False)
+ event.type == "output_transcript_delta" and getattr(event, "shadow", False)
)
assert transcriber.recovery_calls == []
@@ -2621,17 +2586,13 @@ async def test_interrupt_retires_an_entitlement_the_response_never_used(
answer).
"""
speech = (1000).to_bytes(2, "little", signed=True) * 480
- endpoint = _FakeAudioEndpoint(
- output_schedule=((0.35, speech), (0.02, speech))
- )
+ endpoint = _FakeAudioEndpoint(output_schedule=((0.35, speech), (0.02, speech)))
transcriber = _ScheduledInputTranscriber(
[
(0.0, InputTranscriptEvent(kind="speech_started")),
(
0.02,
- InputTranscriptEvent(
- kind="transcript", text="Wetter morgen?", is_final=True
- ),
+ InputTranscriptEvent(kind="transcript", text="Wetter morgen?", is_final=True),
),
]
)
@@ -2680,16 +2641,12 @@ async def test_barge_in_never_consumes_the_new_utterances_entitlement() -> None:
(0.0, InputTranscriptEvent(kind="speech_started")),
(
0.02,
- InputTranscriptEvent(
- kind="transcript", text="Frage eins", is_final=True
- ),
+ InputTranscriptEvent(kind="transcript", text="Frage eins", is_final=True),
),
(0.05, InputTranscriptEvent(kind="speech_started")),
(
0.02,
- InputTranscriptEvent(
- kind="transcript", text="Warte, anders", is_final=True
- ),
+ InputTranscriptEvent(kind="transcript", text="Warte, anders", is_final=True),
),
]
)
@@ -2720,9 +2677,7 @@ async def test_barge_in_never_consumes_the_new_utterances_entitlement() -> None:
audio_after.append(event)
break
- assert audio_after, (
- "the far end's answer to the barge-in utterance must stay audible"
- )
+ assert audio_after, "the far end's answer to the barge-in utterance must stay audible"
await session.close()
@@ -2984,9 +2939,7 @@ async def test_startup_context_never_authorizes_a_response() -> None:
# No microphone energy stands behind this answer, and a configuration
# write is not consent to speak - so it is refused, exactly like any other
# ungrounded turn.
- assert [
- event.text for event in events if event.type == "output_transcript_delta"
- ] == []
+ assert [event.text for event in events if event.type == "output_transcript_delta"] == []
await session.close()
@@ -3014,9 +2967,7 @@ async def test_the_language_pin_never_authorizes_a_response() -> None:
events = [event async for event in session.receive()]
- assert [
- event.text for event in events if event.type == "output_transcript_delta"
- ] == []
+ assert [event.text for event in events if event.type == "output_transcript_delta"] == []
await session.close()
@@ -3040,9 +2991,7 @@ async def test_a_barge_splice_is_sequenced_behind_a_local_boundary() -> None:
(0.25, InputTranscriptEvent(kind="speech_started")),
(
0.0,
- InputTranscriptEvent(
- kind="transcript", text="And again", is_final=True
- ),
+ InputTranscriptEvent(kind="transcript", text="And again", is_final=True),
),
]
)
@@ -3073,9 +3022,9 @@ async def test_a_barge_splice_is_sequenced_behind_a_local_boundary() -> None:
),
]
)
- session = await _provider(
- client, input_transcriber_factory=lambda: transcriber
- ).open_session(RealtimeSessionConfig())
+ session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
+ RealtimeSessionConfig()
+ )
events = []
async with asyncio.timeout(5.0):
@@ -3089,11 +3038,7 @@ async def test_a_barge_splice_is_sequenced_behind_a_local_boundary() -> None:
if event.type == "output_transcript_delta" and "Second" in text:
break
- deltas = [
- i
- for i, event in enumerate(events)
- if event.type == "output_transcript_delta"
- ]
+ deltas = [i for i, event in enumerate(events) if event.type == "output_transcript_delta"]
first_idx = next(
i
for i, event in enumerate(events)
@@ -3125,12 +3070,8 @@ async def test_the_standing_directive_is_reasserted_on_every_delivery() -> None:
baseline = len(client.text_appends)
rule = "SPEAK AS ONE VOICE ONLY."
- await session.update_session(
- instructions="PERSONA BLOCK", standing_directive=rule
- )
- await session.update_session(
- instructions="PERSONA BLOCK", standing_directive=rule
- )
+ await session.update_session(instructions="PERSONA BLOCK", standing_directive=rule)
+ await session.update_session(instructions="PERSONA BLOCK", standing_directive=rule)
payloads = [text for _, text, _ in client.text_appends[baseline:]]
assert len(payloads) == 2, "an unchanged turn still delivers the rule"
@@ -3154,9 +3095,7 @@ async def test_an_unsolicited_opening_never_plays_on_a_grounded_host() -> None:
(0.02, InputTranscriptEvent(kind="speech_started")),
(
0.55,
- InputTranscriptEvent(
- kind="transcript", text="What is up?", is_final=True
- ),
+ InputTranscriptEvent(kind="transcript", text="What is up?", is_final=True),
),
]
)
@@ -3208,20 +3147,15 @@ async def test_an_unsolicited_opening_never_plays_on_a_grounded_host() -> None:
audio_after_final += 1
else:
audio_before_final += 1
- if event.type == "output_transcript_delta" and "real answer" in (
- event.text or ""
- ):
+ if event.type == "output_transcript_delta" and "real answer" in (event.text or ""):
break
assert audio_before_final == 0, (
"an unsolicited opening reached the surface before the first final"
)
- assert audio_after_final > 0, (
- "the re-judged response after the final must play"
- )
+ assert audio_after_final > 0, "the re-judged response after the final must play"
assert session.diagnostics().get("opening_responses_bounded", 0) == 0, (
- "grounded hosts refuse the opener outright; the bound is the "
- "recognizer-less fallback only"
+ "grounded hosts refuse the opener outright; the bound is the recognizer-less fallback only"
)
await session.close()
@@ -3238,9 +3172,7 @@ async def test_a_final_rejudges_the_open_refused_response_immediately() -> None:
(0.02, InputTranscriptEvent(kind="speech_started")),
(
0.25,
- InputTranscriptEvent(
- kind="transcript", text="Quick one?", is_final=True
- ),
+ InputTranscriptEvent(kind="transcript", text="Quick one?", is_final=True),
),
]
)
@@ -3272,9 +3204,7 @@ async def test_a_final_rejudges_the_open_refused_response_immediately() -> None:
input_transcriber_factory=lambda: transcriber,
).open_session(RealtimeSessionConfig())
- events = await _collect_until(
- session, stop_after=2, kind="audio_delta", timeout_s=2.0
- )
+ events = await _collect_until(session, stop_after=2, kind="audio_delta", timeout_s=2.0)
audio_events = [e for e in events if e.type == "audio_delta"]
assert len(audio_events) == 2, (
@@ -3300,9 +3230,7 @@ async def test_a_discarded_utterance_keeps_its_response_window(
(0.01, InputTranscriptEvent(kind="speech_started")),
(
0.0,
- InputTranscriptEvent(
- kind="transcript", text="Hello there.", is_final=True
- ),
+ InputTranscriptEvent(kind="transcript", text="Hello there.", is_final=True),
),
(0.05, InputTranscriptEvent(kind="speech_started")),
(
@@ -3327,18 +3255,14 @@ async def test_a_discarded_utterance_keeps_its_response_window(
),
]
)
- session = await _provider(
- client, input_transcriber_factory=lambda: transcriber
- ).open_session(RealtimeSessionConfig())
+ session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
+ RealtimeSessionConfig()
+ )
events = await _collect_until(
session, stop_after=1, kind="output_transcript_delta", timeout_s=2.0
)
- delivered = [
- event.text
- for event in events
- if event.type == "output_transcript_delta"
- ]
+ delivered = [event.text for event in events if event.type == "output_transcript_delta"]
assert delivered == ["Did you say something?"], (
"the answer to a heard-but-discarded sound must play inside the grace"
)
@@ -3347,9 +3271,7 @@ async def test_a_discarded_utterance_keeps_its_response_window(
@pytest.mark.asyncio
async def test_an_unanswered_discard_window_expires(monkeypatch) -> None:
- monkeypatch.setattr(
- codex_subscription_mod, "_DISCARDED_UTTERANCE_GRACE_S", 0.05
- )
+ monkeypatch.setattr(codex_subscription_mod, "_DISCARDED_UTTERANCE_GRACE_S", 0.05)
transcriber = _ScheduledInputTranscriber(
[
# Priming exchange: the call opening answers no bare cough under
@@ -3358,9 +3280,7 @@ async def test_an_unanswered_discard_window_expires(monkeypatch) -> None:
(0.01, InputTranscriptEvent(kind="speech_started")),
(
0.0,
- InputTranscriptEvent(
- kind="transcript", text="Hello there.", is_final=True
- ),
+ InputTranscriptEvent(kind="transcript", text="Hello there.", is_final=True),
),
(0.05, InputTranscriptEvent(kind="speech_started")),
(
@@ -3385,19 +3305,434 @@ async def test_an_unanswered_discard_window_expires(monkeypatch) -> None:
),
]
)
- session = await _provider(
- client, input_transcriber_factory=lambda: transcriber
- ).open_session(RealtimeSessionConfig())
+ session = await _provider(client, input_transcriber_factory=lambda: transcriber).open_session(
+ RealtimeSessionConfig()
+ )
events = await _collect_until(
session, stop_after=1, kind="output_transcript_delta", timeout_s=1.5
)
- delivered = [
- event.text
+ delivered = [event.text for event in events if event.type == "output_transcript_delta"]
+ assert delivered == [], "past the grace a discarded utterance grounds nothing"
+ await session.close()
+
+
+def test_readback_render_budget_is_declared() -> None:
+ """A delegate readback on this transport is spoken by ChatGPT-Live, whose
+ audio lags its own start (7.4 s scrub-hold measured 2026-08-05). Without a
+ declared budget the session's 2.5 s hosted floor governed, so the surface
+ fallback took delegated answers in the wrong voice or withheld them
+ entirely (AP-21: a declared capability, never a provider-name check)."""
+ assert CodexSubscriptionRealtimeProvider.readback_render_budget_s == 12.0
+ assert CodexSubscriptionRealtimeProvider.readback_render_budget_s > 2.5, (
+ "the declared budget must beat the shared hosted floor"
+ )
+
+
+class _DyingTranscriber(_StubEndpointer):
+ """Local recognizer whose event stream dies on first read."""
+
+ def __init__(self) -> None:
+ super().__init__(speaking=True)
+
+ async def next_event(self): # noqa: ANN202 - test protocol
+ raise RuntimeError("recognizer stream died")
+
+
+_LOUD_FRAME = (1000).to_bytes(2, "little", signed=True) * 480
+
+
+async def test_every_ungrounded_response_is_bounded(monkeypatch) -> None:
+ """F5a: bounding only the opener left responses #2..n unbounded whenever
+ the recognizer was absent or dead — the regime where the two-AIs
+ self-talk loop ran unopposed and past grounded-path fixes 'did not
+ stick'. Every failopen response now keeps the same coarse bound."""
+ monkeypatch.setattr(codex_subscription_mod, "_OPENING_RESPONSE_MAX_S", 0.05)
+ client = _Client()
+ client.subscription = _keeps_stream_open()
+ endpoint = _FakeAudioEndpoint(
+ output_schedule=(
+ # Response 1: second chunk ages past the bound.
+ (0.0, _LOUD_FRAME),
+ (0.1, _LOUD_FRAME),
+ # Response 2: same shape — previously unbounded.
+ (0.1, _LOUD_FRAME),
+ (0.1, _LOUD_FRAME),
+ )
+ )
+ session = await _provider(client, endpoint=endpoint).open_session(RealtimeSessionConfig())
+
+ events = await _collect_until(session, stop_after=2, kind="turn_complete", timeout_s=3.0)
+
+ assert [event.type for event in events].count("turn_complete") == 2
+ diag = session.diagnostics()
+ assert diag.get("opening_responses_bounded", 0) == 1
+ assert diag.get("ungrounded_responses_bounded", 0) == 1, (
+ "the second ungrounded response must be bounded exactly like the opener"
+ )
+ await session.close()
+
+
+async def test_recognizer_rebuild_restores_grounding(monkeypatch) -> None:
+ """F5b: a dead recognizer stream is no longer a one-way latch. The
+ rebuild reuses the ordinary build path (process-wide STT cache), so the
+ call regains its grounding source instead of running ungrounded until
+ hangup."""
+ monkeypatch.setattr(codex_subscription_mod, "_RECOGNIZER_REBUILD_BACKOFF_S", 0.0)
+ replacements = [
+ _DyingTranscriber(),
+ _ScriptedInputTranscriber(
+ [
+ InputTranscriptEvent(kind="speech_started"),
+ InputTranscriptEvent(kind="transcript", text="Hello again.", is_final=True),
+ ]
+ ),
+ ]
+ client = _Client()
+ client.subscription = _keeps_stream_open()
+ session = await _provider(
+ client,
+ input_transcriber_factory=lambda: replacements.pop(0),
+ ).open_session(RealtimeSessionConfig())
+
+ events = await _collect_until(session, stop_after=1, kind="input_transcript", timeout_s=3.0)
+
+ finals = [event for event in events if event.type == "input_transcript"]
+ assert [event.text for event in finals] == ["Hello again."], (
+ "the rebuilt recognizer must ground turns again"
+ )
+ assert not [event for event in events if event.type == "error"], (
+ "a recovered stream death deserves no surface notice"
+ )
+ diag = session.diagnostics()
+ assert diag.get("recognizer_rebuild_attempts", 0) == 1
+ assert diag.get("recognizer_rebuilds_restored", 0) == 1
+ await session.close()
+
+
+async def test_exhausted_rebuilds_degrade_out_loud_exactly_once(
+ monkeypatch,
+) -> None:
+ """F5a+F5b: only after both rebuilds are spent does the call enter the
+ bounded ungrounded regime — and it says so on the surface exactly once
+ (AP-30), instead of the silent one-way latch that hid the degradation."""
+ monkeypatch.setattr(codex_subscription_mod, "_RECOGNIZER_REBUILD_BACKOFF_S", 0.0)
+ client = _Client()
+ client.subscription = _keeps_stream_open()
+ session = await _provider(
+ client,
+ input_transcriber_factory=_DyingTranscriber,
+ ).open_session(RealtimeSessionConfig())
+
+ events = await _collect_until(session, stop_after=1, kind="error", timeout_s=3.0)
+
+ notices = [event for event in events if event.type == "error"]
+ assert len(notices) == 1
+ assert "stopped during this" in str(notices[0].error)
+ assert notices[0].recoverable is True
+ diag = session.diagnostics()
+ assert diag.get("recognizer_rebuild_attempts", 0) == 2
+ assert diag.get("recognizer_rebuilds_restored", 0) == 2
+ assert diag.get("grounding_unavailable_notices", 0) == 1
+ assert session._local_grounding_ok is False
+ await session.close()
+
+
+async def test_failed_rebuilds_also_end_in_one_notice(monkeypatch) -> None:
+ """The rebuild that cannot even BUILD (factory returns None) retries and
+ then reports the same single degradation notice as a dying stream."""
+ monkeypatch.setattr(codex_subscription_mod, "_RECOGNIZER_REBUILD_BACKOFF_S", 0.0)
+ replacements: list = [_DyingTranscriber()]
+ client = _Client()
+ client.subscription = _keeps_stream_open()
+ session = await _provider(
+ client,
+ input_transcriber_factory=lambda: replacements.pop(0) if replacements else None,
+ ).open_session(RealtimeSessionConfig())
+
+ events = await _collect_until(session, stop_after=1, kind="error", timeout_s=3.0)
+
+ notices = [event for event in events if event.type == "error"]
+ assert len(notices) == 1
+ assert "could not be rebuilt" in str(notices[0].error)
+ diag = session.diagnostics()
+ assert diag.get("recognizer_rebuild_attempts", 0) == 2
+ assert diag.get("recognizer_rebuilds_restored", 0) == 0
+ assert diag.get("grounding_unavailable_notices", 0) == 1
+ await session.close()
+
+
+async def test_a_failed_recognizer_build_is_announced_at_session_start() -> None:
+ """F5a: a call whose recognizer BUILD failed used to degrade with only a
+ build-time log line — the silently disarmed grounding gate. The surface
+ now hears about it before the first frame, exactly once."""
+ session = codex_subscription_mod._CodexSubscriptionRealtimeSession(
+ client=_Client(),
+ subscription=_Subscription(),
+ thread_id="thread-1",
+ answer_sdp="v=0\r\nanswer",
+ audio_endpoint=_FakeAudioEndpoint(),
+ input_transcriber=None,
+ grounding_unavailable_reason="RuntimeError: no STT backend",
+ )
+
+ events = []
+ async for event in session.receive():
+ events.append(event)
+ if len(events) >= 2:
+ break
+
+ assert events[0].type == "error"
+ assert events[0].recoverable is True
+ assert "RuntimeError: no STT backend" in str(events[0].error)
+ assert "bounded" in str(events[0].error)
+ assert session.diagnostics().get("grounding_unavailable_notices", 0) == 1
+ await session.close()
+
+
+async def test_an_injected_none_recognizer_stays_silent() -> None:
+ """A caller that explicitly builds the session without a recognizer (every
+ test in this file, and any embedder that owns its own STT story) is a
+ choice, not a degradation — no start-of-call notice."""
+ client = _Client()
+ session = await _provider(client).open_session(RealtimeSessionConfig())
+
+ events = [event async for event in session.receive()]
+
+ assert not [
+ event
for event in events
- if event.type == "output_transcript_delta"
+ if event.type == "error" and "speech recognition is unavailable" in str(event.error)
+ ]
+ await session.close()
+
+
+def test_a_recognizer_build_failure_carries_its_reason(monkeypatch) -> None:
+ """The reason travels to the session so the surface notice can name it."""
+ real_import = codex_subscription_mod.importlib.import_module
+
+ def _refusing_import(name, *args, **kwargs):
+ if name == "jarvis.realtime.input_transcription":
+ raise RuntimeError("no usable STT backend")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(codex_subscription_mod.importlib, "import_module", _refusing_import)
+ provider = CodexSubscriptionRealtimeProvider()
+
+ transcriber, reason = provider._build_input_transcriber_outcome(
+ SimpleNamespace(input_language="de")
+ )
+
+ assert transcriber is None
+ assert reason == "RuntimeError: no usable STT backend"
+
+
+def test_session_language_reaches_the_recognizer(monkeypatch) -> None:
+ """F5c happy path: the resolved session input language is threaded into
+ the local recognizer, which pins it on the STT config it builds."""
+ built = []
+
+ class _NewTranscriber:
+ def __init__(self, *, sample_rate: int, language=None) -> None:
+ built.append((sample_rate, language))
+
+ fake_module = SimpleNamespace(LocalInputTranscriber=_NewTranscriber)
+ real_import = codex_subscription_mod.importlib.import_module
+ monkeypatch.setattr(
+ codex_subscription_mod.importlib,
+ "import_module",
+ lambda name, *a, **k: (
+ fake_module
+ if name == "jarvis.realtime.input_transcription"
+ else real_import(name, *a, **k)
+ ),
+ )
+ provider = CodexSubscriptionRealtimeProvider()
+
+ provider._build_input_transcriber(SimpleNamespace(input_language="de"))
+ provider._build_input_transcriber(SimpleNamespace(input_language="auto"))
+
+ assert built == [
+ (codex_subscription_mod._INPUT_RATE, "de"),
+ (
+ codex_subscription_mod._INPUT_RATE,
+ None,
+ ),
+ ], "an explicit language is passed; 'auto' keeps the configured one"
+
+
+def test_language_kwarg_rejection_warns_exactly_once(monkeypatch, caplog) -> None:
+ """F5c: the tolerance probe for an out-of-tree recognizer without the
+ ``language`` kwarg stays, but its failure is a one-shot WARNING — the
+ silently swallowed capability (a DEBUG line) is how the un-pinned session
+ language survived unreported (AP-30)."""
+ caplog.set_level(logging.DEBUG)
+ monkeypatch.setattr(codex_subscription_mod, "_language_kwarg_rejected_warned", False)
+
+ class _OldTranscriber:
+ def __init__(self, *, sample_rate: int) -> None:
+ self.sample_rate = sample_rate
+
+ fake_module = SimpleNamespace(LocalInputTranscriber=_OldTranscriber)
+ real_import = codex_subscription_mod.importlib.import_module
+ monkeypatch.setattr(
+ codex_subscription_mod.importlib,
+ "import_module",
+ lambda name, *a, **k: (
+ fake_module
+ if name == "jarvis.realtime.input_transcription"
+ else real_import(name, *a, **k)
+ ),
+ )
+ provider = CodexSubscriptionRealtimeProvider()
+ cfg = SimpleNamespace(input_language="de")
+
+ first = provider._build_input_transcriber(cfg)
+ second = provider._build_input_transcriber(cfg)
+
+ assert isinstance(first, _OldTranscriber)
+ assert isinstance(second, _OldTranscriber), (
+ "the probe must fall back, never lose the grounding source"
+ )
+ rejections = [
+ record
+ for record in caplog.records
+ if "does not accept a session language" in record.getMessage()
]
- assert delivered == [], (
- "past the grace a discarded utterance grounds nothing"
+ assert [record.levelno for record in rejections] == [
+ logging.WARNING,
+ logging.DEBUG,
+ ]
+
+
+class _RosterClient(_Client):
+ """Client whose server publishes a live voice roster (codex-cli 0.147)."""
+
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+ self.roster_requests: list[str] = []
+
+ async def realtime_list_voices(self, thread_id: str) -> dict:
+ self.roster_requests.append(thread_id)
+ return {
+ "v1": ["Nova"],
+ "v2": ["cove"],
+ "defaultV1": "nova",
+ "defaultV2": "cove",
+ }
+
+
+class _RosterRpcError(Exception):
+ """Duck-typed stand-in for CodexAppServerRPCError."""
+
+ def __init__(self, message: str, code: int) -> None:
+ super().__init__(message)
+ self.code = code
+
+
+class _RosterRejectingClient(_Client):
+ async def realtime_list_voices(self, thread_id: str) -> dict:
+ del thread_id
+ raise _RosterRpcError("Method not found", -32601)
+
+
+class _RosterDeadTransportClient(_Client):
+ async def realtime_list_voices(self, thread_id: str) -> dict:
+ del thread_id
+ raise RuntimeError("app-server transport is gone")
+
+
+async def test_the_live_voice_roster_extends_the_audited_static_set() -> None:
+ """The server's own listVoices answer is authoritative when readable, so
+ a voice the nine-name frozenset never heard of still validates."""
+ client = _RosterClient()
+ session = await _provider(client).open_session(RealtimeSessionConfig(voice="nova"))
+
+ assert client.roster_requests == ["thread-1"]
+ _thread_id, start = client.realtime_starts[0]
+ assert start["voice"] == "nova"
+ await session.close()
+
+
+async def test_a_rejected_list_voices_falls_back_to_the_static_roster() -> None:
+ """An older server build without the method (JSON-RPC refusal, has a
+ ``code``) degrades to the audited nine-voice frozenset — capability
+ probed, never version-string-gated in this adapter (AP-21/AP-22)."""
+ session = await _provider(_RosterRejectingClient()).open_session(
+ RealtimeSessionConfig(voice="cove")
)
await session.close()
+
+ with pytest.raises(RuntimeError, match="unsupported voice"):
+ await _provider(_RosterRejectingClient()).open_session(RealtimeSessionConfig(voice="nova"))
+
+
+async def test_a_transport_failure_during_list_voices_propagates() -> None:
+ """A failure WITHOUT an RPC code is a dead transport, not a roster
+ verdict; validating against a guess would open a session that cannot
+ work."""
+ with pytest.raises(RuntimeError, match="transport is gone"):
+ await _provider(_RosterDeadTransportClient()).open_session(
+ RealtimeSessionConfig(voice="cove")
+ )
+
+
+class _InstructionSlotClient(_Client):
+ """Client that declares the 0.147 realtimeStartInstructions lever."""
+
+ async def realtime_start(
+ self,
+ thread_id: str,
+ *,
+ realtime_start_instructions: str | None = None,
+ **kwargs,
+ ):
+ kwargs["realtime_start_instructions"] = realtime_start_instructions
+ self.realtime_starts.append((thread_id, kwargs))
+ return SimpleNamespace(
+ response=self.start_response,
+ answer_sdp="v=0\r\nanswer",
+ )
+
+
+async def test_startup_contract_rides_the_instruction_slot_when_declared() -> None:
+ """When the client declares realtime_start_instructions, the startup
+ contract travels as SESSION instructions instead of a trusted first
+ prompt — injected prompt context is what the model audibly acknowledged
+ mid-open."""
+ client = _InstructionSlotClient()
+ session = await _provider(client).open_session(
+ RealtimeSessionConfig(instructions="You are Nova.")
+ )
+
+ _thread_id, start = client.realtime_starts[0]
+ assert start["trusted_prompt"] == ""
+ assert "You are Nova." in start["realtime_start_instructions"]
+ assert "Speak only the assistant side" in start["realtime_start_instructions"]
+ await session.close()
+
+
+async def test_startup_contract_stays_on_the_prompt_without_the_slot() -> None:
+ """A client that does not DECLARE the parameter by name keeps the proven
+ trusted-prompt path — a ``**kwargs`` sink would swallow the contract
+ without sending it, the exact silent capability loss AP-30 forbids."""
+ client = _Client()
+ session = await _provider(client).open_session(
+ RealtimeSessionConfig(instructions="You are Nova.")
+ )
+
+ _thread_id, start = client.realtime_starts[0]
+ assert "realtime_start_instructions" not in start
+ assert "You are Nova." in start["trusted_prompt"]
+ await session.close()
diff --git a/tests/unit/realtime/test_factory_handshake_budget.py b/tests/unit/realtime/test_factory_handshake_budget.py
new file mode 100644
index 0000000000..47ec4b6204
--- /dev/null
+++ b/tests/unit/realtime/test_factory_handshake_budget.py
@@ -0,0 +1,205 @@
+"""The declared-handshake probe must survive every shape of declaration.
+
+``realtime_handshake_budget_s`` is what stops a surface from calling a start
+attempt dead while the transport is still legitimately negotiating. It used to
+read the budget off the CLASS and outside the per-plugin guard, so a provider
+that declares the value as an instance ``property`` (a self-hosted card asking
+for its server's warm-up time) made ``float()`` raise on the descriptor object
+and killed the whole probe — the browser then silently fell back to its
+historical 20 s ceiling.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+import jarvis.realtime.factory as factory
+from jarvis.realtime.session import _PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S
+
+
+class _FakeProvider:
+ supports_realtime = True
+ input_sample_rate = 16_000
+ output_sample_rate = 24_000
+ credential_candidates = (("fake_api_key", "FAKE_API_KEY"),)
+
+ def __init__(self, *, api_key=None):
+ self.api_key = api_key
+
+ async def can_open_duplex_session(self):
+ return True
+
+ async def open_session(self, cfg): # pragma: no cover - never opened here
+ raise NotImplementedError
+
+
+class _PlainBudgetProvider(_FakeProvider):
+ """Declares the budget as an ordinary class attribute."""
+
+ name = "plain-budget-realtime"
+ handshake_budget_s = 30.0
+
+
+class _PropertyBudgetProvider(_FakeProvider):
+ """Declares the budget as an instance property, like the local card."""
+
+ name = "property-budget-realtime"
+
+ @property
+ def handshake_budget_s(self) -> float:
+ return 135.0
+
+
+class _SilentProvider(_FakeProvider):
+ """Declares no budget at all."""
+
+ name = "silent-realtime"
+
+
+class _ExplodingProviderLoad(Exception):
+ pass
+
+
+def _cfg(*provider_ids: str, providers: dict | None = None) -> SimpleNamespace:
+ ordered = [*provider_ids, None, None, None]
+ return SimpleNamespace(
+ voice=SimpleNamespace(mode="realtime"),
+ brain=SimpleNamespace(
+ reply_language="en",
+ providers=providers or {},
+ realtime=SimpleNamespace(
+ provider=ordered[0],
+ fallback_provider=ordered[1],
+ fallback_provider_2=ordered[2],
+ ),
+ ),
+ )
+
+
+def _fake_registry(monkeypatch, plugins: dict, *, keys: bool = True) -> None:
+ def _load(_group, name, protocol=None):
+ provider_cls = plugins[name]
+ if isinstance(provider_cls, type) and issubclass(provider_cls, _ExplodingProviderLoad):
+ raise provider_cls("plugin import blew up")
+ return provider_cls
+
+ monkeypatch.setattr(factory, "list_plugins", lambda _group: list(plugins))
+ monkeypatch.setattr(factory, "load", _load)
+ monkeypatch.setattr(factory, "get_secret_any", lambda _candidates: "fake-key" if keys else None)
+
+
+class _BrokenPlugin(_ExplodingProviderLoad):
+ pass
+
+
+def test_property_declaration_is_resolved_not_stringified(monkeypatch) -> None:
+ """The bug: ``float()`` on the class attribute got the descriptor object."""
+ _fake_registry(monkeypatch, {"property-budget-realtime": _PropertyBudgetProvider})
+
+ assert factory.realtime_handshake_budget_s(_cfg("property-budget-realtime")) == pytest.approx(
+ 135.0
+ )
+
+
+def test_largest_declared_budget_wins_across_declaration_shapes(monkeypatch) -> None:
+ _fake_registry(
+ monkeypatch,
+ {
+ "plain-budget-realtime": _PlainBudgetProvider,
+ "property-budget-realtime": _PropertyBudgetProvider,
+ "silent-realtime": _SilentProvider,
+ },
+ )
+
+ budget = factory.realtime_handshake_budget_s(
+ _cfg(
+ "plain-budget-realtime",
+ "property-budget-realtime",
+ "silent-realtime",
+ )
+ )
+
+ assert budget == pytest.approx(135.0)
+
+
+def test_one_broken_plugin_never_poisons_the_probe(monkeypatch) -> None:
+ """A plugin that raises on load costs only its own declaration."""
+ _fake_registry(
+ monkeypatch,
+ {
+ "property-budget-realtime": _PropertyBudgetProvider,
+ "broken-realtime": _BrokenPlugin,
+ "plain-budget-realtime": _PlainBudgetProvider,
+ },
+ )
+
+ budget = factory.realtime_handshake_budget_s(
+ _cfg(
+ "property-budget-realtime",
+ "broken-realtime",
+ "plain-budget-realtime",
+ )
+ )
+
+ assert budget == pytest.approx(135.0)
+
+
+def test_class_declaration_still_counts_without_a_usable_instance(
+ monkeypatch,
+) -> None:
+ """No credential means no instance — the class read stays the fallback."""
+ _fake_registry(monkeypatch, {"plain-budget-realtime": _PlainBudgetProvider}, keys=False)
+
+ assert factory.realtime_handshake_budget_s(_cfg("plain-budget-realtime")) == pytest.approx(30.0)
+
+
+def test_budget_never_drops_below_the_shared_default(monkeypatch) -> None:
+ _fake_registry(monkeypatch, {"silent-realtime": _SilentProvider})
+
+ assert factory.realtime_handshake_budget_s(_cfg("silent-realtime")) == pytest.approx(
+ _PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S
+ )
+
+
+def test_probe_survives_a_registry_that_cannot_build_candidates(
+ monkeypatch,
+) -> None:
+ """Instance construction failing must still leave the class read."""
+ _fake_registry(monkeypatch, {"plain-budget-realtime": _PlainBudgetProvider})
+
+ def _boom(_cfg_arg, **_kwargs):
+ raise RuntimeError("candidate build failed")
+
+ monkeypatch.setattr(factory, "_identified_provider_candidates", _boom)
+
+ assert factory.realtime_handshake_budget_s(_cfg("plain-budget-realtime")) == pytest.approx(30.0)
+
+
+def test_installed_local_plugin_declares_a_real_budget() -> None:
+ """Against the REAL entry-point registry, not a fake class.
+
+ The local card is the shipped provider that declares its budget as a
+ property; a class-level read here returns the descriptor and the probe
+ dies. Skipped when that plugin is not installed.
+ """
+ from jarvis.core.registry import list_plugins
+
+ if "local-realtime" not in list_plugins("jarvis.realtime"):
+ pytest.skip("local-realtime plugin is not installed")
+
+ cfg = _cfg(
+ "local-realtime",
+ providers={
+ "local-realtime": SimpleNamespace(
+ base_url="http://localhost:8765",
+ model="",
+ launch_command="",
+ )
+ },
+ )
+
+ budget = factory.realtime_handshake_budget_s(cfg)
+
+ assert budget > _PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S
diff --git a/tests/unit/realtime/test_input_transcription_language.py b/tests/unit/realtime/test_input_transcription_language.py
new file mode 100644
index 0000000000..f336597012
--- /dev/null
+++ b/tests/unit/realtime/test_input_transcription_language.py
@@ -0,0 +1,248 @@
+"""The session language reaches the local recognizer, and the engine is reused.
+
+Two defects live here, and they compound. The transport that needs local
+transcription hands over the session's input language; until the recognizer
+accepted one, that language was dropped and the engine ran on ``auto`` — the
+configuration that answers near-silence with caption-style boilerplate, which
+this transport then treats as something the user said. And every call built its
+own engine, so the model load was re-paid inside each handshake, in front of the
+user's first word.
+
+The tests below therefore pin the language on the CONFIG the recognizer is built
+from (not on a keyword some backend may not have), and pin that identical
+construction parameters yield the identical engine while different ones do not.
+"""
+
+from __future__ import annotations
+
+import inspect
+from typing import Any
+
+import pytest
+
+from jarvis.core.config import STTConfig
+from jarvis.realtime import input_transcription as module
+from jarvis.realtime.input_transcription import LocalInputTranscriber
+
+RATE = 24_000
+
+
+class _FakeStt:
+ """A recognizer stand-in that remembers what it was configured with."""
+
+ native_sample_rate = 16_000
+
+ def __init__(self, language: str) -> None:
+ self.language = language
+
+ async def transcribe(self, chunks: Any) -> Any: # pragma: no cover - unused
+ raise AssertionError("these tests never recognize audio")
+
+
+class _FakeSttFactory:
+ """Records every build and hands out a distinct engine each time."""
+
+ def __init__(self) -> None:
+ self.configs: list[Any] = []
+
+ def __call__(self, stt_cfg: Any) -> _FakeStt:
+ self.configs.append(stt_cfg)
+ return _FakeStt(stt_cfg.language)
+
+
[email protected](autouse=True)
+def _clean_recognizer_cache():
+ module._reset_for_tests()
+ yield
+ module._reset_for_tests()
+
+
+def stt_builds(monkeypatch: pytest.MonkeyPatch) -> _FakeSttFactory:
+ """Replace config loading and STT construction with recording fakes."""
+ builder = _FakeSttFactory()
+ config = type("_Config", (), {"stt": STTConfig(provider="groq-api", language="en")})
+
+ monkeypatch.setattr(
+ "jarvis.core.config.load_config", lambda *a, **k: config, raising=True
+ )
+ monkeypatch.setattr(
+ "jarvis.plugins.stt.build_stt_from_config", builder, raising=True
+ )
+ return builder
+
+
+# -- the language kwarg ------------------------------------------------
+
+
+def test_the_language_keyword_is_accepted_and_keyword_only() -> None:
+ """The transport passes ``language=``; a TypeError here drops it silently."""
+ signature = inspect.signature(LocalInputTranscriber.__init__)
+ parameter = signature.parameters["language"]
+
+ assert parameter.kind is inspect.Parameter.KEYWORD_ONLY
+ assert parameter.default is None
+ # The exact call the Codex subscription transport makes.
+ LocalInputTranscriber(sample_rate=RATE, language="de")
+
+
+async def test_the_session_language_reaches_the_built_recognizer(
+ stt_builds: _FakeSttFactory,
+) -> None:
+ transcriber = LocalInputTranscriber(sample_rate=RATE, language="de")
+
+ assert await transcriber.warm() is True
+ assert [cfg.language for cfg in stt_builds.configs] == ["de"]
+
+
+async def test_no_language_keeps_the_configured_one(
+ stt_builds: _FakeSttFactory,
+) -> None:
+ """Existing callers pass nothing and must keep the STT config's own value."""
+ transcriber = LocalInputTranscriber(sample_rate=RATE)
+
+ assert await transcriber.warm() is True
+ assert [cfg.language for cfg in stt_builds.configs] == ["en"]
+
+
+async def test_a_blank_language_is_the_same_as_none(
+ stt_builds: _FakeSttFactory,
+) -> None:
+ transcriber = LocalInputTranscriber(sample_rate=RATE, language=" ")
+
+ assert await transcriber.warm() is True
+ assert [cfg.language for cfg in stt_builds.configs] == ["en"]
+
+
+def test_a_config_without_a_language_field_is_left_alone(caplog) -> None:
+ """An honest no-op beats losing the recognizer over a missing attribute."""
+ plain = object()
+
+ with caplog.at_level("DEBUG", logger=module.__name__):
+ assert module._language_pinned_stt_config(plain, "de") is plain
+
+ assert "carries no language field" in caplog.text
+
+
+async def test_an_injected_factory_configures_itself(caplog) -> None:
+ """An injected factory owns its construction; the drop is said out loud."""
+ built: list[_FakeStt] = []
+
+ def factory() -> _FakeStt:
+ engine = _FakeStt("its-own")
+ built.append(engine)
+ return engine
+
+ transcriber = LocalInputTranscriber(
+ sample_rate=RATE, stt_factory=factory, language="de"
+ )
+
+ with caplog.at_level("DEBUG", logger=module.__name__):
+ assert await transcriber.warm() is True
+
+ assert len(built) == 1
+ assert "session language 'de' is not applied" in caplog.text
+ # An injected engine is the caller's own object and never enters the cache.
+ assert not module._stt_cache
+
+
+# -- the process-wide recognizer cache ---------------------------------
+
+
+async def test_two_sessions_with_the_same_language_share_one_engine(
+ stt_builds: _FakeSttFactory,
+) -> None:
+ first = LocalInputTranscriber(sample_rate=RATE, language="de")
+ second = LocalInputTranscriber(sample_rate=RATE, language="de")
+
+ assert await first.warm() is True
+ assert await second.warm() is True
+
+ assert len(stt_builds.configs) == 1
+ assert len(module._stt_cache) == 1
+
+
+async def test_a_different_language_builds_its_own_engine(
+ stt_builds: _FakeSttFactory,
+) -> None:
+ german = LocalInputTranscriber(sample_rate=RATE, language="de")
+ spanish = LocalInputTranscriber(sample_rate=RATE, language="es")
+
+ assert await german.warm() is True
+ assert await spanish.warm() is True
+
+ assert [cfg.language for cfg in stt_builds.configs] == ["de", "es"]
+ assert len(module._stt_cache) == 2
+
+
+def test_identical_keys_return_the_identical_entry() -> None:
+ builds: list[str] = []
+
+ def build() -> object:
+ builds.append("built")
+ return object()
+
+ first = module._shared_recognizer("key-a", build)
+ again = module._shared_recognizer("key-a", build)
+ other = module._shared_recognizer("key-b", build)
+
+ assert again is first
+ assert other is not first
+ assert len(builds) == 2
+
+
+def test_the_cache_is_bounded() -> None:
+ for index in range(module._STT_CACHE_MAX + 2):
+ module._shared_recognizer(f"key-{index}", object)
+
+ assert len(module._stt_cache) == module._STT_CACHE_MAX
+ # The oldest entries are the ones that went.
+ assert "key-0" not in module._stt_cache
+ assert f"key-{module._STT_CACHE_MAX + 1}" in module._stt_cache
+
+
+def test_a_retired_engine_is_not_handed_out_again() -> None:
+ builds: list[object] = []
+
+ def build() -> object:
+ engine = object()
+ builds.append(engine)
+ return engine
+
+ first = module._shared_recognizer("key-a", build)
+ module._forget_shared_recognizer(first)
+ second = module._shared_recognizer("key-a", build)
+
+ assert second is not first
+ assert len(builds) == 2
+
+
+async def test_recovering_a_wedged_engine_evicts_it_from_the_cache(
+ stt_builds: _FakeSttFactory,
+) -> None:
+ """The wedge must not be inherited by the next call (AP-24)."""
+ transcriber = LocalInputTranscriber(sample_rate=RATE, language="de")
+ assert await transcriber.warm() is True
+ assert len(module._stt_cache) == 1
+
+ await transcriber._recover_recognizer("a test asked for it")
+
+ assert not module._stt_cache
+ assert await transcriber.warm() is True
+ assert len(stt_builds.configs) == 2
+
+
+async def test_a_shared_engine_carries_its_own_in_flight_guard(
+ stt_builds: _FakeSttFactory,
+) -> None:
+ """Two sessions on one engine must not enter it concurrently (AP-24)."""
+ first = LocalInputTranscriber(sample_rate=RATE, language="de")
+ second = LocalInputTranscriber(sample_rate=RATE, language="de")
+ assert await first.warm() is True
+ assert await second.warm() is True
+
+ first._recognition_busy = True
+
+ assert second._recognition_busy is True
+ first._recognition_busy = False
+ assert second._recognition_busy is False
diff --git a/tests/unit/realtime/test_scrub_gate.py b/tests/unit/realtime/test_scrub_gate.py
index 05e9434f81..6b1d75ed15 100644
--- a/tests/unit/realtime/test_scrub_gate.py
+++ b/tests/unit/realtime/test_scrub_gate.py
@@ -568,3 +568,33 @@ async def test_direct_speech_budget_never_clips_a_long_trusted_answer():
)
assert await gate.push_audio(one_minute)
assert await gate.push_audio(one_minute)
+
+
+async def test_response_identity_prevents_cross_response_audio_release():
+ """Transcript B must never authorize buffered PCM from response A."""
+ gate = ScrubHoldGate(language="en")
+ assert await gate.push_audio(_chunk(4), response_id="response-a") == []
+
+ display = await gate.feed_transcript(
+ "This belongs to the next answer.",
+ response_id="response-b",
+ )
+
+ assert display == gate.fallback_phrase()
+ assert gate.hard_leak_pending() is True
+ assert gate.hard_leak_actions() == ("response_identity_mismatch",)
+ assert gate.release_available() == []
+
+
+async def test_response_identity_is_reusable_after_a_real_boundary():
+ gate = ScrubHoldGate(language="en")
+ await gate.feed_transcript("First answer.", response_id="response-a")
+ assert await gate.push_audio(_chunk(4), response_id="response-a")
+
+ gate.drain()
+
+ assert gate.response_id == ""
+ await gate.feed_transcript("Second answer.", response_id="response-b")
+ assert await gate.push_audio(_chunk(4), response_id="response-b")
diff --git a/tests/unit/realtime/test_session_playback_release.py b/tests/unit/realtime/test_session_playback_release.py
new file mode 100644
index 0000000000..c690bf8f4a
--- /dev/null
+++ b/tests/unit/realtime/test_session_playback_release.py
@@ -0,0 +1,194 @@
+"""Half-duplex mute release is gated on PHYSICAL playback where possible.
+
+Provider-frame silence only proves the provider stopped sending; the desktop
+surface still has ~180 ms of jitter reserve plus the device drain audibly
+playing, and releasing the microphone into that tail fed the reply's
+remainder back in as user speech on open speakers. Pinned here: a surface
+playback probe defers the release while audio is physically audible, the
+veto is bounded by the alert threshold (never a new stuck-mute class), a
+probe-less surface pays a conservative drain margin instead, and a broken
+probe degrades to the heuristic — reported, not swallowed.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from types import SimpleNamespace
+from typing import Any
+
+from jarvis.realtime.session import (
+ _HALF_DUPLEX_MUTE_ALERT_S,
+ _HALF_DUPLEX_NO_PROBE_DRAIN_MARGIN_S,
+ _HALF_DUPLEX_SILENT_RELEASE_S,
+ RealtimeVoiceSession,
+)
+
+RATE = 24_000
+
+
+class _IdleWire:
+ session_id = "playback-release-wire"
+ supports_tool_updates = True
+ creates_responses_automatically = False
+ isolates_response_generations = False
+
+ async def send_audio(self, chunk: Any) -> None:
+ del chunk
+
+ async def receive(self): # noqa: ANN201 - async generator, protocol shape
+ if False: # pragma: no cover - an intentionally empty stream
+ yield None
+
+ async def close(self) -> None:
+ return None
+
+
+class _Provider:
+ name = "playback-release"
+ supports_realtime = True
+ input_sample_rate = RATE
+ output_sample_rate = RATE
+
+ async def can_open_duplex_session(self) -> bool:
+ return True
+
+ async def open_session(self, config: Any) -> _IdleWire:
+ del config
+ return _IdleWire()
+
+
+def _config() -> SimpleNamespace:
+ return SimpleNamespace(
+ brain=SimpleNamespace(reply_language="en", providers={}),
+ stt=SimpleNamespace(language="auto"),
+ voice=SimpleNamespace(mode="realtime", realtime_tool_mode="delegate"),
+ latency=SimpleNamespace(enabled=False),
+ )
+
+
+def _session() -> RealtimeVoiceSession:
+ return RealtimeVoiceSession(
+ session_id="playback-release",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda _message: asyncio.sleep(0),
+ providers=[_Provider()],
+ config=_config(),
+ bus=None,
+ surface="desktop",
+ half_duplex=True,
+ browser_sample_rate=RATE,
+ )
+
+
+def _arm_mute(
+ session: RealtimeVoiceSession, *, muted_s: float, silent_s: float
+) -> None:
+ now = time.monotonic()
+ session._output_active = True
+ session._half_duplex_muted_since = now - muted_s
+ session._last_output_audio_at = now - silent_s
+
+
+def test_probe_says_drained_releases_at_the_base_silence_window() -> None:
+ session = _session()
+ session.set_playback_probe(lambda: False)
+ _arm_mute(
+ session,
+ muted_s=3.0,
+ silent_s=_HALF_DUPLEX_SILENT_RELEASE_S + 0.1,
+ )
+ session._note_half_duplex_mute()
+ assert session._output_active is False
+ assert session._mute_emergency_releases == 1
+
+
+def test_probe_still_active_defers_the_release() -> None:
+ session = _session()
+ session.set_playback_probe(lambda: True)
+ _arm_mute(
+ session,
+ muted_s=3.0,
+ silent_s=_HALF_DUPLEX_SILENT_RELEASE_S + 0.5,
+ )
+ session._note_half_duplex_mute()
+ assert session._output_active is True, (
+ "the reply is still physically audible; reopening the microphone now "
+ "would feed its remainder back in"
+ )
+ assert session._mute_emergency_releases == 0
+
+
+def test_probe_veto_is_bounded_by_the_alert_threshold() -> None:
+ # A latched probe must never create a new stuck-mute class: past the
+ # alert threshold the emergency release runs regardless of the probe.
+ session = _session()
+ session.set_playback_probe(lambda: True)
+ _arm_mute(
+ session,
+ muted_s=_HALF_DUPLEX_MUTE_ALERT_S + 0.5,
+ silent_s=_HALF_DUPLEX_SILENT_RELEASE_S + 0.5,
+ )
+ session._note_half_duplex_mute()
+ assert session._output_active is False
+ assert session._mute_emergency_releases == 1
+
+
+def test_without_a_probe_the_drain_margin_extends_the_window() -> None:
+ session = _session()
+ # Silent longer than the base window but inside the drain margin: the
+ # surface's prebuffer/device drain may still be audible, keep the mute.
+ _arm_mute(
+ session,
+ muted_s=4.0,
+ silent_s=_HALF_DUPLEX_SILENT_RELEASE_S + 0.2,
+ )
+ session._note_half_duplex_mute()
+ assert session._output_active is True
+
+ # Past base window plus margin the heuristic release fires as before.
+ _arm_mute(
+ session,
+ muted_s=4.0,
+ silent_s=(
+ _HALF_DUPLEX_SILENT_RELEASE_S
+ + _HALF_DUPLEX_NO_PROBE_DRAIN_MARGIN_S
+ + 0.2
+ ),
+ )
+ session._note_half_duplex_mute()
+ assert session._output_active is False
+ assert session._mute_emergency_releases == 1
+
+
+def test_a_raising_probe_degrades_to_the_heuristic_release() -> None:
+ session = _session()
+
+ def _broken() -> bool:
+ raise RuntimeError("probe died")
+
+ session.set_playback_probe(_broken)
+ _arm_mute(
+ session,
+ muted_s=4.0,
+ silent_s=(
+ _HALF_DUPLEX_SILENT_RELEASE_S
+ + _HALF_DUPLEX_NO_PROBE_DRAIN_MARGIN_S
+ + 0.2
+ ),
+ )
+ session._note_half_duplex_mute()
+ assert session._playback_active_probe is None, (
+ "a raising probe is disabled for the rest of the call"
+ )
+ assert session._output_active is False, (
+ "the heuristic release still works after the probe failure"
+ )
+
+
+def test_set_playback_probe_rejects_non_callables() -> None:
+ session = _session()
+ session.set_playback_probe(None)
+ assert session._playback_active_probe is None
+ session.set_playback_probe("not-a-callable") # type: ignore[arg-type]
+ assert session._playback_active_probe is None
diff --git a/tests/unit/realtime/test_session_response_latency.py b/tests/unit/realtime/test_session_response_latency.py
new file mode 100644
index 0000000000..c143b9f78a
--- /dev/null
+++ b/tests/unit/realtime/test_session_response_latency.py
@@ -0,0 +1,191 @@
+"""``first_final_to_first_audio_ms``: the honest answer-latency metric.
+
+``first_audio_ms`` measures from session start, so it also counts the time
+the user spent listening to the greeting and speaking their own utterance —
+a healthy codex call read 8 311 ms while the wait after the final was 923 ms.
+These tests pin the new metric's contract: it runs from the FIRST user final
+to the first AUDIBLE provider frame after it, silence never closes it, audio
+before any final never starts it, and 0 stays the "never measured" sentinel.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from typing import Any
+
+from jarvis.core.bus import EventBus
+from jarvis.core.events import RealtimeSessionPostmortem
+from jarvis.core.protocols import AudioChunk
+from jarvis.realtime.protocol import RealtimeEvent
+from jarvis.realtime.session import RealtimeVoiceSession
+
+TIMEOUT_S = 5.0
+RATE = 24_000
+AUDIBLE_PCM = b"\x01\x02" * 160 # int16 peak 513, above the silence floor
+SILENT_PCM = b"\x01\x00" * 160 # int16 peak 1, embedded silence
+
+
+class _ScriptedWire:
+ session_id = "response-latency-wire"
+ supports_tool_updates = True
+ creates_responses_automatically = False
+ isolates_response_generations = False
+
+ def __init__(self, events: list[RealtimeEvent]) -> None:
+ self._events = events
+
+ async def receive(self): # noqa: ANN201 - async generator, protocol shape
+ for event in self._events:
+ yield event
+ await asyncio.sleep(0)
+
+ async def send_audio(self, chunk: Any) -> None:
+ del chunk
+
+ async def update_session(self, **kwargs: Any) -> None:
+ del kwargs
+
+ async def request_response(self, **kwargs: Any) -> None:
+ del kwargs
+
+ async def send_text(self, text: str) -> None:
+ del text
+
+ async def truncate(self, audio_end_ms: int) -> None:
+ del audio_end_ms
+
+ async def interrupt(self, **kwargs: Any) -> None:
+ del kwargs
+
+ async def send_tool_result(self, *args: Any) -> None:
+ del args
+
+ async def close(self) -> None:
+ return None
+
+
+class _Provider:
+ name = "scripted"
+ supports_realtime = True
+ input_sample_rate = RATE
+ output_sample_rate = RATE
+
+ def __init__(self, events: list[RealtimeEvent]) -> None:
+ self._events = events
+
+ async def can_open_duplex_session(self) -> bool:
+ return True
+
+ async def open_session(self, config: Any) -> _ScriptedWire:
+ del config
+ return _ScriptedWire(self._events)
+
+
+def _config() -> SimpleNamespace:
+ return SimpleNamespace(
+ brain=SimpleNamespace(reply_language="en", providers={}),
+ stt=SimpleNamespace(language="auto"),
+ voice=SimpleNamespace(mode="realtime", realtime_tool_mode="delegate"),
+ latency=SimpleNamespace(enabled=False),
+ )
+
+
+async def _run_call(
+ events: list[RealtimeEvent],
+) -> RealtimeSessionPostmortem:
+ bus = EventBus()
+ seen: list[RealtimeSessionPostmortem] = []
+
+ async def _collect(event: RealtimeSessionPostmortem) -> None:
+ seen.append(event)
+
+ bus.subscribe(RealtimeSessionPostmortem, _collect)
+ session = RealtimeVoiceSession(
+ session_id="response-latency",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda _message: asyncio.sleep(0),
+ providers=[_Provider(events)],
+ config=_config(),
+ bus=bus,
+ surface="desktop",
+ half_duplex=True,
+ browser_sample_rate=RATE,
+ )
+ await asyncio.wait_for(
+ session.handle_control({"type": "audio_start", "sample_rate": RATE}),
+ TIMEOUT_S,
+ )
+ await asyncio.wait_for(session.wait_finished(), TIMEOUT_S)
+ await asyncio.wait_for(session.end(reason="test"), TIMEOUT_S)
+ assert len(seen) == 1
+ return seen[0]
+
+
+async def test_metric_runs_from_first_final_to_first_audible_frame() -> None:
+ postmortem = await _run_call(
+ [
+ RealtimeEvent(
+ type="input_transcript",
+ text="Hello how are you",
+ is_final=True,
+ item_id="turn-1",
+ ),
+ RealtimeEvent(type="output_transcript_delta", text="Hello there."),
+ RealtimeEvent(
+ type="audio_delta",
+ audio=AudioChunk(
+ pcm=AUDIBLE_PCM, sample_rate=RATE, timestamp_ns=0
+ ),
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ )
+ assert postmortem.first_final_to_first_audio_ms >= 1, (
+ "a captured value is floored to 1 ms so it can never read as the "
+ "0 'never measured' sentinel"
+ )
+ assert (
+ postmortem.first_final_to_first_audio_ms <= postmortem.first_audio_ms
+ or postmortem.first_audio_ms == 0
+ ), "the wait after the final can never exceed the wait from session start"
+
+
+async def test_audio_before_any_final_never_starts_the_measurement() -> None:
+ postmortem = await _run_call(
+ [
+ RealtimeEvent(type="output_transcript_delta", text="Hi there."),
+ RealtimeEvent(
+ type="audio_delta",
+ audio=AudioChunk(
+ pcm=AUDIBLE_PCM, sample_rate=RATE, timestamp_ns=0
+ ),
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ )
+ assert postmortem.first_final_to_first_audio_ms == 0
+
+
+async def test_embedded_silence_never_closes_the_measurement() -> None:
+ postmortem = await _run_call(
+ [
+ RealtimeEvent(
+ type="input_transcript",
+ text="Hello how are you",
+ is_final=True,
+ item_id="turn-1",
+ ),
+ RealtimeEvent(type="output_transcript_delta", text="Hello there."),
+ RealtimeEvent(
+ type="audio_delta",
+ audio=AudioChunk(
+ pcm=SILENT_PCM, sample_rate=RATE, timestamp_ns=0
+ ),
+ ),
+ RealtimeEvent(type="turn_complete"),
+ ]
+ )
+ assert postmortem.first_final_to_first_audio_ms == 0, (
+ "silent PCM is forwarded but is not an audible answer"
+ )
diff --git a/tests/unit/realtime/test_session_toolless_delegate_default.py b/tests/unit/realtime/test_session_toolless_delegate_default.py
new file mode 100644
index 0000000000..d83349edd8
--- /dev/null
+++ b/tests/unit/realtime/test_session_toolless_delegate_default.py
@@ -0,0 +1,219 @@
+"""Delegate-by-default on ambiguous action turns — tool-less transports only.
+
+A provider that declares ``supports_direct_tools=False`` (capability read,
+never a provider-id check) reaches actions ONLY through the session-side
+planner: there is no native tool the model could call, and the
+model-initiated handoff item has never been observed on the live wire. A
+final the planner routes natively is answered unaided by the far end and any
+action in it is silently lost — counted by ``handoff_obligation_misses``
+but never executed. Pinned here: on such a transport an action-shaped but
+ambiguous final (a tasking phrase outside the planner's action vocabulary)
+dispatches the deterministic delegate anyway, the new
+``handoff_ambiguous_delegations`` counter keeps that path distinguishable
+from planner-confirmed action turns and model-initiated handoffs, and a
+provider WITH native tools keeps today's routing untouched.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from typing import Any
+
+from jarvis.brain.turn_planner import TurnPath, TurnPlan
+from jarvis.realtime.protocol import RealtimeEvent
+from jarvis.realtime.session import RealtimeVoiceSession
+
+TIMEOUT_S = 5.0
+RATE = 24_000
+# A tasking phrase whose verb sits OUTSIDE the planner's action vocabulary —
+# the planner routes it natively, which on a tool-less transport used to
+# lose the action.
+AMBIGUOUS_ACTION = "Can you take care of that for me"
+SMALLTALK = "I had a really nice day today"
+
+
+class _NativePlanBrain:
+ """Brain whose planner finds nothing — the ambiguity tie-break decides."""
+
+ conversation_language = "en"
+
+ def __init__(self) -> None:
+ self.calls: list[str] = []
+ self.started = asyncio.Event()
+
+ def plan_turn(self, _text: str) -> TurnPlan:
+ return TurnPlan(path=TurnPath.NATIVE_REALTIME)
+
+ async def __call__(self, text: str) -> str:
+ self.calls.append(text)
+ self.started.set()
+ return "Done."
+
+
+class _Wire:
+ session_id = "toolless-delegate-wire"
+ supports_tool_updates = False
+ creates_responses_automatically = True
+ isolates_response_generations = True
+ direct_speech_is_authoritative = True
+
+ def __init__(self, text: str) -> None:
+ self._text = text
+ self._closed = asyncio.Event()
+ self.speech_sent: list[str] = []
+ self.interrupts = 0
+
+ async def receive(self): # noqa: ANN201 - async generator, protocol shape
+ yield RealtimeEvent(
+ type="input_transcript",
+ text=self._text,
+ is_final=True,
+ item_id="turn-1",
+ )
+ await self._closed.wait()
+
+ async def send_audio(self, chunk: Any) -> None:
+ del chunk
+
+ async def update_session(self, **kwargs: Any) -> None:
+ del kwargs
+
+ async def request_response(self, **kwargs: Any) -> None:
+ del kwargs
+
+ async def send_text(self, text: str) -> None:
+ del text
+
+ async def send_speech(self, text: str) -> None:
+ self.speech_sent.append(text)
+
+ async def truncate(self, audio_end_ms: int) -> None:
+ del audio_end_ms
+
+ async def interrupt(self, **kwargs: Any) -> None:
+ self.interrupts += 1
+
+ async def send_tool_result(self, *args: Any) -> None:
+ del args
+
+ async def close(self) -> None:
+ self._closed.set()
+
+
+class _ToollessProvider:
+ """Codex-shaped capability card: no native tools on the wire."""
+
+ name = "toolless"
+ supports_realtime = True
+ supports_direct_tools = False
+ input_sample_rate = RATE
+ output_sample_rate = RATE
+
+ def __init__(self, wire: _Wire) -> None:
+ self._wire = wire
+
+ async def can_open_duplex_session(self) -> bool:
+ return True
+
+ async def open_session(self, config: Any) -> _Wire:
+ del config
+ return self._wire
+
+
+class _NativeToolsProvider(_ToollessProvider):
+ name = "native-tools"
+ supports_direct_tools = True
+
+
+def _config() -> SimpleNamespace:
+ return SimpleNamespace(
+ brain=SimpleNamespace(reply_language="en", providers={}),
+ stt=SimpleNamespace(language="auto"),
+ voice=SimpleNamespace(mode="realtime", realtime_tool_mode="delegate"),
+ latency=SimpleNamespace(enabled=False),
+ )
+
+
+def _session(
+ provider: _ToollessProvider, brain: _NativePlanBrain
+) -> RealtimeVoiceSession:
+ return RealtimeVoiceSession(
+ session_id="toolless-delegate-default",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda _message: asyncio.sleep(0),
+ providers=[provider],
+ config=_config(),
+ bus=None,
+ surface="desktop",
+ half_duplex=True,
+ browser_sample_rate=RATE,
+ brain=brain,
+ )
+
+
+async def test_ambiguous_action_delegates_by_default_on_a_toolless_wire() -> None:
+ brain = _NativePlanBrain()
+ wire = _Wire(AMBIGUOUS_ACTION)
+ session = _session(_ToollessProvider(wire), brain)
+ await asyncio.wait_for(
+ session.handle_control({"type": "audio_start", "sample_rate": RATE}),
+ TIMEOUT_S,
+ )
+ try:
+ await asyncio.wait_for(brain.started.wait(), TIMEOUT_S)
+ finally:
+ await asyncio.wait_for(session.end(reason="test"), TIMEOUT_S)
+
+ assert brain.calls == [AMBIGUOUS_ACTION], (
+ "the ambiguous action final must reach the deterministic delegate "
+ "instead of being answered unaided by the far end"
+ )
+ assert session._handoff_ambiguous_delegations == 1
+ assert session._handoff_delegate_dispatches == 1
+ assert session._handoff_action_turns == 0, (
+ "an ambiguity dispatch is not a planner-confirmed action turn — the "
+ "counters must keep the origins distinguishable"
+ )
+
+ postmortem = session._build_postmortem("test")
+ assert postmortem.handoff_ambiguous_delegations == 1
+ assert postmortem.handoff_obligation_misses == 0
+
+
+async def test_a_native_tools_provider_keeps_todays_routing() -> None:
+ brain = _NativePlanBrain()
+ wire = _Wire(AMBIGUOUS_ACTION)
+ session = _session(_NativeToolsProvider(wire), brain)
+ await asyncio.wait_for(
+ session.handle_control({"type": "audio_start", "sample_rate": RATE}),
+ TIMEOUT_S,
+ )
+ try:
+ await asyncio.sleep(0.2)
+ finally:
+ await asyncio.wait_for(session.end(reason="test"), TIMEOUT_S)
+
+ assert brain.calls == [], (
+ "with native tools declared, the model itself can act — the "
+ "ambiguity tie-break must not touch this provider"
+ )
+ assert session._handoff_ambiguous_delegations == 0
+ assert session._handoff_delegate_dispatches == 0
+
+
+async def test_plain_smalltalk_stays_native_on_a_toolless_wire() -> None:
+ brain = _NativePlanBrain()
+ wire = _Wire(SMALLTALK)
+ session = _session(_ToollessProvider(wire), brain)
+ await asyncio.wait_for(
+ session.handle_control({"type": "audio_start", "sample_rate": RATE}),
+ TIMEOUT_S,
+ )
+ try:
+ await asyncio.sleep(0.2)
+ finally:
+ await asyncio.wait_for(session.end(reason="test"), TIMEOUT_S)
+
+ assert brain.calls == []
+ assert session._handoff_ambiguous_delegations == 0
diff --git a/tests/unit/test_codex_app_server_warm_ride.py b/tests/unit/test_codex_app_server_warm_ride.py
new file mode 100644
index 0000000000..aecd31c306
--- /dev/null
+++ b/tests/unit/test_codex_app_server_warm_ride.py
@@ -0,0 +1,541 @@
+"""Unit tests for the warm wake-ride audit token, the per-host STUN media-path
+memory, and the unused 0.147 protocol levers of the Codex app-server client.
+
+Every subprocess, pipe, auth result, and process-tree container is a local
+fake, following the pattern of ``tests/unit/codex_app_server/test_transport.py``
+(kept separate because the working tree is shared). The suite never reads a
+Codex auth file, starts the CLI, or touches the network.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import time
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+import jarvis.codex_app_server as transport
+from jarvis.codex_app_server import (
+ CodexAppServerCapability,
+ CodexAppServerClient,
+ CodexAppServerRPCError,
+ 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_owner", None)
+ monkeypatch.setattr(transport, "_subscription_transport_process_lock", None)
+ monkeypatch.setattr(transport, "_subscription_mutation_process_lock", None)
+ monkeypatch.setattr(transport, "_subscription_snapshot_cache", None)
+ monkeypatch.setattr(transport, "_subscription_snapshot_cache_key", "")
+ monkeypatch.setattr(transport, "_subscription_snapshot_cache_at", 0.0)
+ monkeypatch.setattr(transport, "_subscription_status_probe_active", False)
+ monkeypatch.setattr(transport, "_sha256_cache", {})
+ monkeypatch.setattr(transport, "_subscription_snapshot_cache_is_failure", False)
+ monkeypatch.setattr(transport, "_subscription_transport_epoch", 0)
+ monkeypatch.setattr(transport, "_subscription_activation_block", None)
+ monkeypatch.setattr(transport, "_verify_spawn_binary", lambda _path: None)
+ monkeypatch.setattr(transport, "_stun_media_path_memory", {})
+
+
+class FakeStdin:
+ def __init__(self, process: FakeProcess) -> None:
+ self.process = process
+ self.messages: list[dict[str, Any]] = []
+ self.closed = False
+
+ 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:
+ await asyncio.sleep(0)
+
+ def close(self) -> None:
+ self.closed = True
+ self.process.finish(0)
+
+
+class FakeProcess:
+ _next_pid = 5200
+
+ def __init__(
+ self,
+ responder: Callable[[FakeProcess, dict[str, Any]], None] | 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
+
+ def on_client_message(self, message: dict[str, Any]) -> None:
+ 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 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 _default_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":
+ _respond(process, request_id, {"userAgent": "fake"})
+ elif method == "account/read":
+ _respond(
+ process,
+ request_id,
+ {
+ "account": {
+ "type": "chatgpt",
+ "email": "[email protected]",
+ "planType": "plus",
+ },
+ "requiresOpenaiAuth": True,
+ },
+ )
+ elif method == "config/read":
+ _respond(
+ process,
+ request_id,
+ {"config": {}, "layers": [{"name": "sessionFlags", "config": {}}]},
+ )
+ elif method == "configRequirements/read":
+ _respond(process, request_id, {"requirements": None})
+ elif method == "thread/start":
+ _respond(process, request_id, {"thread": {"id": "thread-1"}})
+ elif method == "thread/realtime/listVoices":
+ _respond(
+ process,
+ request_id,
+ {
+ "v1": ["cove"],
+ "v2": ["cove", "maple"],
+ "defaultV1": "cove",
+ "defaultV2": "maple",
+ },
+ )
+ else:
+ _respond(process, request_id, {})
+
+
+class SpawnHarness:
+ def __init__(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ responder: Callable[[FakeProcess, dict[str, Any]], None] | None = None,
+ ) -> None:
+ self.processes: list[FakeProcess] = []
+ self.trees: list[FakeProcessTree] = []
+ self._responder = responder
+ self._pending_tree: FakeProcessTree | None = None
+ self.codex_home = Path("C:/isolated-jarvis-codex-voice-test")
+ self.home_validations = 0
+
+ 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._pending_tree = tree
+ return tree
+
+ async def spawn(*_args: Any, **_kwargs: Any) -> FakeProcess:
+ process = FakeProcess(self._responder)
+ tree = self._pending_tree
+ assert tree is not None
+ self._pending_tree = None
+ self.processes.append(process)
+ self.trees.append(tree)
+ return process
+
+ def validate_home(**_kwargs: object) -> Path:
+ self.home_validations += 1
+ return self.codex_home
+
+ monkeypatch.setattr(transport, "make_process_tree", make_tree)
+ monkeypatch.setattr(transport.asyncio, "create_subprocess_exec", spawn)
+ monkeypatch.setattr(transport, "_validated_subscription_home", validate_home)
+ monkeypatch.setattr(
+ CodexAppServerClient,
+ "_audit_effective_config",
+ lambda *_args, **_kwargs: None,
+ )
+ monkeypatch.setattr(
+ CodexAppServerClient,
+ "_audit_thread_start_response",
+ lambda *_args, **_kwargs: None,
+ )
+
+ def methods(self) -> list[str]:
+ return [str(message.get("method")) for message in self.processes[0].stdin.messages]
+
+
+def _age_stamp(client: CodexAppServerClient) -> None:
+ """Move the shared audit stamp beyond the ride TTL without sleeping."""
+ client._startup_audit_at -= transport._STARTUP_AUDIT_TTL_S + 1.0
+
+
+# --- (a) warm wake-ride audit token -----------------------------------------
+
+
+async def test_warm_verify_mints_a_ride_one_wake_skips_the_reaudit_exactly_once(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ harness = SpawnHarness(monkeypatch)
+ client = CodexAppServerClient()
+
+ # Cold start inside the first thread start consumes the cold one-shot.
+ await client.thread_start()
+ _age_stamp(client)
+ client._warm_audit_process = None
+ client._warm_audit_at = 0.0
+
+ # The warm verify pass completes the FULL audit (profile walk, live
+ # account, config requirements, effective config) and mints the ride.
+ validations_before = harness.home_validations
+ accounts_before = harness.methods().count("account/read")
+ await client.require_chatgpt_login()
+ assert harness.home_validations == validations_before + 1
+ # One account/read for the gate itself plus one inside the full audit.
+ assert harness.methods().count("account/read") == accounts_before + 2
+
+ # A wake word within the TTL rides that just-passed audit: no profile
+ # walk, no account/read, no config RPCs on top of the thread/start frame.
+ validations_before = harness.home_validations
+ methods_before = harness.methods()
+ await client.thread_start()
+ added = harness.methods()[len(methods_before) :]
+ assert added == ["thread/start"]
+ assert harness.home_validations == validations_before
+
+ # The ride is one-shot: the next warm start re-audits in full.
+ methods_before = harness.methods()
+ await client.thread_start()
+ added = harness.methods()[len(methods_before) :]
+ assert added.count("account/read") == 1
+ assert added.count("configRequirements/read") == 1
+ assert added.count("config/read") == 1
+ assert added[-1] == "thread/start"
+ assert harness.home_validations == validations_before + 1
+ await client.close()
+
+
+async def test_expired_warm_ride_still_reaudits_in_full(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ harness = SpawnHarness(monkeypatch)
+ client = CodexAppServerClient()
+
+ await client.thread_start()
+ _age_stamp(client)
+ client._warm_audit_process = None
+ client._warm_audit_at = 0.0
+ await client.require_chatgpt_login()
+
+ # The wake arrives AFTER the TTL: the token must not be honored.
+ client._warm_audit_at -= transport._STARTUP_AUDIT_TTL_S + 1.0
+ client._startup_audit_at -= transport._STARTUP_AUDIT_TTL_S + 1.0
+ methods_before = harness.methods()
+ await client.thread_start()
+ added = harness.methods()[len(methods_before) :]
+ assert added.count("account/read") == 1
+ assert added.count("configRequirements/read") == 1
+ assert added.count("config/read") == 1
+ # Stale or not, the read consumed it — nothing is left to ride.
+ assert client._warm_audit_process is None
+ await client.close()
+
+
+async def test_prime_reuses_a_fresh_audit_stamp_without_new_rpcs(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A prime microseconds after the cold start must not repeat the audit —
+ it re-mints the ride from the stamp of the audit that just passed."""
+ harness = SpawnHarness(monkeypatch)
+ client = CodexAppServerClient()
+
+ await client.ensure_started()
+ methods_before = harness.methods()
+ await client.prime_startup_audit()
+ assert harness.methods() == methods_before
+ assert client._warm_audit_process is client._process
+ assert client._warm_audit_at == client._startup_audit_at
+ await client.close()
+ assert client._warm_audit_process is None
+
+
+# --- (b) per-host STUN media-path memory ------------------------------------
+
+
+def test_stun_memory_prefers_stun_only_after_a_successful_stun_connect() -> None:
+ assert transport.media_path_prefers_stun("chatgpt.com") is False
+
+ transport.record_media_path_outcome("chatgpt.com", needed_stun=True)
+ assert transport.media_path_prefers_stun("chatgpt.com") is True
+ # Normalized per host: case and surrounding whitespace do not split keys.
+ assert transport.media_path_prefers_stun(" CHATGPT.COM ") is True
+ assert transport.media_path_prefers_stun("other.example") is False
+
+ # A later successful host-candidate connect clears the memory.
+ transport.record_media_path_outcome("ChatGPT.com", needed_stun=False)
+ assert transport.media_path_prefers_stun("chatgpt.com") is False
+
+
+def test_stun_memory_expires_after_its_ttl() -> None:
+ transport.record_media_path_outcome("chatgpt.com", needed_stun=True)
+ transport._stun_media_path_memory["chatgpt.com"] = (
+ time.monotonic() - transport._STUN_MEDIA_PATH_TTL_S - 1.0
+ )
+ assert transport.media_path_prefers_stun("chatgpt.com") is False
+ # The stale entry is dropped, not merely ignored.
+ assert "chatgpt.com" not in transport._stun_media_path_memory
+
+
+def test_stun_memory_ignores_empty_hosts() -> None:
+ transport.record_media_path_outcome("", needed_stun=True)
+ transport.record_media_path_outcome(" ", needed_stun=True)
+ assert transport._stun_media_path_memory == {}
+ assert transport.media_path_prefers_stun("") is False
+
+
+# --- (c) protocol levers ----------------------------------------------------
+
+
+async def test_realtime_list_voices_round_trip(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ harness = SpawnHarness(monkeypatch)
+ client = CodexAppServerClient()
+ await client.ensure_started()
+
+ voices = await client.realtime_list_voices("thread-1")
+
+ assert voices["v2"] == ["cove", "maple"]
+ assert voices["defaultV2"] == "maple"
+ frame = next(
+ message
+ for message in harness.processes[0].stdin.messages
+ if message.get("method") == "thread/realtime/listVoices"
+ )
+ assert frame["params"] == {"threadId": "thread-1"}
+ await client.close()
+
+
+async def test_realtime_list_voices_raises_cleanly_when_the_server_lacks_it(
+ 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") == "thread/realtime/listVoices":
+ asyncio.get_running_loop().call_soon(
+ process.emit,
+ {
+ "id": request_id,
+ "error": {"code": -32601, "message": "method not found"},
+ },
+ )
+ return
+ _default_responder(process, message)
+
+ SpawnHarness(monkeypatch, responder)
+ client = CodexAppServerClient()
+ await client.ensure_started()
+
+ with pytest.raises(CodexAppServerRPCError) as excinfo:
+ await client.realtime_list_voices("thread-1")
+ assert excinfo.value.code == -32601
+ await client.close()
+
+
+def _realtime_start_params(harness: SpawnHarness) -> dict[str, Any]:
+ return next(
+ frame["params"]
+ for frame in harness.processes[0].stdin.messages
+ if frame.get("method") == "thread/realtime/start"
+ )
+
+
+async def test_realtime_start_sends_audited_fields_when_set_and_version_trusted(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ harness = SpawnHarness(monkeypatch)
+ client = CodexAppServerClient()
+ await client.ensure_started()
+ client._trusted_binary_version = transport._SUPPORTED_CODEX_VERSION
+
+ await client.realtime_start(
+ "thread-1",
+ version="v3",
+ trusted_prompt="Voice contract",
+ realtime_start_instructions=" Speak as Jarvis. ",
+ realtime_end_instructions="Close the call politely.",
+ codex_responses_as_items=True,
+ codex_response_item_prefix="jarvis:",
+ codex_response_handoff_mode="items",
+ codex_response_handoff_channel_prefixes=(" delegate ", "handoff"),
+ )
+
+ params = _realtime_start_params(harness)
+ assert params["prompt"] == "Voice contract"
+ assert params["realtimeStartInstructions"] == "Speak as Jarvis."
+ assert params["realtimeEndInstructions"] == "Close the call politely."
+ assert params["codexResponsesAsItems"] is True
+ assert params["codexResponseItemPrefix"] == "jarvis:"
+ assert params["codexResponseHandoffMode"] == "items"
+ assert params["codexResponseHandoffChannelPrefixes"] == ["delegate", "handoff"]
+ assert params["delegationAckFiller"] is False
+ await client.close()
+
+
+async def test_realtime_start_omits_audited_fields_when_unset(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ harness = SpawnHarness(monkeypatch)
+ client = CodexAppServerClient()
+ await client.ensure_started()
+ client._trusted_binary_version = transport._SUPPORTED_CODEX_VERSION
+
+ await client.realtime_start("thread-1", version="v3", trusted_prompt="Contract")
+
+ params = _realtime_start_params(harness)
+ for field_name in (
+ "realtimeStartInstructions",
+ "realtimeEndInstructions",
+ "codexResponsesAsItems",
+ "codexResponseItemPrefix",
+ "codexResponseHandoffMode",
+ "codexResponseHandoffChannelPrefixes",
+ ):
+ assert field_name not in params
+ await client.close()
+
+
+async def test_realtime_start_never_sends_audited_fields_to_an_untrusted_binary(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ harness = SpawnHarness(monkeypatch)
+ client = CodexAppServerClient()
+ await client.ensure_started()
+ client._trusted_binary_version = transport._LEGACY_CODEX_VERSION
+
+ await client.realtime_start(
+ "thread-1",
+ version="v3",
+ trusted_prompt="Contract",
+ realtime_start_instructions="Speak as Jarvis.",
+ codex_response_handoff_mode="items",
+ )
+
+ params = _realtime_start_params(harness)
+ assert "realtimeStartInstructions" not in params
+ assert "codexResponseHandoffMode" not in params
+ assert "delegationAckFiller" not in params
+ await client.close()
+
+
+async def test_realtime_start_rejects_invalid_audited_field_values() -> None:
+ client = CodexAppServerClient()
+ invalid_requests: tuple[dict[str, Any], ...] = (
+ {"realtime_start_instructions": 42},
+ {"realtime_end_instructions": "x" * (transport._MAX_REALTIME_START_PROMPT_BYTES + 1)},
+ {"codex_responses_as_items": "yes"},
+ {"codex_response_item_prefix": 7},
+ {"codex_response_handoff_mode": ["items"]},
+ {"codex_response_handoff_channel_prefixes": "not-a-sequence"},
+ {"codex_response_handoff_channel_prefixes": ("ok", "")},
+ )
+
+ for kwargs in invalid_requests:
+ with pytest.raises(CodexSubscriptionUnavailable):
+ await client.realtime_start("thread-1", version="v3", **kwargs)
diff --git a/tests/unit/test_provider_spec.py b/tests/unit/test_provider_spec.py
index 65b3956dad..afd6525464 100644
--- a/tests/unit/test_provider_spec.py
+++ b/tests/unit/test_provider_spec.py
@@ -141,6 +141,19 @@ def test_provider_spec_is_frozen_dataclass() -> None:
raise AssertionError("ProviderSpec should be frozen")
+def test_public_fact_grounding_is_declared_as_a_capability() -> None:
+ """Self-hosted small-model surfaces ground facts without id branches."""
+ for provider_id in ("ollama", "local-openai", "local-realtime"):
+ spec = get_spec(provider_id)
+ assert spec is not None
+ assert spec.requires_public_fact_grounding is True
+
+ for provider_id in ("gemini", "openai", "openai-realtime", "gemini-live"):
+ spec = get_spec(provider_id)
+ assert spec is not None
+ assert spec.requires_public_fact_grounding is False
+
+
# ── New: per-provider credential help + billing classification ───────────────
diff --git a/tests/unit/ui/web/test_realtime_transport_warm_boot_hook.py b/tests/unit/ui/web/test_realtime_transport_warm_boot_hook.py
new file mode 100644
index 0000000000..b8c66e4f6e
--- /dev/null
+++ b/tests/unit/ui/web/test_realtime_transport_warm_boot_hook.py
@@ -0,0 +1,142 @@
+"""The web/headless boot path must warm the selected realtime transports.
+
+``realtime_warm_selected_transports`` pre-opens the transport of every
+explicitly selected realtime provider so its cold start (for a subscription
+transport: a spawned app-server plus a live account check) is not paid inside
+the user's first call. Its only caller used to be the desktop shell, which left
+``run.bat --headless`` and every browser-only install — headless Linux included
+— paying that cost on every first call.
+
+These tests pin the three properties the boot hook must have: it schedules the
+warm, it schedules it exactly once (the desktop shell warms under the same task
+name on the same loop), and a warm that raises never breaks startup.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import pytest
+from loguru import logger
+
+from jarvis.realtime import factory as realtime_factory
+from jarvis.ui.web import server as web_server
+
+
+class _StubServer:
+ """Only the two attributes the boot hook touches.
+
+ Constructing a real ``WebServer`` builds the whole FastAPI app; the hook
+ under test needs nothing but ``cfg`` and its own task slot, so the methods
+ are borrowed onto a stub instead.
+ """
+
+ _schedule_realtime_transport_warm = web_server.WebServer._schedule_realtime_transport_warm
+ _warm_realtime_transports = web_server.WebServer._warm_realtime_transports
+
+ def __init__(self, cfg: Any) -> None:
+ self.cfg = cfg
+ self._realtime_warm_task: asyncio.Task[None] | None = None
+
+
[email protected](autouse=True)
+def _no_boot_delay(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Drop the boot deferral so the tests assert behavior, not wall clock."""
+ monkeypatch.setattr(web_server, "REALTIME_WARM_BOOT_DELAY_S", 0.0)
+
+
+def _record_warm(monkeypatch: pytest.MonkeyPatch, calls: list[Any]) -> None:
+ async def _fake_warm(cfg: Any) -> None:
+ calls.append(cfg)
+
+ monkeypatch.setattr(realtime_factory, "realtime_warm_selected_transports", _fake_warm)
+
+
+async def test_boot_hook_schedules_the_warm_with_the_server_config(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls: list[Any] = []
+ _record_warm(monkeypatch, calls)
+ cfg = object()
+ srv = _StubServer(cfg)
+
+ srv._schedule_realtime_transport_warm()
+
+ assert srv._realtime_warm_task is not None
+ await srv._realtime_warm_task
+ assert calls == [cfg]
+
+
+async def test_repeated_scheduling_warms_exactly_once(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls: list[Any] = []
+ _record_warm(monkeypatch, calls)
+ srv = _StubServer(object())
+
+ srv._schedule_realtime_transport_warm()
+ first = srv._realtime_warm_task
+ srv._schedule_realtime_transport_warm()
+
+ assert srv._realtime_warm_task is first
+ assert first is not None
+ await first
+ assert len(calls) == 1
+
+
+async def test_a_live_warm_task_on_the_loop_is_not_duplicated(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The desktop shell warms under the same task name on the same loop."""
+ calls: list[Any] = []
+ _record_warm(monkeypatch, calls)
+ release = asyncio.Event()
+
+ async def _desktop_warm_worker() -> None:
+ await release.wait()
+
+ foreign = asyncio.create_task(_desktop_warm_worker(), name=web_server.REALTIME_WARM_TASK_NAME)
+ await asyncio.sleep(0)
+ srv = _StubServer(object())
+ try:
+ srv._schedule_realtime_transport_warm()
+ assert srv._realtime_warm_task is None
+ assert calls == []
+ finally:
+ release.set()
+ await foreign
+
+
+async def test_a_raising_warm_never_breaks_startup(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def _boom(cfg: Any) -> None:
+ raise RuntimeError("app-server spawn refused")
+
+ monkeypatch.setattr(realtime_factory, "realtime_warm_selected_transports", _boom)
+ records: list[str] = []
+ sink_id = logger.add(
+ lambda message: records.append(message.record["level"].name), level="WARNING"
+ )
+ srv = _StubServer(object())
+ try:
+ srv._schedule_realtime_transport_warm()
+ task = srv._realtime_warm_task
+ assert task is not None
+ await task
+ assert task.exception() is None
+ finally:
+ logger.remove(sink_id)
+
+ # AP-30: advisory, but never silent.
+ assert "WARNING" in records
+
+
+def test_scheduling_without_a_running_loop_is_a_quiet_no_op() -> None:
+ """A synchronous start (test harness, embedding host) must not raise."""
+ srv = _StubServer(object())
+
+ srv._schedule_realtime_transport_warm()
+
+ assert srv._realtime_warm_task is None