Repository navigation
Studio: permission levels for chat tool calls (Ask, Approve for me, Off, Full access) - #7079
Conversation
…ff, Full access) Replace the Bypass permissions on/off toggle with a four level permission selector, available in Settings > General (new Permissions section above Notifications), the chat settings panel, the composer plus menu, and a new always visible composer pill. Levels: - Ask for approval: every local tool call pauses for allow/deny. - Approve for me: only calls detected as potentially unsafe pause; the python/terminal sandbox stays on. - Off: never pauses; sandbox stays on (previous default behavior). - Full access: never pauses and the sandbox is disabled. Still requires the danger confirmation and is never restored across reloads. Backend adds permission_mode to the OpenAI compatible and Anthropic passthrough payloads and threads it through both tool loops. Auto mode uses a fail closed classifier in tools.py: terminal commands must be on a read only allowlist with no redirection or substitution, python code is AST scanned for writes, exec, process and network use, MCP tools auto run only with read only style names. Unknown tools always ask. Legacy bypass_permissions and confirm_tool_calls keep their exact behavior for existing API callers.
There was a problem hiding this comment.
Code Review
This pull request introduces a granular permission system for local tool execution, offering four modes: "Ask for approval", "Approve for me" (auto-detecting unsafe actions), "Off" (run automatically inside the sandbox), and "Full access" (bypass permissions and disable the sandbox). The changes span backend safety classifiers, API models, routes, frontend composer pills, settings dropdowns, and state management. Feedback on the implementation highlights a potential security bypass in the Python AST safety classifier where indirect references and import aliases are not flagged as unsafe, the need for corresponding unit tests to cover these bypass patterns, and an HTML validation issue in the new composer pill component where an interactive element is nested inside a button.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| 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 | ||
| elif isinstance(node, ast.Call): | ||
| func = node.func | ||
| if isinstance(func, ast.Name): | ||
| if func.id in {"exec", "eval", "__import__", "breakpoint"}: | ||
| return True | ||
| if func.id == "open" and _open_call_writes(node): | ||
| return True | ||
| elif isinstance(func, ast.Attribute): | ||
| if func.attr in _AUTO_UNSAFE_PY_ATTRS: | ||
| return True | ||
| if func.attr == "open" and _open_call_writes(node): | ||
| return True |
There was a problem hiding this comment.
The current AST-based safety classifier in _python_is_potentially_unsafe only checks ast.Attribute and ast.Name nodes when they are the direct func of an ast.Call node. This creates significant safety bypasses for "Approve for me" (auto) mode.
For example, the following patterns will be incorrectly classified as safe and execute without any approval prompt:
- Import alias bypass:
from os import remove remove('file')
- Indirect reference/assignment bypass:
f = os.remove f('file')
To fix this and ensure a robust "fail-closed" safety classifier, we should check ast.Attribute and ast.ImportFrom aliases at the top level of ast.walk to catch any reference to unsafe attributes or imports, and check ast.Name for unsafe built-ins. Additionally, we must wrap the AST traversal logic in a try...except block to prevent malformed files or unexpected structures from propagating unhandled exceptions and crashing the application.
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
for alias in node.names:
if alias.name in _AUTO_UNSAFE_PY_ATTRS or alias.name in {"exec", "eval", "__import__", "breakpoint"}:
return True
elif isinstance(node, ast.Attribute):
if node.attr in _AUTO_UNSAFE_PY_ATTRS:
return True
elif isinstance(node, ast.Name):
if node.id in {"exec", "eval", "__import__", "breakpoint"}:
return True
elif isinstance(node, ast.Call):
func = node.func
if isinstance(func, ast.Name):
if func.id == "open" and _open_call_writes(node):
return True
elif isinstance(func, ast.Attribute):
if func.attr == "open" and _open_call_writes(node):
return True
except Exception:
return TrueReferences
- Wrap AST parsing and traversal logic (such as
ast.parseandast.walk) of third-party or external files in atry...exceptblock to prevent malformed files or unexpected structures from propagating unhandled exceptions and crashing the application.
| ("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), | ||
| ], | ||
| ) |
There was a problem hiding this comment.
To prevent regressions and ensure the safety classifier robustly handles indirect references and import aliases, we should add test cases for these bypass patterns to test_python_classifier.
@pytest.mark.parametrize(
("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), # import alias bypass
("f = os.remove\nf('x')", True), # indirect reference bypass
],
)| <button | ||
| type="button" | ||
| className="composer-pill-btn" | ||
| 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> |
There was a problem hiding this comment.
Nesting an interactive element (like a span with role="button") inside a <button> is invalid HTML according to the W3C HTML specifications and can cause issues with screen readers, keyboard navigation, and click event propagation.
Since DropdownMenuTrigger supports asChild, we can change the outer element from a <button> to a <div> (with role="combobox" for accessibility) and use a standard <button> for the inner close/off switch. This maintains the exact same visual styling and behavior while producing valid, accessible HTML.
<div
role="combobox"
aria-haspopup="listbox"
className="composer-pill-btn cursor-pointer"
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. */}
<button
type="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" />
</button>
<span>{active.label}</span>
<HugeiconsIcon
icon={ChevronDownStandardIcon}
strokeWidth={1.5}
className="composer-pill-caret size-[15px]"
/>
</div>
There was a problem hiding this comment.
Valid accessibility point. This is a frontend-structural change (Radix trigger plus keyboard/focus semantics), so I would rather handle it in a dedicated pass that can be typechecked and eyeballed than restructure the pill blind in this round.
Off moves to the bottom of the level menu with a short description and acts as the feature-off state: the composer pill is hidden entirely while Off, and reselecting the active level toggles back to Off.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fbf9d936b5
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| confirm_tool_calls = bool(payload.confirm_tool_calls) | ||
| and not bool(payload.bypass_permissions), | ||
| bypass_permissions = bool(payload.bypass_permissions), | ||
| permission_mode = payload.permission_mode, |
There was a problem hiding this comment.
Treat Full access as bypass before stream validation
Passing permission_mode only into the generator is too late for non-streaming tool requests: the guard above still rejects confirm_tool_calls=true unless bypass_permissions is explicitly true. A client using the new supported permission_mode: "full" value, which is documented as equivalent to bypass, will get a 400 before the loop can normalize it, unlike bypass_permissions=true; please fold permission_mode == "full" into the route-level bypass checks here and in the safetensors path.
Useful? React with 👍 / 👎.
| if base in _AUTO_SAFE_WRAPPERS: | ||
| prefix_pending = True | ||
| continue | ||
| if base not in _AUTO_SAFE_TERMINAL_COMMANDS: | ||
| return True |
There was a problem hiding this comment.
Fail closed on mutating flags of allowlisted commands
In auto mode this treats an allowlisted command token as read-only without inspecting arguments for commands whose flags can mutate state. For example, find . -delete contains only the allowlisted find command and no redirection/substitution, so it runs without an approval prompt even though it deletes files in the sandbox workdir; please add per-command unsafe flag checks or fail closed for these tools.
Useful? React with 👍 / 👎.
| confirm_tool_calls: | ||
| permissionMode === "ask" || permissionMode === "auto", |
There was a problem hiding this comment.
Preserve RAG autoinject in auto mode
When the default auto permission mode is active this sends confirm_tool_calls: true, but both local tool loops skip forced RAG autoinject whenever confirm_tool_calls is true. Fresh installs using Approve for me with Docs enabled therefore no longer get first-pass KB retrieval even though search_knowledge_base is classified safe and would not prompt; derive the autoinject skip from the actual confirmation need rather than the broad gate request.
Useful? React with 👍 / 👎.
| 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[Literal["ask", "auto", "off", "full"]] = Field( |
There was a problem hiding this comment.
Let unknown permission modes reach normalization
The tool loops explicitly normalize unrecognized modes to ask, and the new behavior is documented as unknown modes falling back safely, but this Literal rejects any unknown string during request validation with a 422 before that normalization can run. Direct clients with a stale or typoed permission_mode fail instead of getting the safe ask fallback; accept a string here and normalize after validation (same issue exists on the Anthropic request field).
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Kept as-is by design: permission_mode is a strict Literal, so an unknown or typo'd mode is a clear 422 at the API boundary rather than a silent coercion. Callers that omit the field still normalize None to ask inside the loops.
| 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), |
There was a problem hiding this comment.
Enable confirmation when Anthropic permission mode asks
This threads permission_mode into the GGUF loop but never passes confirm_tool_calls, and the loop only gates when confirm_tool_calls is true. For Anthropic Messages server-tool requests with permission_mode: "ask" or "auto" and local tools enabled, tool calls still run immediately instead of pausing as the new request field describes; derive/pass the confirm flag for ask/auto or reject those modes.
Useful? React with 👍 / 👎.
| elif isinstance(node, ast.ImportFrom): | ||
| if node.module and node.module.split(".")[0] in _AUTO_UNSAFE_PY_MODULES: | ||
| return True |
There was a problem hiding this comment.
Gate mutating Python functions imported by name
In auto mode this ImportFrom handling only checks the root module name, and later ast.Name calls only special-case exec/eval/open, so code such as from os import remove; remove('x') is treated as safe and runs without approval while deleting sandbox files. Track aliases imported from modules like os, pathlib, and shutil when the imported symbol is one of the mutating functions, or fail closed for those direct imports.
Useful? React with 👍 / 👎.
The permission pill uses a foreground based grey instead of the shared muted pill color, so it reads darker in light mode and lighter in dark mode. Full access keeps the danger yellow.
Chat settings panel: the Bypass permissions label sits on one line with a full width dropdown underneath, styled like the other panel selects. Tooltip shortened and wording uses Unsloth instead of Studio.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 57fc7e7f20
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| lexer = shlex.shlex(command, posix = True, punctuation_chars = ";&|()") | ||
| lexer.whitespace_split = True | ||
| tokens = list(lexer) |
There was a problem hiding this comment.
Treat newlines as command separators
In auto mode, a terminal command such as ls\ntouch x is tokenized with the newline discarded, so after the safe ls sets expect_command false, the later touch is treated as an argument rather than a new command and the call is auto-approved. Shells execute newlines as command separators, and mutating but unblocked commands like touch/mkdir can then change the sandbox workdir without the approval prompt auto mode is meant to require; normalize or split newlines as separators before classifying.
Useful? React with 👍 / 👎.
| if func.attr == "open" and _open_call_writes(node): | ||
| return True |
There was a problem hiding this comment.
Detect write modes for Path.open
Using the builtin open() signature for every .open() call misses pathlib.Path.open, where the first positional argument is the mode. In auto mode, code such as from pathlib import Path; Path('x').open('w').write('hi') is classified as read-only and runs without approval, even though it mutates files in the sandbox; handle Path.open-style mode positions or fail closed for attribute open calls with positional args.
Useful? React with 👍 / 👎.
Extend the Approve for me classifier to catch write and exec paths that slipped through: - terminal: sort -o, tree -o, xxd -r, find -exec/-execdir/-ok/-delete and find -fprint/-fprintf/-fls now ask; plain read-only forms still auto-run. awk is no longer allowlisted since its program can write and call system(). - python: from-imports of mutating names (from os import remove [as rm]) and star imports now ask. Found by a fuzz and edge-case simulation matrix; pinned in test_permission_mode.py.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 443818a09f
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| flag = token.split("=", 1)[0] | ||
| if flag in _AUTO_UNSAFE_COMMAND_FLAGS.get(current_command, ()): |
There was a problem hiding this comment.
Detect attached sort output flags before auto-approving
In auto mode this exact flag comparison misses valid short-option arguments attached to the flag, e.g. sort -o/tmp/out /tmp/in: flag becomes -o/tmp/out, so the write is treated as read-only and runs without approval. I checked GNU sort --help, which documents -o, --output=FILE as writing to a file and states mandatory option arguments apply to short options too, so this form is valid and mutates the sandbox; normalize attached short options such as -oFILE before the allowlist check.
Useful? React with 👍 / 👎.
| "unsloth_settings_active_tab", | ||
| // Chat runtime prefs | ||
| "unsloth_chat_auto_title", | ||
| "unsloth_chat_permission_mode", |
There was a problem hiding this comment.
Reset the legacy confirmation key with permission mode
Clearing only unsloth_chat_permission_mode leaves unsloth_chat_confirm_tool_calls behind, but loadPermissionMode() falls back to that legacy key when the new key is absent, and setPermissionMode() still writes it for ask/auto/off. If a user selects Off and then uses Reset all local preferences, the reset removes the new key but the leftover legacy false restores Off instead of the fresh Auto default, so tool calls remain unprompted after a reset; include the legacy key in this reset list too.
Useful? React with 👍 / 👎.
| if isinstance(func, ast.Name): | ||
| if func.id in {"exec", "eval", "__import__", "breakpoint"}: | ||
| return True | ||
| if func.id == "open" and _open_call_writes(node): | ||
| return True |
There was a problem hiding this comment.
Track Python aliases to mutating attributes
When mutating functions are assigned before being called, auto mode sees only a harmless ast.Name here and auto-approves the code: for example, import os; rm = os.remove; rm('x') deletes a sandbox file without the approval prompt. Since the classifier is intended to fail closed unless the call is provably read-only, track aliases assigned from unsafe attributes (or treat unknown Name calls derived from assignments as unsafe).
Useful? React with 👍 / 👎.
| if token in _SHELL_SEPARATORS or token in _SHELL_KEYWORDS_AS_SEP: | ||
| expect_command = True | ||
| prefix_pending = False | ||
| current_command = "" |
There was a problem hiding this comment.
Preserve find expressions while scanning unsafe flags
Fresh evidence after the new unsafe-flag checks: quoted or escaped find grouping tokens clear current_command here, so find . \( -name x -delete \) misses the later -delete flag and is treated as read-only. I checked find --help, which lists ( EXPR ) as expression operators and -delete as an action, so these parentheses are part of the find expression rather than shell command separators; keep the active find context for them so mutating actions still require approval.
Useful? React with 👍 / 👎.
| if name == "terminal": | ||
| return _terminal_is_potentially_unsafe(str(arguments.get("command", ""))) | ||
| if name == "python": | ||
| return _python_is_potentially_unsafe(str(arguments.get("code", ""))) |
There was a problem hiding this comment.
Don’t auto-approve host file reads as safe tools
In auto mode these classifiers can return safe for read-only terminal/Python file reads, but _bash_exec/_python_exec only set cwd, env, and rlimits; they do not chroot or mount-confine the filesystem. When the Studio process has host credentials reachable from the per-session ~/studio_sandbox/<id> workdir, commands such as cat ../../.ssh/id_rsa or print(open('../../.ssh/id_rsa').read()) run without the Ask prompt and can exfiltrate them; require sandbox-local/sensitive-path checks for file reads before auto-approving.
Useful? React with 👍 / 👎.
A shell runs each line as its own command, but shlex reads newlines as whitespace, so "ls\nrm -rf x" demoted rm to argument position and auto-ran. Normalize newlines and CR to separators, and treat any all separator token as a command boundary so runs of blank lines still split. Found by the simulation matrix; pinned in tests.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3c7009e08d
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| r"^(get|list|search|read|fetch|query|find|describe|show|view|lookup|" | ||
| r"retrieve|count|status|info|help|check)(?:[_\-].*)?$", |
There was a problem hiding this comment.
Fail closed for ambiguous MCP tool names
In auto mode this prefix-only regex auto-approves any MCP tool whose name starts with a read-like verb, even when the rest of the name is mutating. For example, common MCP methods such as get_or_create_issue, read_and_delete_file, or find_and_update_row all match here and run without the approval prompt, while MCP calls are not constrained by the local python/terminal sandbox and can mutate external systems. Please reject names containing mutating verbs anywhere in the tool name, or use explicit read-only metadata instead of prefix-only matching.
Useful? React with 👍 / 👎.
| confirm_tool_calls = bool(payload.confirm_tool_calls) | ||
| and not bool(payload.bypass_permissions), | ||
| bypass_permissions = bool(payload.bypass_permissions), | ||
| permission_mode = payload.permission_mode, |
There was a problem hiding this comment.
Let off mode bypass the non-stream confirm guard
Passing permission_mode only into the generator is too late for non-streaming direct API clients that send permission_mode: "off" with a stale confirm_tool_calls=true: the route-level guard above still rejects them with 400 before the loop can apply the documented/tested behavior that off never prompts and therefore does not need streaming. Please fold permission_mode == "off" into the no-confirm route check as well, and mirror the same fix in the safetensors path.
Useful? React with 👍 / 👎.
| if (option.value === permissionMode) { | ||
| setPermissionMode("off"); |
There was a problem hiding this comment.
Restore prior approval level when leaving Full access
When the current level is Full access, reselecting that row takes this branch before the Full-access confirmation branch and persists off. If a user normally runs in Ask/Auto, temporarily enables Full access, then clicks the active Full access row to disable it, subsequent unsafe tool calls run without prompts inside the sandbox instead of returning to the previous approval level; restore the stored non-full mode or use the existing bypass-off path for this case.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Intentional: reselecting the active row toggles to Off for every level (consistent behavior), and Off is strictly safer than Full since the sandbox comes back on. Leaving Full through its own row landing on Off is the intended path.
| elif isinstance(node, ast.Call): | ||
| func = node.func | ||
| if isinstance(func, ast.Name): | ||
| if func.id in {"exec", "eval", "__import__", "breakpoint"}: |
There was a problem hiding this comment.
Treat dynamic Python call targets as unsafe
In auto mode, a call such as import os; getattr(os, "remove")("x") is treated as safe: the inner getattr reaches this ast.Name branch and is not blocked, while the outer call's callee is an ast.Call and falls through entirely. That lets mutating functions delete sandbox files without the approval prompt; dynamic call targets like getattr/call-valued callees should fail closed unless proven read-only.
Useful? React with 👍 / 👎.
| "write_text", | ||
| "write_bytes", |
There was a problem hiding this comment.
Treat file-like write calls as unsafe
Auto mode catches Path.write_text/write_bytes, but not generic file-object .write() calls, so code such as import tempfile; tempfile.NamedTemporaryFile(delete=False).write(b"hi") creates and writes a sandbox file without any approval prompt. Since the classifier is supposed to ask for state-mutating Python code unless it is provably read-only, include file-like write calls or otherwise track writable file objects instead of allowing them by default.
Useful? React with 👍 / 👎.
Auto-mode (Approve for me) safety classifier hardening: - Python: flag any reference to a mutating attribute, not only direct calls, so indirect refs (f = os.remove; f(x)) and aliases ask. Detect Path.open(mode) write modes and wrap the AST walk to fail closed. - Terminal: match attached short output flags (sort -o/tmp/out) and keep find context across grouping parens so find ( -delete ) asks. - Both: ask before reads that escape the sandbox workdir via parent traversal or hit credential paths (.ssh, .aws, id_rsa, .pem, etc.). permission_mode plumbing: - Fold permission_mode=full into bypass_permissions at the request model so route-level confirm-gate guards see it as bypass. - Reject ask/auto on the Anthropic Messages server-tools path, which has no confirmation channel (mirrors the confirm_tool_calls rejection). - Keep forced RAG autoinject in auto mode: the safe search_knowledge_base retrieval never gates, so derive the skip from the real confirm need. - Reset all local preferences now also clears the legacy confirm key so a reset restores the fresh default instead of the old level. Regression tests added for each case.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3b20aa4f30
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if any(os.path.basename(t.strip(";&|()`{}")).lower() in ("find", "fd") for t in tokens): | ||
| find_flags = _AUTO_UNSAFE_COMMAND_FLAGS["find"] | ||
| if any(t.split("=", 1)[0] in find_flags for t in tokens): | ||
| return True |
There was a problem hiding this comment.
Require approval for fd exec flags
Fresh evidence after the new flag scan: this branch includes fd but only checks GNU find actions, so fd -x rm {} or fd --exec-batch rm is classified as read-only and auto-runs because the rm token is treated as an argument. I checked fd --help, which documents -x, --exec <cmd>... as executing a command for each result and says following positional arguments belong to that command; add fd's exec flags (-x, -X, --exec, --exec-batch) to the unsafe table or fail closed for them.
Useful? React with 👍 / 👎.
| checked={confirmToolCalls && permissionMode !== "full"} | ||
| onCheckedChange={setConfirmToolCalls} | ||
| disabled={bypassPermissions} | ||
| disabled={permissionMode === "full"} |
There was a problem hiding this comment.
Don’t present auto mode as always-confirm
When the persisted/default level is auto, confirmToolCalls is true, so this switch renders as on while the help text says every local tool call pauses for approval; in reality safe calls auto-run without a prompt. A user checking this setting can believe they are in the stricter Ask-for-approval mode even though the backend is approving read-only tools for them, so derive the checked state from permissionMode === "ask" or label the auto gate separately.
Useful? React with 👍 / 👎.
| if _PY_MODE_LITERAL_RE.match(first.value): | ||
| return bool(_PY_WRITE_MODE_RE.search(first.value)) | ||
| return False # a filename, not a mode: read |
There was a problem hiding this comment.
Treat os.open flags as mutating
In auto mode, import os; os.close(os.open("x", os.O_CREAT | os.O_WRONLY)) reaches this Path-style .open() heuristic, where the first string argument is treated as a filename and returns read-only. For os.open, however, the second argument is flags and O_CREAT/O_TRUNC can create or truncate sandbox files without any approval prompt; handle os.open separately or mark it unsafe unless the flags are provably read-only.
Useful? React with 👍 / 👎.
Auto mode ("Approve for me") let a few mutating calls through as safe:
- os.open(...) always creates/writes a descriptor, so treat it as unsafe
even though builtin open in read mode stays safe.
- fd -x/--exec/-X/--exec-batch runs a command per match; scan for these
alongside find's -exec/-delete.
- tempfile writes artefacts and hands back writable handles, so importing
it now asks.
- Calling the result of a call (getattr(os, "remove")("x"), partials) is a
dynamic target the AST can't vet, so fail closed.
- An MCP tool whose name pairs a read verb with a mutating one
(get_or_create_issue, read_and_delete_file) no longer auto-runs on the
read prefix alone.
Also fold permission_mode="off" into confirm_tool_calls=False on both
request models so the non-stream route guard sees the disabled gate, and
drive the Confirm tool calls toggle off permission_mode="ask" so auto no
longer shows it on.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 668a6cc556
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if ( | ||
| func.attr == "open" | ||
| and isinstance(func.value, ast.Name) | ||
| and func.value.id == "os" | ||
| ): |
There was a problem hiding this comment.
Track aliases before treating os.open as safe
Fresh evidence after the new os.open special case: it only matches calls whose receiver is literally named os, so import os as o; o.open('out.txt', o.O_CREAT) falls through to the generic .open() heuristic, treats 'out.txt' as a filename, and is auto-approved even though it creates a file in the sandbox. Track os aliases/from-imported os.open, or fail closed when an attribute open call has extra positional arguments that may be flags/modes.
Useful? React with 👍 / 👎.
| "symlink", | ||
| "link", |
There was a problem hiding this comment.
Include pathlib link methods in unsafe attributes
In auto mode the Python scanner only blocks attribute names listed here; it includes os.symlink/os.link but not pathlib's Path.symlink_to, Path.hardlink_to, or Path.link_to. Code such as from pathlib import Path; Path('link').symlink_to('target') is therefore classified as read-only and runs without approval while mutating the sandbox filesystem; add the pathlib link method names or fail closed for these Path mutators.
Useful? React with 👍 / 👎.
| if isinstance(node, ast.Import): | ||
| for alias in node.names: | ||
| if alias.name.split(".")[0] in _AUTO_UNSAFE_PY_MODULES: | ||
| return True |
There was a problem hiding this comment.
Fail closed on importlib-loaded unsafe modules
In auto mode, import importlib; sp = importlib.import_module('subprocess'); sp.run(['touch', 'x']) is classified as safe: this check only catches literal import subprocess, and the later sp.run call is not one of the unsafe attributes. Because the Python sandbox's static safety check also allows this pattern, dynamically importing modules such as subprocess or requests can spawn processes or use the network without the approval prompt; detect importlib.import_module() for unsafe module names or fail closed on those dynamic imports.
Useful? React with 👍 / 👎.
| # ask/auto need the confirmation gate, which this passthrough has no | ||
| # channel for (same limitation as confirm_tool_calls above). Reject | ||
| # them rather than silently running tools unprompted. off/full are fine. | ||
| if getattr(payload, "permission_mode", None) in ("ask", "auto"): |
There was a problem hiding this comment.
Normalize bypass before rejecting Anthropic modes
When an Anthropic Messages server-tool request carries legacy bypass_permissions=true together with a stale/default permission_mode: "auto" or "ask", this guard still rejects the request even though bypass is documented and normalized elsewhere as the permissive Full-access mode. Direct clients that send both fields cannot use bypass for Anthropic tool calls; skip this rejection when bypass is true, or normalize permission_mode to full before this check.
Useful? React with 👍 / 👎.
| "mkdir", | ||
| "makedirs", | ||
| "truncate", |
There was a problem hiding this comment.
Add os node and metadata mutators to auto checks
Auto mode omits several os filesystem mutators from this attribute list, so code like import os; os.mkfifo('pipe'), os.mknod('node'), or os.utime('x', None) is treated as read-only and runs without approval while creating filesystem nodes or changing file metadata in the sandbox. Add these mutators to the unsafe set, or fail closed for unclassified os attributes that can modify the filesystem.
Useful? React with 👍 / 👎.
|
Pushed another pass over the auto-mode ("Approve for me") classifier from the review notes. All of these were reproduced first, then fixed, then covered with tests:
A couple of notes on the remaining suggestions I did not take:
Verified locally with the permission_mode test suite plus a separate isolated simulation harness (classifier fuzzing, the full mode x confirm x safe/unsafe matrix driving the real tool loop, and a store-invariant check). Source lint, Frontend build, Chat UI, and Studio API checks are green. |
|
Reviewed and validated this end to end: local backend test suites, cross platform staging CI on Linux, macOS and Windows, and a live Studio walkthrough on both Before / afterThe old on/off bypass toggle is replaced by an always visible permission level on the composer, plus a new Permissions section in Settings. The four levelsAsk for approval, Approve for me (the fresh install default), Off, and Full access, all selectable from the composer pill or Settings. Full access still requires the explicit confirmation dialog everywhere: Settings, General, Permissions: Validation
Auto mode classifierThe fail closed classifier looks good after the recent hardening pass. A few narrow cases still auto run in Approve for me when they should ask. All are bounded by the still active sandbox, so they weaken the prompt and not the sandbox, and none are blockers:
A few small non classifier items too: the Anthropic Messages path rejects Overall this looks good to me. Happy to push the classifier and small fixes if you want them folded in here. |
Approve for me now asks for a few cases it previously auto-ran: - os.open via an os alias (import os as o; o.open(path, O_CREAT)) - pathlib symlink_to / hardlink_to / link_to - importlib.import_module dynamic imports - os.mkfifo / os.mknod / os.utime Also fold bypass_permissions into full when a stale ask/auto permission_mode is sent alongside it, so the Anthropic route guard no longer 400s those legacy callers. Adds classifier and request-model regression tests.
|
Pushed a small follow up in e3654b8. Auto mode ("Approve for me") now asks for a few cases that previously auto ran, all fail closed additions:
I also folded Added classifier and request model tests. The permission suites pass locally ( I left two items alone on purpose: reselecting the active Full access row to turn it off is the intended behavior you called out, and the composer pill nesting an interactive element inside a button is a frontend structural change I would rather do in its own pass so it can be typechecked and looked at visually. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e3654b8808
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| confirm_tool_calls = bool(payload.confirm_tool_calls) | ||
| and not bool(payload.bypass_permissions), | ||
| bypass_permissions = bool(payload.bypass_permissions), | ||
| permission_mode = payload.permission_mode, |
There was a problem hiding this comment.
Derive confirmation from permission_mode
When a direct /chat/completions client sends permission_mode: "ask" or "auto" but leaves the legacy confirm_tool_calls field omitted/false, this still passes confirm_tool_calls=False into the GGUF loop, so the loop never creates approval IDs and a non-streaming request can run local tools without the requested gate. The safetensors path uses the same predicate at lines 8232-8235; derive the gate from permission_mode in ("ask", "auto") or reject those modes without streaming/confirmation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2809db6: ask/auto self-enable the confirmation gate at the request model, so a direct /chat/completions caller that omits confirm_tool_calls can no longer run tools ungated. Non-streaming ask/auto now hits the streaming-required guard instead of running unprompted.
| base = os.path.basename(token.strip(";&|()`{}")).lower() | ||
| stem, ext = os.path.splitext(base) | ||
| if ext in {".exe", ".com", ".bat", ".cmd"}: | ||
| base = stem | ||
| if base in _AUTO_SAFE_WRAPPERS: |
There was a problem hiding this comment.
Reject path-qualified commands in auto mode
Because this strips a command-position token down to its basename before the safe-command allowlist is applied, auto mode treats ./ls or /tmp/cat as the trusted read-only utilities. In a sandbox workdir containing a user- or repo-provided executable with an allowlisted name, the shell executes that file without an approval prompt, and _bash_exec only applies cwd/env/blocklist rather than confining what the executable can do; require pathless trusted commands or resolve to known system binaries before auto-approving.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2809db6: a path-qualified command token (./ls, /tmp/cat) now asks instead of matching the trusted utility its basename resolves to.
| _AUTO_UNSAFE_COMMAND_FLAGS = { | ||
| "sort": frozenset({"-o", "--output"}), |
There was a problem hiding this comment.
Require approval for ripgrep preprocessors
This unsafe-flag table does not cover rg --pre, so auto mode approves commands like rg --pre 'sh -c "touch x; cat \"$1\""' needle . after seeing only the allowlisted rg token and then ignoring the preprocessor command as an argument. I checked rg --help, which says --pre=COMMAND searches the stdout of COMMAND PATH and warns that it spawns a process for every searched file, so this flag can execute arbitrary commands and should require approval.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2809db6: rg --pre and --hostname-bin are on the unsafe-flag table now, so auto mode asks before running a ripgrep preprocessor (rg stays on the read-only allowlist otherwise).
Approve for me now asks for cases the review surfaced: - builtin open aliased to a name (f = open; from builtins import open as w) or looked up dynamically (globals()['open']) - pickle / marshal / shelve / dill deserialization - io.FileIO write handles - sort --compress-program (runs an external program) - MCP names carrying save/archive/submit/commit/push/sync/register verbs Also refine the attribute open() write check so an explicit read mode (ZipFile.open(name, "r")) stays auto while os.open flags still ask. Adds test coverage for each case.
|
Ran a broader review pass and pushed 70b537e closing the real auto-mode gaps it turned up. "Approve for me" now asks for:
I also tightened the attribute Two things I looked at and deliberately did not change:
Still worth a small frontend pass (separate from this so it can be typechecked and eyeballed): the composer pill returns |
- rg runs an arbitrary program per file via --pre / --hostname-bin, so "Approve for me" now asks for those flags (rg is on the read-only allowlist). - A path-qualified command token (./ls, /tmp/cat) is an arbitrary executable, not the trusted utility its basename matches, so it asks before running. - A direct /chat/completions caller that sets permission_mode ask/auto but omits the legacy confirm_tool_calls flag now self-enables the confirmation gate, so tools can no longer run ungated on that path. Adds classifier and request-model tests for each case.
|
Pushed 2809db6 closing the last three auto-mode gaps the latest review pass turned up. "Approve for me" now asks for:
It also makes Triage of the rest: the classifier and backend items are all resolved on the current head. Three I left as intentional or deferred, with a note on each thread:
|
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 430c3c3e82
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| 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?:|/)|" |
There was a problem hiding this comment.
Gate meta-refresh navigations in auto mode
When artifact network access is enabled, a render_html call can navigate the sandboxed preview frame with declarative HTML such as <meta http-equiv="refresh" content="0;url=https://example.com">, but this network detector only covers JS navigation sinks and resource attributes, so permission_mode="auto" classifies that canvas as static and runs it without approval. Since render_html is meant to prompt for networked canvases, include meta-refresh URL detection or otherwise fail closed before auto-approving.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2e1f5f7. _RENDER_HTML_NETWORK_RE now matches a <meta http-equiv=refresh ...> tag that carries a url= target, so an auto-mode canvas that navigates the frame to an external origin asks. A bare content="30" self-reload with no url stays safe. Regression rows added in test_permission_mode.py.
| "to_csv", | ||
| "to_parquet", | ||
| "to_pickle", | ||
| "to_json", | ||
| "to_feather", | ||
| "to_hdf", | ||
| "to_excel", | ||
| "to_stata", | ||
| "to_sql", | ||
| "to_xml", |
There was a problem hiding this comment.
Include pandas HTML exporters in auto gating
In permission_mode="auto", Python calls are approved unless their method name appears in this writer set. The adjacent pandas serializers are covered, but DataFrame.to_html("report.html") (and similar path-or-buffer exporters omitted here) writes a file while not matching any unsafe attribute, so it runs without the approval prompt that other file writes get. Add the missing pandas writer methods or gate these APIs by their path/buffer argument before auto-approving them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2e1f5f7. to_html, to_markdown, to_latex, to_clipboard, and to_gbq now sit in _AUTO_UNSAFE_PY_WRITE_METHODS alongside to_xml/to_csv, so df.to_html('report.html') asks. Display-only to_dict()/to_string() stay safe. Regression rows added.
| or _dynamic_name_hits_sensitive(folded) | ||
| or _glob_token_sensitive(folded) |
There was a problem hiding this comment.
Treat absolute Python globs as host directory reads
This path check only treats globs as unsafe when they could resolve to a credential target, so Path('/home').glob('*') or glob.glob('/home/*') can enumerate host directories outside the sandbox without an auto-mode prompt. The same classifier already gates os.listdir('/home') and Path('/etc').iterdir() as host directory reads, so absolute/tilde glob roots should be gated the same way before auto-approving Python tool calls.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2e1f5f7. The directory-enumeration check now also covers glob/rglob/iglob: Path('/home').glob('') and glob.glob('/home/') fold to an absolute root and ask, the same as iterdir/scandir/listdir/walk. A relative pattern like glob.glob('src/*.py') stays safe. Regression rows added.
| "md5sum", | ||
| "shasum", | ||
| "sha1sum", | ||
| "sha256sum", | ||
| "cksum", |
There was a problem hiding this comment.
Prompt before checksum manifests read hidden paths
These checksum commands are allow-listed without treating verification mode as unsafe, but md5sum/sha256sum/shasum/cksum -c read a checksum manifest and then read each named file (their help says -c, --check reads checksum files and checks them). If a manifest in the sandbox names /etc/passwd or another sensitive path, sha256sum -c list is auto-approved because the literal command only mentions list; add -c/--check to the unsafe flags for these tools so indirect host-file reads prompt first.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2e1f5f7. _AUTO_UNSAFE_COMMAND_FLAGS now flags -c/--check for md5sum/sha1sum/sha256sum/shasum/cksum, so sha256sum -c manifest (which reads an arbitrary checklist of paths) asks. Plain sha256sum data.bin stays read-only. Regression rows added.
… absolute glob roots, and checksum verify mode
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
# Conflicts: # .github/workflows/studio-inference-smoke.yml # .github/workflows/studio-mac-inference-smoke.yml # .github/workflows/studio-windows-inference-smoke.yml
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cb46bc0938
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| 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) |
There was a problem hiding this comment.
Treat starred open() args as unsafe
In auto permission mode, a Python call such as open(*('result.txt', 'w')).write('x') reaches this helper with a single ast.Starred positional argument, so mode stays None and the classifier treats the call like a read-only open(). Because the sandbox still permits writes inside the session/project workdir, "Approve for me" will skip the approval prompt for a file mutation; starred positional args should be treated as opaque/write-capable, similar to **kwargs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7e79998: a starred positional splat in builtin open() is now treated as write-capable, symmetric to the existing kwargs-splat rule, so open(*('result.txt','w')).write('x') asks. Added regression tests.
| # builtins.exec / builtins.eval are dynamic code execution. | ||
| if ( | ||
| node.attr in ("exec", "eval") | ||
| and isinstance(node.value, ast.Name) | ||
| and node.value.id in builtins_aliases | ||
| ): |
There was a problem hiding this comment.
Treat builtins.import as unsafe
In auto permission mode, this catches builtins.exec/eval but misses __builtins__.__import__, so code like m=__builtins__.__import__('subprocess'); m.run(['touch','x']) is classified safe and also bypasses the existing import/subprocess static checks because there is no import subprocess node. That lets a Python tool spawn processes and mutate the sandbox/project workdir without the approval prompt that auto mode is supposed to require for process modules.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7e79998: the builtins attribute check now covers import (plus breakpoint and compile) alongside exec and eval, matching the bare-name path, so builtins.import('subprocess') asks and dodges nothing. Added regression tests; benign builtins.print stays safe.
| # Bracket-access obfuscation: window['fetch'](...), self["open"](...). | ||
| r"\[\s*[\"'](?:fetch|open|XMLHttpRequest|WebSocket|EventSource|importScripts|" | ||
| r"sendBeacon|serviceWorker)[\"']\s*\]|" |
There was a problem hiding this comment.
Detect computed render_html network sinks
For render_html in auto mode, the network prompt can be bypassed with computed property access such as window['fet'+'ch']('https://attacker.example'): the regex only matches literal fetch or literal bracket keys, so the call is classified as static and runs without approval. When artifact network access is enabled, this allows network-capable canvas code to execute in the preview without the safety prompt this classifier is meant to enforce.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7e79998: a computed bracket key spliced with string concatenation on a global host object (window'fet'+'ch') now matches, while a plain obj['a'+'b'] key and inline-SVG canvases stay safe. Added regression tests.
| # procfs leaks a (possibly parent) process env/args/memory to a read, | ||
| # including the per-thread aliases under /proc/<pid>/task/<tid>/. | ||
| r"|/proc/[^/\s'\"]+/(?:task/[^/\s'\"]+/)?(?:environ|cmdline|mem|maps)\b" |
There was a problem hiding this comment.
Include /proc fd links in sensitive path checks
In auto permission mode, reads through /proc/<pid>/fd/<n> are currently classified as safe because this procfs pattern only covers env/args/memory/map files. A terminal or Python tool can therefore read another same-UID process's open file descriptor (for example a server-held credential or database file) without approval, even though this is the same kind of host/procfs escape the sensitive-path gate is intended to pause.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7e79998: added fd to the procfs alternation so a /proc/PID/fd/N read (and the per-thread task alias) asks, while /proc/cpuinfo and the fdinfo entries stay safe. Added terminal and python regression tests.
…r_html sinks, and procfs fd reads in auto mode
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7e79998f82
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| r"\bfetch\s*\(|" | ||
| r"XMLHttpRequest|" | ||
| r"\bWebSocket\b|" | ||
| r"\bEventSource\b|" | ||
| r"\bsendBeacon\b|" | ||
| r"\bimportScripts\b|" | ||
| r"navigator\s*\.\s*serviceWorker|" |
There was a problem hiding this comment.
Gate worker-backed canvases before auto-running
When artifact network access is enabled, worker-src http: https: blob: allows new Worker("https://...") or new SharedWorker("https://...") to fetch and execute remote scripts, but the auto-mode network detector only matches fetch, XHR, WebSocket, importScripts, URL attributes, etc. As a result, a render_html call containing a remote Worker is classified as safe and runs without the approval prompt that this mode is supposed to require for networked canvases.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f6a6ff1: added a new Worker(...) / new SharedWorker(...) constructor branch to the render_html network detector, gated like importScripts/serviceWorker (reachable under the worker-src http: https: blob: preview CSP). A var merely named myWorker or an unrelated new WorkerPool(...) stays static. Added regression tests.
| "requests", | ||
| "urllib", | ||
| "urllib3", | ||
| "http", | ||
| "httpx", |
There was a problem hiding this comment.
Prompt on Hugging Face Hub network calls
In auto mode, Python snippets such as from huggingface_hub import hf_hub_download; hf_hub_download(...) are not caught by this network-module list, and the sandbox static check only has special handling for Hugging Face upload methods. Because huggingface_hub is available in this app and downloads contact the network and populate a cache under the sandbox workdir, these calls run without the approval prompt that auto mode is supposed to require for Python network activity.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f6a6ff1: added huggingface_hub to the auto-mode network-module set, so import huggingface_hub and from huggingface_hub import hf_hub_download / snapshot_download ask (network fetch plus on-disk cache write). Added regression tests; a benign non-network import stays safe.
| if ( | ||
| func.id in invoker_aliases | ||
| and node.args | ||
| and _wraps_write_callable(node.args[0]) | ||
| ): | ||
| return True |
There was a problem hiding this comment.
Gate write callables passed through user helpers
The auto classifier only treats write-capable callables as unsafe when they are handed to the hard-coded higher-order helpers here, so a user-defined helper bypasses the prompt, e.g. def run(fn): fn("out.txt", "w").write("x"); run(open). In that case the function body contains fn(...) rather than an open alias and the call site is not map/starmap/etc., so auto mode executes a file write in the sandbox without the approval prompt intended for Python writes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f6a6ff1: a concrete write callable (open/writer/archive-ctor alias or a writer/mutating attribute) handed as an argument to any call now asks, so def run(fn): fn('o','w').write('x'); run(open) is gated the same way the map/starmap/reduce branches already are. A dedicated narrower check omits the fail-closed dynamic/getattr poison aliases so benign passes like run(len) and printing a getattr/subscript result stay safe. Added regression tests.
…rite callables passed to user helpers in auto mode
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Resolve three conflicts against the newer main (permission-mode work, unslothai#7079): keep both the tool-output-scope exports and PermissionModeDropdown in chat/index.ts; in the GGUF loop keep main's permission-mode normalization and the expanded tools import alongside the stream_tool_execution wrapper (thread_id and cancel_event still threaded); union the sandbox_site dir constant with main's auto-mode safety-detection block in tools.py.
…ic message (#8023) * Do not let the default tool policy reject every plain Anthropic message `unsloth studio run` resolves the server-side tool policy to on unless --disable-tools (resolve_tool_policy: "tools default on for every bind", ce193c2). The permission gate added in #7079 read that resolved policy as "this request selected server tools", so for an ordinary tool-free POST /v1/messages it collected the whole catalog, found terminal in it, saw no permission_mode, and returned 400. Every plain Anthropic chat request against a default server answered: permission_mode 'ask' has no confirmation channel for Anthropic Messages server tools A process-wide default is not a per-request selection. The gate now fires on an explicit ask only, enable_tools/mcp_enabled or an Anthropic server-tool type in `tools`, and --disable-tools still vetoes both. Everything the gate rejected because the request asked for something it cannot confirm still rejects: enable_tools with ask or an omitted mode, a bare terminal/python tool type, render_html, and ask for a safe-only selection. Nothing caught it because the four e2e cases that exercise this path live in tests/test_studio_api.py, which studio-backend-ci.yml ignores: they need a live model and a 2 GB GGUF download. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Route on the same predicate the permission gate uses Lifting the gate off the process default fixed the rejection but not its twin: the tool routing below decides server-tool mode from `_effective_enable_tools(payload)` too, so a tool-free request on a default server still entered the local tool loop with the full catalog, python/terminal/render_html included, and confirm_tool_calls unset. That is the execution this channel has no way to confirm, which is what the gate existed to stop. Deciding "did this request select server tools" twice is what let the two disagree, so both now call `_anthropic_selects_server_tools`. A tool-free request takes the plain chat path, an explicit enable_tools/mcp_enabled/server-tool type still routes to the loop under a mode that permits it, and --disable-tools or enable_tools=false still vetoes. * Drop mcp_enabled as a Messages-channel ask, and say where the CLI flag stops AnthropicMessagesRequest is extra="allow", so `mcp_enabled: true` really does arrive and pydantic serves it through __getattr__: reading it as intent routed such a request into a loop holding ALL_TOOLS' terminal/python and not one MCP tool, since nothing on this route loads MCP schemas. It is an ask on the OpenAI routes because those wire MCP discovery. Before this branch it did nothing here, so dropping it restores that. The CLI help and the tool_policy docstring said --enable-tools forces tools on for every request. On /v1/messages it no longer does, deliberately: that channel has no confirmation prompt, so the on direction has to come from the request. The off direction still applies everywhere. Documented rather than left to be discovered. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>





What this does
Replaces the Studio "Bypass permissions" on/off toggle with a four level permission selector for local chat tool calls (terminal, python, web search, RAG, MCP).
UI
Approve for me: unsafe call detection
is_potentially_unsafe_tool_call()intools.pyclassifies each call and fails closed:ls,cat,grep,find,head, ...) with benign wrappers (env,timeout,xargs, ...) forwarding to a checked target. Any redirection, backtick or$()substitution, or unlisted command asks first.open(),exec/eval, filesystem mutation attrs (os.remove,shutil.rmtree,Path.write_text, ...) and process/network modules (subprocess,socket,requests, ...) ask first. Anything the sandbox's static analysis already rejects also asks.get_*,list_*,search*, ...); mutating names (send_*,create_*,delete_*, ...) ask.The sandbox stays on in this mode, so detection only decides prompting; the blocklist and rlimits still apply at execution time.
Backend
permission_mode(ask/auto/off/full) added to the Chat Completions and Anthropic Messages payloads and threaded through both the GGUF and safetensors tool loops.fullandbypass_permissions=truenormalize to the same thing; unset or unknown modes behave asask.bypass_permissionsandconfirm_tool_callsAPI callers keep their exact behavior.Compatibility
Tests
New
tests/test_permission_mode.py(35 tests): classifier cases for terminal/python/MCP/unknown tools, plus loop level tests that auto gates only unsafe calls, ask gates everything, off never gates and keeps the sandbox, full never gates and drops the sandbox, and legacybypass_permissionsimplies full.test_permission_mode.py,test_bypass_permissions.py,test_tool_confirm_loop.py,test_sandbox_tools.py,test_secure_tools_execute.pyandtest_safetensors_tool_loop.pyall pass (900+ tests). Frontend typecheck, biome and i18n parity pass.