Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix: close attempt-owned providers and align integrated MCP and usage contracts

Haozhe Wudc8fd73e6c93
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index e9897f74c..b79830393 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -6,7 +6,7 @@ Zero API key required for HK/US/crypto research markets (yfinance, OKX,
AKShare are free). Trading connector tools are profile-scoped and require the
selected connector's own local app or OAuth setup.
-Surfaces 83 tools: skills, research goals, strategy discovery,
+Surfaces 84 tools: skills, research goals, strategy discovery,
backtest/factor/options/pattern
analysis, deterministic paper-trading matching (paper_trade_step), market data, fundamentals & capital-flow & news & discovery
(get_fund_flow / get_dragon_tiger / get_northbound_flow / get_southbound_flow /
diff --git a/agent/src/providers/stream_guard.py b/agent/src/providers/stream_guard.py
index d913c1de8..816ede45d 100644
--- a/agent/src/providers/stream_guard.py
+++ b/agent/src/providers/stream_guard.py
@@ -143,6 +143,8 @@ def supervised_pulls(
iterator receives a bounded cleanup attempt; a busy generator is closed
by its owning thread when next() returns. Queued late text is not emitted.
"""
+ idle_timeout_s = idle_timeout_s or None
+ total_timeout_s = total_timeout_s or None
if idle_timeout_s is None and total_timeout_s is None and should_cancel is None:
yield from iterator
return
diff --git a/agent/src/session/service.py b/agent/src/session/service.py
index 2d0bbcbac..a83d851a7 100644
--- a/agent/src/session/service.py
+++ b/agent/src/session/service.py
@@ -253,7 +253,7 @@ class SessionService:
deadline = time.monotonic() + max(0.0, timeout)
while any(not task.done() for task in tasks) and time.monotonic() < deadline:
time.sleep(0.01)
- pending = [f"attempt:{session_id}" for session_id, task in self._active_tasks.items()
+ pending = [f"attempt:{session_id}" for session_id, task in list(self._active_tasks.items())
if not task.done()]
for background in list(self._background_handles.values()):
remaining = max(0.0, deadline - time.monotonic())
@@ -612,118 +612,121 @@ class SessionService:
from src.config.loader import load_runtime_agent_config, sanitize_session_overrides
llm = ChatLLM()
- pm = PersistentMemory()
-
- session_id = attempt.session_id
- attempt_id = attempt.attempt_id
- loop = asyncio.get_running_loop()
- tool_trail: list[Dict[str, Any]] = []
- checkpoint = ResponseCheckpoint(self.store, attempt)
+ try:
+ pm = PersistentMemory()
+
+ session_id = attempt.session_id
+ attempt_id = attempt.attempt_id
+ loop = asyncio.get_running_loop()
+ tool_trail: list[Dict[str, Any]] = []
+ checkpoint = ResponseCheckpoint(self.store, attempt)
+
+ safe_overrides = sanitize_session_overrides(session_config) if session_config else session_config
+ agent_config = load_runtime_agent_config(overrides=safe_overrides)
+
+ def event_callback(event_type: str, data: Dict[str, Any]) -> None:
+ """Forward AgentLoop events to the SSE event bus."""
+ try:
+ checkpoint.handle_event(event_type, data)
+ except OSError as exc:
+ # A checkpoint failure must not hide the live response or stop
+ # the agent. The terminal attempt write still gets a chance.
+ logger.warning(
+ "Could not checkpoint response for attempt %s: %s",
+ attempt_id,
+ exc,
+ )
+ if event_type in {"tool_call", "tool_result"}:
+ self._record_tool_trail_event(tool_trail, event_type, data)
+ data["attempt_id"] = attempt_id
+ self.event_bus.emit(session_id, event_type, data)
+
+ def _mcp_collision_warn(msg: str) -> None:
+ """Forward MCP server-name collision warnings to the operator event channel."""
+ self.event_bus.emit(session_id, "mcp.warning", {"attempt_id": attempt_id, "message": msg})
+
+ # One flag per turn, shared by the AgentLoop and the swarm tool. The
+ # loop's own cancel() sets it, so a user stop reaches long-running tools
+ # without a second cancellation channel that can drift out of sync.
+ turn_cancel = threading.Event()
+
+ # Background tasks belong to the session, not to the attempt: a later
+ # attempt must still read what an earlier one started. The attempt id is
+ # kept on each task so cancellation can be attributed later.
+ background_scope = BackgroundScope(
+ owner_id=f"session:{session_id}", attempt_id=attempt_id
+ )
+ background = get_background_manager(Path(self.runs_dir).parent).for_scope(
+ background_scope,
+ on_completion=self._publish_background_completion,
+ )
+ self._background_handles[session_id] = background
- safe_overrides = sanitize_session_overrides(session_config) if session_config else session_config
- agent_config = load_runtime_agent_config(overrides=safe_overrides)
+ registry = await loop.run_in_executor(
+ _AGENT_EXECUTOR,
+ lambda: build_registry(
+ persistent_memory=pm,
+ include_shell_tools=include_shell_tools,
+ agent_config=agent_config,
+ session_id=session_id,
+ event_callback=event_callback,
+ warn_callback=_mcp_collision_warn,
+ cancel_event=turn_cancel,
+ background_manager=background,
+ background_scope=background_scope,
+ ),
+ )
- def event_callback(event_type: str, data: Dict[str, Any]) -> None:
- """Forward AgentLoop events to the SSE event bus."""
- try:
- checkpoint.handle_event(event_type, data)
- except OSError as exc:
- # A checkpoint failure must not hide the live response or stop
- # the agent. The terminal attempt write still gets a chance.
- logger.warning(
- "Could not checkpoint response for attempt %s: %s",
- attempt_id,
- exc,
- )
- if event_type in {"tool_call", "tool_result"}:
- self._record_tool_trail_event(tool_trail, event_type, data)
- data["attempt_id"] = attempt_id
- self.event_bus.emit(session_id, event_type, data)
-
- def _mcp_collision_warn(msg: str) -> None:
- """Forward MCP server-name collision warnings to the operator event channel."""
- self.event_bus.emit(session_id, "mcp.warning", {"attempt_id": attempt_id, "message": msg})
-
- # One flag per turn, shared by the AgentLoop and the swarm tool. The
- # loop's own cancel() sets it, so a user stop reaches long-running tools
- # without a second cancellation channel that can drift out of sync.
- turn_cancel = threading.Event()
-
- # Background tasks belong to the session, not to the attempt: a later
- # attempt must still read what an earlier one started. The attempt id is
- # kept on each task so cancellation can be attributed later.
- background_scope = BackgroundScope(
- owner_id=f"session:{session_id}", attempt_id=attempt_id
- )
- background = get_background_manager(Path(self.runs_dir).parent).for_scope(
- background_scope,
- on_completion=self._publish_background_completion,
- )
- self._background_handles[session_id] = background
+ from src.config.accessor import get_env_config
- registry = await loop.run_in_executor(
- _AGENT_EXECUTOR,
- lambda: build_registry(
- persistent_memory=pm,
- include_shell_tools=include_shell_tools,
- agent_config=agent_config,
- session_id=session_id,
+ agent = AgentLoop(
+ registry=registry,
+ llm=llm,
event_callback=event_callback,
- warn_callback=_mcp_collision_warn,
+ max_iterations=get_env_config().agent_tuning.vibe_trading_agent_max_iterations,
+ persistent_memory=pm,
cancel_event=turn_cancel,
background_manager=background,
- background_scope=background_scope,
- ),
- )
-
- from src.config.accessor import get_env_config
-
- agent = AgentLoop(
- registry=registry,
- llm=llm,
- event_callback=event_callback,
- max_iterations=get_env_config().agent_tuning.vibe_trading_agent_max_iterations,
- persistent_memory=pm,
- cancel_event=turn_cancel,
- background_manager=background,
- )
- self._active_loops[session_id] = agent
+ )
+ self._active_loops[session_id] = agent
- # Build the message history context.
- history = self._convert_messages_to_history(messages) if messages else None
+ # Build the message history context.
+ history = self._convert_messages_to_history(messages) if messages else None
- try:
- result = await loop.run_in_executor(
- _AGENT_EXECUTOR,
- lambda: agent.run(
- user_message=attempt.prompt,
- history=history,
- session_id=session_id,
- ),
- )
- except asyncio.CancelledError:
- agent.cancel()
- raise
- finally:
- self._active_loops.pop(session_id, None)
try:
- checkpoint.flush()
- except OSError as exc:
- logger.warning(
- "Could not flush response checkpoint for attempt %s: %s",
- attempt_id,
- exc,
+ result = await loop.run_in_executor(
+ _AGENT_EXECUTOR,
+ lambda: agent.run(
+ user_message=attempt.prompt,
+ history=history,
+ session_id=session_id,
+ ),
)
+ except asyncio.CancelledError:
+ agent.cancel()
+ raise
+ finally:
+ self._active_loops.pop(session_id, None)
+ try:
+ checkpoint.flush()
+ except OSError as exc:
+ logger.warning(
+ "Could not flush response checkpoint for attempt %s: %s",
+ attempt_id,
+ exc,
+ )
- result["tool_trail"] = tool_trail
+ result["tool_trail"] = tool_trail
- # Load metrics from the run output when available.
- if result.get("run_dir"):
- metrics = self._load_metrics(Path(result["run_dir"]))
- if metrics:
- result["metrics"] = metrics
+ # Load metrics from the run output when available.
+ if result.get("run_dir"):
+ metrics = self._load_metrics(Path(result["run_dir"]))
+ if metrics:
+ result["metrics"] = metrics
- return result
+ return result
+ finally:
+ await llm.aclose()
@staticmethod
def _record_tool_trail_event(
diff --git a/agent/tests/test_background_store_recovery.py b/agent/tests/test_background_store_recovery.py
index 6d55efde4..b68604f2a 100644
--- a/agent/tests/test_background_store_recovery.py
+++ b/agent/tests/test_background_store_recovery.py
@@ -136,7 +136,7 @@ class TestStore:
directory.mkdir()
outside = tmp_path / "outside.json"
outside.write_text(json.dumps(__import__("dataclasses").asdict(make(task_id="deadbeef"))))
- link = directory / f"{'0' * 16}-deadbeef.json"
+ link = store._path_for(make(task_id="deadbeef"))
link.symlink_to(outside)
_records, unreadable = store.load_all()
assert len(unreadable) == 1
diff --git a/agent/tests/test_chat_stream_interruption.py b/agent/tests/test_chat_stream_interruption.py
index 7a4a6e19c..15faaa106 100644
--- a/agent/tests/test_chat_stream_interruption.py
+++ b/agent/tests/test_chat_stream_interruption.py
@@ -251,3 +251,8 @@ def test_partial_stream_no_chunk_error_never_replays():
with pytest.raises(Exception):
client.stream_chat([], idle_timeout_s=1)
assert not provider.invoke_called
+
+
+def test_zero_timeout_keeps_the_existing_disabled_convention():
+ from src.providers.stream_guard import supervised_pulls
+ assert list(supervised_pulls(iter([1, 2]), idle_timeout_s=0, total_timeout_s=0)) == [1, 2]
diff --git a/agent/tests/test_claude_cli_tool_policy.py b/agent/tests/test_claude_cli_tool_policy.py
index 2c9be8440..6ba7376c5 100644
--- a/agent/tests/test_claude_cli_tool_policy.py
+++ b/agent/tests/test_claude_cli_tool_policy.py
@@ -60,7 +60,9 @@ def test_request_for_unoffered_tool_is_fed_back_and_retried(fake_cli) -> None:
assert "trading_place_order: not an available tool" in calls()[1]["stdin"]
# input_tokens is the last prompt's size (what the context meter reads);
# output_tokens is what both attempts generated.
- assert message.usage_metadata["input_tokens"] == 10
+ assert message.usage_metadata["input_tokens"] == 20
+ assert message.usage_metadata["context_input_tokens"] == 10
+ assert message.usage_metadata["calls"] == 2
assert message.usage_metadata["output_tokens"] == 10
diff --git a/agent/tests/test_mcp_new_tools.py b/agent/tests/test_mcp_new_tools.py
index eff22d16c..9b8adf65d 100644
--- a/agent/tests/test_mcp_new_tools.py
+++ b/agent/tests/test_mcp_new_tools.py
@@ -51,6 +51,7 @@ KNOWN_MUTATING_MCP_TOOLS = frozenset(
"start_research_goal",
"trading_select_connection",
"update_research_goal_status",
+ "update_research_goal",
"write_file",
}
)
diff --git a/agent/tests/test_session_service_mcp.py b/agent/tests/test_session_service_mcp.py
index 798b27239..967a92ae3 100644
--- a/agent/tests/test_session_service_mcp.py
+++ b/agent/tests/test_session_service_mcp.py
@@ -2,6 +2,9 @@
from __future__ import annotations
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
import asyncio
import time
from pathlib import Path
@@ -66,7 +69,8 @@ def test_run_with_agent_keeps_event_loop_responsive_during_registry_build(
monkeypatch.setattr("src.session.service.get_shared_index", lambda: _DummyIndex())
monkeypatch.setattr("src.tools.build_registry", _slow_build_registry)
- monkeypatch.setattr("src.providers.chat.ChatLLM", lambda: object())
+ llm = SimpleNamespace(aclose=AsyncMock())
+ monkeypatch.setattr("src.providers.chat.ChatLLM", lambda: llm)
monkeypatch.setattr("src.memory.persistent.PersistentMemory", lambda: object())
monkeypatch.setattr("src.agent.loop.AgentLoop", _agent_factory)
monkeypatch.setattr("src.config.loader.load_runtime_agent_config", lambda overrides=None: object())
@@ -93,7 +97,25 @@ def test_run_with_agent_keeps_event_loop_responsive_during_registry_build(
tick_times, result = asyncio.run(_exercise())
+ llm.aclose.assert_awaited_once()
assert result["status"] == "completed"
assert received_caps == [expected_cap]
assert tick_times, "Expected the event loop ticker to run while registry build was pending"
assert tick_times[0] < 0.18, f"Registry build blocked the event loop for too long: {tick_times[0]:.3f}s"
+
+
+def test_registry_failure_closes_attempt_owned_llm(monkeypatch, tmp_path):
+ llm = SimpleNamespace(aclose=AsyncMock())
+ monkeypatch.setattr("src.providers.chat.ChatLLM", lambda: llm)
+ monkeypatch.setattr("src.session.service.get_shared_index", lambda: _DummyIndex())
+ monkeypatch.setattr("src.memory.persistent.PersistentMemory", lambda: object())
+ monkeypatch.setattr("src.config.loader.load_runtime_agent_config", lambda **kw: object())
+ def fail(**kwargs):
+ raise RuntimeError("registry construction failed")
+ monkeypatch.setattr("src.tools.build_registry", fail)
+ service = SessionService(store=SessionStore(tmp_path / "sessions"),
+ event_bus=EventBus(), runs_dir=tmp_path / "runs")
+ attempt = Attempt(session_id="session-1", prompt="hello")
+ with pytest.raises(RuntimeError, match="registry construction failed"):
+ asyncio.run(service._run_with_agent(attempt))
+ llm.aclose.assert_awaited_once()
diff --git a/agent/tests/test_session_tool_trail.py b/agent/tests/test_session_tool_trail.py
index 85436ca62..59dfc1c4a 100644
--- a/agent/tests/test_session_tool_trail.py
+++ b/agent/tests/test_session_tool_trail.py
@@ -2,6 +2,9 @@
from __future__ import annotations
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
import asyncio
from pathlib import Path
@@ -194,7 +197,8 @@ def test_run_with_agent_consolidates_tool_events_by_call_id(
pass
monkeypatch.setattr("src.tools.build_registry", lambda **kwargs: object())
- monkeypatch.setattr("src.providers.chat.ChatLLM", lambda: object())
+ llm = SimpleNamespace(aclose=AsyncMock())
+ monkeypatch.setattr("src.providers.chat.ChatLLM", lambda: llm)
monkeypatch.setattr("src.memory.persistent.PersistentMemory", lambda: object())
monkeypatch.setattr("src.agent.loop.AgentLoop", _DummyAgentLoop)
monkeypatch.setattr(