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.

revert(realtime): restore the BUG-164 follow-up that a shared-index commit swept away

rubenluetke10-beepe906746ab0f9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5c2377f1d2..202d824e42 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,13 +23,6 @@ versioning per [SemVer](https://semver.org/).
upload is now cut to half a second before it is sent, a transcript that ends
well before your speech does gets only its missing tail read back in, and
a hardware overflow on the microphone is counted as the real loss it is.
-- **The local recognizer says when it cannot reach your GPU — and fixes it
- from inside the app.** On a desktop without the CUDA runtime libraries the
- on-device recognizer quietly ran on the CPU (about eight times slower; the
- cloud fallback took 48 s for a 70 s recording). The provider card now shows
- what the config asked for, what really runs, and why, with a one-click
- install of the missing libraries. They are also available as the `cuda`
- install extra.
- **The wake word no longer fires on a stray single word.** Since the 20 Aug
crash fix, the check that decides between "Hey George" and whatever was
actually said had quietly lost its strongest comparison, so a lone word like
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 6b1733db0c..e1e2f29cf0 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -11570,14 +11570,25 @@ the same honesty clause for every brain. Tests:
``tests/unit/realtime/test_skill_handoff_is_not_done.py`` (the 18:16 turn end
to end, the classifier, pending vs. followed-up loads, every language).
-**Follow-up (not in this fix).** The declaration budget dropped ``spotify``,
-``gmail``, ``google_calendar``, ``home_assistant``, ``youtube_music`` and
-``spawn_worker`` from the native set on this box once the Linear/GitHub/
-NotebookLM MCP servers came online (169 over-budget names at 17:10, 28 at
-16:50) — ADR-0035 §4 drops "everything else, biggest first" after the MCP/CLI/
-Agentic-IDE families. First-party plugin tools behind an installed skill
-deserve a higher rank than a generic bucket; that is a T2 change to
-``_BUDGET_DROP_FAMILIES``.
+**Follow-up fix (2026-08-22, same day).** Three more defects behind the
+same turn, all landed: (1) the declaration budget was the MINIMUM over every
+candidate in the provider chain, so a ``gemini-live`` call ran on the
+``openai-realtime`` fallback's 8 000 tokens and lost ``spotify``,
+``youtube_music``, ``gmail``, ``google_calendar``, ``home_assistant`` and
+``spawn_worker`` to a budget that never applied to its wire —
+``_declaration_budget_chars(provider)`` now takes ONE provider and
+``_fit_declaration_budget`` re-trims the bridge (``set_declaration_budget``) for
+the candidate about to open; (2) under a genuinely tight budget the connected
+music connectors are now the LAST declarations to go (``keep_last`` in
+``_apply_declaration_budget``, read from ``music_service.connected_music_services``);
+(3) ``run-skill`` loaded ``plugin-spotify`` although only YouTube Music was
+connected — it now follows the same resolver as the skill capture and the
+execute-time reroute (``_prefer_connected_music_service``: a named service
+wins, then the preferred connected one, then the only connected one). Tests:
+``test_declaration_budget_per_provider.py``,
+``test_connected_music_connectors_are_the_last_to_go``,
+``test_bridge_refits_the_declared_set_to_a_new_budget``,
+``test_a_music_skill_load_follows_the_only_connected_service``.
**Lesson (BUG-160 family).** A tool result's ``success`` flag says the TOOL
ran, not that the USER'S REQUEST happened. Any tool whose output is
diff --git a/jarvis/plugins/tool/run_skill.py b/jarvis/plugins/tool/run_skill.py
index b12fd92c78..723c02152c 100644
--- a/jarvis/plugins/tool/run_skill.py
+++ b/jarvis/plugins/tool/run_skill.py
@@ -43,6 +43,7 @@ Design notes:
"""
from __future__ import annotations
+import logging
from pathlib import Path
from typing import Any
@@ -50,6 +51,8 @@ from jarvis.core.protocols import ExecutionContext, ToolResult
from jarvis.skills.schema import SkillLifecycleState
from jarvis.skills.skill_context import try_get_skill_context
+log = logging.getLogger(__name__)
+
_MAX_RESOURCE_BYTES = 64 * 1024
_INLINE_DIRECTIVE = (
@@ -158,6 +161,16 @@ class RunSkillTool:
f"Installed skills: {self._installed_names(registry)}"
),
)
+ # Step 3b — a music skill follows the CONNECTED service. The model picks
+ # a skill by name from the roster, and the roster lists both music
+ # skills whether or not their plugin holds a credential; live
+ # 2026-08-22 18:16 it loaded ``plugin-spotify`` on a box where only
+ # YouTube Music was connected, and the instructions it then held were
+ # for the wrong service. Same resolver as the deterministic skill
+ # capture and the execute-time tool reroute (``jarvis.core.music_service``):
+ # a service the user NAMES wins, then the preferred connected one,
+ # then the only connected one.
+ skill = self._prefer_connected_music_service(skill, registry, ctx)
# Everything downstream — the rendered output, the SkillInvoked event,
# the DRAFT/DISABLED refusals — must speak about the skill that was
# actually found, never the guess that led here.
@@ -247,6 +260,57 @@ class RunSkillTool:
# Helpers
# ------------------------------------------------------------------
+ @staticmethod
+ def _prefer_connected_music_service(
+ skill: Any, registry: Any, ctx: ExecutionContext
+ ) -> Any:
+ """Swap a MUSIC skill for its sibling when the request belongs to the
+ other service (see ``jarvis.core.music_service``). Never raises and
+ never swaps to a skill that is missing or not live — a fault keeps the
+ skill as it was."""
+ try:
+ from jarvis.core.music_constants import MUSIC_PLUGIN_IDS
+ from jarvis.core.music_service import (
+ connected_music_services,
+ preferred_music_service,
+ resolve_music_service,
+ )
+
+ fm = getattr(skill, "frontmatter", None)
+ plugin_id = str(getattr(fm, "plugin_id", "") or "").strip()
+ if plugin_id not in MUSIC_PLUGIN_IDS:
+ return skill
+ connected = tuple(connected_music_services())
+ target = resolve_music_service(
+ str(getattr(ctx, "user_utterance", "") or ""),
+ preferred=preferred_music_service(),
+ connected=connected,
+ matched=plugin_id,
+ )
+ if not target or target == plugin_id or target not in connected:
+ return skill
+ sibling_name = f"plugin-{target}"
+ try:
+ sibling = registry.get(sibling_name)
+ except KeyError:
+ return skill
+ if sibling is None or sibling.state not in (
+ SkillLifecycleState.ACTIVE,
+ SkillLifecycleState.VALIDATED,
+ ):
+ return skill
+ log.info(
+ "run-skill: music request routed to %s instead of %s "
+ "(connected=%s)",
+ sibling_name,
+ getattr(skill, "name", plugin_id),
+ ",".join(connected) or "none",
+ )
+ return sibling
+ except Exception as exc: # noqa: BLE001 — a routing nicety must never break a turn
+ log.debug("run-skill: music preference routing skipped: %s", exc)
+ return skill
+
@staticmethod
def _installed_names(registry: Any, *, limit: int = 40) -> str:
"""Comma-joined names of the invocable skills, for a recovery hint."""
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index fcb9da2aae..1ddc53d74b 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -3608,6 +3608,9 @@ class RealtimeVoiceSession:
if not self._provider_is_available(provider):
continue
model, voice = self._active_provider_selection(provider)
+ # ADR-0035 §4: the native tool set is trimmed to THIS candidate's
+ # budget, not to the tightest budget anywhere in the chain.
+ self._fit_declaration_budget(provider)
input_rate = int(getattr(provider, "input_sample_rate", 16_000) or 16_000)
output_rate = int(getattr(provider, "output_sample_rate", 24_000) or 24_000)
session_config = RealtimeSessionConfig(
@@ -9349,12 +9352,19 @@ class RealtimeVoiceSession:
and getattr(self, "_delegate_enabled", False)
)
- def _declaration_budget_chars(self) -> int:
+ def _declaration_budget_chars(self, provider: Any | None = None) -> 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.
+ The smaller of the config bound and a provider's own declared budget
+ (``tool_declaration_budget_tokens``, a capability — AP-21); 0 =
+ unbounded. With ``provider`` given, that ONE provider's budget counts;
+ without it, every candidate's — the conservative first fit at
+ construction time, before the call knows which provider answers.
+ The per-provider fit is applied again at connect
+ (:meth:`_fit_declaration_budget`): live 2026-08-22 a ``gemini-live``
+ session, which declares no budget of its own, ran the whole call on
+ the OpenAI fallback's 8 000 tokens and lost every first-party
+ connector to it.
"""
configured = int(
getattr(
@@ -9365,7 +9375,8 @@ class RealtimeVoiceSession:
or 0
)
budgets = [configured] if configured > 0 else []
- for candidate in self._providers:
+ candidates = [provider] if provider is not None else list(self._providers)
+ for candidate in candidates:
declared = int(
getattr(candidate, "tool_declaration_budget_tokens", 0) or 0
)
@@ -9375,6 +9386,45 @@ class RealtimeVoiceSession:
return 0
return min(budgets) * 4
+ def _fit_declaration_budget(self, provider: Any) -> None:
+ """Re-trim the native tool set to the budget of the provider about to open.
+
+ No-op unless hybrid mode has a bridge that can re-fit. Logs the new
+ shape whenever the declared set actually changed, so a session log
+ always shows the set the wire really carried (AP-30: a trimmed catalog
+ looks exactly like a complete one).
+ """
+ bridge = self._tool_bridge
+ refit = getattr(bridge, "set_declaration_budget", None)
+ if bridge is None or not self._hybrid_enabled or not callable(refit):
+ return
+ budget = self._declaration_budget_chars(provider)
+ try:
+ changed = bool(refit(budget))
+ except Exception: # noqa: BLE001 — the first fit still stands
+ log.warning(
+ "realtime[%s] declaration budget re-fit failed; keeping the "
+ "conservative set",
+ self.session_id,
+ exc_info=True,
+ )
+ return
+ if not changed:
+ return
+ dropped = tuple(getattr(bridge, "dropped_names", ()) or ())
+ log.info(
+ "realtime[%s] tool set re-fit for %s: %d native tools (~%d tokens "
+ "of a %d-token budget), %d over-budget name(s) reachable via "
+ "jarvis_action%s",
+ self.session_id,
+ str(getattr(provider, "name", "") or "provider"),
+ len(bridge.declarations),
+ int(getattr(bridge, "declaration_chars", 0) or 0) // 4,
+ budget // 4,
+ len(dropped),
+ f": {', '.join(dropped)}" if dropped else "",
+ )
+
def _declared_tools(self) -> tuple[dict[str, Any], ...]:
if self._hybrid_enabled:
native = (
diff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.py
index aede6933ce..74b5812750 100644
--- a/jarvis/realtime/tools.py
+++ b/jarvis/realtime/tools.py
@@ -6,6 +6,7 @@ import hashlib
import json
import logging
import re
+from collections.abc import Collection
from dataclasses import dataclass
from typing import Any, cast
from uuid import UUID, uuid4
@@ -378,23 +379,55 @@ def _declaration_size(declaration: dict[str, Any]) -> int:
return _MAX_DESCRIPTION_CHARS
-def _drop_rank(name: str) -> int:
- """Lower rank = dropped earlier (ADR-0035 §4 family order)."""
+def _drop_rank(name: str, keep_last: Collection[str] = ()) -> int:
+ """Lower rank = dropped earlier (ADR-0035 §4 family order).
+
+ ``keep_last`` names outrank every family — they are the LAST to go. The
+ bridge fills it with the connected music connectors (``spotify`` /
+ ``youtube_music``, whichever holds a credential): on this box the
+ "everything else, biggest first" bucket dropped both of them under the
+ 8k-token wire budget (live 2026-08-22 18:16, 169 over-budget names), so
+ "mach Musik an" had no native function to land on while a dozen small
+ first-party tools nobody had asked for stayed declared. A connected
+ connector is something the user set up on purpose; it is declared before
+ anything the catalog merely happens to contain.
+ """
+ if name in keep_last:
+ return len(_BUDGET_DROP_FAMILIES) + 1
for rank, (_family, pattern) in enumerate(_BUDGET_DROP_FAMILIES):
if pattern.search(name):
return rank
return len(_BUDGET_DROP_FAMILIES)
+def _connected_music_connectors() -> tuple[str, ...]:
+ """The music connector tool names holding a usable credential, or ``()``.
+
+ Read through ``jarvis.core.music_service`` (cached for a few seconds there);
+ any fault answers "none" — the budget must never depend on a keyring read
+ succeeding.
+ """
+ try:
+ from jarvis.core.music_service import connected_music_services
+
+ return tuple(str(name) for name in connected_music_services())
+ except Exception as exc: # noqa: BLE001 — a probe fault must not brick the catalog
+ log.debug("realtime tool bridge: music connector probe skipped: %s", exc)
+ return ()
+
+
def _apply_declaration_budget(
rendered: list[tuple[str, dict[str, Any]]],
budget_chars: int,
+ *,
+ keep_last: Collection[str] = (),
) -> 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.
+ declaration first inside it, ties by name; ``keep_last`` names go after
+ every family. Returns (kept in the original order, dropped names in drop
+ order). ``budget_chars <= 0`` keeps all.
"""
if budget_chars <= 0:
return list(rendered), []
@@ -402,9 +435,10 @@ def _apply_declaration_budget(
total = sum(sizes.values())
if total <= budget_chars:
return list(rendered), []
+ keep = frozenset(keep_last)
drop_order = sorted(
(name for name, _decl in rendered),
- key=lambda name: (_drop_rank(name), -sizes[name], name),
+ key=lambda name: (_drop_rank(name, keep), -sizes[name], name),
)
dropped: list[str] = []
for name in drop_order:
@@ -574,7 +608,9 @@ class RealtimeToolBridge:
if alias and alias not in self._wire_to_name:
self._wire_to_name[alias] = str(name)
kept, dropped = _apply_declaration_budget(
- rendered, self._declaration_budget_chars
+ rendered,
+ self._declaration_budget_chars,
+ keep_last=_connected_music_connectors(),
)
self._dropped_names = tuple(dropped)
if dropped:
@@ -612,6 +648,31 @@ class RealtimeToolBridge:
"""Serialized size of the declared set (the budget's own unit)."""
return sum(_declaration_size(item) for item in self._declarations)
+ @property
+ def declaration_budget_chars(self) -> int:
+ """The budget the declared set is currently trimmed to (0 = unbounded)."""
+ return self._declaration_budget_chars
+
+ def set_declaration_budget(self, budget_chars: int) -> bool:
+ """Re-fit the declared set to ``budget_chars``; True when it changed.
+
+ The session builds the bridge before it knows which provider will
+ answer the call, so the first fit is the most conservative budget of
+ the whole chain. Once a candidate is about to be opened, its OWN budget
+ applies (ADR-0035 §4: ``gemini-live`` declares none, the OpenAI-protocol
+ wires declare 8 000 tokens) — live 2026-08-22 a Gemini session was
+ trimmed to the OpenAI fallback's 32 000 characters and lost every
+ first-party connector (``spotify``, ``youtube_music``, ``gmail``,
+ ``google_calendar`` …) to a budget that never applied to its wire.
+ """
+ budget = max(0, int(budget_chars or 0))
+ if budget == self._declaration_budget_chars:
+ return False
+ self._declaration_budget_chars = budget
+ previous = self._declarations
+ self._declarations = self._build_declarations()
+ return self._declarations != previous
+
def set_language(self, language: str) -> None:
self._language = language
diff --git a/tests/unit/brain/test_run_skill_tool.py b/tests/unit/brain/test_run_skill_tool.py
index ac549c9834..916da64a3f 100644
--- a/tests/unit/brain/test_run_skill_tool.py
+++ b/tests/unit/brain/test_run_skill_tool.py
@@ -454,3 +454,93 @@ async def test_run_skill_still_works_on_a_registry_without_resolve() -> None:
result = await RunSkillTool().execute({"skill_name": "demo_skill"}, _ctx())
assert result.success is True
+
+
+# ----------------------------------------------------------------------
+# Music: the loaded skill follows the CONNECTED service
+# ----------------------------------------------------------------------
+
+
+def _music_skill(plugin_id: str) -> Skill:
+ fm = SkillFrontmatter(
+ schema_version="1",
+ name=f"plugin-{plugin_id}",
+ description=f"Play music on {plugin_id}.",
+ plugin_id=plugin_id,
+ risk_policy=SkillRiskPolicy(default_tier="monitor"), # type: ignore[arg-type]
+ execution="inline", # type: ignore[arg-type]
+ )
+ return Skill(
+ path=Path("nonexistent") / f"plugin-{plugin_id}" / "SKILL.md",
+ frontmatter=fm,
+ body=f"Use {plugin_id}.",
+ state=SkillLifecycleState.ACTIVE,
+ body_hash="deadbeef",
+ error=None,
+ )
+
+
+def _music_registry() -> _FakeRegistry:
+ return _FakeRegistry(
+ {
+ "plugin-spotify": _music_skill("spotify"),
+ "plugin-youtube_music": _music_skill("youtube_music"),
+ }
+ )
+
+
+async def test_a_music_skill_load_follows_the_only_connected_service(monkeypatch) -> None:
+ """Live 2026-08-22 18:16: the model asked for ``plugin-spotify`` on a box
+ where only YouTube Music was connected, and held Spotify's how-to."""
+ from jarvis.core import music_service as ms
+
+ monkeypatch.setattr(ms, "connected_music_services", lambda: ("youtube_music",))
+ monkeypatch.setattr(ms, "preferred_music_service", lambda: "auto")
+ runner = _FakeRunner()
+ set_skill_context(SkillContext(registry=_music_registry(), runner=runner)) # type: ignore[arg-type]
+
+ result = await RunSkillTool().execute({"skill_name": "plugin-spotify"}, _ctx())
+
+ assert result.success is True
+ assert result.output["skill_name"] == "plugin-youtube_music"
+ assert runner.calls[0].skill.name == "plugin-youtube_music"
+
+
+async def test_a_named_music_service_is_kept(monkeypatch) -> None:
+ """The user said Spotify: that wins even when YouTube Music is connected too."""
+ from jarvis.core import music_service as ms
+
+ monkeypatch.setattr(
+ ms, "connected_music_services", lambda: ("spotify", "youtube_music")
+ )
+ monkeypatch.setattr(ms, "preferred_music_service", lambda: "youtube_music")
+ set_skill_context(SkillContext(registry=_music_registry(), runner=_FakeRunner())) # type: ignore[arg-type]
+ ctx = ExecutionContext(
+ trace_id=uuid4(),
+ user_utterance="Spiel Jazz auf Spotify.", # i18n-allow: spoken-input fixture
+ config={},
+ memory_read=None,
+ )
+
+ result = await RunSkillTool().execute({"skill_name": "plugin-spotify"}, ctx)
+
+ assert result.success is True
+ assert result.output["skill_name"] == "plugin-spotify"
+
+
+async def test_a_music_skill_stays_when_nothing_is_connected(monkeypatch) -> None:
+ """Nothing to route to: the skill the model named is loaded as before, and
+ its own instructions tell the user the service is not connected."""
+ from jarvis.core import music_service as ms
+
+ monkeypatch.setattr(ms, "connected_music_services", lambda: ())
+ monkeypatch.setattr(ms, "preferred_music_service", lambda: "auto")
+ set_skill_context(SkillContext(registry=_music_registry(), runner=_FakeRunner())) # type: ignore[arg-type]
+
+ result = await RunSkillTool().execute({"skill_name": "plugin-spotify"}, _ctx())
+
+ assert result.success is True
+ assert result.output["skill_name"] == "plugin-spotify"
diff --git a/tests/unit/realtime/test_declaration_budget_per_provider.py b/tests/unit/realtime/test_declaration_budget_per_provider.py
new file mode 100644
index 0000000000..4a1b41ed3f
--- /dev/null
+++ b/tests/unit/realtime/test_declaration_budget_per_provider.py
@@ -0,0 +1,142 @@
+"""The native tool set is trimmed to the budget of the provider that opens.
+
+ADR-0035 §4: ``gemini-live`` / ``vertex-live`` declare no budget of their own
+(the setup is sent once per connection); the OpenAI-protocol wires declare
+8 000 tokens. The session used to take the MINIMUM over every candidate in the
+chain at construction time — so a Gemini call with an OpenAI fallback behind it
+ran the whole session on 8 000 tokens and, live 2026-08-22 18:16, lost every
+first-party connector (``spotify``, ``youtube_music``, ``gmail``,
+``google_calendar`` …) to a budget that never applied to its wire.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+from jarvis.realtime.session import RealtimeVoiceSession
+
+
+class _Transport:
+ creates_responses_automatically = False
+
+ async def send_text(self, text):
+ pass
+
+ async def send_tool_result(self, call_id, name, result):
+ pass
+
+ async def request_response(self, *, required_tool=None):
+ del required_tool
+
+ async def interrupt(self):
+ pass
+
+ async def close(self):
+ pass
+
+
+class _Provider:
+ supports_realtime = True
+ input_sample_rate = 16000
+ output_sample_rate = 24000
+
+ def __init__(self, name: str, budget_tokens: int = 0):
+ self.name = name
+ if budget_tokens:
+ self.tool_declaration_budget_tokens = budget_tokens
+
+ async def can_open_duplex_session(self):
+ return True
+
+ async def open_session(self, cfg):
+ del cfg
+ return _Transport()
+
+
+class _Bridge:
+ """Records every re-fit; reports a change whenever the budget moved."""
+
+ def __init__(self):
+ self.budgets: list[int] = []
+ self.declarations = ({"name": "wiki_recall"},)
+ self.dropped_names = ()
+ self.declaration_chars = 100
+
+ def set_declaration_budget(self, budget_chars: int) -> bool:
+ changed = not self.budgets or self.budgets[-1] != budget_chars
+ self.budgets.append(budget_chars)
+ return changed
+
+
+def _cfg(budget_tokens: int = 20_000):
+ return SimpleNamespace(
+ brain=SimpleNamespace(reply_language="auto", providers={}),
+ stt=SimpleNamespace(language="auto"),
+ voice=SimpleNamespace(
+ mode="realtime", realtime_tool_declaration_budget_tokens=budget_tokens
+ ),
+ latency=SimpleNamespace(enabled=False),
+ )
+
+
+def _build(providers, *, budget_tokens: int = 20_000):
+ return RealtimeVoiceSession(
+ session_id="budget-per-provider",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda _message: asyncio.sleep(0),
+ provider=providers[0],
+ providers=providers,
+ config=_cfg(budget_tokens),
+ bus=None,
+ brain=None,
+ )
+
+
+def test_the_chain_minimum_is_only_the_first_conservative_fit() -> None:
+ gemini = _Provider("gemini-live")
+ openai = _Provider("openai-realtime", budget_tokens=8_000)
+ sess = _build([gemini, openai])
+
+ # Before the call knows its provider: the tightest budget anywhere.
+ assert sess._declaration_budget_chars() == 8_000 * 4
+ # For the candidate about to open: ITS budget, bounded by the config.
+ assert sess._declaration_budget_chars(gemini) == 20_000 * 4
+ assert sess._declaration_budget_chars(openai) == 8_000 * 4
+
+
+def test_the_config_bound_still_caps_a_provider_that_declares_none() -> None:
+ gemini = _Provider("gemini-live")
+ sess = _build([gemini], budget_tokens=5_000)
+ assert sess._declaration_budget_chars(gemini) == 5_000 * 4
+
+
+def test_the_connect_path_refits_the_bridge_to_the_opening_provider() -> None:
+ gemini = _Provider("gemini-live")
+ openai = _Provider("openai-realtime", budget_tokens=8_000)
+ sess = _build([gemini, openai])
+ bridge = _Bridge()
+ sess._tool_bridge = bridge
+ sess._tool_mode = "hybrid"
+ sess._delegate_enabled = True
+
+ sess._fit_declaration_budget(gemini)
+ assert bridge.budgets == [20_000 * 4]
+ # A cross-family fallback to the OpenAI wire tightens the set again.
+ sess._fit_declaration_budget(openai)
+ assert bridge.budgets == [20_000 * 4, 8_000 * 4]
+
+
+def test_a_bridge_without_refit_or_a_non_hybrid_session_is_left_alone() -> None:
+ gemini = _Provider("gemini-live")
+ sess = _build([gemini])
+ sess._tool_bridge = SimpleNamespace(declarations=()) # no set_declaration_budget
+ sess._tool_mode = "hybrid"
+ sess._delegate_enabled = True
+ sess._fit_declaration_budget(gemini) # must not raise
+
+ bridge = _Bridge()
+ sess._tool_bridge = bridge
+ sess._tool_mode = "delegate"
+ sess._fit_declaration_budget(gemini)
+ assert bridge.budgets == []
diff --git a/tests/unit/realtime/test_hybrid_tool_mode.py b/tests/unit/realtime/test_hybrid_tool_mode.py
index ea0ac9a86b..4953b54344 100644
--- a/tests/unit/realtime/test_hybrid_tool_mode.py
+++ b/tests/unit/realtime/test_hybrid_tool_mode.py
@@ -719,3 +719,88 @@ async def test_an_explicit_order_still_runs_a_destructive_command():
result = await _shell_call(bridge, order, "Remove-Item C:/Urlaub -Recurse")
assert result["success"] is True
assert gateway.executed == ["run_shell"]
+
+
+# ---------------------------------------------------------------------------
+# Budget: connected music connectors are the last to go; the set re-fits
+# ---------------------------------------------------------------------------
+
+
+def test_connected_music_connectors_are_the_last_to_go(monkeypatch):
+ """Live 2026-08-22 18:16: ``spotify`` and ``youtube_music`` were both
+ dropped under the 8k-token wire budget as part of the "everything else,
+ biggest first" bucket, and "mach Musik an" had no native function to land
+ on. A connector the user connected on purpose outranks every family."""
+ from jarvis.core import music_service as ms
+
+ monkeypatch.setattr(ms, "connected_music_services", lambda: ("youtube_music",))
+ rendered = [
+ ("youtube_music", {"name": "youtube_music", "description": "y" * 900}),
+ ("spotify", {"name": "spotify", "description": "s" * 900}),
+ ("wiki-recall", {"name": "wiki-recall", "description": "w" * 100}),
+ ("search_web", {"name": "search_web", "description": "q" * 100}),
+ ]
+ # Room for roughly one big declaration and the two small ones.
+ kept, dropped = _apply_declaration_budget(
+ rendered, 1_250, keep_last=("youtube_music",)
+ )
+ assert dropped == ["spotify"]
+ assert [name for name, _d in kept] == ["youtube_music", "wiki-recall", "search_web"]
+ # Tighter still: the small unconnected tools go before the connected one.
+ kept, dropped = _apply_declaration_budget(
+ rendered, 1_000, keep_last=("youtube_music",)
+ )
+ assert "youtube_music" in [name for name, _d in kept]
+ assert "youtube_music" not in dropped
+ # The bridge reads the connected set itself.
+ gateway_tools = (
+ _descriptor("youtube_music", 900),
+ _descriptor("spotify", 900),
+ _descriptor("wiki-recall", 100),
+ )
+
+ class _Gateway:
+ def catalog(self):
+ return gateway_tools
+
+ async def execute(self, *_a, **_k):
+ return ToolResult(success=True, output="ok")
+
+ # Uncompacted on purpose: the compact renderer caps every description at
+ # 450 characters, which would put the whole set under this budget.
+ bridge = RealtimeToolBridge(
+ gateway=_Gateway(), language="en", compact=False, declaration_budget_chars=1_300
+ )
+ assert "spotify" in bridge.dropped_names
+ assert "youtube_music" not in bridge.dropped_names
+
+
+def test_bridge_refits_the_declared_set_to_a_new_budget():
+ """The session builds the bridge before it knows the provider; the budget
+ of the provider about to open is applied at connect (ADR-0035 §4)."""
+
+ class _Gateway:
+ def catalog(self):
+ return (
+ _descriptor("agentic-ide-fanout", 2_000),
+ _descriptor("wiki-recall", 100),
+ )
+
+ async def execute(self, *_a, **_k):
+ return ToolResult(success=True, output="ok")
+
+ bridge = RealtimeToolBridge(
+ gateway=_Gateway(), language="en", compact=True, declaration_budget_chars=600
+ )
+ assert bridge.dropped_names == ("agentic-ide-fanout",)
+ assert bridge.declaration_budget_chars == 600
+ # Same budget → nothing to do.
+ assert bridge.set_declaration_budget(600) is False
+ # A wider budget lets the coding workspace back in.
+ assert bridge.set_declaration_budget(0) is True
+ assert bridge.dropped_names == ()
+ assert any(d["name"].startswith("wiki_recall") for d in bridge.declarations)
+ assert any(d["name"].startswith("agentic_ide_fanout") for d in bridge.declarations)
+ # And the tighter one takes it out again.
+ assert bridge.set_declaration_budget(600) is True
+ assert bridge.dropped_names == ("agentic-ide-fanout",)