"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(scheduled-research): wire the outbox to the session and channel runtimes
Haozhe Wu5e5b5574ceb5
diff --git a/agent/src/api/scheduled_routes.py b/agent/src/api/scheduled_routes.pyindex ee9306b9f..55acc7d47 100644--- a/agent/src/api/scheduled_routes.py+++ b/agent/src/api/scheduled_routes.py@@ -57,12 +57,16 @@ def _get_scheduled_research_store():return _scheduled_research_store-async def _dispatch_scheduled_research_job(job) -> None:+async def _dispatch_scheduled_research_job(job) -> Optional[str]:"""Enqueue one scheduled research job through the session runtime.``send_message`` queues the agent attempt and returns once accepted; itdoes not wait for that agent run to reach a terminal status. The executor's``COMPLETED`` state for this dispatch path means "successfully enqueued."++ Returns:+ The session id the attempt was enqueued into, which is what lets the+ delivery outbox find the briefing once the run actually finishes."""host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")svc = host._get_session_service()@@ -79,6 +83,62 @@ async def _dispatch_scheduled_research_job(job) -> None:session.session_id,)await svc.send_message(session.session_id, job.prompt)+ return session.session_id+++def _read_scheduled_briefing(session_id: str) -> Optional[tuple[str, str]]:+ """Return ``(terminal status, briefing text)`` once a run has finished.++ The assistant reply carries the attempt's terminal status in its metadata,+ and it is the same text the user sees in the session — delivering anything+ else would mean the channel and the app disagree about what the run said.++ Args:+ session_id: Session the scheduled run was dispatched into.++ Returns:+ The status and text, or ``None`` while the run is still in flight.+ """+ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")+ svc = host._get_session_service() if host else None+ if not svc:+ return None+ for message in reversed(svc.get_messages(session_id, limit=50)):+ if message.role != "assistant":+ continue+ status = (message.metadata or {}).get("status")+ if isinstance(status, str) and status:+ return status, message.content or ""+ return None+++async def _send_scheduled_briefing(channel: str, target: Optional[str], text: str) -> None:+ """Deliver one briefing through the configured IM channel.++ Args:+ channel: Channel id as configured in the channel runtime.+ target: Address within that channel, or ``None`` for its default.+ text: The briefing to deliver.++ Raises:+ RuntimeError: If the channel runtime is unavailable or has no such+ channel, so the outbox records a retryable failure rather than+ reporting a delivery that never happened.+ """+ from src.channels.bus.events import OutboundMessage++ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")+ manager = getattr(host, "_channel_manager", None) if host else None+ if manager is None:+ raise RuntimeError("channel runtime is not running")+ adapter = manager.get_channel(channel)+ if adapter is None:+ raise RuntimeError(f"channel {channel!r} is not configured")+ if not target:+ raise RuntimeError(f"channel {channel!r} has no delivery target configured")+ await adapter.send(+ OutboundMessage(channel=channel, chat_id=target, content=text)+ )def _get_scheduled_research_executor():@@ -91,6 +151,8 @@ def _get_scheduled_research_executor():_get_scheduled_research_store(),_dispatch_scheduled_research_job,enabled=_scheduled_research_scheduler_enabled(),+ briefing_reader=_read_scheduled_briefing,+ channel_sender=_send_scheduled_briefing,)return _scheduled_research_executor@@ -145,6 +207,18 @@ class CreateScheduledRunRequest(BaseModel):"semantics. Ignored by interval schedules."),)+ delivery_channel: Optional[str] = Field(+ None,+ description=(+ "Channel id a finished briefing is pushed to. Delivery is opt-in "+ "per job: omit this and results stay in the app, which is the "+ "behaviour every existing job keeps."+ ),+ )+ delivery_target: Optional[str] = Field(+ None,+ description="Address within that channel (chat / group / user id).",+ )class PlaybookResponse(BaseModel):@@ -221,6 +295,34 @@ class ScheduledRunResponse(BaseModel):failure_kind: Optional[str] = Noneconfig: Dict[str, Any] = Field(default_factory=dict)timezone: Optional[str] = None+ delivery_channel: Optional[str] = None+ delivery_target: Optional[str] = None+ delivery_status: str = "none"+ delivery_error: Optional[str] = None+ delivery_updated_at: Optional[int] = None+++def _job_to_response(job: ScheduledResearchJob) -> "ScheduledRunResponse":+ """Flatten a job for the wire, delivery record included.++ ``to_dict`` nests the outbox row; the API keeps it flat because the list+ view reads it per row and a nested object would make every consumer reach+ through a key that means nothing to them.++ Args:+ job: The stored job.++ Returns:+ The response model for that job.+ """+ payload = job.to_dict()+ delivery = payload.pop("delivery", {}) or {}+ return ScheduledRunResponse(+ **payload,+ delivery_status=delivery.get("status", "none"),+ delivery_error=delivery.get("error"),+ delivery_updated_at=delivery.get("updated_at"),+ )# ---------------------------------------------------------------------------@@ -330,9 +432,11 @@ def register_scheduled_routes(created_at=now_ms,config=request.config,timezone=request.timezone,+ delivery_channel=request.delivery_channel,+ delivery_target=request.delivery_target,)_get_scheduled_research_store().upsert(job)- return ScheduledRunResponse(**job.to_dict())+ return _job_to_response(job)@app.get("/scheduled-runs",@@ -347,7 +451,7 @@ def register_scheduled_routes(jobs = _get_scheduled_research_store().list_jobs(status=status_filter, limit=limit)- return [ScheduledRunResponse(**j.to_dict()) for j in jobs]+ return [_job_to_response(j) for j in jobs]@app.delete("/scheduled-runs/{job_id}",@@ -478,4 +582,4 @@ def register_scheduled_routes(raise HTTPException(status_code=422, detail=str(exc)) from exc_get_scheduled_research_store().upsert(job)- return ScheduledRunResponse(**job.to_dict())+ return _job_to_response(job)diff --git a/agent/tests/test_scheduled_delivery_wiring.py b/agent/tests/test_scheduled_delivery_wiring.pynew file mode 100644index 000000000..921da7675--- /dev/null+++ b/agent/tests/test_scheduled_delivery_wiring.py@@ -0,0 +1,146 @@+"""The outbox's two collaborators, wired to the real runtime (#942).++The executor is deliberately ignorant of both the session runtime and the+channel runtime; these are the adapters that connect them, and the properties+that matter are that a briefing is read only once its run is terminal, and+that a delivery which cannot happen raises instead of reporting success.+"""++from __future__ import annotations++import asyncio+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi.testclient import TestClient++import api_server+from src.api import scheduled_routes+from src.scheduled_research.models import DeliveryStatus, ScheduledResearchJob+from src.scheduled_research.store import ScheduledResearchJobStore+++def store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> ScheduledResearchJobStore:+ isolated = ScheduledResearchJobStore(path=tmp_path / "scheduled_jobs.json")+ monkeypatch.setattr(scheduled_routes, "_scheduled_research_store", isolated)+ return isolated+++def client(store: ScheduledResearchJobStore, monkeypatch: pytest.MonkeyPatch) -> TestClient:+ monkeypatch.delenv("API_AUTH_KEY", raising=False)+ monkeypatch.setattr(api_server, "_API_KEY", "")+ return TestClient(api_server.app, client=("127.0.0.1", 50000))+++def _message(role: str, content: str, status: str | None = None) -> SimpleNamespace:+ return SimpleNamespace(+ role=role, content=content, metadata={"status": status} if status else {}+ )+++def _with_messages(monkeypatch: pytest.MonkeyPatch, messages: list[SimpleNamespace]) -> None:+ service = SimpleNamespace(get_messages=lambda _sid, limit=50: messages)+ monkeypatch.setattr(+ api_server, "_get_session_service", lambda: service, raising=False+ )+++def test_a_briefing_is_read_only_once_its_run_is_terminal(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """No status on the reply means the run has not finished."""+ _with_messages(monkeypatch, [_message("user", "brief me")])+ assert scheduled_routes._read_scheduled_briefing("s1") is None++ _with_messages(+ monkeypatch,+ [_message("user", "brief me"), _message("assistant", "VERDICT: hold", "completed")],+ )+ assert scheduled_routes._read_scheduled_briefing("s1") == ("completed", "VERDICT: hold")+++def test_the_briefing_is_the_reply_the_user_would_see(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The last terminal reply, so the channel and the app never disagree."""+ _with_messages(+ monkeypatch,+ [+ _message("assistant", "first pass", "completed"),+ _message("user", "again"),+ _message("assistant", "final answer", "completed"),+ ],+ )++ assert scheduled_routes._read_scheduled_briefing("s1") == ("completed", "final answer")+++def test_a_failed_run_reports_its_status_rather_than_nothing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _with_messages(monkeypatch, [_message("assistant", "could not finish", "failed")])++ status, _text = scheduled_routes._read_scheduled_briefing("s1")+ assert status == "failed"+++ "manager, channel, target, expected",+ [+ (None, "telegram", "chat-1", "channel runtime is not running"),+ (SimpleNamespace(get_channel=lambda _n: None), "telegram", "chat-1", "not configured"),+ (+ SimpleNamespace(get_channel=lambda _n: SimpleNamespace()),+ "telegram",+ None,+ "no delivery target",+ ),+ ],+)+def test_a_delivery_that_cannot_happen_raises(+ monkeypatch: pytest.MonkeyPatch, manager, channel, target, expected+) -> None:+ """Silence here would record a briefing as delivered that never was sent."""+ monkeypatch.setattr(api_server, "_channel_manager", manager, raising=False)++ with pytest.raises(RuntimeError, match=expected):+ asyncio.run(scheduled_routes._send_scheduled_briefing(channel, target, "text"))+++def test_create_accepts_a_delivery_channel_and_reports_its_state(+ client: TestClient, store: ScheduledResearchJobStore+) -> None:+ response = client.post(+ "/scheduled-runs",+ json={+ "prompt": "pre-open scan",+ "schedule": "60000",+ "delivery_channel": "telegram",+ "delivery_target": "chat-9",+ },+ )++ assert response.status_code == 201, response.text+ body = response.json()+ assert body["delivery_channel"] == "telegram"+ assert body["delivery_target"] == "chat-9"+ assert body["delivery_status"] == "none"++ stored = store.get(body["id"])+ assert stored.delivery_channel == "telegram"+ assert stored.delivery.status is DeliveryStatus.NONE+++def test_a_job_without_delivery_is_unchanged_on_the_wire(+ client: TestClient, store: ScheduledResearchJobStore+) -> None:+ """Every job that existed before this feature keeps its exact behaviour."""+ response = client.post("/scheduled-runs", json={"prompt": "p", "schedule": "60000"})++ body = response.json()+ assert body["delivery_channel"] is None+ assert body["delivery_status"] == "none"+ assert store.get(body["id"]).delivery_channel is None