Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat: QVeris paid data marketplace integration (pluggable, single-commit revertable)

Haozhe Wube117a24b42f
diff --git a/README.md b/README.md
index 27a2509b7..76ec36024 100644
--- a/README.md
+++ b/README.md
@@ -287,7 +287,7 @@ Most runs follow the same evidence path: route the request, load the right marke
## 📡 Data Sources & Smart Fallback
-One `get_market_data` call, **18 market-data sources**. Set `source: "auto"` — the loader picks by symbol, then walks a per-market chain ordered by **IP-ban risk**: never-banned public sources first, throttled / key-gated ones last. Zero config, no single point of failure.
+One `get_market_data` call, **18 free market-data sources** (plus the optional **QVeris** premium marketplace). Set `source: "auto"` — the loader picks by symbol, then walks a per-market chain ordered by **IP-ban risk**: never-banned public sources first, throttled / key-gated ones last. Zero config, no single point of failure.
| Source | Markets | Auth | Role |
|--------|---------|------|------|
@@ -298,6 +298,7 @@ One `get_market_data` call, **18 market-data sources**. Set `source: "auto"` —
| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |
| `yfinance` | US / HK | none | wrapper |
| `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |
+| `qveris` | global multi-asset | key · credits | **premium marketplace** — 63+ providers via one key (explicit-only, never in auto fallback) |
| `okx` · `ccxt` | crypto | none | OKX + 100+ exchanges |
| `futu` | HK / A | OpenD | optional local FutuOpenD |
| `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |
@@ -311,6 +312,16 @@ One `get_market_data` call, **18 market-data sources**. Set `source: "auto"` —
Beyond OHLCV, **18 read-only data tools** reach into fundamentals & flow — fund flow, dragon-tiger, northbound, margin, block trades, shareholder count, lockup, sector, research reports, news, SEC filings, financial statements, options chains, institutional holdings, market screening, symbol search, and macro — all exposed over MCP. An explicit `local:` symbol never silently falls back to a network source.
+<!-- QVERIS-START -->
+### 💎 Optional premium data — QVeris
+
+<img src="https://www.qveris.com/logo-color.png" alt="QVeris" height="36">
+
+**Data: free routing or premium, your choice.** Free stays the default: 18 built-in sources with ban-risk fallback, no key, no cost. Premium via QVeris adds 10,000+ capabilities (per QVeris) across 63+ providers for options Greeks, premium fundamentals, China/HK/global data, macro, crypto, news, and filings; failed calls are not charged. Enable it in Settings -> QVeris or `vibe-trading data mode paid`.
+
+*QVeris disclosure: [signing up through the Vibe-Trading referral link](https://qveris.ai/?ref=Vyjjo5G_1cAHJA) gets you **+1,000 bonus credits** and supports the project.*
+<!-- QVERIS-END -->
+
---
## 🔩 Detailed Capabilities
@@ -318,21 +329,22 @@ Beyond OHLCV, **18 read-only data tools** reach into fundamentals & flow — fun
Detailed inventories are folded below to keep the main README scannable. Open them when you want to inspect the available building blocks.
<details>
-<summary><b>Finance Skill Library</b> <sub>79 skills across 8 categories</sub></summary>
+<summary><b>Finance Skill Library</b> <sub>86 skills across 9 categories</sub></summary>
-- 📊 79 specialized finance skills organized into 8 categories
+- 📊 86 specialized finance skills organized into 9 categories
- 🌐 Complete coverage from traditional markets to crypto & DeFi
- 🔬 Comprehensive capabilities spanning data sourcing to quantitative research
| Category | Skills | Examples |
|----------|--------|----------|
-| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` |
-| Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |
-| Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` |
+| Data Source | 10 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar`, `qveris` |
+| Strategy | 19 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |
+| Analysis | 21 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` |
| Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |
| Crypto | 7 | `perp-funding-basis`, `liquidation-heatmap`, `stablecoin-flow`, `defi-yield`, `onchain-analysis` |
-| Flow | 7 | `hk-connect-flow`, `us-etf-flow`, `edgar-sec-filings`, `financial-statement`, `adr-hshare` |
-| Tool | 11 | `backtest-diagnose`, `report-generate`, `pine-script`, `doc-reader`, `web-reader`, `vnpy-export`, `alpha-zoo` |
+| Flow | 8 | `hk-connect-flow`, `us-etf-flow`, `edgar-sec-filings`, `financial-statement`, `adr-hshare` |
+| Tool | 10 | `backtest-diagnose`, `report-generate`, `pine-script`, `doc-reader`, `web-reader`, `vnpy-export`, `trade-journal` |
+| Research | 1 | `alpha-zoo` |
| Risk Analysis | 1 | `ashare-pre-st-filter` |
</details>
@@ -633,7 +645,7 @@ vibe-trading provider doctor # print redacted provider/proxy/package diagnostic
| Command | Description |
|---------|-------------|
| `/help` | Show all commands |
-| `/skills` | List all 79 finance skills |
+| `/skills` | List all 86 finance skills |
| `/swarm` | List 29 swarm team presets |
| `/swarm run <preset> [vars_json]` | Run a swarm team with live streaming |
| `/swarm list` | Swarm run history |
@@ -970,7 +982,7 @@ Browse on ClawHub: [clawhub.ai/skills/vibe-trading](https://clawhub.ai/skills/vi
<details>
<summary><b>OpenSpace — self-evolving skills</b></summary>
-All 79 finance skills are published on [open-space.cloud](https://open-space.cloud) and evolve autonomously through OpenSpace's self-evolution engine.
+All 86 finance skills are published on [open-space.cloud](https://open-space.cloud) and evolve autonomously through OpenSpace's self-evolution engine.
To use with OpenSpace, add both MCP servers to your agent config:
@@ -992,7 +1004,7 @@ To use with OpenSpace, add both MCP servers to your agent config:
}
```
-OpenSpace will auto-discover all 79 skills, enabling auto-fix, auto-improve, and community sharing. Search for Vibe-Trading skills via `search_skills("finance backtest")` in any OpenSpace-connected agent.
+OpenSpace will auto-discover all 86 skills, enabling auto-fix, auto-improve, and community sharing. Search for Vibe-Trading skills via `search_skills("finance backtest")` in any OpenSpace-connected agent.
</details>
@@ -1179,7 +1191,7 @@ Vibe-Trading/
│ │ ├── agent/ # ReAct agent core
│ │ │ ├── loop.py # 5-layer compression + read/write tool batching
│ │ │ ├── context.py # system prompt + auto-recall from persistent memory
-│ │ │ ├── skills.py # skill loader (79 bundled + user-created via CRUD)
+│ │ │ ├── skills.py # skill loader (86 bundled + user-created via CRUD)
│ │ │ ├── tools.py # tool base class + registry
│ │ │ ├── memory.py # lightweight workspace state per run
│ │ │ ├── frontmatter.py # shared YAML frontmatter parser
@@ -1206,7 +1218,7 @@ Vibe-Trading/
│ │ ├── api/ # FastAPI route modules
│ │ │ └── alpha_routes.py # /alpha/list, /alpha/{id}, /alpha/bench, SSE stream
│ │ │
-│ │ ├── skills/ # 79 finance skills in 8 categories (SKILL.md each)
+│ │ ├── skills/ # 86 finance skills in 9 categories (SKILL.md each)
│ │ ├── swarm/ # Swarm DAG execution engine
│ │ │ └── presets/ # 29 swarm preset YAML definitions
│ │ ├── session/ # Multi-turn chat + FTS5 session search
@@ -1214,7 +1226,7 @@ Vibe-Trading/
│ │
│ └── backtest/ # Backtest engines
│ ├── engines/ # 7 engines + composite cross-market engine + options_portfolio
-│ ├── loaders/ # 18 sources: tushare, okx, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp
+│ ├── loaders/ # 19 sources: tushare, okx, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, qveris
│ │ ├── base.py # DataLoader Protocol
│ │ └── registry.py # Registry + auto-fallback chains
│ └── optimizers/ # MVO, equal vol, max div, risk parity
diff --git a/README_ar.md b/README_ar.md
index 7f19ee8ae..c5c3899eb 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -284,7 +284,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
## 📡 مصادر البيانات والتراجع الذكي
-استدعاء واحد لـ `get_market_data`، **18 مصدر بيانات سوقية**. اضبط `source: "auto"` — يختار المُحمّل حسب الرمز، ثم يسير عبر سلسلة لكل سوق مرتبة بحسب **خطر حظر عنوان IP**: المصادر العامة التي لا تُحظر أبداً أولاً، والمصادر المُقيّدة أو المحمية بمفتاح أخيراً. بلا أي إعداد، ولا نقطة فشل واحدة.
+استدعاء واحد لـ `get_market_data`، **18 مصدر بيانات سوقية مجانية** (إضافة إلى سوق مدفوع اختياري **QVeris**). اضبط `source: "auto"` — يختار المُحمّل حسب الرمز، ثم يسير عبر سلسلة لكل سوق مرتبة بحسب **خطر حظر عنوان IP**: المصادر العامة التي لا تُحظر أبداً أولاً، والمصادر المُقيّدة أو المحمية بمفتاح أخيراً. بلا أي إعداد، ولا نقطة فشل واحدة.
| Source | Markets | Auth | Role |
|--------|---------|------|------|
@@ -295,6 +295,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |
| `yfinance` | US / HK | none | wrapper |
| `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |
+| `qveris` | أصول عالمية متعددة | key · credits | **سوق مدفوع** — 63+ مزوداً بمفتاح واحد (اختيار صريح فقط، خارج التراجع التلقائي) |
| `okx` · `ccxt` | crypto | none | OKX + 100+ exchanges |
| `futu` | HK / A | OpenD | optional local FutuOpenD |
| `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |
@@ -308,6 +309,16 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
إلى جانب OHLCV، تصل **18 أداة بيانات للقراءة فقط** إلى الأساسيات والتدفقات — تدفق الأموال، والتنين والنمر، والتدفق الشمالي، والهامش، والصفقات الكتلية، وعدد المساهمين، وفترة الإغلاق، والقطاعات، وتقارير الأبحاث، والأخبار، وإيداعات SEC، والقوائم المالية، وسلاسل الخيارات، والحيازات المؤسسية، وفحص السوق، والبحث عن الرموز، والاقتصاد الكلي — وكلها مكشوفة عبر MCP. ولا يتراجع رمز `local:` صريح أبداً وبصمت إلى مصدر شبكي.
+<!-- QVERIS-START -->
+### 💎 بيانات مدفوعة اختيارية — QVeris
+
+<img src="https://www.qveris.com/logo-color.png" alt="QVeris" height="36">
+
+**البيانات المجانية هي الافتراضي، والمدفوعة عند الحاجة.** تبقى المصادر الـ18 المدمجة مجانية مع تراجع ذكي بحسب خطر الحظر، بلا مفتاح ولا تكلفة. عبر QVeris يفتح مفتاح واحد 63+ مزوداً و10,000+ capabilities (per QVeris) للـ options Greeks، والأساسيات المتقدمة، وبيانات الصين/هونغ كونغ/العالم، والماكرو، والكريبتو، والأخبار، والـ filings؛ ولا تُحتسب المكالمات الفاشلة. فعّله من Settings → QVeris أو `vibe-trading data mode paid`.
+
+*QVeris disclosure: التسجيل عبر [رابط إحالة Vibe-Trading](https://qveris.ai/?ref=Vyjjo5G_1cAHJA) يمنحك **+1,000 رصيداً** إضافياً ويدعم المشروع.*
+<!-- QVERIS-END -->
+
---
## 🔩 القدرات التفصيلية
@@ -315,21 +326,22 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
القوائم التفصيلية مطوية أدناه حتى يبقى README سهل القراءة. افتحها عندما تريد فحص اللبنات المتاحة.
<details>
-<summary><b>مكتبة المهارات المالية</b> <sub>79 مهارة عبر 8 فئات</sub></summary>
+<summary><b>مكتبة المهارات المالية</b> <sub>86 مهارة عبر 9 فئات</sub></summary>
-- 📊 79 مهارة مالية متخصصة منظمة في 8 فئات
+- 📊 86 مهارة مالية متخصصة منظمة في 9 فئات
- 🌐 تغطية كاملة من الأسواق التقليدية إلى الكريبتو وDeFi
- 🔬 قدرات شاملة من مصادر البيانات إلى البحث الكمي
| الفئة | المهارات | أمثلة |
|----------|--------|----------|
-| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` |
-| Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |
-| Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` |
+| Data Source | 10 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar`, `qveris` |
+| Strategy | 19 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |
+| Analysis | 21 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` |
| Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |
| Crypto | 7 | `perp-funding-basis`, `liquidation-heatmap`, `stablecoin-flow`, `defi-yield`, `onchain-analysis` |
-| Flow | 7 | `hk-connect-flow`, `us-etf-flow`, `edgar-sec-filings`, `financial-statement`, `adr-hshare` |
-| Tool | 11 | `backtest-diagnose`, `report-generate`, `pine-script`, `doc-reader`, `web-reader`, `vnpy-export`, `alpha-zoo` |
+| Flow | 8 | `hk-connect-flow`, `us-etf-flow`, `edgar-sec-filings`, `financial-statement`, `adr-hshare` |
+| Tool | 10 | `backtest-diagnose`, `report-generate`, `pine-script`, `doc-reader`, `web-reader`, `vnpy-export`, `trade-journal` |
+| Research | 1 | `alpha-zoo` |
| Risk Analysis | 1 | `ashare-pre-st-filter` |
</details>
@@ -619,7 +631,7 @@ vibe-trading channels status --local # فحص إعدادات قنوات IM وت
| الأمر | الوصف |
|---------|-------------|
| `/help` | عرض كل الأوامر |
-| `/skills` | عرض كل المهارات المالية الـ 79 |
+| `/skills` | عرض كل المهارات المالية الـ 86 |
| `/swarm` | عرض إعدادات فرق السرب الـ 29 |
| `/swarm run <preset> [vars_json]` | تشغيل فريق سرب مع بث مباشر |
| `/swarm list` | سجل تشغيلات السرب |
@@ -929,7 +941,7 @@ npx clawhub@latest install vibe-trading --force
<details>
<summary><b>OpenSpace — مهارات ذاتية التطور</b></summary>
-كل المهارات المالية الـ 79 منشورة على [open-space.cloud](https://open-space.cloud) وتتطور ذاتياً عبر محرك التطور الذاتي في OpenSpace.
+كل المهارات المالية الـ 86 منشورة على [open-space.cloud](https://open-space.cloud) وتتطور ذاتياً عبر محرك التطور الذاتي في OpenSpace.
للاستخدام مع OpenSpace، أضف خادمي MCP إلى إعداد وكيلك:
@@ -951,7 +963,7 @@ npx clawhub@latest install vibe-trading --force
}
```
-سيكتشف OpenSpace كل المهارات الـ 79 تلقائياً، مما يتيح auto-fix وauto-improve والمشاركة المجتمعية. ابحث عن مهارات Vibe-Trading عبر `search_skills("finance backtest")` في أي وكيل متصل بـ OpenSpace.
+سيكتشف OpenSpace كل المهارات الـ 86 تلقائياً، مما يتيح auto-fix وauto-improve والمشاركة المجتمعية. ابحث عن مهارات Vibe-Trading عبر `search_skills("finance backtest")` في أي وكيل متصل بـ OpenSpace.
</details>
@@ -973,7 +985,7 @@ Vibe-Trading/
│ │ ├── agent/ # ReAct agent core
│ │ │ ├── loop.py # 5-layer compression + read/write tool batching
│ │ │ ├── context.py # system prompt + auto-recall from persistent memory
-│ │ │ ├── skills.py # skill loader (79 bundled + user-created via CRUD)
+│ │ │ ├── skills.py # skill loader (86 bundled + user-created via CRUD)
│ │ │ ├── tools.py # tool base class + registry
│ │ │ ├── memory.py # lightweight workspace state per run
│ │ │ ├── frontmatter.py # shared YAML frontmatter parser
@@ -1000,7 +1012,7 @@ Vibe-Trading/
│ │ ├── api/ # وحدات مسارات FastAPI
│ │ │ └── alpha_routes.py # /alpha/list, /alpha/{id}, /alpha/bench, SSE stream
│ │ │
-│ │ ├── skills/ # 79 finance skills in 8 categories (SKILL.md each)
+│ │ ├── skills/ # 86 finance skills in 9 categories (SKILL.md each)
│ │ ├── swarm/ # Swarm DAG execution engine
│ │ │ └── presets/ # 29 swarm preset YAML definitions
│ │ ├── session/ # Multi-turn chat + FTS5 session search
@@ -1008,7 +1020,7 @@ Vibe-Trading/
│ │
│ └── backtest/ # Backtest engines
│ ├── engines/ # 7 engines + composite cross-market engine + options_portfolio
-│ ├── loaders/ # 18 sources: tushare, okx, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp
+│ ├── loaders/ # 19 sources: tushare, okx, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, qveris
│ │ ├── base.py # DataLoader Protocol
│ │ └── registry.py # Registry + auto-fallback chains
│ └── optimizers/ # MVO, equal vol, max div, risk parity
diff --git a/README_ja.md b/README_ja.md
index 754543085..8a03cd589 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -284,7 +284,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
## 📡 データソースとスマートフォールバック
-1 回の `get_market_data` 呼び出しで **18 のマーケットデータソース**にアクセスできます。`source: "auto"` を指定すれば、loader が銘柄に応じてソースを選び、**IP 規制リスク**の順に並んだ市場別チェーンをたどります。規制を受けない公開ソースを先に、スロットリングや key を要するソースを最後に試します。設定不要、単一障害点なし。
+1 回の `get_market_data` 呼び出しで **18 の無料マーケットデータソース**(およびオプションの有料マーケットプレイス **QVeris**)にアクセスできます。`source: "auto"` を指定すれば、loader が銘柄に応じてソースを選び、**IP 規制リスク**の順に並んだ市場別チェーンをたどります。規制を受けない公開ソースを先に、スロットリングや key を要するソースを最後に試します。設定不要、単一障害点なし。
| Source | Markets | Auth | Role |
|--------|---------|------|------|
@@ -295,6 +295,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |
| `yfinance` | US / HK | none | wrapper |
| `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |
+| `qveris` | グローバル・マルチアセット | key · credits | **プレミアムマーケットプレイス** — 1つの key で 63+ providers(明示指定のみ、auto フォールバック対象外) |
| `okx` · `ccxt` | crypto | none | OKX + 100+ exchanges |
| `futu` | HK / A | OpenD | optional local FutuOpenD |
| `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |
@@ -308,6 +309,16 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
OHLCV にとどまらず、**18 の読み取り専用データツール**がファンダメンタルズと資金フローまで踏み込みます。資金フロー、龍虎榜、北向資金、信用取引、大口取引、株主数、ロックアップ、セクター、調査レポート、ニュース、SEC filings、財務諸表、オプションチェーン、機関投資家保有、市場スクリーニング、銘柄検索、マクロまで、すべて MCP 経由で公開されます。明示的な `local:` 銘柄が暗黙のうちにネットワークソースへフォールバックすることは決してありません。
+<!-- QVERIS-START -->
+### 💎 オプションのプレミアムデータ — QVeris
+
+<img src="https://www.qveris.com/logo-color.png" alt="QVeris" height="36">
+
+**データは無料ルーティングが標準、必要なときだけプレミアム。** 既定では 18 の内蔵ソースが自動フォールバックし、key も費用も不要です。QVeris を使うと、63+ providers と 10,000+ capabilities(per QVeris)で、オプション Greeks、高度なファンダメンタルズ、中国・香港・グローバルデータ、マクロ、暗号資産、ニュース、filings を補えます。失敗した call は課金されません。Settings → QVeris または `vibe-trading data mode paid` で有効化できます。
+
+*QVeris disclosure: [Vibe-Trading の紹介リンク](https://qveris.ai/?ref=Vyjjo5G_1cAHJA) から登録すると **+1,000 クレジット** が追加付与され、プロジェクトの支援にもなります。*
+<!-- QVERIS-END -->
+
---
## 🔩 詳細な機能
@@ -315,21 +326,22 @@ OHLCV にとどまらず、**18 の読み取り専用データツール**がフ
メイン README を読みやすく保つため、詳細な一覧は以下に折りたたんでいます。利用できる構成要素を確認したいときに開いてください。
<details>
-<summary><b>Finance Skill Library</b> <sub>8カテゴリにわたる79 skills</sub></summary>
+<summary><b>Finance Skill Library</b> <sub>9カテゴリにわたる86 skills</sub></summary>
-- 📊 79 の金融特化 skills を 8 カテゴリに整理
+- 📊 86 の金融特化 skills を 9 カテゴリに整理
- 🌐 伝統的市場から crypto & DeFi まで完全カバー
- 🔬 データ取得からクオンツリサーチまでを横断する包括的能力
| Category | Skills | Examples |
|----------|--------|----------|
-| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` |
-| Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |
-| Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` |
+| Data Source | 10 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar`, `qveris` |
+| Strategy | 19 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |
+| Analysis | 21 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` |
| Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |
| Crypto | 7 | `perp-funding-basis`, `liquidation-heatmap`, `stablecoin-flow`, `defi-yield`, `onchain-analysis` |
-| Flow | 7 | `hk-connect-flow`, `us-etf-flow`, `edgar-sec-filings`, `financial-statement`, `adr-hshare` |
-| Tool | 11 | `backtest-diagnose`, `report-generate`, `pine-script`, `doc-reader`, `web-reader`, `vnpy-export`, `alpha-zoo` |
+| Flow | 8 | `hk-connect-flow`, `us-etf-flow`, `edgar-sec-filings`, `financial-statement`, `adr-hshare` |
+| Tool | 10 | `backtest-diagnose`, `report-generate`, `pine-script`, `doc-reader`, `web-reader`, `vnpy-export`, `trade-journal` |
+| Research | 1 | `alpha-zoo` |
| Risk Analysis | 1 | `ashare-pre-st-filter` |
</details>
@@ -619,7 +631,7 @@ vibe-trading channels status --local # IM チャンネル設定と install hint
| Command | Description |
|---------|-------------|
| `/help` | 全コマンドを表示 |
-| `/skills` | 79 finance skills を一覧表示 |
+| `/skills` | 86 finance skills を一覧表示 |
| `/swarm` | 29 swarm team presets を一覧表示 |
| `/swarm run <preset> [vars_json]` | live streaming で swarm team を実行 |
| `/swarm list` | Swarm run history |
@@ -926,7 +938,7 @@ ClawHub で見る: [clawhub.ai/skills/vibe-trading](https://clawhub.ai/skills/vi
<details>
<summary><b>OpenSpace — self-evolving skills</b></summary>
-79 の finance skills はすべて [open-space.cloud](https://open-space.cloud) に公開され、OpenSpace の self-evolution engine を通じて自律的に進化します。
+86 の finance skills はすべて [open-space.cloud](https://open-space.cloud) に公開され、OpenSpace の self-evolution engine を通じて自律的に進化します。
OpenSpace と使うには、agent config に両方の MCP servers を追加してください。
@@ -948,7 +960,7 @@ OpenSpace と使うには、agent config に両方の MCP servers を追加し
}
```
-OpenSpace は 79 skills を自動検出し、auto-fix、auto-improve、community sharing を可能にします。OpenSpace-connected agent では `search_skills("finance backtest")` から Vibe-Trading skills を検索できます。
+OpenSpace は 86 skills を自動検出し、auto-fix、auto-improve、community sharing を可能にします。OpenSpace-connected agent では `search_skills("finance backtest")` から Vibe-Trading skills を検索できます。
</details>
@@ -970,7 +982,7 @@ Vibe-Trading/
│ │ ├── agent/ # ReAct エージェントコア
│ │ │ ├── loop.py # 5 層コンテキスト圧縮 + read/write ツールバッチング
│ │ │ ├── context.py # システムプロンプト + 永続メモリからの自動 recall
-│ │ │ ├── skills.py # skill ローダー(79 個同梱 + CRUD でユーザー作成)
+│ │ │ ├── skills.py # skill ローダー(86 個同梱 + CRUD でユーザー作成)
│ │ │ ├── tools.py # ツール基底クラス + レジストリ
│ │ │ ├── memory.py # run ごとの軽量ワークスペース状態
│ │ │ ├── frontmatter.py # 共有 YAML frontmatter パーサー
@@ -997,7 +1009,7 @@ Vibe-Trading/
│ │ ├── api/ # FastAPI ルートモジュール
│ │ │ └── alpha_routes.py # /alpha/list、/alpha/{id}、/alpha/bench、SSE ストリーム
│ │ │
-│ │ ├── skills/ # 8 カテゴリ 79 個の finance skills(各 SKILL.md)
+│ │ ├── skills/ # 9 カテゴリ 86 個の finance skills(各 SKILL.md)
│ │ ├── swarm/ # Swarm DAG 実行エンジン
│ │ │ └── presets/ # 29 個の swarm preset YAML 定義
│ │ ├── session/ # マルチターンチャット + FTS5 セッション検索
@@ -1005,7 +1017,7 @@ Vibe-Trading/
│ │
│ └── backtest/ # バックテストエンジン
│ ├── engines/ # 7 エンジン + クロスマーケット composite engine + options_portfolio
-│ ├── loaders/ # 18 ソース: tushare、okx、yfinance、akshare、baostock、tencent、mootdx、ccxt、futu、local、eastmoney、sina、stooq、yahoo、finnhub、alphavantage、tiingo、fmp
+│ ├── loaders/ # 19 ソース: tushare、okx、yfinance、akshare、baostock、tencent、mootdx、ccxt、futu、local、eastmoney、sina、stooq、yahoo、finnhub、alphavantage、tiingo、fmp、qveris
│ │ ├── base.py # DataLoader Protocol
│ │ └── registry.py # Registry + 自動フォールバックチェーン
│ └── optimizers/ # MVO、equal vol、max div、risk parity
diff --git a/README_ko.md b/README_ko.md
index 4d122ecd6..b7cc0ebab 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -284,7 +284,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
## 📡 데이터 소스 & 스마트 폴백
-`get_market_data` 한 번의 호출, **18개 시장 데이터 소스**. `source: "auto"`로 설정하면 로더가 심볼에 따라 소스를 고르고, 시장별 체인을 **IP 차단 위험** 순으로 따라갑니다: 절대 차단되지 않는 공개 소스를 먼저, 속도 제한 / 키 기반 소스를 마지막에 둡니다. 설정 불필요, 단일 장애 지점 없음.
+`get_market_data` 한 번의 호출, **18개 무료 시장 데이터 소스**(선택형 유료 마켓플레이스 **QVeris** 별도). `source: "auto"`로 설정하면 로더가 심볼에 따라 소스를 고르고, 시장별 체인을 **IP 차단 위험** 순으로 따라갑니다: 절대 차단되지 않는 공개 소스를 먼저, 속도 제한 / 키 기반 소스를 마지막에 둡니다. 설정 불필요, 단일 장애 지점 없음.
| Source | Markets | Auth | Role |
|--------|---------|------|------|
@@ -295,6 +295,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |
| `yfinance` | US / HK | none | wrapper |
| `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |
+| `qveris` | 글로벌 멀티에셋 | key · credits | **프리미엄 마켓플레이스** — key 하나로 63+ providers (명시 지정 전용, auto 폴백 제외) |
| `okx` · `ccxt` | crypto | none | OKX + 100+ exchanges |
| `futu` | HK / A | OpenD | optional local FutuOpenD |
| `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |
@@ -308,6 +309,16 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
OHLCV를 넘어 **18개 읽기 전용 데이터 도구**가 펀더멘털과 자금 흐름까지 닿습니다 — 자금 흐름, 용호방(dragon-tiger), 북향(northbound), 신용거래, 대종거래, 주주 수, 보호예수, 섹터, 리서치 리포트, 뉴스, SEC 공시, 재무제표, 옵션 체인, 기관 보유, 시장 스크리닝, 심볼 검색, 매크로 — 모두 MCP로 노출됩니다. 명시적인 `local:` 심볼은 절대 조용히 네트워크 소스로 폴백하지 않습니다.
+<!-- QVERIS-START -->
+### 💎 선택형 프리미엄 데이터 — QVeris
+
+<img src="https://www.qveris.com/logo-color.png" alt="QVeris" height="36">
+
+**데이터는 기본 무료 라우팅, 필요할 때만 프리미엄.** 기본값은 18개 내장 소스와 차단 위험 기반 폴백이며 key도 비용도 없습니다. QVeris를 켜면 63+ providers와 10,000+ capabilities(per QVeris)로 옵션 Greeks, 고급 펀더멘털, 중국/홍콩/글로벌 데이터, 매크로, 크립토, 뉴스, filings를 보강할 수 있고 실패한 호출은 과금되지 않습니다. Settings → QVeris 또는 `vibe-trading data mode paid`에서 활성화하세요.
+
+*QVeris disclosure: [Vibe-Trading 추천 링크](https://qveris.ai/?ref=Vyjjo5G_1cAHJA)로 가입하면 **+1,000 크레딧**을 추가로 받고 프로젝트를 후원하게 됩니다.*
+<!-- QVERIS-END -->
+
---
## 🔩 상세 기능
@@ -315,21 +326,22 @@ OHLCV를 넘어 **18개 읽기 전용 데이터 도구**가 펀더멘털과 자
메인 README를 읽기 쉽게 유지하기 위해 상세 목록은 아래에 접어 두었습니다. 사용 가능한 구성 요소를 확인하고 싶을 때 열어보세요.
<details>
-<summary><b>금융 스킬 라이브러리</b> <sub>8개 카테고리 79개 스킬</sub></summary>
+<summary><b>금융 스킬 라이브러리</b> <sub>9개 카테고리 86개 스킬</sub></summary>
-- 📊 8개 카테고리로 구성된 79개 전문 금융 스킬
+- 📊 9개 카테고리로 구성된 86개 전문 금융 스킬
- 🌐 전통 시장부터 크립토 & DeFi까지 완전한 커버리지
- 🔬 데이터 sourcing부터 정량 리서치까지 포괄하는 기능
| 카테고리 | 스킬 | 예시 |
|----------|------|------|
-| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` |
-| Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |
-| Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` |
+| Data Source | 10 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar`, `qveris` |
+| Strategy | 19 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |
+| Analysis | 21 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` |
| Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |
| Crypto | 7 | `perp-funding-basis`, `liquidation-heatmap`, `stablecoin-flow`, `defi-yield`, `onchain-analysis` |
-| Flow | 7 | `hk-connect-flow`, `us-etf-flow`, `edgar-sec-filings`, `financial-statement`, `adr-hshare` |
-| Tool | 11 | `backtest-diagnose`, `report-generate`, `pine-script`, `doc-reader`, `web-reader`, `vnpy-export`, `alpha-zoo` |
+| Flow | 8 | `hk-connect-flow`, `us-etf-flow`, `edgar-sec-filings`, `financial-statement`, `adr-hshare` |
+| Tool | 10 | `backtest-diagnose`, `report-generate`, `pine-script`, `doc-reader`, `web-reader`, `vnpy-export`, `trade-journal` |
+| Research | 1 | `alpha-zoo` |
| Risk Analysis | 1 | `ashare-pre-st-filter` |
</details>
@@ -619,7 +631,7 @@ vibe-trading channels status --local # IM 채널 설정과 설치 힌트 확인
| Command | Description |
|---------|-------------|
| `/help` | 모든 명령 표시 |
-| `/skills` | 79개 finance skills 목록 |
+| `/skills` | 86개 finance skills 목록 |
| `/swarm` | 29개 swarm team presets 목록 |
| `/swarm run <preset> [vars_json]` | live streaming으로 swarm team 실행 |
| `/swarm list` | Swarm run history |
@@ -929,7 +941,7 @@ ClawHub에서 보기: [clawhub.ai/skills/vibe-trading](https://clawhub.ai/skills
<details>
<summary><b>OpenSpace — 자가 진화 스킬</b></summary>
-79개 finance skills는 모두 [open-space.cloud](https://open-space.cloud)에 게시되어 있으며 OpenSpace의 self-evolution engine을 통해 자율적으로 발전합니다.
+86개 finance skills는 모두 [open-space.cloud](https://open-space.cloud)에 게시되어 있으며 OpenSpace의 self-evolution engine을 통해 자율적으로 발전합니다.
OpenSpace와 함께 사용하려면 두 MCP server를 agent config에 추가하세요:
@@ -951,7 +963,7 @@ OpenSpace와 함께 사용하려면 두 MCP server를 agent config에 추가하
}
```
-OpenSpace는 79개 skills를 모두 자동 발견하여 auto-fix, auto-improve, community sharing을 활성화합니다. OpenSpace-connected agent에서 `search_skills("finance backtest")`로 Vibe-Trading skills를 검색하세요.
+OpenSpace는 86개 skills를 모두 자동 발견하여 auto-fix, auto-improve, community sharing을 활성화합니다. OpenSpace-connected agent에서 `search_skills("finance backtest")`로 Vibe-Trading skills를 검색하세요.
</details>
@@ -973,7 +985,7 @@ Vibe-Trading/
│ │ ├── agent/ # ReAct agent core
│ │ │ ├── loop.py # 5-layer compression + read/write tool batching
│ │ │ ├── context.py # system prompt + auto-recall from persistent memory
-│ │ │ ├── skills.py # skill loader (79 bundled + user-created via CRUD)
+│ │ │ ├── skills.py # skill loader (86 bundled + user-created via CRUD)
│ │ │ ├── tools.py # tool base class + registry
│ │ │ ├── memory.py # lightweight workspace state per run
│ │ │ ├── frontmatter.py # shared YAML frontmatter parser
@@ -1000,7 +1012,7 @@ Vibe-Trading/
│ │ ├── api/ # FastAPI 라우트 모듈
│ │ │ └── alpha_routes.py # /alpha/list, /alpha/{id}, /alpha/bench, SSE stream
│ │ │
-│ │ ├── skills/ # 79 finance skills in 8 categories (SKILL.md each)
+│ │ ├── skills/ # 86 finance skills in 9 categories (SKILL.md each)
│ │ ├── swarm/ # Swarm DAG execution engine
│ │ │ └── presets/ # 29 swarm preset YAML definitions
│ │ ├── session/ # Multi-turn chat + FTS5 session search
@@ -1008,7 +1020,7 @@ Vibe-Trading/
│ │
│ └── backtest/ # Backtest engines
│ ├── engines/ # 7 engines + composite cross-market engine + options_portfolio
-│ ├── loaders/ # 18 sources: tushare, okx, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp
+│ ├── loaders/ # 19 sources: tushare, okx, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, qveris
│ │ ├── base.py # DataLoader Protocol
│ │ └── registry.py # Registry + auto-fallback chains
│ └── optimizers/ # MVO, equal vol, max div, risk parity
diff --git a/README_zh.md b/README_zh.md
index f6bdd9174..446b97a51 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -285,7 +285,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
## 📡 数据源与智能 Fallback
-一次 `get_market_data` 调用,**18 个行情数据源**。设 `source: "auto"`——loader 按符号自动选源,再沿按 **被封 IP 风险** 排序的同市场链向下走(永不封的公开源在前,限速 / 需 key 的在后)。零配置,无单点故障。
+一次 `get_market_data` 调用,**18 个免费行情数据源**(另有可选付费市场 **QVeris**)。设 `source: "auto"`——loader 按符号自动选源,再沿按 **被封 IP 风险** 排序的同市场链向下走(永不封的公开源在前,限速 / 需 key 的在后)。零配置,无单点故障。
| Source | Markets | Auth | Role |
|--------|---------|------|------|
@@ -296,6 +296,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
| `yahoo` · `sina` · `stooq` | US (/HK) | none | direct chart/quotes/options · K-line to 1984 · EOD CSV |
| `yfinance` | US / HK | none | wrapper |
| `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |
+| `qveris` | 全球多资产 | key · credits | **付费市场** — 一把 key 通 63+ 家(仅显式选用,绝不进 auto 链) |
| `okx` · `ccxt` | crypto | none | OKX + 100+ exchanges |
| `futu` | HK / A | OpenD | optional local FutuOpenD |
| `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |
@@ -309,6 +310,16 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
除 OHLCV 外,**18 个只读数据工具**深入基本面与资金面——资金流、龙虎榜、北向、两融、大宗交易、股东户数、解禁、板块、研报、新闻、SEC 文件、财务报表、期权链、机构持仓、全市场筛选、代码搜索、宏观——全部经 MCP 暴露。显式 `local:` 源永不静默 fallback 到网络源。
+<!-- QVERIS-START -->
+### 💎 可选付费数据 — QVeris
+
+<img src="https://www.qveris.com/logo-color.png" alt="QVeris" height="36">
+
+**数据可走免费,也可按需上付费。** 默认仍是 18 个内置免费源:自动 fallback、无需 key、无成本。通过 QVeris 可用一个 key 解锁 63+ provider、10,000+ capabilities(per QVeris),覆盖期权 Greeks、高级基本面、中国/港股/全球数据、宏观、加密、新闻与 filings;失败调用不扣费。入口在 Settings → QVeris 或 `vibe-trading data mode paid`。
+
+*QVeris 披露:通过 [Vibe-Trading 推荐链接](https://qveris.ai/?ref=Vyjjo5G_1cAHJA) 注册可额外获得 **1,000 积分**,同时支持本项目。*
+<!-- QVERIS-END -->
+
---
## 🔩 Detailed Capabilities
@@ -316,21 +327,22 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an
为保持主 README 易读,详细清单折叠在下方。需要检查可用构件时可展开查看。
<details>
-<summary><b>Finance Skill Library</b> <sub>8 个类别中的 79 个 skills</sub></summary>
+<summary><b>Finance Skill Library</b> <sub>9 个类别中的 86 个 skills</sub></summary>
-- 📊 79 个专业金融 skills,分布在 8 个类别中
+- 📊 86 个专业金融 skills,分布在 9 个类别中
- 🌐 覆盖传统市场、加密与 DeFi
- 🔬 从数据源到量化研究的完整能力链路
| 类别 | Skills | 示例 |
|------|--------|------|
-| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` |
-| Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |
-| Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` |
+| Data Source | 10 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar`, `qveris` |
+| Strategy | 19 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` |
+| Analysis | 21 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` |
| Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |
| Crypto | 7 | `perp-funding-basis`, `liquidation-heatmap`, `stablecoin-flow`, `defi-yield`, `onchain-analysis` |
-| Flow | 7 | `hk-connect-flow`, `us-etf-flow`, `edgar-sec-filings`, `financial-statement`, `adr-hshare` |
-| Tool | 11 | `backtest-diagnose`, `report-generate`, `pine-script`, `doc-reader`, `web-reader`, `vnpy-export`, `alpha-zoo` |
+| Flow | 8 | `hk-connect-flow`, `us-etf-flow`, `edgar-sec-filings`, `financial-statement`, `adr-hshare` |
+| Tool | 10 | `backtest-diagnose`, `report-generate`, `pine-script`, `doc-reader`, `web-reader`, `vnpy-export`, `trade-journal` |
+| Research | 1 | `alpha-zoo` |
| Risk Analysis | 1 | `ashare-pre-st-filter` |
</details>
@@ -618,7 +630,7 @@ vibe-trading channels status --local # 检查 IM 通道配置和依赖安装提
| 命令 | 说明 |
|------|------|
| `/help` | 显示所有命令 |
-| `/skills` | 列出全部 79 个 finance skills |
+| `/skills` | 列出全部 86 个 finance skills |
| `/swarm` | 列出 29 个 swarm team presets |
| `/swarm run <preset> [vars_json]` | 运行一个 swarm team,并实时流式展示 |
| `/swarm list` | Swarm 运行历史 |
@@ -925,7 +937,7 @@ npx clawhub@latest install vibe-trading --force
<details>
<summary><b>OpenSpace — 自进化 skills</b></summary>
-全部 79 个 finance skills 都发布在 [open-space.cloud](https://open-space.cloud),并通过 OpenSpace 的自进化引擎自主演进。
+全部 86 个 finance skills 都发布在 [open-space.cloud](https://open-space.cloud),并通过 OpenSpace 的自进化引擎自主演进。
要配合 OpenSpace 使用,请将两个 MCP servers 都加入你的 agent config:
@@ -947,7 +959,7 @@ npx clawhub@latest install vibe-trading --force
}
```
-OpenSpace 会自动发现全部 79 个 skills,启用 auto-fix、auto-improve 和社区分享。在任意已连接 OpenSpace 的智能体中,可通过 `search_skills("finance backtest")` 搜索 Vibe-Trading skills。
+OpenSpace 会自动发现全部 86 个 skills,启用 auto-fix、auto-improve 和社区分享。在任意已连接 OpenSpace 的智能体中,可通过 `search_skills("finance backtest")` 搜索 Vibe-Trading skills。
</details>
@@ -969,7 +981,7 @@ Vibe-Trading/
│ │ ├── agent/ # ReAct agent 内核
│ │ │ ├── loop.py # 5 层上下文压缩 + 读/写工具批处理
│ │ │ ├── context.py # system prompt + 持久记忆自动召回
-│ │ │ ├── skills.py # skill loader(79 个内置 + 通过 CRUD 创建的用户 skill)
+│ │ │ ├── skills.py # skill loader(86 个内置 + 通过 CRUD 创建的用户 skill)
│ │ │ ├── tools.py # tool 基类 + 注册表
│ │ │ ├── memory.py # 每个 run 的轻量 workspace 状态
│ │ │ ├── frontmatter.py # 共享的 YAML frontmatter 解析器
@@ -996,7 +1008,7 @@ Vibe-Trading/
│ │ ├── api/ # FastAPI 路由模块
│ │ │ └── alpha_routes.py # /alpha/list、/alpha/{id}、/alpha/bench、SSE 流
│ │ │
-│ │ ├── skills/ # 8 个类别共 79 个 finance skills(每个一份 SKILL.md)
+│ │ ├── skills/ # 9 个类别共 86 个 finance skills(每个一份 SKILL.md)
│ │ ├── swarm/ # Swarm DAG 执行引擎
│ │ │ └── presets/ # 29 个 swarm preset YAML 定义
│ │ ├── session/ # 多轮对话 + FTS5 session 搜索
@@ -1004,7 +1016,7 @@ Vibe-Trading/
│ │
│ └── backtest/ # 回测引擎
│ ├── engines/ # 7 个引擎 + 跨市场 composite 引擎 + options_portfolio
-│ ├── loaders/ # 18 个数据源:tushare、okx、yfinance、akshare、baostock、tencent、mootdx、ccxt、futu、local、eastmoney、sina、stooq、yahoo、finnhub、alphavantage、tiingo、fmp
+│ ├── loaders/ # 19 个数据源:tushare、okx、yfinance、akshare、baostock、tencent、mootdx、ccxt、futu、local、eastmoney、sina、stooq、yahoo、finnhub、alphavantage、tiingo、fmp、qveris
│ │ ├── base.py # DataLoader Protocol
│ │ └── registry.py # Registry + 自动 fallback 链路
│ └── optimizers/ # MVO、equal vol、max div、risk parity
diff --git a/agent/api_server.py b/agent/api_server.py
index ff6e9f5c5..e1756a19f 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -935,6 +935,8 @@ from src.api.uploads_routes import ( # noqa: E402
from src.api.channels_routes import register_channels_routes # noqa: E402
register_channels_routes(app)
+from src.api.qveris_routes import qveris_router # noqa: E402 # QVERIS-INTEGRATION
+app.include_router(qveris_router) # QVERIS-INTEGRATION
# Re-export for test monkeypatch compatibility
from src.api.channels_routes import ( # noqa: F401, E402
diff --git a/agent/backtest/loaders/qveris_loader.py b/agent/backtest/loaders/qveris_loader.py
new file mode 100644
index 000000000..92d9f06a8
--- /dev/null
+++ b/agent/backtest/loaders/qveris_loader.py
@@ -0,0 +1,635 @@
+"""QVeris loader: explicit, key-gated OHLCV fetches through QVeris tools.
+
+This loader is intentionally self-contained for the QVeris integration parcel:
+it reads the shared ``~/.vibe-trading/qveris.json`` config schema, applies the
+``QVERIS_API_KEY`` / ``QVERIS_BASE_URL`` environment overrides, and embeds the
+small HTTP client it needs for ``POST /search``, ``POST /tools/execute``, and
+truncated-result downloads.
+
+QVeris is a paid-capability router, so it must only run when the user explicitly
+requests ``source="qveris"``. The registry keeps it out of every auto fallback
+chain.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Dict, Iterable, List, Optional
+
+import pandas as pd
+import requests
+
+from backtest.loaders.base import (
+ cached_loader_fetch,
+ validate_date_range,
+ validate_ohlc,
+)
+from backtest.loaders.registry import register
+
+logger = logging.getLogger(__name__)
+
+_CONFIG_PATH = Path.home() / ".vibe-trading" / "qveris.json"
+_DEFAULT_BASE_URL = "https://qveris.ai/api/v1"
+_API_KEY_ENV = "QVERIS_API_KEY"
+_BASE_URL_ENV = "QVERIS_BASE_URL"
+_MIN_INTERVAL_ENV = "VIBE_TRADING_QVERIS_MIN_INTERVAL"
+_DEFAULT_MIN_INTERVAL_S = 0.5
+_HTTP_TIMEOUT_S = 30.0
+_MAX_RETRIES = 3
+_OHLCV_COLUMNS = ["open", "high", "low", "close", "volume"]
+_DATE_KEYS = (
+ "trade_date",
+ "date",
+ "datetime",
+ "timestamp",
+ "time",
+ "period",
+)
+_FIELD_ALIASES = {
+ "open": ("open", "o", "1. open"),
+ "high": ("high", "h", "2. high"),
+ "low": ("low", "l", "3. low"),
+ "close": ("close", "c", "adj_close", "adjusted_close", "4. close"),
+ "volume": ("volume", "vol", "v", "5. volume", "6. volume"),
+}
+
+
+@dataclass(frozen=True)
+class QVerisConfig:
+ """Resolved QVeris loader configuration."""
+
+ enabled: bool
+ base_url: str
+ api_key: str
+ mode: str
+
+
+def _load_config() -> QVerisConfig:
+ """Read QVeris config with environment overrides.
+
+ Returns:
+ Resolved config. Missing or malformed config files fall back to the
+ disabled default; env vars only override matching fields and do not
+ implicitly enable the integration.
+ """
+ raw: dict[str, Any] = {
+ "enabled": False,
+ "base_url": _DEFAULT_BASE_URL,
+ "api_key": "",
+ "mode": "free",
+ }
+ try:
+ if _CONFIG_PATH.is_file():
+ loaded = json.loads(_CONFIG_PATH.read_text(encoding="utf-8"))
+ if isinstance(loaded, dict):
+ raw.update(loaded)
+ except Exception as exc: # noqa: BLE001 - config read failures mean unavailable
+ logger.warning("qveris config ignored: %s", exc)
+
+ api_key = os.getenv(_API_KEY_ENV, str(raw.get("api_key") or "")).strip()
+ base_url = os.getenv(_BASE_URL_ENV, str(raw.get("base_url") or _DEFAULT_BASE_URL)).strip()
+ return QVerisConfig(
+ enabled=bool(raw.get("enabled")),
+ base_url=(base_url or _DEFAULT_BASE_URL).rstrip("/"),
+ api_key=api_key,
+ mode=_normalize_mode(str(raw.get("mode") or "free")),
+ )
+
+
+def _normalize_mode(mode: str) -> str:
+ """Normalize QVeris paid-route mode."""
+ return {"preview": "free", "allow_paid": "paid", "free": "free", "paid": "paid"}.get(mode.strip(), "free")
+
+
+def _min_interval() -> float:
+ """Resolve the minimum interval between QVeris requests."""
+ raw = os.getenv(_MIN_INTERVAL_ENV)
+ if raw is None or not raw.strip():
+ return _DEFAULT_MIN_INTERVAL_S
+ try:
+ value = float(raw)
+ except ValueError:
+ logger.warning(
+ "invalid %s=%r, using default %s",
+ _MIN_INTERVAL_ENV,
+ raw,
+ _DEFAULT_MIN_INTERVAL_S,
+ )
+ return _DEFAULT_MIN_INTERVAL_S
+ if value < 0:
+ logger.warning(
+ "negative %s=%r, using default %s",
+ _MIN_INTERVAL_ENV,
+ raw,
+ _DEFAULT_MIN_INTERVAL_S,
+ )
+ return _DEFAULT_MIN_INTERVAL_S
+ return value
+
+
+class QVerisClient:
+ """Minimal QVeris HTTP client for search, execute, and full-result GET."""
+
+ def __init__(self, config: QVerisConfig) -> None:
+ """Initialize a session-bound client.
+
+ Args:
+ config: Resolved QVeris config containing base URL and API key.
+ """
+ self._config = config
+ self._session = requests.Session()
+ self._last_request_at = 0.0
+
+ def search(self, query: str, *, limit: int = 20) -> dict[str, Any]:
+ """Call ``POST /search``.
+
+ Args:
+ query: Natural-language capability query.
+ limit: Maximum result count.
+
+ Returns:
+ Decoded response body.
+ """
+ return self._post_json("/search", {"query": query, "limit": limit})
+
+ def execute(
+ self,
+ tool_id: str,
+ parameters: dict[str, Any],
+ *,
+ search_id: str | None = None,
+ ) -> dict[str, Any]:
+ """Call ``POST /tools/execute`` and hydrate truncated results.
+
+ Args:
+ tool_id: QVeris tool identifier returned by search.
+ parameters: Provider parameters.
+ search_id: Optional search correlation id.
+
+ Returns:
+ Decoded execute response, with ``result`` replaced by downloaded
+ full JSON when QVeris returned ``full_content_file_url``.
+ """
+ body: dict[str, Any] = {
+ "parameters": parameters,
+ "max_response_size": 20480,
+ }
+ if search_id:
+ body["search_id"] = search_id
+ payload = self._post_json(f"/tools/execute?tool_id={tool_id}", body)
+ if isinstance(payload, dict) and isinstance(payload.get("result"), dict):
+ full_url = payload["result"].get("full_content_file_url")
+ if isinstance(full_url, str) and full_url:
+ payload = dict(payload)
+ payload["result"] = self._get_json(full_url)
+ return payload
+
+ def _post_json(self, path: str, body: dict[str, Any]) -> dict[str, Any]:
+ url = f"{self._config.base_url}{path}"
+ response = self._request("post", url, json=body, auth=True)
+ decoded = response.json()
+ return decoded if isinstance(decoded, dict) else {}
+
+ def _get_json(self, url: str) -> Any:
+ response = self._request("get", url, auth=False)
+ try:
+ return response.json()
+ except ValueError:
+ return json.loads(response.text)
+
+ def _request(self, method: str, url: str, *, auth: bool, **kwargs: Any) -> requests.Response:
+ headers = {"User-Agent": "Vibe-Trading/1.0"}
+ if auth:
+ headers["Authorization"] = f"Bearer {self._config.api_key}"
+
+ for attempt in range(_MAX_RETRIES + 1):
+ self._wait()
+ response = self._session.request(
+ method,
+ url,
+ headers=headers,
+ timeout=_HTTP_TIMEOUT_S,
+ **kwargs,
+ )
+ if response.status_code != 429:
+ response.raise_for_status()
+ return response
+ if attempt == _MAX_RETRIES:
+ response.raise_for_status()
+ time.sleep(_retry_after_seconds(response))
+ raise AssertionError("unreachable: retry loop must return or raise")
+
+ def _wait(self) -> None:
+ interval = _min_interval()
+ if interval <= 0:
+ return
+ now = time.monotonic()
+ sleep_for = self._last_request_at + interval - now
+ if sleep_for > 0:
+ time.sleep(sleep_for)
+ self._last_request_at = time.monotonic()
+
+
+def _retry_after_seconds(response: requests.Response) -> float:
+ """Parse a Retry-After header, falling back to the default interval."""
+ raw = response.headers.get("Retry-After", "")
+ try:
+ value = float(raw)
+ except (TypeError, ValueError):
+ value = _min_interval()
+ return max(value, 0.0)
+
+
+@register
+class DataLoader:
+ """QVeris OHLCV loader, available only when explicitly configured."""
+
+ name = "qveris"
+ markets = {"us_equity", "hk_equity", "a_share", "crypto", "forex", "fund", "macro"}
+ requires_auth = True
+
+ def __init__(self) -> None:
+ """Initialize without network access."""
+ self._config = _load_config()
+
+ def is_available(self) -> bool:
+ """Return whether paid QVeris routing is enabled and keyed."""
+ return self._config.enabled and bool(self._config.api_key) and self._config.mode == "paid"
+
+ def fetch(
+ self,
+ codes: List[str],
+ start_date: str,
+ end_date: str,
+ *,
+ interval: str = "1D",
+ fields: Optional[List[str]] = None,
+ ) -> Dict[str, pd.DataFrame]:
+ """Fetch daily OHLCV history through selected QVeris capabilities.
+
+ Args:
+ codes: Symbols to fetch.
+ start_date: Inclusive ``YYYY-MM-DD`` start date.
+ end_date: Inclusive ``YYYY-MM-DD`` end date.
+ interval: Bar interval. QVeris selection is optimized for daily
+ bars; non-daily values are passed through when a tool accepts an
+ interval-like parameter.
+ fields: Ignored; QVeris loader returns the standard OHLCV columns.
+
+ Returns:
+ Mapping of input symbol to normalized OHLCV DataFrames.
+
+ Raises:
+ ValueError: If ``start_date`` > ``end_date``.
+ """
+ del fields
+ validate_date_range(start_date, end_date)
+ if not self.is_available():
+ logger.warning("qveris fetch skipped: disabled or %s not set", _API_KEY_ENV)
+ return {}
+
+ client = QVerisClient(self._config)
+ result: Dict[str, pd.DataFrame] = {}
+ for code in codes:
+ try:
+ df = cached_loader_fetch(
+ source=self.name,
+ symbol=code,
+ timeframe=interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ fetch=lambda code=code: self._fetch_one(
+ client, code, start_date, end_date, interval
+ ),
+ )
+ if df is not None and not df.empty:
+ result[code] = df
+ except Exception as exc: # noqa: BLE001 - one symbol must not abort the batch
+ logger.warning("qveris failed for %s: %s", code, exc)
+ return result
+
+ def _fetch_one(
+ self,
+ client: QVerisClient,
+ code: str,
+ start_date: str,
+ end_date: str,
+ interval: str,
+ ) -> Optional[pd.DataFrame]:
+ search_payload = client.search(_search_query(code, interval))
+ candidates = _select_capabilities(search_payload.get("results"), interval)
+ search_id = _str_or_none(search_payload.get("search_id"))
+ for capability in candidates:
+ tool_id = str(capability.get("tool_id") or "").strip()
+ if not tool_id:
+ continue
+ parameters = _build_parameters(capability, code, start_date, end_date, interval)
+ execute_payload = client.execute(tool_id, parameters, search_id=search_id)
+ if execute_payload.get("success") is False:
+ logger.warning("QVeris execute failed for %s via %s", code, tool_id)
+ continue
+ frame = _result_to_frame(execute_payload.get("result"), start_date, end_date)
+ if frame is not None:
+ return frame
+ logger.warning("QVeris result for %s via %s had no parseable bars", code, tool_id)
+ return None
+
+
+_MAX_CANDIDATES = 3
+
+
+def _search_query(symbol: str, interval: str) -> str:
+ """Build a capability-search query for one symbol."""
+ return f"daily OHLCV historical market data for {symbol.strip().upper()} interval {interval}"
+
+
+def _select_capabilities(results: Any, interval: str) -> list[dict[str, Any]]:
+ """Rank OHLCV-like capabilities, excluding wrong-granularity series."""
+ if not isinstance(results, list):
+ return []
+ wanted, unwanted = _granularity_tokens(interval)
+ candidates = []
+ for item in results:
+ if not isinstance(item, dict) or not _looks_ohlcv(item):
+ continue
+ text = _capability_text(item)
+ if any(token in text for token in unwanted):
+ continue
+ priority = 0 if any(token in text for token in wanted) else 1
+ candidates.append((priority, item))
+ ranked = sorted(candidates, key=lambda pair: (pair[0],) + _capability_rank(pair[1]))
+ return [item for _, item in ranked[:_MAX_CANDIDATES]]
+
+
+def _capability_text(item: dict[str, Any]) -> str:
+ return " ".join(
+ str(item.get(key) or "").lower() for key in ("tool_id", "name", "description")
+ )
+
+
+def _granularity_tokens(interval: str) -> tuple[tuple[str, ...], tuple[str, ...]]:
+ """Return (wanted, unwanted) capability-text tokens for a bar interval."""
+ norm = interval.strip().lower()
+ intraday = ("intraday", "minute", "1min", "5min", "15min", "30min", "60min", "hourly")
+ if norm in ("", "1d", "d", "day", "daily"):
+ return ("daily", "eod", "end-of-day", "end of day"), ("monthly", "weekly") + intraday
+ if "min" in norm or norm in ("1h", "4h") or "hour" in norm:
+ return intraday, ("monthly", "weekly")
+ if "w" in norm or "week" in norm:
+ return ("weekly",), ("monthly",) + intraday
+ if "mo" in norm or "month" in norm:
+ return ("monthly",), ("weekly",) + intraday
+ return (), ()
+
+
+def _looks_ohlcv(item: dict[str, Any]) -> bool:
+ text_parts = [
+ item.get("name"),
+ item.get("description"),
+ item.get("provider_name"),
+ json.dumps(item.get("params") or "", default=str),
+ json.dumps(item.get("examples") or "", default=str),
+ ]
+ text = " ".join(str(part or "").lower() for part in text_parts)
+ has_price = any(token in text for token in ("ohlcv", "open", "high", "low", "close", "candle", "historical price"))
+ has_symbol = any(token in text for token in ("symbol", "ticker", "instrument", "code"))
+ return has_price and has_symbol
+
+
+def _capability_rank(item: dict[str, Any]) -> tuple[float, float, str]:
+ success_rate = _success_rate(item.get("stats"))
+ cost = _expected_cost(item.get("expected_cost"))
+ return (-success_rate, cost, str(item.get("tool_id") or item.get("name") or ""))
+
+
+def _success_rate(stats: Any) -> float:
+ if not isinstance(stats, dict):
+ return 0.0
+ value = stats.get("success_rate", 0.0)
+ try:
+ parsed = float(value)
+ except (TypeError, ValueError):
+ return 0.0
+ return parsed / 100.0 if parsed > 1.0 else parsed
+
+
+def _expected_cost(value: Any) -> float:
+ if value is None:
+ return float("inf")
+ text = str(value)
+ number = ""
+ for char in text:
+ if char.isdigit() or char == ".":
+ number += char
+ elif number:
+ break
+ try:
+ return float(number)
+ except ValueError:
+ return float("inf")
+
+
+def _build_parameters(
+ capability: dict[str, Any],
+ code: str,
+ start_date: str,
+ end_date: str,
+ interval: str,
+) -> dict[str, Any]:
+ """Build an execute parameter object from examples plus known date keys."""
+ parameters = _sample_parameters(capability)
+ for param in capability.get("params") or []:
+ if not isinstance(param, dict):
+ continue
+ name = str(param.get("name") or "").strip()
+ if not name:
+ continue
+ lower = name.lower()
+ if _is_symbol_param(lower):
+ parameters[name] = _provider_symbol(code)
+ elif _is_start_param(lower):
+ parameters[name] = start_date
+ elif _is_end_param(lower):
+ parameters[name] = end_date
+ elif _is_interval_param(lower):
+ parameters[name] = _interval_value(param, interval)
+ return parameters
+
+
+def _sample_parameters(capability: dict[str, Any]) -> dict[str, Any]:
+ examples = capability.get("examples")
+ if not isinstance(examples, dict):
+ return {}
+ sample = examples.get("sample_parameters")
+ return dict(sample) if isinstance(sample, dict) else {}
+
+
+def _provider_symbol(code: str) -> str:
+ """Normalize common project US suffixes while preserving other markets."""
+ upper = code.strip().upper()
+ if upper.endswith(".US"):
+ return upper[: -len(".US")]
+ return upper
+
+
+def _is_symbol_param(name: str) -> bool:
+ return any(token in name for token in ("symbol", "ticker", "instrument", "code"))
+
+
+def _is_start_param(name: str) -> bool:
+ return any(token in name for token in ("start", "from", "begin")) and "end" not in name
+
+
+def _is_end_param(name: str) -> bool:
+ return any(token in name for token in ("end", "to", "until"))
+
+
+def _is_interval_param(name: str) -> bool:
+ return any(token in name for token in ("interval", "timeframe", "resolution", "frequency"))
+
+
+def _interval_value(param: dict[str, Any], interval: str) -> str:
+ enum = param.get("enum")
+ if isinstance(enum, list):
+ lowered = {str(value).lower(): value for value in enum}
+ for candidate in (interval, interval.lower(), "1d", "d", "daily"):
+ if candidate.lower() in lowered:
+ return str(lowered[candidate.lower()])
+ return "daily" if interval.upper() == "1D" else interval
+
+
+def _result_to_frame(result: Any, start_date: str, end_date: str) -> Optional[pd.DataFrame]:
+ rows = [_normalize_record(record) for record in _iter_ohlcv_records(result)]
+ cleaned = [row for row in rows if row is not None]
+ if not cleaned:
+ return None
+
+ df = pd.DataFrame(cleaned)
+ df["trade_date"] = pd.to_datetime(df["trade_date"], errors="coerce").astype(
+ "datetime64[ns]"
+ )
+ for field in _OHLCV_COLUMNS:
+ if field not in df.columns:
+ df[field] = None
+ df[field] = pd.to_numeric(df[field], errors="coerce").astype(float)
+ df = df.dropna(subset=["trade_date", "open", "high", "low", "close"])
+ if df.empty:
+ return None
+
+ df = df.set_index("trade_date").sort_index()
+ df = df[_OHLCV_COLUMNS]
+ start = pd.Timestamp(start_date)
+ end = pd.Timestamp(end_date)
+ df = df.loc[(df.index >= start) & (df.index <= end)]
+ df = validate_ohlc(df)
+ return None if df.empty else df
+
+
+def _iter_ohlcv_records(payload: Any) -> Iterable[dict[str, Any]]:
+ """Yield dict-like OHLCV records from common QVeris/provider shapes."""
+ if isinstance(payload, list):
+ for item in payload:
+ yield from _iter_ohlcv_records(item)
+ return
+ if not isinstance(payload, dict):
+ return
+
+ if _record_has_ohlc(payload):
+ yield payload
+
+ date_keyed = _date_keyed_records(payload)
+ if date_keyed is not None:
+ yield from date_keyed
+ return
+
+ yielded = False
+ for key in (
+ "data",
+ "results",
+ "result",
+ "historical",
+ "prices",
+ "items",
+ "rows",
+ "candles",
+ "values",
+ "time_series",
+ "Time Series (Daily)",
+ ):
+ if key in payload:
+ for record in _iter_ohlcv_records(payload[key]):
+ yielded = True
+ yield record
+ if yielded:
+ return
+ # Provider-specific series containers ("Weekly Adjusted Time Series",
+ # "Time Series (5min)", ...) — any nested dict of date-keyed records.
+ for value in payload.values():
+ if isinstance(value, dict):
+ date_keyed = _date_keyed_records(value)
+ if date_keyed:
+ yield from date_keyed
+
+
+def _date_keyed_records(payload: dict[str, Any]) -> list[dict[str, Any]] | None:
+ rows: list[dict[str, Any]] = []
+ for key, value in payload.items():
+ if not isinstance(value, dict) or not _looks_like_date(key):
+ return None
+ row = dict(value)
+ row.setdefault("trade_date", key)
+ rows.append(row)
+ return rows if rows else None
+
+
+def _looks_like_date(value: Any) -> bool:
+ if not isinstance(value, str):
+ return False
+ try:
+ pd.Timestamp(value)
+ except Exception:
+ return False
+ return True
+
+
+def _record_has_ohlc(record: dict[str, Any]) -> bool:
+ lowered = {str(key).lower() for key in record}
+ return all(any(alias in lowered for alias in aliases) for aliases in (
+ _FIELD_ALIASES["open"],
+ _FIELD_ALIASES["high"],
+ _FIELD_ALIASES["low"],
+ _FIELD_ALIASES["close"],
+ ))
+
+
+def _normalize_record(record: dict[str, Any]) -> dict[str, Any] | None:
+ lowered = {str(key).lower(): value for key, value in record.items()}
+ date = _first_value(lowered, _DATE_KEYS)
+ if date is None:
+ return None
+ row = {"trade_date": date}
+ for field, aliases in _FIELD_ALIASES.items():
+ row[field] = _first_value(lowered, aliases)
+ if any(row[field] is None for field in ("open", "high", "low", "close")):
+ return None
+ return row
+
+
+def _first_value(mapping: dict[str, Any], keys: Iterable[str]) -> Any:
+ for key in keys:
+ if key in mapping:
+ return mapping[key]
+ return None
+
+
+def _str_or_none(value: Any) -> str | None:
+ if value is None:
+ return None
+ text = str(value).strip()
+ return text or None
diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.py
index 358203f4a..63d731c3d 100644
--- a/agent/backtest/loaders/registry.py
+++ b/agent/backtest/loaders/registry.py
@@ -48,6 +48,7 @@ VALID_SOURCES: set[str] = {
"alphavantage",
"tiingo",
"fmp",
+ "qveris", # QVERIS-INTEGRATION
"local",
"auto",
}
@@ -92,6 +93,7 @@ def _ensure_registered() -> None:
"backtest.loaders.alphavantage_loader",
"backtest.loaders.tiingo_loader",
"backtest.loaders.fmp_loader",
+ "backtest.loaders.qveris_loader", # QVERIS-INTEGRATION
"backtest.loaders.local_loader",
]
import importlib
@@ -109,7 +111,7 @@ def _ensure_registered() -> None:
# unavailable ``local`` request can degrade into an unrelated network source.
# An explicit ``local`` request that is unavailable is a config problem the user
# must see, not something to paper over with a Yahoo/Tencent fetch.
-_NO_NETWORK_FALLBACK_SOURCES: frozenset[str] = frozenset({"local"})
+_NO_NETWORK_FALLBACK_SOURCES: frozenset[str] = frozenset({"local", "qveris"}) # QVERIS-INTEGRATION
# ---------------------------------------------------------------------------
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 71bf5ee92..3c4a4c9b1 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -2985,8 +2985,113 @@ def _dispatch_channels(args: argparse.Namespace) -> int:
return cmd_channels_login(args.channel_name, force=args.force)
console.print("[red]channels requires a subcommand.[/red] Try: vibe-trading channels status")
return EXIT_USAGE_ERROR
-
-
+# QVERIS-INTEGRATION
+def _print_qveris_config(config) -> None: # QVERIS-INTEGRATION
+ """Render local QVeris config.""" # QVERIS-INTEGRATION
+ from src.tools.qveris_tool import SIGNUP_URL, INVITE_CODE, has_qveris_credentials, is_qveris_configured, mask_api_key, normalize_qveris_mode # QVERIS-INTEGRATION
+ table = Table(title="Data Routing", box=box.SIMPLE) # QVERIS-INTEGRATION
+ table.add_column("Field") # QVERIS-INTEGRATION
+ table.add_column("Value") # QVERIS-INTEGRATION
+ table.add_row("mode", normalize_qveris_mode(config.mode)) # QVERIS-INTEGRATION
+ table.add_row("free_route", "built-in public data") # QVERIS-INTEGRATION
+ table.add_row("premium_provider", "QVeris") # QVERIS-INTEGRATION
+ table.add_row("paid_active", "yes" if is_qveris_configured(config) else "no") # QVERIS-INTEGRATION
+ table.add_row("premium_key", "yes" if has_qveris_credentials(config) else "no") # QVERIS-INTEGRATION
+ table.add_row("base_url", config.base_url) # QVERIS-INTEGRATION
+ table.add_row("api_key", mask_api_key(config.api_key) or "(not set)") # QVERIS-INTEGRATION
+ table.add_row("budget/session", str(config.budget_credits_per_session)) # QVERIS-INTEGRATION
+ table.add_row("signup", SIGNUP_URL) # QVERIS-INTEGRATION
+ table.add_row("invite_code", INVITE_CODE) # QVERIS-INTEGRATION
+ console.print(table) # QVERIS-INTEGRATION
+# QVERIS-INTEGRATION
+def cmd_qveris_status() -> int: # QVERIS-INTEGRATION
+ """Show QVeris local config and live status when configured.""" # QVERIS-INTEGRATION
+ from src.tools.qveris_tool import QVerisClient, is_qveris_configured, load_qveris_config # QVERIS-INTEGRATION
+ config = load_qveris_config() # QVERIS-INTEGRATION
+ _print_qveris_config(config) # QVERIS-INTEGRATION
+ if not is_qveris_configured(config): # QVERIS-INTEGRATION
+ return EXIT_SUCCESS # QVERIS-INTEGRATION
+ try: # QVERIS-INTEGRATION
+ payload = QVerisClient(config).search("status", limit=1) # QVERIS-INTEGRATION
+ console.print(f"[green]QVeris reachable.[/green] remaining_credits={payload.get('remaining_credits')}") # QVERIS-INTEGRATION
+ return EXIT_SUCCESS # QVERIS-INTEGRATION
+ except Exception as exc: # noqa: BLE001 # QVERIS-INTEGRATION
+ console.print(f"[red]QVeris status failed:[/red] {exc}") # QVERIS-INTEGRATION
+ return EXIT_RUN_FAILED # QVERIS-INTEGRATION
+# QVERIS-INTEGRATION
+def cmd_qveris_enable(*, key: str | None = None, url: str | None = None) -> int: # QVERIS-INTEGRATION
+ """Enable QVeris if an API key is present or supplied.""" # QVERIS-INTEGRATION
+ from src.tools.qveris_tool import SIGNUP_URL, INVITE_CODE, QVerisConfig, _read_config_file, save_qveris_config # QVERIS-INTEGRATION
+ existing = _read_config_file() # QVERIS-INTEGRATION
+ api_key = (key or existing.api_key or "").strip() # QVERIS-INTEGRATION
+ if not api_key: # QVERIS-INTEGRATION
+ console.print("[yellow]QVeris API key is required to enable the integration.[/yellow]") # QVERIS-INTEGRATION
+ console.print(f"[dim]Sign up: {SIGNUP_URL} invite_code={INVITE_CODE}[/dim]") # QVERIS-INTEGRATION
+ return EXIT_USAGE_ERROR # QVERIS-INTEGRATION
+ base_url = (url or existing.base_url).strip().rstrip("/") # QVERIS-INTEGRATION
+ if not base_url.startswith(("http://", "https://")): # QVERIS-INTEGRATION
+ console.print("[red]--url must start with http:// or https://[/red]") # QVERIS-INTEGRATION
+ return EXIT_USAGE_ERROR # QVERIS-INTEGRATION
+ saved = save_qveris_config(QVerisConfig(True, base_url, api_key, "paid", existing.budget_credits_per_session)) # QVERIS-INTEGRATION
+ console.print("[green]QVeris paid route enabled.[/green]") # QVERIS-INTEGRATION
+ _print_qveris_config(saved) # QVERIS-INTEGRATION
+ return EXIT_SUCCESS # QVERIS-INTEGRATION
+# QVERIS-INTEGRATION
+def cmd_qveris_mode(
+ *,
+ mode: str,
+ budget: float | None = None,
+ key: str | None = None,
+ url: str | None = None,
+) -> int: # QVERIS-INTEGRATION
+ """Switch QVeris between free and paid modes.""" # QVERIS-INTEGRATION
+ from src.tools.qveris_tool import QVerisConfig, _read_config_file, normalize_qveris_mode, save_qveris_config # QVERIS-INTEGRATION
+ existing = _read_config_file() # QVERIS-INTEGRATION
+ next_mode = normalize_qveris_mode(mode) # QVERIS-INTEGRATION
+ next_budget = existing.budget_credits_per_session if budget is None else max(float(budget), 0.0) # QVERIS-INTEGRATION
+ base_url = (url or existing.base_url).strip().rstrip("/") # QVERIS-INTEGRATION
+ if not base_url.startswith(("http://", "https://")): # QVERIS-INTEGRATION
+ console.print("[red]--url must start with http:// or https://[/red]") # QVERIS-INTEGRATION
+ return EXIT_USAGE_ERROR # QVERIS-INTEGRATION
+ api_key = (key or existing.api_key or "").strip() # QVERIS-INTEGRATION
+ saved = save_qveris_config(QVerisConfig(next_mode == "paid", base_url, api_key, next_mode, next_budget)) # QVERIS-INTEGRATION
+ console.print(f"[green]QVeris mode set to {next_mode}.[/green]") # QVERIS-INTEGRATION
+ _print_qveris_config(saved) # QVERIS-INTEGRATION
+ return EXIT_SUCCESS # QVERIS-INTEGRATION
+# QVERIS-INTEGRATION
+def cmd_qveris_disable() -> int: # QVERIS-INTEGRATION
+ """Disable QVeris without deleting the stored key.""" # QVERIS-INTEGRATION
+ from src.tools.qveris_tool import QVerisConfig, _read_config_file, save_qveris_config # QVERIS-INTEGRATION
+ existing = _read_config_file() # QVERIS-INTEGRATION
+ save_qveris_config(QVerisConfig(False, existing.base_url, existing.api_key, "free", existing.budget_credits_per_session)) # QVERIS-INTEGRATION
+ console.print("[green]QVeris disabled.[/green]") # QVERIS-INTEGRATION
+ return EXIT_SUCCESS # QVERIS-INTEGRATION
+# QVERIS-INTEGRATION
+def cmd_qveris_usage() -> int: # QVERIS-INTEGRATION
+ """Show recent QVeris usage events.""" # QVERIS-INTEGRATION
+ from src.tools.qveris_tool import QVerisClient, is_qveris_configured, load_qveris_config # QVERIS-INTEGRATION
+ config = load_qveris_config() # QVERIS-INTEGRATION
+ if not is_qveris_configured(config): # QVERIS-INTEGRATION
+ console.print("[yellow]QVeris is not configured.[/yellow]") # QVERIS-INTEGRATION
+ return EXIT_USAGE_ERROR # QVERIS-INTEGRATION
+ try: # QVERIS-INTEGRATION
+ payload = QVerisClient(config).usage_history(limit=10, page_size=10) # QVERIS-INTEGRATION
+ except Exception as exc: # noqa: BLE001 # QVERIS-INTEGRATION
+ console.print(f"[red]QVeris usage failed:[/red] {exc}") # QVERIS-INTEGRATION
+ return EXIT_RUN_FAILED # QVERIS-INTEGRATION
+ print(json.dumps(payload, indent=2, ensure_ascii=False)) # QVERIS-INTEGRATION
+ return EXIT_SUCCESS # QVERIS-INTEGRATION
+def _dispatch_data(args: argparse.Namespace) -> int: # QVERIS-INTEGRATION
+ """Dispatch user-facing data-routing commands.""" # QVERIS-INTEGRATION
+ if args.data_command == "status": # QVERIS-INTEGRATION
+ return cmd_qveris_status() # QVERIS-INTEGRATION
+ if args.data_command == "mode": # QVERIS-INTEGRATION
+ return cmd_qveris_mode(mode=args.mode, budget=args.budget, key=args.key, url=args.url) # QVERIS-INTEGRATION
+ if args.data_command == "usage": # QVERIS-INTEGRATION
+ return cmd_qveris_usage() # QVERIS-INTEGRATION
+ console.print("[red]data requires a subcommand.[/red] Try: vibe-trading data status") # QVERIS-INTEGRATION
+ return EXIT_USAGE_ERROR # QVERIS-INTEGRATION
+# QVERIS-INTEGRATION
def _live_server_config(broker: str):
"""Resolve the protected MCP server config for ``broker``.
@@ -4253,6 +4358,17 @@ def _build_parser() -> argparse.ArgumentParser:
login_parser.add_argument("provider", help="OAuth provider name, e.g. openai-codex")
provider_subparsers.add_parser("doctor", help="Print redacted provider diagnostics")
+ # QVERIS-INTEGRATION
+ data_parser = subparsers.add_parser("data", help="Manage data routing mode") # QVERIS-INTEGRATION
+ data_subparsers = data_parser.add_subparsers(dest="data_command") # QVERIS-INTEGRATION
+ data_subparsers.add_parser("status", help="Show active data routing mode") # QVERIS-INTEGRATION
+ data_mode = data_subparsers.add_parser("mode", help="Switch between free public data and paid data routing") # QVERIS-INTEGRATION
+ data_mode.add_argument("mode", choices=["free", "paid"], help="free uses built-in public data; paid enables premium data execution") # QVERIS-INTEGRATION
+ data_mode.add_argument("--budget", type=float, help="Paid-mode credit budget per session") # QVERIS-INTEGRATION
+ data_mode.add_argument("--key", help="Premium data API key") # QVERIS-INTEGRATION
+ data_mode.add_argument("--url", help="Premium data API base URL") # QVERIS-INTEGRATION
+ data_subparsers.add_parser("usage", help="Show recent paid data usage") # QVERIS-INTEGRATION
+ # QVERIS-INTEGRATION
channels_parser = subparsers.add_parser("channels", help="Manage IM channel adapters")
channels_subparsers = channels_parser.add_subparsers(dest="channels_command")
channels_status = channels_subparsers.add_parser("status", help="Show IM channel status")
@@ -5222,6 +5338,8 @@ def main(argv: list[str] | None = None) -> int:
return EXIT_USAGE_ERROR
if args.command == "channels":
return _coerce_exit_code(_dispatch_channels(args))
+ if args.command == "data": # QVERIS-INTEGRATION
+ return _coerce_exit_code(_dispatch_data(args)) # QVERIS-INTEGRATION
if args.command == "run":
return _handle_prompt_command(
args.run_prompt,
diff --git a/agent/cli/main.py b/agent/cli/main.py
index c0c1dbd57..b92c0c45a 100644
--- a/agent/cli/main.py
+++ b/agent/cli/main.py
@@ -83,7 +83,19 @@ def _register_live_slash_commands() -> None:
_register_live_slash_commands()
-
+# QVERIS-INTEGRATION
+def _register_data_slash_commands() -> None: # QVERIS-INTEGRATION
+ """Surface data routing mode in the shared slash registry.""" # QVERIS-INTEGRATION
+ from cli.commands import slash_router # QVERIS-INTEGRATION
+ if any(cmd.name == "data" for cmd in slash_router.SLASH_COMMANDS): # QVERIS-INTEGRATION
+ return # QVERIS-INTEGRATION
+ commands = list(slash_router.SLASH_COMMANDS) # QVERIS-INTEGRATION
+ quit_idx = next((i for i, c in enumerate(commands) if c.name == "quit"), len(commands)) # QVERIS-INTEGRATION
+ commands.insert(quit_idx, slash_router.Command("data", "Data routing mode", "cli.main")) # QVERIS-INTEGRATION
+ slash_router.SLASH_COMMANDS = tuple(commands) # QVERIS-INTEGRATION
+# QVERIS-INTEGRATION
+_register_data_slash_commands() # QVERIS-INTEGRATION
+# QVERIS-INTEGRATION
_AGENT_DIR = Path(__file__).resolve().parents[1]
_ENV_PATH = Path.home() / ".vibe-trading" / ".env"
_PROJECT_ENV_PATH = _AGENT_DIR / ".env"
@@ -901,8 +913,20 @@ def _run_connector_command_from_repl(console: Any, args: list[str]) -> None:
_dispatch_connector(parsed)
except Exception as exc: # noqa: BLE001 — never let a connector command kill the loop
console.print(f"[bold red]/connector failed:[/bold red] {exc}")
-
-
+# QVERIS-INTEGRATION
+def _run_data_command_from_repl(console: Any, args: list[str]) -> None: # QVERIS-INTEGRATION
+ """Run a ``/data ...`` subcommand from the REPL via the CLI dispatcher.""" # QVERIS-INTEGRATION
+ from cli._legacy import _build_parser, _dispatch_data # QVERIS-INTEGRATION
+ argv = ["data", *(args or ["status"])] # QVERIS-INTEGRATION
+ try: # QVERIS-INTEGRATION
+ parsed = _build_parser().parse_args(argv) # QVERIS-INTEGRATION
+ except SystemExit: # QVERIS-INTEGRATION
+ console.print("[dim]Usage: /data [status|mode free|mode paid|usage][/dim]") # QVERIS-INTEGRATION
+ return # QVERIS-INTEGRATION
+ try: # QVERIS-INTEGRATION
+ _dispatch_data(parsed) # QVERIS-INTEGRATION
+ except Exception as exc: # noqa: BLE001 # QVERIS-INTEGRATION
+ console.print(f"[bold red]/data failed:[/bold red] {exc}") # QVERIS-INTEGRATION
def _is_numeric_pick(text: str) -> Optional[int]:
"""Return the chosen ordinal if ``text`` is a bare numeric pick, else None.
@@ -1197,6 +1221,9 @@ def _interactive_loop(max_iter: int, resume_session_id: Optional[str] = None) ->
if slash_name == "connector":
_run_connector_command_from_repl(console, slash_tokens[1:])
continue
+ if slash_name == "data": # QVERIS-INTEGRATION
+ _run_data_command_from_repl(console, slash_tokens[1:]) # QVERIS-INTEGRATION
+ continue # QVERIS-INTEGRATION
rc = _dispatch_slash(text, ctx)
if rc == 2:
break
diff --git a/agent/src/api/qveris_routes.py b/agent/src/api/qveris_routes.py
new file mode 100644
index 000000000..3a94d25cd
--- /dev/null
+++ b/agent/src/api/qveris_routes.py
@@ -0,0 +1,231 @@
+"""QVeris settings and status routes."""
+
+from __future__ import annotations
+
+import sys as _sys
+from typing import Any, Literal
+
+from fastapi import APIRouter, Depends, HTTPException, Request, Security
+from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
+from pydantic import BaseModel, Field
+
+from src.tools.qveris_tool import (
+ INVITE_CODE,
+ SIGNUP_URL,
+ DEFAULT_BASE_URL,
+ QVerisClient,
+ QVerisConfig,
+ _read_config_file,
+ has_qveris_credentials,
+ is_qveris_configured,
+ load_qveris_config,
+ mask_api_key,
+ normalize_qveris_mode,
+ save_qveris_config,
+)
+
+qveris_router = APIRouter()
+_security = HTTPBearer(auto_error=False)
+
+
+class QVerisConfigResponse(BaseModel):
+ """Redacted QVeris config response."""
+
+ enabled: bool
+ base_url: str
+ api_key_masked: str
+ mode: Literal["free", "paid"]
+ budget_credits_per_session: float
+ configured: bool
+ signup_url: str
+ invite_code: str
+
+
+class QVerisConfigUpdate(BaseModel):
+ """QVeris config update payload."""
+
+ enabled: bool | None = None
+ base_url: str | None = None
+ api_key: str | None = None
+ mode: Literal["free", "paid"] | None = None
+ budget_credits_per_session: float | None = Field(default=None, ge=0)
+
+
+class QVerisStatusResponse(BaseModel):
+ """QVeris runtime status response."""
+
+ enabled: bool
+ ok: bool
+ error: str | None
+ remaining_credits: float | None
+ recent: list[dict[str, Any]]
+ signup_url: str
+ invite_code: str
+
+
+def _host():
+ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+ if host is None:
+ raise RuntimeError("api_server module is not loaded")
+ return host
+
+
+async def _require_auth(
+ request: Request,
+ cred: HTTPAuthorizationCredentials | None = Security(_security),
+) -> None:
+ """Delegate read auth to api_server.require_auth."""
+ await _host().require_auth(request, cred)
+
+
+async def _require_settings_write_auth(
+ request: Request,
+ cred: HTTPAuthorizationCredentials | None = Security(_security),
+) -> None:
+ """Delegate write auth to api_server.require_settings_write_auth."""
+ await _host().require_settings_write_auth(request, cred)
+
+
+def _config_response(config: QVerisConfig) -> QVerisConfigResponse:
+ return QVerisConfigResponse(
+ enabled=config.enabled,
+ base_url=config.base_url,
+ api_key_masked=mask_api_key(config.api_key),
+ mode=normalize_qveris_mode(config.mode), # type: ignore[arg-type]
+ budget_credits_per_session=float(config.budget_credits_per_session),
+ configured=has_qveris_credentials(config),
+ signup_url=SIGNUP_URL,
+ invite_code=INVITE_CODE,
+ )
+
+
+def _validate_base_url(base_url: str) -> str:
+ value = (base_url or DEFAULT_BASE_URL).strip().rstrip("/")
+ if not value.startswith(("http://", "https://")):
+ raise HTTPException(status_code=422, detail="base_url must be http(s)")
+ return value
+
+
+def _events_from_usage(payload: dict[str, Any]) -> list[dict[str, Any]]:
+ data = payload.get("data")
+ if isinstance(data, dict):
+ events = data.get("events") or data.get("items") or data.get("data")
+ elif isinstance(data, list):
+ events = data
+ else:
+ events = payload.get("events") or payload.get("items") or []
+ if not isinstance(events, list):
+ return []
+ recent: list[dict[str, Any]] = []
+ for event in events[:10]:
+ if not isinstance(event, dict):
+ continue
+ recent.append(
+ {
+ "ts": str(
+ event.get("ts")
+ or event.get("created_at")
+ or event.get("timestamp")
+ or ""
+ ),
+ "tool_id": str(event.get("tool_id") or ""),
+ "cost": float(event.get("cost") or event.get("amount_credits") or 0.0),
+ "charge_outcome": str(event.get("charge_outcome") or ""),
+ }
+ )
+ return recent
+
+
+@qveris_router.get(
+ "/qveris/config",
+ response_model=QVerisConfigResponse,
+ dependencies=[Depends(_require_auth)],
+)
+async def get_qveris_config() -> QVerisConfigResponse:
+ """Return redacted QVeris config."""
+ return _config_response(load_qveris_config())
+
+
+@qveris_router.put(
+ "/qveris/config",
+ response_model=QVerisConfigResponse,
+ dependencies=[Depends(_require_settings_write_auth)],
+)
+async def put_qveris_config(update: QVerisConfigUpdate) -> QVerisConfigResponse:
+ """Persist QVeris config changes."""
+ existing = _read_config_file()
+ cfg = QVerisConfig(
+ enabled=existing.enabled,
+ base_url=existing.base_url,
+ api_key=existing.api_key,
+ mode=existing.mode,
+ budget_credits_per_session=existing.budget_credits_per_session,
+ )
+ if update.base_url is not None:
+ cfg.base_url = _validate_base_url(update.base_url)
+ if update.api_key:
+ cfg.api_key = update.api_key.strip()
+ if update.mode is not None:
+ cfg.mode = normalize_qveris_mode(update.mode)
+ cfg.enabled = cfg.mode == "paid"
+ elif update.enabled is not None:
+ cfg.enabled = bool(update.enabled)
+ cfg.mode = "paid" if cfg.enabled else "free"
+ if update.budget_credits_per_session is not None:
+ cfg.budget_credits_per_session = float(update.budget_credits_per_session)
+ save_qveris_config(cfg)
+ return _config_response(load_qveris_config())
+
+
+@qveris_router.get(
+ "/qveris/status",
+ response_model=QVerisStatusResponse,
+ dependencies=[Depends(_require_auth)],
+)
+async def get_qveris_status() -> QVerisStatusResponse:
+ """Return QVeris availability, credits, and recent usage."""
+ cfg = load_qveris_config()
+ if not has_qveris_credentials(cfg):
+ return QVerisStatusResponse(
+ enabled=cfg.enabled,
+ ok=False,
+ error="QVeris is not configured",
+ remaining_credits=None,
+ recent=[],
+ signup_url=SIGNUP_URL,
+ invite_code=INVITE_CODE,
+ )
+ if not is_qveris_configured(cfg):
+ return QVerisStatusResponse(
+ enabled=cfg.enabled,
+ ok=False,
+ error="QVeris paid mode is off; free public data routing is active.",
+ remaining_credits=None,
+ recent=[],
+ signup_url=SIGNUP_URL,
+ invite_code=INVITE_CODE,
+ )
+ try:
+ client = QVerisClient(cfg)
+ search = client.search("status", limit=1)
+ usage = client.usage_history(limit=10, page_size=10)
+ remaining = search.get("remaining_credits")
+ return QVerisStatusResponse(
+ enabled=cfg.enabled,
+ ok=True,
+ error=None,
+ remaining_credits=float(remaining) if remaining is not None else None,
+ recent=_events_from_usage(usage),
+ signup_url=SIGNUP_URL,
+ invite_code=INVITE_CODE,
+ )
+ except Exception as exc: # noqa: BLE001 - status endpoint reports health.
+ return QVerisStatusResponse(
+ enabled=cfg.enabled,
+ ok=False,
+ error=str(exc),
+ remaining_credits=None,
+ recent=[],
+ signup_url=SIGNUP_URL,
+ invite_code=INVITE_CODE,
+ )
diff --git a/agent/src/skills/data-routing/SKILL.md b/agent/src/skills/data-routing/SKILL.md
index 19cac01d1..6505e257b 100644
--- a/agent/src/skills/data-routing/SKILL.md
+++ b/agent/src/skills/data-routing/SKILL.md
@@ -37,6 +37,7 @@ per-source skill.
| alphavantage | US equities | Yes (`ALPHAVANTAGE_API_KEY`) | Unrestricted | data-routing |
| tiingo | US equities | Yes (`TIINGO_API_KEY`) | Unrestricted | data-routing |
| fmp | US equities | Yes (`FMP_API_KEY`) | Unrestricted | data-routing |
+| qveris | Global multi-asset (paid, credits) | Yes (`QVERIS_API_KEY` / Settings) | QVeris API | qveris <!-- QVERIS-INTEGRATION --> |
## Capability → Tool Routing
diff --git a/agent/src/skills/qveris/SKILL.md b/agent/src/skills/qveris/SKILL.md
new file mode 100644
index 000000000..70b736e28
--- /dev/null
+++ b/agent/src/skills/qveris/SKILL.md
@@ -0,0 +1,110 @@
+---
+name: qveris
+category: data-source
+description: Paid capability marketplace for global multi-asset data; use it when free Vibe-Trading sources lack coverage, depth, or provider quality, and keep free sources as the default for routine OHLCV.
+---
+# QVeris
+
+QVeris is a paid capability marketplace for global market, fundamental, macro,
+derivatives, crypto, China/HK, news, filings, and alternative-data calls. Use it
+when the built-in free sources cannot cover the requested dataset, when the user
+explicitly asks for QVeris, or when a premium provider is needed for depth such
+as options Greeks, analyst/calendar feeds, broad provider comparison, or paid
+China/HK/global coverage. For ordinary OHLCV, keep `source: "auto"` on the free
+loader chain unless the user explicitly selects `source: "qveris"`.
+
+Signup link: [QVeris via Vibe-Trading](https://qveris.ai/?ref=Vyjjo5G_1cAHJA).
+Invite code fallback: `Vyjjo5G_1cAHJA`.
+
+## Workflow
+
+### 1. Discover with `qveris_search`
+
+Call `qveris_search` first. Search is free and returns candidate capabilities
+with `tool_id`, provider, parameters, examples, `expected_cost`, billing rule,
+categories, and `stats` such as `success_rate` and average execution time.
+
+Good queries are concrete:
+
+- `US listed options chain implied volatility Greeks AAPL`
+- `Hong Kong market daily OHLCV financial statements`
+- `FRED CPI Treasury yield curve macro series`
+- `China A share northbound fund flow daily`
+
+### 2. Inspect with `qveris_inspect`
+
+Call `qveris_inspect` on one or more `tool_id` values before any paid call.
+Inspect is free and returns the fuller parameter schema and sample parameters.
+Use it to verify required parameters, enum values, date formats, and output
+shape before execution.
+
+### 3. Call with `qveris_execute`
+
+Call `qveris_execute` only after the user has enabled QVeris and the tool has
+been inspected. Pass the inspected `tool_id`, the exact `parameters`, and a
+reasonable `max_response_size`. Use `session_id` and `search_id` when available
+so usage can be reconciled later.
+
+## Choosing a Capability
+
+Prefer the candidate with the best combination of:
+
+1. High `stats.success_rate`.
+2. Low `expected_cost` for equivalent data.
+3. Provider fit for the task: official or specialist sources before generic
+ mirrors when the figure matters.
+4. Parameter clarity: required fields and examples should match the user's
+ requested asset, date range, and granularity.
+
+Do not assume tools with similar names are interchangeable. The measured catalog
+has very large quality variance inside the same category; design notes recorded
+FMP tools ranging from near-zero to 100% success and some tradefeeds tools at
+0%. Surface `success_rate` and `expected_cost` in the answer whenever the user is
+choosing among paid options.
+
+## Billing and Modes
+
+- The default free route is Vibe-Trading's built-in public data stack; QVeris
+ tools are unavailable in `mode="free"`.
+- Discover (`qveris_search`) and inspect (`qveris_inspect`) are free only after
+ the user explicitly enables the paid QVeris route.
+- Execute (`qveris_execute`) is paid only when the provider call is billable.
+- Failed calls, empty results, and parameter errors are not charged by the
+ QVeris contract; observed missing-parameter calls returned `success=false`,
+ `cost=0.0`, `status=not_charged`, and unchanged balance.
+- `mode="free"` means the original free public-data path stays active and
+ QVeris is hidden from agent/tool/backtest routing.
+- `mode="paid"` permits QVeris discovery, inspect, and execute calls, bounded by
+ `budget_credits_per_session`.
+- Never hide cost: every successful execute result should preserve `cost` and
+ `remaining_credits` for the user.
+
+Configuration can come from `QVERIS_API_KEY` / `QVERIS_BASE_URL`, or from
+Settings -> QVeris / `vibe-trading data mode paid`. If QVeris is disabled, in
+free mode, or no API key is configured, the tools should be treated as
+unavailable.
+
+## Truncation
+
+`qveris_execute` accepts `max_response_size` (`20480` default, `-1` means do not
+ask QVeris to truncate). When a response is too large, QVeris returns a result
+object containing a message, `truncated_content`, and `full_content_file_url`.
+If the full JSON is required, fetch that signed URL and use the full payload.
+If a summary is enough, cite that the response was truncated and work only from
+`truncated_content`.
+
+## Balance and Usage
+
+Check balance and recent usage through:
+
+- Web: Settings -> QVeris.
+- CLI: `vibe-trading data status` or `vibe-trading data usage`.
+- Agent/API tools: status is derived from free search/ledger/usage endpoints.
+
+For reconciliation, prefer `execution_id`, `tool_id`, `charge_outcome`, `cost`,
+and `remaining_credits` over text summaries.
+
+## References
+
+- [REST API reference](qveris/references/rest-api.md)
+- [Coverage map](qveris/references/coverage.md)
diff --git a/agent/src/skills/qveris/references/coverage.md b/agent/src/skills/qveris/references/coverage.md
new file mode 100644
index 000000000..afe12f504
--- /dev/null
+++ b/agent/src/skills/qveris/references/coverage.md
@@ -0,0 +1,64 @@
+# QVeris Coverage Map
+
+This map condenses the 2026-07-07 Vibe-Trading design evidence. The measured
+sample ran 20 finance-domain searches at `limit=50`; every search hit the
+50-result cap. Deduplicated sample coverage was 841 tools across 63 providers.
+QVeris also markets "10,000+ capabilities" across 15+ categories; cite that as
+"10,000+ capabilities (per QVeris)".
+
+## Provider Head List
+
+Observed head providers and counts from the design sample:
+
+| Provider | Sample count | Strong fit |
+|----------|--------------|------------|
+| FMP | 79 | US/global equities, fundamentals, calendars, ratios. |
+| AlphaVantage | 75 | Equities, fundamentals, FX, macro-style time series. |
+| TwelveData | 62 | Global market data and technical/time-series endpoints. |
+| CoinGecko + CoinGecko Pro | 49 | Crypto spot, asset metadata, market data. |
+| hangseng_polysource | 46 | Hong Kong market data. |
+| cn_financial_pro | 41 | China financial data. |
+| Census | 36 | Official US economic/demographic data. |
+| Finnhub | 35 | Equities, news, filings, estimates, company data. |
+| EODHD | 27 | End-of-day global equity data. |
+| weather_gov | 27 | Weather data for commodity/event research. |
+| ThetaData | 25 | US options chains, implied volatility, Greeks. |
+| HKMA | 19 | Hong Kong monetary and macro data. |
+| Deribit | 13 | Crypto derivatives. |
+| Other observed providers | part of 63 total | cninfo, caidazi, FRED, US Treasury, SEC, Tiingo, Yahoo, Tradier, OKX, CoinMarketCap, and additional marketplace providers. |
+
+The full 63-provider raw file is not committed in this repo. Do not invent a full
+provider list from memory; use the observed head list above plus live search
+results from `qveris_search`.
+
+## Category Routing
+
+| Category | Representative tools/providers | Typical cost range | Route to QVeris when | Prefer free Vibe-Trading sources when |
+|----------|--------------------------------|--------------------|----------------------|---------------------------------------|
+| US/global equities OHLCV | FMP, AlphaVantage, TwelveData, EODHD, Yahoo | 1-24.2 credits/call | The user asks for a paid provider, global breadth, or a source not covered by free loaders. | Routine OHLCV can use `source:"auto"` with yahoo/stooq/sina/eastmoney/yfinance/free fallbacks. |
+| A-share and China market data | cn_financial_pro, cninfo, caidazi | 1-24.2 credits/call | Premium China fields, document-style data, or provider-specific coverage are needed. | A-share OHLCV and common flow/fundamental tools are covered by tencent/mootdx/eastmoney/akshare/tushare. |
+| Hong Kong market data | hangseng_polysource, HKMA, Yahoo/FMP-style providers | 1-24.2 credits/call | HK-specific premium breadth or monetary data is required. | Routine HK OHLCV can use eastmoney/yahoo/futu/yfinance/akshare/local. |
+| Fundamentals and financial statements | FMP, Finnhub, AlphaVantage, SEC, cn_financial_pro | 1-24.2 credits/call | Cross-provider comparison, premium vendor ratios, or non-US/non-China/HK coverage is needed. | US SEC facts and A/HK Eastmoney statements are available through built-in read-only tools. |
+| SEC filings and institutional data | SEC, Finnhub, FMP | 1-24.2 credits/call | Marketplace convenience or 13F/filing enrichment is needed. | Official SEC filings/companyfacts should stay on built-in SEC tools when sufficient. |
+| News and sentiment | Finnhub, FMP, AlphaVantage, web-search providers | 1-24.2 credits/call | Paid sentiment/news feeds or broad provider comparison are needed. | Basic stock news and web context can use built-in `get_stock_news` / `web_search`. |
+| Earnings calendar and analyst estimates | Finnhub, FMP, AlphaVantage | 1-24.2 credits/call | The user needs estimates, surprises, or vendor calendars. | Avoid paid calls if the task only needs high-level narrative or public filings. |
+| ETF holdings and fund data | FMP, AlphaVantage, market-data providers | 1-24.2 credits/call | Holdings/constituents are not in free tooling or need vendor consistency. | Basic OHLCV and many A-share/fund flows can use free loaders/tools. |
+| Options chains, IV, Greeks | ThetaData, Tradier, Yahoo, FMP | 1-24.2 credits/call | Greeks, implied volatility surfaces, or specialist options data are required. | Basic US options chains can start with built-in `get_options_chain`. |
+| FX and rates | AlphaVantage, TwelveData, US Treasury, FRED | 1-24.2 credits/call | Paid FX/rate granularity or provider-specific fields are needed. | Macro/FRED and basic FX can use built-in `get_macro_series`, tushare, or akshare when sufficient. |
+| Crypto spot/derivatives/on-chain | CoinGecko Pro, Deribit, OKX, CoinMarketCap | 1-24.2 credits/call | CoinGecko Pro, derivatives, breadth, or paid metadata are needed. | Routine crypto OHLCV should use okx/ccxt/yfinance/local. |
+| Commodities and weather | FMP-style commodity feeds, weather_gov | 1-24.2 credits/call | Weather-sensitive commodity/event analysis needs structured weather data. | Public web/document research is enough for qualitative context. |
+| Macro official data | FRED, Census, US Treasury, HKMA | 1-24.2 credits/call | One key should access many official-style sources through one interface. | Built-in FRED macro is preferred when it covers the series and key is configured. |
+| Corporate actions | FMP, AlphaVantage, EODHD | 1-24.2 credits/call | Dividends, splits, IPO, or vendor-adjusted history is missing in free sources. | Use free loaders for simple adjusted/unadjusted OHLCV where adequate. |
+| Short interest and alternative data | Finnhub/FMP-style feeds, marketplace providers | 1-24.2 credits/call | The data class is absent from built-in tools. | Use built-in data only when it directly covers the requested metric. |
+
+## Agent Policy
+
+- Start with free Vibe-Trading sources for routine OHLCV and official/free tools.
+- Use QVeris for paid breadth, specialist data, and provider comparison.
+- Always inspect before execute.
+- Rank paid candidates by `stats.success_rate`, `expected_cost`, provider fit,
+ and parameter clarity.
+- Tell the user when a result is single-source or when provider quality varies.
+- Failed, empty, and parameter-error executions are expected not to charge; keep
+ `execution_id`, `charge_outcome`, `reason_code`, `cost`, and
+ `remaining_credits` in the evidence trail.
diff --git a/agent/src/skills/qveris/references/rest-api.md b/agent/src/skills/qveris/references/rest-api.md
new file mode 100644
index 000000000..847e4f65e
--- /dev/null
+++ b/agent/src/skills/qveris/references/rest-api.md
@@ -0,0 +1,215 @@
+# QVeris REST API Reference
+
+This reference is based on the frozen Vibe-Trading QVeris contract dated
+2026-07-07. API authentication uses `Authorization: Bearer <QVERIS_API_KEY>`.
+The default base endpoint is the QVeris API v1 base configured by
+`QVERIS_BASE_URL`; Vibe-Trading's default is the production API v1 endpoint from
+the frozen contract.
+
+## Common Fields
+
+| Field | Type | Meaning |
+|-------|------|---------|
+| `session_id` | string? | Optional caller session for usage grouping. |
+| `search_id` | string? | Search correlation id returned by `/search`. |
+| `remaining_credits` | number? | Account credits after the request or latest free lookup. |
+| `error_message` | string? | Provider or API error text. Treat as user-facing diagnostic, not a stack trace. |
+
+Errors may appear as HTTP errors or as HTTP 200 responses with
+`success=false`, `error_message`, and an execution/billing outcome. Parse both.
+
+## POST `/search` (Free)
+
+Searches the marketplace for matching capabilities. Invalid keys return HTTP
+401 with empty results.
+
+### Request
+
+| Field | Type | Required | Notes |
+|-------|------|----------|-------|
+| `query` | string | yes | Natural-language capability query. |
+| `limit` | integer | no | 1-100, default 20. |
+| `session_id` | string | no | Optional Vibe-Trading session id. |
+
+### Response
+
+| Field | Type | Notes |
+|-------|------|-------|
+| `query` | string | Echoed query. |
+| `search_id` | string | Pass to inspect/execute for attribution. |
+| `total` | integer | Total matched capabilities. |
+| `results` | array | Capability summaries, see below. |
+| `elapsed_time_ms` | number | Search latency. |
+| `remaining_credits` | number? | Current balance if returned. |
+| `error_message` | string? | Present on degraded/error response. |
+
+### Result Object
+
+| Field | Type | Notes |
+|-------|------|-------|
+| `tool_id` | string | Required for inspect/execute. |
+| `name` | string | Capability display name. |
+| `description` | string | Capability summary. |
+| `provider_name` | string? | Provider/vendor name. |
+| `params` | array | Parameter summaries with `name`, `type`, `required`, `description`, optional `enum`. |
+| `examples.sample_parameters` | object? | Example request parameters. |
+| `expected_cost` | string | Quoted expected credit cost; compare before execute. |
+| `billing_rule` | object | Billing terms; preserve for user-visible cost quotes. |
+| `stats` | object | Includes `avg_execution_time_ms`, `success_rate`, and provider stats when present. |
+| `categories` | array | Category objects, usually with `slug`. |
+
+## POST `/tools/by-ids` (Free)
+
+Fetches full capability metadata by `tool_id`. Use this before paid execution.
+
+### Request
+
+| Field | Type | Required | Notes |
+|-------|------|----------|-------|
+| `tool_ids` | string[] | yes | One or more ids returned by search. |
+| `search_id` | string | no | Original search correlation id. |
+| `session_id` | string | no | Optional Vibe-Trading session id. |
+
+### Response
+
+The response uses the same `results` shape as `/search`, but with fuller
+`params` and examples. Treat missing fields as absent, not fatal.
+
+## POST `/tools/execute?tool_id={tool_id}` (Paid When Billable)
+
+Executes one capability. Vibe-Trading must keep QVeris unavailable in `free`
+mode and check session budget in `paid` mode before sending the request.
+
+### Query
+
+| Field | Type | Required | Notes |
+|-------|------|----------|-------|
+| `tool_id` | string | yes | Capability id from search/inspect. |
+
+### Request Body
+
+| Field | Type | Required | Notes |
+|-------|------|----------|-------|
+| `search_id` | string | no | Correlates execution to discovery. |
+| `session_id` | string | no | Correlates execution to Vibe-Trading session. |
+| `model` | string | no | Optional model hint accepted by QVeris. |
+| `parameters` | object | yes | Exact parameters from inspected schema. |
+| `max_response_size` | integer | no | Default 20480; `-1` requests no truncation. |
+
+### Response
+
+| Field | Type | Notes |
+|-------|------|-------|
+| `execution_id` | string | Use for usage reconciliation. |
+| `result` | object | Provider payload or truncation envelope. |
+| `success` | boolean | Provider/API success. |
+| `error_message` | string? | Error when `success=false`. |
+| `execution_time` | number? | Provider execution time. |
+| `elapsed_time_ms` | number? | End-to-end latency. |
+| `billing.summary` | string? | Human billing summary. |
+| `billing.list_amount_credits` | number? | Listed credit amount. |
+| `execution_outcome.outcome` | string? | Execution outcome label. |
+| `execution_outcome.reason_code` | string? | Reason for charge or no-charge state. |
+| `execution_outcome.provider_success` | boolean? | Whether upstream provider succeeded. |
+| `execution_outcome.billable_success` | boolean? | Whether success is billable. |
+| `execution_outcome.result_valid` | boolean? | Whether result passed QVeris validation. |
+| `execution_outcome.status` | string? | Settlement status such as `not_charged`. |
+| `cost` | number | Actual charged credits; observed parameter errors return `0.0`. |
+| `remaining_credits` | number | Balance after settlement. |
+
+### Truncation Envelope
+
+When the provider payload exceeds `max_response_size`, `result` contains:
+
+| Field | Type | Notes |
+|-------|------|-------|
+| `message` | string | Explains the response is too long. |
+| `full_content_file_url` | string | Signed URL for the full JSON payload. |
+| `truncated_content` | string/object | Partial payload for quick inspection. |
+
+Fetch `full_content_file_url` only when the full result is necessary. Signed
+URLs may expire and should not be persisted as durable evidence.
+
+## GET `/auth/usage/history/v2` (Free)
+
+Usage event history and summary endpoint. The response shape is intentionally
+parsed leniently because QVeris may return events at the top level or under
+`data`.
+
+### Query Parameters
+
+| Parameter | Type | Notes |
+|-----------|------|-------|
+| `execution_id` | string | Filter one execution. |
+| `start_date`, `end_date` | string | Date range filters. |
+| `kind` | string | Common values: `discover`, `call`, `model`. |
+| `charge_outcome` | string | `charged`, `included`, `failed_not_charged`, `failed_charged_review`. |
+| `summary` | boolean | `true` for aggregate summary. |
+| `bucket` | string | Common value: `day`. |
+| `limit` | integer | Max rows. |
+| `page`, `page_size` | integer | Pagination. |
+
+### Event Fields
+
+| Field | Type | Notes |
+|-------|------|-------|
+| `id` | string | Usage event id. |
+| `event_type` | string | Event category. |
+| `session_id` | string? | Caller session. |
+| `search_id` | string? | Search id. |
+| `execution_id` | string? | Execution id. |
+| `tool_id` | string? | Capability id. |
+| `success` | boolean? | Request success. |
+| `charge_outcome` | string? | Settlement result. |
+| `duration_ms` | number? | Duration in milliseconds. |
+
+## GET `/auth/credits/ledger` (Free)
+
+Credit ledger endpoint for balance and audit.
+
+### Query Parameters
+
+| Parameter | Type | Notes |
+|-----------|------|-------|
+| `direction` | string | `consume`, `grant`, or `any`. |
+| `entry_type` | string | Ledger entry type filter. |
+| `summary` | boolean | `true` for aggregate summary. |
+| `limit` | integer | Max rows. |
+| `page`, `page_size` | integer | Pagination. |
+
+### Item Fields
+
+| Field | Type | Notes |
+|-------|------|-------|
+| `id` | string | Ledger entry id. |
+| `entry_type` | string | Examples: `consume_tool_execute`, `grant_welcome_bonus`. |
+| `amount_credits` | number | Negative means consumption; positive means grant. |
+| `execution_id` | string? | Execution id for consumed credits. |
+| `pre_settlement_bill` | object? | Bill details before settlement. |
+
+## Charge Outcomes and Reason Codes
+
+| Field/value | Meaning | Agent behavior |
+|-------------|---------|----------------|
+| `charge_outcome=charged` | Credits were consumed. | Report `cost` and `remaining_credits`. |
+| `charge_outcome=included` | Included/free quota covered it. | Report no incremental charge if `cost=0`. |
+| `charge_outcome=failed_not_charged` | Failure was not charged. | Surface error and suggest parameter/provider fix. |
+| `charge_outcome=failed_charged_review` | Failure may need billing review. | Preserve `execution_id` and tell user to review usage. |
+| `reason_code=missing_required_parameter` | Parameters invalid or missing. | Inspect schema, repair parameters, no charge expected. |
+| `reason_code=empty_result` | Provider returned no usable data. | No charge expected; try different date/symbol/provider. |
+| `reason_code=provider_error` | Upstream provider failed. | No charge expected; try alternate provider. |
+| unknown `reason_code` | QVeris may add values. | Treat as opaque evidence; do not infer charge beyond `cost`. |
+
+## 429 Rate Limits
+
+Contracted nominal limits are search 120/min and execute 200/min, but measured
+bursts around 20 requests in a short window can return 429. Clients must throttle
+requests and retry 429 responses using headers.
+
+| Header | Required handling |
+|--------|-------------------|
+| `Retry-After` | Sleep for the indicated seconds before retry. |
+| `X-RateLimit-*` | If present, log only redacted/non-secret values and respect reset hints. |
+
+Vibe-Trading clients should use a minimum request interval of 0.5 seconds and at
+most 3 retries on 429.
diff --git a/agent/src/tools/qveris_tool.py b/agent/src/tools/qveris_tool.py
new file mode 100644
index 000000000..b9c25c4f9
--- /dev/null
+++ b/agent/src/tools/qveris_tool.py
@@ -0,0 +1,480 @@
+"""QVeris discovery and execution tools."""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import tempfile
+import time
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any
+
+import httpx
+
+from src.agent.tools import BaseTool
+
+SIGNUP_URL = "https://qveris.ai/?ref=Vyjjo5G_1cAHJA"
+INVITE_CODE = "Vyjjo5G_1cAHJA"
+DEFAULT_BASE_URL = "https://qveris.ai/api/v1"
+QVERIS_CONFIG_PATH = Path.home() / ".vibe-trading" / "qveris.json"
+VALID_MODES = {"free", "paid"}
+_LEGACY_MODE_MAP = {
+ "preview": "free",
+ "allow_paid": "paid",
+ "free": "free",
+ "paid": "paid",
+}
+
+_SESSION_SPEND: dict[str, float] = {}
+
+
+@dataclass
+class QVerisConfig:
+ """QVeris local configuration."""
+
+ enabled: bool = False
+ base_url: str = DEFAULT_BASE_URL
+ api_key: str = ""
+ mode: str = "free"
+ budget_credits_per_session: float = 50.0
+
+
+def _read_config_file() -> QVerisConfig:
+ """Read the persisted QVeris config without env overrides."""
+ if not QVERIS_CONFIG_PATH.exists():
+ return QVerisConfig()
+ try:
+ raw = json.loads(QVERIS_CONFIG_PATH.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return QVerisConfig()
+ cfg = QVerisConfig()
+ if isinstance(raw, dict):
+ cfg.enabled = bool(raw.get("enabled", cfg.enabled))
+ cfg.base_url = str(raw.get("base_url") or cfg.base_url)
+ cfg.api_key = str(raw.get("api_key") or "")
+ cfg.mode = normalize_qveris_mode(str(raw.get("mode") or cfg.mode))
+ try:
+ cfg.budget_credits_per_session = float(
+ raw.get("budget_credits_per_session", cfg.budget_credits_per_session)
+ )
+ except (TypeError, ValueError):
+ cfg.budget_credits_per_session = 50.0
+ if cfg.budget_credits_per_session < 0:
+ cfg.budget_credits_per_session = 0.0
+ return cfg
+
+
+def load_qveris_config() -> QVerisConfig:
+ """Load QVeris config with environment overrides applied."""
+ cfg = _read_config_file()
+ env_key = os.getenv("QVERIS_API_KEY")
+ env_url = os.getenv("QVERIS_BASE_URL")
+ if env_key is not None:
+ cfg.api_key = env_key.strip()
+ if env_url is not None:
+ cfg.base_url = env_url.strip() or DEFAULT_BASE_URL
+ return cfg
+
+
+def save_qveris_config(config: QVerisConfig) -> QVerisConfig:
+ """Persist QVeris config with atomic replace and 0600 permissions.
+
+ Args:
+ config: Configuration to persist.
+
+ Returns:
+ The normalized configuration that was written.
+ """
+ cfg = QVerisConfig(
+ enabled=bool(config.enabled),
+ base_url=(config.base_url or DEFAULT_BASE_URL).rstrip("/"),
+ api_key=config.api_key or "",
+ mode=normalize_qveris_mode(config.mode),
+ budget_credits_per_session=max(float(config.budget_credits_per_session), 0.0),
+ )
+ QVERIS_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp_name = tempfile.mkstemp(
+ prefix=".qveris.", suffix=".tmp", dir=str(QVERIS_CONFIG_PATH.parent)
+ )
+ tmp_path = Path(tmp_name)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump(asdict(cfg), handle, ensure_ascii=False, indent=2)
+ handle.write("\n")
+ os.chmod(tmp_path, 0o600)
+ os.replace(tmp_path, QVERIS_CONFIG_PATH)
+ os.chmod(QVERIS_CONFIG_PATH, 0o600)
+ finally:
+ if tmp_path.exists():
+ tmp_path.unlink()
+ return cfg
+
+
+def mask_api_key(api_key: str) -> str:
+ """Return a non-reversible display mask for an API key."""
+ key = (api_key or "").strip()
+ if not key:
+ return ""
+ if len(key) <= 7:
+ return "***"
+ return f"{key[:4]}…{key[-3:]}"
+
+
+def normalize_qveris_mode(mode: str | None) -> str:
+ """Normalize user-facing QVeris mode names."""
+ return _LEGACY_MODE_MAP.get(str(mode or "").strip(), "free")
+
+
+def has_qveris_credentials(config: QVerisConfig | None = None) -> bool:
+ """Return whether a QVeris API key is saved or provided."""
+ cfg = config or load_qveris_config()
+ return bool(cfg.api_key.strip())
+
+
+def is_qveris_configured(config: QVerisConfig | None = None) -> bool:
+ """Return whether QVeris paid routing should be visible."""
+ cfg = config or load_qveris_config()
+ return has_qveris_credentials(cfg) and normalize_qveris_mode(cfg.mode) == "paid"
+
+
+def _json_response(payload: dict[str, Any]) -> str:
+ """Serialize a tool response."""
+ return json.dumps(payload, ensure_ascii=False, default=str)
+
+
+def _parse_expected_cost(value: Any) -> float | None:
+ """Extract a numeric expected-cost hint from QVeris metadata."""
+ if value is None:
+ return None
+ if isinstance(value, (int, float)):
+ return float(value)
+ match = re.search(r"-?\d+(?:\.\d+)?", str(value))
+ if not match:
+ return None
+ return float(match.group(0))
+
+
+def _quote_from_tool(tool: dict[str, Any] | None) -> dict[str, Any]:
+ """Project quote fields from a QVeris tool descriptor."""
+ tool = tool or {}
+ return {
+ "tool_id": tool.get("tool_id"),
+ "name": tool.get("name"),
+ "expected_cost": tool.get("expected_cost"),
+ "billing_rule": tool.get("billing_rule"),
+ "stats": tool.get("stats"),
+ }
+
+
+class QVerisClient:
+ """Small synchronous client for the QVeris REST API."""
+
+ def __init__(
+ self,
+ config: QVerisConfig | None = None,
+ *,
+ client: httpx.Client | None = None,
+ min_interval_seconds: float = 0.5,
+ max_429_retries: int = 3,
+ ) -> None:
+ """Initialize the client.
+
+ Args:
+ config: Optional config; defaults to :func:`load_qveris_config`.
+ client: Injectable HTTP client for tests.
+ min_interval_seconds: Minimum spacing between requests.
+ max_429_retries: Maximum retries for HTTP 429 responses.
+ """
+ self.config = config or load_qveris_config()
+ self.base_url = self.config.base_url.rstrip("/")
+ self._client = client or httpx.Client(follow_redirects=True, timeout=60.0)
+ self._min_interval_seconds = max(float(min_interval_seconds), 0.0)
+ self._max_429_retries = max(int(max_429_retries), 0)
+ self._last_request_at = 0.0
+
+ def _headers(self) -> dict[str, str]:
+ return {"Authorization": f"Bearer {self.config.api_key}"}
+
+ def _wait_for_slot(self) -> None:
+ if self._min_interval_seconds <= 0:
+ return
+ elapsed = time.monotonic() - self._last_request_at
+ wait = self._min_interval_seconds - elapsed
+ if wait > 0:
+ time.sleep(wait)
+
+ def _request(
+ self,
+ method: str,
+ path: str,
+ *,
+ json_body: dict[str, Any] | None = None,
+ params: dict[str, Any] | None = None,
+ auth: bool = True,
+ ) -> dict[str, Any]:
+ """Send a JSON request with spacing and 429 Retry-After handling."""
+ url = path if path.startswith(("http://", "https://")) else f"{self.base_url}{path}"
+ attempts = 0
+ while True:
+ self._wait_for_slot()
+ response = self._client.request(
+ method,
+ url,
+ json=json_body,
+ params=params,
+ headers=self._headers() if auth else None,
+ )
+ self._last_request_at = time.monotonic()
+ if response.status_code == 429 and attempts < self._max_429_retries:
+ attempts += 1
+ retry_after = response.headers.get("Retry-After", "1")
+ try:
+ delay = max(float(retry_after), 0.0)
+ except ValueError:
+ delay = 1.0
+ time.sleep(delay)
+ continue
+ response.raise_for_status()
+ if not response.content:
+ return {}
+ return response.json()
+
+ def _download_full_content(self, url: str) -> Any:
+ payload = self._request("GET", url, auth=False)
+ return payload
+
+ def _hydrate_truncated_result(self, payload: dict[str, Any]) -> dict[str, Any]:
+ result = payload.get("result")
+ if not isinstance(result, dict):
+ return payload
+ full_url = result.get("full_content_file_url")
+ if not isinstance(full_url, str) or not full_url:
+ return payload
+ try:
+ result["full_content"] = self._download_full_content(full_url)
+ result["full_content_downloaded"] = True
+ except Exception as exc: # noqa: BLE001 - preserve the paid response.
+ result["full_content_download_error"] = str(exc)
+ return payload
+
+ def search(
+ self, query: str, *, limit: int = 20, session_id: str | None = None
+ ) -> dict[str, Any]:
+ """Call ``POST /search``."""
+ body: dict[str, Any] = {"query": query, "limit": min(max(int(limit), 1), 100)}
+ if session_id:
+ body["session_id"] = session_id
+ return self._request("POST", "/search", json_body=body)
+
+ def inspect(
+ self,
+ tool_ids: list[str],
+ *,
+ search_id: str | None = None,
+ session_id: str | None = None,
+ ) -> dict[str, Any]:
+ """Call ``POST /tools/by-ids``."""
+ body: dict[str, Any] = {"tool_ids": tool_ids}
+ if search_id:
+ body["search_id"] = search_id
+ if session_id:
+ body["session_id"] = session_id
+ return self._request("POST", "/tools/by-ids", json_body=body)
+
+ def execute(
+ self,
+ tool_id: str,
+ *,
+ parameters: dict[str, Any],
+ search_id: str | None = None,
+ session_id: str | None = None,
+ model: str | None = None,
+ max_response_size: int = 20480,
+ ) -> dict[str, Any]:
+ """Call ``POST /tools/execute`` and hydrate truncated results."""
+ body: dict[str, Any] = {
+ "parameters": parameters,
+ "max_response_size": max_response_size,
+ }
+ if search_id:
+ body["search_id"] = search_id
+ if session_id:
+ body["session_id"] = session_id
+ if model:
+ body["model"] = model
+ payload = self._request(
+ "POST",
+ "/tools/execute",
+ json_body=body,
+ params={"tool_id": tool_id},
+ )
+ return self._hydrate_truncated_result(payload)
+
+ def usage_history(self, **params: Any) -> dict[str, Any]:
+ """Call ``GET /auth/usage/history/v2``."""
+ return self._request("GET", "/auth/usage/history/v2", params=params)
+
+ def credits_ledger(self, **params: Any) -> dict[str, Any]:
+ """Call ``GET /auth/credits/ledger``."""
+ return self._request("GET", "/auth/credits/ledger", params=params)
+
+
+class _QVerisBaseTool(BaseTool):
+ """Shared availability and client helpers for QVeris tools."""
+
+ @classmethod
+ def check_available(cls) -> bool:
+ """Hide QVeris tools until explicitly enabled and keyed."""
+ return is_qveris_configured()
+
+ def _client(self) -> QVerisClient:
+ return QVerisClient()
+
+
+class QVerisSearchTool(_QVerisBaseTool):
+ """Discover QVeris capabilities."""
+
+ name = "qveris_search"
+ description = (
+ "Search QVeris premium data/tool capabilities. Discover/inspect calls "
+ "are free; choose tools by expected_cost and stats.success_rate."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "Capability search query."},
+ "limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 100,
+ "default": 20,
+ },
+ "session_id": {"type": "string"},
+ },
+ "required": ["query"],
+ }
+
+ def execute(self, **kwargs: Any) -> str:
+ if not is_qveris_configured():
+ return _json_response({"ok": False, "error": "QVeris is not configured"})
+ payload = self._client().search(
+ str(kwargs["query"]),
+ limit=int(kwargs.get("limit", 20)),
+ session_id=kwargs.get("session_id"),
+ )
+ return _json_response({"ok": True, **payload})
+
+
+class QVerisInspectTool(_QVerisBaseTool):
+ """Inspect full QVeris tool parameter schemas."""
+
+ name = "qveris_inspect"
+ description = "Inspect QVeris tools by id before executing a paid call."
+ parameters = {
+ "type": "object",
+ "properties": {
+ "tool_ids": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "QVeris tool ids from qveris_search.",
+ },
+ "search_id": {"type": "string"},
+ "session_id": {"type": "string"},
+ },
+ "required": ["tool_ids"],
+ }
+
+ def execute(self, **kwargs: Any) -> str:
+ if not is_qveris_configured():
+ return _json_response({"ok": False, "error": "QVeris is not configured"})
+ payload = self._client().inspect(
+ list(kwargs["tool_ids"]),
+ search_id=kwargs.get("search_id"),
+ session_id=kwargs.get("session_id"),
+ )
+ return _json_response({"ok": True, **payload})
+
+
+class QVerisExecuteTool(_QVerisBaseTool):
+ """Execute a selected QVeris capability behind paid-mode budget gates."""
+
+ name = "qveris_execute"
+ description = (
+ "Execute a QVeris tool when paid QVeris routing is enabled. Enforces "
+ "the per-session credit budget before sending a billable request."
+ )
+ is_readonly = True
+ parameters = {
+ "type": "object",
+ "properties": {
+ "tool_id": {"type": "string"},
+ "parameters": {"type": "object"},
+ "search_id": {"type": "string"},
+ "session_id": {"type": "string"},
+ "model": {"type": "string"},
+ "max_response_size": {"type": "integer", "default": 20480},
+ "expected_cost": {
+ "description": "Optional quote copied from qveris_search/inspect.",
+ },
+ "billing_rule": {"type": "object"},
+ },
+ "required": ["tool_id", "parameters"],
+ }
+
+ def _quote(
+ self, client: QVerisClient, tool_id: str, kwargs: dict[str, Any]
+ ) -> dict[str, Any]:
+ quote = {
+ "tool_id": tool_id,
+ "expected_cost": kwargs.get("expected_cost"),
+ "billing_rule": kwargs.get("billing_rule"),
+ }
+ if quote["expected_cost"] is not None or quote["billing_rule"] is not None:
+ return quote
+ inspected = client.inspect(
+ [tool_id],
+ search_id=kwargs.get("search_id"),
+ session_id=kwargs.get("session_id"),
+ )
+ results = inspected.get("results") if isinstance(inspected, dict) else None
+ first = results[0] if isinstance(results, list) and results else None
+ return _quote_from_tool(first)
+
+ def execute(self, **kwargs: Any) -> str:
+ cfg = load_qveris_config()
+ if not is_qveris_configured(cfg):
+ return _json_response({"ok": False, "error": "QVeris is not configured"})
+ client = self._client()
+ tool_id = str(kwargs["tool_id"])
+ quote = self._quote(client, tool_id, kwargs)
+ session_id = str(kwargs.get("session_id") or "default")
+ spent = _SESSION_SPEND.get(session_id, 0.0)
+ budget = max(float(cfg.budget_credits_per_session), 0.0)
+ expected = _parse_expected_cost(quote.get("expected_cost"))
+ if spent >= budget or (expected is not None and spent + expected > budget):
+ return _json_response(
+ {
+ "ok": False,
+ "status": "budget_exceeded",
+ "spent_credits": spent,
+ "budget_credits_per_session": budget,
+ "quote": quote,
+ }
+ )
+
+ payload = client.execute(
+ tool_id,
+ parameters=dict(kwargs["parameters"]),
+ search_id=kwargs.get("search_id"),
+ session_id=kwargs.get("session_id"),
+ model=kwargs.get("model"),
+ max_response_size=int(kwargs.get("max_response_size", 20480)),
+ )
+ cost = float(payload.get("cost") or 0.0)
+ _SESSION_SPEND[session_id] = spent + max(cost, 0.0)
+ payload["cost"] = cost
+ payload["remaining_credits"] = payload.get("remaining_credits")
+ payload["session_spent_credits"] = _SESSION_SPEND[session_id]
+ return _json_response({"ok": True, **payload})
diff --git a/agent/tests/test_cli_data.py b/agent/tests/test_cli_data.py
new file mode 100644
index 000000000..d67f5d7dd
--- /dev/null
+++ b/agent/tests/test_cli_data.py
@@ -0,0 +1,44 @@
+from __future__ import annotations
+
+import pytest
+
+from cli import _legacy
+
+
+def test_data_parser_accepts_status_mode_and_usage() -> None:
+ parser = _legacy._build_parser()
+
+ status = parser.parse_args(["data", "status"])
+ assert status.command == "data"
+ assert status.data_command == "status"
+
+ free = parser.parse_args(["data", "mode", "free"])
+ assert free.command == "data"
+ assert free.data_command == "mode"
+ assert free.mode == "free"
+
+ paid = parser.parse_args([
+ "data",
+ "mode",
+ "paid",
+ "--budget",
+ "30",
+ "--key",
+ "sk-test",
+ "--url",
+ "https://qveris.test/api/v1",
+ ])
+ assert paid.mode == "paid"
+ assert paid.budget == 30
+ assert paid.key == "sk-test"
+ assert paid.url == "https://qveris.test/api/v1"
+
+ usage = parser.parse_args(["data", "usage"])
+ assert usage.data_command == "usage"
+
+
+def test_qveris_is_not_a_top_level_user_command() -> None:
+ parser = _legacy._build_parser()
+
+ with pytest.raises(SystemExit):
+ parser.parse_args(["qveris", "status"])
diff --git a/agent/tests/test_qveris_loader.py b/agent/tests/test_qveris_loader.py
new file mode 100644
index 000000000..86ec7ed93
--- /dev/null
+++ b/agent/tests/test_qveris_loader.py
@@ -0,0 +1,455 @@
+"""Tests for qveris_loader: config gating, mocked HTTP fetches, and registry safety.
+
+All QVeris calls are mocked by replacing ``requests.Session`` inside the loader
+module. No test reaches the live QVeris API or a signed full-content URL.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import pandas as pd
+import pytest
+
+from backtest.loaders import qveris_loader as qv
+from backtest.loaders.base import NoAvailableSourceError
+from backtest.loaders.registry import (
+ FALLBACK_CHAINS,
+ LOADER_REGISTRY,
+ get_loader_cls_with_fallback,
+)
+
+
+class _FakeResponse:
+ """Small response stub for the loader's embedded HTTP client."""
+
+ def __init__(
+ self,
+ payload: Any,
+ *,
+ status_code: int = 200,
+ headers: dict[str, str] | None = None,
+ text: str | None = None,
+ ) -> None:
+ self._payload = payload
+ self.status_code = status_code
+ self.headers = headers or {}
+ self.text = text if text is not None else json.dumps(payload)
+
+ def json(self) -> Any:
+ return self._payload
+
+ def raise_for_status(self) -> None:
+ if self.status_code >= 400:
+ raise RuntimeError(f"HTTP {self.status_code}")
+
+
+class _FakeSession:
+ """Queue-backed fake requests session."""
+
+ def __init__(self, responses: list[_FakeResponse]) -> None:
+ self.responses = responses
+ self.calls: list[dict[str, Any]] = []
+
+ def request(self, method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ self.calls.append({"method": method, "url": url, "kwargs": kwargs})
+ assert self.responses, f"unexpected HTTP call: {method} {url}"
+ return self.responses.pop(0)
+
+
[email protected](autouse=True)
+def _isolated_qveris_config(monkeypatch, tmp_path):
+ """Default every test to disabled QVeris with no cache or request sleep."""
+ monkeypatch.setattr(qv, "_CONFIG_PATH", tmp_path / "qveris.json")
+ monkeypatch.delenv("QVERIS_API_KEY", raising=False)
+ monkeypatch.delenv("QVERIS_BASE_URL", raising=False)
+ monkeypatch.setenv("VIBE_TRADING_DATA_CACHE", "0")
+ monkeypatch.setenv("VIBE_TRADING_QVERIS_MIN_INTERVAL", "0")
+
+
+def _write_config(
+ path,
+ *,
+ enabled: bool = True,
+ api_key: str = "sk_test",
+ mode: str = "paid",
+) -> None:
+ path.write_text(
+ json.dumps(
+ {
+ "enabled": enabled,
+ "base_url": "https://qveris.test/api/v1",
+ "api_key": api_key,
+ "mode": mode,
+ "budget_credits_per_session": 50.0,
+ }
+ ),
+ encoding="utf-8",
+ )
+
+
+def _capability(
+ tool_id: str = "tool_good",
+ *,
+ success_rate: float = 0.99,
+ expected_cost: str = "1.0 credits",
+) -> dict[str, Any]:
+ return {
+ "tool_id": tool_id,
+ "name": "Daily OHLCV candles",
+ "description": "Historical open high low close volume by ticker symbol",
+ "expected_cost": expected_cost,
+ "stats": {"success_rate": success_rate},
+ "params": [
+ {"name": "symbol", "type": "string", "required": True},
+ {"name": "start_date", "type": "string", "required": True},
+ {"name": "end_date", "type": "string", "required": True},
+ {"name": "interval", "type": "string", "enum": ["daily", "1D"]},
+ ],
+ "examples": {"sample_parameters": {"adjusted": True}},
+ }
+
+
+def _install_session(monkeypatch, responses: list[_FakeResponse]) -> _FakeSession:
+ session = _FakeSession(responses)
+ monkeypatch.setattr(qv.requests, "Session", lambda: session)
+ return session
+
+
+class TestAvailability:
+ """Config and env override gating."""
+
+ def test_missing_config_is_unavailable(self):
+ assert qv.DataLoader().is_available() is False
+
+ def test_disabled_config_stays_unavailable_even_with_env_key(self, monkeypatch):
+ _write_config(qv._CONFIG_PATH, enabled=False, api_key="")
+ monkeypatch.setenv("QVERIS_API_KEY", "sk_env")
+ assert qv.DataLoader().is_available() is False
+
+ def test_enabled_config_with_key_is_available(self):
+ _write_config(qv._CONFIG_PATH, enabled=True, api_key="sk_file")
+ assert qv.DataLoader().is_available() is True
+
+ def test_env_key_overrides_empty_file_key(self, monkeypatch):
+ _write_config(qv._CONFIG_PATH, enabled=True, api_key="")
+ monkeypatch.setenv("QVERIS_API_KEY", "sk_env")
+ assert qv.DataLoader().is_available() is True
+
+ def test_metadata(self):
+ assert qv.DataLoader.name == "qveris"
+ assert qv.DataLoader.requires_auth is True
+
+
+class TestFetch:
+ """fetch() search-selects, executes, normalizes, and isolates empty symbols."""
+
+ def test_returns_empty_without_availability_and_makes_no_http(self, monkeypatch):
+ session = _install_session(monkeypatch, [])
+ assert qv.DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31") == {}
+ assert session.calls == []
+
+ def test_free_mode_keeps_qveris_loader_unavailable(self, monkeypatch):
+ _write_config(qv._CONFIG_PATH, enabled=True, api_key="sk_test", mode="free")
+ session = _install_session(monkeypatch, [])
+
+ assert qv.DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31") == {}
+ assert session.calls == []
+
+ def test_search_execute_happy_path_selects_best_capability(self, monkeypatch):
+ _write_config(qv._CONFIG_PATH)
+ session = _install_session(
+ monkeypatch,
+ [
+ _FakeResponse(
+ {
+ "search_id": "s_123",
+ "results": [
+ _capability("expensive", success_rate=0.99, expected_cost="5 credits"),
+ _capability("cheap", success_rate=0.99, expected_cost="1 credits"),
+ _capability("weaker", success_rate=0.5, expected_cost="0.1 credits"),
+ ],
+ }
+ ),
+ _FakeResponse(
+ {
+ "success": True,
+ "result": {
+ "data": [
+ {
+ "date": "2024-01-02",
+ "open": "100",
+ "high": "112",
+ "low": "99",
+ "close": "110",
+ "volume": "1000",
+ }
+ ]
+ },
+ }
+ ),
+ ],
+ )
+
+ out = qv.DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")
+
+ assert list(out) == ["AAPL.US"]
+ df = out["AAPL.US"]
+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]
+ assert df.index.name == "trade_date"
+ assert isinstance(df.index, pd.DatetimeIndex)
+ assert df.index.dtype == "datetime64[ns]"
+ assert df.loc["2024-01-02", "close"] == 110.0
+ assert df.loc["2024-01-02", "volume"] == 1000.0
+
+ assert session.calls[0]["url"] == "https://qveris.test/api/v1/search"
+ assert session.calls[0]["kwargs"]["json"]["limit"] == 20
+ assert session.calls[1]["url"].endswith("/tools/execute?tool_id=cheap")
+ execute_body = session.calls[1]["kwargs"]["json"]
+ assert execute_body["search_id"] == "s_123"
+ assert execute_body["parameters"]["symbol"] == "AAPL"
+ assert execute_body["parameters"]["start_date"] == "2024-01-01"
+ assert execute_body["parameters"]["end_date"] == "2024-01-31"
+ assert execute_body["parameters"]["adjusted"] is True
+
+ def test_truncated_result_download_path(self, monkeypatch):
+ _write_config(qv._CONFIG_PATH)
+ session = _install_session(
+ monkeypatch,
+ [
+ _FakeResponse({"search_id": "s_1", "results": [_capability()]}),
+ _FakeResponse(
+ {
+ "success": True,
+ "result": {
+ "message": "too long",
+ "full_content_file_url": "https://oss.qveris.cn/full.json",
+ "truncated_content": "[]",
+ },
+ }
+ ),
+ _FakeResponse(
+ [
+ {
+ "date": "2024-01-02",
+ "open": 10,
+ "high": 12,
+ "low": 9,
+ "close": 11,
+ }
+ ]
+ ),
+ ],
+ )
+
+ out = qv.DataLoader().fetch(["MSFT"], "2024-01-01", "2024-01-31")
+
+ assert list(out) == ["MSFT"]
+ assert pd.isna(out["MSFT"].loc["2024-01-02", "volume"])
+ assert session.calls[2]["method"] == "get"
+ assert session.calls[2]["url"] == "https://oss.qveris.cn/full.json"
+ assert "Authorization" not in session.calls[2]["kwargs"]["headers"]
+
+ def test_search_no_ohlcv_result_omits_symbol(self, monkeypatch):
+ _write_config(qv._CONFIG_PATH)
+ session = _install_session(
+ monkeypatch,
+ [
+ _FakeResponse(
+ {
+ "search_id": "s_1",
+ "results": [
+ {
+ "tool_id": "news",
+ "name": "Company news",
+ "description": "Headlines by ticker symbol",
+ "expected_cost": "1",
+ "stats": {"success_rate": 1},
+ }
+ ],
+ }
+ )
+ ],
+ )
+
+ assert qv.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31") == {}
+ assert len(session.calls) == 1
+
+ def test_date_filtering_and_ohlc_validation(self, monkeypatch):
+ _write_config(qv._CONFIG_PATH)
+ session = _install_session(
+ monkeypatch,
+ [
+ _FakeResponse({"search_id": "s_1", "results": [_capability()]}),
+ _FakeResponse(
+ {
+ "success": True,
+ "result": {
+ "historical": [
+ {"date": "2023-12-29", "open": 1, "high": 1, "low": 1, "close": 1},
+ {"date": "2024-01-02", "open": 2, "high": 3, "low": 1, "close": 2.5},
+ {"date": "2024-01-03", "open": 5, "high": 4, "low": 1, "close": 4},
+ {"date": "2024-02-01", "open": 6, "high": 6, "low": 6, "close": 6},
+ ]
+ },
+ }
+ ),
+ ],
+ )
+
+ df = qv.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31")["AAPL"]
+
+ assert [d.strftime("%Y-%m-%d") for d in df.index] == ["2024-01-02"]
+ assert df.loc["2024-01-02", "open"] == 2.0
+ assert len(session.calls) == 2
+
+ def test_invalid_date_range_raises(self):
+ _write_config(qv._CONFIG_PATH)
+ with pytest.raises(ValueError):
+ qv.DataLoader().fetch(["AAPL"], "2024-02-01", "2024-01-01")
+
+
+class TestHttpClient:
+ """429 backoff is local and mockable."""
+
+ def test_429_retries_after_header(self, monkeypatch):
+ _write_config(qv._CONFIG_PATH)
+ session = _install_session(
+ monkeypatch,
+ [
+ _FakeResponse({}, status_code=429, headers={"Retry-After": "0"}),
+ _FakeResponse({"search_id": "s_1", "results": []}),
+ ],
+ )
+
+ payload = qv.QVerisClient(qv._load_config()).search("daily OHLCV AAPL")
+
+ assert payload == {"search_id": "s_1", "results": []}
+ assert len(session.calls) == 2
+
+
+class TestCapabilitySelection:
+ """Granularity filtering and multi-candidate fallback (live-e2e regressions)."""
+
+ def test_daily_request_excludes_monthly_and_intraday_series(self, monkeypatch):
+ """A monthly series with perfect stats must lose to a daily one."""
+ _write_config(qv._CONFIG_PATH)
+ monthly = _capability("alphavantage.time_series.monthly_adjusted.v1", success_rate=1.0)
+ monthly["name"] = "Monthly Adjusted Time Series"
+ intraday = _capability("alphavantage.time-series.intraday.v1", success_rate=1.0)
+ intraday["description"] = "Intraday open high low close by ticker symbol"
+ daily = _capability("tiingo.core.eod.v1", success_rate=0.5)
+ session = _install_session(
+ monkeypatch,
+ [
+ _FakeResponse(
+ {"search_id": "s_1", "results": [monthly, intraday, daily]}
+ ),
+ _FakeResponse(
+ {
+ "success": True,
+ "result": {
+ "data": [
+ {
+ "date": "2024-01-02",
+ "open": 1,
+ "high": 2,
+ "low": 0.5,
+ "close": 1.5,
+ "volume": 10,
+ }
+ ]
+ },
+ }
+ ),
+ ],
+ )
+
+ data = qv.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31")
+
+ assert "AAPL" in data
+ execute_url = session.calls[1]["url"]
+ assert "tiingo.core.eod.v1" in execute_url
+
+ def test_falls_back_to_second_candidate_when_first_result_unparseable(self, monkeypatch):
+ """An unparseable paid result must not silently drop the symbol."""
+ _write_config(qv._CONFIG_PATH)
+ first = _capability("daily_bad", success_rate=0.99)
+ second = _capability("daily_good", success_rate=0.90)
+ session = _install_session(
+ monkeypatch,
+ [
+ _FakeResponse({"search_id": "s_1", "results": [first, second]}),
+ _FakeResponse({"success": True, "result": {"unexpected": "shape"}}),
+ _FakeResponse(
+ {
+ "success": True,
+ "result": {
+ "data": [
+ {
+ "date": "2024-01-02",
+ "open": 1,
+ "high": 2,
+ "low": 0.5,
+ "close": 1.5,
+ "volume": 10,
+ }
+ ]
+ },
+ }
+ ),
+ ],
+ )
+
+ data = qv.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31")
+
+ assert "AAPL" in data
+ assert "daily_bad" in session.calls[1]["url"]
+ assert "daily_good" in session.calls[2]["url"]
+
+ def test_parses_provider_named_series_container(self, monkeypatch):
+ """AlphaVantage-style '<X> Time Series' containers must parse."""
+ _write_config(qv._CONFIG_PATH)
+ session = _install_session(
+ monkeypatch,
+ [
+ _FakeResponse({"search_id": "s_1", "results": [_capability()]}),
+ _FakeResponse(
+ {
+ "success": True,
+ "result": {
+ "Meta Data": {"1. Information": "Daily Prices"},
+ "Time Series (Daily Adjusted)": {
+ "2024-01-02": {
+ "1. open": "1.0",
+ "2. high": "2.0",
+ "3. low": "0.5",
+ "4. close": "1.5",
+ "5. volume": "10",
+ }
+ },
+ },
+ }
+ ),
+ ],
+ )
+
+ data = qv.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31")
+
+ assert "AAPL" in data
+ assert float(data["AAPL"]["close"].iloc[0]) == 1.5
+ assert len(session.calls) == 2
+
+
+def test_auto_fallback_chains_do_not_contain_qveris():
+ """QVeris is explicit-only and must never be selected by source='auto'."""
+ assert "qveris" in LOADER_REGISTRY
+ assert all("qveris" not in chain for chain in FALLBACK_CHAINS.values())
+
+
+def test_explicit_unavailable_qveris_does_not_fallback_to_network():
+ """An unavailable explicit qveris source raises instead of falling back."""
+ with pytest.raises(NoAvailableSourceError) as excinfo:
+ get_loader_cls_with_fallback("qveris")
+ assert "qveris" in str(excinfo.value).lower()
diff --git a/agent/tests/test_qveris_routes.py b/agent/tests/test_qveris_routes.py
new file mode 100644
index 000000000..f22dbaa61
--- /dev/null
+++ b/agent/tests/test_qveris_routes.py
@@ -0,0 +1,151 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from fastapi.testclient import TestClient
+
+import api_server
+from src.api import qveris_routes
+from src.tools import qveris_tool as qt
+
+
+def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ monkeypatch.setattr(qt, "QVERIS_CONFIG_PATH", tmp_path / "qveris.json")
+ monkeypatch.delenv("QVERIS_API_KEY", raising=False)
+ monkeypatch.delenv("QVERIS_BASE_URL", raising=False)
+ monkeypatch.delenv("API_AUTH_KEY", raising=False)
+ monkeypatch.setattr(api_server, "_API_KEY", "")
+ return TestClient(api_server.app, client=("127.0.0.1", 50000))
+
+
+def test_get_config_returns_redacted_unconfigured_shape(client: TestClient):
+ response = client.get("/qveris/config")
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body == {
+ "enabled": False,
+ "base_url": qt.DEFAULT_BASE_URL,
+ "api_key_masked": "",
+ "mode": "free",
+ "budget_credits_per_session": 50.0,
+ "configured": False,
+ "signup_url": qt.SIGNUP_URL,
+ "invite_code": qt.INVITE_CODE,
+ }
+
+
+def test_put_config_persists_and_never_returns_plain_key(client: TestClient):
+ response = client.put(
+ "/qveris/config",
+ json={
+ "enabled": True,
+ "base_url": "https://qveris.example/api",
+ "api_key": "sk-secret-8TI",
+ "mode": "paid",
+ "budget_credits_per_session": 7.5,
+ },
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["enabled"] is True
+ assert body["configured"] is True
+ assert body["api_key_masked"] == "sk-s…8TI"
+ assert "sk-secret-8TI" not in response.text
+ assert qt.load_qveris_config().api_key == "sk-secret-8TI"
+
+
+def test_put_config_rejects_bad_mode_and_bad_url(client: TestClient):
+ bad_mode = client.put("/qveris/config", json={"mode": "live"})
+ bad_url = client.put("/qveris/config", json={"base_url": "ftp://qveris.test"})
+
+ assert bad_mode.status_code == 422
+ assert bad_url.status_code == 422
+
+
+def test_put_config_empty_key_preserves_existing_key(client: TestClient):
+ qt.save_qveris_config(qt.QVerisConfig(enabled=True, api_key="sk-existing-abc"))
+
+ response = client.put("/qveris/config", json={"api_key": "", "mode": "paid"})
+
+ assert response.status_code == 200
+ assert qt.load_qveris_config().api_key == "sk-existing-abc"
+ assert response.json()["mode"] == "paid"
+
+
+def test_status_unconfigured_is_fail_closed(client: TestClient):
+ response = client.get("/qveris/status")
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["enabled"] is False
+ assert body["ok"] is False
+ assert body["remaining_credits"] is None
+ assert body["recent"] == []
+
+
+def test_status_paid_mode_uses_qveris_search_and_usage_history(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+):
+ qt.save_qveris_config(qt.QVerisConfig(enabled=True, api_key="sk-live", mode="paid"))
+
+ class FakeClient:
+ def __init__(self, config):
+ self.config = config
+
+ def search(self, query, *, limit):
+ assert query == "status"
+ assert limit == 1
+ return {"remaining_credits": 88.0}
+
+ def usage_history(self, **params):
+ return {
+ "events": [
+ {
+ "ts": "2026-07-07T00:00:00Z",
+ "tool_id": "tool_1",
+ "cost": 1.5,
+ "charge_outcome": "charged",
+ }
+ ]
+ }
+
+ monkeypatch.setattr(qveris_routes, "QVerisClient", FakeClient)
+
+ response = client.get("/qveris/status")
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["ok"] is True
+ assert body["remaining_credits"] == 88.0
+ assert body["recent"] == [
+ {
+ "ts": "2026-07-07T00:00:00Z",
+ "tool_id": "tool_1",
+ "cost": 1.5,
+ "charge_outcome": "charged",
+ }
+ ]
+
+
+def test_status_free_mode_keeps_public_data_route_and_skips_qveris_call(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+):
+ qt.save_qveris_config(qt.QVerisConfig(enabled=True, api_key="sk-live", mode="free"))
+
+ class FakeClient:
+ def __init__(self, config): # pragma: no cover - must not instantiate
+ raise AssertionError("free mode must not contact QVeris")
+
+ monkeypatch.setattr(qveris_routes, "QVerisClient", FakeClient)
+
+ response = client.get("/qveris/status")
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["ok"] is False
+ assert body["remaining_credits"] is None
+ assert body["recent"] == []
diff --git a/agent/tests/test_qveris_tool.py b/agent/tests/test_qveris_tool.py
new file mode 100644
index 000000000..8cfada6ef
--- /dev/null
+++ b/agent/tests/test_qveris_tool.py
@@ -0,0 +1,192 @@
+from __future__ import annotations
+
+import json
+import stat
+from pathlib import Path
+
+import pytest
+
+from src.tools import qveris_tool as qt
+
+
[email protected](autouse=True)
+def qveris_config_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(qt, "QVERIS_CONFIG_PATH", tmp_path / "qveris.json")
+ monkeypatch.delenv("QVERIS_API_KEY", raising=False)
+ monkeypatch.delenv("QVERIS_BASE_URL", raising=False)
+ qt._SESSION_SPEND.clear()
+ return tmp_path / "qveris.json"
+
+
+class FakeResponse:
+ def __init__(self, status_code: int, payload: dict, headers: dict | None = None):
+ self.status_code = status_code
+ self._payload = payload
+ self.headers = headers or {}
+ self.content = json.dumps(payload).encode("utf-8")
+
+ def raise_for_status(self) -> None:
+ if self.status_code >= 400:
+ raise RuntimeError(f"HTTP {self.status_code}")
+
+ def json(self) -> dict:
+ return self._payload
+
+
+class FakeHttpClient:
+ def __init__(self, responses: list[FakeResponse]):
+ self.responses = responses
+ self.calls: list[dict] = []
+
+ def request(self, method, url, **kwargs):
+ self.calls.append({"method": method, "url": url, **kwargs})
+ return self.responses.pop(0)
+
+
+def test_config_read_write_masks_key_and_uses_0600(qveris_config_path: Path):
+ saved = qt.save_qveris_config(
+ qt.QVerisConfig(
+ enabled=True,
+ base_url="https://example.test/api",
+ api_key="sk-test-8TI",
+ mode="paid",
+ budget_credits_per_session=12.5,
+ )
+ )
+
+ assert saved.enabled is True
+ assert qt.load_qveris_config().api_key == "sk-test-8TI"
+ assert qt.mask_api_key("sk-test-8TI") == "sk-t…8TI"
+ assert stat.S_IMODE(qveris_config_path.stat().st_mode) == 0o600
+
+
+def test_env_overrides_file_config(monkeypatch: pytest.MonkeyPatch):
+ qt.save_qveris_config(
+ qt.QVerisConfig(enabled=True, base_url="https://file.test", api_key="file-key")
+ )
+ monkeypatch.setenv("QVERIS_API_KEY", "env-key")
+ monkeypatch.setenv("QVERIS_BASE_URL", "https://env.test/api")
+
+ cfg = qt.load_qveris_config()
+
+ assert cfg.api_key == "env-key"
+ assert cfg.base_url == "https://env.test/api"
+
+
+def test_free_mode_tools_are_hidden():
+ assert qt.QVerisSearchTool.check_available() is False
+
+ qt.save_qveris_config(qt.QVerisConfig(enabled=True, api_key="sk-live", mode="free"))
+
+ assert qt.QVerisSearchTool.check_available() is False
+
+ qt.save_qveris_config(qt.QVerisConfig(enabled=True, api_key="sk-live", mode="paid"))
+
+ assert qt.QVerisSearchTool.check_available() is True
+
+
+def test_free_mode_execute_is_unavailable(monkeypatch: pytest.MonkeyPatch):
+ qt.save_qveris_config(
+ qt.QVerisConfig(enabled=True, api_key="sk-live", mode="free")
+ )
+
+ class FakeClient:
+ def inspect(self, tool_ids, **kwargs):
+ return {
+ "results": [
+ {
+ "tool_id": tool_ids[0],
+ "expected_cost": "2 credits",
+ "billing_rule": {"kind": "call"},
+ }
+ ]
+ }
+
+ monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: FakeClient())
+
+ payload = json.loads(
+ qt.QVerisExecuteTool().execute(tool_id="tool_1", parameters={"x": 1})
+ )
+
+ assert payload == {"ok": False, "error": "QVeris is not configured"}
+
+
+def test_paid_mode_rejects_when_expected_cost_exceeds_budget(monkeypatch):
+ qt.save_qveris_config(
+ qt.QVerisConfig(
+ enabled=True,
+ api_key="sk-live",
+ mode="paid",
+ budget_credits_per_session=1.0,
+ )
+ )
+
+ class FakeClient:
+ def execute(self, *args, **kwargs): # pragma: no cover - must not call
+ raise AssertionError("execute should be blocked by budget")
+
+ monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: FakeClient())
+
+ payload = json.loads(
+ qt.QVerisExecuteTool().execute(
+ tool_id="tool_1",
+ parameters={},
+ session_id="s1",
+ expected_cost="2 credits",
+ )
+ )
+
+ assert payload["status"] == "budget_exceeded"
+ assert payload["budget_credits_per_session"] == 1.0
+
+
+def test_429_retries_after_retry_after(monkeypatch: pytest.MonkeyPatch):
+ sleeps: list[float] = []
+ monkeypatch.setattr(qt.time, "sleep", lambda value: sleeps.append(value))
+ fake = FakeHttpClient(
+ [
+ FakeResponse(429, {"error": "rate"}, headers={"Retry-After": "0"}),
+ FakeResponse(200, {"results": [], "remaining_credits": 9}),
+ ]
+ )
+ client = qt.QVerisClient(
+ qt.QVerisConfig(enabled=True, api_key="sk-live"),
+ client=fake,
+ min_interval_seconds=0,
+ )
+
+ payload = client.search("aapl", limit=1)
+
+ assert payload["remaining_credits"] == 9
+ assert len(fake.calls) == 2
+ assert sleeps == [0.0]
+
+
+def test_execute_hydrates_truncated_full_content():
+ fake = FakeHttpClient(
+ [
+ FakeResponse(
+ 200,
+ {
+ "success": True,
+ "cost": 1.0,
+ "result": {
+ "message": "too long",
+ "full_content_file_url": "https://oss.qveris.cn/file.json",
+ },
+ },
+ ),
+ FakeResponse(200, {"rows": [{"close": 1.23}]}),
+ ]
+ )
+ client = qt.QVerisClient(
+ qt.QVerisConfig(enabled=True, api_key="sk-live"),
+ client=fake,
+ min_interval_seconds=0,
+ )
+
+ payload = client.execute("tool_1", parameters={}, max_response_size=10)
+
+ assert payload["result"]["full_content"] == {"rows": [{"close": 1.23}]}
+ assert payload["result"]["full_content_downloaded"] is True
+ assert fake.calls[1]["headers"] is None
diff --git a/frontend/src/components/settings/QVerisSettings.tsx b/frontend/src/components/settings/QVerisSettings.tsx
new file mode 100644
index 000000000..c31a0c5f1
--- /dev/null
+++ b/frontend/src/components/settings/QVerisSettings.tsx
@@ -0,0 +1,350 @@
+import { useEffect, useId, useState, type FormEvent } from "react";
+import { ExternalLink, KeyRound, Loader2, Save, SearchCheck } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { toast } from "sonner";
+import { authHeaders } from "@/lib/apiAuth";
+
+type QVerisMode = "free" | "paid";
+
+interface QVerisConfig {
+ enabled: boolean;
+ base_url: string;
+ api_key_masked: string;
+ mode: QVerisMode;
+ budget_credits_per_session: number;
+ configured: boolean;
+ signup_url: string;
+ invite_code: string;
+}
+
+interface QVerisStatus {
+ enabled: boolean;
+ ok: boolean;
+ error: string | null;
+ remaining_credits: number | null;
+ recent: Array<{
+ ts: string;
+ tool_id: string;
+ cost: number;
+ charge_outcome: string;
+ }>;
+ signup_url: string;
+ invite_code: string;
+}
+
+interface QVerisForm {
+ enabled: boolean;
+ base_url: string;
+ api_key: string;
+ mode: QVerisMode;
+ budget_credits_per_session: number;
+}
+
+const DEFAULT_BASE_URL = "https://qveris.ai/api/v1";
+const fieldClass =
+ "w-full rounded-md border bg-background px-3 py-2 text-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/20 disabled:cursor-not-allowed disabled:opacity-60";
+const labelClass = "text-sm font-medium";
+const hintClass = "text-xs text-muted-foreground";
+
+async function requestJson<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 response = await fetch(path, { ...rest, headers: mergedHeaders });
+ if (!response.ok) {
+ let message = `HTTP ${response.status}`;
+ try {
+ const body = await response.json();
+ message = body.detail || body.message || message;
+ } catch { /* ignore */ }
+ throw new Error(message);
+ }
+ return response.json() as Promise<T>;
+}
+
+function formFromConfig(config: QVerisConfig): QVerisForm {
+ return {
+ enabled: config.enabled && config.mode === "paid",
+ base_url: config.base_url || DEFAULT_BASE_URL,
+ api_key: "",
+ mode: config.mode,
+ budget_credits_per_session: config.budget_credits_per_session,
+ };
+}
+
+export function QVerisSettings() {
+ const { t } = useTranslation();
+ const idPrefix = useId();
+ const [config, setConfig] = useState<QVerisConfig | null>(null);
+ const [status, setStatus] = useState<QVerisStatus | null>(null);
+ const [form, setForm] = useState<QVerisForm>({
+ enabled: false,
+ base_url: DEFAULT_BASE_URL,
+ api_key: "",
+ mode: "free",
+ budget_credits_per_session: 50,
+ });
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const load = async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const [nextConfig, nextStatus] = await Promise.all([
+ requestJson<QVerisConfig>("/qveris/config"),
+ requestJson<QVerisStatus>("/qveris/status"),
+ ]);
+ setConfig(nextConfig);
+ setForm(formFromConfig(nextConfig));
+ setStatus(nextStatus);
+ } catch (loadError) {
+ setError(loadError instanceof Error ? loadError.message : t("qveris.testFailed"));
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ useEffect(() => {
+ let alive = true;
+ setLoading(true);
+ setError(null);
+
+ Promise.all([
+ requestJson<QVerisConfig>("/qveris/config"),
+ requestJson<QVerisStatus>("/qveris/status"),
+ ])
+ .then(([nextConfig, nextStatus]) => {
+ if (!alive) return;
+ setConfig(nextConfig);
+ setForm(formFromConfig(nextConfig));
+ setStatus(nextStatus);
+ })
+ .catch((loadError) => {
+ if (!alive) return;
+ setError(loadError instanceof Error ? loadError.message : t("qveris.testFailed"));
+ })
+ .finally(() => {
+ if (alive) setLoading(false);
+ });
+
+ return () => {
+ alive = false;
+ };
+ }, [t]);
+
+ const submit = async (event: FormEvent) => {
+ event.preventDefault();
+ setSaving(true);
+ setError(null);
+ try {
+ const payload: {
+ enabled: boolean;
+ base_url: string;
+ mode: QVerisMode;
+ budget_credits_per_session: number;
+ api_key?: string;
+ } = {
+ enabled: form.mode === "paid" && form.enabled,
+ base_url: form.base_url.trim(),
+ mode: form.mode,
+ budget_credits_per_session: Number(form.budget_credits_per_session) || 0,
+ };
+ const trimmedApiKey = form.api_key.trim();
+ if (trimmedApiKey) payload.api_key = trimmedApiKey;
+
+ const nextConfig = await requestJson<QVerisConfig>("/qveris/config", {
+ method: "PUT",
+ body: JSON.stringify(payload),
+ });
+ setConfig(nextConfig);
+ setForm(formFromConfig(nextConfig));
+ toast.success(t("qveris.saved"));
+ await load();
+ } catch (saveError) {
+ const message = saveError instanceof Error ? saveError.message : t("qveris.testFailed");
+ setError(message);
+ toast.error(t("qveris.testFailed"));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const recent = status?.recent ?? [];
+ const signupUrl = config?.signup_url || "";
+ const inviteCode = config?.invite_code || status?.invite_code || "";
+ const apiKeyPlaceholder = config?.api_key_masked || t("qveris.apiKeyPlaceholder");
+
+ return (
+ <section className="rounded-lg border bg-card p-5 shadow-sm">
+ <div className="mb-5 flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
+ <div className="space-y-1">
+ <div className="flex items-center gap-2">
+ <SearchCheck className="h-4 w-4 text-primary" />
+ <h2 className="text-base font-semibold">{t("qveris.title")}</h2>
+ </div>
+ <p className="max-w-3xl text-sm text-muted-foreground">{t("qveris.subtitle")}</p>
+ </div>
+ <a
+ href={signupUrl || undefined}
+ target="_blank"
+ rel="noreferrer"
+ aria-disabled={!signupUrl}
+ className={`inline-flex items-center justify-center gap-2 rounded-md border px-3 py-2 text-sm transition ${
+ signupUrl
+ ? "text-muted-foreground hover:bg-muted hover:text-foreground"
+ : "pointer-events-none text-muted-foreground opacity-60"
+ }`}
+ >
+ <ExternalLink className="h-4 w-4" />
+ {t("qveris.signupCta")}
+ </a>
+ </div>
+
+ {error ? (
+ <div className="mb-4 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
+ <span className="font-medium">{t("qveris.testFailed")}: </span>
+ <span>{error}</span>
+ </div>
+ ) : null}
+
+ <form onSubmit={submit} className="grid gap-5 lg:grid-cols-[minmax(0,1.1fr)_minmax(280px,0.9fr)]">
+ <div className="grid gap-4">
+ <label className="flex items-center justify-between gap-3 rounded-md border bg-muted/20 px-3 py-2">
+ <span className={labelClass}>{t("qveris.enabled")}</span>
+ <input
+ type="checkbox"
+ checked={form.enabled}
+ onChange={(event) => {
+ const enabled = event.target.checked;
+ setForm({ ...form, enabled, mode: enabled ? "paid" : "free" });
+ }}
+ className="h-4 w-4 accent-primary"
+ disabled={loading}
+ />
+ </label>
+
+ <label className="grid gap-2" htmlFor={`${idPrefix}-base-url`}>
+ <span className={labelClass}>{t("qveris.baseUrl")}</span>
+ <input
+ id={`${idPrefix}-base-url`}
+ value={form.base_url}
+ onChange={(event) => setForm({ ...form, base_url: event.target.value })}
+ className={fieldClass}
+ placeholder={DEFAULT_BASE_URL}
+ disabled={loading}
+ />
+ </label>
+
+ <label className="grid gap-2" htmlFor={`${idPrefix}-api-key`}>
+ <span className={labelClass}>{t("qveris.apiKey")}</span>
+ <div className="relative">
+ <KeyRound className="pointer-events-none absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
+ <input
+ id={`${idPrefix}-api-key`}
+ type="password"
+ value={form.api_key}
+ onChange={(event) => setForm({ ...form, api_key: event.target.value })}
+ className={`${fieldClass} pl-9`}
+ placeholder={apiKeyPlaceholder}
+ autoComplete="current-password"
+ disabled={loading}
+ />
+ </div>
+ <span className={hintClass}>{t("qveris.apiKeyPlaceholder")}</span>
+ </label>
+
+ <div className="grid gap-4 md:grid-cols-2">
+ <label className="grid gap-2" htmlFor={`${idPrefix}-mode`}>
+ <span className={labelClass}>{t("qveris.mode")}</span>
+ <select
+ id={`${idPrefix}-mode`}
+ value={form.mode}
+ onChange={(event) => {
+ const mode = event.target.value as QVerisMode;
+ setForm({ ...form, mode, enabled: mode === "paid" });
+ }}
+ className={fieldClass}
+ disabled={loading}
+ >
+ <option value="free">{t("qveris.modeFree")}</option>
+ <option value="paid">{t("qveris.modePaid")}</option>
+ </select>
+ </label>
+
+ <label className="grid gap-2" htmlFor={`${idPrefix}-budget`}>
+ <span className={labelClass}>{t("qveris.budget")}</span>
+ <input
+ id={`${idPrefix}-budget`}
+ type="number"
+ min={0}
+ step={1}
+ value={form.budget_credits_per_session}
+ onChange={(event) => setForm({ ...form, budget_credits_per_session: Number(event.target.value) })}
+ className={fieldClass}
+ disabled={loading}
+ />
+ <span className={hintClass}>{t("qveris.budgetHint")}</span>
+ </label>
+ </div>
+
+ <button
+ type="submit"
+ disabled={loading || saving}
+ className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-70"
+ >
+ {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
+ {t("qveris.save")}
+ </button>
+ </div>
+
+ <div className="grid gap-4">
+ <div className="rounded-md border bg-muted/20 p-4">
+ <div className="mb-3 flex items-center justify-between gap-3">
+ <span className="text-sm font-medium">{t("qveris.balance")}</span>
+ {loading ? <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" /> : null}
+ </div>
+ <div className="text-2xl font-semibold">
+ {status?.remaining_credits ?? t("qveris.notConfigured")}
+ </div>
+ {status?.error ? <p className="mt-2 text-xs text-destructive">{status.error}</p> : null}
+ </div>
+
+ <div className="rounded-md border bg-muted/20 p-4">
+ <div className="mb-3 text-sm font-medium">{t("qveris.recentUsage")}</div>
+ {recent.length ? (
+ <div className="space-y-2">
+ {recent.map((item) => (
+ <div key={`${item.ts}-${item.tool_id}`} className="rounded-md border bg-background px-3 py-2 text-xs">
+ <div className="flex items-center justify-between gap-3">
+ <span className="font-medium">{item.tool_id}</span>
+ <span className="text-muted-foreground">{item.cost}</span>
+ </div>
+ <div className="mt-1 flex items-center justify-between gap-3 text-muted-foreground">
+ <span>{item.ts}</span>
+ <span>{item.charge_outcome}</span>
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <p className="text-sm text-muted-foreground">{t("qveris.noUsage")}</p>
+ )}
+ </div>
+
+ <div className="rounded-md border bg-muted/20 p-4">
+ <div className="mb-2 text-sm font-medium">{t("qveris.signupHint")}</div>
+ <div className="text-xs text-muted-foreground">{t("qveris.inviteCode")}</div>
+ <div className="mt-1 break-all font-mono text-sm">{inviteCode || t("qveris.notConfigured")}</div>
+ </div>
+ </div>
+ </form>
+ </section>
+ );
+}
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index 7ebe715e1..4c2b4d89f 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -320,6 +320,29 @@
"sessionRuntime": "وقت تشغيل الجلسة",
"flagsReadFrom": "تُقرأ الأعلام من {{env1}} و{{env2}} و{{env3}} في {{env_path}}."
},
+ "qveris": {
+ "title": "سوق أدوات QVeris",
+ "subtitle": "أبقِ البيانات العامة المجانية كخيار افتراضي، وفعّل تنفيذ QVeris المدفوع عند الحاجة فقط.",
+ "enabled": "تفعيل مسار QVeris المدفوع",
+ "baseUrl": "Base URL",
+ "apiKey": "مفتاح API",
+ "apiKeyPlaceholder": "اتركه فارغًا للاحتفاظ بالمفتاح الحالي",
+ "mode": "الوضع",
+ "modeFree": "البيانات العامة المجانية فقط",
+ "modePaid": "تفعيل QVeris المدفوع",
+ "budget": "رصيد Credits لكل جلسة",
+ "budgetHint": "يتوقف التنفيذ المدفوع عند بلوغ ميزانية هذه الجلسة.",
+ "balance": "Credits المتبقية",
+ "recentUsage": "الاستخدام الأخير",
+ "noUsage": "لا يوجد استخدام حديث",
+ "signupCta": "فتح التسجيل",
+ "signupHint": "استخدم رمز الدعوة هذا عند إنشاء حساب QVeris.",
+ "inviteCode": "رمز الدعوة",
+ "save": "حفظ إعدادات QVeris",
+ "saved": "تم حفظ إعدادات QVeris",
+ "testFailed": "فشل طلب QVeris",
+ "notConfigured": "غير مكوّن"
+ },
"agent": {
"connectionLostReconnect": "فُقد الاتصال، جارٍ إعادة الاتصال…",
"connectionRestored": "تمت استعادة الاتصال",
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 2778a9b0c..2bd71033e 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -325,6 +325,29 @@
"sessionRuntime": "Session Runtime",
"flagsReadFrom": "Flags are read from {{env1}}, {{env2}}, and {{env3}} in {{env_path}}."
},
+ "qveris": {
+ "title": "QVeris Tool Marketplace",
+ "subtitle": "Keep free public data as the default, or enable paid QVeris execution for specialized data tools.",
+ "enabled": "Enable paid QVeris route",
+ "baseUrl": "Base URL",
+ "apiKey": "API key",
+ "apiKeyPlaceholder": "Leave blank to keep the current key",
+ "mode": "Mode",
+ "modeFree": "Free public data only",
+ "modePaid": "Paid QVeris enabled",
+ "budget": "Budget credits per session",
+ "budgetHint": "Paid execution stops when this session budget is reached.",
+ "balance": "Remaining credits",
+ "recentUsage": "Recent usage",
+ "noUsage": "No recent usage",
+ "signupCta": "Open signup",
+ "signupHint": "Use this invitation code when creating your QVeris account.",
+ "inviteCode": "Invitation code",
+ "save": "Save QVeris settings",
+ "saved": "QVeris settings saved",
+ "testFailed": "QVeris request failed",
+ "notConfigured": "Not configured"
+ },
"agent": {
"connectionLostReconnect": "Connection lost, reconnecting…",
"connectionRestored": "Connection restored",
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index 43fa2a721..3d0852faa 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -320,6 +320,29 @@
"sessionRuntime": "セッションランタイム",
"flagsReadFrom": "フラグは {{env_path}} の {{env1}}、{{env2}}、{{env3}} から読み取られます。"
},
+ "qveris": {
+ "title": "QVeris ツールマーケットプレイス",
+ "subtitle": "無料の公開データを既定のまま使い、必要なときだけ QVeris の有料実行を有効にします。",
+ "enabled": "QVeris 有料ルートを有効化",
+ "baseUrl": "Base URL",
+ "apiKey": "API キー",
+ "apiKeyPlaceholder": "空欄で現在のキーを保持",
+ "mode": "モード",
+ "modeFree": "無料公開データのみ",
+ "modePaid": "QVeris 有料を有効化",
+ "budget": "セッションごとの予算 Credits",
+ "budgetHint": "このセッション予算に達すると有料実行を停止します。",
+ "balance": "残り Credits",
+ "recentUsage": "最近の使用量",
+ "noUsage": "最近の使用量はありません",
+ "signupCta": "登録を開く",
+ "signupHint": "QVeris アカウント作成時にこの招待コードを使用してください。",
+ "inviteCode": "招待コード",
+ "save": "QVeris 設定を保存",
+ "saved": "QVeris 設定を保存しました",
+ "testFailed": "QVeris リクエストに失敗しました",
+ "notConfigured": "未設定"
+ },
"agent": {
"connectionLostReconnect": "接続が切断されました。再接続しています…",
"connectionRestored": "接続が復元されました",
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index e4f9f3b14..04052872f 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -320,6 +320,29 @@
"sessionRuntime": "세션 런타임",
"flagsReadFrom": "플래그는 {{env_path}}의 {{env1}}, {{env2}}, {{env3}}에서 읽습니다."
},
+ "qveris": {
+ "title": "QVeris 도구 마켓플레이스",
+ "subtitle": "무료 공개 데이터 경로를 기본으로 두고, 필요할 때만 QVeris 유료 실행을 켭니다.",
+ "enabled": "QVeris 유료 경로 활성화",
+ "baseUrl": "Base URL",
+ "apiKey": "API 키",
+ "apiKeyPlaceholder": "비우면 현재 키 유지",
+ "mode": "모드",
+ "modeFree": "무료 공개 데이터만 사용",
+ "modePaid": "QVeris 유료 활성화",
+ "budget": "세션당 예산 Credits",
+ "budgetHint": "이 세션 예산에 도달하면 유료 실행을 중지합니다.",
+ "balance": "남은 Credits",
+ "recentUsage": "최근 사용량",
+ "noUsage": "최근 사용량 없음",
+ "signupCta": "가입 열기",
+ "signupHint": "QVeris 계정을 만들 때 이 초대 코드를 사용하세요.",
+ "inviteCode": "초대 코드",
+ "save": "QVeris 설정 저장",
+ "saved": "QVeris 설정이 저장되었습니다",
+ "testFailed": "QVeris 요청 실패",
+ "notConfigured": "구성되지 않음"
+ },
"agent": {
"connectionLostReconnect": "연결이 끊겼습니다. 재연결 중…",
"connectionRestored": "연결이 복원되었습니다",
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index f81d94313..996c7b294 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -320,6 +320,29 @@
"sessionRuntime": "会话运行时",
"flagsReadFrom": "功能开关从 {{env_path}} 中的 {{env1}}、{{env2}} 和 {{env3}} 读取。"
},
+ "qveris": {
+ "title": "QVeris 工具市场",
+ "subtitle": "默认继续使用免费公开数据;需要专业付费数据时再启用 QVeris。",
+ "enabled": "启用 QVeris 付费通道",
+ "baseUrl": "基础 URL",
+ "apiKey": "API 密钥",
+ "apiKeyPlaceholder": "留空以保留当前密钥",
+ "mode": "模式",
+ "modeFree": "仅使用免费公开数据",
+ "modePaid": "启用 QVeris 付费",
+ "budget": "每会话预算 Credits",
+ "budgetHint": "达到本会话预算后将停止付费执行。",
+ "balance": "剩余 Credits",
+ "recentUsage": "近期用量",
+ "noUsage": "暂无近期用量",
+ "signupCta": "打开注册",
+ "signupHint": "创建 QVeris 账户时使用此邀请码。",
+ "inviteCode": "邀请码",
+ "save": "保存 QVeris 设置",
+ "saved": "QVeris 设置已保存",
+ "testFailed": "QVeris 请求失败",
+ "notConfigured": "未配置"
+ },
"agent": {
"connectionLostReconnect": "连接已断开,正在重连…",
"connectionRestored": "连接已恢复",
diff --git a/frontend/src/pages/Settings.tsx b/frontend/src/pages/Settings.tsx
index 631c41b76..d4582715d 100644
--- a/frontend/src/pages/Settings.tsx
+++ b/frontend/src/pages/Settings.tsx
@@ -3,6 +3,7 @@ import { useEffect, useMemo, useState, type FormEvent } from "react";
import { Database, KeyRound, Loader2, MessageSquareMore, Play, RefreshCw, RotateCcw, Save, Server, SlidersHorizontal, Square } from "lucide-react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
+import { QVerisSettings } from "@/components/settings/QVerisSettings"; // QVERIS-INTEGRATION
import { api, isAuthRequiredError, type ChannelRuntimeStatus, type DataSourceSettings, type LLMProviderOption, type LLMSettings } from "@/lib/api";
import { getApiAuthKey, setApiAuthKey } from "@/lib/apiAuth";
@@ -245,6 +246,8 @@ export function Settings() {
<p className="max-w-3xl text-sm text-muted-foreground">{"Configure model credentials and market data source tokens for this local project."}</p>
</div>
{localApiAccessSection}
+ {/* QVERIS-INTEGRATION */}
+ <QVerisSettings />
<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">
@@ -398,6 +401,9 @@ export function Settings() {
{localApiAccessSection}
+ {/* QVERIS-INTEGRATION */}
+ <QVerisSettings />
+
{channelsSection}
<div className="space-y-2">
diff --git a/frontend/src/pages/__tests__/SettingsQVeris.test.tsx b/frontend/src/pages/__tests__/SettingsQVeris.test.tsx
new file mode 100644
index 000000000..dde06c195
--- /dev/null
+++ b/frontend/src/pages/__tests__/SettingsQVeris.test.tsx
@@ -0,0 +1,229 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import i18n from "@/i18n";
+import { QVerisSettings } from "@/components/settings/QVerisSettings";
+import { Settings } from "../Settings";
+
+const apiMock = vi.hoisted(() => ({
+ getLLMSettings: vi.fn(),
+ getDataSourceSettings: vi.fn(),
+ getChannelStatus: vi.fn(),
+ startChannels: vi.fn(),
+ stopChannels: vi.fn(),
+ updateLLMSettings: vi.fn(),
+ updateDataSourceSettings: vi.fn(),
+}));
+
+vi.mock("@/lib/api", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");
+ return {
+ ...actual,
+ api: apiMock,
+ isAuthRequiredError: vi.fn(() => false),
+ };
+});
+
+vi.mock("@/lib/apiAuth", () => ({
+ authHeaders: vi.fn(() => ({ Authorization: "Bearer local-test-key" })),
+ getApiAuthKey: vi.fn(() => "local-test-key"),
+ setApiAuthKey: vi.fn(),
+}));
+
+vi.mock("sonner", () => ({
+ toast: {
+ success: vi.fn(),
+ error: vi.fn(),
+ },
+}));
+
+function llmSettings() {
+ return {
+ provider: "openrouter",
+ model_name: "deepseek/deepseek-v3.2",
+ base_url: "https://openrouter.ai/api/v1",
+ api_key_env: "OPENROUTER_API_KEY",
+ api_key_configured: false,
+ api_key_required: true,
+ temperature: 0.1,
+ timeout_seconds: 120,
+ max_retries: 2,
+ reasoning_effort: "",
+ sse_timeout_seconds: 300,
+ env_path: "agent/.env",
+ providers: [
+ {
+ name: "openrouter",
+ label: "OpenRouter",
+ api_key_env: "OPENROUTER_API_KEY",
+ base_url_env: "OPENROUTER_BASE_URL",
+ default_model: "deepseek/deepseek-v3.2",
+ default_base_url: "https://openrouter.ai/api/v1",
+ api_key_required: true,
+ auth_type: "api_key",
+ },
+ ],
+ };
+}
+
+function dataSourceSettings() {
+ return {
+ tushare_token_configured: false,
+ baostock_supported: true,
+ baostock_installed: true,
+ baostock_message: "BaoStock available",
+ env_path: "agent/.env",
+ };
+}
+
+function channelStatus() {
+ return {
+ running: false,
+ inbound_queue: 0,
+ outbound_queue: 0,
+ session_count: 0,
+ channels: {},
+ };
+}
+
+function qverisConfig(overrides = {}) {
+ return {
+ enabled: true,
+ base_url: "https://qveris.ai/api/v1",
+ api_key_masked: "sk-...8TI",
+ mode: "paid",
+ budget_credits_per_session: 50,
+ configured: true,
+ signup_url: "https://qveris.ai/?ref=from-api",
+ invite_code: "INVITE-FROM-API",
+ ...overrides,
+ };
+}
+
+function qverisStatus(overrides = {}) {
+ return {
+ enabled: true,
+ ok: true,
+ error: null,
+ remaining_credits: 123.45,
+ recent: [
+ {
+ ts: "2026-07-07T01:02:03Z",
+ tool_id: "sec_filings",
+ cost: 1.25,
+ charge_outcome: "charged",
+ },
+ ],
+ signup_url: "https://qveris.ai/?ref=status",
+ invite_code: "INVITE-FROM-STATUS",
+ ...overrides,
+ };
+}
+
+function jsonResponse(body: unknown, status = 200) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+}
+
+function mockQVerisFetch(config = qverisConfig(), status = qverisStatus()) {
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const path = String(input);
+ if (path === "/qveris/config" && init?.method === "PUT") {
+ const payload = JSON.parse(String(init.body || "{}"));
+ return jsonResponse({ ...config, ...payload, api_key_masked: payload.api_key ? "sk-...NEW" : config.api_key_masked });
+ }
+ if (path === "/qveris/config") return jsonResponse(config);
+ if (path === "/qveris/status") return jsonResponse(status);
+ return jsonResponse({ detail: `Unexpected path: ${path}` }, 404);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+describe("Settings QVeris card", () => {
+ beforeEach(async () => {
+ await i18n.changeLanguage("en");
+ window.localStorage.clear();
+ apiMock.getLLMSettings.mockResolvedValue(llmSettings());
+ apiMock.getDataSourceSettings.mockResolvedValue(dataSourceSettings());
+ apiMock.getChannelStatus.mockResolvedValue(channelStatus());
+ apiMock.startChannels.mockResolvedValue(channelStatus());
+ apiMock.stopChannels.mockResolvedValue(channelStatus());
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ });
+
+ it("renders inside Settings and shows loaded config, balance, and recent usage", async () => {
+ mockQVerisFetch();
+
+ render(<Settings />);
+
+ expect(await screen.findByText("QVeris Tool Marketplace")).toBeInTheDocument();
+ expect(await screen.findByDisplayValue("https://qveris.ai/api/v1")).toBeInTheDocument();
+ expect(screen.getByPlaceholderText("sk-...8TI")).toBeInTheDocument();
+ expect(screen.getByText("123.45")).toBeInTheDocument();
+ expect(screen.getByText("sec_filings")).toBeInTheDocument();
+ });
+
+ it("sends the configured PUT payload when saving with a new API key", async () => {
+ const fetchMock = mockQVerisFetch(qverisConfig({ enabled: false, mode: "free" }), qverisStatus({ recent: [] }));
+ render(<QVerisSettings />);
+
+ await screen.findByDisplayValue("https://qveris.ai/api/v1");
+ fireEvent.click(screen.getByLabelText("Enable paid QVeris route"));
+ fireEvent.change(screen.getByLabelText("Base URL"), { target: { value: "https://example.test/qveris" } });
+ fireEvent.change(screen.getByPlaceholderText("sk-...8TI"), { target: { value: "sk-new-key" } });
+ fireEvent.change(screen.getByLabelText("Mode"), { target: { value: "paid" } });
+ fireEvent.change(screen.getByDisplayValue("50"), { target: { value: "80" } });
+ fireEvent.click(screen.getByRole("button", { name: "Save QVeris settings" }));
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledWith("/qveris/config", expect.objectContaining({ method: "PUT" })));
+ const putCall = fetchMock.mock.calls.find(([path, init]) => String(path) === "/qveris/config" && init?.method === "PUT");
+ expect(JSON.parse(String(putCall?.[1]?.body))).toEqual({
+ enabled: true,
+ base_url: "https://example.test/qveris",
+ mode: "paid",
+ budget_credits_per_session: 80,
+ api_key: "sk-new-key",
+ });
+ });
+
+ it("does not overwrite the saved API key when the key field is left blank", async () => {
+ const fetchMock = mockQVerisFetch();
+ render(<QVerisSettings />);
+
+ await screen.findByDisplayValue("https://qveris.ai/api/v1");
+ fireEvent.click(screen.getByRole("button", { name: "Save QVeris settings" }));
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledWith("/qveris/config", expect.objectContaining({ method: "PUT" })));
+ const putCall = fetchMock.mock.calls.find(([path, init]) => String(path) === "/qveris/config" && init?.method === "PUT");
+ expect(JSON.parse(String(putCall?.[1]?.body))).not.toHaveProperty("api_key");
+ });
+
+ it("uses the signup href from the config response and renders the empty usage state", async () => {
+ mockQVerisFetch(qverisConfig({ signup_url: "https://qveris.ai/?ref=config-response" }), qverisStatus({ recent: [] }));
+ render(<QVerisSettings />);
+
+ const signup = await screen.findByRole("link", { name: "Open signup" });
+ expect(signup).toHaveAttribute("href", "https://qveris.ai/?ref=config-response");
+ expect(screen.getByText("INVITE-FROM-API")).toBeInTheDocument();
+ expect(screen.getByText("No recent usage")).toBeInTheDocument();
+ });
+
+ it("renders QVeris copy in English and Chinese through i18n", async () => {
+ mockQVerisFetch(undefined, qverisStatus({ recent: [] }));
+ const { unmount } = render(<QVerisSettings />);
+ expect(await screen.findByText("QVeris Tool Marketplace")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Save QVeris settings" })).toBeInTheDocument();
+ unmount();
+
+ await i18n.changeLanguage("zh-CN");
+ mockQVerisFetch(undefined, qverisStatus({ recent: [] }));
+ render(<QVerisSettings />);
+ expect(await screen.findByText("QVeris 工具市场")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "保存 QVeris 设置" })).toBeInTheDocument();
+ });
+});
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index 2a8a3a89a..db5f746de 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -6,6 +6,7 @@ const PROXY_PATHS = [
"/sessions",
"/swarm/presets",
"/swarm/runs",
+ "/qveris",
"/settings/llm",
"/settings/data-sources",
"/channels",