"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Harden API and tool security defaults
Haozhe Wu9454d4a27a76
diff --git a/Dockerfile b/Dockerfileindex 64ebd0980..4a84ed5a6 100644--- a/Dockerfile+++ b/Dockerfile@@ -35,6 +35,13 @@ COPY --from=frontend-build /app/frontend/dist frontend/dist# Install CLI entrypointRUN pip install --no-cache-dir -e .+# Runtime should not run as root. Keep writable app data directories owned by+# the service user so named Docker volumes inherit usable permissions.+RUN useradd --create-home --shell /usr/sbin/nologin vibe \+ && mkdir -p agent/runs agent/sessions agent/uploads agent/.swarm/runs \+ && chown -R vibe:vibe /app+USER vibe+# Default portEXPOSE 8899diff --git a/README.md b/README.mdindex 2ded97582..2d13aeb0c 100644--- a/README.md+++ b/README.md@@ -51,6 +51,7 @@## 📰 News+- **2026-05-03** 🛡️ **Security hardening patch**: Tightens default API authentication for non-local deployments, protects sensitive run/session/swarm reads, restricts upload and local file-reading boundaries, gates shell-capable tools by entry point, validates generated strategy loading before import, and runs the Docker image as a non-root user with a localhost-only published port by default. Local CLI and localhost Web UI workflows remain low-friction; remote API/Web deployments should set `API_AUTH_KEY`.- **2026-05-02** 🧭 **Dividend analysis + sharper roadmap**: Added the `dividend-analysis` skill for income stocks, payout sustainability, dividend growth, shareholder yield, ex-dividend mechanics, and yield-trap checks, pinned by bundled-skill regression tests. The public roadmap now focuses on upcoming work: Research Autopilot, Data Bridge, Options Lab, Portfolio Studio, Alpha Zoo, Research Delivery, Trust Layer, and Community sharing.- **2026-05-01** 🔥 **Correlation heatmap + OpenAI Codex OAuth + A-share pre-ST filter**: New correlation dashboard/API computes rolling return correlations and renders an ECharts heatmap for portfolio and symbol analysis ([#64](https://github.com/HKUDS/Vibe-Trading/pull/64)). OpenAI Codex provider support now uses ChatGPT OAuth via `vibe-trading provider login openai-codex`, with Settings metadata and adapter regression tests ([#65](https://github.com/HKUDS/Vibe-Trading/pull/65)). Added and hardened the `ashare-pre-st-filter` skill for A-share ST/*ST risk screening, including Sina penalty relevance filtering so securities-account mentions do not inflate E2 counts ([#63](https://github.com/HKUDS/Vibe-Trading/pull/63)).- **2026-04-30** ⚙️ **Web UI Settings + validation CLI hardening**: New Settings page for LLM provider/model, base URL, reasoning effort, and data source credentials, backed by local/auth-protected settings APIs and data-driven provider metadata ([#57](https://github.com/HKUDS/Vibe-Trading/pull/57)). Also hardens `python -m backtest.validation <run_dir>` so missing, blank, malformed, non-existent, and non-directory inputs fail with clear operator-facing messages before validation starts ([#60](https://github.com/HKUDS/Vibe-Trading/pull/60)).@@ -263,6 +264,8 @@ docker compose up --buildOpen `http://localhost:8899`. Backend + frontend in one container.+Docker publishes the backend on `127.0.0.1:8899` by default and runs the app as a non-root container user. If you intentionally expose the API beyond your own machine, set a strong `API_AUTH_KEY` and send `Authorization: Bearer <key>` from clients.+### Path B: Local install```bash@@ -327,6 +330,10 @@ Copy `agent/.env.example` to `agent/.env` and uncomment the provider block you w| `LANGCHAIN_MODEL_NAME` | Yes | Model name (e.g. `deepseek/deepseek-v3.2`) || `TUSHARE_TOKEN` | No | Tushare Pro token for A-share data (falls back to AKShare) || `TIMEOUT_SECONDS` | No | LLM call timeout, default 120s |+| `API_AUTH_KEY` | Recommended for network deployments | Bearer token required when the API is reachable from non-local clients |+| `VIBE_TRADING_ENABLE_SHELL_TOOLS` | No | Explicit opt-in for shell-capable tools in remote API/MCP-SSE style deployments |+| `VIBE_TRADING_ALLOWED_FILE_ROOTS` | No | Extra comma-separated roots for document and broker-journal imports |+| `VIBE_TRADING_ALLOWED_RUN_ROOTS` | No | Extra comma-separated roots for generated-code run directories |<sub>* Ollama does not require an API key. OpenAI Codex uses ChatGPT OAuth and stores tokens via `oauth-cli-kit`, not in `agent/.env`.</sub>@@ -502,6 +509,12 @@ vibe-trading serve --port 8899Interactive docs: `http://localhost:8899/docs`+### Security defaults++For localhost development, `vibe-trading serve` keeps the browser workflow simple. For any non-local client, sensitive API endpoints require `API_AUTH_KEY`; use `Authorization: Bearer <key>` for JSON/upload requests. Browser EventSource streams are handled by the Web UI after you enter the same key once in Settings.++Shell-capable tools are available to local CLI and trusted localhost workflows, but are not exposed to remote API sessions unless you explicitly set `VIBE_TRADING_ENABLE_SHELL_TOOLS=1`. Document and journal readers are limited to upload/import roots by default; place files under `agent/uploads`, `agent/runs`, `./uploads`, `./data`, `~/.vibe-trading/uploads`, or `~/.vibe-trading/imports`, or add a dedicated directory through `VIBE_TRADING_ALLOWED_FILE_ROOTS`.+### Web UI SettingsThe Web UI Settings page lets local users update the LLM provider/model, base URL, generation parameters, reasoning effort, and optional market data credentials such as the Tushare token. Settings are persisted to `agent/.env`; provider defaults are loaded from `agent/src/providers/llm_providers.json`.diff --git a/README_ar.md b/README_ar.mdindex 82c79f028..219d5bd59 100644--- a/README_ar.md+++ b/README_ar.md@@ -51,6 +51,7 @@## 📰 أحدث الأخبار+- **2026-05-03** 🛡️ **تصحيح لتعزيز الأمان**: يشدد المصادقة الافتراضية للـ API في النشر غير المحلي، ويحمي قراءات run/session/swarm الحساسة، ويقيّد حدود الرفع وقراءة الملفات المحلية، ويتحكم في أدوات shell بحسب نقطة الدخول، ويتحقق من الاستراتيجيات المولدة قبل الاستيراد، ويجعل صورة Docker تعمل افتراضياً كمستخدم غير root وبمنفذ منشور على localhost فقط. تبقى تجربة CLI وWeb UI المحلي منخفضة الاحتكاك؛ ويجب على نشر API/Web البعيد ضبط `API_AUTH_KEY`.- **2026-05-02** 🧭 **تحليل التوزيعات + خارطة طريق أوضح**: تمت إضافة مهارة `dividend-analysis` لأسهم الدخل، واستدامة التوزيعات، ونمو التوزيعات، وعائد المساهمين، وآليات تاريخ الاستحقاق السابق، وفحص فخاخ العائد المرتفع، مع تثبيتها باختبارات انحدار للمهارات المضمنة. تركز خارطة الطريق العامة الآن على Research Autopilot وData Bridge وOptions Lab وPortfolio Studio وAlpha Zoo وResearch Delivery وTrust Layer ومشاركة Community.- **2026-05-01** 🔥 **خريطة ارتباط حرارية + OpenAI Codex OAuth + مرشح pre-ST لأسهم A**: لوحة/API ارتباط جديدة تحسب ارتباطات العوائد المتحركة وتعرضها كخريطة حرارية ECharts لتحليل المحافظ والرموز ([#64](https://github.com/HKUDS/Vibe-Trading/pull/64)). مزود OpenAI Codex يدعم الآن ChatGPT OAuth عبر `vibe-trading provider login openai-codex`، مع بيانات Settings واختبارات انحدار للمحوّل ([#65](https://github.com/HKUDS/Vibe-Trading/pull/65)). تمت إضافة وتعزيز مهارة `ashare-pre-st-filter` لفحص مخاطر ST/*ST في أسهم A، مع فلترة صلة عقوبات Sina حتى لا تضخم إشارات قوائم حسابات الأوراق المالية عدّادات E2 ([#63](https://github.com/HKUDS/Vibe-Trading/pull/63)).- **2026-04-30** ⚙️ **إعدادات Web UI + تعزيز validation CLI**: تمت إضافة صفحة Settings لإعداد LLM provider/model وBase URL وreasoning effort وبيانات اعتماد مصادر البيانات محلياً. واجهات settings API محمية الآن عبر local/auth، كما أصبحت بيانات مزودي النماذج إعدادات مدفوعة بالبيانات ([#57](https://github.com/HKUDS/Vibe-Trading/pull/57)). كذلك تم تعزيز `python -m backtest.validation <run_dir>` لرفض غياب الوسيط، والمسار الفارغ، والمسار غير الصالح، والمسار غير الموجود، والمسار الذي ليس دليلاً برسائل واضحة قبل بدء التحقق ([#60](https://github.com/HKUDS/Vibe-Trading/pull/60)).@@ -262,6 +263,8 @@ docker compose up --buildافتح `http://localhost:8899`. الخلفية + الواجهة الأمامية في حاوية واحدة.+ينشر Docker الخلفية افتراضياً على `127.0.0.1:8899` فقط، ويشغل التطبيق كمستخدم حاوية غير root. إذا كنت تنوي تعريض الـ API خارج جهازك، فاضبط `API_AUTH_KEY` قوياً وأرسل `Authorization: Bearer <key>` من العملاء.+### المسار B: التثبيت المحلي```bash@@ -326,6 +329,10 @@ npx clawhub@latest install vibe-trading --force| `LANGCHAIN_MODEL_NAME` | نعم | اسم النموذج (مثلاً `deepseek/deepseek-v3.2`) || `TUSHARE_TOKEN` | لا | رمز Tushare Pro لبيانات أسهم A (بديل AKShare) || `TIMEOUT_SECONDS` | لا | مهلة استدعاء نموذج اللغة، الافتراضي 120 ثانية |+| `API_AUTH_KEY` | موصى به للنشر الشبكي | Bearer token مطلوب عندما يكون الـ API قابلاً للوصول من عملاء غير محليين |+| `VIBE_TRADING_ENABLE_SHELL_TOOLS` | لا | تفعيل صريح لأدوات shell في نشر API / MCP-SSE البعيد |+| `VIBE_TRADING_ALLOWED_FILE_ROOTS` | لا | جذور إضافية مفصولة بفواصل لاستيراد المستندات وسجلات الوسطاء |+| `VIBE_TRADING_ALLOWED_RUN_ROOTS` | لا | جذور إضافية مفصولة بفواصل لأدلة تشغيل الكود المولد |<sub>* Ollama لا يتطلب مفتاح API.</sub>@@ -431,6 +438,12 @@ vibe-trading serve --port 8899توثيق تفاعلي: `http://localhost:8899/docs`+### الإعدادات الأمنية الافتراضية++في التطوير المحلي، يحافظ `vibe-trading serve` على بساطة سير عمل المتصفح. أي عميل غير محلي يصل إلى واجهات API الحساسة يحتاج إلى `API_AUTH_KEY`؛ استخدم `Authorization: Bearer <key>` لطلبات JSON والرفع. يتعامل Web UI مع بث EventSource بعد إدخال المفتاح نفسه مرة واحدة في Settings.++أدوات shell متاحة للـ CLI المحلي وسير عمل localhost الموثوق، لكنها لا تُعرض افتراضياً لجلسات API البعيدة إلا إذا ضبطت صراحة `VIBE_TRADING_ENABLE_SHELL_TOOLS=1`. قارئات المستندات وسجلات التداول مقيدة افتراضياً بجذور الرفع/الاستيراد؛ ضع الملفات تحت `agent/uploads` أو `agent/runs` أو `./uploads` أو `./data` أو `~/.vibe-trading/uploads` أو `~/.vibe-trading/imports`، أو أضف دليلاً مخصصاً عبر `VIBE_TRADING_ALLOWED_FILE_ROOTS`.+### إعدادات Web UIتتيح صفحة Settings في واجهة الويب للمستخدمين المحليين تحديث LLM provider/model وBase URL ومعلمات التوليد وreasoning effort وبيانات اعتماد مصادر السوق الاختيارية مثل رمز Tushare. تُحفظ الإعدادات في `agent/.env`، وتُحمّل القيم الافتراضية للمزودين من `agent/src/providers/llm_providers.json`.diff --git a/README_ja.md b/README_ja.mdindex 2fd0562d8..f573a9999 100644--- a/README_ja.md+++ b/README_ja.md@@ -51,6 +51,7 @@## 📰 ニュース+- **2026-05-03** 🛡️ **セキュリティハードニングパッチ**: 非ローカルデプロイ向けの既定API認証を強化し、機密性の高いrun/session/swarm読み取りを保護、アップロードとローカルファイル読み取り境界を制限、shell系ツールをエントリーポイント別に制御、生成戦略をimport前に検証し、Dockerイメージは既定で非rootユーザーかつlocalhost限定ポート公開で動作します。CLIとlocalhost Web UIは低摩擦のままです。リモートAPI/Webデプロイでは`API_AUTH_KEY`を設定してください。- **2026-05-02** 🧭 **配当分析 + ロードマップ刷新**: インカム株、配当の持続性、増配、株主還元利回り、権利落ちメカニクス、利回りの罠チェックに対応する `dividend-analysis` スキルを追加し、バンドルスキル回帰テストで固定しました。公開ロードマップは Research Autopilot、Data Bridge、Options Lab、Portfolio Studio、Alpha Zoo、Research Delivery、Trust Layer、Community 共有に絞りました。- **2026-05-01** 🔥 **相関ヒートマップ + OpenAI Codex OAuth + A株 pre-ST フィルター**: 新しい相関ダッシュボード/APIでローリングリターン相関を計算し、ポートフォリオや銘柄分析向けに ECharts ヒートマップで可視化します([#64](https://github.com/HKUDS/Vibe-Trading/pull/64))。OpenAI Codex provider は `vibe-trading provider login openai-codex` による ChatGPT OAuth に対応し、Settings メタデータとアダプター回帰テストも追加([#65](https://github.com/HKUDS/Vibe-Trading/pull/65))。A株の ST/*ST リスクスクリーニング用 `ashare-pre-st-filter` スキルを追加・強化し、Sina 処分公告の関連性フィルターにより証券口座リスト内の言及が E2 回数を水増ししないようにしました([#63](https://github.com/HKUDS/Vibe-Trading/pull/63))。- **2026-04-30** ⚙️ **Web UI設定 + validation CLI強化**: LLM provider/model、Base URL、reasoning effort、データソース認証情報をローカルで設定できる Settings ページを追加。settings API は local/auth で保護され、provider メタデータもデータ駆動設定に移行([#57](https://github.com/HKUDS/Vibe-Trading/pull/57))。さらに `python -m backtest.validation <run_dir>` を強化し、引数なし・空パス・不正パス・存在しないパス・ディレクトリでないパスを検証開始前に分かりやすく失敗させます([#60](https://github.com/HKUDS/Vibe-Trading/pull/60))。@@ -260,6 +261,8 @@ docker compose up --build`http://localhost:8899`を開きます。バックエンドとフロントエンドを1コンテナで提供。+Dockerは既定でバックエンドを`127.0.0.1:8899`にのみ公開し、非rootコンテナユーザーでアプリを実行します。APIを自分のマシン外へ意図的に公開する場合は、強い`API_AUTH_KEY`を設定し、クライアントから`Authorization: Bearer <key>`を送ってください。+### Path B: ローカルインストール```bash@@ -324,6 +327,10 @@ npx clawhub@latest install vibe-trading --force| `LANGCHAIN_MODEL_NAME` | Yes | モデル名(例: `deepseek/deepseek-v3.2`) || `TUSHARE_TOKEN` | No | A株データ用Tushare Proトークン(AKShareにフォールバック) || `TIMEOUT_SECONDS` | No | LLM呼び出しタイムアウト(既定120s) |+| `API_AUTH_KEY` | ネットワークデプロイでは推奨 | APIが非ローカルクライアントから到達可能な場合に必要なBearer token |+| `VIBE_TRADING_ENABLE_SHELL_TOOLS` | No | リモートAPI / MCP-SSE系デプロイでshell系ツールを明示的に有効化 |+| `VIBE_TRADING_ALLOWED_FILE_ROOTS` | No | 文書・ブローカー取引明細インポート用の追加ルート(カンマ区切り) |+| `VIBE_TRADING_ALLOWED_RUN_ROOTS` | No | 生成コードrunディレクトリ用の追加ルート(カンマ区切り) |<sub>* OllamaはAPIキー不要。</sub>@@ -428,6 +435,12 @@ vibe-trading serve --port 8899インタラクティブドキュメント: `http://localhost:8899/docs`+### セキュリティ既定値++localhost開発では、`vibe-trading serve`はブラウザワークフローをシンプルに保ちます。非ローカルクライアントから機密APIへアクセスする場合は`API_AUTH_KEY`が必要です。JSON/アップロードリクエストでは`Authorization: Bearer <key>`を使ってください。ブラウザEventSourceストリームは、Web UIのSettingsで同じキーを一度入力すると処理されます。++shell系ツールはローカルCLIと信頼済みlocalhostワークフローでは利用できますが、リモートAPIセッションには既定で公開されません。必要な場合のみ`VIBE_TRADING_ENABLE_SHELL_TOOLS=1`を明示的に設定してください。文書・取引明細リーダーは既定でアップロード/インポートルートに制限されます。ファイルは`agent/uploads`、`agent/runs`、`./uploads`、`./data`、`~/.vibe-trading/uploads`、`~/.vibe-trading/imports`へ置くか、`VIBE_TRADING_ALLOWED_FILE_ROOTS`で専用ディレクトリを追加してください。+### Web UI SettingsWeb UI Settingsページでは、ローカルユーザーがLLM provider/model、Base URL、生成パラメータ、reasoning effort、Tushare tokenなどの任意の市場データ認証情報を更新できます。設定は`agent/.env`に保存され、providerのデフォルト値は`agent/src/providers/llm_providers.json`から読み込まれます。diff --git a/README_ko.md b/README_ko.mdindex e19b8da03..cd1b30abd 100644--- a/README_ko.md+++ b/README_ko.md@@ -51,6 +51,7 @@## 📰 뉴스+- **2026-05-03** 🛡️ **보안 강화 패치**: 비로컬 배포의 기본 API 인증을 강화하고, 민감한 run/session/swarm 읽기 API를 보호하며, 업로드와 로컬 파일 읽기 경계를 제한하고, shell 가능 도구를 진입점별로 제어합니다. 생성된 전략은 import 전에 검증되며 Docker 이미지는 기본적으로 비root 사용자와 localhost 전용 포트 공개로 실행됩니다. CLI와 localhost Web UI 흐름은 낮은 마찰을 유지합니다. 원격 API/Web 배포에서는 `API_AUTH_KEY`를 설정하세요.- **2026-05-02** 🧭 **배당 분석 + 더 선명한 로드맵**: 인컴 주식, 배당 지속 가능성, 배당 성장, 주주환원 수익률, 배당락 메커니즘, 고배당 함정 점검을 다루는 `dividend-analysis` 스킬을 추가하고 bundled skill 회귀 테스트로 고정했습니다. 공개 로드맵은 Research Autopilot, Data Bridge, Options Lab, Portfolio Studio, Alpha Zoo, Research Delivery, Trust Layer, Community 공유에 집중하도록 정리했습니다.- **2026-05-01** 🔥 **상관관계 히트맵 + OpenAI Codex OAuth + A주 pre-ST 필터**: 새 상관관계 대시보드/API가 롤링 수익률 상관관계를 계산하고, 포트폴리오 및 종목 분석용 ECharts 히트맵으로 렌더링합니다([#64](https://github.com/HKUDS/Vibe-Trading/pull/64)). OpenAI Codex provider는 이제 `vibe-trading provider login openai-codex`로 ChatGPT OAuth를 사용할 수 있으며, Settings 메타데이터와 어댑터 회귀 테스트도 추가되었습니다([#65](https://github.com/HKUDS/Vibe-Trading/pull/65)). A주 ST/*ST 리스크 스크리닝을 위한 `ashare-pre-st-filter` 스킬을 추가하고 강화했으며, Sina 제재 공시 관련성 필터링으로 증권 계좌 목록 언급이 E2 횟수를 부풀리지 않도록 했습니다([#63](https://github.com/HKUDS/Vibe-Trading/pull/63)).- **2026-04-30** ⚙️ **Web UI 설정 + validation CLI 강화**: LLM provider/model, Base URL, reasoning effort, 데이터 소스 자격 증명을 로컬에서 설정할 수 있는 Settings 페이지를 추가했습니다. settings API는 local/auth로 보호되며 provider 메타데이터도 데이터 기반 설정으로 분리되었습니다([#57](https://github.com/HKUDS/Vibe-Trading/pull/57)). 또한 `python -m backtest.validation <run_dir>`가 인자 없음, 빈 경로, 잘못된 경로, 존재하지 않는 경로, 디렉터리가 아닌 경로를 검증 시작 전에 명확한 메시지로 실패하도록 강화했습니다([#60](https://github.com/HKUDS/Vibe-Trading/pull/60)).@@ -260,6 +261,8 @@ docker compose up --build`http://localhost:8899`를 엽니다. 백엔드 + 프런트엔드가 하나의 컨테이너에 있습니다.+Docker는 기본적으로 백엔드를 `127.0.0.1:8899`에만 게시하고, 비root 컨테이너 사용자로 앱을 실행합니다. API를 자신의 머신 밖으로 의도적으로 노출하는 경우 강한 `API_AUTH_KEY`를 설정하고 클라이언트에서 `Authorization: Bearer <key>`를 보내세요.+### 경로 B: 로컬 설치```bash@@ -324,6 +327,10 @@ npx clawhub@latest install vibe-trading --force| `LANGCHAIN_MODEL_NAME` | Yes | 모델 이름(예: `deepseek/deepseek-v3.2`) || `TUSHARE_TOKEN` | No | A주 데이터용 Tushare Pro 토큰(AKShare 폴백) || `TIMEOUT_SECONDS` | No | LLM 호출 타임아웃, 기본 120초 |+| `API_AUTH_KEY` | 네트워크 배포 권장 | API가 비로컬 클라이언트에서 접근 가능한 경우 필요한 Bearer token |+| `VIBE_TRADING_ENABLE_SHELL_TOOLS` | No | 원격 API / MCP-SSE 유형 배포에서 shell 가능 도구를 명시적으로 활성화 |+| `VIBE_TRADING_ALLOWED_FILE_ROOTS` | No | 문서와 브로커 거래 명세서 import용 추가 루트(쉼표 구분) |+| `VIBE_TRADING_ALLOWED_RUN_ROOTS` | No | 생성 코드 run 디렉터리용 추가 루트(쉼표 구분) |<sub>* Ollama는 API 키가 필요 없습니다.</sub>@@ -429,6 +436,12 @@ vibe-trading serve --port 8899인터랙티브 문서: `http://localhost:8899/docs`+### 보안 기본값++localhost 개발에서는 `vibe-trading serve`가 브라우저 워크플로를 단순하게 유지합니다. 비로컬 클라이언트가 민감한 API에 접근하려면 `API_AUTH_KEY`가 필요합니다. JSON/업로드 요청에는 `Authorization: Bearer <key>`를 사용하세요. 브라우저 EventSource 스트림은 Web UI Settings에 같은 키를 한 번 입력하면 처리됩니다.++shell 가능 도구는 로컬 CLI와 신뢰된 localhost 워크플로에서 사용할 수 있지만, 원격 API 세션에는 기본적으로 노출되지 않습니다. 필요한 경우에만 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1`을 명시적으로 설정하세요. 문서와 거래 명세서 리더는 기본적으로 업로드/import 루트로 제한됩니다. 파일은 `agent/uploads`, `agent/runs`, `./uploads`, `./data`, `~/.vibe-trading/uploads`, `~/.vibe-trading/imports`에 두거나, `VIBE_TRADING_ALLOWED_FILE_ROOTS`로 전용 디렉터리를 추가하세요.+### Web UI SettingsWeb UI Settings 페이지에서는 로컬 사용자가 LLM provider/model, Base URL, 생성 파라미터, reasoning effort, Tushare token 같은 선택적 시장 데이터 자격 증명을 업데이트할 수 있습니다. 설정은 `agent/.env`에 저장되며 provider 기본값은 `agent/src/providers/llm_providers.json`에서 로드됩니다.diff --git a/README_zh.md b/README_zh.mdindex 405ff5285..5263f0efe 100644--- a/README_zh.md+++ b/README_zh.md@@ -51,6 +51,7 @@## 📰 新闻+- **2026-05-03** 🛡️ **安全加固补丁**:收紧非本地部署的默认 API 鉴权,保护敏感的 run/session/swarm 读取接口,限制上传与本地文件读取边界,按入口类型控制 shell 能力工具,在导入前校验生成策略,并让 Docker 镜像默认以非 root 用户运行且只发布到 localhost。CLI 与本机 Web UI 仍保持低摩擦;远程 API/Web 部署应配置 `API_AUTH_KEY`。- **2026-05-02** 🧭 **分红分析 + 更清晰的路线图**:新增 `dividend-analysis` 技能,覆盖收益型股票、分红可持续性、股息增长、股东回报率、除息机制与高息陷阱检查,并用 bundled skill 回归测试固定。公开路线图现在聚焦未来工作:Research Autopilot、Data Bridge、Options Lab、Portfolio Studio、Alpha Zoo、Research Delivery、Trust Layer 和 Community 分享。- **2026-05-01** 🔥 **相关性热力图 + OpenAI Codex OAuth + A 股 pre-ST 过滤器**:新增相关性仪表盘/API,可计算滚动收益相关性,并用 ECharts 热力图展示组合与标的相关结构([#64](https://github.com/HKUDS/Vibe-Trading/pull/64))。OpenAI Codex provider 现支持通过 `vibe-trading provider login openai-codex` 使用 ChatGPT OAuth,并补齐 Settings 元数据与适配器回归测试([#65](https://github.com/HKUDS/Vibe-Trading/pull/65))。新增并加固 `ashare-pre-st-filter` 技能,用于 A 股 ST/*ST 风险筛查;Sina 处罚公告相关性过滤会避免证券账户名单提及误计入 E2 频次([#63](https://github.com/HKUDS/Vibe-Trading/pull/63))。- **2026-04-30** ⚙️ **Web UI 设置页 + validation CLI 加固**:新增 Settings 页面,可在本地配置 LLM provider/model、Base URL、reasoning effort 以及数据源凭据;对应 settings API 已加本地/鉴权保护,并把 provider 元数据改为数据驱动配置([#57](https://github.com/HKUDS/Vibe-Trading/pull/57))。同时加固 `python -m backtest.validation <run_dir>`:缺参、空路径、非法路径、不存在路径、非目录路径都会在验证开始前给出明确错误([#60](https://github.com/HKUDS/Vibe-Trading/pull/60))。@@ -260,6 +261,8 @@ docker compose up --build打开 `http://localhost:8899`。后端与前端同一容器。+Docker 默认只把后端发布到 `127.0.0.1:8899`,并以非 root 容器用户运行应用。如果你有意把 API 暴露到本机之外,请设置强 `API_AUTH_KEY`,客户端通过 `Authorization: Bearer <key>` 调用。+### Path B: 本地安装```bash@@ -324,6 +327,10 @@ npx clawhub@latest install vibe-trading --force| `LANGCHAIN_MODEL_NAME` | Yes | 模型名(如 `deepseek/deepseek-v3.2`) || `TUSHARE_TOKEN` | No | A 股数据的 Tushare Pro token(可回退 AKShare) || `TIMEOUT_SECONDS` | No | LLM 调用超时,默认 120s |+| `API_AUTH_KEY` | 网络部署建议设置 | API 可被非本地客户端访问时所需的 Bearer token |+| `VIBE_TRADING_ENABLE_SHELL_TOOLS` | No | 远程 API / MCP-SSE 类部署显式启用 shell 能力工具 |+| `VIBE_TRADING_ALLOWED_FILE_ROOTS` | No | 文档和券商交割单导入的额外逗号分隔目录 |+| `VIBE_TRADING_ALLOWED_RUN_ROOTS` | No | 生成代码 run 目录的额外逗号分隔目录 |<sub>* Ollama 不需要 API key。</sub>@@ -428,6 +435,12 @@ vibe-trading serve --port 8899交互式文档:`http://localhost:8899/docs`+### 安全默认值++本机开发时,`vibe-trading serve` 会尽量保持浏览器工作流简单。任何非本地客户端访问敏感 API 时都需要 `API_AUTH_KEY`;JSON/上传请求请使用 `Authorization: Bearer <key>`。浏览器 EventSource 流由 Web UI 在 Settings 中保存同一个 key 后处理。++Shell 能力工具对本地 CLI 和可信 localhost 工作流可用,但远程 API session 默认不会暴露,除非显式设置 `VIBE_TRADING_ENABLE_SHELL_TOOLS=1`。文档和交割单读取默认限制在上传/导入目录中;请把文件放到 `agent/uploads`、`agent/runs`、`./uploads`、`./data`、`~/.vibe-trading/uploads` 或 `~/.vibe-trading/imports`,也可以通过 `VIBE_TRADING_ALLOWED_FILE_ROOTS` 添加专用目录。+### Web UI 设置Web UI Settings 页面允许本地用户更新 LLM provider/model、Base URL、生成参数、reasoning effort,以及 Tushare token 等可选市场数据凭据。设置会保存到 `agent/.env`;provider 默认值来自 `agent/src/providers/llm_providers.json`。diff --git a/agent/.env.example b/agent/.env.exampleindex c43dd163b..fb38283d5 100644--- a/agent/.env.example+++ b/agent/.env.example@@ -108,12 +108,26 @@ TUSHARE_TOKEN=your-tushare-token# ============================================================================# API Server (optional)# ============================================================================-# Bearer token for API auth (empty = no auth, dev mode)+# Bearer token for API auth.+# Empty dev mode is loopback-only. Set this before exposing port 8899 beyond localhost.# API_AUTH_KEY=# CORS allowed origins (comma-separated)# CORS_ORIGINS=http://localhost:3000,http://localhost:5173,http://localhost:8000# Enable session runtime# ENABLE_SESSION_RUNTIME=true+# Docker compose sets this together with a 127.0.0.1 port bind so browser+# requests from the host machine still count as local dev-mode access.+# Do not enable this when publishing port 8899 on 0.0.0.0 without API_AUTH_KEY.+# VIBE_TRADING_TRUST_DOCKER_LOOPBACK=0+# Advanced local-only opt-in: expose shell execution tools to the agent.+# VIBE_TRADING_ENABLE_SHELL_TOOLS=0+# Optional import roots for read_document/analyze_trade_journal.+# Use comma-separated absolute paths. Defaults include agent/uploads, agent/runs,+# ./uploads, ./data, ~/.vibe-trading/uploads, and ~/.vibe-trading/imports.+# VIBE_TRADING_ALLOWED_FILE_ROOTS=+# Optional run roots for generated-code tools such as write_file/backtest.+# Defaults include agent/runs, ./runs, and ~/.vibe-trading/shadow_runs.+# VIBE_TRADING_ALLOWED_RUN_ROOTS=# ============================================================================# Agent Tuning (optional, defaults are sensible)diff --git a/agent/api_server.py b/agent/api_server.pyindex e8ae43e89..6da1b5b4a 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -7,6 +7,7 @@ V5: ReAct Agent + async /run + CORS env + SSE tool events.from __future__ import annotationsimport asyncio+import hmacimport ipaddressimport jsonimport os@@ -278,6 +279,8 @@ async def _run_startup_preflight() -> None:_security = HTTPBearer(auto_error=False)_API_KEY = os.getenv("API_AUTH_KEY")+_SHELL_TOOLS_ENV = "VIBE_TRADING_ENABLE_SHELL_TOOLS"+_DOCKER_LOOPBACK_ENV = "VIBE_TRADING_TRUST_DOCKER_LOOPBACK"def _configured_api_key() -> str:@@ -286,23 +289,74 @@ def _configured_api_key() -> str:async def require_auth(- cred: HTTPAuthorizationCredentials = Security(_security),+ request: Request,+ cred: Optional[HTTPAuthorizationCredentials] = Security(_security),) -> None:- """Validate Bearer token against API_AUTH_KEY environment variable.-- If API_AUTH_KEY is not set, authentication is skipped (dev mode).- Only write endpoints (POST/PUT/DELETE/PATCH) use this dependency.+ """Validate Bearer token for sensitive API endpoints.Args:+ request: Incoming HTTP request.cred: HTTP Bearer credentials extracted from the Authorization header.Raises:+ HTTPException: 403 when dev-mode auth is reached from a non-local client.HTTPException: 401 when API_AUTH_KEY is set but the token is missing or wrong."""+ _validate_api_auth(request=request, cred=cred)+++async def require_event_stream_auth(+ request: Request,+ api_key: Optional[str] = Query(None),+ cred: Optional[HTTPAuthorizationCredentials] = Security(_security),+) -> None:+ """Validate auth for browser EventSource streams.++ Native EventSource cannot send custom Authorization headers, so event+ stream endpoints may accept the API key from the query string. Normal JSON+ endpoints must continue to use Bearer auth only.++ Args:+ request: Incoming HTTP request.+ api_key: Optional query-string API key for EventSource clients.+ cred: HTTP Bearer credentials extracted from the Authorization header.+ """+ _validate_api_auth(request=request, cred=cred, query_api_key=api_key, allow_query=True)+++def _auth_credential_from_header_or_query(+ cred: Optional[HTTPAuthorizationCredentials],+ query_api_key: Optional[str],+ *,+ allow_query: bool,+) -> str:+ """Return the supplied API credential from the permitted source."""+ if cred and cred.credentials:+ return cred.credentials+ if allow_query and query_api_key:+ return query_api_key+ return ""+++def _validate_api_auth(+ *,+ request: Request,+ cred: Optional[HTTPAuthorizationCredentials],+ query_api_key: Optional[str] = None,+ allow_query: bool = False,+) -> None:+ """Validate configured auth, preserving loopback-only dev mode."""api_key = _configured_api_key()if not api_key:- return- if not cred or cred.credentials != api_key:+ if _is_local_client(request):+ return+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="API_AUTH_KEY is required for non-local API access",+ )++ token = _auth_credential_from_header_or_query(cred, query_api_key, allow_query=allow_query)+ if not token or not hmac.compare_digest(token, api_key):raise HTTPException(status_code=401, detail="Invalid or missing API key")@@ -312,14 +366,67 @@ def _is_local_client(request: Request) -> bool:if host in {"localhost", "testclient"}:return Truetry:- return ipaddress.ip_address(host).is_loopback+ ip = ipaddress.ip_address(host)except ValueError:return False+ if ip.is_loopback:+ return True+ return _trusted_docker_loopback_ip(ip)+++def _env_flag_enabled(name: str) -> bool:+ """Return whether a boolean environment flag is enabled."""+ return os.getenv(name, "").strip().lower() in {"1", "true", "yes", "on"}+++def _default_gateway_ips() -> set[ipaddress.IPv4Address]:+ """Return IPv4 default gateway addresses from Linux procfs."""+ gateways: set[ipaddress.IPv4Address] = set()+ try:+ lines = Path("/proc/net/route").read_text(encoding="utf-8").splitlines()+ except OSError:+ return gateways++ for line in lines[1:]:+ fields = line.split()+ if len(fields) < 3 or fields[1] != "00000000":+ continue+ try:+ raw = int(fields[2], 16).to_bytes(4, byteorder="little")+ gateways.add(ipaddress.IPv4Address(raw))+ except ValueError:+ continue+ return gateways+++def _trusted_docker_loopback_ip(ip: ipaddress._BaseAddress) -> bool:+ """Return whether an IP is the trusted Docker host gateway.++ Docker Desktop presents host requests to a container as the bridge gateway+ instead of 127.0.0.1. This escape hatch is safe only when the published+ port is bound to host loopback, so the official compose file enables it+ together with a 127.0.0.1 port binding.+ """+ if not isinstance(ip, ipaddress.IPv4Address):+ return False+ if not _env_flag_enabled(_DOCKER_LOOPBACK_ENV):+ return False+ return ip in _default_gateway_ips()+++def _env_shell_tools_enabled() -> bool:+ """Return whether server-side shell tools are explicitly enabled."""+ return _env_flag_enabled(_SHELL_TOOLS_ENV)+++def _shell_tools_enabled_for_request(request: Request) -> bool:+ """Return whether this API request may expose shell tools to the agent."""+ return _is_local_client(request) or _env_shell_tools_enabled()async def require_local_or_auth(request: Request,- cred: HTTPAuthorizationCredentials = Security(_security),+ cred: Optional[HTTPAuthorizationCredentials] = Security(_security),) -> None:"""Protect settings access when dev-mode auth is disabled.@@ -328,7 +435,7 @@ async def require_local_or_auth(credential reads or writes in dev mode."""if _configured_api_key():- await require_auth(cred)+ await require_auth(request, cred)returnif not _is_local_client(request):raise HTTPException(@@ -745,7 +852,7 @@ def _build_response_from_run_dir(run_dir: Path, elapsed: float, *, include_analy# API Endpoints# ============================================================================[email protected]("/runs/{run_id}/code")[email protected]("/runs/{run_id}/code", dependencies=[Depends(require_auth)])async def get_run_code(run_id: str):"""Return strategy source files for a run.@@ -766,7 +873,7 @@ async def get_run_code(run_id: str):return result[email protected]("/runs/{run_id}/pine")[email protected]("/runs/{run_id}/pine", dependencies=[Depends(require_auth)])async def get_run_pine(run_id: str):"""Return Pine Script file for a run.@@ -785,7 +892,7 @@ async def get_run_pine(run_id: str):}[email protected]("/runs/{run_id}", response_model=RunResponse)[email protected]("/runs/{run_id}", response_model=RunResponse, dependencies=[Depends(require_auth)])async def get_run_result(run_id: str):"""Fetch full details for a historical run by ``run_id``."""run_dir = RUNS_DIR / run_id@@ -801,7 +908,7 @@ async def get_run_result(run_id: str):return response[email protected]("/runs", response_model=List[RunInfo])[email protected]("/runs", response_model=List[RunInfo], dependencies=[Depends(require_auth)])async def list_runs(limit: int = 20):"""List recent runs with summary fields."""limit = min(max(1, limit), 100)@@ -1150,7 +1257,7 @@ async def create_session(request: CreateSessionRequest):)[email protected]("/sessions", response_model=List[SessionResponse])[email protected]("/sessions", response_model=List[SessionResponse], dependencies=[Depends(require_auth)])async def list_sessions(limit: int = Query(50, ge=1, le=200)):"""List sessions."""svc = _get_session_service()@@ -1170,7 +1277,7 @@ async def list_sessions(limit: int = Query(50, ge=1, le=200)):][email protected]("/sessions/{session_id}", response_model=SessionResponse)[email protected]("/sessions/{session_id}", response_model=SessionResponse, dependencies=[Depends(require_auth)])async def get_session(session_id: str):"""Get one session by id."""svc = _get_session_service()@@ -1224,13 +1331,17 @@ async def update_session(session_id: str, req: UpdateSessionRequest):@app.post("/sessions/{session_id}/messages", dependencies=[Depends(require_auth)])-async def send_message(session_id: str, request: SendMessageRequest):+async def send_message(session_id: str, payload: SendMessageRequest, http_request: Request):"""Send a user message and start the agent loop (natural language strategy)."""svc = _get_session_service()if not svc:raise HTTPException(status_code=501, detail="Session runtime not enabled")try:- result = await svc.send_message(session_id=session_id, content=request.content)+ result = await svc.send_message(+ session_id=session_id,+ content=payload.content,+ include_shell_tools=_shell_tools_enabled_for_request(http_request),+ )return resultexcept ValueError as exc:raise HTTPException(status_code=404, detail=str(exc))@@ -1248,7 +1359,7 @@ async def cancel_session(session_id: str):return {"status": "cancelled"}[email protected]("/sessions/{session_id}/messages", response_model=List[MessageResponse])[email protected]("/sessions/{session_id}/messages", response_model=List[MessageResponse], dependencies=[Depends(require_auth)])async def get_messages(session_id: str, limit: int = Query(100, ge=1, le=1000)):"""List messages for a session."""svc = _get_session_service()@@ -1269,7 +1380,7 @@ async def get_messages(session_id: str, limit: int = Query(100, ge=1, le=1000)):][email protected]("/sessions/{session_id}/events")[email protected]("/sessions/{session_id}/events", dependencies=[Depends(require_event_stream_auth)])async def session_events(session_id: str,request: Request,@@ -1311,15 +1422,23 @@ _BLOCKED_UPLOAD_EXT = {# binaries / executables we should never accept".exe", ".msi", ".bat", ".cmd", ".com", ".scr", ".app", ".dmg",".so", ".dll", ".dylib",+ # executable-adjacent source, shell, config, and template files+ ".py", ".pyw", ".sh", ".bash", ".zsh", ".fish", ".ps1",+ ".yaml", ".yml", ".j2", ".jinja", ".jinja2", ".template",# archives — don't auto-extract; user can unpack locally".zip", ".rar", ".7z", ".tar", ".gz", ".tgz", ".bz2", ".xz",}+_BLOCKED_UPLOAD_NAMES = {+ "dockerfile",+ "containerfile",+}+_SHADOW_ID_RE = __import__("re").compile(r"^shadow_[0-9a-f]{8}$")[email protected]("/shadow-reports/{shadow_id}")[email protected]("/shadow-reports/{shadow_id}", dependencies=[Depends(require_auth)])async def get_shadow_report(shadow_id: str, format: str = "html"):"""Serve a rendered Shadow Account report (HTML by default, PDF if available).@@ -1349,16 +1468,17 @@ async def upload_file(file: UploadFile):"""Upload any document or data file (max 50MB).Accepts most common formats: PDF, Word, Excel, PowerPoint, images,- CSV/TSV, plain text, JSON/YAML/TOML, source code. Executables and- archives are rejected — unpack locally before uploading.+ CSV/TSV, plain text, JSON, and TOML. Executables, executable-adjacent+ source/config/template files, and archives are rejected."""if not file.filename:raise HTTPException(status_code=400, detail="Missing filename")+ filename = Path(file.filename).nameext = Path(file.filename).suffix.lower()- if ext in _BLOCKED_UPLOAD_EXT:+ if ext in _BLOCKED_UPLOAD_EXT or filename.lower() in _BLOCKED_UPLOAD_NAMES:raise HTTPException(status_code=400,- detail=f"File type {ext} is not allowed (executables/archives blocked).",+ detail="This file type is not allowed for upload.",)UPLOADS_DIR.mkdir(parents=True, exist_ok=True)@@ -1427,13 +1547,17 @@ async def list_swarm_presets():@app.post("/swarm/runs", dependencies=[Depends(require_auth)])-async def create_swarm_run(request: dict):+async def create_swarm_run(payload: dict, http_request: Request):"""Start a swarm run: body must include preset_name and user_vars."""runtime = _get_swarm_runtime()- preset_name = request.get("preset_name", "")- user_vars = request.get("user_vars", {})+ preset_name = payload.get("preset_name", "")+ user_vars = payload.get("user_vars", {})try:- run = runtime.start_run(preset_name, user_vars)+ run = runtime.start_run(+ preset_name,+ user_vars,+ include_shell_tools=_shell_tools_enabled_for_request(http_request),+ )return {"id": run.id, "status": run.status.value, "preset_name": run.preset_name}except FileNotFoundError as e:raise HTTPException(status_code=404, detail=str(e))@@ -1441,7 +1565,7 @@ async def create_swarm_run(request: dict):raise HTTPException(status_code=400, detail=str(e))[email protected]("/swarm/runs")[email protected]("/swarm/runs", dependencies=[Depends(require_auth)])async def list_swarm_runs(limit: int = Query(20, ge=1, le=100)):"""List swarm runs (newest first)."""runtime = _get_swarm_runtime()@@ -1459,7 +1583,7 @@ async def list_swarm_runs(limit: int = Query(20, ge=1, le=100)):][email protected]("/swarm/runs/{run_id}")[email protected]("/swarm/runs/{run_id}", dependencies=[Depends(require_auth)])async def get_swarm_run(run_id: str):"""Swarm run detail including task statuses."""from src.swarm.task_store import TaskStore@@ -1491,7 +1615,7 @@ async def get_swarm_run(run_id: str):}[email protected]("/swarm/runs/{run_id}/events")[email protected]("/swarm/runs/{run_id}/events", dependencies=[Depends(require_event_stream_auth)])async def swarm_run_events(run_id: str, request: Request, last_index: int = Query(0, ge=0)):"""SSE stream for a swarm run."""import asynciodiff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex e55b1dcaf..67728bd70 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -7,6 +7,7 @@ Supports ``engine`` for backtest engine (daily/options, default daily).Usage: ``python -m backtest.runner <run_dir>``"""+import astimport importlib.utilimport jsonimport logging@@ -109,6 +110,7 @@ def _load_module_from_file(file_path: Path, module_name: str):Returns:Loaded module object."""+ _validate_signal_engine_source(file_path)spec = importlib.util.spec_from_file_location(module_name, file_path)module = importlib.util.module_from_spec(spec)sys.modules[module_name] = module@@ -116,6 +118,111 @@ def _load_module_from_file(file_path: Path, module_name: str):return module+def _is_literal_node(node: ast.AST) -> bool:+ """Return whether an AST node is made only from literal values."""+ if isinstance(node, ast.Constant):+ return True+ if isinstance(node, (ast.Tuple, ast.List, ast.Set)):+ return all(_is_literal_node(item) for item in node.elts)+ if isinstance(node, ast.Dict):+ return all(+ (key is None or _is_literal_node(key)) and _is_literal_node(value)+ for key, value in zip(node.keys, node.values)+ )+ return False+++def _is_safe_constant_assignment(node: ast.AST) -> bool:+ """Return whether a top-level assignment is literal-only."""+ if isinstance(node, ast.Assign):+ return _is_literal_node(node.value)+ if isinstance(node, ast.AnnAssign):+ return node.value is None or _is_literal_node(node.value)+ return False+++def _is_safe_reference(node: ast.AST | None) -> bool:+ """Return whether an annotation/base expression cannot call code."""+ if node is None:+ return True+ if isinstance(node, (ast.Name, ast.Attribute, ast.Constant)):+ return True+ if isinstance(node, ast.Subscript):+ return _is_safe_reference(node.value) and _is_safe_reference(node.slice)+ if isinstance(node, ast.Tuple):+ return all(_is_safe_reference(item) for item in node.elts)+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):+ return _is_safe_reference(node.left) and _is_safe_reference(node.right)+ return False+++def _validate_function_def(node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:+ """Reject import-time execution in function definitions."""+ if node.decorator_list:+ raise ValueError(f"Decorators are not allowed on function {node.name!r}")+ for default in [*node.args.defaults, *[d for d in node.args.kw_defaults if d]]:+ if not _is_literal_node(default):+ raise ValueError(f"Non-literal default is not allowed on function {node.name!r}")+ annotations = [node.returns]+ annotations.extend(arg.annotation for arg in node.args.posonlyargs)+ annotations.extend(arg.annotation for arg in node.args.args)+ annotations.extend(arg.annotation for arg in node.args.kwonlyargs)+ annotations.append(node.args.vararg.annotation if node.args.vararg else None)+ annotations.append(node.args.kwarg.annotation if node.args.kwarg else None)+ for annotation in annotations:+ if not _is_safe_reference(annotation):+ raise ValueError(f"Unsafe annotation is not allowed on function {node.name!r}")+++def _validate_class_body(node: ast.ClassDef) -> None:+ """Reject import-time execution inside class bodies."""+ if node.decorator_list:+ raise ValueError(f"Decorators are not allowed on class {node.name!r}")+ for base in node.bases:+ if not _is_safe_reference(base):+ raise ValueError(f"Unsafe base class is not allowed on class {node.name!r}")+ if node.keywords:+ raise ValueError(f"Class keywords are not allowed on class {node.name!r}")+ for child in node.body:+ if isinstance(child, ast.Expr) and isinstance(child.value, ast.Constant):+ continue+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):+ _validate_function_def(child)+ continue+ if _is_safe_constant_assignment(child):+ continue+ if isinstance(child, ast.Pass):+ continue+ raise ValueError(+ f"Executable class-level statement {type(child).__name__} is not allowed"+ )+++def _validate_signal_engine_source(file_path: Path) -> None:+ """Reject import-time executable statements before loading signal_engine.py."""+ try:+ tree = ast.parse(file_path.read_text(encoding="utf-8"), filename=str(file_path))+ except SyntaxError as exc:+ raise ValueError(f"Invalid signal_engine.py syntax: {exc}") from exc++ for node in tree.body:+ if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant):+ continue+ if isinstance(node, (ast.Import, ast.ImportFrom)):+ continue+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):+ _validate_function_def(node)+ continue+ if isinstance(node, ast.ClassDef):+ _validate_class_body(node)+ continue+ if _is_safe_constant_assignment(node):+ continue+ raise ValueError(+ f"Executable top-level statement {type(node).__name__} is not allowed"+ )++# --- Market detection (returns market type, NOT source name) ---_MARKET_PATTERNS = [diff --git a/agent/cli.py b/agent/cli.pyindex 581ba0216..fa971b30c 100644--- a/agent/cli.py+++ b/agent/cli.py@@ -283,7 +283,7 @@ def _run_agent(pm = PersistentMemory()agent = AgentLoop(- registry=build_registry(persistent_memory=pm),+ registry=build_registry(persistent_memory=pm, include_shell_tools=True),llm=ChatLLM(),event_callback=on_event,max_iterations=max_iter,@@ -923,7 +923,12 @@ def cmd_swarm_run_live(preset: str, vars_json: Optional[str] = None) -> None:dashboard = _SwarmDashboard(preset, "")try:- run = runtime.start_run(preset, user_vars, live_callback=dashboard.handle_event)+ run = runtime.start_run(+ preset,+ user_vars,+ live_callback=dashboard.handle_event,+ include_shell_tools=True,+ )except FileNotFoundError as exc:console.print(f"[red]{exc}[/red]")returndiff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex 57dea0e64..9b4e06ad9 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -49,6 +49,12 @@ mcp = FastMCP("Vibe-Trading")_skills_loader = None_registry = None+_include_shell_tools = True+++def _env_shell_tools_enabled() -> bool:+ """Return whether shell tools were explicitly enabled for network MCP."""+ return os.getenv("VIBE_TRADING_ENABLE_SHELL_TOOLS", "").strip().lower() in {"1", "true", "yes", "on"}def _get_skills_loader():@@ -63,7 +69,7 @@ def _get_registry():global _registryif _registry is None:from src.tools import build_registry- _registry = build_registry()+ _registry = build_registry(include_shell_tools=_include_shell_tools)return _registry@@ -693,6 +699,7 @@ def scan_shadow_signals(def main():"""Entry point for `vibe-trading-mcp` CLI command."""+ global _include_shell_tools, _registryimport argparseparser = argparse.ArgumentParser(description="Vibe-Trading MCP Server")@@ -701,6 +708,8 @@ def main():parser.add_argument("--port", type=int, default=8900,help="SSE port (only used with --transport sse)")args = parser.parse_args()+ _include_shell_tools = True if args.transport == "stdio" else _env_shell_tools_enabled()+ _registry = Noneif args.transport == "sse":mcp.run(transport="sse", port=args.port)diff --git a/agent/src/session/service.py b/agent/src/session/service.pyindex df3a9c30e..d71af4341 100644--- a/agent/src/session/service.py+++ b/agent/src/session/service.py@@ -82,13 +82,21 @@ class SessionService:self.event_bus.clear(session_id)return self.store.delete_session(session_id)- async def send_message(self, session_id: str, content: str, role: str = "user") -> Dict[str, Any]:+ async def send_message(+ self,+ session_id: str,+ content: str,+ role: str = "user",+ *,+ include_shell_tools: bool = False,+ ) -> Dict[str, Any]:"""Send a message to a session and trigger execution.Args:session_id: Session ID.content: Message content.role: Message role.+ include_shell_tools: Whether this attempt may use shell tools.Returns:Dictionary containing message_id and attempt_id.@@ -107,12 +115,13 @@ class SessionService:attempt = Attempt(session_id=session_id, parent_attempt_id=session.last_attempt_id, prompt=content)self.store.create_attempt(attempt)+ session.config["include_shell_tools"] = include_shell_toolssession.last_attempt_id = attempt.attempt_idsession.updated_at = datetime.now().isoformat()self.store.update_session(session)self.event_bus.emit(session_id, "attempt.created", {"attempt_id": attempt.attempt_id, "prompt": content})- asyncio.create_task(self._run_attempt(session, attempt))+ asyncio.create_task(self._run_attempt(session, attempt, include_shell_tools=include_shell_tools))return {"message_id": message.message_id, "attempt_id": attempt.attempt_id}async def resume_attempt(self, session_id: str, attempt_id: str, user_input: str) -> Dict[str, Any]:@@ -144,7 +153,8 @@ class SessionService:self.store.update_attempt(attempt)self.event_bus.emit(session_id, "attempt.resumed", {"attempt_id": attempt_id, "user_input": user_input})- asyncio.create_task(self._run_attempt(session, attempt))+ include_shell_tools = bool(session.config.get("include_shell_tools", False))+ asyncio.create_task(self._run_attempt(session, attempt, include_shell_tools=include_shell_tools))return {"status": "resumed", "attempt_id": attempt_id}def get_messages(self, session_id: str, limit: int = 100) -> list[Message]:@@ -174,7 +184,7 @@ class SessionService:loop.cancel()return True- async def _run_attempt(self, session: Session, attempt: Attempt) -> None:+ async def _run_attempt(self, session: Session, attempt: Attempt, *, include_shell_tools: bool = False) -> None:"""Execute an Attempt in the background."""attempt.mark_running()self.store.update_attempt(attempt)@@ -182,7 +192,7 @@ class SessionService:try:messages = self.store.get_messages(session.session_id)- result = await self._run_with_agent(attempt, messages=messages)+ result = await self._run_with_agent(attempt, messages=messages, include_shell_tools=include_shell_tools)if result.get("status") == "success":attempt.mark_completed(summary=result.get("content", ""))else:@@ -217,12 +227,19 @@ class SessionService:self.store.update_attempt(attempt)self.event_bus.emit(session.session_id, "attempt.failed", {"attempt_id": attempt.attempt_id, "error": str(exc)})- async def _run_with_agent(self, attempt: Attempt, messages: list = None) -> Dict[str, Any]:+ async def _run_with_agent(+ self,+ attempt: Attempt,+ messages: list = None,+ *,+ include_shell_tools: bool = False,+ ) -> Dict[str, Any]:"""Execute an attempt with the V5 AgentLoop.Args:attempt: Current execution attempt.messages: Session message history.+ include_shell_tools: Whether the registry may include shell tools.Returns:Result dictionary containing status, run_dir, run_id, metrics, and related fields.@@ -244,7 +261,7 @@ class SessionService:self.event_bus.emit(session_id, event_type, data)agent = AgentLoop(- registry=build_registry(persistent_memory=pm),+ registry=build_registry(persistent_memory=pm, include_shell_tools=include_shell_tools),llm=llm,event_callback=event_callback,max_iterations=50,diff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.pyindex faf9500b6..bf2203cd5 100644--- a/agent/src/swarm/runtime.py+++ b/agent/src/swarm/runtime.py@@ -72,6 +72,7 @@ class SwarmRuntime:preset_name: str,user_vars: dict[str, str],live_callback: Callable | None = None,+ include_shell_tools: bool = False,) -> SwarmRun:"""Start a swarm run. Returns immediately, execution happens in background.@@ -79,6 +80,7 @@ class SwarmRuntime:preset_name: YAML preset name to execute.user_vars: User-provided variables for prompt templates.live_callback: Optional callback invoked for each event in real-time.+ include_shell_tools: Whether workers may register shell tools.Returns:The created SwarmRun instance (status=pending initially).@@ -99,7 +101,7 @@ class SwarmRuntime:thread = threading.Thread(target=self._execute_run,- args=(run, cancel_event),+ args=(run, cancel_event, include_shell_tools),name=f"swarm-{run.id}",daemon=True,)@@ -168,7 +170,12 @@ class SwarmRuntime:timestamp=datetime.now(timezone.utc).isoformat(),)- def _execute_run(self, run: SwarmRun, cancel_event: threading.Event) -> None:+ def _execute_run(+ self,+ run: SwarmRun,+ cancel_event: threading.Event,+ include_shell_tools: bool = False,+ ) -> None:"""Core orchestration loop (runs in background thread).Steps:@@ -184,6 +191,7 @@ class SwarmRuntime:Args:run: SwarmRun to execute.cancel_event: Threading event for cancellation signalling.+ include_shell_tools: Whether workers may register shell tools."""run_id = run.idrun_dir = self._store.run_dir(run_id)@@ -232,6 +240,7 @@ class SwarmRuntime:task_summaries=task_summaries,run_dir=run_dir,cancel_event=cancel_event,+ include_shell_tools=include_shell_tools,)# Process results@@ -320,6 +329,7 @@ class SwarmRuntime:task_summaries: dict[str, str],run_dir: Path,cancel_event: threading.Event,+ include_shell_tools: bool = False,) -> dict[str, WorkerResult]:"""Execute all tasks in a single layer in parallel, with retry on failure.@@ -334,6 +344,7 @@ class SwarmRuntime:task_summaries: Accumulated task summaries from previous layers.run_dir: Run directory path.cancel_event: Cancellation event.+ include_shell_tools: Whether workers may register shell tools.Returns:Mapping of task_id -> WorkerResult for all tasks in this layer.@@ -386,6 +397,7 @@ class SwarmRuntime:run_dir=run_dir,event_callback=_event_callback,run_id=run.id,+ include_shell_tools=include_shell_tools,)futures[future] = tidper_task_budget = agent_spec.timeout_seconds * (agent_spec.max_retries + 1)@@ -439,6 +451,7 @@ class SwarmRuntime:run_dir: Path,event_callback: Callable[[SwarmEvent], None] | None,run_id: str,+ include_shell_tools: bool = False,) -> WorkerResult:"""Run a worker with automatic retry on failure.@@ -454,6 +467,7 @@ class SwarmRuntime:run_dir: Run directory path.event_callback: Optional event callback.run_id: Run identifier for event emission.+ include_shell_tools: Whether the worker may register shell tools.Returns:WorkerResult from the last attempt.@@ -487,6 +501,7 @@ class SwarmRuntime:user_vars=user_vars,run_dir=run_dir,event_callback=event_callback,+ include_shell_tools=include_shell_tools,)cumulative_input_tokens += result.input_tokensdiff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.pyindex a82e3ee20..12eeac1a9 100644--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@ -186,6 +186,7 @@ def run_worker(user_vars: dict[str, str],run_dir: Path,event_callback: Callable[[SwarmEvent], None] | None = None,+ include_shell_tools: bool = False,) -> WorkerResult:"""Execute a single worker task using a lightweight ReAct loop.@@ -205,6 +206,7 @@ def run_worker(user_vars: User-provided variables for template rendering.run_dir: Path to .swarm/runs/{run_id}/ directory.event_callback: Optional callback for swarm events.+ include_shell_tools: Whether this worker may register shell tools.Returns:WorkerResult with status, summary, artifacts, and iteration count.@@ -217,7 +219,7 @@ def run_worker(_emit(event_callback, "worker_started", agent_id, task_id)# 1. Build filtered tool registry- registry = build_filtered_registry(agent_spec.tools)+ registry = build_filtered_registry(agent_spec.tools, include_shell_tools=include_shell_tools)# 2. Create LLMllm = ChatLLM(model_name=agent_spec.model_name)diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.pyindex 188bc8340..c0681817f 100644--- a/agent/src/tools/__init__.py+++ b/agent/src/tools/__init__.py@@ -19,6 +19,7 @@ from src.agent.tools import BaseTool, ToolRegistrylogger = logging.getLogger(__name__)_SUBCLASSES_CACHE: list[type[BaseTool]] | None = None+_SHELL_TOOL_NAMES = {"bash", "background_run"}def _discover_subclasses() -> list[type[BaseTool]]:@@ -54,27 +55,41 @@ def _discover_subclasses() -> list[type[BaseTool]]:return classes-def build_registry(*, persistent_memory: "PersistentMemory | None" = None) -> ToolRegistry:+def build_registry(+ *,+ persistent_memory: "PersistentMemory | None" = None,+ include_shell_tools: bool = False,+) -> ToolRegistry:"""Build the tool registry via auto-discovery.Args:persistent_memory: Shared PersistentMemory instance. Injected intotools that need it (e.g. RememberTool) so all tools share oneinstance instead of each creating their own.+ include_shell_tools: Whether to include tools that execute shell+ commands. Local CLI/stdin entry points can enable this; networked+ server entry points should keep it disabled unless explicitly+ opted in.Returns:ToolRegistry containing all available tools."""from src.tools.remember_tool import RememberTool+ from src.tools.swarm_tool import SwarmToolregistry = ToolRegistry()for cls in _discover_subclasses():try:+ if cls.name in _SHELL_TOOL_NAMES and not include_shell_tools:+ logger.info("Tool %s disabled by shell tool policy", cls.name)+ continueif not cls.check_available():logger.info("Tool %s unavailable, skipping", cls.name)continueif cls is RememberTool and persistent_memory is not None:registry.register(cls(memory=persistent_memory))+ elif cls is SwarmTool:+ registry.register(cls(include_shell_tools=include_shell_tools))else:registry.register(cls())except Exception as exc:@@ -82,16 +97,17 @@ def build_registry(*, persistent_memory: "PersistentMemory | None" = None) -> Toreturn registry-def build_filtered_registry(tool_names: list[str]) -> ToolRegistry:+def build_filtered_registry(tool_names: list[str], *, include_shell_tools: bool = False) -> ToolRegistry:"""Build a ToolRegistry with only specified tools.Args:tool_names: Tool names to include.+ include_shell_tools: Whether to include filtered shell execution tools.Returns:ToolRegistry containing only the requested tools."""- full = build_registry()+ full = build_registry(include_shell_tools=include_shell_tools)filtered = ToolRegistry()for name in tool_names:tool = full.get(name)diff --git a/agent/src/tools/backtest_tool.py b/agent/src/tools/backtest_tool.pyindex 4bf0470a9..6b99c2f1b 100644--- a/agent/src/tools/backtest_tool.py+++ b/agent/src/tools/backtest_tool.py@@ -7,6 +7,7 @@ from pathlib import Pathfrom src.agent.tools import BaseToolfrom src.core.runner import Runner+from src.tools.path_utils import safe_run_dirdef run_backtest(run_dir: str) -> str:@@ -18,7 +19,10 @@ def run_backtest(run_dir: str) -> str:Returns:JSON-formatted execution result."""- run_path = Path(run_dir)+ try:+ run_path = safe_run_dir(run_dir)+ except ValueError as exc:+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)config_path = run_path / "config.json"if not config_path.exists():diff --git a/agent/src/tools/bash_tool.py b/agent/src/tools/bash_tool.pyindex 26e8288b4..74324ccca 100644--- a/agent/src/tools/bash_tool.py+++ b/agent/src/tools/bash_tool.py@@ -3,7 +3,6 @@from __future__ import annotationsimport json-import osimport subprocessfrom typing import Anydiff --git a/agent/src/tools/doc_reader_tool.py b/agent/src/tools/doc_reader_tool.pyindex b0d8ae7e5..4eeaf181c 100644--- a/agent/src/tools/doc_reader_tool.py+++ b/agent/src/tools/doc_reader_tool.py@@ -20,6 +20,7 @@ from pathlib import Pathfrom typing import Any, Callablefrom src.agent.tools import BaseTool+from src.tools.path_utils import safe_document_path_MAX_CHARS = 15000_MIN_TEXT_PER_PAGE = 50@@ -267,7 +268,10 @@ def read_document(file_path: str, pages: str = "") -> str:JSON envelope: status, file, format, char_count, truncated, text,plus format-specific metadata (total_pages, sheets, etc.)."""- path = Path(file_path)+ try:+ path = safe_document_path(file_path)+ except ValueError as exc:+ return _err(str(exc))if not path.exists():return _err(f"File not found: {file_path}")if not path.is_file():diff --git a/agent/src/tools/edit_file_tool.py b/agent/src/tools/edit_file_tool.pyindex c5a775aaa..2ea2675ba 100644--- a/agent/src/tools/edit_file_tool.py+++ b/agent/src/tools/edit_file_tool.py@@ -8,6 +8,7 @@ from typing import Anyfrom src.agent.tools import BaseToolfrom src.tools.path_utils import safe_path as _safe_path+from src.tools.path_utils import safe_run_dir as _safe_run_dirclass EditFileTool(BaseTool):@@ -48,7 +49,8 @@ class EditFileTool(BaseTool):}, ensure_ascii=False)try:- resolved = _safe_path(file_path, Path(run_dir))+ run_root = _safe_run_dir(str(run_dir))+ resolved = _safe_path(file_path, run_root)except ValueError as exc:return json.dumps({"status": "error",diff --git a/agent/src/tools/path_utils.py b/agent/src/tools/path_utils.pyindex f1d3340e0..7106c5723 100644--- a/agent/src/tools/path_utils.py+++ b/agent/src/tools/path_utils.py@@ -1,23 +1,28 @@"""Path safety helpers used by file-access tools.-Two helpers, two threat models:+Three helpers, three threat models:* `safe_path(p, workdir)` — tool-controlled sandbox. Resolves `p` under`workdir` and rejects any escape. Used by `read_file` / `write_file` /`edit_file` where the LLM must stay inside the current run dir.-* `safe_user_path(p)` — user-supplied broker files. Accepts any path inside- the user's home directory or the project CWD, rejects UNC and system- paths. Used by `analyze_trade_journal` and the Shadow Account tools- where the journal CSV is legitimately anywhere in the user's filesystem.+* `safe_user_path(p)` — user-supplied broker files. Accepts files only under+ explicit import roots, not the whole home directory or project tree.-Both raise ``ValueError`` on rejection — callers already expect this.+* `safe_document_path(p)` — document-reader inputs. Uses the same import-root+ boundary as `safe_user_path()`.++All helpers raise ``ValueError`` on rejection — callers already expect this."""from __future__ import annotations+import osfrom pathlib import Path+_ALLOWED_FILE_ROOTS_ENV = "VIBE_TRADING_ALLOWED_FILE_ROOTS"+_ALLOWED_RUN_ROOTS_ENV = "VIBE_TRADING_ALLOWED_RUN_ROOTS"+def _rejects_unc(p: str) -> None:"""Raise ValueError if `p` starts with a UNC share prefix."""@@ -49,33 +54,160 @@ def safe_path(p: str, workdir: Path) -> Path:return resolved-def safe_user_path(p: str) -> Path:- """Validate a user-supplied absolute file path.+def _agent_root() -> Path:+ """Return the agent package root."""+ return Path(__file__).resolve().parents[2]+++def _configured_file_roots() -> list[Path]:+ """Return file roots configured through the environment."""+ raw = os.getenv(_ALLOWED_FILE_ROOTS_ENV, "")+ roots: list[Path] = []+ for item in raw.split(","):+ item = item.strip()+ if not item:+ continue+ _rejects_unc(item)+ roots.append(Path(item).expanduser().resolve())+ return roots+- Used when the LLM passes a broker-export path the user referenced in- natural language. The path may legitimately live anywhere the user- keeps files (Desktop, Downloads, a project subdirectory), so the- envelope is HOME ∪ CWD rather than a tight sandbox.+def _default_file_roots() -> list[Path]:+ """Return default roots for uploaded/imported user files."""+ cwd = Path.cwd().resolve()+ home = Path.home().resolve()+ agent_root = _agent_root()+ return [+ agent_root / "uploads",+ agent_root / "runs",+ cwd / "uploads",+ cwd / "data",+ home / ".vibe-trading" / "uploads",+ home / ".vibe-trading" / "imports",+ ]+++def _default_run_roots() -> list[Path]:+ """Return default roots for generated backtest/tool run directories."""+ cwd = Path.cwd().resolve()+ home = Path.home().resolve()+ agent_root = _agent_root()+ return [+ agent_root / "runs",+ cwd / "runs",+ home / ".vibe-trading" / "shadow_runs",+ ]+++def _allowed_file_roots() -> list[Path]:+ """Return all roots allowed for document and broker-file reads."""+ roots: list[Path] = []+ for root in [*_default_file_roots(), *_configured_file_roots()]:+ resolved = root.resolve()+ if resolved not in roots:+ roots.append(resolved)+ return roots+++def _allowed_run_roots() -> list[Path]:+ """Return all roots allowed for run_dir-based tools."""+ raw = os.getenv(_ALLOWED_RUN_ROOTS_ENV, "")+ configured: list[Path] = []+ for item in raw.split(","):+ item = item.strip()+ if not item:+ continue+ _rejects_unc(item)+ configured.append(Path(item).expanduser().resolve())++ roots: list[Path] = []+ for root in [*_default_run_roots(), *configured]:+ resolved = root.resolve()+ if resolved not in roots:+ roots.append(resolved)+ return roots+++def _safe_import_path(p: str, *, purpose: str) -> Path:+ """Validate a user-supplied path against explicit import roots.Args:- p: User-supplied path. `~` expansion supported.+ p: User-supplied path. `~` expansion is supported.+ purpose: Human-readable purpose for error messages.Returns:- Absolute resolved path.+ Absolute resolved path inside an allowed import root.Raises:- ValueError: If `p` is a UNC share, or resolves outside both the- user's home directory and the current working directory.+ ValueError: If `p` is a UNC share or resolves outside all allowed+ import roots."""_rejects_unc(p)resolved = Path(p).expanduser().resolve()- home = Path.home().resolve()- cwd = Path.cwd().resolve()+ for root in _allowed_file_roots():+ if resolved.is_relative_to(root):+ return resolved++ raise ValueError(+ f"Path {p!r} is outside allowed {purpose} roots. "+ f"Set {_ALLOWED_FILE_ROOTS_ENV} to add an import directory."+ )+++def safe_user_path(p: str) -> Path:+ """Validate a user-supplied broker/export file path.++ Args:+ p: User-supplied path. `~` expansion is supported.++ Returns:+ Absolute resolved path inside an allowed import root.++ Raises:+ ValueError: If `p` is a UNC share or resolves outside all allowed+ import roots.+ """+ return _safe_import_path(p, purpose="user-file")+++def safe_document_path(p: str) -> Path:+ """Validate a document-reader file path.++ Args:+ p: User-supplied document path. `~` expansion is supported.++ Returns:+ Absolute resolved path inside an allowed import root.++ Raises:+ ValueError: If `p` is a UNC share or resolves outside all allowed+ import roots.+ """+ return _safe_import_path(p, purpose="document")+++def safe_run_dir(p: str) -> Path:+ """Validate a run directory used by generated-code tools.++ Args:+ p: User/LLM-supplied run directory. `~` expansion is supported.++ Returns:+ Absolute resolved path inside an allowed run root.++ Raises:+ ValueError: If `p` is a UNC share or resolves outside all allowed run+ roots.+ """+ _rejects_unc(p)+ resolved = Path(p).expanduser().resolve()- if resolved.is_relative_to(home) or resolved.is_relative_to(cwd):- return resolved+ for root in _allowed_run_roots():+ if resolved.is_relative_to(root):+ return resolvedraise ValueError(- f"Path {p!r} is outside the user home directory and project directory"+ f"run_dir {p!r} is outside allowed run roots. "+ f"Set {_ALLOWED_RUN_ROOTS_ENV} to add a run directory.")diff --git a/agent/src/tools/pattern_tool.py b/agent/src/tools/pattern_tool.pyindex bddf241de..d5bd46674 100644--- a/agent/src/tools/pattern_tool.py+++ b/agent/src/tools/pattern_tool.py@@ -14,6 +14,7 @@ import numpy as npimport pandas as pdfrom src.agent.tools import BaseTool+from src.tools.path_utils import safe_run_dir# ---------------------------------------------------------------------------@@ -313,7 +314,12 @@ def run_pattern(run_dir: str, patterns: str = "all", window: int = 10) -> str:Returns:JSON-formatted detection results."""- arts = Path(run_dir) / "artifacts"+ try:+ run_path = safe_run_dir(run_dir)+ except ValueError as exc:+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)++ arts = run_path / "artifacts"ohlcv_files = list(arts.glob("ohlcv_*.csv"))if not ohlcv_files:return json.dumps({"status": "error", "error": "No OHLCV data found; run backtest first"}, ensure_ascii=False)diff --git a/agent/src/tools/read_file_tool.py b/agent/src/tools/read_file_tool.pyindex cdb341b4f..680aedf68 100644--- a/agent/src/tools/read_file_tool.py+++ b/agent/src/tools/read_file_tool.py@@ -8,6 +8,7 @@ from typing import Anyfrom src.agent.tools import BaseToolfrom src.tools.path_utils import safe_path as _safe_path+from src.tools.path_utils import safe_run_dir as _safe_run_dir_OUTPUT_LIMIT = 50_000@@ -42,7 +43,13 @@ class ReadFileTool(BaseTool):allowed_roots = []if run_dir:- allowed_roots.append(Path(run_dir).resolve())+ try:+ allowed_roots.append(_safe_run_dir(str(run_dir)))+ except ValueError as exc:+ return json.dumps({+ "status": "error",+ "error": str(exc),+ }, ensure_ascii=False)# Read-only access to skills/skills_dir = Path(__file__).resolve().parents[1] / "skills"if skills_dir.exists():diff --git a/agent/src/tools/swarm_tool.py b/agent/src/tools/swarm_tool.pyindex 7588b080b..624f18e73 100644--- a/agent/src/tools/swarm_tool.py+++ b/agent/src/tools/swarm_tool.py@@ -585,6 +585,15 @@ class SwarmTool(BaseTool):is_readonly = Falserepeatable = True # loop.py dedups by tool name; each prompt is a distinct run (#42)+ def __init__(self, *, include_shell_tools: bool = False) -> None:+ """Initialize the swarm launcher.++ Args:+ include_shell_tools: Whether worker registries may include shell+ execution tools requested by presets.+ """+ self.include_shell_tools = include_shell_tools+def execute(self, **kwargs: Any) -> str:"""Start a swarm run: auto-match preset, extract variables, wait for completion.@@ -621,7 +630,11 @@ class SwarmTool(BaseTool):runtime = SwarmRuntime(store=store, max_workers=int(os.getenv("SWARM_MAX_WORKERS", "4")))try:- run = runtime.start_run(preset, variables)+ run = runtime.start_run(+ preset,+ variables,+ include_shell_tools=self.include_shell_tools,+ )except FileNotFoundError as exc:return json.dumps({"status": "error", "error": f"Preset not found: {exc}"},diff --git a/agent/src/tools/write_file_tool.py b/agent/src/tools/write_file_tool.pyindex 445591908..7069865f4 100644--- a/agent/src/tools/write_file_tool.py+++ b/agent/src/tools/write_file_tool.py@@ -8,6 +8,7 @@ from typing import Anyfrom src.agent.tools import BaseToolfrom src.tools.path_utils import safe_path as _safe_path+from src.tools.path_utils import safe_run_dir as _safe_run_dirclass WriteFileTool(BaseTool):@@ -46,7 +47,8 @@ class WriteFileTool(BaseTool):}, ensure_ascii=False)try:- resolved = _safe_path(file_path, Path(run_dir))+ run_root = _safe_run_dir(str(run_dir))+ resolved = _safe_path(file_path, run_root)except ValueError as exc:return json.dumps({"status": "error",diff --git a/agent/tests/test_backtest_runner_security.py b/agent/tests/test_backtest_runner_security.pynew file mode 100644index 000000000..c89928a3d--- /dev/null+++ b/agent/tests/test_backtest_runner_security.py@@ -0,0 +1,79 @@+"""Security regression tests for backtest signal_engine loading."""++from __future__ import annotations++import uuid++import pytest++from backtest.runner import _load_module_from_file+++def _module_name() -> str:+ """Return a unique module name for import tests."""+ return f"signal_engine_test_{uuid.uuid4().hex}"+++def test_signal_engine_rejects_top_level_execution(tmp_path) -> None:+ artifact = tmp_path / "top_level_rce"+ signal_file = tmp_path / "signal_engine.py"+ signal_file.write_text(+ "\n".join(+ [+ "import os",+ f"os.system('touch {artifact}')",+ "class SignalEngine:",+ " def generate(self, *args, **kwargs):",+ " return []",+ ]+ ),+ encoding="utf-8",+ )++ with pytest.raises(ValueError, match="Executable top-level statement"):+ _load_module_from_file(signal_file, _module_name())++ assert not artifact.exists()+++def test_signal_engine_rejects_class_level_execution(tmp_path) -> None:+ artifact = tmp_path / "class_level_rce"+ signal_file = tmp_path / "signal_engine.py"+ signal_file.write_text(+ "\n".join(+ [+ "import os",+ "class SignalEngine:",+ f" os.system('touch {artifact}')",+ " def generate(self, *args, **kwargs):",+ " return []",+ ]+ ),+ encoding="utf-8",+ )++ with pytest.raises(ValueError, match="Executable class-level statement"):+ _load_module_from_file(signal_file, _module_name())++ assert not artifact.exists()+++def test_signal_engine_allows_minimal_valid_strategy(tmp_path) -> None:+ signal_file = tmp_path / "signal_engine.py"+ signal_file.write_text(+ "\n".join(+ [+ '"""Generated signal engine."""',+ "THRESHOLD = 3",+ "class SignalEngine:",+ " lookback = 20",+ " def generate(self, *args, **kwargs):",+ " return []",+ ]+ ),+ encoding="utf-8",+ )++ module = _load_module_from_file(signal_file, _module_name())++ assert module.SignalEngine().generate() == []diff --git a/agent/tests/test_doc_reader.py b/agent/tests/test_doc_reader.pyindex 2fca8558c..8794ab358 100644--- a/agent/tests/test_doc_reader.py+++ b/agent/tests/test_doc_reader.py@@ -15,6 +15,12 @@ def _call(path: Path, pages: str = "") -> dict:return json.loads(read_document(str(path), pages))[email protected](autouse=True)+def allow_tmp_documents(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """Allow each test's temporary directory as a document import root."""+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", str(tmp_path))++# ---------------- Plain text variants ----------------@pytest.mark.parametrize("ext", [".txt", ".md", ".log", ".rst"])@@ -136,8 +142,8 @@ def test_pptx_slides(tmp_path: Path) -> None:# ---------------- Error handling -----------------def test_missing_file() -> None:- result = _call(Path("/definitely/not/a/real/file.pdf"))+def test_missing_file(tmp_path: Path) -> None:+ result = _call(tmp_path / "missing.pdf")assert result["status"] == "error"assert "not found" in result["error"].lower()diff --git a/agent/tests/test_doc_reader_security.py b/agent/tests/test_doc_reader_security.pynew file mode 100644index 000000000..56338f34c--- /dev/null+++ b/agent/tests/test_doc_reader_security.py@@ -0,0 +1,48 @@+"""Security regression tests for document and broker-file path boundaries."""++from __future__ import annotations++import json++import pytest++from src.tools.doc_reader_tool import read_document+from src.tools.path_utils import safe_document_path, safe_user_path++[email protected](autouse=True)+def clear_allowed_roots(monkeypatch: pytest.MonkeyPatch) -> None:+ """Start each test with only the built-in import roots."""+ monkeypatch.delenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", raising=False)+++def _read_json(result: str) -> dict:+ """Parse a document-reader JSON envelope."""+ return json.loads(result)+++def test_read_document_rejects_system_paths() -> None:+ result = _read_json(read_document("/etc/passwd"))++ assert result["status"] == "error"+ assert "outside allowed document roots" in result["error"]+++def test_safe_user_path_rejects_root_home_credentials() -> None:+ with pytest.raises(ValueError, match="outside allowed user-file roots"):+ safe_user_path("/root/.aws/credentials")+++def test_read_document_allows_configured_import_root(+ tmp_path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ doc = tmp_path / "note.txt"+ doc.write_text("VT_DOC_OK", encoding="utf-8")+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", str(tmp_path))++ result = _read_json(read_document(str(doc)))++ assert result["status"] == "ok"+ assert result["text"] == "VT_DOC_OK"+ assert safe_document_path(str(doc)) == doc.resolve()diff --git a/agent/tests/test_file_tool_sandbox_security.py b/agent/tests/test_file_tool_sandbox_security.pynew file mode 100644index 000000000..1cc1e6e28--- /dev/null+++ b/agent/tests/test_file_tool_sandbox_security.py@@ -0,0 +1,65 @@+"""Security regression tests for run_dir-based file tools."""++from __future__ import annotations++import json+from pathlib import Path++from src.tools.backtest_tool import run_backtest+from src.tools.edit_file_tool import EditFileTool+from src.tools.read_file_tool import ReadFileTool+from src.tools.write_file_tool import WriteFileTool+++def _body(raw: str) -> dict:+ """Parse a JSON tool response."""+ return json.loads(raw)+++def test_write_file_rejects_unconfigured_absolute_run_dir(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.delenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", raising=False)++ body = _body(WriteFileTool().execute(+ path="code/signal_engine.py",+ content="print('nope')",+ run_dir=str(tmp_path),+ ))++ assert body["status"] == "error"+ assert "outside allowed run roots" in body["error"]+ assert not (tmp_path / "code" / "signal_engine.py").exists()+++def test_read_and_edit_file_accept_configured_run_root(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))+ target = tmp_path / "run" / "notes.md"+ target.parent.mkdir(parents=True)+ target.write_text("alpha beta", encoding="utf-8")++ read_body = _body(ReadFileTool().execute(path="notes.md", run_dir=str(target.parent)))+ edit_body = _body(EditFileTool().execute(+ path="notes.md",+ old_text="beta",+ new_text="gamma",+ run_dir=str(target.parent),+ ))++ assert read_body["status"] == "ok"+ assert "alpha beta" in read_body["content"]+ assert edit_body["status"] == "ok"+ assert target.read_text(encoding="utf-8") == "alpha gamma"+++def test_backtest_rejects_unconfigured_absolute_run_dir(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.delenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", raising=False)+ (tmp_path / "code").mkdir()+ (tmp_path / "config.json").write_text('{"source":"auto","codes":["AAPL"]}', encoding="utf-8")+ (tmp_path / "code" / "signal_engine.py").write_text(+ "class SignalEngine:\n def generate(self, data_map):\n return {}\n",+ encoding="utf-8",+ )++ body = _body(run_backtest(str(tmp_path)))++ assert body["status"] == "error"+ assert "outside allowed run roots" in body["error"]diff --git a/agent/tests/test_path_safety.py b/agent/tests/test_path_safety.pyindex 5ace4d9b8..57924a5b6 100644--- a/agent/tests/test_path_safety.py+++ b/agent/tests/test_path_safety.py@@ -6,7 +6,7 @@ from pathlib import Pathimport pytest-from src.tools.path_utils import safe_path, safe_user_path+from src.tools.path_utils import safe_path, safe_run_dir, safe_user_path# ---------------------------------------------------------------------------@@ -46,14 +46,13 @@ class TestSafePath:# ----------------------------------------------------------------------------# safe_user_path — user-supplied broker files, HOME ∪ CWD envelope+# safe_user_path — user-supplied broker files under explicit import roots# ---------------------------------------------------------------------------class TestSafeUserPath:- def test_home_file_accepted(self, tmp_path: Path, monkeypatch):- # Pretend HOME is tmp_path so we can control the envelope- monkeypatch.setattr(Path, "home", lambda: tmp_path)- target = tmp_path / "Desktop" / "broker.csv"+ def test_configured_import_root_file_accepted(self, tmp_path: Path, monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", str(tmp_path))+ target = tmp_path / "broker.csv"target.parent.mkdir(parents=True, exist_ok=True)target.touch()@@ -61,45 +60,39 @@ class TestSafeUserPath:assert result == target.resolve()def test_tilde_expansion_works(self, tmp_path: Path, monkeypatch):- # Both Path.home() and Path.expanduser() read environment variables,- # so set HOME / USERPROFILE directly rather than patching Path.home.monkeypatch.setenv("HOME", str(tmp_path))monkeypatch.setenv("USERPROFILE", str(tmp_path))- target = tmp_path / "journal.csv"+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", "~/.vibe-imports")+ target = tmp_path / ".vibe-imports" / "journal.csv"+ target.parent.mkdir(parents=True, exist_ok=True)target.touch()- result = safe_user_path("~/journal.csv")+ result = safe_user_path("~/.vibe-imports/journal.csv")assert result == target.resolve()- def test_cwd_file_accepted(self, tmp_path: Path, monkeypatch):- # HOME is far away; CWD is tmp_path- other = tmp_path.parent / "somewhere_else"- other.mkdir(exist_ok=True)- monkeypatch.setattr(Path, "home", lambda: other)+ def test_default_cwd_uploads_file_accepted(self, tmp_path: Path, monkeypatch):monkeypatch.chdir(tmp_path)- target = tmp_path / "local.csv"+ target = tmp_path / "uploads" / "local.csv"+ target.parent.mkdir(parents=True, exist_ok=True)target.touch()- result = safe_user_path("local.csv")+ result = safe_user_path(str(target))assert result == target.resolve()- def test_system_path_outside_envelope_rejected(self, tmp_path: Path, monkeypatch):- # HOME and CWD both inside tmp_path- monkeypatch.setattr(Path, "home", lambda: tmp_path)+ def test_system_path_outside_import_roots_rejected(self, tmp_path: Path, monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", str(tmp_path))monkeypatch.chdir(tmp_path)- # /etc is outside both- with pytest.raises(ValueError, match="outside the user home"):+ with pytest.raises(ValueError, match="outside allowed user-file roots"):safe_user_path("/etc/passwd")def test_parent_traversal_from_cwd_rejected(self, tmp_path: Path, monkeypatch):deep = tmp_path / "deep" / "cwd"deep.mkdir(parents=True)- monkeypatch.setattr(Path, "home", lambda: deep)+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", str(deep))monkeypatch.chdir(deep)- # Resolve back above both HOME and CWD- with pytest.raises(ValueError, match="outside the user home"):+ with pytest.raises(ValueError, match="outside allowed user-file roots"):safe_user_path("../../../../../etc/passwd")def test_unc_path_rejected(self):@@ -109,3 +102,35 @@ class TestSafeUserPath:def test_unix_double_slash_rejected(self):with pytest.raises(ValueError, match="UNC paths"):safe_user_path("//evil-server/share/passwd.csv")+++# ---------------------------------------------------------------------------+# safe_run_dir — tool/backtest run roots+# ---------------------------------------------------------------------------++class TestSafeRunDir:+ def test_configured_run_root_accepted(self, tmp_path: Path, monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))+ run_dir = tmp_path / "run_123"+ run_dir.mkdir()++ result = safe_run_dir(str(run_dir))++ assert result == run_dir.resolve()++ def test_system_tmp_run_dir_rejected_by_default(self, tmp_path: Path, monkeypatch):+ monkeypatch.delenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", raising=False)+ run_dir = tmp_path / "attack_run"+ run_dir.mkdir()++ with pytest.raises(ValueError, match="outside allowed run roots"):+ safe_run_dir(str(run_dir))++ def test_default_agent_runs_dir_accepted(self, tmp_path: Path, monkeypatch):+ monkeypatch.delenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", raising=False)+ agent_runs = Path(__file__).resolve().parents[1] / "runs" / "safe_run"+ agent_runs.mkdir(parents=True, exist_ok=True)++ result = safe_run_dir(str(agent_runs))++ assert result == agent_runs.resolve()diff --git a/agent/tests/test_security_auth_api.py b/agent/tests/test_security_auth_api.pynew file mode 100644index 000000000..28d1a892f--- /dev/null+++ b/agent/tests/test_security_auth_api.py@@ -0,0 +1,147 @@+"""Security regression tests for API authentication boundaries."""++from __future__ import annotations++import ipaddress+from types import SimpleNamespace++import pytest+from fastapi.testclient import TestClient++import api_server+++def _remote_client() -> TestClient:+ """Return a TestClient that simulates a non-loopback caller."""+ return TestClient(api_server.app, client=("203.0.113.10", 50000))+++def _local_client() -> TestClient:+ """Return a TestClient that simulates a loopback caller."""+ return TestClient(api_server.app, client=("127.0.0.1", 50000))++[email protected](autouse=True)+def clear_api_key(monkeypatch: pytest.MonkeyPatch) -> None:+ """Start every auth test from dev-mode auth."""+ monkeypatch.delenv("API_AUTH_KEY", raising=False)+ monkeypatch.delenv("VIBE_TRADING_TRUST_DOCKER_LOOPBACK", raising=False)+ monkeypatch.delenv("VIBE_TRADING_ENABLE_SHELL_TOOLS", raising=False)+ monkeypatch.setattr(api_server, "_API_KEY", "")+++def test_remote_write_requires_api_key_when_key_unset() -> None:+ response = _remote_client().post("/sessions", json={})++ assert response.status_code == 403+ assert "API_AUTH_KEY" in response.json()["detail"]+++def test_local_dev_write_allowed_when_key_unset() -> None:+ response = _local_client().post("/sessions", json={})++ assert response.status_code in {201, 501}+++def test_docker_gateway_dev_write_allowed_only_with_compose_trust_flag(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ request = SimpleNamespace(client=SimpleNamespace(host="172.18.0.1"))+ monkeypatch.setattr(+ api_server,+ "_default_gateway_ips",+ lambda: {ipaddress.IPv4Address("172.18.0.1")},+ )++ assert not api_server._is_local_client(request)++ monkeypatch.setenv("VIBE_TRADING_TRUST_DOCKER_LOOPBACK", "1")++ assert api_server._is_local_client(request)+++def test_docker_network_peer_is_not_local_even_with_compose_trust_flag(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ request = SimpleNamespace(client=SimpleNamespace(host="172.18.0.42"))+ monkeypatch.setenv("VIBE_TRADING_TRUST_DOCKER_LOOPBACK", "1")+ monkeypatch.setattr(+ api_server,+ "_default_gateway_ips",+ lambda: {ipaddress.IPv4Address("172.18.0.1")},+ )++ assert not api_server._is_local_client(request)+++def test_configured_api_key_required_for_sensitive_reads(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("API_AUTH_KEY", "secret")+ monkeypatch.setattr(api_server, "_API_KEY", "secret")+ client = _remote_client()++ for path in [+ "/runs",+ "/sessions",+ "/swarm/runs",+ ]:+ response = client.get(path)+ assert response.status_code == 401, path+++def test_configured_api_key_accepts_bearer_for_sensitive_reads(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("API_AUTH_KEY", "secret")+ monkeypatch.setattr(api_server, "_API_KEY", "secret")++ response = _remote_client().get(+ "/runs",+ headers={"Authorization": "Bearer secret"},+ )++ assert response.status_code == 200+++def test_configured_api_key_required_for_session_event_stream(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("API_AUTH_KEY", "secret")+ monkeypatch.setattr(api_server, "_API_KEY", "secret")++ response = _remote_client().get("/sessions/missing/events")++ assert response.status_code == 401+++def test_session_event_stream_accepts_query_token_for_browser_eventsource(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("API_AUTH_KEY", "secret")+ monkeypatch.setattr(api_server, "_API_KEY", "secret")++ response = _remote_client().get("/sessions/missing/events?api_key=secret")++ assert response.status_code in {404, 501}+++def test_shell_tools_allowed_for_loopback_api_request() -> None:+ request = SimpleNamespace(client=SimpleNamespace(host="127.0.0.1"))++ assert api_server._shell_tools_enabled_for_request(request)+++def test_shell_tools_disabled_for_remote_api_request_by_default() -> None:+ request = SimpleNamespace(client=SimpleNamespace(host="203.0.113.10"))++ assert not api_server._shell_tools_enabled_for_request(request)+++def test_shell_tools_remote_api_request_accepts_explicit_opt_in(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ request = SimpleNamespace(client=SimpleNamespace(host="203.0.113.10"))+ monkeypatch.setenv("VIBE_TRADING_ENABLE_SHELL_TOOLS", "1")++ assert api_server._shell_tools_enabled_for_request(request)diff --git a/agent/tests/test_tool_registry_security.py b/agent/tests/test_tool_registry_security.pynew file mode 100644index 000000000..4766f1d85--- /dev/null+++ b/agent/tests/test_tool_registry_security.py@@ -0,0 +1,25 @@+"""Security regression tests for default tool exposure."""++from __future__ import annotations++import pytest++from src.tools import build_registry+++def test_shell_tools_absent_from_default_registry(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("VIBE_TRADING_ENABLE_SHELL_TOOLS", raising=False)++ registry = build_registry()++ assert "bash" not in registry.tool_names+ assert "background_run" not in registry.tool_names+++def test_shell_tools_require_registry_opt_in(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("VIBE_TRADING_ENABLE_SHELL_TOOLS", raising=False)++ registry = build_registry(include_shell_tools=True)++ assert "bash" in registry.tool_names+ assert "background_run" in registry.tool_namesdiff --git a/agent/tests/test_upload_security.py b/agent/tests/test_upload_security.pynew file mode 100644index 000000000..80e9f5901--- /dev/null+++ b/agent/tests/test_upload_security.py@@ -0,0 +1,43 @@+"""Security regression tests for upload file type restrictions."""++from __future__ import annotations++from pathlib import Path++import pytest+from fastapi.testclient import TestClient++import api_server+++def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:+ monkeypatch.setattr(api_server, "UPLOADS_DIR", tmp_path)+ monkeypatch.delenv("API_AUTH_KEY", raising=False)+ monkeypatch.setattr(api_server, "_API_KEY", "")+ return TestClient(api_server.app, client=("127.0.0.1", 50000))+++ "filename",+ [+ "payload.py",+ "run.sh",+ "config.yaml",+ "config.yml",+ "template.j2",+ "Dockerfile",+ ],+)+def test_upload_blocks_executable_adjacent_files(+ client: TestClient,+ tmp_path: Path,+ filename: str,+) -> None:+ response = client.post(+ "/upload",+ files={"file": (filename, b"content", "application/octet-stream")},+ )++ assert response.status_code == 400+ assert list(tmp_path.iterdir()) == []diff --git a/docker-compose.yml b/docker-compose.ymlindex edb82991a..1fa28b3f7 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -2,9 +2,11 @@ services:vibe-trading:build: .ports:- - "8899:8899"+ - "127.0.0.1:8899:8899"env_file:- agent/.env+ environment:+ - VIBE_TRADING_TRUST_DOCKER_LOOPBACK=1volumes:- vibe-runs:/app/agent/runs- vibe-sessions:/app/agent/sessionsdiff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 83464c4da..c968750b0 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1,17 +1,50 @@+import { authHeaders, withAuthQuery } from "@/lib/apiAuth";+const BASE = "";+export class ApiError extends Error {+ status: number;++ constructor(message: string, status: number) {+ super(message);+ this.name = "ApiError";+ this.status = status;+ }+}++export const AUTH_REQUIRED_MESSAGE =+ "Remote API access requires an API key. Add it in Settings, or run the backend on localhost for local-only use.";++export function isAuthRequiredError(error: unknown): boolean {+ return error instanceof ApiError && (error.status === 401 || error.status === 403);+}++async function errorFromResponse(res: Response): Promise<ApiError> {+ let detail = `HTTP ${res.status}`;+ try {+ const body = await res.json();+ detail = body.detail || body.message || detail;+ } catch { /* ignore */ }+ if (res.status === 401 || res.status === 403) {+ detail = AUTH_REQUIRED_MESSAGE;+ }+ return new ApiError(detail, res.status);+}+async function request<T>(path: string, options?: RequestInit): Promise<T> {+ const { headers, ...rest } = options ?? {};+ const mergedHeaders: Record<string, string> = { "Content-Type": "application/json", ...authHeaders() };+ if (headers) {+ new Headers(headers).forEach((value, key) => {+ mergedHeaders[key] = value;+ });+ }const res = await fetch(`${BASE}${path}`, {- headers: { "Content-Type": "application/json", ...options?.headers },- ...options,+ ...rest,+ headers: mergedHeaders,});if (!res.ok) {- let detail = `HTTP ${res.status}`;- try {- const body = await res.json();- detail = body.detail || body.message || detail;- } catch { /* ignore */ }- throw new Error(detail);+ throw await errorFromResponse(res);}const text = await res.text();return text ? JSON.parse(text) : ({} as T);@@ -26,14 +59,9 @@ export interface UploadResult {async function uploadFile(file: File): Promise<UploadResult> {const form = new FormData();form.append("file", file);- const res = await fetch(`${BASE}/upload`, { method: "POST", body: form });+ const res = await fetch(`${BASE}/upload`, { method: "POST", headers: authHeaders(), body: form });if (!res.ok) {- let detail = `HTTP ${res.status}`;- try {- const body = await res.json();- detail = body.detail || body.message || detail;- } catch { /* ignore */ }- throw new Error(detail);+ throw await errorFromResponse(res);}return res.json();}@@ -51,7 +79,7 @@ export const api = {sendMessage: (sid: string, content: string) => request<{ message_id: string; attempt_id: string }>(`/sessions/${sid}/messages`, { method: "POST", body: JSON.stringify({ content }) }),cancelSession: (sid: string) => request<{ status: string }>(`/sessions/${sid}/cancel`, { method: "POST" }),getSessionMessages: (sid: string) => request<MessageItem[]>(`/sessions/${sid}/messages`),- sseUrl: (sid: string) => `${BASE}/sessions/${sid}/events`,+ sseUrl: (sid: string) => withAuthQuery(`${BASE}/sessions/${sid}/events`),// Swarm APIlistSwarmPresets: () => request<SwarmPreset[]>("/swarm/presets"),@@ -62,6 +90,7 @@ export const api = {}),listSwarmRuns: () => request<SwarmRunSummary[]>("/swarm/runs"),getSwarmRun: (id: string) => request<Record<string, unknown>>(`/swarm/runs/${id}`),+ swarmSseUrl: (id: string) => withAuthQuery(`${BASE}/swarm/runs/${id}/events`),cancelSwarmRun: (id: string) =>request<{ status: string }>(`/swarm/runs/${id}/cancel`, { method: "POST" }),getLLMSettings: () => request<LLMSettings>("/settings/llm"),diff --git a/frontend/src/lib/apiAuth.ts b/frontend/src/lib/apiAuth.tsnew file mode 100644index 000000000..c0a61bae7--- /dev/null+++ b/frontend/src/lib/apiAuth.ts@@ -0,0 +1,30 @@+const STORAGE_KEY = "vibe_trading_api_auth_key";++export function getApiAuthKey(): string {+ return window.localStorage.getItem(STORAGE_KEY) || "";+}++export function setApiAuthKey(value: string): void {+ const trimmed = value.trim();+ if (trimmed) {+ window.localStorage.setItem(STORAGE_KEY, trimmed);+ } else {+ window.localStorage.removeItem(STORAGE_KEY);+ }+}++export function authHeaders(): Record<string, string> {+ const key = getApiAuthKey();+ return key ? { Authorization: `Bearer ${key}` } : {};+}++export function authQuerySuffix(): string {+ const key = getApiAuthKey();+ return key ? `api_key=${encodeURIComponent(key)}` : "";+}++export function withAuthQuery(url: string): string {+ const suffix = authQuerySuffix();+ if (!suffix) return url;+ return `${url}${url.includes("?") ? "&" : "?"}${suffix}`;+}diff --git a/frontend/src/lib/i18n.tsx b/frontend/src/lib/i18n.tsxindex ed54c74f8..8a8d98b8d 100644--- a/frontend/src/lib/i18n.tsx+++ b/frontend/src/lib/i18n.tsx@@ -3,6 +3,13 @@ import { createContext, useContext, type ReactNode } from "react";const messages = {home: "Home", agent: "Agent", runs: "Runs", settings: "Settings",settingsDesc: "Configure model credentials and market data source tokens for this local project.",+ localApiAccess: "Local API access",+ localApiAccessDesc: "For remote or private Web UI deployments, enter the server API key once in this browser. Localhost use can stay blank.",+ localApiKey: "Server API key",+ localApiKeyHint: "Stored only in this browser. Leave blank to clear it.",+ localApiKeySaved: "Local API key saved",+ localApiKeySave: "Save local key",+ settingsUnavailable: "Settings are unavailable",llmSettings: "LLM Settings",llmSettingsDesc: "Choose the model used by the agent and save it to the project-local agent/.env file.",llmConnection: "Connection",diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsxindex 1737b8dec..0ee91b305 100644--- a/frontend/src/pages/Agent.tsx+++ b/frontend/src/pages/Agent.tsx@@ -345,7 +345,7 @@ export function Agent() {try {const result = await api.createSwarmRun(presetName, { goal: prompt });const runId = result.id;- const sseUrl = `/swarm/runs/${runId}/events`;+ const sseUrl = api.swarmSseUrl(runId);const evtSource = new EventSource(sseUrl);let sseFinished = false;diff --git a/frontend/src/pages/Settings.tsx b/frontend/src/pages/Settings.tsxindex 92a0f7637..d55b0c7bb 100644--- a/frontend/src/pages/Settings.tsx+++ b/frontend/src/pages/Settings.tsx@@ -1,7 +1,8 @@import { useEffect, useMemo, useState, type FormEvent } from "react";import { Database, KeyRound, Loader2, RotateCcw, Save, Server, SlidersHorizontal } from "lucide-react";import { toast } from "sonner";-import { api, type DataSourceSettings, type LLMProviderOption, type LLMSettings } from "@/lib/api";+import { api, isAuthRequiredError, type DataSourceSettings, type LLMProviderOption, type LLMSettings } from "@/lib/api";+import { getApiAuthKey, setApiAuthKey } from "@/lib/apiAuth";import { useI18n } from "@/lib/i18n";interface LLMFormState {@@ -37,12 +38,14 @@ export function Settings() {const [dataSettings, setDataSettings] = useState<DataSourceSettings | null>(null);const [form, setForm] = useState<LLMFormState | null>(null);const [apiKey, setApiKey] = useState("");+ const [localApiKey, setLocalApiKeyState] = useState(() => getApiAuthKey());const [clearApiKey, setClearApiKey] = useState(false);const [tushareToken, setTushareToken] = useState("");const [clearTushareToken, setClearTushareToken] = useState(false);const [loading, setLoading] = useState(true);const [saving, setSaving] = useState(false);const [dataSaving, setDataSaving] = useState(false);+ const [settingsLoadError, setSettingsLoadError] = useState<string | null>(null);useEffect(() => {let alive = true;@@ -52,10 +55,17 @@ export function Settings() {setSettings(llmData);setForm(toForm(llmData));setDataSettings(dataSourceData);+ setSettingsLoadError(null);}).catch((error) => {- toast.error(`${t.llmSettingsLoadFailed}: ${error.message}`);- toast.error(`${t.dataSourceSettingsLoadFailed}: ${error.message}`);+ const message = error instanceof Error ? error.message : t.unknownError;+ setSettingsLoadError(message);+ if (isAuthRequiredError(error)) {+ toast.error(message);+ } else {+ toast.error(`${t.llmSettingsLoadFailed}: ${message}`);+ toast.error(`${t.dataSourceSettingsLoadFailed}: ${message}`);+ }}).finally(() => {if (alive) setLoading(false);@@ -91,6 +101,13 @@ export function Settings() {setClearApiKey(false);};+ const submitLocalApiKey = (event: FormEvent) => {+ event.preventDefault();+ setApiAuthKey(localApiKey);+ toast.success(t.localApiKeySaved);+ window.location.reload();+ };+const submit = async (event: FormEvent) => {event.preventDefault();if (!form) return;@@ -132,11 +149,60 @@ export function Settings() {}};+ const localApiAccessSection = (+ <form onSubmit={submitLocalApiKey} className="rounded-lg border bg-card p-5 shadow-sm">+ <div className="mb-4 space-y-1">+ <div className="flex items-center gap-2">+ <KeyRound className="h-4 w-4 text-primary" />+ <h2 className="text-base font-semibold">{t.localApiAccess}</h2>+ </div>+ <p className="text-sm text-muted-foreground">{t.localApiAccessDesc}</p>+ </div>+ <div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]">+ <label className="grid gap-2">+ <span className={labelClass}>{t.localApiKey}</span>+ <input+ type="password"+ value={localApiKey}+ onChange={(event) => setLocalApiKeyState(event.target.value)}+ className={fieldClass}+ placeholder={t.localApiKeyHint}+ autoComplete="current-password"+ />+ </label>+ <button+ type="submit"+ className="inline-flex items-center justify-center gap-2 self-end rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90"+ >+ <Save className="h-4 w-4" />+ {t.localApiKeySave}+ </button>+ </div>+ <p className="mt-2 text-xs text-muted-foreground">{t.localApiKeyHint}</p>+ </form>+ );+if (loading || !form || !settings || !dataSettings) {return (- <div className="flex h-[60vh] items-center justify-center text-muted-foreground">- <Loader2 className="mr-2 h-4 w-4 animate-spin" />- {t.loading}+ <div className="mx-auto max-w-5xl space-y-6 p-6">+ <div className="space-y-2">+ <h1 className="text-2xl font-semibold tracking-tight">{t.settings}</h1>+ <p className="max-w-3xl text-sm text-muted-foreground">{t.settingsDesc}</p>+ </div>+ {localApiAccessSection}+ <div className="flex min-h-32 items-center justify-center rounded-lg border bg-card p-5 text-sm text-muted-foreground">+ {settingsLoadError ? (+ <div className="text-center">+ <div className="font-medium text-foreground">{t.settingsUnavailable}</div>+ <div className="mt-1">{settingsLoadError}</div>+ </div>+ ) : (+ <>+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ {t.loading}+ </>+ )}+ </div></div>);}@@ -160,6 +226,8 @@ export function Settings() {<p className="max-w-3xl text-sm text-muted-foreground">{t.settingsDesc}</p></div>+ {localApiAccessSection}+<div className="space-y-2"><h2 className="text-lg font-semibold tracking-tight">{t.llmSettings}</h2><p className="max-w-3xl text-sm text-muted-foreground">{t.llmSettingsDesc}</p>