Skip to content

"Vibe-Trading: Your Personal Trading Agent"

refactor(api): extract channels routes to src/api/channels_routes.py

shadowinlife88b5945ee213
diff --git a/agent/api_server.py b/agent/api_server.py
index d25de3e12..746a29ca4 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -632,6 +632,17 @@ async def _spa_html_deep_link_fallback(request: Request, call_next):
return await call_next(request)
+# ============================================================================
+# Channel routes - defined in src/api/channels_routes.py
+# Lifecycle functions imported early for startup/shutdown hooks
+# ============================================================================
+
+from src.api.channels_routes import ( # noqa: E402
+ _start_channel_runtime,
+ _stop_channel_runtime,
+)
+
+
@app.on_event("startup")
async def _run_startup_preflight() -> None:
"""Run preflight checks on server startup."""
@@ -1697,39 +1708,6 @@ async def update_data_source_settings(payload: UpdateDataSourceSettingsRequest):
return _build_data_source_settings_response(_read_env_values(ENV_PATH))
[email protected]("/channels/status", dependencies=[Depends(require_auth)])
-async def channels_status():
- """Return IM channel runtime and adapter status."""
- runtime = _get_channel_runtime()
- return runtime.status()
-
-
[email protected]("/channels/start", dependencies=[Depends(require_auth)])
-async def channels_start():
- """Start configured IM channel adapters."""
- runtime = await _start_channel_runtime()
- return {"status": "started", **runtime.status()}
-
-
[email protected]("/channels/stop", dependencies=[Depends(require_auth)])
-async def channels_stop():
- """Stop configured IM channel adapters."""
- runtime = _get_channel_runtime()
- await runtime.stop()
- return {"status": "stopped", **runtime.status()}
-
-
[email protected]("/channels/pairing/command", dependencies=[Depends(require_auth)])
-async def channels_pairing_command(payload: ChannelPairingCommandRequest):
- """Run a pairing command against the shared pairing store."""
- from src.channels.pairing import handle_pairing_command
-
- return {
- "channel": payload.channel,
- "reply": handle_pairing_command(payload.channel, payload.command),
- }
-
-
# ============================================================================
# Session API
# ============================================================================
@@ -1798,20 +1776,6 @@ def _get_channel_runtime():
return _channel_runtime
-async def _start_channel_runtime():
- """Start the IM channel runtime."""
- runtime = _get_channel_runtime()
- await runtime.start(start_manager=True)
- return runtime
-
-
-async def _stop_channel_runtime() -> None:
- """Stop the IM channel runtime if it was initialized."""
- if _channel_runtime is None:
- return
- await _channel_runtime.stop()
-
-
def _get_goal_store():
"""Return the shared finance goal store."""
global _goal_store
@@ -2259,6 +2223,20 @@ from src.api.uploads_routes import ( # noqa: E402
)
+# ============================================================================
+# Channel routes registration - after require_auth is defined
+# ============================================================================
+
+from src.api.channels_routes import register_channels_routes # noqa: E402
+
+register_channels_routes(app)
+
+# Re-export for test monkeypatch compatibility
+from src.api.channels_routes import ( # noqa: F401, E402
+ ChannelPairingCommandRequest,
+)
+
+
# ============================================================================
# Swarm API
# ============================================================================
diff --git a/agent/src/api/channels_routes.py b/agent/src/api/channels_routes.py
new file mode 100644
index 000000000..a79c5e6b6
--- /dev/null
+++ b/agent/src/api/channels_routes.py
@@ -0,0 +1,115 @@
+"""IM channel HTTP routes.
+
+Mounted by ``agent/api_server.py`` via ``register_channels_routes(app, ...)``.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Awaitable, Callable
+
+from fastapi import Depends, FastAPI
+from pydantic import BaseModel
+
+
+# ---------------------------------------------------------------------------
+# Pydantic models (defined locally -- NO shared modules, per maintainer rule)
+# ---------------------------------------------------------------------------
+
+class ChannelPairingCommandRequest(BaseModel):
+ """Pairing command payload for IM channel sender pairing."""
+
+ channel: str
+ command: str
+
+
+# ---------------------------------------------------------------------------
+# Lifecycle helpers (module-level, access host state via sys.modules)
+# ---------------------------------------------------------------------------
+
+
+async def _start_channel_runtime():
+ """Start the IM channel runtime."""
+ import sys as _sys
+
+ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ runtime = host._get_channel_runtime()
+ await runtime.start(start_manager=True)
+ return runtime
+
+
+async def _stop_channel_runtime() -> None:
+ """Stop the IM channel runtime if it was initialized."""
+ import sys as _sys
+
+ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ if host._channel_runtime is None:
+ return
+ await host._channel_runtime.stop()
+
+
+# ---------------------------------------------------------------------------
+# Registration
+# ---------------------------------------------------------------------------
+
+AuthDep = Callable[..., Awaitable[Any] | Any]
+
+
+def register_channels_routes(
+ app: FastAPI,
+ require_auth: AuthDep | None = None,
+) -> None:
+ """Mount the channel routes onto ``app``.
+
+ Resolves ``require_auth`` from the host ``api_server`` module via
+ ``sys.modules`` when not passed explicitly.
+ """
+ # Resolve host dependencies via sys.modules fallback
+ import sys as _sys
+
+ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+
+ if host is None:
+ raise RuntimeError(
+ "register_channels_routes: api_server module not in sys.modules; "
+ "ensure api_server is imported before calling this function"
+ )
+
+ if require_auth is None:
+ require_auth = host.require_auth
+
+ # Late-access closure for monkeypatch compatibility
+ def _get_channel_runtime():
+ """Late-access _get_channel_runtime for test monkeypatch compat."""
+ h = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ return h._get_channel_runtime()
+
+ # --- Routes ---
+
+ @app.get("/channels/status", dependencies=[Depends(require_auth)])
+ async def channels_status():
+ """Return IM channel runtime and adapter status."""
+ runtime = _get_channel_runtime()
+ return runtime.status()
+
+ @app.post("/channels/start", dependencies=[Depends(require_auth)])
+ async def channels_start():
+ """Start configured IM channel adapters."""
+ runtime = await _start_channel_runtime()
+ return {"status": "started", **runtime.status()}
+
+ @app.post("/channels/stop", dependencies=[Depends(require_auth)])
+ async def channels_stop():
+ """Stop configured IM channel adapters."""
+ runtime = _get_channel_runtime()
+ await runtime.stop()
+ return {"status": "stopped", **runtime.status()}
+
+ @app.post("/channels/pairing/command", dependencies=[Depends(require_auth)])
+ async def channels_pairing_command(payload: ChannelPairingCommandRequest):
+ """Run a pairing command against the shared pairing store."""
+ from src.channels.pairing import handle_pairing_command
+
+ return {
+ "channel": payload.channel,
+ "reply": handle_pairing_command(payload.channel, payload.command),
+ }