Skip to content

"Vibe-Trading: Your Personal Trading Agent"

Merge PR #2087: carry configured policies across provider and worker paths

Haozhe Wu15477e3ed55f
diff --cc README.md
index db500c145,b45e0fb01..09c4d8cfe
--- a/README.md
+++ b/README.md
@@@ -1124,12 -1124,14 +1124,14 @@@ LANGCHAIN_PROVIDER=claude-cl
LANGCHAIN_MODEL_NAME=claude-opus-5-5
# LANGCHAIN_REASONING_EFFORT=high # low|medium|high|xhigh|max; passed as --effort
# CLAUDE_CLI_PATH=/opt/homebrew/bin/claude # when `claude` is not on PATH or in ~/.local/bin
- # CLAUDE_CLI_DENY_TOOL_PREFIXES=trading_,etoro_ # default; set empty to offer every tool
- # CLAUDE_CLI_BASH_POLICY=python-only # or `off`
+ # VIBE_TRADING_DENY_TOOL_PREFIXES=trading_,etoro_ # any provider; empty offers every tool
+ # VIBE_TRADING_BASH_POLICY=python-only # any provider, or `off`
+ # CLAUDE_CLI_DENY_TOOL_PREFIXES=trading_,etoro_ # legacy alias when the generic name is unset
+ # CLAUDE_CLI_BASH_POLICY=python-only # legacy alias when the generic name is unset
```
- - `CLAUDE_CLI_DENY_TOOL_PREFIXES` hides tools whose names start with these prefixes from the model. The default hides every `trading_*` and `etoro_*` tool, read-only ones included, so the agent cannot quote or list positions through a broker connector under this provider until you change it.
- - `CLAUDE_CLI_BASH_POLICY=python-only` lets the `bash` tool run only `python <relative script>.py`, `python -c ...`, and read-only `ls`/`cat`/`head`/`tail`/`wc`/`pwd` on non-hidden relative paths (so not `.env`); refused calls are returned to the model so it can choose again. Any other value stops the provider from starting.
-- `VIBE_TRADING_DENY_TOOL_PREFIXES` hides tools whose names start with these prefixes from every provider. The default hides every `trading_*` and `etoro_*` tool, read-only ones included, so the agent cannot quote or list positions through a broker connector until you change it. `CLAUDE_CLI_DENY_TOOL_PREFIXES` remains the fallback alias for existing configurations.
++- `VIBE_TRADING_DENY_TOOL_PREFIXES` hides tools whose names start with these prefixes from every provider. An explicitly configured `CLAUDE_CLI_DENY_TOOL_PREFIXES` remains the fallback alias across providers. With neither configured, other providers retain their existing tool surface; Claude CLI retains its previous `trading_,etoro_` default (including broker reads).
+ - `VIBE_TRADING_BASH_POLICY=python-only` applies the same rule to every provider: `bash` may run only `python <relative script>.py`, `python -c ...`, and read-only `ls`/`cat`/`head`/`tail`/`wc`/`pwd` on non-hidden relative paths (so not `.env`); refused calls are returned to the model so it can choose again. `CLAUDE_CLI_BASH_POLICY` remains the fallback alias. `vibe-trading provider doctor` reports the active policy and which variable supplied it.
> **Warning:** Both settings are convenience filters, not a security boundary. `python -c` can still run arbitrary code, and external MCP tools (`mcp_<server>_<tool>`) are not covered by the default prefixes. Live orders stay bound by the mandate gate and kill switch whatever these settings allow.
@@@ -1239,8 -1241,10 +1241,10 @@@ Copy `agent/.env.example` to `agent/.en
| `TUSHARE_TOKEN` | No | Tushare Pro token for A-share data (falls back to AKShare) |
| `TIMEOUT_SECONDS` | No | LLM call timeout, default 120s |
| `CLAUDE_CLI_PATH` | No | `claude` executable for the `claude-cli` provider when it is not on PATH or in `~/.local/bin` |
- | `CLAUDE_CLI_DENY_TOOL_PREFIXES` | No | Tool-name prefixes hidden from the `claude-cli` model (default `trading_,etoro_`; empty offers every tool) |
- | `CLAUDE_CLI_BASH_POLICY` | No | `python-only` (default) or `off` for the `claude-cli` provider's `bash` tool |
-| `VIBE_TRADING_DENY_TOOL_PREFIXES` | No | Tool-name prefixes hidden from every provider (default `trading_,etoro_`; empty offers every tool) |
-| `VIBE_TRADING_BASH_POLICY` | No | `python-only` (default) or `off` for every provider's `bash` tool |
++| `VIBE_TRADING_DENY_TOOL_PREFIXES` | No | Explicit tool-name filter across every provider; empty offers every tool; unconfigured retains prior provider defaults |
++| `VIBE_TRADING_BASH_POLICY` | No | Explicit `python-only` or `off` across providers; unconfigured retains prior defaults (`python-only` for Claude CLI, `off` otherwise) |
+ | `CLAUDE_CLI_DENY_TOOL_PREFIXES` | No | Legacy alias for `VIBE_TRADING_DENY_TOOL_PREFIXES`, used when the generic name is unset |
+ | `CLAUDE_CLI_BASH_POLICY` | No | Legacy alias for `VIBE_TRADING_BASH_POLICY`, used when the generic name is unset |
| `API_AUTH_KEY` | Recommended for network deployments | Bearer token required when the API is reachable from non-local clients |
| `VIBE_TRADING_ENABLE_SHELL_TOOLS` | No | Explicit opt-in for shell-capable tools in remote API/MCP-SSE style deployments |
| `VIBE_TRADING_ALLOWED_FILE_ROOTS` | No | Extra comma-separated roots for document and broker-journal imports |
diff --cc agent/src/agent/tools.py
index 1bb8ae215,1bb8ae215..33565c479
--- a/agent/src/agent/tools.py
+++ b/agent/src/agent/tools.py
@@@ -5,9 -5,9 +5,9 @@@ from __future__ import annotation
import json
import logging
from abc import ABC, abstractmethod
++from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
--from typing import Any, Dict, List, Optional
class BaseTool(ABC):
@@@ -140,6 -140,6 +140,19 @@@ class ToolRegistry
)
return json.dumps(payload, ensure_ascii=False)
try:
++ # The registry is shared by agent, Swarm and MCP execution. Keep
++ # explicit policy enforcement here so a direct/unoffered call
++ # cannot bypass it. Claude CLI retains its adapter defaults.
++ from src.providers.tool_policy import _deny_prefixes, screen_calls
++
++ if name.startswith(_deny_prefixes()):
++ return json.dumps({"status": "error", "skipped": True,
++ "error": f"{name} is disabled by the active tool policy"})
++ if name in {"bash", "background_run", "cancel_background"}:
++ accepted, notes = screen_calls([{"name": name, "arguments": params}], {name})
++ if notes:
++ return json.dumps({"status": "error", "skipped": True, "error": notes[0]})
++ params = accepted[0]["arguments"]
return tool.execute(**params)
except Exception as exc:
logger.exception("Tool %s failed", name)
diff --cc agent/src/providers/chat.py
index 74a9ee744,0ab55afe1..d250a1d46
--- a/agent/src/providers/chat.py
+++ b/agent/src/providers/chat.py
@@@ -468,7 -469,7 +469,8 @@@ class ChatLLM
Returns:
LLMResponse.
"""
- llm = self._llm.bind_tools(tools) if tools else self._llm
- llm = self._llm.bind_tools(offered_tools(tools)) if tools else self._llm
++ available = offered_tools(tools) if tools else []
++ llm = self._llm.bind_tools(available) if available else self._llm
config = {"timeout": timeout} if timeout else {}
messages, call_kwargs = self._prompt_cache_request(messages)
ai_message = llm.invoke(messages, config=config, **call_kwargs)
@@@ -511,7 -512,7 +513,8 @@@
"""
accumulated = None
try:
- llm = self._llm.bind_tools(tools) if tools else self._llm
- llm = self._llm.bind_tools(offered_tools(tools)) if tools else self._llm
++ available = offered_tools(tools) if tools else []
++ llm = self._llm.bind_tools(available) if available else self._llm
config = {"timeout": timeout} if timeout else {}
messages, call_kwargs = self._prompt_cache_request(messages)
accumulated = None
diff --cc agent/src/providers/claude_cli_policy.py
index d99243c7b,63bb35bc4..c7321ac76
--- a/agent/src/providers/claude_cli_policy.py
+++ b/agent/src/providers/claude_cli_policy.py
@@@ -1,129 -1,19 +1,32 @@@
- """Tool screening for the claude-cli provider: the deny list and the bash policy.
+ """Compatibility re-exports for the provider-agnostic tool policy."""
- Both are convenience filters, not a security boundary: ``python -c`` can still
- run anything, and live orders stay bound by the mandate gate and kill switch.
- """
++from src.providers import tool_policy as _shared
+ from src.providers.tool_policy import (
- _deny_prefixes,
- bash_policy,
+ check_bash_command,
- offered_tools,
- screen_calls,
+ tool_name,
+ )
- from __future__ import annotations
+
- import shlex
- import sys
- from pathlib import Path
- from typing import Any, Optional
++def _deny_prefixes():
++ return _shared._deny_prefixes(legacy_defaults=True)
+
- from src.config.accessor import get_env_config
+
- _PYTHON_COMMANDS = frozenset({"python", "python3"})
- _READONLY_COMMANDS = frozenset({"ls", "cat", "head", "tail", "wc", "pwd"})
- _SHELL_PROCESS_TOOLS = frozenset({"background_run", "cancel_background"})
- _SHELL_OPERATOR_CHARS = set("();<>|&")
++def bash_policy():
++ return _shared.bash_policy(legacy_defaults=True)
+
+
- def _deny_prefixes() -> tuple[str, ...]:
- """Tool-name prefixes never offered to the model; ``""`` disables the list."""
- raw = get_env_config().llm.claude_cli_deny_tool_prefixes
- return tuple(p.strip() for p in raw.split(",") if p.strip())
++def offered_tools(tools):
++ return _shared.offered_tools(tools, legacy_defaults=True)
+
+
- def bash_policy() -> str:
- """``python-only`` (default) or ``off``; anything else is a configuration error."""
- value = get_env_config().llm.claude_cli_bash_policy.strip().lower()
- if value not in {"python-only", "off"}:
- raise RuntimeError(
- f"CLAUDE_CLI_BASH_POLICY must be python-only or off, got {value!r}"
- )
- return value
++def screen_calls(calls, offered):
++ return _shared.screen_calls(calls, offered, legacy_defaults=True)
+
-
- def tool_name(definition: dict[str, Any]) -> str:
- return str((definition.get("function") or definition).get("name") or "")
-
-
- def offered_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
- prefixes = _deny_prefixes()
- return (
- [t for t in tools if not tool_name(t).startswith(prefixes)]
- if prefixes
- else list(tools)
- )
-
-
- def _relative_path(token: str) -> bool:
- return not token.startswith(("/", "~")) and ".." not in Path(token).parts
-
-
- def _hidden_path(token: str) -> bool:
- # ``.env`` and ``.git`` hold credentials; a read would put them in the trace.
- return any(part.startswith(".") and part != "." for part in Path(token).parts)
-
-
- def check_bash_command(command: str) -> tuple[Optional[str], Optional[str]]:
- """Apply the ``python-only`` policy to one shell command.
-
- Args:
- command: The command the model asked ``bash`` to run.
-
- Returns:
- ``(rewritten_command, None)`` when allowed, else ``(None, reason)``.
- An allowed ``python``/``python3`` call is rewritten to this process's
- interpreter so scripts can import Vibe-Trading's own packages.
- """
- if "\n" in command or "`" in command or "$(" in command:
- return None, "newlines, backticks and $( ) are not allowed"
- lexer = shlex.shlex(command, posix=True, punctuation_chars=True)
- lexer.whitespace_split = True
- try:
- tokens = list(lexer)
- except ValueError as exc:
- return None, f"unparseable command: {exc}"
- if not tokens:
- return None, "empty command"
- if any(tok and set(tok) <= _SHELL_OPERATOR_CHARS for tok in tokens):
- return None, "shell operators (; && || | redirection) are not allowed"
- program, args = tokens[0], tokens[1:]
- if program in _PYTHON_COMMANDS:
- if args[:1] == ["-c"] and len(args) >= 2:
- return shlex.join([sys.executable, *args]), None
- if args and args[0].endswith(".py") and _relative_path(args[0]):
- return shlex.join([sys.executable, *args]), None
- return (
- None,
- "python may only run `python <relative script>.py` or `python -c <code>`",
- )
- if program in _READONLY_COMMANDS:
- paths = [a for a in args if not a.startswith("-")]
- if all(_relative_path(p) and not _hidden_path(p) for p in paths):
- return shlex.join(tokens), None
- return (
- None,
- f"{program} may only read non-hidden relative paths inside the working directory",
- )
- return None, f"program {program!r} is not allowed (python-only policy)"
-
-
- def screen_calls(
- calls: list[dict[str, Any]], offered: set[str]
- ) -> tuple[list[dict[str, Any]], list[str]]:
- """Return calls the host may execute, plus one rejection note per refused call."""
- policy = bash_policy()
- accepted: list[dict[str, Any]] = []
- notes: list[str] = []
- for call in calls:
- name = str(call.get("name") or "")
- args = dict(call.get("arguments") or {})
- if name not in offered:
- notes.append(f"- {name}: not an available tool")
- continue
- if policy == "python-only" and name in _SHELL_PROCESS_TOOLS:
- notes.append(
- f"- {name}: background processes are not allowed (python-only policy)"
- )
- continue
- if policy == "python-only" and name == "bash":
- rewritten, reason = check_bash_command(str(args.get("command") or ""))
- if reason:
- notes.append(f"- bash `{args.get('command')}`: {reason}")
- continue
- args["command"] = rewritten
- accepted.append({"name": name, "arguments": args})
- return accepted, notes
+ __all__ = [
+ "_deny_prefixes",
+ "bash_policy",
+ "check_bash_command",
+ "offered_tools",
+ "screen_calls",
+ "tool_name",
+ ]
diff --cc agent/src/providers/tool_policy.py
index 000000000,1f314257c..053246341
mode 000000,100644..100644
--- a/agent/src/providers/tool_policy.py
+++ b/agent/src/providers/tool_policy.py
@@@ -1,0 -1,160 +1,154 @@@
+ """Provider-agnostic tool screening: the deny list and the bash policy.
+
+ Both are convenience filters, not a security boundary: ``python -c`` can still
+ run anything, and live orders stay bound by the mandate gate and kill switch.
+ """
+
+ from __future__ import annotations
+
+ import shlex
++import os
++import subprocess
+ import sys
+ from pathlib import Path
+ from typing import Any, Optional
+
+ from src.config.accessor import get_env_config
+
+ _PYTHON_COMMANDS = frozenset({"python", "python3"})
+ _READONLY_COMMANDS = frozenset({"ls", "cat", "head", "tail", "wc", "pwd"})
+ _SHELL_PROCESS_TOOLS = frozenset({"background_run", "cancel_background"})
+ _SHELL_OPERATOR_CHARS = set("();<>|&")
+
+
-def _deny_prefixes() -> tuple[str, ...]:
- """Tool-name prefixes never offered to the model; ``""`` disables the list."""
++def _policy_value(generic: str, legacy: str, default: str, legacy_defaults: bool) -> tuple[str, str]:
+ config = get_env_config().llm
- raw = config.vibe_trading_deny_tool_prefixes
- if raw is None:
- raw = config.claude_cli_deny_tool_prefixes
++ if (value := getattr(config, generic)) is not None:
++ return value, type(config).model_fields[generic].alias
++ if legacy_defaults or legacy in config.model_fields_set:
++ return getattr(config, legacy), type(config).model_fields[legacy].alias
++ return default, "default"
++
++
++def _deny_prefixes(*, legacy_defaults: bool = False) -> tuple[str, ...]:
++ """Tool-name prefixes never offered to the model; ``""`` disables the list."""
++ raw, _ = _policy_value("vibe_trading_deny_tool_prefixes", "claude_cli_deny_tool_prefixes", "", legacy_defaults)
+ return tuple(p.strip() for p in raw.split(",") if p.strip())
+
+
-def bash_policy() -> str:
- """``python-only`` (default) or ``off``; anything else is a configuration error."""
- config = get_env_config().llm
- generic = config.vibe_trading_bash_policy
- value = (
- (generic if generic is not None else config.claude_cli_bash_policy)
- .strip()
- .lower()
- )
++def bash_policy(*, legacy_defaults: bool = False) -> str:
++ """Resolve an explicitly configured cross-provider policy or prior defaults."""
++ raw, source = _policy_value("vibe_trading_bash_policy", "claude_cli_bash_policy", "off", legacy_defaults)
++ value = raw.strip().lower()
+ if value not in {"python-only", "off"}:
- source = (
- "VIBE_TRADING_BASH_POLICY"
- if generic is not None
- else "CLAUDE_CLI_BASH_POLICY"
- )
+ raise RuntimeError(f"{source} must be python-only or off, got {value!r}")
+ return value
+
+
+ def policy_status() -> dict[str, Any]:
+ """Return the active, non-secret policy for provider diagnostics."""
+ config = get_env_config().llm
++ legacy_defaults = config.langchain_provider.replace("-", "_") == "claude_cli"
++ _, deny_source = _policy_value("vibe_trading_deny_tool_prefixes", "claude_cli_deny_tool_prefixes", "", legacy_defaults)
++ _, bash_source = _policy_value("vibe_trading_bash_policy", "claude_cli_bash_policy", "off", legacy_defaults)
+ return {
- "deny_tool_prefixes": list(_deny_prefixes()),
- "deny_tool_prefixes_source": (
- "VIBE_TRADING_DENY_TOOL_PREFIXES"
- if config.vibe_trading_deny_tool_prefixes is not None
- else "CLAUDE_CLI_DENY_TOOL_PREFIXES"
- ),
- "bash_policy": bash_policy(),
- "bash_policy_source": (
- "VIBE_TRADING_BASH_POLICY"
- if config.vibe_trading_bash_policy is not None
- else "CLAUDE_CLI_BASH_POLICY"
- ),
++ "deny_tool_prefixes": list(_deny_prefixes(legacy_defaults=legacy_defaults)),
++ "deny_tool_prefixes_source": deny_source,
++ "bash_policy": bash_policy(legacy_defaults=legacy_defaults),
++ "bash_policy_source": bash_source,
+ }
+
+
+ def tool_name(definition: dict[str, Any]) -> str:
+ return str((definition.get("function") or definition).get("name") or "")
+
+
-def offered_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
- prefixes = _deny_prefixes()
++def offered_tools(tools: list[dict[str, Any]], *, legacy_defaults: bool = False) -> list[dict[str, Any]]:
++ prefixes = _deny_prefixes(legacy_defaults=legacy_defaults)
+ return (
+ [t for t in tools if not tool_name(t).startswith(prefixes)]
+ if prefixes
+ else list(tools)
+ )
+
+
+ def _relative_path(token: str) -> bool:
+ return not token.startswith(("/", "~")) and ".." not in Path(token).parts
+
+
+ def _hidden_path(token: str) -> bool:
+ # ``.env`` and ``.git`` hold credentials; a read would put them in the trace.
+ return any(part.startswith(".") and part != "." for part in Path(token).parts)
+
+
+ def check_bash_command(command: str) -> tuple[Optional[str], Optional[str]]:
+ """Apply the ``python-only`` policy to one shell command.
+
+ Args:
+ command: The command the model asked ``bash`` to run.
+
+ Returns:
+ ``(rewritten_command, None)`` when allowed, else ``(None, reason)``.
+ An allowed ``python``/``python3`` call is rewritten to this process's
+ interpreter so scripts can import Vibe-Trading's own packages.
+ """
+ if "\n" in command or "`" in command or "$(" in command:
+ return None, "newlines, backticks and $( ) are not allowed"
+ lexer = shlex.shlex(command, posix=True, punctuation_chars=True)
+ lexer.whitespace_split = True
+ try:
+ tokens = list(lexer)
+ except ValueError as exc:
+ return None, f"unparseable command: {exc}"
+ if not tokens:
+ return None, "empty command"
+ if any(tok and set(tok) <= _SHELL_OPERATOR_CHARS for tok in tokens):
+ return None, "shell operators (; && || | redirection) are not allowed"
+ program, args = tokens[0], tokens[1:]
- if program in _PYTHON_COMMANDS:
++ join = subprocess.list2cmdline if os.name == "nt" else shlex.join
++ if program in _PYTHON_COMMANDS or program == sys.executable:
+ if args[:1] == ["-c"] and len(args) >= 2:
- return shlex.join([sys.executable, *args]), None
++ return join([sys.executable, *args]), None
+ if args and args[0].endswith(".py") and _relative_path(args[0]):
- return shlex.join([sys.executable, *args]), None
++ return join([sys.executable, *args]), None
+ return (
+ None,
+ "python may only run `python <relative script>.py` or `python -c <code>`",
+ )
+ if program in _READONLY_COMMANDS:
+ paths = [a for a in args if not a.startswith("-")]
+ if all(_relative_path(p) and not _hidden_path(p) for p in paths):
- return shlex.join(tokens), None
++ return join(tokens), None
+ return (
+ None,
+ f"{program} may only read non-hidden relative paths inside the working directory",
+ )
+ return None, f"program {program!r} is not allowed (python-only policy)"
+
+
+ def screen_calls(
- calls: list[dict[str, Any]], offered: set[str]
++ calls: list[dict[str, Any]], offered: set[str], *, legacy_defaults: bool = False
+ ) -> tuple[list[dict[str, Any]], list[str]]:
+ """Return calls the host may execute, plus one rejection note per refused call."""
- policy = bash_policy()
++ policy = bash_policy(legacy_defaults=legacy_defaults)
+ accepted: list[dict[str, Any]] = []
+ notes: list[str] = []
+ for call in calls:
+ name = str(call.get("name") or "")
+ args = dict(call.get("arguments") or {})
+ if name not in offered:
+ notes.append(f"- {name}: not an available tool")
+ continue
+ if policy == "python-only" and name in _SHELL_PROCESS_TOOLS:
+ notes.append(
+ f"- {name}: background processes are not allowed (python-only policy)"
+ )
+ continue
+ if policy == "python-only" and name == "bash":
+ rewritten, reason = check_bash_command(str(args.get("command") or ""))
+ if reason:
+ notes.append(f"- bash `{args.get('command')}`: {reason}")
+ continue
+ args["command"] = rewritten
+ accepted.append({"name": name, "arguments": args})
+ return accepted, notes
diff --cc agent/tests/test_provider_agnostic_tool_policy.py
index 000000000,70565dbf6..b52dd97fb
mode 000000,100644..100644
--- a/agent/tests/test_provider_agnostic_tool_policy.py
+++ b/agent/tests/test_provider_agnostic_tool_policy.py
@@@ -1,0 -1,234 +1,282 @@@
+ """Provider-agnostic deny lists and bash screening (#2085)."""
+
+ from __future__ import annotations
+
+ import json
+ import sys
+ from types import SimpleNamespace
+
+ import pytest
+ from langchain_core.messages import AIMessage, AIMessageChunk
+
+ from src.agent.context import ContextBuilder
+ from src.agent.loop import AgentLoop
+ from src.agent.tools import BaseTool, ToolRegistry
+ from src.agent.trace import TraceWriter
+ from src.config.accessor import get_env_config, reset_env_config
+ from src.providers.chat import ChatLLM
+ from src.providers.llm import provider_diagnostics
+ from src.providers.tool_policy import bash_policy, policy_status
++from src.providers import tool_policy
++from tests.module_os_helpers import patch_module_os
+
+ _POLICY_ENV = (
+ "VIBE_TRADING_DENY_TOOL_PREFIXES",
+ "VIBE_TRADING_BASH_POLICY",
+ "CLAUDE_CLI_DENY_TOOL_PREFIXES",
+ "CLAUDE_CLI_BASH_POLICY",
+ )
+
+
+ @pytest.fixture(autouse=True)
+ def clean_policy_env(monkeypatch: pytest.MonkeyPatch):
+ for name in _POLICY_ENV:
+ monkeypatch.delenv(name, raising=False)
+ reset_env_config()
+ yield
+ reset_env_config()
+
+
++def shared_policy(monkeypatch):
++ monkeypatch.setenv("VIBE_TRADING_DENY_TOOL_PREFIXES", "trading_,etoro_")
++ monkeypatch.setenv("VIBE_TRADING_BASH_POLICY", "python-only")
++ reset_env_config()
++
++
+ def _tool(name: str) -> dict:
+ return {
+ "type": "function",
+ "function": {
+ "name": name,
+ "description": "test tool",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+
+
+ class _RecordingLLM:
+ def __init__(self) -> None:
+ self.bound_tools: list[dict] | None = None
+
+ def bind_tools(self, tools: list[dict]) -> _RecordingLLM:
+ self.bound_tools = tools
+ return self
+
+ def invoke(self, messages: list[dict], **kwargs: object) -> AIMessage:
+ return AIMessage(content="ok")
+
+ def stream(self, messages: list[dict], **kwargs: object):
+ yield AIMessageChunk(content="ok", response_metadata={"finish_reason": "stop"})
+
+
+ def _chat(llm: _RecordingLLM) -> ChatLLM:
+ chat = ChatLLM.__new__(ChatLLM)
+ chat._llm = llm
+ chat.model_name = "gpt-test"
+ return chat
+
+
-def test_chat_filters_denied_tools_before_any_provider_binds() -> None:
++def test_chat_filters_denied_tools_before_any_provider_binds(shared_policy) -> None:
+ llm = _RecordingLLM()
+
+ _chat(llm).chat(
+ [{"role": "user", "content": "x"}],
+ tools=[
+ _tool("get_market_data"),
+ _tool("trading_place_order"),
+ _tool("etoro_close_position"),
+ ],
+ )
+
+ assert llm.bound_tools is not None
+ assert [item["function"]["name"] for item in llm.bound_tools] == ["get_market_data"]
+
+
-def test_stream_chat_uses_the_same_provider_agnostic_filter() -> None:
++def test_stream_chat_uses_the_same_provider_agnostic_filter(shared_policy) -> None:
+ llm = _RecordingLLM()
+
+ response = _chat(llm).stream_chat(
+ [{"role": "user", "content": "x"}],
+ tools=[_tool("get_market_data"), _tool("trading_place_order")],
+ )
+
+ assert response.content == "ok"
+ assert llm.bound_tools is not None
+ assert [item["function"]["name"] for item in llm.bound_tools] == ["get_market_data"]
+
+
+ class _FakeBashTool(BaseTool):
+ name = "bash"
+ description = "recording bash double"
+ parameters: dict = {"type": "object", "properties": {}}
+ is_readonly = False
+
- def __init__(self, name: str = "bash") -> None:
++ def __init__(self, name: str) -> None:
+ self.name = name
+ self.calls: list[dict] = []
+
+ def execute(self, **kwargs: object) -> str:
+ self.calls.append(kwargs)
+ return json.dumps({"status": "ok", "arguments": kwargs})
+
+
+ def _agent(tool: BaseTool, tmp_path) -> AgentLoop:
+ registry = ToolRegistry()
+ registry.register(tool)
+ agent = AgentLoop(
+ registry=registry,
+ llm=SimpleNamespace(),
+ max_iterations=2,
+ event_callback=lambda name, data: None,
+ )
+ agent.memory.run_dir = str(tmp_path)
+ return agent
+
+
+ def _call(agent: AgentLoop, name: str, arguments: dict, tmp_path) -> list[dict]:
+ messages: list[dict] = []
+ trace = TraceWriter(tmp_path)
+ agent._process_tool_calls(
+ [SimpleNamespace(id="call-1", name=name, arguments=arguments)],
+ ContextBuilder,
+ messages,
+ trace,
+ [],
+ 1,
+ )
+ trace.close()
+ return messages
+
+
-def test_shared_execution_rejects_bash_without_running_it(tmp_path) -> None:
- tool = _FakeBashTool()
++def test_shared_execution_rejects_bash_without_running_it(tmp_path, shared_policy) -> None:
++ tool = _FakeBashTool("bash")
+ agent = _agent(tool, tmp_path)
+
+ messages = _call(agent, "bash", {"command": "curl https://example.com"}, tmp_path)
+
+ assert tool.calls == []
+ assert "not allowed" in messages[0]["content"]
+
+
-def test_shared_execution_rewrites_allowed_python(tmp_path) -> None:
- tool = _FakeBashTool()
++def test_shared_execution_rewrites_allowed_python(tmp_path, shared_policy) -> None:
++ tool = _FakeBashTool("bash")
+ agent = _agent(tool, tmp_path)
+
+ _call(agent, "bash", {"command": "python report.py"}, tmp_path)
+
+ assert len(tool.calls) == 1
+ assert tool.calls[0]["command"].startswith(sys.executable)
+
+
-def test_shared_execution_fail_closed_for_a_directly_denied_tool(tmp_path) -> None:
++def test_shared_execution_fail_closed_for_a_directly_denied_tool(tmp_path, shared_policy) -> None:
+ tool = _FakeBashTool("trading_place_order")
+ agent = _agent(tool, tmp_path)
+
+ messages = _call(agent, "trading_place_order", {}, tmp_path)
+
+ assert tool.calls == []
+ assert "disabled by the active tool policy" in messages[0]["content"]
+
+
+ def test_generic_off_allows_the_shared_bash_path_unchanged(
+ monkeypatch, tmp_path
+ ) -> None:
+ monkeypatch.setenv("VIBE_TRADING_BASH_POLICY", "off")
+ reset_env_config()
- tool = _FakeBashTool()
++ tool = _FakeBashTool("bash")
+ agent = _agent(tool, tmp_path)
+
+ _call(agent, "bash", {"command": "curl https://example.com"}, tmp_path)
+
+ assert len(tool.calls) == 1
+ assert tool.calls[0]["command"] == "curl https://example.com"
+
+
+ def test_generic_values_override_legacy_aliases(monkeypatch) -> None:
+ monkeypatch.setenv("CLAUDE_CLI_BASH_POLICY", "off")
+ monkeypatch.setenv("VIBE_TRADING_BASH_POLICY", "python-only")
+ monkeypatch.setenv("VIBE_TRADING_DENY_TOOL_PREFIXES", "custom_")
+ reset_env_config()
+
+ assert bash_policy() == "python-only"
+ assert policy_status() == {
+ "deny_tool_prefixes": ["custom_"],
+ "deny_tool_prefixes_source": "VIBE_TRADING_DENY_TOOL_PREFIXES",
+ "bash_policy": "python-only",
+ "bash_policy_source": "VIBE_TRADING_BASH_POLICY",
+ }
+
+
+ def test_legacy_values_remain_the_fallback(monkeypatch) -> None:
+ monkeypatch.setenv("CLAUDE_CLI_BASH_POLICY", "off")
+ monkeypatch.setenv("CLAUDE_CLI_DENY_TOOL_PREFIXES", "legacy_")
+ reset_env_config()
+
+ assert policy_status()["deny_tool_prefixes"] == ["legacy_"]
+ assert policy_status()["bash_policy"] == "off"
+
+
+ def test_invalid_generic_policy_names_the_generic_variable(monkeypatch) -> None:
+ monkeypatch.setenv("VIBE_TRADING_BASH_POLICY", "strict")
+ reset_env_config()
+
+ with pytest.raises(RuntimeError, match="VIBE_TRADING_BASH_POLICY"):
+ bash_policy()
+
+
+ def test_provider_doctor_exposes_only_the_active_nonsecret_policy(monkeypatch) -> None:
+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "openai")
+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "gpt-test")
+ monkeypatch.setenv("VIBE_TRADING_DENY_TOOL_PREFIXES", "custom_")
+ monkeypatch.setenv("VIBE_TRADING_BASH_POLICY", "off")
+ reset_env_config()
+
+ diagnostics = provider_diagnostics()
+
+ assert diagnostics["tool_policy"] == {
+ "deny_tool_prefixes": ["custom_"],
+ "deny_tool_prefixes_source": "VIBE_TRADING_DENY_TOOL_PREFIXES",
+ "bash_policy": "off",
+ "bash_policy_source": "VIBE_TRADING_BASH_POLICY",
+ }
+ assert get_env_config().llm.vibe_trading_deny_tool_prefixes == "custom_"
++
++
++def test_unconfigured_non_claude_provider_keeps_its_previous_tool_surface():
++ llm = _RecordingLLM()
++ _chat(llm).chat([{"role": "user", "content": "x"}], tools=[_tool("trading_place_order")])
++ assert [t["function"]["name"] for t in llm.bound_tools] == ["trading_place_order"]
++ assert bash_policy() == "off"
++
++
++def test_all_filtered_tools_do_not_bind_an_empty_schema(shared_policy):
++ llm = _RecordingLLM()
++ response = _chat(llm).chat([{"role": "user", "content": "x"}], tools=[_tool("trading_place_order")])
++ assert response.content == "ok"
++ assert llm.bound_tools is None
++
++
++def test_direct_registry_execution_cannot_bypass_policy(shared_policy):
++ tool = _FakeBashTool("trading_place_order")
++ registry = ToolRegistry()
++ registry.register(tool)
++ result = json.loads(registry.execute(tool.name, {}))
++ assert result["status"] == "error"
++ assert tool.calls == []
++
++
++def test_python_screening_is_idempotent_across_adapter_and_registry():
++ first, reason = tool_policy.check_bash_command('python -c "print(1)"')
++ assert reason is None
++ second, reason = tool_policy.check_bash_command(first)
++ assert reason is None
++ assert second == first
++
++
++def test_windows_python_paths_use_cmd_quoting(monkeypatch):
++ patch_module_os(monkeypatch, tool_policy, name="nt")
++ monkeypatch.setattr(tool_policy.sys, "executable", r"C:\Program Files\Python\python.exe")
++ command, reason = tool_policy.check_bash_command('python -c "print(1)"')
++ assert reason is None
++ assert command.startswith('"C:\\Program Files\\Python\\python.exe" ')