"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(swarm): retry failed/stale/cancelled runs (HTTP + MCP)
Haozhe Wud2f853233fe7
diff --git a/README.md b/README.mdindex b9b4b4c58..f0ae39d7e 100644--- a/README.md+++ b/README.md@@ -675,7 +675,7 @@ Settings reads are side-effect free: `GET /settings/llm` and `GET /settings/data## 🔌 MCP Plugin-Vibe-Trading exposes 35 MCP tools for any MCP-compatible client. Runs as a stdio subprocess — no server setup needed. Core research tools work with zero API keys for HK/US/crypto; trading connector tools use the selected connector profile, and `run_swarm` needs an LLM key.+Vibe-Trading exposes 36 MCP tools for any MCP-compatible client. Runs as a stdio subprocess — no server setup needed. Core research tools work with zero API keys for HK/US/crypto; trading connector tools use the selected connector profile, and `run_swarm` needs an LLM key.<details><summary><b>Claude Desktop</b></summary>@@ -943,7 +943,7 @@ Vibe-Trading/├── agent/ # Backend (Python)│ ├── cli/ # CLI package — interactive TUI + subcommands│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE-│ ├── mcp_server.py # MCP server — 35 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 36 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent corediff --git a/README_ar.md b/README_ar.mdindex a1a9ca6b5..4611d22e5 100644--- a/README_ar.md+++ b/README_ar.md@@ -774,7 +774,7 @@ Vibe-Trading/├── agent/ # Backend (Python)│ ├── cli/ # CLI package — interactive TUI + subcommands│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE-│ ├── mcp_server.py # MCP server — 35 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 36 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent corediff --git a/README_ja.md b/README_ja.mdindex 1815618bd..153feeeeb 100644--- a/README_ja.md+++ b/README_ja.md@@ -671,7 +671,7 @@ Settings reads は side-effect free です。`GET /settings/llm` と `GET /setti## 🔌 MCP Plugin-Vibe-Trading は MCP-compatible client 向けに 35 MCP tools を公開します。stdio subprocess として動作し、server setup は不要です。Core research tools は HK/US/crypto で API key なしに動作し、trading connector tools は選択中の connector profile を使います。LLM key が必要なのは `run_swarm` のみです。+Vibe-Trading は MCP-compatible client 向けに 36 MCP tools を公開します。stdio subprocess として動作し、server setup は不要です。Core research tools は HK/US/crypto で API key なしに動作し、trading connector tools は選択中の connector profile を使います。LLM key が必要なのは `run_swarm` のみです。<details><summary><b>Claude Desktop</b></summary>@@ -771,7 +771,7 @@ Vibe-Trading/├── agent/ # バックエンド (Python)│ ├── cli/ # CLI パッケージ — インタラクティブ TUI + サブコマンド│ ├── api_server.py # FastAPI サーバー — runs、sessions、upload、swarm、SSE-│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 35 tools+│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 36 tools│ ││ ├── src/│ │ ├── agent/ # ReAct エージェントコアdiff --git a/README_ko.md b/README_ko.mdindex 3bacabce8..0fd5c1d40 100644--- a/README_ko.md+++ b/README_ko.md@@ -774,7 +774,7 @@ Vibe-Trading/├── agent/ # Backend (Python)│ ├── cli/ # CLI package — interactive TUI + subcommands│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE-│ ├── mcp_server.py # MCP server — 35 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 36 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent corediff --git a/README_zh.md b/README_zh.mdindex b74e7d9b8..f5490ca22 100644--- a/README_zh.md+++ b/README_zh.md@@ -670,7 +670,7 @@ Settings 读取无副作用:`GET /settings/llm` 和 `GET /settings/data-source## 🔌 MCP Plugin-Vibe-Trading 为任何 MCP-compatible client 暴露 35 个 MCP tools。它作为 stdio subprocess 运行,无需 server setup。核心 research tools 对港股/美股/加密零 API key 可用;trading connector tools 使用当前选择的 connector profile;只有 `run_swarm` 需要 LLM key。+Vibe-Trading 为任何 MCP-compatible client 暴露 36 个 MCP tools。它作为 stdio subprocess 运行,无需 server setup。核心 research tools 对港股/美股/加密零 API key 可用;trading connector tools 使用当前选择的 connector profile;只有 `run_swarm` 需要 LLM key。<details><summary><b>Claude Desktop</b></summary>@@ -770,7 +770,7 @@ Vibe-Trading/├── agent/ # 后端(Python)│ ├── cli/ # CLI 包 —— 交互式 TUI + 子命令│ ├── api_server.py # FastAPI server —— runs、sessions、upload、swarm、SSE-│ ├── mcp_server.py # MCP server —— 35 个工具,面向 OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server —— 36 个工具,面向 OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent 内核diff --git a/agent/api_server.py b/agent/api_server.pyindex 292f9b017..e3cb6be0b 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -2239,6 +2239,39 @@ async def cancel_swarm_run(run_id: str):return {"status": "cancelled"}[email protected]("/swarm/runs/{run_id}/retry", dependencies=[Depends(require_auth)])+async def retry_swarm_run(run_id: str, http_request: Request):+ """Retry a failed, stale, or cancelled swarm run.++ Creates a new run with the same preset and user_vars as the original.+ """+ _validate_path_param(run_id, "run_id")+ runtime = _get_swarm_runtime()+ loaded = runtime._store.load_run(run_id)+ if not loaded:+ raise HTTPException(status_code=404, detail=f"Run {run_id} not found")++ # Reconcile first so a stale "running" run whose host died gets demoted+ # before we gate on status; only a genuinely active run blocks retry.+ from src.swarm.models import RunStatus++ reconciled = runtime._store.reconcile_run(loaded, write=True)+ if reconciled.status == RunStatus.running:+ raise HTTPException(status_code=409, detail="Cannot retry a running run. Cancel it first.")++ try:+ new_run = runtime.start_run(+ reconciled.preset_name,+ reconciled.user_vars or {},+ include_shell_tools=_shell_tools_enabled_for_request(http_request),+ )+ return {"id": new_run.id, "status": new_run.status.value, "preset_name": new_run.preset_name}+ except FileNotFoundError as e:+ raise HTTPException(status_code=404, detail=str(e))+ except ValueError as e:+ raise HTTPException(status_code=400, detail=str(e))++# ============================================================================# Live trading channel — consent commit + kill switch# ============================================================================diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex c5f1ecd40..ff62c6085 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -1285,6 +1285,60 @@ def reap_stale_runs() -> str:return json.dumps({"reaped": reaped}, ensure_ascii=False, indent=2)+def retry_run(run_id: str) -> str:+ """Retry a failed, stale, or cancelled swarm run.++ Re-launches a brand-new run with the same preset and variables as the+ original; the original run is left untouched as a record. Use this after+ spotting a ``failed`` or stale run via ``list_runs``. A still-``running``+ run cannot be retried — cancel or reap it first.++ Args:+ run_id: ID of the run to retry (from ``list_runs`` / ``get_swarm_status``).++ Returns:+ JSON payload for the newly created run (``run_id`` / ``status`` /+ ``preset`` …), or an ``error`` object if the run is missing or active.+ """+ from src.config import load_swarm_agent_config+ from src.swarm.models import RunStatus+ from src.swarm.runtime import SwarmRuntime++ store = _get_swarm_store()+ loaded = store.load_run(run_id)+ if loaded is None:+ return json.dumps({"status": "error", "error": f"Run {run_id} not found"}, ensure_ascii=False)++ # Reconcile first so a zombie "running" run whose host died is demoted+ # before we gate on status; only a genuinely active run blocks retry.+ reconciled = store.reconcile_run(loaded, write=True)+ if reconciled.status == RunStatus.running:+ return json.dumps(+ {"status": "error", "error": "Cannot retry a running run. Cancel or reap it first."},+ ensure_ascii=False,+ )++ agent_config = load_swarm_agent_config()+ runtime = SwarmRuntime(store=store, agent_config=agent_config)+ try:+ new_run = runtime.start_run(+ reconciled.preset_name,+ reconciled.user_vars or {},+ include_shell_tools=_include_shell_tools,+ )+ except FileNotFoundError as exc:+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)+ except ValueError as exc:+ return json.dumps({"status": "error", "error": f"DAG validation failed: {exc}"}, ensure_ascii=False)++ return json.dumps(+ _build_run_payload(store, new_run.id, new_run.preset_name, timed_out=False),+ ensure_ascii=False,+ indent=2,+ )++# ---------------------------------------------------------------------------# Trade journal tool# ---------------------------------------------------------------------------diff --git a/agent/tests/test_mcp_regression.py b/agent/tests/test_mcp_regression.pyindex 9dfe6ed41..3e3454a46 100644--- a/agent/tests/test_mcp_regression.py+++ b/agent/tests/test_mcp_regression.py@@ -161,6 +161,7 @@ def test_mcp_server_exposes_well_known_tool_names() -> None:"read_file","list_swarm_presets","run_swarm",+ "retry_run","start_research_goal","get_research_goal","add_goal_evidence",diff --git a/agent/tests/test_security_auth_api.py b/agent/tests/test_security_auth_api.pyindex b5e86e7bd..1d958332a 100644--- a/agent/tests/test_security_auth_api.py+++ b/agent/tests/test_security_auth_api.py@@ -305,6 +305,7 @@ def test_swarm_run_endpoints_reject_traversal_run_id() -> None:("get", "/swarm/runs/foo.bar"),("get", "/swarm/runs/foo.bar/events"),("post", "/swarm/runs/foo.bar/cancel"),+ ("post", "/swarm/runs/foo.bar/retry"),):response = getattr(client, method)(path)assert response.status_code == 400, f"{method.upper()} {path} should be rejected"diff --git a/agent/tests/test_swarm_retry.py b/agent/tests/test_swarm_retry.pynew file mode 100644index 000000000..a272b2a74--- /dev/null+++ b/agent/tests/test_swarm_retry.py@@ -0,0 +1,85 @@+"""Tests for the swarm-run retry path (MCP ``retry_run`` tool + HTTP endpoint).++Retry re-launches a brand-new run with the same preset/variables as a prior+``failed`` / ``cancelled`` / stale run, leaving the original untouched. A+still-``running`` run must be refused so we never fork an active run.+"""++from __future__ import annotations++import json+from datetime import datetime, timezone++import mcp_server+import src.swarm.runtime as rt+from src.swarm.models import RunStatus, SwarmAgentSpec, SwarmRun, SwarmTask, TaskStatus+from src.swarm.store import SwarmStore+from src.swarm.task_store import TaskStore+++def _make_run(run_id: str, status: RunStatus) -> SwarmRun:+ agent = SwarmAgentSpec(id="analyst", role="Analyst", system_prompt="x", timeout_seconds=300)+ task = SwarmTask(id="t1", agent_id="analyst", prompt_template="do x")+ run = SwarmRun(+ id=run_id,+ preset_name="demo",+ created_at=datetime.now(timezone.utc).isoformat(),+ agents=[agent],+ tasks=[task],+ user_vars={"target": "AAPL.US"},+ )+ run.status = status+ return run+++def test_retry_run_missing_returns_error(tmp_path, monkeypatch):+ store = SwarmStore(base_dir=tmp_path)+ monkeypatch.setattr(mcp_server, "_get_swarm_store", lambda: store)++ payload = json.loads(mcp_server.retry_run("does-not-exist"))++ assert payload["status"] == "error"+ assert "not found" in payload["error"].lower()+++def test_retry_run_refuses_running_run(tmp_path, monkeypatch):+ store = SwarmStore(base_dir=tmp_path)+ run = _make_run("r-running", RunStatus.running)+ store.create_run(run)+ monkeypatch.setattr(mcp_server, "_get_swarm_store", lambda: store)++ payload = json.loads(mcp_server.retry_run("r-running"))++ assert payload["status"] == "error"+ assert "running" in payload["error"].lower()+++def test_retry_run_relaunches_failed_run_with_same_preset(tmp_path, monkeypatch):+ store = SwarmStore(base_dir=tmp_path)+ original = _make_run("r-failed", RunStatus.failed)+ store.create_run(original)+ monkeypatch.setattr(mcp_server, "_get_swarm_store", lambda: store)++ captured: dict[str, object] = {}++ def fake_start_run(self, preset_name, variables, **kwargs):+ captured["preset_name"] = preset_name+ captured["variables"] = variables+ new = _make_run("r-retry", RunStatus.running)+ new.preset_name = preset_name+ self._store.create_run(new)+ TaskStore(self._store.run_dir(new.id)).save_task(+ new.tasks[0].model_copy(update={"status": TaskStatus.in_progress})+ )+ return new++ monkeypatch.setattr(rt.SwarmRuntime, "start_run", fake_start_run)++ payload = json.loads(mcp_server.retry_run("r-failed"))++ # Same preset + user_vars carried over from the original run.+ assert captured["preset_name"] == "demo"+ assert captured["variables"] == {"target": "AAPL.US"}+ # A fresh run id is returned, not the original.+ assert payload["run_id"] == "r-retry"+ assert payload["status"] == "running"diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 4e03ba8d4..24568fedd 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -123,6 +123,8 @@ export const api = {swarmSseUrl: (id: string) => withAuthQuery(`${BASE}/swarm/runs/${id}/events`),cancelSwarmRun: (id: string) =>request<{ status: string }>(`/swarm/runs/${id}/cancel`, { method: "POST" }),+ retrySwarmRun: (id: string) =>+ request<{ id: string; status: string; preset_name: string }>(`/swarm/runs/${id}/retry`, { method: "POST" }),getLLMSettings: () => request<LLMSettings>("/settings/llm"),updateLLMSettings: (settings: UpdateLLMSettingsRequest) =>request<LLMSettings>("/settings/llm", {