Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(connections): keyring as an extra, cached plugin discovery, discovery-only profiles ineligible

Haozhe Wu58af86b47b15
diff --git a/agent/src/api/connection_routes.py b/agent/src/api/connection_routes.py
index f97122e8a..d0aa5c02d 100644
--- a/agent/src/api/connection_routes.py
+++ b/agent/src/api/connection_routes.py
@@ -18,21 +18,36 @@ from src.trading.service import check_connection
class ConnectionRequest(BaseModel):
+ """Payload creating or renaming a read-only connection instance."""
+
id: str = Field(min_length=1, max_length=80)
profile_id: str = Field(min_length=1, max_length=80)
label: str = Field(min_length=1, max_length=80)
class CredentialRequest(BaseModel):
+ """Payload carrying credential values for one connection instance."""
+
values: dict[str, str] = Field(default_factory=dict)
def register_connection_routes(app: FastAPI) -> None:
+ """Register the auth-gated read-only connection endpoints.
+
+ Every route is read-only with respect to the broker: the API exposes
+ connection metadata, credential presence, and a connectivity check, and
+ never reaches an order path.
+
+ Args:
+ app: FastAPI application the routes are attached to.
+ """
+
def store() -> ConnectionStore:
return ConnectionStore()
@app.get("/api/connections", dependencies=[Depends(require_auth)])
def list_connections():
+ """List connection instances, eligible profiles, and the plugin root."""
return {
"status": "ok",
"connections": store().public_list(),
@@ -45,6 +60,7 @@ def register_connection_routes(app: FastAPI) -> None:
dependencies=[Depends(require_settings_write_auth)],
)
def create_connection(payload: ConnectionRequest):
+ """Create one connection instance from an eligible read-only profile."""
try:
instance = store().create(payload.id, payload.profile_id, payload.label)
return {"status": "ok", "connection": instance.to_dict()}
@@ -56,6 +72,7 @@ def register_connection_routes(app: FastAPI) -> None:
dependencies=[Depends(require_settings_write_auth)],
)
def update_connection(connection_id: str, payload: ConnectionRequest):
+ """Rename a connection instance; its id and profile are immutable."""
if payload.id.strip().lower() != connection_id.strip().lower():
raise HTTPException(
status_code=400, detail="connection id cannot be changed"
@@ -83,6 +100,7 @@ def register_connection_routes(app: FastAPI) -> None:
dependencies=[Depends(require_settings_write_auth)],
)
def save_connection_credentials(connection_id: str, payload: CredentialRequest):
+ """Store credentials in the OS vault and return presence flags only."""
try:
instance = store()
connection = instance.get(connection_id)
@@ -107,6 +125,7 @@ def register_connection_routes(app: FastAPI) -> None:
dependencies=[Depends(require_auth)],
)
def check_local_connection(connection_id: str):
+ """Run the connector's read-only status check for one connection."""
try:
connection = store().get(connection_id)
report = check_connection(
@@ -126,6 +145,7 @@ def register_connection_routes(app: FastAPI) -> None:
dependencies=[Depends(require_settings_write_auth)],
)
def delete_connection(connection_id: str):
+ """Delete a connection and its secrets once no portfolio source uses it."""
try:
selected = {
source.connection_id
diff --git a/agent/src/trading/connections.py b/agent/src/trading/connections.py
index 981ae8ee3..b4b027af4 100644
--- a/agent/src/trading/connections.py
+++ b/agent/src/trading/connections.py
@@ -15,9 +15,30 @@ from src.config.paths import get_runtime_root
from src.trading.credentials import CredentialStore
from src.trading.local_plugins import discover_plugins, plugin_by_profile_id
from src.trading.profiles import list_profiles, profile_by_id
+from src.trading.types import TradingProfile
CONFIG_FILENAME = "connections.json"
_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,79}$")
+REQUIRED_READ_CAPABILITIES = frozenset({"account.read", "positions.read"})
+
+
+def is_portfolio_connection_profile(profile: TradingProfile) -> bool:
+ """Report whether a profile can back a read-only portfolio connection.
+
+ A profile qualifies only when it is read-only and declares both
+ ``account.read`` and ``positions.read``. A profile that advertises tool
+ discovery alone cannot serve a holdings read, so it is not eligible even
+ though it is read-only.
+
+ Args:
+ profile: Built-in or operator-installed trading profile.
+
+ Returns:
+ True when the profile can serve account and position reads.
+ """
+ return bool(profile.readonly) and REQUIRED_READ_CAPABILITIES.issubset(
+ profile.capabilities
+ )
def _now() -> str:
@@ -25,6 +46,20 @@ def _now() -> str:
def _credential_reference(profile_id: str, connection_id: str) -> str:
+ """Return the credential locator implied by a profile's transport.
+
+ Args:
+ profile_id: Profile backing the connection instance.
+ connection_id: Identifier of the connection instance.
+
+ Returns:
+ An opaque reference naming where the credentials live. Only local
+ plugins keep secrets in the OS vault; the other transports reuse the
+ connector's own OAuth cache, local session, or config file.
+
+ Raises:
+ ValueError: If the profile id is unknown.
+ """
profile = profile_by_id(profile_id)
if profile.transport == "local_plugin":
return CredentialStore.reference(connection_id)
@@ -37,6 +72,16 @@ def _credential_reference(profile_id: str, connection_id: str) -> str:
@dataclass(frozen=True)
class TradingConnection:
+ """One user-configured connection instance.
+
+ Attributes:
+ id: Lowercase identifier, unique within the registry.
+ profile_id: Trading profile the connection reads through.
+ label: Human-readable name shown in the UI.
+ credential_ref: Opaque locator for the credentials; never a secret.
+ created_at: ISO-8601 UTC creation timestamp.
+ """
+
id: str
profile_id: str
label: str
@@ -44,11 +89,23 @@ class TradingConnection:
created_at: str
def to_dict(self) -> dict[str, str]:
+ """Return the connection as a JSON-serializable mapping.
+
+ Returns:
+ A mapping of the metadata fields; it carries no secret values.
+ """
return asdict(self)
class ConnectionStore:
- """Owner-only metadata store; secret values live in the OS credential vault."""
+ """Owner-only metadata store; secret values live in the OS credential vault.
+
+ Args:
+ path: Registry file path. Defaults to ``connections.json`` under the
+ user runtime root.
+ credential_store: Credential vault used for local plugin secrets.
+ Defaults to the OS-backed store.
+ """
def __init__(
self,
@@ -60,6 +117,16 @@ class ConnectionStore:
self.credentials = credential_store or CredentialStore()
def list(self) -> list[TradingConnection]:
+ """Read every stored connection.
+
+ Returns:
+ The validated connections, or an empty list when no registry file
+ exists yet.
+
+ Raises:
+ ValueError: If the registry file is unreadable, is not valid JSON,
+ or holds a row that fails validation.
+ """
if not self.path.exists():
return []
try:
@@ -74,6 +141,18 @@ class ConnectionStore:
return [self._parse(row) for row in rows]
def get(self, connection_id: str) -> TradingConnection:
+ """Look up one stored connection by id.
+
+ Args:
+ connection_id: Identifier to resolve; case and surrounding
+ whitespace are normalized before matching.
+
+ Returns:
+ The matching connection.
+
+ Raises:
+ ValueError: If no stored connection has that id.
+ """
target = str(connection_id or "").strip().lower()
for connection in self.list():
if connection.id == target:
@@ -81,6 +160,18 @@ class ConnectionStore:
raise ValueError(f"unknown local connection: {target or '?'}")
def save(self, connection: TradingConnection) -> TradingConnection:
+ """Validate and persist a connection, replacing any row with its id.
+
+ Args:
+ connection: Connection to store.
+
+ Returns:
+ The validated connection as it was written.
+
+ Raises:
+ ValueError: If the connection fails validation, for example an
+ invalid id, an ineligible profile, or an unusable label.
+ """
validated = self._parse(connection.to_dict())
rows = [row for row in self.list() if row.id != validated.id]
rows.append(validated)
@@ -90,6 +181,20 @@ class ConnectionStore:
def create(
self, connection_id: str, profile_id: str, label: str
) -> TradingConnection:
+ """Create a new connection instance.
+
+ Args:
+ connection_id: Identifier for the new connection.
+ profile_id: Read-only profile the connection reads through.
+ label: Human-readable name.
+
+ Returns:
+ The stored connection.
+
+ Raises:
+ ValueError: If the id is already used, or the connection fails
+ validation.
+ """
normalized_id = str(connection_id or "").strip().lower()
if any(row.id == normalized_id for row in self.list()):
raise ValueError(f"local connection already exists: {normalized_id}")
@@ -106,6 +211,20 @@ class ConnectionStore:
def ensure(
self, connection_id: str, profile_id: str, label: str
) -> TradingConnection:
+ """Return an existing connection, creating it when absent.
+
+ Args:
+ connection_id: Identifier to resolve or create.
+ profile_id: Read-only profile the connection must use.
+ label: Human-readable name used only when creating.
+
+ Returns:
+ The existing or newly created connection.
+
+ Raises:
+ ValueError: If an existing connection with that id uses a
+ different profile, or creation fails validation.
+ """
try:
existing = self.get(connection_id)
except ValueError:
@@ -117,12 +236,30 @@ class ConnectionStore:
return existing
def delete(self, connection_id: str) -> None:
+ """Delete a connection and any secrets stored for it.
+
+ Args:
+ connection_id: Identifier of the connection to remove.
+
+ Raises:
+ ValueError: If no stored connection has that id.
+ """
connection = self.get(connection_id)
fields = credential_fields(connection.profile_id)
self.credentials.delete(connection.id, fields)
self._write([row for row in self.list() if row.id != connection.id])
def public_list(self) -> list[dict[str, Any]]:
+ """Return UI-facing rows for every stored connection.
+
+ Returns:
+ One mapping per connection, enriched with its profile metadata and
+ a per-field boolean credential status. Secret values are never
+ included.
+
+ Raises:
+ ValueError: If the registry holds a row that fails validation.
+ """
result = []
for connection in self.list():
profile = profile_by_id(connection.profile_id)
@@ -149,6 +286,19 @@ class ConnectionStore:
@staticmethod
def _parse(raw: object) -> TradingConnection:
+ """Validate one registry row.
+
+ Args:
+ raw: Decoded registry row.
+
+ Returns:
+ The validated connection.
+
+ Raises:
+ ValueError: If the row is not an object, carries an invalid id or
+ label, names an unknown or ineligible profile, or claims a
+ credential reference that does not match its transport.
+ """
if not isinstance(raw, dict):
raise ValueError("each local connection must be an object")
connection_id = str(raw.get("id") or "").strip().lower()
@@ -156,10 +306,7 @@ class ConnectionStore:
raise ValueError(f"invalid local connection id: {connection_id or '?'}")
profile_id = str(raw.get("profile_id") or "").strip().lower()
profile = profile_by_id(profile_id)
- if not profile.readonly or not (
- {"account.read", "positions.read"}.issubset(profile.capabilities)
- or "mcp.read.discovery" in profile.capabilities
- ):
+ if not is_portfolio_connection_profile(profile):
raise ValueError(
f"connection profile is not eligible for read-only portfolios: {profile_id}"
)
@@ -192,6 +339,11 @@ class ConnectionStore:
)
def _write(self, connections: list[TradingConnection]) -> None:
+ """Atomically rewrite the registry file with owner-only permissions.
+
+ Args:
+ connections: Full set of connections to persist.
+ """
self.path.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary = tempfile.mkstemp(
prefix=".connections-",
@@ -220,6 +372,19 @@ class ConnectionStore:
def credential_field_catalog(profile_id: str) -> list[dict[str, Any]]:
+ """Return the credential fields a profile declares.
+
+ Args:
+ profile_id: Profile to inspect.
+
+ Returns:
+ Field metadata for local plugin profiles, otherwise an empty list
+ because the other transports own their own credential storage.
+
+ Raises:
+ ValueError: If the profile id is unknown, or names a local plugin that
+ is not installed.
+ """
profile = profile_by_id(profile_id)
if profile.transport == "local_plugin":
return [
@@ -230,18 +395,35 @@ def credential_field_catalog(profile_id: str) -> list[dict[str, Any]]:
def credential_fields(profile_id: str) -> tuple[str, ...]:
+ """Return the credential field names a profile declares.
+
+ Args:
+ profile_id: Profile to inspect.
+
+ Returns:
+ The declared field names, empty when the transport stores its own
+ credentials.
+
+ Raises:
+ ValueError: If the profile id is unknown, or names a local plugin that
+ is not installed.
+ """
return tuple(str(row["name"]) for row in credential_field_catalog(profile_id))
def readonly_profile_catalog() -> list[dict[str, Any]]:
+ """Return the profiles that can back a read-only portfolio connection.
+
+ Returns:
+ One row per eligible profile, sorted by connector, environment and
+ label, followed by one ``invalid_plugin`` diagnostic row per installed
+ plugin directory whose manifest failed validation.
+ """
plugins, errors = discover_plugins()
plugin_ids = {plugin.profile.id for plugin in plugins}
rows = []
for profile in list_profiles():
- if not profile.readonly or not (
- {"account.read", "positions.read"}.issubset(profile.capabilities)
- or "mcp.read.discovery" in profile.capabilities
- ):
+ if not is_portfolio_connection_profile(profile):
continue
rows.append(
{
diff --git a/agent/src/trading/credentials.py b/agent/src/trading/credentials.py
index a95bdd2f1..4c4927647 100644
--- a/agent/src/trading/credentials.py
+++ b/agent/src/trading/credentials.py
@@ -6,30 +6,67 @@ from collections.abc import Iterable, Mapping
from typing import Protocol
SERVICE_NAME = "Vibe-Trading"
+_INSTALL_HINT = (
+ "OS credential vault support is not installed. Install the optional extra: "
+ 'pip install "vibe-trading-ai[keyring]" (or pip install keyring).'
+)
class CredentialBackend(Protocol):
+ """Minimal subset of the ``keyring`` API used by :class:`CredentialStore`."""
+
def get_password(self, service_name: str, username: str) -> str | None: ...
def set_password(self, service_name: str, username: str, password: str) -> None: ...
def delete_password(self, service_name: str, username: str) -> None: ...
class CredentialStore:
- """Store secrets in Keychain/Credential Manager/Secret Service via keyring."""
+ """Store secrets in Keychain/Credential Manager/Secret Service via keyring.
+
+ The ``keyring`` package is an optional extra: it is imported the first time
+ a secret is actually read or written, so importing this module — and every
+ module that only needs connection metadata — stays dependency-free.
+
+ Args:
+ backend: Optional backend implementing the ``keyring`` password API.
+ Tests pass an in-memory double; production leaves it unset so the
+ real OS vault is imported lazily.
+ """
def __init__(self, backend: CredentialBackend | None = None) -> None:
self._backend = backend
@property
def backend(self) -> CredentialBackend:
+ """Return the credential backend, importing ``keyring`` on first use.
+
+ Returns:
+ The injected backend, otherwise the imported ``keyring`` module.
+
+ Raises:
+ RuntimeError: If ``keyring`` is not installed. The message names
+ the optional extra that provides it.
+ """
if self._backend is None:
- import keyring
+ try:
+ import keyring
+ except ModuleNotFoundError as exc: # optional extra
+ raise RuntimeError(_INSTALL_HINT) from exc
self._backend = keyring
return self._backend
@staticmethod
def reference(connection_id: str) -> str:
+ """Return the opaque vault reference stored beside a connection.
+
+ Args:
+ connection_id: Identifier of the local connection instance.
+
+ Returns:
+ A ``keyring://`` reference that names where the secret lives; it
+ never contains the secret itself.
+ """
return f"keyring://vibe-trading/{connection_id}"
@staticmethod
@@ -37,7 +74,17 @@ class CredentialStore:
return f"connection:{connection_id}:{field}"
def save(self, connection_id: str, values: Mapping[str, str]) -> None:
- """Persist non-empty values; blank fields leave an existing secret unchanged."""
+ """Persist non-empty values; blank fields leave an existing secret unchanged.
+
+ Args:
+ connection_id: Identifier of the local connection instance.
+ values: Mapping of credential field name to secret value. Empty or
+ whitespace-only values are skipped so a partial form submission
+ cannot erase a stored secret.
+
+ Raises:
+ RuntimeError: If the ``keyring`` extra is not installed.
+ """
for field, raw_value in values.items():
value = str(raw_value or "").strip()
if value:
@@ -48,6 +95,19 @@ class CredentialStore:
)
def load(self, connection_id: str, fields: Iterable[str]) -> dict[str, str]:
+ """Read the stored secrets for a connection.
+
+ Args:
+ connection_id: Identifier of the local connection instance.
+ fields: Credential field names declared by the connector manifest.
+
+ Returns:
+ Mapping of field name to secret value, omitting fields that have
+ no stored value.
+
+ Raises:
+ RuntimeError: If the ``keyring`` extra is not installed.
+ """
values: dict[str, str] = {}
for field in fields:
value = self.backend.get_password(
@@ -59,11 +119,26 @@ class CredentialStore:
return values
def status(self, connection_id: str, fields: Iterable[str]) -> dict[str, bool]:
+ """Report which credential fields have a stored value.
+
+ Args:
+ connection_id: Identifier of the local connection instance.
+ fields: Credential field names declared by the connector manifest.
+
+ Returns:
+ Mapping of field name to a boolean presence flag. A field whose
+ backend lookup fails is reported as missing rather than raising, so
+ a locked vault cannot break the connection listing.
+
+ Raises:
+ RuntimeError: If the ``keyring`` extra is not installed.
+ """
+ backend = self.backend
result = {}
for field in fields:
try:
result[field] = bool(
- self.backend.get_password(
+ backend.get_password(
SERVICE_NAME,
self._username(connection_id, field),
)
@@ -73,9 +148,21 @@ class CredentialStore:
return result
def delete(self, connection_id: str, fields: Iterable[str]) -> None:
+ """Remove the stored secrets for a connection.
+
+ Args:
+ connection_id: Identifier of the local connection instance.
+ fields: Credential field names declared by the connector manifest.
+
+ Raises:
+ RuntimeError: If the ``keyring`` extra is not installed.
+ Exception: Whatever the backend raises for a failure other than a
+ missing entry, which is treated as already deleted.
+ """
+ backend = self.backend
for field in fields:
try:
- self.backend.delete_password(
+ backend.delete_password(
SERVICE_NAME,
self._username(connection_id, field),
)
diff --git a/agent/src/trading/local_plugins.py b/agent/src/trading/local_plugins.py
index efdb2a509..98a3529d7 100644
--- a/agent/src/trading/local_plugins.py
+++ b/agent/src/trading/local_plugins.py
@@ -19,15 +19,36 @@ _FIELD_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$")
_REQUIRED_CAPABILITIES = {"account.read", "positions.read"}
_ALLOWED_CAPABILITIES = frozenset(READ_CAPABILITIES)
+_CACHE_LIMIT = 16
+_ManifestSignature = tuple[tuple[str, int, int], ...]
+_CACHE: dict[
+ str,
+ tuple[_ManifestSignature, list["LocalConnectorPlugin"], list[dict[str, str]]],
+] = {}
+
@dataclass(frozen=True)
class CredentialField:
+ """One credential input a local connector manifest declares.
+
+ Attributes:
+ name: Snake-case field name used as the credential vault key.
+ label: Human-readable label rendered by the connection UI.
+ secret: Whether the value must be masked and stored in the OS vault.
+ required: Whether the connector refuses to run without the value.
+ """
+
name: str
label: str
secret: bool = True
required: bool = True
def to_dict(self) -> dict[str, Any]:
+ """Return the field as a JSON-serializable mapping.
+
+ Returns:
+ A mapping of the field metadata. It never carries a secret value.
+ """
return {
"name": self.name,
"label": self.label,
@@ -38,6 +59,16 @@ class CredentialField:
@dataclass(frozen=True)
class LocalConnectorPlugin:
+ """A validated, operator-installed read-only connector.
+
+ Attributes:
+ profile: Trading profile the manifest declares, always read-only.
+ directory: Directory holding the manifest and the adapter module.
+ entrypoint: Adapter file name, resolved inside ``directory``.
+ auth_type: Free-form authentication label from the manifest.
+ credential_fields: Credential inputs the adapter expects.
+ """
+
profile: TradingProfile
directory: Path
entrypoint: str
@@ -46,9 +77,16 @@ class LocalConnectorPlugin:
@property
def module_path(self) -> Path:
+ """Return the adapter module path inside the plugin directory."""
return self.directory / self.entrypoint
def public_dict(self) -> dict[str, Any]:
+ """Return UI-facing plugin metadata.
+
+ Returns:
+ A mapping describing the plugin. Credential values are never
+ included — only the declared field metadata.
+ """
return {
"profile_id": self.profile.id,
"directory": str(self.directory),
@@ -58,11 +96,30 @@ class LocalConnectorPlugin:
def plugin_root() -> Path:
+ """Return the directory holding operator-installed connector plugins.
+
+ Returns:
+ ``<runtime root>/connectors``, the only directory adapters are loaded
+ from. It lives under the user's runtime root, never inside the repo.
+ """
return get_runtime_root() / "connectors"
def parse_manifest(path: Path) -> LocalConnectorPlugin:
- """Validate a local manifest as a strictly read-only connector contract."""
+ """Validate a local manifest as a strictly read-only connector contract.
+
+ Args:
+ path: Path to a ``connector.json`` manifest file.
+
+ Returns:
+ The validated plugin, with a read-only ``local_plugin`` profile.
+
+ Raises:
+ ValueError: If the manifest is unreadable, malformed, declares any
+ capability outside the read set, omits ``account.read`` or
+ ``positions.read``, is not marked read-only, or names an
+ entrypoint that escapes the manifest directory or does not exist.
+ """
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
@@ -145,24 +202,89 @@ def parse_manifest(path: Path) -> LocalConnectorPlugin:
)
+def _manifest_signature(manifests: list[Path]) -> _ManifestSignature:
+ """Fingerprint the manifest set so unchanged directories skip re-parsing.
+
+ Args:
+ manifests: Manifest paths found under one plugin root.
+
+ Returns:
+ A tuple of ``(path, mtime_ns, size)`` triples. A manifest that
+ disappears between the glob and the stat is fingerprinted as missing so
+ the next call re-parses.
+ """
+ signature: list[tuple[str, int, int]] = []
+ for manifest in manifests:
+ try:
+ stat = manifest.stat()
+ except OSError:
+ signature.append((str(manifest), -1, -1))
+ continue
+ signature.append((str(manifest), stat.st_mtime_ns, stat.st_size))
+ return tuple(signature)
+
+
+def clear_plugin_cache() -> None:
+ """Drop every cached discovery result.
+
+ Discovery is normally invalidated by manifest timestamps; call this when a
+ caller replaces manifest content without changing its size or timestamp.
+ """
+ _CACHE.clear()
+
+
def discover_plugins(
root: Path | None = None,
) -> tuple[list[LocalConnectorPlugin], list[dict[str, str]]]:
- """Discover valid plugins and return field-safe diagnostics for invalid ones."""
+ """Discover valid plugins and return field-safe diagnostics for invalid ones.
+
+ Results are cached per plugin root and reused while every manifest keeps
+ its timestamp and size, because profile lookups re-run discovery on every
+ call. Scaffolding, installing, or editing a connector changes the manifest
+ set or its timestamps and therefore forces a re-parse.
+
+ Args:
+ root: Plugin directory to scan. Defaults to :func:`plugin_root`.
+
+ Returns:
+ A tuple of the valid plugins and one diagnostic mapping per invalid
+ directory, each carrying only the directory name and the error text.
+ """
directory = root or plugin_root()
+ key = str(directory)
if not directory.exists():
+ _CACHE.pop(key, None)
return [], []
+ manifests = sorted(directory.glob(f"*/{MANIFEST_FILENAME}"))
+ signature = _manifest_signature(manifests)
+ cached = _CACHE.get(key)
+ if cached is not None and cached[0] == signature:
+ return list(cached[1]), [dict(error) for error in cached[2]]
plugins: list[LocalConnectorPlugin] = []
errors: list[dict[str, str]] = []
- for manifest in sorted(directory.glob(f"*/{MANIFEST_FILENAME}")):
+ for manifest in manifests:
try:
plugins.append(parse_manifest(manifest))
except ValueError as exc:
errors.append({"directory": manifest.parent.name, "error": str(exc)[:300]})
- return plugins, errors
+ if key not in _CACHE and len(_CACHE) >= _CACHE_LIMIT:
+ _CACHE.pop(next(iter(_CACHE)))
+ _CACHE[key] = (signature, plugins, errors)
+ return list(plugins), [dict(error) for error in errors]
def plugin_by_profile_id(profile_id: str) -> LocalConnectorPlugin:
+ """Return the installed plugin that owns a profile id.
+
+ Args:
+ profile_id: Profile id declared by an installed connector manifest.
+
+ Returns:
+ The matching plugin from the operator's plugin root.
+
+ Raises:
+ ValueError: If no installed plugin declares that profile id.
+ """
plugins, _ = discover_plugins()
for plugin in plugins:
if plugin.profile.id == profile_id:
@@ -171,7 +293,19 @@ def plugin_by_profile_id(profile_id: str) -> LocalConnectorPlugin:
def load_adapter(plugin: LocalConnectorPlugin) -> ModuleType:
- """Load a plugin selected by the local operator from its private directory."""
+ """Load a plugin selected by the local operator from its private directory.
+
+ Args:
+ plugin: A plugin returned by discovery, so its module path is always a
+ file inside the operator's plugin root.
+
+ Returns:
+ The imported adapter module.
+
+ Raises:
+ RuntimeError: If the module cannot be loaded, or does not implement
+ ``check_status``, ``get_account_snapshot`` and ``get_positions``.
+ """
module_name = (
f"vibe_local_connector_{plugin.profile.id.replace('-', '_').replace('.', '_')}"
)
diff --git a/agent/src/trading/plugin_scaffold.py b/agent/src/trading/plugin_scaffold.py
index 4a8cd5029..23fab9e80 100644
--- a/agent/src/trading/plugin_scaffold.py
+++ b/agent/src/trading/plugin_scaffold.py
@@ -7,7 +7,12 @@ import re
import shutil
from pathlib import Path
-from src.trading.local_plugins import MANIFEST_FILENAME, parse_manifest, plugin_root
+from src.trading.local_plugins import (
+ MANIFEST_FILENAME,
+ LocalConnectorPlugin,
+ parse_manifest,
+ plugin_root,
+)
_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
@@ -42,7 +47,20 @@ def get_positions(*, credentials: Mapping[str, str], config: Mapping[str, Any])
def scaffold_connector(connector_id: str, destination: Path) -> Path:
- """Create a safe local connector starter for Codex or a developer to fill in."""
+ """Create a read-only local connector starter for a developer to fill in.
+
+ Args:
+ connector_id: Lowercase connector id used for the directory name, the
+ generated profile id, and the manifest connector field.
+ destination: Parent directory the template directory is created in.
+
+ Returns:
+ The created template directory.
+
+ Raises:
+ ValueError: If the connector id is not lowercase letters, numbers and
+ dashes, or the destination directory already exists.
+ """
clean = str(connector_id or "").strip().lower()
if not _ID_RE.fullmatch(clean):
raise ValueError("connector id must use lowercase letters, numbers, and dashes")
@@ -87,20 +105,43 @@ def scaffold_connector(connector_id: str, destination: Path) -> Path:
(target / "adapter.py").write_text(_ADAPTER_TEMPLATE, encoding="utf-8")
(target / "README.md").write_text(
f"# {clean} local connector\n\n"
- "This directory is local-only. Implement the official read endpoints in `adapter.py`, "
+ "This directory is local-only. Implement `adapter.py` from the broker's official "
+ "read-only API docs, "
"then run `vibe-trading connector validate .` and `vibe-trading connector install .`.\n",
encoding="utf-8",
)
return target
-def validate_connector(directory: Path):
- """Validate a local connector directory without importing its Python code."""
+def validate_connector(directory: Path) -> LocalConnectorPlugin:
+ """Validate a local connector directory without importing its Python code.
+
+ Args:
+ directory: Directory holding a ``connector.json`` manifest.
+
+ Returns:
+ The validated plugin described by the manifest.
+
+ Raises:
+ ValueError: If the manifest is missing, malformed, or declares
+ anything beyond read-only capabilities.
+ """
return parse_manifest(directory.expanduser().resolve() / MANIFEST_FILENAME)
def install_connector(directory: Path) -> Path:
- """Install a validated local connector under the user's runtime directory."""
+ """Install a validated local connector under the user's runtime directory.
+
+ Args:
+ directory: Directory holding the connector to install.
+
+ Returns:
+ The installed directory under the operator's plugin root.
+
+ Raises:
+ ValueError: If the manifest fails validation, or a connector with the
+ same id is already installed.
+ """
plugin = validate_connector(directory)
root = plugin_root()
root.mkdir(parents=True, exist_ok=True)
diff --git a/agent/src/trading/profiles.py b/agent/src/trading/profiles.py
index 3a13088bb..b0702c980 100644
--- a/agent/src/trading/profiles.py
+++ b/agent/src/trading/profiles.py
@@ -47,7 +47,14 @@ def config_path() -> Path:
def list_profiles() -> list[TradingProfile]:
- """Return built-in profiles plus operator-installed local read-only plugins."""
+ """Return built-in profiles plus operator-installed local read-only plugins.
+
+ Returns:
+ The built-in profiles, followed by the profile of every valid plugin
+ installed under the user's plugin root. A plugin never shadows a
+ built-in profile id, and an invalid manifest is skipped rather than
+ breaking the registry.
+ """
from src.trading.local_plugins import discover_plugins
plugins, _ = discover_plugins()
diff --git a/agent/tests/test_local_connections_hardening.py b/agent/tests/test_local_connections_hardening.py
new file mode 100644
index 000000000..fab806b96
--- /dev/null
+++ b/agent/tests/test_local_connections_hardening.py
@@ -0,0 +1,254 @@
+"""Packaging, caching, and eligibility guards for local read-only connections."""
+
+from __future__ import annotations
+
+import builtins
+import json
+import os
+import subprocess
+import sys
+import tomllib
+from pathlib import Path
+
+import pytest
+
+from src.trading import local_plugins
+from src.trading.connections import (
+ ConnectionStore,
+ is_portfolio_connection_profile,
+ readonly_profile_catalog,
+)
+from src.trading.credentials import CredentialStore
+from src.trading.local_plugins import clear_plugin_cache, discover_plugins
+from src.trading.plugin_scaffold import scaffold_connector
+from src.trading.profiles import profile_by_id
+
+ROOT = Path(__file__).resolve().parents[2]
+AGENT_DIR = ROOT / "agent"
+
+
+class _MemoryCredentials:
+ """In-memory stand-in for the OS credential vault."""
+
+ def __init__(self):
+ self.values: dict[tuple[str, str], str] = {}
+
+ def get_password(self, service_name: str, username: str):
+ return self.values.get((service_name, username))
+
+ def set_password(self, service_name: str, username: str, password: str):
+ self.values[(service_name, username)] = password
+
+ def delete_password(self, service_name: str, username: str):
+ self.values.pop((service_name, username), None)
+
+
+def _normalized_requirement_name(requirement: str) -> str:
+ name = requirement.split(";", 1)[0]
+ for marker in ("[", "<", ">", "="):
+ name = name.split(marker, 1)[0]
+ return name.strip().lower()
+
+
+# ---------------------------------------------------------------------------
+# keyring is an optional extra
+# ---------------------------------------------------------------------------
+
+
+def test_keyring_is_not_a_core_install_dependency() -> None:
+ """An OS credential vault is only needed by users who install a plugin."""
+ pyproject = tomllib.loads((ROOT / "pyproject.toml").read_text())
+
+ core_dependencies = {
+ _normalized_requirement_name(requirement)
+ for requirement in pyproject["project"]["dependencies"]
+ }
+ requirements_txt = {
+ _normalized_requirement_name(line)
+ for line in (ROOT / "agent" / "requirements.txt").read_text().splitlines()
+ if line and not line.startswith("#")
+ }
+ keyring_extra = {
+ _normalized_requirement_name(requirement)
+ for requirement in pyproject["project"]["optional-dependencies"]["keyring"]
+ }
+
+ assert "keyring" not in core_dependencies
+ assert "keyring" not in requirements_txt
+ assert "keyring" in keyring_extra
+
+
+def test_credential_store_names_the_extra_when_keyring_is_missing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A missing optional vault must produce an actionable install hint."""
+ real_import = builtins.__import__
+
+ def blocking_import(name, *args, **kwargs):
+ if name == "keyring" or name.startswith("keyring."):
+ raise ModuleNotFoundError("No module named 'keyring'")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", blocking_import)
+ monkeypatch.delitem(sys.modules, "keyring", raising=False)
+
+ with pytest.raises(RuntimeError, match=r'vibe-trading-ai\[keyring\]'):
+ CredentialStore().save("main-account", {"api_key": "value"})
+
+
+def test_connection_modules_import_without_keyring_installed() -> None:
+ """Connection metadata must stay importable on a base install.
+
+ Runs in a child process because re-importing these modules in the test
+ process would leave two copies of every profile class behind.
+ """
+ code = (
+ "import sys;"
+ "sys.meta_path.insert(0, type('Block', (), {"
+ "'find_module': staticmethod(lambda name, path=None: None),"
+ "'find_spec': staticmethod("
+ "lambda name, path=None, target=None: "
+ "(_ for _ in ()).throw(ModuleNotFoundError(name)) "
+ "if name.split('.')[0] == 'keyring' else None)})());"
+ "import src.trading.connections, src.trading.profiles, "
+ "src.api.connection_routes;"
+ "print('imported')"
+ )
+ env = os.environ.copy()
+ env["PYTHONPATH"] = str(AGENT_DIR) + os.pathsep + env.get("PYTHONPATH", "")
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ cwd=str(AGENT_DIR),
+ env=env,
+ timeout=600,
+ )
+
+ assert result.returncode == 0, (
+ "the connection modules import keyring eagerly, so a base install "
+ f"cannot even list connections: {result.stderr.decode()[-2000:]}"
+ )
+ assert "imported" in result.stdout.decode()
+
+
+# ---------------------------------------------------------------------------
+# Manifest discovery cache
+# ---------------------------------------------------------------------------
+
+
[email protected](autouse=True)
+def _isolated_plugin_cache():
+ """Keep cached discovery results from leaking between tests."""
+ clear_plugin_cache()
+ yield
+ clear_plugin_cache()
+
+
+def _count_manifest_parses(monkeypatch: pytest.MonkeyPatch) -> list[int]:
+ calls = [0]
+ real_parse = local_plugins.parse_manifest
+
+ def counting_parse(path: Path):
+ calls[0] += 1
+ return real_parse(path)
+
+ monkeypatch.setattr(local_plugins, "parse_manifest", counting_parse)
+ return calls
+
+
+def test_discovery_reuses_parsed_manifests_until_one_changes(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Profile lookups re-run discovery, so unchanged manifests must not re-parse."""
+ scaffold_connector("cached-broker", tmp_path)
+ calls = _count_manifest_parses(monkeypatch)
+
+ first, _ = discover_plugins(tmp_path)
+ second, _ = discover_plugins(tmp_path)
+
+ assert calls[0] == 1
+ assert [plugin.profile.id for plugin in second] == [
+ plugin.profile.id for plugin in first
+ ]
+
+ manifest = tmp_path / "cached-broker" / "connector.json"
+ payload = json.loads(manifest.read_text(encoding="utf-8"))
+ payload["profile"]["label"] = "Cached Broker renamed by the operator"
+ manifest.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+
+ refreshed, _ = discover_plugins(tmp_path)
+
+ assert calls[0] == 2
+ assert refreshed[0].profile.label == "Cached Broker renamed by the operator"
+
+
+def test_discovery_cache_is_keyed_on_the_plugin_root(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A test or operator that repoints the runtime root must see its own plugins."""
+ first_root = tmp_path / "first"
+ second_root = tmp_path / "second"
+ scaffold_connector("first-broker", first_root)
+ scaffold_connector("second-broker", second_root)
+
+ monkeypatch.setattr(local_plugins, "get_runtime_root", lambda: tmp_path / "first")
+ monkeypatch.setattr(local_plugins, "plugin_root", lambda: first_root)
+ assert [plugin.profile.connector for plugin in discover_plugins()[0]] == [
+ "first-broker"
+ ]
+
+ monkeypatch.setattr(local_plugins, "plugin_root", lambda: second_root)
+ assert [plugin.profile.connector for plugin in discover_plugins()[0]] == [
+ "second-broker"
+ ]
+
+
+def test_discovery_of_a_new_plugin_invalidates_the_cached_result(tmp_path) -> None:
+ """Installing a connector changes the manifest set, so discovery refreshes."""
+ scaffold_connector("early-broker", tmp_path)
+ assert [plugin.profile.connector for plugin in discover_plugins(tmp_path)[0]] == [
+ "early-broker"
+ ]
+
+ scaffold_connector("later-broker", tmp_path)
+
+ assert sorted(
+ plugin.profile.connector for plugin in discover_plugins(tmp_path)[0]
+ ) == ["early-broker", "later-broker"]
+
+
+# ---------------------------------------------------------------------------
+# Connection profile eligibility
+# ---------------------------------------------------------------------------
+
+
+def test_discovery_only_profile_cannot_back_a_portfolio_connection(tmp_path) -> None:
+ """A tool-discovery profile cannot serve account or position reads."""
+ profile = profile_by_id("ibkr-live-official-mcp-readonly")
+ assert profile.readonly is True
+ assert profile.capabilities == ("mcp.read.discovery",)
+ assert is_portfolio_connection_profile(profile) is False
+
+ store = ConnectionStore(
+ tmp_path / "connections.json",
+ credential_store=CredentialStore(_MemoryCredentials()),
+ )
+ with pytest.raises(ValueError, match="not eligible"):
+ store.create("ibkr-main", profile.id, "IBKR main")
+
+ assert profile.id not in {row.get("id") for row in readonly_profile_catalog()}
+
+
+def test_readonly_broker_sdk_profile_backs_a_portfolio_connection(tmp_path) -> None:
+ """A read-only SDK profile that exposes both reads stays eligible."""
+ profile = profile_by_id("binance-live-sdk-readonly")
+ assert is_portfolio_connection_profile(profile) is True
+
+ store = ConnectionStore(
+ tmp_path / "connections.json",
+ credential_store=CredentialStore(_MemoryCredentials()),
+ )
+ connection = store.create("main-binance", profile.id, "Main Binance")
+
+ assert connection.profile_id == "binance-live-sdk-readonly"
+ assert profile.id in {row.get("id") for row in readonly_profile_catalog()}
diff --git a/pyproject.toml b/pyproject.toml
index 3b4146695..03c5d465c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -49,7 +49,6 @@ dependencies = [
"ccxt>=4.5.71",
"aiohttp>=3.14.3",
"cryptography>=50.0.0",
- "keyring>=25.0.0",
"fastapi>=0.104.0",
"uvicorn[standard]>=0.24.0",
"websockets>=12.0",
@@ -164,6 +163,13 @@ smc = [
# Intel-Mac install into a source build that needs cmake (discussion #1035).
"smartmoneyconcepts>=0.0.27",
]
+keyring = [
+ # OS credential vault (Keychain / Credential Manager / Secret Service) for
+ # user-installed local read-only connector plugins. CredentialStore imports
+ # it lazily and raises an actionable hint naming this extra, so a base
+ # install stays lean for users who configure no local connector.
+ "keyring>=25.0.0",
+]
dingtalk = [
"dingtalk-stream>=0.24.0",
]