Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(realtime): hybrid tool mode — the live model calls every tool itself, the Tool Model is for computer use (ADR-0035)
Haraldbda4c50cabbc
diff --git a/docs/adr/0035-realtime-native-tools-except-computer-use.md b/docs/adr/0035-realtime-native-tools-except-computer-use.mdnew file mode 100644index 0000000000..0e8e9d3d49--- /dev/null+++ b/docs/adr/0035-realtime-native-tools-except-computer-use.md@@ -0,0 +1,198 @@+# ADR-0035 — Realtime native tools: the live model calls every Jarvis tool itself; the Tool Model is for computer use++**Status:** Accepted · **Date:** 2026-08-19 · **Phase:** Voice UX, realtime engine (every transport, every provider)++## Context++Maintainer mandate (2026-08-19): the realtime voice model must be allowed to+call *every* Jarvis tool directly — except computer use. The Tool Model+(`[brain.tool_model]`, historically `cu_model` / `[brain.computer_use]`) was+introduced for computer use and became the delegate for every action turn+along the way. That generalisation is what the user hears as "no+conversational flow": the live model is fast, the delegate is not.++Measured 2026-08-17..19 (flight recorder, 74 realtime turns, vertex-live):++- 55 of 74 turns involved a delegation (31 planner-forced, 11 empty-turn+ recoveries, 13 model-requested).+- First audio: native median **0.9 s**; delegated median **7.2 s**+ (p25 4.4 s, p75 12.4 s). Delegation alone: median 5.6 s.+- Every delegated brain round carries **18–46k input tokens** (system prompt,+ 87 tool schemas, context, history) — a 3–6 s floor before the delegate has+ said a word, even when it answers "Hello".+- Mis-routed conversation: "sprich mal mit mir" 3.2 s, "was würdest du+ empfehlen" 15.6 s, "Wer waren die 10 berühmtesten Wissenschaftler?" 5.6 s,+ "gucken, was morgen für ein Tag ist" 5.5 s (the same question without+ "gucken" answered natively in 0.9 s). <!-- i18n-allow: quoted live utterances -->++What the live model can do today: **nothing**. In the default `delegate` tool+mode it has exactly one function, `jarvis_action`, and `end_call`. The former+`direct` mode declared the whole dynamic catalog and was demoted to a+diagnostic opt-in (BUG-051 §5): a live reproduction on OpenAI Realtime showed+134 declarations, ~26k requested input tokens per response and a 40k TPM+limit — one turn before rate limiting. Today's catalog is 87 tools, ~78k+characters of declarations (~15–20k tokens under compaction). The execution+path for native calls — `RealtimeToolBridge` → `SupervisorToolGateway` /+`ToolExecutor`, risk tiers, two-turn voice confirm, STT/spawn/CU/research+guards — exists, is tested, and is unchanged by this ADR.++## Decision++One provider-neutral design (CLAUDE.md §3). The behaviour is the same on+every transport; transport-specific mechanisms are declared capabilities.++### 1. New default tool mode: `hybrid`++`[voice].realtime_tool_mode` gains the value `hybrid` and it becomes the+default. `delegate` and `direct` stay as explicit choices (unknown values+fail closed to `delegate`, as before).++In `hybrid` the live model receives **three kinds of functions**:++1. the supervisor tool catalog, **minus the computer-use vehicles**+ (`jarvis.brain.cu_gate.CU_VEHICLE_TOOL_NAMES`), rendered compactly (§4);+2. `jarvis_action` — narrowed to (a) operating the computer on screen+ (click, type, navigate inside application windows until a multi-step+ desktop task is done), (b) looking at the screen, and (c) any Jarvis+ capability for which the model has **no function of its own** (a tool+ dropped under the declaration budget, or one that connected after the+ session started);+3. `end_call`.++The role directive changes accordingly: *the user's world is reached with+your own functions, immediately; the screen is reached through+`jarvis_action`.* The announce-without-acting rule, the never-invent-results+rule, the several-targets rule and the spoken-reply rendering are unchanged.++### 2. What stays deterministic (delegate-owned) in `hybrid`++The planner (`jarvis/brain/turn_planner.py`) keeps classifying every final.+Its `requires_orchestrator` verdict no longer forces a delegation; it becomes+the turn-mode hint *"this turn needs the user's world — use your functions+now"*. A delegation is still forced for exactly these classes:++- **computer use:** an explicit harness mention ("computer use") or a desktop+ ACTION verb together with a desktop SURFACE noun (`cu_gate`+ `_DESKTOP_ACTION_RE` ∧ `_DESKTOP_SURFACE_RE`, i.e. narrower than "CU may+ run"); a bare action verb without a surface ("öffne Spotify") stays with+ the live model and its functions; <!-- i18n-allow: quoted utterance -->+- **screen look:** `TurnReason.SCREEN_CONTEXT` — the supervisor captures and+ attaches the one-shot image the live model cannot see;+- **public-fact grounding** when the active provider declares+ `requires_public_fact_grounding` (unchanged);+- **pending two-turn confirmations and open delegate questions**+ (`_brain_awaits_voice_confirm`, `_answers_open_delegate_question`) —+ these answer a turn the delegate already owns.++Everything else — Wiki, settings, connected data, media, skills, missions,+coding panes, files, CLI/MCP/plugin tools — is the live model's own call.++### 3. Slow native calls get the instant ack++A native function call is blocking on every current transport (ADR-0034 §2:+`NON_BLOCKING` is unsupported on Vertex and on the 3.1 Live model; OpenAI+waits for `function_call_output`). The ADR-0033 rule therefore applies to+native tool calls as to delegated turns: short work stays chatter-free for+`SHORT_GRACE_S` (3 s); a longer call gets ONE ack line from the closed pool+of the work class the planner assigned the turn (tool-activity pool as the+fallback), at most once per turn (`_native_tool_ack_after_grace`). Because+the live model is blocked on the call, the line rides the surface status+channel BUG-070 established — moving it into the live voice is the same+follow-up ADR-0034 §2.4 names. The result is spoken when it lands; a new+user turn while a call is open takes the ADR-0034 unblock path+(`_PENDING_TOOL_CALL_INTERIM_RESULT`) and the real result is parked.++### 4. Declaration budget and compaction++Declarations are rendered compactly for the live model: tool description+capped (default 450 characters, a sentence boundary preferred), parameter+descriptions capped (default 120 characters), schema otherwise intact.+`[voice].realtime_tool_declaration_budget_tokens` (default 20 000; estimate+= characters / 4) bounds the whole set. Over budget, tools are dropped in a+deterministic priority order until the set fits — longest declaration first+within the lowest-priority family (`agentic-ide-*` when no workspace is+open, then `cli_*`, then the rest) — and **every dropped name is logged at+session start**. A dropped tool is not lost: it is reachable through+`jarvis_action` (§1.2c), whose delegate keeps the full catalog.++A provider may declare `tool_declaration_budget_tokens` (capability, AP-21)+to lower the budget for its own wire: `openai-realtime` and `local-realtime`+(OpenAI protocol, TPM-metered per response) declare 8 000 unless the config+overrides it; `gemini-live` / `vertex-live` declare none (the setup is sent+once per connection). Transports with `supports_direct_tools = False` stay in+the deterministic delegate mode — nothing to declare on that wire.++### 5. Session-static declarations++Gemini Live cannot change tools mid-session (`supports_tool_updates =+False`): a CLI, MCP or plugin that connects during a call is reachable via+`jarvis_action` until the next session, and the existing warning says so.+OpenAI-protocol transports take the refreshed declarations through+`session.update` (unchanged).++### 6. Provider × mode matrix++| Transport | `hybrid` (default) | `delegate` | `direct` |+|---|---|---|---|+| `vertex-live`, `gemini-live` | catalog − CU, + `jarvis_action` (CU/screen/fallback), full budget | as today | full catalog, no `jarvis_action` (diagnostic) |+| `openai-realtime`, `local-realtime` | same set under the 8k-token provider budget; over-budget tools via `jarvis_action` (logged) | as today | as today (diagnostic) |+| `supports_direct_tools = False` (handoff) | degrades to `delegate` with the stated reason | as today | forced `delegate` (as today) |+| Classic pipeline, text chat, channels, CLI | unaffected — the brain already holds its tools; CU stays behind `computer_use` + its gate | — | — |++### 7. Observability++- Session start logs: mode, declared count, token estimate, dropped names.+- `REALTIME_TOOL_COMPLETED` latency span per native call (exists) gains+ `duration_ms`; postmortem counters `native_tool_calls`,+ `native_tool_failures`, `native_tool_denied`, `delegate_cu_dispatches`.+- Postmortem `delegate_*` counters keep their meaning; a drop in+ `delegate_deliveries_completed` with steady `turns_completed` is the+ expected signature of this change.++### 8. Guards++- Every descriptor of the live catalog passes the Gemini schema sanitizer+ (`_sanitize_declarations`) and the OpenAI declaration shape — a unit test+ iterates the seeded catalog plus the native tool plugins.+- `hybrid` session declares `jarvis_action` + `end_call` + catalog − CU; CU+ vehicle names are never declared natively (drift guard).+- The forced-delegation classifier: the live mis-routes above stay native;+ "klick auf den Button", "mach das Fenster zu", "mit computer use …" force+ delegation; "öffne Spotify" does not. <!-- i18n-allow: quoted utterances -->+- Budget: a synthetic 200-tool catalog is trimmed deterministically, dropped+ names logged, `jarvis_action` still declared.+- Parity: a transport with ``supports_direct_tools = False`` never sees the+ hybrid role directive — the session falls back to `delegate` before the+ first instruction is built (`test_hybrid_falls_back_to_delegate_when_a_provider_cannot_declare_tools`),+ so the existing handoff parity test keeps covering the only directive such+ a transport receives.++## Consequences++- Simple actions ("play X", "what is in my calendar", "remember that",+ "switch the provider") move from the 5–8 s delegate path to a 1–3 s native+ call. Conversation and world knowledge stay at ~1 s.+- Per-turn token usage on Gemini Live rises by the declaration block (on the+ order of 15k tokens of persistent context); that is the price of the+ mandate and it is paid once per connection in prefill, not per delegate+ round. On TPM-metered wires the budget keeps it bounded.+- Multi-step chains are now the live model's own rounds. Where the Flash+ live model chooses badly, the guards (STT hallucination, instructional,+ spawn, CU, research) still refuse; a wrong but allowed call is visible in+ the postmortem counters and the tool log. The Tool Model remains the+ orchestrator for computer use, where a wrong click costs the most.+- The delegate stays fully functional: empty-turn recovery (step 1 of the+ 2026-08-19 plan), planner precision (step 2) and a slimmer delegated prompt+ (step 3) still apply to the turns that delegate.++## Alternatives considered++- **Curated fast lane (6–10 native tools).** Smaller prompt, but a second,+ hand-maintained tool list drifts from the catalog and contradicts the+ mandate ("everything but computer use").+- **Keep delegate, make it faster.** Trimming the delegated prompt helps+ every delegation (and is still done), but the round trip through a second+ model keeps a 3 s floor plus readback; the fast path has to be native.+- **Full `direct` as default.** Declares CU to the live model and has no+ fallback for over-budget or late-connected tools; rejected for the same+ reason it was demoted in BUG-051.diff --git a/docs/architecture-overview.md b/docs/architecture-overview.mdindex 1b9932dd82..30e41b14a9 100644--- a/docs/architecture-overview.md+++ b/docs/architecture-overview.md@@ -47,7 +47,7 @@ subprocess flicker, audio host-API) are catalogued there.| **7 — Self-Mod (foundation + writer + tools)** | ✅ | `jarvis/core/self_mod/` (audit, errors, pending, registry, schema, writer). Three router-tier tools: `list_mutable_settings`, `get_config_value`, `set_config_value`. ADR + writeup in `docs/self_mod.md`. **7.5 skill authoring by voice/chat is the `create-skill` router tool** (2026-08-18; `pyproject.toml` → `jarvis.plugins.tool.create_skill:CreateSkillTool`, router-tier, `monitor`; one bounded brain call through `SkillCreatorService`, the same service behind `POST /api/skills/creator/*` and `jarvis skills create`). The older `spawn-skill-author` class is NOT wired (see `docs/LLM-CONTEXT.md` §25). Generated skills land as `state="draft"` and are never auto-activated (AP-15). || **Awareness A0–A5** | ✅ | `jarvis/awareness/` (state, story, salience, verdichter, working_set, episode, recall_store, watchers, probes). Router-tier tools `awareness-snapshot` (A1) + `awareness-recall` (A3). ADR-0009/0010/0012. Hard rule: **never on the voice critical path**. || **Wiki B0/B1/B2/B3/B5/B7/B8/B9** | ✅ | `jarvis/memory/wiki/` (curator, atomic_writer, page_repository, integration, session_rollup, voice_bridge, telemetry, scheduler). Three router-tier tools: `wiki-recall`, `wiki-page-read`, `wiki-ingest`. ADR-0013/0014/0015. B2 = `docs/obsidian-setup.md` + B9-Wizard. B3 = `WikiView.tsx` + 6-endpoint `wiki_routes.py` + `wiki_ws.py` live-reload. **B4 soft-disabled** 2026-05-17 via `[memory.legacy_curator] enabled = false` — legacy Curator package + `data/workspace/` snapshot stay on disk; Hart-Cut (vault migration + reader refactor + package delete) remains open. **B6 not started**. |-| **Realtime → Jarvis-Agents bridge** | ✅ canonical path live | Realtime emits the provider-neutral `jarvis_action`; `BrainManager` delegates heavy work through `spawn-worker`; `jarvis/missions/` owns worker selection, isolation, retries, Critic review, and Kontrollierer sign-off. MCP and marketplace tools are granted by capability, not exposed as worker harness names. |+| **Realtime → Jarvis-Agents bridge** | ✅ canonical path live | **Hybrid tool mode (ADR-0035, 2026-08-19, default):** the live model calls every router tool itself through `RealtimeToolBridge` (catalog minus the computer-use vehicles, compact declarations under `[voice].realtime_tool_declaration_budget_tokens`) and keeps ONE provider-neutral `jarvis_action` for computer use, screen looks and any capability it has no function for; the Tool Model runs only those delegated turns. `delegate` (one function, every action through the router Brain) and `direct` stay as explicit modes. `BrainManager` delegates heavy work through `spawn-worker`; `jarvis/missions/` owns worker selection, isolation, retries, Critic review, and Kontrollierer sign-off. MCP and marketplace tools are granted by capability, not exposed as worker harness names. || **Ack-Brain (pre-thinking)** | ✅ | `jarvis/brain/ack_brain/` — sub-second butler ACK before the deep brain replies. Gemini Flash Lite primary. UI preamble bubble. Suppress-if-fast gate at 2000ms (`[ack_brain].suppress_if_brain_faster_than_ms`). ADR-0014 (flash-brain). || **CLI catalog + terminal view** | ✅ | `jarvis/clis/` (catalog, installer, loader, prober, registry, risk_integration, usage_log) + `jarvis/terminal/` (cross-platform PTY via `terminal.backend.make_pty_backend` — ConPTY/`pywinpty` on Windows, `ptyprocess` on POSIX). Router tool `cli-tools` (virtual loader → one `cli_<name>` tool per connected CLI). UI views: `ClisView`, `TerminalView`. **`spawn-cli-worker` was REMOVED 2026-05-24** (dead entry point; heavy multi-step CLI work goes through `spawn-worker`, single-step through the `cli_<name>` tools — never re-add a CLI spawn tool, it is a D9 recursion vector, AP-5/AP-14). || **Board / Profile ("Knows-you" dashboard)** | ✅ | `jarvis/board/` (aggregator, store, achievements, evaluator, bio prompts, scheduler, `schema.sql`) → `data/board/personal.db`. Parses FlightRecorder JSONL into daily stats / personal records / 10 achievements + an anti-cliché AI-bio. Routes `board_routes.py` (`/api/board/*`) + `profile_routes.py`; views `BoardView.tsx`, `ProfileView.tsx`, `frontend/src/views/profile/`. Deterministic profile writes via the `update-profile` tool. Separate standalone service stub in `board-backend/` (FastAPI + Docker). CHANGELOG `v1.0.0-board`. |diff --git a/jarvis/brain/cu_gate.py b/jarvis/brain/cu_gate.pyindex fc963fb4c2..2eb44fcc27 100644--- a/jarvis/brain/cu_gate.py+++ b/jarvis/brain/cu_gate.py@@ -290,9 +290,44 @@ CU_BLOCKED_MODEL_FEEDBACK: str = ()+def is_explicit_computer_use_turn(user_text: str) -> bool:+ """Does this turn unmistakably ask Jarvis to OPERATE the desktop?++ The realtime engine's deterministic hand-over to the computer-use+ orchestrator (ADR-0035 §2). Deliberately NARROWER than+ :func:`llm_computer_use_allowed`, which decides whether a model-chosen+ ``computer_use`` call MAY run: there a bare action verb ("öffne Spotify")+ is enough, because the model already picked the vehicle. Here the+ orchestrator is imposed on the turn, at 5–45 s of latency, so only the+ strongest evidence counts —++ * the harness itself is named ("computer use"), or+ * a desktop ACTION verb and a desktop SURFACE noun appear together+ ("klick auf den Button", "mach das Fenster zu", "öffne den Browser und+ geh auf …"), and the turn is not a LOOK request. # i18n-allow: quoted utterances++ A bare verb without a surface ("öffne Spotify", "starte die+ Morgenroutine") stays with the live model and its own functions, which+ may still choose ``jarvis_action`` themselves. # i18n-allow: quoted utterances+ An empty turn is not an order.+ """+ normalized = _normalized(user_text).strip()+ if not normalized:+ return False+ if _EXPLICIT_HARNESS_RE.search(normalized):+ return True+ if _is_look_request(user_text):+ return False+ return bool(+ _DESKTOP_ACTION_RE.search(normalized)+ and _DESKTOP_SURFACE_RE.search(normalized)+ )++__all__ = ["CU_BLOCKED_MODEL_FEEDBACK","CU_VEHICLE_TOOL_NAMES","FOLLOW_UP_WINDOW_S",+ "is_explicit_computer_use_turn","llm_computer_use_allowed",]diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 38e1b0780a..2cc5bf020a 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -2649,14 +2649,27 @@ class VoiceConfig(BaseModel):# This must be selected explicitly: choosing the similarly named Realtime# provider never implies this classic-pipeline profile.profile: str = ""- # Realtime tool exposure. "delegate" (default) gives the live model one- # compact jarvis_action function and hands action turns to the key-aware- # router Brain. This keeps the persistent realtime prompt small; declaring- # the full dynamic catalog consumed ~26k input tokens per response and hit- # a 40k TPM limit after one turn. "direct" remains an explicit diagnostic- # opt-in. Read once per session; unknown values fail closed to the compact- # delegate mode.- realtime_tool_mode: str = "delegate"+ # Realtime tool exposure (ADR-0035, 2026-08-19). "hybrid" (default): the+ # live model calls every Jarvis tool itself — the supervisor catalog minus+ # the computer-use vehicles, rendered compactly under+ # ``realtime_tool_declaration_budget_tokens`` — plus one ``jarvis_action``+ # function for computer use, screen looks and any capability it has no+ # function for; the Tool Model runs only those delegated turns. "delegate":+ # the pre-ADR-0035 default — one compact jarvis_action function, every+ # action turn goes to the key-aware router Brain. "direct": the whole+ # dynamic catalog natively and no jarvis_action (diagnostic; a live+ # reproduction on a TPM-metered wire cost ~26k input tokens per response,+ # BUG-051). Read once per session; unknown values fail closed to+ # "delegate".+ realtime_tool_mode: str = "hybrid"+ # ADR-0035 §4: upper bound (tokens, estimated as characters / 4) for the+ # tool declarations a hybrid/direct session sends to the live model. Over+ # budget, declarations are dropped in a deterministic priority order and+ # every dropped name is logged; a dropped tool stays reachable through+ # jarvis_action. A provider may declare a LOWER budget for its own wire+ # (``tool_declaration_budget_tokens`` capability, AP-21); the smaller of+ # the two applies. 0 disables the bound.+ realtime_tool_declaration_budget_tokens: int = 20_000# ADR-0034 (2026-08-18). When the user opens a NEW turn while an earlier# order's provider function call (jarvis_action) is still unanswered on# the wire, the session answers that call at once with a closed "stilldiff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 6978c3925e..a5befb3056 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -1516,6 +1516,9 @@ class LatencyPhase(StrEnum):# model (detail carries class, delay and whether it is contextual).REALTIME_DELEGATE_BRIDGE_REQUESTED = "realtime_delegate_bridge_requested"REALTIME_DELEGATE_COMPLETED = "realtime_delegate_completed"+ # The provider closed a content-bearing turn without output and was asked+ # again natively before any Brain-chain recovery (2026-08-19).+ REALTIME_EMPTY_TURN_REASK = "realtime_empty_turn_reask"REALTIME_TOOL_COMPLETED = "realtime_tool_completed"REALTIME_SCRUB_CANCEL = "realtime_scrub_cancel"REALTIME_CANCEL = "realtime_cancel"@@ -1748,6 +1751,14 @@ class RealtimeSessionPostmortem(Event):delegate_delivery_duplicates_suppressed: int = 0#: In-flight delegates transferred from socket to process lifetime.delegate_deliveries_detached: int = 0+ #: ADR-0035 (hybrid tool mode): function calls the live model made+ #: itself through the realtime tool bridge, how many of them failed,+ #: how many a guard refused, and how many turns the deterministic+ #: computer-use classifier handed to the Tool Model.+ native_tool_calls: int = 0+ native_tool_failures: int = 0+ native_tool_denied: int = 0+ delegate_cu_dispatches: int = 0#: Provider generations discarded whole: they began right after a rendered#: readback with no new user input — the server answered a second boundary#: for the same request (BUG-143). Zero in a healthy call.diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex b0cd9eab44..abb6894fec 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -1380,6 +1380,13 @@ class OpenAIRealtimeProvider:# This is account/quota metadata, not a provider-name feature gate.credential_family = "openai"supports_realtime = True+ # ADR-0035 §4: this wire bills the whole context per response and is+ # TPM-metered (BUG-051: 134 declarations ≈ 26k tokens hit a 40k TPM tier+ # after one turn), so native declarations are bounded tighter here than+ # on a setup-once transport. Tools over the budget stay reachable through+ # jarvis_action; ``[voice].realtime_tool_declaration_budget_tokens`` can+ # only lower this further (the smaller of the two applies).+ tool_declaration_budget_tokens = 8_000implicit_usage_fallback_allowed = Trueinput_sample_rate = _INPUT_RATEoutput_sample_rate = _OUTPUT_RATE@@ -1596,6 +1603,9 @@ class LocalRealtimeProvider:name = "local-realtime"supports_realtime = True+ # Same OpenAI-protocol wire, same per-response context billing model —+ # and a self-hosted model is usually the smaller one (ADR-0035 §4).+ tool_declaration_budget_tokens = 8_000# Never an implicit stand-in: a self-hosted endpoint is a deliberate choice,# and quietly routing a call into one the user did not pick is the opposite# of what a local card is for.diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex b24f779bf8..a772dd1bcd 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -32,6 +32,10 @@ from jarvis.brain.action_honesty import (action_not_started_phrase,has_deferred_action_claim,)+from jarvis.brain.cu_gate import (+ CU_VEHICLE_TOOL_NAMES,+ is_explicit_computer_use_turn,+)from jarvis.brain.output_filter import scrub_for_voicefrom jarvis.brain.provider_test import (BAD_KEY,@@ -718,6 +722,102 @@ _DELEGATE_TURN_NORMAL_DIRECTIVE = ("knowledge yourself, right away.")+# --- Hybrid tool mode (ADR-0035, 2026-08-19) --------------------------------+# The live model holds the Jarvis tool catalog itself (minus the computer-use+# vehicles) AND one jarvis_action function. jarvis_action is narrowed to what+# the live model structurally cannot do on its own: operate the screen (the+# Tool Model orchestrates computer use), look at the screen (the supervisor+# attaches the image), and reach a capability it has no function for (dropped+# under the declaration budget, or connected after the session opened).+_DELEGATE_DECLARATION_HYBRID: dict[str, Any] = {+ "name": "jarvis_action",+ "description": (+ "Hand a request to the Jarvis orchestrator. Call it ONLY for: (1) "+ "operating the user's computer on screen — opening, clicking, typing, "+ "and navigating inside application windows or the browser until a "+ "multi-step desktop task is finished; (2) looking at the user's "+ "screen or a window and describing or reading it; (3) a Jarvis "+ "capability you have NO function of your own for. For everything "+ "else — the user's Wiki and memory, calendar, mail, music, settings, "+ "skills, missions, coding panes, files, connected services — call "+ "your own matching function directly instead. Never call this for "+ "general world knowledge, definitions, opinions, or smalltalk. Also "+ "call it to relay the user's answer to a pending orchestrator question."+ ),+ "parameters": {+ "type": "object",+ "properties": {+ "request": {+ "type": "string",+ "description": "The user's request in their own words.",+ }+ },+ "required": ["request"],+ },+}+_HYBRID_ROLE_DIRECTIVE = (+ "You have live function tools that act on the user's Jarvis app, their "+ "data, and their connected services, plus ONE orchestrator function, "+ "jarvis_action. The user's own world — their Wiki or personal memory, "+ "their own past ('do you remember', 'when did I'), their calendar, mail, "+ "music, files, settings, skills, background missions, coding panes, "+ "integrations, and system state — is reached with YOUR OWN functions, "+ "called immediately in the same response: you cannot see any of it "+ "yourself, so guessing is always wrong, and announcing a lookup without "+ "calling the function is a lie. Chain functions when a request needs "+ "several steps. jarvis_action is reserved for operating the computer on "+ "screen (it clicks, types, and navigates inside any application window "+ "until a multi-step desktop task is done), for looking at the screen, "+ "and for a Jarvis capability you have no function for; a round trip "+ "through it costs the user many seconds, so never use it for something "+ "one of your own functions does. General world knowledge is YOURS: "+ "public facts and figures, well-known people and companies, "+ "definitions, explanations, recommendations, opinions, and ordinary "+ "social chat. Answer those at once from your own knowledge, without any "+ "function call, even when you are only mostly sure — qualify briefly "+ "instead of calling anything. Never tell the user you lack a tool, an "+ "API, access, or permission for something in their world, and never "+ "propose manual workarounds instead of acting: call the function (again, "+ "with the user's correction folded in). The Jarvis-Agent spawn function "+ "is EXPLICIT-REQUEST ONLY: call it when the user themselves asks for an "+ "agent, a subagent, spawning, delegating, or background work — or has "+ "just said yes to your offer to start one; never on your own initiative, "+ "however heavy the topic sounds. Never claim that an action or mission "+ "was started, completed, saved, opened, or changed unless a successful "+ "function result explicitly supports that claim; a promise or an "+ "intention is not a result. When a request names SEVERAL targets, report "+ "ONLY the ones a result actually names as done. If a function returns a "+ "spoken confirmation question, ask the user and call the same function "+ "again only after a clear affirmative answer. jarvis_action returns "+ "spoken_reply: deliver that content in your own voice, in the "+ "conversation language, without reading JSON. For some turns the Jarvis "+ "orchestrator takes over and injects a trusted result on its own; a "+ "separate instruction tells you when, and only then do you wait instead "+ "of calling. Use end_call only when the user says goodbye."+)+_HYBRID_TOOLS_EXPECTED_DIRECTIVE = (+ "This current turn needs the user's own world (their data, settings, "+ "connected services, or an action on their behalf). Call the matching "+ "function of your own NOW, in this response, and answer from its result; "+ "do not answer from guesswork and do not merely announce a lookup. Use "+ "jarvis_action only if no function of yours covers it."+)+_HYBRID_DISCOURAGED_DIRECTIVE = (+ "This current turn looks like general world knowledge or ordinary "+ "conversation. Answer it directly from your own knowledge now, without "+ "calling any function. Call a function on this turn ONLY if the request "+ "actually needs the user's own world (their Wiki or personal memory, "+ "their own past, their files, apps, settings, connected services, or "+ "system state), performs a real action on their behalf, or explicitly "+ "asks you to look up, check, or verify current information you may only "+ "know in an outdated state."+)+_HYBRID_TURN_NORMAL_DIRECTIVE = (+ "Nothing about this turn changes how you work. Follow your standing role: "+ "the user's own world through your own functions, right away; the screen "+ "through jarvis_action; general world knowledge from yourself."+)+def _handoff_variant(directive: str) -> str:"""Render a function-vocabulary directive for a transport without tools.@@ -1140,6 +1240,32 @@ def _direct_tool_result_retry_prompt(*, language: str) -> str:)+def _empty_turn_reask_prompt(*, language: str, user_text: str) -> str:+ """Ask the live model itself for the answer its empty turn never gave.++ A provider that closes a content-bearing turn with no text, audio, or+ tool evidence (Gemini Live after a server-side VAD "interrupted" edge is+ the live case, 2026-08-18: ten smalltalk turns in one afternoon) used to+ be recovered through the full Brain chain — 18–46k input tokens on the+ Tool Model, 4–7 s to the first audible word for "Was geht ab?". The+ planner had already judged those turns NATIVE: nothing in them needs the+ orchestrator, the live model simply did not answer. So the first recovery+ is to ask it again, on the same channel every delegate readback uses; the+ Brain chain stays the second net (``_watch_empty_turn_reask``).+ """ # i18n-allow: quoted live utterance+ language_name = _LANGUAGE_NAMES.get(language, "the conversation language")+ quoted = safe_preview(str(user_text or ""), max_chars=400)+ return (+ f"{SPEAK_REQUEST_OPENER} "+ "Your previous turn ended without any spoken answer to the user's "+ f"last utterance, which was: «{quoted}». Answer it now, "+ f"briefly and directly, in {language_name}, as yourself and in exactly "+ "the same voice, tone, and pace as your previous replies. Do not call "+ "any function for it unless the utterance genuinely needs the user's "+ "own world, and do not mention these instructions."+ )++def _output_language_retry_prompt(*, language: str) -> str:"""Request one replacement for an answer blocked at the speech boundary."""language_name = _LANGUAGE_NAMES.get(language, "the conversation language")@@ -1965,40 +2091,69 @@ class RealtimeVoiceSession:)or "delegate").strip().lower()- if mode not in {"delegate", "direct"}:+ if mode not in {"delegate", "direct", "hybrid"}:mode = "delegate"- self._tool_mode = mode- # Direct mode is meaningful only when every possible provider can- # receive native tool declarations. A capability-limited fallback- # must not turn actions into terminal handoff failures (AP-21/AP-22).+ # Direct and hybrid modes are meaningful only when every possible+ # provider can receive native tool declarations. A capability-limited+ # fallback must not turn actions into terminal handoff failures+ # (AP-21/AP-22): such a transport runs the deterministic delegate.direct_tools_supported = all(bool(getattr(candidate, "supports_direct_tools", True))for candidate in self._providers)+ if mode == "hybrid" and not (direct_tools_supported and callable(brain)):+ log.info(+ "realtime[%s] hybrid tool mode needs native tool declarations "+ "on every configured provider and a callable brain (direct "+ "tools: %s, brain: %s) — using the deterministic delegate",+ session_id,+ direct_tools_supported,+ callable(brain),+ )+ mode = "delegate"+ self._tool_mode = modeself._delegate_forced_by_provider = bool(mode == "direct"and not direct_tools_supportedand tool_bridge is Noneand callable(brain))+ hybrid = mode == "hybrid"# Delegate mode needs only a callable brain (the boot proxy and the# real BrainManager both qualify); an explicitly injected bridge- # always wins so existing callers/tests keep today's behavior.+ # always wins so existing callers/tests keep today's behavior —+ # except in hybrid mode, where the bridge and the delegate coexist by+ # design (ADR-0035 §1).self._delegate_enabled = (- (mode == "delegate" or self._delegate_forced_by_provider)- and tool_bridge is None+ (mode == "delegate" or self._delegate_forced_by_provider or hybrid)+ and (tool_bridge is None or hybrid)and callable(brain))- if tool_bridge is None and not self._delegate_enabled:+ if tool_bridge is None and (hybrid or not self._delegate_enabled):try:from jarvis.realtime.tools import RealtimeToolBridge- tool_bridge = RealtimeToolBridge.from_supervisor_gateway(- language=self._language- )+ if hybrid:+ tool_bridge = RealtimeToolBridge.from_supervisor_gateway(+ language=self._language,+ excluded_tool_names=CU_VEHICLE_TOOL_NAMES,+ compact=True,+ declaration_budget_chars=self._declaration_budget_chars(),+ )+ else:+ tool_bridge = RealtimeToolBridge.from_supervisor_gateway(+ language=self._language+ )except Exception: # noqa: BLE001 — conversation still works without toolslog.warning("Realtime tool bridge is unavailable", exc_info=True)self._tool_bridge = tool_bridge+ # ADR-0035 §3/§7: native tool calls get their own ack watchdog and+ # counters; the turn id keeps the ack to one line per turn.+ self._native_tool_calls = 0+ self._native_tool_failures = 0+ self._native_tool_denied = 0+ self._delegate_cu_dispatches = 0+ self._native_ack_turn_id = ""self._delegate_tasks: set[asyncio.Task[None]] = set()self._delegate_tasks_by_turn: dict[str, set[asyncio.Task[None]]] = {}self._delegate_states_by_turn: dict[str, _DelegateTurnState] = {}@@ -2006,6 +2161,12 @@ class RealtimeVoiceSession:# task — it must never hold a turn open, defer a VAD edge, or refuse# an announcement on behalf of work that is merely a sleeping timer.self._delegate_bridge_task: asyncio.Task[None] | None = None+ # Empty-turn re-ask (2026-08-19): the turn that was asked again+ # natively after the provider closed it without output, and the+ # watchdog that falls back to the Brain chain if the re-ask stays+ # mute too. One re-ask per turn; the id is what makes it one.+ self._empty_turn_reask_turn_id = ""+ self._empty_turn_reask_task: asyncio.Task[None] | None = None# The tool the delegated turn is ACTUALLY running (ToolExecutor's# ActionProposed on the bus) — grounds the +8 s progress line# ("still searching" / "still on the screen") instead of a filler.@@ -2061,7 +2222,26 @@ class RealtimeVoiceSession:session_id,bool(callable(brain)),)- if self._delegate_enabled:+ if self._delegate_enabled and hybrid and tool_bridge is not None:+ dropped = tuple(getattr(tool_bridge, "dropped_names", ()) or ())+ log.info(+ "realtime[%s] tool mode: hybrid — %d native tools (~%d tokens, "+ "%d over-budget name(s) reachable via jarvis_action%s), "+ "computer use via jarvis_action on the Tool Model",+ session_id,+ len(tool_bridge.declarations),+ int(getattr(tool_bridge, "declaration_chars", 0) or 0) // 4,+ len(dropped),+ f": {', '.join(dropped)}" if dropped else "",+ )+ elif self._delegate_enabled and hybrid:+ log.warning(+ "realtime[%s] tool mode: hybrid requested but no supervisor "+ "tool gateway is ready — only jarvis_action is declared; the "+ "delegate carries every action this session",+ session_id,+ )+ elif self._delegate_enabled:log.info("realtime[%s] tool mode: delegate — one action function ""backed by the router brain",@@ -4232,6 +4412,25 @@ class RealtimeVoiceSession:# localized uncertainty instead of letting the# native model invent the public fact.self._delegate_required_for_turn = True+ # ADR-0035 §2: in hybrid mode the live model holds the+ # functions, so a planner "orchestrator" verdict steers+ # it to call them (tools_expected) instead of forcing+ # the delegate. The delegate is still imposed for what+ # the live model structurally cannot do — operate the+ # screen (explicit computer use), look at it (screen+ # context), ground a public fact on a provider that+ # declares it, and answer a turn the delegate already+ # owns (pending confirm / open question).+ hybrid_turn = self._hybrid_enabled+ computer_use_turn = bool(+ hybrid_turn+ and self._last_user_text+ and is_explicit_computer_use_turn(self._last_user_text)+ )+ planner_forces_delegate = bool(+ turn_plan.requires_orchestrator+ and (not hybrid_turn or screen_context_turn)+ )if (self._last_user_textand deterministic_delegate_available@@ -4244,11 +4443,14 @@ class RealtimeVoiceSession:):self._delegate_required_for_turn = (self._delegate_required_for_turn- or turn_plan.requires_orchestrator+ or planner_forces_delegate+ or computer_use_turnor ambiguous_action_defaultor self._brain_awaits_voice_confirm()or self._answers_open_delegate_question())+ if computer_use_turn and self._delegate_required_for_turn:+ self._delegate_cu_dispatches += 1if wait_query_claimed:# The orchestrator answered this turn; no# dispatch, no grounding, no provider response.@@ -4268,6 +4470,11 @@ class RealtimeVoiceSession:not turn_plan.requires_orchestratorand not ambiguous_action_default),+ "tools_expected": bool(+ hybrid_turn+ and turn_plan.requires_orchestrator+ and not self._delegate_required_for_turn+ ),}turn_tool_directive = self._tool_directive(**turn_mode_kwargs@@ -7386,6 +7593,124 @@ class RealtimeVoiceSession:)return False+ # First net: ask the live model itself (a native turn the planner left+ # native has nothing the Brain chain could add except latency). The+ # Brain chain is the second net — on a second empty boundary, or when+ # the re-ask never produces a response at all.+ if await self._reask_provider_for_empty_turn(turn_id):+ return True+ self._recover_empty_turn_via_brain(turn_id)+ return True++ async def _reask_provider_for_empty_turn(self, turn_id: str) -> bool:+ """Ask the live model again before paying a Brain-chain recovery.++ Fires at most ONCE per turn, and only for a turn the planner routed+ natively with no grounding, no pending confirmation and no open+ delegate question — exactly the turns on which the orchestrator has+ nothing to contribute. The request travels on the provider's trusted+ text channel (the same wire as every delegate readback), so it is+ provider-neutral: a transport without ``send_text`` simply skips to+ the Brain chain. Returns True when the re-ask was sent; the watchdog+ then owns the turn until audio arrives or the readback budget runs+ out.+ """+ if not turn_id or self._empty_turn_reask_turn_id == turn_id:+ return False+ send_text = getattr(self._session, "send_text", None)+ if not callable(send_text):+ return False+ if self._active_requires_public_fact_grounding:+ return False+ if self._brain_awaits_voice_confirm() or self._answers_open_delegate_question():+ return False+ try:+ plan = self._plan_turn(self._last_user_text)+ except Exception: # noqa: BLE001 — a planner fault must not block recovery+ return False+ if plan.requires_public_fact_grounding:+ return False+ if plan.requires_orchestrator and (+ not self._hybrid_enabled or TurnReason.SCREEN_CONTEXT in plan.reasons+ ):+ # Delegate mode: an orchestrator turn is the delegate's. Hybrid+ # mode (ADR-0035 §2): the live model holds the functions, so only+ # what it structurally cannot do skips the re-ask.+ return False+ if self._hybrid_enabled and is_explicit_computer_use_turn(self._last_user_text):+ return False+ self._empty_turn_reask_turn_id = turn_id+ self._drop_provider_output_until_new_response = False+ try:+ await send_text(+ _empty_turn_reask_prompt(+ language=self._language, user_text=self._last_user_text+ )+ )+ except Exception: # noqa: BLE001 — the Brain chain runs instead+ log.warning(+ "realtime[%s] empty-turn re-ask could not be sent; recovering "+ "through the Brain chain",+ self.session_id,+ exc_info=True,+ )+ return False+ log.warning(+ "realtime[%s] provider completed turn %s without text, audio, or "+ "tool evidence; asked the live model again (Brain chain on a "+ "second miss)",+ self.session_id,+ turn_id,+ )+ self._mark_latency_named(+ "REALTIME_EMPTY_TURN_REASK",+ detail=f"turn={turn_id};budget_s={self._delegate_readback_budget_s():.1f}",+ )+ previous = self._empty_turn_reask_task+ if previous is not None and not previous.done():+ previous.cancel()+ self._empty_turn_reask_task = asyncio.create_task(+ self._watch_empty_turn_reask(turn_id)+ )+ return True++ async def _watch_empty_turn_reask(self, turn_id: str) -> None:+ """Fall back to the Brain chain when the re-asked provider stays mute."""+ deadline = time.monotonic() + self._delegate_readback_budget_s()+ try:+ while True:+ if (+ self._ended+ or self._session is None+ or self._turn_id != turn_id+ or turn_id in self._delegate_turns+ or self._user_speech_active+ ):+ return+ if (+ self._output_active+ or self._output_samples_sent > 0+ or "".join(self._output_transcript).strip()+ ):+ return+ if time.monotonic() >= deadline:+ break+ await asyncio.sleep(_DELEGATE_READBACK_POLL_S)+ except asyncio.CancelledError:+ raise+ if turn_id in self._delegate_turns or self._turn_id != turn_id:+ return+ log.warning(+ "realtime[%s] the re-asked provider rendered nothing within %.1fs "+ "for turn %s; recovering through the Brain chain",+ self.session_id,+ self._delegate_readback_budget_s(),+ turn_id,+ )+ self._recover_empty_turn_via_brain(turn_id)++ def _recover_empty_turn_via_brain(self, turn_id: str) -> None:+ """Second net: the deterministic delegate answers the empty turn."""self._delegate_required_for_turn = Trueturn_state = _DelegateTurnState(deterministic=True,@@ -7405,7 +7730,6 @@ class RealtimeVoiceSession:turn_id,)self._start_deterministic_delegate(self._last_user_text)- return Truedef _direct_tool_fallback_text(self) -> tuple[str, bool]:"""Return one speakable result without serializing raw tool payloads."""@@ -7792,7 +8116,53 @@ class RealtimeVoiceSession:self._output_language_retry_requested = Falseself._embedded_silence_ms = 0.0+ @property+ def _hybrid_enabled(self) -> bool:+ """ADR-0035: the live model holds the catalog AND jarvis_action.++ ``getattr`` on purpose: directive tests build bare sessions without+ ``__init__`` and read the role/mode lines, which must then mean the+ classic delegate wording.+ """+ return bool(+ getattr(self, "_tool_mode", "") == "hybrid"+ and getattr(self, "_delegate_enabled", False)+ )++ def _declaration_budget_chars(self) -> int:+ """The native declaration budget in characters (ADR-0035 §4).++ The smaller of the config bound and every candidate provider's own+ declared budget (``tool_declaration_budget_tokens``, a capability —+ AP-21); 0 = unbounded.+ """+ configured = int(+ getattr(+ getattr(self._config, "voice", None),+ "realtime_tool_declaration_budget_tokens",+ 20_000,+ )+ or 0+ )+ budgets = [configured] if configured > 0 else []+ for candidate in self._providers:+ declared = int(+ getattr(candidate, "tool_declaration_budget_tokens", 0) or 0+ )+ if declared > 0:+ budgets.append(declared)+ if not budgets:+ return 0+ return min(budgets) * 4+def _declared_tools(self) -> tuple[dict[str, Any], ...]:+ if self._hybrid_enabled:+ native = (+ self._tool_bridge.declarations+ if self._tool_bridge is not None+ else ()+ )+ return (*native, _DELEGATE_DECLARATION_HYBRID, _END_CALL_DECLARATION)if self._delegate_enabled:return (_DELEGATE_DECLARATION, _END_CALL_DECLARATION)if self._tool_bridge is not None:@@ -7809,6 +8179,8 @@ class RealtimeVoiceSession:target = provider if provider is not None else self._providerif not bool(getattr(target, "supports_direct_tools", True)):return _DELEGATE_ROLE_DIRECTIVE_HANDOFF+ if self._hybrid_enabled:+ return _HYBRID_ROLE_DIRECTIVEreturn _DELEGATE_ROLE_DIRECTIVEdef _turn_mode_directive(@@ -7817,6 +8189,7 @@ class RealtimeVoiceSession:delegate_required: bool = False,action_pending: bool = False,delegate_discouraged: bool = False,+ tools_expected: bool = False,provider: Any = None,) -> str:"""The ONE turn-scoped line, prefixed so it retracts the previous one.@@ -7826,20 +8199,34 @@ class RealtimeVoiceSession:empty: on an append-only steering channel an empty directive retractsnothing, so the previous turn's "do not answer at all" would keepstanding over the model (RT-08).++ ``tools_expected`` is the hybrid-mode reading of a planner+ ``requires_orchestrator`` verdict (ADR-0035 §2): the live model holds+ the functions, so the turn is steered to call them now instead of+ being handed to the delegate."""if not self._delegate_enabled:return ""+ target = provider if provider is not None else self._provider+ native_tools = bool(getattr(target, "supports_direct_tools", True))+ hybrid = self._hybrid_enabled and native_toolsif delegate_required:body = _DELEGATE_REQUIRED_DIRECTIVEelif action_pending:body = _DELEGATE_PENDING_DIRECTIVE+ elif hybrid and tools_expected:+ body = _HYBRID_TOOLS_EXPECTED_DIRECTIVEelif delegate_discouraged:- target = provider if provider is not None else self._provider- body = (- _DELEGATE_DISCOURAGED_DIRECTIVE- if bool(getattr(target, "supports_direct_tools", True))- else _DELEGATE_DISCOURAGED_DIRECTIVE_HANDOFF- )+ if hybrid:+ body = _HYBRID_DISCOURAGED_DIRECTIVE+ else:+ body = (+ _DELEGATE_DISCOURAGED_DIRECTIVE+ if native_tools+ else _DELEGATE_DISCOURAGED_DIRECTIVE_HANDOFF+ )+ elif hybrid:+ body = _HYBRID_TURN_NORMAL_DIRECTIVEelse:body = _DELEGATE_TURN_NORMAL_DIRECTIVEreturn f"{_TURN_MODE_PREFIX}{body}"@@ -7850,6 +8237,7 @@ class RealtimeVoiceSession:delegate_required: bool = False,action_pending: bool = False,delegate_discouraged: bool = False,+ tools_expected: bool = False,provider: Any = None,) -> str:"""Role plus this turn's mode line, for the full instruction block.@@ -7865,6 +8253,7 @@ class RealtimeVoiceSession:delegate_required=delegate_required,action_pending=action_pending,delegate_discouraged=delegate_discouraged,+ tools_expected=tools_expected,provider=provider,)return f"{role}\n\n{mode}" if mode else role@@ -9283,6 +9672,15 @@ class RealtimeVoiceSession:{"success": False, "error": "Tool call is not available."},)return+ self._native_tool_calls += 1+ started_at = time.monotonic()+ # ADR-0035 §3: a native call blocks the live model until its result+ # arrives, so a slow one gets the instant-ack treatment — one line+ # after the short grace, at most once per turn.+ ack_task = asyncio.create_task(+ self._native_tool_ack_after_grace(self._turn_id, wire_name),+ name=f"rt-native-tool-ack-{self.session_id}",+ )try:execute = self._tool_bridge.executeexecute_kwargs: dict[str, Any] = {@@ -9312,18 +9710,92 @@ class RealtimeVoiceSession:"success": False,"error": "The tool failed safely and was not completed.",}+ finally:+ if not ack_task.done():+ ack_task.cancel()if result.get("success"):self._executed_tool_names.add(original_name)+ elif result.get("confirmation_required"):+ pass # a pending confirmation is neither a failure nor a denial+ elif "not run" in str(result.get("error", "")) or "not available" in str(+ result.get("error", "")+ ):+ self._native_tool_denied += 1+ else:+ self._native_tool_failures += 1self._direct_tool_results.append((original_name, dict(result)))self._mark_latency_named("REALTIME_TOOL_COMPLETED",detail=(- f"tool={original_name};success={bool(result.get('success'))}"+ f"tool={original_name};success={bool(result.get('success'))};"+ f"duration_ms={round((time.monotonic() - started_at) * 1000)}"),)self._drop_provider_output_until_new_response = Falseawait self._session.send_tool_result(call_id, wire_name, result)+ async def _native_tool_ack_after_grace(self, turn_id: str, wire_name: str) -> None:+ """Speak one instant-ack line when a native tool call outlives the grace.++ The live model is blocked on the function call (ADR-0034 §2), so the+ line cannot ride the live voice; it takes the surface status channel+ BUG-070 established, in the turn's language, from the closed pool for+ the work class the planner assigned the turn (a tool name falls back+ to the tool-activity pools). One line per turn; cancelled by the+ result.+ """+ try:+ await asyncio.sleep(_INSTANT_ACK_GRACE_S)+ except asyncio.CancelledError:+ raise+ if (+ self._ended+ or self._session is None+ or not turn_id+ or self._turn_id != turn_id+ or self._native_ack_turn_id == turn_id+ or self._user_speech_active+ or self._output_active+ or self._output_samples_sent > 0+ ):+ return+ self._native_ack_turn_id = turn_id+ line = ""+ try:+ plan = plan_instant_ack(+ self._plan_turn(self._last_user_text), self._last_user_text+ )+ if plan is not None:+ line = pick_instant_ack_text(+ plan.work_class, self._language, agent_brand=self._agent_brand()+ )+ except Exception: # noqa: BLE001 — the ack is best-effort+ log.debug("realtime[%s] native-tool ack plan failed", self.session_id, exc_info=True)+ if not line:+ activity = classify_tool_activity(wire_name)+ line = pick_progress_text(activity, self._language)+ if not line:+ line = _pick_delegate_bridge_text(self._language)+ if not line:+ return+ log.info(+ "realtime[%s] native tool %s still running after %.1fs; speaking "+ "the instant ack on the surface channel",+ self.session_id,+ wire_name,+ _INSTANT_ACK_GRACE_S,+ )+ self._mark_latency_named(+ "REALTIME_DELEGATE_BRIDGE_REQUESTED",+ detail=f"kind=native_tool;tool={wire_name}",+ )+ try:+ await self._send_json(+ self._surface_speech_message(line, spoken_kind=SPOKEN_KIND_PROGRESS)+ )+ except Exception: # noqa: BLE001 — a failed ack must not hurt the call+ log.debug("realtime[%s] native-tool ack send failed", self.session_id, exc_info=True)+async def _handle_end_call(self, event: Any) -> None:if self._session is not None and self._session_takes_tool_results():try:@@ -11067,6 +11539,10 @@ class RealtimeVoiceSession:self._delegate_delivery_duplicates_suppressed),delegate_deliveries_detached=self._delegate_deliveries_detached,+ native_tool_calls=self._native_tool_calls,+ native_tool_failures=self._native_tool_failures,+ native_tool_denied=self._native_tool_denied,+ delegate_cu_dispatches=self._delegate_cu_dispatches,stale_generations_dropped=self._stale_generations_dropped,opening_responses_bounded=diag.get("opening_responses_bounded", 0),self_dialogue_rebuilds=diag.get("self_dialogue_rebuilds", 0),@@ -11194,6 +11670,12 @@ class RealtimeVoiceSession:):self._delegate_bridge_task.cancel()self._delegate_bridge_task = None+ if (+ self._empty_turn_reask_task is not None+ and not self._empty_turn_reask_task.done()+ ):+ self._empty_turn_reask_task.cancel()+ self._empty_turn_reask_task = Noneif self._action_proposed_subscribed and self._bus is not None:try:from jarvis.core.events import ActionProposeddiff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.pyindex 5b98a47e6c..df59b7a751 100644--- a/jarvis/realtime/tools.py+++ b/jarvis/realtime/tools.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport hashlibimport json+import loggingimport refrom dataclasses import dataclassfrom typing import Any, cast@@ -42,6 +43,26 @@ _VALID_WIRE_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")_MAX_DESCRIPTION_CHARS = 4_000_MAX_ARGUMENT_CHARS = 32_000_MAX_RESULT_CHARS = 8_000+# ADR-0035 §4 compact rendering for the live model: router-brain tool+# descriptions run to 500-2 900 characters of usage prose written for a+# text model with a 12-round loop; the live model needs the purpose and the+# parameters, and the ToolExecutor enforces the risk rules regardless. A+# sentence boundary is preferred when cutting.+COMPACT_DESCRIPTION_CHARS = 450+COMPACT_PARAMETER_DESCRIPTION_CHARS = 120+#: Rough token estimate for the declaration budget (characters per token).+CHARS_PER_TOKEN = 4+# Drop order when a declaration set exceeds its budget (ADR-0035 §4): the+# lowest-priority family goes first, longest declaration first inside it.+# Dropped tools stay reachable through ``jarvis_action``. Families are+# matched on the tool name; anything unmatched is the last to go.+_BUDGET_DROP_FAMILIES: tuple[tuple[str, re.Pattern[str]], ...] = (+ ("agentic-ide", re.compile(r"^agentic[-_]ide[-_]")),+ ("cli", re.compile(r"^cli_")),+ ("mcp", re.compile(r"^mcp__|/")),+)++log = logging.getLogger(__name__)def _wire_name(name: str) -> str:@@ -79,6 +100,79 @@ def _bounded_result(success: bool, output: Any, error: str | None) -> dict[str,}+def _compact_text(text: str, limit: int) -> str:+ """Cut ``text`` to ``limit`` characters, preferring a sentence boundary."""+ value = str(text or "").strip()+ if len(value) <= limit:+ return value+ cut = value[:limit]+ boundary = max(cut.rfind(". "), cut.rfind(".\n"), cut.rfind("! "), cut.rfind("? "))+ if boundary >= limit // 2:+ return cut[: boundary + 1].strip()+ return cut.rstrip() + "…"+++def _compact_schema(schema: Any, parameter_description_limit: int) -> Any:+ """Return ``schema`` with every nested ``description`` capped; structure intact."""+ if isinstance(schema, dict):+ compacted: dict[str, Any] = {}+ for key, value in schema.items():+ if key == "description" and isinstance(value, str):+ compacted[key] = _compact_text(value, parameter_description_limit)+ else:+ compacted[key] = _compact_schema(value, parameter_description_limit)+ return compacted+ if isinstance(schema, list):+ return [_compact_schema(item, parameter_description_limit) for item in schema]+ return schema+++def _declaration_size(declaration: dict[str, Any]) -> int:+ try:+ return len(json.dumps(declaration, ensure_ascii=False, default=str))+ except Exception: # noqa: BLE001 - an unserializable schema counts as large+ return _MAX_DESCRIPTION_CHARS+++def _drop_rank(name: str) -> int:+ """Lower rank = dropped earlier (ADR-0035 §4 family order)."""+ for rank, (_family, pattern) in enumerate(_BUDGET_DROP_FAMILIES):+ if pattern.search(name):+ return rank+ return len(_BUDGET_DROP_FAMILIES)+++def _apply_declaration_budget(+ rendered: list[tuple[str, dict[str, Any]]],+ budget_chars: int,+) -> tuple[list[tuple[str, dict[str, Any]]], list[str]]:+ """Trim ``rendered`` (name, declaration) pairs to ``budget_chars``.++ Deterministic: the lowest-priority family goes first, the longest+ declaration first inside it, ties by name. Returns (kept in the original+ order, dropped names in drop order). ``budget_chars <= 0`` keeps all.+ """+ if budget_chars <= 0:+ return list(rendered), []+ sizes = {name: _declaration_size(decl) for name, decl in rendered}+ total = sum(sizes.values())+ if total <= budget_chars:+ return list(rendered), []+ drop_order = sorted(+ (name for name, _decl in rendered),+ key=lambda name: (_drop_rank(name), -sizes[name], name),+ )+ dropped: list[str] = []+ for name in drop_order:+ if total <= budget_chars:+ break+ dropped.append(name)+ total -= sizes[name]+ dropped_set = set(dropped)+ kept = [(name, decl) for name, decl in rendered if name not in dropped_set]+ return kept, dropped++@dataclass(slots=True)class _PendingConfirmation:trace_id: UUID@@ -97,12 +191,26 @@ class RealtimeToolBridge:gateway: SupervisorToolGateway | None = None,language: str,tools_source: Any = None,+ excluded_tool_names: frozenset[str] | set[str] | None = None,+ compact: bool = False,+ declaration_budget_chars: int = 0,) -> None:+ """``excluded_tool_names`` are never declared AND never executed by+ this bridge (ADR-0035: the computer-use vehicles stay delegate-only).+ ``compact`` renders descriptions for the live model (ADR-0035 §4);+ ``declaration_budget_chars`` (0 = unbounded) trims the set in the+ documented priority order and records the dropped names."""self._tools = dict(tools or {})self._tools_source = tools_sourceself._executor = executorself._gateway = gatewayself._language = language+ self._excluded_tool_names: frozenset[str] = frozenset(+ str(name) for name in (excluded_tool_names or ())+ )+ self._compact = bool(compact)+ self._declaration_budget_chars = max(0, int(declaration_budget_chars or 0))+ self._dropped_names: tuple[str, ...] = ()self._descriptors: dict[str, SupervisorToolDescriptor] = (self._read_descriptors())@@ -114,13 +222,24 @@ class RealtimeToolBridge:@classmethoddef from_supervisor_gateway(- cls, *, language: str+ cls,+ *,+ language: str,+ excluded_tool_names: frozenset[str] | set[str] | None = None,+ compact: bool = False,+ declaration_budget_chars: int = 0,) -> RealtimeToolBridge | None:"""Build from the safety gateway without requiring a classic brain call."""gateway = runtime_refs.get_supervisor_tool_gateway()if gateway is None or not gateway.catalog():return None- return cls(gateway=gateway, language=language)+ return cls(+ gateway=gateway,+ language=language,+ excluded_tool_names=excluded_tool_names,+ compact=compact,+ declaration_budget_chars=declaration_budget_chars,+ )@classmethoddef from_brain(cls, _brain: Any, *, language: str) -> RealtimeToolBridge | None:@@ -130,6 +249,19 @@ class RealtimeToolBridge:def _read_descriptors(self,tools_override: dict[str, Any] | None = None,+ ) -> dict[str, SupervisorToolDescriptor]:+ descriptors = self._read_descriptors_unfiltered(tools_override)+ if not self._excluded_tool_names:+ return descriptors+ return {+ name: item+ for name, item in descriptors.items()+ if name not in self._excluded_tool_names+ }++ def _read_descriptors_unfiltered(+ self,+ tools_override: dict[str, Any] | None = None,) -> dict[str, SupervisorToolDescriptor]:if self._gateway is not None:try:@@ -158,29 +290,73 @@ class RealtimeToolBridge:)return descriptors+ def _render_declaration(+ self, name: str, descriptor: SupervisorToolDescriptor+ ) -> dict[str, Any]:+ if not self._compact:+ return {+ "name": name,+ "description": descriptor.description[:_MAX_DESCRIPTION_CHARS],+ "parameters": descriptor.input_schema,+ }+ return {+ "name": name,+ "description": _compact_text(+ descriptor.description, COMPACT_DESCRIPTION_CHARS+ ),+ "parameters": _compact_schema(+ descriptor.input_schema, COMPACT_PARAMETER_DESCRIPTION_CHARS+ ),+ }+def _build_declarations(self) -> tuple[dict[str, Any], ...]:self._wire_to_name.clear()- declarations: list[dict[str, Any]] = []+ rendered: list[tuple[str, dict[str, Any]]] = []for name, descriptor in sorted(self._descriptors.items()):wire = _wire_name(str(name))if wire in self._wire_to_name:continueself._wire_to_name[wire] = str(name)- declarations.append(- {- "name": wire,- "description": descriptor.description[- :_MAX_DESCRIPTION_CHARS- ],- "parameters": descriptor.input_schema,- }+ rendered.append((str(name), self._render_declaration(wire, descriptor)))+ kept, dropped = _apply_declaration_budget(+ rendered, self._declaration_budget_chars+ )+ self._dropped_names = tuple(dropped)+ if dropped:+ # Names are logged in full (AP-30): a silently trimmed catalog+ # looks exactly like a complete one. The dropped tools remain+ # reachable through jarvis_action.+ log.warning(+ "realtime tool bridge: %d declaration(s) over the %d-char "+ "(~%d-token) budget were dropped from the native set and stay "+ "reachable through jarvis_action: %s",+ len(dropped),+ self._declaration_budget_chars,+ self._declaration_budget_chars // CHARS_PER_TOKEN,+ ", ".join(dropped),)- return tuple(declarations)+ for name in dropped:+ self._wire_to_name.pop(_wire_name(name), None)+ return tuple(declaration for _name, declaration in kept)@propertydef declarations(self) -> tuple[dict[str, Any], ...]:return self._declarations+ @property+ def dropped_names(self) -> tuple[str, ...]:+ """Catalog tools NOT declared natively under the declaration budget."""+ return self._dropped_names++ @property+ def excluded_tool_names(self) -> frozenset[str]:+ return self._excluded_tool_names++ @property+ def declaration_chars(self) -> int:+ """Serialized size of the declared set (the budget's own unit)."""+ return sum(_declaration_size(item) for item in self._declarations)+def set_language(self, language: str) -> None:self._language = languagediff --git a/tests/unit/realtime/test_factory.py b/tests/unit/realtime/test_factory.pyindex ea603039de..f28423109a 100644--- a/tests/unit/realtime/test_factory.py+++ b/tests/unit/realtime/test_factory.py@@ -214,8 +214,11 @@ def test_pipeline_mode_never_builds_realtime_session(monkeypatch):)-def test_realtime_tool_mode_defaults_to_compact_delegate_execution() -> None:- assert VoiceConfig().realtime_tool_mode == "delegate"+def test_realtime_tool_mode_defaults_to_hybrid_native_tools() -> None:+ """ADR-0035: the live model holds the catalog itself; the Tool Model is+ for computer use. ``delegate`` and ``direct`` remain explicit choices."""+ assert VoiceConfig().realtime_tool_mode == "hybrid"+ assert VoiceConfig().realtime_tool_declaration_budget_tokens > 0def test_one_realtime_key_builds_without_a_classic_brain(monkeypatch) -> None:diff --git a/tests/unit/realtime/test_hybrid_tool_mode.py b/tests/unit/realtime/test_hybrid_tool_mode.pynew file mode 100644index 0000000000..cdf496bf6d--- /dev/null+++ b/tests/unit/realtime/test_hybrid_tool_mode.py@@ -0,0 +1,356 @@+"""ADR-0035: hybrid realtime tool mode — the live model calls every Jarvis+tool itself, the Tool Model is for computer use.++Guards: the declared set (catalog minus the computer-use vehicles, plus+``jarvis_action`` and ``end_call``), the narrowed ``jarvis_action``, the+deterministic hand-over (explicit computer use forces the delegate, the+live mis-routes of 2026-08-18 do not), the declaration budget, and the+execute-side exclusion of the computer-use vehicles.+"""++# ruff: noqa: F811 - pytest fixtures re-exported from test_session are re-bound by name+from __future__ import annotations++import asyncio++import pytest++from jarvis.brain.cu_gate import CU_VEHICLE_TOOL_NAMES, is_explicit_computer_use_turn+from jarvis.core.protocols import AudioChunk, SupervisorToolDescriptor, ToolResult+from jarvis.realtime.protocol import RealtimeEvent+from jarvis.realtime.tools import (+ COMPACT_DESCRIPTION_CHARS,+ RealtimeToolBridge,+ _apply_declaration_budget,+)+from tests.unit.realtime.test_session import (+ FakeBrain,+ FakeProvider,+ _session,+ _StubExecutor,+ _StubTool,+ _tool_names,+ wire_supervisor_gateway, # noqa: F401 - pytest fixture re-export+)+++class _CalendarTool(_StubTool):+ name = "google_calendar"+ description = "Read and write the user's Google Calendar. " * 40+ risk_tier = "monitor"+ schema = {+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "description": "What to do with the calendar. " * 20,+ }+ },+ "required": ["action"],+ }+++class _ComputerUseTool(_StubTool):+ name = "computer_use"+ description = "Drive the user's live desktop."+ risk_tier = "monitor"+++class _SearchTool(_StubTool):+ name = "search_web"+ description = "Search the public web."+ risk_tier = "safe"+++def _hybrid_brain():+ brain = FakeBrain(replies=("delegated",))+ brain._tools = {+ "open_app": _StubTool(),+ "google_calendar": _CalendarTool(),+ "computer_use": _ComputerUseTool(),+ "search_web": _SearchTool(),+ }+ return brain+++async def test_hybrid_declares_catalog_minus_cu_plus_jarvis_action(+ wire_supervisor_gateway,+):+ brain = _hybrid_brain()+ wire_supervisor_gateway(brain, _StubExecutor())+ provider = FakeProvider([RealtimeEvent(type="turn_complete")])+ sess = _session(provider, brain=brain, tool_mode="hybrid")++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await sess.end(reason="test")++ names = _tool_names(provider.opened_with)+ assert "open_app" in names+ assert "google_calendar" in names+ assert "search_web" in names+ assert "jarvis_action" in names+ assert "end_call" in names+ assert not (set(names) & CU_VEHICLE_TOOL_NAMES), names+ # jarvis_action is the narrowed hybrid declaration, not the delegate one.+ action = next(d for d in provider.opened_with.tools if d["name"] == "jarvis_action")+ assert "call your own matching function directly" in action["description"]+ assert "operating the user's computer on screen" in action["description"]+ # The role directive is the hybrid one: functions for the user's world.+ instructions = provider.opened_with.instructions+ assert "is reached with YOUR OWN functions" in instructions+ assert "jarvis_action is reserved for operating the computer on screen" in instructions+ # Compact rendering: the 40x description is cut, the schema survives.+ calendar = next(d for d in provider.opened_with.tools if d["name"] == "google_calendar")+ assert len(calendar["description"]) <= COMPACT_DESCRIPTION_CHARS + 1+ assert calendar["parameters"]["required"] == ["action"]+++async def test_hybrid_falls_back_to_delegate_when_a_provider_cannot_declare_tools(+ wire_supervisor_gateway,+):+ class _HandoffProvider(FakeProvider):+ supports_direct_tools = False++ brain = _hybrid_brain()+ wire_supervisor_gateway(brain, _StubExecutor())+ provider = _HandoffProvider([RealtimeEvent(type="turn_complete")])+ sess = _session(provider, brain=brain, tool_mode="hybrid")++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await sess.end(reason="test")++ assert sess._tool_mode == "delegate"+ assert _tool_names(provider.opened_with) == ["jarvis_action", "end_call"]+++async def test_hybrid_bridge_never_executes_a_computer_use_vehicle(+ wire_supervisor_gateway,+):+ brain = _hybrid_brain()+ executor = _StubExecutor()+ wire_supervisor_gateway(brain, executor)+ provider = FakeProvider([RealtimeEvent(type="turn_complete")])+ sess = _session(provider, brain=brain, tool_mode="hybrid")+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()++ bridge = sess._tool_bridge+ assert bridge is not None+ name, result = await bridge.execute(wire_name="computer_use", arguments={})+ assert result["success"] is False+ assert "not available" in result["error"]+ name, result = await bridge.execute(wire_name="open_app", arguments={})+ assert name == "open_app"+ assert result["success"] is True+ await sess.end(reason="test")+++async def test_hybrid_leaves_planner_action_turns_to_the_live_model(+ wire_supervisor_gateway,+):+ """A planner 'orchestrator' verdict steers the model to its functions;+ the delegate is not imposed (ADR-0035 §2)."""+ brain = _hybrid_brain()+ wire_supervisor_gateway(brain, _StubExecutor())+ spoken = AudioChunk(pcm=b"\x01\x02" * 8, sample_rate=24_000, timestamp_ns=0)+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="Was steht heute in meinem Kalender?", # i18n-allow: fixture+ is_final=True,+ ),+ RealtimeEvent(+ type="output_transcript_delta",+ text="Your calendar is empty today.",+ is_final=True,+ ),+ RealtimeEvent(type="audio_delta", audio=spoken),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ sess = _session(provider, brain=brain, tool_mode="hybrid")+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()++ # No deterministic delegate was dispatched for the calendar turn ...+ assert brain.calls == []+ assert not sess._delegate_turns+ # ... and the turn-mode line told the model to use its own functions.+ joined = "\n".join(+ str(update["instructions"] or "") for update in provider.session.session_updates+ )+ assert "Call the matching function of your own NOW" in joined+ await sess.end(reason="test")+++async def test_hybrid_forces_the_delegate_for_explicit_computer_use(+ wire_supervisor_gateway,+):+ brain = _hybrid_brain()+ wire_supervisor_gateway(brain, _StubExecutor())+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="Klick auf den blauen Button im Browser.", # i18n-allow: fixture+ is_final=True,+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ sess = _session(provider, brain=brain, tool_mode="hybrid")+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.sleep(0.3)++ assert sess._delegate_required_for_turn is True+ assert sess._delegate_cu_dispatches == 1+ assert [call[0] for call in brain.calls] == [+ "Klick auf den blauen Button im Browser." # i18n-allow: German fixture+ ]+ await sess.end(reason="test")+++ "utterance",+ [+ "Klick auf den Button.", # i18n-allow: German speech-input fixture+ "Mach das Fenster zu.", # i18n-allow: German speech-input fixture+ "Open the browser and log in to GitHub.",+ "Kannst du bitte mit Computer use den letzten Tab wieder öffnen?", # i18n-allow: fixture+ ],+)+def test_explicit_computer_use_turns(utterance: str) -> None:+ assert is_explicit_computer_use_turn(utterance) is True+++ "utterance",+ [+ "Öffne Spotify.", # i18n-allow: German speech-input fixture+ "Starte die Morgenroutine.", # i18n-allow: German speech-input fixture+ "Spiel mir bitte ein cooles Lied.", # i18n-allow: German speech-input fixture+ "Was siehst du auf meinem Bildschirm?", # i18n-allow: German speech-input fixture+ "Hallo, sprich mal mit mir.", # i18n-allow: German speech-input fixture+ "Wer waren die 10 berühmtesten Wissenschaftler?", # i18n-allow: German fixture+ "Was geht ab?", # i18n-allow: German speech-input fixture+ ],+)+def test_non_desktop_turns_are_not_forced_to_the_delegate(utterance: str) -> None:+ assert is_explicit_computer_use_turn(utterance) is False+++def _descriptor(name: str, size: int) -> SupervisorToolDescriptor:+ return SupervisorToolDescriptor(+ name=name,+ description="x" * size,+ input_schema={"type": "object", "properties": {}},+ risk_tier="safe",+ is_action_tool=False,+ )+++def test_declaration_budget_drops_deterministically_and_keeps_the_rest() -> None:+ rendered = [+ ("agentic-ide-fanout", {"name": "agentic-ide-fanout", "description": "a" * 400}),+ ("agentic-ide-focus", {"name": "agentic-ide-focus", "description": "a" * 100}),+ ("cli_gcloud", {"name": "cli_gcloud", "description": "c" * 300}),+ ("wiki-recall", {"name": "wiki-recall", "description": "w" * 200}),+ ("search_web", {"name": "search_web", "description": "s" * 100}),+ ]+ total = sum(len(str(d)) for _n, d in rendered)+ kept, dropped = _apply_declaration_budget(rendered, total - 1)+ # The lowest-priority family first, the longest member of it first.+ assert dropped == ["agentic-ide-fanout"]+ assert [name for name, _d in kept] == [+ "agentic-ide-focus",+ "cli_gcloud",+ "wiki-recall",+ "search_web",+ ]+ kept, dropped = _apply_declaration_budget(rendered, 50)+ assert dropped[:3] == ["agentic-ide-fanout", "agentic-ide-focus", "cli_gcloud"]+ assert kept == [] or all(name in {"wiki-recall", "search_web"} for name, _d in kept)+ # No budget keeps everything.+ kept, dropped = _apply_declaration_budget(rendered, 0)+ assert dropped == [] and len(kept) == 5+++def test_bridge_budget_hides_dropped_tools_and_reports_them() -> None:+ class _Gateway:+ def catalog(self):+ return (+ _descriptor("agentic-ide-fanout", 2_000),+ _descriptor("wiki-recall", 100),+ _descriptor("computer_use", 100),+ )++ async def execute(self, *_a, **_k):+ return ToolResult(success=True, output="ok")++ bridge = RealtimeToolBridge(+ gateway=_Gateway(),+ language="en",+ excluded_tool_names=CU_VEHICLE_TOOL_NAMES,+ compact=True,+ declaration_budget_chars=600,+ )+ names = [d["name"] for d in bridge.declarations]+ assert len(names) == 1 and names[0].startswith("wiki_recall")+ assert bridge.dropped_names == ("agentic-ide-fanout",)+ assert "computer_use" not in names+ assert bridge.declaration_chars <= 600+++def test_router_catalog_renders_for_every_realtime_wire() -> None:+ """ADR-0035 §8: every router tool survives the compact rendering, the+ wire-name rule, the Gemini schema sanitizer, and the default budget."""+ from jarvis.brain.factory import _load_tools_for_tier+ from jarvis.core.config import JarvisConfig, VoiceConfig+ from jarvis.core.bus import EventBus+ from jarvis.plugins.realtime.gemini_live import _sanitize_declarations+ from jarvis.realtime.tools import CHARS_PER_TOKEN, _VALID_WIRE_NAME++ tools = _load_tools_for_tier(+ "router",+ bus=EventBus(),+ executor=None,+ harness_manager=None,+ user_profile=None,+ people=None,+ config=JarvisConfig(),+ )+ assert "computer_use" in tools, "the CU vehicle must exist to be excluded"+ budget_chars = VoiceConfig().realtime_tool_declaration_budget_tokens * CHARS_PER_TOKEN+ bridge = RealtimeToolBridge(+ tools=tools,+ executor=None,+ language="en",+ excluded_tool_names=CU_VEHICLE_TOOL_NAMES,+ compact=True,+ declaration_budget_chars=budget_chars,+ )+ declarations = bridge.declarations+ assert declarations, "the router catalog rendered no declarations"+ names = [d["name"] for d in declarations]+ assert "computer_use" not in names+ assert len(names) == len(set(names))+ for declaration in declarations:+ assert _VALID_WIRE_NAME.fullmatch(declaration["name"]), declaration["name"]+ assert isinstance(declaration["parameters"], dict)+ assert len(declaration["description"]) <= COMPACT_DESCRIPTION_CHARS + 1+ assert bridge.declaration_chars <= budget_chars+ sanitized = _sanitize_declarations(tuple(declarations))+ assert len(sanitized) == len(declarations)+ for entry in sanitized:+ params = entry.get("parameters") or {}+ properties = params.get("properties") or {}+ for required in params.get("required") or ():+ assert required in properties, (entry["name"], required)diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 8fca3eeabb..d4c4fcaebf 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -196,6 +196,51 @@ class AutomaticDelegateProvider(FakeProvider):return self.session+class ScriptedTextTurnsSession(FakeSession):+ """Emit one native turn, then one scripted batch per trusted text input.++ Batch ``n`` is released when the ``n``-th ``send_text`` arrives, so a test+ can script "the provider answers the re-ask" and "the provider stays mute+ again, then renders the delegate result" as distinct transports.+ """++ creates_responses_automatically = True++ def __init__(self, before_result, *batches):+ super().__init__([])+ self._before_result = before_result+ self._batches = list(batches)+ self._text_arrived = asyncio.Event()++ async def receive(self):+ for event in self._before_result:+ yield event+ await asyncio.sleep(0)+ for index, batch in enumerate(self._batches, start=1):+ while len(self.text_inputs) < index:+ await self._text_arrived.wait()+ self._text_arrived.clear()+ for event in batch:+ yield event+ await asyncio.sleep(0)++ async def send_text(self, text):+ await super().send_text(text)+ self._text_arrived.set()+++class ScriptedTextTurnsProvider(FakeProvider):+ def __init__(self, before_result, *batches):+ super().__init__([])+ self._before_result = before_result+ self._batches = batches++ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = ScriptedTextTurnsSession(self._before_result, *self._batches)+ return self.session++class FailingProvider(FakeProvider):name = "failing-family"@@ -4774,10 +4819,79 @@ async def test_direct_mode_builds_bridge_from_brain(wire_supervisor_gateway):assert "jarvis_action" not in names+async def test_empty_provider_turn_is_reasked_natively_before_any_brain_call():+ """A native turn the provider dropped is asked again — no Tool Model.++ Live 2026-08-18: Gemini Live closed ten smalltalk turns ("Was geht ab?",+ "Okay.") without output and every one was recovered through the full+ Brain chain (18–46k tokens, 4–7 s to the first word). The planner had+ routed them natively; the first recovery must be the live model itself.+ """ # i18n-allow: quoted live utterances+ user_text = "Tell me a joke about penguins."+ native_reply = "We could build a tiny game together."+ spoken_audio = AudioChunk(+ pcm=b"\x01\x02" * 8,+ sample_rate=24_000,+ timestamp_ns=0,+ )+ brain = FakeBrain(replies=("never spoken",))+ provider = ScriptedTextTurnsProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text=user_text,+ is_final=True,+ ),+ RealtimeEvent(type="turn_complete"),+ ],+ [+ RealtimeEvent(+ type="output_transcript_delta",+ text=native_reply,+ is_final=True,+ ),+ RealtimeEvent(type="audio_delta", audio=spoken_audio),+ RealtimeEvent(type="turn_complete"),+ ],+ )+ jsons: list[dict] = []+ binaries: list[bytes] = []+ bus = FakeBus()+ sess = _session(+ provider,+ brain=brain,+ tool_mode="direct",+ jsons=jsons,+ binaries=binaries,+ bus=bus,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(sess.wait_finished(), timeout=2)++ assert brain.calls == [], "the Brain chain is the SECOND net, not the first"+ assert len(provider.session.text_inputs) == 1+ reask = provider.session.text_inputs[0]+ assert "without any spoken answer" in reask+ assert user_text in reask+ assert "<trusted_action_result>" not in reask+ assert binaries == [spoken_audio.pcm]+ assert sum(item.get("type") == "turn_complete" for item in jsons) == 1+ completed = [event for event in bus.events if isinstance(event, VoiceTurnCompleted)]+ assert len(completed) == 1+ assert completed[0].jarvis_text == native_reply+ await sess.end(reason="test")++@pytest.mark.asyncioasync def test_direct_mode_recovers_provider_turn_that_has_no_output():- """A substantive user turn must never complete as successful silence."""- user_text = "I am bored. What could we do?"+ """A substantive user turn must never complete as successful silence.++ The provider drops the turn, ignores the re-ask with a second empty+ boundary, and only then does the Brain chain run — exactly once.+ """+ user_text = "Tell me a joke about penguins."recovered_reply = "We could build a tiny game together."spoken_audio = AudioChunk(pcm=b"\x01\x02" * 8,@@ -4785,7 +4899,7 @@ async def test_direct_mode_recovers_provider_turn_that_has_no_output():timestamp_ns=0,)brain = FakeBrain(replies=(recovered_reply,))- provider = AutomaticDelegateProvider(+ provider = ScriptedTextTurnsProvider([RealtimeEvent(type="input_transcript",@@ -4794,6 +4908,9 @@ async def test_direct_mode_recovers_provider_turn_that_has_no_output():),RealtimeEvent(type="turn_complete"),],+ # The re-ask is answered with a second empty boundary ...+ [RealtimeEvent(type="turn_complete")],+ # ... and the delegate result is then rendered natively.[RealtimeEvent(type="output_transcript_delta",@@ -4820,8 +4937,9 @@ async def test_direct_mode_recovers_provider_turn_that_has_no_output():await asyncio.wait_for(sess.wait_finished(), timeout=2)assert [call[0] for call in brain.calls] == [user_text]- assert len(provider.session.text_inputs) == 1- assert "<trusted_action_result>" in provider.session.text_inputs[0]+ assert len(provider.session.text_inputs) == 2+ assert "without any spoken answer" in provider.session.text_inputs[0]+ assert "<trusted_action_result>" in provider.session.text_inputs[1]assert binaries == [spoken_audio.pcm]assert sum(item.get("type") == "turn_complete" for item in jsons) == 1completed = [event for event in bus.events if isinstance(event, VoiceTurnCompleted)]@@ -4830,6 +4948,108 @@ async def test_direct_mode_recovers_provider_turn_that_has_no_output():await sess.end(reason="test")+async def test_mute_reask_falls_back_to_brain_after_the_readback_budget(monkeypatch):+ """A re-ask the provider never answers at all is not the end of the turn."""+ import jarvis.realtime.session as session_module++ monkeypatch.setattr(session_module, "_DELEGATE_READBACK_WAIT_S", 0.1)+ user_text = "Tell me a joke about penguins."+ recovered_reply = "We could build a tiny game together."+ spoken_audio = AudioChunk(+ pcm=b"\x01\x02" * 8,+ sample_rate=24_000,+ timestamp_ns=0,+ )+ brain = FakeBrain(replies=(recovered_reply,))+ provider = ScriptedTextTurnsProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text=user_text,+ is_final=True,+ ),+ RealtimeEvent(type="turn_complete"),+ ],+ # The re-ask produces NOTHING — not even a boundary ...+ [],+ # ... the watchdog dispatches the Brain chain, whose result renders.+ [+ RealtimeEvent(+ type="output_transcript_delta",+ text=recovered_reply,+ is_final=True,+ ),+ RealtimeEvent(type="audio_delta", audio=spoken_audio),+ RealtimeEvent(type="turn_complete"),+ ],+ )+ binaries: list[bytes] = []+ bus = FakeBus()+ sess = _session(+ provider,+ brain=brain,+ tool_mode="direct",+ binaries=binaries,+ bus=bus,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(sess.wait_finished(), timeout=3)++ assert [call[0] for call in brain.calls] == [user_text]+ assert len(provider.session.text_inputs) == 2+ assert "<trusted_action_result>" in provider.session.text_inputs[1]+ assert binaries == [spoken_audio.pcm]+ completed = [event for event in bus.events if isinstance(event, VoiceTurnCompleted)]+ assert len(completed) == 1+ assert completed[0].jarvis_text == recovered_reply+ await sess.end(reason="test")+++async def test_empty_turn_that_needs_the_orchestrator_is_not_reasked():+ """A turn the planner routed to the orchestrator never goes back native."""+ user_text = "What is in my wiki about the Berlin project?"+ recovered_reply = "Your wiki has two pages about the Berlin project."+ spoken_audio = AudioChunk(+ pcm=b"\x01\x02" * 8,+ sample_rate=24_000,+ timestamp_ns=0,+ )+ brain = FakeBrain(replies=(recovered_reply,))+ provider = ScriptedTextTurnsProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text=user_text,+ is_final=True,+ ),+ RealtimeEvent(type="turn_complete"),+ ],+ [+ RealtimeEvent(+ type="output_transcript_delta",+ text=recovered_reply,+ is_final=True,+ ),+ RealtimeEvent(type="audio_delta", audio=spoken_audio),+ RealtimeEvent(type="turn_complete"),+ ],+ )+ binaries: list[bytes] = []+ sess = _session(provider, brain=brain, tool_mode="direct", binaries=binaries)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(sess.wait_finished(), timeout=2)++ assert [call[0] for call in brain.calls] == [user_text]+ assert len(provider.session.text_inputs) == 1+ assert "<trusted_action_result>" in provider.session.text_inputs[0]+ assert binaries == [spoken_audio.pcm]+ await sess.end(reason="test")++@pytest.mark.asyncioasync def test_text_only_provider_answer_uses_surface_tts_without_brain_retry():"""An audio-mode response with text but zero PCM is not treated as spoken."""@@ -4907,11 +5127,16 @@ async def test_empty_provider_turn_without_brain_speaks_local_error():@pytest.mark.asyncioasync def test_empty_recovery_response_uses_surface_tts_without_rerunning_brain():- """A second provider failure speaks the grounded result through local TTS."""- user_text = "I am bored. What could we do?"+ """A third provider failure speaks the grounded result through local TTS.++ Empty turn, empty re-ask, Brain chain once, and the provider stays mute on+ the delivered result too: the surface TTS speaks it, the brain is not+ re-run.+ """+ user_text = "Tell me a joke about penguins."recovered_reply = "We could build a tiny game together."brain = FakeBrain(replies=(recovered_reply,))- provider = AutomaticDelegateProvider(+ provider = ScriptedTextTurnsProvider([RealtimeEvent(type="input_transcript",@@ -4921,6 +5146,7 @@ async def test_empty_recovery_response_uses_surface_tts_without_rerunning_brain(RealtimeEvent(type="turn_complete"),],[RealtimeEvent(type="turn_complete")],+ [RealtimeEvent(type="turn_complete")],)jsons: list[dict] = []bus = FakeBus()@@ -5820,12 +6046,12 @@ async def test_turn_complete_waits_for_slow_delegate_task_on_same_turn():brain = FakeBrain(replies=("Completed on the original turn.",), gate=gate)provider = FakeProvider([- RealtimeEvent(type="input_transcript", text="do it", is_final=True),+ RealtimeEvent(type="input_transcript", text="Open the calculator.", is_final=True),RealtimeEvent(type="tool_call",call_id="slow-same-turn",tool_name="jarvis_action",- tool_args={"request": "do it"},+ tool_args={"request": "Open the calculator."},),RealtimeEvent(type="turn_complete"),]@@ -5838,7 +6064,7 @@ async def test_turn_complete_waits_for_slow_delegate_task_on_same_turn():assert original_turn_idassert original_turn_id in sess._delegate_turns- assert sess._last_user_text == "do it"+ assert sess._last_user_text == "Open the calculator."assert sess._turn_has_pending_delegate(original_turn_id) is Truegate.set()