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.

fix(missions): fail fast with an actionable message when the worker model cannot call tools

Ruben Lütkeaba3d533e808
diff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.py
index c385af79eb..ab00aaea5b 100644
--- a/jarvis/missions/workers/api_agent_worker.py
+++ b/jarvis/missions/workers/api_agent_worker.py
@@ -137,6 +137,25 @@ def _build_brain(provider: str, model: str) -> Any:
return getattr(mod, cls_name)(model=model)
+def _tool_incapable_message(model: str, provider: str, *, detail: str = "") -> str:
+ """Shared honest-failure text for a worker model that cannot call tools.
+
+ Missions deliver ALL work through tool calls (Write/Edit/Bash/...); a
+ text-only reply produces an empty diff and the mission dies 3 critic
+ loops later with an inscrutable ``critic_loop_exhausted`` (forensics
+ Bug 10). Fail fast and actionably instead.
+ """
+ msg = (
+ f"worker model {model!r} (provider {provider!r}) cannot call tools, "
+ "and missions deliver work exclusively through tool calls. Pick a "
+ "tool-capable model under Settings -> Jarvis-Agents (brain.worker), "
+ "then retry the mission."
+ )
+ if detail:
+ msg = f"{msg} (provider error: {detail})"
+ return msg
+
+
class ApiAgentWorker:
"""Phase-6 worker that drives an OpenAI-compatible API brain in a tool loop.
@@ -201,6 +220,25 @@ class ApiAgentWorker:
yield res
return
+ # AP-21: gate on CAPABILITY, and only on an explicit "no" — an absent
+ # probe or one that raises is UNKNOWN, and unknown must PROCEED (never
+ # brick a mission on a probe glitch). Only can_call_tools() returning
+ # False literally gates. Checked BEFORE the turn loop so a tool-less
+ # model fails in one line instead of 3 silent critic loops later.
+ try:
+ can_call_tools = bool(brain.can_call_tools())
+ except Exception: # noqa: BLE001 — capability probe must never brick a mission
+ can_call_tools = True
+ if not can_call_tools:
+ res = ClaudeResult(
+ subtype="error_during_execution", is_error=True, session_id=session_id,
+ duration_ms=0,
+ result=_tool_incapable_message(resolved_model, self.provider),
+ )
+ _emit_line(res)
+ yield res
+ return
+
logger.info(
"ApiAgentWorker[%s] spawn in-process: provider=%s model=%s cwd=%s",
worker_id, self.provider, resolved_model, worktree,
@@ -235,11 +273,35 @@ class ApiAgentWorker:
)
text_parts: list[str] = []
tool_calls: list[dict[str, Any]] = []
- async for delta in brain.complete(req):
- if delta.content:
- text_parts.append(delta.content)
- if delta.tool_call:
- tool_calls.append(delta.tool_call)
+ try:
+ async for delta in brain.complete(req):
+ if delta.content:
+ text_parts.append(delta.content)
+ if delta.tool_call:
+ tool_calls.append(delta.tool_call)
+ except Exception as exc: # noqa: BLE001
+ # The capability pre-gate (above) catches a model the brain
+ # ALREADY knows is tool-incapable. Some providers (OpenRouter
+ # routing to a tool-less upstream) only discover this on the
+ # FIRST live round-trip, surfacing as a 404 "no endpoints
+ # found that support tool use"-class error. Recognize that
+ # shape on turn 0 and convert it to the SAME honest message
+ # instead of letting the raw provider error propagate up as
+ # an inscrutable worker failure.
+ low = str(exc).lower()
+ if turn == 0 and "tool" in low and ("support" in low or "404" in low):
+ res = ClaudeResult(
+ subtype="error_during_execution", is_error=True,
+ session_id=session_id,
+ duration_ms=int((time.perf_counter() - t0) * 1000),
+ result=_tool_incapable_message(
+ resolved_model, self.provider, detail=str(exc)
+ ),
+ )
+ _emit_line(res)
+ yield res
+ return
+ raise
assistant_text = "".join(text_parts).strip()
if assistant_text:
diff --git a/tests/missions/test_api_agent_worker_capability_gate.py b/tests/missions/test_api_agent_worker_capability_gate.py
new file mode 100644
index 0000000000..8ff2594fc6
--- /dev/null
+++ b/tests/missions/test_api_agent_worker_capability_gate.py
@@ -0,0 +1,145 @@
+"""A tool-incapable worker model must fail the mission EARLY with an
+actionable message — not via empty-diff critic exhaustion (fresh-machine
+Bug 10, forensics). Covers both:
+
+1. the pre-gate on ``brain.can_call_tools()`` before the turn loop even
+ starts (``complete()`` must never be reached), and
+2. the wrap of the FIRST ``brain.complete()`` round-trip, converting an
+ OpenRouter-style "no endpoints support tool use" provider error into the
+ same honest message instead of a raw/opaque failure.
+
+AP-21: gate on CAPABILITY, and only on an explicit "no" — absent or raising
+probes are UNKNOWN and must PROCEED.
+"""
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from pathlib import Path
+
+import pytest
+
+from jarvis.core.protocols import BrainDelta, BrainRequest
+from jarvis.missions.workers.api_agent_worker import ApiAgentWorker
+
+
+class _NoToolsBrain:
+ """Explicitly reports it cannot call tools — the gate must catch this
+ BEFORE ``complete()`` is ever awaited."""
+
+ def can_call_tools(self) -> bool:
+ return False
+
+ async def complete(self, req: BrainRequest): # pragma: no cover - must never run
+ raise AssertionError("complete() called despite can_call_tools()==False")
+ yield # pragma: no cover
+
+
+class _RaisingProbeBrain:
+ """A capability probe that raises is UNKNOWN, not "no" — must proceed
+ (AP-21) and reach ``complete()`` normally."""
+
+ def can_call_tools(self) -> bool:
+ raise RuntimeError("capability catalog unavailable")
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ yield BrainDelta(content="ok")
+ yield BrainDelta(finish_reason="end_turn")
+
+
+class _NoProbeBrain:
+ """No ``can_call_tools`` attribute at all — absent is also UNKNOWN and
+ must proceed, mirroring the FakeBrain used by the sibling worker tests."""
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ yield BrainDelta(content="ok")
+ yield BrainDelta(finish_reason="end_turn")
+
+
+class _NoEndpointsBrain:
+ """Reports itself tool-capable, but the FIRST live round-trip fails with
+ an OpenRouter-shaped 'no endpoints support tool use' error — the gate
+ can't catch this in advance; only the first-call wrap can."""
+
+ def can_call_tools(self) -> bool:
+ return True
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ raise RuntimeError(
+ "Error code: 404 - No endpoints found that support tool use."
+ )
+ yield # pragma: no cover
+
+
+def _patch_brain(monkeypatch: pytest.MonkeyPatch, brain: object) -> None:
+ import jarvis.missions.workers.api_agent_worker as mod
+
+ monkeypatch.setattr(mod, "_build_brain", lambda provider, model: brain, raising=False)
+
+
+async def _drain(worker: ApiAgentWorker, **kw): # noqa: ANN003
+ events = []
+ async for ev in worker.spawn(**kw):
+ events.append(ev)
+ return events
+
+
+async def test_tool_incapable_model_fails_early(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_brain(monkeypatch, _NoToolsBrain())
+ worker = ApiAgentWorker("openrouter")
+ events = await _drain(
+ worker, prompt="build x", worktree=tmp_path, env={}, job=None,
+ worker_id="m::0", log_dir=tmp_path / "_logs",
+ )
+
+ errors = [e for e in events if getattr(e, "is_error", False)]
+ assert errors, "expected an early error result"
+ msg = (errors[-1].result or "").lower()
+ assert "cannot call tools" in msg
+ assert "jarvis-agents" in msg
+ # the gate fires before the turn loop — no assistant/user turn was emitted
+ kinds = [type(e).__name__ for e in events]
+ assert "ClaudeAssistantMessage" not in kinds
+ assert kinds[-1] == "ClaudeResult"
+
+
+async def test_raising_capability_probe_is_unknown_and_proceeds(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_brain(monkeypatch, _RaisingProbeBrain())
+ worker = ApiAgentWorker("openrouter")
+ events = await _drain(
+ worker, prompt="build x", worktree=tmp_path, env={}, job=None,
+ worker_id="m::0", log_dir=tmp_path / "_logs",
+ )
+ assert events[-1].is_error is False
+
+
+async def test_missing_capability_probe_is_unknown_and_proceeds(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_brain(monkeypatch, _NoProbeBrain())
+ worker = ApiAgentWorker("openrouter")
+ events = await _drain(
+ worker, prompt="build x", worktree=tmp_path, env={}, job=None,
+ worker_id="m::0", log_dir=tmp_path / "_logs",
+ )
+ assert events[-1].is_error is False
+
+
+async def test_first_round_trip_no_endpoints_error_is_translated(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_brain(monkeypatch, _NoEndpointsBrain())
+ worker = ApiAgentWorker("openrouter")
+ events = await _drain(
+ worker, prompt="build x", worktree=tmp_path, env={}, job=None,
+ worker_id="m::0", log_dir=tmp_path / "_logs",
+ )
+
+ errors = [e for e in events if getattr(e, "is_error", False)]
+ assert errors, "expected the raw provider error to be translated"
+ msg = (errors[-1].result or "").lower()
+ assert "cannot call tools" in msg
+ assert "jarvis-agents" in msg