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: add an edit_file tool so agents stop rewriting whole files (#8753)

Michael Han3cb8ecce7828
diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.py
index b4ff82e7d26..d246e2da68a 100644
--- a/studio/backend/core/inference/tool_loop_controller.py
+++ b/studio/backend/core/inference/tool_loop_controller.py
@@ -261,6 +261,11 @@ def status_for_tool(tool_name: str, arguments: Mapping[str, Any]) -> str:
if tool_name == "terminal":
preview = str(arguments.get("command") or "")[:60]
return f"Running: {preview}" if preview else "Running command..."
+ if tool_name == "edit_file":
+ # The name, not the patch: the tool card below already shows the edit.
+ path = str(arguments.get("path") or "").strip()
+ name = path.replace("\\", "/").rstrip("/").rpartition("/")[2]
+ return f"Editing: {name}" if name else "Editing file..."
mcp = mcp_display_parts(tool_name)
if mcp:
return f"Calling: {mcp[0]} · {mcp[1]}"
@@ -277,6 +282,8 @@ def awaiting_approval_status(tool_name: str) -> str:
return "Waiting for approval: Python"
if tool_name == "terminal":
return "Waiting for approval: command"
+ if tool_name == "edit_file":
+ return "Waiting for approval: file edit"
mcp = mcp_display_parts(tool_name)
if mcp:
return f"Waiting for approval: {mcp[0]} · {mcp[1]}"
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index f729940f721..1a8ea33f910 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -4543,7 +4543,7 @@ def is_always_safe_tool(name: str) -> bool:
# Tools whose provisional card is only a text preview of the arguments, so it can stream
# while awaiting approval.
-_TEXT_PREVIEW_TOOLS = frozenset({"python", "terminal"})
+_TEXT_PREVIEW_TOOLS = frozenset({"python", "terminal", "edit_file"})
def has_text_only_provisional_card(name: str) -> bool:
@@ -4606,6 +4606,11 @@ def is_potentially_unsafe_tool_call(name: str, arguments: dict) -> bool:
return _terminal_is_potentially_unsafe(str(arguments.get("command", "")))
if name == "python":
return _python_is_potentially_unsafe(str(arguments.get("code", "")))
+ # Always writes, and python's open(..., "w") already prompts, so the cheaper
+ # tool must not become the quiet way around that. Stated rather than left to
+ # the fail-closed default, so a later clause cannot drop it.
+ if name == "edit_file":
+ return True
return True
@@ -8883,6 +8888,466 @@ def _remove_session_sandbox_locked(session_id: str, delete_files: bool) -> bool:
return False
+# edit_file
+#
+# Without it, changing a file means a whole-file `cat > f <<'EOF'` or
+# open(...).write(...): ~7.7k output tokens to rewrite a 500-line file that a
+# patch does in ~45, and anything the model fails to retype is lost.
+#
+# Exact-string replacement, not a unified diff: models corrupt @@ hunk headers
+# far more often than they mis-copy a literal snippet, and a bad header patches
+# the wrong place instead of failing. A missing or non-unique old_string is a
+# hard error naming the match count, so the retry is "add context".
+
+# The whole text is read to find the match, so the cap is on the file.
+_EDIT_FILE_MAX_BYTES = _env_int("UNSLOTH_STUDIO_EDIT_FILE_MAX_BYTES", 16 * 1024 * 1024)
+
+# Bounded receipt: lines alone are no bound, since one line of minified JS can
+# be the whole file, so characters are capped per line and over the receipt.
+_EDIT_FILE_DIFF_LINES = 40
+_EDIT_FILE_DIFF_LINE_CHARS = 200
+_EDIT_FILE_DIFF_CHARS = 4000
+# Lines either side of the first change that are handed to difflib. Diffing the
+# whole file would split it into one str per line: 8M of them at the 16MB cap.
+_EDIT_FILE_DIFF_WINDOW_LINES = 120
+
+
+def _edit_file_resolve(
+ raw_path: str, session_id: "str | None", disable_sandbox: bool
+) -> "tuple[str | None, str]":
+ """Resolve the model's path the way python/terminal resolve theirs.
+
+ Same rules as the sitecustomize shim: a code-interpreter habit prefix
+ (/mnt/data, /workspace, ...) keeps its suffix under the workdir, everything
+ else is relative to it. Containment is checked on the realpath, so a symlink
+ planted inside cannot reach out.
+ """
+ raw = (raw_path or "").strip()
+ if not raw:
+ return None, "Error: 'path' is required."
+ workdir = _get_workdir(session_id)
+ candidate = raw
+ # An absolute path already inside the workdir is a real path, not a habit
+ # one: a project rooted at /workspace/repo would otherwise have its own
+ # prefix stripped and be rejoined onto itself.
+ already_inside = os.path.isabs(raw) and not _is_outside_workdir(raw, workdir)
+ if not disable_sandbox and not already_inside:
+ for prefix in _MISSING_PATH_PREFIXES:
+ if candidate == prefix or candidate.startswith(prefix + "/"):
+ candidate = candidate[len(prefix) :].lstrip("/")
+ break
+ if not candidate:
+ return None, "Error: 'path' is required."
+ target = candidate if os.path.isabs(candidate) else os.path.join(workdir, candidate)
+ try:
+ target = os.path.realpath(target)
+ except (OSError, ValueError):
+ return None, f"Error: cannot resolve path '{raw}'."
+ # Full access runs python/terminal unsandboxed already; holding this one
+ # tool to the workdir would just push the model back to cat.
+ if not disable_sandbox and _is_outside_workdir(target, workdir):
+ return None, (
+ f"Error: '{raw}' is outside this conversation's working directory, "
+ "which is the only place edit_file can write. Use a relative path "
+ f"(for example '{os.path.basename(raw) or 'file.py'}')."
+ )
+ return target, ""
+
+
+def _edit_file_decode(data: bytes, path: str) -> "tuple[str, str, str, str]":
+ """Decode file bytes into (text, newline, bom, error).
+
+ ``text`` is normalized to \\n so an old_string with plain newlines still
+ matches a CRLF file; matching raw bytes would fail every edit of a
+ Windows-authored source. The original convention is returned so the write
+ puts it back instead of converting every line ending in the file.
+ """
+ bom = ""
+ if data.startswith(codecs.BOM_UTF8):
+ bom = codecs.BOM_UTF8.decode("utf-8")
+ data = data[len(codecs.BOM_UTF8) :]
+ try:
+ text = data.decode("utf-8")
+ except UnicodeDecodeError:
+ return "", "\n", "", f"Error: '{os.path.basename(path)}' is not UTF-8 text."
+ if "\x00" in text:
+ return "", "\n", "", f"Error: '{os.path.basename(path)}' is a binary file."
+ crlf = text.count("\r\n")
+ # Judged against the total so a file with a couple of stray CRs is still
+ # written back as LF; a mixed file is normalized to whichever dominates.
+ newline = "\r\n" if crlf and crlf * 2 >= text.count("\n") else "\n"
+ return text.replace("\r\n", "\n"), newline, bom, ""
+
+
+def _edit_file_write(
+ path: str,
+ text: str,
+ newline: str,
+ bom: str,
+ *,
+ expect: "bytes | None" = None,
+ workdir: "str | None" = None,
+) -> str:
+ """Write the new content, replacing the file atomically.
+
+ Sibling temp file then rename: an interrupted write must not leave a source
+ file half-replaced. The mode is carried over so an edit keeps the
+ executable bit.
+
+ ``expect`` are the bytes the edit was computed from, compared again here so
+ a file another chat rewrote meanwhile is not reverted to this call's stale
+ copy. ``workdir`` re-checks containment just before the rename, so a parent
+ swapped for a symlink after the path was resolved is caught.
+ """
+ payload = (bom + text.replace("\n", newline)).encode("utf-8")
+ directory = os.path.dirname(path) or "."
+ try:
+ os.makedirs(directory, exist_ok = True)
+ except OSError as exc:
+ return f"Error: cannot create directory for '{os.path.basename(path)}': {exc}"
+ tmp = ""
+ try:
+ fd, tmp = tempfile.mkstemp(dir = directory, prefix = ".unsloth_edit_")
+ with os.fdopen(fd, "wb") as fh:
+ fh.write(payload)
+ try:
+ shutil.copymode(path, tmp)
+ except OSError:
+ pass # new file, or a mode we cannot read; the default is fine
+ if workdir is not None and _is_outside_workdir(path, workdir):
+ return (
+ f"Error: '{os.path.basename(path)}' moved outside the working "
+ "directory while the edit was being prepared; nothing was written."
+ )
+ if expect is not None:
+ try:
+ with open(path, "rb") as fh:
+ current = fh.read(len(expect) + 1)
+ except OSError:
+ current = None
+ if current != expect:
+ return (
+ f"Error: '{os.path.basename(path)}' changed while this edit "
+ "was being prepared; nothing was written. Read it again and "
+ "redo the edit against the current contents."
+ )
+ os.replace(tmp, path)
+ tmp = ""
+ except OSError as exc:
+ return f"Error: cannot write '{os.path.basename(path)}': {exc}"
+ finally:
+ if tmp:
+ with contextlib.suppress(OSError):
+ os.remove(tmp)
+ return ""
+
+
+_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(,\d+)? \+(\d+)(,\d+)? @@")
+
+
+def _edit_file_shift_hunk(line: str, offset: int) -> str:
+ """Add ``offset`` to both line numbers in a @@ hunk header."""
+ match = _HUNK_HEADER_RE.match(line)
+ if not match:
+ return line
+ before_span = match.group(2) or ""
+ after_span = match.group(4) or ""
+ shifted = (
+ f"@@ -{int(match.group(1)) + offset}{before_span} "
+ f"+{int(match.group(3)) + offset}{after_span} @@"
+ )
+ return shifted + line[match.end() :]
+
+
+def _edit_file_line_window(text: str, index: int, lines: int) -> "tuple[int, int]":
+ """Offsets of a window of ``lines`` lines either side of ``index``."""
+ start = index
+ for _ in range(lines):
+ newline = text.rfind("\n", 0, start)
+ if newline == -1:
+ start = 0
+ break
+ start = newline
+ if start and text[start : start + 1] == "\n":
+ start += 1
+ end = index
+ for _ in range(lines):
+ newline = text.find("\n", end)
+ if newline == -1:
+ end = len(text)
+ break
+ end = newline + 1
+ return start, max(end, index)
+
+
+def _edit_file_receipt(
+ before: str,
+ old: str,
+ new: str,
+ name: str,
+ count: int,
+ change_at: int = 0,
+) -> str:
+ """A bounded unified diff of what changed.
+
+ Line-numbered so the model can confirm the edit landed where it meant. Two
+ separate bounds, because either alone leaks: difflib sees only a window
+ around the first change, and the generator is consumed lazily.
+ """
+ import difflib
+ import itertools
+
+ window_start, window_end = _edit_file_line_window(
+ before, change_at, _EDIT_FILE_DIFF_WINDOW_LINES
+ )
+ # The window is cut out of the old text and the replacement replayed on it,
+ # rather than a second window of the same LINE COUNT cut out of the new one.
+ # An edit that adds or removes lines shifts everything after it, so equal
+ # windows end on different text and difflib calls that a second hunk --
+ # deletions the edit never made, a window away from anything that changed.
+ window_end = max(window_end, change_at + len(old)) # keep the match whole
+ before_window = before[window_start:window_end]
+ # Right in both modes: without replace_all the file held exactly one match.
+ after_window = before_window.replace(old, new)
+ first_line = before.count("\n", 0, window_start) + 1
+ stream = difflib.unified_diff(
+ before_window.split("\n"),
+ after_window.split("\n"),
+ lineterm = "",
+ n = 2,
+ )
+ # drop the ---/+++ headers; the name is on the summary line
+ taken = list(itertools.islice(stream, 2 + _EDIT_FILE_DIFF_LINES + 1))[2:]
+ plural = "" if count == 1 else "s"
+ head = f"Edited {name} ({count} replacement{plural})"
+ if not taken:
+ return head
+ if len(taken) > _EDIT_FILE_DIFF_LINES:
+ # An exact remaining count would cost the full diff this avoids.
+ diff = taken[:_EDIT_FILE_DIFF_LINES] + ["... (more diff lines)"]
+ else:
+ diff = taken
+ diff = [
+ line
+ if len(line) <= _EDIT_FILE_DIFF_LINE_CHARS
+ else f"{line[:_EDIT_FILE_DIFF_LINE_CHARS]}... (+{len(line) - _EDIT_FILE_DIFF_LINE_CHARS} chars)"
+ for line in diff
+ ]
+ # difflib numbered the hunks against the window, so shift them back to real
+ # file lines; line 3 of a 9000-line file is worse than no numbers at all.
+ if first_line > 1:
+ diff = [_edit_file_shift_hunk(line, first_line - 1) for line in diff]
+ body = "\n".join(diff)
+ if len(body) > _EDIT_FILE_DIFF_CHARS:
+ body = body[:_EDIT_FILE_DIFF_CHARS] + "\n... (receipt truncated)"
+ return head + "\n" + body
+
+
+def _edit_file_replace_all(value: object) -> "bool | None":
+ """Read replace_all strictly; None means "not a boolean".
+
+ bool("false") is True, and models do emit the JSON string. Coercing it that
+ way turns the multi-match guard off and rewrites every occurrence.
+ """
+ if value is None:
+ return False
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str):
+ lowered = value.strip().lower()
+ if lowered in ("true", "1", "yes"):
+ return True
+ if lowered in ("false", "0", "no", ""):
+ return False
+ if isinstance(value, int):
+ return bool(value)
+ return None
+
+
+def _edit_file_create(
+ target: str,
+ new: str,
+ name: str,
+ newline: str,
+ workdir: "str | None" = None,
+) -> str:
+ """Handle the empty-old_string case: create a file, never clobber one.
+
+ A zero-byte file is writable here on purpose: refusing every existing target
+ would strand the model, since an empty old_string would be refused and no
+ other old_string can match an empty file.
+
+ The absent case is created with O_EXCL rather than checked and then written:
+ two chats sharing a workspace can both pass a lexists() check and the later
+ rename drops the earlier file. O_EXCL also gives the new file the usual
+ umask-derived mode, where a mkstemp temp file would leave it 0600.
+ """
+ payload = (new.replace("\n", newline)).encode("utf-8")
+ if not os.path.lexists(target):
+ directory = os.path.dirname(target) or "."
+ try:
+ os.makedirs(directory, exist_ok = True)
+ except OSError as exc:
+ return f"Error: cannot create directory for '{name}': {exc}"
+ if workdir is not None and _is_outside_workdir(target, workdir):
+ return (
+ f"Error: '{name}' moved outside the working directory while the "
+ "edit was being prepared; nothing was written."
+ )
+ flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
+ # Never follow a symlink planted at the final component in the meantime.
+ flags |= getattr(os, "O_NOFOLLOW", 0)
+ try:
+ fd = os.open(target, flags, 0o666)
+ except FileExistsError:
+ return (
+ f"Error: '{name}' was created by something else while this call "
+ "was preparing it; nothing was written."
+ )
+ except OSError as exc:
+ return f"Error: cannot write '{name}': {exc}"
+ try:
+ with os.fdopen(fd, "wb") as fh:
+ fh.write(payload)
+ except OSError as exc:
+ # ENOSPC partway through leaves the bytes that fit -- a file
+ # truncated mid-token -- and the retry the message asks for cannot
+ # clear it, since an empty old_string refuses a non-empty target.
+ # Removing the inode puts the retry back on the create path.
+ with contextlib.suppress(OSError):
+ os.remove(target)
+ return f"Error: cannot write '{name}': {exc}"
+ return f"Created {name} ({new.count(chr(10)) + 1 if new else 0} lines)"
+ try:
+ st = os.stat(target)
+ except OSError:
+ st = None
+ # Refused rather than measured: a FIFO reports st_size 0, so it fell into
+ # the zero-byte branch below, whose write reopens the target -- and open()
+ # on a FIFO with no writer blocks for ever.
+ if st is None or not S_ISREG(st.st_mode) or st.st_size:
+ return (
+ f"Error: '{name}' already exists. An empty 'old_string' only "
+ "creates a new file; to change this one, pass the exact text to "
+ "replace."
+ )
+ # Guarded like any other edit, so a chat that filled it in is not clobbered.
+ error = _edit_file_write(target, new, newline, "", expect = b"", workdir = workdir)
+ if error:
+ return error
+ return f"Created {name} ({new.count(chr(10)) + 1 if new else 0} lines)"
+
+
+def _edit_file(
+ arguments: dict,
+ session_id: "str | None" = None,
+ disable_sandbox: bool = False,
+) -> str:
+ """Replace an exact string in a file. See the notes above."""
+ old = arguments.get("old_string")
+ new = arguments.get("new_string")
+ # Checked, not coerced: str(None) would write the literal "None" into a file.
+ if not isinstance(old, str) or not isinstance(new, str):
+ return "Error: 'old_string' and 'new_string' must both be strings."
+ # A truncated emoji escape ("\ud83d") survives json.loads as a lone surrogate
+ # that cannot be encoded, and the UnicodeEncodeError the write raises is
+ # swallowed upstream into "Unknown tool: edit_file" -- the one answer that
+ # sends the model back to the whole-file rewrite. old_string needs no check,
+ # being only ever compared.
+ try:
+ new.encode("utf-8")
+ except UnicodeEncodeError:
+ return (
+ "Error: 'new_string' contains unpaired surrogate characters, usually "
+ "a half-written emoji; nothing was written. Send it again as plain text."
+ )
+ target, error = _edit_file_resolve(
+ str(arguments.get("path") or ""), session_id, disable_sandbox
+ )
+ if error:
+ return error
+ name = os.path.basename(target)
+ # Normalized for the same reason the file is, so the two can match.
+ old = old.replace("\r\n", "\n")
+ new = new.replace("\r\n", "\n")
+ replace_all = _edit_file_replace_all(arguments.get("replace_all"))
+ if replace_all is None:
+ return "Error: 'replace_all' must be true or false."
+ # Decided before the no-op check below, not after: both strings empty is the
+ # documented way to create __init__.py or .gitkeep, and read as "identical,
+ # nothing to change" it was refused, leaving no way to write a zero-byte
+ # file.
+ if not old:
+ return _edit_file_create(
+ target,
+ new,
+ name,
+ "\n",
+ workdir = None if disable_sandbox else _get_workdir(session_id),
+ )
+ if old == new:
+ return "Error: 'old_string' and 'new_string' are identical; nothing to change."
+ try:
+ st = os.stat(target)
+ except FileNotFoundError:
+ return f"Error: '{name}' does not exist. Pass an empty 'old_string' to create it."
+ except OSError as exc:
+ return f"Error: cannot read '{name}': {exc}"
+ if os.path.isdir(target):
+ return f"Error: '{name}' is a directory."
+ # A FIFO reads forever and a character device such as /dev/zero reads until
+ # memory runs out. Neither reports a useful st_size, and this path carries
+ # no timeout or cancel event, so the turn cannot be recovered.
+ if not S_ISREG(st.st_mode):
+ return f"Error: '{name}' is not a regular file."
+ if st.st_size > _EDIT_FILE_MAX_BYTES:
+ return (
+ f"Error: '{name}' is larger than "
+ f"{_EDIT_FILE_MAX_BYTES // (1024 * 1024)}MB; edit it with python instead."
+ )
+ try:
+ with open(target, "rb") as fh:
+ data = fh.read(_EDIT_FILE_MAX_BYTES + 1)
+ except OSError as exc:
+ return f"Error: cannot read '{name}': {exc}"
+ before, newline, bom, error = _edit_file_decode(data, target)
+ if error:
+ return error
+ count = before.count(old)
+ if count == 0:
+ return (
+ f"Error: 'old_string' was not found in {name}. It must match the "
+ "file byte for byte, including indentation. Read the file and copy "
+ "the text to replace out of it."
+ )
+ if count > 1 and not replace_all:
+ return (
+ f"Error: 'old_string' matches {count} places in {name}. Include "
+ "surrounding lines to make it unique, or pass replace_all=true to "
+ f"change all {count}."
+ )
+ after = before.replace(old, new) if replace_all else before.replace(old, new, 1)
+ error = _edit_file_write(
+ target,
+ after,
+ newline,
+ bom,
+ expect = data,
+ workdir = None if disable_sandbox else _get_workdir(session_id),
+ )
+ if error:
+ return error
+ # Windowed around the first replacement, rather than diffing the whole file.
+ return _edit_file_receipt(
+ before,
+ old,
+ new,
+ name,
+ count if replace_all else 1,
+ change_at = max(before.find(old), 0),
+ )
+
+
WEB_SEARCH_TOOL = {
"type": "function",
"function": {
@@ -9155,6 +9620,7 @@ TERMINAL_TOOL_FULL_ACCESS = {
},
}
+# edit_file is registered below, once its schema exists.
_FULL_ACCESS_TOOL_BY_NAME = {
"python": PYTHON_TOOL_FULL_ACCESS,
"terminal": TERMINAL_TOOL_FULL_ACCESS,
@@ -9162,11 +9628,11 @@ _FULL_ACCESS_TOOL_BY_NAME = {
def apply_full_access_tool_descriptions(tools: list[dict]) -> list[dict]:
- """Swap python/terminal for their Full access schemas.
+ """Swap python/terminal/edit_file for their Full access schemas.
- Only the two sandboxed built-ins are touched; web_search, render_html,
+ Only the sandboxed built-ins are touched; web_search, render_html,
search_knowledge_base and MCP tools are passed through untouched, and a list
- without either built-in is returned as-is so callers can apply this
+ without any of them is returned as-is so callers can apply this
unconditionally. The input list is never mutated -- ALL_TOOLS entries are
module globals shared across requests.
"""
@@ -9185,6 +9651,71 @@ def apply_full_access_tool_descriptions(tools: list[dict]) -> list[dict]:
return out if swapped else tools
+EDIT_FILE_TOOL = {
+ "type": "function",
+ "function": {
+ "name": "edit_file",
+ # The description does the steering: given the tool but no preference,
+ # a model keeps writing heredocs because that is what it was trained on.
+ "description": (
+ "Change a file by replacing an exact string in it. Prefer this over "
+ "rewriting a file with python or a shell heredoc: it sends only the "
+ "lines that change, so editing a large file costs a fraction of the "
+ "tokens and cannot drop the parts you did not retype. Read the file "
+ "first and copy old_string out of it verbatim, including indentation. "
+ "old_string must match exactly one place unless replace_all is true; "
+ "if it matches none or several you get an error and nothing is "
+ "written. Paths are relative to the working directory."
+ ),
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "File to edit, relative to the working directory.",
+ },
+ "old_string": {
+ "type": "string",
+ "description": (
+ "Exact text to replace, copied from the file. Pass an "
+ "empty string to create a new file."
+ ),
+ },
+ "new_string": {
+ "type": "string",
+ "description": "Text to put in its place.",
+ },
+ "replace_all": {
+ "type": "boolean",
+ "description": (
+ "Replace every occurrence instead of requiring a unique "
+ "match. Defaults to false."
+ ),
+ },
+ },
+ "required": ["path", "old_string", "new_string"],
+ },
+ },
+}
+
+# Appended, not substituted: the sandboxed text never claims absolute paths
+# fail, so there is nothing false to rewrite, only a capability to add. A model
+# that thinks it cannot reach a real checkout falls back to the whole-file rewrite.
+_EDIT_FILE_FULL_ACCESS_CLAUSE = (
+ " The code sandbox is disabled, so an absolute path resolves as written and "
+ "edits the real file there, anywhere the Unsloth Studio process can reach."
+)
+
+EDIT_FILE_TOOL_FULL_ACCESS = {
+ "type": "function",
+ "function": {
+ **EDIT_FILE_TOOL["function"],
+ "description": EDIT_FILE_TOOL["function"]["description"] + _EDIT_FILE_FULL_ACCESS_CLAUSE,
+ },
+}
+
+_FULL_ACCESS_TOOL_BY_NAME["edit_file"] = EDIT_FILE_TOOL_FULL_ACCESS
+
RENDER_HTML_TOOL = {
"type": "function",
"function": {
@@ -9245,6 +9776,7 @@ ALL_TOOLS = [
WEB_SEARCH_TOOL,
PYTHON_TOOL,
TERMINAL_TOOL,
+ EDIT_FILE_TOOL,
RENDER_HTML_TOOL,
SEARCH_KNOWLEDGE_BASE_TOOL,
]
@@ -9548,6 +10080,15 @@ def execute_tool(
disable_sandbox = disable_sandbox,
output_callback = output_callback,
)
+ # Same in-flight guard as the two above: it writes into the session workdir,
+ # so a chat deleted mid-call must not unlink it underneath.
+ if name == "edit_file":
+ with _session_in_flight(session_id):
+ return _edit_file(
+ arguments,
+ session_id = session_id,
+ disable_sandbox = disable_sandbox,
+ )
return f"Unknown tool: {name}"
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 9ae073134a0..3bfcdc3392e 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -1551,7 +1551,7 @@ class ChatCompletionRequest(BaseModel):
None,
description = (
"[x-unsloth] List of enabled tool names. Local GGUF/safetensors models "
- "accept ['web_search', 'python', 'terminal', 'render_html']. External "
+ "accept ['web_search', 'python', 'terminal', 'edit_file', 'render_html']. External "
"providers accept ['web_search', 'web_fetch', 'code_execution'] for "
"Anthropic and ['web_search', 'code_execution', 'image_generation'] for "
"OpenAI Responses. If None, all local tools are enabled and no "
@@ -1568,7 +1568,7 @@ class ChatCompletionRequest(BaseModel):
)
bypass_permissions: Optional[bool] = Field(
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.",
+ 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). edit_file is likewise unconfined: an absolute path resolves as written and edits the real file there, instead of being held to the conversation's working directory. Secret env vars are still stripped. Takes precedence over confirm_tool_calls.",
)
permission_mode: Optional[str] = Field(
None,
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 1bb65d5df6a..3aaf1b7768d 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3227,7 +3227,7 @@ _TOOL_CODE_TIP = (
# "no, I am sandboxed" from training data rather than reading its own tool list,
# so the environment is stated outright and the guess sent to a tool call.
# Fixed order so the sentence reads the same whichever way the caller listed them.
-_LOCAL_CODE_TOOLS = ("python", "terminal")
+_LOCAL_CODE_TOOLS = ("python", "terminal", "edit_file")
def _full_access_tip(code_tools: list[str]) -> str:
@@ -3239,7 +3239,8 @@ def _full_access_tip(code_tools: list[str]) -> str:
if len(code_tools) == 1:
subject = f"The {code_tools[0]} tool runs"
else:
- subject = "The " + " and ".join(code_tools) + " tools run"
+ # Three names now, so only the last pair takes the "and".
+ subject = "The " + ", ".join(code_tools[:-1]) + f" and {code_tools[-1]} tools run"
return (
subject + " where Unsloth Studio is running, with the code sandbox and the "
"approval prompts disabled, so you can inspect and change whatever that "
diff --git a/studio/backend/tests/test_edit_file_tool.py b/studio/backend/tests/test_edit_file_tool.py
new file mode 100644
index 00000000000..e014ed3ac90
--- /dev/null
+++ b/studio/backend/tests/test_edit_file_tool.py
@@ -0,0 +1,608 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Tests for the edit_file tool in core/inference/tools.py.
+
+Pinned here: a miss or an ambiguous match fails loudly and writes nothing, and
+the file's encoding, line endings and mode survive an edit.
+"""
+
+import os
+import stat
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+_BACKEND_ROOT = Path(__file__).resolve().parents[1]
+if str(_BACKEND_ROOT) not in sys.path:
+ sys.path.insert(0, str(_BACKEND_ROOT))
+
+from core.inference import tools
+from core.inference.tools import (
+ ALL_TOOLS,
+ EDIT_FILE_TOOL,
+ EDIT_FILE_TOOL_FULL_ACCESS,
+ apply_full_access_tool_descriptions,
+ execute_tool,
+ is_potentially_unsafe_tool_call,
+)
+
+
+def workdir(tmp_path, monkeypatch):
+ """Point the session workdir at a tmp dir, as the executor would."""
+ monkeypatch.setattr(tools, "_get_workdir", lambda session_id = None: str(tmp_path))
+ return tmp_path
+
+
+def _edit(**arguments) -> str:
+ return execute_tool("edit_file", arguments, session_id = "t")
+
+
+class TestReplacement:
+ def test_a_unique_match_is_replaced(self, workdir):
+ target = workdir / "a.py"
+ target.write_text("def a():\n return 1\n")
+ result = _edit(path = "a.py", old_string = "return 1", new_string = "return 42")
+ assert target.read_text() == "def a():\n return 42\n"
+ assert "1 replacement" in result
+
+ def test_the_receipt_shows_the_change_not_the_file(self, workdir):
+ target = workdir / "big.py"
+ target.write_text("filler = 0\n" * 500 + "TARGET = 1\n")
+ result = _edit(path = "big.py", old_string = "TARGET = 1", new_string = "TARGET = 2")
+ assert "TARGET = 2" in result
+ assert len(result) < 400
+ assert result.count("filler = 0") <= 2 # diff context lines only
+
+ def test_a_missing_old_string_writes_nothing(self, workdir):
+ target = workdir / "a.py"
+ target.write_text("x = 1\n")
+ result = _edit(path = "a.py", old_string = "y = 2", new_string = "y = 3")
+ assert result.startswith("Error:")
+ assert target.read_text() == "x = 1\n"
+
+ def test_an_ambiguous_match_names_the_count_and_writes_nothing(self, workdir):
+ target = workdir / "a.py"
+ target.write_text("v = 1\nv = 1\nv = 1\n")
+ result = _edit(path = "a.py", old_string = "v = 1", new_string = "v = 2")
+ assert result.startswith("Error:")
+ assert "3" in result # the model needs the count to decide what to do
+ assert target.read_text() == "v = 1\nv = 1\nv = 1\n"
+
+ def test_replace_all_takes_every_occurrence(self, workdir):
+ target = workdir / "a.py"
+ target.write_text("v = 1\nv = 1\n")
+ result = _edit(path = "a.py", old_string = "v = 1", new_string = "v = 2", replace_all = True)
+ assert target.read_text() == "v = 2\nv = 2\n"
+ assert "2 replacements" in result
+
+ def test_only_the_first_match_changes_without_replace_all(self, workdir):
+ # A unique-match rule that silently edited all of them would corrupt
+ # files whenever the model's snippet turned out not to be unique.
+ target = workdir / "a.py"
+ target.write_text("head\nv = 1\nmid\nv = 1\ntail\n")
+ _edit(
+ path = "a.py",
+ old_string = "head\nv = 1",
+ new_string = "head\nv = 9",
+ )
+ assert target.read_text() == "head\nv = 9\nmid\nv = 1\ntail\n"
+
+ def test_an_identical_edit_is_refused(self, workdir):
+ target = workdir / "a.py"
+ target.write_text("x = 1\n")
+ assert _edit(path = "a.py", old_string = "x", new_string = "x").startswith("Error:")
+
+ def test_non_string_arguments_are_refused(self, workdir):
+ # str(None) would write the literal "None" into a source file.
+ (workdir / "a.py").write_text("x = 1\n")
+ assert _edit(path = "a.py", old_string = None, new_string = "y").startswith("Error:")
+ assert _edit(path = "a.py", old_string = "x", new_string = 3).startswith("Error:")
+
+
+class TestCreation:
+ def test_an_empty_old_string_creates_the_file(self, workdir):
+ result = _edit(path = "new.py", old_string = "", new_string = "x = 1\n")
+ assert (workdir / "new.py").read_text() == "x = 1\n"
+ assert result.startswith("Created")
+
+ def test_both_strings_empty_creates_an_empty_file(self, workdir):
+ # __init__.py and .gitkeep are written this way, and the
+ # identical-strings no-op used to refuse them.
+ result = _edit(path = "pkg/__init__.py", old_string = "", new_string = "")
+ assert (workdir / "pkg" / "__init__.py").read_bytes() == b""
+ assert result.startswith("Created")
+
+ def test_creation_never_clobbers_an_existing_file(self, workdir):
+ target = workdir / "a.py"
+ target.write_text("keep me\n")
+ result = _edit(path = "a.py", old_string = "", new_string = "gone")
+ assert result.startswith("Error:")
+ assert target.read_text() == "keep me\n"
+
+ def test_editing_a_missing_file_says_how_to_create_it(self, workdir):
+ result = _edit(path = "nope.py", old_string = "a", new_string = "b")
+ assert result.startswith("Error:")
+ assert "old_string" in result
+
+
+class TestFileShapeSurvives:
+ def test_crlf_endings_are_matched_and_preserved(self, workdir):
+ # Writing back LF would rewrite every line of a file it did match.
+ target = workdir / "a.txt"
+ target.write_bytes(b"one\r\ntwo\r\nthree\r\n")
+ result = _edit(path = "a.txt", old_string = "two", new_string = "TWO")
+ assert not result.startswith("Error:")
+ assert target.read_bytes() == b"one\r\nTWO\r\nthree\r\n"
+
+ def test_a_utf8_bom_is_preserved(self, workdir):
+ target = workdir / "a.txt"
+ target.write_bytes(b"\xef\xbb\xbfhello world\n")
+ _edit(path = "a.txt", old_string = "world", new_string = "there")
+ assert target.read_bytes() == b"\xef\xbb\xbfhello there\n"
+
+ def test_unicode_content_survives(self, workdir):
+ target = workdir / "a.txt"
+ target.write_text("こんにちは世界\n", encoding = "utf-8")
+ _edit(path = "a.txt", old_string = "世界", new_string = "みなさん")
+ assert target.read_text(encoding = "utf-8") == "こんにちはみなさん\n"
+
+ @pytest.mark.skipif(sys.platform == "win32", reason = "POSIX file mode")
+ def test_the_executable_bit_is_preserved(self, workdir):
+ target = workdir / "run.sh"
+ target.write_text("#!/bin/sh\necho hi\n")
+ os.chmod(target, 0o755)
+ _edit(path = "run.sh", old_string = "echo hi", new_string = "echo bye")
+ assert stat.S_IMODE(os.stat(target).st_mode) == 0o755
+
+ def test_a_binary_file_is_refused(self, workdir):
+ target = workdir / "blob.bin"
+ target.write_bytes(b"\x00\x01\x02binary")
+ assert _edit(path = "blob.bin", old_string = "binary", new_string = "x").startswith("Error:")
+ assert target.read_bytes() == b"\x00\x01\x02binary"
+
+
+class TestPathContainment:
+ def test_a_traversal_path_is_refused(self, workdir):
+ outside = workdir.parent / "outside.txt"
+ outside.write_text("secret\n")
+ result = _edit(path = "../outside.txt", old_string = "secret", new_string = "pwned")
+ assert result.startswith("Error:")
+ assert outside.read_text() == "secret\n"
+
+ @pytest.mark.skipif(sys.platform == "win32", reason = "POSIX symlinks")
+ def test_a_symlink_out_of_the_workdir_is_refused(self, workdir):
+ outside = workdir.parent / "outside.txt"
+ outside.write_text("secret\n")
+ os.symlink(outside, workdir / "link.txt")
+ result = _edit(path = "link.txt", old_string = "secret", new_string = "pwned")
+ assert result.startswith("Error:")
+ assert outside.read_text() == "secret\n"
+
+ def test_a_code_interpreter_habit_path_keeps_its_suffix(self, workdir):
+ # The same rewrite the python shim applies.
+ result = _edit(path = "/mnt/data/out.txt", old_string = "", new_string = "hi\n")
+ assert not result.startswith("Error:")
+ assert (workdir / "out.txt").read_text() == "hi\n"
+
+ def test_an_empty_path_is_refused(self, workdir):
+ assert _edit(path = " ", old_string = "a", new_string = "b").startswith("Error:")
+
+
+class TestReviewFindings:
+ def test_a_long_line_does_not_blow_up_the_receipt(self, workdir):
+ # Capping diff LINES bounds nothing when one line is the whole file:
+ # before the char cap a 200KB file returned a 400KB receipt.
+ target = workdir / "min.js"
+ target.write_text("var a=" + "x" * 200_000 + ";")
+ result = _edit(path = "min.js", old_string = "var a=", new_string = "var b=")
+ assert not result.startswith("Error:")
+ assert len(result) < 2000
+
+ def test_replace_all_as_the_string_false_does_not_replace_all(self, workdir):
+ # bool("false") is True, and models emit the JSON string.
+ target = workdir / "a.txt"
+ target.write_text("a\na\na\n")
+ result = _edit(path = "a.txt", old_string = "a", new_string = "b", replace_all = "false")
+ assert result.startswith("Error:")
+ assert target.read_text() == "a\na\na\n"
+
+ def test_replace_all_as_the_string_true_still_works(self, workdir):
+ target = workdir / "a.txt"
+ target.write_text("a\na\n")
+ _edit(path = "a.txt", old_string = "a", new_string = "b", replace_all = "true")
+ assert target.read_text() == "b\nb\n"
+
+ def test_an_unreadable_replace_all_is_refused(self, workdir):
+ target = workdir / "a.txt"
+ target.write_text("a\n")
+ result = _edit(path = "a.txt", old_string = "a", new_string = "b", replace_all = "maybe")
+ assert result.startswith("Error:")
+ assert target.read_text() == "a\n"
+
+ @pytest.mark.skipif(sys.platform == "win32", reason = "POSIX FIFO")
+ def test_a_fifo_is_refused_rather_than_read(self, workdir):
+ # read() on a FIFO blocks forever and nothing here can cancel the turn.
+ os.mkfifo(workdir / "pipe")
+ assert _edit(path = "pipe", old_string = "a", new_string = "b").startswith("Error:")
+
+ def test_an_absolute_path_inside_a_workdir_under_a_habit_prefix(self, workdir, monkeypatch):
+ # A project rooted at /workspace/repo had its own prefix stripped and
+ # rejoined onto itself, resolving to /workspace/repo/repo/a.py.
+ monkeypatch.setattr(tools, "_MISSING_PATH_PREFIXES", (str(workdir.parent), "/mnt/data"))
+ (workdir / "a.py").write_text("x = 1\n")
+ result = _edit(path = str(workdir / "a.py"), old_string = "x = 1", new_string = "x = 2")
+ assert not result.startswith("Error:")
+ assert (workdir / "a.py").read_text() == "x = 2\n"
+
+ def test_a_habit_path_outside_the_workdir_still_remaps(self, workdir):
+ # The fix above must not switch off the remap it narrows.
+ result = _edit(path = "/mnt/data/out.txt", old_string = "", new_string = "hi\n")
+ assert not result.startswith("Error:")
+ assert (workdir / "out.txt").read_text() == "hi\n"
+
+ def test_a_concurrent_write_is_not_silently_reverted(self, workdir):
+ # Both chats read, both write, and the later os.replace used to
+ # discard the earlier edit without a word.
+ target = workdir / "s.py"
+ target.write_text("A = 1\nB = 2\n")
+ stale = target.read_bytes()
+ _edit(path = "s.py", old_string = "B = 2", new_string = "B = 99")
+ error = tools._edit_file_write(
+ str(target),
+ stale.decode().replace("A = 1", "A = 42"),
+ "\n",
+ "",
+ expect = stale,
+ )
+ assert error.startswith("Error:")
+ assert target.read_text() == "A = 1\nB = 99\n"
+
+ def test_containment_is_rechecked_at_write_time(self, workdir):
+ # A parent swapped for a symlink between resolve and rename.
+ outside = workdir.parent / "escaped.txt"
+ error = tools._edit_file_write(str(outside), "pwned", "\n", "", workdir = str(workdir))
+ assert error.startswith("Error:")
+ assert not outside.exists()
+
+ def test_an_empty_file_stays_writable(self, workdir):
+ # Refusing every existing target would strand the model here.
+ target = workdir / "placeholder.py"
+ target.touch()
+ result = _edit(path = "placeholder.py", old_string = "", new_string = "x = 1\n")
+ assert not result.startswith("Error:")
+ assert target.read_text() == "x = 1\n"
+
+
+class TestSecondReviewFindings:
+ def test_a_huge_replace_all_does_not_build_the_whole_diff(self, workdir):
+ # Fed the entire file and drained into a list, replace_all near the
+ # size cap allocated ~500MB for a 200-character receipt.
+ target = workdir / "big.txt"
+ target.write_text("a\n" * 300_000)
+ started = time.monotonic()
+ result = _edit(path = "big.txt", old_string = "a", new_string = "b", replace_all = True)
+ elapsed = time.monotonic() - started
+ assert not result.startswith("Error:")
+ assert len(result) < 2000
+ # Windowing makes this near-instant; diffing 300k lines does not.
+ assert elapsed < 2.0
+ assert target.read_text().startswith("b\nb\n")
+
+ def test_the_receipt_keeps_real_file_line_numbers(self, workdir):
+ # difflib numbers the hunk from the slice it was handed, so a receipt
+ # pointing at line 3 of a 9000-line file would be worse than none.
+ target = workdir / "mid.py"
+ target.write_text("".join(f"line{i}\n" for i in range(1, 9001)))
+ result = _edit(path = "mid.py", old_string = "line8000\n", new_string = "CHANGED\n")
+ assert "@@ -7998" in result
+ assert "+CHANGED" in result
+
+ def test_a_change_in_the_first_lines_still_numbers_from_one(self, workdir):
+ target = workdir / "top.py"
+ target.write_text("".join(f"line{i}\n" for i in range(1, 200)))
+ result = _edit(path = "top.py", old_string = "line2\n", new_string = "TOP\n")
+ assert "@@ -1" in result
+
+ @pytest.mark.skipif(sys.platform == "win32", reason = "POSIX file mode")
+ def test_a_created_file_gets_the_usual_mode(self, workdir):
+ # mkstemp makes the temp file 0600 and copymode had nothing to copy from,
+ # so new files landed 0600 and locked out anyone reading generated files.
+ _edit(path = "fresh.py", old_string = "", new_string = "x = 1\n")
+ umask = os.umask(0)
+ os.umask(umask)
+ mode = stat.S_IMODE(os.stat(workdir / "fresh.py").st_mode)
+ assert mode == 0o666 & ~umask
+
+ def test_creating_a_file_that_appeared_meanwhile_is_refused(self, workdir):
+ # Both chats could pass a lexists check and the later write win.
+ target = workdir / "race.py"
+ assert not _edit(path = "race.py", old_string = "", new_string = "first\n").startswith("Error:")
+ result = _edit(path = "race.py", old_string = "", new_string = "second\n")
+ assert result.startswith("Error:")
+ assert target.read_text() == "first\n"
+
+ def test_filling_an_empty_file_is_guarded_against_a_racer(self, workdir):
+ # The zero-byte path carries the same expect check as an edit.
+ target = workdir / "z.py"
+ target.touch()
+ target.write_text("someone got here first\n")
+ error = tools._edit_file_write(str(target), "mine\n", "\n", "", expect = b"")
+ assert error.startswith("Error:")
+ assert target.read_text() == "someone got here first\n"
+
+
+class TestThirdReviewFindings:
+ def test_the_receipt_does_not_invent_deletions_at_the_window_edge(self, workdir):
+ # Windowing each text by LINE COUNT made difflib report a second hunk:
+ # "-line319" for a line still in the file, which a model would restore.
+ target = workdir / "shift.py"
+ target.write_text("".join(f"line{i}\n" for i in range(1, 401)))
+ result = _edit(path = "shift.py", old_string = "line200\n", new_string = "A\nB\n")
+ after = target.read_text()
+ removed = [line[1:] for line in result.splitlines() if line.startswith("-")]
+ assert removed == ["line200"]
+ assert all(removed_line + "\n" not in after for removed_line in removed)
+
+ def test_the_receipt_numbers_a_line_count_change_from_the_real_line(self, workdir):
+ target = workdir / "grow.py"
+ target.write_text("".join(f"line{i}\n" for i in range(1, 401)))
+ result = _edit(path = "grow.py", old_string = "line200\n", new_string = "A\nB\n")
+ assert "@@ -198,5 +198,6 @@" in result
+
+ def test_a_deletion_does_not_invent_additions_at_the_window_edge(self, workdir):
+ target = workdir / "shrink.py"
+ target.write_text("".join(f"line{i}\n" for i in range(1, 401)))
+ result = _edit(
+ path = "shrink.py",
+ old_string = "line200\nline201\nline202\n",
+ new_string = "M\n",
+ )
+ after = target.read_text()
+ added = [line[1:] for line in result.splitlines() if line.startswith("+")]
+ assert added == ["M"]
+ assert all(added_line + "\n" in after for added_line in added)
+
+ @pytest.mark.skipif(sys.platform == "win32", reason = "POSIX FIFO")
+ def test_creating_over_a_fifo_is_refused_rather_than_reopened(self, workdir):
+ # A FIFO reports st_size 0, so an empty old_string fell into the
+ # zero-byte branch, whose write reopens the target and never returns.
+ import threading
+
+ os.mkfifo(workdir / "pipe")
+ done = []
+ worker = threading.Thread(
+ target = lambda: done.append(_edit(path = "pipe", old_string = "", new_string = "x\n")),
+ daemon = True,
+ )
+ worker.start()
+ worker.join(10)
+ assert done, "edit_file blocked forever on a FIFO"
+ assert done[0].startswith("Error:")
+ assert stat.S_ISFIFO(os.stat(workdir / "pipe").st_mode)
+
+ def test_the_receipt_never_reports_a_change_the_file_does_not_show(self, workdir):
+ # The property behind the two window cases above: every '-' line really
+ # gone and every '+' line really present. The receipt is all the model
+ # learns, so an untruthful one is wrong even if the bytes are right.
+ import random
+
+ random.seed(7)
+ target = workdir / "prop.py"
+ for _ in range(60):
+ total = random.choice([50, 130, 260, 500])
+ at = random.randrange(1, total)
+ grow = random.randrange(0, 6)
+ target.write_text("".join(f"line{i}\n" for i in range(1, total + 1)))
+ result = _edit(
+ path = "prop.py",
+ old_string = f"line{at}\n",
+ new_string = "".join(f"N{j}\n" for j in range(grow)) or "Z\n",
+ )
+ after = target.read_text()
+ for line in result.splitlines():
+ if line.startswith("-") and not line.startswith("---"):
+ assert line[1:] + "\n" not in after, (total, at, grow, line)
+ if line.startswith("+") and not line.startswith("+++"):
+ assert line[1:] + "\n" in after, (total, at, grow, line)
+
+ @pytest.mark.skipif(sys.platform == "win32", reason = "POSIX device node")
+ def test_full_access_does_not_replace_a_device_node(self, workdir):
+ # /dev/null stats as zero bytes, so measuring size alone sent it down
+ # the create branch, whose rename would have swapped the character
+ # device for a regular file.
+ result = execute_tool(
+ "edit_file",
+ {"path": "/dev/null", "old_string": "", "new_string": "x\n"},
+ session_id = "t",
+ disable_sandbox = True,
+ )
+ assert result.startswith("Error:")
+ assert stat.S_ISCHR(os.stat("/dev/null").st_mode)
+
+ @pytest.mark.parametrize("path,old", [("app.py", "TODO"), ("fresh.py", "")])
+ def test_an_unencodable_new_string_is_refused_not_dropped(self, workdir, path, old):
+ # '"\ud83d"' is a truncated emoji after json.loads: a lone surrogate
+ # that cannot be encoded. The UnicodeEncodeError was swallowed upstream
+ # into "Unknown tool: edit_file". Edit and create both encode.
+ import json
+
+ arguments = json.loads(
+ '{"path": "%s", "old_string": "%s", "new_string": "\\ud83d launch"}' % (path, old)
+ )
+ target = workdir / "app.py"
+ target.write_text("x = 1\n# TODO\ny = 2\n")
+
+ result = _edit(**arguments)
+
+ assert result.startswith("Error:"), result
+ assert "surrogate" in result
+ assert target.read_text() == "x = 1\n# TODO\ny = 2\n"
+ assert not (workdir / "fresh.py").exists()
+
+ def test_a_paired_surrogate_emoji_still_writes_normally(self, workdir):
+ # A real emoji arrives as a matched pair and is ordinary text.
+ target = workdir / "app.py"
+ target.write_text("# TODO\n")
+ result = _edit(path = "app.py", old_string = "TODO", new_string = "done \U0001f680")
+ assert not result.startswith("Error:"), result
+ assert target.read_text() == "# done \U0001f680\n"
+
+
+class TestPublicSchema:
+ def test_the_request_schema_lists_edit_file(self):
+ # A built-in missing from the generated OpenAPI schema is undiscoverable.
+ from models.inference import ChatCompletionRequest
+ description = ChatCompletionRequest.model_fields["enabled_tools"].description
+ assert "edit_file" in description
+
+ def test_bypass_permissions_says_edit_file_is_unconfined(self):
+ from models.inference import ChatCompletionRequest
+ description = ChatCompletionRequest.model_fields["bypass_permissions"].description
+ assert "edit_file" in description
+
+
+class TestRegistration:
+ def test_the_tool_is_offered(self):
+ assert EDIT_FILE_TOOL in ALL_TOOLS
+
+ def test_the_description_steers_away_from_whole_file_rewrites(self):
+ # Without the steer a model keeps writing heredocs.
+ description = EDIT_FILE_TOOL["function"]["description"].lower()
+ assert "prefer this" in description
+ assert "rewriting" in description
+
+ def test_an_edit_still_asks_in_auto_mode(self):
+ assert is_potentially_unsafe_tool_call("edit_file", {"path": "a.py"}) is True
+
+ def test_full_access_says_absolute_paths_resolve(self):
+ # Otherwise the model assumes it cannot reach a real checkout.
+ swapped = apply_full_access_tool_descriptions([EDIT_FILE_TOOL])
+ assert swapped == [EDIT_FILE_TOOL_FULL_ACCESS]
+ assert "absolute path" in swapped[0]["function"]["description"]
+
+ def test_full_access_leaves_the_schema_alone(self):
+ sandboxed = EDIT_FILE_TOOL["function"]["parameters"]
+ assert EDIT_FILE_TOOL_FULL_ACCESS["function"]["parameters"] == sandboxed
+
+
+class TestFullAccessEscapesTheWorkdir:
+ def test_an_absolute_path_resolves_when_the_sandbox_is_off(self, workdir, tmp_path):
+ outside = tmp_path.parent / "real_project.py"
+ outside.write_text("x = 1\n")
+ result = execute_tool(
+ "edit_file",
+ {"path": str(outside), "old_string": "x = 1", "new_string": "x = 2"},
+ session_id = "t",
+ disable_sandbox = True,
+ )
+ assert not result.startswith("Error:")
+ assert outside.read_text() == "x = 2\n"
+
+
[email protected](os.name != "posix", reason = "RLIMIT_FSIZE is POSIX-only")
+class TestCreationLeavesNothingBehindWhenTheWriteFails:
+ """A create that runs out of space must not strand a truncated file.
+
+ RLIMIT_FSIZE is a real kernel write failure shaped like ENOSPC or a quota:
+ the bytes that fit are on disk and the rest fail.
+ """
+
+ @staticmethod
+ def _capped(limit):
+ import resource
+ import signal
+
+ soft, hard = resource.getrlimit(resource.RLIMIT_FSIZE)
+ previous = signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
+ resource.setrlimit(resource.RLIMIT_FSIZE, (limit, hard))
+ return (soft, hard, previous)
+
+ @staticmethod
+ def _restore(saved):
+ import resource
+ import signal
+
+ soft, hard, previous = saved
+ resource.setrlimit(resource.RLIMIT_FSIZE, (soft, hard))
+ signal.signal(signal.SIGXFSZ, previous)
+
+ def test_a_half_written_file_is_removed_not_left_truncated(self, workdir):
+ # The failure lands mid-payload, cutting the file off mid-token.
+ body = "".join(f"def f{i}():\n return {i}\n\n" for i in range(4000))
+ saved = self._capped(4096)
+ try:
+ result = execute_tool(
+ "edit_file",
+ {"path": "report.py", "old_string": "", "new_string": body},
+ session_id = "t",
+ )
+ finally:
+ self._restore(saved)
+ assert result.startswith("Error:")
+ assert not (workdir / "report.py").exists()
+
+ def test_the_retry_the_error_asks_for_then_succeeds(self, workdir):
+ # A leftover partial file would make the failure permanent.
+ body = "".join(f"def f{i}():\n return {i}\n\n" for i in range(4000))
+ saved = self._capped(4096)
+ try:
+ execute_tool(
+ "edit_file",
+ {"path": "report.py", "old_string": "", "new_string": body},
+ session_id = "t",
+ )
+ finally:
+ self._restore(saved)
+ retry = execute_tool(
+ "edit_file",
+ {"path": "report.py", "old_string": "", "new_string": body},
+ session_id = "t",
+ )
+ assert not retry.startswith("Error:")
+ assert (workdir / "report.py").read_text() == body
+
+ def test_a_failure_at_close_leaves_nothing_either(self, workdir, monkeypatch):
+ # A payload smaller than the io buffer reaches the disk only at close,
+ # where a full disk reports failures for data written earlier. Injected
+ # rather than rlimit'd so it lands there whatever the buffer size.
+ real = os.fdopen
+
+ def failing(fd, *args, **kwargs):
+ handle = real(fd, *args, **kwargs)
+ closed = handle.close
+
+ def close():
+ # CPython releases the descriptor even when the closing flush
+ # fails, so the real failure closes before it raises.
+ closed()
+ raise OSError(28, "No space left on device")
+
+ handle.close = close
+ return handle
+
+ monkeypatch.setattr(os, "fdopen", failing)
+ result = execute_tool(
+ "edit_file",
+ {"path": "notes.py", "old_string": "", "new_string": "print('hi')\n"},
+ session_id = "t",
+ )
+ monkeypatch.undo()
+ assert result.startswith("Error:")
+ assert not (workdir / "notes.py").exists()
+
+ def test_a_failed_create_does_not_remove_someone_elses_file(self, workdir):
+ # The cleanup must only reach the inode this call created.
+ target = workdir / "keep.py"
+ target.write_text("x = 1\n")
+ result = execute_tool(
+ "edit_file",
+ {"path": "keep.py", "old_string": "", "new_string": "y = 2\n"},
+ session_id = "t",
+ )
+ assert result.startswith("Error:")
+ assert "already exists" in result
+ assert target.read_text() == "x = 1\n"
diff --git a/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx b/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
index f6e32d32686..c372a8060e8 100644
--- a/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
+++ b/studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx
@@ -105,6 +105,7 @@ const TOOL_CALL_LABELS: Record<string, string> = {
code_execution: "Code",
python: "Python",
terminal: "Terminal",
+ edit_file: "Edit",
image_generation: "Images",
search_knowledge_base: "Docs",
render_html: "Canvas",
@@ -121,7 +122,8 @@ function toolCategoryFromCall(toolName: string): string | null {
if (
normalized === "code_execution" ||
normalized === "python" ||
- normalized === "terminal"
+ normalized === "terminal" ||
+ normalized === "edit_file"
) {
return "code";
}
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index d8352795661..a2625bfa872 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -1714,7 +1714,7 @@ export async function buildLocalTokenCountExtras(
enabled_tools: [
...(ragOn ? ["search_knowledge_base"] : []),
...(toolsEnabled ? ["web_search"] : []),
- ...(codeToolsEnabled ? ["python", "terminal"] : []),
+ ...(codeToolsEnabled ? ["python", "terminal", "edit_file"] : []),
...(artifactsEnabled ? ["render_html"] : []),
],
mcp_enabled: mcpEnabledForChat,
@@ -5556,7 +5556,9 @@ export function createOpenAIStreamAdapter(
? ["search_knowledge_base"]
: []),
...(toolsEnabled ? ["web_search"] : []),
- ...(codeToolsEnabled ? ["python", "terminal"] : []),
+ ...(codeToolsEnabled
+ ? ["python", "terminal", "edit_file"]
+ : []),
...(renderHtmlToolEnabledForThisTurn
? ["render_html"]
: []),
diff --git a/studio/frontend/src/features/chat/api/code-tool-placement.ts b/studio/frontend/src/features/chat/api/code-tool-placement.ts
index a730d0ceef4..616feb02555 100644
--- a/studio/frontend/src/features/chat/api/code-tool-placement.ts
+++ b/studio/frontend/src/features/chat/api/code-tool-placement.ts
@@ -45,7 +45,9 @@ export function selectCodeToolNames(input: CodeToolPlacementInput): CodeToolName
if (!input.codeToolsEnabled) return { local: [], hosted: [] };
if (input.hostedCodeExecutionForThisTurn) return { local: [], hosted: ["code_execution"] };
if (input.providerHostsCodeExecution) return { local: [], hosted: [] };
- return { local: ["python", "terminal"], hosted: [] };
+ // edit_file is local-only: when the provider hosts execution the files live
+ // in its sandbox, so a local editor would patch a copy nothing else sees.
+ return { local: ["python", "terminal", "edit_file"], hosted: [] };
}
/**
diff --git a/studio/frontend/src/features/chat/utils/tool-status.ts b/studio/frontend/src/features/chat/utils/tool-status.ts
index 16c86bbd49b..d57cea759b3 100644
--- a/studio/frontend/src/features/chat/utils/tool-status.ts
+++ b/studio/frontend/src/features/chat/utils/tool-status.ts
@@ -6,10 +6,14 @@ export const NUDGE_TOOL_CALLS_STATUS = "Nudging tool calls";
export type ToolStatusKind = "nudge" | "terminal" | "web";
-/** Which glyph the badge shows: exact match for the nudge, "Running" prefix for sandbox tools, globe otherwise. */
+/** Which glyph the badge shows: exact match for the nudge, "Running"/"Editing" prefix for sandbox tools, globe otherwise. */
export function toolStatusKind(status: string): ToolStatusKind {
if (status === NUDGE_TOOL_CALLS_STATUS) {
return "nudge";
}
- return status.startsWith("Running") ? "terminal" : "web";
+ // edit_file reports "Editing: name", not "Running", and it is as local as the
+ // other two. Without it a file edit shows the globe, i.e. the web-search glyph.
+ return status.startsWith("Running") || status.startsWith("Editing")
+ ? "terminal"
+ : "web";
}
diff --git a/studio/frontend/tests/code-tool-placement.test.ts b/studio/frontend/tests/code-tool-placement.test.ts
index 2fc34c4ed25..3560cf5c593 100644
--- a/studio/frontend/tests/code-tool-placement.test.ts
+++ b/studio/frontend/tests/code-tool-placement.test.ts
@@ -69,10 +69,24 @@ test("a provider with no sandbox uses Studio's own tools", () => {
hostedCodeExecutionForThisTurn: false,
providerHostsCodeExecution: false,
}),
- { local: ["python", "terminal"], hosted: [] },
+ { local: ["python", "terminal", "edit_file"], hosted: [] },
);
});
+test("edit_file is local-only, never a stand-in for a hosted sandbox", () => {
+ // It must not creep into the hosted branch just because the Code pill is
+ // what turns it on.
+ for (const hosted of [true, false]) {
+ const names = selectCodeToolNames({
+ codeToolsEnabled: true,
+ hostedCodeExecutionForThisTurn: hosted,
+ providerHostsCodeExecution: true,
+ });
+ assert.ok(!names.local.includes("edit_file"));
+ assert.ok(!names.hosted.includes("edit_file"));
+ }
+});
+
test("the pill being off asks for nothing on either side", () => {
for (const providerHostsCodeExecution of [true, false]) {
assert.deepEqual(
diff --git a/studio/frontend/tests/tool-status.test.ts b/studio/frontend/tests/tool-status.test.ts
index b20585bd086..77d668bc044 100644
--- a/studio/frontend/tests/tool-status.test.ts
+++ b/studio/frontend/tests/tool-status.test.ts
@@ -21,6 +21,9 @@ test("sandbox tools keep the terminal glyph", () => {
"Running Python...",
"Running: ls -la",
"Running command...",
+ // edit_file is as local as the other two, but reports "Editing: name".
+ "Editing: chart.py",
+ "Editing file...",
]) {
assert.equal(toolStatusKind(status), "terminal", status);
}