"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
refactor(cli): split agent/cli.py into agent/cli/ package
Haozhe Wub5a44a1e5677
diff --git a/README.md b/README.mdindex 7a257fe0f..189f3a962 100644--- a/README.md+++ b/README.md@@ -46,12 +46,13 @@## 📰 News+- **2026-05-21** 🧱 **CLI package refactor**: `agent/cli.py` (3216 LOC) split into the `agent/cli/` package — interactive front door, slash router, Rich components, plus a `_legacy.py` shim that preserves every subcommand and re-exports every public symbol so `cli.cmd_*` / `cli._INIT_ENV_PATH` / `cli.Confirm` keep working. New FastAPI middleware serves the SPA shell when a browser opens `/runs/{id}` or `/correlation` directly; same narrowing landed in the Vite dev proxy. Version unified via `cli/_version.py` (no more drift between `--version` and the banner), `python -m cli` restored via `__main__.py`, and the chat-gate narrowed so `chat --help` / `chat extra` reach legacy argparse instead of being swallowed by the REPL.- **2026-05-20** 🔬 **Hypothesis Registry CLI**: Closes the CLI side of the Hypothesis Registry shipped backend-only on 2026-05-16. `vibe-trading hypothesis list` prints a Rich table or JSON (`--status` filter, `--limit`); `show <id>` renders a detail panel including linked run cards; `invalidate <id> --note "..."` flips status to `rejected` while preserving prior invalidation notes when `--note` is omitted. Honors the existing `VIBE_TRADING_HYPOTHESES_PATH` env override and adds a per-invocation `--path`. 22 new tests cover wiring, JSON output, status filter, limit, missing-id errors, and note persistence.- **2026-05-19** ✨ **Live tool feedback + graceful cancel**: Long-running tools (backtests, large PDFs, swarm workers) no longer look frozen. Each tool call now emits a 3-second heartbeat plus structured per-stage progress — `run_backtest` shows phase markers (`validate` / `simulate` / `finalize`), `read_document` ticks per page on PDF or per sheet on Excel, `read_url` marks `fetch` / `parse`. The CLI Rich Live dashboard renders a Unicode spinner, ASCII progress bar, ETA, and stacks up to 3 parallel tools keyed by name; the frontend chat ships a new `ToolProgressIndicator` with rAF-coalesced renders, ARIA `role="status"` + hidden native `<progress>` for screen readers, and a determinate `ProgressRing` SVG when total is known. First `Ctrl+C` during a CLI run now calls `agent.cancel()` for graceful exit (current step finishes, trace closes cleanly); a second within 2s force-quits. Reusable primitives extracted along the way: `ProgressBar.tsx` and `lib/tools.ts` (shared tool-name i18n).-- **2026-05-18** 🧹 **Cleanup pass + three latent bug fixes**: `CompositeEngine` no longer misroutes bare Chinese-futures codes like `RB2410` to `GlobalFuturesEngine` — `_is_china_futures` moved into a shared `_market_hooks` module with a case-normalized product table and a non-CN exchange guard, plus 9 new regression cases. Session FTS5 indexes now persist timestamps so cross-session search can sort by date; the same path also fixed a re-upsert that was wall-clocking every session's `started_at`. The Vite dev-mode proxy gained the missing `/alpha` entry so the AlphaZoo page resolves on `npm run dev`. `tests/test_e2e_harness_v2.py` (real-LLM e2e suite) is now gated behind `VIBE_TRADING_RUN_LIVE_E2E=1` so CI no longer changes shape based on env-key presence. Ruff `per-file-ignores` added for the factor zoo (3783 → 0 F401 noise), frontend tsconfig enables `noUnusedLocals` / `noUnusedParameters` as regression guards, and 76 unused `vw = vwap(...)` boilerplate lines were dropped from `gtja191` alphas. Net **-918 LOC**.<details><summary>Earlier news</summary>+- **2026-05-18** 🧹 **Cleanup pass + three latent bug fixes**: `CompositeEngine` no longer misroutes bare Chinese-futures codes like `RB2410` to `GlobalFuturesEngine` — `_is_china_futures` moved into a shared `_market_hooks` module with a case-normalized product table and a non-CN exchange guard, plus 9 new regression cases. Session FTS5 indexes now persist timestamps so cross-session search can sort by date; the same path also fixed a re-upsert that was wall-clocking every session's `started_at`. The Vite dev-mode proxy gained the missing `/alpha` entry so the AlphaZoo page resolves on `npm run dev`. `tests/test_e2e_harness_v2.py` (real-LLM e2e suite) is now gated behind `VIBE_TRADING_RUN_LIVE_E2E=1` so CI no longer changes shape based on env-key presence. Ruff `per-file-ignores` added for the factor zoo (3783 → 0 F401 noise), frontend tsconfig enables `noUnusedLocals` / `noUnusedParameters` as regression guards, and 76 unused `vw = vwap(...)` boilerplate lines were dropped from `gtja191` alphas. Net **-918 LOC**.- **2026-05-17** 🧬 **Alpha Zoo v1 (0.1.8)**: 452 pre-built quant alphas across 4 zoos — `qlib158` (Microsoft Qlib, Apache-2 attribution), `alpha101` (Kakushadze 101 Formulaic Alphas, paper rewrite from arXiv:1601.00991), `gtja191` (Guotai Junan 2014 short-horizon factor report), and `academic` (Fama-French 5 + Carhart price-based proxies). One-line CLI to bench any zoo on your universe: `vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`. Ships with AST purity gate, lookahead-guard test, `pytest-socket` network kill-switch, per-zoo LICENSE.md, and a Developer Certificate of Origin (DCO) workflow for community PRs. Auto-rendered Alpha Library at [vibetrading.wiki/alpha-library/](https://vibetrading.wiki/alpha-library/) + research-lab post [Which of the 191 GTJA alphas still work in 2026?](https://vibetrading.wiki/research-lab/posts/alpha-191-in-2026.html).- **2026-05-16** 🧪 **Research spine update**: Added a backend Hypothesis Registry with `create_hypothesis`, `update_hypothesis`, `link_backtest`, and `search_hypotheses`; external-content readers now attach warning-only `security_warnings`; and Shadow Account scanning now uses deterministic OHLCV feature evaluation instead of the old calendar-phase stub.- **2026-05-15** 🪪 The run detail page now surfaces the Trust Layer run card alongside metrics and artifacts, completing the UI side of the `run_card.json` work landed on 2026-05-12. `PersistentMemory.add()` was also hardened on length, empty/whitespace-only names, and C0/C1 control bytes from the #108/#109/#110 triage ([#112](https://github.com/HKUDS/Vibe-Trading/pull/112), thanks @Teerapat-Vatpitak).@@ -845,7 +846,7 @@ tool names unique. Rename the server in agent config if you want a different pre```Vibe-Trading/├── agent/ # Backend (Python)-│ ├── cli.py # CLI entrypoint — interactive TUI + subcommands+│ ├── 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│ │diff --git a/README_ar.md b/README_ar.mdindex 7bf72f9aa..3524ff582 100644--- a/README_ar.md+++ b/README_ar.md@@ -46,12 +46,13 @@## 📰 الأخبار+- **2026-05-21** 🧱 **إعادة هيكلة حزمة CLI**: تقسيم `agent/cli.py` (3216 سطراً) إلى حزمة `agent/cli/` — واجهة تفاعلية، موجّه slash، مكوّنات Rich، وطبقة `_legacy.py` تحافظ على كل الأوامر الفرعية وتعيد تصدير كل الرموز العامة فتبقى `cli.cmd_*` / `cli._INIT_ENV_PATH` / `cli.Confirm` كما هي. Middleware جديد في FastAPI يخدم قشرة SPA عند فتح `/runs/{id}` أو `/correlation` مباشرة من المتصفح، مع نفس التضييق في بروكسي Vite للتطوير. توحيد سلسلة الإصدار عبر `cli/_version.py` (إنهاء الانحراف بين `--version` والبانر)، استعادة `python -m cli` عبر `__main__.py`، وتضييق بوابة chat بحيث تصل `chat --help` / `chat extra` إلى argparse القديم بدلاً من ابتلاع REPL لها.- **2026-05-20** 🔬 **Hypothesis Registry CLI**: استكمال جانب CLI لـ Hypothesis Registry الذي شُحن backend فقط في 2026-05-16. يُخرج `vibe-trading hypothesis list` جدول Rich أو JSON (مع فلتر `--status` و`--limit`)؛ يعرض `show <id>` لوحة تفاصيل تتضمن run cards المرتبطة؛ يقلب `invalidate <id> --note "..."` الحالة إلى `rejected` ويُبقي ملاحظات الإبطال السابقة عند حذف `--note`. متغير البيئة `VIBE_TRADING_HYPOTHESES_PATH` ما زال مدعوماً، مع إضافة `--path` لكل استدعاء. تغطي 22 اختباراً جديداً الربط، إخراج JSON، فلتر الحالة، الحد، أخطاء معرّف مفقود، وثبات الملاحظات.- **2026-05-19** ✨ **تغذية راجعة حيّة للأدوات + إلغاء سلس**: لم تعد الأدوات الطويلة (backtests، PDF كبيرة، عمّال swarm) تبدو متجمدة. كل استدعاء أداة يُصدر الآن نبضة قلب كل 3 ثوانٍ، بالإضافة إلى تقدّم مرحلي مهيكل — يُظهر `run_backtest` علامات الأطوار (`validate` / `simulate` / `finalize`)، ويُحدّث `read_document` عدّاد كل صفحة على PDF أو كل ورقة على Excel، ويُعلِم `read_url` بمرحلتي `fetch` / `parse`. تعرض لوحة Rich Live في CLI دوّاراً Unicode وشريط تقدّم ASCII وETA، وتُكدّس حتى 3 أدوات متوازية مفهرسة بالاسم. تضيف الواجهة الأمامية مكوّن `ToolProgressIndicator` جديد مع تجميع rAF، وARIA `role="status"` + `<progress>` أصلي مخفي لقارئات الشاشة، وSVG `ProgressRing` حتمي عندما يكون المجموع معروفاً. أول `Ctrl+C` أثناء تشغيل CLI يستدعي الآن `agent.cancel()` للخروج السلس (تكتمل الخطوة الحالية وتُغلق التتبعات بنظافة)، والثاني خلال ثانيتين يفرض الإنهاء. تم استخراج عناصر أساسية قابلة لإعادة الاستخدام: `ProgressBar.tsx` و`lib/tools.ts` (تعيين i18n لأسماء الأدوات المشترك).-- **2026-05-18** 🧹 **تنظيف + إصلاح 3 أخطاء كامنة**: لم يعد `CompositeEngine` يوجّه رموز العقود الآجلة الصينية بدون لاحقة (مثل `RB2410`) إلى `GlobalFuturesEngine` بشكل خاطئ — انتقل `_is_china_futures` إلى وحدة `_market_hooks` المشتركة مع تطبيع حالة جدول المنتجات + حارس لبورصة غير صينية، وأُضيفت 9 حالات اختبار انحدار. تحفظ فهارس FTS5 للجلسات الآن الطوابع الزمنية، فيمكن لبحث الجلسات الفرز بالتاريخ، ونفس التغيير أصلح مسار إعادة الإدراج الذي كان يستبدل `started_at` بساعة الحائط في كل مرة. أُضيف `/alpha` المفقود إلى بروكسي تطوير Vite، فتُحلّ صفحة AlphaZoo الآن على `npm run dev`. تم تقييد `tests/test_e2e_harness_v2.py` (مجموعة e2e بـ LLM حقيقي) خلف `VIBE_TRADING_RUN_LIVE_E2E=1` كي لا تغيّر CI شكلها بناءً على وجود مفتاح البيئة. أُضيفت إلى ruff قاعدة `per-file-ignores` لمكتبة المعاملات (الضوضاء F401 من 3783 إلى 0)، وفُعِّلت `noUnusedLocals` / `noUnusedParameters` في tsconfig الواجهة كحواجز انحدار، وحُذف 76 سطراً من نموذج `vw = vwap(...)` غير المستخدم في ملفات `gtja191`. الصافي **-918 سطراً**.<details><summary>أخبار سابقة</summary>+- **2026-05-18** 🧹 **تنظيف + إصلاح 3 أخطاء كامنة**: لم يعد `CompositeEngine` يوجّه رموز العقود الآجلة الصينية بدون لاحقة (مثل `RB2410`) إلى `GlobalFuturesEngine` بشكل خاطئ — انتقل `_is_china_futures` إلى وحدة `_market_hooks` المشتركة مع تطبيع حالة جدول المنتجات + حارس لبورصة غير صينية، وأُضيفت 9 حالات اختبار انحدار. تحفظ فهارس FTS5 للجلسات الآن الطوابع الزمنية، فيمكن لبحث الجلسات الفرز بالتاريخ، ونفس التغيير أصلح مسار إعادة الإدراج الذي كان يستبدل `started_at` بساعة الحائط في كل مرة. أُضيف `/alpha` المفقود إلى بروكسي تطوير Vite، فتُحلّ صفحة AlphaZoo الآن على `npm run dev`. تم تقييد `tests/test_e2e_harness_v2.py` (مجموعة e2e بـ LLM حقيقي) خلف `VIBE_TRADING_RUN_LIVE_E2E=1` كي لا تغيّر CI شكلها بناءً على وجود مفتاح البيئة. أُضيفت إلى ruff قاعدة `per-file-ignores` لمكتبة المعاملات (الضوضاء F401 من 3783 إلى 0)، وفُعِّلت `noUnusedLocals` / `noUnusedParameters` في tsconfig الواجهة كحواجز انحدار، وحُذف 76 سطراً من نموذج `vw = vwap(...)` غير المستخدم في ملفات `gtja191`. الصافي **-918 سطراً**.- **2026-05-17** 🧬 **Alpha Zoo v1 (0.1.8)**: 452 ألفا كمّي جاهز عبر 4 zoos — `qlib158` (ميزات Alpha158 من Microsoft Qlib، إسناد Apache-2.0)، `alpha101` (إعادة تنفيذ "101 Formulaic Alphas" من Kakushadze بناءً على ورقة arXiv:1601.00991)، `gtja191` (تقرير بحث Guotai Junan 2014 لعوامل تداول قصيرة الأجل)، `academic` (Fama-French 5 + Carhart momentum كـ proxy قائم على الأسعار). سطر أوامر واحد للـ bench على أي universe: `vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`. تتضمن بوابة AST للنقاء، اختبار حماية lookahead، عزل الشبكة عبر `pytest-socket`، LICENSE.md لكل zoo، وسير عمل توقيع DCO لمساهمات المجتمع. تقديم Alpha Library تلقائياً على [vibetrading.wiki/alpha-library/](https://vibetrading.wiki/alpha-library/)، مع منشور Research Lab [Which of the 191 GTJA alphas still work in 2026?](https://vibetrading.wiki/research-lab/posts/alpha-191-in-2026.html).- **2026-05-16** 🧪 **تحديث عمود البحث**: أضيف backend Hypothesis Registry مع `create_hypothesis` و`update_hypothesis` و`link_backtest` و`search_hypotheses`. تضيف قارئات المحتوى الخارجي الآن `security_warnings` تحذيرية فقط، وانتقل ماسح Shadow Account من calendar-phase stub القديم إلى تقييم حتمي لميزات OHLCV.- **2026-05-15** 🪪 تعرض صفحة تفاصيل الـ run الآن بطاقة Trust Layer run card إلى جانب المقاييس والمخرجات، لتكمل الجانب الواجهي من عمل `run_card.json` الذي هبط في 2026-05-12. كما تم تعزيز `PersistentMemory.add()` على مسارات الطول والأسماء الفارغة أو التي تحتوي على فراغات فقط وبايتات التحكم C0/C1 ضمن فرز #108/#109/#110 ([#112](https://github.com/HKUDS/Vibe-Trading/pull/112)، شكراً @Teerapat-Vatpitak).@@ -760,7 +761,7 @@ npx clawhub@latest install vibe-trading --force```Vibe-Trading/├── agent/ # Backend (Python)-│ ├── cli.py # CLI entrypoint — interactive TUI + subcommands+│ ├── 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│ │diff --git a/README_ja.md b/README_ja.mdindex 32b03b0d7..f5753cd92 100644--- a/README_ja.md+++ b/README_ja.md@@ -46,12 +46,13 @@## 📰 ニュース+- **2026-05-21** 🧱 **CLI パッケージリファクタ**: `agent/cli.py`(3216 LOC)を `agent/cli/` パッケージへ分割 — インタラクティブな入口、slash ルーター、Rich コンポーネント、そしてすべてのサブコマンドを保ち `cli.cmd_*` / `cli._INIT_ENV_PATH` / `cli.Confirm` などの公開シンボルを再エクスポートする `_legacy.py` shim。新しい FastAPI ミドルウェアはブラウザが `/runs/{id}` または `/correlation` を直接開いた際に SPA シェルを返し、同じ絞り込みを Vite dev プロキシにも反映。バージョン文字列は `cli/_version.py` で一本化(`--version` とバナーのドリフト解消)、`python -m cli` を `__main__.py` で復活、chat ゲートを絞り `chat --help` / `chat extra` は REPL に飲み込まれずレガシー argparse に届きます。- **2026-05-20** 🔬 **Hypothesis Registry CLI**: 2026-05-16 にバックエンドのみで公開された Hypothesis Registry の CLI 側を完成させました。`vibe-trading hypothesis list` は Rich テーブルまたは JSON を出力(`--status` フィルタと `--limit` をサポート)、`show <id>` はリンクされた run card を含む詳細パネルを描画、`invalidate <id> --note "..."` はステータスを `rejected` に切り替え、`--note` を省略すると既存の invalidation notes を保持します。既存の `VIBE_TRADING_HYPOTHESES_PATH` 環境変数オーバーライドに加え、呼び出し単位の `--path` も使えます。配線、JSON 出力、ステータスフィルタ、limit、ID 不在エラー、ノート永続化を 22 のテストでカバー。- **2026-05-19** ✨ **ツールのライブフィードバック + グレースフルキャンセル**: 長時間実行されるツール(バックテスト、大きい PDF、swarm worker)が固まったように見えなくなりました。各ツール呼び出しは 3 秒ごとのハートビートに加え、構造化された段階進捗を発行します — `run_backtest` はフェーズマーカー(`validate` / `simulate` / `finalize`)、`read_document` は PDF ではページ単位、Excel ではシート単位、`read_url` は `fetch` / `parse` をマーク。CLI の Rich Live ダッシュボードは Unicode スピナー、ASCII プログレスバー、ETA を描画し、ツール名でキー付けして最大 3 つの並列ツールをスタック表示します。フロントエンドのチャットには新規 `ToolProgressIndicator` を追加し、rAF コアレッシング、ARIA `role="status"` + スクリーンリーダー向けの非表示 `<progress>`、合計が既知の場合は determinate な `ProgressRing` SVG を備えます。CLI 実行中の最初の `Ctrl+C` は `agent.cancel()` を呼んでグレースフル終了(現在のステップが完了し、trace がクリーンに閉じる)し、2 秒以内に 2 度目を押すと強制終了します。再利用可能なプリミティブ `ProgressBar.tsx` と `lib/tools.ts`(共有ツール名 i18n マッピング)も抽出。-- **2026-05-18** 🧹 **クリーンアップ + 3 つの潜在バグ修正**: `CompositeEngine` が取引所サフィックスのない中国先物コード(`RB2410` 等)を `GlobalFuturesEngine` に誤ルーティングしていた問題を修正。`_is_china_futures` を共有の `_market_hooks` モジュールに移し、製品コード表を大小文字正規化 + 非中国取引所のガードを追加、回帰ケース 9 件を新設しました。session FTS5 インデックスがタイムスタンプを永続化するようになり、クロスセッション検索を日付ソートできるようになりました。同じ修正で、re-upsert 経路が `started_at` を wall-clock で上書きしていた副次バグも解消しました。Vite 開発プロキシに `/alpha` を追加し、AlphaZoo ページが `npm run dev` で解決されるようになりました。`tests/test_e2e_harness_v2.py`(実 LLM の e2e スイート)は `VIBE_TRADING_RUN_LIVE_E2E=1` でゲート化し、CI が環境変数の有無で形を変えないようにしました。ruff に factor zoo 用の `per-file-ignores` を追加(F401 ノイズ 3783 → 0)、フロントエンド tsconfig は `noUnusedLocals` / `noUnusedParameters` を有効化して回帰ガードとし、`gtja191` alpha の未使用 `vw = vwap(...)` 雛形 76 件も削除しました。正味 **-918 行**。<details><summary>過去のニュース</summary>+- **2026-05-18** 🧹 **クリーンアップ + 3 つの潜在バグ修正**: `CompositeEngine` が取引所サフィックスのない中国先物コード(`RB2410` 等)を `GlobalFuturesEngine` に誤ルーティングしていた問題を修正。`_is_china_futures` を共有の `_market_hooks` モジュールに移し、製品コード表を大小文字正規化 + 非中国取引所のガードを追加、回帰ケース 9 件を新設しました。session FTS5 インデックスがタイムスタンプを永続化するようになり、クロスセッション検索を日付ソートできるようになりました。同じ修正で、re-upsert 経路が `started_at` を wall-clock で上書きしていた副次バグも解消しました。Vite 開発プロキシに `/alpha` を追加し、AlphaZoo ページが `npm run dev` で解決されるようになりました。`tests/test_e2e_harness_v2.py`(実 LLM の e2e スイート)は `VIBE_TRADING_RUN_LIVE_E2E=1` でゲート化し、CI が環境変数の有無で形を変えないようにしました。ruff に factor zoo 用の `per-file-ignores` を追加(F401 ノイズ 3783 → 0)、フロントエンド tsconfig は `noUnusedLocals` / `noUnusedParameters` を有効化して回帰ガードとし、`gtja191` alpha の未使用 `vw = vwap(...)` 雛形 76 件も削除しました。正味 **-918 行**。- **2026-05-17** 🧬 **Alpha Zoo v1(0.1.8)**: 4 つの zoo にまたがる 452 個の事前構築 quant alpha を同梱しました — `qlib158`(Microsoft Qlib の Alpha158 特徴量、Apache-2.0 出処明示)、`alpha101`(Kakushadze の "101 Formulaic Alphas" を arXiv:1601.00991 から論文ベースで書き直し)、`gtja191`(国泰君安 2014 年の短期取引型 alpha レポート)、`academic`(Fama-French 5 + Carhart 動量の価格ベース proxy 実装)。任意の universe で 1 行 CLI: `vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`。AST 純関数ゲート、look-ahead ガードテスト、`pytest-socket` ネットワーク遮断、各 zoo ごとの LICENSE.md、コミュニティ PR 用の DCO 署名フローも同梱。Alpha Library 自動レンダリングは [vibetrading.wiki/alpha-library/](https://vibetrading.wiki/alpha-library/)、Research Lab には [Which of the 191 GTJA alphas still work in 2026?](https://vibetrading.wiki/research-lab/posts/alpha-191-in-2026.html) を公開。- **2026-05-16** 🧪 **リサーチ基盤アップデート**: backend Hypothesis Registry を追加し、`create_hypothesis`、`update_hypothesis`、`link_backtest`、`search_hypotheses` を提供します。外部コンテンツ reader は warning-only の `security_warnings` を付与し、Shadow Account scanner は旧 calendar-phase stub から決定的な OHLCV feature evaluation に移行しました。- **2026-05-15** 🪪 Run 詳細ページが metrics と artifacts の隣に Trust Layer の run card を描画するようになり、2026-05-12 に入った `run_card.json` 側の UI 半分が揃いました。`PersistentMemory.add()` も #108/#109/#110 の triage を受け、長さ、空・空白だけの name、C0/C1 制御バイトの各経路で強化されました([#112](https://github.com/HKUDS/Vibe-Trading/pull/112)、@Teerapat-Vatpitak に感謝)。@@ -757,7 +758,7 @@ OpenSpace は 75 skills を自動検出し、auto-fix、auto-improve、community```Vibe-Trading/├── agent/ # バックエンド (Python)-│ ├── cli.py # CLI エントリポイント — インタラクティブ TUI + サブコマンド+│ ├── cli/ # CLI パッケージ — インタラクティブ TUI + サブコマンド│ ├── api_server.py # FastAPI サーバー — runs、sessions、upload、swarm、SSE│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 22 tools│ │diff --git a/README_ko.md b/README_ko.mdindex 255e6b4ec..58ea71cb3 100644--- a/README_ko.md+++ b/README_ko.md@@ -46,12 +46,13 @@## 📰 뉴스+- **2026-05-21** 🧱 **CLI 패키지 리팩토링**: `agent/cli.py`(3216 LOC)를 `agent/cli/` 패키지로 분할 — 대화형 진입점, 슬래시 라우터, Rich 컴포넌트, 그리고 모든 서브커맨드를 보존하고 `cli.cmd_*` / `cli._INIT_ENV_PATH` / `cli.Confirm` 등 공개 심볼을 재내보내는 `_legacy.py` shim. 새 FastAPI 미들웨어는 브라우저가 `/runs/{id}` 또는 `/correlation`에 직접 접근할 때 SPA 셸을 반환하며, 동일한 좁힘을 Vite dev 프록시에도 반영했습니다. 버전 문자열은 `cli/_version.py` 단일 소스로 통합(`--version`과 배너 드리프트 해결), `python -m cli`는 `__main__.py`로 복원, chat 게이트를 좁혀 `chat --help` / `chat extra`가 REPL에 삼켜지지 않고 레거시 argparse에 도달합니다.- **2026-05-20** 🔬 **Hypothesis Registry CLI**: 2026-05-16에 백엔드만 출시된 Hypothesis Registry의 CLI 측을 완성했습니다. `vibe-trading hypothesis list`는 Rich 테이블 또는 JSON을 출력합니다(`--status` 필터, `--limit` 지원). `show <id>`는 링크된 run card를 포함한 상세 패널을 렌더링합니다. `invalidate <id> --note "..."`는 상태를 `rejected`로 전환하며, `--note`를 생략하면 기존 invalidation notes를 유지합니다. 기존 `VIBE_TRADING_HYPOTHESES_PATH` 환경변수 오버라이드와 호출별 `--path`를 모두 지원합니다. 22개의 새 테스트가 와이어링, JSON 출력, 상태 필터, limit, ID 누락 오류, 노트 영속성을 다룹니다.- **2026-05-19** ✨ **도구 라이브 피드백 + 우아한 취소**: 오래 걸리는 도구(백테스트, 큰 PDF, swarm worker)가 멈춘 것처럼 보이지 않게 되었습니다. 모든 도구 호출은 이제 3초 간격의 하트비트와 구조화된 단계별 진행 상황을 발행합니다 — `run_backtest`는 단계 마커(`validate` / `simulate` / `finalize`), `read_document`는 PDF에서는 페이지 단위, Excel에서는 시트 단위, `read_url`은 `fetch` / `parse`를 표시합니다. CLI의 Rich Live 대시보드는 유니코드 스피너, ASCII 진행 표시줄, ETA를 렌더링하고 도구 이름으로 키된 최대 3개의 병렬 도구를 스택 표시합니다. 프런트엔드 채팅에는 새로운 `ToolProgressIndicator`를 추가했으며, rAF 코얼레싱, ARIA `role="status"` + 스크린 리더용 숨겨진 네이티브 `<progress>`, 총량을 알 때 결정적 `ProgressRing` SVG로 전환합니다. CLI 실행 중 첫 번째 `Ctrl+C`는 이제 `agent.cancel()`을 호출해 우아하게 종료(현재 단계가 끝나고 trace가 깨끗하게 닫힘)하고, 2초 이내 두 번째는 강제 종료합니다. 재사용 가능한 기본 요소도 추출했습니다: `ProgressBar.tsx`와 `lib/tools.ts`(공유 도구 이름 i18n).-- **2026-05-18** 🧹 **정리 + 3개의 잠재 버그 수정**: `CompositeEngine`이 거래소 접미사가 없는 중국 선물 코드(`RB2410` 등)를 `GlobalFuturesEngine`으로 잘못 라우팅하던 문제를 수정했습니다. `_is_china_futures`를 공유 `_market_hooks` 모듈로 옮기고, 상품 코드 테이블에 대소문자 정규화 + 비중국 거래소 가드를 추가했으며, 회귀 케이스 9개를 새로 작성했습니다. session FTS5 인덱스가 타임스탬프를 영구 저장하게 되어 크로스 세션 검색에서 날짜 정렬이 가능해졌으며, 동일 변경으로 re-upsert 경로가 `started_at`을 wall-clock으로 덮어쓰던 부수 버그도 해결했습니다. Vite 개발 프록시에 누락되었던 `/alpha`를 추가하여 AlphaZoo 페이지가 `npm run dev`에서 정상 해석됩니다. `tests/test_e2e_harness_v2.py`(실 LLM e2e 스위트)는 `VIBE_TRADING_RUN_LIVE_E2E=1`로 게이트하여 CI가 환경변수 유무에 따라 형태를 바꾸지 않도록 했습니다. ruff에 factor zoo용 `per-file-ignores`를 추가(F401 잡음 3783 → 0)하고, 프런트엔드 tsconfig에 `noUnusedLocals` / `noUnusedParameters`를 활성화해 회귀 가드로 두었으며, `gtja191` alpha 파일들의 사용되지 않는 `vw = vwap(...)` 보일러플레이트 76개도 삭제했습니다. 순 **-918줄**.<details><summary>이전 뉴스</summary>+- **2026-05-18** 🧹 **정리 + 3개의 잠재 버그 수정**: `CompositeEngine`이 거래소 접미사가 없는 중국 선물 코드(`RB2410` 등)를 `GlobalFuturesEngine`으로 잘못 라우팅하던 문제를 수정했습니다. `_is_china_futures`를 공유 `_market_hooks` 모듈로 옮기고, 상품 코드 테이블에 대소문자 정규화 + 비중국 거래소 가드를 추가했으며, 회귀 케이스 9개를 새로 작성했습니다. session FTS5 인덱스가 타임스탬프를 영구 저장하게 되어 크로스 세션 검색에서 날짜 정렬이 가능해졌으며, 동일 변경으로 re-upsert 경로가 `started_at`을 wall-clock으로 덮어쓰던 부수 버그도 해결했습니다. Vite 개발 프록시에 누락되었던 `/alpha`를 추가하여 AlphaZoo 페이지가 `npm run dev`에서 정상 해석됩니다. `tests/test_e2e_harness_v2.py`(실 LLM e2e 스위트)는 `VIBE_TRADING_RUN_LIVE_E2E=1`로 게이트하여 CI가 환경변수 유무에 따라 형태를 바꾸지 않도록 했습니다. ruff에 factor zoo용 `per-file-ignores`를 추가(F401 잡음 3783 → 0)하고, 프런트엔드 tsconfig에 `noUnusedLocals` / `noUnusedParameters`를 활성화해 회귀 가드로 두었으며, `gtja191` alpha 파일들의 사용되지 않는 `vw = vwap(...)` 보일러플레이트 76개도 삭제했습니다. 순 **-918줄**.- **2026-05-17** 🧬 **Alpha Zoo v1 (0.1.8)**: 4개 zoo에 걸친 452개의 사전 빌드된 quant alpha를 번들로 제공 — `qlib158`(Microsoft Qlib의 Alpha158 특성, Apache-2.0 출처 표기), `alpha101`(Kakushadze의 "101 Formulaic Alphas"를 arXiv:1601.00991 논문 부록에서 재구현), `gtja191`(국태군안 2014 단기 거래형 alpha 리서치 보고서), `academic`(Fama-French 5 + Carhart 모멘텀의 가격 기반 proxy 구현). 한 줄 CLI로 임의 universe에서 벤치: `vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`. AST 순수 함수 게이트, look-ahead 가드 테스트, `pytest-socket` 네트워크 차단, zoo별 LICENSE.md, 커뮤니티 PR용 DCO 서명 워크플로우 포함. Alpha Library 자동 렌더링: [vibetrading.wiki/alpha-library/](https://vibetrading.wiki/alpha-library/), Research Lab 글: [Which of the 191 GTJA alphas still work in 2026?](https://vibetrading.wiki/research-lab/posts/alpha-191-in-2026.html).- **2026-05-16** 🧪 **리서치 기반 업데이트**: backend Hypothesis Registry를 추가해 `create_hypothesis`, `update_hypothesis`, `link_backtest`, `search_hypotheses`를 제공합니다. 외부 콘텐츠 reader는 warning-only `security_warnings`를 붙이고, Shadow Account scanner는 기존 calendar-phase stub 대신 deterministic OHLCV feature evaluation을 사용합니다.- **2026-05-15** 🪪 Run 상세 페이지에서 metrics와 artifacts 옆에 Trust Layer run card를 렌더링해, 2026-05-12에 들어간 `run_card.json` 작업의 UI 측을 마무리합니다. `PersistentMemory.add()`도 #108/#109/#110 triage에 따라 길이, 빈 문자열 또는 공백만으로 이루어진 name, C0/C1 제어 바이트 경로에서 강화되었습니다([#112](https://github.com/HKUDS/Vibe-Trading/pull/112), @Teerapat-Vatpitak 감사합니다).@@ -760,7 +761,7 @@ OpenSpace는 75개 skills를 모두 자동 발견하여 auto-fix, auto-improve,```Vibe-Trading/├── agent/ # Backend (Python)-│ ├── cli.py # CLI entrypoint — interactive TUI + subcommands+│ ├── 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│ │diff --git a/README_zh.md b/README_zh.mdindex 09e644b33..5d00391b8 100644--- a/README_zh.md+++ b/README_zh.md@@ -46,12 +46,13 @@## 📰 News+- **2026-05-21** 🧱 **CLI 包重构**:`agent/cli.py`(3216 行)拆成 `agent/cli/` 包 —— 交互入口、slash 路由、Rich 组件,加 `_legacy.py` shim 保留所有子命令并 re-export 所有公共符号,`cli.cmd_*` / `cli._INIT_ENV_PATH` / `cli.Confirm` 不变。新增 FastAPI middleware:浏览器直开 `/runs/{id}` 或 `/correlation` 时返回 SPA shell;Vite dev proxy 同步收窄到相同 regex。版本号通过 `cli/_version.py` 单一来源(`--version` 与 banner 不再 drift),`python -m cli` 通过 `__main__.py` 恢复,chat-gate 收窄使 `chat --help` / `chat extra` 正确走 legacy argparse 而不被新 REPL 吞掉。- **2026-05-20** 🔬 **Hypothesis Registry CLI**:补齐了 5-16 上线但只有后端的 Hypothesis Registry 的 CLI 侧。`vibe-trading hypothesis list` 输出 Rich 表格或 JSON(支持 `--status` 过滤、`--limit`);`show <id>` 渲染详情面板,包含已 link 的 run card;`invalidate <id> --note "..."` 把 status 翻成 `rejected`,省略 `--note` 时保留原有 invalidation notes。沿用 `VIBE_TRADING_HYPOTHESES_PATH` 环境变量,并新增按调用覆盖的 `--path`。22 个新单测覆盖 wiring、JSON 输出、状态过滤、limit、缺 id 报错、备注持久化。- **2026-05-19** ✨ **工具实时反馈 + 优雅取消**:长时间运行的工具(回测、大 PDF、swarm worker)不再看起来卡死。每个工具调用现在会发出 3 秒一次的心跳,以及结构化的阶段进度 —— `run_backtest` 输出阶段标记(`validate` / `simulate` / `finalize`),`read_document` 在 PDF 上按页打点 / Excel 上按工作表打点,`read_url` 标记 `fetch` / `parse`。CLI 的 Rich Live 面板渲染 Unicode 转轮、ASCII 进度条、ETA,按工具名最多堆叠 3 个并行工具;前端 chat 新增 `ToolProgressIndicator`,rAF 合并刷新、ARIA `role="status"` + 隐藏的原生 `<progress>` 供屏幕阅读器使用,已知总数时切换为 determinate 的 `ProgressRing` SVG。CLI 中第一次 `Ctrl+C` 现在会调 `agent.cancel()` 优雅退出(当前步骤跑完、trace 干净关闭);2 秒内第二次 `Ctrl+C` 强制退出。顺手抽出可复用基础件:`ProgressBar.tsx` 和 `lib/tools.ts`(共享工具名 i18n 映射)。-- **2026-05-18** 🧹 **清理一次 + 3 个潜伏 bug 修复**:`CompositeEngine` 不再把无交易所后缀的中国期货代码(如 `RB2410`)错误路由到 `GlobalFuturesEngine` —— `_is_china_futures` 移到共享的 `_market_hooks` 模块,产品代码表做了大小写归一并加入非中国交易所守卫,新增 9 条回归用例。session FTS5 索引现在会持久化时间戳,跨 session 搜索可按日期排序;同一改动也修复了 re-upsert 路径每次都用 wall-clock 覆盖 `started_at` 的副作用 bug。前端 Vite dev proxy 补上漏配的 `/alpha`,AlphaZoo 页在 `npm run dev` 下不再 404。`tests/test_e2e_harness_v2.py`(真 LLM 的 e2e 套件)现在用 `VIBE_TRADING_RUN_LIVE_E2E=1` 做环境门控,CI 不再因为有无 LLM key 而静默切状态。Ruff 为 factor zoo 添加 `per-file-ignores`(3783 → 0 F401 噪音),前端 tsconfig 打开 `noUnusedLocals` / `noUnusedParameters` 做回归护栏,并删掉了 76 个 `gtja191` alpha 文件里没用上的 `vw = vwap(...)` 残留。净 **-918 行**。<details><summary>更早的更新</summary>+- **2026-05-18** 🧹 **清理一次 + 3 个潜伏 bug 修复**:`CompositeEngine` 不再把无交易所后缀的中国期货代码(如 `RB2410`)错误路由到 `GlobalFuturesEngine` —— `_is_china_futures` 移到共享的 `_market_hooks` 模块,产品代码表做了大小写归一并加入非中国交易所守卫,新增 9 条回归用例。session FTS5 索引现在会持久化时间戳,跨 session 搜索可按日期排序;同一改动也修复了 re-upsert 路径每次都用 wall-clock 覆盖 `started_at` 的副作用 bug。前端 Vite dev proxy 补上漏配的 `/alpha`,AlphaZoo 页在 `npm run dev` 下不再 404。`tests/test_e2e_harness_v2.py`(真 LLM 的 e2e 套件)现在用 `VIBE_TRADING_RUN_LIVE_E2E=1` 做环境门控,CI 不再因为有无 LLM key 而静默切状态。Ruff 为 factor zoo 添加 `per-file-ignores`(3783 → 0 F401 噪音),前端 tsconfig 打开 `noUnusedLocals` / `noUnusedParameters` 做回归护栏,并删掉了 76 个 `gtja191` alpha 文件里没用上的 `vw = vwap(...)` 残留。净 **-918 行**。- **2026-05-17** 🧬 **Alpha Zoo v1(0.1.8)**:内置 452 个量化 alpha,覆盖 4 个 zoo —— `qlib158`(Microsoft Qlib 的 Alpha158 特征,Apache-2.0 出处声明)、`alpha101`(Kakushadze 的 "101 Formulaic Alphas",从 arXiv:1601.00991 论文公式重写)、`gtja191`(国君证券 2014 短周期交易型因子研报)、`academic`(Fama-French 5 因子 + Carhart 动量的价格代理实现)。一行 CLI 就能在自己的 universe 上跑横评:`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`。配套设施包括 AST 纯函数门禁、lookahead 防护测试、`pytest-socket` 网络隔离、每个 zoo 一份 LICENSE.md、社区贡献用的 DCO 签名流程;Alpha Library 自动渲染上线 [vibetrading.wiki/alpha-library/](https://vibetrading.wiki/alpha-library/);Research Lab 同步发布 [《191 个 GTJA alpha 哪些在 2026 还能用》](https://vibetrading.wiki/research-lab/posts/alpha-191-in-2026.html)。- **2026-05-16** 🧪 **研究主干更新**:新增后端 Hypothesis Registry,提供 `create_hypothesis`、`update_hypothesis`、`link_backtest`、`search_hypotheses`;外部内容读取工具现在会附加 warning-only 的 `security_warnings`;Shadow Account 扫描也从旧的日历 phase stub 升级为确定性的 OHLCV 特征评估。- **2026-05-15** 🪪 Run 详情页现在会在 metrics 和 artifacts 旁边渲染 Trust Layer 的 run card,把 2026-05-12 已落地的 `run_card.json` 工作补齐到 UI 一侧。`PersistentMemory.add()` 也根据 #108/#109/#110 的 triage,在长度限制、空 / 纯空白 name、以及 C0/C1 控制字节三条路径上做了加固([#112](https://github.com/HKUDS/Vibe-Trading/pull/112),感谢 @Teerapat-Vatpitak)。@@ -756,7 +757,7 @@ OpenSpace 会自动发现全部 75 个 skills,启用 auto-fix、auto-improve```Vibe-Trading/├── agent/ # 后端(Python)-│ ├── cli.py # CLI 入口 —— 交互式 TUI + 子命令+│ ├── cli/ # CLI 包 —— 交互式 TUI + 子命令│ ├── api_server.py # FastAPI server —— runs、sessions、upload、swarm、SSE│ ├── mcp_server.py # MCP server —— 22 个工具,面向 OpenClaw / Claude Desktop│ │diff --git a/agent/api_server.py b/agent/api_server.pyindex 3a1b04fde..9db33a982 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -11,6 +11,7 @@ import hmacimport ipaddressimport jsonimport os+import reimport signalimport timeimport csv@@ -297,6 +298,61 @@ app.add_middleware()+# ----------------------------------------------------------------------------+# SPA deep-link fallback+# ----------------------------------------------------------------------------+# A handful of API routes share their path with frontend SPA routes (e.g.+# ``/runs/{id}`` and ``/correlation``). Because FastAPI matches registered+# routes before the static SPA mount, a browser that refreshes or bookmarks+# one of these URLs would receive JSON (or 401/422) instead of the SPA shell.+# The middleware below serves ``frontend/dist/index.html`` when the request+# clearly came from a browser (``Accept`` contains ``text/html``); programmatic+# clients are routed to the real API handler as before.+#+# Patterns are written narrowly so the SPA shell only shadows paths that+# actually correspond to frontend pages. In particular ``/runs/{id}`` is+# the RunDetail page, but ``/runs/{id}/code`` and ``/runs/{id}/pine`` are+# API-only endpoints with no SPA route — using a broad ``/runs/`` prefix+# here would incorrectly hijack those when the browser sets ``Accept:+# text/html`` (e.g. a user pasting the URL into the address bar).++_FRONTEND_DIST = Path(__file__).resolve().parent.parent / "frontend" / "dist"+_SPA_HTML_EXACT_PATHS: frozenset[str] = frozenset({"/correlation"})+# Each regex matches a complete request path. Trailing slash optional.+_SPA_HTML_PATH_REGEX: tuple[re.Pattern[str], ...] = (+ # ``/runs/{run_id}`` — RunDetail page. Excludes ``/runs/{id}/code``,+ # ``/runs/{id}/pine`` (API only) and ``/runs`` (collection endpoint).+ re.compile(r"^/runs/[^/]+/?$"),+)+++def _is_spa_html_route(path: str) -> bool:+ """Return True when ``path`` corresponds to a frontend SPA page that+ shadows an API endpoint and should fall back to ``index.html`` on+ browser navigation."""+ if path in _SPA_HTML_EXACT_PATHS:+ return True+ return any(pattern.match(path) for pattern in _SPA_HTML_PATH_REGEX)++[email protected]("http")+async def _spa_html_deep_link_fallback(request: Request, call_next):+ """Serve ``frontend/dist/index.html`` when a browser navigates directly to+ an SPA path that also exists as an API endpoint.++ Conflicts: ``/runs/{id}`` (RunDetail page vs API) and ``/correlation``+ (Correlation page vs API). Programmatic clients (``Accept: */*`` or+ ``application/json``) still hit the real API handler.+ """+ if request.method == "GET":+ accept = request.headers.get("accept", "")+ if "text/html" in accept and _is_spa_html_route(request.url.path):+ index = _FRONTEND_DIST / "index.html"+ if index.exists():+ return FileResponse(str(index))+ return await call_next(request)++@app.on_event("startup")async def _run_startup_preflight() -> None:"""Run preflight checks on server startup."""diff --git a/agent/cli/__init__.py b/agent/cli/__init__.pynew file mode 100644index 000000000..af219e568--- /dev/null+++ b/agent/cli/__init__.py@@ -0,0 +1,106 @@+"""Vibe-Trading CLI package.++The legacy single-file CLI has been preserved verbatim as+``cli/_legacy.py`` and is the source of truth for non-interactive+subcommands (``serve``, ``run``, ``mcp``, ``sessions``, ``swarm`` ...).+The front door (:mod:`cli.main`) shows the banner, runs the+onboarding wizard when needed, then drives the interactive loop+built on :mod:`cli.input`, :mod:`cli.completer`, and+:mod:`cli.commands.*`. Non-interactive entries still pass through to+``_legacy.main``.++The console-script entry in ``pyproject.toml``+(``vibe-trading = "cli:main"``) points at the ``main`` callable exported+here.++Compatibility note: tests and downstream callers historically reached+into ``cli._INIT_ENV_PATH`` / ``cli.cmd_memory_list`` / ``cli.Confirm``+etc. To preserve that surface we re-export every public name from+``_legacy`` at package import time. New code should import the same+helpers from ``cli._legacy`` directly.+"""++from __future__ import annotations++from cli import _legacy as _legacy+from cli.main import main++# Re-export the legacy module's public surface (anything not prefixed+# with two underscores). This lets ``cli.cmd_memory_list`` /+# ``cli._INIT_ENV_PATH`` / ``cli.Prompt`` etc. keep working without us+# having to enumerate every name by hand.+for _name in dir(_legacy):+ if _name.startswith("__"):+ continue+ globals().setdefault(_name, getattr(_legacy, _name))+del _name+++# Symbols tests may monkeypatch on the ``cli`` package that legacy+# callables still read from their own module globals. Keep this list+# explicit so accidental package-level attributes don't bleed into+# ``_legacy``.+_LEGACY_SYNCED_GLOBALS: tuple[str, ...] = (+ "_INIT_ENV_PATH",+ "AGENT_DIR",+ "RUNS_DIR",+ "SWARM_DIR",+ "SESSIONS_DIR",+ "UPLOADS_DIR",+ "_PROVIDER_CHOICES",+)+++def _sync_legacy_test_overrides() -> None:+ """Mirror package-level monkeypatches onto ``_legacy``'s module globals.++ Tests reach into ``cli.<NAME>`` to override constants, but legacy+ callables read ``<NAME>`` from their own module namespace. This hook+ copies any patched value back to ``_legacy`` for the allowlist below.+ """+ pkg_globals = globals()+ for name in _LEGACY_SYNCED_GLOBALS:+ if name not in pkg_globals:+ continue+ new_value = pkg_globals[name]+ if getattr(_legacy, name, None) is not new_value:+ setattr(_legacy, name, new_value)+++def cmd_init() -> int:+ """Compatibility wrapper for callers patching ``cli._INIT_ENV_PATH``."""+ _sync_legacy_test_overrides()+ return _legacy.cmd_init()+++# Wrap every ``cmd_*`` callable re-exported from ``_legacy`` so a package-level+# monkeypatch of any symbol in ``_LEGACY_SYNCED_GLOBALS`` is propagated to+# ``_legacy`` before the call. Without this, ``patch.object(cli, "RUNS_DIR",+# tmp); cli.cmd_list()`` would silently read the unpatched ``_legacy.RUNS_DIR``.+import functools as _functools # noqa: E402++def _make_synced_legacy_wrapper(legacy_fn): # noqa: ANN001+ """Wrap ``legacy_fn`` so the package-level monkeypatch sync fires first."""++ @_functools.wraps(legacy_fn)+ def _wrapper(*args, **kwargs):+ _sync_legacy_test_overrides()+ # Re-read the (possibly just-synced) attribute from ``_legacy`` in+ # case the test also patched the function itself.+ return getattr(_legacy, legacy_fn.__name__)(*args, **kwargs)++ _wrapper.__wrapped__ = legacy_fn+ return _wrapper+++for _cmd_name in [n for n in globals() if n.startswith("cmd_") and n != "cmd_init"]:+ _cmd_obj = globals()[_cmd_name]+ if callable(_cmd_obj) and getattr(_cmd_obj, "__module__", "") == "cli._legacy":+ globals()[_cmd_name] = _make_synced_legacy_wrapper(_cmd_obj)+del _cmd_name, _cmd_obj+++__all__ = ["main", *sorted(+ name for name in globals()+ if not name.startswith("_") and name != "main"+)]diff --git a/agent/cli/__main__.py b/agent/cli/__main__.pynew file mode 100644index 000000000..1a40d6466--- /dev/null+++ b/agent/cli/__main__.py@@ -0,0 +1,5 @@+"""Allow ``python -m cli`` to run the CLI entrypoint."""++from cli.main import _entrypoint++_entrypoint()diff --git a/agent/cli.py b/agent/cli/_legacy.pysimilarity index 99%rename from agent/cli.pyrename to agent/cli/_legacy.pyindex 624073a02..44be15604 100644--- a/agent/cli.py+++ b/agent/cli/_legacy.py@@ -35,7 +35,6 @@ for _s in ("stdout", "stderr"):if callable(_r):_r(encoding="utf-8", errors="replace")-from rich.console import Consolefrom rich import boxfrom rich.columns import Columnsfrom rich.live import Live@@ -46,8 +45,10 @@ from rich.syntax import Syntaxfrom rich.table import Tablefrom rich.text import Text-console = Console()-AGENT_DIR = Path(__file__).resolve().parent+from cli.theme import get_console++console = get_console()+AGENT_DIR = Path(__file__).resolve().parents[1]RUNS_DIR = AGENT_DIR / "runs"SWARM_DIR = AGENT_DIR / ".swarm" / "runs"SESSIONS_DIR = AGENT_DIR / "sessions"@@ -58,7 +59,7 @@ EXIT_RUN_FAILED = 1EXIT_USAGE_ERROR = 2RICH_TAG_PATTERN = re.compile(r"\[/?[^\]]+\]")-_VERSION = "0.1.7"+from cli._version import __version__ as _VERSION # noqa: E402 — single source of truth# Agent color assignments for swarm display_AGENT_STYLES = ["cyan", "magenta", "green", "yellow", "blue", "bright_red", "bright_cyan", "bright_magenta"]diff --git a/agent/cli/_version.py b/agent/cli/_version.pynew file mode 100644index 000000000..a5bfb25ff--- /dev/null+++ b/agent/cli/_version.py@@ -0,0 +1,26 @@+"""Single source of truth for the CLI version string.++Reads ``vibe-trading-ai``'s installed package metadata when available+(``pip install -e .`` is enough). Falls back to the static constant+below for un-installed checkouts (e.g. running straight from a clone+with ``PYTHONPATH=agent``).++Keep the fallback in sync with ``pyproject.toml`` ``[project] version``.+"""++from __future__ import annotations++from typing import Final++try:+ from importlib.metadata import PackageNotFoundError, version as _pkg_version++ try:+ __version__: Final[str] = _pkg_version("vibe-trading-ai")+ except PackageNotFoundError:+ __version__ = "0.1.8"+except ImportError: # pragma: no cover — importlib.metadata is stdlib on 3.8++ __version__ = "0.1.8"+++__all__ = ["__version__"]diff --git a/agent/cli/commands/__init__.py b/agent/cli/commands/__init__.pynew file mode 100644index 000000000..e17cba030--- /dev/null+++ b/agent/cli/commands/__init__.py@@ -0,0 +1,18 @@+"""Slash command implementations.++Each command module exports a ``run(ctx, *args) -> int`` callable. Modules+that own multiple commands (``chat``, ``show``, ``session``) also expose+named ``cmd_<name>`` callables so the slash router can dispatch by+command keyword.++The :data:`SLASH_COMMANDS` registry lives in :mod:`.slash_router`.+"""++from .slash_router import SLASH_COMMANDS, Command, find_exact, match_commands++__all__ = [+ "Command",+ "SLASH_COMMANDS",+ "find_exact",+ "match_commands",+]diff --git a/agent/cli/commands/chat.py b/agent/cli/commands/chat.pynew file mode 100644index 000000000..35c319f5b--- /dev/null+++ b/agent/cli/commands/chat.py@@ -0,0 +1,254 @@+"""Chat-flow slash commands: ``/model``, ``/clear``, ``/journal``,+``/shadow``, ``/swarm``, ``/debug``, ``/quit``.++``/model`` renders the current configuration via the legacy+``_show_settings`` helper. ``/swarm`` dispatches to the legacy+``_handle_swarm_command`` so the existing presets keep working. ``/clear``+clears the screen and reprints the banner. ``/journal``, ``/shadow``, and+``/debug`` show a "Coming soon" placeholder pointing at the established+fallback workflows.+"""++from __future__ import annotations++import os+from typing import Any, Optional++from rich.console import Console+from rich.panel import Panel+from rich.text import Text++from cli.theme import get_console+++def _resolve_console(console: Optional[Console] = None) -> Console:+ """Return the shared CLI console, or a caller-supplied override."""+ if console is not None:+ return console+ return get_console()+++def _coming_soon(command: str, *, hint: str) -> int:+ """Render the placeholder panel for not-yet-wired commands."""+ console = _resolve_console()+ body = Text()+ body.append(f"/{command} is not yet wired up to the interactive CLI.\n\n", style="dim")+ body.append("Until then: ", style="dim")+ body.append(hint, style="bold")+ console.print(Panel(body, title=f"/{command}", border_style="dim", padding=(1, 2)))+ return 0+++# --- /model ----------------------------------------------------------------+++def cmd_model(ctx: Any = None, *args: str) -> int: # noqa: ARG001 — ctx unused+ """Print the current provider/model + how to re-run the wizard."""+ console = _resolve_console()+ try:+ from cli._legacy import _show_settings++ _show_settings()+ except Exception as exc: # noqa: BLE001 — legacy may be absent on partial install+ provider = os.getenv("LANGCHAIN_PROVIDER", "(not set)")+ model = os.getenv("LANGCHAIN_MODEL_NAME", "(not set)")+ console.print(Text(f"Provider: {provider}", style="bold"))+ console.print(Text(f"Model: {model}", style="bold"))+ console.print(Text(f"(legacy _show_settings unavailable: {exc})", style="dim"))++ console.print()+ console.print(+ Text(+ "Run `vibe-trading init` to switch provider, model, or credentials.",+ style="dim",+ )+ )+ return 0+++# --- /clear, /journal, /shadow, /swarm, /debug, /quit ----------------------+++def cmd_clear(ctx: Any = None, *args: str) -> int: # noqa: ARG001+ """Clear the screen and reprint the welcome banner."""+ console = _resolve_console()+ try:+ console.clear()+ except Exception: # noqa: BLE001 — clear can fail on dumb terminals+ pass+ # Best-effort: reprint the banner so the conversation appears fresh.+ # Reuse the cached stats populated at startup so the redrawn banner+ # shows the real skills / tools / sessions counts, not zeros.+ try:+ from cli.intro import print_banner+ from cli.main import _collect_banner_stats++ print_banner(console, **_collect_banner_stats())+ except Exception: # noqa: BLE001+ console.print(Text("Conversation cleared.", style="dim"))+ # Caller is expected to also drop in-memory conversation history.+ if ctx is not None and hasattr(ctx, "history"):+ try:+ ctx.history.clear()+ except Exception: # noqa: BLE001+ pass+ return 0+++def _queue_prompt(ctx: Any, prompt: str) -> bool:+ """Stash ``prompt`` on ``ctx.pending_prompt`` for the loop to consume.++ Returns ``True`` if the context exposes a writable ``pending_prompt``+ attribute, ``False`` otherwise (e.g. a tiny test stub) — the caller+ falls back to printing the canonical instruction in that case.+ """+ if ctx is None or not hasattr(ctx, "pending_prompt"):+ return False+ try:+ ctx.pending_prompt = prompt+ return True+ except Exception: # noqa: BLE001 — never crash the slash dispatch+ return False+++def cmd_journal(ctx: Any = None, *args: str) -> int:+ """Queue an "analyze my trade journal at <path>" agent turn.++ With a path: ``/journal trades.csv`` becomes the prompt+ ``Analyze my trade journal at trades.csv`` which is queued on+ ``ctx.pending_prompt`` and executed by the interactive loop on the+ next tick. Without a path the command prints the canonical+ instruction so the user can paste it themselves.+ """+ console = _resolve_console()+ path = " ".join(args).strip()+ if not path:+ body = Text()+ body.append("Usage: ", style="dim")+ body.append("/journal <path-to-csv>\n", style="bold")+ body.append("Example: ", style="dim")+ body.append('/journal ~/Downloads/journal.csv\n\n', style="bold")+ body.append("Or type the prompt directly: ", style="dim")+ body.append('"analyze my trade journal at <path>"', style="bold")+ console.print(Panel(body, title="/journal", border_style="dim", padding=(1, 2)))+ return 0++ prompt = f"Analyze my trade journal at {path}"+ if _queue_prompt(ctx, prompt):+ console.print(Text(f"→ Running: {prompt}", style="dim"))+ return 0+ # Fallback when the context does not support queuing (legacy callers).+ console.print(Text(f'Type: "{prompt}"', style="bold"))+ return 0+++def cmd_shadow(ctx: Any = None, *args: str) -> int:+ """Queue a Shadow Account agent turn.++ ``/shadow`` opens / inspects the shadow account. ``/shadow <path>``+ trains a new shadow from a trade journal at that path. Both forms+ queue the canonical natural-language prompt on ``ctx.pending_prompt``+ so the ReAct loop picks the right tool (``extract_shadow_strategy``,+ ``run_shadow_backtest``, ``render_shadow_report``).+ """+ console = _resolve_console()+ path = " ".join(args).strip()+ if path:+ prompt = f"Train a shadow account from my trade journal at {path}"+ else:+ prompt = "Open the shadow account dashboard and show the latest report"++ if _queue_prompt(ctx, prompt):+ console.print(Text(f"→ Running: {prompt}", style="dim"))+ return 0+ console.print(Text(f'Type: "{prompt}"', style="bold"))+ return 0+++def cmd_swarm(ctx: Any = None, *args: str) -> int: # noqa: ARG001+ """Dispatch to the legacy swarm handler."""+ try:+ from cli._legacy import _handle_swarm_command++ _handle_swarm_command(" ".join(args))+ return 0+ except Exception as exc: # noqa: BLE001+ console = _resolve_console()+ console.print(Text(f"/swarm failed: {exc}", style="bold red"))+ return 1+++def cmd_debug(ctx: Any = None, *args: str) -> int: # noqa: ARG001+ """Toggle the debug summary that prints after each agent turn.++ When ON the interactive loop appends a single muted line after every+ turn containing ``iter``, ``tools``, ``elapsed``, and an approximate+ context-size estimate — see ``_print_debug_summary`` in+ :mod:`cli.main`. When OFF the summary is suppressed.+ """+ console = _resolve_console()+ if ctx is not None and hasattr(ctx, "debug"):+ try:+ ctx.debug = not bool(getattr(ctx, "debug", False))+ state = "ON" if ctx.debug else "OFF"+ console.print(Text(f"Debug summary: {state}", style="bold"))+ if ctx.debug:+ console.print(+ Text(+ "After each turn a one-line summary will print: "+ "iterations, tool count, elapsed, approx context tokens.",+ style="dim",+ )+ )+ return 0+ except Exception as exc: # noqa: BLE001+ console.print(Text(f"/debug toggle failed: {exc}", style="bold red"))+ return 1+ return _coming_soon(+ "debug",+ hint="set `VIBE_TRADING_DEBUG=1` and restart for verbose logging.",+ )+++def cmd_quit(ctx: Any = None, *args: str) -> int: # noqa: ARG001+ """Signal exit by returning a distinct exit code.++ The interactive loop interprets ``2`` as "user-requested quit" and+ performs session persistence + final farewell before terminating.+ """+ return 2+++# --- Module-level dispatch table -----------------------------------------++_DISPATCH = {+ "model": cmd_model,+ "clear": cmd_clear,+ "journal": cmd_journal,+ "shadow": cmd_shadow,+ "swarm": cmd_swarm,+ "debug": cmd_debug,+ "quit": cmd_quit,+}+++def run(ctx: Any = None, command: str = "model", *args: str) -> int:+ """Dispatch ``run("model")`` / ``run("clear")`` / ... to the right handler."""+ handler = _DISPATCH.get(command)+ if handler is None:+ console = _resolve_console()+ console.print(Text(f"Unknown chat command: /{command}", style="bold red"))+ return 1+ return handler(ctx, *args)+++__all__ = [+ "run",+ "cmd_model",+ "cmd_clear",+ "cmd_journal",+ "cmd_shadow",+ "cmd_swarm",+ "cmd_debug",+ "cmd_quit",+]diff --git a/agent/cli/commands/help.py b/agent/cli/commands/help.pynew file mode 100644index 000000000..cd361dc06--- /dev/null+++ b/agent/cli/commands/help.py@@ -0,0 +1,64 @@+"""``/help`` — Show the slash command list and keyboard shortcuts.++Renders ``SLASH_COMMANDS`` as a two-column Rich table (name in primary+color, description muted) plus a short keyboard-shortcuts panel.+"""++from __future__ import annotations++from typing import Any++from rich.console import Console+from rich.table import Table+from rich.text import Text++from .slash_router import SLASH_COMMANDS+++def _resolve_console() -> Console:+ """Return the shared CLI console."""+ from cli.theme import get_console++ return get_console()+++_SHORTCUTS: tuple[tuple[str, str], ...] = (+ ("⏎", "Send"),+ ("Shift+⏎", "Newline"),+ ("Tab", "Accept completion"),+ ("↑/↓", "Browse history (or navigate completions)"),+ ("Ctrl+C", "Clear input · then exit hint"),+ ("Ctrl+D", "Exit (auto-saves session)"),+ ("/", "Open slash command typeahead"),+)+++def run(ctx: Any = None, *args: str) -> int: # noqa: ARG001 — ctx unused here+ """Print the help screen. Always returns 0."""+ console = _resolve_console()++ commands_table = Table.grid(padding=(0, 2))+ commands_table.add_column(style="bold #d97706", no_wrap=True)+ commands_table.add_column(style="dim")+ for cmd in SLASH_COMMANDS:+ commands_table.add_row(f"/{cmd.name}", cmd.description)++ console.print()+ console.print(Text("Commands", style="bold"))+ console.print(commands_table)+ console.print()++ shortcuts_table = Table.grid(padding=(0, 2))+ shortcuts_table.add_column(style="bold", no_wrap=True)+ shortcuts_table.add_column(style="dim")+ for key, desc in _SHORTCUTS:+ shortcuts_table.add_row(key, desc)++ console.print(Text("Keyboard", style="bold"))+ console.print(shortcuts_table)+ console.print()++ return 0+++__all__ = ["run"]diff --git a/agent/cli/commands/memory.py b/agent/cli/commands/memory.pynew file mode 100644index 000000000..268c2d876--- /dev/null+++ b/agent/cli/commands/memory.py@@ -0,0 +1,67 @@+"""``/memory`` — list / show persistent memory snippets.++Delegates to the legacy ``cmd_memory_list`` / ``cmd_memory_show`` /+``cmd_memory_search`` callables. ``/memory`` with no args lists; with+a single arg shows one; with ``search <q>`` runs FTS; with+``forget <name>`` deletes one.+"""++from __future__ import annotations++from typing import Any++from rich.console import Console+from rich.text import Text++from cli.theme import get_console+++def _resolve_console() -> Console:+ """Return the shared CLI console."""+ return get_console()+++def cmd_memory(ctx: Any = None, *args: str) -> int: # noqa: ARG001+ """Dispatch sub-actions:++ * ``/memory`` → list+ * ``/memory <name>`` → show+ * ``/memory search <q>`` → full-text search+ * ``/memory forget <name>``→ delete a snippet+ """+ console = _resolve_console()++ if not args:+ try:+ from cli._legacy import cmd_memory_list++ return cmd_memory_list()+ except Exception as exc: # noqa: BLE001+ console.print(Text(f"/memory list failed: {exc}", style="bold red"))+ return 1++ sub = args[0]+ rest = args[1:]+ try:+ if sub == "search" and rest:+ from cli._legacy import cmd_memory_search++ return cmd_memory_search(" ".join(rest))+ if sub == "forget" and rest:+ from cli._legacy import cmd_memory_forget++ return cmd_memory_forget(rest[0], yes=False)+ from cli._legacy import cmd_memory_show++ return cmd_memory_show(sub)+ except Exception as exc: # noqa: BLE001+ console.print(Text(f"/memory failed: {exc}", style="bold red"))+ return 1+++def run(ctx: Any = None, *args: str) -> int:+ """Single-entrypoint wrapper for the slash router."""+ return cmd_memory(ctx, *args)+++__all__ = ["run", "cmd_memory"]diff --git a/agent/cli/commands/session.py b/agent/cli/commands/session.pynew file mode 100644index 000000000..d00c45ba3--- /dev/null+++ b/agent/cli/commands/session.py@@ -0,0 +1,98 @@+"""``/history``, ``/search``, ``/export`` — session lifecycle commands.++* ``/history`` lists recent sessions (legacy ``cmd_sessions``).+* ``/search <query>`` runs FTS5 across the session store via+ :class:`src.session.search.SessionSearchIndex`.+* ``/export`` is a placeholder — the rich export lives in the Web bubble.+"""++from __future__ import annotations++from typing import Any++from rich.console import Console+from rich.panel import Panel+from rich.text import Text++from cli.theme import get_console+++def _resolve_console() -> Console:+ """Return the shared CLI console."""+ return get_console()+++def cmd_history(ctx: Any = None, *args: str) -> int: # noqa: ARG001+ """List recent sessions via legacy ``cmd_sessions``."""+ console = _resolve_console()+ try:+ from cli._legacy import cmd_sessions++ cmd_sessions()+ return 0+ except Exception as exc: # noqa: BLE001+ console.print(Text(f"/history failed: {exc}", style="bold red"))+ return 1+++def cmd_search(ctx: Any = None, *args: str) -> int: # noqa: ARG001+ """Full-text search across recorded sessions."""+ console = _resolve_console()+ if not args:+ console.print(Text("Usage: /search <query>", style="bold red"))+ return 1++ query = " ".join(args)+ try:+ from src.session.search import get_shared_index++ index = get_shared_index()+ matches = index.search(query)+ except Exception as exc: # noqa: BLE001+ console.print(Text(f"/search failed: {exc}", style="bold red"))+ return 1++ if not matches:+ console.print(Text(f"No matches for '{query}'.", style="dim"))+ return 0++ for hit in matches:+ line = Text()+ line.append(str(hit.session_id), style="bold")+ line.append(" ")+ line.append(hit.title, style="dim")+ line.append(" ")+ line.append(hit.snippet or "", style="dim")+ console.print(line)+ return 0+++def cmd_export(ctx: Any = None, *args: str) -> int: # noqa: ARG001+ """Placeholder until the rich export lands."""+ console = _resolve_console()+ body = Text()+ body.append("/export is not yet wired up to the interactive CLI.\n\n", style="dim")+ body.append("Until then: ", style="dim")+ body.append("the web UI exports md/json from the message footer.", style="bold")+ console.print(Panel(body, title="/export", border_style="dim", padding=(1, 2)))+ return 0+++_DISPATCH = {+ "history": cmd_history,+ "search": cmd_search,+ "export": cmd_export,+}+++def run(ctx: Any = None, command: str = "history", *args: str) -> int:+ """Dispatch ``run("history")`` / ``run("search", ...)`` / ``run("export")``."""+ handler = _DISPATCH.get(command)+ if handler is None:+ console = _resolve_console()+ console.print(Text(f"Unknown session command: /{command}", style="bold red"))+ return 1+ return handler(ctx, *args)+++__all__ = ["run", "cmd_history", "cmd_search", "cmd_export"]diff --git a/agent/cli/commands/show.py b/agent/cli/commands/show.pynew file mode 100644index 000000000..09efefd99--- /dev/null+++ b/agent/cli/commands/show.py@@ -0,0 +1,86 @@+"""``/show``, ``/skill``, ``/pine`` — read-only inspect commands.++All three already exist as fully-featured ``cmd_*`` callables in+``cli._legacy``; this module is a thin shim so the slash router can+dispatch by command name without importing the legacy module top-level+(which is heavy — it pulls in providers, swarm, etc.).+"""++from __future__ import annotations++from typing import Any++from rich.console import Console+from rich.text import Text++from cli.theme import get_console+++def _resolve_console() -> Console:+ """Return the shared CLI console."""+ return get_console()+++def cmd_show(ctx: Any = None, *args: str) -> int: # noqa: ARG001+ """``/show <run_id>`` — replay a prior run via the legacy handler."""+ console = _resolve_console()+ if not args:+ console.print(Text("Usage: /show <run_id>", style="bold red"))+ return 1+ try:+ from cli._legacy import cmd_show as legacy_show++ legacy_show(args[0])+ return 0+ except Exception as exc: # noqa: BLE001+ console.print(Text(f"/show failed: {exc}", style="bold red"))+ return 1+++def cmd_skill(ctx: Any = None, *args: str) -> int: # noqa: ARG001+ """``/skill`` — list bundled + user skills (legacy ``cmd_skills``)."""+ console = _resolve_console()+ try:+ from cli._legacy import cmd_skills++ cmd_skills()+ return 0+ except Exception as exc: # noqa: BLE001+ console.print(Text(f"/skill failed: {exc}", style="bold red"))+ return 1+++def cmd_pine(ctx: Any = None, *args: str) -> int: # noqa: ARG001+ """``/pine <run_id>`` — emit Pine Script for a prior backtest."""+ console = _resolve_console()+ if not args:+ console.print(Text("Usage: /pine <run_id>", style="bold red"))+ return 1+ try:+ from cli._legacy import cmd_pine as legacy_pine++ legacy_pine(args[0])+ return 0+ except Exception as exc: # noqa: BLE001+ console.print(Text(f"/pine failed: {exc}", style="bold red"))+ return 1+++_DISPATCH = {+ "show": cmd_show,+ "skill": cmd_skill,+ "pine": cmd_pine,+}+++def run(ctx: Any = None, command: str = "show", *args: str) -> int:+ """Dispatch ``run("show", run_id)`` / ``run("skill")`` etc."""+ handler = _DISPATCH.get(command)+ if handler is None:+ console = _resolve_console()+ console.print(Text(f"Unknown show command: /{command}", style="bold red"))+ return 1+ return handler(ctx, *args)+++__all__ = ["run", "cmd_show", "cmd_skill", "cmd_pine"]diff --git a/agent/cli/commands/slash_router.py b/agent/cli/commands/slash_router.pynew file mode 100644index 000000000..8eb5515ed--- /dev/null+++ b/agent/cli/commands/slash_router.py@@ -0,0 +1,155 @@+"""Slash command registry + fuzzy matcher.++Source of truth for the 15 user-facing slash commands defined in+``docs/2026-05-19_session02_uiux_design_proposal.md`` §3.4.++Each :class:`Command` is a frozen dataclass — registry entries are+immutable so callers can cache filtered slices without worrying about+mutation. ``match_commands`` powers the typeahead in+:mod:`agent.cli.completer`.+"""++from __future__ import annotations++from dataclasses import dataclass+++@dataclass(frozen=True)+class Command:+ """A single slash command entry.++ Attributes:+ name: The command keyword, without leading ``/``.+ description: One-line muted description shown in the completion menu.+ handler_module: Dotted path to the module exposing ``run(ctx, *args)``.+ """++ name: str+ description: str+ handler_module: str+++# Order here = order shown in bare ``/`` typeahead. Group by frequency so the+# most-used commands surface first (help/model/memory/history are top).+SLASH_COMMANDS: tuple[Command, ...] = (+ Command("help", "Show keyboard shortcuts and command list", "cli.commands.help"),+ Command("model", "Switch LLM provider and model", "cli.commands.chat"),+ Command("memory", "Show / manage persistent memory", "cli.commands.memory"),+ Command("history", "Browse and resume prior sessions", "cli.commands.session"),+ Command("search", "Full-text search across all sessions", "cli.commands.session"),+ Command("swarm", "Multi-agent presets (committee / quant / risk)", "cli.commands.chat"),+ Command("skill", "List / load / unload skills", "cli.commands.show"),+ Command("show", "Show prior run by id", "cli.commands.show"),+ Command("clear", "Clear current conversation", "cli.commands.chat"),+ Command("pine", "Export current strategy as Pine Script", "cli.commands.show"),+ Command("journal", "Analyze trade journal CSV", "cli.commands.chat"),+ Command("shadow", "Train / view shadow account", "cli.commands.chat"),+ Command("export", "Export current session (md / json)", "cli.commands.session"),+ Command("debug", "Toggle debug panel (token usage / latency)", "cli.commands.chat"),+ Command("quit", "Exit (also: q, exit, :q)", "cli.commands.chat"),+)+++# Aliases — same handler, different surface keyword. Keep separate from the+# main registry so typeahead does not duplicate rows.+_ALIASES: dict[str, str] = {+ "q": "quit",+ "exit": "quit",+ ":q": "quit",+ "?": "help",+}+++def _parse_token(input_text: str) -> str:+ """Strip the leading ``/`` and isolate the command token.++ >>> _parse_token("/me arg")+ 'me'+ >>> _parse_token("/")+ ''+ >>> _parse_token("not a slash")+ ''+ """+ text = input_text.lstrip()+ if not text.startswith("/"):+ return ""+ # ``/foo bar`` → ``foo``. Use ``split(None, 1)`` to handle any whitespace.+ parts = text[1:].split(None, 1)+ return parts[0] if parts else ""+++def _fuzzy_score(needle: str, name: str) -> int:+ """Return a heuristic score for ``needle`` matching ``name``.++ Higher = better. ``0`` means no match.++ Scoring order (boundary-friendly, like dexter's slash matcher):+ prefix match → 100 + length bonus+ substring match → 50 + length bonus+ subsequence match (chars in order) → 10 + chars matched+ otherwise → 0+ """+ if not needle:+ return 1 # bare ``/`` shows everything in registry order+ needle_l = needle.lower()+ name_l = name.lower()+ if name_l.startswith(needle_l):+ return 100 + len(needle_l)+ if needle_l in name_l:+ return 50 + len(needle_l)+ # subsequence match: every char of needle appears in order inside name+ j = 0+ for ch in name_l:+ if j < len(needle_l) and ch == needle_l[j]:+ j += 1+ if j == len(needle_l):+ return 10 + j+ return 0+++def match_commands(input_text: str) -> list[Command]:+ """Return commands that fuzzy-match ``input_text``.++ Only matches when the trimmed input starts with ``/``. The leading slash+ and any trailing arguments are stripped before scoring; only the command+ token participates in the match.++ Result is ordered best-match first, ties broken by registry order.++ Args:+ input_text: Raw input line, possibly empty.++ Returns:+ A new list — callers may freely mutate without side effects.+ """+ token = _parse_token(input_text)+ if not input_text.lstrip().startswith("/"):+ return []++ # Resolve aliases up front so ``/q`` shows the ``quit`` row.+ if token in _ALIASES:+ token = _ALIASES[token]++ scored: list[tuple[int, int, Command]] = []+ for idx, cmd in enumerate(SLASH_COMMANDS):+ score = _fuzzy_score(token, cmd.name)+ if score > 0:+ # Negative idx so ties prefer earlier registry position when+ # sorted descending by score.+ scored.append((score, -idx, cmd))+ scored.sort(reverse=True)+ return [cmd for _score, _idx, cmd in scored]+++def find_exact(name: str) -> Command | None:+ """Resolve an exact command name or alias.++ Returns ``None`` if no match — callers handle the "unknown command"+ response themselves so error UX stays consistent.+ """+ key = name.lstrip("/").strip()+ key = _ALIASES.get(key, key)+ for cmd in SLASH_COMMANDS:+ if cmd.name == key:+ return cmd+ return Nonediff --git a/agent/cli/completer.py b/agent/cli/completer.pynew file mode 100644index 000000000..b655842ca--- /dev/null+++ b/agent/cli/completer.py@@ -0,0 +1,115 @@+"""FuzzyCompleter for slash commands.++Returns completions only when the line starts with ``/`` so normal prose+typing is not polluted by suggestions. Each completion advertises the+command description in muted style with the command name in the brand+primary color (sourced from :mod:`agent.cli.theme` when available; falls+back to ``ansibrightyellow`` so the file is importable before Parcel α+ships ``theme.py``).+"""++from __future__ import annotations++from typing import Iterable++from prompt_toolkit.completion import CompleteEvent, Completer, Completion+from prompt_toolkit.document import Document+from prompt_toolkit.formatted_text import FormattedText++from .commands.slash_router import SLASH_COMMANDS, Command, match_commands+++def _primary_style() -> str:+ """Resolve the brand-orange ``style`` string for prompt_toolkit.++ Rich and prompt_toolkit do not share a style grammar, so we read the+ brand hex from :mod:`cli.theme` (the single source of truth) and+ rewrite it for prompt_toolkit's ``fg:#xxxxxx`` syntax. NO_COLOR users+ pick the no-op style so completions remain visible without color.+ """+ try:+ from cli.theme import Theme++ brand = getattr(Theme, "brand_hex", None)+ if isinstance(brand, str) and brand:+ return f"fg:{brand} bold"+ except Exception: # noqa: BLE001 — never block typeahead on theme import+ pass+ # Fallback approximates brand orange in 256-color terminals.+ return "fg:#d97706 bold"+++def _muted_style() -> str:+ """Resolve the muted ``style`` string for prompt_toolkit descriptions."""+ return "fg:#9ca3af"+++class SlashCompleter(Completer):+ """prompt_toolkit completer that fuzzy-matches the slash registry.++ Behaviour mirrors dexter's slash typeahead: bare ``/`` lists everything,+ ``/m`` filters by prefix/substring/subsequence. Completions are emitted+ only when the cursor sits on the first token of the line — once the user+ types ``/help `` (with a trailing space) we get out of the way so they+ can fill in arguments without the menu re-popping.+ """++ def __init__(self, commands: Iterable[Command] = SLASH_COMMANDS) -> None:+ # Snapshot the registry; commands is a tuple of frozen dataclasses+ # so the snapshot itself is effectively immutable.+ self._commands = tuple(commands)++ # ----------------------------------------------------------------- API+ def get_completions(+ self,+ document: Document,+ complete_event: CompleteEvent,+ ) -> Iterable[Completion]:+ text = document.text_before_cursor+ stripped = text.lstrip()++ # Bail unless the line starts with ``/`` AND we are still typing the+ # command token (no space yet). This means ``/help <enter args>``+ # stops triggering completions once the user moves past the keyword.+ if not stripped.startswith("/"):+ return+ # Find the slash position (the leading whitespace is irrelevant once+ # we have confirmed it leads with ``/``).+ slash_idx = text.index("/")+ token_zone = text[slash_idx + 1 :]+ if " " in token_zone or "\t" in token_zone:+ return++ matches = match_commands(stripped)+ if not matches:+ return++ # Compute the replacement window so the chosen completion overwrites+ # whatever the user typed after ``/``.+ start_position = -len(token_zone)++ # Right-pad each command name so the description column lines up.+ name_width = max((len(c.name) for c in matches), default=0) + 2++ primary = _primary_style()+ muted = _muted_style()++ for cmd in matches:+ padded_name = cmd.name.ljust(name_width)+ display: FormattedText = FormattedText(+ [+ (primary, f"/{padded_name}"),+ (muted, cmd.description),+ ]+ )+ # ``text`` is the value inserted on accept (no leading slash —+ # the slash is already in the buffer at ``slash_idx``).+ yield Completion(+ text=cmd.name,+ start_position=start_position,+ display=display,+ display_meta=cmd.description,+ )+++__all__ = ["SlashCompleter"]diff --git a/agent/cli/components/__init__.py b/agent/cli/components/__init__.pynew file mode 100644index 000000000..a52780ae0--- /dev/null+++ b/agent/cli/components/__init__.py@@ -0,0 +1,18 @@+"""Reusable CLI render components.++Each component returns a Rich renderable (Text / Panel / Table) so callers+can ``console.print`` or stuff it into a Live group.+"""++from .chat_log import render_history+from .hint_bar import render_hint_bar+from .tool_event import render_tool_event, render_tool_events+from .working_indicator import ThinkingSpinner++__all__ = [+ "ThinkingSpinner",+ "render_history",+ "render_hint_bar",+ "render_tool_event",+ "render_tool_events",+]diff --git a/agent/cli/components/chat_log.py b/agent/cli/components/chat_log.pynew file mode 100644index 000000000..49718209e--- /dev/null+++ b/agent/cli/components/chat_log.py@@ -0,0 +1,77 @@+"""Minimal chat-log renderer — stub for the demo.++Iterates a list of turn dicts and prints user / assistant lines with the+expected meta header. Defer the rich features (collapsible tool+timeline, markdown rendering, action footer) to post-demo work — they+belong in the Web bubble (Parcel C / D), not in the CLI replay.++Turn shape:+ {+ "role": "user" | "assistant",+ "content": str,+ "timestamp": str | None, # ISO or formatted clock+ "meta": str | None, # "Vibe · 4.1s · 1.2k tokens · $0.003"+ }+"""++from __future__ import annotations++from typing import Iterable, Mapping, Optional++from rich.console import Console+from rich.text import Text+++def _resolve_console(console: Optional[Console]) -> Console:+ """Return ``console`` if given, else the shared CLI console."""+ if console is not None:+ return console+ from cli.theme import get_console++ return get_console()+++def _render_turn(turn: Mapping[str, object]) -> Text:+ """Compose the meta header line for one turn."""+ role = str(turn.get("role", "user"))+ timestamp = turn.get("timestamp")+ meta = turn.get("meta")+ header = Text()+ if role == "assistant":+ # "Vibe" is the brand wordmark for assistant turns — primary color+ header.append("Vibe", style="bold #d97706")+ else:+ header.append("you", style="bold")+ if timestamp:+ header.append(f" {timestamp}", style="dim")+ if meta:+ header.append(f" · {meta}", style="dim")+ return header+++def render_history(+ turns: Iterable[Mapping[str, object]],+ *,+ console: Optional[Console] = None,+) -> None:+ """Print past turns to ``console``.++ Args:+ turns: Iterable of turn dicts (see module docstring for shape).+ console: Override; defaults to the shared CLI console.++ No return value — this is a side-effecting renderer.+ """+ cons = _resolve_console(console)+ for turn in turns:+ cons.print(_render_turn(turn))+ content = str(turn.get("content", ""))+ if content:+ # Body intentionally renders as plain text — markdown / katex+ # / syntax highlighting live in the Web bubble. The CLI keeps+ # the body monospaced for diff-friendly replay.+ cons.print(content)+ cons.print() # blank line between turns+++__all__ = ["render_history"]diff --git a/agent/cli/components/hint_bar.py b/agent/cli/components/hint_bar.pynew file mode 100644index 000000000..bba3987bf--- /dev/null+++ b/agent/cli/components/hint_bar.py@@ -0,0 +1,67 @@+"""Bottom hint bar — left + right aligned.++Renders a single-line hint where the right-aligned segment hugs the+terminal edge regardless of left-segment width. Mirrors dexter's+``hint-bar.ts``.++Used to surface keyboard guidance ("Tab to complete · /help for+commands") and ephemeral state ("input cleared", "cancelled").+"""++from __future__ import annotations++import shutil++from rich.text import Text+++def _terminal_width(default: int = 80) -> int:+ """Best-effort terminal width detection (falls back gracefully)."""+ try:+ size = shutil.get_terminal_size((default, 20))+ return max(20, size.columns)+ except (OSError, ValueError):+ return default+++def render_hint_bar(left: str, right: str = "", *, width: int | None = None) -> Text:+ """Return a Rich :class:`Text` row with ``left`` and right-aligned ``right``.++ The bar always fits the terminal width:+ * If ``left + right`` fits, pad with spaces between them+ * Otherwise truncate the left segment with an ellipsis so the+ right hint remains visible (right-side hint usually carries+ the *current* Ctrl+C semantics — losing it is worse than+ losing context)++ Args:+ left: Left segment (e.g. ``"↑/↓ navigate · Tab/⏎ select"``).+ right: Right segment (e.g. ``"Esc to cancel"``); may be empty.+ width: Override terminal width. Defaults to autodetect.+ """+ cols = width if width is not None else _terminal_width()+ if right == "":+ # Only a left hint — clip and pad to width, dim style throughout.+ text = Text(left[:cols], style="dim")+ return text++ # Reserve at least one space between left and right segments.+ available_for_left = cols - len(right) - 1+ if available_for_left < 1:+ # Right segment alone is wider than the terminal — show right only.+ return Text(right[: cols].rjust(cols), style="dim")++ if len(left) > available_for_left:+ left = left[: max(1, available_for_left - 1)].rstrip() + "…"++ padding = cols - len(left) - len(right)+ if padding < 1:+ padding = 1+ bar = Text()+ bar.append(left, style="dim")+ bar.append(" " * padding)+ bar.append(right, style="dim")+ return bar+++__all__ = ["render_hint_bar"]diff --git a/agent/cli/components/tool_event.py b/agent/cli/components/tool_event.pynew file mode 100644index 000000000..da2d9d70d--- /dev/null+++ b/agent/cli/components/tool_event.py@@ -0,0 +1,218 @@+"""Single tool invocation render.++Layout (matches design_proposal §3.5):++ ⏺ Get Financials ("AAPL", quarterly, last 8 quarters) 1.4s · 8 quarters++* ``⏺`` (U+23FA media-record) marker, color-coded by status:+ running → ``--warning`` amber (pulse via Rich style ``blink`` when+ the terminal advertises it, otherwise solid amber)+ ok → ``--success`` green, solid+ error → ``--danger`` red, solid+* Tool name pretty-printed (``get_financials`` → ``Get Financials``)+* Args summary prefers ``query`` then ``prompt``, else the first 2+ ``key=value`` pairs each truncated to 40 chars+* Duration formatted via :func:`agent.cli.utils.format.format_duration`+ when Parcel α has shipped it; otherwise a local fallback is used+"""++from __future__ import annotations++from typing import Any, Iterable, Literal, Mapping++from rich.text import Text+++Status = Literal["running", "ok", "error"]+++# Status → (Rich style, marker glyph). The glyph stays the same; the style+# encodes color + decoration (bold/blink). dexter only changes brightness+# of the marker rather than swapping glyphs.+_STATUS_STYLE: dict[Status, str] = {+ # ``blink`` is gracefully ignored by Rich when the terminal does not+ # advertise the capability, so we always include it.+ "running": "bold blink #f59e0b", # amber, F-002 warning+ "ok": "bold #16a34a", # green, F-002 success+ "error": "bold #dc2626", # red, F-002 danger+}++_ARG_VALUE_MAX = 40+++# ---------------------------------------------------------------- helpers ----+++def _pretty_tool_name(name: str) -> str:+ """Convert ``get_financials`` to ``Get Financials``.++ Strips a leading ``get_`` prefix when present (dexter convention).+ Underscores and hyphens become spaces; each whitespace-separated+ token is title-cased. Acronyms preserved when fully upper.+ """+ cleaned = name.strip()+ if cleaned.lower().startswith("get_"):+ cleaned = cleaned[4:]+ tokens = cleaned.replace("-", " ").replace("_", " ").split()+ out: list[str] = []+ for tok in tokens:+ if tok.isupper() and len(tok) <= 4:+ out.append(tok)+ else:+ out.append(tok[:1].upper() + tok[1:].lower())+ return " ".join(out) if out else cleaned+++def _truncate(value: str, limit: int = _ARG_VALUE_MAX) -> str:+ if len(value) <= limit:+ return value+ return value[: limit - 1].rstrip() + "…"+++def _summarize_args(args: Mapping[str, Any] | None) -> str:+ """Produce a one-line args summary.++ Rules:+ * ``args is None`` or empty → empty string+ * ``query`` field present → ``"<value>"`` (quoted)+ * ``prompt`` field present → ``"<value>"`` (quoted)+ * otherwise → first 2 ``key=value`` pairs, value truncated to 40 chars++ Returns the bare summary string; callers wrap it in parens.+ """+ if not args:+ return ""++ # Prefer the well-known semantic keys+ for primary_key in ("query", "prompt"):+ if primary_key in args:+ return f'"{_truncate(str(args[primary_key]))}"'++ pairs: list[str] = []+ for key, value in list(args.items())[:2]:+ rendered_value = _truncate(_render_value(value))+ pairs.append(f"{key}={rendered_value}")+ return ", ".join(pairs)+++def _render_value(value: Any) -> str:+ """Compact ``repr``-ish formatting suitable for inline arg display."""+ if isinstance(value, str):+ return value+ if isinstance(value, bool):+ return "true" if value else "false"+ if value is None:+ return "null"+ if isinstance(value, (list, tuple)):+ # Show length to avoid blowing up the line on huge arrays.+ if len(value) <= 3:+ return "[" + ", ".join(_render_value(v) for v in value) + "]"+ return f"[{len(value)} items]"+ if isinstance(value, Mapping):+ return f"{{{len(value)} keys}}"+ return str(value)+++def _format_duration_local(ms: float) -> str:+ """Local fallback when ``agent.cli.utils.format.format_duration`` is absent.++ Parcel α owns the canonical implementation; until it lands we keep a+ minimal version here so the demo build is not blocked on cross-parcel+ ordering. Numbers match the contract in design_proposal §3.5:++ < 1000ms → "740ms"+ < 60s → "1.4s"+ ≥ 60s → "1m12s"+ """+ if ms < 1000:+ return f"{int(round(ms))}ms"+ seconds = ms / 1000+ if seconds < 60:+ return f"{seconds:.1f}s"+ minutes = int(seconds // 60)+ rem = int(seconds - minutes * 60)+ return f"{minutes}m{rem:02d}s"+++def _format_duration(ms: float) -> str:+ """Delegate to the shared formatter; fall back locally on import error."""+ try:+ from cli.utils.format import format_duration++ return format_duration(ms)+ except Exception: # noqa: BLE001 — never block render on helper issues+ return _format_duration_local(ms)+++# ---------------------------------------------------------------- public ----+++def render_tool_event(+ name: str,+ args: Mapping[str, Any] | None = None,+ status: Status = "running",+ duration_ms: float | None = None,+ *,+ result_summary: str | None = None,+) -> Text:+ """Return a Rich :class:`Text` row describing a single tool call.++ Args:+ name: Raw tool name (``get_financials``); pretty-printed in output.+ args: Argument mapping; summarised inline.+ status: ``"running"`` | ``"ok"`` | ``"error"``.+ duration_ms: When the call finished, total wall time in milliseconds.+ result_summary: Optional one-line summary appended after the+ duration (e.g. ``"8 quarters"``).++ Returns:+ A Rich ``Text`` object — caller decides whether to ``console.print``+ it, stuff it into a ``Group``, or stream it as a transient row.+ """+ if status not in _STATUS_STYLE:+ # Be lenient — unknown statuses degrade to "running" instead of+ # raising; CLI rendering should never crash the agent loop.+ status = "running"++ marker = Text("⏺ ", style=_STATUS_STYLE[status])+ line = Text()+ line.append(marker)+ line.append(_pretty_tool_name(name), style="bold")++ summary = _summarize_args(args)+ if summary:+ line.append(f" ({summary})", style="dim")++ suffix_parts: list[str] = []+ if duration_ms is not None:+ suffix_parts.append(_format_duration(duration_ms))+ if result_summary:+ suffix_parts.append(result_summary)+ if suffix_parts:+ line.append(" " + " · ".join(suffix_parts), style="dim")++ return line+++def render_tool_events(events: Iterable[Mapping[str, Any]]) -> list[Text]:+ """Convenience: render a list of event dicts.++ Each event dict needs ``name`` plus any of ``args`` / ``status`` /+ ``duration_ms`` / ``result_summary``. Useful for replaying a stored+ run via :mod:`agent.cli.commands.show`.+ """+ rendered: list[Text] = []+ for ev in events:+ rendered.append(+ render_tool_event(+ name=str(ev.get("name", "tool")),+ args=ev.get("args"),+ status=ev.get("status", "ok"),+ duration_ms=ev.get("duration_ms"),+ result_summary=ev.get("result_summary"),+ )+ )+ return rendered+++__all__ = ["render_tool_event", "render_tool_events"]diff --git a/agent/cli/components/working_indicator.py b/agent/cli/components/working_indicator.pynew file mode 100644index 000000000..bc614e5e6--- /dev/null+++ b/agent/cli/components/working_indicator.py@@ -0,0 +1,144 @@+"""Thinking spinner — picks a random verb on entry, hides on exit.++Wraps :class:`rich.live.Live` with ``transient=True`` so the spinner+erases itself once the context exits — leaving the answer print+uncluttered (the bug nanobot called out in their StreamRenderer+docstring: transient=True avoids the "ghost spinner" duplication).++If :mod:`agent.cli.utils.thinking_verbs` has not landed yet (Parcel α+ships it) we fall back to ``"Pondering…"`` so the demo build still+works.+"""++from __future__ import annotations++import random+from types import TracebackType+from typing import Optional++from rich.console import Console+from rich.live import Live+from rich.spinner import Spinner+from rich.text import Text+++_FALLBACK_VERBS: tuple[str, ...] = (+ "Pondering…",+ "Analyzing…",+ "Reasoning…",+ "Thinking…",+ "Investigating…",+)+++def _pick_verb() -> str:+ """Pick a thinking verb via the shared helper, with a local fallback."""+ try:+ from cli.utils.thinking_verbs import pick_thinking_verb++ verb = pick_thinking_verb()+ if isinstance(verb, str) and verb:+ return verb+ except Exception: # noqa: BLE001 — never block the spinner on helper issues+ pass+ return random.choice(_FALLBACK_VERBS)+++def _resolve_console() -> Console:+ """Return the shared CLI console."""+ from cli.theme import get_console++ return get_console()+++class ThinkingSpinner:+ """Context manager that shows a Rich spinner + thinking verb.++ Usage:+ with ThinkingSpinner() as spinner:+ spinner.update_verb("Backtesting…") # optional mid-run swap+ ... do agent work ...++ The spinner is ``transient=True`` so it disappears when the block+ exits. Use :meth:`pause` to temporarily hide the spinner while+ printing auxiliary lines (e.g. a tool event row) — borrowed from+ nanobot's StreamRenderer pattern.+ """++ def __init__(+ self,+ verb: Optional[str] = None,+ *,+ console: Optional[Console] = None,+ spinner_name: str = "dots",+ ) -> None:+ self._verb = verb or _pick_verb()+ self._console = console or _resolve_console()+ self._spinner_name = spinner_name+ self._live: Optional[Live] = None++ # --------------------------------------------------------- lifecycle ----+ def __enter__(self) -> "ThinkingSpinner":+ self._live = Live(+ self._renderable(),+ console=self._console,+ transient=True,+ refresh_per_second=12,+ )+ self._live.__enter__()+ return self++ def __exit__(+ self,+ exc_type: Optional[type[BaseException]],+ exc: Optional[BaseException],+ tb: Optional[TracebackType],+ ) -> None:+ live, self._live = self._live, None+ if live is not None:+ live.__exit__(exc_type, exc, tb)++ # ------------------------------------------------------------- helpers --+ def _renderable(self) -> Spinner:+ # ``Spinner.text`` accepts Rich Text for styling — keep the verb in+ # the dim style so the live region is unobtrusive.+ return Spinner(self._spinner_name, text=Text(self._verb, style="dim"))++ def update_verb(self, verb: str) -> None:+ """Swap the verb mid-run (e.g. ``"Backtesting…"`` once tools fire)."""+ self._verb = verb+ if self._live is not None:+ self._live.update(self._renderable())++ def pause(self) -> "_SpinnerPause":+ """Yield a context manager that hides the spinner inside its block.++ Useful when callers need to ``console.print`` a tool-event row+ without the spinner frame racing with the print to stdout.+ """+ return _SpinnerPause(self)+++class _SpinnerPause:+ """Inner context manager returned by :meth:`ThinkingSpinner.pause`."""++ def __init__(self, parent: ThinkingSpinner) -> None:+ self._parent = parent+ self._saved_live: Optional[Live] = None++ def __enter__(self) -> None:+ # Stash the live so __exit__ on the outer spinner does nothing+ # while we are paused; restart it on exit.+ if self._parent._live is not None:+ self._parent._live.__exit__(None, None, None)+ self._saved_live = self._parent._live+ self._parent._live = None++ def __exit__(self, exc_type, exc, tb) -> None: # noqa: ANN001+ if self._saved_live is not None:+ self._parent._live = self._saved_live+ self._parent._live.__enter__()+ self._saved_live = None+++__all__ = ["ThinkingSpinner"]diff --git a/agent/cli/input.py b/agent/cli/input.pynew file mode 100644index 000000000..cb0389239--- /dev/null+++ b/agent/cli/input.py@@ -0,0 +1,337 @@+"""prompt_toolkit input editor + ``SafeFileHistory``.++Wraps a :class:`PromptSession` with:+ * The slash :class:`~cli.completer.SlashCompleter`+ * Multi-line editing — Enter inserts a newline only when the buffer is+ mid-bracket; Alt+Enter / Esc-Enter inserts a newline unconditionally;+ a plain Enter on a balanced buffer submits.+ * Ctrl+C with three-state semantics (clear buffer → exit hint → exit)+ * A surrogate-safe :class:`FileHistory` subclass for Windows users+ * UTF-8 stdout reconfigure on Windows so the brand glyph ``⏺`` and the+ Rich box-drawing characters print without ``UnicodeEncodeError``++Cancel-during-generation lives outside the input loop — that is owned by+the agent runner in :mod:`cli.main`. Here we only handle the *input+editing* and *idle* states.+"""++from __future__ import annotations++import sys+import time+from pathlib import Path+from typing import Optional++from prompt_toolkit import PromptSession+from prompt_toolkit.formatted_text import FormattedText+from prompt_toolkit.history import FileHistory+from prompt_toolkit.key_binding import KeyBindings+++# Sentinel raised by the Ctrl+C path so the caller can distinguish+# "user pressed Ctrl+C on an empty line" from real EOF. We reuse+# :class:`EOFError` so prompt_toolkit's existing plumbing keeps working;+# the caller decides between "show hint" and "exit" via timing.+_EXIT_HINT_GAP_SEC = 2.0+++# ---------------------------------------------------------------- history ----+++class SafeFileHistory(FileHistory):+ """:class:`FileHistory` that strips invalid surrogate code points.++ Background:+ Windows terminals occasionally inject lone surrogate halves into+ pasted Unicode (emoji, mixed-script CJK). prompt_toolkit's default+ ``store_string`` writes the line straight to disk using the+ system encoding, which raises ``UnicodeEncodeError`` and corrupts+ the history file. This subclass round-trips the string through+ ``utf-16-le`` with ``surrogatepass`` and then back to a sanitised+ string before delegating to the parent implementation.++ The cleanup is safe to run on every line — sanitised input that+ contains only valid code points round-trips unchanged.+ """++ def store_string(self, string: str) -> None: # type: ignore[override]+ super().store_string(_strip_surrogates(string))+++def _strip_surrogates(text: str) -> str:+ """Drop unpaired surrogate code points from ``text``."""+ try:+ round_tripped = text.encode("utf-16-le", "surrogatepass").decode(+ "utf-16-le", "replace"+ )+ except UnicodeError:+ return "".join(ch for ch in text if not 0xD800 <= ord(ch) <= 0xDFFF)+ cleaned = round_tripped.encode("utf-8", "ignore").decode("utf-8", "ignore")+ return cleaned.replace("�", "")+++# ---------------------------------------------------------------- session ----+++def _force_utf8_stdout() -> None:+ """Reconfigure stdout to UTF-8 on Windows so brand glyphs render."""+ if sys.platform != "win32":+ return+ for stream in (sys.stdout, sys.stderr):+ reconfigure = getattr(stream, "reconfigure", None)+ if callable(reconfigure):+ try:+ reconfigure(encoding="utf-8")+ except (OSError, ValueError):+ # Best-effort — a redirected pipe may refuse encoding swaps.+ pass+++def _has_unbalanced_brackets(text: str) -> bool:+ """Return True if ``text`` contains unbalanced ``()``/``[]``/``{}`` pairs.++ Used to decide whether a plain Enter should submit or insert a+ newline. Strings inside ``"..."`` / ``'...'`` are skipped so a user+ typing ``"hello (world)"`` does not get stuck in multi-line mode.+ """+ stack: list[str] = []+ pairs = {")": "(", "]": "[", "}": "{"}+ openers = set(pairs.values())+ in_str: Optional[str] = None+ escape = False+ for ch in text:+ if escape:+ escape = False+ continue+ if ch == "\\":+ escape = True+ continue+ if in_str is not None:+ if ch == in_str:+ in_str = None+ continue+ if ch in ("'", '"'):+ in_str = ch+ continue+ if ch in openers:+ stack.append(ch)+ elif ch in pairs:+ if not stack or stack[-1] != pairs[ch]:+ return True+ stack.pop()+ return bool(stack) or in_str is not None+++class _CtrlCState:+ """Track Ctrl+C presses so the outer loop can implement two-press exit.++ Attributes:+ previous_press_ts: Monotonic timestamp of the press *before* the+ most recent one. ``0.0`` means "no prior press".+ last_window_hit: Set by :meth:`record_press_and_check_window` —+ ``True`` iff the press that just landed was inside the+ configured window relative to ``previous_press_ts``. Cached+ so :func:`ctrl_c_within_window` does not re-read the clock+ and decide independently of the keybinding.++ The two-press semantics live here (not in the outer loop) because+ the keybinding fires *before* the EOFError propagates, and we want+ the outer loop's view of "are we inside the window?" to reflect the+ decision made at the exact press moment — not whatever ``time.monotonic()``+ reads a few microseconds later.+ """++ __slots__ = ("previous_press_ts", "last_window_hit")++ def __init__(self) -> None:+ self.previous_press_ts: float = 0.0+ self.last_window_hit: bool = False++ def record_press_and_check_window(self, window_sec: float = _EXIT_HINT_GAP_SEC) -> bool:+ """Record the current press, return True iff inside the window.++ Args:+ window_sec: Two-press window in seconds.++ Returns:+ ``False`` for the very first press (``previous_press_ts == 0``).+ ``True`` if the gap between the prior press and this one is+ below ``window_sec``. Otherwise ``False`` (treated as a fresh+ first press for the next round).+ """+ now = time.monotonic()+ prev = self.previous_press_ts+ self.previous_press_ts = now+ if prev == 0.0:+ self.last_window_hit = False+ return False+ hit = (now - prev) < window_sec+ self.last_window_hit = hit+ return hit+++def _build_keybindings(state: _CtrlCState) -> KeyBindings:+ """Wire Ctrl+C + multi-line submit semantics.++ State machine (idle / typing):++ Ctrl+C with text → clear the buffer and stay at the prompt+ Ctrl+C empty (first) → exit with ``EOFError``; caller prints hint+ and records the press timestamp.+ Ctrl+C empty (twice) → caller sees the timestamp inside 2 s and+ actually exits the loop.++ Enter on balanced buffer → submit+ Enter on unbalanced buffer → insert newline+ Alt-Enter / Esc-Enter → insert newline unconditionally+ """+ kb = KeyBindings()++ @kb.add("c-c")+ def _(event) -> None: # noqa: ANN001 — prompt_toolkit event+ buf = event.app.current_buffer+ if buf.text:+ buf.reset()+ event.app.invalidate()+ return+ # Empty buffer → record the press (this updates the state so the+ # outer loop's two-press check has the right prior timestamp) and+ # propagate EOF so the outer loop can decide whether to print the+ # exit hint or actually exit.+ state.record_press_and_check_window(_EXIT_HINT_GAP_SEC)+ event.app.exit(exception=EOFError())++ @kb.add("enter")+ def _(event) -> None: # noqa: ANN001+ buf = event.app.current_buffer+ text = buf.text+ if _has_unbalanced_brackets(text):+ buf.insert_text("\n")+ return+ buf.validate_and_handle()++ # Alt+Enter / Esc-Enter — unconditional newline.+ @kb.add("escape", "enter")+ def _(event) -> None: # noqa: ANN001+ event.app.current_buffer.insert_text("\n")++ return kb+++def _default_history_path() -> Path:+ """Where ``~/.vibe-trading/history`` lives by default."""+ home = Path.home() / ".vibe-trading"+ return home / "history"+++def make_session(history_path: Optional[Path] = None) -> PromptSession:+ """Construct a configured :class:`PromptSession`.++ Args:+ history_path: Override for the persistent history file. ``None``+ uses ``~/.vibe-trading/history``.++ Returns:+ A ready-to-use ``PromptSession`` wired to the slash completer,+ Ctrl+C bindings, multi-line editing, and a surrogate-safe+ history file. The session exposes ``vibe_ctrl_c_state`` on the+ returned object so callers can implement the two-press exit+ confirmation.+ """+ _force_utf8_stdout()++ path = history_path or _default_history_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ # Touch the file so FileHistory's first read does not fail on a fresh+ # install.+ if not path.exists():+ path.touch(mode=0o600)++ # Lazy import so unit tests can import this module without instantiating+ # the slash registry side-effects.+ from cli.completer import SlashCompleter++ ctrl_c_state = _CtrlCState()+ session = PromptSession(+ history=SafeFileHistory(str(path)),+ completer=SlashCompleter(),+ complete_while_typing=True,+ key_bindings=_build_keybindings(ctrl_c_state),+ enable_history_search=True,+ mouse_support=False,+ multiline=True,+ )+ # Expose the state so the outer loop can implement two-press exit.+ setattr(session, "vibe_ctrl_c_state", ctrl_c_state)+ return session+++# ---------------------------------------------------------------- helpers ----+++def get_user_input(+ prompt_message: str = "> ",+ *,+ session: Optional[PromptSession] = None,+) -> str:+ """Prompt the user with the configured session and return the input.++ Convenience for one-shot callers. Reuses ``session`` when supplied so+ the persistent history and completer carry across calls — otherwise+ a fresh session is built (and torn down).++ Raises:+ EOFError: When the user hits Ctrl+D, or Ctrl+C on an empty line.+ """+ sess = session or make_session()+ formatted = FormattedText([("class:prompt", prompt_message)])+ return sess.prompt(formatted)+++def ctrl_c_within_window(session: PromptSession, window_sec: float = _EXIT_HINT_GAP_SEC) -> bool:+ """Return True if the most recent Ctrl+C press was a "second press".++ A "second press" means the user pressed Ctrl+C twice within+ ``window_sec`` on an empty buffer — that's the signal to actually+ exit. The decision is made at *press time* by+ :meth:`_CtrlCState.record_press_and_check_window` and cached on the+ state object; the outer loop reads the cached flag here.++ Falls back to a timestamp comparison against ``previous_press_ts``+ for two cases:++ * ``SimpleNamespace`` test doubles that set ``last_press_ts`` directly+ (legacy test fixtures predate the two-timestamp design).+ * ``vibe_ctrl_c_state`` being absent entirely (defensive — returns+ ``False`` so the caller treats it as "no exit").++ Args:+ session: The active prompt_toolkit session (or a duck-typed+ stand-in exposing ``vibe_ctrl_c_state``).+ window_sec: Window length in seconds. Only used by the fallback+ paths described above; the primary path trusts the cached+ ``last_window_hit`` already computed against the configured+ window.++ Returns:+ ``True`` iff the loop should now exit.+ """+ state = getattr(session, "vibe_ctrl_c_state", None)+ if state is None:+ return False+ # Primary path — the keybinding cached the press-time decision.+ if hasattr(state, "last_window_hit"):+ return bool(state.last_window_hit)+ # Legacy fallback for test doubles that only set ``last_press_ts``.+ last_ts = getattr(state, "last_press_ts", 0.0)+ if last_ts <= 0.0:+ return False+ return (time.monotonic() - last_ts) < window_sec+++__all__ = [+ "SafeFileHistory",+ "make_session",+ "get_user_input",+ "ctrl_c_within_window",+]diff --git a/agent/cli/intro.py b/agent/cli/intro.pynew file mode 100644index 000000000..0354f5532--- /dev/null+++ b/agent/cli/intro.py@@ -0,0 +1,155 @@+"""Startup banner for the interactive CLI.++The layout follows §3.3 of the 2026-05-19 UI/UX design proposal:++ Vibe-Trading v0.2.0+ ─────────────────────────────────────────────+ Natural-language finance research that+ thinks before it answers.++ Model: deepseek/deepseek-v3.2+ Skills: 72 loaded+ Tools: 27 registered+ Sessions: 3 prior (use /history to browse)++ Try one of these:+ > Compare AAPL and MSFT fundamentals+ > Backtest a momentum strategy on BTC, 2020-now+ > What's the implied vol on TSLA Jan 2026 calls?++ /help for commands · Ctrl+C to clear input · Ctrl+D to exit+ ─────────────────────────────────────────────++The wordmark "Vibe-Trading" is rendered in the brand orange (single accent),+everything else uses neutral / dim styles per the "Orange discipline rule".+No emoji, no ASCII-art logo — wordmark-only (proposal §1.3).+"""++from __future__ import annotations++from typing import Final, Sequence++from rich.console import Console+from rich.text import Text++from cli._version import __version__ as _VERSION+from cli.theme import Theme++_TAGLINE: Final[str] = (+ "Natural-language finance research that\nthinks before it answers."+)++_DEFAULT_EXAMPLES: Final[tuple[str, ...]] = (+ "Compare AAPL and MSFT fundamentals",+ "Backtest a momentum strategy on BTC, 2020-now",+ "What's the implied vol on TSLA Jan 2026 calls?",+)+++def _rule(console: Console, *, width: int = 60) -> None:+ """Print a single-character horizontal rule using muted style."""++ char = "─"+ target = min(width, max(20, console.size.width - 2))+ console.print(Text(char * target, style=Theme.muted))+++def print_banner(+ console: Console,+ *,+ model: str,+ skills: int,+ tools: int,+ sessions: int,+ examples: Sequence[str] | None = None,+ version: str = _VERSION,+) -> None:+ """Render the startup banner.++ Args:+ console: Shared Rich console (use :func:`cli.theme.get_console`).+ model: Active LLM model id, e.g. ``"deepseek/deepseek-v3.2"``.+ skills: Number of skills currently loaded.+ tools: Number of tools registered in the agent registry.+ sessions: Number of prior sessions on disk. ``0`` suppresses the+ "/history to browse" hint.+ examples: Three prompt examples to show under "Try one of these:".+ Defaults to a curated triplet covering equities / crypto /+ options.+ version: Override version string (defaults to the package+ metadata version via :mod:`cli._version`).++ Notes:+ - Wordmark is the *only* primary-orange element (design proposal §1.3+ "Orange discipline rule").+ - Padding on the left is two spaces, matching dexter's intro.ts.+ - Examples are prefixed with ``>`` (not ``•``) so they read as REPL+ input prompts, hinting that the user can paste them verbatim.+ """++ pad = " "+ console.print() # leading blank line++ # ── Wordmark ────────────────────────────────────────────────────────+ wordmark = Text()+ wordmark.append(pad)+ wordmark.append("Vibe-Trading", style=Theme.primary)+ wordmark.append(f" v{version}", style=Theme.muted)+ console.print(wordmark)++ # ── Rule ────────────────────────────────────────────────────────────+ indent = Text(pad)+ rule = Text("─" * 50, style=Theme.muted)+ console.print(indent + rule)++ # ── Tagline ─────────────────────────────────────────────────────────+ for line in _TAGLINE.splitlines():+ console.print(Text(pad) + Text(line, style=Theme.muted))+ console.print()++ # ── Stats grid ──────────────────────────────────────────────────────+ rows: list[tuple[str, str]] = [+ ("Model", model),+ ("Skills", f"{skills} loaded"),+ ("Tools", f"{tools} registered"),+ ]+ if sessions > 0:+ rows.append(("Sessions", f"{sessions} prior (use /history to browse)"))+ else:+ rows.append(("Sessions", "none yet"))++ label_width = max(len(label) for label, _ in rows) + 2+ for label, value in rows:+ line = Text(pad)+ line.append(f"{label}:".ljust(label_width), style=Theme.label)+ line.append(value, style=Theme.muted)+ console.print(line)++ console.print()++ # ── Examples ────────────────────────────────────────────────────────+ console.print(Text(pad) + Text("Try one of these:", style=Theme.label))+ for ex in (examples or _DEFAULT_EXAMPLES):+ line = Text(pad)+ line.append("> ", style=Theme.primary_dim)+ line.append(ex, style=Theme.muted)+ console.print(line)++ console.print()++ # ── Footer hint ─────────────────────────────────────────────────────+ footer = Text(pad)+ footer.append("/help", style=Theme.info)+ footer.append(" for commands · ", style=Theme.muted)+ footer.append("Ctrl+C", style=Theme.info)+ footer.append(" to clear input · ", style=Theme.muted)+ footer.append("Ctrl+D", style=Theme.info)+ footer.append(" to exit", style=Theme.muted)+ console.print(footer)++ # ── Bottom rule ─────────────────────────────────────────────────────+ console.print(indent + Text("─" * 60, style=Theme.muted))+ console.print()+++__all__ = ["print_banner"]diff --git a/agent/cli/main.py b/agent/cli/main.pynew file mode 100644index 000000000..11b91e640--- /dev/null+++ b/agent/cli/main.py@@ -0,0 +1,863 @@+"""Interactive CLI front door for Vibe-Trading.++Responsibilities:++1. Detect whether ``~/.vibe-trading/.env`` exists; if missing, run the+ onboarding wizard (:mod:`cli.onboard`) before doing anything else.+2. Render the startup banner (:mod:`cli.intro`) on interactive entry.+3. For interactive entry (no subcommand, or ``chat``) drive the REPL+ built on :mod:`cli.input`, :mod:`cli.completer`,+ :mod:`cli.commands.slash_router`, :mod:`cli.components.working_indicator`,+ :mod:`cli.components.tool_event`, and :mod:`cli.components.hint_bar`.+4. For every other subcommand delegate to ``cli._legacy.main`` so the+ long tail of ``serve``, ``run``, ``mcp``, ``sessions``, ``swarm`` etc.+ keeps working without regression.++The console script entry in ``pyproject.toml`` (``vibe-trading = "cli:main"``)+hits :func:`main`.+"""++from __future__ import annotations++import importlib+import os+import sys+import threading+import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Dict, List, Optional, Sequence++from cli.intro import print_banner+from cli.onboard import run_onboarding+from cli.theme import Theme, get_console++_ENV_PATH = Path.home() / ".vibe-trading" / ".env"+# Best-effort fallbacks used only when the probe genuinely fails (missing+# dependency, broken install). The numbers track the actual bundled counts+# so a probe failure still shows a plausible banner rather than "0 loaded".+_FALLBACK_SKILLS = 77+_FALLBACK_TOOLS = 31+_HISTORY_RETAINED_TURNS = 6 # how many prior turns to feed the agent loop++# Cached banner-stats and session-store so ``/clear`` and repeat slash handlers+# don't redo the heavy build_registry() / SessionStore construction.+_BANNER_STATS_CACHE: Dict[str, Any] = {}+_SESSION_STORE_CACHE: Any = None+++# ---------------------------------------------------------------------------+# Stat probes (best-effort, never blocking)+# ---------------------------------------------------------------------------+++def _probe_model_name() -> str:+ """Return the configured LLM model id, or a placeholder."""+ name = os.environ.get("LANGCHAIN_MODEL_NAME") or os.environ.get("OPENAI_MODEL")+ if name:+ return name+ try:+ text = _ENV_PATH.read_text(encoding="utf-8")+ for line in text.splitlines():+ if line.startswith("LANGCHAIN_MODEL_NAME="):+ return line.split("=", 1)[1].strip()+ except OSError:+ pass+ return "unset (use /model to pick one)"+++def _probe_tool_count() -> int:+ """Count registered tools without blocking startup on import errors."""+ try:+ from src.tools import build_registry++ return len(build_registry())+ except Exception: # noqa: BLE001 — never block startup on stats+ return _FALLBACK_TOOLS+++def _probe_skill_count() -> int:+ """Count bundled + user skills without blocking startup on import errors.++ Reads ``SkillsLoader.skills`` directly — that is the authoritative list+ populated by :meth:`SkillsLoader._load` from bundled ``agent/skills/``+ plus ``~/.vibe-trading/skills/user/``.+ """+ try:+ from src.agent.skills import SkillsLoader++ loader = SkillsLoader()+ return len(loader.skills)+ except Exception: # noqa: BLE001+ return _FALLBACK_SKILLS+++def _probe_session_count() -> int:+ """Count recorded sessions from the SQLite store."""+ db_path = Path.home() / ".vibe-trading" / "sessions.db"+ if not db_path.exists():+ return 0+ try:+ import sqlite3++ with sqlite3.connect(str(db_path)) as conn:+ row = conn.execute("SELECT COUNT(*) FROM sessions").fetchone()+ return int(row[0]) if row else 0+ except Exception: # noqa: BLE001+ return 0+++def _collect_banner_stats(*, refresh: bool = False) -> Dict[str, Any]:+ """Return the four banner stat values, computing them at most once.++ The interactive launch path runs every probe synchronously (the+ user is already waiting for the prompt). Subsequent callers+ (``/clear`` re-render, ``/debug`` summary) reuse the cached values+ so they don't re-import the tool registry on every keystroke.++ Args:+ refresh: When True, recompute and overwrite the cache.++ Returns:+ ``{"model": str, "skills": int, "tools": int, "sessions": int}``.+ """+ if _BANNER_STATS_CACHE and not refresh:+ return dict(_BANNER_STATS_CACHE)+ stats: Dict[str, Any] = {+ "model": _probe_model_name(),+ "skills": _probe_skill_count(),+ "tools": _probe_tool_count(),+ "sessions": _probe_session_count(),+ }+ _BANNER_STATS_CACHE.clear()+ _BANNER_STATS_CACHE.update(stats)+ return dict(stats)+++# ---------------------------------------------------------------------------+# Routing helpers+# ---------------------------------------------------------------------------+++def _is_interactive_invocation(argv: Sequence[str]) -> bool:+ """Decide whether this invocation should drive the interactive loop.++ Interactive entry requires:++ * Both stdin and stdout are TTYs (no piped / redirected I/O).+ * Either no arguments at all, or exactly the ``chat`` subcommand.++ Anything else — a flag (``-p``, ``--json``, ``--help``), a recognised+ subcommand (``serve``, ``run``, ``alpha``, ``hypothesis`` ...), or an+ unknown positional — is delegated to ``_legacy.main`` so argparse+ can either dispatch it or produce its standard "unrecognized+ arguments" error. Routing typos here would silently drop the user+ into chat, which is worse than the argparse error.++ Args:+ argv: The argument list passed to :func:`main`, *excluding*+ ``sys.argv[0]``.++ Returns:+ ``True`` if the caller should drive the interactive loop.+ """+ if not sys.stdin.isatty() or not sys.stdout.isatty():+ return False+ if not argv:+ return True+ if argv[0].startswith("-"):+ return False+ return _is_supported_chat_invocation(argv)+++def _is_supported_chat_invocation(argv: Sequence[str]) -> bool:+ """Return True for chat invocations handled by the interactive front door."""+ if not argv or argv[0] != "chat":+ return False+ if len(argv) == 1:+ return True+ if len(argv) == 2 and argv[1].startswith("--max-iter="):+ try:+ int(argv[1].split("=", 1)[1])+ return True+ except ValueError:+ return False+ if len(argv) == 3 and argv[1] == "--max-iter":+ try:+ int(argv[2])+ return True+ except ValueError:+ return False+ return False+++def _maybe_run_onboarding() -> bool:+ """Run the first-launch wizard when ``.env`` is missing.++ Returns:+ ``True`` if startup should proceed, ``False`` if the user cancelled+ the wizard cleanly.+ """+ if _ENV_PATH.exists():+ return True+ console = get_console()+ written = run_onboarding(console=console)+ if written is None:+ return False+ # Reload env so downstream code picks up the fresh credentials.+ try:+ from dotenv import load_dotenv++ load_dotenv(written, override=True)+ except Exception: # noqa: BLE001 — legacy will load again later+ pass+ return True+++def _show_banner() -> None:+ """Print the welcome banner using best-effort stat probes."""+ stats = _collect_banner_stats()+ print_banner(get_console(), **stats)+++# ---------------------------------------------------------------------------+# Interactive context+# ---------------------------------------------------------------------------+++@dataclass+class InteractiveContext:+ """State bag handed to slash-command handlers and the run loop.++ Attributes:+ session_id: Active session id (populated lazily on first turn).+ history: Compact transcript (role/content pairs) fed back to the+ agent for follow-up context.+ max_iter: ReAct iteration ceiling.+ debug: Whether the ``/debug`` panel is currently shown.+ pending_prompt: Optional prompt queued by a slash handler+ (``/journal``, ``/shadow``) that the loop should execute as+ the next user turn. Consumed by :func:`_interactive_loop`+ and cleared.+ """++ session_id: Optional[str] = None+ history: List[Dict[str, str]] = field(default_factory=list)+ max_iter: int = 50+ debug: bool = False+ pending_prompt: Optional[str] = None+++# ---------------------------------------------------------------------------+# Session-store integration+# ---------------------------------------------------------------------------+++def _session_store() -> Any:+ """Return a process-wide :class:`SessionStore` rooted at ``agent/sessions``.++ Cached on the module so repeat ``_append_message`` / ``_new_session``+ calls don't re-import ``src.session.store`` every turn.+ """+ global _SESSION_STORE_CACHE+ if _SESSION_STORE_CACHE is None:+ from cli._legacy import SESSIONS_DIR # filesystem path constant+ from src.session.store import SessionStore++ _SESSION_STORE_CACHE = SessionStore(base_dir=SESSIONS_DIR)+ return _SESSION_STORE_CACHE+++def _new_session(prompt_preview: str) -> Optional[str]:+ """Create a fresh session record. Returns the id, or None on failure.++ Dual-writes to the filesystem :class:`SessionStore` (canonical JSONL+ log under ``agent/sessions/``) *and* to the SQLite FTS5 search index+ (``~/.vibe-trading/sessions.db``) so cross-session search via+ :class:`SessionSearchIndex` finds turns recorded from the interactive+ loop. Matches the pattern in :class:`SessionService`.+ """+ title = prompt_preview[:60] or "untitled"+ try:+ from src.session.models import Session, SessionStatus++ store = _session_store()+ session = Session(+ title=title,+ status=SessionStatus.ACTIVE,+ )+ store.create_session(session)+ except Exception: # noqa: BLE001 — never block the turn on persistence+ return None++ # Index in SQLite for FTS5 cross-session search. Best-effort — never+ # block the turn if the search index is unavailable.+ try:+ from src.session.search import get_shared_index++ get_shared_index().index_session(session.session_id, title)+ except Exception: # noqa: BLE001+ pass+ return session.session_id+++def _append_message(session_id: str, role: str, content: str) -> None:+ """Append a single message to the session JSONL log + FTS5 index.++ Dual-writes:++ * Canonical: append the :class:`Message` to ``messages.jsonl`` via+ the filesystem :class:`SessionStore`. ``_maybe_resume_last_session``+ and the legacy ``sessions`` CLI both read from here.+ * Search index: insert the same row into the SQLite FTS5 index so+ ``SessionSearchTool`` finds it. Required for the CLAUDE.md promise+ that cross-session full-text search works.++ Args:+ session_id: Active session id. Skipped if empty.+ role: ``"user"`` / ``"assistant"`` / ``"tool"``.+ content: Message text. Empty/whitespace strings are skipped.+ """+ if not session_id or not content:+ return+ try:+ from src.session.models import Message++ store = _session_store()+ store.append_message(+ Message(session_id=session_id, role=role, content=content)+ )+ except Exception: # noqa: BLE001 — persistence is best-effort+ pass++ # FTS5 cross-session search. Independent try/except so a JSONL write+ # that succeeded is not retried just because the search index failed.+ try:+ from src.session.search import get_shared_index++ get_shared_index().index_message(session_id, role, content)+ except Exception: # noqa: BLE001+ pass+++def _maybe_resume_last_session(console: Any) -> Optional[Dict[str, Any]]:+ """Prompt to resume the most recent session, if any exist.++ Returns:+ A dict ``{"session_id": str, "history": list[dict], "title": str}``+ when the user opts to resume, otherwise ``None`` (new session).+ """+ try:+ store = _session_store()+ sessions = store.list_sessions(limit=1)+ except Exception: # noqa: BLE001+ return None+ if not sessions:+ return None++ last = sessions[0]+ title = last.title or "(untitled)"+ console.print()+ console.print(+ f"[dim]Resume last session ({title})? (r)esume / (n)ew (default: new)[/dim]"+ )+ try:+ choice = input("> ").strip().lower()+ except (EOFError, KeyboardInterrupt):+ return None+ if choice not in {"r", "resume", "y", "yes"}:+ return None++ try:+ messages = store.get_messages(last.session_id, limit=_HISTORY_RETAINED_TURNS * 2)+ except Exception: # noqa: BLE001+ messages = []+ history = [+ {"role": m.role, "content": m.content}+ for m in messages+ if m.role in {"user", "assistant"} and m.content.strip()+ ]+ return {+ "session_id": last.session_id,+ "history": history[-_HISTORY_RETAINED_TURNS:],+ "title": title,+ }+++# ---------------------------------------------------------------------------+# Async preflight+# ---------------------------------------------------------------------------+++def _start_preflight_async() -> threading.Thread:+ """Run ``src.preflight.run_preflight`` in a daemon thread.++ The welcome banner has already painted by the time this runs, so the+ user sees something useful immediately while credential / network+ probes happen in the background. We swallow exceptions because the+ legacy path runs preflight again before any agent invocation — this+ pre-warm is opportunistic. Audit item 11.+ """+ def _worker() -> None:+ try:+ from src.preflight import run_preflight++ run_preflight(get_console())+ except Exception: # noqa: BLE001+ pass++ thread = threading.Thread(target=_worker, daemon=True, name="vibe-preflight")+ thread.start()+ return thread+++# ---------------------------------------------------------------------------+# Slash dispatch+# ---------------------------------------------------------------------------+++# Module paths that fan out to multiple commands via ``run(ctx, name, *args)``.+_MULTI_COMMAND_MODULES = frozenset({+ "cli.commands.chat",+ "cli.commands.show",+ "cli.commands.session",+})+++def _suggest_commands(unknown: str) -> List[str]:+ """Return up to three "did you mean" suggestions for ``unknown``.++ Uses :func:`difflib.get_close_matches` (edit-distance based) as the+ primary signal so single-character typos like ``/historu`` → ``/history``+ or ``/jurnal`` → ``/journal`` are caught — the subsequence scorer in+ ``slash_router.match_commands`` ranks transpositions poorly and is+ used here only as a fallback to fill any remaining slot.++ Args:+ unknown: The bare command token (no leading ``/``).++ Returns:+ Deduplicated command names, edit-distance suggestions first,+ capped at three entries.+ """+ import difflib++ from cli.commands.slash_router import SLASH_COMMANDS, match_commands++ all_names = [cmd.name for cmd in SLASH_COMMANDS]+ primary = difflib.get_close_matches(unknown, all_names, n=3, cutoff=0.6)++ # Fill remaining slots from the subsequence scorer so very short+ # typos (``/hi`` → ``/history``) still surface if difflib found+ # nothing close enough.+ suggestions: list[str] = list(primary)+ if len(suggestions) < 3:+ for cmd in match_commands("/" + unknown):+ if cmd.name not in suggestions:+ suggestions.append(cmd.name)+ if len(suggestions) >= 3:+ break+ return suggestions[:3]+++def _dispatch_slash(line: str, ctx: InteractiveContext) -> int:+ """Route a slash command line to its handler.++ Returns:+ Exit code from the handler. ``2`` is the conventional "user+ requested quit" sentinel (see ``cmd_quit``). Any other value is+ treated as continue-the-loop.+ """+ from cli.commands.slash_router import find_exact++ console = get_console()+ stripped = line.lstrip().lstrip("/")+ parts = stripped.split()+ if not parts:+ console.print("[dim]Type /help to see available commands.[/dim]")+ return 0+ name, *args = parts+ cmd = find_exact(name)+ if cmd is None:+ # Use edit-distance suggestions (difflib) so single-char typos+ # surface the right command — the subsequence scorer in+ # ``slash_router.match_commands`` does not handle transpositions.+ suggestions = _suggest_commands(name)+ console.print(f"[bold red]Unknown command:[/] /{name}")+ if suggestions:+ preview = ", ".join(f"/{s}" for s in suggestions)+ console.print(f"[dim]Did you mean: {preview}?[/dim]")+ console.print("[dim]Type /help to see available commands.[/dim]")+ return 0++ try:+ module = importlib.import_module(cmd.handler_module)+ except ImportError as exc:+ console.print(+ f"[bold red]Failed to load /{cmd.name} handler ({exc})[/bold red]"+ )+ return 0++ try:+ if cmd.handler_module in _MULTI_COMMAND_MODULES:+ return int(module.run(ctx, cmd.name, *args))+ return int(module.run(ctx, *args))+ except SystemExit as exc:+ # Treat the canonical "user quit" codes (0 / 2 / None) as+ # a loop break; anything else is a genuine handler failure+ # and should keep the REPL alive so the user can recover.+ code = exc.code+ if code in (None, 0, 2):+ return 2+ console.print(f"[bold red]/{cmd.name} exited with code {code}[/]")+ return 0+ except Exception as exc: # noqa: BLE001 — never let a handler kill the loop+ console.print(f"[bold red]/{cmd.name} raised {type(exc).__name__}: {exc}[/]")+ return 0+++# ---------------------------------------------------------------------------+# Interactive loop+# ---------------------------------------------------------------------------+++def _summarise_tool_result(tool: str, status: str, preview: str) -> str:+ """Short suffix to render after a finished tool event."""+ if status != "ok":+ return preview[:48].replace("\n", " ")+ # Delegate to the legacy preview helper which already knows about+ # backtest sharpe / shadow id / etc.+ try:+ from cli._legacy import _format_tool_result_preview, _strip_rich_tags++ return _strip_rich_tags(_format_tool_result_preview(tool, status, preview))[:48]+ except Exception: # noqa: BLE001+ return ""+++def _print_debug_summary(+ console: Any,+ result: Dict[str, Any],+ elapsed: float,+ ctx: InteractiveContext,+) -> None:+ """Render the one-line ``[debug]`` summary after a turn.++ Reads the iteration count from ``result`` (populated by+ :class:`src.agent.loop.AgentLoop`), counts tool events from+ ``react_trace`` when present, and approximates the post-turn+ context size from ``ctx.history``. Best-effort — any missing field+ falls back to ``?`` so the summary still prints.+ """+ iterations = result.get("iterations", "?")+ trace = result.get("react_trace") or []+ if isinstance(trace, list):+ tools = sum(+ 1+ for entry in trace+ if isinstance(entry, dict) and entry.get("type") == "tool_result"+ )+ else:+ tools = "?"+ history_chars = sum(len(m.get("content", "")) for m in ctx.history)+ # Rough char-to-token ratio (matches the loop's estimator).+ approx_tokens = history_chars // 4+ console.print(+ f"[dim][debug] iter={iterations} tools={tools} "+ f"elapsed={elapsed:.1f}s ctx≈{approx_tokens}tok ({history_chars}ch)[/dim]"+ )+++def _run_one_turn(user_input: str, ctx: InteractiveContext) -> None:+ """Execute a single agent turn with the Rich dashboard.++ Routes through :func:`cli._legacy._run_agent` so all tool callbacks,+ persistent memory, and the ReAct engine remain untouched — we only+ swap in the Rich dashboard and persist the turn to ``SessionStore``.+ """+ from cli._legacy import _RunDashboard, _print_result, _run_agent+ from rich.live import Live++ console = get_console()++ if ctx.session_id is None:+ ctx.session_id = _new_session(user_input)+ _append_message(ctx.session_id or "", "user", user_input)++ start = time.perf_counter()+ dashboard = _RunDashboard(user_input, ctx.max_iter)+ # ``transient=False`` — keep the final timeline visible after the run+ # completes. Audit item 4.+ try:+ with Live(+ dashboard.render(),+ console=console,+ refresh_per_second=6,+ transient=False,+ ) as live:+ dashboard.live = live+ result = _run_agent(+ user_input,+ history=ctx.history[-_HISTORY_RETAINED_TURNS:],+ max_iter=ctx.max_iter,+ dashboard=dashboard,+ )+ except (KeyboardInterrupt, BrokenPipeError):+ # BrokenPipe: caller did ``vibe-trading chat | head`` and the+ # downstream pipe closed mid-render. Print may itself fail on+ # the closed fd, so swallow that defensively too.+ try:+ console.print("\n[yellow]Interrupted[/yellow]")+ except (BrokenPipeError, OSError):+ pass+ return++ elapsed = time.perf_counter() - start+ _print_result(result, elapsed)++ ctx.history.append({"role": "user", "content": user_input})+ answer = (result.get("content") or "").strip()+ if answer:+ ctx.history.append({"role": "assistant", "content": answer})+ _append_message(ctx.session_id or "", "assistant", answer)++ if ctx.debug:+ _print_debug_summary(console, result, elapsed, ctx)+++def _print_input_hint(console: Any, hint: str) -> None:+ """Render the bottom hint bar in muted style."""+ from cli.components.hint_bar import render_hint_bar++ console.print(render_hint_bar(left=hint, right="Ctrl+D · /quit to exit"))+++def _interactive_loop(max_iter: int) -> int:+ """Drive the new interactive REPL.++ Returns:+ Process exit code (always ``0`` on a clean exit).+ """+ console = get_console()++ # Warm up the preflight in a background thread so the wait is hidden.+ _start_preflight_async()++ ctx = InteractiveContext(max_iter=max_iter)++ # Offer to resume the most recent session. Audit item 8.+ resume = _maybe_resume_last_session(console)+ if resume is not None:+ ctx.session_id = resume["session_id"]+ ctx.history = list(resume["history"])+ console.print(+ f"[dim]Resumed session: {resume['title']} ({len(ctx.history)} prior turns)[/dim]"+ )++ # Build the prompt session once so history + completer persist.+ try:+ from cli.input import ctrl_c_within_window, make_session+ except Exception as exc: # noqa: BLE001 — fall back gracefully if prompt_toolkit broken+ console.print(f"[red]Failed to initialise input layer: {exc}[/red]")+ console.print("[dim]Falling back to legacy interactive loop.[/dim]")+ from cli._legacy import cmd_interactive++ try:+ cmd_interactive(max_iter)+ except Exception: # noqa: BLE001+ return 1+ return 0++ session = make_session()+ _print_input_hint(console, "↑/↓ history · / for commands · Esc-Enter newline")++ while True:+ try:+ user_input = session.prompt("> ")+ except KeyboardInterrupt:+ # Should not reach here — the keybinding raises EOFError instead.+ continue+ except EOFError:+ # Two interpretations: Ctrl+D (always exit), or Ctrl+C on an+ # empty line (show hint, exit on second press).+ #+ # ``ctrl_c_within_window`` reads a press-time decision cached+ # by the keybinding: True iff the gap between the *previous*+ # Ctrl+C press and *this* one is < 2 s. First press → False+ # (no prior press) → we print the hint and continue. Second+ # press inside the window → True → we break.+ if ctrl_c_within_window(session, window_sec=2.0):+ break+ console.print(+ "[dim]Press Ctrl+C again within 2s, Ctrl+D, or type /quit to exit[/dim]"+ )+ continue++ text = user_input.strip()+ if not text:+ continue++ # Slash command path.+ if text.startswith("/"):+ rc = _dispatch_slash(text, ctx)+ if rc == 2:+ break+ # A handler may queue an agent prompt (``/journal <path>``,+ # ``/shadow ...``). Drain it here so the slash command turns+ # into a real turn without round-tripping through stdin.+ queued = ctx.pending_prompt+ if queued:+ ctx.pending_prompt = None+ _run_one_turn(queued, ctx)+ continue++ # Natural-language path — drive the agent.+ _run_one_turn(text, ctx)++ console.print("[dim]Goodbye[/dim]")+ return 0+++# ---------------------------------------------------------------------------+# Public entry point+# ---------------------------------------------------------------------------+++def main(argv: Optional[list[str]] = None) -> int:+ """CLI entrypoint returning a process exit code.++ Behaviour:++ * Interactive entry (no subcommand, or ``chat`` + TTY): show banner,+ run onboarding wizard if needed, then drop into the interactive+ loop driven by ``cli/input.py``, ``cli/completer.py``,+ and ``cli/commands/*``.+ * Non-interactive entry (``serve``, ``run -p ...``, ``mcp``,+ ``swarm``, piped stdin, etc.): pass through to ``cli._legacy.main``+ so every existing subcommand keeps working unchanged.++ Args:+ argv: Optional argument list (defaults to ``sys.argv[1:]``).++ Returns:+ Process exit code.+ """+ raw_argv = list(sys.argv[1:] if argv is None else argv)+ interactive = _is_interactive_invocation(raw_argv)++ if interactive:+ if not _maybe_run_onboarding():+ return 0+ _show_banner()+ # Strip the optional ``chat`` token + any ``--max-iter`` flag so+ # the new loop can read them directly without re-parsing argv.+ max_iter = _extract_max_iter(raw_argv, default=50)+ return _interactive_loop(max_iter)++ # Delegate every other path to the legacy dispatcher.+ try:+ from cli import _legacy+ except ImportError as exc: # pragma: no cover — packaging error+ get_console().print(+ f" Internal error: cannot import cli._legacy ({exc}).",+ style=Theme.danger,+ )+ return 2++ return int(_legacy.main(raw_argv))+++def _extract_max_iter(argv: Sequence[str], *, default: int) -> int:+ """Pull ``--max-iter <N>`` (or ``--max-iter=N``) out of ``argv``.++ The legacy argparse setup accepts ``--max-iter`` both at the top+ level and as ``chat --max-iter``. We just need the integer; the+ presence/absence of ``chat`` was already determined upstream.+ """+ it = iter(range(len(argv)))+ for i in it:+ token = argv[i]+ if token == "--max-iter" and i + 1 < len(argv):+ try:+ return int(argv[i + 1])+ except ValueError:+ return default+ if token.startswith("--max-iter="):+ try:+ return int(token.split("=", 1)[1])+ except ValueError:+ return default+ return default+++def _entrypoint() -> None:+ """Thin wrapper so the console script and ``python -m cli.main`` agree."""+ sys.exit(main())+++# ---------------------------------------------------------------------------+# Optional typer integration (only used by ``python -m cli.main --help``)+# ---------------------------------------------------------------------------+++def _build_typer_app(): # type: ignore[no-untyped-def]+ """Build a typer app that mirrors the legacy surface. Best-effort only."""+ try:+ import typer+ except ImportError:+ return None++ app = typer.Typer(+ add_completion=False,+ no_args_is_help=False,+ help="Vibe-Trading — natural-language finance research agent.",+ rich_markup_mode=None,+ )++ @app.callback(invoke_without_command=True)+ def _default(ctx: typer.Context) -> None: # noqa: ANN001+ if ctx.invoked_subcommand is None:+ sys.exit(main(ctx.args))++ @app.command("chat", help="Start the interactive ReAct chat loop.")+ def _chat(+ max_iter: int = typer.Option(50, "--max-iter", help="Maximum ReAct iterations."),+ ) -> None:+ sys.exit(main(["chat", "--max-iter", str(max_iter)]))++ @app.command("serve", help="Start the FastAPI server.")+ def _serve(+ host: str = typer.Option("0.0.0.0", "--host"),+ port: int = typer.Option(8000, "--port"),+ dev: bool = typer.Option(False, "--dev", help="Also boot the Vite dev server."),+ ) -> None:+ forwarded = ["serve", "--host", host, "--port", str(port)]+ if dev:+ forwarded.append("--dev")+ sys.exit(main(forwarded))++ @app.command("list", help="List recent runs.")+ def _list(limit: int = typer.Option(20, "--limit")) -> None:+ sys.exit(main(["list", "--limit", str(limit)]))++ @app.command("show", help="Show a recorded run by id.")+ def _show(run_id: str = typer.Argument(...)) -> None:+ sys.exit(main(["show", run_id]))++ @app.command("init", help="Re-run the interactive setup wizard.")+ def _init() -> None:+ run_onboarding(console=get_console())++ return app+++# ``python -m cli.main`` support — uses typer help if available, else main().+if __name__ == "__main__":+ typer_app = _build_typer_app()+ if typer_app is not None:+ typer_app()+ else:+ _entrypoint()+++__all__ = ["main", "InteractiveContext"]diff --git a/agent/cli/onboard.py b/agent/cli/onboard.pynew file mode 100644index 000000000..aa9824468--- /dev/null+++ b/agent/cli/onboard.py@@ -0,0 +1,499 @@+"""First-launch onboarding wizard.++Triggered automatically when ``~/.vibe-trading/.env`` does not exist. Five+back-steppable steps (provider → model → key → timeout → optional Tushare),+matching §3.2 of the 2026-05-19 UI/UX design proposal.++Each step persists immediately to ``~/.vibe-trading/.env.partial`` and the+file is atomically renamed to ``.env`` only on completion, so a crash mid-+wizard never leaves a corrupt ``.env`` behind. API key entry is masked.++Prefers ``questionary`` when available; otherwise drives prompt_toolkit+directly so Esc / Left-arrow can be bound to a back-step sentinel.+"""++from __future__ import annotations++import os+import tempfile+from dataclasses import dataclass+from pathlib import Path+from typing import Callable, Final, Sequence++from rich.console import Console+from rich.text import Text++from cli.theme import Theme, get_console++# Sentinels for back-navigation / cancel returned by selectors.+BACK = object()+CANCEL = object()+++# ---------------------------------------------------------------------------+# Provider catalogue — mirrors _PROVIDER_CHOICES in cli/_legacy.py+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class Provider:+ """One selectable LLM provider option shown in step 1."""++ key: str+ label: str+ description: str+ default_model: str+ key_env: str | None+ base_env: str+ base_url: str+ key_prefix: str | None+ suggested_models: tuple[str, ...]+++PROVIDERS: Final[tuple[Provider, ...]] = (+ Provider("openrouter", "OpenRouter", "recommended — 200+ models, one key",+ "deepseek/deepseek-v3.2",+ "OPENROUTER_API_KEY", "OPENROUTER_BASE_URL",+ "https://openrouter.ai/api/v1", "sk-or-",+ ("deepseek/deepseek-v3.2", "openai/gpt-5",+ "anthropic/claude-opus-4-7", "google/gemini-2.5-pro")),+ Provider("openai", "OpenAI", "GPT-5 / GPT-4o direct",+ "gpt-4o", "OPENAI_API_KEY", "OPENAI_BASE_URL",+ "https://api.openai.com/v1", "sk-",+ ("gpt-5", "gpt-4o", "o3-mini")),+ Provider("deepseek", "DeepSeek",+ "cheapest tier — good for batch backtest research",+ "deepseek-chat", "DEEPSEEK_API_KEY", "DEEPSEEK_BASE_URL",+ "https://api.deepseek.com/v1", "sk-",+ ("deepseek-chat", "deepseek-reasoner")),+ Provider("ollama", "Ollama", "local, free, no API key",+ "qwen2.5:32b", None, "OLLAMA_BASE_URL",+ "http://localhost:11434", None,+ ("qwen2.5:32b", "llama3.3:70b", "deepseek-r1:14b")),+)++TIMEOUT_CHOICES: Final[tuple[tuple[str, str], ...]] = (+ ("2400", "2400s (4 minutes — research mode, recommended)"),+ ("600", "600s (10 minutes — large backtests / swarm runs)"),+ ("120", "120s (2 minutes — quick lookup mode)"),+)+++# ---------------------------------------------------------------------------+# Filesystem helpers (atomic partial save → final rename)+# ---------------------------------------------------------------------------+++def _env_dir() -> Path: return Path.home() / ".vibe-trading"+def _env_path() -> Path: return _env_dir() / ".env"+def _partial_path() -> Path: return _env_dir() / ".env.partial"+++def _render_env(values: dict[str, str]) -> str:+ """Render values as a stable ``.env`` body (KEY=value lines)."""+ return "\n".join(f"{k}={v}" for k, v in values.items() if v) + "\n"+++def _save_partial(values: dict[str, str]) -> None:+ """Best-effort write to ``.env.partial`` (crash-resilience nicety)."""+ try:+ _env_dir().mkdir(parents=True, exist_ok=True)+ _partial_path().write_text(_render_env(values), encoding="utf-8")+ try:+ _partial_path().chmod(0o600)+ except OSError:+ pass+ except OSError:+ pass+++def _finalize(values: dict[str, str]) -> Path:+ """Atomically write ``.env``. Returns the final path."""+ _env_dir().mkdir(parents=True, exist_ok=True)+ content = _render_env(values)+ fd, tmp_name = tempfile.mkstemp(prefix=".env.", dir=str(_env_dir()))+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as f:+ f.write(content)+ tmp_path = Path(tmp_name)+ try:+ tmp_path.chmod(0o600)+ except OSError:+ pass+ tmp_path.replace(_env_path())+ finally:+ try:+ Path(tmp_name).unlink()+ except (FileNotFoundError, OSError):+ pass+ try:+ _partial_path().unlink()+ except (FileNotFoundError, OSError):+ pass+ return _env_path()+++# ---------------------------------------------------------------------------+# Selector with back-step (custom prompt_toolkit Application)+# ---------------------------------------------------------------------------+++def _select_with_back(prompt: str, choices: Sequence[tuple[str, str]], *,+ default_index: int = 0,+ console: Console | None = None) -> str | object:+ """Vertically-scrollable selector. Returns chosen value, BACK, or CANCEL.++ Keybindings: ↑/↓ navigate, Enter confirm, Esc/← back, Ctrl+C cancel.+ Falls back to a numeric stdin prompt if prompt_toolkit is unavailable.+ """+ cons = console or get_console()+ cons.print()+ cons.print(Text(f"? {prompt}", style=Theme.label))++ try:+ from prompt_toolkit import Application+ from prompt_toolkit.formatted_text import FormattedText+ from prompt_toolkit.key_binding import KeyBindings+ from prompt_toolkit.layout import Layout+ from prompt_toolkit.layout.containers import HSplit, Window+ from prompt_toolkit.layout.controls import FormattedTextControl+ from prompt_toolkit.styles import Style as PTStyle+ except ImportError:+ return _select_numeric(choices, default_index, cons)++ state = {"index": max(0, min(default_index, len(choices) - 1)), "result": None}++ def _format() -> FormattedText:+ out: list[tuple[str, str]] = []+ for i, (_, label) in enumerate(choices):+ if i == state["index"]:+ out.append(("class:cursor", " > "))+ out.append(("class:selected", f"{label}\n"))+ else:+ out.append(("", " "))+ out.append(("class:option", f"{label}\n"))+ out.append(("class:hint",+ "\n ↑/↓ navigate · Enter select · Esc/← back · Ctrl+C cancel"))+ return FormattedText(out)++ kb = KeyBindings()++ @kb.add("up")+ @kb.add("c-p")+ def _(event): # type: ignore[no-redef]+ state["index"] = (state["index"] - 1) % len(choices); event.app.invalidate()++ @kb.add("down")+ @kb.add("c-n")+ def _(event): # type: ignore[no-redef]+ state["index"] = (state["index"] + 1) % len(choices); event.app.invalidate()++ @kb.add("enter")+ def _(event): # type: ignore[no-redef]+ state["result"] = choices[state["index"]][0]; event.app.exit()++ @kb.add("escape", eager=True)+ @kb.add("left")+ def _(event): # type: ignore[no-redef]+ state["result"] = BACK; event.app.exit()++ @kb.add("c-c")+ @kb.add("c-d")+ def _(event): # type: ignore[no-redef]+ state["result"] = CANCEL; event.app.exit()++ style = PTStyle.from_dict({+ "cursor": f"{Theme.brand_hex} bold",+ "selected": f"{Theme.brand_hex} bold",+ "option": "",+ "hint": "#808080",+ })+ layout = Layout(HSplit([Window(FormattedTextControl(_format), wrap_lines=False)]))+ app: Application = Application(layout=layout, key_bindings=kb, style=style, full_screen=False)+ try:+ app.run()+ except (EOFError, KeyboardInterrupt):+ return CANCEL+ return state["result"] if state["result"] is not None else CANCEL+++def _select_numeric(choices: Sequence[tuple[str, str]], default_index: int,+ console: Console) -> str | object:+ """Stdin-only fallback selector."""+ for i, (_, label) in enumerate(choices, start=1):+ marker = ">" if (i - 1) == default_index else " "+ console.print(f" {marker} [{i}] {label}", style=Theme.muted)+ console.print(Text(" (type number, b=back, q=cancel)", style=Theme.muted))+ try:+ raw = input("> ").strip().lower()+ except (EOFError, KeyboardInterrupt):+ return CANCEL+ if raw in {"b", "back"}: return BACK+ if raw in {"q", "quit", "cancel"}: return CANCEL+ if not raw: return choices[default_index][0]+ try:+ idx = int(raw)+ if 1 <= idx <= len(choices):+ return choices[idx - 1][0]+ except ValueError:+ pass+ console.print(Text(" invalid selection, try again", style=Theme.danger))+ return _select_numeric(choices, default_index, console)+++# ---------------------------------------------------------------------------+# Masked / plain prompts+# ---------------------------------------------------------------------------+++def _prompt_secret(prompt: str, *, console: Console) -> str | object:+ """Read a masked secret. Returns string, BACK, or CANCEL."""+ console.print()+ console.print(Text(f"? {prompt}", style=Theme.label))+ console.print(Text(+ " (input hidden · Enter to submit · Esc to go back · Ctrl+C to cancel)",+ style=Theme.muted,+ ))+ try:+ from prompt_toolkit import prompt as pt_prompt+ from prompt_toolkit.key_binding import KeyBindings++ kb = KeyBindings()+ sentinel: dict[str, object] = {"action": None}++ @kb.add("escape", eager=True)+ def _(event): # type: ignore[no-redef]+ sentinel["action"] = BACK; event.app.exit(result="")++ try:+ value = pt_prompt("> ", is_password=True, key_bindings=kb)+ except (EOFError, KeyboardInterrupt):+ return CANCEL+ if sentinel["action"] is BACK:+ return BACK+ return value.strip()+ except ImportError:+ import getpass+ try:+ return getpass.getpass("> ").strip()+ except (EOFError, KeyboardInterrupt):+ return CANCEL+++def _prompt_text(prompt: str, *, default: str = "",+ console: Console) -> str | object:+ """Read a plain string. Returns string, BACK, or CANCEL."""+ console.print()+ console.print(Text(f"? {prompt}", style=Theme.label))+ if default:+ console.print(Text(f" (Enter for default: {default} · Esc to go back)",+ style=Theme.muted))+ else:+ console.print(Text(" (Enter to skip · Esc to go back)", style=Theme.muted))++ try:+ from prompt_toolkit import prompt as pt_prompt+ from prompt_toolkit.key_binding import KeyBindings++ kb = KeyBindings()+ sentinel: dict[str, object] = {"action": None}++ @kb.add("escape", eager=True)+ def _(event): # type: ignore[no-redef]+ sentinel["action"] = BACK; event.app.exit(result="")++ try:+ value = pt_prompt("> ", key_bindings=kb)+ except (EOFError, KeyboardInterrupt):+ return CANCEL+ if sentinel["action"] is BACK:+ return BACK+ v = value.strip()+ return v if v else default+ except ImportError:+ try:+ raw = input("> ").strip()+ return raw if raw else default+ except (EOFError, KeyboardInterrupt):+ return CANCEL+++# ---------------------------------------------------------------------------+# Wizard+# ---------------------------------------------------------------------------+++def _validate_key(provider: Provider, key: str) -> str | None:+ """Return error message or None if key looks plausible."""+ if not key:+ return "API key cannot be empty."+ if provider.key_prefix and not key.startswith(provider.key_prefix):+ return f"Expected key to start with '{provider.key_prefix}'."+ if len(key) < 12:+ return "That key looks too short."+ return None+++def _intro_header(console: Console) -> None:+ console.print()+ console.print(Text(" Vibe-Trading setup", style=Theme.primary))+ console.print(Text(+ " We didn't find a config at ~/.vibe-trading/.env.\n"+ " Let's set up in under a minute.",+ style=Theme.muted,+ ))+++def run_onboarding(*, console: Console | None = None) -> Path | None:+ """Run the 5-step wizard. Returns the written ``.env`` path or None.++ Returns ``None`` when the user cancels (Ctrl+C / Esc at step 1) so the+ caller can exit cleanly without writing a partial config.+ """+ cons = console or get_console()+ _intro_header(cons)++ values: dict[str, str] = {"LANGCHAIN_TEMPERATURE": "0.0", "MAX_RETRIES": "2"}+ state: dict[str, object] = {"provider": None, "model": None, "key": None}++ def step_provider() -> object:+ choices = [(p.key, f"{p.label:<14} {p.description}") for p in PROVIDERS]+ result = _select_with_back("Pick a model provider", choices,+ default_index=0, console=cons)+ if result is BACK or result is CANCEL:+ return result+ provider = next(p for p in PROVIDERS if p.key == result)+ state["provider"] = provider+ values["LANGCHAIN_PROVIDER"] = provider.key+ values[provider.base_env] = provider.base_url+ _save_partial(values)+ return "ok"++ def step_model() -> object:+ provider: Provider = state["provider"] # type: ignore[assignment]+ choices: list[tuple[str, str]] = [+ (m, f"{m}{' (default)' if m == provider.default_model else ''}")+ for m in provider.suggested_models+ ]+ choices.append(("__custom__", "other (type custom model id)"))+ default_idx = next(+ (i for i, (v, _) in enumerate(choices) if v == provider.default_model),+ 0,+ )+ choice = _select_with_back("Pick a model", choices,+ default_index=default_idx, console=cons)+ if choice is BACK or choice is CANCEL:+ return choice+ if choice == "__custom__":+ custom = _prompt_text("Type the model id",+ default=provider.default_model, console=cons)+ if custom is BACK or custom is CANCEL:+ return custom+ model = str(custom) or provider.default_model+ else:+ model = str(choice)+ state["model"] = model+ values["LANGCHAIN_MODEL_NAME"] = model+ _save_partial(values)+ return "ok"++ def step_key() -> object:+ provider: Provider = state["provider"] # type: ignore[assignment]+ if provider.key_env is None:+ cons.print()+ cons.print(Text(" Ollama runs locally — no API key needed.",+ style=Theme.success))+ return "ok"+ while True:+ key = _prompt_secret(+ f"Paste your {provider.label} API key "+ "(saved to ~/.vibe-trading/.env, never logged)",+ console=cons,+ )+ if key is BACK or key is CANCEL:+ return key+ err = _validate_key(provider, str(key))+ if err is None:+ state["key"] = key+ values[provider.key_env] = str(key)+ _save_partial(values)+ return "ok"+ cons.print(Text(f" {err} Try again, or press Esc to go back.",+ style=Theme.danger))++ def step_timeout() -> object:+ choice = _select_with_back("Default request timeout",+ list(TIMEOUT_CHOICES),+ default_index=0, console=cons)+ if choice is BACK or choice is CANCEL:+ return choice+ values["TIMEOUT_SECONDS"] = str(choice)+ _save_partial(values)+ return "ok"++ def step_tushare() -> object:+ choices = [+ ("__skip__", "No, skip (most users)"),+ ("__paste__", "Yes — paste my Tushare token"),+ ]+ decision = _select_with_back(+ "Enable Tushare for China A-share data? (optional)",+ choices, default_index=0, console=cons,+ )+ if decision is BACK or decision is CANCEL:+ return decision+ if decision == "__paste__":+ token = _prompt_secret("Tushare token", console=cons)+ if token is BACK or token is CANCEL:+ return token+ if str(token).strip():+ values["TUSHARE_TOKEN"] = str(token).strip()+ _save_partial(values)+ return "ok"++ steps: list[Callable[[], object]] = [+ step_provider, step_model, step_key, step_timeout, step_tushare,+ ]++ i = 0+ while i < len(steps):+ result = steps[i]()+ if result is CANCEL:+ cons.print()+ cons.print(Text(" Setup cancelled. No config written.",+ style=Theme.warning))+ return None+ if result is BACK:+ if i == 0:+ cons.print()+ cons.print(Text(" Setup cancelled. No config written.",+ style=Theme.warning))+ return None+ i -= 1+ continue+ i += 1++ final_path = _finalize(values)++ cons.print()+ cons.print(Text(f" ✓ Wrote {final_path}", style=Theme.success))+ cons.print()++ tour = _select_with_back(+ "Want a quick tour? (or jump straight in)",+ [("__skip__", "Skip — drop me in chat"),+ ("__tour__", "Show me a 30-second sample run")],+ default_index=0, console=cons,+ )+ if tour == "__tour__":+ cons.print()+ cons.print(Text(+ " Tip: try `analyze AAPL last 30 days` as your first prompt.\n"+ " Type /help any time to see all commands.",+ style=Theme.muted,+ ))++ return final_path+++__all__ = ["run_onboarding", "PROVIDERS", "Provider", "BACK", "CANCEL"]diff --git a/agent/cli/stream.py b/agent/cli/stream.pynew file mode 100644index 000000000..554f8dd64--- /dev/null+++ b/agent/cli/stream.py@@ -0,0 +1,345 @@+"""Streaming renderer + thinking spinner for the interactive CLI.++Single-agent mode (the only mode demoed in Parcel α): a short-lived+``Rich.Live`` with ``transient=True`` drives the spinner while the model+thinks; tool events and the final answer are emitted as *static* prints so+they persist on screen after the live area is erased. This avoids the+"ghost re-paint" bug that plagued Vibe-Trading's earlier Live-based+dashboards (nanobot lesson, design proposal §3.5).++Swarm mode is a stub: callers should fall through to the legacy Rich Live+dashboard in ``cli/_legacy.py``. The full multi-agent grid lands in Parcel β.++Tool events use the dexter-style ``⏺ Tool Name (args) duration · summary``+format. Tool names are auto-Title-Cased with a small acronym whitelist.+"""++from __future__ import annotations++import re+import threading+import time+from contextlib import contextmanager+from dataclasses import dataclass, field+from typing import Iterator, Optional++from rich.console import Console+from rich.live import Live+from rich.text import Text++from cli.theme import Theme, get_console+from cli.utils.format import format_duration+from cli.utils.thinking_verbs import pick_thinking_verb++_PREFIX_RE = re.compile(r"^(get|run|do|fetch|load|build|compute|calc(?:ulate)?)_")++# Canonical acronyms that should render UPPERCASE rather than Title-Case.+# Whitelist (not "len <= 3" heuristic) so common words like "web" stay "Web".+_ACRONYMS: frozenset[str] = frozenset({+ "api", "url", "csv", "json", "yaml", "sql", "tsv", "pdf",+ "ai", "ml", "dcf", "fcf", "roe", "roi", "pe", "pb", "iv",+ "btc", "eth", "usd", "cny", "id",+})+++def beautify_tool_name(raw: str) -> str:+ """``get_market_data`` → ``Market Data``. Acronyms in whitelist UPPER."""+ if not raw:+ return raw+ parts = _PREFIX_RE.sub("", raw).split("_")+ out: list[str] = []+ for part in parts:+ if not part:+ continue+ out.append(part.upper() if part.lower() in _ACRONYMS else part.capitalize())+ return " ".join(out) if out else raw+++def summarize_args(args: dict | str | None, *, max_len: int = 60) -> str:+ """Compact single-line preview. Prefers query/symbol/url; truncates long."""+ if not args:+ return ""+ if isinstance(args, str):+ return _truncate(args, max_len)+ if not isinstance(args, dict):+ return _truncate(str(args), max_len)+ for priority_key in ("query", "prompt", "url", "symbol", "ticker", "code"):+ if priority_key in args and args[priority_key]:+ return f'"{_truncate(str(args[priority_key]), max_len - 2)}"'+ pieces: list[str] = []+ used = 0+ for k, v in args.items():+ token = f"{k}={_truncate(str(v), 20)}"+ if used + len(token) + 2 > max_len:+ pieces.append("…"); break+ pieces.append(token); used += len(token) + 2+ return ", ".join(pieces)+++def _truncate(value: str, max_len: int) -> str:+ if len(value) <= max_len:+ return value+ if max_len <= 1:+ return "…"+ return value[: max_len - 1] + "…"+++# ---------------------------------------------------------------------------+# ThinkingSpinner+# ---------------------------------------------------------------------------+++@dataclass+class _SpinnerState:+ verb: str+ started_at: float+ paused: bool = False+ stopped: bool = False+ extra: str = ""+++class ThinkingSpinner:+ """Transient spinner that can be paused/resumed safely.++ ``pause()`` is a context manager: stops the underlying ``Live`` (clearing+ its line), yields so the caller can print a static line, then restarts.+ This is nanobot's pattern and avoids ANSI escape interleaving.+ """++ def __init__(self, console: Console | None = None) -> None:+ self._console = console or get_console()+ self._state = _SpinnerState(+ verb=pick_thinking_verb(), started_at=time.monotonic()+ )+ self._live: Optional[Live] = None+ self._lock = threading.Lock()+ self._tick_thread: Optional[threading.Thread] = None++ def start(self, verb: str | None = None) -> None:+ """Begin rendering. ``verb`` rerolls per turn if not supplied."""+ with self._lock:+ if self._live is not None:+ return+ self._state.verb = verb or pick_thinking_verb()+ self._state.started_at = time.monotonic()+ self._state.paused = False+ self._state.stopped = False+ self._live = Live(self._render(), console=self._console,+ refresh_per_second=10, transient=True)+ self._live.start(refresh=False)+ self._tick_thread = threading.Thread(target=self._tick, daemon=True)+ self._tick_thread.start()++ def stop(self) -> None:+ """Stop and erase the spinner line."""+ with self._lock:+ self._state.stopped = True+ if self._live is not None:+ try:+ self._live.stop()+ except Exception: # noqa: BLE001 — Rich shutdown can race+ pass+ self._live = None++ def set_extra(self, extra: str) -> None:+ """Update the right-hand suffix (e.g. token / cost preview)."""+ self._state.extra = extra++ @contextmanager+ def pause(self) -> Iterator[None]:+ """Suspend the spinner so the caller can safely ``console.print``."""+ was_running = False+ with self._lock:+ if self._live is not None and not self._state.stopped:+ was_running = True+ self._state.paused = True+ try:+ self._live.stop()+ except Exception: # noqa: BLE001+ pass+ self._live = None+ try:+ yield+ finally:+ if was_running and not self._state.stopped:+ with self._lock:+ self._state.paused = False+ self._live = Live(self._render(), console=self._console,+ refresh_per_second=10, transient=True)+ self._live.start(refresh=False)++ def _render(self) -> Text:+ elapsed_ms = int((time.monotonic() - self._state.started_at) * 1000)+ text = Text()+ text.append(" ")+ text.append("●", style=Theme.warning) # pulse anchor (no emoji)+ text.append(" ")+ text.append(self._state.verb, style=Theme.primary_dim)+ text.append(" ")+ text.append(format_duration(elapsed_ms), style=Theme.muted)+ if self._state.extra:+ text.append(" · ", style=Theme.muted)+ text.append(self._state.extra, style=Theme.muted)+ return text++ def _tick(self) -> None:+ """Refresh duration label every 100 ms."""+ while not self._state.stopped:+ time.sleep(0.1)+ with self._lock:+ if self._live is not None and not self._state.paused:+ try:+ self._live.update(self._render(), refresh=True)+ except Exception: # noqa: BLE001+ pass+++# ---------------------------------------------------------------------------+# StreamRenderer+# ---------------------------------------------------------------------------+++@dataclass+class ToolCall:+ """A single tool invocation observed during a turn."""++ name: str+ args: dict | str | None+ started_at: float = field(default_factory=time.monotonic)+ finished_at: Optional[float] = None+ summary: str = ""++ @property+ def duration_ms(self) -> int | None:+ if self.finished_at is None:+ return None+ return int((self.finished_at - self.started_at) * 1000)+++class StreamRenderer:+ """Drives the streaming display for a single agent turn.++ Mode ``"single"`` is the focus of Parcel α. Mode ``"swarm"`` is a stub+ — callers should detect it and route to ``_legacy`` swarm rendering.+ """++ def __init__(self, *, mode: str = "single",+ console: Console | None = None) -> None:+ if mode not in {"single", "swarm"}:+ raise ValueError(f"unknown StreamRenderer mode: {mode!r}")+ self._mode = mode+ self._console = console or get_console()+ self._spinner: Optional[ThinkingSpinner] = None+ self._active_calls: dict[str, ToolCall] = {}++ @property+ def mode(self) -> str:+ return self._mode++ @contextmanager+ def turn(self, *, verb: str | None = None) -> Iterator["StreamRenderer"]:+ """Context manager wrapping one agent turn. Manages spinner lifecycle."""+ if self._mode == "swarm":+ yield self+ return+ self._spinner = ThinkingSpinner(self._console)+ self._spinner.start(verb=verb)+ try:+ yield self+ finally:+ if self._spinner is not None:+ self._spinner.stop()+ self._spinner = None+ self._active_calls.clear()++ def on_tool_start(self, name: str, args: dict | str | None) -> None:+ """Record a tool call start. Line emitted only when call finishes."""+ self._active_calls[name] = ToolCall(name=name, args=args)++ def on_tool_end(self, name: str, *, summary: str = "") -> None:+ """Mark a tool call finished and emit its static line."""+ call = self._active_calls.pop(name, None)+ if call is None:+ call = ToolCall(name=name, args=None,+ finished_at=time.monotonic(), summary=summary)+ else:+ call.finished_at = time.monotonic()+ call.summary = summary+ self._print_tool_line(call)++ def _print_tool_line(self, call: ToolCall) -> None:+ line = Text()+ line.append("⏺", style=Theme.success)+ line.append(" ")+ line.append(beautify_tool_name(call.name), style=Theme.label)+ args_preview = summarize_args(+ call.args if isinstance(call.args, (dict, str)) else None+ )+ if args_preview:+ line.append(" ")+ line.append(f"({args_preview})", style=Theme.muted)+ # Right-pad so the duration column aligns at column 60.+ pad_to = 60+ current_len = len(line.plain)+ line.append(" " * max(2, pad_to - current_len))+ if call.duration_ms is not None:+ line.append(format_duration(call.duration_ms), style=Theme.muted)+ if call.summary:+ line.append(" · ", style=Theme.muted)+ line.append(call.summary, style=Theme.muted)+ self._emit_static(line)++ def _emit_static(self, renderable) -> None: # type: ignore[no-untyped-def]+ """Print a static line, pausing the spinner if running."""+ if self._spinner is not None:+ with self._spinner.pause():+ self._console.print(renderable)+ else:+ self._console.print(renderable)++ def print_answer(self, body: str) -> None:+ """Print the assistant's final answer, prefixed with the brand marker."""+ if self._spinner is not None:+ self._spinner.stop()+ self._spinner = None+ lines = body.splitlines() or [""]+ head = Text()+ head.append("⏺ ", style=Theme.primary)+ head.append(lines[0])+ self._console.print(head)+ for line in lines[1:]:+ self._console.print(Text(" " + line))+ self._console.print()++ def print_footer(self, *, run_id: str, tool_count: int,+ duration_ms: int | float | None,+ token_count: int | None, cost: float | None) -> None:+ """``/show <id> · N tool calls · 4.1s · 1.2k tokens · $0.003``."""+ from cli.utils.format import abbreviate_num, format_tokens++ line = Text(" ")+ line.append(f"/show {run_id}", style=Theme.info)+ line.append(" · ", style=Theme.muted)+ line.append(+ f"{tool_count} tool call{'s' if tool_count != 1 else ''}",+ style=Theme.muted,+ )+ line.append(" · ", style=Theme.muted)+ line.append(format_duration(duration_ms), style=Theme.muted)+ if token_count is not None:+ line.append(" · ", style=Theme.muted)+ line.append(format_tokens(token_count), style=Theme.muted)+ if cost is not None:+ line.append(" · ", style=Theme.muted)+ line.append(abbreviate_num(cost, currency="$"), style=Theme.muted)+ self._console.print(line)+ self._console.print()+++__all__ = [+ "StreamRenderer",+ "ThinkingSpinner",+ "ToolCall",+ "beautify_tool_name",+ "summarize_args",+]diff --git a/agent/cli/theme.py b/agent/cli/theme.pynew file mode 100644index 000000000..260937abb--- /dev/null+++ b/agent/cli/theme.py@@ -0,0 +1,239 @@+"""Centralised Rich Style table for the Vibe-Trading CLI.++All visible colour decisions for the CLI live here so the look stays consistent+with the web app (see ``frontend/src/index.css`` design tokens). The brand+accent is the orange wordmark colour selected in the 2026-05-19 UI/UX design+proposal (§1.3):++* light terminals: ``#d97706`` (WCAG-AA white-on-orange contrast 4.8:1)+* dark terminals: ``#fa9842`` (matches web ``--primary`` in dark mode)++Semantic styles follow the design proposal's "Orange discipline rule" — only+the brand wordmark, the primary CTA, and the agent identity should ever use+``Theme.primary``. Tool status, success, danger and warning use their own+semantic tokens so the orange stays meaningful.++The module exposes a single shared :class:`rich.console.Console` instance via+:func:`get_console` so every component (banner, onboarding wizard, stream+renderer, status bar) renders to the same TTY. ``NO_COLOR`` is honoured by+forcing Rich into no-color mode at construction time.+"""++from __future__ import annotations++import os+import sys+from dataclasses import dataclass+from typing import Final++from rich.console import Console+from rich.style import Style++# ---------------------------------------------------------------------------+# Brand palette (single source of truth — mirrored in frontend/src/index.css)+# ---------------------------------------------------------------------------++BRAND_ORANGE_LIGHT: Final[str] = "#d97706"+"""Wordmark / primary CTA colour on light terminals (web ``--primary`` light)."""++BRAND_ORANGE_DARK: Final[str] = "#fa9842"+"""Wordmark / primary CTA colour on dark terminals (web ``--primary`` dark)."""+++def _is_dark_terminal(console: Console) -> bool:+ """Heuristically decide whether the terminal is rendering on a dark theme.++ Rich does not expose a foolproof "dark mode?" probe, so we use a best-effort+ chain:++ 1. Explicit override via ``VIBE_TRADING_THEME`` env var (``dark``/``light``).+ 2. ``COLORFGBG`` (set by xterm/rxvt/Konsole): the part after ``;`` is the+ background colour index. ``0`` (black) → dark, anything else → light.+ 3. macOS Terminal.app sets ``TERM_PROGRAM=Apple_Terminal`` without a colour+ hint — assume dark (it is the macOS Big Sur+ default).+ 4. Fallback: dark (matches the modern default across iTerm, Alacritty,+ Windows Terminal, VS Code integrated terminal).++ Args:+ console: Rich console (used to short-circuit when colour is disabled).++ Returns:+ ``True`` if dark mode should be assumed.+ """++ override = os.environ.get("VIBE_TRADING_THEME", "").strip().lower()+ if override in {"dark", "light"}:+ return override == "dark"++ if console.color_system is None:+ # No colour at all — pick dark so dim styles read correctly when forced+ # to ANSI later, but in practice nothing will be coloured.+ return True++ colorfgbg = os.environ.get("COLORFGBG", "")+ if ";" in colorfgbg:+ bg = colorfgbg.split(";")[-1].strip()+ if bg.isdigit():+ return int(bg) in {0, 1, 2, 3, 4, 5, 6, 7, 8} # low ANSI ⇒ dark++ if os.environ.get("TERM_PROGRAM", "").lower() == "apple_terminal":+ return True++ return True+++@dataclass(frozen=True)+class _ThemeStyles:+ """Immutable bundle of Rich :class:`Style` instances used CLI-wide."""++ primary: Style+ """Brand orange. Reserved for wordmark, primary CTA, agent identity."""++ primary_dim: Style+ """Slightly muted brand orange for hover/inactive variants."""++ success: Style+ """Tool completed, backtest passed, env saved (green)."""++ danger: Style+ """Failures, validation errors, destructive prompts (red)."""++ warning: Style+ """Tool running, partial state, non-blocking caution (amber)."""++ info: Style+ """Hints, secondary headings, neutral attention (cyan)."""++ muted: Style+ """Captions, dim metadata, separators (dim grey)."""++ bold: Style+ """Section headers, table column titles."""++ label: Style+ """Inline labels (e.g. ``Model:``) — slightly bolder than ``muted``."""++ accent_bg: Style+ """Reverse-video accent — used for the slash-typeahead highlight."""+++_NO_COLOR: Final[bool] = "NO_COLOR" in os.environ+++def _build_styles(dark: bool, no_color: bool) -> _ThemeStyles:+ """Construct the style bundle for the current terminal mode."""++ if no_color:+ plain = Style()+ return _ThemeStyles(+ primary=Style(bold=True),+ primary_dim=Style(),+ success=Style(),+ danger=Style(bold=True),+ warning=Style(),+ info=Style(),+ muted=Style(dim=True),+ bold=Style(bold=True),+ label=Style(bold=True),+ accent_bg=Style(reverse=True),+ )++ brand = BRAND_ORANGE_DARK if dark else BRAND_ORANGE_LIGHT+ brand_dim = "#a35a04" if not dark else "#c87a2f"++ return _ThemeStyles(+ primary=Style(color=brand, bold=True),+ primary_dim=Style(color=brand_dim),+ success=Style(color="#16a34a", bold=True),+ danger=Style(color="#dc2626", bold=True),+ warning=Style(color="#d97706"), # amber for in-flight tools+ info=Style(color="#0891b2"),+ muted=Style(color="#737373", dim=True) if not dark else Style(color="#9ca3af", dim=True),+ bold=Style(bold=True),+ label=Style(color="#525252", bold=True) if not dark else Style(color="#d4d4d8", bold=True),+ accent_bg=Style(color=brand, reverse=True, bold=True),+ )+++# ---------------------------------------------------------------------------+# Singleton console + style accessors+# ---------------------------------------------------------------------------+++def _make_console() -> Console:+ """Create the shared Rich console.++ ``force_terminal`` is *not* set: Rich's own ``isatty`` detection is+ correct and forcing it leaks ANSI escapes into ``docker exec -i`` /+ piped output (nanobot lesson, issue #3265).++ ``no_color`` honours ``NO_COLOR`` (https://no-color.org).+ """++ return Console(+ no_color=_NO_COLOR,+ soft_wrap=False,+ highlight=False,+ emoji=False, # project rule: no emoji anywhere+ markup=True,+ stderr=False,+ legacy_windows=False if sys.platform == "win32" else None,+ )+++_console: Console = _make_console()+_dark: bool = _is_dark_terminal(_console)+_styles: _ThemeStyles = _build_styles(_dark, _NO_COLOR or _console.color_system is None)+++def get_console() -> Console:+ """Return the shared console instance.++ Returns:+ The single :class:`Console` everyone in ``agent/cli`` writes to.+ """++ return _console+++def is_dark() -> bool:+ """Return ``True`` if dark-mode styles are active."""++ return _dark+++class Theme:+ """Namespace of Rich :class:`Style` instances used across the CLI.++ Use as attribute access (``Theme.primary``) so that swapping the+ underlying palette only requires editing this module. Each attribute is a+ :class:`rich.style.Style` and can be passed to ``console.print`` directly+ or composed via ``Text("…", style=Theme.primary)``.++ Example:+ >>> from cli.theme import Theme, get_console+ >>> get_console().print("Vibe-Trading", style=Theme.primary)+ """++ primary: Final[Style] = _styles.primary+ primary_dim: Final[Style] = _styles.primary_dim+ success: Final[Style] = _styles.success+ danger: Final[Style] = _styles.danger+ warning: Final[Style] = _styles.warning+ info: Final[Style] = _styles.info+ muted: Final[Style] = _styles.muted+ bold: Final[Style] = _styles.bold+ label: Final[Style] = _styles.label+ accent_bg: Final[Style] = _styles.accent_bg++ # Convenience aliases used by intro / stream+ brand_hex: Final[str] = BRAND_ORANGE_DARK if _dark else BRAND_ORANGE_LIGHT+++__all__ = [+ "Theme",+ "get_console",+ "is_dark",+ "BRAND_ORANGE_LIGHT",+ "BRAND_ORANGE_DARK",+]diff --git a/agent/cli/utils/__init__.py b/agent/cli/utils/__init__.pynew file mode 100644index 000000000..e785088e8--- /dev/null+++ b/agent/cli/utils/__init__.py@@ -0,0 +1,16 @@+"""Small, pure helpers shared across CLI components.++Everything here is stateless and side-effect free — safe to import from any+module in ``agent/cli``. Larger or stateful helpers belong in their own module+(see ``cli/stream.py`` for the streaming renderer).+"""++from cli.utils.format import abbreviate_num, format_duration, format_tokens+from cli.utils.thinking_verbs import pick_thinking_verb++__all__ = [+ "abbreviate_num",+ "format_duration",+ "format_tokens",+ "pick_thinking_verb",+]diff --git a/agent/cli/utils/format.py b/agent/cli/utils/format.pynew file mode 100644index 000000000..07985e09d--- /dev/null+++ b/agent/cli/utils/format.py@@ -0,0 +1,157 @@+"""Pure formatting helpers for the CLI surface.++These mirror the formatting conventions used in the web app (see+``frontend/src/lib/format.ts``) so a duration printed in the CLI reads the+same as one printed in the chat bubble:++* ``format_duration(ms_or_s)`` → ``"230ms" | "1.4s" | "4m 12s"``+* ``format_tokens(n)`` → ``"1.2k tokens" | "452 tokens"``+* ``abbreviate_num(n)`` → ``"$0.003" | "12.4M" | "452"``++All functions are pure and tolerate ``None`` / negative inputs so callers can+hand them raw counter values without pre-validation.+"""++from __future__ import annotations++from typing import Union++Number = Union[int, float]+++# ---------------------------------------------------------------------------+# Duration+# ---------------------------------------------------------------------------+++def format_duration(value: Number | None, *, unit: str = "ms") -> str:+ """Render a duration as a short, human-readable string.++ Args:+ value: Numeric duration. Treated as milliseconds by default — this+ matches the rest of the codebase (tool callbacks, ``elapsed_ms``+ in ``cli/_legacy.py``, the spinner clock). Pass ``unit="s"`` if+ you already have seconds.+ unit: Either ``"ms"`` (default) or ``"s"``.++ Returns:+ Compact label, e.g. ``"230ms"``, ``"1.4s"``, ``"2m 05s"``. ``None``+ and negative values render as ``"—"``.+ """++ if value is None:+ return "—"+ try:+ v = float(value)+ except (TypeError, ValueError):+ return "—"+ if v < 0:+ return "—"++ if unit == "s":+ seconds = v+ elif unit == "ms":+ seconds = v / 1000.0+ else:+ raise ValueError(f"unit must be 'ms' or 's', got {unit!r}")++ if seconds < 1.0:+ return f"{int(round(seconds * 1000))}ms"+ if seconds < 60:+ # 1.4s, 12.0s — keep one decimal to communicate sub-second jitter+ return f"{seconds:.1f}s"+ minutes, rem = divmod(int(round(seconds)), 60)+ if minutes < 60:+ return f"{minutes}m {rem:02d}s"+ hours, minutes = divmod(minutes, 60)+ return f"{hours}h {minutes:02d}m"+++# ---------------------------------------------------------------------------+# Tokens+# ---------------------------------------------------------------------------+++def format_tokens(count: Number | None) -> str:+ """Render a token count with a thousands-suffix.++ Args:+ count: Integer-ish token count. ``None`` / negatives → ``"0 tokens"``.++ Returns:+ E.g. ``"452 tokens"``, ``"1.2k tokens"``, ``"3.4M tokens"``.+ """++ if count is None:+ return "0 tokens"+ try:+ n = int(count)+ except (TypeError, ValueError):+ return "0 tokens"+ if n <= 0:+ return "0 tokens"++ if n < 1_000:+ return f"{n} tokens"+ if n < 1_000_000:+ return f"{n / 1_000:.1f}k tokens"+ if n < 1_000_000_000:+ return f"{n / 1_000_000:.1f}M tokens"+ return f"{n / 1_000_000_000:.1f}B tokens"+++# ---------------------------------------------------------------------------+# Generic abbreviation (dollars / counts / sizes)+# ---------------------------------------------------------------------------+++def abbreviate_num(value: Number | None, *, currency: str | None = None) -> str:+ """Abbreviate a number with magnitude suffix.++ Use this for status-bar numbers where horizontal space is scarce. Currency+ amounts under ``$1`` keep 3-decimal precision so per-call cost reads+ sensibly (e.g. ``$0.003``).++ Args:+ value: Raw number to abbreviate. ``None`` → ``"—"``.+ currency: Optional currency symbol prefix (e.g. ``"$"``). When set,+ small fractional values keep 3 decimals.++ Returns:+ Abbreviated string. Examples::++ abbreviate_num(452) → "452"+ abbreviate_num(12_400) → "12.4k"+ abbreviate_num(3_200_000) → "3.2M"+ abbreviate_num(0.003, currency="$") → "$0.003"+ abbreviate_num(1.42, currency="$") → "$1.42"+ """++ if value is None:+ return "—"+ try:+ n = float(value)+ except (TypeError, ValueError):+ return "—"++ prefix = currency or ""+ sign = "-" if n < 0 else ""+ n_abs = abs(n)++ if currency is not None and n_abs < 1.0:+ # 3 decimals communicates per-token / per-call cost precision+ return f"{sign}{prefix}{n_abs:.3f}"++ if n_abs < 1_000:+ if currency is not None or not float(n_abs).is_integer():+ return f"{sign}{prefix}{n_abs:.2f}".rstrip("0").rstrip(".")+ return f"{sign}{prefix}{int(n_abs)}"++ for unit, divisor in (("k", 1_000), ("M", 1_000_000), ("B", 1_000_000_000), ("T", 1_000_000_000_000)):+ if n_abs < divisor * 1_000:+ return f"{sign}{prefix}{n_abs / divisor:.1f}{unit}"++ return f"{sign}{prefix}{n_abs:.1e}"+++__all__ = ["format_duration", "format_tokens", "abbreviate_num"]diff --git a/agent/cli/utils/thinking_verbs.py b/agent/cli/utils/thinking_verbs.pynew file mode 100644index 000000000..252086878--- /dev/null+++ b/agent/cli/utils/thinking_verbs.py@@ -0,0 +1,41 @@+"""Random "thinking" verb for the streaming spinner.++The status bar shows a verb while the agent is generating to communicate that+work is happening even before the first token arrives. Borrowed from the+dexter CLI: the verb is rerolled per agent turn so the user perceives variety+across runs rather than a single hard-coded label.+"""++from __future__ import annotations++import random+from typing import Final, Tuple++THINKING_VERBS: Final[Tuple[str, ...]] = (+ "Pondering",+ "Analyzing",+ "Reasoning",+ "Investigating",+ "Synthesizing",+ "Cross-checking",+)+++def pick_thinking_verb(*, seed: int | None = None) -> str:+ """Pick a random verb suffixed with an ellipsis.++ Args:+ seed: Optional deterministic seed (used by tests). When ``None`` the+ module-level :func:`random.choice` is used.++ Returns:+ ``"Pondering…"``, ``"Analyzing…"``, etc.+ """++ if seed is not None:+ rng = random.Random(seed)+ return f"{rng.choice(THINKING_VERBS)}…"+ return f"{random.choice(THINKING_VERBS)}…"+++__all__ = ["pick_thinking_verb", "THINKING_VERBS"]diff --git a/agent/tests/test_cli_interactive.py b/agent/tests/test_cli_interactive.pynew file mode 100644index 000000000..6cc2fe637--- /dev/null+++ b/agent/tests/test_cli_interactive.py@@ -0,0 +1,556 @@+"""Tests for the interactive CLI scaffolding.++Covers:++* Slash-router fuzzy matching and exact lookup+* ``cli.main`` routing helpers (interactive detection, max-iter extraction)+* ``cli.input._has_unbalanced_brackets`` (multi-line Enter semantics)+* The bottom hint-bar renderer+* Tool-event row rendering+* ``cli.input.ctrl_c_within_window`` two-press exit confirmation+"""++from __future__ import annotations++import time+from types import SimpleNamespace+from typing import Any++import pytest+++# ---------------------------------------------------------------------------+# Slash router+# ---------------------------------------------------------------------------+++class TestSlashRouter:+ def test_find_exact_known(self) -> None:+ from cli.commands.slash_router import find_exact++ cmd = find_exact("help")+ assert cmd is not None+ assert cmd.name == "help"++ def test_find_exact_alias(self) -> None:+ from cli.commands.slash_router import find_exact++ cmd = find_exact("q")+ assert cmd is not None and cmd.name == "quit"++ def test_find_exact_unknown_returns_none(self) -> None:+ from cli.commands.slash_router import find_exact++ assert find_exact("definitely-not-a-real-command") is None++ def test_match_prefix(self) -> None:+ from cli.commands.slash_router import match_commands++ matches = [c.name for c in match_commands("/cl")]+ assert "clear" in matches++ def test_match_subsequence(self) -> None:+ from cli.commands.slash_router import match_commands++ # ``hsto`` is a subsequence of ``history``.+ matches = [c.name for c in match_commands("/hsto")]+ assert "history" in matches++ def test_match_returns_empty_for_non_slash(self) -> None:+ from cli.commands.slash_router import match_commands++ assert match_commands("plain text") == []++ def test_handler_module_uses_cli_package(self) -> None:+ from cli.commands.slash_router import SLASH_COMMANDS++ for cmd in SLASH_COMMANDS:+ assert cmd.handler_module.startswith("cli."), (+ f"{cmd.name!r} handler_module {cmd.handler_module!r} should "+ "live under the ``cli`` package root, not ``agent.cli``."+ )+++# ---------------------------------------------------------------------------+# Main routing helpers+# ---------------------------------------------------------------------------+++class TestMainRouting:+ def test_extract_max_iter_space_separated(self) -> None:+ from cli.main import _extract_max_iter++ assert _extract_max_iter(["chat", "--max-iter", "77"], default=50) == 77++ def test_extract_max_iter_equals_separated(self) -> None:+ from cli.main import _extract_max_iter++ assert _extract_max_iter(["--max-iter=12"], default=50) == 12++ def test_extract_max_iter_default(self) -> None:+ from cli.main import _extract_max_iter++ assert _extract_max_iter([], default=42) == 42++ def test_non_interactive_subcommands_route_to_legacy(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from cli.main import _is_interactive_invocation++ # Force a TTY so the only signal that drops the interactive path+ # is the recognised subcommand.+ monkeypatch.setattr("sys.stdin.isatty", lambda: True)+ monkeypatch.setattr("sys.stdout.isatty", lambda: True)+ for sub in ("serve", "run", "list", "mcp", "swarm", "init", "hypothesis"):+ assert _is_interactive_invocation([sub]) is False, sub++ def test_legacy_flags_route_to_legacy(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from cli.main import _is_interactive_invocation++ monkeypatch.setattr("sys.stdin.isatty", lambda: True)+ monkeypatch.setattr("sys.stdout.isatty", lambda: True)+ for flag in ("--list", "--show", "--skills", "--version"):+ assert _is_interactive_invocation([flag]) is False, flag++ def test_chat_is_interactive(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from cli.main import _is_interactive_invocation++ monkeypatch.setattr("sys.stdin.isatty", lambda: True)+ monkeypatch.setattr("sys.stdout.isatty", lambda: True)+ assert _is_interactive_invocation(["chat"]) is True++ def test_empty_argv_is_interactive(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from cli.main import _is_interactive_invocation++ monkeypatch.setattr("sys.stdin.isatty", lambda: True)+ monkeypatch.setattr("sys.stdout.isatty", lambda: True)+ assert _is_interactive_invocation([]) is True++ def test_unknown_positional_routes_to_legacy(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Unknown bare tokens must delegate to legacy so argparse reports the typo."""+ from cli.main import _is_interactive_invocation++ monkeypatch.setattr("sys.stdin.isatty", lambda: True)+ monkeypatch.setattr("sys.stdout.isatty", lambda: True)+ for token in ("foo", "alphazoo", "helpme"):+ assert _is_interactive_invocation([token]) is False, token++ def test_piped_stdin_disables_interactive(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from cli.main import _is_interactive_invocation++ monkeypatch.setattr("sys.stdin.isatty", lambda: False)+ monkeypatch.setattr("sys.stdout.isatty", lambda: True)+ assert _is_interactive_invocation([]) is False++ def test_chat_with_supported_max_iter(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """``chat`` with a parseable --max-iter belongs to the REPL."""+ from cli.main import _is_interactive_invocation++ monkeypatch.setattr("sys.stdin.isatty", lambda: True)+ monkeypatch.setattr("sys.stdout.isatty", lambda: True)+ for argv in (["chat", "--max-iter", "10"], ["chat", "--max-iter=42"]):+ assert _is_interactive_invocation(argv) is True, argv++ def test_chat_help_routes_to_legacy(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """``chat --help`` / ``-h`` must reach legacy argparse for the help screen."""+ from cli.main import _is_interactive_invocation++ monkeypatch.setattr("sys.stdin.isatty", lambda: True)+ monkeypatch.setattr("sys.stdout.isatty", lambda: True)+ for argv in (["chat", "--help"], ["chat", "-h"]):+ assert _is_interactive_invocation(argv) is False, argv++ def test_chat_with_bad_max_iter_routes_to_legacy(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """A non-integer ``--max-iter`` must reach argparse so it can complain."""+ from cli.main import _is_interactive_invocation++ monkeypatch.setattr("sys.stdin.isatty", lambda: True)+ monkeypatch.setattr("sys.stdout.isatty", lambda: True)+ for argv in (["chat", "--max-iter", "bad"], ["chat", "--max-iter=bad"]):+ assert _is_interactive_invocation(argv) is False, argv++ def test_chat_with_extra_positional_routes_to_legacy(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """Extra positionals on ``chat`` are user errors — let argparse say so."""+ from cli.main import _is_interactive_invocation++ monkeypatch.setattr("sys.stdin.isatty", lambda: True)+ monkeypatch.setattr("sys.stdout.isatty", lambda: True)+ for argv in (["chat", "extra"], ["chat", "foo", "bar"]):+ assert _is_interactive_invocation(argv) is False, argv+++# ---------------------------------------------------------------------------+# Main-level dispatch smoke+# ---------------------------------------------------------------------------+++class TestMainDispatch:+ """``cli.main(argv)`` must hand non-interactive argv to ``_legacy.main`` verbatim.++ These don't exercise the real legacy handlers (they would spin up+ servers, hit the network, or block on prompts). Instead they patch+ ``_legacy.main`` and assert ``cli.main`` forwards the exact argv.+ """++ def test_cmd_wrappers_propagate_package_monkeypatch(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Patching ``cli.RUNS_DIR`` must reach ``_legacy`` before any cmd_* runs.++ Regression for the partial-sync trap: before this wrapper, only+ ``cmd_init`` triggered the sync, so ``patch.object(cli, "RUNS_DIR",+ tmp); cli.cmd_list()`` silently read the unpatched ``_legacy.RUNS_DIR``.+ """+ from pathlib import Path++ import cli++ captured: dict[str, Any] = {}++ def fake_cmd_list(*args, **kwargs): # noqa: ANN001+ captured["runs_dir"] = cli._legacy.RUNS_DIR+ return 0++ monkeypatch.setattr(cli._legacy, "cmd_list", fake_cmd_list)+ monkeypatch.setattr(cli, "RUNS_DIR", Path("/tmp/regression-runs-dir"))++ cli.cmd_list(20)++ assert captured.get("runs_dir") == Path("/tmp/regression-runs-dir")++ @pytest.mark.parametrize(+ "argv",+ [+ ["serve", "--port", "8901"],+ ["run", "-p", "what is AAPL"],+ ["list", "--limit", "5"],+ ["show", "abc123"],+ ["hypothesis", "list"],+ ["alpha", "list"],+ ["memory", "show", "feedback-research-first"],+ ["provider", "login", "openai-codex"],+ ["init"],+ ["--list"],+ ["--show", "abc123"],+ ["--version"],+ ["--help"],+ ["chat", "--help"],+ ["chat", "--max-iter", "bad"],+ ["chat", "extra"],+ ],+ )+ def test_non_interactive_argv_forwarded_to_legacy(+ self, monkeypatch: pytest.MonkeyPatch, argv: list[str]+ ) -> None:+ """Every non-REPL argv shape must reach ``_legacy.main`` untouched."""+ from cli.main import main as cli_main_fn++ # Force a TTY so the only reason these argv shapes don't enter the+ # REPL is the chat-gate / flag / subcommand routing.+ monkeypatch.setattr("sys.stdin.isatty", lambda: True)+ monkeypatch.setattr("sys.stdout.isatty", lambda: True)++ captured: dict[str, Any] = {}++ def fake_legacy_main(passed_argv): # noqa: ANN001+ captured["argv"] = list(passed_argv)+ return 0++ from cli import _legacy++ monkeypatch.setattr(_legacy, "main", fake_legacy_main)++ rc = cli_main_fn(argv)++ assert rc == 0, argv+ assert captured.get("argv") == argv, (argv, captured)+++# ---------------------------------------------------------------------------+# Input layer+# ---------------------------------------------------------------------------+++class TestInputHelpers:+ def test_balanced_brackets(self) -> None:+ from cli.input import _has_unbalanced_brackets++ assert _has_unbalanced_brackets("hello world") is False+ assert _has_unbalanced_brackets("foo(bar)") is False+ assert _has_unbalanced_brackets("[1,2,{3:4}]") is False++ def test_unbalanced_open(self) -> None:+ from cli.input import _has_unbalanced_brackets++ assert _has_unbalanced_brackets("def f(x:\n return") is True++ def test_strings_ignored(self) -> None:+ from cli.input import _has_unbalanced_brackets++ # The unbalanced ``(`` sits inside a string literal.+ assert _has_unbalanced_brackets('print("a (b c")') is False++ def test_strip_surrogates_keeps_plain_text(self) -> None:+ from cli.input import _strip_surrogates++ assert _strip_surrogates("hello") == "hello"++ def test_strip_surrogates_drops_lone_half(self) -> None:+ from cli.input import _strip_surrogates++ # \ud83d alone is a lone high surrogate.+ cleaned = _strip_surrogates("a\ud83db")+ assert "\ud83d" not in cleaned+ assert cleaned.startswith("a") and cleaned.endswith("b")++ def test_ctrl_c_within_window_returns_false_when_unset(self) -> None:+ from cli.input import ctrl_c_within_window++ session = SimpleNamespace()+ assert ctrl_c_within_window(session) is False++ def test_ctrl_c_within_window_uses_state(self) -> None:+ from cli.input import ctrl_c_within_window++ state = SimpleNamespace(last_press_ts=time.monotonic())+ session = SimpleNamespace(vibe_ctrl_c_state=state)+ assert ctrl_c_within_window(session, window_sec=2.0) is True++ def test_ctrl_c_window_expires(self) -> None:+ from cli.input import ctrl_c_within_window++ state = SimpleNamespace(last_press_ts=time.monotonic() - 10.0)+ session = SimpleNamespace(vibe_ctrl_c_state=state)+ assert ctrl_c_within_window(session, window_sec=2.0) is False+++# ---------------------------------------------------------------------------+# Ctrl+C two-press regression (Parcel I, Bug 1)+# ---------------------------------------------------------------------------+++class TestCtrlCTwoPress:+ """Regression coverage for the broken first-press-exits behaviour.++ Before the fix in Parcel I the keybinding stamped ``last_press_ts``+ on every press and ``ctrl_c_within_window`` computed+ ``now - last_press_ts`` — yielding ~0 on the first press, so the+ outer loop exited immediately. These tests pin the corrected+ two-timestamp design in place.+ """++ def test_first_press_returns_false(self) -> None:+ from cli.input import _CtrlCState++ state = _CtrlCState()+ # First press → no prior press → must report "not in window".+ assert state.record_press_and_check_window(window_sec=2.0) is False++ def test_second_press_within_window_returns_true(self) -> None:+ from cli.input import _CtrlCState++ state = _CtrlCState()+ state.record_press_and_check_window(window_sec=2.0) # first press+ # Second press immediately after → inside the 2 s window.+ assert state.record_press_and_check_window(window_sec=2.0) is True++ def test_second_press_after_window_returns_false(self) -> None:+ from cli.input import _CtrlCState++ state = _CtrlCState()+ # Simulate a first press well in the past.+ state.previous_press_ts = time.monotonic() - 3.0+ # This press is the "second" one, but it lands outside the window+ # — must be treated as a fresh first press for the next round.+ assert state.record_press_and_check_window(window_sec=2.0) is False++ def test_window_check_reads_cached_decision(self) -> None:+ from cli.input import _CtrlCState, ctrl_c_within_window++ state = _CtrlCState()+ # Simulate the keybinding's press-time decision.+ state.record_press_and_check_window(window_sec=2.0) # first → False+ session = SimpleNamespace(vibe_ctrl_c_state=state)+ assert ctrl_c_within_window(session, window_sec=2.0) is False++ state.record_press_and_check_window(window_sec=2.0) # second → True+ assert ctrl_c_within_window(session, window_sec=2.0) is True+++# ---------------------------------------------------------------------------+# Slash typo suggestions (Parcel I, Bug 3)+# ---------------------------------------------------------------------------+++class TestSlashTypoSuggestions:+ """``/historu`` and ``/jurnal`` must surface ``history`` / ``journal``."""++ def test_single_char_typo_history(self) -> None:+ from cli.main import _suggest_commands++ assert "history" in _suggest_commands("historu")++ def test_single_char_typo_journal(self) -> None:+ from cli.main import _suggest_commands++ assert "journal" in _suggest_commands("jurnal")++ def test_close_to_quit(self) -> None:+ from cli.main import _suggest_commands++ # ``quti`` is a transposition of ``quit`` — subsequence scoring+ # misses this; difflib edit-distance catches it.+ assert "quit" in _suggest_commands("quti")++ def test_no_match_returns_empty(self) -> None:+ from cli.main import _suggest_commands++ suggestions = _suggest_commands("xyzqwerty")+ # Either empty, or no obviously-wrong entry. The contract is+ # "never raises" and "respects the 3-entry cap".+ assert len(suggestions) <= 3+++# ---------------------------------------------------------------------------+# /journal /shadow /debug behaviour (Parcel I, Bug 4)+# ---------------------------------------------------------------------------+++class TestChatCommandsAreActionable:+ """``/journal`` and ``/shadow`` queue real prompts, not "Coming soon"."""++ def test_journal_with_path_queues_prompt(self) -> None:+ from cli.commands.chat import cmd_journal++ ctx = SimpleNamespace(pending_prompt=None)+ rc = cmd_journal(ctx, "trades.csv")+ assert rc == 0+ assert ctx.pending_prompt is not None+ assert "trade journal" in ctx.pending_prompt.lower()+ assert "trades.csv" in ctx.pending_prompt++ def test_journal_without_path_prints_usage(self) -> None:+ from cli.commands.chat import cmd_journal++ ctx = SimpleNamespace(pending_prompt=None)+ rc = cmd_journal(ctx)+ # No prompt queued (no path), but the command must not crash and+ # must not silently swallow the request.+ assert rc == 0+ assert ctx.pending_prompt is None++ def test_shadow_without_args_opens_dashboard(self) -> None:+ from cli.commands.chat import cmd_shadow++ ctx = SimpleNamespace(pending_prompt=None)+ rc = cmd_shadow(ctx)+ assert rc == 0+ assert ctx.pending_prompt is not None+ assert "shadow" in ctx.pending_prompt.lower()++ def test_shadow_with_path_trains(self) -> None:+ from cli.commands.chat import cmd_shadow++ ctx = SimpleNamespace(pending_prompt=None)+ rc = cmd_shadow(ctx, "trades.csv")+ assert rc == 0+ assert ctx.pending_prompt is not None+ assert "trades.csv" in ctx.pending_prompt+ assert "shadow" in ctx.pending_prompt.lower()++ def test_debug_toggles_flag(self) -> None:+ from cli.commands.chat import cmd_debug++ ctx = SimpleNamespace(debug=False)+ cmd_debug(ctx)+ assert ctx.debug is True+ cmd_debug(ctx)+ assert ctx.debug is False+++# ---------------------------------------------------------------------------+# Components+# ---------------------------------------------------------------------------+++class TestHintBar:+ def test_left_only(self) -> None:+ from cli.components.hint_bar import render_hint_bar++ bar = render_hint_bar("hello", width=20)+ assert "hello" in bar.plain++ def test_left_right_fit(self) -> None:+ from cli.components.hint_bar import render_hint_bar++ bar = render_hint_bar("L", "R", width=10).plain+ assert bar.startswith("L") and bar.endswith("R")++ def test_truncation_preserves_right(self) -> None:+ from cli.components.hint_bar import render_hint_bar++ bar = render_hint_bar("a very long left segment", "Ctrl+C", width=20).plain+ assert bar.endswith("Ctrl+C")+++class TestToolEventRender:+ def test_running_status(self) -> None:+ from cli.components.tool_event import render_tool_event++ text = render_tool_event("get_financials", {"query": "AAPL"}, status="running")+ assert "Financials" in text.plain+ assert "AAPL" in text.plain++ def test_ok_with_duration(self) -> None:+ from cli.components.tool_event import render_tool_event++ text = render_tool_event(+ "run_backtest",+ {"symbol": "BTC"},+ status="ok",+ duration_ms=1400,+ )+ # 1400 ms ~= 1.4s in the shared formatter.+ assert "1.4s" in text.plain++ def test_error_renders(self) -> None:+ from cli.components.tool_event import render_tool_event++ text = render_tool_event("load_skill", {"name": "x"}, status="error")+ assert "x" in text.plain++ def test_unknown_status_degrades(self) -> None:+ from cli.components.tool_event import render_tool_event++ # Unknown statuses should not raise — they degrade to "running".+ text = render_tool_event("foo", None, status="bogus") # type: ignore[arg-type]+ assert "Foo" in text.plain+++# ---------------------------------------------------------------------------+# Working indicator+# ---------------------------------------------------------------------------+++class TestWorkingIndicator:+ def test_pick_verb_returns_string(self) -> None:+ from cli.components.working_indicator import _pick_verb++ verb = _pick_verb()+ assert isinstance(verb, str) and verb+++# ---------------------------------------------------------------------------+# Package compatibility surface+# ---------------------------------------------------------------------------+++class TestPackageCompat:+ def test_cli_reexports_legacy_helpers(self) -> None:+ import cli++ # Historically the tests reached into ``cli._render_env_content``+ # and ``cli.cmd_memory_list``; the package keeps re-exporting+ # them so downstream callers stay green.+ assert hasattr(cli, "_render_env_content")+ assert hasattr(cli, "cmd_memory_list")+ assert hasattr(cli, "cmd_init")+ assert callable(cli.main)diff --git a/agent/tests/test_spa_deep_link.py b/agent/tests/test_spa_deep_link.pynew file mode 100644index 000000000..2645d09f7--- /dev/null+++ b/agent/tests/test_spa_deep_link.py@@ -0,0 +1,50 @@+"""Regression tests for the SPA deep-link middleware in ``api_server``.++The middleware intercepts browser navigation (``Accept: text/html``) to+SPA pages that share a path with an API endpoint, serving the SPA shell+instead. It must NOT intercept API-only paths even when called with a+text/html accept header — the matcher is intentionally narrow so things+like ``/runs/{id}/code`` and ``/runs/{id}/pine`` keep returning the+correct API response.+"""++from __future__ import annotations++import pytest+++class TestSpaHtmlRouteMatcher:+ """Pin the matcher used by ``_spa_html_deep_link_fallback`` middleware."""++ @pytest.mark.parametrize(+ "path",+ [+ "/correlation", # Correlation page+ "/runs/abc", # RunDetail (no trailing slash)+ "/runs/abc-123", # RunDetail with dashes+ "/runs/abc/", # RunDetail (trailing slash)+ ],+ )+ def test_spa_pages_match(self, path: str) -> None:+ from api_server import _is_spa_html_route++ assert _is_spa_html_route(path) is True, path++ @pytest.mark.parametrize(+ "path",+ [+ "/runs", # collection endpoint (API only)+ "/runs/abc/code", # API-only — must NOT be hijacked+ "/runs/abc/pine", # API-only — must NOT be hijacked+ "/runs/abc/code/",+ "/runs/abc/foo/bar", # deeper nested — defensive+ "/sessions/xyz", # different namespace+ "/api",+ "/skills",+ "/correlation/extra", # only the bare /correlation page exists+ ],+ )+ def test_api_only_paths_do_not_match(self, path: str) -> None:+ from api_server import _is_spa_html_route++ assert _is_spa_html_route(path) is False, pathdiff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex 600e86bfb..1548a0bad 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -3,21 +3,27 @@ import react from "@vitejs/plugin-react";import path from "path";const PROXY_PATHS = [- "/runs","/sessions","/swarm/presets","/swarm/runs","/settings/llm","/settings/data-sources",- "/correlation","/upload","/shadow-reports",- "/alpha",];export default defineConfig(({ mode }) => {const env = loadEnv(mode, process.cwd(), "");const apiTarget = env.VITE_API_URL || "http://localhost:8899";+ const apiProxy = { target: apiTarget, changeOrigin: true };+ const apiProxyWithHtmlFallback = {+ ...apiProxy,+ bypass(req: { headers: { accept?: string } }) {+ if (req.headers.accept?.includes("text/html")) {+ return "/index.html";+ }+ },+ };return {plugins: [react()],@@ -26,9 +32,17 @@ export default defineConfig(({ mode }) => {},server: {port: 5899,- proxy: Object.fromEntries(- PROXY_PATHS.map((p) => [p, { target: apiTarget, changeOrigin: true }]),- ),+ proxy: {+ ...Object.fromEntries(PROXY_PATHS.map((p) => [p, apiProxy])),+ // SPA RunDetail page — only the two-segment ``/runs/{id}``+ // form should fall back to ``index.html`` on browser navigation.+ // ``/runs/{id}/code`` and ``/runs/{id}/pine`` are API-only and+ // must keep proxying to the backend even when Accept is text/html.+ "^/runs/[^/]+/?$": apiProxyWithHtmlFallback,+ "/runs": apiProxy,+ "/correlation": apiProxyWithHtmlFallback,+ "^/alpha(?:/|$)": apiProxy,+ },},build: {rollupOptions: {diff --git a/pyproject.toml b/pyproject.tomlindex 0572105f8..95a06e4b2 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -70,11 +70,11 @@ vibe-trading-mcp = "mcp_server:main"[tool.setuptools]package-dir = {"" = "agent"}-py-modules = ["cli", "api_server", "mcp_server"]+py-modules = ["api_server", "mcp_server"][tool.setuptools.packages.find]where = ["agent"]-include = ["src*", "backtest*"]+include = ["src*", "backtest*", "cli*"][tool.setuptools.package-data]"src" = [diff --git a/scripts/dev b/scripts/devindex e375db2f9..9bd145284 100644--- a/scripts/dev+++ b/scripts/dev@@ -130,7 +130,7 @@ wait_for_url() {}cmd_up() {- start_service backend env PYTHONPATH="$ROOT/agent" "$PYTHON_BIN" "$ROOT/agent/cli.py" serve \+ start_service backend env PYTHONPATH="$ROOT/agent" "$PYTHON_BIN" -c 'import cli, sys; raise SystemExit(cli.main(sys.argv[1:]))' serve \--host "$BACKEND_HOST" \--port "$BACKEND_PORT"start_service frontend bash -lc '@@ -159,7 +159,7 @@ cmd_restart() {case "$service" inbackend)stop_service backend- start_service backend env PYTHONPATH="$ROOT/agent" "$PYTHON_BIN" "$ROOT/agent/cli.py" serve \+ start_service backend env PYTHONPATH="$ROOT/agent" "$PYTHON_BIN" -c 'import cli, sys; raise SystemExit(cli.main(sys.argv[1:]))' serve \--host "$BACKEND_HOST" \--port "$BACKEND_PORT"wait_for_url backend "http://127.0.0.1:$BACKEND_PORT/health" 30