Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(openbb): OpenBB Workspace agent bridge (#817)

Roger Ye9c0712b493b9
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index d5bb32d7e..c06c9f625 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -28,7 +28,15 @@ jobs:
-r requirements-lock.txt
- name: Install dependencies
- run: pip install -e ".[dev]"
+ # `openbb` is included so agent/tests/test_openbb_bridge actually runs:
+ # those tests importorskip on openbb_ai, so without the extra the whole
+ # OpenBB Workspace bridge would report green while never being exercised.
+ run: pip install -e ".[dev,openbb]"
+
+ - name: Verify optional extras under test are importable
+ # Fails loudly if the openbb extra stops resolving, instead of letting
+ # the bridge suite silently degrade to skips.
+ run: python -c "import openbb_ai, importlib.metadata as m; print('openbb-ai', m.version('openbb-ai'))"
- name: Repository safety gates
run: bash tools/ci_grep_gates.sh
diff --git a/agent/api_server.py b/agent/api_server.py
index e284587d3..ffa5672fd 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -52,6 +52,7 @@ from src.api.security import ( # noqa: F401, E402
_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,
@@ -280,6 +281,11 @@ register_alpha_routes(app)
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 Routes - defined in src/api/scheduled_routes.py
diff --git a/agent/requirements.txt b/agent/requirements.txt
index 17cf2b4c9..8c32d44b6 100644
--- a/agent/requirements.txt
+++ b/agent/requirements.txt
@@ -51,6 +51,7 @@ websockets>=12.0
pydantic>=2.0.0
python-multipart>=0.0.18
sse-starlette>=1.6.0
+# optional: pip install "vibe-trading-ai[openbb]" — OpenBB Workspace custom-agent bridge (openbb-ai protocol models + SSE helpers)
# MCP Server
fastmcp>=2.14.0
diff --git a/agent/src/api/security.py b/agent/src/api/security.py
index ce4c17395..1d0ce7197 100644
--- a/agent/src/api/security.py
+++ b/agent/src/api/security.py
@@ -34,6 +34,20 @@ _DEFAULT_CORS_ORIGINS: tuple[str, ...] = (
"http://127.0.0.1:8000",
)
+# Opt-in additive CORS origins. Unlike ``CORS_ORIGINS`` — which *replaces* the
+# loopback defaults — entries here are appended to whatever the effective origin
+# list already is, so trusting one extra browser origin never silently drops the
+# bundled Web UI. Every entry widens a credentialed CORS surface across the whole
+# API (see ``add_middleware(CORSMiddleware, allow_credentials=True)`` in
+# ``api_server.py``), so it stays empty by default and off the loopback contract.
+# Example — trust OpenBB Workspace as a custom-agent host:
+# VIBE_TRADING_EXTRA_CORS_ORIGINS=https://pro.openbb.co
+# Set it as a real process env var (shell export / docker-compose `environment:` /
+# systemd). Like ``CORS_ORIGINS``, it is resolved when ``api_server`` builds the
+# middleware, which happens before ``run_preflight()`` loads ``agent/.env`` —
+# a value living only in that file would be read too late.
+_EXTRA_CORS_ORIGINS_ENV = "VIBE_TRADING_EXTRA_CORS_ORIGINS"
+
_DEFAULT_LOOPBACK_HOSTS = frozenset({
"localhost",
"127.0.0.1",
@@ -63,6 +77,30 @@ def _parse_cors_origins(raw: Optional[str]) -> List[str]:
return origins
+def _parse_extra_cors_origins(raw: Optional[str]) -> List[str]:
+ """Parse the additive CORS origin allow-list, rejecting a wildcard.
+
+ Args:
+ raw: Comma-separated origin list from ``VIBE_TRADING_EXTRA_CORS_ORIGINS``,
+ or ``None`` / empty when the operator opted out.
+
+ Returns:
+ The explicit extra origins, in declaration order.
+
+ Raises:
+ RuntimeError: If ``*`` is requested; credentialed CORS forbids it.
+ """
+ if raw is None or not raw.strip():
+ return []
+ origins = [origin.strip() for origin in raw.split(",") if origin.strip()]
+ if "*" in origins:
+ raise RuntimeError(
+ f"{_EXTRA_CORS_ORIGINS_ENV}='*' is not allowed while credentials are "
+ "enabled; list explicit origins instead."
+ )
+ return origins
+
+
def _parse_extra_loopback_hosts(raw: Optional[str]) -> set[str]:
"""Return additional trusted Host names for loopback API traffic."""
if raw is None or not raw.strip():
@@ -105,8 +143,17 @@ def _is_loopback_bind_host(host: str) -> bool:
def _get_cors_origins() -> List[str]:
+ """Return the effective CORS allow-list: base origins plus opt-in extras."""
from src.config.accessor import get_env_config
- return _parse_cors_origins(get_env_config().api.cors_origins or None)
+
+ config = get_env_config().api
+ origins = _parse_cors_origins(config.cors_origins or None)
+ for origin in _parse_extra_cors_origins(
+ config.vibe_trading_extra_cors_origins or None
+ ):
+ if origin not in origins:
+ origins.append(origin)
+ return origins
# ============================================================================
diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.py
index ba7facab6..29de6e2e4 100644
--- a/agent/src/config/env_schema.py
+++ b/agent/src/config/env_schema.py
@@ -235,6 +235,12 @@ class APIConfig(_EnvBase):
api_auth_key: str = Field(alias="API_AUTH_KEY", default="")
vibe_trading_api_key: str = Field(alias="VIBE_TRADING_API_KEY", default="")
cors_origins: str = Field(alias="CORS_ORIGINS", default="")
+ # Additive, unlike CORS_ORIGINS: these origins are appended to the loopback
+ # defaults instead of replacing them. Used to admit a hosted console (e.g.
+ # OpenBB Workspace) without discarding the local-dev origins.
+ vibe_trading_extra_cors_origins: str = Field(
+ alias="VIBE_TRADING_EXTRA_CORS_ORIGINS", default="",
+ )
api_allowed_hosts: str = Field(alias="API_ALLOWED_HOSTS", default="")
# Comma-separated Host/Origin allow-list for the network MCP transports
# (--transport sse / http). Empty means loopback-only (127.0.0.1,
diff --git a/agent/src/openbb_bridge/__init__.py b/agent/src/openbb_bridge/__init__.py
new file mode 100644
index 000000000..bb39f1c95
--- /dev/null
+++ b/agent/src/openbb_bridge/__init__.py
@@ -0,0 +1,57 @@
+"""OpenBB Workspace bridge for Vibe-Trading.
+
+This package exposes Vibe-Trading's :class:`AgentLoop` as an OpenBB Workspace
+custom agent. It is a non-invasive adapter layer: it does not modify any of
+Vibe-Trading's core components (AgentLoop, ToolRegistry, SessionService) and can
+be enabled or removed independently of the rest of the API server.
+
+The ``openbb-ai`` SDK ships in the optional ``openbb`` extra::
+
+ pip install "vibe-trading-ai[openbb]"
+
+Nothing here imports that SDK at module level, so ``api_server`` can call
+:func:`try_register_openbb_routes` unconditionally and stay a thin assembler —
+the guarded import and its operator messaging live in this package instead.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+logger = logging.getLogger("openbb_bridge")
+
+__all__ = ["try_register_openbb_routes"]
+
+
+def try_register_openbb_routes(app: Any) -> bool:
+ """Mount the OpenBB Workspace routes when the optional extra is installed.
+
+ Args:
+ app: The FastAPI application to mount onto.
+
+ Returns:
+ ``True`` when ``/agents.json`` and ``/v1/query`` were registered,
+ ``False`` when the bridge stayed disabled. Never raises: a broken
+ optional integration must not take down the core API.
+ """
+ try:
+ from .routes import register_openbb_routes
+ except ModuleNotFoundError as exc:
+ logger.info(
+ 'OpenBB Workspace bridge disabled (%s). Install with: '
+ 'pip install "vibe-trading-ai[openbb]"',
+ exc,
+ )
+ return False
+ except Exception as exc:
+ # SDK present but unusable (version skew, broken install): still fail open.
+ logger.warning("OpenBB Workspace bridge failed to import: %s", exc)
+ return False
+
+ try:
+ register_openbb_routes(app)
+ except Exception as exc:
+ logger.warning("OpenBB Workspace bridge not registered: %s", exc)
+ return False
+ return True
diff --git a/agent/src/openbb_bridge/adapter.py b/agent/src/openbb_bridge/adapter.py
new file mode 100644
index 000000000..cc13e08a1
--- /dev/null
+++ b/agent/src/openbb_bridge/adapter.py
@@ -0,0 +1,308 @@
+"""Core adapter bridging OpenBB Workspace ``/v1/query`` to Vibe-Trading.
+
+The :class:`OpenBBQueryAdapter` is responsible for:
+
+* creating one **ephemeral** Vibe-Trading session per ``/v1/query`` request and
+ replaying the full history the request carried into it;
+* injecting workspace context (explicit context items, widget metadata,
+ dashboard info) into the user's message;
+* triggering the Vibe-Trading ``AgentLoop`` via ``SessionService.send_message``;
+* consuming the session event bus and translating each event into OpenBB SSE
+ objects until the underlying attempt completes or fails.
+
+Why a fresh session per request: ``openbb_ai.models.QueryRequest`` carries no
+conversation / thread identifier (verified against openbb-ai 2.1.0 — its fields
+are ``messages``, ``context``, ``widgets``, ``urls``, ``api_keys``,
+``force_web_search``, ``timezone``, ``workspace_state``, ``workspace_options``,
+``tools``), and OpenBB's contract is explicitly stateless with the whole history
+resupplied every turn. Any server-side identity would therefore have to be
+derived from message *content*, which collides across unrelated conversations
+(two chats opening with "hello" would share one session and leak history into
+each other). Deriving nothing and replaying the supplied history instead keeps
+conversations isolated by construction.
+
+The adapter never mutates Vibe-Trading's core components; it only orchestrates
+their public API.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, AsyncGenerator, List, Optional
+
+from openbb_ai.helpers import message_chunk, reasoning_step
+
+from src.session.models import Message
+
+from .context_injector import WorkspaceContextInjector
+from .event_mapper import SSEEventMapper
+
+logger = logging.getLogger("openbb_bridge")
+
+# Roles as used by OpenBB Workspace messages (``openbb_ai.models.RoleEnum`` is a
+# str-enum, so plain string comparison is exact).
+_ROLE_HUMAN = "human"
+_ROLE_AI = "ai"
+
+# OpenBB role -> Vibe-Trading role for history replay. ``tool`` messages are not
+# replayed as turns; their payload is folded into the context prefix instead.
+_ROLE_TO_VIBE = {_ROLE_HUMAN: "user", _ROLE_AI: "assistant"}
+
+_TERMINAL_EVENTS = {"attempt.completed", "attempt.failed"}
+
+# Session titles surface in the Vibe-Trading UI; keep them short but identifiable.
+_TITLE_MAX_CHARS = 48
+
+
+class OpenBBQueryAdapter:
+ """Adapt an OpenBB ``QueryRequest`` onto the Vibe-Trading agent."""
+
+ def __init__(
+ self,
+ session_service: Any,
+ context_injector: Optional[WorkspaceContextInjector] = None,
+ event_mapper: Optional[SSEEventMapper] = None,
+ ) -> None:
+ """Bind the adapter to a session service.
+
+ Args:
+ session_service: The ``SessionService`` instance driving the agent.
+ context_injector: Optional injector override; a default is built when
+ omitted.
+ event_mapper: Optional event mapper override; a default is built when
+ omitted.
+ """
+ self.session_service = session_service
+ self.context_injector = context_injector or WorkspaceContextInjector()
+ self.event_mapper = event_mapper or SSEEventMapper()
+
+ # ------------------------------------------------------------------
+ # Public entry point
+ # ------------------------------------------------------------------
+ async def handle_query(self, request: Any) -> AsyncGenerator[Any, None]:
+ """Yield ``openbb_ai`` SSE objects for an OpenBB ``QueryRequest``.
+
+ Args:
+ request: The parsed ``openbb_ai.models.QueryRequest``.
+
+ Yields:
+ ``openbb_ai`` SSE objects (message chunks and reasoning steps).
+ """
+ user_message = self._extract_last_human_message(request)
+
+ if not user_message or not self._should_execute(request):
+ yield reasoning_step(
+ message="Waiting for user input.",
+ event_type="INFO",
+ )
+ return
+
+ session_id = self._create_ephemeral_session(user_message)
+ self._replay_history(session_id, request)
+
+ enriched = self.context_injector.inject(request, user_message)
+
+ try:
+ result = await self.session_service.send_message(session_id, enriched)
+ except Exception as exc:
+ logger.error("Failed to dispatch message to Vibe-Trading: %s", exc)
+ yield reasoning_step(
+ message=f"Failed to start the agent: {exc}",
+ event_type="ERROR",
+ )
+ yield message_chunk(text=f"Sorry, the agent could not be started: {exc}")
+ return
+
+ attempt_id = result.get("attempt_id")
+ try:
+ async for sse in self._consume_events(session_id, attempt_id):
+ yield sse
+ finally:
+ # The session stays on disk for auditing, but nothing will ever
+ # reconnect to this one-shot stream — drop its in-memory replay
+ # buffer so a long-lived server does not accumulate one buffer per
+ # Workspace turn.
+ self.session_service.event_bus.clear(session_id)
+
+ # ------------------------------------------------------------------
+ # Event consumption
+ # ------------------------------------------------------------------
+ async def _consume_events(
+ self, session_id: str, attempt_id: Optional[str]
+ ) -> AsyncGenerator[Any, None]:
+ """Translate session-bus events into OpenBB SSE objects until terminal.
+
+ Args:
+ session_id: The ephemeral session being streamed.
+ attempt_id: The attempt this request started, used to ignore
+ stragglers.
+
+ Yields:
+ ``openbb_ai`` SSE objects.
+ """
+ saw_text = False
+ async for event in self.session_service.event_bus.subscribe(session_id):
+ event_type = event.event_type
+ data = event.data or {}
+
+ if event_type == "heartbeat":
+ continue
+
+ ev_attempt = data.get("attempt_id")
+ if attempt_id and ev_attempt and ev_attempt != attempt_id:
+ continue
+
+ if event_type == "text_delta" and data.get("delta"):
+ saw_text = True
+
+ for sse in self.event_mapper.map(event_type, data):
+ yield sse
+
+ if event_type in _TERMINAL_EVENTS and (
+ not attempt_id or ev_attempt == attempt_id
+ ):
+ async for sse in self._finalize(event_type, data, saw_text):
+ yield sse
+ break
+
+ async def _finalize(
+ self, event_type: str, data: dict, saw_text: bool
+ ) -> AsyncGenerator[Any, None]:
+ """Emit any closing summary / error after the attempt terminates.
+
+ Args:
+ event_type: The terminal event type.
+ data: The terminal event payload.
+ saw_text: Whether any answer text was already streamed.
+
+ Yields:
+ ``openbb_ai`` SSE objects.
+ """
+ if event_type == "attempt.failed":
+ error = data.get("error") or "The agent run failed."
+ yield reasoning_step(message=f"Run failed: {error}", event_type="ERROR")
+ if not saw_text:
+ yield message_chunk(text=f"The agent run failed: {error}")
+ return
+
+ # attempt.completed: only send the summary if nothing was streamed.
+ if not saw_text:
+ summary = data.get("summary") or ""
+ if summary:
+ yield message_chunk(text=summary)
+
+ # ------------------------------------------------------------------
+ # Session lifecycle
+ # ------------------------------------------------------------------
+ def _create_ephemeral_session(self, user_message: str) -> str:
+ """Create a one-shot session for a single OpenBB request.
+
+ Args:
+ user_message: The question being asked, used for a readable title.
+
+ Returns:
+ The new session's id.
+ """
+ title = user_message.strip().replace("\n", " ")[:_TITLE_MAX_CHARS]
+ session = self.session_service.create_session(
+ title=f"OpenBB Workspace: {title}" if title else "OpenBB Workspace"
+ )
+ logger.info("OpenBB request -> ephemeral Vibe session %s", session.session_id)
+ return session.session_id
+
+ def _replay_history(self, session_id: str, request: Any) -> None:
+ """Persist the history OpenBB supplied into the ephemeral session.
+
+ Every message preceding the final human message is replayed so the agent
+ sees the whole conversation. The final human message is dispatched
+ separately via ``send_message`` so it is the turn that triggers the loop.
+
+ Writes go straight to the store rather than through
+ ``SessionService.send_message``: a ``user``-role send would start a
+ second attempt, and indexing one-shot replayed turns would pollute
+ cross-session search with duplicates of the Workspace transcript.
+
+ Args:
+ session_id: The ephemeral session to seed.
+ request: The parsed ``QueryRequest``.
+ """
+ messages = self._get_messages(request)
+ if not messages:
+ return
+
+ last_human_idx = self._last_human_index(messages)
+ prior = messages[:last_human_idx] if last_human_idx is not None else messages
+
+ replayed = 0
+ for message in prior:
+ vibe_role = _ROLE_TO_VIBE.get(getattr(message, "role", None))
+ if vibe_role is None:
+ continue # tool messages are folded into the context prefix
+ content = self._message_text(message)
+ if not content:
+ continue
+ try:
+ self.session_service.store.append_message(
+ Message(session_id=session_id, role=vibe_role, content=content)
+ )
+ replayed += 1
+ except Exception as exc:
+ logger.warning("Failed to replay history message: %s", exc)
+
+ if replayed:
+ logger.info(
+ "Replayed %d supplied message(s) into session %s", replayed, session_id
+ )
+
+ # ------------------------------------------------------------------
+ # Request parsing helpers
+ # ------------------------------------------------------------------
+ @staticmethod
+ def _get_messages(request: Any) -> List[Any]:
+ """Return the request's message list, or an empty list."""
+ return getattr(request, "messages", None) or []
+
+ @classmethod
+ def _extract_last_human_message(cls, request: Any) -> str:
+ """Return the text of the most recent human message, or ``""``."""
+ messages = cls._get_messages(request)
+ for message in reversed(messages):
+ if getattr(message, "role", None) == _ROLE_HUMAN:
+ return cls._message_text(message)
+ return ""
+
+ @classmethod
+ def _should_execute(cls, request: Any) -> bool:
+ """Return whether the most recent message is from the human."""
+ messages = cls._get_messages(request)
+ if not messages:
+ return False
+ return getattr(messages[-1], "role", None) == _ROLE_HUMAN
+
+ @classmethod
+ def _last_human_index(cls, messages: List[Any]) -> Optional[int]:
+ """Return the index of the last human message, or ``None``."""
+ for idx in range(len(messages) - 1, -1, -1):
+ if getattr(messages[idx], "role", None) == _ROLE_HUMAN:
+ return idx
+ return None
+
+ @staticmethod
+ def _message_text(message: Any) -> str:
+ """Extract plain text from an OpenBB message of any supported shape.
+
+ Args:
+ message: An ``LlmClientMessage``-like object or mapping.
+
+ Returns:
+ The message's textual content, or ``""`` when there is none.
+ """
+ content = getattr(message, "content", None)
+ if content is None and isinstance(message, dict):
+ content = message.get("content")
+ if isinstance(content, str):
+ return content
+ # Function-call content or other structured payloads: stringify safely.
+ if content is None:
+ return ""
+ return str(content)
diff --git a/agent/src/openbb_bridge/context_injector.py b/agent/src/openbb_bridge/context_injector.py
new file mode 100644
index 000000000..3d86f9330
--- /dev/null
+++ b/agent/src/openbb_bridge/context_injector.py
@@ -0,0 +1,344 @@
+"""Inject OpenBB Workspace context into a user message.
+
+Every ``/v1/query`` request carries the workspace state alongside the question.
+Vibe-Trading's :class:`AgentLoop` has no concept of OpenBB widgets, so this
+module distils the request into a compact natural-language prefix prepended to
+the user's message.
+
+Three sources are folded in, in decreasing order of usefulness:
+
+* ``QueryRequest.context`` — explicit context items the user attached (tables,
+ artifacts, parsed PDFs). ``RawContext.data.items[].content`` is plain text, so
+ this is the one place actual **data** arrives, and it is ingested verbatim
+ under a hard character budget.
+* ``tool``-role messages — payloads returned by a widget-retrieval round trip,
+ read out of ``DataContent.items[].content`` under the same budget.
+* ``QueryRequest.widgets`` / ``workspace_state`` — widget and dashboard
+ *metadata* only. OpenBB does not put widget values in these; fetching them
+ requires the ``get_widget_data`` function-call round trip, which this bridge
+ does not implement. The prefix therefore says so explicitly, so the model uses
+ the widget parameters as intent (e.g. "the user is looking at AAPL") and pulls
+ values with Vibe-Trading's own data tools instead of inventing them.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, List, Optional
+
+logger = logging.getLogger("openbb_bridge")
+
+# Guard rails to keep the injected context small.
+MAX_WIDGETS = 10
+MAX_VALUE_CHARS = 200
+MAX_PARAMS_PER_WIDGET = 8
+
+# Hard ceiling on attached data (context items + tool payloads combined). The
+# agent's own 5-layer compression handles the rest of the prompt, but unbounded
+# spreadsheet or PDF dumps would blow the first LLM call before it ever runs.
+MAX_DATA_CHARS = 8000
+DATA_TRUNCATION_MARKER = "... [truncated: attached data exceeded the 8000-character budget]"
+
+
+def _safe(obj: Any, attr: str, default: Any = None) -> Any:
+ """Return ``obj.attr`` (attribute) or ``obj[attr]`` (mapping) if present.
+
+ Args:
+ obj: Object or mapping to read from.
+ attr: Attribute / key name.
+ default: Value returned when absent or ``None``.
+
+ Returns:
+ The resolved value, or *default*.
+ """
+ if obj is None:
+ return default
+ value = getattr(obj, attr, None)
+ if value is None and isinstance(obj, dict):
+ value = obj.get(attr, default)
+ return default if value is None else value
+
+
+def _truncate(text: str, limit: int = MAX_VALUE_CHARS) -> str:
+ """Return *text* clipped to *limit* characters with an ellipsis marker.
+
+ Args:
+ text: Value to clip; coerced to ``str``.
+ limit: Maximum length of the result.
+
+ Returns:
+ The clipped text.
+ """
+ text = str(text)
+ if len(text) <= limit:
+ return text
+ return text[: limit - 3] + "..."
+
+
+class WorkspaceContextInjector:
+ """Format OpenBB workspace context and inject it into the user message."""
+
+ def inject(self, request: Any, user_message: str) -> str:
+ """Return ``user_message`` prefixed with a formatted context block.
+
+ Args:
+ request: The parsed ``openbb_ai.models.QueryRequest`` instance.
+ user_message: The raw text of the last human message.
+
+ Returns:
+ The enriched message, or *user_message* unchanged when the request
+ carried no usable context.
+ """
+ try:
+ blocks: List[str] = []
+
+ # Attached data first: it is the only block with real values, and it
+ # owns the shared character budget.
+ budget = MAX_DATA_CHARS
+ data_block, budget = self._format_attached_data(request, budget)
+ if data_block:
+ blocks.append(data_block)
+
+ tool_block, budget = self._format_tool_results(request, budget)
+ if tool_block:
+ blocks.append(tool_block)
+
+ widget_block = self._format_widgets(request)
+ if widget_block:
+ blocks.append(widget_block)
+
+ dashboard_block = self._format_dashboard(request)
+ if dashboard_block:
+ blocks.append(dashboard_block)
+
+ if not blocks:
+ return user_message
+
+ context = "\n\n".join(blocks)
+ return (
+ "[OpenBB Workspace context]\n"
+ f"{context}\n"
+ "[End of context]\n\n"
+ f"{user_message}"
+ )
+ except Exception as exc: # never break a query because of context
+ logger.warning("Failed to inject workspace context: %s", exc)
+ return user_message
+
+ # ------------------------------------------------------------------
+ # Attached data (QueryRequest.context)
+ # ------------------------------------------------------------------
+ def _format_attached_data(self, request: Any, budget: int) -> tuple[Optional[str], int]:
+ """Render ``QueryRequest.context`` items within a character budget.
+
+ Args:
+ request: The parsed ``QueryRequest``.
+ budget: Remaining characters available for attached data.
+
+ Returns:
+ A ``(block, remaining_budget)`` tuple; *block* is ``None`` when the
+ request attached no context items.
+ """
+ items = _safe(request, "context", []) or []
+ if not items:
+ return None, budget
+
+ lines = ["The user attached the following data. Treat it as authoritative:"]
+ for item in items:
+ name = _safe(item, "name", "context item")
+ description = _safe(item, "description", "")
+ header = f"- {name}"
+ if description:
+ header += f" ({_truncate(description)})"
+ lines.append(header)
+
+ payload, budget = self._render_data_content(_safe(item, "data"), budget)
+ if payload:
+ lines.append(self._indent(payload))
+ if budget <= 0:
+ self._note_truncation(lines)
+ break
+
+ return "\n".join(lines), budget
+
+ # ------------------------------------------------------------------
+ # Tool / function-call results carried in the message history
+ # ------------------------------------------------------------------
+ def _format_tool_results(self, request: Any, budget: int) -> tuple[Optional[str], int]:
+ """Render ``tool``-role message payloads within a character budget.
+
+ Args:
+ request: The parsed ``QueryRequest``.
+ budget: Remaining characters available for attached data.
+
+ Returns:
+ A ``(block, remaining_budget)`` tuple; *block* is ``None`` when the
+ history carried no tool results.
+ """
+ messages = _safe(request, "messages", []) or []
+ lines: List[str] = []
+ for message in messages:
+ if _safe(message, "role") != "tool":
+ continue
+ function = _safe(message, "function", "tool")
+ entries = _safe(message, "data")
+ if entries is None:
+ continue
+ if not isinstance(entries, (list, tuple)):
+ entries = [entries]
+
+ rendered: List[str] = []
+ for entry in entries:
+ payload, budget = self._render_data_content(entry, budget)
+ if payload:
+ rendered.append(payload)
+ if budget <= 0:
+ break
+ if rendered:
+ lines.append(f"- {function}:")
+ lines.append(self._indent("\n".join(rendered)))
+ if budget <= 0:
+ self._note_truncation(lines)
+ break
+
+ if not lines:
+ return None, budget
+ return "\n".join(["Data already retrieved in this conversation:", *lines]), budget
+
+ @staticmethod
+ def _note_truncation(lines: List[str]) -> None:
+ """Append the truncation marker unless the last line already carries it."""
+ if not lines or not lines[-1].endswith(DATA_TRUNCATION_MARKER):
+ lines.append(f" {DATA_TRUNCATION_MARKER}")
+
+ def _render_data_content(self, data: Any, budget: int) -> tuple[str, int]:
+ """Extract text from a ``DataContent``-like payload within *budget*.
+
+ Handles ``DataContent`` (``.items[].content``), a bare string, and
+ anything else by falling back to ``str()`` so a Workspace-version drift
+ degrades to a truncated repr instead of dropping the payload.
+
+ Args:
+ data: The payload to render.
+ budget: Remaining characters available.
+
+ Returns:
+ A ``(text, remaining_budget)`` tuple; *text* is ``""`` when nothing
+ renderable was found or the budget is exhausted.
+ """
+ if data is None or budget <= 0:
+ return "", budget
+
+ chunks: List[str] = []
+ items = _safe(data, "items")
+ if isinstance(items, (list, tuple)):
+ for item in items:
+ content = _safe(item, "content")
+ if content:
+ chunks.append(str(content))
+ elif isinstance(data, str):
+ chunks.append(data)
+ else:
+ chunks.append(str(data))
+
+ text = "\n".join(chunk for chunk in chunks if chunk).strip()
+ if not text:
+ return "", budget
+ if len(text) > budget:
+ return text[:budget] + DATA_TRUNCATION_MARKER, 0
+ return text, budget - len(text)
+
+ @staticmethod
+ def _indent(text: str) -> str:
+ """Indent every line of *text* by four spaces."""
+ return "\n".join(f" {line}" for line in text.splitlines())
+
+ # ------------------------------------------------------------------
+ # Widgets (metadata only)
+ # ------------------------------------------------------------------
+ def _collect_widgets(self, request: Any) -> List[Any]:
+ """Return every widget across the primary / secondary / extra groups."""
+ collection = _safe(request, "widgets")
+ if collection is None:
+ return []
+ widgets: List[Any] = []
+ for group in ("primary", "secondary", "extra"):
+ widgets.extend(_safe(collection, group, []) or [])
+ return widgets
+
+ def _format_widgets(self, request: Any) -> Optional[str]:
+ """Render widget names and current parameters, flagging the data gap.
+
+ Args:
+ request: The parsed ``QueryRequest``.
+
+ Returns:
+ The formatted block, or ``None`` when no widgets were supplied.
+ """
+ widgets = self._collect_widgets(request)
+ if not widgets:
+ return None
+
+ lines = [
+ "The user has these widgets on their dashboard. Only names and "
+ "parameters are available — their values are NOT attached, so use "
+ "your own data tools to fetch anything you need instead of guessing:"
+ ]
+ for widget in widgets[:MAX_WIDGETS]:
+ name = _safe(widget, "name", "Unnamed widget")
+ description = _safe(widget, "description", "")
+ origin = _safe(widget, "origin", "")
+ header = f"- {name}"
+ if origin:
+ header += f" (source: {origin})"
+ if description:
+ header += f": {_truncate(description)}"
+ lines.append(header)
+
+ params = _safe(widget, "params", []) or []
+ param_summaries: List[str] = []
+ for param in params[:MAX_PARAMS_PER_WIDGET]:
+ p_name = _safe(param, "name")
+ if p_name is None:
+ continue
+ p_value = _safe(param, "current_value")
+ if p_value is not None:
+ param_summaries.append(f"{p_name}={_truncate(p_value, 60)}")
+ else:
+ param_summaries.append(str(p_name))
+ if param_summaries:
+ lines.append(f" params: {', '.join(param_summaries)}")
+
+ remaining = len(widgets) - MAX_WIDGETS
+ if remaining > 0:
+ lines.append(f" ...and {remaining} more widget(s).")
+ return "\n".join(lines)
+
+ # ------------------------------------------------------------------
+ # Dashboard
+ # ------------------------------------------------------------------
+ def _format_dashboard(self, request: Any) -> Optional[str]:
+ """Render the current dashboard's name and active tab.
+
+ ``openbb_ai.models.DashboardInfo`` exposes ``id`` / ``name`` /
+ ``current_tab_id`` / ``tabs`` — there is no description field, so only
+ those are reported.
+
+ Args:
+ request: The parsed ``QueryRequest``.
+
+ Returns:
+ The formatted line, or ``None`` when no dashboard info was supplied.
+ """
+ dashboard = _safe(_safe(request, "workspace_state"), "current_dashboard_info")
+ if dashboard is None:
+ return None
+
+ name = _safe(dashboard, "name")
+ if not name:
+ return None
+ line = f"Current dashboard: {name}"
+ tab_id = _safe(dashboard, "current_tab_id")
+ if tab_id:
+ line += f" (active tab: {_truncate(tab_id, 60)})"
+ return line
diff --git a/agent/src/openbb_bridge/event_mapper.py b/agent/src/openbb_bridge/event_mapper.py
new file mode 100644
index 000000000..1c4b853da
--- /dev/null
+++ b/agent/src/openbb_bridge/event_mapper.py
@@ -0,0 +1,143 @@
+"""Map Vibe-Trading internal events to OpenBB Workspace SSE events.
+
+Vibe-Trading's :class:`AgentLoop` emits fine-grained events through the session
+event bus (``text_delta``, ``tool_call``, ``tool_result``, ...). OpenBB
+Workspace expects a different, smaller vocabulary of Server-Sent Events built
+with the ``openbb_ai`` helper functions (``message_chunk``, ``reasoning_step``,
+...).
+
+:class:`SSEEventMapper` translates one Vibe-Trading event into zero or more
+``openbb_ai`` SSE objects. Returning an empty list means "swallow this event"
+(used for high-frequency progress / bookkeeping events that would only add
+noise to the Workspace transcript).
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Dict, List
+
+from openbb_ai.helpers import message_chunk, reasoning_step
+
+logger = logging.getLogger("openbb_bridge")
+
+# Vibe-Trading event types that carry the visible answer text.
+_TEXT_EVENTS = {"text_delta"}
+
+# Events that are pure progress / telemetry and should not reach Workspace.
+_SILENT_EVENTS = {
+ "reasoning_delta",
+ "thinking_done",
+ "tool_progress",
+ "tool_heartbeat",
+ "llm_usage",
+ "stream_start",
+ "message.received",
+ "attempt.created",
+ "session.created",
+}
+
+
+def _clip(value: Any, limit: int = 500) -> str:
+ """Return *value* stringified and clipped to *limit* characters."""
+ text = str(value)
+ return text if len(text) <= limit else text[: limit - 3] + "..."
+
+
+class SSEEventMapper:
+ """Translate Vibe-Trading events into ``openbb_ai`` SSE objects."""
+
+ def map(self, event_type: str, data: Dict[str, Any]) -> List[Any]:
+ """Translate one Vibe-Trading event into ``openbb_ai`` SSE objects.
+
+ Args:
+ event_type: The session-bus event type.
+ data: The event payload; ``None`` is tolerated.
+
+ Returns:
+ Zero or more ``openbb_ai`` SSE objects. An empty list means the event
+ was deliberately swallowed (progress noise, unknown type, or a
+ mapping error).
+ """
+ data = data or {}
+ try:
+ if event_type in _TEXT_EVENTS:
+ delta = data.get("delta", "")
+ return [message_chunk(text=delta)] if delta else []
+
+ if event_type in _SILENT_EVENTS:
+ return []
+
+ if event_type == "tool_call":
+ tool = data.get("tool", "tool")
+ arguments = data.get("arguments")
+ details = arguments if isinstance(arguments, dict) else None
+ return [
+ reasoning_step(
+ message=f"Calling tool: {tool}",
+ event_type="INFO",
+ details=details,
+ )
+ ]
+
+ if event_type == "tool_result":
+ tool = data.get("tool", "tool")
+ status = data.get("status", "done")
+ elapsed = data.get("elapsed_ms")
+ preview = data.get("preview")
+ suffix = f" ({elapsed}ms)" if elapsed is not None else ""
+ level = "ERROR" if str(status).lower() in {"error", "failed"} else "INFO"
+ return [
+ reasoning_step(
+ message=f"Tool {tool} -> {status}{suffix}",
+ event_type=level,
+ details=_clip(preview) if preview else None,
+ )
+ ]
+
+ if event_type == "compact":
+ summary = data.get("summary")
+ return [
+ reasoning_step(
+ message="Context compacted to stay within limits.",
+ event_type="INFO",
+ details=_clip(summary) if summary else None,
+ )
+ ]
+
+ if event_type == "stream_reset":
+ return [
+ reasoning_step(
+ message="Model stream reset, retrying.",
+ event_type="WARNING",
+ )
+ ]
+
+ if event_type == "goal.updated":
+ goal = data.get("goal") or data.get("summary")
+ return [
+ reasoning_step(
+ message="Goal updated.",
+ event_type="INFO",
+ details=_clip(goal) if goal else None,
+ )
+ ]
+
+ if event_type == "mcp.warning":
+ message = data.get("message", "MCP warning")
+ return [reasoning_step(message=_clip(message), event_type="WARNING")]
+
+ if event_type == "attempt.started":
+ return [
+ reasoning_step(
+ message="Vibe-Trading agent started.",
+ event_type="INFO",
+ )
+ ]
+
+ # Unknown event: swallow it rather than leaking internal noise.
+ logger.debug("Unmapped Vibe-Trading event: %s", event_type)
+ return []
+ except Exception as exc: # never break the stream on a mapping error
+ logger.warning("Failed to map event %s: %s", event_type, exc)
+ return []
diff --git a/agent/src/openbb_bridge/models.py b/agent/src/openbb_bridge/models.py
new file mode 100644
index 000000000..09111f55d
--- /dev/null
+++ b/agent/src/openbb_bridge/models.py
@@ -0,0 +1,33 @@
+"""Pydantic models for the OpenBB Workspace bridge layer.
+
+Only the ``/agents.json`` manifest needs a model: OpenBB Workspace is a
+stateless caller that supplies the full conversation history on every
+``/v1/query`` request, so the bridge keeps no cross-request session bookkeeping.
+"""
+
+from __future__ import annotations
+
+from typing import Dict
+
+from pydantic import BaseModel, Field
+
+
+class AgentManifest(BaseModel):
+ """A single agent entry in the ``/agents.json`` manifest.
+
+ OpenBB Workspace consumes this structure to discover a custom agent, learn
+ which endpoint to call, and which optional features are supported. The field
+ set mirrors the published agents.json spec (name / description / image /
+ endpoints / features).
+ """
+
+ name: str = Field(description="Human readable name of the agent.")
+ description: str = Field(description="Short description shown in the UI.")
+ image: str = Field(default="", description="URL of the agent avatar image.")
+ endpoints: Dict[str, str] = Field(
+ description="Map of endpoint kind -> URL, e.g. {'query': '/v1/query'}."
+ )
+ features: Dict[str, bool] = Field(
+ default_factory=dict,
+ description="Feature flags such as streaming / widget-dashboard-select.",
+ )
diff --git a/agent/src/openbb_bridge/routes.py b/agent/src/openbb_bridge/routes.py
new file mode 100644
index 000000000..ad2c10d03
--- /dev/null
+++ b/agent/src/openbb_bridge/routes.py
@@ -0,0 +1,161 @@
+"""FastAPI routes exposing Vibe-Trading as an OpenBB Workspace custom agent.
+
+Two endpoints make up the OpenBB Workspace custom-agent contract:
+
+* ``GET /agents.json`` -- the agent manifest used for discovery. Static
+ metadata only (name, description, avatar URL, endpoint, feature flags), so it
+ stays unauthenticated like the other discovery surfaces; nothing about a user,
+ a session, or a run is reachable through it.
+* ``POST /v1/query`` -- the streaming query endpoint (SSE). This one reaches
+ the full agent registry, so it carries the same ``require_auth`` dependency as
+ ``POST /sessions/{id}/messages``.
+
+Both are registered onto the shared FastAPI app via
+:func:`register_openbb_routes`, which resolves auth dependencies from the host
+``api_server`` module the same way the other route modules do.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import AsyncGenerator, Dict, Optional
+from urllib.parse import urljoin
+
+from fastapi import Depends, FastAPI, Request
+from fastapi.responses import JSONResponse
+from openbb_ai.helpers import message_chunk, reasoning_step
+from openbb_ai.models import QueryRequest
+from sse_starlette.sse import EventSourceResponse
+
+from src.api.state import _get_session_service
+
+from .adapter import OpenBBQueryAdapter
+from .models import AgentManifest
+
+logger = logging.getLogger("openbb_bridge")
+
+# The agent key must be a stable slug; Workspace uses it as the agent id.
+AGENT_KEY = "vibe_trading_agent"
+
+QUERY_PATH = "/v1/query"
+
+_MANIFEST = AgentManifest(
+ name="Vibe-Trading Finance Agent",
+ description=(
+ "AI-powered quantitative finance research agent with backtesting, "
+ "factor analysis, swarm teams, and a broad multi-market financial tool "
+ "library covering data, strategy generation, and trade analysis."
+ ),
+ image="https://raw.githubusercontent.com/HKUDS/Vibe-Trading/main/frontend/public/favicon.png",
+ endpoints={"query": QUERY_PATH},
+ features={
+ # SSE streaming: implemented by the adapter's event mapper.
+ "streaming": True,
+ # Explicitly selected widgets arrive in ``widgets.primary`` and their
+ # names / parameters are injected into the prompt.
+ "widget-dashboard-select": True,
+ # Dashboard-wide widget discovery would only be useful with the
+ # ``get_widget_data`` retrieval round trip (yield a function call, close
+ # the stream, wait for a follow-up request). That is not implemented, so
+ # the flag stays off rather than advertising data the agent never fetches.
+ "widget-dashboard-search": False,
+ },
+)
+
+# Cache one adapter per session-service instance.
+_adapter_cache: Dict[int, OpenBBQueryAdapter] = {}
+
+
+def _get_adapter() -> Optional[OpenBBQueryAdapter]:
+ """Return an adapter bound to the current session service, or ``None``."""
+ service = _get_session_service()
+ if service is None:
+ return None
+ key = id(service)
+ adapter = _adapter_cache.get(key)
+ if adapter is None:
+ adapter = OpenBBQueryAdapter(session_service=service)
+ _adapter_cache[key] = adapter
+ return adapter
+
+
+def register_openbb_routes(app: FastAPI) -> None:
+ """Mount the OpenBB Workspace agent routes onto ``app``.
+
+ Resolves shared auth dependencies from the host ``api_server`` module via
+ ``sys.modules``, mirroring ``register_sessions_routes``.
+
+ Args:
+ app: The FastAPI application to mount onto.
+
+ Raises:
+ RuntimeError: If ``api_server`` has not been imported yet.
+ """
+ import sys as _sys
+
+ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ if host is None:
+ raise RuntimeError(
+ "register_openbb_routes: api_server module not in sys.modules; "
+ "ensure api_server is imported before calling this function"
+ )
+
+ require_auth = host.require_auth
+
+ @app.get("/agents.json")
+ def agents_manifest(request: Request) -> JSONResponse:
+ """Advertise Vibe-Trading as an OpenBB Workspace agent.
+
+ ``endpoints.query`` is resolved against the URL the manifest was fetched
+ through, because Workspace stores it verbatim and calls it directly.
+ """
+ manifest = _MANIFEST.model_dump()
+ manifest["endpoints"] = {
+ "query": urljoin(str(request.base_url), QUERY_PATH.lstrip("/"))
+ }
+ return JSONResponse(content={AGENT_KEY: manifest})
+
+ @app.post(QUERY_PATH, dependencies=[Depends(require_auth)])
+ async def query(request: QueryRequest) -> EventSourceResponse:
+ """Handle an OpenBB Workspace query and stream results back as SSE."""
+ adapter = _get_adapter()
+
+ if adapter is None:
+
+ async def unavailable() -> AsyncGenerator[dict, None]:
+ yield reasoning_step(
+ message="Vibe-Trading session runtime is not enabled.",
+ event_type="ERROR",
+ ).model_dump()
+ yield message_chunk(
+ text=(
+ "The Vibe-Trading session runtime is not enabled. "
+ "Set ENABLE_SESSION_RUNTIME=true to use the OpenBB "
+ "Workspace agent."
+ )
+ ).model_dump()
+
+ return EventSourceResponse(
+ content=unavailable(), media_type="text/event-stream"
+ )
+
+ async def event_stream() -> AsyncGenerator[dict, None]:
+ try:
+ async for sse in adapter.handle_query(request):
+ yield sse.model_dump()
+ except Exception as exc: # pragma: no cover - defensive
+ logger.exception("Unexpected error while handling OpenBB query")
+ yield reasoning_step(
+ message=f"Internal error: {exc}", event_type="ERROR"
+ ).model_dump()
+ yield message_chunk(
+ text=f"Sorry, an internal error occurred: {exc}"
+ ).model_dump()
+
+ return EventSourceResponse(
+ content=event_stream(), media_type="text/event-stream"
+ )
+
+ logger.info(
+ "OpenBB Workspace agent routes registered (/agents.json, %s)", QUERY_PATH
+ )
diff --git a/agent/tests/test_openbb_bridge/__init__.py b/agent/tests/test_openbb_bridge/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/agent/tests/test_openbb_bridge/test_adapter.py b/agent/tests/test_openbb_bridge/test_adapter.py
new file mode 100644
index 000000000..81de3e284
--- /dev/null
+++ b/agent/tests/test_openbb_bridge/test_adapter.py
@@ -0,0 +1,213 @@
+"""Unit tests for :class:`OpenBBQueryAdapter`."""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+pytest.importorskip("openbb_ai")
+
+from src.openbb_bridge.adapter import OpenBBQueryAdapter
+
+
+class _FakeEvent:
+ def __init__(self, event_type, data):
+ self.event_type = event_type
+ self.data = data
+
+
+class _FakeEventBus:
+ def __init__(self, events):
+ self._events = events
+ self.cleared = []
+
+ async def subscribe(self, session_id, last_event_id=None, *, replay_all=False):
+ for event in self._events:
+ yield event
+
+ def clear(self, session_id):
+ self.cleared.append(session_id)
+
+
+class _FakeStore:
+ def __init__(self):
+ self.messages = []
+
+ def append_message(self, message):
+ self.messages.append(message)
+
+
+class _FakeSessionService:
+ def __init__(self, events):
+ self.event_bus = _FakeEventBus(events)
+ self.store = _FakeStore()
+ self._sessions = {}
+ self.sent = []
+ self._counter = 0
+
+ def create_session(self, title=""):
+ self._counter += 1
+ session_id = f"sess-{self._counter}"
+ session = SimpleNamespace(session_id=session_id, title=title)
+ self._sessions[session_id] = session
+ return session
+
+ def get_session(self, session_id):
+ return self._sessions.get(session_id)
+
+ async def send_message(self, session_id, content, role="user"):
+ self.sent.append((session_id, content, role))
+ return {"message_id": "m1", "attempt_id": "att1"}
+
+
+def _human(text):
+ return SimpleNamespace(role="human", content=text)
+
+
+def _ai(text):
+ return SimpleNamespace(role="ai", content=text)
+
+
+def _request(messages):
+ return SimpleNamespace(
+ messages=messages, widgets=None, workspace_state=None, context=None
+ )
+
+
+async def _collect(agen):
+ return [item async for item in agen]
+
+
+def test_happy_path_streams_text_and_completes():
+ events = [
+ _FakeEvent("attempt.started", {"attempt_id": "att1"}),
+ _FakeEvent("text_delta", {"delta": "Hello ", "attempt_id": "att1"}),
+ _FakeEvent("text_delta", {"delta": "world", "attempt_id": "att1"}),
+ _FakeEvent("attempt.completed", {"attempt_id": "att1", "summary": "done"}),
+ ]
+ service = _FakeSessionService(events)
+ adapter = OpenBBQueryAdapter(session_service=service)
+
+ out = asyncio.run(_collect(adapter.handle_query(_request([_human("hi")]))))
+
+ # The user message was dispatched to a new session.
+ assert len(service.sent) == 1
+ assert service.sent[0][2] == "user"
+ # At least the two text chunks were emitted.
+ assert len(out) >= 2
+
+
+def test_no_execution_when_last_message_not_human():
+ service = _FakeSessionService([])
+ adapter = OpenBBQueryAdapter(session_service=service)
+
+ out = asyncio.run(
+ _collect(adapter.handle_query(_request([_human("hi"), _ai("answer")])))
+ )
+
+ assert service.sent == [] # nothing dispatched
+ assert len(out) == 1 # only the "waiting for input" reasoning step
+
+
+def test_identical_openings_never_share_a_session():
+ """Two conversations that start the same way must stay isolated.
+
+ The original implementation keyed a persistent session on a hash of the
+ first message, so any two chats opening with "hello" merged and leaked each
+ other's history. QueryRequest carries no conversation id, so each request
+ now gets its own ephemeral session instead.
+ """
+ events = [_FakeEvent("attempt.completed", {"attempt_id": "att1", "summary": ""})]
+ service = _FakeSessionService(events)
+ adapter = OpenBBQueryAdapter(session_service=service)
+
+ asyncio.run(_collect(adapter.handle_query(_request([_human("hello")]))))
+ asyncio.run(_collect(adapter.handle_query(_request([_human("hello")]))))
+
+ sessions = [sent[0] for sent in service.sent]
+ assert len(sessions) == 2
+ assert len(set(sessions)) == 2
+ # No cross-request mapping state is retained at all.
+ assert not hasattr(adapter, "_session_map")
+
+
+def test_full_supplied_history_is_replayed_on_every_request():
+ """OpenBB is stateless: later turns must still replay the whole history."""
+ events = [_FakeEvent("attempt.completed", {"attempt_id": "att1", "summary": ""})]
+ service = _FakeSessionService(events)
+ adapter = OpenBBQueryAdapter(session_service=service)
+
+ history = [
+ _human("first question"),
+ _ai("first answer"),
+ _human("second question"),
+ _ai("second answer"),
+ _human("third question"),
+ ]
+ asyncio.run(_collect(adapter.handle_query(_request(history))))
+
+ replayed = [(m.role, m.content) for m in service.store.messages]
+ assert replayed == [
+ ("user", "first question"),
+ ("assistant", "first answer"),
+ ("user", "second question"),
+ ("assistant", "second answer"),
+ ]
+ # Only the final human turn goes through send_message, so exactly one
+ # attempt is started.
+ assert len(service.sent) == 1
+ assert service.sent[0][1].endswith("third question")
+
+
+def test_tool_messages_are_not_replayed_as_turns():
+ events = [_FakeEvent("attempt.completed", {"attempt_id": "att1", "summary": ""})]
+ service = _FakeSessionService(events)
+ adapter = OpenBBQueryAdapter(session_service=service)
+
+ messages = [
+ _human("q1"),
+ SimpleNamespace(role="tool", function="get_price", data=[]),
+ _human("q2"),
+ ]
+ asyncio.run(_collect(adapter.handle_query(_request(messages))))
+
+ assert [m.role for m in service.store.messages] == ["user"]
+
+
+def test_event_buffer_is_released_after_the_stream_ends():
+ events = [_FakeEvent("attempt.completed", {"attempt_id": "att1", "summary": ""})]
+ service = _FakeSessionService(events)
+ adapter = OpenBBQueryAdapter(session_service=service)
+
+ asyncio.run(_collect(adapter.handle_query(_request([_human("hi")]))))
+
+ assert service.event_bus.cleared == [service.sent[0][0]]
+
+
+def test_failed_attempt_emits_error_and_message():
+ events = [
+ _FakeEvent("attempt.started", {"attempt_id": "att1"}),
+ _FakeEvent("attempt.failed", {"attempt_id": "att1", "error": "kaboom"}),
+ ]
+ service = _FakeSessionService(events)
+ adapter = OpenBBQueryAdapter(session_service=service)
+
+ out = asyncio.run(_collect(adapter.handle_query(_request([_human("hi")]))))
+ # An error reasoning step + a fallback message chunk should be present.
+ assert len(out) >= 2
+
+
+def test_events_from_other_attempts_are_ignored():
+ events = [
+ _FakeEvent("text_delta", {"delta": "stale", "attempt_id": "OTHER"}),
+ _FakeEvent("text_delta", {"delta": "fresh", "attempt_id": "att1"}),
+ _FakeEvent("attempt.completed", {"attempt_id": "att1", "summary": ""}),
+ ]
+ service = _FakeSessionService(events)
+ adapter = OpenBBQueryAdapter(session_service=service)
+
+ out = asyncio.run(_collect(adapter.handle_query(_request([_human("hi")]))))
+ # Only the fresh chunk should have been emitted (stale one filtered out).
+ assert len(out) == 1
diff --git a/agent/tests/test_openbb_bridge/test_context_injector.py b/agent/tests/test_openbb_bridge/test_context_injector.py
new file mode 100644
index 000000000..1d6001e5a
--- /dev/null
+++ b/agent/tests/test_openbb_bridge/test_context_injector.py
@@ -0,0 +1,217 @@
+"""Unit tests for :class:`WorkspaceContextInjector`.
+
+The widget / dashboard / context cases are built from the real
+``openbb_ai.models`` classes rather than stand-ins, so a field that the SDK does
+not actually have (``DashboardInfo`` has no ``description``, for example) shows
+up as a failing assertion instead of a silently empty block.
+"""
+
+from __future__ import annotations
+
+import uuid
+from types import SimpleNamespace
+
+import pytest
+
+pytest.importorskip("openbb_ai")
+
+from openbb_ai.models import (
+ DashboardInfo,
+ DataContent,
+ LlmClientFunctionCallResultMessage,
+ LlmClientMessage,
+ PlaintextDataFormat,
+ QueryRequest,
+ RawContext,
+ SingleDataContent,
+ Widget,
+ WidgetCollection,
+ WidgetParam,
+ WorkspaceState,
+)
+
+from src.openbb_bridge.context_injector import (
+ DATA_TRUNCATION_MARKER,
+ MAX_DATA_CHARS,
+ WorkspaceContextInjector,
+)
+
+
+def _data_content(*payloads: str) -> DataContent:
+ return DataContent(
+ items=[
+ SingleDataContent(
+ content=payload,
+ data_format=PlaintextDataFormat(data_type="md", filename="d.md"),
+ )
+ for payload in payloads
+ ],
+ extra_citations=[],
+ )
+
+
+def _raw_context(name: str, *payloads: str, description: str = "") -> RawContext:
+ return RawContext(
+ uuid=uuid.uuid4(),
+ name=name,
+ description=description,
+ data=_data_content(*payloads),
+ )
+
+
+def _widget(name: str, description: str = "", origin: str = "openbb", params=None) -> Widget:
+ return Widget(
+ uuid=uuid.uuid4(),
+ origin=origin,
+ widget_id=name.lower().replace(" ", "_"),
+ name=name,
+ description=description,
+ params=params or [],
+ metadata={},
+ )
+
+
+def _param(name: str, current_value=None) -> WidgetParam:
+ return WidgetParam(
+ name=name, type="ticker", description="", current_value=current_value
+ )
+
+
+def _request(**kwargs) -> QueryRequest:
+ kwargs.setdefault("messages", [LlmClientMessage(role="human", content="q")])
+ kwargs.setdefault("workspace_options", {})
+ return QueryRequest(**kwargs)
+
+
+def test_no_context_returns_message_unchanged():
+ injector = WorkspaceContextInjector()
+ assert injector.inject(_request(), "hello") == "hello"
+
+
+def test_widget_names_and_params_are_injected():
+ injector = WorkspaceContextInjector()
+ request = _request(
+ widgets=WidgetCollection(
+ primary=[
+ _widget("Price Chart", "AAPL price", params=[_param("symbol", "AAPL")])
+ ],
+ secondary=[],
+ extra=[],
+ )
+ )
+ result = injector.inject(request, "What is the trend?")
+
+ assert "Price Chart" in result
+ assert "symbol=AAPL" in result
+ assert result.endswith("What is the trend?")
+ assert "OpenBB Workspace context" in result
+
+
+def test_widget_block_states_that_values_are_not_attached():
+ """Guards against the model inventing widget values it never received."""
+ injector = WorkspaceContextInjector()
+ request = _request(
+ widgets=WidgetCollection(primary=[_widget("Price Chart")], secondary=[], extra=[])
+ )
+ result = injector.inject(request, "q")
+
+ assert "NOT attached" in result
+
+
+def test_dashboard_name_and_tab_are_injected():
+ injector = WorkspaceContextInjector()
+ request = _request(
+ workspace_state=WorkspaceState(
+ current_dashboard_info=DashboardInfo(
+ id="dash-1", name="My Portfolio", current_tab_id="tab-1"
+ )
+ )
+ )
+ result = injector.inject(request, "summarize")
+
+ assert "My Portfolio" in result
+ assert "tab-1" in result
+
+
+def test_widget_list_is_truncated():
+ injector = WorkspaceContextInjector()
+ request = _request(
+ widgets=WidgetCollection(
+ primary=[_widget(f"W{i}") for i in range(25)], secondary=[], extra=[]
+ )
+ )
+ result = injector.inject(request, "q")
+
+ assert "more widget(s)" in result
+
+
+def test_attached_context_data_is_ingested_verbatim():
+ """``QueryRequest.context`` is the only place real values arrive."""
+ injector = WorkspaceContextInjector()
+ request = _request(
+ context=[_raw_context("Prices", "AAPL,190.5\nMSFT,410.2", description="table")]
+ )
+ result = injector.inject(request, "which is cheaper?")
+
+ assert "Prices" in result
+ assert "AAPL,190.5" in result
+ assert "MSFT,410.2" in result
+ assert result.endswith("which is cheaper?")
+
+
+def test_attached_context_data_is_bounded_with_a_marker():
+ injector = WorkspaceContextInjector()
+ payload = "P" * (MAX_DATA_CHARS * 3)
+ request = _request(context=[_raw_context("Huge", payload)])
+ result = injector.inject(request, "q")
+
+ assert DATA_TRUNCATION_MARKER in result
+ assert result.count(DATA_TRUNCATION_MARKER) == 1
+ # The budget bounds the payload; headers and the marker are the only extras.
+ assert result.count("P") == MAX_DATA_CHARS
+ assert len(result) < MAX_DATA_CHARS + 500
+
+
+def test_data_budget_is_shared_across_context_items():
+ injector = WorkspaceContextInjector()
+ request = _request(
+ context=[
+ _raw_context("First", "P" * MAX_DATA_CHARS),
+ _raw_context("Second", "SECOND_ITEM_SENTINEL"),
+ ]
+ )
+ result = injector.inject(request, "q")
+
+ assert result.count("P") == MAX_DATA_CHARS
+ assert "SECOND_ITEM_SENTINEL" not in result
+ assert DATA_TRUNCATION_MARKER in result
+
+
+def test_tool_result_payloads_are_extracted_not_reprd():
+ injector = WorkspaceContextInjector()
+ tool_message = LlmClientFunctionCallResultMessage(
+ function="get_widget_data",
+ input_arguments={},
+ data=[_data_content("AAPL,190.5")],
+ extra_state={},
+ )
+ request = _request(
+ messages=[
+ LlmClientMessage(role="human", content="q1"),
+ tool_message,
+ LlmClientMessage(role="human", content="q2"),
+ ]
+ )
+ result = injector.inject(request, "q2")
+
+ assert "get_widget_data" in result
+ assert "AAPL,190.5" in result
+ # A bare repr of the pydantic list would leak class names into the prompt.
+ assert "DataContent(" not in result
+
+
+def test_injection_never_raises_on_a_malformed_request():
+ injector = WorkspaceContextInjector()
+ broken = SimpleNamespace(context=object(), widgets=object(), workspace_state=object())
+
+ assert injector.inject(broken, "hello") == "hello"
diff --git a/agent/tests/test_openbb_bridge/test_cors_opt_in.py b/agent/tests/test_openbb_bridge/test_cors_opt_in.py
new file mode 100644
index 000000000..82e7e996d
--- /dev/null
+++ b/agent/tests/test_openbb_bridge/test_cors_opt_in.py
@@ -0,0 +1,51 @@
+"""CORS regressions for the additive VIBE_TRADING_EXTRA_CORS_ORIGINS opt-in.
+
+The OpenBB Workspace bridge needs a browser origin the loopback defaults do not
+cover. It must be opt-in: CORS is installed globally with credentials, and in
+keyless dev mode safe GETs are admitted by local peer address, so an origin
+trusted here can read every other endpoint too.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+import api_server
+from src.api import security
+
+
+def test_openbb_origin_is_not_trusted_by_default(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("CORS_ORIGINS", raising=False)
+ monkeypatch.delenv("VIBE_TRADING_EXTRA_CORS_ORIGINS", raising=False)
+
+ assert "https://pro.openbb.co" not in security._get_cors_origins()
+
+
+def test_extra_origins_are_appended_to_the_loopback_defaults(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("CORS_ORIGINS", raising=False)
+ monkeypatch.setenv("VIBE_TRADING_EXTRA_CORS_ORIGINS", "https://pro.openbb.co")
+
+ origins = security._get_cors_origins()
+
+ # Additive, not replacing: the bundled Web UI origins survive.
+ assert set(api_server._DEFAULT_CORS_ORIGINS).issubset(origins)
+ assert origins[-1] == "https://pro.openbb.co"
+
+
+def test_extra_origins_are_deduplicated(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("CORS_ORIGINS", "https://pro.openbb.co")
+ monkeypatch.setenv("VIBE_TRADING_EXTRA_CORS_ORIGINS", "https://pro.openbb.co")
+
+ assert security._get_cors_origins() == ["https://pro.openbb.co"]
+
+
+def test_extra_origins_reject_credentialed_wildcard() -> None:
+ with pytest.raises(RuntimeError, match="VIBE_TRADING_EXTRA_CORS_ORIGINS"):
+ api_server._parse_extra_cors_origins("https://pro.openbb.co,*")
+
+
+def test_extra_origins_parse_blank_input_as_empty() -> None:
+ assert api_server._parse_extra_cors_origins(None) == []
+ assert api_server._parse_extra_cors_origins(" , ") == []
diff --git a/agent/tests/test_openbb_bridge/test_event_mapper.py b/agent/tests/test_openbb_bridge/test_event_mapper.py
new file mode 100644
index 000000000..b6c38e650
--- /dev/null
+++ b/agent/tests/test_openbb_bridge/test_event_mapper.py
@@ -0,0 +1,57 @@
+"""Unit tests for :class:`SSEEventMapper`."""
+
+from __future__ import annotations
+
+import pytest
+
+pytest.importorskip("openbb_ai")
+
+from src.openbb_bridge.event_mapper import SSEEventMapper
+
+
+def test_text_delta_maps_to_single_message_chunk():
+ mapper = SSEEventMapper()
+ out = mapper.map("text_delta", {"delta": "Hello", "attempt_id": "a1"})
+ assert len(out) == 1
+ dumped = out[0].model_dump()
+ assert "event" in dumped and "data" in dumped
+
+
+def test_empty_text_delta_is_swallowed():
+ mapper = SSEEventMapper()
+ assert mapper.map("text_delta", {"delta": ""}) == []
+
+
+def test_silent_events_produce_nothing():
+ mapper = SSEEventMapper()
+ for event_type in ("reasoning_delta", "thinking_done", "tool_progress",
+ "tool_heartbeat", "llm_usage"):
+ assert mapper.map(event_type, {"attempt_id": "a1"}) == []
+
+
+def test_tool_call_maps_to_reasoning_step():
+ mapper = SSEEventMapper()
+ out = mapper.map("tool_call", {"tool": "get_market_data", "arguments": {"symbol": "AAPL"}})
+ assert len(out) == 1
+ assert out[0].model_dump()["event"] # non-empty event name
+
+
+def test_tool_result_error_status_still_maps():
+ mapper = SSEEventMapper()
+ out = mapper.map(
+ "tool_result",
+ {"tool": "x", "status": "error", "elapsed_ms": 12, "preview": "boom"},
+ )
+ assert len(out) == 1
+
+
+def test_unknown_event_is_swallowed():
+ mapper = SSEEventMapper()
+ assert mapper.map("totally_unknown", {"foo": "bar"}) == []
+
+
+def test_mapping_never_raises_on_bad_data():
+ mapper = SSEEventMapper()
+ # Missing keys / None data must not raise.
+ assert mapper.map("tool_call", {}) is not None
+ assert mapper.map("text_delta", None) == []
diff --git a/agent/tests/test_openbb_bridge/test_registration_guard.py b/agent/tests/test_openbb_bridge/test_registration_guard.py
new file mode 100644
index 000000000..cdf0f40dc
--- /dev/null
+++ b/agent/tests/test_openbb_bridge/test_registration_guard.py
@@ -0,0 +1,68 @@
+"""Regressions for the optional-extra registration guard.
+
+``openbb-ai`` lives in the optional ``openbb`` extra, so ``api_server`` must come
+up cleanly on a base install. These tests do not need the SDK — that is the
+point — so they deliberately skip the module-level ``importorskip`` the rest of
+the suite uses.
+"""
+
+from __future__ import annotations
+
+import sys
+
+import pytest
+from fastapi import FastAPI
+
+from src.openbb_bridge import try_register_openbb_routes
+
+
+class _BlockOpenBBAI:
+ """A meta-path finder that makes ``import openbb_ai`` fail as if absent."""
+
+ def find_module(self, fullname, path=None): # pragma: no cover - legacy API
+ return None
+
+ def find_spec(self, fullname, path=None, target=None):
+ if fullname == "openbb_ai" or fullname.startswith("openbb_ai."):
+ raise ModuleNotFoundError(f"No module named {fullname!r}")
+ return None
+
+
+def without_openbb_ai(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Simulate a base install with no ``openbb`` extra."""
+ for name in list(sys.modules):
+ if name.startswith("openbb_ai") or name.startswith("src.openbb_bridge."):
+ monkeypatch.delitem(sys.modules, name)
+ monkeypatch.setattr(sys, "meta_path", [_BlockOpenBBAI(), *sys.meta_path])
+
+
+def test_registration_is_a_no_op_without_the_extra(without_openbb_ai: None):
+ app = FastAPI()
+
+ assert try_register_openbb_routes(app) is False
+ assert not [route for route in app.routes if getattr(route, "path", "") == "/v1/query"]
+
+
+def test_registration_mounts_both_routes_with_the_extra():
+ pytest.importorskip("openbb_ai")
+ app = FastAPI()
+ # register_openbb_routes resolves auth off the host module, so import it.
+ import api_server # noqa: F401
+
+ assert try_register_openbb_routes(app) is True
+ paths = {getattr(route, "path", "") for route in app.routes}
+ assert {"/agents.json", "/v1/query"} <= paths
+
+
+def test_registration_failure_never_escapes(monkeypatch: pytest.MonkeyPatch):
+ """A broken bridge must not take the core API down."""
+ pytest.importorskip("openbb_ai")
+ from src.openbb_bridge import routes as bridge_routes
+
+ def _boom(app):
+ raise RuntimeError("bridge exploded")
+
+ monkeypatch.setattr(bridge_routes, "register_openbb_routes", _boom)
+
+ assert try_register_openbb_routes(FastAPI()) is False
diff --git a/agent/tests/test_openbb_bridge/test_routes.py b/agent/tests/test_openbb_bridge/test_routes.py
new file mode 100644
index 000000000..19efc6699
--- /dev/null
+++ b/agent/tests/test_openbb_bridge/test_routes.py
@@ -0,0 +1,161 @@
+"""Integration tests for the OpenBB Workspace bridge HTTP endpoints."""
+
+from __future__ import annotations
+
+import pytest
+from fastapi.testclient import TestClient
+
+pytest.importorskip("openbb_ai")
+
+import api_server
+from openbb_ai.helpers import message_chunk
+from openbb_ai.models import LlmClientMessage, QueryRequest
+from src.openbb_bridge import routes as bridge_routes
+
+
+def _local_client() -> TestClient:
+ """Return a TestClient that simulates a loopback caller."""
+ return TestClient(api_server.app, client=("127.0.0.1", 50000))
+
+
+def _remote_client() -> TestClient:
+ """Return a TestClient that simulates a non-loopback caller."""
+ return TestClient(api_server.app, client=("203.0.113.10", 50000))
+
+
+def _query_body() -> dict:
+ return QueryRequest(
+ messages=[LlmClientMessage(role="human", content="hi")]
+ ).model_dump(mode="json")
+
+
[email protected](autouse=True)
+def clear_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Start every bridge test from dev-mode (keyless loopback) auth."""
+ monkeypatch.delenv("API_AUTH_KEY", raising=False)
+ monkeypatch.setattr(api_server, "_API_KEY", "")
+
+
+def client() -> TestClient:
+ return _local_client()
+
+
+def fake_adapter(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Replace the real adapter so no agent loop is started."""
+
+ class _FakeAdapter:
+ async def handle_query(self, request):
+ yield message_chunk(text="hello from vibe")
+
+ monkeypatch.setattr(bridge_routes, "_get_adapter", lambda: _FakeAdapter())
+
+
+def test_agents_json_returns_manifest(client: TestClient):
+ response = client.get("/agents.json")
+
+ assert response.status_code == 200
+ body = response.json()
+ assert bridge_routes.AGENT_KEY in body
+ agent = body[bridge_routes.AGENT_KEY]
+ assert agent["name"]
+ assert agent["features"]["streaming"] is True
+
+
+def test_agents_json_advertises_an_absolute_query_url(client: TestClient):
+ """Workspace stores endpoints.query verbatim, so it must be absolute."""
+ response = client.get("/agents.json")
+
+ query_url = response.json()[bridge_routes.AGENT_KEY]["endpoints"]["query"]
+ assert query_url.startswith("http://")
+ assert query_url.endswith(bridge_routes.QUERY_PATH)
+
+
+def test_manifest_only_advertises_implemented_features(client: TestClient):
+ """widget-dashboard-search needs the get_widget_data round trip we lack."""
+ features = client.get("/agents.json").json()[bridge_routes.AGENT_KEY]["features"]
+
+ assert features["widget-dashboard-search"] is False
+
+
+def test_query_streams_from_adapter(client: TestClient, fake_adapter: None):
+ response = client.post("/v1/query", json=_query_body())
+
+ assert response.status_code == 200
+ assert "hello from vibe" in response.text
+
+
+def test_query_reports_when_runtime_unavailable(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.setattr(bridge_routes, "_get_adapter", lambda: None)
+
+ response = client.post("/v1/query", json=_query_body())
+
+ assert response.status_code == 200
+ assert "not enabled" in response.text
+
+
+def test_remote_query_requires_api_key_when_key_unset(fake_adapter: None):
+ """Keyless dev mode must not expose the agent registry to the network."""
+ response = _remote_client().post("/v1/query", json=_query_body())
+
+ assert response.status_code == 403
+ assert "API_AUTH_KEY" in response.json()["detail"]
+
+
+def test_query_rejects_missing_or_wrong_bearer_when_key_configured(
+ monkeypatch: pytest.MonkeyPatch, fake_adapter: None
+):
+ monkeypatch.setenv("API_AUTH_KEY", "secret")
+ monkeypatch.setattr(api_server, "_API_KEY", "secret")
+
+ for client in (_local_client(), _remote_client()):
+ assert client.post("/v1/query", json=_query_body()).status_code == 401
+ wrong = client.post(
+ "/v1/query",
+ json=_query_body(),
+ headers={"Authorization": "Bearer nope"},
+ )
+ assert wrong.status_code == 401
+
+
+def test_query_accepts_valid_bearer_when_key_configured(
+ monkeypatch: pytest.MonkeyPatch, fake_adapter: None
+):
+ monkeypatch.setenv("API_AUTH_KEY", "secret")
+ monkeypatch.setattr(api_server, "_API_KEY", "secret")
+
+ response = _remote_client().post(
+ "/v1/query",
+ json=_query_body(),
+ headers={"Authorization": "Bearer secret"},
+ )
+
+ assert response.status_code == 200
+ assert "hello from vibe" in response.text
+
+
+def test_query_rejects_cross_site_browser_post(fake_adapter: None):
+ """A loopback peer is not enough when the POST comes from another origin."""
+ response = _local_client().post(
+ "/v1/query",
+ json=_query_body(),
+ headers={
+ "Origin": "https://pro.openbb.co",
+ "Sec-Fetch-Site": "cross-site",
+ },
+ )
+
+ assert response.status_code == 403
+
+
+def test_unadvertised_ai_service_routes_are_not_mounted(client: TestClient):
+ """chat-title / dashboard-title / enhance-prompt were removed, not just hidden."""
+ for path in (
+ "/v1/generate/chat/title",
+ "/v1/generate/dashboard/title",
+ "/v1/enhance_prompt",
+ ):
+ assert client.post(path, json={}).status_code == 404, path
diff --git a/pyproject.toml b/pyproject.toml
index 366c33339..e6f533070 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -115,6 +115,12 @@ anthropic = [
# when absent, so the base install stays lean for users who don't use it.
"langchain-anthropic>=1.3.0,<2",
]
+openbb = [
+ # OpenBB Workspace custom-agent bridge (src/openbb_bridge): protocol models
+ # + SSE helpers. api_server.py registers /agents.json and /v1/query only
+ # when this import succeeds, so a base install stays unaffected.
+ "openbb-ai>=2.0.0,<3",
+]
ashare = [
# Free, no-auth A-share source over BaoStock's TCP protocol; bypasses the
# HTTP CDN IP blocks that affect eastmoney-backed sources. The Tencent