Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(swarm): preserve preset context for continuations (#200)

Chengcheng Dingd1ed1019c09f
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.py
index 9811e352d..dcdfb92ba 100644
--- a/agent/src/agent/context.py
+++ b/agent/src/agent/context.py
@@ -43,7 +43,9 @@ Decide which workflow to use based on the request:
5. Do NOT write run_backtest.py. The engine is built-in.
**Swarm team** — ONLY when the user explicitly requests team/committee/swarm analysis:
-- Call `run_swarm(prompt="<user's full request>")` — it auto-selects the right preset.
+- Call `run_swarm(prompt="<user's full request>", preset_name="<explicit preset>")` when the user names a preset/team, e.g. `investment_committee`.
+- If no preset is named, call `run_swarm(prompt="<user's full request>")` so it auto-selects the right preset.
+- For follow-up wording like "continue", "finish the report", or "continue from ...", do NOT start a fresh swarm from that fragment. Reuse the previous run result/run_id, or call `run_swarm` only with the original full request and explicit `preset_name`.
- Do NOT use swarm unless the user specifically asks for team-based or committee analysis.
**Analysis / research** — user wants factor analysis, options pricing, market data, or general research:
diff --git a/agent/src/tools/swarm_tool.py b/agent/src/tools/swarm_tool.py
index 61ab4148f..fa8911999 100644
--- a/agent/src/tools/swarm_tool.py
+++ b/agent/src/tools/swarm_tool.py
@@ -394,6 +394,65 @@ def _match_preset(prompt: str) -> str:
return "equity_research_team"
+_PRESET_NAMES = {preset_name for preset_name, _, _ in _PRESET_KEYWORDS}
+_CONTINUATION_PATTERNS = (
+ r"^\s*continue\b",
+ r"^\s*resume\b",
+ r"^\s*finish\b",
+ r"\bcontinue\s+(?:and\s+)?finish\b",
+ r"\bcontinue\s+from\b",
+ r"\bfinish\s+(?:the\s+)?report\b",
+ r"\bcomplete\s+(?:the\s+)?report\b",
+ r"\bpick\s+up\s+from\b",
+ r"^\s*继续",
+ r"^\s*接着",
+)
+
+
+def _normalize_preset_name(value: str) -> str | None:
+ """Normalize an explicit preset name and validate it against bundled presets."""
+ normalized = re.sub(r"[\s-]+", "_", value.strip().lower())
+ return normalized if normalized in _PRESET_NAMES else None
+
+
+def _has_preset_signal(prompt: str) -> bool:
+ """Return whether prompt contains an explicit preset name or routing keyword."""
+ normalized_prompt = re.sub(r"[\s-]+", "_", prompt.strip().lower())
+ for preset_name, _, _ in _PRESET_KEYWORDS:
+ if re.search(rf"(?<![a-z0-9]){re.escape(preset_name)}(?![a-z0-9])", normalized_prompt):
+ return True
+ for _, keywords, _ in _PRESET_KEYWORDS:
+ for kw in keywords:
+ if re.search(kw, prompt, re.IGNORECASE):
+ return True
+ return False
+
+
+def _looks_like_continuation_prompt(prompt: str) -> bool:
+ """Detect prompts that refer to prior work instead of a fresh swarm task."""
+ return any(re.search(pattern, prompt, re.IGNORECASE) for pattern in _CONTINUATION_PATTERNS)
+
+
+def _resolve_preset(prompt: str, explicit_preset: str | None = None) -> tuple[str | None, str | None]:
+ """Resolve the preset to run, returning an error string when ambiguous."""
+ if explicit_preset:
+ preset = _normalize_preset_name(explicit_preset)
+ if preset is None:
+ available = ", ".join(sorted(_PRESET_NAMES))
+ return None, f"Unknown preset_name '{explicit_preset}'. Available presets: {available}"
+ return preset, None
+
+ if _looks_like_continuation_prompt(prompt) and not _has_preset_signal(prompt):
+ return (
+ None,
+ "Ambiguous continuation swarm prompt. Reuse the previous swarm result, "
+ "or call run_swarm with preset_name and the original full request. "
+ "Refusing to auto-route this continuation to equity_research_team.",
+ )
+
+ return _match_preset(prompt), None
+
+
def _extract_market(prompt: str) -> str:
"""Extract target market label from prompt.
@@ -572,10 +631,10 @@ class SwarmTool(BaseTool):
name = "run_swarm"
description = (
"Run a multi-agent swarm team for complex analysis tasks. "
- "Provide a natural language prompt; the tool picks a preset from agent/src/swarm/presets "
+ "Provide a natural language prompt and, when known, an explicit preset_name from agent/src/swarm/presets "
"(e.g. equity_research_team, quant_strategy_desk, global_allocation_committee, risk_committee) "
- "and fills template variables. "
- "Example: run_swarm(prompt='Analyze A-share new energy opportunities for Q2 2026')"
+ "so follow-up/continuation prompts do not lose routing context. "
+ "Example: run_swarm(prompt='Analyze A-share new energy opportunities for Q2 2026', preset_name='equity_research_team')"
)
parameters = {
"type": "object",
@@ -584,6 +643,10 @@ class SwarmTool(BaseTool):
"type": "string",
"description": "Natural language description of the analysis task.",
},
+ "preset_name": {
+ "type": "string",
+ "description": "Optional explicit swarm preset name when the user named one or this is a continuation.",
+ },
},
"required": ["prompt"],
}
@@ -632,11 +695,17 @@ class SwarmTool(BaseTool):
ensure_ascii=False,
)
- preset = _match_preset(prompt)
+ preset, preset_error = _resolve_preset(prompt, kwargs.get("preset_name"))
+ if preset_error:
+ return json.dumps(
+ {"status": "error", "error": preset_error},
+ ensure_ascii=False,
+ )
+ assert preset is not None
variables = _build_variables(preset, prompt)
logger.info(
- "SwarmTool: matched preset=%s, variables=%s from prompt: %s",
+ "SwarmTool: resolved preset=%s, variables=%s from prompt: %s",
preset,
variables,
prompt[:100],
diff --git a/agent/tests/test_swarm_tool_preset_matching.py b/agent/tests/test_swarm_tool_preset_matching.py
index d1e7aebdc..ad03d269e 100644
--- a/agent/tests/test_swarm_tool_preset_matching.py
+++ b/agent/tests/test_swarm_tool_preset_matching.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import json
+
import src.tools.swarm_tool as swarm_tool
@@ -24,3 +26,34 @@ def test_explicit_preset_name_accepts_spaces() -> None:
prompt = "Use the investment committee preset for NVDA"
assert swarm_tool._match_preset(prompt) == "investment_committee"
+
+
+def test_explicit_preset_parameter_is_normalized() -> None:
+ preset, error = swarm_tool._resolve_preset(
+ "Continue and finish the report.",
+ explicit_preset="Investment Committee",
+ )
+
+ assert error is None
+ assert preset == "investment_committee"
+
+
+def test_ambiguous_continuation_does_not_fallback_to_equity_team() -> None:
+ preset, error = swarm_tool._resolve_preset(
+ "Continue and finish report. Continue from 'Trim 25% of position if price r'."
+ )
+
+ assert preset is None
+ assert error is not None
+ assert "equity_research_team" in error
+
+
+def test_swarm_tool_rejects_ambiguous_continuation_before_starting_run() -> None:
+ payload = json.loads(
+ swarm_tool.SwarmTool().execute(
+ prompt="Continue and finish report. Continue from 'Trim 25% of position if price r'."
+ )
+ )
+
+ assert payload["status"] == "error"
+ assert "Ambiguous continuation" in payload["error"]