"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(trading): add connector-first broker profiles
Haozhe Wu52f5059159ab
diff --git a/README.md b/README.mdindex bfe904163..b9b4b4c58 100644--- a/README.md+++ b/README.md@@ -46,12 +46,13 @@## 📰 News+- **2026-05-31** 🔌 **Connector-first broker architecture (IBKR + Robinhood)**: Trading access now starts from a selectable connector profile instead of separate broker/live entry points. `vibe-trading connector list/use/check/account/positions/orders/quote/history` and the MCP `trading_*` tools share the same selected profile, where paper/live is an attribute of the connector. IBKR can be used immediately through a local read-only TWS / IB Gateway profile, while the official IBKR remote MCP path is seeded as an OAuth `mcp.read` probe until stable read tool names are available. Robinhood Agentic Trading remains the bounded live MCP connector behind OAuth, a committed mandate, order guard, audit ledger, and instant halt.- **2026-05-30** 🧰 **Robustness pass — backtest, agent loop, sessions**: LLM-generated signal engines now pass pre-flight interface validation before instantiation, catching circular self-imports, a missing `generate()`, non-defaulted `__init__` args, and wrong return types with actionable JSON errors instead of raw tracebacks ([#149](https://github.com/HKUDS/Vibe-Trading/pull/149)); a follow-up routes source-level AST validation errors through the same clean JSON envelope. The agent loop no longer burns all 50 iterations into a `failed` status with no output — it mirrors the swarm worker's wrap-up nudge at 80% of the iteration budget and drops tool definitions on the last iteration to force a final text answer ([#148](https://github.com/HKUDS/Vibe-Trading/pull/148)), guarded to fire only mid-run so it never displaces research-goal context. Session message writes now `flush + fsync` each append so expensive AI responses survive a mid-write crash, and the read path skips corrupted JSONL lines (logging the first 200 chars for recovery) instead of 500-ing the whole `/messages` endpoint ([#147](https://github.com/HKUDS/Vibe-Trading/pull/147)). The Web composer also fixes IME Enter handling so a composition-confirming Enter no longer submits mid-word ([#146](https://github.com/HKUDS/Vibe-Trading/pull/146)).- **2026-05-29** 🔐 **Robinhood Agentic Trading support (opt-in, bounded autonomy)**: Adds support for Robinhood Agentic Trading (remote MCP, OAuth). Off and read-only by default; the agent acts only inside a user-committed mandate (symbols / order size / exposure / leverage / daily cap), with a filesystem-level instant kill switch, preemptive flatten, mandate auto-expiry, a full audit ledger, and a persistent autonomous runner. No custody, no venue — the broker holds funds and executes; we only relay intent. Experimental / use at your own risk.-- **2026-05-28** 🧪 **Swarm safety + strict alpha gate + worker MCP**: Swarm DAG blocks downstream tasks when upstream fails ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145)). New `run_bench_strict()` adds a same-universe random control + OOS split to catch factors that just track market beta ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143), thanks @Soli22de). Swarm workers can call operator-configured external MCP servers, with trust boundary pinned ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142), thanks @shadowinlife).<details><summary>Earlier news</summary>+- **2026-05-28** 🧪 **Swarm safety + strict alpha gate + worker MCP**: Swarm DAG blocks downstream tasks when upstream fails ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145)). New `run_bench_strict()` adds a same-universe random control + OOS split to catch factors that just track market beta ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143), thanks @Soli22de). Swarm workers can call operator-configured external MCP servers, with trust boundary pinned ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142), thanks @shadowinlife).- **2026-05-27** 📊 **mootdx A-share data source + output polish**: New `mootdx` loader speaks the native 通达信 TCP protocol for A-share OHLCV (no auth, no IP rate-limit, daily + intraday with 25-page walk-back pagination), slotting between tushare and akshare in the fallback chain ([#107](https://github.com/HKUDS/Vibe-Trading/issues/107)). CCXT loader now reads `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY` so Binance/OKX public data works from restricted networks ([#126](https://github.com/HKUDS/Vibe-Trading/pull/126), thanks @ruok808). Final-answer rendering also dropped the ugly full-width `---` horizontal separators on CLI and Web: the system prompt now nudges the agent toward markdown tables and `##` headings, the CLI renderer strips standalone HRs as defense-in-depth, and the chat bubble hides any `<hr>` that slips through ([#139](https://github.com/HKUDS/Vibe-Trading/issues/139), thanks @sdwxm188).- **2026-05-26** ✅ **Research Goal lifecycle closure**: Goal mode now behaves like a real task runner: Web UI goal creation creates or binds the session and immediately sends the kickoff turn; active goals can be continued, edited, cancelled, and completed across Web/API/CLI/MCP; and the agent advances from the current goal snapshot (criteria, evidence, claims, open items) instead of only the original prompt. Covered-but-still-active goals now enter an audit/status update instead of stopping silently, with regression coverage across backend, CLI, MCP, and frontend events.@@ -674,7 +675,7 @@ Settings reads are side-effect free: `GET /settings/llm` and `GET /settings/data## 🔌 MCP Plugin-Vibe-Trading exposes 22 MCP tools for any MCP-compatible client. Runs as a stdio subprocess — no server setup needed. **21 of 22 tools work with zero API keys** (HK/US/crypto). Only `run_swarm` needs an LLM key.+Vibe-Trading exposes 35 MCP tools for any MCP-compatible client. Runs as a stdio subprocess — no server setup needed. Core research tools work with zero API keys for HK/US/crypto; trading connector tools use the selected connector profile, and `run_swarm` needs an LLM key.<details><summary><b>Claude Desktop</b></summary>@@ -716,7 +717,7 @@ vibe-trading-mcp --transport sse # SSE for web clients</details>-**MCP tools exposed (22):** `list_skills`, `load_skill`, `backtest`, `factor_analysis`, `analyze_options`, `pattern_recognition`, `get_market_data`, `web_search`, `read_url`, `read_document`, `read_file`, `write_file`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `list_swarm_presets`, `run_swarm`, `get_swarm_status`, `get_run_result`, `list_runs`.+**MCP tools exposed (35):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `analyze_options`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`.### SWARM external MCP tools@@ -789,12 +790,89 @@ Create `~/.vibe-trading/agent.json`:}```-Run any CLI command — tools from `my-server` are automatically injected into the agent's registry after local tools:+Run any CLI command — tools from ordinary external servers are automatically injected into the agent's registry after local tools:```bashvibe-trading run "use my-server to do X"```+### Official IBKR MCP read-only probe++Vibe-Trading can connect directly to Interactive Brokers' official remote MCP+endpoint in read-only mode. Add this to `~/.vibe-trading/agent.json`:++```json+{+ "mcpServers": {+ "ibkr": {+ "type": "streamableHttp",+ "url": "https://api.ibkr.com/v1/api/mcp",+ "auth": {+ "type": "oauth",+ "scopes": ["mcp.read"],+ "clientName": "Vibe-Trading",+ "cacheDir": "~/.vibe-trading/live/ibkr/oauth"+ },+ "enabledTools": ["*"]+ }+ }+}+```++Then start the browser OAuth flow:++```bash+vibe-trading connector authorize ibkr-live-official-mcp-readonly+```++The wildcard is accepted only for IBKR's `mcp.read` probe. Authorizing this+profile confirms access to IBKR's official read scope; generic `trading_account`+and `trading_positions` calls stay disabled until IBKR publishes stable read+tool names that Vibe-Trading can map safely. A config that adds `mcp.write` must+pin an explicit tool allowlist and still passes through the live order guard.++If IBKR issues a pre-registered OAuth client, add `clientId` and `clientSecret`+inside `auth`.++### Trading connectors: fastest path++For users who cannot wait for IBKR OAuth client approval, connect to a local+TWS or IB Gateway session. Credentials stay inside IBKR's desktop app; Vibe-+Trading only connects to `127.0.0.1` and exposes it as a connector profile.++Install the optional SDK:++```bash+pip install "vibe-trading-ai[ibkr]"+```++Open TWS paper trading or IB Gateway paper, enable API socket clients, then run:++```bash+vibe-trading connector list+vibe-trading connector use ibkr-paper-local+vibe-trading connector configure ibkr-paper-local --yes+vibe-trading connector check+vibe-trading connector account+vibe-trading connector positions+vibe-trading connector orders+vibe-trading connector quote AAPL+vibe-trading connector history AAPL --duration "30 D" --bar-size "1 day"+```++Default local ports:++| App | Paper | Live read-only |+|-----|-------|----------------|+| TWS | `7497` | `7496` |+| IB Gateway | `4002` | `4001` |++The agent exposes connector-scoped tools named `trading_connections`,+`trading_select_connection`, `trading_check`, `trading_account`,+`trading_positions`, `trading_orders`, `trading_quote`, and `trading_history`.+Live-broker raw MCP tools are not registered directly as `mcp_<broker>_*`.+No IBKR order-placement tool is registered.+### Config reference| Field | Type | Default | Description |@@ -832,7 +910,8 @@ When creating a session via the API you can pass `mcpServers` inside `session.co### Tool naming-Remote tools are exposed with stable names: `mcp_<server>_<tool>`.+Ordinary remote tools are exposed with stable names: `mcp_<server>_<tool>`.+Live-broker MCP servers stay behind the `trading_*` connector surface.If two server names produce the same ASCII-safe local prefix (e.g. `foo-bar` and `foo_bar` both become `foo_bar`), a deterministic hash suffix is appended at the server-segment level so names remain unique. The operator receives a warning:@@ -864,7 +943,7 @@ Vibe-Trading/├── agent/ # Backend (Python)│ ├── cli/ # CLI package — interactive TUI + subcommands│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE-│ ├── mcp_server.py # MCP server — 22 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 35 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent corediff --git a/README_ar.md b/README_ar.mdindex da1724b98..6c63b6ada 100644--- a/README_ar.md+++ b/README_ar.md@@ -46,12 +46,13 @@## 📰 الأخبار+- **2026-05-31** 🔌 **بنية وسطاء تعتمد أولاً على connectors (IBKR + Robinhood)**: يبدأ الوصول إلى التداول الآن من connector profile قابل للاختيار، لا من مداخل منفصلة للوسيط أو live. أوامر `vibe-trading connector list/use/check/account/positions/orders/quote/history` وأدوات MCP `trading_*` تشترك في نفس profile المحدد، حيث تكون paper/live مجرد خاصية ضمن connector. يمكن استخدام IBKR فوراً عبر profile محلي للقراءة فقط من TWS / IB Gateway، بينما يُزرع مسار MCP الرسمي البعيد لـ IBKR كتحقق OAuth بنطاق `mcp.read` إلى أن تتوفر أسماء أدوات قراءة مستقرة. يظل Robinhood Agentic Trading هو connector MCP حيّاً ومحدوداً خلف OAuth وmandate مُلتزم وorder guard وسجل تدقيق وhalt فوري.- **2026-05-30** 🧰 **جولة متانة — backtest وagent loop وsession**: تمرّ الآن signal engines المولّدة بواسطة LLM بتحقق مسبق من الواجهة قبل الإنشاء، فتلتقط مبكراً الأخطاء الشائعة مثل self-import الدائري، وغياب `generate()`، ووسائط `__init__` بلا قيم افتراضية، ونوع الإرجاع الخاطئ، وتُرجِع أخطاء JSON قابلة للتنفيذ بدل traceback خام ([#149](https://github.com/HKUDS/Vibe-Trading/pull/149))؛ ومتابعةٌ لاحقة توجّه أخطاء تحقق AST على مستوى المصدر عبر نفس مغلّف JSON النظيف. لم يعد agent loop يستنزف الخمسين تكراراً ليصل إلى حالة `failed` بلا أي مخرجات — فهو يحاكي أسلوب swarm worker المُجرَّب: يحقن wrap-up nudge عند 80% من ميزانية التكرار ويُسقط تعريفات الأدوات في التكرار الأخير لفرض إجابة نصية ([#148](https://github.com/HKUDS/Vibe-Trading/pull/148))، مع حارس يجعله يُطلَق في المنتصف فقط كي لا يزيح سياق research-goal. كتابة رسائل الجلسة تجري الآن `flush + fsync` بعد كل append حتى تنجو ردود الـ AI الباهظة من تعطّل أثناء الكتابة، ويتخطّى مسار القراءة أسطر JSONL التالفة (مع تسجيل أول 200 حرف للاسترداد) بدل إعطاء 500 لنقطة `/messages` كاملة ([#147](https://github.com/HKUDS/Vibe-Trading/pull/147)). كما أصلح محرّر الإدخال في الويب معالجة Enter مع IME بحيث لا يؤدي Enter لتأكيد التركيب إلى إرسال في منتصف الكلمة ([#146](https://github.com/HKUDS/Vibe-Trading/pull/146)).- **2026-05-29** 🔐 **دعم Robinhood Agentic Trading (اختياري، استقلالية محدودة)**: أُضيف دعم Robinhood Agentic Trading (MCP عن بُعد، OAuth). مُعطَّل وللقراءة فقط افتراضياً؛ ويتداول الوكيل تلقائياً فقط ضمن mandate يلتزم به المستخدم (الرموز / حجم الأمر / التعرّض / الرافعة / الحد اليومي)، مع kill switch فوري على مستوى الملفات، وتصفية استباقية للمراكز، وانتهاء صلاحية تلقائي لـ mandate، وسجل تدقيق كامل، و runner مستقل دائم. لا حفظ للأموال ولا تشغيل لمنصة تداول — الوسيط يحتفظ بالأموال وينفّذ، ونحن ننقل النية فقط. تجريبي / الاستخدام على مسؤوليتك.-- **2026-05-28** 🧪 **سلامة Swarm + بوّابة alpha صارمة + MCP لعمّال swarm**: يحجب Swarm DAG الآن المهام المتفرعة عندما تفشل المهمة الأعلى ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145)). دالة `run_bench_strict()` الجديدة تضيف فوق بوّابة IC تحكماً عشوائياً بنفس universe + قسمة train/test OOS لاصطياد العوامل التي تتبع beta السوق فقط ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143)، شكراً @Soli22de). يستطيع عمّال Swarm الآن استدعاء أدوات من خوادم MCP خارجية يضبطها المشغل، مع تثبيت حدود الثقة باختبارات مخصصة ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142)، شكراً @shadowinlife).<details><summary>أخبار سابقة</summary>+- **2026-05-28** 🧪 **سلامة Swarm + بوّابة alpha صارمة + MCP لعمّال swarm**: يحجب Swarm DAG الآن المهام المتفرعة عندما تفشل المهمة الأعلى ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145)). دالة `run_bench_strict()` الجديدة تضيف فوق بوّابة IC تحكماً عشوائياً بنفس universe + قسمة train/test OOS لاصطياد العوامل التي تتبع beta السوق فقط ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143)، شكراً @Soli22de). يستطيع عمّال Swarm الآن استدعاء أدوات من خوادم MCP خارجية يضبطها المشغل، مع تثبيت حدود الثقة باختبارات مخصصة ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142)، شكراً @shadowinlife).- **2026-05-27** 📊 **مصدر بيانات A-share عبر mootdx + تحسين الإخراج**: محمّل `mootdx` الجديد يتحدث بروتوكول 通达信 TCP الأصلي لبيانات OHLCV لأسهم A (بدون مصادقة، بدون قيود معدل لكل IP، يومي + intraday مع pagination تراجع بـ 25 صفحة)، ويُدرج بين tushare وakshare في سلسلة fallback ([#107](https://github.com/HKUDS/Vibe-Trading/issues/107)). محمّل CCXT يقرأ الآن `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY` ليعمل جلب بيانات Binance/OKX العامة من الشبكات المقيدة ([#126](https://github.com/HKUDS/Vibe-Trading/pull/126)، شكراً @ruok808). عرض الإجابة النهائية أزال أيضاً فواصل `---` الأفقية القبيحة بعرض كامل على CLI وWeb: يحث system prompt الآن agent على استخدام جداول markdown وعناوين `##`، يجرّد CLI renderer أسطر HR المستقلة كدفاع متعمق، ويخفي chat bubble أي `<hr>` ينفذ عبر ([#139](https://github.com/HKUDS/Vibe-Trading/issues/139)، شكراً @sdwxm188).- **2026-05-26** ✅ **إغلاق دورة حياة Research Goal**: أصبح Goal mode يعمل كمنفّذ مهام حقيقي: إنشاء goal من Web UI ينشئ الجلسة أو يربطها ويرسل kickoff turn فوراً؛ يمكن متابعة active goals وتعديلها وإلغاؤها وإكمالها عبر Web/API/CLI/MCP؛ ويتقدم agent loop من لقطة goal الحالية (criteria وevidence وclaims وopen items) بدلاً من الاعتماد على prompt الأصلي فقط. عندما تكون criteria covered لكن goal لا يزال active، ينتقل النظام إلى audit/status update بدلاً من التوقف الصامت، مع تغطية انحدارية عبر backend وCLI وMCP وfrontend events.diff --git a/README_ja.md b/README_ja.mdindex ff4c0eb5d..32559bfb0 100644--- a/README_ja.md+++ b/README_ja.md@@ -46,12 +46,13 @@## 📰 ニュース+- **2026-05-31** 🔌 **Connector-first ブローカーアーキテクチャ(IBKR + Robinhood)**: 取引アクセスは、個別のブローカー入口や live 入口ではなく、選択可能な connector profile から始まるようになりました。`vibe-trading connector list/use/check/account/positions/orders/quote/history` と MCP の `trading_*` ツールは同じ選択済み profile を共有し、paper/live は connector 配下の属性として扱われます。IBKR はローカル読み取り専用 TWS / IB Gateway profile ですぐ使え、公式 IBKR リモート MCP は安定した read tool 名が公開されるまで OAuth `mcp.read` probe として seed されています。Robinhood Agentic Trading は引き続き、OAuth、コミット済み mandate、order guard、audit ledger、instant halt の背後にある bounded live MCP connector です。- **2026-05-30** 🧰 **堅牢性パス — backtest、agent loop、session**: LLM 生成の signal engine は、インスタンス化の前にインターフェース事前検証を通すようになりました。循環 self-import、`generate()` の欠落、デフォルト値のない `__init__` 引数、誤った戻り値型といった典型ミスを早期に捕捉し、生の traceback ではなく実行可能な JSON エラーで返します ([#149](https://github.com/HKUDS/Vibe-Trading/pull/149))。続くフォローアップで、ソースレベルの AST 検証エラーも同じクリーンな JSON エンベロープに乗せました。agent loop は 50 反復を使い切って出力のない `failed` 状態に陥らなくなりました——swarm worker の実績ある方式に倣い、反復予算の 80% で wrap-up nudge を注入し、最後の反復で tool 定義を外してテキスト回答を強制します ([#148](https://github.com/HKUDS/Vibe-Trading/pull/148))。途中でのみ発火するようガードしてあり、research-goal の文脈を押しのけることはありません。session のメッセージ書き込みは append ごとに `flush + fsync` するようになり、高価な AI 応答が書き込み途中のクラッシュでも残ります。読み取り側は壊れた JSONL 行をスキップし(復旧用に先頭 200 文字をログ)、`/messages` エンドポイント全体を 500 にしません ([#147](https://github.com/HKUDS/Vibe-Trading/pull/147))。Web の入力欄は IME の Enter 処理も修正し、変換確定の Enter で語の途中送信が起きないようにしました ([#146](https://github.com/HKUDS/Vibe-Trading/pull/146))。- **2026-05-29** 🔐 **Robinhood Agentic Trading 対応(オプトイン・有界自律)**: Robinhood Agentic Trading に対応しました(リモート MCP、OAuth)。デフォルトでは無効かつ読み取り専用。エージェントはユーザーがコミットした mandate(銘柄/注文サイズ/エクスポージャー/レバレッジ/日次上限)の範囲内でのみ自律取引し、ファイルレベルの即時 kill switch、先制的なポジション手仕舞い、mandate の自動失効、完全な監査台帳、永続的な自律 runner を備えます。資金の保管なし・取引所運営なし——資金の保有と執行はブローカーが行い、こちらは意図を中継するだけです。実験的 / 自己責任でご利用ください。-- **2026-05-28** 🧪 **Swarm の安全性 + 厳格 alpha gate + worker 側 MCP**: Swarm DAG は上流タスクが失敗したとき下流タスクをブロックするようになりました ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145))。新規 `run_bench_strict()` は IC gate に同 universe のランダムコントロール + train/test OOS 分割を追加し、市場 beta を追っているだけの偽 factor を捕捉します ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143), @Soli22de さんに感謝)。Swarm worker は operator が設定した外部 MCP server からツールを呼べるようになり、信頼境界は専用テストで固定されています ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142), @shadowinlife さんに感謝)。<details><summary>過去のニュース</summary>+- **2026-05-28** 🧪 **Swarm の安全性 + 厳格 alpha gate + worker 側 MCP**: Swarm DAG は上流タスクが失敗したとき下流タスクをブロックするようになりました ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145))。新規 `run_bench_strict()` は IC gate に同 universe のランダムコントロール + train/test OOS 分割を追加し、市場 beta を追っているだけの偽 factor を捕捉します ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143), @Soli22de さんに感謝)。Swarm worker は operator が設定した外部 MCP server からツールを呼べるようになり、信頼境界は専用テストで固定されています ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142), @shadowinlife さんに感謝)。- **2026-05-27** 📊 **mootdx A 株データソース + 出力スタイル**: 新規 `mootdx` loader はネイティブ 通达信 TCP プロトコルで A 株 OHLCV を取得します(認証不要、IP 速度制限なし、日足 + 分足の 25 ページ walk-back ページング)。fallback chain では tushare と akshare の間に配置されます ([#107](https://github.com/HKUDS/Vibe-Trading/issues/107))。CCXT loader は `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY` を読み込み、制限されたネットワークから Binance/OKX の公開データを取得できるようになりました ([#126](https://github.com/HKUDS/Vibe-Trading/pull/126), @ruok808 さんに感謝)。最終回答のレンダリングからは CLI と Web の見苦しい全幅 `---` セパレータを削除しました: system prompt は markdown table と `##` heading を促し、CLI renderer は単独 HR を defense-in-depth として除去し、chat bubble はすり抜けた `<hr>` を隠します ([#139](https://github.com/HKUDS/Vibe-Trading/issues/139), @sdwxm188 さんに感謝)。- **2026-05-26** ✅ **Research Goal ライフサイクルの閉ループ化**: Goal mode が実際のタスクランナーのように動くようになりました。Web UI で goal を作成すると session を作成または bind し、即座に kickoff turn を送ります。active goal は Web/API/CLI/MCP から continue/edit/cancel/complete でき、agent loop は最初の prompt だけでなく現在の goal snapshot(criteria、evidence、claims、open items)から前進します。criteria が covered でも goal が active のままなら silent stop ではなく audit/status update に入り、backend、CLI、MCP、frontend events の回帰で固定しました。diff --git a/README_ko.md b/README_ko.mdindex 5a37dc852..e0ca2537b 100644--- a/README_ko.md+++ b/README_ko.md@@ -46,12 +46,13 @@## 📰 뉴스+- **2026-05-31** 🔌 **Connector-first 브로커 아키텍처(IBKR + Robinhood)**: 거래 접근은 이제 별도의 브로커/live 진입점이 아니라 선택 가능한 connector profile에서 시작합니다. `vibe-trading connector list/use/check/account/positions/orders/quote/history`와 MCP `trading_*` 도구는 동일한 선택 profile을 공유하며, paper/live는 connector의 속성으로 다룹니다. IBKR은 로컬 읽기 전용 TWS / IB Gateway profile로 즉시 사용할 수 있고, 공식 IBKR 원격 MCP 경로는 안정적인 read tool 이름이 제공될 때까지 OAuth `mcp.read` probe로 seed되어 있습니다. Robinhood Agentic Trading은 계속 OAuth, 커밋된 mandate, order guard, audit ledger, instant halt 뒤에 있는 bounded live MCP connector입니다.- **2026-05-30** 🧰 **견고성 패스 — backtest, agent loop, session**: LLM이 생성한 signal engine은 이제 인스턴스화 전에 인터페이스 사전 검증을 거칩니다. 순환 self-import, 누락된 `generate()`, 기본값 없는 `__init__` 인자, 잘못된 반환 타입 같은 흔한 실수를 조기에 잡아 원시 traceback 대신 실행 가능한 JSON 오류로 반환합니다 ([#149](https://github.com/HKUDS/Vibe-Trading/pull/149)). 후속 작업으로 소스 수준 AST 검증 오류도 동일한 깔끔한 JSON 봉투에 실었습니다. agent loop는 더 이상 50회 반복을 모두 소진하고 출력 없는 `failed` 상태로 끝나지 않습니다 — swarm worker의 검증된 방식을 따라 반복 예산의 80%에서 wrap-up nudge를 주입하고 마지막 반복에서 tool 정의를 제거해 텍스트 답변을 강제합니다 ([#148](https://github.com/HKUDS/Vibe-Trading/pull/148)). 중간에만 발동하도록 가드되어 research-goal 컨텍스트를 밀어내지 않습니다. session 메시지 쓰기는 이제 append마다 `flush + fsync`하여 비싼 AI 응답이 쓰기 도중 크래시에도 살아남고, 읽기 경로는 손상된 JSONL 줄을 건너뛰며(복구용으로 앞 200자 로깅) `/messages` 엔드포인트 전체를 500으로 만들지 않습니다 ([#147](https://github.com/HKUDS/Vibe-Trading/pull/147)). Web 입력창은 IME Enter 처리도 수정해 조합 확정 Enter가 단어 도중에 전송되지 않도록 했습니다 ([#146](https://github.com/HKUDS/Vibe-Trading/pull/146)).- **2026-05-29** 🔐 **Robinhood Agentic Trading 지원(옵트인, 제한된 자율성)**: Robinhood Agentic Trading을 지원합니다(원격 MCP, OAuth). 기본적으로 비활성·읽기 전용이며, 에이전트는 사용자가 커밋한 mandate(종목/주문 규모/익스포저/레버리지/일일 한도) 범위 안에서만 자율 거래합니다. 파일 수준의 즉시 kill switch, 선제적 포지션 청산, mandate 자동 만료, 완전한 감사 원장, 영속 자율 runner를 갖췄습니다. 수탁 없음·거래소 없음 — 자금 보유와 체결은 브로커가 하고, 우리는 의도만 중계합니다. 실험적 / 사용에 따른 책임은 본인에게 있습니다.-- **2026-05-28** 🧪 **Swarm 안전성 + 엄격 alpha 게이트 + worker MCP**: Swarm DAG가 상위 태스크 실패 시 하위 태스크를 차단합니다 ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145)). 새 `run_bench_strict()`는 IC 게이트 위에 동일 universe 랜덤 컨트롤 + 학습/테스트 OOS 분할을 추가해 시장 beta만 따라가는 가짜 factor를 잡아냅니다 ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143), @Soli22de 감사). Swarm worker는 이제 operator가 설정한 외부 MCP server를 호출할 수 있으며 신뢰 경계는 전용 테스트로 고정되어 있습니다 ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142), @shadowinlife 감사).<details><summary>이전 뉴스</summary>+- **2026-05-28** 🧪 **Swarm 안전성 + 엄격 alpha 게이트 + worker MCP**: Swarm DAG가 상위 태스크 실패 시 하위 태스크를 차단합니다 ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145)). 새 `run_bench_strict()`는 IC 게이트 위에 동일 universe 랜덤 컨트롤 + 학습/테스트 OOS 분할을 추가해 시장 beta만 따라가는 가짜 factor를 잡아냅니다 ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143), @Soli22de 감사). Swarm worker는 이제 operator가 설정한 외부 MCP server를 호출할 수 있으며 신뢰 경계는 전용 테스트로 고정되어 있습니다 ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142), @shadowinlife 감사).- **2026-05-27** 📊 **mootdx A주 데이터 소스 + 출력 정리**: 새 `mootdx` loader는 네이티브 通达信 TCP 프로토콜로 A주 OHLCV를 가져옵니다(인증 불필요, IP 속도 제한 없음, 일봉 + 분봉의 25 페이지 walk-back 페이지네이션). fallback chain에서 tushare와 akshare 사이에 위치합니다 ([#107](https://github.com/HKUDS/Vibe-Trading/issues/107)). CCXT loader는 이제 `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY`를 읽어 제한된 네트워크에서 Binance/OKX 공개 데이터를 가져올 수 있습니다 ([#126](https://github.com/HKUDS/Vibe-Trading/pull/126), @ruok808 감사). 최종 답변 렌더링에서도 CLI와 Web의 보기 흉한 전체 너비 `---` 구분자를 제거했습니다: system prompt는 markdown 테이블과 `##` 헤딩 사용을 유도하고, CLI 렌더러는 독립 HR을 defense-in-depth로 제거하며, 채팅 버블은 빠져나온 `<hr>`을 숨깁니다 ([#139](https://github.com/HKUDS/Vibe-Trading/issues/139), @sdwxm188 감사).- **2026-05-26** ✅ **Research Goal lifecycle 폐쇄 루프**: Goal mode가 실제 task runner처럼 동작합니다. Web UI에서 goal을 만들면 session을 생성하거나 바인딩하고 즉시 kickoff turn을 보냅니다. active goal은 Web/API/CLI/MCP에서 continue/edit/cancel/complete할 수 있으며, agent loop는 최초 prompt만이 아니라 현재 goal snapshot(criteria, evidence, claims, open items)을 기준으로 진행합니다. criteria가 covered였지만 goal이 active로 남아 있으면 조용히 멈추지 않고 audit/status update로 들어가며, backend, CLI, MCP, frontend events 회귀로 고정했습니다.diff --git a/README_zh.md b/README_zh.mdindex 0c98479f8..ddfd99565 100644--- a/README_zh.md+++ b/README_zh.md@@ -46,12 +46,13 @@## 📰 News+- **2026-05-31** 🔌 **Connector-first 券商架构(IBKR + Robinhood)**:交易接入现在从可选择的 connector profile 开始,不再拆成分散的券商入口和 live 入口。`vibe-trading connector list/use/check/account/positions/orders/quote/history` 与 MCP `trading_*` 工具共享同一个选中的 profile;paper/live 只是该 connector 下的属性。IBKR 可立即通过本地只读 TWS / IB Gateway profile 使用;官方 IBKR 远程 MCP 先作为 OAuth `mcp.read` 探测种子,等待稳定 read 工具名后再映射。Robinhood Agentic Trading 仍是有界 live MCP connector,必须经过 OAuth、已提交 mandate、order guard、审计账本和即时 halt。- **2026-05-30** 🧰 **健壮性专项 — backtest、agent loop、session**:LLM 生成的 signal engine 现在会在实例化前先过接口预检,提前抓出循环 self-import、缺失 `generate()`、`__init__` 参数没有默认值、返回类型错误等常见问题,并给出可操作的 JSON 报错而非原始 traceback([#149](https://github.com/HKUDS/Vibe-Trading/pull/149));后续一并把源码级 AST 校验的报错也走同一套干净的 JSON 信封。agent loop 不再把 50 次迭代全烧光后留下一个没有任何输出的 `failed` 状态——它复用 swarm worker 已验证的做法:在迭代预算 80% 处注入 wrap-up nudge,并在最后一次迭代丢掉 tool 定义以强制产出文本答案([#148](https://github.com/HKUDS/Vibe-Trading/pull/148)),且只在中途触发,绝不挤掉 research-goal 上下文。session 消息写入现在每次 append 后 `flush + fsync`,让昂贵的 AI 回复能在写到一半崩溃时存活;读取端则跳过损坏的 JSONL 行(记录前 200 字符以便人工恢复),而不是让整个 `/messages` 端点 500([#147](https://github.com/HKUDS/Vibe-Trading/pull/147))。Web 输入框也修了 IME 回车处理,让中日韩输入法的确认上屏回车不再误触发提交([#146](https://github.com/HKUDS/Vibe-Trading/pull/146))。- **2026-05-29** 🔐 **支持 Robinhood Agentic Trading(可选开启、有界自主)**:新增对 Robinhood Agentic Trading 的支持(远程 MCP,OAuth)。默认关闭且只读;仅在用户提交的 mandate(标的/单量/敞口/杠杆/每日笔数)内自主交易,配文件级即时 kill switch、抢占式平仓、mandate 自动过期、完整审计账本,以及一个持久自主 runner。无托管、无场所——券商持有资金并执行,我们只中继意图。实验性 / 风险自负。-- **2026-05-28** 🧪 **Swarm 安全 + 严格 alpha 门 + worker 端 MCP**:Swarm DAG 在上游任务失败时阻断下游任务([#145](https://github.com/HKUDS/Vibe-Trading/pull/145))。新增 `run_bench_strict()` 在 IC 门之上加入同 universe 随机控制 + 训练/测试 OOS 切分,识别只是跟随市场 beta 的伪因子([#143](https://github.com/HKUDS/Vibe-Trading/pull/143),感谢 @Soli22de)。Swarm worker 现在可以调用 operator 配置的外部 MCP server,信任边界由专项测试固定([#142](https://github.com/HKUDS/Vibe-Trading/pull/142),感谢 @shadowinlife)。<details><summary>更早的更新</summary>+- **2026-05-28** 🧪 **Swarm 安全 + 严格 alpha 门 + worker 端 MCP**:Swarm DAG 在上游任务失败时阻断下游任务([#145](https://github.com/HKUDS/Vibe-Trading/pull/145))。新增 `run_bench_strict()` 在 IC 门之上加入同 universe 随机控制 + 训练/测试 OOS 切分,识别只是跟随市场 beta 的伪因子([#143](https://github.com/HKUDS/Vibe-Trading/pull/143),感谢 @Soli22de)。Swarm worker 现在可以调用 operator 配置的外部 MCP server,信任边界由专项测试固定([#142](https://github.com/HKUDS/Vibe-Trading/pull/142),感谢 @shadowinlife)。- **2026-05-27** 📊 **mootdx A 股数据源 + 输出排版**:新增 `mootdx` loader,走原生通达信 TCP 协议拉 A 股 OHLCV(无需 token,无 IP 速率限制,日线 + 分钟线 25 页 walk-back 分页),在 fallback chain 中位于 tushare 和 akshare 之间([#107](https://github.com/HKUDS/Vibe-Trading/issues/107))。CCXT loader 现在会读取 `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY`,使 Binance/OKX 公开数据可在受限网络下拉取([#126](https://github.com/HKUDS/Vibe-Trading/pull/126),感谢 @ruok808)。最终回答的渲染也去掉了 CLI 和 Web 上丑陋的全宽 `---` 分隔符:系统提示鼓励 agent 用 markdown 表格和 `##` 标题,CLI 渲染端兜底 strip 孤立 HR,前端 chat 气泡隐藏任何漏过去的 `<hr>`([#139](https://github.com/HKUDS/Vibe-Trading/issues/139),感谢 @sdwxm188)。- **2026-05-26** ✅ **Research Goal 生命周期闭环**:Goal 模式现在像真正的任务运行器:Web UI 创建 goal 会创建或绑定 session,并立刻发出 kickoff turn;active goal 可在 Web/API/CLI/MCP 中继续、编辑、取消和完成;agent loop 会按当前 goal snapshot(criteria、evidence、claims、open items)推进,而不是只按最初 prompt。criteria 已 covered 但 goal 仍 active 时,会进入 audit/status 更新,不再静默停住,并用 backend、CLI、MCP 与 frontend events 回归覆盖固定。diff --git a/agent/SKILL.md b/agent/SKILL.mdindex e41415ece..f8f8b9463 100644--- a/agent/SKILL.md+++ b/agent/SKILL.md@@ -1,7 +1,7 @@---name: vibe-tradingversion: 0.1.8-description: Professional finance research toolkit — backtesting (7 engines + benchmark comparison panel), factor analysis, Alpha Zoo (452 pre-built alphas across qlib158/alpha101/gtja191/academic), options pricing, 75 finance skills, 29 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 7 data sources (tushare, yfinance, okx, akshare, mootdx, ccxt, futu).+description: Professional finance research toolkit — backtesting (7 engines + benchmark comparison panel), factor analysis, Alpha Zoo (452 pre-built alphas across qlib158/alpha101/gtja191/academic), options pricing, 77 finance skills, 29 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 7 data sources (tushare, yfinance, okx, akshare, mootdx, ccxt, futu).dependencies:python: ">=3.11"pip:@@ -23,7 +23,7 @@ mcp:# Vibe-Trading-Professional finance research toolkit with AI-powered backtesting (7 engines), multi-agent teams, 75 specialized skills, the **Alpha Zoo** (452 pre-built quantitative alphas across qlib158 / alpha101 / gtja191 / academic with one-line CLI benchmarking), and the Shadow Account loop — extract your implicit trading rules from a journal, backtest them across A股/港股/美股/crypto, then see where they would have served you better.+Professional finance research toolkit with AI-powered backtesting (7 engines), multi-agent teams, 77 specialized skills, the **Alpha Zoo** (452 pre-built quantitative alphas across qlib158 / alpha101 / gtja191 / academic with one-line CLI benchmarking), and the Shadow Account loop — extract your implicit trading rules from a journal, backtest them across A股/港股/美股/crypto, then see where they would have served you better.## Setup@@ -53,7 +53,7 @@ Add to your agent's MCP config:### API Key Requirements-**21 of 22 MCP tools work with zero API keys.** After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, document reading, trade journal analysis, shadow-account extraction/backtest/report, the Alpha Zoo (452 pre-built alphas), and all 75 skills are ready to use for HK/US equities and crypto.+Core research MCP tools work with zero API keys for HK/US/crypto. After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, document reading, trade journal analysis, shadow-account extraction/backtest/report, the Alpha Zoo (452 pre-built alphas), and all 77 skills are ready to use. IBKR tools require a local TWS / IB Gateway session; `run_swarm` requires an LLM key.| Feature | Key needed | When ||---------|-----------|------|@@ -108,7 +108,7 @@ One-line cross-sectional IC / IR / alive-reversed-dead categorisation across fouEach alpha ships with `__alpha_meta__` (formula LaTeX + theme + universe + warmup + columns required), guarded by an AST purity gate + 300-row lookahead sentinel test. Use the `vibe-trading alpha {list,show,bench,compare,export-manifest}` CLI, the `/alpha/*` REST routes (browser at `/alpha-zoo`), or compose multi-factor signals via `ZooSignalEngine.from_zoo(...)`.-### Finance Skills (75)+### Finance Skills (77)Comprehensive knowledge base covering:- Technical analysis (candlestick, Elliott wave, Ichimoku, SMC, harmonic, chanlun)- Quantitative methods (factor research, ML strategy, pair trading, multi-factor)@@ -121,12 +121,16 @@ Comprehensive knowledge base covering:Use `load_skill(name)` to access full methodology docs with code templates.-## Available MCP Tools (22)+## Available MCP Tools (35)| Tool | Description | API Key ||------|-------------|---------|-| `list_skills` | List all 75 finance skills | None |+| `list_skills` | List all 77 finance skills | None || `load_skill` | Load full skill documentation | None |+| `start_research_goal` | Create an auditable research goal | None |+| `get_research_goal` | Read the current research goal | None |+| `add_goal_evidence` | Attach evidence to a research goal | None |+| `update_research_goal_status` | Update goal lifecycle status | None || `backtest` | Run vectorized backtest engine | None* || `factor_analysis` | IC/IR analysis + layered backtest | None* || `analyze_options` | Black-Scholes price + Greeks | None |@@ -147,8 +151,17 @@ Use `load_skill(name)` to access full methodology docs with code templates.| `get_swarm_status` | Poll swarm run status without blocking | None || `get_run_result` | Get final report and task summaries | None || `list_runs` | List recent swarm runs with metadata | None |--<sub>*A-share symbols require `TUSHARE_TOKEN`. HK/US/crypto are free.</sub>+| `reap_stale_runs` | Finalize stale swarm runs | None |+| `trading_connections` | List selectable connector profiles | None |+| `trading_select_connection` | Select the default connector profile | None |+| `trading_check` | Check connector readiness | Connector app/OAuth |+| `trading_account` | Read account summary from selected connector | Connector app/OAuth |+| `trading_positions` | Read positions from selected connector | Connector app/OAuth |+| `trading_orders` | Read open orders from selected connector | Connector app/OAuth |+| `trading_quote` | Read a quote snapshot from selected connector | Connector app/OAuth |+| `trading_history` | Read historical bars from selected connector | Connector app/OAuth |++<sub>*A-share symbols require `TUSHARE_TOKEN`. HK/US/crypto are free. Trading connector rows use the selected connector profile, e.g. IBKR local TWS/Gateway or Robinhood MCP OAuth.</sub>## Quick Start@@ -156,7 +169,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.pip install vibe-trading-ai```-That's it — no API keys needed for HK/US/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `analyze_trade_journal`, `extract_shadow_strategy`, `web_search`, the **Alpha Zoo** (`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`), and all 75 skills immediately.+That's it — no API keys needed for HK/US/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `analyze_trade_journal`, `extract_shadow_strategy`, `web_search`, the **Alpha Zoo** (`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`), and all 77 skills immediately.## Loading Tools from External MCP Servers@@ -181,7 +194,57 @@ Create `~/.vibe-trading/agent.json`:}```-Remote tools appear automatically in every `vibe-trading run` / `vibe-trading chat` call. They are injected after local tools under stable names: `mcp_<server>_<tool>`.+Ordinary external MCP tools appear automatically in every `vibe-trading run` / `vibe-trading chat` call. They are injected after local tools under stable names: `mcp_<server>_<tool>`. Live-broker MCP servers are consumed through the connector-scoped `trading_*` tools instead of exposing raw `mcp_<broker>_*` tools to the agent.++### Official IBKR MCP read-only probe++Add Interactive Brokers' official MCP endpoint as a read-only external server:++```json+{+ "mcpServers": {+ "ibkr": {+ "type": "streamableHttp",+ "url": "https://api.ibkr.com/v1/api/mcp",+ "auth": {+ "type": "oauth",+ "scopes": ["mcp.read"],+ "clientName": "Vibe-Trading",+ "cacheDir": "~/.vibe-trading/live/ibkr/oauth"+ },+ "enabledTools": ["*"]+ }+ }+}+```++Authorize it with `vibe-trading connector authorize ibkr-live-official-mcp-readonly`. The wildcard is accepted+only for this `mcp.read` probe. Generic `trading_account` and `trading_positions`+calls stay disabled until IBKR publishes stable read tool names that Vibe-Trading+can map safely; `mcp.write` requires an explicit tool allowlist and live+order-guard handling. If IBKR issues a pre-registered OAuth client, add+`clientId` and `clientSecret` inside `auth`.++### Trading connector profiles++The public trading surface is connector-first. Choose a connector profile, then+paper/live is just an attribute under that connector.++```bash+pip install "vibe-trading-ai[ibkr]"+vibe-trading connector list+vibe-trading connector use ibkr-paper-local+vibe-trading connector configure ibkr-paper-local --yes+vibe-trading connector check+vibe-trading connector account+vibe-trading connector positions+vibe-trading connector orders+vibe-trading connector quote AAPL+vibe-trading connector history AAPL --duration "30 D" --bar-size "1 day"+```++Default ports are TWS paper `7497`, IB Gateway paper `4002`, TWS live-readonly+`7496`, and IB Gateway live-readonly `4001`.### Config fieldsdiff --git a/agent/api_server.py b/agent/api_server.pyindex eaddfeba5..06e1e595e 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -10,6 +10,7 @@ import asyncioimport hmacimport ipaddressimport json+import loggingimport osimport reimport signal@@ -47,11 +48,7 @@ ENV_EXAMPLE_PATH = AGENT_DIR / ".env.example"MAX_UPLOAD_SIZE = 50 * 1024 * 1024 # 50 MB_UPLOAD_CHUNK_SIZE = 1024 * 1024 # 1 MB-# Rich console for colored logsconsole = Console()--import logging-logger = logging.getLogger(__name__)@@ -1245,20 +1242,20 @@ async def list_runs(limit: int = 20):"""List recent runs with summary fields."""limit = min(max(1, limit), 100)runs_dir = RUNS_DIR-+if not runs_dir.exists():return []-+run_dirs = sorted([d for d in runs_dir.iterdir() if d.is_dir()],key=lambda x: x.name,reverse=True)-+results = []for d in run_dirs[:limit]:run_id = d.name-+# Status from state.json or artifactsstatus_val = "unknown"state_file = _load_json_file(d / "state.json")@@ -1268,7 +1265,7 @@ async def list_runs(limit: int = 20):status_val = "success"elif (d / "review_report.json").exists():status_val = "success"-+# Parse created_at from run_id (YYYYMMDD_HHMMSS or run_YYYYMMDD_HHMMSS)created_at = "Unknown"if run_id.startswith("run_"):@@ -1283,11 +1280,11 @@ async def list_runs(limit: int = 20):d_str, t_str = parts[0], parts[1]if len(d_str) == 8 and len(t_str) == 6:created_at = f"{d_str[:4]}-{d_str[4:6]}-{d_str[6:8]} {t_str[:2]}:{t_str[2:4]}:{t_str[4:6]}"-+if created_at == "Unknown":mtime = datetime.fromtimestamp(d.stat().st_mtime)created_at = mtime.strftime("%Y-%m-%d %H:%M:%S")-+prompt = Nonereq_file = d / "req.json"planner_file = d / "planner_output.json"@@ -1304,12 +1301,12 @@ async def list_runs(limit: int = 20):prompt = planner_data.get("user_goal") or planner_data.get("goal")except (json.JSONDecodeError, OSError):pass-+if not prompt:prompt_file = d / "user_prompt.txt"if prompt_file.exists():prompt = prompt_file.read_text(encoding="utf-8").strip()-+total_return = Nonesharpe = Nonemetrics_file = d / "artifacts" / "metrics.csv"@@ -1324,7 +1321,7 @@ async def list_runs(limit: int = 20):breakexcept (OSError, ValueError):pass-+run_context = load_run_context(d)results.append(RunInfo(run_id=run_id,@@ -1337,7 +1334,7 @@ async def list_runs(limit: int = 20):start_date=run_context.get("start_date"),end_date=run_context.get("end_date"),))-+return results@@ -2689,6 +2686,15 @@ def _runner_liveness_state(broker: str) -> RunnerLivenessState:return RunnerLivenessState(broker=broker, alive=alive, last_tick=tick, last_tick_age_seconds=age)+def _connector_profile_for_broker(broker: str) -> str:+ """Return the public connector profile id for a live broker key."""+ if broker == "robinhood":+ return "robinhood-live-mcp"+ if broker == "ibkr":+ return "ibkr-live-official-mcp-readonly"+ return f"{broker}-live-mcp"++@app.get("/live/status", response_model=LiveStatusResponse, dependencies=[Depends(require_auth)])async def live_status_endpoint(broker: Optional[str] = Query(None, max_length=64)):"""Return live-channel status: auth, active mandate, runner liveness, halt (C2).@@ -2749,9 +2755,10 @@ async def live_authorize_endpoint(payload: LiveAuthorizeRequest):"broker": broker,"oauth_token_present": _oauth_token_present(broker),"instruction": (- f"Run `vibe-trading live authorize {broker}` from the device that will "- "hold the broker session. This opens the broker's own OAuth consent flow; "- "Vibe-Trading never holds funds and only relays intent once you authorize."+ f"Run `vibe-trading connector authorize {_connector_profile_for_broker(broker)}` "+ "from the device that will hold the broker session. This opens the "+ "broker's own OAuth consent flow; Vibe-Trading never holds funds and "+ "only relays intent once you authorize."),"note": ("The live channel stays read-only until the OAuth token is present AND a "@@ -2837,14 +2844,26 @@ def _build_live_runner(broker: str) -> Any:if _runner_factory is not None:return _runner_factory(broker)- from functools import partial-from src.live.audit import write_live_actionfrom src.live.runtime.reconcile import reconcilefrom src.live.runtime.runner import LiveRunnerfrom src.live.runtime.scheduler import Schedulerfrom src.live.runtime.triggers import Trigger+ from src.trading.service import runner_tool_name+ def _tool(operation: str) -> str:+ remote_tool = runner_tool_name(broker, operation)+ if remote_tool is None:+ raise LiveRunnerUnavailable(+ f"live runner for {broker!r} does not define remote tool {operation!r}"+ )+ return remote_tool++ positions_tool = _tool("positions")+ balance_tool = _tool("account")+ open_orders_tool = _tool("orders")+ submit_order_tool = _tool("submit_order")+ cancel_order_tool = _tool("cancel_order")adapter = _live_broker_adapter(broker) # raises LiveRunnerUnavailable if absentdef _read(remote_tool: str):@@ -2856,8 +2875,8 @@ def _build_live_runner(broker: str) -> Any:# Field mapping against the real Robinhood schema is finalized post-access# (L6); the action discriminator is broker-agnostic.if order.get("action") == "cancel":- return adapter.call_tool("cancel_order", order)- return adapter.call_tool("place_order", order)+ return adapter.call_tool(cancel_order_tool, order)+ return adapter.call_tool(submit_order_tool, order)svc = _get_session_service()session = svc.create_session(title=f"live-runner:{broker}")@@ -2892,9 +2911,9 @@ def _build_live_runner(broker: str) -> Any:broker,agent_caller=_agent_caller,reconcile_fn=reconcile,- read_positions=_read("get_positions"),- read_balance=_read("get_account"),- read_open_orders=_read("list_orders"),+ read_positions=_read(positions_tool),+ read_balance=_read(balance_tool),+ read_open_orders=_read(open_orders_tool),submit_fn=_submit,write_audit_fn=_audit_with_bus,scheduler=scheduler,@@ -2932,6 +2951,13 @@ async def start_runner_endpoint(payload: LiveRunnerControlRequest):broker = payload.broker.strip().lower()if not broker:raise HTTPException(status_code=400, detail="broker must not be blank")+ from src.trading.service import broker_supports_live_runner++ if not broker_supports_live_runner(broker):+ raise HTTPException(+ status_code=400,+ detail=f"live runner is not supported for {broker}",+ )existing = _runner_tasks.get(broker)if existing is not None and not existing.done():@@ -2954,9 +2980,15 @@ async def start_runner_endpoint(payload: LiveRunnerControlRequest):task = asyncio.ensure_future(_drive_runner(runner))_runner_tasks[broker] = task- task.add_done_callback(lambda t, b=broker: _runner_tasks.pop(b, None) if _runner_tasks.get(b) is t else None)+ task.add_done_callback(+ lambda t, b=broker: _runner_tasks.pop(b, None) if _runner_tasks.get(b) is t else None+ )- _emit_live_event(payload.session_id, "live.action", {"kind": "runner_started", "broker": broker})+ _emit_live_event(+ payload.session_id,+ "live.action",+ {"kind": "runner_started", "broker": broker},+ )return {"broker": broker, "started": True, "already_running": False}@@ -2971,13 +3003,24 @@ async def stop_runner_endpoint(payload: LiveRunnerControlRequest):broker = payload.broker.strip().lower()if not broker:raise HTTPException(status_code=400, detail="broker must not be blank")+ from src.trading.service import broker_supports_live_runner++ if not broker_supports_live_runner(broker):+ raise HTTPException(+ status_code=400,+ detail=f"live runner is not supported for {broker}",+ )task = _runner_tasks.pop(broker, None)if task is None or task.done():return {"broker": broker, "stopped": False, "was_running": False}task.cancel()- _emit_live_event(payload.session_id, "live.action", {"kind": "runner_stopped", "broker": broker})+ _emit_live_event(+ payload.session_id,+ "live.action",+ {"kind": "runner_stopped", "broker": broker},+ )return {"broker": broker, "stopped": True, "was_running": True}diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex a21dd9623..68cf506e1 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -12,6 +12,8 @@ Usage:from __future__ import annotations+# ruff: noqa: E402+import argparseimport csvimport json@@ -24,7 +26,7 @@ import timeimport uuidfrom datetime import datetimefrom pathlib import Path-from typing import Any, Dict, List, Optional+from typing import TYPE_CHECKING, Any, Dict, List, Optionalimport warningswarnings.filterwarnings("ignore", message=".*Importing verbose from langchain.*")@@ -61,6 +63,9 @@ RICH_TAG_PATTERN = re.compile(r"\[/?[^\]]+\]")from cli._version import __version__ as _VERSION # noqa: E402 — single source of truth+if TYPE_CHECKING:+ from src.agent.loop import AgentLoop+# Agent color assignments for swarm display_AGENT_STYLES = ["cyan", "magenta", "green", "yellow", "blue", "bright_red", "bright_cyan", "bright_magenta"]_agent_color_map: dict[str, str] = {}@@ -1977,7 +1982,7 @@ class _SwarmDashboard:color = "green" if self.final_status == "completed" else "red"title_status = f"[{color}]{self.final_status.upper()}[/{color}]"else:- title_status = f"[cyan]RUNNING[/cyan]"+ title_status = "[cyan]RUNNING[/cyan]"title = f"{self.preset} {title_status} {mins}:{secs:02d}"@@ -2145,7 +2150,7 @@ def cmd_swarm_run_live(preset: str, vars_json: Optional[str] = None) -> None:token_str = f"\nTokens: ~{tokens_in + tokens_out:,} (in: {tokens_in:,} out: {tokens_out:,})"if current.final_report:- console.print(f"\n[bold]\u2500\u2500 Final Report \u2500\u2500[/bold]")+ console.print("\n[bold]\u2500\u2500 Final Report \u2500\u2500[/bold]")console.print(current.final_report[:2000])console.print(f"\n[{status_color}]{current.status.value.upper()}[/{status_color}] Time: {mins}m {secs}s{token_str}")@@ -2696,27 +2701,15 @@ def cmd_provider_login(provider: str) -> int:# ----------------------------------------------------------------------------# Live trading channel (`vibe-trading live ...`) — SPEC.md §9 Decision 1.+# Live connector runtime internals.## Every state-changing verb here is a PRIVILEGED USER-SIDE action: none is# reachable from the agent loop / tool registry. There is deliberately NO# `live commit` verb — committing a mandate happens only through the consent-# flow's `POST /mandate/commit`, never the CLI (the CLI cannot create or widen-# a mandate). The verbs are:-#-# live authorize <broker> Desktop OAuth bootstrap (opens browser, writes-# the token cache). The only way to turn on the channel.-# live run [<broker>] Run the persistent runner in the FOREGROUND (tails-# the heartbeat; Ctrl+C stops it). SPEC §7.5.-# live start [<broker>] Start the persistent runner in the background.-# live stop [<broker>] Stop the persistent runner.-# live status Per-broker auth state + active mandate (limits +-# expires_at countdown) + halt state + runner-# liveness / last-tick (read-only).-# live mandate [<broker>] Print the committed mandate (read-only).-# live halt [<broker>] Trip the kill switch (writes the HALT sentinel).-# live resume [<broker>] Clear the halt (explicit privileged re-enable).-# live revoke <broker> Revoke OAuth token + delete the mandate (full off).+# flow's `POST /mandate/commit`, never a CLI command (the CLI cannot create or+# widen a mandate). The public CLI surface is `vibe-trading connector ...`;+# `cmd_live_*` helpers remain only as the broker-runtime implementation behind+# connector profiles.# ---------------------------------------------------------------------------_DEFAULT_LIVE_BROKER = "robinhood"@@ -2834,7 +2827,7 @@ def cmd_live_authorize(broker: str) -> int:)console.print("[dim]The channel is read-only until you commit a mandate and enable "- "order tools. Use `vibe-trading live status` to check state.[/dim]"+ "order tools. Use `vibe-trading connector status` to check state.[/dim]")return EXIT_SUCCESS@@ -3043,7 +3036,7 @@ def cmd_live_halt(broker: Optional[str] = None) -> int:With no broker, trips the global switch (halts all brokers); with a broker,trips only that broker's sentinel. The gate rejects all order attempts until- the switch is cleared with ``live resume``.+ the switch is cleared with ``vibe-trading connector resume``.Args:broker: Broker key, or ``None`` for the global switch.@@ -3058,7 +3051,7 @@ def cmd_live_halt(broker: Optional[str] = None) -> int:scope = target or "ALL brokers"console.print(f"[bold red]Live trading halted[/bold red] for {scope}.")console.print(f"[dim]Sentinel: {path}[/dim]")- console.print("[dim]Run `vibe-trading live resume` to re-enable.[/dim]")+ console.print("[dim]Run `vibe-trading connector resume` to re-enable.[/dim]")return EXIT_SUCCESS@@ -3166,7 +3159,7 @@ def cmd_live_start(broker: Optional[str] = None) -> int:runner_id = result.get("runner_id") or _runner_id_for(key)console.print(f"[green]Live runner started[/green] for {key} [dim]({runner_id})[/dim].")- console.print("[dim]Check it with `vibe-trading live status`.[/dim]")+ console.print("[dim]Check it with `vibe-trading connector status`.[/dim]")return EXIT_SUCCESS@@ -3175,7 +3168,7 @@ def cmd_live_stop(broker: Optional[str] = None) -> int:Relays a stop request to ``POST /live/runner/stop``. Stopping the runnerhalts autonomous activity but does NOT clear a tripped kill switch or revoke- the mandate — use ``live resume`` / ``live revoke`` for those.+ the mandate — use ``connector resume`` / ``connector revoke`` for those.Args:broker: Broker key, or ``None`` for the default broker (``robinhood``).@@ -3266,31 +3259,615 @@ def cmd_live_run(broker: Optional[str] = None) -> int:return EXIT_SUCCESS-def _dispatch_live(args: argparse.Namespace) -> int:- """Route a parsed ``live`` subcommand to its handler."""- sub = getattr(args, "live_command", None)+# ---------------------------------------------------------------------------+# Trading connector commands+# ---------------------------------------------------------------------------++def _profile_id(value: Optional[str]) -> Optional[str]:+ """Normalize an optional connector profile id."""+ if value is None:+ return None+ text = value.strip().lower()+ return text or None+++def _selected_profile_or(value: Optional[str]):+ """Resolve the selected or explicit trading profile."""+ from src.trading.profiles import profile_by_id++ return profile_by_id(_profile_id(value))+++def cmd_connector_list() -> int:+ """List selectable trading connector profiles."""+ from src.trading.profiles import list_profiles, load_selected_profile_id++ selected = load_selected_profile_id()+ table = Table(title="Trading Connectors", box=box.SIMPLE_HEAVY, show_lines=False)+ table.add_column("Selected", justify="center", width=8)+ table.add_column("Profile")+ table.add_column("Connector")+ table.add_column("Env")+ table.add_column("Transport")+ table.add_column("Capabilities")+ for profile in list_profiles():+ table.add_row(+ "[green]*[/green]" if profile.id == selected else "",+ f"[cyan]{profile.id}[/cyan]\n[dim]{profile.label}[/dim]",+ profile.connector,+ profile.environment,+ profile.transport,+ ", ".join(profile.capabilities),+ )+ console.print(table)+ console.print("[dim]Use `vibe-trading connector use <profile>` to set the default profile.[/dim]")+ return EXIT_SUCCESS+++def cmd_connector_use(profile_id: str) -> int:+ """Select the default trading connector profile."""+ from src.trading.profiles import profile_by_id, save_selected_profile_id++ try:+ profile = profile_by_id(profile_id)+ path = save_selected_profile_id(profile.id)+ except ValueError as exc:+ console.print(f"[red]{exc}[/red]")+ return EXIT_USAGE_ERROR+ console.print(f"[green]Selected trading connector[/green] {profile.id}")+ console.print(f"[dim]{profile.label} · {profile.environment} · {profile.transport}[/dim]")+ console.print(f"[dim]Config: {path}[/dim]")+ return EXIT_SUCCESS+++def cmd_connector_configure(+ profile_id: str,+ *,+ host: str = "127.0.0.1",+ port: int | None = None,+ client_id: int = 77,+ account: str | None = None,+ yes: bool = False,+) -> int:+ """Configure a local connector profile."""+ from src.trading.connectors.ibkr.local import IBKRLocalConfig, config_path, save_config++ try:+ profile = _selected_profile_or(profile_id)+ except ValueError as exc:+ console.print(f"[red]{exc}[/red]")+ return EXIT_USAGE_ERROR+ if profile.transport != "local_tws" or profile.connector != "ibkr":+ console.print(f"[red]{profile.id} is not a local TWS/Gateway profile.[/red]")+ return EXIT_USAGE_ERROR++ path = config_path()+ if path.exists() and not yes:+ console.print(f"[yellow]Local connector config already exists:[/yellow] {path}")+ try:+ if not Confirm.ask("Overwrite it?", default=False):+ console.print("[dim]Aborted.[/dim]")+ return EXIT_SUCCESS+ except EOFError:+ console.print("[dim]No input available; use --yes for non-interactive setup.[/dim]")+ return EXIT_USAGE_ERROR++ cfg = IBKRLocalConfig.from_mapping(+ {+ **profile.config,+ "host": host,+ "port": port or profile.config.get("port"),+ "clientId": client_id,+ "account": account,+ "readonly": True,+ }+ )+ path = save_config(cfg)+ console.print(f"[green]Configured[/green] {profile.id} [dim]({path})[/dim]")+ console.print(f"[dim]Run `vibe-trading connector check {profile.id}` to verify it.[/dim]")+ return EXIT_SUCCESS+++def cmd_connector_check(+ profile_id: Optional[str] = None,+ *,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ account: str | None = None,+) -> int:+ """Check selected or explicit trading connector profile."""+ from src.trading.service import check_connection++ try:+ profile = _selected_profile_or(profile_id)+ report = check_connection(profile.id, host=host, port=port, client_id=client_id, account=account)+ except Exception as exc: # noqa: BLE001+ console.print(f"[red]Connector check failed:[/red] {exc}")+ return EXIT_RUN_FAILED++ title = f"Trading Connector: {profile.id}"+ if profile.transport == "local_tws":+ table = Table(title=title, box=box.SIMPLE_HEAVY, show_lines=False)+ table.add_column("Endpoint")+ table.add_column("Profile")+ table.add_column("Address")+ table.add_column("State")+ for row in report.get("ports", []):+ open_state = "[green]open[/green]" if row.get("open") else "[dim]closed[/dim]"+ table.add_row(+ str(row.get("label")),+ str(row.get("profile")),+ f"{row.get('host')}:{row.get('port')}",+ open_state,+ )+ console.print(table)+ target = report.get("target", {})+ target_state = "open" if target.get("open") else "closed"+ console.print(f"Target: [bold]{target.get('host')}:{target.get('port')}[/bold] ({target_state})")+ sdk = report.get("sdk", {})+ if not sdk.get("installed"):+ console.print("[yellow]Missing optional dependency:[/yellow] pip install 'ib_async>=2.0'")+ if report.get("account"):+ accounts = ", ".join(report["account"].get("accounts", [])) or "(none)"+ console.print(f"Accounts: [cyan]{rich_escape(accounts)}[/cyan]")+ else:+ table = Table(title=title, box=box.SIMPLE_HEAVY, show_lines=False)+ table.add_column("Field", style="cyan")+ table.add_column("Value")+ table.add_row("Connector", profile.connector)+ table.add_row("Environment", profile.environment)+ table.add_row("Transport", profile.transport)+ table.add_row("Configured", "yes" if report.get("configured") else "[red]no[/red]")+ table.add_row("OAuth token", "present" if report.get("oauth_token_present") else "[yellow]missing[/yellow]")+ table.add_row("Capabilities", ", ".join(report.get("capabilities", [])))+ console.print(table)++ if report.get("status") not in {"ok"}:+ console.print(f"[red]{rich_escape(str(report.get('error') or report.get('status') or 'not ready'))}[/red]")+ return EXIT_RUN_FAILED+ console.print("[green]Connector profile is ready.[/green]")+ return EXIT_SUCCESS+++def _print_connector_account(result: dict[str, Any]) -> int:+ accounts = ", ".join(result.get("accounts", [])) or "(none)"+ console.print(f"Accounts: [cyan]{rich_escape(accounts)}[/cyan]")+ rows = result.get("summary", [])+ if not rows:+ console.print("[dim]No account summary returned.[/dim]")+ return EXIT_SUCCESS+ table = Table(title=f"Account Summary · {result.get('profile_id')}", box=box.SIMPLE_HEAVY, show_lines=False)+ table.add_column("Account")+ table.add_column("Tag")+ table.add_column("Value", justify="right")+ table.add_column("Currency")+ for row in rows:+ table.add_row(+ str(row.get("account") or ""),+ str(row.get("tag") or ""),+ str(row.get("value") or ""),+ str(row.get("currency") or ""),+ )+ console.print(table)+ return EXIT_SUCCESS+++def cmd_connector_account(+ profile_id: Optional[str] = None,+ *,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ account: str | None = None,+) -> int:+ """Print account summary from a connector profile."""+ from src.trading.service import get_account++ try:+ result = get_account(_profile_id(profile_id), host=host, port=port, client_id=client_id, account=account)+ except Exception as exc: # noqa: BLE001+ console.print(f"[red]Connector account failed:[/red] {exc}")+ return EXIT_RUN_FAILED+ if result.get("status") == "error":+ console.print(f"[red]{rich_escape(str(result.get('error')))}[/red]")+ return EXIT_RUN_FAILED+ return _print_connector_account(result)+++def cmd_connector_positions(+ profile_id: Optional[str] = None,+ *,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ account: str | None = None,+) -> int:+ """Print positions from a connector profile."""+ from src.trading.service import get_positions++ try:+ result = get_positions(_profile_id(profile_id), host=host, port=port, client_id=client_id, account=account)+ except Exception as exc: # noqa: BLE001+ console.print(f"[red]Connector positions failed:[/red] {exc}")+ return EXIT_RUN_FAILED+ if result.get("status") == "error":+ console.print(f"[red]{rich_escape(str(result.get('error')))}[/red]")+ return EXIT_RUN_FAILED+ rows = result.get("positions", [])+ if not rows:+ console.print("[dim]No positions returned.[/dim]")+ return EXIT_SUCCESS+ table = Table(title=f"Positions · {result.get('profile_id')}", box=box.SIMPLE_HEAVY, show_lines=False)+ table.add_column("Account")+ table.add_column("Symbol")+ table.add_column("Type")+ table.add_column("Qty", justify="right")+ table.add_column("Avg Cost", justify="right")+ table.add_column("Currency")+ for row in rows:+ table.add_row(+ str(row.get("account") or ""),+ str(row.get("local_symbol") or row.get("symbol") or ""),+ str(row.get("sec_type") or ""),+ str(row.get("position") or ""),+ str(row.get("avg_cost") or ""),+ str(row.get("currency") or ""),+ )+ console.print(table)+ return EXIT_SUCCESS+++def cmd_connector_orders(+ profile_id: Optional[str] = None,+ *,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ account: str | None = None,+ include_executions: bool = False,+) -> int:+ """Print open orders from a connector profile."""+ from src.trading.service import get_open_orders++ try:+ result = get_open_orders(+ _profile_id(profile_id),+ host=host,+ port=port,+ client_id=client_id,+ account=account,+ include_executions=include_executions,+ )+ except Exception as exc: # noqa: BLE001+ console.print(f"[red]Connector orders failed:[/red] {exc}")+ return EXIT_RUN_FAILED+ if result.get("status") == "error":+ console.print(f"[red]{rich_escape(str(result.get('error')))}[/red]")+ return EXIT_RUN_FAILED+ orders = result.get("open_orders", [])+ if not orders:+ console.print("[dim]No open orders returned.[/dim]")+ return EXIT_SUCCESS+ table = Table(title=f"Open Orders · {result.get('profile_id')}", box=box.SIMPLE_HEAVY, show_lines=False)+ table.add_column("Account")+ table.add_column("Symbol")+ table.add_column("Action")+ table.add_column("Type")+ table.add_column("Qty", justify="right")+ table.add_column("Limit", justify="right")+ table.add_column("Status")+ for row in orders:+ contract = row.get("contract") or {}+ order = row.get("order") or row+ order_status = row.get("status") or {}+ table.add_row(+ str(order.get("account") or ""),+ str(contract.get("local_symbol") or contract.get("symbol") or ""),+ str(order.get("action") or ""),+ str(order.get("order_type") or ""),+ str(order.get("total_quantity") or ""),+ str(order.get("limit_price") or ""),+ str(order_status.get("status") or ""),+ )+ console.print(table)+ return EXIT_SUCCESS+++def cmd_connector_quote(+ symbol: str,+ profile_id: Optional[str] = None,+ *,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ account: str | None = None,+ exchange: str = "SMART",+ currency: str = "USD",+ sec_type: str = "STK",+) -> int:+ """Print a quote from a connector profile."""+ from src.trading.service import get_quote++ try:+ result = get_quote(+ symbol,+ _profile_id(profile_id),+ host=host,+ port=port,+ client_id=client_id,+ account=account,+ exchange=exchange,+ currency=currency,+ sec_type=sec_type,+ )+ except Exception as exc: # noqa: BLE001+ console.print(f"[red]Connector quote failed:[/red] {exc}")+ return EXIT_RUN_FAILED+ if result.get("status") == "error":+ console.print(f"[red]{rich_escape(str(result.get('error')))}[/red]")+ return EXIT_RUN_FAILED+ quote = result.get("quote", {})+ table = Table(title=f"Quote {result.get('symbol', symbol)} · {result.get('profile_id')}", box=box.SIMPLE_HEAVY)+ table.add_column("Bid", justify="right")+ table.add_column("Ask", justify="right")+ table.add_column("Last", justify="right")+ table.add_column("Close", justify="right")+ table.add_column("Volume", justify="right")+ table.add_row(+ str(quote.get("bid") or ""),+ str(quote.get("ask") or ""),+ str(quote.get("last") or ""),+ str(quote.get("close") or ""),+ str(quote.get("volume") or ""),+ )+ console.print(table)+ return EXIT_SUCCESS+++def cmd_connector_history(+ symbol: str,+ profile_id: Optional[str] = None,+ *,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ account: str | None = None,+ exchange: str = "SMART",+ currency: str = "USD",+ sec_type: str = "STK",+ duration: str = "30 D",+ bar_size: str = "1 day",+ what_to_show: str = "TRADES",+ use_rth: bool = True,+) -> int:+ """Print historical bars from a connector profile."""+ from src.trading.service import get_history++ try:+ result = get_history(+ symbol,+ _profile_id(profile_id),+ host=host,+ port=port,+ client_id=client_id,+ account=account,+ exchange=exchange,+ currency=currency,+ sec_type=sec_type,+ duration=duration,+ bar_size=bar_size,+ what_to_show=what_to_show,+ use_rth=use_rth,+ )+ except Exception as exc: # noqa: BLE001+ console.print(f"[red]Connector history failed:[/red] {exc}")+ return EXIT_RUN_FAILED+ if result.get("status") == "error":+ console.print(f"[red]{rich_escape(str(result.get('error')))}[/red]")+ return EXIT_RUN_FAILED+ rows = result.get("bars", [])+ if not rows:+ console.print("[dim]No historical bars returned.[/dim]")+ return EXIT_SUCCESS+ table = Table(title=f"History {result.get('symbol', symbol)} · {result.get('profile_id')}", box=box.SIMPLE_HEAVY)+ table.add_column("Date")+ table.add_column("Open", justify="right")+ table.add_column("High", justify="right")+ table.add_column("Low", justify="right")+ table.add_column("Close", justify="right")+ table.add_column("Volume", justify="right")+ for row in rows[-20:]:+ table.add_row(+ str(row.get("date") or ""),+ str(row.get("open") or ""),+ str(row.get("high") or ""),+ str(row.get("low") or ""),+ str(row.get("close") or ""),+ str(row.get("volume") or ""),+ )+ console.print(table)+ return EXIT_SUCCESS+++def _live_profile_connector(+ profile_id: Optional[str],+ *,+ require_runner: bool = False,+) -> tuple[int, Optional[str]]:+ """Resolve a profile to a live-capable connector key."""+ try:+ profile = _selected_profile_or(profile_id)+ except ValueError as exc:+ console.print(f"[red]{exc}[/red]")+ return EXIT_USAGE_ERROR, None+ if profile.environment != "live" or profile.transport != "remote_mcp":+ console.print(f"[red]{profile.id} is not a live remote MCP connector profile.[/red]")+ return EXIT_USAGE_ERROR, None+ if require_runner:+ from src.trading.service import profile_supports_live_runner++ if not profile_supports_live_runner(profile):+ console.print(f"[red]{profile.id} does not support live runner management.[/red]")+ return EXIT_USAGE_ERROR, None+ return EXIT_SUCCESS, profile.connector+++def cmd_connector_authorize(profile_id: Optional[str]) -> int:+ """Authorize a remote MCP connector profile."""+ code, broker = _live_profile_connector(profile_id)+ if code != EXIT_SUCCESS or broker is None:+ return code+ return cmd_live_authorize(broker)+++def cmd_connector_status(profile_id: Optional[str]) -> int:+ """Show connector status."""+ try:+ profile = _selected_profile_or(profile_id)+ except ValueError as exc:+ console.print(f"[red]{exc}[/red]")+ return EXIT_USAGE_ERROR+ if profile.environment == "live" and profile.transport == "remote_mcp":+ check_code = cmd_connector_check(profile.id)+ if check_code != EXIT_SUCCESS:+ return check_code+ return cmd_live_status(profile.connector)+ return cmd_connector_check(profile.id)+++def cmd_connector_start(profile_id: Optional[str]) -> int:+ """Start a live remote MCP connector runner."""+ code, broker = _live_profile_connector(profile_id, require_runner=True)+ if code != EXIT_SUCCESS or broker is None:+ return code+ return cmd_live_start(broker)+++def cmd_connector_stop(profile_id: Optional[str]) -> int:+ """Stop a live remote MCP connector runner."""+ code, broker = _live_profile_connector(profile_id, require_runner=True)+ if code != EXIT_SUCCESS or broker is None:+ return code+ return cmd_live_stop(broker)+++def cmd_connector_halt(profile_id: Optional[str]) -> int:+ """Trip the halt switch for a live remote MCP connector profile."""+ code, broker = _live_profile_connector(profile_id, require_runner=True)+ if code != EXIT_SUCCESS or broker is None:+ return code+ return cmd_live_halt(broker)+++def cmd_connector_resume(profile_id: Optional[str]) -> int:+ """Clear the halt switch for a live remote MCP connector profile."""+ code, broker = _live_profile_connector(profile_id, require_runner=True)+ if code != EXIT_SUCCESS or broker is None:+ return code+ return cmd_live_resume(broker)+++def cmd_connector_revoke(profile_id: Optional[str]) -> int:+ """Revoke a live remote MCP connector profile."""+ code, broker = _live_profile_connector(profile_id)+ if code != EXIT_SUCCESS or broker is None:+ return code+ return cmd_live_revoke(broker)+++def _dispatch_connector(args: argparse.Namespace) -> int:+ """Route parsed ``connector`` subcommands."""+ sub = getattr(args, "connector_command", None)+ if sub == "list":+ return cmd_connector_list()+ if sub == "use":+ return cmd_connector_use(args.profile)+ if sub == "configure":+ return cmd_connector_configure(+ args.profile,+ host=args.host,+ port=args.port,+ client_id=args.client_id,+ account=args.account,+ yes=args.yes,+ )+ if sub == "check":+ return cmd_connector_check(+ args.profile,+ host=args.host,+ port=args.port,+ client_id=args.client_id,+ account=args.account,+ )+ if sub == "account":+ return cmd_connector_account(+ args.profile,+ host=args.host,+ port=args.port,+ client_id=args.client_id,+ account=args.account,+ )+ if sub == "positions":+ return cmd_connector_positions(+ args.profile,+ host=args.host,+ port=args.port,+ client_id=args.client_id,+ account=args.account,+ )+ if sub == "orders":+ return cmd_connector_orders(+ args.profile,+ host=args.host,+ port=args.port,+ client_id=args.client_id,+ account=args.account,+ include_executions=args.include_executions,+ )+ if sub == "quote":+ return cmd_connector_quote(+ args.symbol,+ args.profile,+ host=args.host,+ port=args.port,+ client_id=args.client_id,+ account=args.account,+ exchange=args.exchange,+ currency=args.currency,+ sec_type=args.sec_type,+ )+ if sub == "history":+ return cmd_connector_history(+ args.symbol,+ args.profile,+ host=args.host,+ port=args.port,+ client_id=args.client_id,+ account=args.account,+ exchange=args.exchange,+ currency=args.currency,+ sec_type=args.sec_type,+ duration=args.duration,+ bar_size=args.bar_size,+ what_to_show=args.what_to_show,+ use_rth=not args.no_rth,+ )if sub == "authorize":- return cmd_live_authorize(args.live_broker)- if sub == "run":- return cmd_live_run(getattr(args, "live_broker", None))+ return cmd_connector_authorize(args.profile)+ if sub == "status":+ return cmd_connector_status(args.profile)if sub == "start":- return cmd_live_start(getattr(args, "live_broker", None))+ return cmd_connector_start(args.profile)if sub == "stop":- return cmd_live_stop(getattr(args, "live_broker", None))- if sub == "status":- return cmd_live_status(getattr(args, "live_broker", None))- if sub == "mandate":- return cmd_live_mandate(getattr(args, "live_broker", None))+ return cmd_connector_stop(args.profile)if sub == "halt":- return cmd_live_halt(getattr(args, "live_broker", None))+ return cmd_connector_halt(args.profile)if sub == "resume":- return cmd_live_resume(getattr(args, "live_broker", None))+ return cmd_connector_resume(args.profile)if sub == "revoke":- return cmd_live_revoke(args.live_broker)- console.print(- "[red]live requires a subcommand.[/red] "- "Try: vibe-trading live status"- )+ return cmd_connector_revoke(args.profile)+ console.print("[red]connector requires a subcommand.[/red] Try: vibe-trading connector list")return EXIT_USAGE_ERROR@@ -3381,69 +3958,87 @@ def _build_parser() -> argparse.ArgumentParser:memory_forget_parser.add_argument("name", help="Memory title or filename stem")memory_forget_parser.add_argument("-y", "--yes", action="store_true", help="Skip confirmation prompt")- # Live trading channel (SPEC.md §9 Decision 1). Every verb is a privileged- # user-side action; there is intentionally NO `live commit` verb.- live_parser = subparsers.add_parser("live", help="Manage the live trading channel")- live_subparsers = live_parser.add_subparsers(dest="live_command")+ connector_parser = subparsers.add_parser("connector", help="Manage trading connector profiles")+ connector_subparsers = connector_parser.add_subparsers(dest="connector_command")- live_authorize = live_subparsers.add_parser(- "authorize", help="Desktop OAuth bootstrap — opens browser, turns the channel on"- )- live_authorize.add_argument("live_broker", metavar="broker", help="Broker key, e.g. robinhood")+ connector_subparsers.add_parser("list", help="List selectable connector profiles")- live_run = live_subparsers.add_parser(- "run", help="Run the persistent runner in the foreground (Ctrl+C to stop)"- )- live_run.add_argument(- "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: robinhood)"- )-- live_start = live_subparsers.add_parser(- "start", help="Start the persistent runner in the background"- )- live_start.add_argument(- "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: robinhood)"- )-- live_stop = live_subparsers.add_parser(- "stop", help="Stop the persistent runner"- )- live_stop.add_argument(- "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: robinhood)"- )-- live_status = live_subparsers.add_parser(- "status", help="Show auth state, active mandate, and halt state (read-only)"- )- live_status.add_argument(- "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: robinhood)"- )-- live_mandate = live_subparsers.add_parser(- "mandate", help="Print the committed mandate (read-only)"- )- live_mandate.add_argument(- "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: robinhood)"- )-- live_halt = live_subparsers.add_parser(- "halt", help="Trip the kill switch (writes the HALT sentinel)"- )- live_halt.add_argument(- "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: global)"- )+ connector_use = connector_subparsers.add_parser("use", help="Select the default connector profile")+ connector_use.add_argument("profile", help="Profile id, e.g. ibkr-paper-local")- live_resume = live_subparsers.add_parser(- "resume", help="Clear the halt (explicit privileged re-enable)"- )- live_resume.add_argument(- "live_broker", metavar="broker", nargs="?", default=None, help="Broker key (default: global)"- )-- live_revoke = live_subparsers.add_parser(- "revoke", help="Revoke OAuth token + delete mandate (full off)"- )- live_revoke.add_argument("live_broker", metavar="broker", help="Broker key, e.g. robinhood")+ def _add_connector_profile_arg(p: argparse.ArgumentParser, *, required: bool = False) -> None:+ if required:+ p.add_argument("profile", help="Connector profile id")+ else:+ p.add_argument("profile", nargs="?", default=None, help="Connector profile id (default: selected)")++ def _add_connector_local(p: argparse.ArgumentParser) -> None:+ p.add_argument("--host", default=None)+ p.add_argument("--port", type=int, default=None)+ p.add_argument("--client-id", dest="client_id", type=int, default=None)+ p.add_argument("--account", default=None, help="Optional account code")++ def _add_connector_contract(p: argparse.ArgumentParser) -> None:+ p.add_argument("--exchange", default="SMART")+ p.add_argument("--currency", default="USD")+ p.add_argument("--sec-type", dest="sec_type", default="STK")++ connector_configure = connector_subparsers.add_parser("configure", help="Configure a local connector profile")+ _add_connector_profile_arg(connector_configure, required=True)+ connector_configure.add_argument("--host", default="127.0.0.1")+ connector_configure.add_argument("--port", type=int, default=None)+ connector_configure.add_argument("--client-id", dest="client_id", type=int, default=77)+ connector_configure.add_argument("--account", default=None)+ connector_configure.add_argument("-y", "--yes", action="store_true", help="Overwrite without prompting")++ connector_check = connector_subparsers.add_parser("check", help="Check selected connector readiness")+ _add_connector_profile_arg(connector_check)+ _add_connector_local(connector_check)++ connector_status = connector_subparsers.add_parser("status", help="Show selected connector status")+ _add_connector_profile_arg(connector_status)++ connector_authorize = connector_subparsers.add_parser("authorize", help="Authorize a remote MCP connector profile")+ _add_connector_profile_arg(connector_authorize)++ connector_account = connector_subparsers.add_parser("account", help="Read account summary")+ _add_connector_profile_arg(connector_account)+ _add_connector_local(connector_account)++ connector_positions = connector_subparsers.add_parser("positions", help="Read current positions")+ _add_connector_profile_arg(connector_positions)+ _add_connector_local(connector_positions)++ connector_orders = connector_subparsers.add_parser("orders", help="Read open orders")+ _add_connector_profile_arg(connector_orders)+ _add_connector_local(connector_orders)+ connector_orders.add_argument("--include-executions", action="store_true")++ connector_quote = connector_subparsers.add_parser("quote", help="Read a quote snapshot")+ connector_quote.add_argument("symbol")+ _add_connector_profile_arg(connector_quote)+ _add_connector_local(connector_quote)+ _add_connector_contract(connector_quote)++ connector_history = connector_subparsers.add_parser("history", help="Read historical bars")+ connector_history.add_argument("symbol")+ _add_connector_profile_arg(connector_history)+ _add_connector_local(connector_history)+ _add_connector_contract(connector_history)+ connector_history.add_argument("--duration", default="30 D")+ connector_history.add_argument("--bar-size", dest="bar_size", default="1 day")+ connector_history.add_argument("--what-to-show", dest="what_to_show", default="TRADES")+ connector_history.add_argument("--no-rth", action="store_true", help="Include outside-regular-hours data when available")++ for name, help_text in (+ ("start", "Start the selected live connector runner"),+ ("stop", "Stop the selected live connector runner"),+ ("halt", "Trip the selected live connector kill switch"),+ ("resume", "Clear the selected live connector kill switch"),+ ("revoke", "Revoke the selected live connector OAuth token and mandate"),+ ):+ p = connector_subparsers.add_parser(name, help=help_text)+ _add_connector_profile_arg(p)# Alpha Zoo subcommands (registered via cli_handlers.add_subparser)from src.factors.cli_handlers import add_subparser as _add_alpha_subparser@@ -3948,8 +4543,8 @@ def main(argv: list[str] | None = None) -> int:if args.command == "hypothesis":from src.hypotheses.cli_handlers import dispatch as _hyp_dispatchreturn _coerce_exit_code(_hyp_dispatch(args))- if args.command == "live":- return _coerce_exit_code(_dispatch_live(args))+ if args.command == "connector":+ return _coerce_exit_code(_dispatch_connector(args))if args.command == "memory":if args.memory_command == "list":return _coerce_exit_code(cmd_memory_list(args.memory_type))diff --git a/agent/cli/main.py b/agent/cli/main.pyindex 4afd452c1..46175ae34 100644--- a/agent/cli/main.py+++ b/agent/cli/main.py@@ -34,17 +34,17 @@ from cli.theme import Theme, get_consoledef _register_live_slash_commands() -> None:- """Surface the live-trading slash commands in the shared registry.+ """Surface connector live-trading slash commands in the shared registry.- Discoverability fix (SPEC.md Consent §4 + §9 audit): ``/live``, ``/halt`` and- ``/resume`` are privileged kill-switch / runner surface actions intercepted+ Discoverability fix (SPEC.md Consent §4 + §9 audit): ``/connector``,+ ``/halt`` and ``/resume`` are privileged kill-switch / runner surface actions interceptedin the REPL input path (never dispatched to the model), so they were absentfrom the slash registry — meaning ``/help``, the typeahead completer, and thefuzzy matcher never listed them. We append them here, at this module's importtime, which runs on every interactive startup *before* the lazily-imported``cli.commands.help`` / ``cli.completer`` first read the registry. Both ofthose read ``slash_router.SLASH_COMMANDS`` (help) / call ``match_commands``- (completer) which resolve the live module attribute, so the single+ (completer) which resolve the connector module attribute, so the singlereassignment here surfaces the commands in all three places.The registry is a tuple of frozen dataclasses, so we build a NEW tuple rather@@ -56,7 +56,7 @@ def _register_live_slash_commands() -> None:existing = {cmd.name for cmd in slash_router.SLASH_COMMANDS}additions = (slash_router.Command(- "live", "Live trading channel (status / run / halt)", "cli.main"+ "connector", "Trading connector profiles (status / start / halt)", "cli.main"),slash_router.Command("halt", "Kill switch — halt ALL live trading now", "cli.main"@@ -68,7 +68,7 @@ def _register_live_slash_commands() -> None:new = tuple(cmd for cmd in additions if cmd.name not in existing)if not new:return- # Insert the live group just before ``quit`` (the conventional last row) so+ # Insert the connector group just before ``quit`` (the conventional last row) so# the kill switch sits with the other safety-relevant commands.commands = list(slash_router.SLASH_COMMANDS)quit_idx = next(@@ -272,12 +272,12 @@ def _show_banner() -> None:console = get_console()print_banner(console, **stats)# Discoverability one-liner (SPEC.md §9 audit): point users at the- # live-trading channel + its CLI surface. Live is opt-in and read-only by+ # connector channel + its CLI surface. Live profiles are opt-in and read-only by# default, so this is a pointer, not an enablement.console.print(" [dim]Live trading (opt-in, read-only by default): "- "[/dim][bold]/live[/bold][dim] in chat · "- "[/dim][bold]vibe-trading live --help[/bold][dim] · "+ "[/dim][bold]/connector[/bold][dim] in chat · "+ "[/dim][bold]vibe-trading connector --help[/bold][dim] · ""[/dim][bold]/halt[/bold][dim] = kill switch.[/dim]")console.print()@@ -811,7 +811,7 @@ def _trip_halt_from_repl(console: Any, *, reason: str) -> None:returnconsole.print("[bold red]Live trading halted[/bold red] — all live order tools are now "- "disabled until you run [bold]/resume[/bold] or [bold]vibe-trading live resume[/bold]."+ "disabled until you run [bold]/resume[/bold] or [bold]vibe-trading connector resume[/bold].")console.print(f"[dim]HALT sentinel: {path}[/dim]")@@ -821,7 +821,7 @@ def _clear_halt_from_repl(console: Any) -> None:Clearing the halt is a privileged surface action — an explicit re-enable,never an agent tool (SPEC.md Consent §4). It is intercepted in the input- path so the model never performs it. Mirrors ``vibe-trading live resume``+ path so the model never performs it. Mirrors ``vibe-trading connector resume``with no broker (the global scope).Args:@@ -842,35 +842,35 @@ def _clear_halt_from_repl(console: Any) -> None:console.print("[dim]No active global halt to clear.[/dim]")-def _run_live_command_from_repl(console: Any, args: list[str]) -> None:- """Run a ``/live ...`` subcommand from the REPL via the legacy dispatcher.+def _run_connector_command_from_repl(console: Any, args: list[str]) -> None:+ """Run a ``/connector ...`` subcommand from the REPL via the dispatcher.- ``/live`` is a thin in-REPL bridge to the ``vibe-trading live`` subcommand- group (SPEC.md §9 Decision 1): ``/live status``, ``/live run``,- ``/live start``, ``/live stop``, ``/live mandate``, etc. It parses the+ ``/connector`` is a thin in-REPL bridge to the ``vibe-trading connector``+ subcommand group (SPEC.md §9 Decision 1): ``/connector status``,+ ``/connector start``, ``/connector stop``, ``/connector halt``, etc. It parses thearguments through the same argparse surface as the non-interactive CLI anddispatches to the same privileged handlers — none of which is an agent tool.- A bare ``/live`` defaults to ``status`` so the most common read is one+ A bare ``/connector`` defaults to ``status`` so the most common read is onekeystroke away.Args:console: Rich console for error messages.- args: Tokens following ``/live`` (e.g. ``["status", "robinhood"]``).+ args: Tokens following ``/connector`` (e.g. ``["status", "robinhood-live-mcp"]``)."""- from cli._legacy import _build_parser, _dispatch_live+ from cli._legacy import _build_parser, _dispatch_connector- argv = ["live", *(args or ["status"])]+ argv = ["connector", *(args or ["status"])]parser = _build_parser()try:parsed = parser.parse_args(argv)except SystemExit:# argparse already printed usage to stderr; keep the REPL alive.- console.print("[dim]Usage: /live [status|run|start|stop|mandate|halt|resume|revoke][/dim]")+ console.print("[dim]Usage: /connector [list|status|start|stop|halt|resume|revoke][/dim]")returntry:- _dispatch_live(parsed)- except Exception as exc: # noqa: BLE001 — never let a live command kill the loop- console.print(f"[bold red]/live failed:[/bold red] {exc}")+ _dispatch_connector(parsed)+ except Exception as exc: # noqa: BLE001 — never let a connector command kill the loop+ console.print(f"[bold red]/connector failed:[/bold red] {exc}")def _is_numeric_pick(text: str) -> Optional[int]:@@ -1130,7 +1130,7 @@ def _interactive_loop(max_iter: int) -> int:# Slash command path.if text.startswith("/"):- # /halt /stop /resume /live are privileged live-trading surface+ # /halt /stop /resume /connector are privileged live-trading surface# actions handled in the input path, never dispatched to the model# (SPEC.md Consent §4 / §9 Decision 1).slash_tokens = text.lstrip("/").split()@@ -1142,8 +1142,8 @@ def _interactive_loop(max_iter: int) -> int:if slash_name == "resume":_clear_halt_from_repl(console)continue- if slash_name == "live":- _run_live_command_from_repl(console, slash_tokens[1:])+ if slash_name == "connector":+ _run_connector_command_from_repl(console, slash_tokens[1:])continuerc = _dispatch_slash(text, ctx)if rc == 2:diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex eb275008b..c5f1ecd40 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -1,8 +1,10 @@#!/usr/bin/env python3-"""Vibe-Trading MCP Server — expose 22 finance research tools to any MCP client.+"""Vibe-Trading MCP Server — expose finance research tools to any MCP client.Works with OpenClaw, Claude Desktop, Cursor, and any MCP-compatible client.-Zero API key required for HK/US/crypto markets (yfinance, OKX, AKShare are free).+Zero API key required for HK/US/crypto research markets (yfinance, OKX,+AKShare are free). Trading connector tools are profile-scoped and require the+selected connector's own local app or OAuth setup.Usage:python mcp_server.py # stdio transport (default)@@ -26,6 +28,8 @@ Claude Desktop config:from __future__ import annotations+# ruff: noqa: E402+import jsonimport loggingimport math@@ -621,6 +625,240 @@ def read_file(path: str) -> str:return registry.execute("read_file", {"path": path})+# ---------------------------------------------------------------------------+# Trading connector tools+# ---------------------------------------------------------------------------+++def _trading_common_args(+ *,+ connection: str | None = None,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ account: str | None = None,+) -> dict[str, Any]:+ """Build shared optional trading connector arguments."""+ payload: dict[str, Any] = {}+ if connection:+ payload["connection"] = connection+ if host:+ payload["host"] = host+ if port is not None:+ payload["port"] = port+ if client_id is not None:+ payload["client_id"] = client_id+ if account:+ payload["account"] = account+ return payload+++def trading_connections() -> str:+ """List selectable trading connector profiles.++ The connector is the first-level choice. Paper/live is an attribute of each+ profile under that connector.+ """+ registry = _get_registry()+ return registry.execute("trading_connections", {})+++def trading_select_connection(connection: str) -> str:+ """Select the default trading connector profile for later trading_* calls.++ Args:+ connection: Profile id, e.g. ``ibkr-paper-local`` or ``robinhood-live-mcp``.+ """+ registry = _get_registry()+ return registry.execute("trading_select_connection", {"connection": connection})+++def trading_check(+ connection: str | None = None,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ account: str | None = None,+) -> str:+ """Check whether a trading connector profile is configured and reachable.++ This never places orders. For local profiles, it checks the user's local+ app/socket. For remote MCP profiles, it reports config and OAuth-token+ presence without returning secrets.++ Args:+ connection: Optional profile id. Defaults to the selected profile.+ host: Optional local host override.+ port: Optional local socket port override.+ client_id: Optional local client id override.+ account: Optional account code filter.+ """+ registry = _get_registry()+ return registry.execute(+ "trading_check",+ _trading_common_args(connection=connection, host=host, port=port, client_id=client_id, account=account),+ )+++def trading_account(+ connection: str | None = None,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ account: str | None = None,+) -> str:+ """Read account data from the selected trading connector profile.++ Args:+ connection: Optional profile id. Defaults to the selected profile.+ host: Optional local host override.+ port: Optional local socket port override.+ client_id: Optional local client id override.+ account: Optional account code filter.+ """+ registry = _get_registry()+ return registry.execute(+ "trading_account",+ _trading_common_args(connection=connection, host=host, port=port, client_id=client_id, account=account),+ )+++def trading_positions(+ connection: str | None = None,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ account: str | None = None,+) -> str:+ """Read positions from the selected trading connector profile.++ Args:+ connection: Optional profile id. Defaults to the selected profile.+ host: Optional local host override.+ port: Optional local socket port override.+ client_id: Optional local client id override.+ account: Optional account code filter.+ """+ registry = _get_registry()+ return registry.execute(+ "trading_positions",+ _trading_common_args(connection=connection, host=host, port=port, client_id=client_id, account=account),+ )+++def trading_orders(+ connection: str | None = None,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ account: str | None = None,+ include_executions: bool = False,+) -> str:+ """Read open orders from the selected trading connector profile.++ Read-only: this tool does not place, cancel, modify, or replace orders.++ Args:+ connection: Optional profile id. Defaults to the selected profile.+ host: Optional local host override.+ port: Optional local socket port override.+ client_id: Optional local client id override.+ account: Optional account code filter.+ include_executions: Include recent executions when available.+ """+ params = _trading_common_args(connection=connection, host=host, port=port, client_id=client_id, account=account)+ params["include_executions"] = include_executions+ registry = _get_registry()+ return registry.execute("trading_orders", params)+++def trading_quote(+ symbol: str,+ connection: str | None = None,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ account: str | None = None,+ exchange: str = "SMART",+ currency: str = "USD",+ sec_type: str = "STK",+) -> str:+ """Read a quote snapshot from the selected trading connector profile.++ Args:+ symbol: Symbol such as AAPL.+ connection: Optional profile id. Defaults to the selected profile.+ host: Optional local host override.+ port: Optional local socket port override.+ client_id: Optional local client id override.+ account: Optional account code filter.+ exchange: Exchange routing, default SMART.+ currency: Contract currency, default USD.+ sec_type: Security type, default STK.+ """+ params = _trading_common_args(connection=connection, host=host, port=port, client_id=client_id, account=account)+ params.update({"symbol": symbol, "exchange": exchange, "currency": currency, "sec_type": sec_type})+ registry = _get_registry()+ return registry.execute("trading_quote", params)+++def trading_history(+ symbol: str,+ connection: str | None = None,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ account: str | None = None,+ exchange: str = "SMART",+ currency: str = "USD",+ sec_type: str = "STK",+ duration: str = "30 D",+ bar_size: str = "1 day",+ what_to_show: str = "TRADES",+ use_rth: bool = True,+) -> str:+ """Read historical bars from the selected trading connector profile.++ Args:+ symbol: Symbol such as AAPL.+ connection: Optional profile id. Defaults to the selected profile.+ host: Optional local host override.+ port: Optional local socket port override.+ client_id: Optional local client id override.+ account: Optional account code filter.+ exchange: Exchange routing, default SMART.+ currency: Contract currency, default USD.+ sec_type: Security type, default STK.+ duration: IBKR duration string, default 30 D.+ bar_size: IBKR bar size, default 1 day.+ what_to_show: Data type, default TRADES.+ use_rth: Use regular trading hours.+ """+ params = _trading_common_args(connection=connection, host=host, port=port, client_id=client_id, account=account)+ params.update(+ {+ "symbol": symbol,+ "exchange": exchange,+ "currency": currency,+ "sec_type": sec_type,+ "duration": duration,+ "bar_size": bar_size,+ "what_to_show": what_to_show,+ "use_rth": use_rth,+ }+ )+ registry = _get_registry()+ return registry.execute("trading_history", params)++# ---------------------------------------------------------------------------# Swarm team tool# ---------------------------------------------------------------------------diff --git a/agent/src/config/schema.py b/agent/src/config/schema.pyindex df4db243d..09f5578c0 100644--- a/agent/src/config/schema.py+++ b/agent/src/config/schema.py@@ -7,19 +7,42 @@ from urllib.parse import urlsplitfrom pydantic import BaseModel, ConfigDict, Field, model_validator-# Live-broker MCP server keys. These channels place real orders, so a wildcard-# ``enabled_tools`` (which would re-admit every WRITE/UNKNOWN tool) is rejected-# at config-load time — a live channel must pin an explicit read-only allowlist.-LIVE_BROKER_SERVER_KEYS: frozenset[str] = frozenset({"robinhood"})+# Live-broker MCP server keys. These channels may place real orders, so a+# wildcard ``enabled_tools`` (which would re-admit every WRITE/UNKNOWN tool) is+# rejected at config-load time unless a broker-specific read-only OAuth probe is+# explicitly documented below.+LIVE_BROKER_SERVER_KEYS: frozenset[str] = frozenset({"robinhood", "ibkr"})++# URL host suffix -> canonical live-broker key. Detection by host prevents an+# aliased config key from bypassing the wildcard rejection / classification gate.+LIVE_BROKER_URL_HOST_SUFFIX_TO_KEY: dict[str, str] = {+ "robinhood.com": "robinhood",+ "ibkr.com": "ibkr",+}# Live-broker URL host suffixes. Detecting a live broker by config key alone is# bypassable: a Robinhood agentic URL placed under any other key (e.g. ``rh``)# would otherwise dodge BOTH the wildcard rejection AND the classification gate,-# exposing ``place_order`` ungated. So a server whose ``url`` host matches one of-# these suffixes is treated as a live broker regardless of its config key. The-# name-key path (``LIVE_BROKER_SERVER_KEYS``) stays as a fallback for stdio /-# non-URL live channels and for keys that intentionally name a known broker.-LIVE_BROKER_URL_HOST_SUFFIXES: tuple[str, ...] = ("robinhood.com",)+# exposing ``place_order`` ungated. So a server whose ``url`` host matches one+# of these suffixes is treated as a live broker regardless of its config key.+# The name-key path (``LIVE_BROKER_SERVER_KEYS``) stays as a fallback for stdio+# / non-URL live channels and for keys that intentionally name a known broker.+LIVE_BROKER_URL_HOST_SUFFIXES: tuple[str, ...] = tuple(LIVE_BROKER_URL_HOST_SUFFIX_TO_KEY)++# IBKR's official MCP endpoint does not publish stable tool names until after+# OAuth. To support a first-run read-only probe, we allow a wildcard only when+# the IBKR server is constrained to the documented read scope and does not carry+# the write scope. The live registry still fail-closes WRITE/UNKNOWN tools after+# discovery; this exception is only for read-tool discovery under ``mcp.read``.+LIVE_BROKER_READONLY_WILDCARD_REQUIRED_SCOPES: dict[str, frozenset[str]] = {+ "ibkr": frozenset({"mcp.read"}),+}+LIVE_BROKER_READONLY_WILDCARD_ALLOWED_EXTRA_SCOPES: dict[str, frozenset[str]] = {+ "ibkr": frozenset({"openid", "profile", "email", "account-ids"}),+}+LIVE_BROKER_WRITE_SCOPES: dict[str, frozenset[str]] = {+ "ibkr": frozenset({"mcp.write"}),+}def _url_host(url: str) -> str:@@ -56,13 +79,45 @@ def is_live_broker_url(url: str) -> bool:``True`` when the URL host equals or is a subdomain of a live-brokerhost suffix."""+ return live_broker_key_for_url(url) is not None+++def live_broker_key_for_url(url: str) -> str | None:+ """Resolve a live broker key from an MCP server URL host.++ Args:+ url: The MCP server ``url`` from config.++ Returns:+ The canonical broker key when the URL host equals or is a subdomain of+ a known live-broker suffix; otherwise ``None``.+ """host = _url_host(url)if not host:- return False- return any(- host == suffix or host.endswith(f".{suffix}")- for suffix in LIVE_BROKER_URL_HOST_SUFFIXES- )+ return None+ for suffix, broker in LIVE_BROKER_URL_HOST_SUFFIX_TO_KEY.items():+ if host == suffix or host.endswith(f".{suffix}"):+ return broker+ return None+++def live_broker_key_for_entry(+ server_key: str, server: "MCPServerConfig | MCPServerConfigOverride"+) -> str | None:+ """Resolve the canonical broker key for a config entry.++ Args:+ server_key: The MCP server key from config.+ server: The server config (or override) carrying the ``url``.++ Returns:+ The canonical broker key when either the key or URL identifies a live+ broker; otherwise ``None``.+ """+ key = server_key.strip().lower()+ if key in LIVE_BROKER_SERVER_KEYS:+ return key+ return live_broker_key_for_url(getattr(server, "url", "") or "")def is_live_broker_entry(server_key: str, server: "MCPServerConfig | MCPServerConfigOverride") -> bool:@@ -79,9 +134,44 @@ def is_live_broker_entry(server_key: str, server: "MCPServerConfig | MCPServerCoReturns:``True`` when either the key or the URL host identifies a live broker."""- if server_key.strip().lower() in LIVE_BROKER_SERVER_KEYS:- return True- return is_live_broker_url(getattr(server, "url", "") or "")+ return live_broker_key_for_entry(server_key, server) is not None+++def _allows_readonly_wildcard_probe(+ server_key: str, server: "MCPServerConfig | MCPServerConfigOverride"+) -> bool:+ """Return whether a live broker may use ``enabled_tools=["*"]``.++ The only supported exception today is IBKR's official MCP read probe:+ tool names are not known before OAuth, but the token request can be pinned+ to ``mcp.read``. Any write scope or missing read scope fails closed.++ Args:+ server_key: The MCP server key from config.+ server: The server config carrying OAuth scopes.++ Returns:+ ``True`` only for a broker-specific read-only OAuth probe.+ """+ broker = live_broker_key_for_entry(server_key, server)+ if broker is None:+ return False++ required = LIVE_BROKER_READONLY_WILDCARD_REQUIRED_SCOPES.get(broker)+ if not required:+ return False++ auth = getattr(server, "auth", None)+ if auth is None:+ return False++ scopes = {scope.strip() for scope in getattr(auth, "scopes", []) if scope.strip()}+ write_scopes = LIVE_BROKER_WRITE_SCOPES.get(broker, frozenset())+ allowed_extras = LIVE_BROKER_READONLY_WILDCARD_ALLOWED_EXTRA_SCOPES.get(+ broker, frozenset()+ )+ allowed = set(required | allowed_extras)+ return required.issubset(scopes) and scopes.isdisjoint(write_scopes) and scopes <= allowed# Canonical seed for the operator-side ``~/.vibe-trading/agent.json`` mcpServers# entry that wires the Robinhood Agentic Trading channel. It ships OFF-by-default@@ -101,7 +191,7 @@ ROBINHOOD_MCP_SERVER_SEED: dict[str, object] = {"cache_dir": "~/.vibe-trading/live/robinhood/oauth",},# Seed the OFF-by-default READ allowlist to EXACTLY the canonical curated- # READ tool names (``src.live.robinhood_classification.ROBINHOOD_TOOL_CLASS``).+ # READ tool names (``src.trading.connectors.robinhood.classification.ROBINHOOD_TOOL_CLASS``).# These MUST match the curated map's READ entries: a name here that the map# does not classify READ would resolve UNKNOWN -> gated -> refused, silently# hiding the real read tool. Canonical READ catalog: get_account,@@ -115,6 +205,25 @@ ROBINHOOD_MCP_SERVER_SEED: dict[str, object] = {],}+# Canonical seed for IBKR's official remote MCP server. The endpoint is visible+# from Claude's connector page / install command and advertises OAuth scopes+# ``mcp.read`` and ``mcp.write``. This seed intentionally requests ONLY+# ``mcp.read`` and uses ``enabled_tools=["*"]`` as a read-only discovery probe,+# because IBKR tool names are not public until OAuth completes. If the operator+# later requests ``mcp.write``, the wildcard exception no longer applies and the+# config must pin an explicit tool allowlist plus pass the live order gate.+IBKR_MCP_SERVER_SEED: dict[str, object] = {+ "type": "streamableHttp",+ "url": "https://api.ibkr.com/v1/api/mcp",+ "auth": {+ "type": "oauth",+ "scopes": ["mcp.read"],+ "client_name": "Vibe-Trading",+ "cache_dir": "~/.vibe-trading/live/ibkr/oauth",+ },+ "enabled_tools": ["*"],+}+def _to_camel(name: str) -> str:"""Convert snake_case names to camelCase aliases.@@ -161,6 +270,10 @@ class MCPOAuthConfig(ConfigBase):``None`` (default) lets the OAuth provider pick a free port.client_id: Optional pre-registered OAuth client id (skips dynamicclient registration when provided).+ client_secret: Optional pre-registered OAuth client secret. Used only+ with ``client_id`` for providers that reject public clients.+ client_metadata_url: Optional HTTPS client metadata document URL. Some+ MCP OAuth providers use this URL itself as the client id."""type: Literal["oauth"] = "oauth"@@ -169,6 +282,8 @@ class MCPOAuthConfig(ConfigBase):cache_dir: str = "~/.vibe-trading/live/robinhood/oauth"callback_port: int | None = Field(default=None, ge=1, le=65535)client_id: str | None = None+ client_secret: str | None = None+ client_metadata_url: str | None = Noneclass MCPServerConfig(ConfigBase):@@ -275,6 +390,8 @@ class AgentConfig(ConfigBase):"""for server_key, server in self.mcp_servers.items():if is_live_broker_entry(server_key, server) and "*" in server.enabled_tools:+ if _allows_readonly_wildcard_probe(server_key, server):+ continueraise ValueError(f"Live-broker MCP server '{server_key}' may not use a wildcard ""enabledTools allowlist ('*'); pin an explicit read-only tool list"@@ -298,4 +415,4 @@ class AgentConfigOverride(ConfigBase):extra="ignore",)- mcp_servers: dict[str, MCPServerConfigOverride] = Field(default_factory=dict)\ No newline at end of file+ mcp_servers: dict[str, MCPServerConfigOverride] = Field(default_factory=dict)diff --git a/agent/src/live/extractors/__init__.py b/agent/src/live/extractors/__init__.pyindex f694a3850..0e42280fb 100644--- a/agent/src/live/extractors/__init__.py+++ b/agent/src/live/extractors/__init__.py@@ -15,15 +15,15 @@ from __future__ import annotationsfrom typing import Callablefrom src.live.enforcement import OrderIntent-from src.live.extractors.robinhood import (+from src.trading.connectors.robinhood.extractor import (extract_order_intent as _robinhood_extract,)#: Signature every broker extractor satisfies.OrderIntentExtractor = Callable[[str, dict], "OrderIntent | None"]-#: Broker key → order-intent extractor. Adding a live broker is additive: drop-#: in an ``extractors/<broker>.py`` and register it here.+#: Broker key → order-intent extractor. Broker-specific parsers live with their+#: connector package; this module is only the live-safety lookup table.BROKER_EXTRACTORS: dict[str, OrderIntentExtractor] = {"robinhood": _robinhood_extract,}diff --git a/agent/src/live/order_guard.py b/agent/src/live/order_guard.pyindex 6caf092f4..a2185db6c 100644--- a/agent/src/live/order_guard.py+++ b/agent/src/live/order_guard.py@@ -66,9 +66,8 @@ _COUNTER_FILENAME = "trade_counter.json"#: to emit a ``live.action`` event without touching the agent loop.LIVE_ACTION_RESULT_KEY = "live_action"-#: Canonical Robinhood READ tools the gate uses to snapshot positions/balance-#: and (for quantity orders) a live quote. Pinned to the frozen catalog: READ =-#: {get_account, get_positions, get_quotes, list_orders}.+#: Fallback READ tools the gate uses to snapshot positions/balance and live+#: quotes. Connector mappings in ``src.trading`` override these when available._POSITIONS_TOOLS = ("get_positions",)_BALANCE_TOOLS = ("get_account",)_QUOTE_TOOLS = ("get_quotes",)@@ -165,8 +164,8 @@ class LiveOrderGuardTool(MCPRemoteTool):mandate=mandate,)- positions = self._read_first(_POSITIONS_TOOLS)- balance = self._read_first(_BALANCE_TOOLS)+ positions = self._read_first(self._read_tools("positions", _POSITIONS_TOOLS))+ balance = self._read_first(self._read_tools("account", _BALANCE_TOOLS))daily_count = self._read_daily_count()breach = check_mandate(@@ -274,7 +273,7 @@ class LiveOrderGuardTool(MCPRemoteTool):Returns:A positive USD price, or ``None``."""- for remote in _QUOTE_TOOLS:+ for remote in self._read_tools("quote", _QUOTE_TOOLS):try:result = self._adapter.call_tool(remote, {"symbol": symbol}, local_name=remote@@ -474,6 +473,16 @@ class LiveOrderGuardTool(MCPRemoteTool):return resultreturn None+ def _read_tools(self, operation: str, fallback: tuple[str, ...]) -> tuple[str, ...]:+ """Return connector-specific read tools, falling back to legacy names."""+ try:+ from src.trading.service import runner_tool_name++ remote = runner_tool_name(self.broker, operation)+ except Exception: # pragma: no cover - guard must fail closed later+ remote = None+ return (remote,) if remote else fallback+# -- daily counter ------------------------------------------------------def _counter_path(self):diff --git a/agent/src/live/registry.py b/agent/src/live/registry.pyindex 63ab71220..5f8a78cd4 100644--- a/agent/src/live/registry.py+++ b/agent/src/live/registry.py@@ -14,22 +14,26 @@ from __future__ import annotationsimport logging-from src.config.schema import LIVE_BROKER_SERVER_KEYS, is_live_broker_url+from src.config.schema import (+ LIVE_BROKER_SERVER_KEYS,+ is_live_broker_url,+ live_broker_key_for_url,+)from src.live.classification import ToolClass, classify_toolfrom src.live.halt import halt_flag_setfrom src.live.order_guard import LiveOrderGuardTool-from src.live.robinhood_classification import ROBINHOOD_TOOL_CLASSfrom src.tools.mcp import MCPRemoteTool+from src.trading.connectors.ibkr.classification import IBKR_TOOL_CLASS+from src.trading.connectors.robinhood.classification import ROBINHOOD_TOOL_CLASSlogger = logging.getLogger(__name__)#: Per-broker curated classification maps (Tier 2). Keyed by broker name; an#: aliased server key resolves to its broker via :func:`_broker_for`.-_BROKER_CURATED_MAPS = {"robinhood": ROBINHOOD_TOOL_CLASS}--#: URL host suffix -> broker name, so a live-broker URL under an arbitrary key-#: still resolves to the right curated map / mandate / halt namespace.-_HOST_SUFFIX_TO_BROKER = {"robinhood.com": "robinhood"}+_BROKER_CURATED_MAPS = {+ "robinhood": ROBINHOOD_TOOL_CLASS,+ "ibkr": IBKR_TOOL_CLASS,+}def is_live_broker(server_name: str, url: str = "") -> bool:@@ -71,13 +75,8 @@ def _broker_for(server_name: str, url: str = "") -> str:key = server_name.strip().lower()if key in LIVE_BROKER_SERVER_KEYS:return key- from src.config.schema import _url_host- host = _url_host(url)- for suffix, broker in _HOST_SUFFIX_TO_BROKER.items():- if host == suffix or host.endswith(f".{suffix}"):- return broker- return key+ return live_broker_key_for_url(url) or key#: FastMCP's OAuth token cache collection name (``TokenStorageAdapter``).diff --git a/agent/src/live/runtime/flatten.py b/agent/src/live/runtime/flatten.pyindex fe0680058..cca6b854e 100644--- a/agent/src/live/runtime/flatten.py+++ b/agent/src/live/runtime/flatten.py@@ -181,12 +181,26 @@ def _cancel_resting_orders(report["errors"].append({"phase": "cancel", "order_id": order_id, "error": str(exc)})- _audit(broker, _CANCEL_TOOL, f"cancel order {order_id}", request,- None, "error", str(exc))+ _audit(+ broker,+ _sweep_tool(broker, "cancel_order", _CANCEL_TOOL),+ f"cancel order {order_id}",+ request,+ None,+ "error",+ str(exc),+ )continuereport["cancelled_order_ids"].append(order_id)- _audit(broker, _CANCEL_TOOL, f"cancel order {order_id}", request,- response, "accepted", None)+ _audit(+ broker,+ _sweep_tool(broker, "cancel_order", _CANCEL_TOOL),+ f"cancel order {order_id}",+ request,+ response,+ "accepted",+ None,+ )def _flatten_open_positions(@@ -234,12 +248,38 @@ def _flatten_open_positions(report["errors"].append({"phase": "flatten", "symbol": symbol, "error": str(exc)})- _audit(broker, _FLATTEN_TOOL, intent, request, None, "error", str(exc))+ _audit(+ broker,+ _sweep_tool(broker, "submit_order", _FLATTEN_TOOL),+ intent,+ request,+ None,+ "error",+ str(exc),+ )continuereport["flatten_orders_submitted"].append({"symbol": symbol, "qty": close_qty, "side": side, "response": response})- _audit(broker, _FLATTEN_TOOL, intent, request, response, "accepted", None)+ _audit(+ broker,+ _sweep_tool(broker, "submit_order", _FLATTEN_TOOL),+ intent,+ request,+ response,+ "accepted",+ None,+ )+++def _sweep_tool(broker: str, operation: str, fallback: str) -> str:+ """Return the connector-specific sweep tool name for audit records."""+ try:+ from src.trading.service import runner_tool_name++ return runner_tool_name(broker, operation) or fallback+ except Exception: # pragma: no cover - audit should not fail the sweep+ return fallbackdef _audit(diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.pyindex 6d6acae4f..c246f3a95 100644--- a/agent/src/tools/__init__.py+++ b/agent/src/tools/__init__.py@@ -193,15 +193,28 @@ def build_registry(if not should_register_live_channel(interactive=interactive, url=server_url, cache_dir=cache_dir):+ profile_hint = (+ "ibkr-live-official-mcp-readonly"+ if server_name.strip().lower() == "ibkr"+ else f"{server_name}-live-mcp"+ )skip_msg = (- f"Robinhood live channel configured but not authorized — "- f"run `vibe-trading live authorize {server_name}` on a "- f"desktop session"+ f"{server_name} live connector configured but not authorized — "+ f"run `vibe-trading connector authorize {profile_hint}` "+ f"on a desktop session")logger.warning(skip_msg)if warn_callback is not None:warn_callback(skip_msg)continue+ info_msg = (+ f"{server_name} live connector is available through trading_* tools; "+ "broker-specific MCP wrappers are hidden from the agent registry"+ )+ logger.info(info_msg)+ if warn_callback is not None:+ warn_callback(info_msg)+ continuewrappers = build_mcp_tool_wrappers(server_name,diff --git a/agent/src/tools/mcp.py b/agent/src/tools/mcp.pyindex 33d84682d..807c9d8a4 100644--- a/agent/src/tools/mcp.py+++ b/agent/src/tools/mcp.py@@ -418,6 +418,8 @@ class MCPServerAdapter:token_storage=_build_token_store(oauth_config.cache_dir),callback_port=oauth_config.callback_port,client_id=oauth_config.client_id,+ client_secret=oauth_config.client_secret,+ client_metadata_url=oauth_config.client_metadata_url,)transport = StreamableHttpTransport(url=self.server_config.url,@@ -1017,4 +1019,4 @@ __all__ = ["make_mcp_tool_name","normalize_mcp_tool_schema","resolve_mcp_server_tool_name_segments",-]\ No newline at end of file+]diff --git a/agent/src/tools/trading_connector_tool.py b/agent/src/tools/trading_connector_tool.pynew file mode 100644index 000000000..8a6ca85ac--- /dev/null+++ b/agent/src/tools/trading_connector_tool.py@@ -0,0 +1,291 @@+"""Connector-first trading tools.++Tools take an optional ``connection`` profile id. If omitted, they use the+selected profile from ``~/.vibe-trading/trading-connections.json``.+"""++from __future__ import annotations++import json+from typing import Any++from src.agent.tools import BaseTool+from src.trading.profiles import (+ list_profiles,+ load_selected_profile_id,+ profile_by_id,+ save_selected_profile_id,+)+from src.trading.service import (+ check_connection,+ get_account,+ get_history,+ get_open_orders,+ get_positions,+ get_quote,+)+++def _json_result(payload: dict[str, Any]) -> str:+ return json.dumps(payload, ensure_ascii=False)+++def _connection(value: Any) -> str | None:+ if value is None:+ return None+ text = str(value).strip()+ return text or None+++def _int_or_none(value: Any) -> int | None:+ if value in (None, ""):+ return None+ return int(value)+++TRADING_COMMON_PARAMETERS = {+ "connection": {+ "type": "string",+ "description": "Trading connector profile id, e.g. ibkr-paper-local or robinhood-live-mcp. Defaults to the selected profile.",+ },+ "host": {+ "type": "string",+ "description": "Optional local TWS/Gateway host override for local profiles.",+ },+ "port": {+ "type": "integer",+ "description": "Optional local TWS/Gateway port override for local profiles.",+ },+ "client_id": {+ "type": "integer",+ "description": "Optional local TWS/Gateway client id override for local profiles.",+ },+ "account": {+ "type": "string",+ "description": "Optional account code filter when supported by the connector.",+ },+}+++def _overrides(kwargs: dict[str, Any]) -> dict[str, Any]:+ return {+ "host": _connection(kwargs.get("host")),+ "port": _int_or_none(kwargs.get("port")),+ "client_id": _int_or_none(kwargs.get("client_id")),+ "account": _connection(kwargs.get("account")),+ }+++class TradingConnectionsTool(BaseTool):+ """List available trading connector profiles."""++ name = "trading_connections"+ description = (+ "List selectable trading connector profiles. Connectors come first; paper/live is a profile attribute."+ )+ parameters = {"type": "object", "properties": {}, "required": []}+ repeatable = True+ is_readonly = True++ def execute(self, **_: Any) -> str:+ """List connector profiles and mark the selected one."""+ try:+ selected = load_selected_profile_id()+ return _json_result(+ {+ "status": "ok",+ "selected_profile": selected,+ "profiles": [profile.to_dict(selected=profile.id == selected) for profile in list_profiles()],+ }+ )+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})+++class TradingSelectConnectionTool(BaseTool):+ """Select the default trading connector profile."""++ name = "trading_select_connection"+ description = "Select the default trading connector profile for subsequent trading_* tool calls."+ parameters = {+ "type": "object",+ "properties": {+ "connection": {+ "type": "string",+ "description": "Profile id to select, e.g. ibkr-paper-local.",+ }+ },+ "required": ["connection"],+ }+ repeatable = True+ is_readonly = False++ def execute(self, **kwargs: Any) -> str:+ """Persist the selected profile id."""+ try:+ profile = profile_by_id(str(kwargs["connection"]).strip())+ path = save_selected_profile_id(profile.id)+ return _json_result({"status": "ok", "selected_profile": profile.id, "path": str(path)})+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})+++class TradingCheckTool(BaseTool):+ """Check a trading connector profile."""++ name = "trading_check"+ description = "Check whether a trading connector profile is configured and reachable. This never places orders."+ parameters = {+ "type": "object",+ "properties": TRADING_COMMON_PARAMETERS,+ "required": [],+ }+ repeatable = True+ is_readonly = True++ def execute(self, **kwargs: Any) -> str:+ """Check connector readiness."""+ try:+ return _json_result(check_connection(_connection(kwargs.get("connection")), **_overrides(kwargs)))+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})+++class TradingAccountTool(BaseTool):+ """Read account summary from a trading connector profile."""++ name = "trading_account"+ description = "Read account summary from the selected trading connector profile. Read-only."+ parameters = TradingCheckTool.parameters+ repeatable = True+ is_readonly = True++ def execute(self, **kwargs: Any) -> str:+ """Read account summary."""+ try:+ return _json_result(get_account(_connection(kwargs.get("connection")), **_overrides(kwargs)))+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})+++class TradingPositionsTool(BaseTool):+ """Read positions from a trading connector profile."""++ name = "trading_positions"+ description = "Read positions from the selected trading connector profile. Read-only."+ parameters = TradingCheckTool.parameters+ repeatable = True+ is_readonly = True++ def execute(self, **kwargs: Any) -> str:+ """Read positions."""+ try:+ return _json_result(get_positions(_connection(kwargs.get("connection")), **_overrides(kwargs)))+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})+++class TradingOrdersTool(BaseTool):+ """Read open orders from a trading connector profile."""++ name = "trading_orders"+ description = "Read open orders from the selected trading connector profile. Read-only."+ parameters = {+ "type": "object",+ "properties": {+ **TRADING_COMMON_PARAMETERS,+ "include_executions": {"type": "boolean", "default": False},+ },+ "required": [],+ }+ repeatable = True+ is_readonly = True++ def execute(self, **kwargs: Any) -> str:+ """Read open orders."""+ try:+ return _json_result(+ get_open_orders(+ _connection(kwargs.get("connection")),+ include_executions=bool(kwargs.get("include_executions", False)),+ **_overrides(kwargs),+ )+ )+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})+++class TradingQuoteTool(BaseTool):+ """Read a quote from a trading connector profile."""++ name = "trading_quote"+ description = "Read a quote snapshot from the selected trading connector profile. Read-only."+ parameters = {+ "type": "object",+ "properties": {+ **TRADING_COMMON_PARAMETERS,+ "symbol": {"type": "string", "description": "Symbol, e.g. AAPL"},+ "exchange": {"type": "string", "default": "SMART"},+ "currency": {"type": "string", "default": "USD"},+ "sec_type": {"type": "string", "default": "STK"},+ },+ "required": ["symbol"],+ }+ repeatable = True+ is_readonly = True++ def execute(self, **kwargs: Any) -> str:+ """Read quote snapshot."""+ try:+ return _json_result(+ get_quote(+ str(kwargs["symbol"]),+ _connection(kwargs.get("connection")),+ exchange=str(kwargs.get("exchange") or "SMART"),+ currency=str(kwargs.get("currency") or "USD"),+ sec_type=str(kwargs.get("sec_type") or "STK"),+ **_overrides(kwargs),+ )+ )+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})+++class TradingHistoryTool(BaseTool):+ """Read historical bars from a trading connector profile."""++ name = "trading_history"+ description = "Read historical bars from the selected trading connector profile. Read-only."+ parameters = {+ "type": "object",+ "properties": {+ **TradingQuoteTool.parameters["properties"],+ "duration": {"type": "string", "default": "30 D"},+ "bar_size": {"type": "string", "default": "1 day"},+ "what_to_show": {"type": "string", "default": "TRADES"},+ "use_rth": {"type": "boolean", "default": True},+ },+ "required": ["symbol"],+ }+ repeatable = True+ is_readonly = True++ def execute(self, **kwargs: Any) -> str:+ """Read historical bars."""+ try:+ return _json_result(+ get_history(+ str(kwargs["symbol"]),+ _connection(kwargs.get("connection")),+ exchange=str(kwargs.get("exchange") or "SMART"),+ currency=str(kwargs.get("currency") or "USD"),+ sec_type=str(kwargs.get("sec_type") or "STK"),+ duration=str(kwargs.get("duration") or "30 D"),+ bar_size=str(kwargs.get("bar_size") or "1 day"),+ what_to_show=str(kwargs.get("what_to_show") or "TRADES"),+ use_rth=bool(kwargs.get("use_rth", True)),+ **_overrides(kwargs),+ )+ )+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})diff --git a/agent/src/trading/__init__.py b/agent/src/trading/__init__.pynew file mode 100644index 000000000..cfc7308ad--- /dev/null+++ b/agent/src/trading/__init__.py@@ -0,0 +1,31 @@+"""Trading connector profiles and operations."""++from src.trading.profiles import (+ list_profiles,+ load_selected_profile_id,+ profile_by_id,+ save_selected_profile_id,+)+from src.trading.service import (+ check_connection,+ get_account,+ get_history,+ get_open_orders,+ get_positions,+ get_quote,+)+from src.trading.types import TradingProfile++__all__ = [+ "TradingProfile",+ "check_connection",+ "get_account",+ "get_history",+ "get_open_orders",+ "get_positions",+ "get_quote",+ "list_profiles",+ "load_selected_profile_id",+ "profile_by_id",+ "save_selected_profile_id",+]diff --git a/agent/src/trading/connectors/__init__.py b/agent/src/trading/connectors/__init__.pynew file mode 100644index 000000000..f4336edbc--- /dev/null+++ b/agent/src/trading/connectors/__init__.py@@ -0,0 +1,2 @@+"""Broker-specific trading connector implementations."""+diff --git a/agent/src/trading/connectors/ibkr/__init__.py b/agent/src/trading/connectors/ibkr/__init__.pynew file mode 100644index 000000000..f5a3588c9--- /dev/null+++ b/agent/src/trading/connectors/ibkr/__init__.py@@ -0,0 +1,25 @@+"""Interactive Brokers connector package."""++from src.trading.connectors.ibkr.local import (+ DEFAULT_ENDPOINTS,+ IBKRLocalConfig,+ check_local_status,+ get_account_snapshot,+ get_historical_bars,+ get_open_orders,+ get_positions,+ get_quote,+ save_config,+)++__all__ = [+ "DEFAULT_ENDPOINTS",+ "IBKRLocalConfig",+ "check_local_status",+ "get_account_snapshot",+ "get_historical_bars",+ "get_open_orders",+ "get_positions",+ "get_quote",+ "save_config",+]diff --git a/agent/src/trading/connectors/ibkr/classification.py b/agent/src/trading/connectors/ibkr/classification.pynew file mode 100644index 000000000..e305cde41--- /dev/null+++ b/agent/src/trading/connectors/ibkr/classification.py@@ -0,0 +1,26 @@+"""Curated IBKR MCP tool classification overrides.++IBKR's official MCP tool catalog is discovered only after OAuth, so this map is+intentionally sparse. READ tools are expected to come from MCP annotations under+the read-only ``mcp.read`` scope. State-changing names listed here are pinned+WRITE when they appear, and anything not annotated read-only remains UNKNOWN+and therefore fail-closed by the live registry.+"""++from __future__ import annotations++from src.live.classification import ToolClass++#: Sparse IBKR write catalog. Unknown names still fail closed.+IBKR_TOOL_CLASS: dict[str, ToolClass] = {+ "place_order": ToolClass.WRITE,+ "placeOrder": ToolClass.WRITE,+ "submit_order": ToolClass.WRITE,+ "submitOrder": ToolClass.WRITE,+ "cancel_order": ToolClass.WRITE,+ "cancelOrder": ToolClass.WRITE,+ "modify_order": ToolClass.WRITE,+ "modifyOrder": ToolClass.WRITE,+ "replace_order": ToolClass.WRITE,+ "replaceOrder": ToolClass.WRITE,+}diff --git a/agent/src/trading/connectors/ibkr/local.py b/agent/src/trading/connectors/ibkr/local.pynew file mode 100644index 000000000..1ba543005--- /dev/null+++ b/agent/src/trading/connectors/ibkr/local.py@@ -0,0 +1,592 @@+"""Local read-only Interactive Brokers connector via TWS / IB Gateway.++This module intentionally connects only to a user-owned local TWS or IB Gateway+session. It does not handle IBKR credentials, does not talk to cloud broker+endpoints directly, and exposes no order-placement method.+"""++from __future__ import annotations++import json+import socket+from dataclasses import asdict, dataclass+from pathlib import Path+from types import ModuleType+from typing import Any, Iterable, Mapping++from src.config.paths import get_runtime_root++CONFIG_FILENAME = "ibkr-local.json"++DEFAULT_ENDPOINTS: tuple[dict[str, Any], ...] = (+ {"profile": "paper", "label": "TWS Paper", "host": "127.0.0.1", "port": 7497},+ {"profile": "paper", "label": "IB Gateway Paper", "host": "127.0.0.1", "port": 4002},+ {"profile": "live-readonly", "label": "TWS Live", "host": "127.0.0.1", "port": 7496},+ {"profile": "live-readonly", "label": "IB Gateway Live", "host": "127.0.0.1", "port": 4001},+)++PROFILE_DEFAULT_PORTS = {+ "paper": 7497,+ "live-readonly": 7496,+}+++class IBKRDependencyError(RuntimeError):+ """Raised when the optional ``ib_async`` package is not installed."""+++class IBKRConnectionError(RuntimeError):+ """Raised when a local TWS / IB Gateway connection cannot be established."""+++class IBKRProfileMismatchError(RuntimeError):+ """Raised when a paper profile appears to be connected to a live account."""+++@dataclass(frozen=True)+class IBKRLocalConfig:+ """Local TWS / IB Gateway connection settings.++ Args:+ host: Local host where TWS / IB Gateway listens.+ port: Socket API port. TWS paper defaults to 7497.+ client_id: TWS API client id.+ profile: ``paper`` or ``live-readonly``.+ account: Optional account code to filter requests.+ timeout: Connection timeout in seconds.+ readonly: Always passed as true when the SDK supports it.+ """++ host: str = "127.0.0.1"+ port: int = 7497+ client_id: int = 77+ profile: str = "paper"+ account: str | None = None+ timeout: float = 8.0+ readonly: bool = True++ @classmethod+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "IBKRLocalConfig":+ """Build a config from a JSON-like mapping.++ Args:+ data: Mapping with any subset of config fields.++ Returns:+ A normalized config.+ """+ payload = dict(data or {})+ profile = str(payload.get("profile") or "paper").strip().lower()+ if profile not in PROFILE_DEFAULT_PORTS:+ raise ValueError("profile must be 'paper' or 'live-readonly'")+ default_port = PROFILE_DEFAULT_PORTS[profile]+ return cls(+ host=str(payload.get("host") or "127.0.0.1").strip(),+ port=int(payload.get("port") or default_port),+ client_id=int(payload.get("client_id", payload.get("clientId", 77))),+ profile=profile,+ account=_clean_optional_str(payload.get("account")),+ timeout=float(payload.get("timeout") or 8.0),+ readonly=bool(payload.get("readonly", True)),+ )++ def with_overrides(+ self,+ *,+ host: str | None = None,+ port: int | None = None,+ client_id: int | None = None,+ profile: str | None = None,+ account: str | None = None,+ ) -> "IBKRLocalConfig":+ """Return a copy with CLI/tool overrides applied."""+ payload = asdict(self)+ if profile is not None:+ payload["profile"] = profile+ if port is None:+ payload["port"] = PROFILE_DEFAULT_PORTS[profile]+ if host is not None:+ payload["host"] = host+ if port is not None:+ payload["port"] = port+ if client_id is not None:+ payload["client_id"] = client_id+ if account is not None:+ payload["account"] = account+ return IBKRLocalConfig.from_mapping(payload)+++def config_path() -> Path:+ """Return the user-level IBKR local config path."""+ return get_runtime_root() / CONFIG_FILENAME+++def load_config() -> IBKRLocalConfig:+ """Load local IBKR settings from ``~/.vibe-trading/ibkr-local.json``."""+ path = config_path()+ if not path.exists():+ return IBKRLocalConfig()+ try:+ return IBKRLocalConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))+ except (OSError, ValueError, json.JSONDecodeError) as exc:+ raise ValueError(f"invalid IBKR local config at {path}: {exc}") from exc+++def save_config(config: IBKRLocalConfig) -> Path:+ """Persist local IBKR settings.++ Args:+ config: Settings to write.++ Returns:+ The config path.+ """+ path = config_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(asdict(config), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ try:+ path.chmod(0o600)+ except OSError:+ pass+ return path+++def ib_async_available() -> bool:+ """Return whether the optional ``ib_async`` SDK can be imported."""+ try:+ _require_ib_async()+ return True+ except IBKRDependencyError:+ return False+++def check_local_status(+ config: IBKRLocalConfig | None = None,+ *,+ scan: bool = True,+) -> dict[str, Any]:+ """Check local port and SDK readiness.++ Args:+ config: Optional target config.+ scan: Whether to scan the default local ports.++ Returns:+ JSON-serializable health report.+ """+ cfg = config or load_config()+ report: dict[str, Any] = {+ "status": "ok",+ "config": asdict(cfg),+ "sdk": {"package": "ib_async", "installed": ib_async_available()},+ }+ if scan:+ report["ports"] = scan_default_ports()++ target_open = tcp_port_open(cfg.host, cfg.port)+ report["target"] = {+ "host": cfg.host,+ "port": cfg.port,+ "open": target_open,+ }+ if not target_open:+ report["status"] = "error"+ report["error"] = (+ f"No TWS / IB Gateway socket is listening at {cfg.host}:{cfg.port}. "+ "Open TWS or IB Gateway, log in, and enable API socket clients."+ )+ return report++ if not report["sdk"]["installed"]:+ report["status"] = "error"+ report["error"] = "Optional dependency missing: install with `pip install ib_async>=2.0`."+ return report++ try:+ account = get_account_snapshot(config=cfg)+ except Exception as exc: # noqa: BLE001 - health endpoint should report cleanly+ report["status"] = "error"+ report["error"] = str(exc)+ return report++ report["account"] = {+ "accounts": account.get("accounts", []),+ "profile": cfg.profile,+ }+ return report+++def scan_default_ports(timeout: float = 0.35) -> list[dict[str, Any]]:+ """Scan the standard local IBKR socket ports."""+ return [+ {+ **endpoint,+ "open": tcp_port_open(str(endpoint["host"]), int(endpoint["port"]), timeout=timeout),+ }+ for endpoint in DEFAULT_ENDPOINTS+ ]+++def tcp_port_open(host: str, port: int, timeout: float = 0.5) -> bool:+ """Return whether a TCP socket accepts connections."""+ try:+ with socket.create_connection((host, int(port)), timeout=timeout):+ return True+ except OSError:+ return False+++def get_account_snapshot(config: IBKRLocalConfig | None = None) -> dict[str, Any]:+ """Fetch account codes and account summary values."""+ cfg = config or load_config()+ ib = _connect(cfg)+ try:+ accounts = _managed_accounts(ib)+ summary = [_account_value_to_dict(item) for item in _account_summary(ib, cfg.account)]+ accounts = sorted(set(accounts) | {str(item.get("account")) for item in summary if item.get("account")})+ _assert_profile(cfg, accounts)+ return {+ "status": "ok",+ "profile": cfg.profile,+ "accounts": accounts,+ "summary": summary,+ }+ finally:+ _disconnect(ib)+++def get_positions(config: IBKRLocalConfig | None = None) -> dict[str, Any]:+ """Fetch current IBKR positions."""+ cfg = config or load_config()+ ib = _connect(cfg)+ try:+ accounts = _managed_accounts(ib)+ _assert_profile(cfg, accounts)+ rows = []+ for item in _call(ib, "positions"):+ account = str(_obj_get(item, "account", ""))+ if cfg.account and account and account != cfg.account:+ continue+ contract = _obj_get(item, "contract")+ rows.append(+ {+ "account": account,+ "symbol": _obj_get(contract, "symbol"),+ "local_symbol": _obj_get(contract, "localSymbol"),+ "sec_type": _obj_get(contract, "secType"),+ "exchange": _obj_get(contract, "exchange"),+ "currency": _obj_get(contract, "currency"),+ "con_id": _obj_get(contract, "conId"),+ "position": _obj_get(item, "position"),+ "avg_cost": _obj_get(item, "avgCost"),+ }+ )+ return {"status": "ok", "profile": cfg.profile, "positions": rows}+ finally:+ _disconnect(ib)+++def get_open_orders(config: IBKRLocalConfig | None = None, *, include_executions: bool = False) -> dict[str, Any]:+ """Fetch open orders and optionally recent executions."""+ cfg = config or load_config()+ ib = _connect(cfg)+ try:+ accounts = _managed_accounts(ib)+ _assert_profile(cfg, accounts)+ trades = _safe_call(ib, "openTrades") or []+ orders = [_trade_to_dict(trade) for trade in trades]+ if not orders:+ orders = [_order_to_dict(order) for order in (_safe_call(ib, "openOrders") or [])]+ result: dict[str, Any] = {"status": "ok", "profile": cfg.profile, "open_orders": orders}+ if include_executions:+ result["executions"] = [_execution_to_dict(item) for item in _executions(ib)]+ return result+ finally:+ _disconnect(ib)+++def get_quote(+ symbol: str,+ *,+ config: IBKRLocalConfig | None = None,+ exchange: str = "SMART",+ currency: str = "USD",+ sec_type: str = "STK",+) -> dict[str, Any]:+ """Fetch a top-of-book quote snapshot."""+ cfg = config or load_config()+ ib = _connect(cfg)+ try:+ accounts = _managed_accounts(ib)+ _assert_profile(cfg, accounts)+ contract = _make_contract(symbol, exchange=exchange, currency=currency, sec_type=sec_type)+ _qualify_contract(ib, contract)+ ticker = ib.reqMktData(contract, "", False, False)+ _sleep(ib, 2.0)+ try:+ ib.cancelMktData(contract)+ except Exception:+ pass+ return {+ "status": "ok",+ "symbol": symbol.upper(),+ "exchange": exchange,+ "currency": currency,+ "quote": {+ "bid": _obj_get(ticker, "bid"),+ "ask": _obj_get(ticker, "ask"),+ "last": _obj_get(ticker, "last"),+ "close": _obj_get(ticker, "close"),+ "volume": _obj_get(ticker, "volume"),+ "time": str(_obj_get(ticker, "time", "")),+ },+ }+ finally:+ _disconnect(ib)+++def get_historical_bars(+ symbol: str,+ *,+ config: IBKRLocalConfig | None = None,+ exchange: str = "SMART",+ currency: str = "USD",+ sec_type: str = "STK",+ duration: str = "30 D",+ bar_size: str = "1 day",+ what_to_show: str = "TRADES",+ use_rth: bool = True,+) -> dict[str, Any]:+ """Fetch historical bars from local TWS / IB Gateway."""+ cfg = config or load_config()+ ib = _connect(cfg)+ try:+ accounts = _managed_accounts(ib)+ _assert_profile(cfg, accounts)+ contract = _make_contract(symbol, exchange=exchange, currency=currency, sec_type=sec_type)+ _qualify_contract(ib, contract)+ bars = ib.reqHistoricalData(+ contract,+ endDateTime="",+ durationStr=duration,+ barSizeSetting=bar_size,+ whatToShow=what_to_show,+ useRTH=use_rth,+ formatDate=1,+ )+ return {+ "status": "ok",+ "symbol": symbol.upper(),+ "duration": duration,+ "bar_size": bar_size,+ "bars": [_bar_to_dict(bar) for bar in bars],+ }+ finally:+ _disconnect(ib)+++def _connect(config: IBKRLocalConfig):+ if not tcp_port_open(config.host, config.port):+ raise IBKRConnectionError(+ f"No TWS / IB Gateway socket is listening at {config.host}:{config.port}. "+ "Open TWS or IB Gateway, log in, and enable API socket clients."+ )+ module = _require_ib_async()+ ib = module.IB()+ try:+ ib.connect(+ config.host,+ config.port,+ clientId=config.client_id,+ timeout=config.timeout,+ readonly=config.readonly,+ account=config.account or "",+ )+ except TypeError:+ ib.connect(config.host, config.port, clientId=config.client_id, timeout=config.timeout)+ except Exception as exc:+ raise IBKRConnectionError(f"Could not connect to TWS / IB Gateway at {config.host}:{config.port}: {exc}") from exc+ return ib+++def _disconnect(ib: Any) -> None:+ try:+ ib.disconnect()+ except Exception:+ pass+++def _require_ib_async() -> ModuleType:+ try:+ import ib_async # type: ignore+ except ModuleNotFoundError as exc:+ raise IBKRDependencyError("ib_async is not installed; run `pip install ib_async>=2.0`.") from exc+ return ib_async+++def _managed_accounts(ib: Any) -> list[str]:+ accounts = _safe_call(ib, "managedAccounts") or []+ if isinstance(accounts, str):+ return [item.strip() for item in accounts.split(",") if item.strip()]+ return [str(item) for item in accounts if str(item)]+++def _account_summary(ib: Any, account: str | None) -> list[Any]:+ try:+ if account:+ return list(ib.accountSummary(account))+ return list(ib.accountSummary())+ except TypeError:+ return list(ib.accountSummary())+++def _assert_profile(config: IBKRLocalConfig, accounts: Iterable[str]) -> None:+ account_list = [account for account in accounts if account]+ if config.profile != "paper":+ return+ has_paper = any(account.upper().startswith("DU") for account in account_list)+ has_live = any(account.upper().startswith("U") and not account.upper().startswith("DU") for account in account_list)+ if account_list and (not has_paper or has_live):+ raise IBKRProfileMismatchError(+ "Configured profile is paper, but connected accounts do not look like IBKR paper accounts. "+ "Use `vibe-trading connector configure ibkr-live-local-readonly` only if you intend "+ "read-only live-account access."+ )+++def _make_contract(symbol: str, *, exchange: str, currency: str, sec_type: str) -> Any:+ module = _require_ib_async()+ clean_symbol = symbol.strip().upper()+ clean_type = sec_type.strip().upper()+ if clean_type == "STK" and hasattr(module, "Stock"):+ return module.Stock(clean_symbol, exchange, currency)+ contract = module.Contract()+ contract.symbol = clean_symbol+ contract.secType = clean_type+ contract.exchange = exchange+ contract.currency = currency+ return contract+++def _qualify_contract(ib: Any, contract: Any) -> None:+ try:+ ib.qualifyContracts(contract)+ except Exception:+ pass+++def _sleep(ib: Any, seconds: float) -> None:+ if hasattr(ib, "sleep"):+ ib.sleep(seconds)+++def _call(obj: Any, name: str) -> Any:+ return getattr(obj, name)()+++def _safe_call(obj: Any, name: str) -> Any:+ fn = getattr(obj, name, None)+ if fn is None:+ return None+ return fn()+++def _executions(ib: Any) -> list[Any]:+ for name in ("executions", "fills", "reqExecutions"):+ result = _safe_call(ib, name)+ if result:+ return list(result)+ return []+++def _obj_get(obj: Any, name: str, default: Any = None) -> Any:+ if obj is None:+ return default+ if isinstance(obj, Mapping):+ return obj.get(name, default)+ return getattr(obj, name, default)+++def _clean_optional_str(value: Any) -> str | None:+ if value is None:+ return None+ text = str(value).strip()+ return text or None+++def _account_value_to_dict(item: Any) -> dict[str, Any]:+ return {+ "account": _obj_get(item, "account"),+ "tag": _obj_get(item, "tag"),+ "value": _obj_get(item, "value"),+ "currency": _obj_get(item, "currency"),+ "model_code": _obj_get(item, "modelCode"),+ }+++def _trade_to_dict(trade: Any) -> dict[str, Any]:+ return {+ "contract": _contract_to_dict(_obj_get(trade, "contract")),+ "order": _order_to_dict(_obj_get(trade, "order")),+ "status": _order_status_to_dict(_obj_get(trade, "orderStatus")),+ }+++def _order_to_dict(order: Any) -> dict[str, Any]:+ return {+ "order_id": _obj_get(order, "orderId"),+ "action": _obj_get(order, "action"),+ "order_type": _obj_get(order, "orderType"),+ "total_quantity": _obj_get(order, "totalQuantity"),+ "limit_price": _obj_get(order, "lmtPrice"),+ "aux_price": _obj_get(order, "auxPrice"),+ "tif": _obj_get(order, "tif"),+ "account": _obj_get(order, "account"),+ }+++def _order_status_to_dict(status: Any) -> dict[str, Any]:+ return {+ "status": _obj_get(status, "status"),+ "filled": _obj_get(status, "filled"),+ "remaining": _obj_get(status, "remaining"),+ "avg_fill_price": _obj_get(status, "avgFillPrice"),+ }+++def _execution_to_dict(item: Any) -> dict[str, Any]:+ execution = _obj_get(item, "execution", item)+ contract = _obj_get(item, "contract")+ return {+ "contract": _contract_to_dict(contract),+ "exec_id": _obj_get(execution, "execId"),+ "account": _obj_get(execution, "acctNumber"),+ "side": _obj_get(execution, "side"),+ "shares": _obj_get(execution, "shares"),+ "price": _obj_get(execution, "price"),+ "time": str(_obj_get(execution, "time", "")),+ }+++def _contract_to_dict(contract: Any) -> dict[str, Any]:+ return {+ "symbol": _obj_get(contract, "symbol"),+ "local_symbol": _obj_get(contract, "localSymbol"),+ "sec_type": _obj_get(contract, "secType"),+ "exchange": _obj_get(contract, "exchange"),+ "currency": _obj_get(contract, "currency"),+ "con_id": _obj_get(contract, "conId"),+ }+++def _bar_to_dict(bar: Any) -> dict[str, Any]:+ return {+ "date": str(_obj_get(bar, "date", "")),+ "open": _obj_get(bar, "open"),+ "high": _obj_get(bar, "high"),+ "low": _obj_get(bar, "low"),+ "close": _obj_get(bar, "close"),+ "volume": _obj_get(bar, "volume"),+ "average": _obj_get(bar, "average"),+ "bar_count": _obj_get(bar, "barCount"),+ }diff --git a/agent/src/trading/connectors/ibkr/profiles.py b/agent/src/trading/connectors/ibkr/profiles.pynew file mode 100644index 000000000..f27a377f5--- /dev/null+++ b/agent/src/trading/connectors/ibkr/profiles.py@@ -0,0 +1,44 @@+"""Built-in Interactive Brokers connector profiles."""++from __future__ import annotations++from src.trading.types import READ_CAPABILITIES, TradingProfile++IBKR_PROFILES: tuple[TradingProfile, ...] = (+ TradingProfile(+ id="ibkr-paper-local",+ connector="ibkr",+ label="IBKR Paper · TWS / Gateway",+ environment="paper",+ transport="local_tws",+ capabilities=READ_CAPABILITIES,+ readonly=True,+ config={"profile": "paper", "host": "127.0.0.1", "port": 7497, "client_id": 77},+ notes="Uses the user's local TWS paper session. No IBKR credentials enter Vibe-Trading.",+ ),+ TradingProfile(+ id="ibkr-live-local-readonly",+ connector="ibkr",+ label="IBKR Live · TWS / Gateway Read-Only",+ environment="live",+ transport="local_tws",+ capabilities=READ_CAPABILITIES,+ readonly=True,+ config={"profile": "live-readonly", "host": "127.0.0.1", "port": 7496, "client_id": 77},+ notes="Reads a local live TWS/Gateway session only. Order placement is not exposed.",+ ),+ TradingProfile(+ id="ibkr-live-official-mcp-readonly",+ connector="ibkr",+ label="IBKR Live · Official MCP Read-Only",+ environment="live",+ transport="remote_mcp",+ capabilities=("mcp.read.discovery",),+ readonly=True,+ config={"server": "ibkr"},+ notes=(+ "Requires IBKR official MCP OAuth approval. Generic account/position tools "+ "stay disabled until IBKR publishes stable read tool names."+ ),+ ),+)diff --git a/agent/src/trading/connectors/robinhood/__init__.py b/agent/src/trading/connectors/robinhood/__init__.pynew file mode 100644index 000000000..971428160--- /dev/null+++ b/agent/src/trading/connectors/robinhood/__init__.py@@ -0,0 +1,2 @@+"""Robinhood connector package."""+diff --git a/agent/src/live/robinhood_classification.py b/agent/src/trading/connectors/robinhood/classification.pysimilarity index 100%rename from agent/src/live/robinhood_classification.pyrename to agent/src/trading/connectors/robinhood/classification.pydiff --git a/agent/src/live/extractors/robinhood.py b/agent/src/trading/connectors/robinhood/extractor.pysimilarity index 100%rename from agent/src/live/extractors/robinhood.pyrename to agent/src/trading/connectors/robinhood/extractor.pydiff --git a/agent/src/trading/connectors/robinhood/mcp.py b/agent/src/trading/connectors/robinhood/mcp.pynew file mode 100644index 000000000..f221f01f1--- /dev/null+++ b/agent/src/trading/connectors/robinhood/mcp.py@@ -0,0 +1,40 @@+"""Robinhood remote MCP generic-operation mapping."""++from __future__ import annotations++from typing import Any++_REMOTE_TOOL_NAMES = {+ "account": "get_account",+ "positions": "get_positions",+ "orders": "list_orders",+ "quote": "get_quotes",+}++_RUNNER_TOOL_NAMES = {+ "account": "get_account",+ "positions": "get_positions",+ "orders": "list_orders",+ "quote": "get_quotes",+ "submit_order": "place_order",+ "cancel_order": "cancel_order",+}+++def remote_tool_name(operation: str) -> str | None:+ """Return the Robinhood remote tool name for a generic operation."""+ return _REMOTE_TOOL_NAMES.get(operation)+++def runner_tool_name(operation: str) -> str | None:+ """Return the Robinhood remote tool name used by live runner plumbing."""+ return _RUNNER_TOOL_NAMES.get(operation)+++def remote_arguments(operation: str, arguments: dict[str, Any]) -> dict[str, Any]:+ """Normalize generic arguments for a Robinhood remote MCP operation."""+ if operation == "quote":+ symbol = arguments.get("symbol")+ symbols = arguments.get("symbols")+ return {"symbols": symbols or ([symbol] if symbol else [])}+ return {}diff --git a/agent/src/trading/connectors/robinhood/profiles.py b/agent/src/trading/connectors/robinhood/profiles.pynew file mode 100644index 000000000..997660b66--- /dev/null+++ b/agent/src/trading/connectors/robinhood/profiles.py@@ -0,0 +1,26 @@+"""Built-in Robinhood connector profiles."""++from __future__ import annotations++from src.trading.types import TradingProfile++ROBINHOOD_PROFILES: tuple[TradingProfile, ...] = (+ TradingProfile(+ id="robinhood-live-mcp",+ connector="robinhood",+ label="Robinhood Live · Agentic MCP",+ environment="live",+ transport="remote_mcp",+ capabilities=(+ "account.read",+ "positions.read",+ "orders.read",+ "quotes.read",+ "orders.place.requires_mandate",+ "runner.manage.requires_mandate",+ ),+ readonly=False,+ config={"server": "robinhood"},+ notes="Reads via Robinhood MCP; execution stays behind OAuth, mandate, guard, audit, and halt.",+ ),+)diff --git a/agent/src/trading/profiles.py b/agent/src/trading/profiles.pynew file mode 100644index 000000000..2fd98141d--- /dev/null+++ b/agent/src/trading/profiles.py@@ -0,0 +1,77 @@+"""Trading connector profile registry and selected-profile storage."""++from __future__ import annotations++import json+from pathlib import Path++from src.config.paths import get_runtime_root+from src.trading.connectors.ibkr.profiles import IBKR_PROFILES+from src.trading.connectors.robinhood.profiles import ROBINHOOD_PROFILES+from src.trading.types import TradingProfile++CONFIG_FILENAME = "trading-connections.json"+DEFAULT_PROFILE_ID = "ibkr-paper-local"++BUILTIN_PROFILES: tuple[TradingProfile, ...] = (+ *IBKR_PROFILES,+ *ROBINHOOD_PROFILES,+)+++def config_path() -> Path:+ """Return the trading connector config path."""+ return get_runtime_root() / CONFIG_FILENAME+++def list_profiles() -> list[TradingProfile]:+ """Return built-in trading connector profiles."""+ return list(BUILTIN_PROFILES)+++def profile_by_id(profile_id: str | None = None) -> TradingProfile:+ """Resolve a profile id or the saved selected profile.++ Args:+ profile_id: Optional explicit profile id.++ Returns:+ Matching profile.++ Raises:+ ValueError: If the profile id is unknown.+ """+ target = (profile_id or load_selected_profile_id()).strip().lower()+ for profile in BUILTIN_PROFILES:+ if profile.id == target:+ return profile+ raise ValueError(f"unknown trading connector profile: {target}")+++def load_selected_profile_id() -> str:+ """Load the selected trading profile id."""+ path = config_path()+ if not path.exists():+ return DEFAULT_PROFILE_ID+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return DEFAULT_PROFILE_ID+ selected = str(payload.get("selected_profile") or DEFAULT_PROFILE_ID).strip().lower()+ return selected or DEFAULT_PROFILE_ID+++def save_selected_profile_id(profile_id: str) -> Path:+ """Persist the selected trading profile id."""+ profile = profile_by_id(profile_id)+ path = config_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ json.dumps({"selected_profile": profile.id}, indent=2, ensure_ascii=False) + "\n",+ encoding="utf-8",+ )+ try:+ path.chmod(0o600)+ except OSError:+ pass+ return pathdiff --git a/agent/src/trading/service.py b/agent/src/trading/service.pynew file mode 100644index 000000000..9d788941e--- /dev/null+++ b/agent/src/trading/service.py@@ -0,0 +1,322 @@+"""Connector-first trading operations used by CLI, MCP, and agent tools."""++from __future__ import annotations++from typing import Any++from src.trading.profiles import list_profiles, profile_by_id+from src.trading.types import TradingProfile++RUNNER_CAPABILITY = "runner.manage.requires_mandate"+++def check_connection(profile_id: str | None = None, **overrides: Any) -> dict[str, Any]:+ """Check a connector profile without mutating broker state."""+ profile = profile_by_id(profile_id)+ if profile.transport == "local_tws":+ from src.trading.connectors.ibkr.local import check_local_status++ cfg = _ibkr_config(profile, overrides)+ report = check_local_status(cfg)+ report["profile_id"] = profile.id+ report["connector"] = profile.connector+ report["environment"] = profile.environment+ report["transport"] = profile.transport+ return report++ return _remote_status(profile)+++def get_account(profile_id: str | None = None, **overrides: Any) -> dict[str, Any]:+ """Read account summary for a connector profile."""+ profile = profile_by_id(profile_id)+ if profile.transport == "local_tws":+ from src.trading.connectors.ibkr.local import get_account_snapshot++ return _with_profile(profile, get_account_snapshot(_ibkr_config(profile, overrides)))+ return _call_remote(profile, "account", {})+++def get_positions(profile_id: str | None = None, **overrides: Any) -> dict[str, Any]:+ """Read positions for a connector profile."""+ profile = profile_by_id(profile_id)+ if profile.transport == "local_tws":+ from src.trading.connectors.ibkr.local import get_positions as _get_positions++ return _with_profile(profile, _get_positions(_ibkr_config(profile, overrides)))+ return _call_remote(profile, "positions", {})+++def get_open_orders(+ profile_id: str | None = None,+ *,+ include_executions: bool = False,+ **overrides: Any,+) -> dict[str, Any]:+ """Read open orders for a connector profile."""+ profile = profile_by_id(profile_id)+ if profile.transport == "local_tws":+ from src.trading.connectors.ibkr.local import get_open_orders as _get_open_orders++ return _with_profile(+ profile,+ _get_open_orders(_ibkr_config(profile, overrides), include_executions=include_executions),+ )+ return _call_remote(profile, "orders", {})+++def get_quote(+ symbol: str,+ profile_id: str | None = None,+ *,+ exchange: str = "SMART",+ currency: str = "USD",+ sec_type: str = "STK",+ **overrides: Any,+) -> dict[str, Any]:+ """Read a quote for a connector profile."""+ profile = profile_by_id(profile_id)+ if profile.transport == "local_tws":+ from src.trading.connectors.ibkr.local import get_quote as _get_quote++ return _with_profile(+ profile,+ _get_quote(+ symbol,+ config=_ibkr_config(profile, overrides),+ exchange=exchange,+ currency=currency,+ sec_type=sec_type,+ ),+ )+ return _call_remote(profile, "quote", {"symbols": [symbol], "symbol": symbol})+++def get_history(+ symbol: str,+ profile_id: str | None = None,+ *,+ exchange: str = "SMART",+ currency: str = "USD",+ sec_type: str = "STK",+ duration: str = "30 D",+ bar_size: str = "1 day",+ what_to_show: str = "TRADES",+ use_rth: bool = True,+ **overrides: Any,+) -> dict[str, Any]:+ """Read historical bars for a connector profile."""+ profile = profile_by_id(profile_id)+ if profile.transport == "local_tws":+ from src.trading.connectors.ibkr.local import get_historical_bars++ return _with_profile(+ profile,+ get_historical_bars(+ symbol,+ config=_ibkr_config(profile, overrides),+ exchange=exchange,+ currency=currency,+ sec_type=sec_type,+ duration=duration,+ bar_size=bar_size,+ what_to_show=what_to_show,+ use_rth=use_rth,+ ),+ )+ return _unsupported(profile, "history.read")+++def profile_supports_live_runner(profile: TradingProfile) -> bool:+ """Return whether a profile can run the managed live runner."""+ return (+ profile.environment == "live"+ and profile.transport == "remote_mcp"+ and RUNNER_CAPABILITY in profile.capabilities+ )+++def live_runner_profile_for_broker(broker: str) -> TradingProfile | None:+ """Return the live-runner profile for a broker, if one exists."""+ key = str(broker or "").strip().lower()+ if not key:+ return None+ for profile in list_profiles():+ if profile.connector == key and profile_supports_live_runner(profile):+ return profile+ return None+++def broker_supports_live_runner(broker: str) -> bool:+ """Return whether any configured profile exposes live runner management."""+ return live_runner_profile_for_broker(broker) is not None+++def runner_tool_name(connector: str, operation: str) -> str | None:+ """Map a runner operation to a connector-specific remote MCP tool name."""+ if connector == "robinhood":+ from src.trading.connectors.robinhood.mcp import runner_tool_name as _runner_tool_name++ return _runner_tool_name(operation)+ return None+++def _with_profile(profile: TradingProfile, payload: dict[str, Any]) -> dict[str, Any]:+ """Add connector profile metadata to an operation payload."""+ result = dict(payload)+ result["profile_id"] = profile.id+ result["connector"] = profile.connector+ result["environment"] = profile.environment+ result["transport"] = profile.transport+ return result+++def _ibkr_config(profile: TradingProfile, overrides: dict[str, Any]):+ """Build an IBKR local config from a trading profile and call overrides."""+ from src.trading.connectors.ibkr.local import IBKRLocalConfig, config_path, load_config++ default_cfg = IBKRLocalConfig.from_mapping(profile.config)+ base = load_config()+ if config_path().exists() and base.profile == default_cfg.profile:+ cfg = base+ else:+ cfg = default_cfg+ return cfg.with_overrides(+ host=_clean(overrides.get("host")),+ port=_int_or_none(overrides.get("port")),+ client_id=_int_or_none(overrides.get("client_id")),+ account=_clean(overrides.get("account")),+ )+++def _remote_status(profile: TradingProfile) -> dict[str, Any]:+ """Return local authorization/config status for a remote MCP profile."""+ from src.config.loader import load_agent_config+ from src.live.registry import has_cached_oauth_token++ server_name = str(profile.config.get("server") or profile.connector)+ server = (load_agent_config().mcp_servers or {}).get(server_name)+ auth = getattr(server, "auth", None) if server is not None else None+ token_present = False+ if server is not None and auth is not None:+ token_present = has_cached_oauth_token(server.url, auth.cache_dir)+ return {+ "status": "ok" if token_present else "not_authorized",+ "profile_id": profile.id,+ "connector": profile.connector,+ "environment": profile.environment,+ "transport": profile.transport,+ "configured": server is not None,+ "oauth_token_present": token_present,+ "capabilities": list(profile.capabilities),+ "readonly": profile.readonly,+ "notes": profile.notes,+ }+++def _call_remote(profile: TradingProfile, operation: str, arguments: dict[str, Any]) -> dict[str, Any]:+ """Call a known read operation on a remote MCP connector profile."""+ from src.config.loader import load_agent_config+ from src.live.registry import has_cached_oauth_token+ from src.tools.mcp import MCPServerAdapter++ remote_name = _remote_tool_name(profile.connector, operation)+ if remote_name is None:+ return _unsupported(profile, f"{operation}.read")++ server_name = str(profile.config.get("server") or profile.connector)+ server = (load_agent_config().mcp_servers or {}).get(server_name)+ if server is None:+ return {+ "status": "error",+ "profile_id": profile.id,+ "connector": profile.connector,+ "environment": profile.environment,+ "transport": profile.transport,+ "error": f"remote MCP server '{server_name}' is not configured",+ }++ enabled_tools = list(getattr(server, "enabled_tools", None) or [])+ if "*" not in enabled_tools and remote_name not in enabled_tools:+ return {+ "status": "error",+ "profile_id": profile.id,+ "connector": profile.connector,+ "environment": profile.environment,+ "transport": profile.transport,+ "error": f"remote tool '{remote_name}' is not enabled for connector profile '{profile.id}'",+ "enabled_tools": enabled_tools,+ }++ auth = getattr(server, "auth", None)+ if profile.environment == "live" and auth is None:+ return {+ "status": "error",+ "profile_id": profile.id,+ "connector": profile.connector,+ "environment": profile.environment,+ "transport": profile.transport,+ "error": f"connector profile '{profile.id}' has no OAuth auth configured",+ }+ if auth is not None and not has_cached_oauth_token(server.url, auth.cache_dir):+ return {+ "status": "not_authorized",+ "profile_id": profile.id,+ "connector": profile.connector,+ "environment": profile.environment,+ "transport": profile.transport,+ "error": (+ f"connector profile '{profile.id}' is not authorized. "+ f"Run `vibe-trading connector authorize {profile.id}` from a desktop session."+ ),+ }++ adapter = MCPServerAdapter(server_name, server)+ return _with_profile(+ profile,+ adapter.call_tool(remote_name, _remote_arguments(profile.connector, operation, arguments)),+ )+++def _remote_tool_name(connector: str, operation: str) -> str | None:+ """Map generic read operations to current remote MCP tool names."""+ if connector == "robinhood":+ from src.trading.connectors.robinhood.mcp import remote_tool_name++ return remote_tool_name(operation)+ return None+++def _remote_arguments(connector: str, operation: str, arguments: dict[str, Any]) -> dict[str, Any]:+ """Normalize generic arguments for a remote MCP operation."""+ if connector == "robinhood":+ from src.trading.connectors.robinhood.mcp import remote_arguments++ return remote_arguments(operation, arguments)+ return {}+++def _unsupported(profile: TradingProfile, capability: str) -> dict[str, Any]:+ """Return a standard unsupported-capability payload."""+ return {+ "status": "error",+ "profile_id": profile.id,+ "connector": profile.connector,+ "environment": profile.environment,+ "transport": profile.transport,+ "error": f"profile '{profile.id}' does not support {capability} through the generic trading tool yet",+ "capabilities": list(profile.capabilities),+ }+++def _clean(value: Any) -> str | None:+ if value is None:+ return None+ text = str(value).strip()+ return text or None+++def _int_or_none(value: Any) -> int | None:+ if value in (None, ""):+ return None+ return int(value)diff --git a/agent/src/trading/types.py b/agent/src/trading/types.pynew file mode 100644index 000000000..dd0219767--- /dev/null+++ b/agent/src/trading/types.py@@ -0,0 +1,51 @@+"""Shared trading connector data types."""++from __future__ import annotations++from dataclasses import asdict, dataclass, field+from typing import Any, Literal++Environment = Literal["paper", "live"]+Transport = Literal["local_tws", "remote_mcp"]++READ_CAPABILITIES = (+ "account.read",+ "positions.read",+ "orders.read",+ "quotes.read",+ "history.read",+)+++@dataclass(frozen=True)+class TradingProfile:+ """A user-selectable trading connector profile.++ Args:+ id: Stable profile id used by CLI/tools.+ connector: Broker/connector key, e.g. ``ibkr`` or ``robinhood``.+ label: Human-readable display label.+ environment: Paper or live account environment.+ transport: How Vibe-Trading reaches the connector.+ capabilities: Capability strings exposed by this profile.+ readonly: Whether every operation in this profile is read-only.+ config: Connector-specific defaults.+ notes: User-facing caveats.+ """++ id: str+ connector: str+ label: str+ environment: Environment+ transport: Transport+ capabilities: tuple[str, ...]+ readonly: bool+ config: dict[str, Any] = field(default_factory=dict)+ notes: str = ""++ def to_dict(self, *, selected: bool = False) -> dict[str, Any]:+ """Return a JSON-serializable profile snapshot."""+ payload = asdict(self)+ payload["capabilities"] = list(self.capabilities)+ payload["selected"] = selected+ return payloaddiff --git a/agent/tests/test_api_live_runtime.py b/agent/tests/test_api_live_runtime.pyindex 5595b9a2a..949605283 100644--- a/agent/tests/test_api_live_runtime.py+++ b/agent/tests/test_api_live_runtime.py@@ -123,7 +123,7 @@ def test_authorize_onramp_describes_cli_flow(tmp_path: Path, monkeypatch) -> Nonassert body["broker"] == "robinhood"assert body["oauth_token_present"] is False# On-ramp must point at the desktop CLI flow and never return a token.- assert "vibe-trading live authorize robinhood" in body["instruction"]+ assert "vibe-trading connector authorize robinhood-live-mcp" in body["instruction"]assert "token" not in body@@ -149,6 +149,19 @@ def test_runner_start_requires_committed_mandate(tmp_path: Path, monkeypatch) ->assert "mandate" in response.json()["detail"].lower()+def test_runner_start_rejects_readonly_connector_without_runner(+ tmp_path: Path, monkeypatch+) -> None:+ client = _client(tmp_path, monkeypatch)++ response = client.post("/live/runner/start", json={"broker": "ibkr"})++ assert response.status_code == 400+ detail = response.json()["detail"].lower()+ assert "ibkr" in detail+ assert "runner" in detail++def test_runner_start_blocked_by_kill_switch(tmp_path: Path, monkeypatch) -> None:client = _client(tmp_path, monkeypatch)monkeypatch.setattr(diff --git a/agent/tests/test_classification.py b/agent/tests/test_classification.pyindex 99baa3134..413ccc6ae 100644--- a/agent/tests/test_classification.py+++ b/agent/tests/test_classification.py@@ -5,7 +5,8 @@ from __future__ import annotationsfrom mcp.types import ToolAnnotationsfrom src.live.classification import ToolClass, classify_tool-from src.live.robinhood_classification import ROBINHOOD_TOOL_CLASS+from src.trading.connectors.ibkr.classification import IBKR_TOOL_CLASS+from src.trading.connectors.robinhood.classification import ROBINHOOD_TOOL_CLASSdef test_tier1_explicit_read_only_hint_true_is_read() -> None:@@ -62,3 +63,9 @@ def test_map_read_pin_not_overridden_by_absent_annotation() -> None:"""A curated READ wins even when annotations are present but silent."""ann = ToolAnnotations(title="quotes", readOnlyHint=None)assert classify_tool("get_quotes", ann, ROBINHOOD_TOOL_CLASS) is ToolClass.READ+++def test_ibkr_sparse_map_pins_known_order_names_write() -> None:+ """IBKR read names are annotation-discovered, but order names stay WRITE."""+ assert classify_tool("place_order", None, IBKR_TOOL_CLASS) is ToolClass.WRITE+ assert classify_tool("cancelOrder", ToolAnnotations(readOnlyHint=True), IBKR_TOOL_CLASS) is ToolClass.WRITEdiff --git a/agent/tests/test_cli_live.py b/agent/tests/test_cli_live.pyindex 536dbed2f..f063c8492 100644--- a/agent/tests/test_cli_live.py+++ b/agent/tests/test_cli_live.py@@ -1,11 +1,11 @@-"""Tests for the `vibe-trading live` CLI surface + REPL intercepts (P6).+"""Tests for the connector-first live CLI surface + REPL intercepts (P6).Covers SPEC.md §9 Decision 1 (CLI surface table) and Consent §2/§4:-* The ``live`` subcommand group dispatches each verb to the right handler.-* ``live halt`` / ``live resume`` trip and clear the kill switch on disk.-* ``live status`` / ``live mandate`` are read-only and reflect disk state.-* ``live revoke`` deletes the token cache + mandate.+* The ``connector`` subcommand group dispatches each verb to the right handler.+* Connector live commands trip/clear the kill switch on disk.+* Live status/mandate helpers are read-only and reflect disk state.+* Connector revoke deletes the token cache + mandate.* The REPL intercepts a bare numeric pick as a COMMIT — it calls the commitendpoint directly and NEVER routes the pick to the agent/model.* The REPL intercepts a bare "停"/"stop"/"/halt" turn — it trips the kill@@ -91,60 +91,55 @@ def _write_mandate(root: Path, broker: str = "robinhood", *, schema_version: int# ----------------------------------------------------------------------------class TestLiveDispatch:+class TestConnectorLiveDispatch:def _dispatch(self, argv: list[str]) -> int:- from cli._legacy import _build_parser, _dispatch_live+ from cli._legacy import _build_parser, _dispatch_connectorargs = _build_parser().parse_args(argv)- return _dispatch_live(args)+ return _dispatch_connector(args)def test_authorize_routes_to_handler(self) -> None:- with patch("cli._legacy.cmd_live_authorize", return_value=0) as m:- assert self._dispatch(["live", "authorize", "robinhood"]) == 0- m.assert_called_once_with("robinhood")+ with patch("cli._legacy.cmd_connector_authorize", return_value=0) as m:+ assert self._dispatch(["connector", "authorize", "robinhood-live-mcp"]) == 0+ m.assert_called_once_with("robinhood-live-mcp")def test_status_routes_with_broker(self) -> None:- with patch("cli._legacy.cmd_live_status", return_value=0) as m:- self._dispatch(["live", "status", "robinhood"])- m.assert_called_once_with("robinhood")+ with patch("cli._legacy.cmd_connector_status", return_value=0) as m:+ self._dispatch(["connector", "status", "robinhood-live-mcp"])+ m.assert_called_once_with("robinhood-live-mcp")- def test_status_routes_default_broker_none(self) -> None:- with patch("cli._legacy.cmd_live_status", return_value=0) as m:- self._dispatch(["live", "status"])- m.assert_called_once_with(None)-- def test_mandate_routes(self) -> None:- with patch("cli._legacy.cmd_live_mandate", return_value=0) as m:- self._dispatch(["live", "mandate"])+ def test_status_routes_default_profile_none(self) -> None:+ with patch("cli._legacy.cmd_connector_status", return_value=0) as m:+ self._dispatch(["connector", "status"])m.assert_called_once_with(None)def test_halt_routes(self) -> None:- with patch("cli._legacy.cmd_live_halt", return_value=0) as m:- self._dispatch(["live", "halt"])+ with patch("cli._legacy.cmd_connector_halt", return_value=0) as m:+ self._dispatch(["connector", "halt"])m.assert_called_once_with(None)def test_resume_routes(self) -> None:- with patch("cli._legacy.cmd_live_resume", return_value=0) as m:- self._dispatch(["live", "resume", "robinhood"])- m.assert_called_once_with("robinhood")+ with patch("cli._legacy.cmd_connector_resume", return_value=0) as m:+ self._dispatch(["connector", "resume", "robinhood-live-mcp"])+ m.assert_called_once_with("robinhood-live-mcp")def test_revoke_routes(self) -> None:- with patch("cli._legacy.cmd_live_revoke", return_value=0) as m:- self._dispatch(["live", "revoke", "robinhood"])- m.assert_called_once_with("robinhood")+ with patch("cli._legacy.cmd_connector_revoke", return_value=0) as m:+ self._dispatch(["connector", "revoke", "robinhood-live-mcp"])+ m.assert_called_once_with("robinhood-live-mcp")def test_no_subcommand_is_usage_error(self) -> None:from cli._legacy import EXIT_USAGE_ERROR- assert self._dispatch(["live"]) == EXIT_USAGE_ERROR+ assert self._dispatch(["connector"]) == EXIT_USAGE_ERROR- def test_no_live_commit_verb_exists(self) -> None:- """SPEC: the CLI live group must not be able to create/widen a mandate."""+ def test_no_connector_commit_verb_exists(self) -> None:+ """SPEC: the CLI connector group must not be able to create/widen a mandate."""from cli._legacy import _build_parserparser = _build_parser()with pytest.raises(SystemExit):- parser.parse_args(["live", "commit", "robinhood"])+ parser.parse_args(["connector", "commit", "robinhood-live-mcp"])# ---------------------------------------------------------------------------@@ -184,6 +179,58 @@ class TestLiveHaltResume:assert cmd_live_resume(None) == 0+class TestConnectorHaltResume:+ def test_halt_without_profile_rejects_default_paper_profile(+ self, live_root: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from cli._legacy import EXIT_USAGE_ERROR, cmd_connector_halt+ from src.trading import profiles++ monkeypatch.setattr(profiles, "get_runtime_root", lambda: live_root)++ assert cmd_connector_halt(None) == EXIT_USAGE_ERROR+ assert not (live_root / "live" / "HALT").exists()++ def test_halt_without_profile_uses_selected_connector(+ self, live_root: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+ ) -> None:+ from cli._legacy import cmd_connector_halt+ from src.live.halt import halt_flag_set+ from src.trading import profiles++ monkeypatch.setattr(profiles, "get_runtime_root", lambda: live_root)+ profiles.save_selected_profile_id("robinhood-live-mcp")++ assert cmd_connector_halt(None) == 0+ assert (live_root / "live" / "robinhood" / "HALT").exists()+ assert not (live_root / "live" / "HALT").exists()+ assert halt_flag_set("robinhood") is True++ out = capsys.readouterr().out+ assert "vibe-trading connector resume" in out+ assert "vibe-trading live" not in out++ def test_resume_without_profile_uses_selected_connector(+ self, live_root: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from cli._legacy import cmd_connector_halt, cmd_connector_resume+ from src.live.halt import halt_flag_set+ from src.trading import profiles++ monkeypatch.setattr(profiles, "get_runtime_root", lambda: live_root)+ profiles.save_selected_profile_id("robinhood-live-mcp")++ cmd_connector_halt(None)+ assert cmd_connector_resume(None) == 0+ assert halt_flag_set("robinhood") is False++ def test_halt_with_explicit_non_live_profile_fails(self, live_root: Path) -> None:+ from cli._legacy import EXIT_USAGE_ERROR, cmd_connector_halt++ assert cmd_connector_halt("ibkr-paper-local") == EXIT_USAGE_ERROR+ assert not (live_root / "live" / "HALT").exists()++# ---------------------------------------------------------------------------# status / mandate (read-only)# ---------------------------------------------------------------------------diff --git a/agent/tests/test_cli_runtime.py b/agent/tests/test_cli_runtime.pyindex a600a9b92..9d39e97f2 100644--- a/agent/tests/test_cli_runtime.py+++ b/agent/tests/test_cli_runtime.py@@ -3,16 +3,16 @@Covers SPEC.md §7.5 (persistent runner control) + §9 Decision 1 (CLI surfacetable) + the §9 audit discoverability fix:-* ``live run`` / ``live start`` / ``live stop`` dispatch to their handlers and+* ``connector start`` / ``connector stop`` dispatch to their handlers andrelay to the R6 surface endpoints (``POST /live/runner/start|stop``).-* ``live status`` surfaces runner liveness + last-tick from the liveness+* Connector live status surfaces runner liveness + last-tick from the livenesscontract (``src.live.runtime.liveness``), degrading cleanly when the runtimemodule is not yet present.* The slash registry / ``/help`` / typeahead completer now include- ``live`` / ``halt`` / ``resume`` (previously undiscoverable surface actions),+ ``connector`` / ``halt`` / ``resume`` (previously undiscoverable surface actions),and ``/stop`` resolves as the kill-switch alias of ``/halt``.-* The REPL intercepts ``/resume`` (clear halt) and ``/live ...`` (bridge to the- live subcommand group) in the input path — neither is dispatched to the model.+* The REPL intercepts ``/resume`` (clear halt) and ``/connector ...`` (bridge to+ the connector subcommand group) in the input path — neither is dispatched to the model.The API client is stubbed (``httpx``) and the liveness module is injected into``sys.modules`` so no server / concurrent runtime parcel is needed.@@ -99,45 +99,45 @@ class _FakeResp:# ----------------------------------------------------------------------------# Subcommand dispatch (run / start / stop) — argparse + _dispatch_live+# Subcommand dispatch (run / start / stop) — argparse + _dispatch_connector# ---------------------------------------------------------------------------class TestRunnerDispatch:def _dispatch(self, argv: List[str]) -> int:- from cli._legacy import _build_parser, _dispatch_live+ from cli._legacy import _build_parser, _dispatch_connectorargs = _build_parser().parse_args(argv)- return _dispatch_live(args)+ return _dispatch_connector(args)def test_run_routes_to_handler(self) -> None:- with patch("cli._legacy.cmd_live_run", return_value=0) as m:- assert self._dispatch(["live", "run", "robinhood"]) == 0- m.assert_called_once_with("robinhood")+ with patch("cli._legacy.cmd_connector_start", return_value=0) as m:+ assert self._dispatch(["connector", "start", "robinhood-live-mcp"]) == 0+ m.assert_called_once_with("robinhood-live-mcp")- def test_run_default_broker_none(self) -> None:- with patch("cli._legacy.cmd_live_run", return_value=0) as m:- self._dispatch(["live", "run"])+ def test_start_default_profile_none(self) -> None:+ with patch("cli._legacy.cmd_connector_start", return_value=0) as m:+ self._dispatch(["connector", "start"])m.assert_called_once_with(None)def test_start_routes_to_handler(self) -> None:- with patch("cli._legacy.cmd_live_start", return_value=0) as m:- self._dispatch(["live", "start", "robinhood"])- m.assert_called_once_with("robinhood")+ with patch("cli._legacy.cmd_connector_start", return_value=0) as m:+ self._dispatch(["connector", "start", "robinhood-live-mcp"])+ m.assert_called_once_with("robinhood-live-mcp")def test_stop_routes_to_handler(self) -> None:- with patch("cli._legacy.cmd_live_stop", return_value=0) as m:- self._dispatch(["live", "stop"])+ with patch("cli._legacy.cmd_connector_stop", return_value=0) as m:+ self._dispatch(["connector", "stop"])m.assert_called_once_with(None)def test_subparsers_registered(self) -> None:- """run/start/stop parse without error (the parser knows them)."""+ """start/stop parse without error (the parser knows them)."""from cli._legacy import _build_parserparser = _build_parser()- for verb in ("run", "start", "stop"):- parsed = parser.parse_args(["live", verb])- assert parsed.live_command == verb+ for verb in ("start", "stop"):+ parsed = parser.parse_args(["connector", verb])+ assert parsed.connector_command == verb# ---------------------------------------------------------------------------@@ -162,6 +162,31 @@ class TestRunnerControlEndpoints:assert captured["body"]["broker"] == "robinhood"assert captured["body"]["foreground"] is False+ def test_connector_start_message_uses_connector_status(+ self, capsys: pytest.CaptureFixture[str]+ ) -> None:+ from cli._legacy import EXIT_SUCCESS, cmd_connector_start++ def _post(url: str, json: Dict[str, Any], timeout: float) -> _FakeResp: # noqa: A002+ return _FakeResp({"runner_id": "live-robinhood", "status": "started"})++ with patch("httpx.post", _post):+ assert cmd_connector_start("robinhood-live-mcp") == EXIT_SUCCESS++ out = capsys.readouterr().out+ assert "vibe-trading connector status" in out+ assert "vibe-trading live" not in out++ def test_connector_start_rejects_readonly_ibkr_mcp(+ self, capsys: pytest.CaptureFixture[str]+ ) -> None:+ from cli._legacy import EXIT_USAGE_ERROR, cmd_connector_start++ assert cmd_connector_start("ibkr-live-official-mcp-readonly") == EXIT_USAGE_ERROR++ out = capsys.readouterr().out+ assert "does not support live runner management" in out+def test_stop_posts_to_runner_stop(self) -> None:from cli._legacy import EXIT_SUCCESS, cmd_live_stop@@ -252,22 +277,59 @@ class TestStatusLiveness:assert "unknown" in out+class TestConnectorStatusReadiness:+ def test_remote_live_status_fails_when_not_configured(+ self, capsys: pytest.CaptureFixture[str]+ ) -> None:+ from cli._legacy import EXIT_RUN_FAILED, cmd_connector_status++ with patch(+ "src.config.loader.load_agent_config",+ return_value=types.SimpleNamespace(mcp_servers={}),+ ):+ assert cmd_connector_status("robinhood-live-mcp") == EXIT_RUN_FAILED++ out = capsys.readouterr().out+ assert "Trading Connector: robinhood-live-mcp" in out+ assert "Live channel:" not in out++ def test_remote_live_status_fails_when_not_authorized(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ from cli._legacy import EXIT_RUN_FAILED, cmd_connector_status++ server = types.SimpleNamespace(+ url="https://example.invalid/mcp",+ auth=types.SimpleNamespace(cache_dir=str(tmp_path / "oauth")),+ enabled_tools=["*"],+ )+ with patch(+ "src.config.loader.load_agent_config",+ return_value=types.SimpleNamespace(mcp_servers={"robinhood": server}),+ ), patch("src.live.registry.has_cached_oauth_token", return_value=False):+ assert cmd_connector_status("robinhood-live-mcp") == EXIT_RUN_FAILED++ out = capsys.readouterr().out+ assert "not_authorized" in out+ assert "Live channel:" not in out++# ---------------------------------------------------------------------------# Discoverability: registry + help + completer now include live/halt/resume# ---------------------------------------------------------------------------class TestSlashDiscoverability:- def test_registry_includes_live_group(self) -> None:+ def test_registry_includes_connector_group(self) -> None:from cli.commands.slash_router import SLASH_COMMANDSnames = {c.name for c in SLASH_COMMANDS}- assert {"live", "halt", "resume"} <= names+ assert {"connector", "halt", "resume"} <= namesdef test_find_exact_resolves_new_commands(self) -> None:from cli.commands.slash_router import find_exact- for name in ("live", "halt", "resume"):+ for name in ("connector", "halt", "resume"):assert find_exact(name) is not Nonedef test_stop_is_alias_of_halt(self) -> None:@@ -278,15 +340,15 @@ class TestSlashDiscoverability:assert cmd.name == "halt"def test_match_commands_surfaces_in_typeahead(self) -> None:- """The completer ranks via match_commands — the live group must appear."""+ """The completer ranks via match_commands — the connector group must appear."""from cli.commands.slash_router import match_commandsnames = {c.name for c in match_commands("/ha")}assert "halt" in names- names = {c.name for c in match_commands("/li")}- assert "live" in names+ names = {c.name for c in match_commands("/co")}+ assert "connector" in names- def test_completer_yields_live_group(self) -> None:+ def test_completer_yields_connector_group(self) -> None:from prompt_toolkit.document import Documentfrom cli.completer import SlashCompleter@@ -296,18 +358,18 @@ class TestSlashDiscoverability:comp.get_completions(Document("/", cursor_position=1), complete_event=None))texts = {c.text for c in completions}- assert {"live", "halt", "resume"} <= texts+ assert {"connector", "halt", "resume"} <= texts- def test_help_lists_live_group(self, capsys: pytest.CaptureFixture[str]) -> None:- """``/help`` renders the registry — the live group must be present."""+ def test_help_lists_connector_group(self, capsys: pytest.CaptureFixture[str]) -> None:+ """``/help`` renders the registry — the connector group must be present."""from cli.commands import help as help_cmd# help.py binds SLASH_COMMANDS at import; our registration runs at# cli.main import (already done above) so the bound tuple includes them.- assert {"live", "halt", "resume"} <= {c.name for c in help_cmd.SLASH_COMMANDS}+ assert {"connector", "halt", "resume"} <= {c.name for c in help_cmd.SLASH_COMMANDS}help_cmd.run(None)out = capsys.readouterr().out- assert "/live" in out+ assert "/connector" in outassert "/halt" in outassert "/resume" in out@@ -322,7 +384,7 @@ class TestSlashDiscoverability:# ----------------------------------------------------------------------------# REPL intercepts: /resume clears halt, /live bridges to the subcommand group+# REPL intercepts: /resume clears halt, /connector bridges to the subcommand group# ---------------------------------------------------------------------------@@ -345,33 +407,33 @@ class TestReplResumeIntercept:assert "No active global halt" in capsys.readouterr().out-class TestReplLiveBridge:- def test_live_bridges_to_dispatch_live(self) -> None:+class TestReplConnectorBridge:+ def test_connector_bridges_to_dispatch_connector(self) -> None:console = main.get_console()- with patch("cli._legacy._dispatch_live", return_value=0) as disp:- main._run_live_command_from_repl(console, ["status", "robinhood"])+ with patch("cli._legacy._dispatch_connector", return_value=0) as disp:+ main._run_connector_command_from_repl(console, ["status", "robinhood-live-mcp"])disp.assert_called_once()parsed = disp.call_args.args[0]- assert parsed.live_command == "status"- assert parsed.live_broker == "robinhood"+ assert parsed.connector_command == "status"+ assert parsed.profile == "robinhood-live-mcp"- def test_bare_live_defaults_to_status(self) -> None:+ def test_bare_connector_defaults_to_status(self) -> None:console = main.get_console()- with patch("cli._legacy._dispatch_live", return_value=0) as disp:- main._run_live_command_from_repl(console, [])+ with patch("cli._legacy._dispatch_connector", return_value=0) as disp:+ main._run_connector_command_from_repl(console, [])parsed = disp.call_args.args[0]- assert parsed.live_command == "status"+ assert parsed.connector_command == "status"- def test_live_run_bridges_to_run_handler(self) -> None:+ def test_connector_start_bridges_to_start_handler(self) -> None:console = main.get_console()- with patch("cli._legacy.cmd_live_run", return_value=0) as run:- main._run_live_command_from_repl(console, ["run"])- run.assert_called_once_with(None)+ with patch("cli._legacy.cmd_connector_start", return_value=0) as start:+ main._run_connector_command_from_repl(console, ["start"])+ start.assert_called_once_with(None)- def test_invalid_live_subcommand_keeps_loop_alive(+ def test_invalid_connector_subcommand_keeps_loop_alive(self, capsys: pytest.CaptureFixture[str]) -> None:console = main.get_console()# Unknown subcommand → argparse SystemExit, caught, usage printed.- main._run_live_command_from_repl(console, ["frobnicate"])- assert "Usage: /live" in capsys.readouterr().out+ main._run_connector_command_from_repl(console, ["frobnicate"])+ assert "Usage: /connector" in capsys.readouterr().outdiff --git a/agent/tests/test_default_deny_unknown_robinhood_tool.py b/agent/tests/test_default_deny_unknown_robinhood_tool.pyindex 1cfe1d06d..bce0a930d 100644--- a/agent/tests/test_default_deny_unknown_robinhood_tool.py+++ b/agent/tests/test_default_deny_unknown_robinhood_tool.py@@ -30,7 +30,7 @@ from mcp import types as mcp_typesfrom src.live.classification import ToolClass, classify_toolfrom src.live.order_guard import LiveOrderGuardToolfrom src.live.registry import wrap_live_broker_tools-from src.live.robinhood_classification import ROBINHOOD_TOOL_CLASS+from src.trading.connectors.robinhood.classification import ROBINHOOD_TOOL_CLASSfrom src.tools.mcp import MCPRemoteTool, build_mcp_tool_wrapperspytestmark = pytest.mark.unitdiff --git a/agent/tests/test_enforcement_l6.py b/agent/tests/test_enforcement_l6.pyindex 57ffa84ab..54f821f84 100644--- a/agent/tests/test_enforcement_l6.py+++ b/agent/tests/test_enforcement_l6.py@@ -23,13 +23,13 @@ import src.live.enforcement as enforcementimport src.live.order_guard as order_guardimport src.live.paths as pathsfrom src.live.classification import ToolClass-from src.live.extractors.robinhood import extract_order_intent+from src.trading.connectors.robinhood.extractor import extract_order_intentfrom src.live.mandate.model import (MANDATE_SCHEMA_VERSION,AssetClass,InstrumentType,)-from src.live.robinhood_classification import ROBINHOOD_TOOL_CLASS+from src.trading.connectors.robinhood.classification import ROBINHOOD_TOOL_CLASSfrom src.tools.mcp import MCPRemoteToolSpecdiff --git a/agent/tests/test_ibkr_local.py b/agent/tests/test_ibkr_local.pynew file mode 100644index 000000000..b77bdf6e5--- /dev/null+++ b/agent/tests/test_ibkr_local.py@@ -0,0 +1,233 @@+"""Unit tests for the local IBKR TWS / IB Gateway bridge."""++from __future__ import annotations++import json+import sys+import types+from types import SimpleNamespace+from unittest.mock import patch++import pytest++from src.trading.connectors.ibkr import local+from src.tools.trading_connector_tool import TradingPositionsTool++pytestmark = pytest.mark.unit+++class _FakeContract:+ def __init__(self) -> None:+ self.symbol = ""+ self.secType = ""+ self.exchange = ""+ self.currency = ""+ self.conId = 0+ self.localSymbol = ""+++class _FakeStock(_FakeContract):+ def __init__(self, symbol: str, exchange: str, currency: str) -> None:+ super().__init__()+ self.symbol = symbol+ self.secType = "STK"+ self.exchange = exchange+ self.currency = currency+ self.conId = 101+ self.localSymbol = symbol+++class _FakeIB:+ def connect(self, host, port, *, clientId, timeout, readonly=True, account=""):+ self.host = host+ self.port = port+ self.client_id = clientId+ self.readonly = readonly+ self.account = account++ def disconnect(self):+ self.disconnected = True++ def managedAccounts(self):+ return ["DU12345"]++ def accountSummary(self, account=""):+ return [+ SimpleNamespace(account="DU12345", tag="NetLiquidation", value="100000", currency="USD", modelCode="")+ ]++ def positions(self):+ contract = SimpleNamespace(+ symbol="AAPL",+ localSymbol="AAPL",+ secType="STK",+ exchange="SMART",+ currency="USD",+ conId=265598,+ )+ return [SimpleNamespace(account="DU12345", contract=contract, position=3, avgCost=150.0)]++ def openTrades(self):+ return []++ def qualifyContracts(self, contract):+ return [contract]++ def reqMktData(self, contract, genericTickList, snapshot, regulatorySnapshot):+ return SimpleNamespace(bid=100.0, ask=100.2, last=100.1, close=99.0, volume=1234, time="")++ def cancelMktData(self, contract):+ return None++ def sleep(self, seconds):+ return None++ def reqHistoricalData(+ self,+ contract,+ *,+ endDateTime,+ durationStr,+ barSizeSetting,+ whatToShow,+ useRTH,+ formatDate,+ ):+ return [SimpleNamespace(date="2026-05-29", open=1, high=2, low=0.5, close=1.5, volume=100)]+++def fake_ib_async(monkeypatch: pytest.MonkeyPatch):+ module = types.ModuleType("ib_async")+ module.IB = _FakeIB+ module.Stock = _FakeStock+ module.Contract = _FakeContract+ monkeypatch.setitem(sys.modules, "ib_async", module)+ monkeypatch.setattr(local, "tcp_port_open", lambda *_, **__: True)+ return module+++def test_config_defaults_to_paper_port() -> None:+ cfg = local.IBKRLocalConfig.from_mapping({"profile": "paper"})+ assert cfg.host == "127.0.0.1"+ assert cfg.port == 7497+ assert cfg.readonly is True+++def test_account_snapshot_reads_summary(fake_ib_async) -> None:+ cfg = local.IBKRLocalConfig()+ result = local.get_account_snapshot(cfg)++ assert result["status"] == "ok"+ assert result["accounts"] == ["DU12345"]+ assert result["summary"][0]["tag"] == "NetLiquidation"+++def test_positions_are_serialized(fake_ib_async) -> None:+ result = local.get_positions(local.IBKRLocalConfig())++ assert result["positions"][0]["symbol"] == "AAPL"+ assert result["positions"][0]["position"] == 3+++def test_quote_and_history_are_readonly(fake_ib_async) -> None:+ quote = local.get_quote("AAPL", config=local.IBKRLocalConfig())+ history = local.get_historical_bars("AAPL", config=local.IBKRLocalConfig())++ assert quote["quote"]["last"] == 100.1+ assert history["bars"][0]["close"] == 1.5+++def test_paper_profile_rejects_live_account(monkeypatch: pytest.MonkeyPatch, fake_ib_async) -> None:+ class _LiveIB(_FakeIB):+ def managedAccounts(self):+ return ["U12345"]++ def accountSummary(self, account=""):+ return [SimpleNamespace(account="U12345", tag="NetLiquidation", value="1", currency="USD", modelCode="")]++ fake_ib_async.IB = _LiveIB++ with pytest.raises(local.IBKRProfileMismatchError):+ local.get_account_snapshot(local.IBKRLocalConfig(profile="paper"))+++def test_check_status_reports_missing_sdk(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(local, "ib_async_available", lambda: False)+ monkeypatch.setattr(local, "tcp_port_open", lambda *_, **__: True)++ report = local.check_local_status(local.IBKRLocalConfig(), scan=False)++ assert report["status"] == "error"+ assert "ib_async" in report["error"]+++def test_positions_tool_returns_json(fake_ib_async) -> None:+ payload = json.loads(TradingPositionsTool().execute(connection="ibkr-paper-local"))++ assert payload["status"] == "ok"+ assert payload["profile_id"] == "ibkr-paper-local"+ assert payload["positions"][0]["symbol"] == "AAPL"+++def test_service_uses_persisted_ibkr_local_config(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ """Configured local endpoint values must survive later connector calls."""+ from src.trading import service++ monkeypatch.setattr(local, "get_runtime_root", lambda: tmp_path)+ local.save_config(+ local.IBKRLocalConfig(+ profile="paper",+ host="192.168.10.8",+ port=4002,+ client_id=123,+ account="DU999",+ )+ )+ captured: dict[str, local.IBKRLocalConfig] = {}++ def _check(cfg: local.IBKRLocalConfig) -> dict[str, object]:+ captured["cfg"] = cfg+ return {"status": "ok", "ports": [], "target": {}, "sdk": {"installed": True}}++ monkeypatch.setattr(local, "check_local_status", _check)++ assert service.check_connection("ibkr-paper-local")["status"] == "ok"++ cfg = captured["cfg"]+ assert cfg.host == "192.168.10.8"+ assert cfg.port == 4002+ assert cfg.client_id == 123+ assert cfg.account == "DU999"+++def test_cli_connector_routes_to_handler() -> None:+ from cli._legacy import _build_parser, _dispatch_connector++ args = _build_parser().parse_args(["connector", "check", "ibkr-paper-local", "--account", "DU12345"])+ with patch("cli._legacy.cmd_connector_check", return_value=0) as handler:+ assert _dispatch_connector(args) == 0+ handler.assert_called_once_with(+ "ibkr-paper-local",+ host=None,+ port=None,+ client_id=None,+ account="DU12345",+ )+++def test_cli_connector_check_passes_account_to_backend() -> None:+ from cli._legacy import cmd_connector_check++ report = {"status": "ok", "ports": [], "target": {}, "sdk": {"installed": True}}+ with patch("src.trading.service.check_connection", return_value=report) as check:+ assert cmd_connector_check("ibkr-paper-local", account="DU12345") == 0+ check.assert_called_once_with(+ "ibkr-paper-local",+ host=None,+ port=None,+ client_id=None,+ account="DU12345",+ )diff --git a/agent/tests/test_ibkr_mcp_seed.py b/agent/tests/test_ibkr_mcp_seed.pynew file mode 100644index 000000000..4e3d8f27a--- /dev/null+++ b/agent/tests/test_ibkr_mcp_seed.py@@ -0,0 +1,91 @@+"""IBKR official MCP read-only probe wiring.++The IBKR endpoint exposes tool names only after OAuth, so the seed uses a+read-only ``mcp.read`` wildcard probe. These tests keep that narrow exception+from becoming an ungated live-broker wildcard.+"""++from __future__ import annotations++from typing import Any++import pytest+from fastmcp.client.client import CallToolResult+from mcp import types as mcp_types++from src.config.schema import AgentConfig, IBKR_MCP_SERVER_SEED+from src.live.order_guard import LiveOrderGuardTool+from src.live.registry import is_live_broker, wrap_live_broker_tools+from src.tools.mcp import MCPRemoteTool, build_mcp_tool_wrappers++pytestmark = pytest.mark.unit+++class _FakeIBKRClient:+ """Mock IBKR MCP client exposing one annotated read and one write."""++ async def __aenter__(self) -> "_FakeIBKRClient":+ return self++ async def __aexit__(self, exc_type, exc, tb) -> None:+ return None++ async def list_tools(self) -> list[mcp_types.Tool]:+ return [+ mcp_types.Tool(+ name="portfolio",+ description="read account portfolio",+ inputSchema={"type": "object"},+ annotations=mcp_types.ToolAnnotations(readOnlyHint=True),+ ),+ mcp_types.Tool(+ name="place_order",+ description="place an order",+ inputSchema={"type": "object"},+ annotations=mcp_types.ToolAnnotations(readOnlyHint=False),+ ),+ ]++ async def call_tool(+ self,+ name: str,+ arguments: dict[str, Any] | None = None,+ *,+ timeout: float | int | None = None,+ raise_on_error: bool = False,+ ) -> CallToolResult:+ raise AssertionError("registry assembly must not call tools")+++def _factory() -> _FakeIBKRClient:+ return _FakeIBKRClient()+++def test_ibkr_seed_validates_as_readonly_probe() -> None:+ cfg = AgentConfig.model_validate({"mcpServers": {"ibkr": IBKR_MCP_SERVER_SEED}})+ server = cfg.mcp_servers["ibkr"]++ assert server.url == "https://api.ibkr.com/v1/api/mcp"+ assert server.auth is not None+ assert server.auth.scopes == ["mcp.read"]+ assert server.enabled_tools == ["*"]+++def test_ibkr_alias_url_resolves_to_live_broker_and_wraps_writes() -> None:+ cfg = AgentConfig.model_validate({"mcpServers": {"ib": IBKR_MCP_SERVER_SEED}})+ server = cfg.mcp_servers["ib"]++ assert is_live_broker("ib", server.url)++ wrappers = build_mcp_tool_wrappers("ib", server, client_factory=_factory)+ gated = wrap_live_broker_tools("ib", wrappers, url=server.url)+ by_name = {tool._spec.remote_name: tool for tool in gated}++ assert type(by_name["portfolio"]) is MCPRemoteTool+ assert by_name["portfolio"].is_readonly is True+ assert isinstance(by_name["place_order"], LiveOrderGuardTool)+ assert by_name["place_order"].broker == "ibkr"+++def test_ibkr_lookalike_host_is_not_live_broker() -> None:+ assert not is_live_broker("ib", "https://api.ibkr.com.evil.test/v1/api/mcp")diff --git a/agent/tests/test_mcp_oauth_schema.py b/agent/tests/test_mcp_oauth_schema.pyindex 0b1323dbd..a0168fc1a 100644--- a/agent/tests/test_mcp_oauth_schema.py+++ b/agent/tests/test_mcp_oauth_schema.py@@ -23,6 +23,7 @@ from fastmcp.client.transports.stdio import StdioTransportfrom pydantic import ValidationErrorfrom src.config.schema import (+ IBKR_MCP_SERVER_SEED,LIVE_BROKER_SERVER_KEYS,ROBINHOOD_MCP_SERVER_SEED,AgentConfig,@@ -46,6 +47,9 @@ def test_oauth_config_round_trip_snake_and_camel() -> None:"client_name": "Vibe-Trading","cache_dir": "~/.vibe-trading/live/robinhood/oauth","callback_port": 8765,+ "client_id": "client-id",+ "client_secret": "client-secret",+ "client_metadata_url": "https://example.com/oauth/client.json",})camel = MCPOAuthConfig.model_validate(@@ -55,11 +59,17 @@ def test_oauth_config_round_trip_snake_and_camel() -> None:"clientName": "Vibe-Trading","cacheDir": "~/.vibe-trading/live/robinhood/oauth","callbackPort": 8765,+ "clientId": "client-id",+ "clientSecret": "client-secret",+ "clientMetadataUrl": "https://example.com/oauth/client.json",})assert snake == camelassert snake.client_name == "Vibe-Trading"assert snake.callback_port == 8765+ assert snake.client_id == "client-id"+ assert snake.client_secret == "client-secret"+ assert snake.client_metadata_url == "https://example.com/oauth/client.json"def test_server_config_carries_auth() -> None:@@ -92,6 +102,18 @@ def test_robinhood_seed_is_readonly_and_oauth() -> None:assert "robinhood" in LIVE_BROKER_SERVER_KEYS+def test_ibkr_seed_is_official_readonly_oauth_probe() -> None:+ cfg = AgentConfig.model_validate({"mcpServers": {"ibkr": IBKR_MCP_SERVER_SEED}})+ ibkr = cfg.mcp_servers["ibkr"]+ assert ibkr.resolved_transport() == "streamableHttp"+ assert ibkr.url == "https://api.ibkr.com/v1/api/mcp"+ assert ibkr.auth is not None and ibkr.auth.type == "oauth"+ assert ibkr.auth.scopes == ["mcp.read"]+ assert ibkr.auth.cache_dir == "~/.vibe-trading/live/ibkr/oauth"+ assert ibkr.enabled_tools == ["*"]+ assert "ibkr" in LIVE_BROKER_SERVER_KEYS++# --------------------------------------------------------------------------- ## Validator rejections# --------------------------------------------------------------------------- #@@ -135,6 +157,38 @@ def test_live_broker_rejects_wildcard_allowlist() -> None:)+def test_ibkr_rejects_wildcard_when_write_scope_is_requested() -> None:+ with pytest.raises(ValidationError, match="wildcard"):+ AgentConfig.model_validate(+ {+ "mcpServers": {+ "ibkr": {+ "type": "streamableHttp",+ "url": "https://api.ibkr.com/v1/api/mcp",+ "auth": {"type": "oauth", "scopes": ["mcp.read", "mcp.write"]},+ "enabledTools": ["*"],+ }+ }+ }+ )+++def test_ibkr_rejects_wildcard_without_read_scope() -> None:+ with pytest.raises(ValidationError, match="wildcard"):+ AgentConfig.model_validate(+ {+ "mcpServers": {+ "ibkr": {+ "type": "streamableHttp",+ "url": "https://api.ibkr.com/v1/api/mcp",+ "auth": {"type": "oauth", "scopes": ["openid"]},+ "enabledTools": ["*"],+ }+ }+ }+ )++def test_non_live_broker_still_allows_wildcard() -> None:# A non-broker HTTP server keeps the default ["*"] semantics.cfg = AgentConfig.model_validate(@@ -160,6 +214,9 @@ def test_build_client_yields_oauth_streamable_transport() -> None:"scopes": ["trading.read"],"client_name": "Vibe-Trading","callback_port": 8765,+ "client_id": "client-id",+ "client_secret": "client-secret",+ "client_metadata_url": "https://example.com/oauth/client.json",},})@@ -171,6 +228,9 @@ def test_build_client_yields_oauth_streamable_transport() -> None:assert transport.auth._scopes == ["trading.read"]assert transport.auth._client_name == "Vibe-Trading"assert transport.auth._callback_port == 8765+ assert transport.auth._client_id == "client-id"+ assert transport.auth._client_secret == "client-secret"+ assert transport.auth._client_metadata_url == "https://example.com/oauth/client.json"def test_static_header_http_path_unchanged() -> None:diff --git a/agent/tests/test_mcp_regression.py b/agent/tests/test_mcp_regression.pyindex 14a93c896..9dfe6ed41 100644--- a/agent/tests/test_mcp_regression.py+++ b/agent/tests/test_mcp_regression.py@@ -26,6 +26,7 @@ from __future__ import annotationsimport importlibimport sysfrom pathlib import Path+from typing import Anyimport pytest@@ -117,7 +118,7 @@ def test_mcp_server_imports_without_raising() -> None:def test_mcp_server_exposes_expected_tool_count() -> None:"""The MCP server FastMCP instance must expose the expected number of tools.- 22 tools are documented. We use >= 20 as the floor to tolerate minor+ 35 tools are documented. We use >= 30 as the floor to tolerate minoradditions or future removals without breaking this regression gate.Uses the public async list_tools() API so this test is stable acrossfastmcp version upgrades.@@ -130,8 +131,8 @@ def test_mcp_server_exposes_expected_tool_count() -> None:tools = asyncio.run(mcp_instance.list_tools())tool_count = len(tools)- assert tool_count >= 20, (- f"Expected at least 20 MCP server tools, found {tool_count}. "+ assert tool_count >= 30, (+ f"Expected at least 30 MCP server tools, found {tool_count}. ""Check whether any tools were accidentally removed from mcp_server.py.")@@ -164,9 +165,77 @@ def test_mcp_server_exposes_well_known_tool_names() -> None:"get_research_goal","add_goal_evidence","update_research_goal_status",+ "trading_connections",+ "trading_select_connection",+ "trading_check",+ "trading_account",+ "trading_positions",+ "trading_orders",+ "trading_quote",+ "trading_history",}missing = expected - registeredassert not missing, (f"MCP server is missing well-known tools: {missing}. ""A tool may have been accidentally renamed or removed.")+++class _RecordingRegistry:+ """Tiny registry stub that records MCP wrapper payloads."""++ def __init__(self) -> None:+ self.calls: list[tuple[str, dict[str, Any]]] = []++ def execute(self, name: str, payload: dict[str, Any]) -> str:+ self.calls.append((name, payload))+ return "{}"+++def test_trading_mcp_wrappers_do_not_send_implicit_local_overrides(monkeypatch: pytest.MonkeyPatch) -> None:+ """No-arg trading_* MCP calls must not override profile defaults."""+ mod = _import_mcp_server()+ registry = _RecordingRegistry()+ monkeypatch.setattr(mod, "_get_registry", lambda: registry)++ mod.trading_check()+ mod.trading_account()+ mod.trading_positions()+ mod.trading_orders()++ assert registry.calls == [+ ("trading_check", {}),+ ("trading_account", {}),+ ("trading_positions", {}),+ ("trading_orders", {"include_executions": False}),+ ]+++def test_trading_mcp_wrappers_forward_explicit_local_overrides(monkeypatch: pytest.MonkeyPatch) -> None:+ """Explicit local override fields are still forwarded to the backend."""+ mod = _import_mcp_server()+ registry = _RecordingRegistry()+ monkeypatch.setattr(mod, "_get_registry", lambda: registry)++ mod.trading_account(+ connection="ibkr-paper-local",+ host="localhost",+ port=4002,+ client_id=123,+ account="DU12345",+ )+ mod.trading_check(account="DU12345")++ assert registry.calls == [+ (+ "trading_account",+ {+ "connection": "ibkr-paper-local",+ "host": "localhost",+ "port": 4002,+ "client_id": 123,+ "account": "DU12345",+ },+ ),+ ("trading_check", {"account": "DU12345"}),+ ]diff --git a/agent/tests/test_mcp_server_smoke.py b/agent/tests/test_mcp_server_smoke.pyindex ac8c0497d..2d430dd56 100644--- a/agent/tests/test_mcp_server_smoke.py+++ b/agent/tests/test_mcp_server_smoke.py@@ -40,10 +40,10 @@ INIT_TIMEOUT = 30.0# safe lower bound that still flags the deadlock quickly.CALL_TIMEOUT = 15.0-# Tools we rely on as a baseline. The repo currently ships 22 tools; we-# assert ``>= 20`` so unrelated tool additions / removals don't break the+# Tools we rely on as a baseline. The repo currently ships 35 tools; we+# assert ``>= 30`` so unrelated tool additions / removals don't break the# test, but a regression that drops half the catalogue still fires.-EXPECTED_MIN_TOOL_COUNT = 20+EXPECTED_MIN_TOOL_COUNT = 30REQUIRED_TOOL_NAMES = {"analyze_options","get_market_data",@@ -52,6 +52,14 @@ REQUIRED_TOOL_NAMES = {"get_research_goal","add_goal_evidence","update_research_goal_status",+ "trading_connections",+ "trading_select_connection",+ "trading_check",+ "trading_account",+ "trading_positions",+ "trading_orders",+ "trading_quote",+ "trading_history",}diff --git a/agent/tests/test_no_set_mandate_tool.py b/agent/tests/test_no_set_mandate_tool.pyindex 5b2494b9e..0bc646152 100644--- a/agent/tests/test_no_set_mandate_tool.py+++ b/agent/tests/test_no_set_mandate_tool.py@@ -21,12 +21,11 @@ import astimport refrom pathlib import Path-import pytest-import src.live.mandate.store as storeAGENT_DIR = Path(__file__).resolve().parent.parentLIVE_DIR = AGENT_DIR / "src" / "live"+TRADING_DIR = AGENT_DIR / "src" / "trading"_FORBIDDEN_NAME = re.compile(r"^(_)?(set|write|update|grant|authorize|enable|widen)_(mandate|limit|live|authorization)([_a-z]*)?$"@@ -71,7 +70,7 @@ def test_agent_reachable_modules_never_open_mandate_for_write() -> None:LIVE_DIR / "order_guard.py",LIVE_DIR / "enforcement.py",LIVE_DIR / "extractors" / "__init__.py",- LIVE_DIR / "extractors" / "robinhood.py",+ TRADING_DIR / "connectors" / "robinhood" / "extractor.py",LIVE_DIR / "mandate" / "store.py",]write_modes = {"w", "wb", "a", "ab", "w+", "r+", "x"}diff --git a/agent/tests/test_readonly_default.py b/agent/tests/test_readonly_default.pyindex cc7b453c9..45cd37c4c 100644--- a/agent/tests/test_readonly_default.py+++ b/agent/tests/test_readonly_default.py@@ -23,7 +23,6 @@ from __future__ import annotationsimport jsonfrom datetime import datetime, timedelta, timezonefrom pathlib import Path-from typing import Anyimport pytestfrom fastmcp.client.client import CallToolResult@@ -39,7 +38,7 @@ from src.config.schema import (from src.live.mandate.model import MANDATE_SCHEMA_VERSIONfrom src.live.order_guard import LiveOrderGuardToolfrom src.live.registry import is_live_broker, wrap_live_broker_tools-from src.live.robinhood_classification import ROBINHOOD_TOOL_CLASS+from src.trading.connectors.robinhood.classification import ROBINHOOD_TOOL_CLASSfrom src.live.classification import ToolClassfrom src.tools.mcp import MCPRemoteTool, build_mcp_tool_wrappersdiff --git a/agent/tests/test_trading_connections.py b/agent/tests/test_trading_connections.pynew file mode 100644index 000000000..aa99290ef--- /dev/null+++ b/agent/tests/test_trading_connections.py@@ -0,0 +1,97 @@+"""Tests for connector-first trading profile operations."""++from __future__ import annotations++import json+from types import SimpleNamespace++import pytest++from src.trading import profiles, service+from src.tools import build_registry+from src.tools.trading_connector_tool import TradingSelectConnectionTool++pytestmark = pytest.mark.unit+++def _agent_config(server) -> SimpleNamespace:+ return SimpleNamespace(mcp_servers={"robinhood": server})+++def test_remote_call_requires_enabled_tool(monkeypatch: pytest.MonkeyPatch) -> None:+ """Generic remote reads must respect the operator MCP allowlist."""+ server = SimpleNamespace(+ url="https://agent.robinhood.com/mcp/trading",+ enabled_tools=["get_account"],+ auth=SimpleNamespace(cache_dir="/tmp/vibe-no-token"),+ )+ monkeypatch.setattr("src.config.loader.load_agent_config", lambda: _agent_config(server))+ monkeypatch.setattr("src.live.registry.has_cached_oauth_token", lambda *_: True)++ result = service.get_positions("robinhood-live-mcp")++ assert result["status"] == "error"+ assert "not enabled" in result["error"]+++def test_remote_call_requires_cached_oauth(monkeypatch: pytest.MonkeyPatch) -> None:+ """Generic remote reads must not trigger OAuth from tool/API/MCP paths."""+ server = SimpleNamespace(+ url="https://agent.robinhood.com/mcp/trading",+ enabled_tools=["get_positions"],+ auth=SimpleNamespace(cache_dir="/tmp/vibe-no-token"),+ )+ monkeypatch.setattr("src.config.loader.load_agent_config", lambda: _agent_config(server))+ monkeypatch.setattr("src.live.registry.has_cached_oauth_token", lambda *_: False)++ result = service.get_positions("robinhood-live-mcp")++ assert result["status"] == "not_authorized"+ assert "connector authorize robinhood-live-mcp" in result["error"]+++def test_ibkr_official_profile_does_not_advertise_unknown_generic_reads() -> None:+ """IBKR official MCP stays honest until stable remote tool names are known."""+ profile = profiles.profile_by_id("ibkr-live-official-mcp-readonly")++ assert profile.capabilities == ("mcp.read.discovery",)+ result = service.get_account(profile.id)+ assert result["status"] == "error"+ assert "does not support" in result["error"]+++def test_select_connection_tool_returns_canonical_profile_id(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ """Selecting a profile should persist and return the canonical id."""+ monkeypatch.setattr(profiles, "get_runtime_root", lambda: tmp_path)++ result = TradingSelectConnectionTool().execute(connection="IBKR-PAPER-LOCAL")++ assert result+ payload = json.loads(result)+ assert payload["status"] == "ok"+ assert payload["selected_profile"] == "ibkr-paper-local"+ assert profiles.load_selected_profile_id() == "ibkr-paper-local"+++def test_live_broker_mcp_wrappers_are_hidden_from_agent_registry(monkeypatch: pytest.MonkeyPatch) -> None:+ """Connector-first registry must not expose broker-specific mcp_* tools."""+ server = SimpleNamespace(+ url="https://agent.robinhood.com/mcp/trading",+ enabled_tools=["get_positions"],+ auth=SimpleNamespace(cache_dir="/tmp/vibe-token"),+ )+ agent_config = SimpleNamespace(mcp_servers={"robinhood": server})+ monkeypatch.setattr("src.live.registry.is_live_broker", lambda *_: True)+ monkeypatch.setattr("src.live.registry.should_register_live_channel", lambda **_: True)++ def fail_build_wrappers(*_, **__):+ raise AssertionError("live broker wrappers should not be registered directly")++ monkeypatch.setattr("src.tools.mcp.build_mcp_tool_wrappers", fail_build_wrappers)++ registry = build_registry(agent_config=agent_config, include_shell_tools=False)++ assert "trading_positions" in registry.tool_names+ assert not any(name.startswith("mcp_robinhood_") for name in registry.tool_names)diff --git a/frontend/src/components/chat/MandateProposalCard.tsx b/frontend/src/components/chat/MandateProposalCard.tsxindex 723d1361f..b351a7723 100644--- a/frontend/src/components/chat/MandateProposalCard.tsx+++ b/frontend/src/components/chat/MandateProposalCard.tsx@@ -177,7 +177,7 @@ function ProfileTile({}/**- * Renders a live-trading mandate proposal (SPEC Consent §1/§2).+ * Renders a connector-runtime mandate proposal (SPEC Consent §1/§2).** Each profile tile shows concrete numbers (universe, max order, daily cap, leverage,* instruments). Committing calls `api.commitMandate` — a privileged surface action,@@ -191,9 +191,15 @@ export const MandateProposalCard = memo(function MandateProposalCard({ proposal,const handleCommit = useCallback(async (ordinal: number) => {if (busyOrdinal != null) return;+ const broker = proposal.account?.broker?.trim().toLowerCase();+ if (!broker) {+ toast.error("Cannot commit mandate: connector broker is missing. Ask the agent to regenerate the proposal.");+ return;+ }setBusyOrdinal(ordinal);try {await api.commitMandate({+ broker,proposal_id: proposal.proposal_id,selected_ordinal: ordinal,adjustments: null,@@ -207,7 +213,7 @@ export const MandateProposalCard = memo(function MandateProposalCard({ proposal,toast.error(error instanceof Error ? error.message : "Failed to commit mandate.");}},- [busyOrdinal, proposal.proposal_id, proposal.session_id],+ [busyOrdinal, proposal.account?.broker, proposal.proposal_id, proposal.session_id],);// Collapsed state: a compact active-mandate badge (same visual family as the goal badge).@@ -254,7 +260,7 @@ export const MandateProposalCard = memo(function MandateProposalCard({ proposal,)}<div className="min-w-0"><p className="text-sm font-semibold text-foreground">- {isReauth ? "Re-authorize live mandate" : "Live trading mandate"}+ {isReauth ? "Re-authorize connector mandate" : "Connector runtime mandate"}</p>{proposal.intent_normalized && (<p className="text-xs text-muted-foreground">{proposal.intent_normalized}</p>diff --git a/frontend/src/components/chat/RunnerStatus.tsx b/frontend/src/components/chat/RunnerStatus.tsxindex ea32c0c30..b751ecccd 100644--- a/frontend/src/components/chat/RunnerStatus.tsx+++ b/frontend/src/components/chat/RunnerStatus.tsx@@ -1,4 +1,4 @@-import { memo, useCallback, useState } from "react";+import { memo, useCallback, useEffect, useState } from "react";import {Activity,Power,@@ -17,6 +17,7 @@ import {type LiveStatus,type LiveBrokerStatus,type LiveMandateLimits,+ type LiveAuthorizeResponse,} from "@/lib/api";interface Props {@@ -36,9 +37,11 @@ function formatUsd(value: number | undefined): string {return `$${value.toLocaleString("en-US", { maximumFractionDigits: 0 })}`;}-function formatRelative(iso: string | null | undefined): string {- if (!iso) return "never";- const then = new Date(iso).getTime();+function formatRelative(value: string | number | null | undefined): string {+ if (value == null || value === "") return "never";+ const then = typeof value === "number"+ ? (value < 1_000_000_000_000 ? value * 1000 : value)+ : new Date(value).getTime();if (!Number.isFinite(then)) return "unknown";const deltaSec = Math.round((Date.now() - then) / 1000);if (deltaSec < 0) return "just now";@@ -66,17 +69,22 @@ function formatCountdown(iso: string | undefined): { label: string; expired: boofunction summarizeLimits(limits: LiveMandateLimits | undefined): string {if (!limits) return "";const parts: string[] = [];- if (limits.max_order_usd != null) parts.push(`≤${formatUsd(limits.max_order_usd)}/order`);- if (limits.daily_trade_cap != null) parts.push(`${limits.daily_trade_cap}/day`);- if (limits.leverage != null) {- const lev = typeof limits.leverage === "number"- ? (limits.leverage <= 1 ? "no leverage" : `${limits.leverage}×`)- : (limits.leverage.toLowerCase() === "none" ? "no leverage" : limits.leverage);- parts.push(lev);- }+ if (limits.max_order_notional_usd != null) parts.push(`≤${formatUsd(limits.max_order_notional_usd)}/order`);+ if (limits.max_trades_per_day != null) parts.push(`${limits.max_trades_per_day}/day`);+ if (limits.max_leverage != null) parts.push(limits.max_leverage <= 1 ? "no leverage" : `${limits.max_leverage}×`);return parts.join(" · ");}+function fallbackConnectorProfileForBroker(broker: string): string {+ if (broker === "robinhood") return "robinhood-live-mcp";+ if (broker === "ibkr") return "ibkr-live-official-mcp-readonly";+ return `${broker}-live-mcp`;+}++function fallbackAuthorizeInstruction(broker: string): string {+ return `Run \`vibe-trading connector authorize ${fallbackConnectorProfileForBroker(broker)}\` from the desktop session that will hold the broker connection.`;+}+function BrokerRow({broker,halted,@@ -87,20 +95,44 @@ function BrokerRow({onRefresh: () => void;}) {const [busy, setBusy] = useState(false);+ const [authorizeHint, setAuthorizeHint] = useState<LiveAuthorizeResponse | null>(null);+ const [authorizeFailed, setAuthorizeFailed] = useState(false);+ const brokerKey = broker.auth.broker;+ const authorized = broker.auth.oauth_token_present;const runnerAlive = broker.runner?.alive ?? false;const mandate = broker.mandate ?? null;const countdown = formatCountdown(mandate?.expires_at);+ const authorizeInstruction = authorizeHint?.instruction+ ?? (authorizeFailed ? fallbackAuthorizeInstruction(brokerKey) : "Loading connector authorization instructions...");+ const authorizeNote = "The connector channel stays read-only until OAuth succeeds and a mandate is committed.";++ useEffect(() => {+ let cancelled = false;+ setAuthorizeHint(null);+ setAuthorizeFailed(false);+ if (authorized || !brokerKey) return () => { cancelled = true; };++ api.authorizeLive(brokerKey)+ .then((response) => {+ if (!cancelled) setAuthorizeHint(response);+ })+ .catch(() => {+ if (!cancelled) setAuthorizeFailed(true);+ });++ return () => { cancelled = true; };+ }, [authorized, brokerKey]);const toggleRunner = useCallback(async () => {if (busy) return;setBusy(true);try {if (runnerAlive) {- await api.stopLiveRunner(broker.broker);- toast.success(`Runner stopped for ${broker.broker}`);+ await api.stopLiveRunner(brokerKey);+ toast.success(`Runner stopped for ${brokerKey}`);} else {- await api.startLiveRunner(broker.broker);- toast.success(`Runner started for ${broker.broker}`);+ await api.startLiveRunner(brokerKey);+ toast.success(`Runner started for ${brokerKey}`);}onRefresh();} catch (error) {@@ -108,14 +140,14 @@ function BrokerRow({} finally {setBusy(false);}- }, [broker.broker, busy, runnerAlive, onRefresh]);+ }, [brokerKey, busy, runnerAlive, onRefresh]);return (<div className="grid gap-2 rounded-lg border bg-muted/20 p-2.5"><div className="flex items-center justify-between gap-2"><div className="flex min-w-0 items-center gap-1.5">- <span className="truncate text-xs font-semibold capitalize text-foreground">{broker.broker}</span>- {broker.authorized ? (+ <span className="truncate text-xs font-semibold capitalize text-foreground">{brokerKey}</span>+ {authorized ? (<span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-1.5 py-0.5 text-[10px] font-medium text-emerald-600 dark:text-emerald-400"><ShieldCheck className="h-2.5 w-2.5" />Authorized@@ -129,22 +161,23 @@ function BrokerRow({</div></div>- {/* Connect-broker on-ramp for unauthorized brokers (C2). The OAuth bootstrap+ {/* Connect-profile on-ramp for unauthorized brokers (C2). The OAuth bootstrapis a desktop-only CLI step (SPEC §4 headless behavior), so the web surfacesurfaces the discoverable instruction rather than driving the browser flow. */}- {!broker.authorized ? (+ {!authorized ? (<div className="grid gap-1.5 rounded-md border border-dashed border-primary/30 bg-primary/5 p-2"><div className="flex items-center gap-1.5 text-[11px] font-medium text-primary"><PlugZap className="h-3 w-3 shrink-0" />- Connect this broker to enable live trading+ Connect this profile to enable connector runtime</div><p className="text-[10px] leading-relaxed text-muted-foreground">- Authorize on a desktop session:{" "}- <code className="rounded bg-background px-1 py-0.5 font-mono text-[10px] text-foreground">- vibe-trading live authorize {broker.broker}- </code>- . The channel stays read-only until OAuth succeeds and a mandate is committed.+ {authorizeInstruction}</p>+ {authorizeNote && (+ <p className="text-[10px] leading-relaxed text-muted-foreground">+ {authorizeNote}+ </p>+ )}</div>) : (<>@@ -199,7 +232,7 @@ function BrokerRow({</div>) : (<div className="rounded-md border border-dashed bg-background/40 p-2 text-[10px] text-muted-foreground">- No active mandate. Ask the agent to propose one, then commit it to begin autonomous trading.+ No active mandate. Ask the agent to propose one, then commit it before starting the connector runtime.</div>)}@@ -211,7 +244,7 @@ function BrokerRow({</span>) : (<span className="text-[10px] text-muted-foreground">- {runnerAlive ? "Trading autonomously inside mandate" : "Idle"}+ {runnerAlive ? "Runtime active inside mandate" : "Idle"}</span>)}<button@@ -241,10 +274,10 @@ function BrokerRow({** Renders the shared `GET /live/status` snapshot (polled once by Agent.tsx and passed* in as `status`, so the kill switch and this panel share a single poller). Per authorized- * broker: runner running state, last heartbeat tick, the active mandate's limits, and an+ * profile: runner running state, last heartbeat tick, the active mandate's limits, and an* expiry countdown. `onRefresh` asks the parent to re-poll after a runner start/stop. Unauthorized- * brokers get a "Connect broker" on-ramp so a web user can discover how to enable live- * trading. Runner start/stop are privileged surface fetches (`api.startLiveRunner` /+ * profiles get a connector on-ramp so a web user can discover how to enable connector+ * runtime execution. Runner start/stop are privileged surface fetches (`api.startLiveRunner` /* `api.stopLiveRunner`), never chat messages. Collapses to a compact toggle.*/export const RunnerStatus = memo(function RunnerStatus({ status, unavailable, halted, onRefresh }: Props) {@@ -253,9 +286,9 @@ export const RunnerStatus = memo(function RunnerStatus({ status, unavailable, haif (unavailable) return null;if (!status || status.brokers.length === 0) return null;- const isHalted = halted ?? status.halted;+ const isHalted = halted ?? status.global_halted;const anyRunning = status.brokers.some((b) => b.runner?.alive);- const authorizedCount = status.brokers.filter((b) => b.authorized).length;+ const authorizedCount = status.brokers.filter((b) => b.auth.oauth_token_present).length;return (<div className="grid gap-2">@@ -263,13 +296,13 @@ export const RunnerStatus = memo(function RunnerStatus({ status, unavailable, hatype="button"onClick={() => setOpen((v) => !v)}className="inline-flex max-w-full items-center gap-1.5 justify-self-start rounded-lg bg-primary/10 px-2.5 py-1 text-left text-xs font-medium text-primary transition-colors hover:bg-primary/15"- aria-label="Live runtime status"+ aria-label="Connector runtime status"aria-expanded={open}><Activity className="h-3 w-3 shrink-0" />- <span className="shrink-0">Live runtime</span>+ <span className="shrink-0">Connector runtime</span><span className="truncate text-muted-foreground">- {authorizedCount > 0 ? `${authorizedCount} connected` : "no broker connected"}+ {authorizedCount > 0 ? `${authorizedCount} connected` : "no connector connected"}</span>{anyRunning && !isHalted && (<span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-1.5 py-0.5 text-[10px] font-medium text-emerald-600 dark:text-emerald-400">@@ -289,7 +322,7 @@ export const RunnerStatus = memo(function RunnerStatus({ status, unavailable, ha{open && (<div className="grid gap-2 rounded-xl border border-primary/20 bg-background/95 p-3 shadow-sm">{status.brokers.map((broker) => (- <BrokerRow key={broker.broker} broker={broker} halted={isHalted} onRefresh={onRefresh} />+ <BrokerRow key={broker.auth.broker} broker={broker} halted={isHalted || broker.halted} onRefresh={onRefresh} />))}</div>)}diff --git a/frontend/src/components/chat/WelcomeScreen.tsx b/frontend/src/components/chat/WelcomeScreen.tsxindex 822b3ac0a..818f17bcf 100644--- a/frontend/src/components/chat/WelcomeScreen.tsx+++ b/frontend/src/components/chat/WelcomeScreen.tsx@@ -1,4 +1,4 @@-import { Bot, TrendingUp, Globe, Sparkles, Users, UserCircle2, NotebookPen } from "lucide-react";+import { Bot, TrendingUp, Globe, Sparkles, Users, UserCircle2, NotebookPen, Landmark } from "lucide-react";interface Example {title: string;@@ -104,6 +104,28 @@ const CATEGORIES: Category[] = [},],},+ {+ label: "Trading Connectors",+ icon: <Landmark className="h-4 w-4" />,+ color: "text-cyan-400 border-cyan-500/30 hover:border-cyan-500/60 hover:bg-cyan-500/5",+ examples: [+ {+ title: "Check Selected Connector",+ desc: "List connector profiles and verify the selected one",+ prompt: "List my trading connector profiles, show which one is selected, then check that selected connector. If it is not ready, tell me exactly what setup step is missing. Do not place or modify orders.",+ },+ {+ title: "Analyze Connector Portfolio",+ desc: "Read account summary and positions from the selected connector",+ prompt: "Use the selected trading connector profile to summarize my account, positions, concentration, cash, and portfolio risk. Do not place or modify orders.",+ },+ {+ title: "Quote & Trend",+ desc: "Fetch a quote plus recent daily bars through the selected connector",+ prompt: "Use the selected trading connector to fetch an AAPL quote and 30 daily bars, then summarize the current quote versus the recent trend. Keep it read-only.",+ },+ ],+ },{label: "Shadow Account",icon: <UserCircle2 className="h-4 w-4" />,@@ -129,10 +151,11 @@ const CATEGORIES: Category[] = [];const CAPABILITY_CHIPS = [- "70 Finance Skills",+ "77 Finance Skills","29 Swarm Presets",- "32 Agent Tools",+ "44 Agent Tools","3 Markets: A-Share · Crypto · HK/US",+ "Trading Connector Profiles","Minute to Daily Timeframes","4 Portfolio Optimizers","15+ Risk Metrics",@@ -213,5 +236,3 @@ export function WelcomeScreen({ onExample }: Props) {</div>);}--diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 79a128a90..191ceba17 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -156,31 +156,36 @@ export const api = {alphaBenchStreamUrl: (jobId: string) =>withAuthQuery(`${BASE}/alpha/bench/${encodeURIComponent(jobId)}/stream`),- // Live trading channel — privileged surface actions (NOT agent tools).+ // Connector runtime channel — privileged surface actions (NOT agent tools).// commit is the ONLY action that writes a mandate; halt trips the kill switch.commitMandate: (body: CommitMandateRequest) =>request<CommitMandateResponse>("/mandate/commit", {method: "POST",body: JSON.stringify(body),}),- haltLive: (session_id: string) =>+ haltLive: (session_id?: string, broker?: string, reason?: string) =>request<HaltLiveResponse>("/live/halt", {method: "POST",- body: JSON.stringify({ session_id }),+ body: JSON.stringify({ session_id, broker, reason }),}),// Read the persistent runtime status across all authorized brokers (SPEC §7.5).// Polled by the RunnerStatus panel; a plain authenticated GET, never a chat message.getLiveStatus: () => request<LiveStatus>("/live/status"),+ authorizeLive: (broker: string) =>+ request<LiveAuthorizeResponse>("/live/authorize", {+ method: "POST",+ body: JSON.stringify({ broker }),+ }),// Start/stop the persistent runner (SPEC §7.5). Privileged surface actions, not agent tools.- startLiveRunner: (broker?: string) =>+ startLiveRunner: (broker: string) =>request<LiveRunnerResponse>("/live/runner/start", {method: "POST",- body: JSON.stringify(broker ? { broker } : {}),+ body: JSON.stringify({ broker }),}),- stopLiveRunner: (broker?: string) =>+ stopLiveRunner: (broker: string) =>request<LiveRunnerResponse>("/live/runner/stop", {method: "POST",- body: JSON.stringify(broker ? { broker } : {}),+ body: JSON.stringify({ broker }),}),};@@ -671,7 +676,7 @@ export interface AlphaBenchResult {by_theme: Record<string, { alive: number; reversed: number; dead: number }>;}-// --- Live trading channel types ---+// --- Connector runtime channel types ---/** One mandate profile inside a `mandate.proposal` event (SPEC Consent §1). */export interface MandateProfile {@@ -724,7 +729,7 @@ export interface MandateCommitted {/** Payload of the `live.halted` SSE event (SPEC Consent §4). */export interface LiveHalted {- broker?: string;+ broker?: string | null;tripped_at?: string;by?: string;reason?: string;@@ -743,6 +748,7 @@ export interface LiveAction {}export interface CommitMandateRequest {+ broker: string;proposal_id: string;selected_ordinal: number;/** Present only on the adjust path (SPEC Consent §3); null otherwise. */@@ -750,6 +756,8 @@ export interface CommitMandateRequest {/** Explicit affirmative consent; the surface sets it on the user's click. */consent_ack: boolean;session_id?: string;+ account_ref?: string;+ lifetime_days?: number;}export interface CommitMandateResponse {@@ -763,54 +771,83 @@ export interface CommitMandateResponse {}export interface HaltLiveResponse {- status: string;- tripped_at?: string;+ halted: boolean;+ broker?: string | null;+ reason: string;+ sentinel: string;+}++export interface LiveAuthorizeRequest {+ broker: string;+}++export interface LiveAuthorizeResponse {+ broker: string;+ oauth_token_present: boolean;+ instruction: string;+ note?: string;}/** Mandate limits surfaced inside a `GET /live/status` broker entry (SPEC §7.5). */export interface LiveMandateLimits {- max_order_usd?: number;- daily_trade_cap?: number;- leverage?: string | number;- instruments?: string[];- universe?: string[] | string;+ max_order_notional_usd?: number;+ max_total_exposure_usd?: number;+ max_leverage?: number;+ max_trades_per_day?: number;+ allowed_instruments?: string[];+ account_funding_usd?: number;[key: string]: unknown;}/** Active mandate block of a `GET /live/status` broker entry. */export interface LiveMandateStatus {+ broker?: string;mandate_id?: string;+ account_ref?: string;+ created_at?: string;limits?: LiveMandateLimits;/** ISO timestamp the mandate auto-expires (SPEC §7.5 #7 proactive expiry). */expires_at?: string;+ expires_in_seconds?: number | null;+ expired?: boolean;}/** Runner liveness block of a `GET /live/status` broker entry (SPEC §7.5 #3). */export interface LiveRunnerLiveness {+ broker?: string;alive: boolean;- /** ISO timestamp of the last heartbeat tick; null if the runner never started. */- last_tick?: string | null;+ /** Unix epoch seconds of the last heartbeat tick; null if the runner never started. */+ last_tick?: number | string | null;+ last_tick_age_seconds?: number | null;+}++export interface LiveBrokerAuthStatus {+ broker: string;+ oauth_token_present: boolean;+ is_live_broker: boolean;}/** One broker entry in the `GET /live/status` response. */export interface LiveBrokerStatus {- broker: string;- authorized: boolean;+ auth: LiveBrokerAuthStatus;mandate?: LiveMandateStatus | null;runner: LiveRunnerLiveness;+ halted: boolean;}/** Response of `GET /live/status` (SPEC §7.5 runner status panel + C2). */export interface LiveStatus {brokers: LiveBrokerStatus[];- halted: boolean;+ global_halted: boolean;}/** Response of `POST /live/runner/start|stop`. */export interface LiveRunnerResponse {- status: string;- broker?: string;- alive?: boolean;+ broker: string;+ started?: boolean;+ already_running?: boolean;+ stopped?: boolean;+ was_running?: boolean;}export interface MessageItem {diff --git a/frontend/src/lib/tools.ts b/frontend/src/lib/tools.tsindex ca97aa51d..3be249cd4 100644--- a/frontend/src/lib/tools.ts+++ b/frontend/src/lib/tools.ts@@ -10,6 +10,14 @@ export const TOOL_LABELS: Record<string, string> = {bash: "Run command",read_url: "Read webpage",read_document: "Read document",+ trading_connections: "List trading connectors",+ trading_select_connection: "Select trading connector",+ trading_check: "Check trading connector",+ trading_account: "Read connector account",+ trading_positions: "Read connector positions",+ trading_orders: "Read connector orders",+ trading_quote: "Read connector quote",+ trading_history: "Read connector history",compact: "Compact context",create_task: "Create task",update_task: "Update task",diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsxindex 90dc399dd..0141f203c 100644--- a/frontend/src/pages/Agent.tsx+++ b/frontend/src/pages/Agent.tsx@@ -1,6 +1,6 @@import { useEffect, useRef, useState, useMemo, useCallback, type FormEvent } from "react";import { useSearchParams } from "react-router-dom";-import { Send, Loader2, ArrowDown, Square, Download, Plus, Paperclip, X, Users, Target, ChevronDown, Pencil, Check, Play, OctagonX, Activity, Ban, CheckCircle2 } from "lucide-react";+import { Send, Loader2, ArrowDown, Square, Download, Plus, Paperclip, X, Users, Target, ChevronDown, Pencil, Check, Play, OctagonX, Activity, Ban, CheckCircle2, Landmark } from "lucide-react";import { toast } from "sonner";import { useAgentStore } from "@/stores/agent";import { useSSE } from "@/hooks/useSSE";@@ -41,8 +41,12 @@ const act = () => useAgentStore.getState();/** Poll cadence for the shared `GET /live/status` snapshot. */const LIVE_STATUS_POLL_INTERVAL_MS = 15_000;+const CONNECTOR_CHECK_PROMPT =+ "List my trading connector profiles, show which one is selected, then check that selected connector. If it is not ready, tell me exactly what setup step is missing. Do not place or modify orders.";+const CONNECTOR_PORTFOLIO_PROMPT =+ "Use the selected trading connector profile to summarize my account, positions, concentration, cash, and portfolio risk. Do not place or modify orders.";-/* ---------- Live trading channel ----------+/* ---------- Connector runtime channel ----------* Mandate proposals and live-action chips render as standalone timeline items,* never folded into the thinking timeline (SPEC Consent §2 grouping note). They* are driven by dedicated state rather than the chat message store because they@@ -60,6 +64,23 @@ interface LiveActionItem {}type LiveItem = ProposalItem | LiveActionItem;+function normalizeBrokerScope(broker: string | null | undefined): string | null {+ const normalized = broker?.trim().toLowerCase();+ return normalized || null;+}++function isGlobalLiveHalt(halt: LiveHalted | null): boolean {+ return halt != null && normalizeBrokerScope(halt.broker) == null;+}++function haltScopeStillActive(halt: LiveHalted, status: LiveStatus): boolean {+ const broker = normalizeBrokerScope(halt.broker);+ if (!broker) return status.global_halted;+ return status.global_halted || status.brokers.some((item) => (+ normalizeBrokerScope(item.auth.broker) === broker && item.halted+ ));+}+function liveActionStyle(kind: string): { icon: typeof Activity; tone: string } {switch (kind) {case "order_rejected":@@ -87,7 +108,7 @@ function LiveActionChip({ action }: { action: LiveAction }) {<div className="flex-1 min-w-0"><div className={["inline-flex max-w-full flex-wrap items-center gap-1.5 rounded-lg border px-2.5 py-1 text-xs", tone].join(" ")}><Icon className="h-3 w-3 shrink-0" />- <span className="shrink-0 font-medium uppercase tracking-wide text-[10px]">LIVE</span>+ <span className="shrink-0 font-medium uppercase tracking-wide text-[10px]">RUNTIME</span><span className="shrink-0 font-medium">{liveActionLabel(action)}</span>{action.intent_normalized && (<span className="truncate text-foreground/80">· {action.intent_normalized}</span>@@ -208,7 +229,7 @@ export function Agent() {const [goalEditActive, setGoalEditActive] = useState(false);const [goalEditValue, setGoalEditValue] = useState("");- /* Live trading channel state (SPEC Consent §1/§4/§5) */+ /* Connector runtime channel state (SPEC Consent §1/§4/§5) */const [liveItems, setLiveItems] = useState<LiveItem[]>([]);const [committedMandates, setCommittedMandates] = useState<Record<string, MandateCommitted>>({});const [liveHalted, setLiveHalted] = useState<LiveHalted | null>(null);@@ -217,7 +238,7 @@ export function Agent() {* (commit / halt / resume / runner-affecting action) rather than waiting a tick. */const [liveStatusRefresh, setLiveStatusRefresh] = useState(0);/* Shared `GET /live/status` snapshot. Owned here (single poller) and passed down- * to RunnerStatus, so the global kill switch can be shown whenever live trading+ * to RunnerStatus, so the global kill switch can be shown whenever connector runtime* could be active out-of-band (CLI/another session), not only off in-session SSE* items (audit M2: always-available global halt — SPEC Consent §4). */const [liveStatus, setLiveStatus] = useState<LiveStatus | null>(null);@@ -552,7 +573,7 @@ export function Agent() {// the RunnerStatus panel re-polls so its per-broker rows show "halted".setLiveHalted(halted);setLiveStatusRefresh((n) => n + 1);- toast.warning("Live trading halted — runner stopped, resting orders cancelled");+ toast.warning("Connector runtime halted — runner stopped, resting orders cancelled");},"live.resumed": (d) => {@@ -562,7 +583,7 @@ export function Agent() {void d;setLiveHalted(null);setLiveStatusRefresh((n) => n + 1);- toast.success("Live trading resumed");+ toast.success("Connector runtime resumed");},"live.action": (d) => {@@ -570,7 +591,7 @@ export function Agent() {const action = d as unknown as LiveAction;if (!action.kind) return;setLiveItems((items) => [...items, { kind: "live_action", timestamp: Date.now(), action }]);- if (action.kind === "halt_tripped") setLiveHalted({ reason: action.intent_normalized });+ if (action.kind === "halt_tripped") setLiveHalted({ broker: action.broker, reason: action.intent_normalized });if (action.kind === "halt_cleared") setLiveHalted(null);// Mandate-affecting / runner-affecting actions should refresh the runtime panel.if (["mandate_committed", "halt_tripped", "halt_cleared"].includes(action.kind)) {@@ -621,11 +642,14 @@ export function Agent() {/* Single shared poller for `GET /live/status`. RunnerStatus consumes this snapshot* as a prop rather than polling independently, and the global kill switch reads it- * to stay available whenever live trading could be active out-of-band. */+ * to stay available whenever connector runtime activity could be active out-of-band. */const refreshLiveStatus = useCallback(async () => {try {const next = await api.getLiveStatus();setLiveStatus(next);+ setLiveHalted((current) => (+ current && !haltScopeStillActive(current, next) ? null : current+ ));setLiveStatusUnavailable(false);} catch (error) {// A 404/501 means the runtime endpoint is not wired on this backend; treat the@@ -774,15 +798,15 @@ export function Agent() {// (e.g. a runner started from the CLI / another session). The backend scopes// the SSE broadcast by session_id when present; an empty string is a valid// global trip.- await api.haltLive(sessionId ?? "");+ await api.haltLive(sessionId ?? undefined);// Preemptive halt: the server trips the kill switch (cancel resting orders +// optional flatten per SPEC §7.5 #6) and broadcasts live.halted. Reflect// optimistically and re-poll the runtime panel so the runner shows stopped.- setLiveHalted((cur) => cur ?? { by: "frontend", tripped_at: new Date().toISOString() });+ setLiveHalted((cur) => cur ?? { broker: null, by: "frontend", tripped_at: new Date().toISOString() });setLiveStatusRefresh((n) => n + 1);- toast.success("Live trading halted");+ toast.success("Connector runtime halted");} catch (error) {- toast.error(error instanceof Error ? error.message : "Failed to halt live trading.");+ toast.error(error instanceof Error ? error.message : "Failed to halt connector runtime.");} finally {setHalting(false);}@@ -952,23 +976,23 @@ export function Agent() {return rows.sort((a, b) => a.sort - b.sort);}, [groups, liveItems]);- /* Whether live trading could be active *anywhere* — the global kill switch must be+ /* Whether connector runtime activity could be active *anywhere* — the global kill switch must be* available whenever it could (audit M2 / SPEC Consent §4). Driven off both* in-session SSE artifacts AND the shared `/live/status` snapshot, so a runner* started from the CLI or another browser session still surfaces the halt button* in a freshly-loaded web session. */const liveStatusActive =liveStatus != null &&- (liveStatus.halted ||- liveStatus.brokers.some((b) => b.authorized || b.runner?.alive || b.mandate != null));+ (liveStatus.global_halted ||+ liveStatus.brokers.some((b) => b.auth.oauth_token_present || b.runner?.alive || b.mandate != null));const liveActive =liveItems.length > 0 ||Object.keys(committedMandates).length > 0 ||liveHalted != null ||liveStatusActive;- /* The kill switch reflects a halt from either an in-session SSE event or the polled- * status, so the halted/resumed state stays consistent across surfaces. */- const liveIsHalted = liveHalted != null || (liveStatus?.halted ?? false);+ /* The global kill switch reflects only a global halt from either an in-session SSE+ * event or the polled status; broker-scoped halts stay on their broker row. */+ const liveIsHalted = isGlobalLiveHalt(liveHalted) || (liveStatus?.global_halted ?? false);return (<div className="flex flex-col flex-1 min-w-0 overflow-hidden h-full">@@ -1287,7 +1311,7 @@ export function Agent() {{liveIsHalted ? (<span className="inline-flex items-center gap-1.5 rounded-lg bg-destructive/10 px-2.5 py-1 text-xs font-medium text-destructive"><OctagonX className="h-3 w-3" />- Live trading halted+ Connector runtime halted</span>) : (<button@@ -1295,10 +1319,10 @@ export function Agent() {onClick={handleHaltLive}disabled={halting}className="inline-flex items-center gap-1.5 rounded-lg border border-destructive/40 bg-destructive/5 px-2.5 py-1 text-xs font-medium text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-40"- title="Instantly halt all live trading for this session"+ title="Instantly halt connector runtime activity">{halting ? <Loader2 className="h-3 w-3 animate-spin" /> : <OctagonX className="h-3 w-3" />}- Halt live trading+ Halt connector runtime</button>)}</div>@@ -1352,6 +1376,29 @@ export function Agent() {<Users className="h-4 w-4" />Agent Swarm</button>+ <div className="border-t my-1" />+ <button+ type="button"+ onClick={() => {+ setShowUploadMenu(false);+ void runPrompt(CONNECTOR_CHECK_PROMPT);+ }}+ className="w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors flex items-center gap-2"+ >+ <Landmark className="h-4 w-4" />+ Check Trading Connector+ </button>+ <button+ type="button"+ onClick={() => {+ setShowUploadMenu(false);+ void runPrompt(CONNECTOR_PORTFOLIO_PROMPT);+ }}+ className="w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors flex items-center gap-2"+ >+ <Landmark className="h-4 w-4" />+ Analyze Connector Portfolio+ </button></div>)}</div>diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex 1548a0bad..f4f78ca66 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -8,6 +8,8 @@ const PROXY_PATHS = ["/swarm/runs","/settings/llm","/settings/data-sources",+ "/mandate",+ "/live","/upload","/shadow-reports",];diff --git a/pyproject.toml b/pyproject.tomlindex 88d4d3f5c..9c89a38b9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -91,6 +91,9 @@ include = ["src*", "backtest*", "cli*"]"src.factors" = ["zoo/**/*.yaml", "zoo/**/*.md", "zoo/**/NOTICE"][project.optional-dependencies]+ibkr = [+ "ib_async>=2.0",+]dev = ["pytest>=7.0","pytest-cov>=4.0",