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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: size a tool result against the room the thread has left (#9563)
Daniel Han48cdec1cb329
diff --git a/studio/backend/core/inference/context_window.py b/studio/backend/core/inference/context_window.pyindex ee6b37fba8b..18dccc67a16 100644--- a/studio/backend/core/inference/context_window.py+++ b/studio/backend/core/inference/context_window.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport jsonimport os+import refrom collections.abc import Callablefrom typing import Any, Optional@@ -59,6 +60,67 @@ def estimate_messages_tokens_dense(messages: list[dict]) -> int:return total+# ASCII that runs this far without a break is not prose. Measured with Qwen3 over 16-20k+# character samples, in characters per token: base64 1.35, hex 1.13, minified JSON 2.75,+# against English prose at 3.27 and Python source at 4.38. The estimate above charges all+# of them the English four, so a pasted blob is priced at a third of what it costs, and a+# caller sizing the room LEFT then hands out room that is already occupied.+#+# The rule is per RUN rather than per message, so a blob pasted into a sentence is priced+# as a blob: a run this long is the thing itself. 64 characters rather than a rounder+# number because base64 is conventionally wrapped at 76, and at a threshold of 80 a+# wrapped blob scores as ordinary prose. Measured on the samples above, runs of 64++# non-space characters cover 100% of an unwrapped blob, 98.6% of a wrapped one, 0% of the+# Python source and 23.5% of a README -- and that 23.5% is its URLs and table rules, which+# tokenise near this rate themselves rather than at the prose rate.+_DENSE_RUN_CHARS = 64+# Two characters per token, not one. It stays BELOW the measured cost of every sample, so+# no turn is priced above what it really costs: over-pricing a turn spends the very room+# this budget exists to hand out, and a result cut to pay for room that was never occupied+# is the same waste from the other side.+_DENSE_RUN_CHARS_PER_TOKEN = 2+_DENSE_RUN_RE = re.compile(r"\S{%d,}" % _DENSE_RUN_CHARS)+++def estimate_messages_tokens_conservative(+ messages: list[dict], *, dense_ascii: bool = False+) -> int:+ """`estimate_messages_tokens_dense`, with unbroken ASCII runs charged as the blobs+ they are.++ For the caller with no tokenizer and no rolling fit behind it: the native loop prices+ what a thread has already spent, and if that number is low the result it then admits+ is what pushes the next prompt past the window, with nothing downstream to recover.+ Non-ASCII keeps its token per character, ordinary ASCII keeps the English four, and+ only the long unbroken runs are charged at `_DENSE_RUN_CHARS_PER_TOKEN`.++ ``dense_ascii`` charges ALL of a message's ASCII at that rate, for the messages that+ are dense whether or not they hold an unbroken run: a tool result is `hexdump`, `ls+ -l` or a stack trace as often as it is a blob, and those are space-separated. It+ applies to the ASCII only, so a CJK result is not charged twice for being a result.+ """+ total = 0+ for message in messages:+ try:+ text = json.dumps(message, ensure_ascii = False)+ except Exception:+ total += 1+ continue+ wide = sum(1 for char in text if ord(char) > 127)+ if dense_ascii:+ total += max(1, wide + (len(text) - wide) // _DENSE_RUN_CHARS_PER_TOKEN)+ continue+ # ASCII only: a run of CJK is already charged a token a character above, and+ # charging it here as well would price it twice.+ runs = sum(+ sum(1 for char in match.group(0) if ord(char) <= 127)+ for match in _DENSE_RUN_RE.finditer(text)+ )+ plain = len(text) - wide - runs+ total += max(1, wide + runs // _DENSE_RUN_CHARS_PER_TOKEN + plain // 4)+ return total++def group_turns(messages: list[dict]) -> list[list[dict]]:"""Split messages into the turn groups the rolling window evicts as single units.@@ -244,6 +306,50 @@ def retrieval_budget(return room+# Headroom against the tokenizer disagreeing with the estimate that sized a result. A+# result is measured in characters and spent in tokens, so the conversion is the thing+# that can be wrong; 1% of the budget absorbs that without noticeably shortening output.+_TOOL_RESULT_BUDGET_BUFFER = 0.99++# What a truncated result costs BESIDES its body: the notice naming the cut, the spill+# path and the command that resumes it. Measured at 60-85 tokens, held clear of that.+# Reserved rather than ignored because the body is sized and the notice appended after,+# so a budget spent entirely on the body overshoots by the notice every time, and at zero+# room, where the notice IS the message, by the whole of it.+#+# Charged by `tools._truncate`, at the point it knows the result really is being cut, and+# NOT subtracted from the room below. A result that fits carries no notice, so holding+# this back up front would cut a result that would have fitted whole and then spend more+# than it saved: 200 tokens of room, a 100-token result, and reserving first leaves 72 for+# the body and appends ~70 tokens of notice explaining the 28 that were dropped.+_RESULT_NOTICE_RESERVE = 128+++def tool_result_budget(+ context_length: int,+ max_tokens: Optional[int],+ prompt_tokens: int,+ *,+ buffer: float = _TOOL_RESULT_BUDGET_BUFFER,+) -> int:+ """Tokens a tool result may add without pushing the next prompt past its budget.++ The cap before this was a share of the WINDOW, so it never fell as the conversation+ filled: one result could take half a small context however little was left, and the+ next fit cannot recover because it protects the newest turn, the very result that does+ not fit. This prices the same result against the room actually remaining.++ Against ``prompt_budget`` rather than ``context_length``: a result sized to fill the+ physical window leaves the prompt fitting and nothing to answer in. Room for the reply+ is not room for the result. The figure covers the whole tool message, notice included:+ see `_RESULT_NOTICE_RESERVE`, which the truncation charges against this room when it+ turns out to need one. A caller with several tool calls to serve divides what comes+ back between them.+ """+ target = prompt_budget(context_length, max_tokens)+ return max(0, int(target * buffer) - int(prompt_tokens or 0))++def _latest_turn_count(messages: list[dict], count_tokens: Callable[[list[dict]], int]) -> tuple[int, bool]:diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 15752faea7e..36a83b0cc10 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -57,6 +57,7 @@ from core.inference.context_window import (fit_rolling_context,messages_have_media,retrieval_budget,+ tool_result_budget,)from core.inference.stream_errors import stream_error_from_chunkfrom core.inference.llama_server_args import (@@ -25293,7 +25294,7 @@ class LlamaCppBackend:# the card's id for the first matching call (same tool name) to reconcile._text_provisional_id = _text_args_id if not has_structured_tc else ""- for tc in tool_calls or []:+ for _call_index, tc in enumerate(tool_calls or []):func = tc.get("function", {})tool_name = func.get("name", "")if (@@ -25453,9 +25454,7 @@ class LlamaCppBackend:# the result lands in the current tool exchange, which rolling# truncation protects, so a top_k the window cannot hold ends# the turn in an unrecoverable context-length error.- if self._effective_context_length and accepts_kwarg(- execute_tool, "conversation_budget_tokens"- ):+ if self._effective_context_length:# Priced against the catalogue too: the messages alone# leave the tools array out, and a big catalogue can put# the request near its budget while this still reports@@ -25470,10 +25469,15 @@ class LlamaCppBackend:# and the next iteration cannot evict it again because the# current tool exchange is protected.#- # So price it exactly instead, here: this runs when the- # model actually reaches for a retrieval tool on a request- # that did not truncate, not on every turn. A failure falls- # back to the estimate, which is what this did before.+ # So price it exactly instead, here. A failure falls back+ # to the estimate, which is what this did before.+ #+ # Once per TOOL CALL, not once per retrieval: every result+ # is now sized against this figure, not only a retrieval's,+ # because a `cat` of a large file overflows the window the+ # same way a too-large recall does and is likewise+ # protected from eviction once appended. One tokenizer pass+ # over the conversation next to running the tool itself.## Recomputed on EVERY search, not cached for the request.# The count is absolute, and the loop appends the assistant@@ -25524,30 +25528,78 @@ class LlamaCppBackend:else estimate_messages_tokens_dense(safe_tools or [])))- if accepts_kwarg(execute_tool, "conversation_token_counter"):- # The admission check estimates a result's size by- # characters, which is optimistic for ASCII that- # tokenises densely: code, minified JSON, hashes and- # command output all run nearer two or three- # characters per token than four. This path has a- # tokenizer, so hand it over and let the check spend- # the budget as exactly as it computes it.- kwargs["conversation_token_counter"] = lambda text: (- self.count_chat_tokens(- [{"role": "tool", "content": text}],- None,- None,- strict = False,+ # What ANY result may add before the next prompt is over+ # budget, for every tool and not just the retrieval ones.+ # The old cap was a share of the WINDOW and never fell as+ # the thread filled, so the last result before an overflow+ # claimed as much as the first, and nothing downstream+ # recovers: the fit protects the newest turn.+ if accepts_kwarg(execute_tool, "result_budget_tokens"):+ # Split across the calls still to run in this batch,+ # and after their arguments. One assistant turn can+ # call several tools, and the loop appends each call+ # only as it runs it, so `_spent` here knows nothing+ # about the rest of the batch: sized as if it were+ # alone, the first result can take all the room the+ # other calls and their results still need, and the+ # finished exchange is protected as the newest turn.+ _pending = list(tool_calls or [])[_call_index + 1 :]+ _pending_msgs = [+ {+ "role": "assistant",+ "content": json.dumps(_call, default = str),+ }+ for _call in _pending+ ]+ # Measured, not estimated: the estimator charges ASCII+ # four characters per token, and a pending call can+ # carry base64, minified JSON or a block of code, which+ # run nearer one or two. Under-priced, the first result+ # is handed room the later ARGUMENTS already occupy.+ _pending_args = 0+ if _pending_msgs:+ try:+ _pending_args = self.count_chat_tokens(+ _pending_msgs, None, None, strict = True+ )+ except Exception:+ logger.debug(+ "result budget: pending call count failed",+ exc_info = True,+ )+ _pending_args = 2 * estimate_messages_tokens_dense(+ _pending_msgs+ )+ kwargs["result_budget_tokens"] = tool_result_budget(+ self._effective_context_length,+ max_tokens,+ _spent + _pending_args,+ ) // (len(_pending) + 1)+ if accepts_kwarg(execute_tool, "conversation_budget_tokens"):+ if accepts_kwarg(execute_tool, "conversation_token_counter"):+ # The admission check estimates a result's size by+ # characters, which is optimistic for ASCII that+ # tokenises densely: code, minified JSON, hashes and+ # command output all run nearer two or three+ # characters per token than four. This path has a+ # tokenizer, so hand it over and let the check spend+ # the budget as exactly as it computes it.+ kwargs["conversation_token_counter"] = lambda text: (+ self.count_chat_tokens(+ [{"role": "tool", "content": text}],+ None,+ None,+ strict = False,+ ))+ # The result and reply are protected on the next fit, so+ # the result cannot spend their entire shared budget.+ kwargs["conversation_budget_tokens"] = _retrieval_budget(+ self._effective_context_length,+ max_tokens,+ _spent,+ reply_returns = True,)- # The result and reply are protected on the next fit, so- # the result cannot spend their entire shared budget.- kwargs["conversation_budget_tokens"] = _retrieval_budget(- self._effective_context_length,- max_tokens,- _spent,- reply_returns = True,- )if accepts_output_callback(execute_tool):kwargs["output_callback"] = _output_callbackkwargs.update(search_images_kwargs(execute_tool, _decision.tool_name))diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.pyindex 3780c5e6807..bc04fd1256c 100644--- a/studio/backend/core/inference/safetensors_agentic.py+++ b/studio/backend/core/inference/safetensors_agentic.py@@ -16,6 +16,7 @@ parses tool calls from the cumulative text and dispatches viaimport bisectimport inspect+import jsonimport reimport threadingfrom typing import Callable, Generator, Optional@@ -1175,7 +1176,7 @@ def run_safetensors_tool_loop(# abort it and drop the parallel calls that follow.deferred_noop_msgs: list = []- for tc in tool_calls or []:+ for _call_index, tc in enumerate(tool_calls or []):func = tc.get("function", {}) or {}tool_name = func.get("name", "") or ""provisional_match = (@@ -1342,6 +1343,73 @@ def run_safetensors_tool_loop(+ estimate_messages_tokens_dense(tools or []),reply_returns = True,)+ # And what a RESULT may add, which is the same question asked of+ # every tool rather than of retrieval alone. This loop has no rolling+ # fit behind it either, so a `cat` of a file the model just wrote is+ # protected as the newest exchange and there is nothing downstream to+ # evict it.+ if context_length and _accepts_kwarg(execute_tool, "result_budget_tokens"):+ from core.inference.context_window import (+ estimate_messages_tokens_conservative as _spent_tokens,+ estimate_messages_tokens_dense as _dense_tokens,+ tool_result_budget,+ )++ # The window itself as well, not only the room: nothing in the+ # tools layer can see a native model's context length (its probe+ # answers for a resident GGUF), and a cap with no window to size+ # against falls back to the window-independent constant.+ if _accepts_kwarg(execute_tool, "context_tokens"):+ kwargs["context_tokens"] = int(context_length)+ # Tool results are counted TWICE, which charges them two+ # characters per token instead of four. The estimator's rate is an+ # English one, and this budget exists because the results these+ # tools return are base64, minified JSON, hashes and command+ # output, which run nearer two. Under-pricing what is already in+ # the conversation hands the next call room that is occupied, and+ # this loop has no exact count and no rolling fit to catch it.+ results = [+ message for message in conversation if message.get("role") == "tool"+ ]+ # Removed from the thread below rather than added on top of it:+ # the conservative estimate already prices every message it is+ # given, so leaving the results in and adding them again charges+ # them twice, and a CJK result twice over at a token per character+ # each time. A thread with one sizable earlier result would then+ # report no room while it still had plenty.+ rest = [+ message for message in conversation if message.get("role") != "tool"+ ]+ # Split across the calls still to run in this batch, and after+ # their arguments, exactly as the GGUF loop does: one turn can+ # call several tools and each call is appended only as it runs,+ # so sizing a result as if it were alone lets the first take the+ # room the rest of the batch still needs.+ pending = list(tool_calls or [])[_call_index + 1 :]+ pending_args = [+ {"role": "assistant", "content": json.dumps(call, default = str)}+ for call in pending+ ]+ kwargs["result_budget_tokens"] = tool_result_budget(+ int(context_length),+ max_tokens,+ # Conservative for the thread as a whole, not only for the+ # tool turns doubled below: a user or assistant turn can hold+ # a pasted blob or a block of minified JSON, and priced at the+ # English rate it reports a third of what it costs. Nothing+ # here can measure exactly, and the room this produces is what+ # the next result is admitted against.+ _spent_tokens(rest)+ + _spent_tokens(tools or [])+ # Every ASCII character of a result at two per token, not only+ # its unbroken runs: a result is `hexdump`, `ls -l` or a stack+ # trace as often as it is a blob, and those carry spaces.+ + _spent_tokens(results, dense_ascii = True)+ # Doubled for the same reason the results above are: a pending+ # call can carry base64, minified JSON or a block of code, and+ # nothing on this path can price a string exactly.+ + 2 * _dense_tokens(pending_args),+ ) // (len(pending) + 1)if _accepts_output_callback(execute_tool):kwargs["output_callback"] = _output_callbackkwargs.update(_search_images_kwargs(execute_tool, _decision.tool_name))diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 5040e57398b..9941e01eba4 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -24,6 +24,7 @@ import reimport shleximport shutilimport ssl+import statfrom stat import S_ISREGimport subprocessimport sys@@ -32,6 +33,10 @@ import contextlibimport threadingfrom contextvars import ContextVar+# What a truncated result costs besides its body, charged where the cut is decided rather+# than held back from the room in advance. See its definition for why that matters.+from .context_window import _RESULT_NOTICE_RESERVE+# The window of the model THIS request is served by, set by execute_tool for the call's# duration. Left unset, the budget falls back to the process-global probe, which is right# for the local loops and wrong for anything else: an external-provider request runs@@ -44,6 +49,15 @@ _REQUEST_CONTEXT_TOKENS: ContextVar = ContextVar(default = _UNSET_CONTEXT_TOKENS,)+# What the CONVERSATION has left, as opposed to how big the window is. The window alone+# cannot size a result: it does not fall as the thread fills, so the last result before an+# overflow is allowed exactly as much room as the first. None means the caller could not+# say, and every cap then behaves exactly as it did before this existed.+_REQUEST_RESULT_BUDGET: ContextVar = ContextVar(+ "unsloth_request_result_budget_tokens",+ default = None,+)+import uuidimport timeimport urllib.parse@@ -8754,6 +8768,24 @@ def session_sandbox_has_files(session_id: str) -> bool:return False+def _is_spill_artifact(sandbox: str, parent: str, name: str) -> bool:+ """Whether ``parent/name`` is a spill this process wrote, rather than anything else.++ Both halves are checked: the name has to be one `_spill_full_output` generates, and it+ has to sit at the spill root or one scope below it. A link is never one, whatever it+ is called.+ """+ root = os.path.join(sandbox, _SPILL_DIR)+ if parent != root and os.path.dirname(parent) != root:+ return False+ identity, owned = _spill_record(root)+ if identity is None or identity != _spill_identity(root):+ # No record of this directory: it came with the sandbox or was replaced, so+ # everything in it is the user's, however the files are named.+ return False+ return _is_recorded_spill(root, os.path.join(parent, name), owned)++def _holds_no_user_files(target: str, owner: "str | None" = None) -> bool:"""Whether a sandbox holds nothing but (possibly empty) directories.@@ -8775,6 +8807,14 @@ def _holds_no_user_files(target: str, owner: "str | None" = None) -> bool:marker = _marker_owner(target)if marker is not None and owner in (None, marker):continue+ # Studio's own, like the marker above: a spill is truncated tool output this+ # process wrote and deliberately kept off the file cards, so counting one as+ # the user's content leaves an unreachable sandbox behind, reported as holding+ # files the user never created. Only the artifacts themselves, by the name+ # `_spill_full_output` generates: the directory is writable, tool code can+ # create anything in it, and a real file there is the user's like any other.+ if _is_spill_artifact(target, parent, name):+ continuereturn Falsebudget -= 1if budget <= 0:@@ -8881,6 +8921,10 @@ def _remove_session_sandbox_locked(session_id: str, delete_files: bool) -> bool:# evidence, and it names the other chat.return False_workdirs.pop(session_id, None)+ # Resolved BEFORE anything is removed: the record is named by the real path of the+ # spill directory, which cannot be derived once the tree is gone. Without this every+ # deleted chat that ever truncated output leaves one small file behind for good.+ forget_record = _spill_record_path(os.path.join(target, _SPILL_DIR))try:if delete_files:# Renamed while locked, deleted after: every tool start takes this@@ -8891,8 +8935,12 @@ def _remove_session_sandbox_locked(session_id: str, delete_files: bool) -> bool:os.rename(target, detached)except OSError:shutil.rmtree(target, ignore_errors = True)- return not os.path.isdir(target)+ gone = not os.path.isdir(target)+ if gone:+ _forget_spill_record(forget_record)+ return gone_queue_detached_delete(detached)+ _forget_spill_record(forget_record)return True# Empty means no files of the user's: a tool that only ran mkdir, or# deleted what it wrote, leaves directories behind, and the chat record@@ -8900,7 +8948,10 @@ def _remove_session_sandbox_locked(session_id: str, delete_files: bool) -> bool:if not _holds_no_user_files(target, _sandbox_name(session_id)):return Falseshutil.rmtree(target, ignore_errors = True)- return not os.path.isdir(target)+ gone = not os.path.isdir(target)+ if gone:+ _forget_spill_record(forget_record)+ return goneexcept OSError:return False@@ -10043,6 +10094,7 @@ def execute_tool(conversation_token_counter = None,context_tokens = _UNSET_CONTEXT_TOKENS,search_images: bool = False,+ result_budget_tokens: int | None = None,) -> str:"""Execute a tool by name with the given arguments; returns a string.@@ -10065,31 +10117,41 @@ def execute_tool(# Set unconditionally, so a value from an earlier call on this thread can never be# read by a later one. That is what makes a try/finally reset unnecessary here._REQUEST_CONTEXT_TOKENS.set(context_tokens)+ # Same rule, and it matters more here: a stale budget is a budget measured before this+ # turn's own tool exchanges existed, which is precisely the undercount that lets the+ # last result overflow.+ _REQUEST_RESULT_BUDGET.set(result_budget_tokens)effective_timeout = _EXEC_TIMEOUT if timeout is _TIMEOUT_UNSET else timeoutif name == "search_knowledge_base":- return _search_knowledge_base_with_budget(- arguments,- rag_scope,- effective_timeout,- cancel_event,+ return _fit_result_to_room(+ _search_knowledge_base_with_budget(+ arguments,+ rag_scope,+ effective_timeout,+ cancel_event,+ ),+ name,)if name == "search_conversation":# Scoped by thread id alone: the archive is this chat's own evicted turns, so it# works with or without a document rag_scope.- return _search_knowledge_base_with_budget(- arguments,- {- "thread_id": thread_id,- "branch_messages": conversation_branch,- "budget_tokens": conversation_budget_tokens,- "token_counter": conversation_token_counter,- },- effective_timeout,- cancel_event,- search_fn = _search_conversation,+ return _fit_result_to_room(+ _search_knowledge_base_with_budget(+ arguments,+ {+ "thread_id": thread_id,+ "branch_messages": conversation_branch,+ "budget_tokens": conversation_budget_tokens,+ "token_counter": conversation_token_counter,+ },+ effective_timeout,+ cancel_event,+ search_fn = _search_conversation,+ ),+ name,)if name == "render_html":- return _render_html_result(arguments)+ return _fit_result_to_room(_render_html_result(arguments), name)if name.startswith(MCP_TOOL_PREFIX):try:_, server_id, tool_name = name.split("__", 2)@@ -10128,26 +10190,32 @@ def execute_tool(and parse_server_headers(row) == headers)- return call_tool_sync(- url = url,- headers = headers,- name = tool_name,- args = arguments,- timeout = effective_timeout,- use_oauth = bool(server.get("use_oauth")),- cancel_event = cancel_event,- scope = mcp_scope,- config_check = _config_current,+ return _fit_result_to_room(+ call_tool_sync(+ url = url,+ headers = headers,+ name = tool_name,+ args = arguments,+ timeout = effective_timeout,+ use_oauth = bool(server.get("use_oauth")),+ cancel_event = cancel_event,+ scope = mcp_scope,+ config_check = _config_current,+ ),+ name,)if name == "web_search":- return _web_search(- arguments.get("query", ""),- url = arguments.get("url"),- timeout = effective_timeout,- cancel_event = cancel_event,- website_policy = website_policy,- include_images = search_images,- image_queries = arguments.get("image_queries"),+ return _fit_result_to_room(+ _web_search(+ arguments.get("query", ""),+ url = arguments.get("url"),+ timeout = effective_timeout,+ cancel_event = cancel_event,+ website_policy = website_policy,+ include_images = search_images,+ image_queries = arguments.get("image_queries"),+ ),+ name,)# Both run with the session's sandbox as cwd, so a chat deleted mid-call# must not unlink it from under them.@@ -10160,6 +10228,7 @@ def execute_tool(session_id,disable_sandbox = disable_sandbox,output_callback = output_callback,+ thread_id = thread_id,)if name == "terminal":with _session_in_flight(session_id):@@ -10170,15 +10239,19 @@ def execute_tool(session_id,disable_sandbox = disable_sandbox,output_callback = output_callback,+ thread_id = thread_id,)# 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 _fit_result_to_room(+ _edit_file(+ arguments,+ session_id = session_id,+ disable_sandbox = disable_sandbox,+ ),+ name,)return f"Unknown tool: {name}"@@ -10878,6 +10951,11 @@ _MAX_PAGE_CHARS = 16000 # cap fetched page text (after HTML-to-MD conversion)# to answer, so a third is already generous._PAGE_CONTEXT_SHARE = 0.35# Below this a page is too clipped to answer from, so the fetch is not worth making small.+# Half, when the room has to be converted to characters with no way to check the answer.+# See `_dense_char_limit`: the conversion charges ASCII an English four characters per+# token and the dense ASCII these tools print runs nearer two.+_UNMEASURED_ROOM_MARGIN = 0.5+_MIN_PAGE_CHARS = 2000# A percent-escape is one non-ASCII byte written in ASCII, and tokenises like one._HEX_PAIR_RE = re.compile(r"[0-9A-Fa-f]{2}")@@ -11776,6 +11854,22 @@ def _page_char_budget() -> int:return max(_MIN_PAGE_CHARS, min(_MAX_PAGE_CHARS, int(ctx * 4 * _PAGE_CONTEXT_SHARE)))+def _request_result_room() -> int | None:+ """Tokens this result may add before the NEXT prompt is over budget.++ None when the caller could not say, and every cap then behaves exactly as it did+ before this existed: external providers, the hosted path and any tool loop that does+ not price its own conversation all take that leg.+ """+ room = _REQUEST_RESULT_BUDGET.get()+ if room is None:+ return None+ try:+ return max(0, int(room))+ except (TypeError, ValueError):+ return None++def _window_context_tokens() -> int | None:"""The window this request is served by, or None when it cannot be read."""scoped = _REQUEST_CONTEXT_TOKENS.get()@@ -11934,6 +12028,34 @@ def _probe_cache(llama, ctx: int) -> dict:return cache+def _neutralized_for_prompt(chunk: str, llama) -> str:+ """``chunk`` as the outgoing request will carry it, rather than as it is in hand.++ The same sweep the request path applies, through the same helper and the backend's own+ markup profile, so the two cannot disagree about what a marker becomes. `_PROBE_ROLE`+ is a user role, which takes the full control rewrite a tool result takes rather than+ the boundary-only one an assistant turn takes.++ Best effort: a sweep that cannot run leaves the text as it was, which is the estimate+ this had before and never worse.+ """+ if not chunk:+ return chunk+ try:+ from .chat_template_helpers import neutralize_control_markup_in_messages # noqa: PLC0415++ swept = neutralize_control_markup_in_messages(+ [{"role": _PROBE_ROLE, "content": chunk}],+ None,+ getattr(llama, "markup_profile", None),+ )+ content = swept[0].get("content") if swept else None+ return content if isinstance(content, str) else chunk+ except Exception: # noqa: BLE001 -- measuring is never fatal+ logger.debug("result budget: markup sweep failed", exc_info = True)+ return chunk++def _loaded_token_counter(ctx: int):"""The tokenizer of the model serving this request, or None when there is not one.@@ -11994,6 +12116,14 @@ def _loaded_token_counter(ctx: int):cache[chunk] = valuedef _rendered(chunk: str):+ # Priced as the request will really carry it. A tool result is swept for control+ # markup before it is sent (`neutralize_control_markup_in_messages`, #7066), and+ # the sweep costs tokens: a live `<|eot_id|>` is one special token raw and several+ # ordinary ones once it has been broken up. A result full of them measured on the+ # raw text fits the room here and does not fit the prompt that follows, which is+ # the overflow this budget exists to prevent, reached through the leg that is+ # supposed to be the accurate one.+ chunk = _neutralized_for_prompt(chunk, llama)with _PROBE_COUNT_LOCK:hit = cache.get(chunk)if hit is not None and chunk != _PROBE_BASELINE:@@ -12087,7 +12217,13 @@ def _loaded_token_counter(ctx: int):_EXACT_FIT_PASSES = 5-def _exact_prefix_chars(text: str, chars: int, token_budget: float, ctx: int) -> int:+def _exact_prefix_chars(+ text: str,+ chars: int,+ token_budget: float,+ ctx: int,+ floor: int | None = None,+) -> int:"""`chars`, shrunk until the prefix really costs `token_budget`. Never grown.The estimate below charges every ASCII character a flat 0.25 tokens, which is an@@ -12102,14 +12238,20 @@ def _exact_prefix_chars(text: str, chars: int, token_budget: float, ctx: int) ->costs and shrinks every page that was already fine. So when a tokenizer is serving therequest, ask it; when none is, keep the estimate exactly as it was."""- # An estimate already at or below the readable floor cannot be improved on, so nothing- # measured here could change the caller's answer. Every value below is at most `chars`- # or is exactly `_MIN_PAGE_CHARS`, and `_dense_char_limit` clamps with- # `max(_MIN_PAGE_CHARS, ...)`, so with `chars <= _MIN_PAGE_CHARS` the caller lands on- # the floor whichever branch is taken. Checked before the counter is even looked up:- # this is the small-window case, and it used to spend a full set of round trips- # rediscovering a number the caller already had.- if chars <= _MIN_PAGE_CHARS:+ # `floor` is the caller's, not this function's: when a thread has 100 tokens left, the+ # 2,000-character comfort floor is 666 tokens of dense output and the overflow this+ # whole path exists to prevent. Defaulted, so the page callers are unchanged.+ if floor is None:+ floor = _MIN_PAGE_CHARS+ # An estimate already at or below the floor the caller guarantees cannot be improved+ # on, so nothing measured here could change its answer. Every value below is at most+ # `chars` or is exactly `floor`, so with `chars <= floor` the caller lands on the same+ # number whichever branch is taken. Checked before the counter is even looked up: this+ # is the small-window case, and it used to spend a full set of round trips+ # rediscovering a number the caller already had. Against the caller's floor rather+ # than `_MIN_PAGE_CHARS` itself, since a room-aware caller passes a lower one and+ # returning early on the legacy constant would skip the measurement it asked for.+ if chars <= floor:return charscounter = _loaded_token_counter(ctx)if counter is None:@@ -12144,15 +12286,67 @@ def _exact_prefix_chars(text: str, chars: int, token_budget: float, ctx: int) ->previous = (chars, spent)# The floor still applies, and stopping here saves a round trip that cannot# change the answer.- if fitted <= _MIN_PAGE_CHARS:- return _MIN_PAGE_CHARS+ if fitted <= floor:+ return floorchars = min(fitted, chars - 1) # always progress, so the loop cannot stall# Out of passes with the last shrink still unmeasured. Returning it would be the# unchecked prefix above, so fall back to the floor the caller guarantees anyway.- return _MIN_PAGE_CHARS+ return floor+++def _can_measure_tokens(ctx: int, text: str) -> bool:+ """Whether this request's tokens can really be counted, not merely whether a counter+ is exposed.++ `_loaded_token_counter` returns a callable that answers None whenever the probe does+ not come back with a number: `/apply-template` failing, or a chat template that drops+ the probe role, or a backend that stopped serving between the check and the call.+ `_exact_prefix_chars` then hands back the caller's estimate untouched, which charges+ plain ASCII the English four characters per token; base64, minified JSON and hashes+ run nearer two, so a room that was never halved is spent about twice over. A counter+ that cannot measure has to be treated exactly like a counter that is not there.++ Probed on this text's own opening rather than a constant, so a template that refuses+ some content and not other content is judged on what is actually being sized.+ """+ counter = _loaded_token_counter(ctx)+ if counter is None:+ return False+ return counter(text[:_MEASURABILITY_PROBE_CHARS] or "x") is not None+++# Enough to render as a real message and cheap enough to price on every call.+_MEASURABILITY_PROBE_CHARS = 64+++def _text_token_cost(text: str, ctx: int) -> float:+ """What ``text`` really costs, measured when the serving model can measure it.++ The estimate is the inverse of `_dense_prefix_chars`: ASCII at the English four+ characters per token, everything else at one. Doubled when nothing can check it, for+ the same reason `_UNMEASURED_ROOM_MARGIN` halves a room that cannot be measured.+ """+ counter = _loaded_token_counter(ctx) if ctx else None+ measured = None+ if counter is not None:+ try:+ spent = counter(text)+ measured = None if spent is None else float(spent)+ except Exception:+ logger.debug("token count failed", exc_info = True)+ if measured is not None:+ return measured+ # A counter that could not answer is a counter that is not there: taking its presence+ # as proof the estimate is safe is what leaves dense ASCII priced at the English rate.+ estimate = sum(0.25 if character.isascii() else 1.0 for character in text)+ return estimate / _UNMEASURED_ROOM_MARGIN-def _dense_char_limit(text: str, max_chars: int) -> int:+def _dense_char_limit(+ text: str,+ max_chars: int,+ reserve_tokens: float = 0.0,+) -> int:"""`max_chars`, lowered when `text` tokenises denser than four characters per token.Without this the window-derived caps above reserve their share only for English. On@@ -12162,18 +12356,70 @@ def _dense_char_limit(text: str, max_chars: int) -> int:That is the same irreducible refusal the budget exists to prevent."""ctx = _window_context_tokens()- if not ctx or len(text) <= _MIN_PAGE_CHARS:- return max_chars+ room = _request_result_room()+ if room is None and (not ctx or len(text) <= _MIN_PAGE_CHARS):+ # Nothing measured, so the caller's cap is the only budget there is, and the+ # reserve comes off it at the same four characters per token used everywhere else+ # the real rate is unknown.+ return max(0, max_chars - int(reserve_tokens * 4))+ if room is not None and not _can_measure_tokens(ctx or 0, text):+ # Nothing here can measure this model's tokens: `_can_measure_tokens` answers only+ # for a resident GGUF that just proved it can price a string, and a native+ # safetensors model is served through a loop with no rolling fit to recover if the+ # estimate is wrong. The estimate below+ # charges plain ASCII four characters per token, which is an English rate; base64,+ # minified JSON and hashes run nearer two, so the room could be spent twice over.+ # Halved so the optimistic rate becomes a pessimistic one. It costs a shorter+ # result on a path that cannot check its own arithmetic, which is the side to be+ # wrong on when being wrong the other way is an unrecoverable turn.+ room = int(room * _UNMEASURED_ROOM_MARGIN)# Kept a float, so English text lands on exactly the character budget rather than- # one character short of it.- share = ctx * _PAGE_CONTEXT_SHARE+ # one character short of it. Unknown window, known room: the room is the whole answer,+ # which is the native case where nothing here can see a context length.+ share = float(ctx * _PAGE_CONTEXT_SHARE) if ctx else float(room)+ # Whatever the caller will append is part of what has to fit, and it is taken off the+ # TOKEN budget rather than off the character cap: a punctuation-heavy path tokenises+ # far more densely than the prose characters that would otherwise be dropped to make+ # room for it, so subtracting its length in characters buys less room than it costs.+ share = max(0.0, share - reserve_tokens)+ if room is not None:+ room = max(0, int(room - reserve_tokens))+ # The share is a fraction of the WINDOW and does not fall as the thread fills, so+ # on its own it lets the last result before an overflow claim as much as the+ # first. Whichever of the two is smaller is the one that has to hold.+ share = min(share, float(room))+ # Never below the floor that keeps a result worth reading...+ floor = _MIN_PAGE_CHARS+ if room is not None:+ # ...but the floor is a comfort, not a right. 2,000 characters of dense output on+ # a thread with room for 100 tokens is the overflow this budget exists to prevent,+ # and the fit protects the newest turn so nothing downstream recovers. In the+ # extreme it leaves the stub alone, which is small enough to stay servable.+ #+ # MEASURED, not estimated: the flat four-characters-per-token rule hands back+ # about a third more than the room holds. Bottomed at one character rather than+ # the legacy floor, since going below it is the point.+ room_chars = _dense_prefix_chars(text, float(room))+ if not ctx:+ # No window to measure against, so the estimate above is the answer, already+ # halved for being unmeasurable.+ return min(max_chars, room_chars)+ # Bottomed at ZERO, not at one character. A thread at its budget measures a room of+ # zero, and a real tokenizer charges for the framing around even an empty string,+ # so the exact fit lands on nothing fitting. One character here is not a rounding+ # detail: it puts `_truncate` past its `limit <= 0` stub and back on the ordinary+ # notice, which is the ~90 tokens the stub exists to avoid spending when the+ # measurement just said there are none.+ floor = min(floor, _exact_prefix_chars(text, room_chars, float(room), ctx, 0))fitted = _dense_prefix_chars(text, share)# And measured rather than estimated when the serving model can measure it: the rule- # above is honest about non-ASCII and still optimistic about dense ASCII.- fitted = _exact_prefix_chars(text, min(fitted, max_chars), share, ctx)- # Never above what the caller allowed, and never below the floor that keeps a page- # worth reading. An explicit cap smaller than the floor still wins.- return min(max_chars, max(_MIN_PAGE_CHARS, fitted))+ # above is honest about non-ASCII and still optimistic about dense ASCII. The floor+ # goes WITH it: the exact fit bottoms out on that value, so leaving it at the legacy+ # 2,000 would hand back 2,000 characters on a thread with room for a few hundred --+ # the same overflow, reached through the leg that is supposed to be the accurate one.+ fitted = _exact_prefix_chars(text, min(fitted, max_chars), share, ctx, floor)+ # An explicit cap smaller than the floor still wins.+ return min(max_chars, max(floor, fitted))def _truncate_page_text(text: str, max_chars: int) -> str:@@ -13871,7 +14117,31 @@ def _cancel_watcher(cancel_event.wait(poll_interval) if cancel_event else None-def _truncate(text: str, limit: int | None = None) -> str:+def _appended_by_the_loop(text: str) -> float:+ """What the tool loop will add to this result after the tool has handed it back.++ `ToolCallCompletion.model_message` appends `TOOL_ERROR_NUDGE` to a result that opens+ with one of `TOOL_ERROR_PREFIXES`, after this budget has already let the body take the+ whole room, and a parallel batch of failed calls carries one nudge each. Priced in+ tokens like the retry hint, and only for the results that will really carry it.+ """+ try:+ from .tool_call_parser import TOOL_ERROR_NUDGE, TOOL_ERROR_PREFIXES # noqa: PLC0415+ except Exception: # noqa: BLE001 -- an unpriced nudge, not a failed tool call+ logger.debug("result budget: tool error nudge unavailable", exc_info = True)+ return 0.0+ if not text.startswith(TOOL_ERROR_PREFIXES):+ return 0.0+ return _text_token_cost(TOOL_ERROR_NUDGE, _window_context_tokens())+++def _truncate(+ text: str,+ limit: int | None = None,+ workdir: str | None = None,+ scope: "str | None" = "",+ hint: str = "",+) -> str:# Resolved per call, not bound at import: the default would freeze the constant# before any model is loaded, which is exactly when the window is still unknown.if limit is None:@@ -13879,18 +14149,926 @@ def _truncate(text: str, limit: int | None = None) -> str:# Same correction as a fetched page: a character cap reserves its share of the window# only for English, and a command that prints CJK or percent-escaped text costs two to# three times what the cap assumed.- limit = _dense_char_limit(text, limit)+ # Whatever the loop will append to this result once it has it: the tool-error nudge+ # goes on after the tool has returned, so a result sized to fill the room arrives at+ # the prompt with the nudge past the end of it. Charged only to the results that will+ # actually carry one, since a reserve taken from every result spends room the thread+ # has.+ cap, cost = limit, _appended_by_the_loop(text)+ if hint:+ # Priced in tokens, not characters, and taken off the budget before it is converted+ # (see `_dense_char_limit`). A failing absolute path is dense: subtracting its+ # LENGTH from the character cap frees fewer tokens than the hint then spends, which+ # is the unbudgeted overflow this whole change exists to prevent. It may take at+ # most half the room; past that the output is worth more than the advice about it.+ plain = _dense_char_limit(text, limit, cost)+ cost += _text_token_cost(hint, _window_context_tokens())+ with_hint = _dense_char_limit(text, limit, cost)+ if plain > 0 and (len(text) <= with_hint or with_hint * 2 >= plain):+ limit = with_hint+ else:+ # Nothing to spend on advice: at zero room the stub IS the message, and when+ # paying for it would cut the output in half the output is worth more than the+ # advice about it. Nothing is dropped while the result fits anyway.+ limit, hint, cost = plain, "", _appended_by_the_loop(text)+ else:+ limit = _dense_char_limit(text, limit, cost)# Mode-neutral notice: this result serves both the streaming UI and# non-streaming callers and must stay byte-identical with and without an# output_callback (a regression-tested invariant), so it can't claim the# user saw the full output.- if len(text) > limit:- return text[:limit] + (- f"\n\n... (truncated to {limit} chars for the model; {len(text)} chars "- "total. The full output is not retained here; any files the code wrote "- "persist in the working directory.)"+ if len(text) <= limit:+ return text + hint+ # Only now is a notice certain, and only now is it charged. Held back before the+ # measurement above, it would cut results that fit: a 100-token result with 200 tokens+ # of room would be sized against 72 and come back as 72 tokens of body plus ~70 of+ # notice, which is more of the window spent to say less. See `_RESULT_NOTICE_RESERVE`.+ #+ # Against a priced room only. With none, the caller's character cap is the whole+ # budget and the notice has always been appended past it; taking a token reserve off a+ # character cap there would cut every legacy caller's output to nothing.+ if _request_result_room() is not None:+ limit = _dense_char_limit(text, cap, cost + _RESULT_NOTICE_RESERVE)+ if limit <= 0 and len(_zero_room_stub(len(text), None, True)) >= len(text):+ # Decided BEFORE the spill: a result this short is served whole below, and writing+ # a file (and creating the spill directory) for output that is never cut is a side+ # effect with nothing on the other side of it.+ return text + hint+ spill, complete = _spill_full_output(text, workdir, scope)+ if limit <= 0:+ # No room for a body, so no room for the usual notice either: at this point the+ # notice IS the message, and the full one costs ~90 tokens of a budget that just+ # reported none. Kept to a line so the thread stays servable and the next fit can+ # evict older turns and recover, which is the whole reason a stub beats a refusal.+ stub = _zero_room_stub(len(text), spill, complete)+ # A short result costs less than the notice explaining it is gone, and replacing+ # "done" with a longer sentence saves nothing and loses the answer.+ return (stub if len(stub) < len(text) else text) + hint+ head, on_boundary = _head_whole_lines(text, limit)+ if spill is None:+ return (+ head+ + (+ f"\n\n... (truncated to {limit} chars for the model; {len(text)} chars "+ "total. The full output is not retained here; any files the code wrote "+ "persist in the working directory.)"+ )+ + hint)- return text+ # The rest is not advice, it is reachable: the sandbox persists between calls and the+ # model already has the terminal, so naming the exact next command turns a dead end+ # into paging. Truncating without one is what makes a model re-run the same command+ # and truncate identically.+ if on_boundary:+ # No "+1" when the head already ends in a newline: the count is of the lines+ # SHOWN, and a trailing break closes the last one rather than opening another.+ # Reachable at a limit of 1 on output that starts with a blank line, where the+ # head is "\n" alone and a count of two makes the hint resume at line 3, skipping+ # the first line the reader never saw.+ shown = 0 if not head else head.count("\n") + (0 if head.endswith("\n") else 1)+ total = text.count("\n") + 1+ resume = f"sed -n '{shown + 1},{shown + max(1, shown)}p' {spill}"+ where = f"showing lines 1-{shown} of {total}"+ else:+ # Cut inside a line, so a line number would name the NEXT one and skip the rest of+ # the line still unread -- on single-line output, everything. Bytes resume exactly+ # where this stopped. Measured in bytes, not characters, because that is what+ # `tail -c` counts and the two differ on any non-ASCII text.+ offset = len(head.encode("utf-8", "surrogatepass"))+ # The chunk is as many BYTES as the next `len(head)` characters actually occupy,+ # not as many bytes as this one did. `head -c` counts bytes, and a round number of+ # them lands inside a code point on any mixed-width text, so the model would read+ # back a mangled character at the end of every chunk (the runner decodes with+ # errors="replace"). The text is here, so the boundary is not a guess.+ chunk = text[len(head) : len(head) * 2 or None]+ span = len(chunk.encode("utf-8", "surrogatepass"))+ resume = f"tail -c +{offset + 1} {spill} | head -c {max(1, span)}"+ where = f"showing the first {len(head)} chars of {len(text)}"+ # The workdir sentence stays whatever else the notice says: it is about the files the+ # CODE wrote, not the spill, and it is the only thing telling the model those survive.+ common = (+ f"\n\n... (truncated to {limit} chars for the model; {where}, {len(text)} chars "+ f"total. {_capitalise(_spill_phrase(spill, complete))}, and any files the code "+ "wrote persist in the working directory"+ )+ if not _posix_tools_available():+ # A cmd-only Windows host has none of sed, tail or head, so the command would fail+ # and the model would most likely re-run the command that truncated. Name where+ # the output is and stop there, rather than promising paging that cannot happen.+ return head + common + ".)" + hint+ return head + common + f" -- continue with:\n {resume})" + hint+++def _fit_result_to_room(text, name = None):+ """Cap a tool that does not cap its own output, when this request priced its room.++ `python` and `terminal` truncate against this same budget before they return, so this+ is a no-op for them. The other tools hand their string back whole: an MCP response is+ unbounded, a fetched page or an edit receipt runs to a few thousand characters, and+ any of them can overflow a nearly full local thread and then be protected as its+ newest exchange, which is the failure the budget exists to prevent.++ No spill file: these tools have no sandbox of their own, and `edit_file` must not have+ a workdir created underneath a caller running with code execution off. So the cap+ comes with the plain notice and no paging hint, which is the scope limit this change+ states rather than hides.++ With no priced room -- external providers, the hosted path, any loop that does not+ measure its own conversation -- the text is returned untouched, so nothing outside a+ local tool loop changes.+ """+ if _request_result_room() is None or not isinstance(text, str) or not text:+ return text+ # Only the part the model will actually be shown is measured and cut. The rest is a+ # frontend-only envelope -- an MCP image array, web_search thumbnails, RAG sources --+ # which `strip_result_for_model` removes before the result is replayed, so it costs+ # the window nothing and must come back byte-identical: every consumer of the+ # __MCP_IMAGES__ envelope requires the whole valid JSON array, and a cut anywhere+ # inside a megabyte of base64 does not lose the image quietly, it replays the broken+ # fragment to the model instead.+ body, suffix = _split_frontend_suffix(text, name)+ if not body:+ return text+ fitted = _truncate(body)+ return fitted + suffix if fitted is not body else text+++def _split_frontend_suffix(text: str, name: "str | None") -> "tuple[str, str]":+ """``text`` split into what the model sees and the trailing frontend-only envelope.++ `strip_result_for_model` is the same function the replay path uses, so the split+ follows its validation exactly -- a result that merely mentions a sentinel keeps it in+ the body and is capped with it, which is the conservative half.+ """+ from .tool_loop_controller import strip_result_for_model++ try:+ body = strip_result_for_model(text, name)+ except Exception:+ logger.debug("frontend suffix split failed", exc_info = True)+ return text, ""+ # It only ever strips a suffix, so the remainder is the exact bytes that were removed+ # (including whatever whitespace the strip rstripped away).+ if not isinstance(body, str) or not text.startswith(body):+ return text, ""+ return body, text[len(body) :]+++def _head_whole_lines(text: str, limit: int) -> "tuple[str, bool]":+ """``text`` cut to at most ``limit`` characters, and whether it ended on a line break.++ Whole lines where possible, so the hint can name a line that resumes exactly where+ this stopped; a mid-line cut would repeat or lose one, and on a file printed verbatim+ that is a line of the user's own code.++ The flag is not decoration. One enormous line (minified JS, base64) has no boundary to+ cut on, and a line number would then name the line AFTER the one the reader is halfway+ through, skipping the rest of it. On single-line output that returns nothing at all.+ """+ head = text[:limit]+ cut = head.rfind("\n")+ # Only when a boundary is actually near the end: rewinding further would throw away+ # the whole result to keep the hint tidy.+ if cut > 0 and cut >= limit // 2:+ return head[:cut], True+ return head, head.endswith("\n")+++def _posix_tools_available() -> bool:+ """Whether the shell these tools run in has sed/tail/head.++ `_get_shell_cmd` falls back to `cmd /c` on a Windows host with no trusted bash, and+ none of those exist there, so a hint naming them is a command the model cannot run.+ The spill is still worth naming; the command is not.+ """+ if sys.platform != "win32":+ return True+ return _windows_bash() is not None+++# Dot-directory on purpose: `_snapshot_workdir_files` skips those, so the spill never+# appears as a file the model created and never earns a download card in the UI. A plain+# name here would put a phantom artifact beside every truncated result.+_SPILL_DIR = ".unsloth_tool_output"+_SPILL_KEEP = 20+# A result reaches here whole, so one `cat` of a multi-gigabyte file would be retained in+# full and twenty of them would fill the host's disk. The subprocess file-size limit does+# not apply: this output came through a pipe, not a file the sandbox wrote. A spill exists+# so the model can page through what it was shown, and 8 MB is already far more of that+# than any window can consume.+_SPILL_MAX_BYTES = 8 * 1024 * 1024++# How much of a result is encoded at a time when it is hashed. UTF-8 encodes one code+# point at a time, so a stream built from slices of the string is byte for byte the stream+# built from the whole of it, whatever the chunk size.+_SPILL_HASH_CHUNK_CHARS = 1 << 20+++def _digest_and_head(text: str, max_bytes: int) -> "tuple[str, int, bytes]":+ """``(digest, encoded length, the first max_bytes of it)``, in one bounded pass.++ Encoding the whole result to hash it and again to cut it puts two more copies of it+ through memory, and at most `max_bytes` of the second is ever written. The output this+ runs on is by definition the output that did not fit: `cat` of a file the model just+ wrote can be hundreds of megabytes, and spending it twice more inside the backend, at+ the point the result is already in hand, risks the stall or the OOM instead of the+ bounded answer this whole path exists to return.+ """+ digest = hashlib.sha256()+ head = bytearray()+ total = 0+ for start in range(0, len(text), _SPILL_HASH_CHUNK_CHARS):+ chunk = text[start : start + _SPILL_HASH_CHUNK_CHARS].encode("utf-8", "surrogatepass")+ digest.update(chunk)+ total += len(chunk)+ if len(head) < max_bytes:+ head += chunk[: max_bytes - len(head)]+ return digest.hexdigest()[:12], total, bytes(head)+++_SPILL_MAX_TOTAL_BYTES = 64 * 1024 * 1024+# Exactly the names `_spill_full_output` generates: twelve hex characters of a content+# digest. The prune below deletes what it matches, and the sandbox is the user's own+# directory -- a session may open on one that already holds a folder of this name, and+# anything in it that Studio did not write is not Studio's to remove.+_SPILL_NAME_RE = re.compile(r"[0-9a-f]{12}\.txt")+# Written once, when this process creates the spill directory. Ownership is RECORDED+# rather than inferred from the names inside: a sandbox can be a project the user opened,+# a directory of this name in it may be theirs, and a file name proves nothing about who+# wrote it. Without the marker nothing here writes, prunes or discounts anything there.+_SPILL_RECORD_HEADER = "unsloth-studio tool output "+# One lock per spill root. Appending a spill and rewriting the manifest after a prune are+# a read-modify-write over one shared file, and a project's chats share a sandbox: two+# calls spilling at once could otherwise have the pruner drop the entry the other just+# appended, leaving a file nothing counts, prunes, or recognises as Studio's.+_SPILL_LOCKS: "dict[str, threading.Lock]" = {}+_SPILL_LOCKS_GUARD = threading.Lock()+++def _spill_lock(root: str) -> "threading.Lock":+ key = os.path.realpath(root)+ with _SPILL_LOCKS_GUARD:+ return _SPILL_LOCKS.setdefault(key, threading.Lock())+++def _spill_records_dir() -> str:+ """Where the spill manifests live: Studio's own storage, NOT the sandbox.++ The sandbox is a directory tool code writes to, so nothing kept inside it can be+ evidence about the sandbox. A marker file there was replaceable by a link, and once it+ is a plain file the model can rewrite its contents and name the user's own files as+ Studio's, which turns the cleanup into a delete and the prune into an unlink. Held+ beside the other records this file already keeps outside the sandboxes.+ """+ try:+ from utils.paths.storage_roots import studio_root # noqa: PLC0415+ return os.path.join(str(studio_root()), "tool-output-records")+ except Exception:+ return os.path.join(+ os.path.dirname(os.path.realpath(sandbox_root())), "tool-output-records"+ )+++def _spill_record_path(root: str) -> str:+ """The record for one spill root, named by a digest of its real path."""+ digest = hashlib.sha256(os.path.realpath(root).encode("utf-8", "surrogatepass")).hexdigest()+ return os.path.join(_spill_records_dir(), f"{digest[:24]}.txt")+++def _spill_identity(root: str) -> "str | None":+ """The directory's device and inode, which is what the record claims ownership OF.++ Tool code can delete `.unsloth_tool_output` and make its own in the same place. That+ is a different directory with the same path, and a record that only knew the path+ would hand the new one's contents to the prune.+ """+ try:+ stat = os.lstat(root)+ except OSError:+ return None+ if not os.path.isdir(root) or os.path.islink(root):+ return None+ return f"{stat.st_dev}:{stat.st_ino}"+++def _own_spill_root(root: str) -> bool:+ """Whether the spill directory is one this process made, creating it if it is absent.++ Ownership is recorded outside the sandbox (`_spill_records_dir`) and is of a specific+ directory, not of a path: a `.unsloth_tool_output` that came with the sandbox, or one+ tool code deleted and recreated, has no matching record and is left alone entirely.+ """+ if os.path.islink(root):+ return False+ try:+ # The existence check, the creation and the first record are ONE locked step. Two+ # first-time spills in a shared project sandbox can both see the directory absent,+ # and the slower one would otherwise write an empty record over the winner's, which+ # leaves the winner's spill owned by nobody: never pruned, counted as the user's+ # content on cleanup, and outside the byte budget for good.+ with _spill_lock(root):+ existed = os.path.isdir(root)+ if not existed:+ if os.path.exists(root):+ return False+ os.makedirs(root, exist_ok = True)+ identity = _spill_identity(root)+ if identity is None:+ return False+ recorded = _spill_record(root)[0]+ if recorded is None:+ if existed and os.listdir(root):+ # Not ours and not empty, so it came with the sandbox.+ return False+ os.makedirs(_spill_records_dir(), exist_ok = True)+ _write_spill_manifest(root, {}, identity = identity)+ recorded = identity+ return recorded == identity+ except OSError:+ logger.debug("tool result spill ownership check failed", exc_info = True)+ return False+++# Only where the platform can do the whole write through a directory descriptor: Windows+# has neither O_DIRECTORY nor dir_fd, and there the path-based write below stands, with the+# link checks it already makes.+_DIR_FD_WRITES = (+ hasattr(os, "O_DIRECTORY")+ and os.open in getattr(os, "supports_dir_fd", set())+ and os.link in getattr(os, "supports_dir_fd", set())+ and os.unlink in getattr(os, "supports_dir_fd", set())+)+++def _write_spill_file(target_dir: str, name: str, body: str) -> "str | None":+ """Write one spill into ``target_dir``, without following a link at any point.++ The directory is opened ONCE, O_NOFOLLOW, and every step after that is relative to+ that descriptor. Checking the path and then writing to it by name is a race a shared+ project sandbox can lose: another call can replace the directory with a symlink in+ between, and both the create and the rename would follow it, putting this output+ outside the sandbox with the backend's own permissions.++ Still written to a fresh O_EXCL file and installed under the real name rather than+ opened over whatever is there: the spill name comes from content the model produced, so+ it can predict it and pre-create it, as a symlink or as a hard link sharing an inode+ with some file elsewhere.++ Installed with `os.link`, which fails when the name is taken, rather than a rename,+ which on POSIX replaces silently. The caller checks the destination first, but between+ that check and this write another call sharing the workspace can put a file there, and+ a rename would then destroy it.++ Returns the stamp of what was installed, or None if nothing was. The stamp is taken+ here rather than re-read from the path afterwards, because by then another call can+ have replaced the file and the record would name its content as Studio's.+ """+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL+ if not _DIR_FD_WRITES:+ tmp = os.path.join(target_dir, f".tmp-{uuid.uuid4().hex[:12]}.txt")+ try:+ with os.fdopen(+ os.open(tmp, flags | getattr(os, "O_NOFOLLOW", 0), 0o600),+ "w",+ encoding = "utf-8",+ newline = "",+ ) as handle:+ handle.write(body)+ installed = os.path.join(target_dir, name)+ os.link(tmp, installed)+ _quiet_unlink(tmp)+ return _spill_stamp(installed)+ except OSError:+ logger.debug("tool result spill write failed", exc_info = True)+ _quiet_unlink(tmp)+ return None+ dir_fd = None+ tmp_name = f".tmp-{uuid.uuid4().hex[:12]}.txt"+ try:+ dir_fd = os.open(target_dir, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)+ with os.fdopen(+ os.open(tmp_name, flags, 0o600, dir_fd = dir_fd), "w", encoding = "utf-8", newline = ""+ ) as handle:+ handle.write(body)+ # `os.link` rather than a rename: rename replaces the destination silently on+ # POSIX, and the name may have been taken since the caller looked. link fails with+ # EEXIST instead, which is the answer this wants.+ os.link(tmp_name, name, src_dir_fd = dir_fd, dst_dir_fd = dir_fd)+ _quiet_unlink(tmp_name, dir_fd = dir_fd)+ # Through the same descriptor, so it is the file just linked rather than whatever+ # the name resolves to by the time this returns.+ stat = os.stat(name, dir_fd = dir_fd, follow_symlinks = False)+ return ":".join(+ str(part)+ for part in (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns)+ )+ except OSError:+ logger.debug("tool result spill write failed", exc_info = True)+ if dir_fd is not None:+ _quiet_unlink(tmp_name, dir_fd = dir_fd)+ return None+ finally:+ if dir_fd is not None:+ os.close(dir_fd)+++def _quiet_unlink(path: str, dir_fd = None) -> None:+ try:+ os.unlink(path, dir_fd = dir_fd) if dir_fd is not None else os.unlink(path)+ except OSError:+ pass+++def _forget_spill_record(path: str) -> None:+ """Drop the record for a sandbox that has been removed. See `_spill_records_dir`."""+ try:+ os.remove(path)+ except OSError:+ pass+++def _spill_stamp(path: str) -> "str | None":+ """What a spill looked like when it was written: device, inode, size, mtime, ctime.++ A recorded PATH is not the file: tool code can write its own content over one, in+ place, keeping the inode. mtime alone is not enough either, since `os.utime` can put+ it back and a coarse-grained filesystem can leave it unchanged on its own; ctime moves+ on any write to the file OR its metadata and cannot be set back from userspace, so+ restoring the mtime is itself a change this sees.+ """+ try:+ stat = os.lstat(path)+ except OSError:+ return None+ if not os.path.isfile(path) or os.path.islink(path):+ return None+ return ":".join(+ str(part)+ for part in (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns)+ )+++def _stamp_size(stamp: str) -> "int | None":+ """The size a stamp remembers. See `_spill_stamp`."""+ try:+ return int(stamp.split(":")[2])+ except (IndexError, ValueError):+ return None+++def _file_digest(path: str, expected_size: "int | None" = None) -> "str | None":+ """The digest of what is on disk now, or None when it is not a file this may read.++ Opened O_NOFOLLOW and O_NONBLOCK and checked through the DESCRIPTOR, not the path. The+ stamp was taken a moment ago and this runs in the sandbox's own directory: between the+ two, tool code can put a symlink at the name, or a FIFO, or a device. A plain open+ would follow the first and block forever on the others, and this is called+ synchronously by the prune and by chat deletion, neither of which has a timeout.++ ``expected_size`` refuses anything that is not the size the record remembers, so a+ file swapped for an enormous one is not hashed before it is rejected.+ """+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)+ fd = None+ try:+ fd = os.open(path, flags)+ info = os.fstat(fd)+ if not stat.S_ISREG(info.st_mode):+ return None+ if expected_size is not None and info.st_size != expected_size:+ return None+ digest = hashlib.sha256()+ with os.fdopen(fd, "rb") as handle:+ fd = None+ for chunk in iter(lambda: handle.read(1 << 20), b""):+ digest.update(chunk)+ return digest.hexdigest()+ except OSError:+ return None+ finally:+ if fd is not None:+ os.close(fd)+++def _is_recorded_spill(root: str, path: str, owned: "dict[str, tuple[str, str]]") -> bool:+ """Whether ``path`` is still the file this wrote, rather than one written over it.++ Both the stamp and the CONTENT, because the stamp is only evidence about metadata: the+ content is what says this file is still the output this process put there, and it is+ the last word before anything is deleted. Read only after the cheap check passes, so+ the cost falls on the handful of files that already look like ours.+ """+ relative = os.path.relpath(path, root).replace(os.sep, "/")+ recorded = owned.get(relative)+ if recorded is None or recorded[0] != _spill_stamp(path):+ return False+ return recorded[1] == _file_digest(path, _stamp_size(recorded[0]))+++def _spill_record(root: str) -> "tuple[str | None, dict[str, tuple[str, str]]]":+ """The recorded identity of ``root`` and the spills written into it.++ ``(None, {})`` when there is no record, which is the answer for any directory this+ process did not create. An unreadable or half-written record reads the same way, which+ retains too much rather than deleting something that was never ours.+ """+ try:+ with open(_spill_record_path(root), encoding = "utf-8") as handle:+ lines = handle.read().splitlines()+ except OSError:+ return None, {}+ if not lines or not lines[0].startswith(_SPILL_RECORD_HEADER):+ return None, {}+ identity = lines[0][len(_SPILL_RECORD_HEADER) :].strip() or None+ entries: "dict[str, tuple[str, str]]" = {}+ for line in lines[1:]:+ name, _, rest = line.strip().partition("\t")+ stamp, _, digest = rest.partition("\t")+ if name and stamp and digest:+ # Last line wins: the same content spilled twice rewrites the file, and the+ # stamp of the write actually on disk is the later one.+ entries[name] = (stamp, digest)+ return identity, entries+++def _spill_manifest(root: str) -> "dict[str, tuple[str, str]]":+ """The spills this process wrote into ``root``: relative path to stamp and digest."""+ return _spill_record(root)[1]+++def _write_spill_manifest(+ root: str,+ entries,+ identity: "str | None" = None,+) -> None:+ """Rewrite the record with ``entries`` (relative name to stamp), atomically."""+ if identity is None:+ identity = _spill_record(root)[0]+ path = _spill_record_path(root)+ os.makedirs(os.path.dirname(path), exist_ok = True)+ tmp = None+ try:+ fd, tmp = tempfile.mkstemp(dir = os.path.dirname(path), prefix = ".tmp-record-")+ with os.fdopen(fd, "w", encoding = "utf-8") as handle:+ handle.write(f"{_SPILL_RECORD_HEADER}{identity or ''}\n")+ for name in sorted(entries):+ stamp, digest = entries[name]+ handle.write(f"{name}\t{stamp}\t{digest}\n")+ os.replace(tmp, path)+ tmp = None+ finally:+ if tmp is not None and os.path.exists(tmp):+ try:+ os.remove(tmp)+ except OSError:+ pass+++def _record_spill(root: str, relative: str, stamp: str, digest: str) -> None:+ """Append one written spill, with the stamp and digest of what was INSTALLED.++ Not re-read from the path: between the install and this, another call sharing the+ sandbox can replace the file, and stating the path then records that call's content as+ Studio's, which a later prune or cleanup would delete. The writer knows what it put+ there, so it says so.+ """+ try:+ with _spill_lock(root):+ with open(_spill_record_path(root), "a", encoding = "utf-8") as handle:+ handle.write(f"{relative}\t{stamp}\t{digest}\n")+ except OSError:+ logger.debug("tool result spill record append failed", exc_info = True)+++def _spill_scope(session_id: "str | None", thread_id: "str | None") -> "str | None":+ """Where this call's spills belong, or None for "retain nothing".++ Nothing is retained in a sandbox that more than one chat runs in. A project's chats+ share one session by design (`project_session_id`) and a call with no session lands in+ the shared `_default` one, and in both the sandbox is a directory every sibling chat's+ model has a terminal in: a sub-directory is not access control, it is a name. Writing+ a result there puts output that existed only in one chat's response on disk where the+ next chat can read it, and lets that chat prune the files this one was told to page+ through.++ So the trade is stated rather than hidden: in a project, a large result is truncated+ with a notice and no continuation. Only a chat with a sandbox of its own gets paging.+ ``thread_id`` is taken and unused for that reason -- it identifies the chat, which is+ not the thing that has to be separate.+ """+ if not session_id or session_id.startswith(_PROJECT_SESSION_PREFIX):+ return None+ return ""+++def _spill_phrase(spill: str, complete: bool) -> str:+ """How the notice names the spill, which depends on whether all of it got there.++ Lower case, and capitalised by the caller that needs it: the phrase ends in a path,+ and case-folding a whole sentence to fit it into another would fold that too.+ """+ if complete:+ return f"full output saved to {spill}"+ return f"the first {_SPILL_MAX_BYTES} bytes of it are saved to {spill}"+++def _capitalise(phrase: str) -> str:+ """First letter only. `str.capitalize` lower-cases the rest, including a path."""+ return phrase[:1].upper() + phrase[1:]+++def _zero_room_stub(size: int, spill: "str | None", complete: bool) -> str:+ """The whole message when there is no room for a body. See `_truncate`."""+ located = f", {_spill_phrase(spill, complete)}" if spill else ""+ return f"(output omitted: {size} chars, no context room left{located})"+++def _spill_full_output(+ text: str,+ workdir: str | None,+ scope: "str | None" = "",+) -> "tuple[str | None, bool]":+ """Write the result into the sandbox; return its relative path and whether it is whole.++ ``(None, True)`` whenever it cannot be done -- no workdir, a read-only mount, a full+ disk, a path that is not what it claims to be. The caller then falls back to the plain+ notice, because a hint naming a file that is not there is worse than admitting the+ output is gone.+ """+ if not workdir or not os.path.isdir(workdir) or scope is None:+ return None, True+ try:+ if not _own_spill_root(os.path.join(workdir, _SPILL_DIR)):+ return None, True+ relative = f"{_SPILL_DIR}/{scope}" if scope else _SPILL_DIR+ target_dir = os.path.join(workdir, *relative.split("/"))+ # The sandbox is a directory the model runs commands in, so `.unsloth_tool_output`+ # may already be a symlink it made, or one that came with a project opened as the+ # workdir. makedirs(exist_ok=True) and a plain open() both follow it, which writes+ # this result outside the sandbox with the backend's own permissions and then lets+ # the prune delete files there. Refuse instead: no spill means a notice without a+ # continuation hint, which is a great deal better than a write out of bounds.+ if any(+ os.path.islink(os.path.join(workdir, *relative.split("/")[: n + 1]))+ for n in range(len(relative.split("/")))+ ):+ return None, True+ os.makedirs(target_dir, exist_ok = True)+ expected = os.path.join(os.path.realpath(workdir), *relative.split("/"))+ if os.path.realpath(target_dir) != expected:+ return None, True+ # Named from the CONTENT, not at random. The result has to come back byte-identical+ # with and without an output_callback (the streaming invariant asserted by+ # test_truncated_result_identical_and_notice_neutral_with_streaming), and a random+ # name puts a different path in the notice on each of the two runs. Content+ # addressing also means asking for the same file twice reuses one spill instead of+ # filling the sandbox with copies, which is the repeat case this whole change is+ # about.+ # Bounded before it is written rather than after: pruning by count alone still+ # lets one enormous result through, and by then it is already on the disk.+ digest, spilled_bytes, head = _digest_and_head(text, _SPILL_MAX_BYTES)+ name = f"{digest}.txt"+ complete = spilled_bytes <= _SPILL_MAX_BYTES+ # Cut on a character boundary, so what lands is still decodable text.+ body = text if complete else head.decode("utf-8", "ignore")+ # newline="" so the bytes on disk are the bytes measured. The default translates+ # "\n" to os.linesep, which on Windows writes an extra byte per line, and the+ # byte offset in the continuation hint is counted from the untranslated text --+ # so a mid-line resume would start one byte early for every preceding newline.+ path = os.path.join(target_dir, name)+ # Written to a fresh O_EXCL file and moved into place, never opened O_TRUNC over+ # whatever is already at that path. The spill name is derived from content the+ # model produced, so it can predict it and pre-create it: as a symlink (refused by+ # O_NOFOLLOW and the check above) or as a HARD link, which reports islink() false+ # and shares the inode of some file outside the sandbox. Truncating that writes+ # through to it with the backend's privileges; replacing a directory entry does+ # not touch the linked file at all.+ # The name comes from the content, so re-running a command lands on the same path,+ # and the file there may no longer be the spill this wrote: a later call can have+ # put the user's own data at it. `_is_recorded_spill` is what says whether it is+ # still ours, and the rename below would otherwise replace it either way.+ path = os.path.join(target_dir, name)+ if os.path.exists(path):+ # The name is the digest of the text, so a recorded spill at it already HOLDS+ # this content: reuse it and write nothing. That is the repeat case this whole+ # change is about, and not writing is also the only way not to race with+ # another call that may be replacing the file right now.+ if _is_recorded_spill(+ os.path.join(workdir, _SPILL_DIR),+ path,+ _spill_manifest(os.path.join(workdir, _SPILL_DIR)),+ ):+ return f"{relative}/{name}", complete+ # Not ours: the user's code put something at that path, and the install below+ # would replace it.+ return None, True+ stamp = _write_spill_file(target_dir, name, body)+ if stamp is None:+ return None, True+ _record_spill(+ os.path.join(workdir, _SPILL_DIR),+ f"{scope}/{name}" if scope else name,+ stamp,+ hashlib.sha256(body.encode("utf-8", "surrogatepass")).hexdigest(),+ )+ _prune_spills(target_dir, os.path.join(workdir, _SPILL_DIR))+ # Relative, so the command works from the cwd the tools already run in, and so+ # the absolute sandbox path never reaches the model.+ return f"{relative}/{name}", complete+ except Exception:+ logger.debug("tool result spill failed", exc_info = True)+ return None, True+++def _spill_files(root: str, directory: str, owned: "set[str]") -> "list[str]":+ """The spills in one directory: the ones ``owned`` records this process having written.++ Everything else there is the user's, whatever it is called. Links are never spills.+ """+ try:+ names = os.listdir(directory)+ except OSError:+ return []+ return [+ path+ for path in (os.path.join(directory, name) for name in names)+ if _is_recorded_spill(root, path, owned)+ ]+++def _unlink_verified_spill(root: str, path: str, owned: "dict[str, tuple[str, str]]") -> bool:+ """Delete a spill, and only ever the file that was checked.++ Moved to a private name first. A rename is atomic, so from that point the inode this+ verifies is the inode this deletes: a sandbox writer that replaces the original name+ afterwards replaces nothing that is on its way out. Verifying and then unlinking by+ name cannot promise that, because the manifest lock orders Studio's own threads and+ the thing racing here is the sandbox.++ Checked again under the private name, and put back if it no longer matches, since at+ that point it is not the file this recorded and is not this to delete. The rename+ itself moves ctime, which is ours to move, so the second check compares the device,+ inode, size and mtime, and the content.++ Nothing but a regular file with the recorded identity is moved at all: a directory or+ a FIFO left at the name by the sandbox is rejected through its own descriptor before+ the rename, so the restore below is never asked to put back a kind of thing `os.link`+ cannot. That leaves only the vanishing window between the check and the rename, and+ the restore handles it by falling back to a rename when the name is free again.+ """+ directory, name = os.path.split(path)+ recorded = owned.get(os.path.relpath(path, root).replace(os.sep, "/"))+ if recorded is None:+ return False+ if not _is_stamped_regular(path, recorded[0]):+ return False+ private = os.path.join(directory, f".tmp-prune-{uuid.uuid4().hex[:12]}.txt")+ try:+ os.rename(path, private)+ except OSError:+ return False+ stamp = _spill_stamp(private)+ if (+ stamp is not None+ and stamp.split(":")[:4] == recorded[0].split(":")[:4]+ and recorded[1] == _file_digest(private, _stamp_size(recorded[0]))+ ):+ _quiet_unlink(private)+ return True+ _restore_pruned_path(private, path)+ return False+++def _is_stamped_regular(path: str, stamp: str) -> bool:+ """Whether ``path`` is right now the regular file ``stamp`` recorded.++ Through a descriptor rather than the path, and for the same reasons `_file_digest`+ does it that way: O_NOFOLLOW refuses a symlink dropped at the name and O_NONBLOCK+ refuses to hang on a FIFO or a device. A directory opens, and is rejected by the+ mode check. ctime is deliberately not compared -- the caller compares it under the+ private name, where the rename it performs has already moved it.+ """+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)+ fd = None+ try:+ fd = os.open(path, flags)+ info = os.fstat(fd)+ except OSError:+ return False+ finally:+ if fd is not None:+ os.close(fd)+ if not stat.S_ISREG(info.st_mode):+ return False+ return [str(part) for part in (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns)] == (+ stamp.split(":")[:4]+ )+++def _restore_pruned_path(private: str, path: str) -> None:+ """Put back something the prune moved but must not delete.++ `os.link` first, because it refuses to overwrite: if the sandbox has taken the name+ again in the meantime, the file it put there is not this to replace. A hard link+ cannot be made to a directory, so when it fails and the name is in fact free, the+ rename that moved this here is reversed instead, which works whatever was moved.+ Neither can promise the name is still free at the instant it runs, so the last resort+ is to leave the data under the private name and say where it went, rather than+ unlink it.+ """+ try:+ os.link(private, path)+ _quiet_unlink(private)+ return+ except OSError:+ pass+ try:+ if not os.path.lexists(path):+ os.rename(private, path)+ return+ except OSError:+ pass+ # The name is taken again, so whatever is there now is not this to overwrite either.+ # The file stays, under a name nothing will prune.+ logger.warning("tool result spill prune: kept a swapped file as %s", private)+++def _prune_spills(target_dir: str, root: "str | None" = None) -> None:+ """Bound this scope by count and the whole spill tree by bytes.++ A long session prints many large results and each one is retained; without this the+ sandbox grows without bound for output the model has almost certainly finished paging+ through.++ The byte budget is enforced across ``root`` rather than per directory. A project's+ chats each get their own scope under one shared sandbox, so a per-directory limit is+ really a per-chat limit and a project with many tool-using chats multiplies it by+ however many there are.+ """+ root = root or target_dir+ try:+ # Held across the read and the rewrite below, so a spill recorded in between is+ # not dropped from the manifest by a prune that read it before the append.+ with _spill_lock(root):+ _prune_spills_locked(target_dir, root)+ except Exception:+ logger.debug("tool result spill prune failed", exc_info = True)+++def _prune_spills_locked(target_dir: str, root: str) -> None:+ try:+ identity, owned = _spill_record(root)+ if identity is None or identity != _spill_identity(root):+ # No record of this directory, so it came with the sandbox or was replaced.+ return+ removed = set()+ # Newest first within this scope, so the count keeps the ones still being paged.+ for extra in sorted(+ _spill_files(root, target_dir, owned), key = os.path.getmtime, reverse = True+ )[_SPILL_KEEP:]:+ if _unlink_verified_spill(root, extra, owned):+ removed.add(extra)++ everything = [p for p in _spill_files(root, root, owned) if p not in removed]+ for name in sorted(os.listdir(root)):+ scope = os.path.join(root, name)+ if os.path.isdir(scope) and not os.path.islink(scope):+ everything.extend(p for p in _spill_files(root, scope, owned) if p not in removed)+ kept, total = 0, 0+ for path in sorted(everything, key = os.path.getmtime, reverse = True):+ try:+ size = os.path.getsize(path)+ except OSError:+ continue+ # The newest is always kept, whatever the budget says: it is the file the+ # notice about to be returned names, and a hint pointing at a path that was+ # deleted on the way out is worse than no hint at all.+ if kept == 0 or total + size <= _SPILL_MAX_TOTAL_BYTES:+ kept, total = kept + 1, total + size+ continue+ if _unlink_verified_spill(root, path, owned):+ removed.add(path)+ # The manifest follows the files: a name left in it after its file is gone would+ # keep being counted as something this owns.+ _write_spill_manifest(+ root,+ {+ name: stamp+ for name, stamp in owned.items()+ if os.path.join(root, *name.split("/")) not in removed+ },+ )+ # An emptied scope is a chat that stopped spilling, and leaving its directory+ # behind is what makes the sandbox look non-empty to the cleanup.+ for name in sorted(os.listdir(root)):+ scope = os.path.join(root, name)+ if os.path.isdir(scope) and not os.path.islink(scope) and not os.listdir(scope):+ try:+ os.rmdir(scope)+ except OSError:+ pass+ except Exception:+ logger.debug("tool result spill prune failed", exc_info = True)# ChatGPT code-interpreter path conventions models write out of habit; none@@ -14362,6 +15540,7 @@ def _python_exec(session_id: str | None = None,disable_sandbox: bool = False,output_callback = None,+ thread_id: str | None = None,) -> str:"""Execute Python code in a subprocess sandbox.@@ -14377,7 +15556,11 @@ def _python_exec(if not disable_sandbox:error = _check_code_safety(code)if error:- return error+ # Capped like any other result: the analyzer names every occurrence it+ # found, so code that repeats a forbidden construct enough times reports+ # back something larger than the room that is left, which is the overflow+ # this budget exists to prevent. See `_fit_result_to_room`.+ return _truncate(error)# Stripping the child env is not enough: a same-UID child can read# /proc/<getppid()>/environ to recover the unfiltered secrets, so close# that read here too, not only in bypass mode. Best-effort: the child env@@ -14394,6 +15577,12 @@ def _python_exec(tmp_path = None_scratch_name = Noneworkdir = _get_workdir(session_id)+ # `_get_workdir(None)` is the shared `_default` sandbox, and a project's chats share+ # one session by design. Retaining a result in either, under a path the next chat can+ # list, would leave behind output that existed only in this call's own response. See+ # `_spill_scope`, which returns None for exactly those cases.+ spill_scope = _spill_scope(session_id, thread_id)+ spill_dir = workdir if session_id else Nonecall_token = _call_started(workdir)# Snapshot mtimes to detect new and overwritten files._before = _snapshot_workdir_files(workdir)@@ -14481,11 +15670,17 @@ def _python_exec(# paths are judged against the real workdir (project sessions live outside# the default sandbox root).hint = _missing_path_hint(result, workdir)- result = _truncate(result) if result.strip() else "(no output)"- result += hint- # Before ours is appended, and whether or not one is: a program's own- # marker line is not an envelope.+ # Before the fit, not after it. Defusing inserts a space into every line that+ # opens with a marker, so a result full of them grows after it has been measured+ # and the text replayed to the model is larger than the prefix that was admitted.+ # Before ours is appended, and whether or not one is: a program's own marker line+ # is not an envelope.result = _defuse_sentinels(result)+ result = (+ _truncate(result, workdir = spill_dir, scope = spill_scope, hint = hint)+ if result.strip()+ else "(no output)" + hint+ )# Only for a chat that has an id: without one every first turn shares# the _default workdir, so a card pinned to it would later download@@ -14496,7 +15691,9 @@ def _python_exec(return resultexcept Exception as e:- return f"Execution error: {e}"+ # An exception message carries whatever the failure put in it, so it is capped+ # like the result would have been.+ return _truncate(f"Execution error: {e}")finally:_call_finished(call_token)if _scratch_name:@@ -14517,6 +15714,7 @@ def _bash_exec(session_id: str | None = None,disable_sandbox: bool = False,output_callback = None,+ thread_id: str | None = None,) -> str:"""Execute a bash command in a subprocess sandbox.@@ -14532,7 +15730,9 @@ def _bash_exec(if not disable_sandbox:blocked = _find_blocked_commands(command)if blocked:- return f"Blocked command(s) for safety: {', '.join(sorted(blocked))}"+ # Capped for the same reason the Python analyzer's error is: it lists what+ # it found in the command it was handed.+ return _truncate(f"Blocked command(s) for safety: {', '.join(sorted(blocked))}")# Stripping the child env is not enough: a same-UID child can read# /proc/<getppid()>/environ to recover the unfiltered secrets, so close# that read here too, not only in bypass mode. Best-effort: the child env@@ -14547,9 +15747,14 @@ def _bash_exec()workdir = None+ spill_dir = None+ spill_scope = Nonecall_token = Nonetry:workdir = _get_workdir(session_id)+ # Same scoping as _python_exec: nothing is retained in a sandbox that is shared.+ spill_scope = _spill_scope(session_id, thread_id)+ spill_dir = workdir if session_id else Nonecall_token = _call_started(workdir)# Same pre-run snapshot as _python_exec. A command that writes a file used# to produce "(no output)" and no other trace anywhere in the product.@@ -14611,16 +15816,21 @@ def _bash_exec(result = f"Exit code {proc.returncode}:\n{result}"# Same missing-path healing as _python_exec.hint = _missing_path_hint(result, workdir)- result = _truncate(result) if result.strip() else "(no output)"- result += hint- result = _defuse_sentinels(result) # see _python_exec+ result = _defuse_sentinels(result) # before the fit; see _python_exec+ result = (+ _truncate(result, workdir = spill_dir, scope = spill_scope, hint = hint)+ if result.strip()+ else "(no output)" + hint+ )# Only for a chat that has an id (see _python_exec).if session_id:result += _created_file_sentinels(workdir, _before, None, call_token)return resultexcept Exception as e:- return f"Execution error: {e}"+ # An exception message carries whatever the failure put in it, so it is capped+ # like the result would have been.+ return _truncate(f"Execution error: {e}")finally:_call_finished(call_token)_forget_tool_pid(locals().get("proc"))diff --git a/studio/backend/tests/test_tool_result_fits_window.py b/studio/backend/tests/test_tool_result_fits_window.pynew file mode 100644index 00000000000..3cf526efb65--- /dev/null+++ b/studio/backend/tests/test_tool_result_fits_window.py@@ -0,0 +1,2150 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A tool result has to fit the room the conversation has LEFT, not a share of the window.++`test_web_page_cap_fits_window.py` made the cap a share of the loaded window, which fixed+one result being larger than the whole prompt budget. It does not fall as the thread fills,+so the last result before an overflow is allowed exactly as much as the first:++ ctx 4096 -> min(16000, max(2000, 4096 * 4 * 0.35)) = 5734 chars++which is roughly 1,900 tokens of the dense ASCII these tools print, about 47% of the whole+window, granted no matter how little is left. Reported live: `Qwen3.6-35B-A3B-GGUF` at 4096+with code execution, "Create a Flappy Bird and save it to game.html", then "Print and show+game.html verbatim" repeatedly. Each `cat` is individually under the cap and they accumulate+until the turn cannot be served, and nothing downstream recovers -- the fit protects the+newest turn, so compaction may not drop the very result that does not fit.+"""++from __future__ import annotations++import hashlib+import shutil+import os++import pytest++from core.inference import tools+from core.inference.context_window import (+ _RESULT_NOTICE_RESERVE,+ estimate_messages_tokens_conservative,+ estimate_messages_tokens_dense,+ prompt_budget,+ tool_result_budget,+)++[email protected](autouse = True)+def _unknown_window(monkeypatch):+ """Default to "no model loaded", and to "the caller did not price the thread"."""+ monkeypatch.setattr(tools, "_loaded_context_tokens", lambda: None)+ ctx_token = tools._REQUEST_CONTEXT_TOKENS.set(tools._UNSET_CONTEXT_TOKENS)+ room_token = tools._REQUEST_RESULT_BUDGET.set(None)+ yield+ tools._REQUEST_CONTEXT_TOKENS.reset(ctx_token)+ tools._REQUEST_RESULT_BUDGET.reset(room_token)+++def _window(monkeypatch, ctx):+ monkeypatch.setattr(tools, "_loaded_context_tokens", lambda: ctx)+++def _spill_path(out: str) -> str:+ """The spill path out of a notice, without the punctuation that follows it."""+ return out.split("saved to ")[1].split(" ")[0].rstrip(".,)")++[email protected](autouse = True)+def _records(tmp_path_factory, monkeypatch):+ """Ownership records live in Studio's own storage, so tests get their own copy of it+ rather than writing into the real one."""+ where = tmp_path_factory.mktemp("tool-output-records")+ monkeypatch.setattr(tools, "_spill_records_dir", lambda: str(where))+++def _own(workdir) -> "os.PathLike":+ """The spill directory as Studio itself would leave it: created, and recorded as ours.++ Tests that pre-create it are standing in for a sandbox this process has already+ spilled into. A directory made any other way has no record, which is the case+ `_own_spill_root` deliberately refuses.+ """+ root = workdir / tools._SPILL_DIR+ assert tools._own_spill_root(str(root))+ return root+++def _spills(directory) -> list:+ """Everything in a spill directory. The ownership record is not in there."""+ return list(directory.iterdir())+++def _room(value):+ tools._REQUEST_RESULT_BUDGET.set(value)+++# Dense ASCII, which is what a printed file is: no spaces to tokenise cheaply.+def _dense(chars: int) -> str:+ line = "x" * 79+ out = "\n".join(line for _ in range(chars // 80 + 1))+ return out[:chars]+++class TestTheBudgetFollowsTheRoom:+ def test_it_shrinks_as_the_conversation_grows(self):+ """The whole point: the same window, three different answers."""+ ctx, target = 4096, prompt_budget(4096, None)+ early = tool_result_budget(ctx, None, 200)+ middle = tool_result_budget(ctx, None, target // 2)+ late = tool_result_budget(ctx, None, target - 100)++ assert early > middle > late+ # And never more than the budget it is measured against.+ assert early <= target++ def test_a_full_thread_gets_nothing_rather_than_a_share(self):+ """At or past the budget the answer is zero, not a floor. A floor here is the+ overflow: the result lands in the newest turn, which the next fit protects."""+ target = prompt_budget(4096, None)+ assert tool_result_budget(4096, None, target) == 0+ assert tool_result_budget(4096, None, target + 5_000) == 0++ def test_it_reserves_the_reply_room_rather_than_filling_the_window(self):+ """Sized against prompt_budget, not context_length. Filling to 99% of the physical+ window leaves the prompt fitting and nothing to answer in, which is the+ reserve-missing case the rolling fit already has to rescue."""+ room = tool_result_budget(4096, None, 0)+ assert room < prompt_budget(4096, None) <= 4096+ # The gap is the reply reserve, and it is most of the difference from the window.+ assert 4096 - room > 1_000+++class TestTheCharacterCapHonoursIt:+ def test_a_nearly_full_thread_cannot_spend_the_window_share(self, monkeypatch):+ """5,734 characters is what the window share allows at ctx 4096. With 120 tokens+ of room left it must not be handed anything close to that."""+ _window(monkeypatch, 4096)+ text = _dense(40_000)++ wide = tools._dense_char_limit(text, tools._MAX_OUTPUT_CHARS)+ _room(120)+ narrow = tools._dense_char_limit(text, tools._MAX_OUTPUT_CHARS)++ assert narrow < wide+ # 120 tokens of dense ASCII is a few hundred characters, nowhere near the share.+ assert narrow < 2_000++ def test_the_floor_yields_when_the_room_is_smaller_than_it(self, monkeypatch):+ """_MIN_PAGE_CHARS keeps a result worth reading, but it is a comfort and not a+ right: holding 2,000 characters of dense output when 30 tokens remain reinstates+ the overflow the budget exists to prevent."""+ _window(monkeypatch, 4096)+ _room(30)++ limit = tools._dense_char_limit(_dense(40_000), tools._MAX_OUTPUT_CHARS)++ assert limit < tools._MIN_PAGE_CHARS++ def test_the_floor_yields_on_the_measured_leg_too(self, monkeypatch):+ """The leg the test above misses, and the one that matters most.++ `_exact_prefix_chars` bottoms out on the floor, so with a tokenizer serving the+ request it returned the legacy 2,000 characters however little room was left:+ 100 tokens of room bought 2,000 characters, 666 tokens of dense output, 6.6x the+ budget. The accurate leg was the leaky one.+ """+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ _room(100)++ limit = tools._dense_char_limit(_dense(40_000), tools._MAX_OUTPUT_CHARS)++ assert limit // _CHARS_PER_TOKEN <= 100, "the measured leg overshot the room"+ assert limit < tools._MIN_PAGE_CHARS++ def test_an_unpriced_call_behaves_exactly_as_before(self, monkeypatch):+ """The blast radius. External providers and the hosted path never set a room, and+ must see the window-share cap they saw before this existed."""+ _window(monkeypatch, 4096)+ text = _dense(40_000)++ before = tools._dense_char_limit(text, tools._MAX_OUTPUT_CHARS)+ _room(None)+ after = tools._dense_char_limit(text, tools._MAX_OUTPUT_CHARS)++ assert after == before++ def test_an_unknown_window_with_no_room_keeps_the_caller_cap(self):+ """Nothing measured at all, so there is nothing to lower the cap with."""+ assert tools._dense_char_limit(_dense(40_000), 9_000) == 9_000++ def test_a_known_room_holds_even_with_an_unknown_window(self, monkeypatch):+ """The native case: no resident GGUF, so `_window_context_tokens` sees nothing,+ while the loop that called it knows exactly how full the thread is. Reading the+ window as "no limits" there leaves every result uncapped on the one path with no+ rolling fit to recover."""+ monkeypatch.setattr(tools, "_loaded_token_counter", lambda ctx: None)+ _room(50)++ limit = tools._dense_char_limit(_dense(40_000), 9_000)++ assert 0 < limit <= 50 * 4 * tools._UNMEASURED_ROOM_MARGIN+++class TestPagingTheRest:+ def test_the_hint_names_a_range_that_resumes_where_the_head_stopped(self, tmp_path):+ """A truncation the model can act on. The line the hint names must be the line+ after the last one shown -- off by one either repeats a line of the user's file or+ loses it."""+ text = "\n".join(f"line {i}" for i in range(1, 501))++ out = tools._truncate(text, 200, workdir = str(tmp_path))++ head = out.split("\n\n... (truncated")[0]+ shown = head.count("\n") + 1+ assert f"showing lines 1-{shown} of 500" in out+ assert f"sed -n '{shown + 1}," in out+ # The named line really is the next one, read back off the spill.+ spill = _spill_path(out)+ full = (tmp_path / spill).read_text().splitlines()+ assert full[shown] == f"line {shown + 1}"++ def test_the_head_stops_on_a_line_boundary(self, tmp_path):+ """So the hint's line number is exact rather than approximate."""+ text = "\n".join(f"line {i}" for i in range(1, 501))++ out = tools._truncate(text, 200, workdir = str(tmp_path))++ head = out.split("\n\n... (truncated")[0]+ assert not head.endswith("\n")+ assert head.splitlines()[-1] == f"line {head.count(chr(10)) + 1}"++ def test_one_enormous_line_is_still_cut_rather_than_dropped(self, tmp_path):+ """Minified JS and base64 have no newline to rewind to. Rewinding anyway would+ throw the whole result away to keep the hint tidy."""+ out = tools._truncate("A" * 40_000, 500, workdir = str(tmp_path))++ head = out.split("\n\n... (truncated")[0]+ assert len(head) == 500++ def test_a_mid_line_cut_resumes_by_bytes_rather_than_by_line(self, tmp_path):+ """A line number cannot describe a cut that landed inside a line.++ `shown` counts the partial line as complete, so a line-based resume starts at the+ line AFTER the one the reader is standing in the middle of and skips everything+ still unread in it. On single-line output -- minified JS, base64, one long JSON --+ that is the entire remainder, and `sed` returns nothing at all.+ """+ out = tools._truncate("A" * 40_000, 500, workdir = str(tmp_path))++ assert "sed -n" not in out, "a line number cannot resume a mid-line cut"+ assert "tail -c +501" in out+ # And it really does resume at the first unseen byte.+ spill = _spill_path(out)+ assert (tmp_path / spill).read_text()[500:501] == "A"++ def test_a_boundary_cut_still_resumes_by_line(self, tmp_path):+ """The byte fallback must not swallow the readable case."""+ out = tools._truncate(+ "\n".join(f"line {i}" for i in range(1, 501)), 200, workdir = str(tmp_path)+ )++ assert "sed -n" in out+ assert "tail -c" not in out++ def test_a_multibyte_mid_line_cut_counts_bytes_not_characters(self, tmp_path):+ """`tail -c` counts bytes. Handing it a character count resumes in the middle of a+ codepoint on any non-ASCII output, which is most of a CJK result."""+ out = tools._truncate("你好" * 10_000, 300, workdir = str(tmp_path))++ head = out.split("\n\n... (truncated")[0]+ offset = int(out.split("tail -c +")[1].split(" ")[0]) - 1+ assert offset == len(head.encode("utf-8"))+ assert offset > len(head), "bytes, not characters, for multibyte text"++ def test_the_full_output_is_recoverable_from_the_spill(self, tmp_path):+ text = "\n".join(f"line {i}" for i in range(1, 2_001))++ out = tools._truncate(text, 300, workdir = str(tmp_path))++ spill = _spill_path(out)+ assert (tmp_path / spill).read_text() == text++ def test_the_spill_is_hidden_from_the_created_files_card(self, tmp_path):+ """It lives in a dot-directory, which `_snapshot_workdir_files` skips. Without+ that, every truncated result would grow a phantom download beside it."""+ before = tools._snapshot_workdir_files(str(tmp_path))+ tools._truncate("\n".join(str(i) for i in range(5_000)), 200, workdir = str(tmp_path))+ after = tools._snapshot_workdir_files(str(tmp_path))++ assert after == before++ def test_a_cmd_only_windows_host_gets_no_command_it_cannot_run(self, tmp_path, monkeypatch):+ """`_get_shell_cmd` falls back to `cmd /c` when the host has no trusted bash, and+ cmd has no sed, tail or head. Naming one anyway hands the model a command that+ fails, and the likely next move is re-running the call that truncated."""+ monkeypatch.setattr(tools.sys, "platform", "win32")+ monkeypatch.setattr(tools, "_windows_bash", lambda: None)++ out = tools._truncate(+ "\n".join(f"line {i}" for i in range(1, 501)), 200, workdir = str(tmp_path)+ )++ assert "saved to" in out, "the spill is still worth naming"+ assert "continue with" not in out+ for tool in ("sed -n", "tail -c", "head -c"):+ assert tool not in out++ def test_a_windows_host_with_bash_still_gets_the_command(self, tmp_path, monkeypatch):+ """The guard must not strip paging from the Windows hosts that can page."""+ monkeypatch.setattr(tools.sys, "platform", "win32")+ monkeypatch.setattr(tools, "_windows_bash", lambda: r"C:\Program Files\Git\bin\bash.exe")++ out = tools._truncate(+ "\n".join(f"line {i}" for i in range(1, 501)), 200, workdir = str(tmp_path)+ )++ assert "continue with" in out+ assert "sed -n" in out++ def test_the_spill_is_written_without_newline_translation(self, tmp_path, monkeypatch):+ """The byte offset in the hint is counted from the untranslated text, so the file+ has to hold those same bytes. The default text mode writes os.linesep, which on+ Windows adds a byte per line and moves every later offset, resuming early and+ repeating output.++ Asserted on the open() call rather than on the bytes, because this platform does+ not translate: comparing the file here would pass with or without the fix and+ prove nothing about the platform the bug is on.+ """+ seen = {}+ real_fdopen = os.fdopen++ def _recording_fdopen(+ fd,+ mode = "r",+ *args,+ **kwargs,+ ):+ # os.fdopen since the spill is opened O_NOFOLLOW by descriptor; the kwarg the+ # newline behaviour rides on is the same one either way.+ if "w" in mode:+ seen.update(kwargs)+ return real_fdopen(fd, mode, *args, **kwargs)++ monkeypatch.setattr(os, "fdopen", _recording_fdopen)+ text = "\n".join(f"line {i}" for i in range(1, 200))+ out = tools._truncate(text, 120, workdir = str(tmp_path))++ assert seen.get("newline") == "", f"spill opened with newline={seen.get('newline')!r}"+ assert (tmp_path / _spill_path(out)).read_bytes() == text.encode("utf-8")++ def test_no_workdir_falls_back_to_the_plain_notice(self):+ """A hint naming a file that is not there is worse than admitting it is gone."""+ out = tools._truncate("\n".join(str(i) for i in range(5_000)), 200)++ assert "truncated to" in out+ assert "sed -n" not in out+ assert "saved to" not in out++ def test_spills_do_not_accumulate_without_bound(self, tmp_path):+ # Distinct bodies, so each really is a new spill: identical output is content+ # addressed onto one file and would never exercise the prune at all.+ for n in range(tools._SPILL_KEEP + 6):+ tools._truncate(+ f"run {n}\n" + "\n".join(str(i) for i in range(5_000)), 200, workdir = str(tmp_path)+ )++ assert len(_spills(tmp_path / tools._SPILL_DIR)) <= tools._SPILL_KEEP++ def test_the_same_output_twice_reuses_one_spill(self, tmp_path):+ """Content addressed, so the notice is identical between the streaming and+ non-streaming runs of one call, and printing the same file twice does not fill+ the sandbox with copies."""+ text = "\n".join(f"line {i}" for i in range(1, 2_000))++ first = tools._truncate(text, 200, workdir = str(tmp_path))+ second = tools._truncate(text, 200, workdir = str(tmp_path))++ assert first == second+ assert len(_spills(tmp_path / tools._SPILL_DIR)) == 1+++# Three characters per token, which is what the code tools actually print: minified HTML,+# base64 and hexdumps all run nearer three than the four the character estimate assumes.+# `_loaded_token_counter` is the same seam llama_cpp fills with the serving model.+_CHARS_PER_TOKEN = 3+++def _tokenizer(monkeypatch):+ # `token_budget` is the counter's own early-out and defaults to "no budget", exactly+ # as the real one does.+ monkeypatch.setattr(+ tools,+ "_loaded_token_counter",+ lambda ctx: (lambda chunk, token_budget = 0.0: len(chunk) // _CHARS_PER_TOKEN),+ )+++def _cat_game_html(monkeypatch, page, *, price_the_room):+ """Run `cat game.html` three times and return what the thread ends up spending."""+ ctx = 4096+ spent = 300 # system turn plus the first question+ for _ in range(3):+ _room(tool_result_budget(ctx, None, spent) if price_the_room else None)+ limit = tools._dense_char_limit(page, tools._tool_result_char_budget())+ served = tools._truncate(page, limit, workdir = None)+ spent += len(served) // _CHARS_PER_TOKEN + 40 # the result plus the turn's framing+ return spent+++class TestTheReportedScenario:+ def test_repeated_prints_of_one_file_stay_inside_the_window(self, monkeypatch):+ """The user's repro, as arithmetic. `cat game.html` three times at ctx 4096.++ Reported against Qwen3.6-35B-A3B at 4096: each result is individually under the+ cap, and the third turn cannot be served. Priced against the room left, and with+ the serving model pricing the characters, the three together never pass the budget.+ """+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ target = prompt_budget(4096, None)++ spent = _cat_game_html(monkeypatch, _dense(40_000), price_the_room = True)++ assert spent < target, (+ f"three printed results spent {spent} tokens of a {target}-token budget; "+ "the thread can no longer be served and the fit cannot evict the newest turn"+ )++ def test_the_same_loop_overflows_when_the_room_is_ignored(self, monkeypatch):+ """The control, and what makes the test above non-vacuous: with the room unset --+ exactly the old behaviour -- the same three prints do overflow."""+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ target = prompt_budget(4096, None)++ spent = _cat_game_html(monkeypatch, _dense(40_000), price_the_room = False)++ assert spent > target++ def test_without_a_tokenizer_the_margin_still_keeps_it_inside(self, monkeypatch):+ """The native path, where nothing can price a string exactly.++ `_loaded_token_counter` answers only for a resident GGUF, so a safetensors model+ converts its room with the four-characters-per-token English estimate, and the+ dense ASCII these tools print runs nearer three. Left alone that overspends by+ about a third, on the one loop with no rolling fit to recover with, so the+ conversion is halved instead (`_UNMEASURED_ROOM_MARGIN`).+ """+ _window(monkeypatch, 4096) # deliberately NO _tokenizer()+ target = prompt_budget(4096, None)++ spent = _cat_game_html(monkeypatch, _dense(40_000), price_the_room = True)++ assert spent < target+++def _within_room(out: str, room: int) -> None:+ """The body and the notice explaining the cut both fit inside the room.++ `_RESULT_NOTICE_RESERVE` is charged by `_truncate` at the point the cut is decided, so+ the number the caller was given covers the whole result rather than the body alone.+ """+ body = out.split("\n\n... (")[0]+ assert len(body) // _CHARS_PER_TOKEN <= room, "the body alone overruns the room"+ assert len(out) // _CHARS_PER_TOKEN <= room, "the notice is not inside the room"+++class TestEveryToolIsHeldToTheRoom:+ """`python` and `terminal` truncate themselves; the rest hand their string back whole.++ An MCP response is unbounded and an edit receipt or a search result runs to thousands+ of characters, so a tool that is not the code sandbox can overflow the same nearly full+ thread and land in the newest turn, which the next fit protects. Whatever the tool, the+ result has to be held to the room.+ """++ def test_a_web_search_result_is_capped_by_the_room(self, monkeypatch):+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ monkeypatch.setattr(tools, "_web_search", lambda *a, **k: _dense(40_000))+ out = tools.execute_tool("web_search", {"query": "flappy bird"}, result_budget_tokens = 120)++ assert len(out) < 40_000+ _within_room(out, 120)++ def test_an_mcp_response_is_capped_by_the_room(self, monkeypatch):+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ monkeypatch.setattr(+ tools.mcp_servers_db,+ "get_server",+ lambda _id: {"url": "https://example.invalid/mcp", "is_enabled": True},+ )+ monkeypatch.setattr(tools, "parse_server_headers", lambda _s: {})+ monkeypatch.setattr(tools, "is_stdio", lambda _u: False)+ monkeypatch.setattr(tools, "call_tool_sync", lambda **k: _dense(40_000))+ out = tools.execute_tool(+ f"{tools.MCP_TOOL_PREFIX}srv__read_file", {}, result_budget_tokens = 120+ )++ assert len(out) < 40_000+ _within_room(out, 120)++ def test_an_edit_receipt_is_capped_by_the_room(self, monkeypatch):+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ monkeypatch.setattr(tools, "_edit_file", lambda *a, **k: _dense(8_000))+ out = tools.execute_tool(+ "edit_file", {"path": "game.html"}, session_id = None, result_budget_tokens = 120+ )++ assert len(out) < 8_000+ _within_room(out, 120)++ def test_an_unpriced_thread_keeps_todays_result_exactly(self, monkeypatch):+ """The hosted path and every external provider: no room measured, nothing capped.+ Without this leg the change would start truncating results it cannot price."""+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ page = _dense(40_000)+ monkeypatch.setattr(tools, "_web_search", lambda *a, **k: page)+ assert (+ tools.execute_tool("web_search", {"query": "flappy bird"}, result_budget_tokens = None)+ == page+ )++ def test_a_short_result_survives_a_thread_with_no_room(self, monkeypatch):+ """At zero room the notice IS the message, but only while it is the cheaper of the+ two. Replacing "done" with a longer sentence about "done" being gone spends more+ tokens and loses the answer."""+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ monkeypatch.setattr(tools, "_web_search", lambda *a, **k: "done")+ assert tools.execute_tool("web_search", {"query": "x"}, result_budget_tokens = 0) == "done"+++class TestPruningOnlyTouchesStudioSpills:+ def test_files_studio_did_not_write_are_left_alone(self, tmp_path):+ """The sandbox can be a directory the user already had, including one that already+ holds a `.unsloth_tool_output`. Pruning by extension deletes their files."""+ target = _own(tmp_path)+ mine = [target / f"{i:012x}.txt" for i in range(tools._SPILL_KEEP + 5)]+ for path in mine:+ path.write_text("spill")+ tools._write_spill_manifest(+ str(target),+ {p.name: (tools._spill_stamp(str(p)), tools._file_digest(str(p))) for p in mine},+ )+ theirs = [target / "notes.txt", target / "receipts-2026.txt"]+ for path in theirs:+ path.write_text("keep me")++ tools._prune_spills(str(target))++ assert all(path.exists() for path in theirs)+ assert len([p for p in target.iterdir() if p.name.endswith(".txt")]) == (+ tools._SPILL_KEEP + len(theirs)+ )++ def test_a_spill_named_file_this_did_not_write_is_not_pruned(self, tmp_path):+ """The marker records the DIRECTORY, and tool code can create a file with a+ plausible name in it afterwards. A name is not evidence of who wrote it."""+ target = _own(tmp_path)+ theirs = target / "abcdef123456.txt"+ theirs.write_text("mine")+ for n in range(tools._SPILL_KEEP + 5):+ tools._truncate(f"run {n}\n" + _dense(3_000), 200, workdir = str(tmp_path))++ assert theirs.read_text() == "mine"++ def test_and_the_cleanup_reads_it_the_same_way(self, tmp_path):+ target = _own(tmp_path)+ (target / "abcdef123456.txt").write_text("mine")++ assert not tools._holds_no_user_files(str(tmp_path))++ def test_an_unowned_directory_is_not_pruned_at_all(self, tmp_path):+ """A name proves nothing about who wrote it. Without the marker this directory came+ with the sandbox, and every file in it is the user's however it is named."""+ target = tmp_path / tools._SPILL_DIR+ target.mkdir()+ theirs = [target / f"{i:012x}.txt" for i in range(tools._SPILL_KEEP + 5)]+ for path in theirs:+ path.write_text("mine")++ tools._prune_spills(str(target))++ assert all(path.exists() for path in theirs)++ def test_an_unowned_directory_is_never_written_to(self, tmp_path):+ """And nothing is added to it either, so the notice falls back to no paging hint+ rather than putting Studio's files among the user's."""+ (tmp_path / tools._SPILL_DIR).mkdir()+ (tmp_path / tools._SPILL_DIR / "notes.txt").write_text("mine")++ out = tools._truncate("\n".join(str(i) for i in range(5_000)), 200, workdir = str(tmp_path))++ assert "saved to" not in out+ assert [p.name for p in (tmp_path / tools._SPILL_DIR).iterdir()] == ["notes.txt"]++ def test_a_file_named_like_a_spill_in_an_unowned_directory_is_user_content(self, tmp_path):+ """And the cleanup reads it the same way, so deleting the chat does not take it."""+ target = tmp_path / tools._SPILL_DIR+ target.mkdir()+ (target / "abcdef123456.txt").write_text("mine")++ assert not tools._holds_no_user_files(str(tmp_path))+++class TestTheFrontendEnvelopeSurvivesTheCap:+ """Only what the model is shown is measured, and only it is cut.++ An MCP screenshot comes back as a trailing `__MCP_IMAGES__` JSON array that can run to+ megabytes of base64. `strip_result_for_model` removes it before the result is replayed,+ so it costs the window nothing, and every consumer needs the whole valid array: a cut+ inside it does not lose the image quietly, it hands the model the broken fragment.+ """++ @staticmethod+ def _envelope(pixels: int) -> str:+ return '\n__MCP_IMAGES__:[{"data": "%s", "mimeType": "image/png"}]' % ("A" * pixels)++ def _mcp(self, monkeypatch, result):+ monkeypatch.setattr(+ tools.mcp_servers_db,+ "get_server",+ lambda _id: {"url": "https://example.invalid/mcp", "is_enabled": True},+ )+ monkeypatch.setattr(tools, "parse_server_headers", lambda _s: {})+ monkeypatch.setattr(tools, "is_stdio", lambda _u: False)+ monkeypatch.setattr(tools, "call_tool_sync", lambda **k: result)+ return tools.execute_tool(+ f"{tools.MCP_TOOL_PREFIX}srv__screenshot", {}, result_budget_tokens = 120+ )++ def test_an_image_envelope_comes_back_whole(self, monkeypatch):+ from core.inference.tool_loop_controller import strip_result_for_model++ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ envelope = self._envelope(60_000)++ out = self._mcp(monkeypatch, _dense(40_000) + envelope)++ assert out.endswith(envelope), "the image envelope was cut"+ # And the part that is replayed to the model is the capped one.+ _within_room(strip_result_for_model(out, "mcp"), 120)++ def test_the_envelope_is_not_charged_to_the_room(self, monkeypatch):+ """Its size cannot shrink the body: the model never sees those bytes."""+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ page = _dense(40_000)++ small = self._mcp(monkeypatch, page + self._envelope(100))+ large = self._mcp(monkeypatch, page + self._envelope(500_000))++ assert small.split("\n__MCP_IMAGES__")[0] == large.split("\n__MCP_IMAGES__")[0]++ def test_text_that_merely_mentions_the_marker_is_still_capped(self, monkeypatch):+ """The conservative half, and the same rule the replay path applies: no valid JSON+ array, no envelope, so it is ordinary output and is measured like any other."""+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)++ out = self._mcp(monkeypatch, _dense(40_000) + "\n__MCP_IMAGES__: see the docs")++ _within_room(out, 120)+++class TestTheSpillStaysInsideTheSandbox:+ """The workdir is a directory the model runs commands in, and can be a project the+ user opened. Anything there may be a symlink it made or one that came with the+ project, and following it writes this result outside the sandbox with the backend's+ own permissions."""++ def test_a_symlinked_spill_directory_is_refused(self, tmp_path):+ workdir = tmp_path / "sandbox"+ workdir.mkdir()+ outside = tmp_path / "outside"+ outside.mkdir()+ (workdir / tools._SPILL_DIR).symlink_to(outside, target_is_directory = True)++ out = tools._truncate("\n".join(str(i) for i in range(5_000)), 200, workdir = str(workdir))++ assert list(outside.iterdir()) == [], "the spill was written outside the sandbox"+ # Refused, not crashed: the notice is still served, just without a paging hint.+ assert "truncated to" in out+ assert "saved to" not in out++ def test_a_symlinked_spill_file_is_refused(self, tmp_path):+ workdir = tmp_path / "sandbox"+ workdir.mkdir()+ victim = tmp_path / "victim.txt"+ victim.write_text("do not overwrite me")+ text = "\n".join(str(i) for i in range(5_000))+ target = _own(workdir)+ digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]+ (target / f"{digest}.txt").symlink_to(victim)++ out = tools._truncate(text, 200, workdir = str(workdir))++ assert victim.read_text() == "do not overwrite me"+ # Refused rather than replaced: whatever is at that path is not a spill this+ # recorded, so it is the user's, and the notice does without a paging hint.+ assert "saved to" not in out+ assert (target / f"{digest}.txt").is_symlink()++ def test_pruning_does_not_follow_symlinks_either(self, tmp_path):+ target = _own(tmp_path)+ victim = tmp_path / "victim.txt"+ victim.write_text("keep me")+ for i in range(tools._SPILL_KEEP + 5):+ (target / f"{i:012x}.txt").write_text("spill")+ # Oldest by mtime, so a prune that follows links would unlink it first.+ (target / ("f" * 12 + ".txt")).symlink_to(victim)+ os.utime(target / ("f" * 12 + ".txt"), (0, 0), follow_symlinks = False)++ tools._prune_spills(str(target))++ # os.remove would only unlink the link, so the file it points at is safe either+ # way; what the filter buys is that a name Studio did not write is left alone.+ assert (target / ("f" * 12 + ".txt")).is_symlink()+ assert victim.read_text() == "keep me"+++class TestSpillsAreBoundedInBytes:+ def test_one_enormous_result_is_capped_on_disk(self, tmp_path, monkeypatch):+ """The result arrives here whole, and the sandbox file-size limit does not apply to+ output that came through a pipe. Without a byte cap a single `cat` of a huge file+ is retained in full."""+ monkeypatch.setattr(tools, "_SPILL_MAX_BYTES", 4_096)+ text = _dense(50_000)++ out = tools._truncate(text, 200, workdir = str(tmp_path))++ spill = tmp_path / _spill_path(out)+ assert spill.stat().st_size <= 4_096+ # And the notice says so rather than promising the whole thing.+ assert "Full output saved to" not in out+ assert "first 4096 bytes" in out++ def test_the_directory_is_bounded_in_bytes_not_just_in_files(self, tmp_path, monkeypatch):+ """Twenty large-but-legal spills are still tens of gigabytes of the host's disk."""+ monkeypatch.setattr(tools, "_SPILL_MAX_TOTAL_BYTES", 20_000)+ for n in range(10):+ tools._truncate(f"run {n}\n" + _dense(9_000), 200, workdir = str(tmp_path))++ spills = list((tmp_path / tools._SPILL_DIR).iterdir())+ assert sum(p.stat().st_size for p in spills) <= 20_000+ assert spills, "the newest spill has to survive; it is the one just named"++ def test_the_spill_just_named_is_never_pruned(self, tmp_path, monkeypatch):+ """The notice returned with it names that path, so a budget that deletes it on the+ way out leaves the model a hint pointing at nothing."""+ monkeypatch.setattr(tools, "_SPILL_MAX_TOTAL_BYTES", 100)++ out = tools._truncate(_dense(50_000), 200, workdir = str(tmp_path))++ assert (tmp_path / _spill_path(out)).exists()++ def test_a_result_served_whole_leaves_no_spill_behind(self, tmp_path):+ """At zero room a short result is served as it is, so nothing was cut and there is+ nothing to page through. Writing a file (and creating the directory) for it is a+ side effect with nothing on the other side of it."""+ assert tools._truncate("done", 0, workdir = str(tmp_path)) == "done"++ assert not (tmp_path / tools._SPILL_DIR).exists()+++class TestTheHintCountsTheLinesItShowed:+ def test_a_head_ending_in_a_newline_does_not_claim_an_extra_line(self, tmp_path):+ """At a limit of 1 on output starting with a blank line the head is "\\n" alone:+ one line shown, so the hint has to resume at line 2. Counting two skips a line the+ reader never saw."""+ text = "\n" + "\n".join(f"line {i}" for i in range(2, 400))++ out = tools._truncate(text, 1, workdir = str(tmp_path))++ assert "showing lines 1-1 of" in out+ assert "sed -n '2," in out+++class TestTheSpillCannotBeAimedElsewhere:+ def test_a_hard_link_at_the_spill_path_is_not_written_through(self, tmp_path):+ """The name is a digest of content the model produced, so it can predict it and+ pre-create it. A hard link reports islink() false and shares the inode of a file+ outside the sandbox, so an O_TRUNC open writes through to it."""+ workdir = tmp_path / "sandbox"+ workdir.mkdir()+ victim = tmp_path / "victim.txt"+ victim.write_text("do not overwrite me")+ text = "\n".join(str(i) for i in range(5_000))+ target = _own(workdir)+ digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]+ os.link(victim, target / f"{digest}.txt")++ out = tools._truncate(text, 200, workdir = str(workdir))++ assert victim.read_text() == "do not overwrite me"+ # And nothing is written at that name either: it is not a spill this recorded, so+ # it is the user's, whatever it is linked to.+ assert "saved to" not in out+ assert (target / f"{digest}.txt").read_text() == "do not overwrite me"++ def test_no_temporary_file_is_left_behind(self, tmp_path):+ tools._truncate("\n".join(str(i) for i in range(5_000)), 200, workdir = str(tmp_path))++ names = [p.name for p in _spills(tmp_path / tools._SPILL_DIR)]+ assert all(tools._SPILL_NAME_RE.fullmatch(n) for n in names), names+++class TestAZeroCapStaysZero:+ def test_real_tokenizer_framing_does_not_buy_a_character(self, monkeypatch):+ """A thread at its budget measures a room of zero, and a real tokenizer charges for+ the framing around even an empty string. Handing back one character puts _truncate+ past its stub path and onto the ordinary notice, which is the ~90 tokens the stub+ exists not to spend when the measurement just said there are none."""+ _window(monkeypatch, 4096)+ # Nonzero for an empty probe, which is what a chat template does.+ monkeypatch.setattr(+ tools, "_loaded_token_counter", lambda ctx: (lambda chunk: 4 + len(chunk) // 3)+ )+ _room(0)+ text = _dense(40_000)++ assert tools._dense_char_limit(text, tools._MAX_OUTPUT_CHARS) == 0+ out = tools._truncate(text, tools._tool_result_char_budget())+ assert out.startswith("(output omitted:")+ assert "truncated to" not in out+++class TestOneChatsOutputStaysItsOwn:+ """`_get_workdir(None)` is the shared `_default` sandbox, and a project's chats share+ one session by design (`project_session_id`). A spill in either outlives the call under+ a path the next chat can list and read, and can be pruned out from under the chat that+ was told to page through it. Before this change that output existed only in the+ originating response."""++ @staticmethod+ def _spill_args(+ monkeypatch,+ tmp_path,+ session_id,+ thread_id = None,+ ):+ seen = {}+ # A real directory: the command runs with it as cwd, and a path that is not there+ # fails the call long before anything is truncated.+ monkeypatch.setattr(tools, "_get_workdir", lambda _sid: str(tmp_path))+ real = tools._truncate++ def _recording(+ text,+ limit = None,+ workdir = None,+ **kwargs,+ ):+ seen.update(kwargs, workdir = workdir)+ return real(text, limit if limit is not None else 200)++ monkeypatch.setattr(tools, "_truncate", _recording)+ # Builtin printf over a brace expansion: no command substitution, because the+ # sandbox caps processes and a fork fails the call before it ever truncates.+ tools._bash_exec("printf 'x%.0s' {1..5000}", None, 30, session_id, thread_id = thread_id)+ return seen++ def test_a_call_without_a_session_does_not_spill(self, monkeypatch, tmp_path):+ assert self._spill_args(monkeypatch, tmp_path, None)["workdir"] is None++ def test_a_project_chat_without_a_thread_does_not_spill(self, monkeypatch, tmp_path):+ """Nothing identifies the chat, and the session is shared with every other chat in+ the project, so there is nowhere to put it that is only this chat's."""+ session = tools.project_session_id("proj-1")++ assert self._spill_args(monkeypatch, tmp_path, session)["scope"] is None++ def test_a_project_chat_retains_nothing_even_with_a_thread(self, monkeypatch, tmp_path):+ """A sub-directory is not access control, it is a name: every sibling chat in the+ project has a terminal in that same sandbox and can read and prune whatever is in+ it. So a project chat truncates with a notice and no continuation."""+ session = tools.project_session_id("proj-1")++ assert self._spill_args(monkeypatch, tmp_path, session, "chat-a")["scope"] is None+ assert self._spill_args(monkeypatch, tmp_path, session, "chat-b")["scope"] is None++ def test_a_private_session_still_spills(self, monkeypatch, tmp_path):+ """The control: the feature has to keep working where the sandbox is the+ conversation's own."""+ seen = self._spill_args(monkeypatch, tmp_path, "chat-1")++ assert seen["workdir"] == str(tmp_path)+ assert seen["scope"] == ""++ def test_a_scope_puts_the_spill_in_its_own_directory(self, tmp_path):+ """And the notice names that path, so paging still works from the sandbox cwd."""+ text = "\n".join(str(i) for i in range(5_000))++ out = tools._truncate(text, 200, workdir = str(tmp_path), scope = "abc123abc123")++ assert _spill_path(out).startswith(f"{tools._SPILL_DIR}/abc123abc123/")+ assert (tmp_path / _spill_path(out)).read_text().startswith("0\n1\n")++ def test_a_scope_of_none_retains_nothing(self, tmp_path):+ out = tools._truncate(+ "\n".join(str(i) for i in range(5_000)), 200, workdir = str(tmp_path), scope = None+ )++ assert "saved to" not in out+ assert not (tmp_path / tools._SPILL_DIR).exists()+++class TestTheRetryHintIsInsideTheCap:+ """`_missing_path_hint` is appended to the result and goes to the model with it, so it+ is part of what has to fit. Added after the cap it is unbudgeted, and a failing+ absolute path is dense text: on a thread with no room left those characters are the+ overflow the cap exists to prevent."""++ _HINT = " " + "x" * 400++ def test_the_hint_is_charged_to_the_limit(self):+ """Paid for out of the body, and at its token cost rather than its length: a+ punctuation-heavy path tokenises far more densely than the prose it displaces."""+ text = "\n".join(str(i) for i in range(5_000))++ capped = tools._truncate(text, 4_000, hint = self._HINT)+ plain = tools._truncate(text, 4_000)++ assert capped.endswith(self._HINT)+ body = capped.split("\n\n... (")[0]+ assert len(body) + len(self._HINT) <= len(plain.split("\n\n... (")[0])++ def test_a_hint_too_large_for_the_room_is_dropped(self):+ """Past half the room the output is worth more than the advice about it."""+ text = "\n".join(str(i) for i in range(5_000))++ capped = tools._truncate(text, 900, hint = self._HINT)++ assert self._HINT not in capped++ def test_a_dense_hint_costs_more_than_its_length(self, monkeypatch):+ """The point of pricing it in tokens. A punctuation-heavy absolute path tokenises+ far more densely than the prose characters that would be dropped to make room for+ it, so subtracting its LENGTH from the character cap buys less than it spends."""+ _window(monkeypatch, 4096)+ # A separator is its own token and a letter is a quarter of one, which is roughly+ # what a tokenizer does to a path next to prose.+ monkeypatch.setattr(+ tools,+ "_loaded_token_counter",+ lambda ctx: (+ lambda chunk, token_budget = 0.0: sum(1.0 if c == "/" else 0.25 for c in chunk)+ ),+ )+ _room(400)+ text = _dense(40_000)+ hint = "/" * 100++ without = tools._truncate(text, tools._MAX_OUTPUT_CHARS).split("\n\n... (")[0]+ with_hint = tools._truncate(text, tools._MAX_OUTPUT_CHARS, hint = hint)++ assert with_hint.endswith(hint)+ body = with_hint.split("\n\n... (")[0]+ # The hint is 100 tokens and the body runs four characters to the token, so the+ # body has to give up about 400 characters to pay for it. Charged as prose it+ # gives up its length, which line rounding can inflate a little: three times over+ # is comfortably past anything that rounding explains.+ assert len(without) - len(body) >= 3 * len(+ hint+ ), "the body gave up about the hint's length, so the hint was charged as prose"++ def test_a_result_that_fits_still_carries_it(self):+ assert tools._truncate("ok", 1_000, hint = self._HINT) == "ok" + self._HINT+++class TestTheSafetensorsLoopPricesItToo:+ """The native path runs the same tools against the same window, and has no rolling fit+ behind it: a `cat` of a file the model just wrote lands in the newest exchange with+ nothing downstream able to evict it."""++ @staticmethod+ def _run(+ context_length,+ messages = None,+ calls = 1,+ ):+ """One `terminal` call through the real loop, returning the kwargs it was given."""+ import threading++ from core.inference.safetensors_agentic import run_safetensors_tool_loop++ def _model(messages):+ state["turns"] += 1+ if state["turns"] > 1:+ yield "done"+ return+ call = "".join(+ '<tool_call>{"name":"terminal","arguments":{"command":"cat game%d.html"}}'+ "</tool_call>" % n+ for n in range(calls)+ )+ for n in range(1, len(call) + 1):+ yield call[:n]++ state = {"turns": 0}+ seen = []+ list(+ run_safetensors_tool_loop(+ single_turn = _model,+ messages = list(messages or [{"role": "user", "content": "print game.html"}]),+ tools = [{"type": "function", "function": {"name": "terminal"}}],+ execute_tool = lambda name, args, **kwargs: seen.append(kwargs) or "x" * 40_000,+ cancel_event = threading.Event(),+ max_tool_iterations = 2,+ thread_id = "t-sf",+ context_length = context_length,+ max_tokens = 512,+ )+ )+ return seen[0]++ def test_it_prices_the_room_for_the_tool(self):+ """Without it execute_tool takes the None default and every cap is disabled here."""+ room = self._run(4096).get("result_budget_tokens")++ assert isinstance(room, int)+ assert 0 < room < prompt_budget(4096, 512)++ def test_it_passes_the_window_as_well_as_the_room(self):+ """A room with no window to size against is not a cap: `_dense_char_limit` has no+ share to take and hands back the window-independent constant."""+ assert self._run(4096).get("context_tokens") == 4096++ def test_a_result_already_in_the_thread_is_priced_densely(self):+ """The estimator charges ASCII four characters per token, an English rate, and the+ results these tools return run nearer two. Priced at the English rate the second+ call is handed room the first call already occupies, and this loop has no exact+ count and no rolling fit to catch it.++ Differential, so it cannot pass on the arithmetic alone: the same characters in a+ user turn are ordinary prose and stay at the estimator's rate, while in a tool+ result every ASCII character is charged at the dense one.++ Spaced deliberately. An unbroken run of 4,000 characters is priced as a blob+ wherever it appears, so a body without spaces would compare the two rates against+ each other and find them equal.+ """+ body = "abcd " * 800+ as_result = self._run(+ 4096,+ messages = [+ {"role": "user", "content": "print it"},+ {"role": "tool", "content": body},+ ],+ )["result_budget_tokens"]+ as_prose = self._run(+ 4096,+ messages = [+ {"role": "user", "content": "print it"},+ {"role": "user", "content": body},+ ],+ )["result_budget_tokens"]++ assert as_result < as_prose++ def test_a_parallel_batch_splits_the_room(self):+ """One turn can call several tools, and each call is appended only as it runs, so+ the spend knows nothing about the rest of the batch. Sized as if it were alone, the+ first result takes the room the other calls and their results still need, and the+ finished exchange is protected as the newest turn."""+ alone = self._run(4096)["result_budget_tokens"]+ first_of_three = self._run(4096, calls = 3)["result_budget_tokens"]++ assert first_of_three <= alone // 3++ def test_an_unknown_window_prices_nothing(self):+ """The same leg the GGUF loop takes: no window, no budget, today's behaviour."""+ assert self._run(None).get("result_budget_tokens") is None+++class TestAProjectIsBoundedAsOneWorkspace:+ def test_the_byte_budget_spans_every_scope(self, tmp_path, monkeypatch):+ """A project's chats share one sandbox and get one scope each, so a per-directory+ budget is really a per-chat budget multiplied by however many chats there are."""+ monkeypatch.setattr(tools, "_SPILL_MAX_TOTAL_BYTES", 30_000)+ for chat in range(6):+ tools._truncate(+ f"chat {chat}\n" + _dense(9_000), 200, workdir = str(tmp_path), scope = f"{chat:012x}"+ )++ root = tmp_path / tools._SPILL_DIR+ spilled = [p for p in root.rglob("*.txt")]+ assert sum(p.stat().st_size for p in spilled) <= 30_000+ assert spilled, "the newest spill has to survive; it is the one just named"++ def test_an_emptied_scope_leaves_no_directory_behind(self, tmp_path, monkeypatch):+ """Deleting a chat does not remove its scope, and an empty directory left in the+ sandbox is what makes the cleanup treat it as holding something."""+ monkeypatch.setattr(tools, "_SPILL_MAX_TOTAL_BYTES", 12_000)+ for chat in range(4):+ tools._truncate(+ f"chat {chat}\n" + _dense(9_000), 200, workdir = str(tmp_path), scope = f"{chat:012x}"+ )++ root = tmp_path / tools._SPILL_DIR+ scopes = [p for p in root.iterdir() if p.is_dir()]+ # The budget holds two of the four, so the other two were emptied by the prune and+ # then removed rather than left standing.+ assert len(scopes) < 4+ assert all(any(scope.iterdir()) for scope in scopes)+++class TestDeletingAChatIsNotBlockedByItsSpills:+ def test_a_sandbox_holding_only_spills_is_still_removable(self, tmp_path):+ """Spills are Studio's own, written by this process and deliberately kept off the+ file cards. Counted as the user's content they leave an unreachable sandbox behind,+ reported as holding files the user never created."""+ tools._truncate(+ "\n".join(str(i) for i in range(5_000)),+ 200,+ workdir = str(tmp_path),+ scope = "abc123abc123",+ )++ assert tools._holds_no_user_files(str(tmp_path))++ def test_a_real_file_beside_them_still_counts(self):+ """The control: this must not turn into "delete any sandbox"."""+ import tempfile+ with tempfile.TemporaryDirectory() as workdir:+ tools._truncate(+ "\n".join(str(i) for i in range(5_000)), 200, workdir = workdir, scope = "abc123abc123"+ )+ open(os.path.join(workdir, "game.html"), "w").close()++ assert not tools._holds_no_user_files(workdir)++ def test_a_user_file_inside_the_spill_directory_still_counts(self, tmp_path):+ """The directory is writable and the tools can create anything in it. Skipping the+ whole tree means deleting a chat deletes a file the user's own code wrote."""+ tools._truncate(+ "\n".join(str(i) for i in range(5_000)),+ 200,+ workdir = str(tmp_path),+ scope = "abc123abc123",+ )+ (tmp_path / tools._SPILL_DIR / "notes.txt").write_text("mine")++ assert not tools._holds_no_user_files(str(tmp_path))++ def test_a_file_named_like_a_spill_but_placed_elsewhere_counts(self, tmp_path):+ """The name alone is not the test: twelve hex characters is a plausible name for+ anything, and outside the spill root nothing here wrote it."""+ (tmp_path / "abcdef123456.txt").write_text("mine")++ assert not tools._holds_no_user_files(str(tmp_path))+++class TestTheNativePathIsBoundedWithoutATokenizer:+ """`_loaded_token_counter` answers only for a resident GGUF, so on a safetensors model+ the room is converted with the four-characters-per-token English estimate and never+ corrected. Dense ASCII runs nearer two, and that loop has no rolling fit to recover."""++ def test_an_unmeasurable_room_is_halved(self, monkeypatch):+ _window(monkeypatch, 4096)+ monkeypatch.setattr(tools, "_loaded_token_counter", lambda ctx: None)+ _room(400)+ text = _dense(40_000)++ assert tools._dense_char_limit(text, tools._MAX_OUTPUT_CHARS) == pytest.approx(+ 400 * 4 * tools._UNMEASURED_ROOM_MARGIN, rel = 0.02+ )++ def test_a_measurable_room_is_not(self, monkeypatch):+ """The control: where the serving model can price the string, the exact fit does+ the work and no blanket margin is applied on top of it."""+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ _room(400)+ text = _dense(40_000)++ limit = tools._dense_char_limit(text, tools._MAX_OUTPUT_CHARS)+ assert limit > 400 * 4 * tools._UNMEASURED_ROOM_MARGIN+ assert limit // _CHARS_PER_TOKEN <= 400+++class TestOwnershipIsNotKeptWhereToolCodeCanWriteIt:+ """The sandbox is a directory the model runs commands in, so nothing kept inside it is+ evidence about it. A marker file there can be replaced with a link, and once it is a+ plain file its contents can be rewritten to name the user's own files as Studio's,+ which turns the cleanup into a delete. The record lives in Studio's own storage."""++ def test_nothing_about_ownership_is_written_into_the_sandbox(self, tmp_path):+ out = tools._truncate("\n".join(str(i) for i in range(5_000)), 200, workdir = str(tmp_path))++ names = [p.name for p in (tmp_path / tools._SPILL_DIR).iterdir()]+ assert names == [os.path.basename(_spill_path(out))]++ def test_a_directory_that_came_with_the_sandbox_is_never_adopted(self, tmp_path):+ (tmp_path / tools._SPILL_DIR).mkdir()+ (tmp_path / tools._SPILL_DIR / "notes.txt").write_text("mine")++ out = tools._truncate("\n".join(str(i) for i in range(5_000)), 200, workdir = str(tmp_path))++ assert "saved to" not in out+ assert not tools._holds_no_user_files(str(tmp_path))++ def test_a_replaced_directory_loses_the_record(self, tmp_path):+ """Tool code can delete `.unsloth_tool_output` and make its own in the same place.+ Same path, different directory, and a record that only knew the path would hand+ the new one's contents to the prune."""+ spilled = tools._truncate(+ "\n".join(str(i) for i in range(5_000)), 200, workdir = str(tmp_path)+ )+ name = os.path.basename(_spill_path(spilled))+ root = tmp_path / tools._SPILL_DIR+ shutil.rmtree(root)+ root.mkdir()+ # The same NAME the record already knows, which is what makes the path alone+ # insufficient: this file is the user's and the record was written about another+ # directory that no longer exists.+ theirs = root / name+ theirs.write_text("mine")+ for n in range(tools._SPILL_KEEP + 5):+ tools._truncate(f"run {n}\n" + _dense(3_000), 200, workdir = str(tmp_path))++ assert theirs.read_text() == "mine"+ assert not tools._is_spill_artifact(str(tmp_path), str(root), name)++ def test_a_spill_written_over_stops_being_ours(self, tmp_path):+ """A recorded path is not the file. Tool code can write its own content over a+ spill, in place, and from then on it is the user's: not something to prune, and+ not something the cleanup may delete the sandbox on top of."""+ spilled = tools._truncate(+ "\n".join(str(i) for i in range(5_000)), 200, workdir = str(tmp_path)+ )+ theirs = tmp_path / _spill_path(spilled)+ theirs.write_text("the user's own data")++ for n in range(tools._SPILL_KEEP + 5):+ tools._truncate(f"run {n}\n" + _dense(3_000), 200, workdir = str(tmp_path))++ assert theirs.read_text() == "the user's own data"+ assert not tools._holds_no_user_files(str(tmp_path))++ def test_an_untouched_spill_is_still_ours(self, tmp_path):+ """The control: reading a spill back, which is the whole point of writing it, must+ not turn it into user content."""+ spilled = tools._truncate(+ "\n".join(str(i) for i in range(5_000)), 200, workdir = str(tmp_path)+ )+ (tmp_path / _spill_path(spilled)).read_text()++ assert tools._holds_no_user_files(str(tmp_path))+++class TestConcurrentSpillsKeepTheirRecords:+ def test_a_spill_recorded_during_a_prune_is_not_dropped(self, tmp_path):+ """A project's chats share one sandbox. Appending a spill and rewriting the+ manifest after a prune are a read-modify-write over one file, and a pruner that+ read it before another call appended would discard the newer entry, leaving a+ file nothing counts, prunes, or recognises as Studio's."""+ import threading++ workdir = str(tmp_path)+ started = threading.Barrier(8)+ results = []++ def _spill(n):+ started.wait()+ results.append(+ tools._truncate(+ f"chat {n}\n" + _dense(3_000), 200, workdir = workdir, scope = f"{n:012x}"+ )+ )++ threads = [threading.Thread(target = _spill, args = (n,)) for n in range(8)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ root = tmp_path / tools._SPILL_DIR+ recorded = set(tools._spill_manifest(str(root)))+ on_disk = {str(p.relative_to(root)) for p in root.rglob("*.txt") if p.name != "victim.txt"}+ assert on_disk, results[:1]+ assert on_disk <= recorded, "a spill on disk that the manifest does not record"++ def test_a_spill_restored_to_its_old_mtime_is_still_not_ours(self, tmp_path):+ """mtime alone is forgeable: same-sized content and `os.utime` put it back, and a+ coarse-grained filesystem can leave it unchanged without any help. ctime moves on+ any write and cannot be set from userspace, and the content is checked besides."""+ spilled = tools._truncate(+ "\n".join(str(i) for i in range(5_000)), 200, workdir = str(tmp_path)+ )+ theirs = tmp_path / _spill_path(spilled)+ was = theirs.stat()+ theirs.write_bytes(b"m" * was.st_size)+ os.utime(theirs, ns = (was.st_atime_ns, was.st_mtime_ns))++ assert theirs.stat().st_size == was.st_size+ assert theirs.stat().st_mtime_ns == was.st_mtime_ns+ assert not tools._holds_no_user_files(str(tmp_path))++ @pytest.mark.skipif(+ not tools._DIR_FD_WRITES, reason = "no dir_fd support; the path-based write stands"+ )+ def test_the_spill_write_never_follows_a_swapped_directory(self, tmp_path):+ """A shared project sandbox can lose the race between checking the directory and+ writing into it by name: another call can put a symlink there in between, and a+ path-based create and rename both follow it.++ Checked on the writer itself, since by construction the swap happens after every+ check the caller makes.+ """+ outside = tmp_path / "outside"+ outside.mkdir()+ swapped = tmp_path / "scope"+ swapped.symlink_to(outside, target_is_directory = True)++ assert tools._write_spill_file(str(swapped), "abcdef123456.txt", "x" * 100) is None+ assert list(outside.iterdir()) == [], "the spill was written outside the sandbox"++ def test_the_writer_still_works_on_a_real_directory(self, tmp_path):+ """The control, so the refusal above is not simply "never writes"."""+ assert tools._write_spill_file(str(tmp_path), "abcdef123456.txt", "x" * 100)++ assert (tmp_path / "abcdef123456.txt").read_text() == "x" * 100+++class TestARemovedSandboxTakesItsRecordWithIt:+ """Session workdirs are unique, so a record left behind is one small file per deleted+ chat, for the life of the installation."""++ @staticmethod+ def _sandbox(tmp_path, monkeypatch, session):+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))+ tools._workdirs.clear()+ workdir = tools.get_sandbox_workdir(session)+ tools._truncate("\n".join(str(i) for i in range(5_000)), 200, workdir = workdir)+ record = tools._spill_record_path(os.path.join(workdir, tools._SPILL_DIR))+ assert os.path.exists(record)+ return workdir, record++ def test_an_empty_sandbox_takes_its_record(self, tmp_path, monkeypatch):+ """Only spills are left in it, so the sandbox goes without opting into files."""+ workdir, record = self._sandbox(tmp_path, monkeypatch, "__LOCALID_spill111")++ assert tools.remove_session_sandbox("__LOCALID_spill111") is True++ assert not os.path.exists(workdir)+ assert not os.path.exists(record)++ def test_a_sandbox_deleted_with_its_files_does_too(self, tmp_path, monkeypatch):+ workdir, record = self._sandbox(tmp_path, monkeypatch, "__LOCALID_spill222")+ open(os.path.join(workdir, "game.html"), "w").close()++ assert tools.remove_session_sandbox("__LOCALID_spill222", delete_files = True) is True++ assert not os.path.exists(record)++ def test_the_fallback_deletion_takes_it_too(self, tmp_path, monkeypatch):+ """The rename can fail (a cross-device sandbox root, a locked tree on Windows), and+ the rmtree that stands in for it deletes just as much, so it has to forget just as+ much."""+ workdir, record = self._sandbox(tmp_path, monkeypatch, "__LOCALID_spill444")++ def _no_rename(*args, **kwargs):+ raise OSError("rename unavailable")++ monkeypatch.setattr(tools.os, "rename", _no_rename)++ assert tools.remove_session_sandbox("__LOCALID_spill444", delete_files = True) is True++ assert not os.path.exists(workdir)+ assert not os.path.exists(record)++ def test_a_sandbox_that_stays_keeps_its_record(self, tmp_path, monkeypatch):+ """The control: the files are the user's, the sandbox stays, and so does the+ record of what in it is Studio's."""+ workdir, record = self._sandbox(tmp_path, monkeypatch, "__LOCALID_spill333")+ open(os.path.join(workdir, "game.html"), "w").close()++ assert tools.remove_session_sandbox("__LOCALID_spill333") is False++ assert os.path.exists(record)++ def test_rerunning_a_command_does_not_overwrite_replaced_content(self, tmp_path):+ """The name comes from the content, so running the same command again lands on the+ same path. If the user's code put its own data there in between, the rename would+ replace it: the manifest already knows it stopped being ours, and the write has to+ ask."""+ text = "\n".join(str(i) for i in range(5_000))+ spilled = tools._truncate(text, 200, workdir = str(tmp_path))+ theirs = tmp_path / _spill_path(spilled)+ theirs.write_text("the user's own data")++ again = tools._truncate(text, 200, workdir = str(tmp_path))++ assert theirs.read_text() == "the user's own data"+ assert "saved to" not in again++ def test_the_same_output_twice_still_reuses_its_own_spill(self, tmp_path):+ """The control: an untouched spill is still ours, so the repeat case this whole+ change is about keeps working instead of refusing on its own file."""+ text = "\n".join(str(i) for i in range(5_000))++ first = tools._truncate(text, 200, workdir = str(tmp_path))+ second = tools._truncate(text, 200, workdir = str(tmp_path))++ assert first == second+ assert len(_spills(tmp_path / tools._SPILL_DIR)) == 1++ def test_a_first_spill_is_not_disowned_by_a_racing_one(self, tmp_path):+ """Two first-time spills in one sandbox can both see the directory absent. The+ slower one must not write an empty record over the winner's: that would leave the+ winner's spill owned by nobody, never pruned and counted as the user's content."""+ import threading++ ready = threading.Barrier(6)+ outs = []++ def _spill(n):+ ready.wait()+ outs.append(tools._truncate(f"chat {n}\n" + _dense(3_000), 200, workdir = str(tmp_path)))++ threads = [threading.Thread(target = _spill, args = (n,)) for n in range(6)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ root = tmp_path / tools._SPILL_DIR+ recorded = set(tools._spill_manifest(str(root)))+ on_disk = {p.name for p in root.iterdir()}+ assert on_disk and on_disk <= recorded, "a spill on disk that the record disowned"+++class TestTheContinuationChunkDecodes:+ """`head -c` counts bytes. A round number of them lands inside a code point on any+ mixed-width text, and the terminal runner decodes with errors="replace", so the+ continuation the notice advertises would hand back a mangled character every time."""++ @staticmethod+ def _resume(out: str) -> "tuple[int, int]":+ """The byte offset and chunk size out of a `tail -c +N | head -c M` hint."""+ tail, _, head = out.rsplit("tail -c +", 1)[1].partition(" | head -c ")+ return int(tail.split()[0]), int(head.rstrip(")").strip())++ def test_the_chunk_ends_on_a_character_boundary(self, tmp_path):+ # One long line, so the cut is mid-line and the hint is byte-based. 299 ASCII+ # characters and then three-byte ones: the head is 302 bytes, and 302 bytes of+ # what follows is 100 characters plus two bytes of the next.+ text = "a" * 299 + "€" * 4_000++ out = tools._truncate(text, 300, workdir = str(tmp_path))+ offset, span = self._resume(out)++ blob = (tmp_path / _spill_path(out)).read_bytes()+ chunk = blob[offset - 1 : offset - 1 + span]+ # Strict, because errors="replace" is exactly what hides this.+ assert chunk.decode("utf-8")++ def test_the_chunk_resumes_where_the_head_stopped(self, tmp_path):+ text = "a" * 299 + "€" * 4_000++ out = tools._truncate(text, 300, workdir = str(tmp_path))+ offset, span = self._resume(out)++ shown = out.split("\n\n... (")[0]+ blob = (tmp_path / _spill_path(out)).read_bytes()+ assert (+ blob[offset - 1 : offset - 1 + span].decode("utf-8")+ == text[len(shown) : len(shown) + len(shown)]+ )+++class TestInstallingASpillNeverReplacesAnything:+ """The caller checks the destination, then the write takes as long as it takes. In+ that window another call sharing the workspace can put a file at the name, and a+ rename would replace it silently: POSIX rename overwrites, link does not."""++ def test_a_name_taken_during_the_write_is_not_overwritten(self, tmp_path):+ theirs = tmp_path / "abcdef123456.txt"+ theirs.write_text("the user's own data")++ assert tools._write_spill_file(str(tmp_path), theirs.name, "x" * 100) is None++ assert theirs.read_text() == "the user's own data"++ def test_no_temporary_is_left_when_the_name_is_taken(self, tmp_path):+ (tmp_path / "abcdef123456.txt").write_text("mine")++ tools._write_spill_file(str(tmp_path), "abcdef123456.txt", "x" * 100)++ assert [p.name for p in tmp_path.iterdir()] == ["abcdef123456.txt"]++ def test_an_unchanged_spill_is_reused_without_writing(self, tmp_path, monkeypatch):+ """And the repeat case does not go near the install at all: the name is the digest+ of the text, so a recorded spill at it already holds exactly this content."""+ text = "\n".join(str(i) for i in range(5_000))+ first = tools._truncate(text, 200, workdir = str(tmp_path))++ def _refuse(*args, **kwargs):+ raise AssertionError("rewrote a spill that was already there")++ monkeypatch.setattr(tools, "_write_spill_file", _refuse)++ assert tools._truncate(text, 200, workdir = str(tmp_path)) == first++ def test_the_record_names_what_was_installed_not_what_is_there_now(self, tmp_path):+ """Between the install and the record, another call sharing the sandbox can replace+ the file. Stating the path then records THAT content as Studio's, and a later prune+ or cleanup deletes the user's data on the strength of it."""+ root = _own(tmp_path)+ name = "abcdef123456.txt"+ stamp = tools._write_spill_file(str(root), name, "the spill")+ # The replacement, in the window the record must not read across.+ (root / name).write_text("the user's own data")++ tools._record_spill(str(root), name, stamp, hashlib.sha256(b"the spill").hexdigest())++ assert not tools._is_recorded_spill(+ str(root), str(root / name), tools._spill_manifest(str(root))+ )+ assert not tools._holds_no_user_files(str(tmp_path))+++class TestPruningDeletesOnlyWhatItChecked:+ """The manifest lock orders Studio's own threads; the thing racing here is the sandbox.+ A background process can replace a recorded spill between the check and the unlink, and+ a delete by name then takes the replacement."""++ @staticmethod+ def _swap_after_check(monkeypatch, victim, content):+ """Replace the file after the prune has verified it and before it deletes it.++ Hooked on the sort that runs between the two, since a swap during the verification+ is caught by the verification itself and proves nothing about the window after it.+ """+ real = os.path.getmtime++ def _getmtime(path):+ result = real(path)+ if os.fspath(path) == victim:+ open(victim, "w").write(content)+ return result++ monkeypatch.setattr(os.path, "getmtime", _getmtime)++ def test_a_file_swapped_after_the_check_is_not_deleted(self, tmp_path, monkeypatch):+ # Enough that the oldest are on their way out: a prune with nothing to delete+ # would prove nothing about what it deletes.+ for n in range(tools._SPILL_KEEP + 5):+ tools._truncate(f"run {n}\n" + _dense(3_000), 200, workdir = str(tmp_path))+ root = tmp_path / tools._SPILL_DIR+ victim = sorted(_spills(root), key = lambda p: p.stat().st_mtime)[0]+ # Lowered so this pass has files to delete: the prune after each spill has already+ # brought the directory back to the limit.+ monkeypatch.setattr(tools, "_SPILL_KEEP", 5)+ self._swap_after_check(monkeypatch, str(victim), "the user's own data")++ tools._prune_spills(str(root))++ assert victim.exists(), "the prune deleted a file it had not verified"+ assert victim.read_text() == "the user's own data"++ def test_an_untouched_spill_is_still_pruned(self, tmp_path):+ """The control: the budget still has to bite, or the fix above is just "never+ delete anything"."""+ for n in range(tools._SPILL_KEEP + 5):+ tools._truncate(f"run {n}\n" + _dense(3_000), 200, workdir = str(tmp_path))++ assert len(_spills(tmp_path / tools._SPILL_DIR)) <= tools._SPILL_KEEP++ def test_nothing_is_left_under_a_temporary_name(self, tmp_path):+ for n in range(tools._SPILL_KEEP + 5):+ tools._truncate(f"run {n}\n" + _dense(3_000), 200, workdir = str(tmp_path))++ names = [p.name for p in _spills(tmp_path / tools._SPILL_DIR)]+ assert all(tools._SPILL_NAME_RE.fullmatch(n) for n in names), names+++class TestReadingASpillCannotBeRedirected:+ """The stamp is taken a moment before the content is read, and this runs in the+ sandbox's own directory. A plain open by name would follow a symlink installed in+ between and block forever on a FIFO or a device, with no timeout above it."""++ def test_a_symlink_at_the_name_is_not_followed(self, tmp_path):+ elsewhere = tmp_path / "elsewhere.txt"+ elsewhere.write_text("someone else's file")+ link = tmp_path / "abcdef123456.txt"+ link.symlink_to(elsewhere)++ assert tools._file_digest(str(link)) is None++ def test_a_fifo_is_refused_rather_than_read(self, tmp_path):+ fifo = tmp_path / "abcdef123456.txt"+ os.mkfifo(fifo)++ # Would block forever on a plain open, so a hang here is the failure.+ assert tools._file_digest(str(fifo)) is None++ def test_a_file_of_the_wrong_size_is_refused_before_it_is_read(self, tmp_path):+ real = tmp_path / "abcdef123456.txt"+ real.write_text("x" * 100)++ assert tools._file_digest(str(real), 100)+ assert tools._file_digest(str(real), 101) is None++ def test_an_ordinary_spill_still_reads(self, tmp_path):+ """The control: everything above has to leave the normal case working."""+ spilled = tools._truncate(+ "\n".join(str(i) for i in range(5_000)), 200, workdir = str(tmp_path)+ )++ assert tools._holds_no_user_files(str(tmp_path)), spilled+++class TestPruningNeverMovesSomethingItCannotPutBack:+ """A rename moves whatever is at the name, and the sandbox can put anything there.++ The prune moves a spill to a private name so the inode it verified is the inode it+ deletes. If the sandbox replaced that name with a directory first, the rename takes+ the directory, the stamp check then rejects it, and `os.link` cannot put a directory+ back: the user's data ends up stranded under a hidden temporary name. So nothing but+ the regular file the record remembers is moved in the first place.+ """++ @staticmethod+ def _a_recorded_spill(tmp_path) -> "tuple[str, str, dict]":+ spilled = tools._truncate(+ "\n".join(str(i) for i in range(5_000)), 200, workdir = str(tmp_path)+ )+ root = str(tmp_path / tools._SPILL_DIR)+ return root, str(tmp_path / _spill_path(spilled)), tools._spill_manifest(root)++ @staticmethod+ def _private_names(root) -> list:+ return [p.name for p in os.scandir(root) if p.name.startswith(".tmp-prune-")]++ @staticmethod+ def _watch_renames(monkeypatch) -> list:+ """Every source `os.rename` was asked to move. Putting a thing back afterwards is+ the backstop; not moving it at all is the fix."""+ moved = []+ real = os.rename++ def _rename(src, dst, *args, **kwargs):+ moved.append(os.fspath(src))+ return real(src, dst, *args, **kwargs)++ monkeypatch.setattr(os, "rename", _rename)+ return moved++ def test_a_directory_left_at_the_name_is_not_moved(self, tmp_path, monkeypatch):+ root, spill, owned = self._a_recorded_spill(tmp_path)+ os.unlink(spill)+ os.mkdir(spill)+ open(os.path.join(spill, "receipts.csv"), "w").write("the user's own data")+ moved = self._watch_renames(monkeypatch)++ assert tools._unlink_verified_spill(root, spill, owned) is False+ assert spill not in moved, "a directory was moved to a private name"+ assert os.path.isdir(spill), "the prune moved a directory it could not put back"+ assert open(os.path.join(spill, "receipts.csv")).read() == "the user's own data"+ assert not self._private_names(root)++ def test_a_fifo_left_at_the_name_is_not_moved(self, tmp_path, monkeypatch):+ root, spill, owned = self._a_recorded_spill(tmp_path)+ os.unlink(spill)+ os.mkfifo(spill)+ moved = self._watch_renames(monkeypatch)++ # A plain open would block here with no timeout above it, so a hang is the failure.+ assert tools._unlink_verified_spill(root, spill, owned) is False+ assert spill not in moved, "a FIFO was moved to a private name"+ assert os.path.exists(spill)+ assert not self._private_names(root)++ def test_a_file_written_over_in_place_is_not_moved(self, tmp_path, monkeypatch):+ """Same name, same inode, different content: the identity check is not just a+ file-type check."""+ root, spill, owned = self._a_recorded_spill(tmp_path)+ open(spill, "w").write("the user's own data")+ moved = self._watch_renames(monkeypatch)++ assert tools._unlink_verified_spill(root, spill, owned) is False+ assert spill not in moved, "a file the sandbox had rewritten was moved"+ assert open(spill).read() == "the user's own data"+ assert not self._private_names(root)++ def test_a_spill_moved_and_then_rejected_is_put_back(self, tmp_path, monkeypatch):+ """The window between the check and the rename is narrow, not closed, so the+ restore still has to work when `os.link` is the one thing that cannot do it."""+ root, spill, owned = self._a_recorded_spill(tmp_path)+ was = open(spill).read()+ real_rename = os.rename++ def _rename(src, dst, *args, **kwargs):+ result = real_rename(src, dst, *args, **kwargs)+ if os.fspath(src) == spill:+ # Swapped in the instant after the move, which is what the check above+ # cannot see and the restore has to survive.+ open(dst, "w").write("changed underneath")+ return result++ monkeypatch.setattr(os, "rename", _rename)+ monkeypatch.setattr(os, "link", _refuses_directories)++ assert tools._unlink_verified_spill(root, spill, owned) is False+ assert os.path.isfile(spill), "the prune stranded a file it declined to delete"+ assert open(spill).read() == "changed underneath", was[:20]+ assert not self._private_names(root)++ def test_an_untouched_spill_is_still_deleted(self, tmp_path):+ """The control: everything above has to leave the prune able to prune."""+ root, spill, owned = self._a_recorded_spill(tmp_path)++ assert tools._unlink_verified_spill(root, spill, owned) is True+ assert not os.path.exists(spill)+ assert not self._private_names(root)+++def _refuses_directories(*args, **kwargs):+ """`os.link` as it behaves on the case that motivates this: EPERM, always."""+ raise OSError(1, "Operation not permitted")+++class TestARejectedToolCallIsHeldToTheRoomToo:+ """`python` and `terminal` cap the output of a run, but a call that never gets that+ far returns straight out of the validator. The Python analyzer names every occurrence+ it found, so code repeating one forbidden construct reports back a result larger than+ the room that is left, which is the overflow the budget exists to prevent."""++ @staticmethod+ def _tampering(times: int) -> str:+ return "import signal\ndef h(a, b): pass\n" + "\n".join(+ "signal.signal(signal.SIGALRM, h)" for _ in range(times)+ )++ def test_the_unsafe_code_error_is_capped(self, monkeypatch):+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ uncapped = tools._check_code_safety(self._tampering(400))+ assert uncapped and len(uncapped) > 10_000, "the analyzer stopped amplifying"++ out = tools.execute_tool("python", {"code": self._tampering(400)}, result_budget_tokens = 400)++ assert out.startswith("Error: unsafe code detected")+ _within_room(out, 400)++ def test_a_blocked_command_is_capped(self, monkeypatch):+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ monkeypatch.setattr(tools, "_find_blocked_commands", lambda command: {_dense(40_000)})++ out = tools.execute_tool("terminal", {"command": "ls"}, result_budget_tokens = 400)++ assert out.startswith("Blocked command(s) for safety:")+ _within_room(out, 400)++ def test_a_short_rejection_is_returned_whole(self, monkeypatch):+ """The control: a cap that rewrote every rejection would hide what was wrong."""+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)++ out = tools.execute_tool("python", {"code": self._tampering(1)}, result_budget_tokens = 120)++ assert out == tools._check_code_safety(self._tampering(1))+++class TestTheNoticeIsChargedWhereTheCutIsDecided:+ """A result that fits carries no notice, so reserving for one before the size is known+ cuts results that would have fitted, and spends more of the window doing it: 200 tokens+ of room and a 100-token result leaves 72 for the body and appends ~70 tokens of notice+ to explain the 28 that were dropped. The reserve belongs at the point the cut is+ decided, not in the number the caller is handed."""++ @staticmethod+ def _room_for(text: str, spare: int) -> int:+ """The room `tool_result_budget` reports for a thread that leaves `text` fitting+ with `spare` tokens to go. Through the budget, because that is where the reserve+ used to come off."""+ target = int(prompt_budget(4096, None) * 0.99)+ cost = len(text) // _CHARS_PER_TOKEN+ return tool_result_budget(4096, None, target - cost - spare)++ def test_a_result_that_fits_is_not_cut_to_pay_for_a_notice(self, monkeypatch):+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ text = _dense(3_000)+ # Comfortably inside the room and well inside the reserve, which is the band where+ # holding the reserve back turns a whole result into a truncated one.+ room = self._room_for(text, _RESULT_NOTICE_RESERVE // 2)+ _room(room)++ out = tools._truncate(text, 1_000_000)++ assert out == text, out[-200:]++ def test_the_notice_is_still_inside_the_room_when_it_is_needed(self, monkeypatch):+ """The other half: charged late, it still has to be charged."""+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ text = _dense(200_000)+ room = self._room_for(_dense(3_000), _RESULT_NOTICE_RESERVE // 2)+ _room(room)++ out = tools._truncate(text, 1_000_000)++ assert "... (truncated" in out+ _within_room(out, room)++ def test_a_caller_with_no_priced_room_is_unchanged(self, monkeypatch):+ """The legacy leg: with no room the caller's character cap is the whole budget and+ the notice has always been appended past it. Charging a token reserve against a+ character cap there would cut every one of those callers to nothing."""+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)++ out = tools._truncate("\n".join(f"line {i}" for i in range(1, 501)), 200)++ assert out.startswith("line 1\n")+ assert "... (truncated to 200 chars" in out+++class TestACounterThatCannotAnswerIsNotACounter:+ """`_loaded_token_counter` hands back a callable that returns None whenever the probe+ does not come back with a number: `/apply-template` failing, or a template that drops+ the probe role. `_exact_prefix_chars` then keeps the caller's estimate, which charges+ ASCII the English four characters per token, and the margin that exists for exactly+ this case was skipped because a counter was, technically, present."""++ @staticmethod+ def _mute(monkeypatch):+ """A backend that exposes a counter and can never price anything with it."""+ monkeypatch.setattr(+ tools, "_loaded_token_counter", lambda ctx: (lambda chunk, token_budget = 0.0: None)+ )++ def test_a_counter_that_measures_nothing_gets_the_conservative_margin(self, monkeypatch):+ _window(monkeypatch, 4096)+ _room(200)+ text = _dense(100_000)++ self._mute(monkeypatch)+ mute = tools._dense_char_limit(text, 1_000_000)+ monkeypatch.setattr(tools, "_loaded_token_counter", lambda ctx: None)+ absent = tools._dense_char_limit(text, 1_000_000)++ assert mute == absent, "a counter that cannot measure was trusted anyway"+ # 200 tokens at the estimate's four ASCII characters per token, halved.+ assert mute <= 200 * 4 * tools._UNMEASURED_ROOM_MARGIN++ def test_a_hint_is_priced_conservatively_too(self, monkeypatch):+ """`_text_token_cost` reads the same counter, and a hint priced at the English+ rate is spent at the dense one."""+ _window(monkeypatch, 4096)+ hint = "\n\n(" + _dense(400) + ")"++ self._mute(monkeypatch)+ mute = tools._text_token_cost(hint, 4096)+ monkeypatch.setattr(tools, "_loaded_token_counter", lambda ctx: None)+ absent = tools._text_token_cost(hint, 4096)++ assert mute == absent+ assert mute >= len(hint) * 0.25 / tools._UNMEASURED_ROOM_MARGIN++ def test_a_counter_that_answers_is_still_believed(self, monkeypatch):+ """The control: the margin is for measurement that failed, not for measurement."""+ _window(monkeypatch, 4096)+ _room(200)+ text = _dense(100_000)+ _tokenizer(monkeypatch)++ measured = tools._dense_char_limit(text, 1_000_000)++ assert measured > 200 * 4 * tools._UNMEASURED_ROOM_MARGIN+++class TestADenseNativeTurnIsPricedAsOne:+ """The native loop has no tokenizer and no rolling fit, so the number it computes for+ what the thread has already spent is the whole defence. Charging a pasted blob the+ English four characters per token reports a third of what it costs, and the result+ admitted against that difference is what puts the next prompt over the window.++ Measured with Qwen3 over 16-20k character samples, in characters per token: base64+ 1.35, hex 1.13, minified JSON 2.75, English prose 3.27, Python source 4.38.+ """++ @staticmethod+ def _turn(text: str) -> list:+ return [{"role": "user", "content": text}]++ def test_a_pasted_blob_costs_more_than_the_same_length_of_prose(self):+ blob = self._turn(_dense(20_000).replace("\n", ""))+ prose = self._turn("word " * 4_000)++ assert len(blob[0]["content"]) >= len(prose[0]["content"]) * 0.9+ assert estimate_messages_tokens_conservative(blob) > (+ 1.9 * estimate_messages_tokens_conservative(prose)+ )++ def test_prose_and_code_are_priced_as_before(self):+ """The rule is for blobs. Prose and indented source have no unbroken runs that+ long, and charging them twice would spend room the thread has not."""+ for text in ("word " * 4_000, "def f(x):\n return x + 1\n" * 500):+ turn = self._turn(text)+ assert estimate_messages_tokens_conservative(turn) == (+ estimate_messages_tokens_dense(turn)+ )++ def test_wrapped_base64_is_still_a_blob(self):+ """Conventionally wrapped at 76 characters, which is why the run threshold is 64+ rather than a rounder number above it."""+ wrapped = self._turn("\n".join("QUJDREVG" * 9 + "QUJD" for _ in range(250)))++ assert estimate_messages_tokens_conservative(wrapped) > (+ 1.5 * estimate_messages_tokens_dense(wrapped)+ )++ def test_the_loop_hands_out_less_room_after_a_blob(self):+ """End to end through the real loop: the same number of characters, priced as what+ they are, leaves less room for the result that follows."""+ # Sized to leave room either way at this window: two threads that both fit, one+ # of which has spent twice what the other has on the same character count.+ blob = TestTheSafetensorsLoopPricesItToo._run(+ 4096, messages = [{"role": "user", "content": _dense(4_000).replace("\n", "")}]+ )["result_budget_tokens"]+ prose = TestTheSafetensorsLoopPricesItToo._run(+ 4096, messages = [{"role": "user", "content": "word " * 800}]+ )["result_budget_tokens"]++ assert blob < prose+++class TestSpillingDoesNotCopyTheResultAgain:+ """The output this path runs on is by definition the output that did not fit. Encoding+ all of it to hash it and all of it again to cut it puts two more copies of a `cat` of a+ file the model just wrote through memory, at the point the result is already in hand,+ when at most `_SPILL_MAX_BYTES` of the second is ever written."""++ def test_the_pass_is_bounded_by_the_cap_rather_than_the_result(self, tmp_path, monkeypatch):+ import tracemalloc++ monkeypatch.setattr(tools, "_SPILL_MAX_BYTES", 4_096)+ text = _dense(8_000_000)++ tracemalloc.start()+ try:+ tools._spill_full_output(text, str(tmp_path), "")+ _current, peak = tracemalloc.get_traced_memory()+ finally:+ tracemalloc.stop()++ assert peak < len(text) // 2, f"{peak} bytes for a {len(text)} character result"++ def test_the_name_is_still_the_digest_of_the_whole_text(self, tmp_path):+ text = "\n".join(f"line {i}" for i in range(20_000))++ spilled, complete = tools._spill_full_output(text, str(tmp_path), "")++ assert complete+ whole = hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest()[:12]+ assert spilled.endswith(f"{whole}.txt"), spilled++ def test_a_chunk_boundary_does_not_change_the_bytes(self, tmp_path, monkeypatch):+ """UTF-8 encodes a code point at a time, so slicing the string cannot split one.+ Forced small, so every multi-byte character in this text straddles a boundary."""+ monkeypatch.setattr(tools, "_SPILL_HASH_CHUNK_CHARS", 3)+ text = "aé漢🙂" * 2_000++ spilled, complete = tools._spill_full_output(text, str(tmp_path), "")++ whole = hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest()[:12]+ assert complete and spilled.endswith(f"{whole}.txt")+ assert (tmp_path / _spill_path(f"saved to {spilled} ")).read_text(encoding = "utf-8") == text++ def test_an_oversized_result_is_still_cut_at_the_cap(self, tmp_path, monkeypatch):+ monkeypatch.setattr(tools, "_SPILL_MAX_BYTES", 4_096)+ text = _dense(200_000)++ spilled, complete = tools._spill_full_output(text, str(tmp_path), "")++ assert not complete+ written = (tmp_path / _spill_path(f"saved to {spilled} ")).read_bytes()+ assert len(written) <= 4_096+ assert written == text.encode("utf-8")[: len(written)]+++class TestAToolResultIsPricedOnceOnTheNativePath:+ """The conservative estimate prices every message it is handed, results included, so+ adding a separately priced result total on top charges those messages twice. On text+ it already charges a token a character, that is two tokens per character, and a thread+ holding one sizable earlier result reports no room while it still has plenty."""++ @staticmethod+ def _budget(message: dict) -> int:+ return TestTheSafetensorsLoopPricesItToo._run(+ 8192, messages = [{"role": "user", "content": "print it"}, message]+ )["result_budget_tokens"]++ def test_a_wide_result_costs_what_the_same_text_costs_anywhere(self):+ """CJK is already a token a character in the estimate. Charging a result for being+ a result on top of that prices it at two, which is not a rate any tokenizer has."""+ text = "文字" * 700++ as_result = self._budget({"role": "tool", "content": text})+ as_prose = self._budget({"role": "user", "content": text})++ assert as_result > 0 and as_prose > 0+ assert as_prose - as_result < as_prose * 0.05, (as_result, as_prose)++ def test_a_spaced_ascii_result_is_still_priced_densely(self):+ """The control: pricing it once must not mean pricing it as prose. `hexdump`,+ `ls -l` and stack traces carry spaces and still tokenise near two."""+ text = "abcd " * 1_200++ as_result = self._budget({"role": "tool", "content": text})+ as_prose = self._budget({"role": "user", "content": text})++ assert as_result < as_prose+++class TestTheResultIsPricedAsItWillBeSent:+ """A tool result is swept for control markup before it is sent (#7066), and the sweep+ costs tokens: a live `<|eot_id|>` is one special token in the raw text and several+ ordinary ones once it has been broken up. Measured on the raw prefix, a result full of+ them fits the room here and does not fit the prompt that follows, which is the overflow+ this budget exists to prevent reached through the accurate leg."""++ @staticmethod+ def _serving(monkeypatch, ctx):+ """A loaded backend that charges a token per character, so the count moves with+ exactly what the sweep does to the text."""+ from types import SimpleNamespace++ backend = SimpleNamespace(+ is_loaded = True,+ context_length = ctx,+ count_chat_tokens = lambda messages, *a, **k: sum(len(m["content"]) for m in messages),+ )+ monkeypatch.setattr("routes.inference.get_llama_cpp_backend", lambda: backend)+ return backend++ def test_the_counter_prices_the_swept_text(self, monkeypatch):+ from core.inference.chat_template_helpers import (+ neutralize_control_markup_in_messages,+ )++ self._serving(monkeypatch, 4096)+ raw = "<|eot_id|>" * 50+ swept = neutralize_control_markup_in_messages(+ [{"role": "user", "content": raw}], None, None+ )[0]["content"]+ assert len(swept) > len(raw), "the sweep left this text alone; pick another marker"++ counter = tools._loaded_token_counter(4096)++ assert counter(raw) == len(swept)++ def test_a_result_of_markers_is_cut_to_what_the_sweep_costs(self, monkeypatch):+ self._serving(monkeypatch, 4096)+ _window(monkeypatch, 4096)+ _room(200)+ text = "<|eot_id|>" * 400++ kept = tools._dense_char_limit(text, 1_000_000)++ from core.inference.chat_template_helpers import (+ neutralize_control_markup_in_messages,+ )++ cost = len(+ neutralize_control_markup_in_messages(+ [{"role": "user", "content": text[:kept]}], None, None+ )[0]["content"]+ )+ assert cost <= 200, f"{kept} characters cost {cost} tokens of a 200 token room"++ def test_ordinary_text_is_unchanged_by_the_sweep(self, monkeypatch):+ """The control: text with no markup in it is priced exactly as it was."""+ self._serving(monkeypatch, 4096)+ text = _dense(4_000)++ assert tools._loaded_token_counter(4096)(text) == len(text)+++class TestWhatTheLoopAppendsIsPricedToo:+ """The tool hands its result back and the loop adds to it: a result that opens with a+ tool-error prefix gets `TOOL_ERROR_NUDGE`, after this budget has already let the body+ take the whole room, and a parallel batch of failed calls carries one nudge each."""++ @staticmethod+ def _fitted(monkeypatch, prefix: str) -> int:+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ _room(400)+ return len(tools._truncate(prefix + _dense(40_000)))++ def test_an_error_result_is_shortened_by_what_the_nudge_costs(self, monkeypatch):+ from core.inference.tool_call_parser import TOOL_ERROR_NUDGE++ # The same length, so the only thing between them is the nudge one of them will be+ # given: "Error" is a `TOOL_ERROR_PREFIXES` entry and "Alpha" is not.+ failed = self._fitted(monkeypatch, "Error: ")+ fine = self._fitted(monkeypatch, "Alpha: ")++ # In characters, at the rate the fixture's counter charges them.+ assert fine - failed >= len(TOOL_ERROR_NUDGE) * 0.9, (failed, fine)++ def test_the_result_and_its_nudge_fit_the_room_together(self, monkeypatch):+ from core.inference.tool_call_parser import TOOL_ERROR_NUDGE++ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ _room(400)++ out = tools._truncate("Error: " + _dense(40_000))++ _within_room(out + TOOL_ERROR_NUDGE, 400)++ def test_an_ordinary_result_does_not_pay_for_one(self, monkeypatch):+ """The control: charged to the results that carry it, not to every result. A+ reserve taken from all of them spends room the thread has."""+ assert self._fitted(monkeypatch, "Alpha: ") == self._fitted(monkeypatch, "Bravo: ")+++class TestTheResultIsFittedAsItIsReplayed:+ """`_defuse_sentinels` inserts a space into every line that opens with a frontend+ marker. Applied after the fit, output full of such lines grows once it has been+ measured, and the text replayed to the model is larger than the prefix admitted."""++ def test_the_body_is_the_length_the_notice_claims(self, monkeypatch):+ """Through the real terminal path, on output that is all marker lines. The notice+ names the number of characters the body was cut to, so a body longer than that is+ text that was added after the measurement."""+ import re++ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ # Anchored on the line start, so the text has to carry the break with it.+ lines = "\n__FILES__:x" * 3+ assert tools._defuse_sentinels(lines) != lines, "not a marker line any more"++ out = tools.execute_tool(+ "terminal",+ {"command": "seq 4000 | sed 's/.*/__FILES__:x/'"},+ result_budget_tokens = 400,+ )++ head, _, notice = out.partition("\n\n... (truncated to ")+ assert notice, out[:200]+ # At most, not exactly: the head stops on a line boundary, so it comes in under+ # the limit. Over it is text that was added after the measurement.+ assert len(head) <= int(re.match(r"(\d+) chars", notice).group(1)), len(head)+ assert head == tools._defuse_sentinels(head)