Skip to content

"Vibe-Trading: Your Personal Trading Agent"

11.3 KB
Raw Blame
#!/usr/bin/env python3
"""Vibe-Trading API Server - RESTful API for finance research and backtesting.

Thin assembler: creates the FastAPI app, mounts middleware, registers route
modules, and re-exports symbols for test compatibility.  All shared
infrastructure lives in ``src.api.{security,models,helpers,state}``.
"""

from __future__ import annotations

import asyncio
import logging
from contextlib import asynccontextmanager
from pathlib import Path
from typing import AsyncIterator

from fastapi import FastAPI, HTTPException, Request, status  # noqa: F401
from fastapi.responses import FileResponse  # noqa: F401
from fastapi.middleware.cors import CORSMiddleware
from rich.console import Console

from cli._version import __version__ as APP_VERSION
from src.ui_services import build_run_analysis, load_run_context  # noqa: F401

# UTF-8 on Windows
import sys as _sys
for _s in ("stdout", "stderr"):
    _r = getattr(getattr(_sys, _s, None), "reconfigure", None)
    if callable(_r):
        _r(encoding="utf-8", errors="replace")

# ---------------------------------------------------------------------------
# Extracted infrastructure — re-exported for route-module and test access
# ---------------------------------------------------------------------------

from src.api.security import (  # noqa: F401, E402
    _API_KEY,
    _CORS_ORIGINS,
    _DEFAULT_CORS_ORIGINS,
    _DEFAULT_LOOPBACK_HOSTS,
    _EXTRA_LOOPBACK_HOSTS,
    _SAFE_BROWSER_METHODS,
    _apply_security_headers,
    _auth_credential_from_header_or_query,
    _configured_api_key,
    _consume_sse_ticket,
    _default_gateway_ips,
    _env_shell_tools_enabled,
    _host_without_port,
    _is_allowed_loopback_host,
    _is_local_client,
    _is_loopback_bind_host,
    _is_loopback_origin,
    _mint_sse_ticket,
    _origin_matches_request_host,
    _parse_cors_origins,
    _parse_extra_cors_origins,
    _parse_extra_loopback_hosts,
    _redact_query_secrets,
    _reject_cross_site_browser_request,
    _reject_untrusted_loopback_host,
    _require_shutdown_authorization,
    _security,
    _shell_tools_enabled_for_request,
    _trusted_docker_loopback_ip,
    _validate_api_auth,
    install_access_log_redaction_filter,
    require_auth,
    require_event_stream_auth,
    require_local_or_auth,
    require_settings_write_auth,
)

from src.api.models import (  # noqa: F401, E402
    Artifact,
    BacktestMetrics,
    RAGSelection,
    RunInfo,
    RunResponse,
)

from src.api.helpers import (  # noqa: F401, E402
    AGENT_DIR,
    ENV_EXAMPLE_PATH,
    ENV_PATH,
    LEGACY_ENV_PATH,
    RUNS_DIR,
    SESSIONS_DIR,
    UPLOADS_DIR,
    _coerce_float,
    _coerce_int,
    _ensure_agent_env_file,
    _format_env_value,
    _FRONTEND_DIST,
    _is_configured_secret,
    _is_spa_html_route,
    _project_relative_path,
    _read_env_values,
    _SAFE_PATH_PARAM_RE,
    _spa_html_deep_link_fallback,
    _strip_env_value,
    _validate_path_param,
    _write_env_values,
)

from src.api.state import (  # noqa: F401, E402
    _channel_bus,
    _channel_manager,
    _channel_runtime,
    _get_channel_runtime,
    _get_session_service,
    _session_service,
)

console = Console()
logger = logging.getLogger(__name__)

from src.api.channels_routes import (  # noqa: F401, E402
    _start_channel_runtime,
    _stop_channel_runtime,
)
from src.api.scheduled_routes import (  # noqa: F401, E402
    _start_scheduled_research_executor,
    _stop_scheduled_research_executor,
    _stop_scheduled_research_on_shutdown,
)


async def _run_startup_preflight() -> None:
    """Run preflight checks on server startup."""
    from src.preflight import run_preflight

    from src.config import migrate as _migrate

    try:
        _migrate.migrate_legacy_state()  # one-time pre-#904 state move; must never block startup
    except Exception:  # pragma: no cover — best-effort
        logging.getLogger(__name__).warning("Legacy state migration failed", exc_info=True)
    run_preflight(console)
    # Sole scheduler start point (single-writer invariant, scheduler-unification
    # T12): this lifespan call is the only production site that starts the
    # scheduled-research kernel, exactly once per process, and it seeds the
    # protected system jobs into the store before the first tick can run
    # (order + flag-off early-return documented on the callee).
    _start_scheduled_research_executor()
    from src.config.accessor import get_env_config

    if get_env_config().agent_tuning.vibe_trading_channels_auto_start:
        await _start_channel_runtime()


@asynccontextmanager
async def _lifespan(_: FastAPI) -> AsyncIterator[None]:
    """Run API startup and guaranteed reverse-order shutdown."""
    try:
        await _run_startup_preflight()
        yield
    finally:
        await _stop_scheduled_research_on_shutdown()
        # Reap background work this host owns before its runtime disappears.
        # Read the existing service rather than _get_session_service(): a
        # shutdown must not create the very object it is trying to release.
        import src.api.state as _api_state

        service = getattr(_api_state, "_session_service", None)
        if service is not None:
            pending = await asyncio.to_thread(service.shutdown, timeout=5.0)
            if pending:
                logger.warning("Background cleanup incomplete at shutdown: %s", pending)


app = FastAPI(
    title="Vibe-Trading API",
    description="Vibe-Trading API: natural-language finance research, backtesting, and swarm workflows",
    version=APP_VERSION,
    docs_url=None,  # docs/redoc/openapi re-registered behind require_auth
    redoc_url=None,  # in register_system_routes -- see the rationale there
    openapi_url=None,
    lifespan=_lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=_CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.middleware("http")(_reject_untrusted_loopback_host)
app.middleware("http")(_spa_html_deep_link_fallback)
app.middleware("http")(_apply_security_headers)


# Route registration + re-exports

# --- Runs ---
from src.api.runs_routes import register_runs_routes  # noqa: E402
register_runs_routes(app)

from src.api.runs_routes import _build_response_from_run_dir  # noqa: F401, E402
from src.api.attribution_routes import register_attribution_routes  # noqa: E402
register_attribution_routes(app)

# --- Sessions ---
from src.api.sessions_routes import register_sessions_routes  # noqa: E402
register_sessions_routes(app)

from src.api.research_artifact_routes import register_research_artifact_routes  # noqa: E402
register_research_artifact_routes(app)

from src.api.sessions_routes import (  # noqa: F401, E402
    _goal_store,
    _live_action_frame_from_tool_result,
    _mandate_proposal_frame_from_tool_result,
)

# --- System ---
from src.api.system_routes import register_system_routes  # noqa: E402
register_system_routes(app)

from src.api.system_routes import _terminate_current_process  # noqa: F401, E402

# --- Settings ---
from src.api.settings_routes import register_settings_routes  # noqa: E402
register_settings_routes(app)

from src.api.settings_routes import (  # noqa: F401, E402
    _baostock_supported,
    _baostock_installed,
    _load_llm_providers,
)

from src.api.custom_provider_routes import register_custom_provider_routes  # noqa: E402
register_custom_provider_routes(app, require_local_or_auth, require_settings_write_auth)

from src.api.pixel_office_routes import register_pixel_office_routes  # noqa: E402
register_pixel_office_routes(app, require_local_or_auth, require_settings_write_auth)
from src.api.strategy_adaptation_routes import register_strategy_adaptation_routes  # noqa: E402
register_strategy_adaptation_routes(app, require_settings_write_auth)

# --- Uploads ---
from src.api.uploads_routes import register_uploads_routes  # noqa: E402
register_uploads_routes(app)

from src.api.uploads_routes import (  # noqa: F401, E402
    MAX_UPLOAD_SIZE,
    _BLOCKED_UPLOAD_EXT,
    _BLOCKED_UPLOAD_NAMES,
    _SHADOW_ID_RE,
    _UPLOAD_CHUNK_SIZE,
)

# --- Channels ---
from src.api.channels_routes import register_channels_routes  # noqa: E402
register_channels_routes(app)
from src.api.channels_config_routes import register_channels_config_routes  # noqa: E402
register_channels_config_routes(app)

from src.api.channels_routes import (  # noqa: F401, E402
    ChannelPairingCommandRequest,
)

# --- Swarm ---
from src.api.swarm_routes import register_swarm_routes  # noqa: E402
register_swarm_routes(app)

from src.api.swarm_routes import _get_swarm_runtime  # noqa: F401, E402

# --- Live trading ---
from src.api.live_routes import register_live_routes  # noqa: E402
register_live_routes(app)

# --- Read-only portfolio dashboard ---
from src.api.portfolio_routes import register_portfolio_routes  # noqa: E402
register_portfolio_routes(app)
from src.api.paper_trade_routes import register_paper_trade_routes  # noqa: E402
register_paper_trade_routes(app)

from src.api.connection_routes import register_connection_routes  # noqa: E402
register_connection_routes(app)

from src.api.live_routes import (  # noqa: F401, E402
    CommitMandateRequest,
    LiveHaltRequest,
    LiveAuthorizeRequest,
    LiveRunnerControlRequest,
    BrokerAuthState,
    MandateLimits,
    ActiveMandateState,
    RunnerLivenessState,
    LiveBrokerStatus,
    LiveStatusResponse,
    LiveRunnerUnavailable,
    _runner_tasks,
    _runner_factory,
    _emit_live_event,
    _fetch_broker_ceilings,
    _live_account_choices,
    _mandate_account_ref,
    _known_live_brokers,
    _oauth_token_present,
    _active_mandate_state,
    _runner_liveness_state,
    _live_broker_adapter,
    _build_live_runner,
    _drive_runner,
    _stop_live_runners,
    _connector_verify_cache,
    _check_connector_status,
)

# --- Alpha Zoo ---
from src.api.alpha_routes import register_alpha_routes  # noqa: E402
register_alpha_routes(app)

# --- Options analysis ---
from src.api.options_routes import register_options_routes  # noqa: E402
register_options_routes(app)

from src.api.shannon_routes import register_shannon_routes  # noqa: E402
register_shannon_routes(app, require_auth)

# --- Auth helpers (SSE tickets) ---
from src.api.auth_routes import register_auth_routes  # noqa: E402
register_auth_routes(app)

# --- OpenBB Workspace agent bridge (GET /agents.json, POST /v1/query) ---
# No-op unless the optional `openbb` extra is installed; self-reports either way.
from src.openbb_bridge import try_register_openbb_routes  # noqa: E402  # OPENBB-WORKSPACE-INTEGRATION
try_register_openbb_routes(app)

# --- Scheduled research ---
from src.api.scheduled_routes import register_scheduled_routes  # noqa: E402
register_scheduled_routes(app)

from src.api.scheduled_routes import (  # noqa: E402, F401
    CreateRunFromPlaybookRequest,
    CreateScheduledRunRequest,
    PlaybookResponse,
    ScheduledRunResponse,
    _dispatch_scheduled_research_job,
    _get_scheduled_research_executor,
    _get_scheduled_research_store,
    _scheduled_research_scheduler_enabled,
)


# ============================================================================
# Main Entry Point
# ============================================================================

def serve_main(argv: list[str] | None = None) -> int:
    """Start the API server, preserving the module's public CLI entry point."""
    from src.api.server_cli import serve

    return serve(app, argv, repo_root=Path(__file__).resolve().parent.parent)


if __name__ == "__main__":
    raise SystemExit(serve_main())