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
fix(realtime): shape-check native tool calls on the user's words; plugin tools drop first under the budget
Haraldcc0af10a63e1
diff --git a/docs/adr/0035-realtime-native-tools-except-computer-use.md b/docs/adr/0035-realtime-native-tools-except-computer-use.mdindex 0e8e9d3d49..e9f694073c 100644--- a/docs/adr/0035-realtime-native-tools-except-computer-use.md+++ b/docs/adr/0035-realtime-native-tools-except-computer-use.md@@ -87,6 +87,32 @@ now"*. A delegation is still forced for exactly these classes:Everything else — Wiki, settings, connected data, media, skills, missions,coding panes, files, CLI/MCP/plugin tools — is the live model's own call.+**Execute-side turn-shape guard (live lesson, first hybrid session+2026-08-19 12:50).** Prompt compliance is not a correctness boundary: on+garbled or conversational turns the live model picked *something* — "Was+genau, wie ist mein X-Shield?" called a freshly installed plugin's balance+tool, "Was oh mein Gott, wieso lag es so rum?" called `app-restart` (an+`ask`-tier tool whose two-turn confirmation the next utterance could have+answered). <!-- i18n-allow: quoted live utterances --> The bridge therefore+refuses, on the user's own words (`RealtimeToolBridge._guard` →+`_turn_shape_refusal`, same vocabulary as the planner):++- a namespaced plugin/MCP tool unless the turn names that plugin (id,+ usage-card keywords, or a noun of its tools — `plugin_is_relevant`, the+ rule the router brain already applies before it sees plugin tools);+- an `ask`-tier (or side-effect) tool unless the turn ORDERS an action+ (`turn_planner.is_action_order`: an action verb outside the+ conversational idioms, now including German prefixed verbs "anmachen",+ "einschalten"); <!-- i18n-allow: quoted German verbs -->+- any other non-`safe` tool unless the turn orders, tasks ("kannst du",+ "please"), or asks for the user's world (a planner reason).++A two-turn confirmation resume or a short affirmative (≤ 4 words, the+echo-confirmation classifier) is the second half of an order and is not+shape-checked. `safe` read-only tools are never refused here. The refusal+text tells the model to answer or ask back, and counts as+`native_tool_denied`.+### 3. Slow native calls get the instant ackA native function call is blocking on every current transport (ADR-0034 §2:@@ -110,9 +136,11 @@ 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 adeterministic 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+within the lowest-priority family: namespaced plugin/MCP tools first (the+most numerous and the most domain-specific; a freshly installed MCP plugin+alone added ~80 on 2026-08-19 and would otherwise have pushed the coding+workspace out), then `cli_*`, then `agentic-ide-*`, 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)diff --git a/jarvis/brain/turn_planner.py b/jarvis/brain/turn_planner.pyindex 33d9b86b95..5ebe39457d 100644--- a/jarvis/brain/turn_planner.py+++ b/jarvis/brain/turn_planner.py@@ -285,6 +285,10 @@ _ACTION_FALLBACK_RE = re.compile(r"stell\w*|spiel\w*|merk(?!wuerdig)\w*|notier\w*|trag(?!isch|oedi)\w*|"r"leg(?:e|st|t|en)?\b|anleg\w*|setz\w*|pausier\w*|aktivier\w*|deaktivier\w*|"r"erinner\w*|dreh\w*|mach\w*|nutz\w*|benutz\w*|verwend\w*|"+ # German prefixed verbs ("anmachen", "einschalten", "ausstellen",+ # "aufdrehen"): the bare stems above never see them, because the prefix+ # sits before the stem inside one word. # i18n-allow: names the German verb forms+ r"(?:an|aus|ein|auf|zu|um|ab)(?:mach|schalt|stell|dreh)\w*|"r"sprich\w*|sprech\w*|brich|brech\w*|abbrech\w*|lauter|leiser|" # i18n-allow: speech inputr"abre\w*|cierra\w*|inicia\w*|crea\w*|escrib\w*|guarda\w*|"r"cambia\w*|instala\w*|conecta\w*|elimina\w*|envia\w*|"@@ -662,6 +666,33 @@ def is_lookup_shape(text: str) -> bool:)+def is_action_order(text: str) -> bool:+ """Whether ``text`` orders an action: an action verb outside the+ conversational idioms.++ The execute-side guard for native realtime tool calls (ADR-0035) uses it:+ an ``ask``-tier tool may run only on a turn that orders something. Pure+ regex over the idiom-stripped utterance — the same weak-scan text+ ``plan_turn`` feeds its action detector.+ """+ normalized = _normalize(text).strip()+ if not normalized:+ return False+ weak_scan_text = _ASSISTANT_DAYPLAN_RE.sub(" ", normalized)+ weak_scan_text = _DATE_TRIVIA_RE.sub(" ", weak_scan_text)+ weak_scan_text = _GERMAN_NONCOMMAND_ACTION_SPAN_RE.sub(" ", weak_scan_text)+ weak_scan_text = _TALK_TO_ME_RE.sub(" ", weak_scan_text)+ weak_scan_text = _WELLBEING_RE.sub(" ", weak_scan_text)+ return bool(_ACTION_FALLBACK_RE.search(weak_scan_text))+++def is_assistant_tasking(text: str) -> bool:+ """Whether ``text`` explicitly tasks the assistant ("kannst du", "please",+ "dass du") — weaker than an action verb, stronger than a bare question."""+ normalized = _normalize(text).strip()+ return bool(normalized and _ASSISTANT_TASKING_RE.search(normalized))++def is_public_fact_question(text: str) -> bool:"""Return whether ``text`` asks for a concrete public-world fact.@@ -1061,6 +1092,8 @@ __all__ = ["TurnPath","TurnPlan","TurnReason",+ "is_action_order",+ "is_assistant_tasking","is_contextual_follow_up","is_public_fact_question","plan_turn",diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex a772dd1bcd..044b76d784 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -793,14 +793,22 @@ _HYBRID_ROLE_DIRECTIVE = ("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."+ "of calling. Plugin and MCP functions — the ones carrying a service name "+ "— are for requests that name or clearly mean that service; never reach "+ "for one because it is merely available. A function whose purpose does "+ "not match the request is never a substitute for a matching one: when the "+ "request is unclear, garbled, or no function fits, do not guess a "+ "function — answer what you can or ask one short question back. 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."+ "This current turn looks like it needs the user's own world (their data, "+ "settings, connected services, or an action on their behalf). If one of "+ "your functions clearly matches the request, call it NOW, in this "+ "response, and answer from its result; do not answer from guesswork and "+ "do not merely announce a lookup. If no function clearly matches, do not "+ "call one at random — ask one short question back instead. Use "+ "jarvis_action only if no function of yours covers a clear request.")_HYBRID_DISCOURAGED_DIRECTIVE = ("This current turn looks like general world knowledge or ordinary "diff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.pyindex df59b7a751..f7bfb2484e 100644--- a/jarvis/realtime/tools.py+++ b/jarvis/realtime/tools.py@@ -28,6 +28,11 @@ from jarvis.brain.tool_use_loop import (_is_stt_hallucinated,_should_block_action_as_research,)+from jarvis.brain.turn_planner import (+ is_action_order,+ is_assistant_tasking,+ plan_turn,+)from jarvis.core import runtime_refsfrom jarvis.core.protocols import (RiskTier,@@ -56,10 +61,18 @@ CHARS_PER_TOKEN = 4# 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.+#+# Order (live lesson 2026-08-19 12:50, the first hybrid session): one freshly+# installed MCP plugin contributed ~80 namespaced tools and the budget then+# dropped the ENTIRE coding-workspace family (agentic-ide-*) while dozens of+# that plugin's tools stayed declared. Namespaced plugin/MCP tools go first —+# they are the most numerous, the most domain-specific, and each is gated at+# execute time on the user naming its service anyway — then connected CLIs,+# then the coding workspace, then everything else._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__|/")),+ ("cli", re.compile(r"^cli_")),+ ("agentic-ide", re.compile(r"^agentic[-_]ide[-_]")),)log = logging.getLogger(__name__)@@ -127,6 +140,83 @@ def _compact_schema(schema: Any, parameter_description_limit: int) -> Any:return schema+def _plugin_id_of(name: str) -> str:+ """``"<plugin>/<tool>"`` → ``"<plugin>"``; ``""`` for native tools."""+ pid, sep, _rest = str(name or "").partition("/")+ return pid if sep else ""+++def _turn_shape_refusal(descriptor: SupervisorToolDescriptor, name: str, user_text: str) -> str:+ """Refuse a native call whose tool the user's words cannot have asked for.++ The live model holds the whole catalog (ADR-0035) and, on a garbled or+ conversational turn, picks SOMETHING: in the first hybrid session+ (2026-08-19 12:50) "Was genau, wie ist mein X-Shield?" called a+ freshly installed plugin's balance tool, and "Was oh mein Gott, wieso lag+ es so rum?" called app-restart — an ``ask``-tier tool whose two-turn+ confirmation the very next utterance could have answered. Prompt+ compliance is not a correctness boundary (BUG-047 class rule); the+ boundary is here, at execute time, on the user's own words: # i18n-allow: quoted utterances++ * a namespaced plugin/MCP tool runs only when the turn names that plugin+ (its id, its usage-card keywords, or a noun of its own tools) — the same+ relevance rule the router brain applies before it even sees them;+ * an ``ask``-tier tool runs only on a turn that ORDERS an action (an+ action verb); a question, an exclamation, or a greeting never does;+ * any other non-``safe`` tool runs only on a turn that orders, tasks, or+ asks for the user's world (a planner reason) — a turn with none of+ those ("Was geht ab?", "Okay.") gets no side effect. # i18n-allow: quoted utterances++ Read-only ``safe`` tools are never refused here. An empty utterance+ (non-conversational launch routes) fails open. Returns the model-facing+ refusal text, or ``""`` to allow.+ """+ text = str(user_text or "").strip()+ if not text:+ return ""+ plugin_id = _plugin_id_of(name)+ if plugin_id:+ try:+ from jarvis.marketplace.plugin_relevance import plugin_is_relevant++ relevant = plugin_is_relevant(text, plugin_id, [descriptor])+ except Exception: # noqa: BLE001 — a relevance fault must not brick the plugin+ relevant = True+ if not relevant:+ return (+ f"{name} was not run: the user did not mention the {plugin_id} "+ "service, so its functions are not what this request asks for. "+ "Answer the user's actual request; call a plugin function only "+ "when the user names that service or clearly asks for it."+ )+ tier = str(getattr(descriptor, "risk_tier", "monitor") or "monitor")+ if tier == "safe":+ return ""+ orders = is_action_order(text)+ if tier in {"ask", "block"} or _is_side_effect_tool(descriptor):+ if orders:+ return ""+ return (+ f"{name} was not run: the user's words do not order an action — "+ "they are a question, a remark, or a greeting. Never start a "+ "consequential action from such a turn. Answer the user directly, "+ "or ask what they want done."+ )+ if orders or is_assistant_tasking(text):+ return ""+ try:+ has_world_reason = bool(plan_turn(text).reasons)+ except Exception: # noqa: BLE001 — the planner must not brick a tool call+ has_world_reason = True+ if has_world_reason:+ return ""+ return (+ f"{name} was not run: nothing in the user's words asks for it — no "+ "action, no request about their data or services. Answer the user "+ "directly; if you are unsure what they want, ask."+ )++def _declaration_size(declaration: dict[str, Any]) -> int:try:return len(json.dumps(declaration, ensure_ascii=False, default=str))@@ -612,11 +702,34 @@ class RealtimeToolBridge:"",):message = "This sounds like research, not an action on a connected system."- else:+ elif self._answers_a_pending_question(name, user_text):+ # The second half of an order the model already asked about+ # (a two-turn confirmation, a confirmed delegation offer) is not+ # a fresh turn to shape-check: "Yes." orders nothing by itself.return ""+ else:+ message = _turn_shape_refusal(descriptor, name, user_text)+ if not message:+ return ""await self._publish_denied(name, message)return message+ def _answers_a_pending_question(self, name: str, user_text: str) -> bool:+ pending = self._pending+ if pending is not None and pending.tool_name == name:+ return True+ # A SHORT affirmative ("Ja.", "Yes, go ahead.") answers an offer the+ # model made in its own words (the confirmed-delegation unlock). Long+ # sentences are not confirmations even when they contain an+ # affirmative token — "Was genau, wie ist mein X-Shield?" carries+ # "genau" and is a question (live 2026-08-19). # i18n-allow: quoted utterance+ if len(str(user_text or "").split()) > 4:+ return False+ try:+ return classify_response(user_text, language=self._language) == "confirm"+ except Exception: # noqa: BLE001 — the classifier must not brick a call+ return False+async def _publish_denied(self, name: str, reason: str) -> None:publisher = getattr(self._gateway if self._gateway is not None else self._executor,diff --git a/tests/unit/realtime/test_hybrid_tool_mode.py b/tests/unit/realtime/test_hybrid_tool_mode.pyindex cdf496bf6d..95a23d1cf7 100644--- a/tests/unit/realtime/test_hybrid_tool_mode.py+++ b/tests/unit/realtime/test_hybrid_tool_mode.py@@ -186,7 +186,7 @@ async def test_hybrid_leaves_planner_action_turns_to_the_live_model(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+ assert "call it NOW, in this response" in joinedawait sess.end(reason="test")@@ -265,22 +265,33 @@ def test_declaration_budget_drops_deterministically_and_keeps_the_rest() -> None("wiki-recall", {"name": "wiki-recall", "description": "w" * 200}),("search_web", {"name": "search_web", "description": "s" * 100}),]+ rendered.insert(+ 0, ("higgsfield/balance", {"name": "higgsfield_balance", "description": "h" * 50})+ )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"]+ # The lowest-priority family first (namespaced plugin/MCP tools), then+ # connected CLIs, then the coding workspace — longest member first.+ assert dropped == ["higgsfield/balance"]+ kept, dropped = _apply_declaration_budget(rendered, total - 100)+ assert dropped == ["higgsfield/balance", "cli_gcloud"]assert [name for name, _d in kept] == [+ "agentic-ide-fanout","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 dropped[:4] == [+ "higgsfield/balance",+ "cli_gcloud",+ "agentic-ide-fanout",+ "agentic-ide-focus",+ ]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+ assert dropped == [] and len(kept) == 6def test_bridge_budget_hides_dropped_tools_and_reports_them() -> None:@@ -313,10 +324,10 @@ def test_router_catalog_renders_for_every_realtime_wire() -> None:"""ADR-0035 §8: every router tool survives the compact rendering, thewire-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, VoiceConfigfrom jarvis.core.bus import EventBus+ from jarvis.core.config import JarvisConfig, VoiceConfigfrom jarvis.plugins.realtime.gemini_live import _sanitize_declarations- from jarvis.realtime.tools import CHARS_PER_TOKEN, _VALID_WIRE_NAME+ from jarvis.realtime.tools import _VALID_WIRE_NAME, CHARS_PER_TOKENtools = _load_tools_for_tier("router",@@ -354,3 +365,104 @@ def test_router_catalog_renders_for_every_realtime_wire() -> None:properties = params.get("properties") or {}for required in params.get("required") or ():assert required in properties, (entry["name"], required)+++# --- Execute-side turn-shape guards (live lesson 2026-08-19 12:50) ----------+++def _descriptor_with_tier(name: str, tier: str) -> SupervisorToolDescriptor:+ return SupervisorToolDescriptor(+ name=name,+ description=f"{name} tool",+ input_schema={"type": "object", "properties": {}},+ risk_tier=tier, # type: ignore[arg-type]+ is_action_tool=False,+ )+++class _RecordingGateway:+ def __init__(self, descriptors):+ self._items = tuple(descriptors)+ self.executed: list[str] = []++ def catalog(self):+ return self._items++ async def execute(self, name, _arguments, _request):+ self.executed.append(name)+ return ToolResult(success=True, output="ok")++ async def publish_guard_denied(self, *_a, **_k):+ return None+++def _guarded_bridge():+ gateway = _RecordingGateway(+ [+ _descriptor_with_tier("app-restart", "ask"),+ _descriptor_with_tier("higgsfield/balance", "monitor"),+ _descriptor_with_tier("google_calendar", "monitor"),+ _descriptor_with_tier("spotify", "monitor"),+ _descriptor_with_tier("search_web", "safe"),+ ]+ )+ bridge = RealtimeToolBridge(gateway=gateway, language="de", compact=True)+ return gateway, bridge+++async def _call(bridge, wire_name, user_text):+ await bridge.handle_user_transcript(user_text)+ _name, result = await bridge.execute(wire_name=wire_name, arguments={})+ return result+++async def test_ask_tier_tool_needs_an_action_order():+ gateway, bridge = _guarded_bridge()+ # The live incident: a remark/question must never start app-restart.+ wire = "app_restart_" + _wire_suffix("app-restart")+ remark = "Was oh mein Gott, wieso lag es so rum?" # i18n-allow: live utterance+ result = await _call(bridge, wire, remark)+ assert result["success"] is False and "was not run" in result["error"]+ assert gateway.executed == []+ # An order does.+ result = await _call(bridge, wire, "Starte die App neu.") # i18n-allow: German fixture+ assert result["success"] is True+ assert gateway.executed == ["app-restart"]+++async def test_plugin_tool_needs_its_service_named():+ gateway, bridge = _guarded_bridge()+ wire = "higgsfield_balance_" + _wire_suffix("higgsfield/balance")+ result = await _call(bridge, wire, "Was genau, wie ist mein X-Shield?") # i18n-allow: live+ assert result["success"] is False and "did not mention the higgsfield" in result["error"]+ assert gateway.executed == []+ result = await _call(bridge, wire, "Wie ist mein Guthaben bei Higgsfield?") # i18n-allow+ assert result["success"] is True+ assert gateway.executed == ["higgsfield/balance"]+++async def test_monitor_tool_needs_an_order_a_tasking_or_a_world_request():+ gateway, bridge = _guarded_bridge()+ # Smalltalk: no side effect.+ result = await _call(bridge, "spotify", "Was geht ab?") # i18n-allow: German fixture+ assert result["success"] is False and "was not run" in result["error"]+ # A data request about the user's world is allowed on a monitor tool.+ calendar_question = "Was steht heute in meinem Kalender?" # i18n-allow: German fixture+ result = await _call(bridge, "google_calendar", calendar_question)+ assert result["success"] is True+ # An order is allowed.+ result = await _call(bridge, "spotify", "Spiel mir was von Ed Sheeran.") # i18n-allow: fixture+ assert result["success"] is True+ # Safe tools are never refused by the shape guard.+ result = await _call(bridge, "search_web", "Was geht ab?") # i18n-allow: German fixture+ assert result["success"] is True+ assert gateway.executed == ["google_calendar", "spotify", "search_web"]+++def _wire_suffix(name: str) -> str:+ import hashlib++ return hashlib.sha256(name.encode("utf-8")).hexdigest()[:10]