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(skills): recognise a skill from what the user means, not the words
Harald7c0073123897
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex ef0d189676..56cdb52ad4 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -5982,14 +5982,14 @@ class BrainManager:if conditional is not None:return conditional- lines = [f"- `{getattr(s, 'name', '')}` — {b}" for _, s, b in scored]- return (- "[Skill candidates] The user's request scored against these "- "installed skills. If one genuinely fits, call the `run-skill` tool "- "with that name FIRST and follow the returned instructions. If none "- "fits, ignore this block entirely and answer normally — these are "- "ranked suggestions, not a verdict.\n" + "\n".join(lines)- )+ # Shared with the realtime session's own candidate hint — one wording,+ # so the suggestion does not change shape depending on which engine is+ # answering (jarvis/skills/prompt_injection.py).+ from jarvis.skills.prompt_injection import render_skill_candidate_hint++ return render_skill_candidate_hint(+ [(str(getattr(s, "name", "")), b) for _, s, b in scored]+ ) or Nonedef _render_conditional_narrow_injection(self,diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex aa842071b1..d3b6819691 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -2744,6 +2744,79 @@ class RealtimeVoiceSession:except Exception: # noqa: BLE001 — never cost the turn its answerlog.debug("Realtime skill handoff skipped", exc_info=True)+ def _skill_candidates_directive(self, text: str) -> str:+ """Skills that scored on this turn but not strongly enough to take it.++ The scorer routinely finds the right skill for a paraphrase and lands+ in the NARROW band, which never captures — a matched skill is a+ TAKEOVER (it strips ``run-skill``, stands down computer-use and the+ evidence gate), so the floor sits at FIRE for good reason. Measured on+ the shipped corpus: of ten natural requests carrying no trigger phrase,+ the scorer identified the right skill six times and fired three.++ The brain path already turns that surplus into a suggestion the model+ may ignore. Realtime discarded it. This closes that gap, at NARROW+ only: a FIRE match is already inlined by ``_skill_directive`` or handed+ to the brain by ``_note_skill_for_delegate``, and showing it here too+ would put two instruction sets on one turn.++ Never raises — a suggestion must not be able to cost a live call.+ """+ utterance = str(text or "").strip()+ if not utterance:+ return ""+ try:+ from jarvis.skills.match_eval import BAND_NARROW, evaluate_match+ from jarvis.skills.prompt_injection import render_skill_candidate_hint+ from jarvis.skills.skill_context import try_get_skill_context++ context = try_get_skill_context()+ if context is None:+ return ""+ limit = max(1, int(getattr(self._skills_cfg(), "narrow_candidates", 3)))+ decision = evaluate_match(context.registry, utterance, limit=limit + 2)+ if decision.band != BAND_NARROW:+ return ""+ entries: list[tuple[str, str]] = []+ for candidate in decision.candidates or ():+ if len(entries) >= limit:+ break+ if getattr(candidate, "band", "") != BAND_NARROW:+ continue+ try:+ skill = context.registry.get(candidate.skill_name)+ except Exception: # noqa: BLE001+ # The index ranked a name the registry no longer holds —+ # a hot reload between ranking and rendering. Skip that+ # candidate, keep the rest of the hint.+ log.debug(+ "skill candidate %r vanished between rank and render",+ candidate.skill_name,+ exc_info=True,+ )+ continue+ frontmatter = getattr(skill, "frontmatter", None)+ if frontmatter is None:+ continue+ blurb = " ".join(+ f"{getattr(frontmatter, 'description', '') or ''} "+ f"{getattr(frontmatter, 'when_to_use', '') or ''}".split()+ )[:400]+ entries.append((str(skill.name), blurb))+ return render_skill_candidate_hint(entries)+ except Exception: # noqa: BLE001 — a hint must never end a call+ log.debug("Realtime skill candidate hint unavailable", exc_info=True)+ return ""++ def _skills_cfg(self) -> Any:+ """The ``[skills]`` config section, or defaults."""+ section = getattr(self._config, "skills", None)+ if section is not None:+ return section+ from jarvis.core.config import SkillsConfig++ return SkillsConfig()+def _skills_directive(self, *, compact: bool | None = None) -> str:"""The installed-skill roster for this session's instructions.@@ -4647,8 +4720,16 @@ class RealtimeVoiceSession:# fires on every final transcript, so a# qualifying skill rides along instead of paying# the delegate boundary wait.- skill_directive=self._skill_directive(- self._last_user_text or ""+ # Captured skill, else the ranked suggestion —+ # mutually exclusive by construction (one is+ # FIRE-only, the other NARROW-only), and the+ # same either/or the brain path uses, so a turn+ # never carries two instruction sets.+ skill_directive=(+ self._skill_directive(self._last_user_text or "")+ or self._skill_candidates_directive(+ self._last_user_text or ""+ )),skills_directive=self._skills_directive(),# Rebuilt per turn: panes open and close middiff --git a/jarvis/skills/prompt_injection.py b/jarvis/skills/prompt_injection.pyindex 742dfefae0..5ba005461f 100644--- a/jarvis/skills/prompt_injection.py+++ b/jarvis/skills/prompt_injection.py@@ -19,6 +19,8 @@ Design constraints:"""from __future__ import annotations+from collections.abc import Sequence+from jarvis.skills.registry import SkillRegistry# Per-entry cap on the rendered description+when_to_use text (mirrors the@@ -194,8 +196,44 @@ def render_available_skills_section(return f"{header}\n{intro}\n{body}{outro}"-#: Per-entry description budget for the realtime roster. The block is re-sent-#: with every per-turn session update, so it buys names first and prose second.+def render_skill_candidate_hint(entries: Sequence[tuple[str, str]]) -> str:+ """The "these scored, you decide" block for a turn nothing captured.++ One home for this wording on purpose. The brain path has shipped it since+ the 2026-08-12 rework and the realtime path had nothing at all, so a NARROW+ match — the scorer found the right skill but not strongly enough to take+ the turn over — was simply discarded in a live call. Two renderers would+ drift, and a hint that says something different depending on which engine+ is running is worse than one that is merely imperfect.++ ``entries`` is ``(skill_name, blurb)``, best first and already truncated by+ the caller. Returns ``""`` for an empty list so callers can append blindly.++ The decision explicitly stays with the model: a wrong candidate is ignored,+ never executed. That is what makes this block safe to show on a merely+ plausible match, where an automatic capture would not be.+ """+ lines = [f"- `{name}` — {blurb}" if blurb else f"- `{name}`" for name, blurb in entries]+ if not lines:+ return ""+ return (+ "[Skill candidates] The user's request scored against these "+ "installed skills. If one genuinely fits, call the `run-skill` tool "+ "with that name FIRST and follow the returned instructions. If none "+ "fits, ignore this block entirely and answer normally — these are "+ "ranked suggestions, not a verdict.\n" + "\n".join(lines)+ )+++#: Per-entry budget for the RICH realtime tier: description + when_to_use.+#: ``when_to_use`` is the field that says when a skill applies, in the words+#: people actually use — it is what lets a model match "wie sieht mein Tag aus"+#: to a skill triggered on "Morgenroutine". The first realtime roster shipped+#: description-only at 70 chars and cut exactly that text off, which left the+#: live model with a topic label instead of a matching rule.+_REALTIME_RICH_CHARS = 300++#: Per-entry budget for the SHORT tier — description only, no matching rule._REALTIME_DESC_CHARS = 70@@ -203,7 +241,7 @@ def render_realtime_skills_directive(registry: SkillRegistry,*,compact: bool = False,- budget_chars: int = 4000,+ budget_chars: int = 9000,) -> str:"""Render the installed-skill roster for a live voice session.@@ -216,11 +254,17 @@ def render_realtime_skills_directive(heard of — and it binds every realtime transport alike, because they allshare one instruction builder.- Names outrank prose here. When the roster does not fit ``budget_chars``- the descriptions are dropped and every name is kept, never the other way- round: a described skill that is missing from the list is uncallable,- while a bare name is still enough for ``run-skill`` to resolve. ``compact``- (small self-hosted brains) goes straight to the names-only form.+ Degrades in three steps, richest first, and never below the names:++ 1. name + description + ``when_to_use`` — the matching rule, so the model+ can recognise a paraphrase the author's trigger regex never predicted.+ This is the tier that makes recognition work like Claude Code's;+ 2. name + short description — the topic, without the matching rule;+ 3. names only.++ Names outrank prose at every step: a described skill that is missing from+ the list is uncallable, while a bare name is still enough for ``run-skill``+ to resolve. ``compact`` (small self-hosted brains) goes straight to step 3.Returns ``""`` when no skill is invocable, so the caller can drop theblock from the instruction assembly entirely.@@ -229,7 +273,8 @@ def render_realtime_skills_directive(active = registry.list_active()except Exception: # noqa: BLE001 — a roster fault must never break a callreturn ""- entries: list[tuple[str, str, bool]] = [] # (name, description, is_builtin)+ # (name, rich blurb, short blurb, is_builtin)+ entries: list[tuple[str, str, str, bool]] = []for skill in active:fm = getattr(skill, "frontmatter", None)if fm is None:@@ -238,31 +283,42 @@ def render_realtime_skills_directive(if not name:continuedesc = " ".join((getattr(fm, "description", "") or "").split())- if len(desc) > _REALTIME_DESC_CHARS:- desc = desc[: _REALTIME_DESC_CHARS - 1].rstrip() + "…"- entries.append((name, desc, _is_builtin(skill)))+ when = " ".join((getattr(fm, "when_to_use", "") or "").split())+ rich = f"{desc} {when}".strip()+ if len(rich) > _REALTIME_RICH_CHARS:+ rich = rich[: _REALTIME_RICH_CHARS - 1].rstrip() + "…"+ short = desc+ if len(short) > _REALTIME_DESC_CHARS:+ short = short[: _REALTIME_DESC_CHARS - 1].rstrip() + "…"+ entries.append((name, rich, short, _is_builtin(skill)))if not entries:return ""# User-authored skills first — same attention argument as the brain listing.- entries.sort(key=lambda e: (e[2], e[0]))- names_only = ", ".join(name for name, _, _ in entries)+ entries.sort(key=lambda e: (e[3], e[0]))header = "[Installed skills — the user's saved way of doing these tasks]\n"rule = (- "\nTo run one, call the run-skill tool with the name EXACTLY as spelled "- "above — copy it character for character, never re-word it and never "- "invent one that is not listed. If the user names a skill that is not "- "on this list, say so instead of guessing. A matching skill always "- "beats answering from scratch. A plain question that merely mentions "- "the topic is not a match."+ "\nEach line says what a skill is for and when it applies. Match on "+ "MEANING, not on wording: the user will not repeat these words, so a "+ "request that asks for the same outcome is a match even when it shares "+ "no vocabulary with the line. To run one, call the run-skill tool with "+ "the name EXACTLY as spelled above — copy it character for character, "+ "never re-word it and never invent one that is not listed. If the user "+ "names a skill that is not on this list, say so instead of guessing. A "+ "matching skill always beats answering from scratch. A plain question "+ "that merely mentions the topic is not a match.")+if not compact:- listed = "\n".join(- f"- {name} — {desc}" if desc else f"- {name}"- for name, desc, _ in entries- )- block = f"{header}{listed}{rule}"- if len(block) <= budget_chars:- return block+ for index in (1, 2): # 1 = rich blurb, 2 = short blurb+ listed = "\n".join(+ f"- {name} — {entry[index]}" if entry[index] else f"- {name}"+ for entry in entries+ for name in (entry[0],)+ )+ block = f"{header}{listed}{rule}"+ if len(block) <= budget_chars:+ return block+ names_only = ", ".join(name for name, _, _, _ in entries)return f"{header}{names_only}{rule}"diff --git a/tests/unit/realtime/test_session_skills_roster.py b/tests/unit/realtime/test_session_skills_roster.pyindex 3ccad511b2..e32f186298 100644--- a/tests/unit/realtime/test_session_skills_roster.py+++ b/tests/unit/realtime/test_session_skills_roster.py@@ -51,7 +51,13 @@ class _Session:)-def _write_skill(root: Path, name: str, *, description: str = "test skill") -> None:+def _write_skill(+ root: Path,+ name: str,+ *,+ description: str = "test skill",+ tags: str = "",+) -> None:folder = root / namefolder.mkdir(parents=True, exist_ok=True)(folder / "SKILL.md").write_text(@@ -61,6 +67,7 @@ def _write_skill(root: Path, name: str, *, description: str = "test skill") -> N'schema_version: "1"',f"name: {name}",f"description: {description}",+ *([f"tags: {tags}"] if tags else []),"---","","## Body",@@ -213,3 +220,97 @@ def test_a_brain_without_the_hook_is_tolerated(skills_root: Path) -> None:_install(skills_root)_Session(brain=object())._note_skill_for_delegate("morning-routine")+++# ---------------------------------------------------------------------------+# NARROW candidates become a suggestion instead of silence+# ---------------------------------------------------------------------------+++class _CfgSession(_Session):+ """Adds the config surface the candidate hint reads."""++ def __init__(self, **kw) -> None:+ super().__init__(**kw)+ self._config = None++ def _has_pending_delegate_from_earlier_turn(self) -> bool:+ return False++ _skill_candidates_directive = (+ session_module.RealtimeVoiceSession._skill_candidates_directive+ )+ _skills_cfg = session_module.RealtimeVoiceSession._skills_cfg+ _skill_directive = session_module.RealtimeVoiceSession._skill_directive+++#: Scores 0.756 against the fixture below, between its HINT floor (0.330) and+#: its FIRE floor (1.019) — i.e. exactly the band this feature is about.+NARROW_UTTERANCE = "ich brauche konzentration" # i18n-allow: test input+++def _narrow_root(tmp_path: Path) -> Path:+ """A corpus where a paraphrase scores but does not reach FIRE."""+ root = tmp_path / "skills"+ root.mkdir()+ _write_skill(+ root,+ "deep-work-mode",+ description=(+ "Activates a distraction-free focus sprint with a pomodoro timer."+ ),+ tags="[pomodoro, fokus, konzentration, ruhe]", # i18n-allow: fixture data+ )+ for index in range(8):+ _write_skill(root, f"filler-{index}", description=f"unrelated topic {index}")+ return root+++def test_a_narrow_match_is_offered_to_the_model(tmp_path: Path) -> None:+ """The scorer finds the right skill for a paraphrase far more often than it+ fires — measured six of ten on the shipped corpus, three fired. The brain+ path already turned that surplus into a suggestion; realtime discarded it."""+ _install(_narrow_root(tmp_path))++ hint = _CfgSession()._skill_candidates_directive(NARROW_UTTERANCE)++ assert "deep-work-mode" in hint+ assert "not a verdict" in hint+++def test_an_empty_utterance_offers_nothing(tmp_path: Path) -> None:+ _install(_narrow_root(tmp_path))++ assert _CfgSession()._skill_candidates_directive(" ") == ""+++def test_an_unrelated_turn_offers_nothing(tmp_path: Path) -> None:+ """Silence is the common case and must stay free."""+ _install(_narrow_root(tmp_path))++ assert _CfgSession()._skill_candidates_directive("danke dir") == "" # i18n-allow+++def test_a_fire_match_is_not_also_offered_as_a_candidate(+ skills_root: Path,+) -> None:+ """A FIRE match is inlined or handed to the brain. Adding the hint on top+ would put two instruction sets on one turn."""+ _install(skills_root)+ session = _CfgSession()++ # The builtin's own trigger vocabulary — a FIRE-band hit, not a paraphrase.+ assert session._skill_candidates_directive("morning-routine") == ""+++def test_a_registry_fault_never_breaks_the_hint(skills_root: Path) -> None:+ class _Exploding:+ def list_active(self): # noqa: ANN202+ raise RuntimeError("registry is on fire")++ def get(self, name): # noqa: ANN202+ raise RuntimeError("registry is on fire")++ set_skill_context(SkillContext(registry=_Exploding(), runner=_StubRunner())) # type: ignore[arg-type]++ assert _CfgSession()._skill_candidates_directive("anything at all") == ""diff --git a/tests/unit/skills/test_prompt_injection.py b/tests/unit/skills/test_prompt_injection.pyindex 6ce8d8950d..e600537950 100644--- a/tests/unit/skills/test_prompt_injection.py+++ b/tests/unit/skills/test_prompt_injection.py@@ -15,6 +15,7 @@ from dataclasses import dataclassfrom jarvis.skills.prompt_injection import (render_available_skills_section,render_realtime_skills_directive,+ render_skill_candidate_hint,)@@ -464,3 +465,64 @@ def test_realtime_directive_skips_skills_without_frontmatter() -> None:assert "morning-routine" in outassert "broken" not in out+++def test_realtime_directive_carries_the_when_to_use_matching_rule() -> None:+ """``when_to_use`` is the field that says WHEN a skill applies, in the+ words people actually use. The first realtime roster shipped+ description-only at 70 chars and cut it off, leaving the live model a topic+ label where it needed a matching rule."""+ registry = _FakeRegistry(skills=[+ _FakeSkill(name="morning-routine", frontmatter=_FakeFrontmatter(+ description="Delivers the user's spoken morning briefing.",+ when_to_use='Use when the user asks "wie sieht mein Tag aus".')),+ ])++ out = render_realtime_skills_directive(registry) # type: ignore[arg-type]++ assert "wie sieht mein Tag aus" in out+ assert "MEANING" in out # the paraphrase instruction+++def test_realtime_directive_degrades_rich_then_short_then_names() -> None:+ """Three tiers, richest first, and never below the names."""+ skills = [+ _FakeSkill(name=f"skill-{i:02d}", frontmatter=_FakeFrontmatter(+ description=f"Does thing {i}. " + "padding " * 12,+ when_to_use="Use when " + "more padding " * 12))+ for i in range(12)+ ]+ registry = _FakeRegistry(skills=skills)++ rich = render_realtime_skills_directive(registry, budget_chars=99_000) # type: ignore[arg-type]+ short = render_realtime_skills_directive(registry, budget_chars=1_800) # type: ignore[arg-type]+ names = render_realtime_skills_directive(registry, budget_chars=900) # type: ignore[arg-type]++ assert "Use when" in rich+ assert "Use when" not in short and "Does thing 0" in short+ assert "Does thing 0" not in names+ # The one invariant every tier keeps: no skill loses its name.+ for out in (rich, short, names):+ for i in range(12):+ assert f"skill-{i:02d}" in out+++# ----------------------------------------------------------------------+# The shared candidate hint+# ----------------------------------------------------------------------+++def test_candidate_hint_names_the_skills_and_leaves_the_choice_open() -> None:+ out = render_skill_candidate_hint(+ [("morning-routine", "Your day at a glance."), ("deep-work-mode", "")]+ )++ assert "`morning-routine` — Your day at a glance." in out+ assert "`deep-work-mode`" in out+ assert "run-skill" in out+ # The safety argument for showing a merely plausible match at all.+ assert "not a verdict" in out+++def test_candidate_hint_is_empty_without_candidates() -> None:+ assert render_skill_candidate_hint([]) == ""