Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(tools): fail closed on malformed tool arguments (#913, #911)

santhreal7c0f35fbdb31
diff --git a/agent/src/tools/alpha_zoo_tool.py b/agent/src/tools/alpha_zoo_tool.py
index 3a4242c29..d332e3a37 100644
--- a/agent/src/tools/alpha_zoo_tool.py
+++ b/agent/src/tools/alpha_zoo_tool.py
@@ -117,7 +117,7 @@ def run_alpha_zoo(**kwargs: Any) -> dict[str, Any]:
limit_raw = kwargs.get("limit", _DEFAULT_LIMIT)
try:
limit = int(limit_raw)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return {"status": "error", "error": f"limit must be int, got {limit_raw!r}"}
if limit <= 0:
return {"status": "error", "error": "limit must be > 0"}
diff --git a/agent/src/tools/block_trades_tool.py b/agent/src/tools/block_trades_tool.py
index 6150f3b99..f73acf99d 100644
--- a/agent/src/tools/block_trades_tool.py
+++ b/agent/src/tools/block_trades_tool.py
@@ -79,7 +79,7 @@ def _clamp_days(days: Any) -> int:
"""
try:
value = int(days)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return _DEFAULT_DAYS
if value < 1:
return 1
diff --git a/agent/src/tools/fred_macro_tool.py b/agent/src/tools/fred_macro_tool.py
index b723f5da4..a535bf740 100644
--- a/agent/src/tools/fred_macro_tool.py
+++ b/agent/src/tools/fred_macro_tool.py
@@ -20,7 +20,6 @@ from __future__ import annotations
import json
import logging
-import os
from typing import Any
from backtest.loaders._http import resolve_min_interval, throttled_get_json
@@ -229,7 +228,7 @@ def _clamp_limit(value: Any) -> int:
"""Coerce a requested observation count into the supported range."""
try:
n = int(value)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return _DEFAULT_LIMIT
return max(1, min(n, _MAX_LIMIT))
diff --git a/agent/src/tools/iwencai_tool.py b/agent/src/tools/iwencai_tool.py
index 7be782139..43bf62c80 100644
--- a/agent/src/tools/iwencai_tool.py
+++ b/agent/src/tools/iwencai_tool.py
@@ -18,7 +18,6 @@ from __future__ import annotations
import json
import logging
-import os
from typing import Any
from backtest.loaders._http import resolve_min_interval, throttled_get_json
@@ -62,7 +61,7 @@ def _coerce_limit(value: Any) -> int:
"""
try:
limit = int(value)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return _DEFAULT_LIMIT
if limit < 1:
return _DEFAULT_LIMIT
diff --git a/agent/src/tools/lockup_expiry_tool.py b/agent/src/tools/lockup_expiry_tool.py
index dacc5bca8..0f2a96d74 100644
--- a/agent/src/tools/lockup_expiry_tool.py
+++ b/agent/src/tools/lockup_expiry_tool.py
@@ -65,7 +65,7 @@ def _clamp_horizon(horizon_days: Any) -> int:
"""
try:
value = int(horizon_days)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return _DEFAULT_HORIZON_DAYS
if value < 1:
return 1
diff --git a/agent/src/tools/margin_trading_tool.py b/agent/src/tools/margin_trading_tool.py
index 02c2ad534..464fa8dc2 100644
--- a/agent/src/tools/margin_trading_tool.py
+++ b/agent/src/tools/margin_trading_tool.py
@@ -84,7 +84,7 @@ def _clamp_days(days: Any) -> int:
"""
try:
value = int(days)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return _DEFAULT_DAYS
if value <= 0:
return _DEFAULT_DAYS
diff --git a/agent/src/tools/northbound_tool.py b/agent/src/tools/northbound_tool.py
index 50ddf681c..1b93f7996 100644
--- a/agent/src/tools/northbound_tool.py
+++ b/agent/src/tools/northbound_tool.py
@@ -164,7 +164,7 @@ def _clamp_lookback(value: Any) -> int:
"""
try:
days = int(value)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return _DEFAULT_LOOKBACK_DAYS
if days < 1:
return 1
diff --git a/agent/src/tools/options_chain_tool.py b/agent/src/tools/options_chain_tool.py
index 031f61ade..5c3c273c9 100644
--- a/agent/src/tools/options_chain_tool.py
+++ b/agent/src/tools/options_chain_tool.py
@@ -106,7 +106,7 @@ def _coerce_expiration(value: Any) -> Optional[int]:
return None
try:
return int(value)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return None
diff --git a/agent/src/tools/options_pricing_tool.py b/agent/src/tools/options_pricing_tool.py
index 7d1075b62..0dbc128b9 100644
--- a/agent/src/tools/options_pricing_tool.py
+++ b/agent/src/tools/options_pricing_tool.py
@@ -130,14 +130,34 @@ class OptionsPricingTool(BaseTool):
Optional risk_free_rate.
Returns:
- JSON string containing price, delta, gamma, theta, vega.
+ JSON string containing price, delta, gamma, theta, vega, or an error
+ envelope when an argument is missing or cannot be read as a number.
+ ``risk_free_rate`` is optional and defaults to its schema value 0.05,
+ so an explicit JSON ``null`` is treated as omission.
"""
- spot = float(kwargs["spot"])
- strike = float(kwargs["strike"])
- expiry_days = float(kwargs["expiry_days"])
- r = float(kwargs.get("risk_free_rate", 0.05))
- sigma = float(kwargs["volatility"])
- option_type = kwargs["option_type"]
+ try:
+ if "spot" not in kwargs or kwargs["spot"] is None:
+ raise ValueError("spot is required")
+ if "strike" not in kwargs or kwargs["strike"] is None:
+ raise ValueError("strike is required")
+ if "expiry_days" not in kwargs or kwargs["expiry_days"] is None:
+ raise ValueError("expiry_days is required")
+ if "volatility" not in kwargs or kwargs["volatility"] is None:
+ raise ValueError("volatility is required")
+ spot = float(kwargs["spot"])
+ strike = float(kwargs["strike"])
+ expiry_days = float(kwargs["expiry_days"])
+ r_val = kwargs.get("risk_free_rate")
+ r = float(r_val if r_val is not None and r_val != "" else 0.05)
+ sigma = float(kwargs["volatility"])
+ option_type = str(kwargs.get("option_type") or "")
+ except (TypeError, ValueError, KeyError, OverflowError) as exc:
+ # OverflowError: a JSON integer larger than a float (e.g. 10**10000)
+ # raises it from float(), and it must not escape this envelope.
+ return json.dumps(
+ {"status": "error", "tool": "options_pricing", "error": f"invalid or missing input argument: {exc}"},
+ ensure_ascii=False,
+ )
err = _validate_inputs(spot, strike, expiry_days, sigma, r, option_type)
if err is not None:
diff --git a/agent/src/tools/qveris_tool.py b/agent/src/tools/qveris_tool.py
index d9f66115f..b13f4e907 100644
--- a/agent/src/tools/qveris_tool.py
+++ b/agent/src/tools/qveris_tool.py
@@ -9,6 +9,7 @@ import re
import tempfile
import threading
import time
+from collections.abc import Mapping
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
@@ -327,6 +328,33 @@ class QVerisClient:
return self._request("GET", "/auth/credits/ledger", params=params)
+def _positive_int(value: Any, field: str, default: int) -> int:
+ """Resolve an optional positive-integer option from tool kwargs.
+
+ Args:
+ value: Raw argument value; ``None`` and ``""`` mean "not supplied".
+ field: Argument name, used in the error message.
+ default: Value to use when the argument was not supplied.
+
+ Returns:
+ The requested integer, or ``default`` when the argument was absent.
+
+ Raises:
+ ValueError: If the value is present but not a finite positive integer.
+ QVeris calls are billable, so an explicitly malformed option is
+ rejected instead of being replaced by a default.
+ """
+ if value is None or value == "":
+ return default
+ try:
+ number = float(value)
+ except (TypeError, ValueError, OverflowError):
+ raise ValueError(f"{field} must be a positive integer, got {value!r}") from None
+ if not math.isfinite(number) or number != int(number) or int(number) < 1:
+ raise ValueError(f"{field} must be a positive integer, got {value!r}")
+ return int(number)
+
+
class _QVerisBaseTool(BaseTool):
"""Shared availability and client helpers for QVeris tools."""
@@ -363,11 +391,25 @@ class QVerisSearchTool(_QVerisBaseTool):
}
def execute(self, **kwargs: Any) -> str:
+ """Search QVeris capabilities after validating the request schema.
+
+ A missing ``query`` is a schema-invalid request, not an empty search:
+ it is rejected rather than sent to the marketplace as ``""``.
+ """
if not is_qveris_configured():
return _json_response({"ok": False, "error": "QVeris is not configured"})
+ query = kwargs.get("query")
+ if not isinstance(query, str) or not query.strip():
+ return _json_response(
+ {"ok": False, "error": "query is required (non-empty string)"}
+ )
+ try:
+ limit = _positive_int(kwargs.get("limit"), "limit", 20)
+ except ValueError as exc:
+ return _json_response({"ok": False, "error": str(exc)})
payload = self._client().search(
- str(kwargs["query"]),
- limit=int(kwargs.get("limit", 20)),
+ query.strip(),
+ limit=limit,
session_id=kwargs.get("session_id"),
)
return _json_response({"ok": True, **payload})
@@ -449,11 +491,38 @@ class QVerisExecuteTool(_QVerisBaseTool):
return _quote_from_tool(first)
def execute(self, **kwargs: Any) -> str:
+ """Execute a QVeris capability behind the per-session credit budget.
+
+ The request schema is validated FIRST — before the quote lookup, before
+ the budget reservation, and before ``client.execute`` — because this
+ tool is not read-only and every call spends real credits. A missing
+ ``tool_id``/``parameters`` is a schema-invalid request, so it must never
+ be normalised into an empty-parameter call to the marketplace.
+ """
cfg = load_qveris_config()
if not is_qveris_configured(cfg):
return _json_response({"ok": False, "error": "QVeris is not configured"})
+ raw_tool_id = kwargs.get("tool_id")
+ if not isinstance(raw_tool_id, str) or not raw_tool_id.strip():
+ return _json_response(
+ {"ok": False, "error": "tool_id is required (non-empty string)"}
+ )
+ if "parameters" not in kwargs or not isinstance(kwargs["parameters"], Mapping):
+ return _json_response(
+ {
+ "ok": False,
+ "error": "parameters is required and must be an object; refusing a billable call with an unvalidated request",
+ }
+ )
+ try:
+ max_response_size = _positive_int(
+ kwargs.get("max_response_size"), "max_response_size", 20480
+ )
+ except ValueError as exc:
+ return _json_response({"ok": False, "error": str(exc)})
+ parameters = dict(kwargs["parameters"])
client = self._client()
- tool_id = str(kwargs["tool_id"])
+ tool_id = raw_tool_id.strip()
quote = self._quote(client, tool_id, kwargs)
session_id = str(kwargs.get("session_id") or "default")
budget = max(float(cfg.budget_credits_per_session), 0.0)
@@ -483,11 +552,11 @@ class QVerisExecuteTool(_QVerisBaseTool):
try:
payload = client.execute(
tool_id,
- parameters=dict(kwargs["parameters"]),
+ parameters=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)),
+ max_response_size=max_response_size,
)
except Exception:
with _SESSION_BUDGET_LOCK:
diff --git a/agent/src/tools/report_audit_tool.py b/agent/src/tools/report_audit_tool.py
index 8b3c7673e..93c654e44 100644
--- a/agent/src/tools/report_audit_tool.py
+++ b/agent/src/tools/report_audit_tool.py
@@ -244,6 +244,24 @@ def _pct_diff_for_json(diff: float) -> float | None:
return round(diff * 100, 2)
+def _finite_number(value: Any) -> float | None:
+ """Coerce a verification value to a finite float, or None when unusable.
+
+ Args:
+ value: Raw ``reported_value``/``fetched_value`` from a result item.
+
+ Returns:
+ The value as a finite float, or ``None`` when it is missing, not
+ numeric, or non-finite (NaN/Infinity) — i.e. cannot be verified.
+ A genuine reported ``0`` is a valid number and returns ``0.0``.
+ """
+ try:
+ number = float(value)
+ except (TypeError, ValueError, OverflowError):
+ return None
+ return number if math.isfinite(number) else None
+
+
def render_verdict(results: list[dict[str, Any]], report_name: str = "") -> dict[str, Any]:
"""Render a PASS/FAIL verdict from per-point verification results.
@@ -252,6 +270,10 @@ def render_verdict(results: list[dict[str, Any]], report_name: str = "") -> dict
both sources must pass for a point to pass, both fail to fail, otherwise the
point warns (treated as a caliber mismatch, not a failure).
+ A point whose ``reported_value`` is missing, ``None``, or non-finite is
+ unverifiable, so it fails with an explicit ``reason`` instead of being
+ treated as a reported zero. A genuine reported ``0`` stays valid.
+
Args:
results: List of verification objects — ``{id, label, reported_value,
unit, fetched_value, fetched_source, (optional) fetched_value2,
@@ -271,10 +293,33 @@ def render_verdict(results: list[dict[str, Any]], report_name: str = "") -> dict
if fetched is None:
continue # not verified — skip, do not count
total += 1
- reported = float(item.get("reported_value", 0))
label = item.get("label", "?")
unit = item.get("unit", "")
source = item.get("fetched_source", "?")
+
+ # A missing/non-numeric reported value is unverifiable evidence, NOT a
+ # reported zero: fabricating 0.0 here would let `None` vs fetched 0 pass
+ # the tolerance check and falsely certify the report.
+ raw_reported = item.get("reported_value")
+ reported = _finite_number(raw_reported)
+ if reported is None:
+ fail_items.append({
+ "id": item.get("id"), "label": label,
+ "reported": None, "unit": unit,
+ "fetched": _finite_number(fetched), "source": source,
+ "fetched2": _finite_number(item.get("fetched_value2")),
+ "source2": item.get("fetched_source2", ""),
+ "diff1_pct": None, "diff2_pct": None,
+ "reason": (
+ "reported value missing — cannot verify"
+ if raw_reported is None
+ else f"reported value is not a finite number ({raw_reported!r}) — cannot verify"
+ ),
+ "raw_text": item.get("raw_text", ""),
+ "line_number": item.get("line_number", 0),
+ })
+ continue
+
fetched = float(fetched)
diff1 = _pct_diff(reported, fetched)
@@ -404,9 +449,16 @@ class ReportAuditTool(BaseTool):
report_text = kwargs.get("report_text")
if not isinstance(report_text, str) or not report_text.strip():
return _err("report_text (non-empty markdown) is required for extract")
- ratio = float(kwargs.get("ratio") or 0.15)
- seed = kwargs.get("seed")
- seed = int(seed) if seed is not None else None
+ raw_ratio = kwargs.get("ratio")
+ try:
+ ratio = float(raw_ratio) if raw_ratio is not None and raw_ratio != "" else 0.15
+ except (TypeError, ValueError, OverflowError):
+ return _err(f"invalid ratio: {raw_ratio!r}")
+ raw_seed = kwargs.get("seed")
+ try:
+ seed = int(raw_seed) if raw_seed is not None and raw_seed != "" else None
+ except (TypeError, ValueError, OverflowError):
+ return _err(f"invalid seed: {raw_seed!r}")
points = extract_data_points(report_text)
sampled = sample_points(points, ratio=ratio, seed=seed)
result: dict[str, Any] = {
diff --git a/agent/src/tools/research_reports_tool.py b/agent/src/tools/research_reports_tool.py
index d893f88a8..612d7f3b6 100644
--- a/agent/src/tools/research_reports_tool.py
+++ b/agent/src/tools/research_reports_tool.py
@@ -161,7 +161,7 @@ def _clamp_limit(value: Any) -> int:
"""Coerce a requested report count into the supported ``1.._MAX_LIMIT`` range."""
try:
n = int(value)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return _DEFAULT_LIMIT
return max(1, min(n, _MAX_LIMIT))
diff --git a/agent/src/tools/sec_filings_tool.py b/agent/src/tools/sec_filings_tool.py
index 3d510649f..2782029ce 100644
--- a/agent/src/tools/sec_filings_tool.py
+++ b/agent/src/tools/sec_filings_tool.py
@@ -152,7 +152,7 @@ def _clamp_limit(value: Any) -> int:
"""Coerce a requested count into the supported ``1.._MAX_LIMIT`` range."""
try:
n = int(value)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return _DEFAULT_LIMIT
return max(1, min(n, _MAX_LIMIT))
diff --git a/agent/src/tools/session_search_tool.py b/agent/src/tools/session_search_tool.py
index 61bf3b474..c1cbec7d6 100644
--- a/agent/src/tools/session_search_tool.py
+++ b/agent/src/tools/session_search_tool.py
@@ -41,13 +41,24 @@ class SessionSearchTool(BaseTool):
**kwargs: Must include query; optionally max_results.
Returns:
- JSON with search results or error.
+ JSON with search results or error. An absent ``max_results`` falls
+ back to 3; an explicitly malformed one is an error, not a default.
"""
query = kwargs.get("query", "")
if not query:
return json.dumps({"status": "error", "error": "query required"})
- max_results = min(int(kwargs.get("max_results", 3)), 10)
+ raw_max = kwargs.get("max_results")
+ if raw_max is None or raw_max == "":
+ max_results = 3
+ else:
+ try:
+ max_results = min(max(1, int(raw_max)), 10)
+ except (TypeError, ValueError, OverflowError):
+ return json.dumps(
+ {"status": "error", "error": f"max_results must be an integer, got {raw_max!r}"},
+ ensure_ascii=False,
+ )
try:
from src.session.search import get_shared_index
diff --git a/agent/src/tools/shadow_account_tool.py b/agent/src/tools/shadow_account_tool.py
index 6833105bb..921d6e8db 100644
--- a/agent/src/tools/shadow_account_tool.py
+++ b/agent/src/tools/shadow_account_tool.py
@@ -38,6 +38,30 @@ def _ok(**payload: Any) -> str:
return json.dumps({"status": "ok", **payload}, ensure_ascii=False, default=str)
+def _int_arg(value: Any, field: str, default: int) -> int:
+ """Resolve an optional integer argument from tool kwargs.
+
+ Args:
+ value: Raw argument value; ``None`` and ``""`` mean "not supplied".
+ field: Argument name, used in the error message.
+ default: Value to use when the argument was not supplied.
+
+ Returns:
+ The requested integer, or ``default`` when the argument was absent.
+
+ Raises:
+ ValueError: If the value is present but not an integer. Only an absent
+ value may fall back to the default — silently replacing a malformed
+ explicit value would answer a different question than was asked.
+ """
+ if value is None or value == "":
+ return default
+ try:
+ return int(value)
+ except (TypeError, ValueError, OverflowError):
+ raise ValueError(f"{field} must be an integer, got {value!r}") from None
+
+
def _validate_optional_journal_path(raw: Any) -> str | None:
"""Validate a journal_path kwarg that may be missing/empty.
@@ -93,11 +117,16 @@ class ExtractShadowStrategyTool(BaseTool):
journal_path = str(safe_user_path(journal_path))
except ValueError as exc:
return _err(str(exc))
+ try:
+ min_support = _int_arg(kwargs.get("min_support"), "min_support", 3)
+ max_rules = _int_arg(kwargs.get("max_rules"), "max_rules", 5)
+ except ValueError as exc:
+ return _err(str(exc))
try:
profile = extract_shadow_profile(
journal_path,
- min_support=int(kwargs.get("min_support", 3)),
- max_rules=int(kwargs.get("max_rules", 5)),
+ min_support=min_support,
+ max_rules=max_rules,
)
except (FileNotFoundError, ValueError) as exc:
return _err(str(exc))
@@ -318,13 +347,18 @@ class ScanShadowSignalsTool(BaseTool):
shadow_id = kwargs.get("shadow_id")
if not shadow_id:
return _err("shadow_id is required")
+ # Arguments are validated before the profile load so a schema error is
+ # reported as such instead of being masked by a missing-profile error.
+ try:
+ per_market = _int_arg(kwargs.get("per_market"), "per_market", 3)
+ except ValueError as exc:
+ return _err(str(exc))
try:
profile = load_profile(shadow_id)
except FileNotFoundError as exc:
return _err(str(exc))
target = kwargs.get("date") or None
- per_market = int(kwargs.get("per_market", 3))
signals = scan_today_signals(profile, target_date=target, per_market=per_market)
return _ok(
shadow_id=profile.shadow_id,
diff --git a/agent/src/tools/shareholder_count_tool.py b/agent/src/tools/shareholder_count_tool.py
index 20a218e9c..9dfb78466 100644
--- a/agent/src/tools/shareholder_count_tool.py
+++ b/agent/src/tools/shareholder_count_tool.py
@@ -134,7 +134,7 @@ def _clamp_periods(value: Any) -> int:
"""Coerce a requested period count into the supported ``1.._MAX_PERIODS`` range."""
try:
n = int(value)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return _MAX_PERIODS
return max(1, min(n, _MAX_PERIODS))
diff --git a/agent/src/tools/stock_news_tool.py b/agent/src/tools/stock_news_tool.py
index 0ea92338e..3cff06686 100644
--- a/agent/src/tools/stock_news_tool.py
+++ b/agent/src/tools/stock_news_tool.py
@@ -66,7 +66,7 @@ def _clamp_limit(raw: Any) -> int:
"""
try:
value = int(raw)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return _DEFAULT_LIMIT
if value < 1:
return 1
diff --git a/agent/src/tools/symbol_search_tool.py b/agent/src/tools/symbol_search_tool.py
index ab76cb288..ea80d725c 100644
--- a/agent/src/tools/symbol_search_tool.py
+++ b/agent/src/tools/symbol_search_tool.py
@@ -159,7 +159,7 @@ def _clamp_limit(value: Any) -> int:
"""Coerce a requested count into the supported ``1.._MAX_LIMIT`` range."""
try:
n = int(value)
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
return _DEFAULT_LIMIT
return max(1, min(n, _MAX_LIMIT))
diff --git a/agent/src/tools/trading_connector_tool.py b/agent/src/tools/trading_connector_tool.py
index befd42c8a..af637a392 100644
--- a/agent/src/tools/trading_connector_tool.py
+++ b/agent/src/tools/trading_connector_tool.py
@@ -7,6 +7,7 @@ selected profile from ``~/.vibe-trading/trading-connections.json``.
from __future__ import annotations
import json
+import math
from typing import Any
from src.agent.tools import BaseTool
@@ -39,16 +40,92 @@ def _connection(value: Any) -> str | None:
return text or None
-def _int_or_none(value: Any) -> int | None:
- if value in (None, ""):
+class InvalidTradingArgument(ValueError):
+ """A numeric trading argument was supplied but is malformed or non-finite."""
+
+
+def _brief(value: Any) -> str:
+ """Render a rejected argument for an error message without ever raising.
+
+ ``repr()`` is not total: an int with more than 4300 digits raises
+ ``ValueError`` under Python's int→str limit. An order tool must not fail to
+ describe why it refused, so fall back to the type name.
+
+ Args:
+ value: The rejected argument value.
+
+ Returns:
+ A short, printable description of the value.
+ """
+ try:
+ text = repr(value)
+ except Exception: # noqa: BLE001 — building an error message must never fail
+ return f"<unprintable {type(value).__name__}>"
+ return text if len(text) <= 80 else f"{text[:77]}..."
+
+
+def _finite_float(value: Any, field: str) -> float:
+ """Convert a supplied numeric argument to a finite float.
+
+ Args:
+ value: Raw argument value (already known to be present).
+ field: Argument name, used in the error message.
+
+ Returns:
+ The value as a finite float.
+
+ Raises:
+ InvalidTradingArgument: If the value is not numeric, or is NaN/Infinity.
+ Trading tools are action-bearing, so a malformed size/price/port is
+ rejected outright rather than coerced to a default.
+ """
+ try:
+ number = float(value)
+ except (TypeError, ValueError, OverflowError):
+ raise InvalidTradingArgument(f"{field} must be a finite number, got {_brief(value)}") from None
+ if not math.isfinite(number):
+ raise InvalidTradingArgument(f"{field} must be a finite number, got {_brief(value)}")
+ return number
+
+
+def _int_or_none(value: Any, field: str = "value") -> int | None:
+ """Coerce an optional whole-number argument, rejecting malformed input.
+
+ Args:
+ value: Raw argument value; ``None`` and ``""`` mean "not supplied".
+ field: Argument name, used in the error message.
+
+ Returns:
+ The integer value, or ``None`` when the argument was not supplied.
+
+ Raises:
+ InvalidTradingArgument: If the value is present but not a finite whole
+ number.
+ """
+ if value is None or value == "":
return None
- return int(value)
+ number = _finite_float(value, field)
+ if number != int(number):
+ raise InvalidTradingArgument(f"{field} must be a whole number, got {_brief(value)}")
+ return int(number)
-def _num_or_none(value: Any) -> float | None:
- if value in (None, ""):
+def _num_or_none(value: Any, field: str = "value") -> float | None:
+ """Coerce an optional numeric argument, rejecting malformed input.
+
+ Args:
+ value: Raw argument value; ``None`` and ``""`` mean "not supplied".
+ field: Argument name, used in the error message.
+
+ Returns:
+ The float value, or ``None`` when the argument was not supplied.
+
+ Raises:
+ InvalidTradingArgument: If the value is present but not a finite number.
+ """
+ if value is None or value == "":
return None
- return float(value)
+ return _finite_float(value, field)
TRADING_COMMON_PARAMETERS = {
@@ -76,10 +153,23 @@ TRADING_COMMON_PARAMETERS = {
def _overrides(kwargs: dict[str, Any]) -> dict[str, Any]:
+ """Build the local-connector override dict, rejecting malformed numerics.
+
+ Args:
+ kwargs: Raw tool arguments.
+
+ Returns:
+ Override mapping with ``None`` for every unsupplied field.
+
+ Raises:
+ InvalidTradingArgument: If ``port`` or ``client_id`` is supplied but
+ malformed. Silently dropping them would connect to a different
+ terminal than the caller asked for.
+ """
return {
"host": _connection(kwargs.get("host")),
- "port": _int_or_none(kwargs.get("port")),
- "client_id": _int_or_none(kwargs.get("client_id")),
+ "port": _int_or_none(kwargs.get("port"), "port"),
+ "client_id": _int_or_none(kwargs.get("client_id"), "client_id"),
"account": _connection(kwargs.get("account")),
}
@@ -341,12 +431,24 @@ class TradingPlaceOrderTool(BaseTool):
is_readonly = False
def execute(self, **kwargs: Any) -> str:
- """Place an order via the connector profile."""
- # LLMs frequently populate BOTH sizing fields, leaving the unused one at
- # 0; a zero size is never valid, so treat it as absent to preserve the
- # "exactly one of quantity/notional" contract.
- quantity = _num_or_none(kwargs.get("quantity")) or None
- notional = _num_or_none(kwargs.get("notional")) or None
+ """Place an order via the connector profile.
+
+ Every numeric argument is converted first and a malformed or non-finite
+ value aborts with an error envelope BEFORE the service is called: an
+ order tool must fail closed rather than drop a bad size field and place
+ a different, plausible-looking order.
+ """
+ try:
+ # LLMs frequently populate BOTH sizing fields, leaving the unused
+ # one at 0; a zero size is never valid, so treat it as absent to
+ # preserve the "exactly one of quantity/notional" contract.
+ quantity = _num_or_none(kwargs.get("quantity"), "quantity") or None
+ notional = _num_or_none(kwargs.get("notional"), "notional") or None
+ limit_price = _num_or_none(kwargs.get("limit_price"), "limit_price")
+ overrides = _overrides(kwargs)
+ except InvalidTradingArgument as exc:
+ return _json_result({"status": "error", "error": str(exc)})
+
try:
return _json_result(
place_order(
@@ -356,9 +458,9 @@ class TradingPlaceOrderTool(BaseTool):
quantity=quantity,
notional=notional,
order_type=str(kwargs.get("order_type") or "market"),
- limit_price=_num_or_none(kwargs.get("limit_price")),
+ limit_price=limit_price,
time_in_force=str(kwargs.get("time_in_force") or "day"),
- **_overrides(kwargs),
+ **overrides,
)
)
except Exception as exc: # noqa: BLE001
@@ -383,14 +485,23 @@ class TradingCancelOrderTool(BaseTool):
is_readonly = False
def execute(self, **kwargs: Any) -> str:
- """Cancel an order via the connector profile."""
+ """Cancel an order via the connector profile.
+
+ Malformed connector overrides are rejected before the service call, so a
+ cancel never silently targets a different terminal than requested.
+ """
+ try:
+ overrides = _overrides(kwargs)
+ except InvalidTradingArgument as exc:
+ return _json_result({"status": "error", "error": str(exc)})
+
try:
return _json_result(
cancel_order(
str(kwargs["order_id"]),
_connection(kwargs.get("connection")),
symbol=_connection(kwargs.get("symbol")),
- **_overrides(kwargs),
+ **overrides,
)
)
except Exception as exc: # noqa: BLE001
diff --git a/agent/src/tools/web_search_tool.py b/agent/src/tools/web_search_tool.py
index 0f3057ed9..0726c01c4 100644
--- a/agent/src/tools/web_search_tool.py
+++ b/agent/src/tools/web_search_tool.py
@@ -13,12 +13,11 @@ from __future__ import annotations
import json
import logging
-import os
import time
from typing import Any
from src.agent.tools import BaseTool
-from src.config.accessor import _parse_bool, get_env_config
+from src.config.accessor import get_env_config
from src.security.scanner import with_security_warnings
logger = logging.getLogger(__name__)
@@ -178,10 +177,32 @@ class WebSearchTool(BaseTool):
Returns:
JSON envelope with status, query, the backend list used, and results
- (or an actionable error message on persistent failure).
+ (or an actionable error message on persistent failure). An absent
+ ``max_results`` falls back to 5; an explicitly malformed one is an
+ error, not a silent default.
"""
- query = kwargs["query"]
- max_results = min(int(kwargs.get("max_results", 5)), 10)
+ raw_query = kwargs.get("query")
+ if not isinstance(raw_query, str) or not raw_query.strip():
+ return json.dumps(
+ {"status": "error", "tool": "web_search", "error": "query is mandatory (non-empty string)"},
+ ensure_ascii=False,
+ )
+ query = raw_query.strip()
+ raw_max = kwargs.get("max_results")
+ if raw_max is None or raw_max == "":
+ max_results = 5
+ else:
+ try:
+ max_results = min(max(1, int(raw_max)), 10)
+ except (TypeError, ValueError, OverflowError):
+ return json.dumps(
+ {
+ "status": "error",
+ "tool": "web_search",
+ "error": f"max_results must be an integer, got {raw_max!r}",
+ },
+ ensure_ascii=False,
+ )
backends = (get_env_config().agent_tuning.vibe_trading_search_backends or _DEFAULT_BACKENDS).strip() or "auto"
# Fast path: Alibaba Cloud IQS if configured (official API, CN-direct,
diff --git a/agent/tests/test_options_pricing_degenerate.py b/agent/tests/test_options_pricing_degenerate.py
index 732f1362c..bebda4b2e 100644
--- a/agent/tests/test_options_pricing_degenerate.py
+++ b/agent/tests/test_options_pricing_degenerate.py
@@ -87,6 +87,40 @@ def test_non_finite_inputs_rejected_with_error(kw):
assert "finite" in out["error"]
[email protected]("field", ["spot", "strike", "expiry_days", "volatility"])
+def test_missing_required_argument_is_error_not_keyerror(field):
+ """A required argument that is absent or null yields an error envelope."""
+ kw = dict(spot=100, strike=100, expiry_days=30, volatility=0.25, option_type="call")
+ del kw[field]
+ assert _run(**kw)["status"] == "error"
+
+ kw[field] = None
+ out = _run(**kw)
+ assert out["status"] == "error"
+ assert out["error"]
+
+
[email protected]("field", ["spot", "strike", "expiry_days", "volatility", "risk_free_rate"])
+def test_unrepresentable_integer_is_error_not_overflowerror(field):
+ """float(10**10000) raises OverflowError; it must not escape the envelope."""
+ kw = dict(spot=100, strike=100, expiry_days=30, volatility=0.25, option_type="call")
+ kw[field] = 10 ** 10000
+ out = _run(**kw)
+ assert out["status"] == "error"
+ assert "invalid or missing input argument" in out["error"]
+
+
+def test_risk_free_rate_none_falls_back_to_schema_default():
+ """risk_free_rate is optional: explicit null means "use the 0.05 default"."""
+ explicit_null = _run(spot=100, strike=100, expiry_days=30, volatility=0.25,
+ risk_free_rate=None, option_type="call")
+ omitted = _run(spot=100, strike=100, expiry_days=30, volatility=0.25, option_type="call")
+
+ assert explicit_null["status"] == "ok"
+ assert explicit_null["inputs"]["risk_free_rate"] == 0.05
+ assert explicit_null["price"] == omitted["price"]
+
+
def test_output_is_strict_json_no_nan():
# json.loads already enforces strict JSON; assert it parses for all branches.
for kw in (
diff --git a/agent/tests/test_report_audit_tool.py b/agent/tests/test_report_audit_tool.py
index 017eaf764..debf2e590 100644
--- a/agent/tests/test_report_audit_tool.py
+++ b/agent/tests/test_report_audit_tool.py
@@ -161,6 +161,66 @@ def test_verdict_two_sources_split_is_warn_not_fail() -> None:
assert out["warn_count"] == 1 and out["fail_count"] == 0
+def test_verdict_missing_reported_value_fails_against_nonzero_fetched() -> None:
+ """A None reported value is unverifiable evidence, so the point fails."""
+ out = render_verdict([{"reported_value": None, "fetched_value": 100.0, "label": "rev"}])
+ assert out["verdict"] == "FAIL"
+ assert out["fail_count"] == 1
+ assert out["pass_count"] == 0
+
+
+def test_verdict_missing_reported_value_fails_against_zero_fetched() -> None:
+ """The false-PASS case: None vs fetched 0 must NOT be read as 0 == 0.
+
+ Mapping a missing reported value to 0.0 makes ``_pct_diff(0, 0) == 0``, which
+ would certify a report from evidence that was never verified.
+ """
+ out = render_verdict([{"reported_value": None, "fetched_value": 0.0, "label": "rev"}])
+ assert out["verdict"] == "FAIL"
+ assert out["fail_count"] == 1
+ assert out["pass_count"] == 0
+ assert "missing" in out["fail_items"][0]["reason"]
+ assert out["fail_items"][0]["reported"] is None
+
+
+def test_verdict_absent_reported_value_key_fails() -> None:
+ """An entirely absent reported_value key is the same unverifiable case."""
+ out = render_verdict([{"fetched_value": 0.0, "label": "rev"}])
+ assert out["verdict"] == "FAIL"
+ assert out["fail_count"] == 1
+
+
+def test_verdict_genuine_reported_zero_still_passes() -> None:
+ """A real reported 0 is valid data and must keep passing against fetched 0."""
+ out = render_verdict([{"reported_value": 0, "fetched_value": 0.0, "label": "rev"}])
+ assert out["verdict"] == "PASS"
+ assert out["pass_count"] == 1
+ assert out["fail_count"] == 0
+
+
[email protected]("bad", [float("nan"), float("inf"), "n/a", {}])
+def test_verdict_non_finite_reported_value_fails_with_reason(bad: Any) -> None:
+ """NaN/Infinity/junk are equally unverifiable and stay JSON-serializable."""
+ out = render_verdict([{"reported_value": bad, "fetched_value": 12.0, "label": "rev"}])
+ assert out["verdict"] == "FAIL"
+ assert "cannot verify" in out["fail_items"][0]["reason"]
+ json.dumps(out, allow_nan=False) # must not leak NaN/Infinity tokens
+
+
+def test_execute_verdict_missing_reported_value_is_reported_not_certified() -> None:
+ """End-to-end through the tool envelope: unverifiable evidence fails."""
+ raw = ReportAuditTool().execute(
+ command="verdict",
+ results=[{"id": 1, "label": "rev", "reported_value": None,
+ "fetched_value": 0.0, "fetched_source": "m"}],
+ )
+ assert "NaN" not in raw and "Infinity" not in raw
+ env = json.loads(raw)
+ assert env["status"] == "ok"
+ assert env["verdict"] == "FAIL"
+ assert env["fail_items"][0]["reason"]
+
+
def test_verdict_skips_points_without_fetched_value() -> None:
out = render_verdict([
{"id": 1, "label": "a", "reported_value": 100, "fetched_value": None},
diff --git a/agent/tests/test_tools_type_value_safety.py b/agent/tests/test_tools_type_value_safety.py
new file mode 100644
index 000000000..3faf9273e
--- /dev/null
+++ b/agent/tests/test_tools_type_value_safety.py
@@ -0,0 +1,499 @@
+"""Argument type/value safety at tool entrypoints (PR #913).
+
+Two rules are enforced here, and the distinction matters:
+
+* An **absent** optional argument may fall back to its documented default.
+* An **explicitly malformed** argument (non-numeric, NaN/Infinity, or an integer
+ too large for a float) must NOT be silently replaced by a default. Read-only
+ data tools clamp such values, but every entrypoint that spends money or places
+ an order fails closed with an error envelope *before* the side effect.
+
+Every test here is hermetic: no network call, no ``~/.vibe-trading`` access, and
+each one reaches the branch it claims to cover.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from types import ModuleType, SimpleNamespace
+from typing import Any
+
+import pytest
+
+from src.tools import qveris_tool as qt
+from src.tools import shadow_account_tool as sat
+from src.tools.alpha_zoo_tool import run_alpha_zoo
+from src.tools.block_trades_tool import _clamp_days as block_trades_clamp_days
+from src.tools.fred_macro_tool import _clamp_limit as fred_clamp_limit
+from src.tools.iwencai_tool import _coerce_limit as iwencai_coerce_limit
+from src.tools.lockup_expiry_tool import _clamp_horizon as lockup_clamp_horizon
+from src.tools.margin_trading_tool import _clamp_days as margin_clamp_days
+from src.tools.northbound_tool import _clamp_lookback
+from src.tools.options_chain_tool import _coerce_expiration
+from src.tools.options_pricing_tool import OptionsPricingTool
+from src.tools.report_audit_tool import ReportAuditTool
+from src.tools.research_reports_tool import _clamp_limit as research_clamp_limit
+from src.tools.sec_filings_tool import _clamp_limit as sec_clamp_limit
+from src.tools.session_search_tool import SessionSearchTool
+from src.tools.shareholder_count_tool import _clamp_periods as shareholder_clamp_periods
+from src.tools.stock_news_tool import _clamp_limit as stock_news_clamp_limit
+from src.tools.symbol_search_tool import _clamp_limit as symbol_clamp_limit
+from src.tools.trading_connector_tool import (
+ InvalidTradingArgument,
+ TradingPlaceOrderTool,
+ _int_or_none,
+ _num_or_none,
+)
+from src.tools.web_search_tool import WebSearchTool
+
+pytestmark = pytest.mark.unit
+
+# A JSON integer with no float representation. NOTE: ``int()`` of an int is the
+# identity, so this only overflows on paths that go through ``float()`` — the
+# ``int()``-based clamp helpers legitimately clamp it to their maximum instead.
+# Kept under Python's 4300-digit int→str limit so pytest can build a test id.
+_UNREPRESENTABLE_INT = 10 ** 400
+
+
+# ── read-only clamp helpers: non-finite falls back, finite is unchanged ────────
+
+
+def test_clamp_helpers_survive_non_finite_and_preserve_finite_values() -> None:
+ """Read-only limit helpers clamp junk instead of raising OverflowError.
+
+ ``int(float("inf"))`` raises OverflowError — that is the failure mode these
+ helpers now absorb. A huge *integer* needs no absorbing: ``int()`` accepts it
+ and the normal range clamp applies.
+ """
+ assert _clamp_lookback(float("inf")) == 30
+ assert _clamp_lookback(float("-inf")) == 30
+ assert _clamp_lookback(_UNREPRESENTABLE_INT) == 250 # clamped to the max lookback
+ assert block_trades_clamp_days(float("inf")) == 30
+ assert fred_clamp_limit(float("inf")) == 2000
+ assert iwencai_coerce_limit(float("inf")) == 20
+ assert lockup_clamp_horizon(float("inf")) == 90
+ assert margin_clamp_days(float("inf")) == 30
+ assert research_clamp_limit(float("inf")) == 20
+ assert sec_clamp_limit(float("inf")) == 20
+ assert shareholder_clamp_periods(float("inf")) == 24
+ assert stock_news_clamp_limit(float("inf")) == 20
+ assert symbol_clamp_limit(float("inf")) == 10
+ assert _coerce_expiration(float("inf")) is None
+ assert _coerce_expiration(float("-inf")) is None
+
+ # Finite requests must be untouched by the hardening.
+ assert _clamp_lookback(7) == 7
+ assert _clamp_lookback("7") == 7
+ assert fred_clamp_limit(50) == 50
+ assert _coerce_expiration(3) == 3
+
+
+def test_alpha_zoo_rejects_non_finite_limit() -> None:
+ """run_alpha_zoo answers with an error envelope, not an OverflowError."""
+ for bad in (float("inf"), float("-inf"), float("nan"), "many", None):
+ res = run_alpha_zoo(action="list_alphas", limit=bad)
+ assert res["status"] == "error"
+ assert "limit must be" in res["error"]
+
+
+# ── trading connector: action-bearing, so it must fail closed ─────────────────
+
+
+def test_trading_numeric_helpers_reject_malformed_values() -> None:
+ """Malformed order numerics raise instead of degrading to None."""
+ assert _num_or_none(None) is None
+ assert _num_or_none("") is None
+ assert _num_or_none(2) == 2.0
+ assert _int_or_none(None) is None
+ assert _int_or_none("7") == 7
+
+ for bad in (float("nan"), float("inf"), float("-inf"), {}, [], "invalid", _UNREPRESENTABLE_INT):
+ with pytest.raises(InvalidTradingArgument):
+ _num_or_none(bad, "quantity")
+ with pytest.raises(InvalidTradingArgument):
+ _int_or_none(bad, "port")
+
+ # A fractional port is not a whole number and must not be truncated.
+ with pytest.raises(InvalidTradingArgument):
+ _int_or_none(7.5, "port")
+
+
+ "bad_kwargs",
+ [
+ {"quantity": "bad", "notional": 100},
+ {"quantity": float("nan")},
+ {"quantity": float("inf")},
+ {"quantity": 5, "limit_price": "abc"},
+ {"quantity": 5, "port": "not-a-port"},
+ {"quantity": 5, "client_id": float("inf")},
+ ],
+)
+def test_place_order_never_reaches_service_with_malformed_arguments(
+ monkeypatch: pytest.MonkeyPatch, bad_kwargs: dict[str, Any]
+) -> None:
+ """Regression: `quantity="bad", notional=100` must not become a $100 order."""
+ calls: list[dict[str, Any]] = []
+
+ def fail_place_order(*args: Any, **kwargs: Any) -> dict[str, Any]:
+ calls.append(kwargs)
+ raise AssertionError("place_order must not be called for malformed input")
+
+ monkeypatch.setattr("src.tools.trading_connector_tool.place_order", fail_place_order)
+
+ payload = json.loads(
+ TradingPlaceOrderTool().execute(
+ symbol="NVDA", connection="alpaca-paper-trade", side="buy", **bad_kwargs
+ )
+ )
+
+ assert payload["status"] == "error"
+ assert payload["error"]
+ assert calls == []
+
+
+def test_place_order_still_forwards_valid_arguments(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The fail-closed guard must not break a well-formed order."""
+ seen: dict[str, Any] = {}
+
+ def fake_place_order(symbol: str, connection: Any, **kwargs: Any) -> dict[str, Any]:
+ seen.update({"symbol": symbol, "connection": connection, **kwargs})
+ return {"status": "ok"}
+
+ monkeypatch.setattr("src.tools.trading_connector_tool.place_order", fake_place_order)
+
+ payload = json.loads(
+ TradingPlaceOrderTool().execute(
+ symbol="NVDA",
+ connection="alpaca-paper-trade",
+ side="buy",
+ quantity=2,
+ notional=0,
+ port=7497,
+ )
+ )
+
+ assert payload["status"] == "ok"
+ assert seen["quantity"] == 2.0
+ assert seen["notional"] is None
+ assert seen["port"] == 7497
+
+
+# ── QVeris: not read-only, spends real credits ────────────────────────────────
+
+
+def paid_qveris(tmp_path, monkeypatch: pytest.MonkeyPatch):
+ """Configure paid-mode QVeris against a tmp config file (never the real key)."""
+ 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()
+ qt._SESSION_RESERVED.clear()
+ qt.save_qveris_config(
+ qt.QVerisConfig(enabled=True, api_key="sk-test", mode="paid", budget_credits_per_session=50.0)
+ )
+ yield
+ qt._SESSION_SPEND.clear()
+ qt._SESSION_RESERVED.clear()
+
+
+def _forbid_qveris_client(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Make any QVeris client construction an outright test failure."""
+
+ def fail(self: Any) -> Any:
+ raise AssertionError("no QVeris client may be built for an invalid request")
+
+ monkeypatch.setattr(qt.QVerisSearchTool, "_client", fail)
+ monkeypatch.setattr(qt.QVerisExecuteTool, "_client", fail)
+
+
[email protected]("kwargs", [{}, {"query": None}, {"query": " "}, {"query": 5}])
+def test_qveris_search_rejects_missing_query(
+ paid_qveris: None, monkeypatch: pytest.MonkeyPatch, kwargs: dict[str, Any]
+) -> None:
+ """A missing query must not be sent to the marketplace as an empty search."""
+ _forbid_qveris_client(monkeypatch)
+
+ payload = json.loads(qt.QVerisSearchTool().execute(**kwargs))
+
+ assert payload["ok"] is False
+ assert "query is required" in payload["error"]
+
+
[email protected]("bad_limit", [float("inf"), float("nan"), "many", 0, -3, 2.5, {}])
+def test_qveris_search_rejects_malformed_limit(
+ paid_qveris: None, monkeypatch: pytest.MonkeyPatch, bad_limit: Any
+) -> None:
+ """An explicitly malformed limit errors instead of quietly becoming 20."""
+ _forbid_qveris_client(monkeypatch)
+
+ payload = json.loads(qt.QVerisSearchTool().execute(query="btc", limit=bad_limit))
+
+ assert payload["ok"] is False
+ assert "limit must be a positive integer" in payload["error"]
+
+
+def test_qveris_search_forwards_valid_request(paid_qveris: None, monkeypatch: pytest.MonkeyPatch) -> None:
+ """A well-formed search still reaches the client with a defaulted limit."""
+ seen: dict[str, Any] = {}
+
+ class FakeClient:
+ def search(self, query: str, **kwargs: Any) -> dict[str, Any]:
+ seen.update({"query": query, **kwargs})
+ return {"results": []}
+
+ monkeypatch.setattr(qt.QVerisSearchTool, "_client", lambda self: FakeClient())
+
+ payload = json.loads(qt.QVerisSearchTool().execute(query=" btc "))
+
+ assert payload["ok"] is True
+ assert seen["query"] == "btc"
+ assert seen["limit"] == 20
+
+
+ ("kwargs", "expected"),
+ [
+ ({"tool_id": "t1"}, "parameters is required"),
+ ({"tool_id": "t1", "parameters": None}, "parameters is required"),
+ ({"tool_id": "t1", "parameters": "{}"}, "parameters is required"),
+ ({"tool_id": "t1", "parameters": []}, "parameters is required"),
+ ({"parameters": {"x": 1}}, "tool_id is required"),
+ ({"tool_id": "", "parameters": {"x": 1}}, "tool_id is required"),
+ ({"tool_id": "t1", "parameters": {}, "max_response_size": float("inf")}, "max_response_size"),
+ ({"tool_id": "t1", "parameters": {}, "max_response_size": "big"}, "max_response_size"),
+ ],
+)
+def test_qveris_execute_never_bills_an_invalid_request(
+ paid_qveris: None, monkeypatch: pytest.MonkeyPatch, kwargs: dict[str, Any], expected: str
+) -> None:
+ """A schema-invalid billable call is refused before quote/budget/execute."""
+ _forbid_qveris_client(monkeypatch)
+
+ payload = json.loads(qt.QVerisExecuteTool().execute(**kwargs))
+
+ assert payload["ok"] is False
+ assert expected in payload["error"]
+ assert qt._SESSION_RESERVED == {}
+ assert qt._SESSION_SPEND == {}
+
+
+def test_qveris_execute_accepts_a_genuinely_empty_parameters_object(
+ paid_qveris: None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """`parameters={}` is a valid supplied value — only a MISSING field is refused."""
+ seen: dict[str, Any] = {}
+
+ class FakeClient:
+ def execute(self, tool_id: str, **kwargs: Any) -> dict[str, Any]:
+ seen.update({"tool_id": tool_id, **kwargs})
+ return {"success": True, "cost": 1.0, "result": {}}
+
+ monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: FakeClient())
+
+ payload = json.loads(
+ qt.QVerisExecuteTool().execute(
+ tool_id="tool_1", parameters={}, session_id="s1", expected_cost="1 credit"
+ )
+ )
+
+ assert payload["ok"] is True
+ assert seen["parameters"] == {}
+ assert seen["max_response_size"] == 20480
+
+
+# ── report_audit extract options ──────────────────────────────────────────────
+
+
+def test_report_audit_rejects_invalid_ratio_and_seed() -> None:
+ """Malformed sampling options error instead of silently reshaping the sample."""
+ bad_ratio = json.loads(
+ ReportAuditTool().execute(command="extract", report_text="收入:1亿", ratio="invalid")
+ )
+ assert bad_ratio["status"] == "error"
+ assert "invalid ratio" in bad_ratio["error"]
+
+ bad_seed = json.loads(
+ ReportAuditTool().execute(command="extract", report_text="收入:1亿", seed=float("inf"))
+ )
+ assert bad_seed["status"] == "error"
+ assert "invalid seed" in bad_seed["error"]
+
+
+# ── options pricing ───────────────────────────────────────────────────────────
+
+
[email protected]("bad_spot", [None, "", {}, [], "abc"])
+def test_options_pricing_rejects_unusable_spot(bad_spot: Any) -> None:
+ """A missing/malformed required argument returns an error envelope."""
+ payload = json.loads(
+ OptionsPricingTool().execute(
+ spot=bad_spot, strike=100, expiry_days=30, volatility=0.2, option_type="call"
+ )
+ )
+ assert payload["status"] == "error"
+ assert payload["error"]
+
+
+# ── session search: must not touch ~/.vibe-trading/sessions.db ────────────────
+
+
+def test_session_search_rejects_malformed_max_results(monkeypatch: pytest.MonkeyPatch) -> None:
+ """An explicit junk max_results errors before the session index is opened."""
+
+ def fail_get_shared_index() -> Any:
+ raise AssertionError("the shared session index must not be opened")
+
+ monkeypatch.setattr("src.session.search.get_shared_index", fail_get_shared_index)
+
+ for bad in (float("nan"), float("inf"), "lots", {}, []):
+ payload = json.loads(SessionSearchTool().execute(query="btc", max_results=bad))
+ assert payload["status"] == "error"
+ assert "max_results must be an integer" in payload["error"]
+
+
+def test_session_search_absent_max_results_defaults_to_three(monkeypatch: pytest.MonkeyPatch) -> None:
+ """An absent max_results still defaults, and the default reaches the index."""
+ seen: dict[str, Any] = {}
+
+ class FakeIndex:
+ def search(self, query: str, max_sessions: int = 3) -> list[Any]:
+ seen.update({"query": query, "max_sessions": max_sessions})
+ return []
+
+ monkeypatch.setattr("src.session.search.get_shared_index", lambda: FakeIndex())
+
+ payload = json.loads(SessionSearchTool().execute(query="btc"))
+
+ assert payload["status"] == "ok"
+ assert seen == {"query": "btc", "max_sessions": 3}
+
+
+# ── web search: must not perform a real search ───────────────────────────────
+
+
[email protected](autouse=True)
+def _no_search_env(monkeypatch: pytest.MonkeyPatch):
+ """Keep the Aliyun IQS fast path and backend overrides out of these tests."""
+ monkeypatch.delenv("ALIYUN_IQS_API_KEY", raising=False)
+ monkeypatch.delenv("VIBE_TRADING_SEARCH_BACKENDS", raising=False)
+ monkeypatch.delenv("VIBE_TRADING_SEARCH_BING_FALLBACK", raising=False)
+
+
+def _install_fake_ddgs(monkeypatch: pytest.MonkeyPatch, recorder: dict[str, Any]) -> None:
+ """Replace the ``ddgs`` module so no HTTP request can be issued."""
+ module = ModuleType("ddgs")
+
+ class FakeDDGS:
+ def __enter__(self) -> "FakeDDGS":
+ return self
+
+ def __exit__(self, *exc: Any) -> bool:
+ return False
+
+ def text(self, query: str, max_results: int = 5, **kwargs: Any) -> list[dict[str, str]]:
+ recorder["calls"] = recorder.get("calls", 0) + 1
+ recorder["max_results"] = max_results
+ return [{"title": "T", "href": "https://example.test/a", "body": "b"}]
+
+ module.DDGS = FakeDDGS
+ monkeypatch.setitem(sys.modules, "ddgs", module)
+
+
[email protected]("bad_query", [None, "", " ", 5, {}])
+def test_web_search_rejects_unusable_query(monkeypatch: pytest.MonkeyPatch, bad_query: Any) -> None:
+ """A junk query is refused without any search being attempted."""
+ recorder: dict[str, Any] = {}
+ _install_fake_ddgs(monkeypatch, recorder)
+
+ payload = json.loads(WebSearchTool().execute(query=bad_query))
+
+ assert payload["status"] == "error"
+ assert "query is mandatory" in payload["error"]
+ assert recorder.get("calls", 0) == 0
+
+
[email protected]("bad_max", [float("nan"), float("inf"), "five", {}, []])
+def test_web_search_rejects_malformed_max_results(monkeypatch: pytest.MonkeyPatch, bad_max: Any) -> None:
+ """An explicit junk max_results errors instead of searching with 5."""
+ recorder: dict[str, Any] = {}
+ _install_fake_ddgs(monkeypatch, recorder)
+
+ payload = json.loads(WebSearchTool().execute(query="nvidia", max_results=bad_max))
+
+ assert payload["status"] == "error"
+ assert "max_results must be an integer" in payload["error"]
+ assert recorder.get("calls", 0) == 0
+
+
+def test_web_search_absent_max_results_defaults_to_five(monkeypatch: pytest.MonkeyPatch) -> None:
+ """An absent max_results defaults to 5 and is forwarded to the backend."""
+ recorder: dict[str, Any] = {}
+ _install_fake_ddgs(monkeypatch, recorder)
+
+ payload = json.loads(WebSearchTool().execute(query="nvidia"))
+
+ assert payload["status"] == "ok"
+ assert recorder["calls"] == 1
+ assert recorder["max_results"] == 5
+
+
+# ── shadow account ───────────────────────────────────────────────────────────
+
+
[email protected]("field", ["min_support", "max_rules"])
+def test_extract_shadow_strategy_rejects_malformed_integers(
+ monkeypatch: pytest.MonkeyPatch, tmp_path, field: str
+) -> None:
+ """A malformed rule-mining option errors before the journal is parsed."""
+ journal = tmp_path / "journal.csv"
+ journal.write_text("x\n", encoding="utf-8")
+
+ def fail_extract(*args: Any, **kwargs: Any) -> Any:
+ raise AssertionError("the journal must not be parsed for malformed options")
+
+ monkeypatch.setattr(sat, "extract_shadow_profile", fail_extract)
+ monkeypatch.setattr(sat, "safe_user_path", lambda raw: journal)
+
+ payload = json.loads(
+ sat.ExtractShadowStrategyTool().execute(journal_path=str(journal), **{field: float("inf")})
+ )
+
+ assert payload["status"] == "error"
+ assert f"{field} must be an integer" in payload["error"]
+
+
+def test_scan_shadow_signals_rejects_malformed_per_market(monkeypatch: pytest.MonkeyPatch) -> None:
+ """per_market is validated before the profile load, so the branch is reached."""
+
+ def fail_load(*args: Any, **kwargs: Any) -> Any:
+ raise AssertionError("no profile should be loaded for a malformed per_market")
+
+ monkeypatch.setattr(sat, "load_profile", fail_load)
+
+ payload = json.loads(
+ sat.ScanShadowSignalsTool().execute(shadow_id="shadow-1", per_market=float("inf"))
+ )
+
+ assert payload["status"] == "error"
+ assert "per_market must be an integer" in payload["error"]
+
+
+def test_scan_shadow_signals_absent_per_market_defaults_to_three(monkeypatch: pytest.MonkeyPatch) -> None:
+ """An absent per_market defaults to 3 and reaches the scanner."""
+ seen: dict[str, Any] = {}
+
+ monkeypatch.setattr(sat, "load_profile", lambda shadow_id: SimpleNamespace(shadow_id=shadow_id))
+
+ def fake_scan(profile: Any, target_date: Any = None, per_market: int = 3) -> list[Any]:
+ seen.update({"shadow_id": profile.shadow_id, "target_date": target_date, "per_market": per_market})
+ return []
+
+ monkeypatch.setattr(sat, "scan_today_signals", fake_scan)
+
+ payload = json.loads(sat.ScanShadowSignalsTool().execute(shadow_id="shadow-1"))
+
+ assert payload["status"] == "ok"
+ assert seen == {"shadow_id": "shadow-1", "target_date": None, "per_market": 3}