Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(swarm): report tool failures as errors

xkam7ar4e0e312b2b5d
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index 2f89a7203..5b2ae848b 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -691,15 +691,23 @@ def run_worker(
emit=_on_heartbeat,
):
result = registry.execute(tc.name, args)
- if tc.name != "load_skill" and not _is_error_result(result):
+ result_is_error = _is_error_result(result)
+ if tc.name != "load_skill" and not result_is_error:
data_tool_calls += 1
tc_elapsed = time.monotonic() - tc_start
_emit(
- event_callback, "tool_result", agent_id, task_id,
- {"tool": tc.name, "elapsed_ms": int(tc_elapsed * 1000),
- "status": "ok", "iteration": iteration,
- "result_preview": _preview_tool_result(result),
- **mcp_meta},
+ event_callback,
+ "tool_result",
+ agent_id,
+ task_id,
+ {
+ "tool": tc.name,
+ "elapsed_ms": int(tc_elapsed * 1000),
+ "status": "error" if result_is_error else "ok",
+ "iteration": iteration,
+ "result_preview": _preview_tool_result(result),
+ **mcp_meta,
+ },
)
messages.append(
ContextBuilder.format_tool_result(tc.id, tc.name, result[:10_000])
diff --git a/agent/tests/test_swarm_m4_e2e.py b/agent/tests/test_swarm_m4_e2e.py
index c98454544..023138b72 100644
--- a/agent/tests/test_swarm_m4_e2e.py
+++ b/agent/tests/test_swarm_m4_e2e.py
@@ -480,6 +480,7 @@ def test_tool_call_events_carry_mcp_metadata_and_redact_sensitive_arguments(
assert call_data["remote_tool"] == "search"
assert result_data["server"] == "kb"
assert result_data["remote_tool"] == "search"
+ assert result_data["status"] == "ok"
# R-10: redaction is applied to known sensitive keys.
assert call_data["arguments"]["api_key"] == "[redacted]"
@@ -565,6 +566,8 @@ def test_remote_tool_transport_failure_does_not_crash_worker(tmp_path: Path) ->
# decide what to do next. ``stream_chat`` was called twice: once to
# produce the tool call and once to produce the final text.
assert len(llm_factory.stub.tool_defs_seen) >= 2 # type: ignore[attr-defined]
+ tool_results = [event for event in events if event.type == "tool_result"]
+ assert tool_results and tool_results[0].data["status"] == "error"
# --------------------------------------------------------------------------- #
diff --git a/agent/tests/test_swarm_output_contract.py b/agent/tests/test_swarm_output_contract.py
index 40d27c1ac..0ecf7c722 100644
--- a/agent/tests/test_swarm_output_contract.py
+++ b/agent/tests/test_swarm_output_contract.py
@@ -19,9 +19,14 @@ from __future__ import annotations
import threading
from pathlib import Path
+import pytest
+
+from src.agent.tools import BaseTool, ToolRegistry
+from src.providers.chat import LLMResponse, ToolCallRequest
from src.swarm.models import (
RunStatus,
SwarmAgentSpec,
+ SwarmEvent,
SwarmRun,
SwarmTask,
WorkerResult,
@@ -32,8 +37,10 @@ from src.swarm.worker import (
_is_data_agent,
_is_error_result,
_report_written,
+ run_worker,
)
import src.swarm.runtime as rt
+import src.swarm.worker as worker_mod
PLAN_STUB = (
"### Phase 1 — Plan\n"
@@ -206,3 +213,87 @@ def test_is_error_result_other_status_values():
not error envelopes (the worker still credits them as a tool call)."""
assert _is_error_result('{"status": "degenerate", "warning": "T=0"}') is False
assert _is_error_result('{"status": "warning"}') is False
+
+
+class _ResultTool(BaseTool):
+ """Return one canned result or raise to exercise ToolRegistry normalization."""
+
+ name = "market_probe"
+ description = "Return a canned market result."
+ parameters = {"type": "object", "properties": {}}
+
+ def __init__(self, result: str, *, raises: bool = False) -> None:
+ self._result = result
+ self._raises = raises
+
+ def execute(self, **kwargs) -> str:
+ if self._raises:
+ raise RuntimeError("local probe failed")
+ return self._result
+
+
+class _ScriptedLLM:
+ def __init__(self) -> None:
+ self._responses = [
+ LLMResponse(
+ content=None,
+ tool_calls=[
+ ToolCallRequest(id="call-1", name="market_probe", arguments={})
+ ],
+ finish_reason="tool_calls",
+ ),
+ LLMResponse(
+ content="Completed the requested market analysis with a clear conclusion.",
+ tool_calls=[],
+ finish_reason="stop",
+ ),
+ ]
+
+ def stream_chat(self, messages, tools=None, timeout=None, on_text_chunk=None):
+ return self._responses.pop(0)
+
+
+ ("result", "raises", "expected_event_status", "expected_worker_status"),
+ [
+ ('{"status": "ok", "data": [1]}', False, "ok", "completed"),
+ ('{"status": "error", "trace": "...', False, "error", "incomplete"),
+ ("", True, "error", "incomplete"),
+ ],
+)
+def test_tool_result_event_status_and_evidence_credit_agree(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ result: str,
+ raises: bool,
+ expected_event_status: str,
+ expected_worker_status: str,
+) -> None:
+ registry = ToolRegistry()
+ registry.register(_ResultTool(result, raises=raises))
+ monkeypatch.setattr(
+ worker_mod, "build_swarm_registry", lambda *args, **kwargs: registry
+ )
+ monkeypatch.setattr(worker_mod, "ChatLLM", lambda *args, **kwargs: _ScriptedLLM())
+
+ events: list[SwarmEvent] = []
+ worker_result = run_worker(
+ agent_spec=SwarmAgentSpec(
+ id="analyst",
+ role="Analyst",
+ system_prompt="Analyse the result.",
+ tools=["market_probe"],
+ max_iterations=3,
+ ),
+ task=SwarmTask(
+ id="task", agent_id="analyst", prompt_template="Probe the market."
+ ),
+ upstream_summaries={},
+ user_vars={},
+ run_dir=tmp_path,
+ event_callback=events.append,
+ )
+
+ tool_result = next(event for event in events if event.type == "tool_result")
+ assert tool_result.data["status"] == expected_event_status
+ assert worker_result.status == expected_worker_status