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): bound the tool-loop's fixed block and make its cost visible

Ruben Lütkeb69b8f3a213d
diff --git a/docs/commands-reference.md b/docs/commands-reference.md
index f96fb3e97b..47da720ee9 100644
--- a/docs/commands-reference.md
+++ b/docs/commands-reference.md
@@ -175,7 +175,7 @@ Return the latest persisted user transcript and its complete voice turn, optiona
Return the effective live Brain tool surface, including native, connected CLI, Marketplace, and MCP tools.
-- **Endpoint:** `GET /api/tools`
+- **Endpoint:** `GET /api/tools/brief`
- **Arguments:** none
- **Requires confirmation:** no
- **Desktop UI section:** `settings`
diff --git a/jarvis/brain/cost.py b/jarvis/brain/cost.py
index 855fa86f81..c951454857 100644
--- a/jarvis/brain/cost.py
+++ b/jarvis/brain/cost.py
@@ -88,14 +88,21 @@ PRICING_USD_PER_MTOK: dict[str, tuple[float, float]] = {
# ── DeepSeek ────────────────────────────────────────────────────
"deepseek-chat": (0.27, 1.10),
"deepseek-reasoner": (0.55, 2.19),
- # ── OpenRouter (proxied models, same price as the origin) ──────────
+ # ── OpenRouter (proxied models; rates from the OpenRouter pricing
+ # feed, re-verified 2026-07-28 — they can diverge from the origin's
+ # native-API price) ────────────────────────────────────────────────
"anthropic/claude-haiku-4.5": (0.80, 4.0),
- "anthropic/claude-opus-4.8": (15.0, 75.0),
+ "anthropic/claude-opus-4.8": (5.0, 25.0),
+ "anthropic/claude-opus-4.8-fast": (10.0, 50.0),
"anthropic/claude-opus-4.7": (15.0, 75.0),
"anthropic/claude-sonnet-4.6": (3.0, 15.0),
"google/gemini-3.5-flash": (1.50, 9.0),
"google/gemini-3.5-flash-lite": (0.30, 2.50),
"google/gemini-3.6-flash": (1.50, 7.50),
+ # 2026-07-28 audit: 1.87M tokens in 30 days ran on deepseek-v4-flash
+ # while it was absent here — the single biggest remaining $0 hole.
+ "deepseek/deepseek-v4-flash": (0.14, 0.28),
+ "deepseek/deepseek-v4-pro": (0.435, 0.87),
# ── Mistral (same ordering) ──────────────────────────────────────
"mistral-small-3.1": (0.20, 0.60),
"mistral-large-3": (3.0, 9.0),
diff --git a/jarvis/brain/iteration_budget.py b/jarvis/brain/iteration_budget.py
index 3c66c3ca94..e8f94fdaf4 100644
--- a/jarvis/brain/iteration_budget.py
+++ b/jarvis/brain/iteration_budget.py
@@ -28,19 +28,33 @@ class IterationBudget:
"""Tracks turns and generated tokens for a conversation loop."""
max_turns: int = 15
max_tokens_total: int = 50_000
+ #: Cost backstop over the CUMULATIVE re-sent prompt. Distinct from the
+ #: 2026-06-01 trap above: input never counts against the small OUTPUT
+ #: ceiling — this is its own bound, sized so no legitimate flow reaches
+ #: it (~15 rounds of a 27k-token fixed block). Live 2026-07-26: one
+ #: voice turn summed 686k input tokens across loop rounds ≈ $1 on the
+ #: configured tool model. Tripping this behaves exactly like the other
+ #: two bounds: the loop's budget directive forces one final grounded
+ #: synthesis round — an honest answer, never a silent drop.
+ max_input_tokens_total: int = 400_000
turns_used: int = 0
tokens_used: int = 0 # OUTPUT tokens accumulated (runaway-generation signal)
- input_tokens_seen: int = 0 # telemetry only — re-sent prompt, not a budget input
+ input_tokens_seen: int = 0 # cumulative re-sent prompt (cost backstop + telemetry)
def record_turn(self, tokens_in: int = 0, tokens_out: int = 0) -> None:
self.turns_used += 1
- # Only generated (output) tokens count toward the ceiling — see module
- # docstring. The re-sent prompt is tracked separately for telemetry.
+ # Only generated (output) tokens count toward the OUTPUT ceiling — see
+ # module docstring. The re-sent prompt accumulates against its own,
+ # far larger cost backstop.
self.tokens_used += int(tokens_out)
self.input_tokens_seen += int(tokens_in)
def exceeded(self) -> bool:
- return self.turns_used >= self.max_turns or self.tokens_used >= self.max_tokens_total
+ return (
+ self.turns_used >= self.max_turns
+ or self.tokens_used >= self.max_tokens_total
+ or self.input_tokens_seen >= self.max_input_tokens_total
+ )
def remaining_turns(self) -> int:
return max(0, self.max_turns - self.turns_used)
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index ef4018510d..8ef4ac849a 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -794,6 +794,24 @@ def _is_instructional_question(user_text: str) -> bool:
# NEVER in here (the question must stay answerable inline).
_SPAWN_TOOL_NAMES: frozenset[str] = frozenset({"spawn_worker", "multi_spawn"})
+# Agentic-IDE pane tools that only make sense RELATIVE TO AN OPEN WORKSPACE.
+# With none open, every one of them can only fail — while their schemas cost
+# ~10 KB of input on every tool-loop iteration (2026-07-28 cost audit).
+# Deliberately NOT listed: ``agentic-ide-status`` (answers "nothing is open"
+# honestly) and ``agentic-ide-resume`` (the command that OPENS a workspace
+# by voice — hiding it would strand the feature).
+_AGENTIC_IDE_WORKSPACE_TOOL_NAMES: frozenset[str] = frozenset({
+ "agentic-ide-terminal-report",
+ "agentic-ide-prompt",
+ "agentic-ide-fanout",
+ "agentic-ide-spawn-terminals",
+ "agentic-ide-move-terminal",
+ "agentic-ide-close-agent-terminals",
+ "agentic-ide-focus",
+ "agentic-ide-interrupted",
+ "agentic-ide-continue-interrupted",
+})
+
# Consequential action tools a turn with NO action signal of its own must never
# INHERIT from the conversation context. GENERAL rule (not one phrase): a
# question, a remark, or a mis-transcription asks for no desktop action, so it
@@ -5438,6 +5456,36 @@ class BrainManager:
log.debug("knowledge-question spawn-hide gate failed", exc_info=True)
return tools
+ def _hide_agentic_ide_tools_without_workspace(
+ self, tools: dict[str, Tool]
+ ) -> dict[str, Tool]:
+ """Drop the pane-scoped Agentic-IDE tools when NO workspace is open.
+
+ A capability gate, not a keyword guess: without an open workspace
+ those tools can only fail, so hiding them loses nothing — and their
+ schemas are ~10 KB of input re-sent on every tool-loop iteration.
+ ``agentic-ide-status`` and ``agentic-ide-resume`` always stay (see
+ _AGENTIC_IDE_WORKSPACE_TOOL_NAMES). Defensive: any fault returns
+ the tools unchanged so a gate bug can never blind the brain.
+ """
+ if not isinstance(tools, dict):
+ return tools
+ try:
+ if not any(n in tools for n in _AGENTIC_IDE_WORKSPACE_TOOL_NAMES):
+ return tools
+ from jarvis.agentic_ide.session import get_registry as _ide_registry
+
+ if _ide_registry().session is not None:
+ return tools
+ return {
+ n: tool
+ for n, tool in tools.items()
+ if n not in _AGENTIC_IDE_WORKSPACE_TOOL_NAMES
+ }
+ except Exception: # noqa: BLE001 — gate must never blind the brain
+ log.debug("agentic-ide workspace tool gate failed", exc_info=True)
+ return tools
+
def _hide_action_tools_on_signalless_turn(
self, tools: dict[str, Tool], user_text: str
) -> dict[str, Tool]:
@@ -9432,6 +9480,14 @@ class BrainManager:
_turn_tools = self._hide_spawn_when_plugin_tool_handles_turn(
_turn_tools, routing_text
)
+ # Agentic-IDE pane tools exist only relative to an OPEN workspace
+ # (2026-07-28 cost audit): with none open they can only fail,
+ # while their schemas ride every loop iteration. Status/resume
+ # always stay visible.
+ if isinstance(_turn_tools, dict):
+ _turn_tools = self._hide_agentic_ide_tools_without_workspace(
+ _turn_tools
+ )
# A referential follow-up that inherited a currently registered
# plugin/MCP tool remains inline even when that tool has no usage
# card. The explicit heavy-work and artifact requests above retain
@@ -9667,8 +9723,22 @@ class BrainManager:
try:
from jarvis.brain.cost import calculate_cost_usd
cost_usd_total = calculate_cost_usd(model, tokens_in_total, tokens_out_total)
+ if cost_usd_total == 0.0 and tokens_in_total > 0:
+ # An unknown model prices as $0.00 and every surface
+ # then renders the turn as free — that silence is how
+ # 1.87M deepseek tokens went unbilled for a month
+ # (2026-07-28 cost audit). Say it once per turn.
+ log.warning(
+ "No pricing entry for model %r — %d in / %d out "
+ "tokens recorded as $0.00; add it to "
+ "jarvis/brain/cost.py PRICING_USD_PER_MTOK",
+ model, tokens_in_total, tokens_out_total,
+ )
except Exception: # noqa: BLE001
- pass
+ log.warning(
+ "Cost calculation failed for model %r — recording $0.00",
+ model, exc_info=True,
+ )
await self._bus.publish(BrainTurnStarted(
provider=prov_name,
model=model,
diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.py
index 1c713ac83f..25da8ebc46 100644
--- a/jarvis/commands/registry.py
+++ b/jarvis/commands/registry.py
@@ -492,7 +492,10 @@ def _build_registry() -> tuple[AppCommand, ...]:
"connected CLI, Marketplace, and MCP tools."
),
method="GET",
- path="/api/tools",
+ # The brief listing, deliberately not /api/tools: the full route
+ # serializes every schema (50-200k chars) and the tool-result cap
+ # slices that mid-JSON (2026-07-28 cost audit).
+ path="/api/tools/brief",
worker_allowed=True,
params={"type": "object", "properties": {}},
ui_section="settings",
diff --git a/jarvis/core/capabilities.py b/jarvis/core/capabilities.py
index 84f8ccf43c..8ace09ccd2 100644
--- a/jarvis/core/capabilities.py
+++ b/jarvis/core/capabilities.py
@@ -292,6 +292,16 @@ class CapabilityRegistry:
return True
return False
+ #: Prompt-render budget. Every MCP tool and CLI registers a capability,
+ #: so an unbounded render duplicated the whole tool surface inside the
+ #: system prompt on every turn (2026-07-28 cost audit) while every
+ #: neighbouring prompt section carries a budget. Overflow is announced
+ #: with an "… and N more" tail — never a silent hard slice, because this
+ #: block also anchors the "never invent tools" rule and the evidence
+ #: gate.
+ _RENDER_MAX_ENTRIES = 40
+ _RENDER_MAX_DESCRIPTION_CHARS = 160
+
def render_for_prompt(self, lang: Literal["de", "en"] = "de") -> str:
"""Render the registered capabilities as a bullet list for the system
prompt, replacing the old hard-coded ``NUTZE: search_web`` block.
@@ -304,7 +314,22 @@ class CapabilityRegistry:
caps = self.all()
if not caps:
return "No capabilities registered."
- lines = [f"• {cap.id} — {cap.description}" for cap in caps]
+ shown = caps[: self._RENDER_MAX_ENTRIES]
+ lines = []
+ for cap in shown:
+ description = str(cap.description or "")
+ if len(description) > self._RENDER_MAX_DESCRIPTION_CHARS:
+ description = (
+ description[: self._RENDER_MAX_DESCRIPTION_CHARS - 1] + "…"
+ )
+ lines.append(f"• {cap.id} — {description}")
+ hidden = len(caps) - len(shown)
+ if hidden > 0:
+ hidden_ids = ", ".join(cap.id for cap in caps[len(shown) :])
+ lines.append(
+ f"… and {hidden} more capabilities (available, just not "
+ f"described here): {hidden_ids}"
+ )
return "\n".join(lines)
diff --git a/jarvis/plugins/brain/_anthropic_base.py b/jarvis/plugins/brain/_anthropic_base.py
index b6905fc917..3266a2f925 100644
--- a/jarvis/plugins/brain/_anthropic_base.py
+++ b/jarvis/plugins/brain/_anthropic_base.py
@@ -238,7 +238,12 @@ async def stream_complete(
usage_d = {
"input_tokens": int(getattr(usage, "input_tokens", 0) or 0),
"output_tokens": int(getattr(usage, "output_tokens", 0) or 0),
- "cache_read_input_tokens": int(
+ # The protocol key is cache_hit_tokens (protocols.py) —
+ # this plugin used to forward Anthropic's wire name
+ # cache_read_input_tokens, which no consumer reads, so
+ # cache hits were invisible in cost and telemetry and
+ # cache regressions could not be measured.
+ "cache_hit_tokens": int(
getattr(usage, "cache_read_input_tokens", 0) or 0),
}
yield BrainDelta(finish_reason=finish, usage=usage_d or None)
diff --git a/jarvis/plugins/brain/_openai_base.py b/jarvis/plugins/brain/_openai_base.py
index 285680f2c1..bc0605d81d 100644
--- a/jarvis/plugins/brain/_openai_base.py
+++ b/jarvis/plugins/brain/_openai_base.py
@@ -377,10 +377,19 @@ async def stream_complete(
# Usage info (OpenAI delivers this in the last chunk)
usage = getattr(chunk, "usage", None)
if usage is not None:
- yield BrainDelta(usage={
+ usage_payload = {
"input_tokens": int(getattr(usage, "prompt_tokens", 0) or 0),
"output_tokens": int(getattr(usage, "completion_tokens", 0) or 0),
- })
+ }
+ # Cache hits were invisible on this path (2026-07-28 cost audit:
+ # 84% of tool-loop tokens ran through OpenAI-protocol gateways) —
+ # without the protocol's cache_hit_tokens key nobody can measure
+ # whether a prompt-cache change works or what a turn really cost.
+ details = getattr(usage, "prompt_tokens_details", None)
+ cached = int(getattr(details, "cached_tokens", 0) or 0)
+ if cached > 0:
+ usage_payload["cache_hit_tokens"] = cached
+ yield BrainDelta(usage=usage_payload)
_UNSUPPORTED_ERROR_MARKERS = (
diff --git a/jarvis/ui/web/tools_routes.py b/jarvis/ui/web/tools_routes.py
index 1ee9db19c2..2e480eb1ab 100644
--- a/jarvis/ui/web/tools_routes.py
+++ b/jarvis/ui/web/tools_routes.py
@@ -63,3 +63,28 @@ async def list_tools(request: Request) -> dict[str, Any]:
"total": len(tools),
"by_source": by_source,
}
+
+
+async def list_tools_brief(request: Request) -> dict[str, Any]:
+ """The tool surface as a language model needs it: names, one line each.
+
+ The full listing above serializes every schema and runs to 50-200k
+ characters; the model-facing tool-result cap sliced that to 8k
+ mid-JSON, so the ``tools-list`` voice command paid thousands of input
+ tokens per loop iteration for a structurally broken fragment
+ (2026-07-28 cost audit). Schemas stay in the full route for the UI.
+ """
+ full = await list_tools(request)
+ return {
+ "tools": [
+ {
+ "name": t["name"],
+ "summary": str(t["description"]).split("\n", 1)[0][:140],
+ "source": t["source"],
+ }
+ for t in full["tools"]
+ ],
+ "total": full["total"],
+ "by_source": full["by_source"],
+ }
diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.py
index 47bcab8f40..662ab4f660 100644
--- a/tests/unit/brain/test_routing.py
+++ b/tests/unit/brain/test_routing.py
@@ -3506,3 +3506,78 @@ def test_pc_control_run_skill_gate_is_fault_tolerant() -> None:
manager = _manager_with_cu_runskill_search()
sentinel = object()
assert manager._hide_run_skill_on_pc_control_turn(sentinel, "Oeffne Chrome") is sentinel # type: ignore[arg-type] # i18n-allow: German voice command under test
+
+
+# ---------------------------------------------------------------------------
+# Agentic-IDE workspace tool gate (2026-07-28 cost audit): the pane-scoped
+# agentic-ide-* tools only make sense relative to an OPEN workspace. With none
+# open they can only fail, while their schemas cost ~10 KB of input on every
+# tool-loop iteration. agentic-ide-status (honest "nothing is open" answer)
+# and agentic-ide-resume (the command that OPENS a workspace by voice) must
+# never be hidden.
+# ---------------------------------------------------------------------------
+
+
+class _FakeIdeTool:
+ schema: dict[str, Any] = {}
+
+ def __init__(self, name: str) -> None:
+ self.name = name
+
+
+def _manager_with_ide_tools() -> BrainManager:
+ tools = {
+ name: _FakeIdeTool(name)
+ for name in (
+ "agentic-ide-status",
+ "agentic-ide-resume",
+ "agentic-ide-prompt",
+ "agentic-ide-terminal-report",
+ "agentic-ide-spawn-terminals",
+ )
+ }
+ tools["search_web"] = _FakeSearchTool()
+ return BrainManager(
+ config=JarvisConfig(),
+ bus=EventBus(),
+ tools=tools,
+ tool_executor=_RecordingExecutor(), # type: ignore[arg-type]
+ )
+
+
+def test_no_workspace_hides_pane_tools_keeps_status_and_resume(monkeypatch) -> None:
+ import jarvis.agentic_ide.session as ide_session
+
+ class _NoWorkspaceRegistry:
+ session = None
+
+ monkeypatch.setattr(ide_session, "get_registry", lambda: _NoWorkspaceRegistry())
+ manager = _manager_with_ide_tools()
+ gated = manager._hide_agentic_ide_tools_without_workspace(dict(manager._tools))
+ assert "agentic-ide-prompt" not in gated
+ assert "agentic-ide-terminal-report" not in gated
+ assert "agentic-ide-spawn-terminals" not in gated
+ assert "agentic-ide-status" in gated, "status must answer 'nothing open' honestly"
+ assert "agentic-ide-resume" in gated, "resume is what OPENS a workspace by voice"
+ assert "search_web" in gated
+
+
+def test_open_workspace_keeps_every_pane_tool(monkeypatch) -> None:
+ import jarvis.agentic_ide.session as ide_session
+
+ class _OpenWorkspaceRegistry:
+ session = object()
+
+ monkeypatch.setattr(ide_session, "get_registry", lambda: _OpenWorkspaceRegistry())
+ manager = _manager_with_ide_tools()
+ gated = manager._hide_agentic_ide_tools_without_workspace(dict(manager._tools))
+ assert set(gated) == set(manager._tools), "an open workspace hides nothing"
+
+
+def test_agentic_ide_gate_is_fault_tolerant() -> None:
+ manager = _manager_with_ide_tools()
+ sentinel = object()
+ assert (
+ manager._hide_agentic_ide_tools_without_workspace(sentinel) # type: ignore[arg-type]
+ is sentinel
+ )
diff --git a/tests/unit/test_iteration_budget.py b/tests/unit/test_iteration_budget.py
index 9e17b4121f..a1a90b0d75 100644
--- a/tests/unit/test_iteration_budget.py
+++ b/tests/unit/test_iteration_budget.py
@@ -36,6 +36,21 @@ def test_huge_resent_prompt_does_not_exhaust_the_loop():
assert b.input_tokens_seen == 60_000
+def test_cumulative_input_backstop_trips_only_on_runaway_loops():
+ # 2026-07-28 cost audit: one voice turn summed 686k input tokens across
+ # loop rounds (the fixed ~27k block re-sent every iteration) ≈ $1. The
+ # input backstop bounds that tail without touching legitimate flows —
+ # and unlike the 2026-06-01 trap, a single large-context turn stays
+ # far below it.
+ b = IterationBudget(max_turns=100, max_tokens_total=50_000)
+ b.record_turn(tokens_in=60_000, tokens_out=40)
+ assert not b.exceeded(), "one large-context turn must not trip the backstop"
+ for _ in range(6):
+ b.record_turn(tokens_in=60_000, tokens_out=40)
+ assert b.input_tokens_seen >= 400_000
+ assert b.exceeded()
+
+
def test_snapshot_structure():
b = IterationBudget(max_turns=5, max_tokens_total=500)
b.record_turn(tokens_in=100, tokens_out=50)