Skip to content

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

feat(brain): show a model the tools it needs and keep the rest reachable (#618)

Ruben Lütke367429943622
diff --git a/docs/adr/0011-router-pure-dispatcher.md b/docs/adr/0011-router-pure-dispatcher.md
index c085026d7b..118d900586 100644
--- a/docs/adr/0011-router-pure-dispatcher.md
+++ b/docs/adr/0011-router-pure-dispatcher.md
@@ -1454,3 +1454,42 @@ native tools.
echoing provider text, `token_expired` → one refresh + retry, `Retry-After`
handling, cursor pagination, channel/DM resolution, per-action risk tiers.
- `tests/unit/brain/test_routing.py` (exact router set includes `slack`).
+
+## Amendment 2026-10-13 — Shown tools and `find_tools`
+
+`ROUTER_TOOLS` says what the router may call. Which of those schemas ride a
+request is a second decision, made per turn in
+`BrainManager._shortlist_tools` (`jarvis/brain/tool_shortlist.py`).
+
+Until now the answer was "all that fit": when the set exceeded a small
+model's window the largest schemas were dropped first, which removed the
+richly described tools before the trivial ones, and a dropped tool was
+unreachable for the turn. Now the turn's tools are split into a **shown**
+set, chosen by priority (the tool a gate mandated, the caller's own tools,
+the everyday core, then the rest), and a **deferred** rest that stays
+callable. A deferred tool named outright runs; `find_tools` searches the
+deferred set by intent and names what matches, and those tools ride the
+following rounds as ordinary definitions. When the window is what forced the
+split, room for the finder and for what it adds is held back first.
+
+Tools are deferred for three reasons only: the window cannot hold them, the
+window marks a small model (32,768 tokens or less, shown 24 tools besides the
+pinned ones), or the caller has a role that names its tools
+(`TurnOverride.tools_direct`, set for a society agent with a focus). A hosted
+model with room and no role gets the unchanged dict.
+
+`find_tools` is not a member of `ROUTER_TOOLS` and not a standing tool: it is
+built per turn from that turn's deferred dict and exists only when something
+was deferred. It is read-only (`safe`), searches nothing but the dict it was
+built from, and so cannot widen what a turn may call; every call it leads to
+still goes through `ToolExecutor`. A lookup is not an action: it is not
+recorded among the tools that ran, gets no spoken acknowledgement and no
+"done" marker. No spawn tool enters any set through it
+(AP-5/AP-14): it returns only tools the turn already held.
+
+### Regression guards
+
+- `tests/unit/brain/test_tool_shortlist.py` (priority, deferral, the loop
+ revealing found tools, the manager's three reasons)
+- `tests/unit/brain/test_context_window_fit.py` (window and count limits)
+- `tests/unit/brain/test_routing.py` (exact router set, unchanged)
diff --git a/jarvis/agent_chat/runner_brain.py b/jarvis/agent_chat/runner_brain.py
index 4a90cc85c8..4e1501da48 100644
--- a/jarvis/agent_chat/runner_brain.py
+++ b/jarvis/agent_chat/runner_brain.py
@@ -169,6 +169,9 @@ def build_override(
kit.session_tool_filter(session) if kit.session_tool_filter is not None else None,
plan_filter if stance == PLAN_STANCE else None,
),
+ tools_direct=(
+ kit.session_direct_tools(session) if kit.session_direct_tools is not None else None
+ ),
credential_scope=kit.credential_scope,
system_extra=system_extra,
tool_context={
diff --git a/jarvis/agent_chat/surface_kits.py b/jarvis/agent_chat/surface_kits.py
index b9a54f927e..a047f0ba48 100644
--- a/jarvis/agent_chat/surface_kits.py
+++ b/jarvis/agent_chat/surface_kits.py
@@ -42,6 +42,9 @@ ExtraBuilder = Callable[[Any, Any], Awaitable[str]]
SessionToolsBuilder = Callable[[Any, Any, Any], dict[str, Tool]]
SessionExtraBuilder = Callable[[Any, Any, Any], Awaitable[str]]
SessionFilterBuilder = Callable[[Any], Callable[[dict[str, Tool]], dict[str, Tool]] | None]
+#: ``session -> tool names`` this session's caller works with, or ``None``
+#: (see ``TurnOverride.tools_direct``).
+SessionDirectTools = Callable[[Any], frozenset[str] | None]
#: ``(session, tool_name, args) -> handled``: what "Always allow" on the
#: approval card means on this surface. ``True`` = the surface remembered it
#: its own way (a society agent writes its own approval rule); ``False`` =
@@ -104,6 +107,7 @@ class SurfaceKit:
session_tools: SessionToolsBuilder | None = None
session_system_extra: SessionExtraBuilder | None = None
session_tool_filter: SessionFilterBuilder | None = None
+ session_direct_tools: SessionDirectTools | None = None
#: How the card's "Always allow" is remembered here (see the alias above).
session_always_allow: SessionAlwaysAllow | None = None
turn_completed: Callable[[Any, ChatCompletion], Awaitable[None]] | None = None
@@ -173,6 +177,13 @@ def _society_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, Tool]
return society_tool_filter(session)
+def _society_direct(session: Any) -> frozenset[str] | None:
+ """The tools the agent's role points at (lazy)."""
+ from jarvis.society.surface import society_direct_tools
+
+ return society_direct_tools(session)
+
+
async def _society_always_allow(session: Any, tool_name: str, args: dict[str, Any]) -> bool:
""" "Always allow" writes the agent's own approval rule (lazy)."""
from jarvis.society.surface import remember_always_allow
@@ -284,6 +295,7 @@ _KITS: Final[dict[str, SurfaceKit]] = {
session_tools=_society_tools,
session_system_extra=_society_extra,
session_tool_filter=_society_filter,
+ session_direct_tools=_society_direct,
session_always_allow=_society_always_allow,
turn_completed=_society_completed,
history_start=_society_history_start,
diff --git a/jarvis/brain/ack_generator.py b/jarvis/brain/ack_generator.py
index da8c2dfeb5..274ad11c0a 100644
--- a/jarvis/brain/ack_generator.py
+++ b/jarvis/brain/ack_generator.py
@@ -119,6 +119,8 @@ ACK_SKIP_TOOLS: frozenset[str] = frozenset({
# passive observations
"screen_snapshot",
"whoami",
+ # looking up which tool to use is not something to announce
+ "find_tools",
# fast passive memory reads (2026-07-06: wiki-recall answered in 72 ms —
# a spoken "one moment" for that is pure chatter)
"wiki_recall",
diff --git a/jarvis/brain/dispatcher.py b/jarvis/brain/dispatcher.py
index 32964037ad..699b1c70e0 100644
--- a/jarvis/brain/dispatcher.py
+++ b/jarvis/brain/dispatcher.py
@@ -13,7 +13,7 @@ that is the responsibility of `BrainManager` (so we can switch between providers
from __future__ import annotations
import logging
-from collections.abc import AsyncIterator, Awaitable, Callable
+from collections.abc import AsyncIterator, Awaitable, Callable, Iterable
from typing import Any
from uuid import UUID, uuid4
@@ -50,9 +50,13 @@ class BrainDispatcher:
reasoning_effort: ReasoningEffort | None = None,
tool_context: dict[str, Any] | None = None,
loop_control: LoopControl | None = None,
+ deferred_tools: Iterable[str] = (),
) -> None:
self._brain = brain
self._tools = tools or {}
+ # Names in ``tools`` that stay callable but are not shown to the
+ # model (jarvis/brain/tool_shortlist.py).
+ self._deferred_tools = frozenset(deferred_tools)
self._executor = executor
# Extra keys merged into every tool's ``ExecutionContext.config`` for
# this dispatcher's turns (e.g. ``{"delivery": "written"}`` for a
@@ -95,10 +99,12 @@ class BrainDispatcher:
reasoning_effort=self._reasoning_effort,
tool_context=self._tool_context,
loop_control=self._loop_control,
+ deferred_tools=self._deferred_tools,
)
def set_tools(self, tools: dict[str, Tool]) -> None:
self._tools = dict(tools)
+ self._deferred_tools = frozenset()
def set_system_prompt(self, prompt: str | None) -> None:
self._system_prompt = prompt
@@ -180,6 +186,7 @@ class BrainDispatcher:
reasoning_effort=self._reasoning_effort,
tool_context=self._tool_context,
loop_control=self._loop_control,
+ deferred_tools=self._deferred_tools,
)
return await loop.run(
messages,
@@ -244,5 +251,6 @@ class BrainDispatcher:
"description": getattr(t, "description", ""),
"input_schema": t.schema,
}
- for t in self._tools.values()
+ for name, t in self._tools.items()
+ if name not in self._deferred_tools
]
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 487e10a379..b70b95e069 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -40,7 +40,7 @@ from collections.abc import (
)
from contextvars import ContextVar
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any, Literal
+from typing import TYPE_CHECKING, Any, Literal, cast
from uuid import UUID, uuid4
# Real turn outcomes feed the passive health record behind the status dots.
@@ -78,6 +78,13 @@ from jarvis.core.protocols import (
ReasoningEffort,
Tool,
)
+from jarvis.brain.tool_shortlist import (
+ FIND_TOOLS_NAME,
+ ROLE_BASE,
+ FindToolsTool,
+ plan_surface,
+ tool_tokens,
+)
from jarvis.brain.turn_override import TurnOverride
from jarvis.core.redact import safe_preview
from jarvis.core.response_style import CONVERSATIONAL_RESPONSE_STYLE
@@ -3860,6 +3867,8 @@ class BrainManager:
delegated_voice: bool = False,
tool_context: dict[str, Any] | None = None,
loop_control: Any = None,
+ own_tools: Iterable[str] = (),
+ direct_tools: frozenset[str] | None = None,
) -> BrainDispatcher:
"""Builds the dispatcher with an optional tool override.
@@ -3887,24 +3896,39 @@ class BrainManager:
as soon as evidence suffices — to the system prompt of delegated
voice turns only, so classic chat prompts stay byte-identical.
- The tool surface is then sized to the brain's context window
- (2026-08-27, ``_fit_tools_to_brain``); the turn's message log counts
- toward that — a delegated turn's from ``_TURN_HISTORY_OVERRIDE``, a
- classic turn's from the live ``self._history`` (the same two sources
- ``_cu_context_lines`` reads).
+ The tool surface is then split into what the model is shown and
+ what stays callable behind ``find_tools`` (``_shortlist_tools``);
+ the turn's message log counts toward the budget — a delegated turn's
+ from ``_TURN_HISTORY_OVERRIDE``, a classic turn's from the live
+ ``self._history`` (the same two sources ``_cu_context_lines`` reads).
+
+ ``own_tools`` / ``direct_tools``: the caller's own hands, always
+ shown, and — for a caller whose role names the tools it works with —
+ the only others that are (``TurnOverride.tools_direct``).
"""
tools = tools_override if tools_override is not None else self._tools
system_prompt = self._build_system_prompt()
history = _TURN_HISTORY_OVERRIDE.get()
if history is None:
history = tuple(getattr(self, "_history", None) or ())
- tools = self._fit_tools_to_brain(
- tools, brain, system_prompt=system_prompt, history=history
+ tools, deferred = self._shortlist_tools(
+ tools,
+ brain,
+ system_prompt=system_prompt,
+ history=history,
+ own_tools=own_tools,
+ direct_tools=direct_tools,
)
# Per-plugin usage guidance for whichever plugins are active this turn
# (the "MCP + thin skill" reliability layer). Appended last so it sits
# closest to the turn; only present when a plugin tool is in scope.
- cards = self._plugin_usage_cards_block(tools)
+ # Cards only for the tools the model is shown: guidance for a tool it
+ # cannot see spends the window on nothing.
+ cards = self._plugin_usage_cards_block(
+ {name: tool for name, tool in tools.items() if name not in deferred}
+ if deferred
+ else tools
+ )
if cards:
system_prompt = f"{system_prompt}\n\n{cards}"
if delegated_voice:
@@ -3922,6 +3946,7 @@ class BrainManager:
reasoning_effort=reasoning_effort,
tool_context=tool_context,
loop_control=loop_control,
+ deferred_tools=deferred,
**kwargs,
)
@@ -3949,6 +3974,10 @@ class BrainManager:
kwargs["max_turns"] = override.max_turns
if override.loop_control is not None:
kwargs["loop_control"] = override.loop_control
+ if override.tools_extra:
+ kwargs["own_tools"] = tuple(override.tools_extra)
+ if override.tools_direct is not None:
+ kwargs["direct_tools"] = override.tools_direct
return kwargs
async def render_surface_prompt(self, *, user_text: str) -> tuple[str, str]:
@@ -6872,35 +6901,49 @@ class BrainManager:
)
return {n: t for n, t in tools.items() if n != "screenshot"}
- def _fit_tools_to_brain(
+ def _shortlist_tools(
self,
tools: dict[str, Tool],
brain: Any,
*,
system_prompt: str,
history: Sequence[BrainMessage] | None,
- ) -> dict[str, Tool]:
- """Size the turn's tool surface to the answering brain's context window.
-
- Live 2026-08-27 10:11 (and 2026-08-26 20:32, 20:58): the front page's
- chat ran on a local 32k model, the registry held 221 tools (78
- built-in, 131 from three connected MCP servers, 12 CLIs) and a plain
- "Hallo" went out as 67,852 tokens. The server refused it with a 400,
- the one-provider chain was exhausted, and the user read "I can't
- reach my provider — check the network". Nothing had ever read
- ``Brain.context_window``: the Ollama plugin narrows it to the model's
- ``num_ctx`` so the manager can budget, and the manager budgeted
- nothing. Cloud brains declare 128k–1M and are never touched here; a
- brain without a declared window is left alone as well.
-
- The tool a deterministic gate mandated this turn and ``run-skill`` on
- a skill match are never dropped. Everything else follows the order in
- ``_fit_tools_to_context_window``. A tool the model cannot see is one
- capability lost for one turn; a request the server refuses is the
- whole turn lost.
- """
- if not isinstance(tools, dict) or not tools:
- return tools
+ own_tools: Iterable[str] = (),
+ direct_tools: frozenset[str] | None = None,
+ ) -> tuple[dict[str, Tool], frozenset[str]]:
+ """Decide which of the turn's tools the model is SHOWN.
+
+ Returns ``(tools, deferred names)``. Every tool stays in the dict and
+ stays callable; the deferred ones are not put in front of the model
+ and are reached through ``find_tools``
+ (``jarvis/brain/tool_shortlist.py``). With nothing deferred the dict comes back
+ untouched, which is every turn of a hosted model with room to spare.
+
+ Three reasons to defer, each on its own evidence:
+
+ * **The window.** Live 2026-08-27: a local 32k model, 221 tools, a
+ plain "Hallo" went out as 67,852 tokens and the server refused it.
+ The first answer dropped what did not fit, largest first — which
+ removed the richly described tools (a save tool with a real schema)
+ before a parameterless list tool, and a dropped tool was gone for
+ the turn. Now the everyday tools are shown first and the rest is
+ deferred, not lost.
+ * **A small model.** A window of ``_SMALL_WINDOW_TOKENS`` or less is
+ a small model, and a small model picks badly from a long list even
+ when the list fits: it is shown ``_SMALL_MODEL_DIRECT_TOOLS`` at
+ most. Gated on the declared window, never a provider name (AP-21).
+ * **The caller's role.** ``direct_tools`` names the tools an agent
+ works with; it is shown those and its own hands, on any provider.
+
+ The provider's own tool-count cap (``max_tools``) defers the same way.
+ The tool a deterministic gate mandated this turn, ``run-skill`` on a
+ skill match and the caller's own hands are always shown.
+ """
+ nothing: frozenset[str] = frozenset()
+ # A real tool of that name leaves no room for the finder: show
+ # everything, as before.
+ if not isinstance(tools, dict) or not tools or FIND_TOOLS_NAME in tools:
+ return tools, nothing
try:
window = int(getattr(brain, "context_window", 0) or 0)
except (TypeError, ValueError):
@@ -6911,37 +6954,68 @@ class BrainManager:
except (TypeError, ValueError):
# A malformed tool limit means 'unknown'; no trimming then.
max_tools = 0
- if window <= 0 and max_tools <= 0:
- return tools
- used = (
- _approx_tokens(system_prompt)
- + _approx_history_tokens(history)
- + _CONTEXT_FIT_RESERVE_TOKENS
- )
- keep: set[str] = set()
+ if window <= 0 and max_tools <= 0 and direct_tools is None:
+ return tools, nothing
+ keep: set[str] = {name for name in own_tools if name in tools}
mandated = getattr(self, "_evidence_required_tool", None)
if mandated:
keep.add(str(mandated))
if getattr(self, "_skill_turn_match", None) is not None:
keep.add("run-skill")
- fitted, dropped = _fit_tools_to_context_window(
- tools, context_window=window, used_tokens=used, keep=keep, max_tools=max_tools
+ used = (
+ _approx_tokens(system_prompt)
+ + _approx_history_tokens(history)
+ + _CONTEXT_FIT_RESERVE_TOKENS
)
- if dropped:
- log.warning(
- "Tool surface trimmed for %s: %d of %d tools hidden this turn so "
- "the request fits the model's %d-token window and %s-tool cap "
- "(prompt+history ~%d tokens, budget for tools %d). First hidden: %s",
- getattr(brain, "name", type(brain).__name__),
- len(dropped),
- len(tools),
- window,
- max_tools or "no",
- used,
- max(window - used, 0),
- ", ".join(dropped[:5]),
- )
- return fitted
+ budget = max(window - used, 0) if window > 0 else None
+ # One slot of a provider's count cap is held for ``find_tools``.
+ limits = [max(max_tools - 1, 1)] if max_tools > 0 else []
+ if 0 < window <= _SMALL_WINDOW_TOKENS:
+ limits.append(_SMALL_MODEL_DIRECT_TOOLS + len(keep))
+ max_direct = min(limits) if limits else 0
+ only = None if direct_tools is None else {*direct_tools, *ROLE_BASE}
+ plan = plan_surface(
+ tools, keep=keep, budget_tokens=budget, max_direct=max_direct, only=only
+ )
+ if not plan.deferred:
+ return tools, nothing
+ reveal_tokens: int | None = None
+ if budget is not None:
+ # The finder and what it reveals need room of their own. When the
+ # window is what forced the split, hold that room back and choose
+ # again; otherwise the first lookup overflows the window that the
+ # shown tools already fill to the brim.
+ spent = sum(tool_tokens(name, tool) for name, tool in plan.direct.items())
+ headroom = budget - spent
+ if headroom < _REVEAL_RESERVE_TOKENS:
+ reveal_tokens = min(_REVEAL_RESERVE_TOKENS, budget // 3)
+ plan = plan_surface(
+ tools,
+ keep=keep,
+ budget_tokens=max(budget - reveal_tokens - _FINDER_TOKENS, 0),
+ max_direct=max_direct,
+ only=only,
+ )
+ else:
+ reveal_tokens = headroom - _FINDER_TOKENS
+ surface: dict[str, Tool] = dict(plan.direct)
+ surface[FIND_TOOLS_NAME] = cast(
+ Tool, FindToolsTool(plan.deferred, reveal_tokens=reveal_tokens)
+ )
+ surface.update(plan.deferred)
+ log.info(
+ "Tool surface for %s: %d of %d tools shown, %d behind find_tools "
+ "(window %s, prompt+history ~%d tokens, count limit %s). First deferred: %s",
+ getattr(brain, "name", type(brain).__name__),
+ len(plan.direct),
+ len(tools),
+ len(plan.deferred),
+ window or "undeclared",
+ used,
+ min(limits) if limits else "none",
+ ", ".join(list(plan.deferred)[:5]),
+ )
+ return surface, frozenset(plan.deferred)
def _hide_spawn_on_knowledge_question(
self, tools: dict[str, Tool], user_text: str
@@ -14225,6 +14299,16 @@ async def _settle_context_window(brain: Any) -> None:
#: small enough for this to matter — see ``_fit_tools_to_context_window``.
_CONTEXT_FIT_RESERVE_TOKENS = 4096
+#: A declared window at or below this is a small model: it is shown a short
+#: list of tools even when a longer one would fit (see ``_shortlist_tools``).
+_SMALL_WINDOW_TOKENS = 32_768
+#: How many tools such a model is shown besides the ones a turn pins.
+_SMALL_MODEL_DIRECT_TOOLS = 24
+#: Room held back for the definitions ``find_tools`` adds during a turn whose
+#: window is already full, and for the finder itself with its index of names.
+_REVEAL_RESERVE_TOKENS = 2_000
+_FINDER_TOKENS = 700
+
#: Chars per token for the size estimate. Deliberately low: tool schemas are
#: JSON, which tokenizes denser than prose, and over-estimating costs a few
#: tools on a 32k window while under-estimating costs the whole turn.
@@ -14255,17 +14339,7 @@ def _approx_history_tokens(history: Sequence[BrainMessage] | None) -> int:
def _tool_surface_tokens(name: str, tool: Any) -> int:
"""What ONE tool costs on the wire: name, description and schema."""
- description = getattr(tool, "description", "") or ""
- schema = getattr(tool, "schema", None) or {}
- try:
- wire = json.dumps(
- {"name": name, "description": description, "input_schema": schema},
- ensure_ascii=False,
- default=str,
- )
- except (TypeError, ValueError):
- wire = f"{name} {description} {schema}"
- return _approx_tokens(wire)
+ return tool_tokens(name, tool)
def _fit_tools_to_context_window(
@@ -14276,48 +14350,33 @@ def _fit_tools_to_context_window(
keep: Iterable[str] = (),
max_tools: int = 0,
) -> tuple[dict[str, Tool], list[str]]:
- """Shrink a tool surface until it fits ``context_window`` and ``max_tools``.
-
- Returns ``(surviving tools, dropped names in drop order)``. A window or a
- tool cap of ``0`` or less means the brain declared none. ``used_tokens``
- is everything else the request carries (system prompt, history,
- reserve); what remains is the budget for tools.
-
- Drop order, deliberately: connected-server tools first — they are
- additions to Jarvis's own surface, each one a full JSON schema, and on a
- small window they are what does not fit (live 2026-08-27: 131 of 221
- tools came from three MCP servers). Within a group the largest go first,
- so as many hands as possible stay. Names in ``keep`` are never dropped.
- When even the prompt alone exceeds the window every droppable tool goes
- and the caller's log says so; the request still fails, but honestly.
+ """The tools that fit ``context_window`` and ``max_tools``, and the rest.
+
+ Returns ``(tools that fit, names passed over)``. A window or a tool cap
+ of ``0`` or less means the brain declared none. ``used_tokens`` is
+ everything else the request carries (system prompt, history, reserve);
+ what remains is the budget for tools.
+
+ The choice is made by ``plan_surface``: the everyday tools first, then
+ the rest in registry order, connected-server tools last — they are
+ additions to the app's own surface, each one a full JSON schema (live
+ 2026-08-27: 131 of 221 tools came from three MCP servers). A tool that
+ does not fit is passed over and the next one tried. Names in ``keep``
+ always fit. When even the prompt alone exceeds the window nothing but
+ ``keep`` is left.
"""
if (context_window <= 0 and max_tools <= 0) or not tools:
return tools, []
- costs = {name: _tool_surface_tokens(name, tool) for name, tool in tools.items()}
- budget = context_window - used_tokens if context_window > 0 else sum(costs.values())
- total = sum(costs.values())
- count_cap = max_tools if max_tools > 0 else len(tools)
- if total <= budget and len(tools) <= count_cap:
- return tools, []
- kept = set(keep)
- droppable = [name for name in tools if name not in kept]
- # A stable sort keeps the registry order inside each (group, size) tie.
- droppable.sort(
- key=lambda name: (
- 0 if getattr(tools[name], "is_mcp_tool", False) else 1,
- -costs[name],
- )
+ plan = plan_surface(
+ tools,
+ keep=keep,
+ budget_tokens=max(context_window - used_tokens, 0) if context_window > 0 else None,
+ max_direct=max(max_tools, 0),
)
- dropped: list[str] = []
- remaining = len(tools)
- for name in droppable:
- if total <= budget and remaining <= count_cap:
- break
- total -= costs[name]
- remaining -= 1
- dropped.append(name)
- gone = set(dropped)
- return {name: tool for name, tool in tools.items() if name not in gone}, dropped
+ if not plan.deferred:
+ return tools, []
+ passed = set(plan.deferred)
+ return {name: tool for name, tool in tools.items() if name not in passed}, list(plan.deferred)
#: Wordings with which providers refuse a request larger than the model's
diff --git a/jarvis/brain/router.py b/jarvis/brain/router.py
index dae0a5d2ea..0c828152de 100644
--- a/jarvis/brain/router.py
+++ b/jarvis/brain/router.py
@@ -527,7 +527,10 @@ class RouterBrain:
# "task done" cleanly. Trivial-path turns (no tool_calls) skip
# this; Voice-Control utterances skip too (action == confirmation).
final_text = agg.text or ""
- if agg.tool_calls and not is_voice_control_utterance(utterance):
+ # A turn that only looked up which tool exists did nothing to
+ # report as done.
+ acted = any(tc.get("name") != "find_tools" for tc in agg.tool_calls)
+ if acted and not is_voice_control_utterance(utterance):
from .ack_generator import final_summary_marker
lang = self._output_locale(utterance)
marker = final_summary_marker(language=lang)
diff --git a/jarvis/brain/tool_shortlist.py b/jarvis/brain/tool_shortlist.py
new file mode 100644
index 0000000000..db68c3bce5
--- /dev/null
+++ b/jarvis/brain/tool_shortlist.py
@@ -0,0 +1,334 @@
+"""Which tools a model is SHOWN, as opposed to which it may use.
+
+A turn's tool dict says what the model is allowed to call. Sending every
+schema of that dict is a separate decision, and until now it was the only one
+made: a 32k local model was handed whatever fit, and what did not fit was
+dropped largest-first. The richly described tools went first — a save tool
+with a real schema disappeared before a parameterless list tool — and a
+dropped tool was gone for the turn.
+
+This module splits the dict in two:
+
+* the **direct** set, whose schemas ride the request, chosen by priority
+ (what the turn mandated, the caller's own hands, the everyday core) until a
+ token budget or a count limit is reached;
+* the **deferred** rest, which stays callable. The model reaches it through
+ one small ``find_tools`` tool that searches it by intent; what it finds is
+ shown as a real tool definition from the next round on, and a deferred tool
+ the model names outright simply runs.
+
+Nothing becomes unreachable, so narrowing the direct set never recreates
+"a tool the model cannot see is the bug users report". ``find_tools`` only
+ever searches the dict it was built from: it cannot widen what a turn is
+allowed to call, and it is not part of any standing tool set.
+
+Pure and synchronous; no registry is imported here (AP-26).
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from collections.abc import Callable, Iterable, Mapping
+from dataclasses import dataclass
+from typing import Any, Final
+
+from jarvis.core.protocols import ExecutionContext, RiskTier, Tool, ToolResult
+
+__all__ = [
+ "CORE_PRIORITY",
+ "FIND_TOOLS_NAME",
+ "FindToolsTool",
+ "ROLE_BASE",
+ "SurfacePlan",
+ "canonical",
+ "plan_surface",
+ "tool_tokens",
+]
+
+FIND_TOOLS_NAME: Final[str] = "find_tools"
+
+#: The everyday tools, most needed first: what stays in front of a small
+#: model when not everything fits. Canonical names (see :func:`canonical`).
+#: Anything not listed keeps its registry order behind these.
+CORE_PRIORITY: Final[tuple[str, ...]] = (
+ "search_web",
+ "wiki_recall",
+ "wiki_ingest",
+ "remember",
+ "wiki_list",
+ "wiki_page_read",
+ "run_skill",
+ "contact_lookup",
+ "call_contact",
+ "contact_upsert",
+ "update_profile",
+ "computer_use",
+ "screenshot",
+ "screen_snapshot",
+ "spawn_worker",
+ "run_shell",
+ "find_app_action",
+ "run_app_action",
+ "describe_app_settings",
+ "navigate",
+ "create_artifact",
+ "delegate_to_agent",
+ "message_agent",
+ "society_status",
+ "switch_provider",
+ "google_calendar",
+ "gmail",
+ "google_drive",
+ "spotify",
+ "youtube_music",
+ "slack",
+ "home_assistant",
+ "vercel",
+ "list_mutable_settings",
+ "get_config_value",
+ "set_config_value",
+)
+
+#: What a caller with a role is shown besides the tools the role names: the
+#: reads nearly every job starts with. Canonical names.
+ROLE_BASE: Final[frozenset[str]] = frozenset(
+ {"search_web", "wiki_recall", "wiki_list", "wiki_page_read", "run_skill"}
+)
+
+#: Chars per token for the size estimate; the same conservative figure the
+#: brain manager budgets the rest of the request with.
+_CHARS_PER_TOKEN: Final[int] = 3
+
+#: How many tools one ``find_tools`` answer names. A small model that asked
+#: for one tool must not get forty.
+_FIND_MAX_RESULTS: Final[int] = 6
+#: Length of the one-line description each named tool gets in the answer. The
+#: schema itself is not repeated there: it arrives as a tool definition.
+_FIND_LINE_CHARS: Final[int] = 200
+#: Query words that say nothing about which tool is meant.
+_STOP_WORDS: Final[frozenset[str]] = frozenset(
+ {"a", "an", "and", "for", "from", "i", "in", "is", "it", "me", "my", "of", "on", "or",
+ "please", "the", "this", "to", "want", "with"}
+)
+#: Names listed in the tool's own description, so a model can ask for an exact
+#: one instead of guessing words.
+_INDEX_MAX_NAMES: Final[int] = 80
+_INDEX_MAX_CHARS: Final[int] = 1_600
+
+_WORD_RE = re.compile(r"[a-z0-9]+")
+
+
+def canonical(name: str) -> str:
+ """Hyphen-, dot- and case-insensitive form of a tool name."""
+ return (name or "").strip().lower().replace("-", "_").replace(".", "_")
+
+
+def tool_tokens(name: str, tool: Any) -> int:
+ """What ONE tool costs on the wire: name, description and schema."""
+ description = getattr(tool, "description", "") or ""
+ schema = getattr(tool, "schema", None) or {}
+ try:
+ wire = json.dumps(
+ {"name": name, "description": description, "input_schema": schema},
+ ensure_ascii=False,
+ default=str,
+ )
+ except (TypeError, ValueError): # unserialisable schema: size its repr instead
+ wire = f"{name} {description} {schema}"
+ return len(wire) // _CHARS_PER_TOKEN + 1
+
+
+@dataclass(frozen=True, slots=True)
+class SurfacePlan:
+ """The split of one turn's tools."""
+
+ #: Shown to the model, in the order they were chosen.
+ direct: dict[str, Tool]
+ #: Callable but not shown, in the order they were passed over.
+ deferred: dict[str, Tool]
+
+
+def plan_surface(
+ tools: Mapping[str, Tool],
+ *,
+ keep: Iterable[str] = (),
+ priority: Iterable[str] = CORE_PRIORITY,
+ budget_tokens: int | None = None,
+ max_direct: int = 0,
+ only: Iterable[str] | None = None,
+) -> SurfacePlan:
+ """Choose the direct set of ``tools``.
+
+ ``keep`` names are always direct, whatever the budget: the tool a
+ deterministic gate mandated this turn, and the caller's own hands.
+ The rest is taken in this order until ``budget_tokens`` (``None`` = no
+ token limit) or ``max_direct`` (``0`` = no count limit) is reached:
+ names in ``priority`` by their position, then everything else in the
+ order of ``tools``, connected-server tools last — they are additions to
+ the app's own surface, each one a full JSON schema.
+
+ ``only``, when given, is the whole direct set besides ``keep``: an agent
+ whose role names the tools it works with is shown those and nothing
+ else. A tool that does not fit is passed over and the next one is tried,
+ so one oversized schema cannot starve the smaller ones behind it.
+ """
+ kept = {name for name in keep if name in tools}
+ rank = {canonical(name): index for index, name in enumerate(priority)}
+ allowed = None if only is None else {canonical(name) for name in only}
+ position = {name: index for index, name in enumerate(tools)}
+ candidates = [name for name in tools if name not in kept]
+ unranked = len(rank)
+ candidates.sort(
+ key=lambda name: (
+ rank.get(canonical(name), unranked),
+ 1 if getattr(tools[name], "is_mcp_tool", False) else 0,
+ position[name],
+ )
+ )
+ direct: dict[str, Tool] = {name: tools[name] for name in tools if name in kept}
+ spent = sum(tool_tokens(name, tools[name]) for name in direct)
+ passed: list[str] = []
+ for name in candidates:
+ if allowed is not None and canonical(name) not in allowed:
+ passed.append(name)
+ continue
+ if max_direct > 0 and len(direct) >= max_direct:
+ passed.append(name)
+ continue
+ cost = tool_tokens(name, tools[name])
+ if budget_tokens is not None and spent + cost > budget_tokens:
+ passed.append(name)
+ continue
+ direct[name] = tools[name]
+ spent += cost
+ return SurfacePlan(direct=direct, deferred={name: tools[name] for name in passed})
+
+
+def _words(text: str) -> set[str]:
+ return set(_WORD_RE.findall((text or "").lower()))
+
+
+class FindToolsTool:
+ """Search the tools of this turn that were not put in front of the model.
+
+ Read-only. The answer names the matching tools with one line each;
+ ``reveal`` is called with those names, and the loop then sends their
+ schemas as real tool definitions from the next round on. The schema is
+ deliberately not repeated in the answer: paid once, not twice.
+
+ ``reveal_tokens`` bounds what one turn may reveal when the window is what
+ forced the deferral. A match beyond it is still named, so the model can
+ call it; only its definition does not ride along. ``None`` = no bound.
+
+ A lookup is not an action: ``is_lookup_only`` keeps it out of the record
+ of tools that ran, which the honesty guards and the spoken "done" read.
+ """
+
+ name: str = FIND_TOOLS_NAME
+ risk_tier: RiskTier = "safe"
+ is_lookup_only: bool = True
+
+ def __init__(
+ self,
+ deferred: Mapping[str, Tool],
+ *,
+ reveal: Callable[[Iterable[str]], None] | None = None,
+ reveal_tokens: int | None = None,
+ ) -> None:
+ self._deferred = dict(deferred)
+ self._reveal = reveal
+ self._reveal_tokens = reveal_tokens
+ self._revealed: set[str] = set()
+ names = sorted(self._deferred)
+ listed: list[str] = []
+ used = 0
+ for candidate in names[:_INDEX_MAX_NAMES]:
+ if used + len(candidate) + 2 > _INDEX_MAX_CHARS:
+ break
+ listed.append(candidate)
+ used += len(candidate) + 2
+ more = len(names) - len(listed)
+ index = ", ".join(listed) + (f" and {more} more" if more > 0 else "")
+ self.description = (
+ "More tools are available than the ones listed here. Call this with a "
+ "few words for what you want to do, or an exact tool name. The matching "
+ "tools are then added to your tools and you call the one you need by "
+ f"its name. Not listed above: {index}."
+ )
+ self.schema: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "What you want to do, or a tool name.",
+ }
+ },
+ "required": ["query"],
+ }
+
+ def bind(self, reveal: Callable[[Iterable[str]], None]) -> None:
+ """Attach the loop that shows revealed tools from its next round on."""
+ self._reveal = reveal
+
+ def read_only_for_args(self, args: dict[str, Any]) -> bool:
+ return True
+
+ def _ranked(self, query: str) -> list[str]:
+ wanted = canonical(query)
+ exact = [name for name in self._deferred if canonical(name) == wanted]
+ if exact:
+ return exact
+ terms = _words(query) - _STOP_WORDS
+ if not terms:
+ return sorted(self._deferred)
+ scored: list[tuple[int, str]] = []
+ for name, tool in self._deferred.items():
+ in_name = len(terms & _words(name))
+ in_text = len(terms & _words(getattr(tool, "description", "") or ""))
+ score = in_name * 3 + in_text
+ if score:
+ scored.append((score, name))
+ scored.sort(key=lambda item: (-item[0], item[1]))
+ return [name for _score, name in scored]
+
+ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
+ query = str((args or {}).get("query") or "").strip()
+ ranked = self._ranked(query)
+ found: list[dict[str, Any]] = []
+ newly: list[str] = []
+ for name in ranked[:_FIND_MAX_RESULTS]:
+ tool = self._deferred[name]
+ line = " ".join((getattr(tool, "description", "") or "").split())
+ entry: dict[str, Any] = {"name": name, "description": line[:_FIND_LINE_CHARS]}
+ if name not in self._revealed:
+ cost = tool_tokens(name, tool)
+ if self._reveal_tokens is not None and cost > self._reveal_tokens:
+ # No room left to show its definition this turn. It can
+ # still be called; the arguments are named here instead.
+ properties = (getattr(tool, "schema", None) or {}).get("properties")
+ entry["arguments"] = sorted(properties) if isinstance(properties, dict) else []
+ else:
+ if self._reveal_tokens is not None:
+ self._reveal_tokens -= cost
+ self._revealed.add(name)
+ newly.append(name)
+ found.append(entry)
+ if not found:
+ return ToolResult(
+ success=True,
+ output={
+ "tools": [],
+ "note": "No tool matches. Try other words, or answer without one.",
+ "available": sorted(self._deferred)[:_INDEX_MAX_NAMES],
+ },
+ )
+ if self._reveal is not None and newly:
+ self._reveal(newly)
+ return ToolResult(
+ success=True,
+ output={
+ "tools": found,
+ "note": "These are now among your tools. Call the one you need by its name.",
+ },
+ )
diff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.py
index ce8b7323ef..5f86182359 100644
--- a/jarvis/brain/tool_use_loop.py
+++ b/jarvis/brain/tool_use_loop.py
@@ -17,7 +17,7 @@ import json
import logging
import re
import time
-from collections.abc import Awaitable, Callable
+from collections.abc import Awaitable, Callable, Iterable
from typing import Any
from uuid import UUID, uuid4
@@ -55,6 +55,7 @@ from .loop_control import (
)
from .streaming import StreamingAggregate, aggregate, aggregate_with_consumer
from .tool_call_recovery import extract_leaked_tool_calls
+from .tool_shortlist import FIND_TOOLS_NAME
# Central backstop for tool-output bloat: no tool result may exceed this many
# chars in the tool-role message fed back to the brain. Individual tools should
@@ -641,10 +642,21 @@ class ToolUseLoop:
reasoning_effort: ReasoningEffort | None = None,
tool_context: dict[str, Any] | None = None,
loop_control: LoopControl | None = None,
+ deferred_tools: Iterable[str] = (),
) -> None:
self._brain = brain
self._tools = tools
self._executor = executor
+ # Tools of this turn whose schemas are NOT sent (jarvis/brain/
+ # tool_shortlist.py). They stay in ``tools`` and run when called; the
+ # ``find_tools`` tool reveals the ones the model asked about, and the
+ # next round then carries their schemas.
+ self._hidden: set[str] = {name for name in deferred_tools if name in tools}
+ self._surface_changed = False
+ finder = tools.get(FIND_TOOLS_NAME) if self._hidden else None
+ bind = getattr(finder, "bind", None)
+ if callable(bind):
+ bind(self._reveal_tools)
# Caller-supplied keys for every tool's ``ExecutionContext.config``
# (see BrainDispatcher.tool_context). Per-turn keys set below win.
self._tool_context = dict(tool_context or {})
@@ -809,9 +821,17 @@ class ToolUseLoop:
"description": getattr(tool, "description", ""),
"input_schema": tool.schema,
}
- for tool in self._tools.values()
+ for name, tool in self._tools.items()
+ if name not in self._hidden
]
+ def _reveal_tools(self, names: Iterable[str]) -> None:
+ """Show the schemas of deferred tools from the next round on."""
+ found = {name for name in names if name in self._hidden}
+ if found:
+ self._hidden -= found
+ self._surface_changed = True
+
async def _phase(self, phase: str, detail: str = "") -> None:
"""Report what the turn is doing — once per change, never per token."""
control = self._control
@@ -978,6 +998,12 @@ class ToolUseLoop:
log.info("tool_use_loop: %d steer message(s) folded in", len(pending))
round_no += 1
await self._phase(PHASE_GATHER, f"round {round_no}")
+ if self._surface_changed:
+ self._surface_changed = False
+ # Only while tools are still on offer: a round that was forced
+ # tool-less (deadline, final answer) must stay that way.
+ if tools_payload:
+ tools_payload = self._tool_schemas()
req = BrainRequest(
messages=tuple(current_messages),
@@ -1294,7 +1320,10 @@ class ToolUseLoop:
# prompt advertises skills/CLIs it was not granted recovers
# from "run-skill is not here" only if it learns what is
# (BUG-212 — the briefing ended on the fallback phrase).
- available = ", ".join(sorted(self._tools)) or "none"
+ available = (
+ ", ".join(sorted(n for n in self._tools if n not in self._hidden))
+ or "none"
+ )
tool_result_payload = {
"error": (
f"Tool '{tool_name}' is not available in this turn. "
@@ -1567,7 +1596,10 @@ class ToolUseLoop:
# absent — this is what keeps the voice pipeline from speaking
# "Erledigt." for a desktop action that did not happen
# (2026-06-09).
- if result.success:
+ # A lookup that only names other tools is not an action:
+ # counting it would let "I sent the mail" stand after a
+ # turn that only searched for the mail tool.
+ if result.success and not getattr(tool, "is_lookup_only", False):
final_agg.executed_tool_names.add(tool_name)
# suppress_response=True: tool provides its own final response,
# the second brain iteration is skipped (fix for 1-3 s stall
diff --git a/jarvis/brain/turn_override.py b/jarvis/brain/turn_override.py
index 788afccc1e..59b83e4550 100644
--- a/jarvis/brain/turn_override.py
+++ b/jarvis/brain/turn_override.py
@@ -103,6 +103,12 @@ class TurnOverride:
applies (the folder tools of a chat, scoped to its working directory).
``tool_filter``
Applied last; a plan-mode caller keeps the read-only tools only.
+ ``tools_direct``
+ The tools this caller works with. When set, the model is shown these
+ and ``tools_extra``; every other tool the turn may use stays callable
+ behind ``find_tools`` (``jarvis/brain/tool_shortlist.py``). ``None``
+ shows everything that fits, which is what voice and the typed chat
+ get.
``tool_context``
Extra keys for every tool's ``ExecutionContext.config`` this turn —
the approval surface, the working directory, written delivery.
@@ -131,6 +137,7 @@ class TurnOverride:
reasoning_effort: ReasoningEffort | None = None
tools_extra: Mapping[str, Tool] = field(default_factory=dict)
tool_filter: Callable[[dict[str, Tool]], dict[str, Tool]] | None = None
+ tools_direct: frozenset[str] | None = None
tool_context: Mapping[str, Any] = field(default_factory=dict)
credential_scope: str = "agent"
max_turns: int | None = None
diff --git a/jarvis/society/surface.py b/jarvis/society/surface.py
index a3d4cab2fa..173193dcfd 100644
--- a/jarvis/society/surface.py
+++ b/jarvis/society/surface.py
@@ -43,7 +43,13 @@ from .agent_tools import (
WikiNoteTool,
)
from .ask_tool import ASK_USER_TOOL_NAME, AskUserTool
-from .capabilities import CapabilityKind, CapabilityRow, capability_id_for_tool, select_tools
+from .capabilities import (
+ CapabilityKind,
+ CapabilityRow,
+ capability_id_for_tool,
+ select_tools,
+ tool_name_for_capability,
+)
from .coding_threads import CodingThreadTool
from .communication import COMMUNICATION_GUIDANCE
from .conversation_tool import ConversationRecallTool, RoutineInvokeTool, RoutineListTool
@@ -836,6 +842,31 @@ def society_tool_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, T
return _apply
+def society_direct_tools(session: Any) -> frozenset[str] | None:
+ """The tools an agent's focus names, or ``None`` when it has none.
+
+ An agent may use everything it is granted, but it is SHOWN its own tools
+ and the ones its role points at; the rest stays callable behind
+ ``find_tools`` (``jarvis/brain/tool_shortlist.py``). An agent without a
+ focus, or one whose row is not cached yet, is shown everything as before.
+ """
+ rt = current_runtime()
+ agent_id = agent_id_of(getattr(session, "session_id", "") or "")
+ if rt is None or agent_id is None:
+ return None
+ agent = rt.cached_agent(agent_id)
+ if agent is None or not agent.focus:
+ return None
+ from jarvis.clis.capability_provider import equivalent_grants
+
+ names = {
+ name
+ for cap_id in equivalent_grants(agent.focus)
+ if (name := tool_name_for_capability(cap_id))
+ }
+ return frozenset(names) if names else None
+
+
def requires_explicit_approval(session_id: str, tool_name: str, args: dict[str, Any]) -> bool:
"""Keep an agent's explicit ask rules effective even in Bypass mode."""
from .approvals import matches
diff --git a/tests/unit/brain/test_context_window_fit.py b/tests/unit/brain/test_context_window_fit.py
index 0a082950fa..cf259da7ac 100644
--- a/tests/unit/brain/test_context_window_fit.py
+++ b/tests/unit/brain/test_context_window_fit.py
@@ -111,7 +111,7 @@ class TestFitToolsToContextWindow:
"linear/list_issues",
]
- def test_then_the_largest_remaining_tools_go_first(self) -> None:
+ def test_a_tool_that_does_not_fit_is_passed_over_for_the_next(self) -> None:
tools = {
"tiny": _tool("tiny", size=1),
"huge": _tool("huge", size=40),
@@ -157,21 +157,24 @@ class TestFitOnTheManager:
def test_cloud_sized_window_keeps_the_whole_surface(self) -> None:
m = self._mgr()
tools = {f"t{i}": _tool(f"t{i}", size=10, mcp=i % 2 == 0) for i in range(221)}
- fitted = m._fit_tools_to_brain(
+ fitted, deferred = m._shortlist_tools(
tools, _FakeBrain(1_048_576), system_prompt="x" * 40_000, history=None
)
- assert fitted is tools
+ assert fitted is tools and not deferred
def test_local_window_trims_the_live_shape(self) -> None:
# 221 tools, a long system prompt, a 32k window: the surface shrinks
# and the connected-server tools are the ones that went.
m = self._mgr()
tools = {f"t{i}": _tool(f"t{i}", size=10, mcp=i % 2 == 0) for i in range(221)}
- fitted = m._fit_tools_to_brain(
+ surface, deferred = m._shortlist_tools(
tools, _FakeBrain(32_768), system_prompt="x" * 30_000, history=None
)
- assert 0 < len(fitted) < 221
- assert not any(t.is_mcp_tool for t in fitted.values())
+ shown = {n: t for n, t in surface.items() if n not in deferred}
+ assert 0 < len(shown) < 221
+ assert not any(getattr(t, "is_mcp_tool", False) for t in shown.values())
+ # Deferred, not dropped: every tool is still there to be called.
+ assert set(tools) <= set(surface)
def test_mandated_tool_survives_a_local_window(self) -> None:
m = self._mgr()
@@ -182,11 +185,12 @@ class TestFitOnTheManager:
"run-skill": _tool("run-skill", size=60),
"github/x": _tool("github/x", size=60, mcp=True),
}
- fitted = m._fit_tools_to_brain(
+ surface, deferred = m._shortlist_tools(
tools, _FakeBrain(4_200), system_prompt="", history=None
)
- assert {"search_web", "run-skill"} <= set(fitted)
- assert "github/x" not in fitted
+ shown = set(surface) - deferred
+ assert {"search_web", "run-skill"} <= shown
+ assert "github/x" not in shown
def test_undeclared_window_is_left_alone(self) -> None:
m = self._mgr()
@@ -195,7 +199,10 @@ class TestFitOnTheManager:
name = "w"
tools = {"a": _tool("a", size=60)}
- assert m._fit_tools_to_brain(tools, _Windowless(), system_prompt="", history=None) is tools
+ surface, deferred = m._shortlist_tools(
+ tools, _Windowless(), system_prompt="", history=None
+ )
+ assert surface is tools and not deferred
# ---------------------------------------------------------- the cause
diff --git a/tests/unit/brain/test_tool_shortlist.py b/tests/unit/brain/test_tool_shortlist.py
new file mode 100644
index 0000000000..b62989a37b
--- /dev/null
+++ b/tests/unit/brain/test_tool_shortlist.py
@@ -0,0 +1,455 @@
+"""A model is shown the tools it needs; the rest stays reachable.
+
+Reported from testing with local models: a 9B model never called the save
+tool, a larger one only ever listed. Two causes met. The whole tool set was
+sent to every turn, and when it did not fit a small window the largest schemas
+were dropped first — the richly described save tool before the parameterless
+list tool — and a dropped tool was gone for the turn.
+"""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from dataclasses import dataclass, field
+from typing import Any
+from uuid import uuid4
+
+import pytest
+
+from jarvis.brain.manager import (
+ _SMALL_MODEL_DIRECT_TOOLS,
+ BrainManager,
+)
+from jarvis.brain.tool_shortlist import (
+ CORE_PRIORITY,
+ FIND_TOOLS_NAME,
+ FindToolsTool,
+ canonical,
+ plan_surface,
+ tool_tokens,
+)
+from jarvis.brain.tool_use_loop import ToolUseLoop
+from jarvis.core.protocols import BrainDelta, BrainRequest, ExecutionContext, ToolResult
+
+
+@dataclass
+class _Tool:
+ name: str
+ description: str = "does a thing"
+ schema: dict[str, Any] = field(default_factory=dict)
+ risk_tier: str = "safe"
+ is_mcp_tool: bool = False
+
+ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:
+ return ToolResult(success=True, output={"ran": self.name, "args": args})
+
+
+def _tool(name: str, *, size: int = 1, mcp: bool = False, description: str = "") -> _Tool:
+ props = {f"p{i}": {"type": "string", "description": "x" * 40} for i in range(size)}
+ return _Tool(
+ name=name,
+ description=description or f"{name} tool",
+ schema={"type": "object", "properties": props},
+ is_mcp_tool=mcp,
+ )
+
+
+class _Brain:
+ name = "fake"
+
+ def __init__(self, window: int) -> None:
+ self.context_window = window
+
+
+def _ctx() -> ExecutionContext:
+ return ExecutionContext(trace_id=uuid4(), user_utterance="", config={}, memory_read=None)
+
+
+# ── Choosing what is shown ───────────────────────────────────────────────
+
+
+def test_the_save_tool_outlives_a_larger_budget_squeeze_than_the_list_tool_did() -> None:
+ """The reported shape: a described save tool, a parameterless list tool,
+ and a budget that holds only some of the surface. Largest-first dropped
+ the save tool. Priority keeps both and lets the unranked extras go."""
+ tools = {
+ "wiki-list": _tool("wiki-list", size=0),
+ "extra_a": _tool("extra_a", size=6),
+ "extra_b": _tool("extra_b", size=6),
+ "wiki-ingest": _tool("wiki-ingest", size=4),
+ }
+ budget = tool_tokens("wiki-list", tools["wiki-list"]) + tool_tokens(
+ "wiki-ingest", tools["wiki-ingest"]
+ )
+ plan = plan_surface(tools, budget_tokens=budget)
+ assert set(plan.direct) == {"wiki-ingest", "wiki-list"}
+ assert set(plan.deferred) == {"extra_a", "extra_b"}
+
+
+def test_priority_matches_hyphen_and_underscore_spellings() -> None:
+ assert canonical("wiki-ingest") == canonical("wiki_ingest") == "wiki_ingest"
+ tools = {"zzz": _tool("zzz"), "search_web": _tool("search_web"), "wiki-recall": _tool("x")}
+ plan = plan_surface(tools, max_direct=2)
+ assert list(plan.direct) == ["search_web", "wiki-recall"]
+
+
+def test_a_count_limit_shows_the_everyday_tools_first() -> None:
+ tools = {f"other{i}": _tool(f"other{i}") for i in range(30)}
+ for name in ("search_web", "wiki-ingest", "run-skill"):
+ tools[name] = _tool(name)
+ plan = plan_surface(tools, max_direct=5)
+ assert {"search_web", "wiki-ingest", "run-skill"} <= set(plan.direct)
+ assert len(plan.direct) == 5
+
+
+def test_connected_server_tools_wait_behind_the_apps_own() -> None:
+ tools = {
+ "github/create_issue": _tool("github/create_issue", mcp=True),
+ "own_a": _tool("own_a"),
+ "own_b": _tool("own_b"),
+ }
+ plan = plan_surface(tools, max_direct=2)
+ assert set(plan.direct) == {"own_a", "own_b"}
+
+
+def test_pinned_tools_are_shown_whatever_the_budget() -> None:
+ tools = {"mandated": _tool("mandated", size=40), "other": _tool("other")}
+ plan = plan_surface(tools, keep={"mandated"}, budget_tokens=0)
+ assert list(plan.direct) == ["mandated"]
+ assert list(plan.deferred) == ["other"]
+
+
+def test_one_oversized_tool_does_not_starve_the_ones_behind_it() -> None:
+ tools = {"huge": _tool("huge", size=60), "small": _tool("small")}
+ plan = plan_surface(tools, budget_tokens=tool_tokens("small", tools["small"]))
+ assert list(plan.direct) == ["small"]
+
+
+def test_a_role_shows_only_its_tools_and_what_is_pinned() -> None:
+ tools = {name: _tool(name) for name in ("gmail", "slack", "run_shell", "own_note")}
+ plan = plan_surface(tools, keep={"own_note"}, only={"gmail"})
+ assert set(plan.direct) == {"own_note", "gmail"}
+ assert set(plan.deferred) == {"slack", "run_shell"}
+
+
+def test_everything_fits_means_nothing_is_deferred() -> None:
+ tools = {"a": _tool("a"), "b": _tool("b")}
+ plan = plan_surface(tools, budget_tokens=1_000_000)
+ assert plan.deferred == {}
+ assert list(plan.direct) == ["a", "b"]
+
+
+def test_the_core_list_has_no_duplicates() -> None:
+ assert len(set(CORE_PRIORITY)) == len(CORE_PRIORITY)
+ assert all(name == canonical(name) for name in CORE_PRIORITY)
+
+
+# ── Reaching the rest ────────────────────────────────────────────────────
+
+
+async def test_find_tools_names_what_was_asked_and_reveals_it() -> None:
+ deferred = {
+ "calendar_create": _tool("calendar_create", description="Create a calendar event"),
+ "mail_send": _tool("mail_send", description="Send an email message"),
+ }
+ revealed: list[str] = []
+ finder = FindToolsTool(deferred, reveal=revealed.extend)
+ result = await finder.execute({"query": "I want to send an email"}, _ctx())
+ names = [entry["name"] for entry in result.output["tools"]]
+ assert names == ["mail_send"]
+ # The definition arrives as a real tool next round; repeating the schema
+ # here would pay for it twice in a window that is already full.
+ assert "input_schema" not in result.output["tools"][0]
+ assert revealed == ["mail_send"]
+
+
+async def test_a_tool_found_twice_is_revealed_once() -> None:
+ revealed: list[str] = []
+ finder = FindToolsTool({"mail_send": _tool("mail_send")}, reveal=revealed.extend)
+ await finder.execute({"query": "mail_send"}, _ctx())
+ await finder.execute({"query": "mail_send"}, _ctx())
+ assert revealed == ["mail_send"]
+
+
+async def test_a_full_window_bounds_what_one_turn_reveals() -> None:
+ """Shown tools already fill the window. What a lookup adds must fit the
+ room that was held back for it; a match beyond that is still named, with
+ its arguments, so it can be called."""
+ deferred = {
+ "mail_send": _tool("mail_send", size=1, description="send mail"),
+ "mail_search": _tool("mail_search", size=30, description="search mail"),
+ }
+ revealed: list[str] = []
+ room = tool_tokens("mail_send", deferred["mail_send"])
+ finder = FindToolsTool(deferred, reveal=revealed.extend, reveal_tokens=room)
+ result = await finder.execute({"query": "mail"}, _ctx())
+ assert revealed == ["mail_send"]
+ by_name = {entry["name"]: entry for entry in result.output["tools"]}
+ assert set(by_name) == {"mail_send", "mail_search"}
+ assert "arguments" not in by_name["mail_send"]
+ assert by_name["mail_search"]["arguments"] == sorted(f"p{i}" for i in range(30))
+
+
+async def test_find_tools_resolves_an_exact_name_in_either_spelling() -> None:
+ finder = FindToolsTool({"wiki-ingest": _tool("wiki-ingest"), "other": _tool("other")})
+ result = await finder.execute({"query": "wiki_ingest"}, _ctx())
+ assert [entry["name"] for entry in result.output["tools"]] == ["wiki-ingest"]
+
+
+async def test_find_tools_says_so_when_nothing_matches() -> None:
+ finder = FindToolsTool({"mail_send": _tool("mail_send")})
+ result = await finder.execute({"query": "teleport"}, _ctx())
+ assert result.success is True
+ assert result.output["tools"] == []
+ assert result.output["available"] == ["mail_send"]
+
+
+def test_find_tools_names_what_it_holds_and_never_anything_else() -> None:
+ finder = FindToolsTool({"b_tool": _tool("b_tool"), "a_tool": _tool("a_tool")})
+ assert "a_tool, b_tool" in finder.description
+ assert finder.risk_tier == "safe"
+ assert finder.read_only_for_args({}) is True
+
+
+def test_a_long_tail_of_names_is_summarised_not_dumped() -> None:
+ finder = FindToolsTool({f"tool_number_{i:03d}": _tool("t") for i in range(300)})
+ assert "more" in finder.description
+ assert len(finder.description) < 2_400
+
+
+# ── The loop ─────────────────────────────────────────────────────────────
+
+
+class _RunningExecutor:
+ """Runs the tool for real, as ``ToolExecutor.execute`` would."""
+
+ def __init__(self) -> None:
+ self.ran: list[str] = []
+
+ async def execute(self, tool: Any, args: dict[str, Any], **_: Any) -> ToolResult:
+ self.ran.append(tool.name)
+ return await tool.execute(args, _ctx())
+
+
+class _ScriptedBrain:
+ """Answers each round with the next scripted tool call, then with text."""
+
+ def __init__(self, calls: list[tuple[str, dict[str, Any]]]) -> None:
+ self._calls = list(calls)
+ self.requests: list[BrainRequest] = []
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ self.requests.append(req)
+ index = len(self.requests) - 1
+ if index < len(self._calls):
+ name, args = self._calls[index]
+ yield BrainDelta(tool_call={"id": f"c{index}", "name": name, "input": args})
+ yield BrainDelta(finish_reason="tool_use")
+ return
+ yield BrainDelta(content="done")
+ yield BrainDelta(finish_reason="stop")
+
+ def shown(self, round_index: int) -> list[str]:
+ return [spec["name"] for spec in self.requests[round_index].tools]
+
+
+def _surface() -> tuple[dict[str, Any], frozenset[str]]:
+ deferred = {"mail_send": _tool("mail_send", description="Send an email message")}
+ tools: dict[str, Any] = {"search_web": _tool("search_web")}
+ tools[FIND_TOOLS_NAME] = FindToolsTool(deferred)
+ tools.update(deferred)
+ return tools, frozenset(deferred)
+
+
+async def test_a_deferred_tool_is_not_shown_until_it_was_found() -> None:
+ tools, deferred = _surface()
+ brain = _ScriptedBrain(
+ [(FIND_TOOLS_NAME, {"query": "send email"}), ("mail_send", {"to": "anna"})]
+ )
+ executor = _RunningExecutor()
+ loop = ToolUseLoop(brain, tools, executor, deferred_tools=deferred) # type: ignore[arg-type]
+ result = await loop.run([], user_utterance="send anna the notes by email")
+ assert brain.shown(0) == ["search_web", FIND_TOOLS_NAME]
+ # Found in round one, so its schema rides every round after that.
+ assert "mail_send" in brain.shown(1)
+ assert executor.ran == [FIND_TOOLS_NAME, "mail_send"]
+ assert "done" in result.text
+
+
+async def test_a_lookup_is_not_recorded_as_something_that_was_done() -> None:
+ """The honesty guards read the record of tools that ran. A turn that only
+ searched for the mail tool must not be able to say the mail was sent."""
+ tools, deferred = _surface()
+ brain = _ScriptedBrain([(FIND_TOOLS_NAME, {"query": "send email"})])
+ executor = _RunningExecutor()
+ loop = ToolUseLoop(brain, tools, executor, deferred_tools=deferred) # type: ignore[arg-type]
+ result = await loop.run([], user_utterance="send anna the notes by email")
+ assert executor.ran == [FIND_TOOLS_NAME]
+ assert result.executed_tool_names == set()
+
+
+def test_the_dispatcher_payload_leaves_deferred_tools_out() -> None:
+ from jarvis.brain.dispatcher import BrainDispatcher
+
+ tools, deferred = _surface()
+ dispatcher = BrainDispatcher(_Brain(32_768), tools=tools, deferred_tools=deferred) # type: ignore[arg-type]
+ assert [spec["name"] for spec in dispatcher.tools_payload()] == [
+ "search_web",
+ FIND_TOOLS_NAME,
+ ]
+
+
+async def test_a_deferred_tool_named_outright_simply_runs() -> None:
+ """Deferred means not shown, never not allowed."""
+ tools, deferred = _surface()
+ brain = _ScriptedBrain([("mail_send", {"to": "anna"})])
+ executor = _RunningExecutor()
+ loop = ToolUseLoop(brain, tools, executor, deferred_tools=deferred) # type: ignore[arg-type]
+ await loop.run([], user_utterance="send anna the notes by email")
+ assert executor.ran == ["mail_send"]
+
+
+async def test_without_deferred_tools_the_loop_is_unchanged() -> None:
+ tools = {"search_web": _tool("search_web"), "mail_send": _tool("mail_send")}
+ brain = _ScriptedBrain([])
+ loop = ToolUseLoop(brain, tools, _RunningExecutor()) # type: ignore[arg-type]
+ await loop.run([], user_utterance="hello")
+ assert brain.shown(0) == ["search_web", "mail_send"]
+
+
+# ── The manager's decision ───────────────────────────────────────────────
+
+
+def _mgr() -> BrainManager:
+ m = BrainManager.__new__(BrainManager) # bypass heavy __init__
+ m._tools = {}
+ m._evidence_required_tool = None
+ m._skill_turn_match = None
+ return m
+
+
+def _shown(surface: dict[str, Any], deferred: frozenset[str]) -> list[str]:
+ return [name for name in surface if name not in deferred]
+
+
+def test_a_hosted_model_with_room_is_handed_the_same_dict() -> None:
+ tools = {f"t{i}": _tool(f"t{i}", size=10) for i in range(221)}
+ surface, deferred = _mgr()._shortlist_tools(
+ tools, _Brain(1_048_576), system_prompt="x" * 40_000, history=None
+ )
+ assert surface is tools
+ assert deferred == frozenset()
+
+
+def test_a_small_model_is_shown_a_short_list_even_when_more_would_fit() -> None:
+ """Choosing well from 80 tools is the hard part for a small model, not
+ fitting them into the window."""
+ tools = {f"other{i}": _tool(f"other{i}", size=0) for i in range(80)}
+ tools["wiki-ingest"] = _tool("wiki-ingest", size=4)
+ tools["wiki-list"] = _tool("wiki-list", size=0)
+ surface, deferred = _mgr()._shortlist_tools(
+ tools, _Brain(32_768), system_prompt="", history=None
+ )
+ shown = _shown(surface, deferred)
+ assert len(shown) == _SMALL_MODEL_DIRECT_TOOLS + 1 # plus find_tools
+ assert {"wiki-ingest", "wiki-list", FIND_TOOLS_NAME} <= set(shown)
+ # Nothing was lost: every tool is still in the dict the loop executes from.
+ assert set(tools) <= set(surface)
+
+
+def test_what_the_turn_pinned_is_shown_on_top_of_the_short_list() -> None:
+ m = _mgr()
+ m._evidence_required_tool = "other79"
+ tools = {f"other{i}": _tool(f"other{i}", size=0) for i in range(80)}
+ surface, deferred = m._shortlist_tools(
+ tools, _Brain(16_384), system_prompt="", history=None, own_tools=("other78",)
+ )
+ shown = _shown(surface, deferred)
+ assert {"other78", "other79"} <= set(shown)
+
+
+def test_an_agent_with_a_role_is_shown_its_tools_on_any_provider() -> None:
+ tools = {name: _tool(name) for name in ("gmail", "slack", "run_shell", "search_web")}
+ tools["society_note"] = _tool("society_note")
+ surface, deferred = _mgr()._shortlist_tools(
+ tools,
+ _Brain(1_048_576),
+ system_prompt="",
+ history=None,
+ own_tools=("society_note",),
+ direct_tools=frozenset({"gmail"}),
+ )
+ shown = _shown(surface, deferred)
+ # Its own hands, what its role names, and the reads every job starts with.
+ assert set(shown) == {"society_note", "gmail", "search_web", FIND_TOOLS_NAME}
+ assert deferred == frozenset({"slack", "run_shell"})
+
+
+def test_an_agent_whose_role_covers_everything_gets_no_find_tool() -> None:
+ tools = {"gmail": _tool("gmail"), "society_note": _tool("society_note")}
+ surface, deferred = _mgr()._shortlist_tools(
+ tools,
+ _Brain(1_048_576),
+ system_prompt="",
+ history=None,
+ own_tools=("society_note",),
+ direct_tools=frozenset({"gmail"}),
+ )
+ assert surface is tools and deferred == frozenset()
+
+
+def test_a_providers_count_cap_defers_instead_of_dropping() -> None:
+ class _Capped(_Brain):
+ max_tools = 10
+
+ tools = {f"t{i}": _tool(f"t{i}") for i in range(30)}
+ surface, deferred = _mgr()._shortlist_tools(
+ tools, _Capped(1_048_576), system_prompt="", history=None
+ )
+ shown = _shown(surface, deferred)
+ # The cap counts what is sent, find_tools included.
+ assert len(shown) == 10 and FIND_TOOLS_NAME in shown
+ assert len(deferred) == 21
+
+
+def test_a_full_window_holds_room_back_for_what_a_lookup_adds() -> None:
+ """Filling the window to the brim with shown tools left no room for the
+ finder or for a single revealed definition: the first lookup overflowed."""
+ tools = {f"t{i}": _tool(f"t{i}", size=10) for i in range(221)}
+ brain = _Brain(60_000)
+ surface, deferred = _mgr()._shortlist_tools(
+ tools, brain, system_prompt="x" * 60_000, history=None
+ )
+ finder = surface[FIND_TOOLS_NAME]
+ shown_cost = sum(
+ tool_tokens(name, tool)
+ for name, tool in surface.items()
+ if name not in deferred and name != FIND_TOOLS_NAME
+ )
+ budget = 60_000 - (60_000 // 3 + 1) - 4_096
+ assert finder._reveal_tokens is not None and finder._reveal_tokens > 0
+ assert shown_cost + finder._reveal_tokens + tool_tokens(FIND_TOOLS_NAME, finder) <= budget
+
+
+def test_a_real_tool_called_find_tools_is_never_overwritten() -> None:
+ tools = {f"t{i}": _tool(f"t{i}") for i in range(80)}
+ tools[FIND_TOOLS_NAME] = _tool(FIND_TOOLS_NAME)
+ surface, deferred = _mgr()._shortlist_tools(
+ tools, _Brain(8_192), system_prompt="", history=None
+ )
+ assert surface is tools and deferred == frozenset()
+
+
+def test_a_count_cap_of_one_still_caps() -> None:
+ class _One(_Brain):
+ max_tools = 1
+
+ tools = {f"t{i}": _tool(f"t{i}") for i in range(5)}
+ surface, deferred = _mgr()._shortlist_tools(
+ tools, _One(1_048_576), system_prompt="", history=None
+ )
+ assert len(deferred) == 4
diff --git a/tests/unit/society/test_surface.py b/tests/unit/society/test_surface.py
index 0794415106..7fc63bc083 100644
--- a/tests/unit/society/test_surface.py
+++ b/tests/unit/society/test_surface.py
@@ -744,3 +744,23 @@ async def test_a_cache_miss_keeps_the_agents_own_reporting_tools(
assert {MESSAGE_TOOL_NAME, "society_ask_user", MEMORY_RECALL_TOOL_NAME} <= picked
assert SHELL_TOOL_NAME not in picked and WIKI_NOTE_TOOL_NAME not in picked, "no writes"
assert not picked & set(TOOLS), "no granted hands while the grants are unknown"
+
+
+async def test_an_agent_is_shown_the_tools_its_focus_names(rt: SocietyRuntime):
+ """An agent may use everything it is granted, but the model is shown its
+ own tools and the ones its role points at; the rest waits behind
+ find_tools. Without a focus nothing is narrowed."""
+ from jarvis.society.surface import society_direct_tools
+
+ await rt.roster.create(name="Mailer", approval_mode="bypass", focus=["plugin:gmail"])
+ await rt.roster.create(name="Generalist", approval_mode="bypass")
+ mailer = SimpleNamespace(session_id="society:mailer", surface="society")
+ generalist = SimpleNamespace(session_id="society:generalist", surface="society")
+ # Before the briefing filled the cache nothing is known, so nothing narrows.
+ assert society_direct_tools(mailer) is None
+ await society_system_extra(None, None, mailer)
+ await society_system_extra(None, None, generalist)
+ direct = society_direct_tools(mailer)
+ assert direct is not None and "gmail" in direct
+ assert society_direct_tools(generalist) is None
+ assert society_direct_tools(SimpleNamespace(session_id="jarvis-chat")) is None