Skip to content

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

Studio: compact long chats on API models too (#12786)

Nilayf16d10483770
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index 09edc19fefe..f35358c81a9 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -17,7 +17,7 @@ import threading
import time
import weakref
import wave
-from typing import Any, AsyncGenerator, Literal, NamedTuple, Optional, Union
+from typing import Any, AsyncGenerator, Awaitable, Callable, Literal, NamedTuple, Optional, Union
from urllib.parse import urlparse, urlsplit, urlunsplit
import httpx
@@ -62,6 +62,11 @@ logger = structlog.get_logger(__name__)
_MAX_CONCATENATED_WAV_BYTES = 64 * 1024 * 1024
_MAX_CONCATENATED_WAV_SEGMENTS = 1_024
+CompactionFallback = Callable[
+ [list[dict[str, Any]]],
+ Awaitable[tuple[list[dict[str, Any]], Optional[int], Optional[str]]],
+]
+
def _merge_concatenated_wav_segments(
audio: bytes, cancelled: Optional[threading.Event] = None
@@ -643,9 +648,7 @@ def _anthropic_code_execution_version(model: str) -> str:
_ANTHROPIC_CODE_EXECUTION_BETA = "code-execution-2025-08-25"
-# Anthropic server-side context compaction (beta compact-2026-01-12), supported on Claude 5, Opus 4.6/4.7/4.8, Sonnet
-# 4.6 and Mythos Preview. Same beta header for all; the dated `compact_20260112` type lives in body
-# `context_management.edits`. Models outside the prefix list are silently ignored so we do not 400 upstream.
+# Anthropic compaction uses compact-2026-01-12 and ignores unsupported models to avoid 400s.
_ANTHROPIC_COMPACTION_PREFIXES = _ANTHROPIC_5_PREFIXES + (
"claude-opus-4-7",
"claude-opus-4-6",
@@ -654,13 +657,13 @@ _ANTHROPIC_COMPACTION_PREFIXES = _ANTHROPIC_5_PREFIXES + (
)
_ANTHROPIC_COMPACTION_BETA = "compact-2026-01-12"
_ANTHROPIC_COMPACTION_TYPE = "compact_20260112"
-# The threshold must be >= 50K tokens; lower 400s. Clamp on the way out so a UI slider cannot underflow.
+# thresholds below 50K tokens return an upstream 400.
_ANTHROPIC_COMPACTION_MIN = 50_000
+# compaction above this is slow and costly on 1M-token windows; Anthropic defaults to 150K.
+_SERVER_COMPACTION_MAX = 200_000
-# Anthropic fast-mode beta, Opus 5 / Opus 4.8 only: Opus 4.7 400s on `speed`; Opus 4.6 accepts it but runs at standard
-# speed and reports `usage.speed: "standard"`, so exposing the toggle there promises a speed-up that never happens.
-# Sonnet 5 never had it. Mutually exclusive with the Priority service tier.
+# Anthropic fast mode is limited to Opus 5/4.8; Opus 4.7 rejects speed, 4.6 reports standard, and Priority conflicts.
_ANTHROPIC_FAST_MODE_BETA = "fast-mode-2026-02-01"
_ANTHROPIC_FAST_MODE_PREFIXES = (
"claude-opus-5",
@@ -672,24 +675,27 @@ def _anthropic_supports_compaction(model: str) -> bool:
return model.startswith(_ANTHROPIC_COMPACTION_PREFIXES)
+def compacts_server_side(
+ provider_type: Optional[str], base_url: Optional[str], api_type: Optional[str], model: str
+) -> bool:
+ if provider_type == "anthropic":
+ return _anthropic_supports_compaction(model)
+ return (provider_type == "openai" or api_type == "responses") and _is_openai_family_cloud(
+ base_url
+ )
+
+
def _anthropic_supports_fast_mode(model: str) -> bool:
- # Require a family boundary ("" or "-") after the prefix so IDs like "claude-opus-4-70" / "claude-opus-4-7b" do
- # not match.
+ # require a family boundary so IDs such as claude-opus-4-70 do not match.
return any(model == p or model.startswith(f"{p}-") for p in _ANTHROPIC_FAST_MODE_PREFIXES)
-# Cap on ``cited_text`` forwarded in document_citations tool_events; bounds SSE bytes on multi-KB cited spans (the
-# frontend trims to 240 chars anyway).
+# cap cited_text to bound SSE size; the frontend trims it to 240 characters.
_CITED_TEXT_MAX_LEN = 512
def _anthropic_citation_key(citation: dict[str, Any]) -> tuple:
- """Stable dedup key for an Anthropic ``citations_delta.citation``. Anchor fields vary per type
- (char_location, page_location, content_block_location, search_result_location); both start
- AND exclusive end indices are in the key so same-start / different-end pairs stay distinct.
- search_result_location keys on ``search_result_index`` + ``source`` instead of document_index
- so distinct results with the same source do not collapse. Unknown shapes fall back to a
- stringified copy (more entries, never collisions)."""
+ """build a stable Anthropic citation key that preserves range ends and distinct search results."""
ctype = citation.get("type")
doc = citation.get("document_index")
title = citation.get("document_title") or ""
@@ -1483,6 +1489,10 @@ class ExternalProviderClient:
# Generous per-byte read timeout: reasoning models pause tens of seconds between bytes, but a dead upstream
# must eventually error, not hang forever.
self._stream_timeout = httpx.Timeout(timeout, connect = 10.0, read = 300.0)
+ # Some OpenAI/Azure deployments expose /responses but reject its optional context_management field. The
+ # client lives for the whole Studio tool loop, so remember that capability result instead of paying for the
+ # same guaranteed 400 on every provider turn.
+ self._responses_compaction_rejected = False
def _auth_headers(self) -> dict[str, str]:
"""Build authentication headers using the provider's registry config."""
@@ -1567,6 +1577,7 @@ class ExternalProviderClient:
stream: bool = True,
preserve_thinking: Optional[bool] = None,
thread_id: Optional[str] = None,
+ compaction_fallback: Optional[CompactionFallback] = None,
) -> AsyncGenerator[str, None]:
"""Yield OpenAI-format SSE lines from the external provider. OpenAI-compatible providers
forward lines verbatim; for Anthropic the native Messages API SSE is translated.
@@ -1665,6 +1676,7 @@ class ExternalProviderClient:
tool_choice,
response_format,
stream = stream if self.provider_type == "custom" else True,
+ compaction_fallback = compaction_fallback,
):
yield line
return
@@ -2461,14 +2473,12 @@ class ExternalProviderClient:
fast_mode: Optional[bool] = None,
tools: Optional[list[dict[str, Any]]] = None,
) -> AsyncGenerator[str, None]:
- """Call the Anthropic Messages API and translate its SSE to OpenAI format:
- content_block_delta -> chunk with delta.content, message_delta -> chunk with
- finish_reason, message_stop -> data: [DONE], all others skipped."""
+ """call Anthropic Messages and translate its SSE into OpenAI stream events."""
import json as _json
- # Extract system prompt; translate image_url parts to Anthropic format
system: Optional[str] = None
filtered: list[dict[str, Any]] = []
+ compaction_replayed = False
for msg in messages:
if msg.get("role") == "system":
content = msg.get("content", "")
@@ -2483,7 +2493,7 @@ class ExternalProviderClient:
extra = msg.get("extra_content") or {}
native_content = (extra.get("anthropic") or {}).get("content")
if msg.get("role") == "assistant" and isinstance(native_content, list):
- # Replay the signed native blocks, not the loop's <think>-marked display text; kept calls follow.
+ # replay signed native blocks because display text has synthetic <think> markers.
content = []
# OpenAI role="tool" with list content -> Anthropic native tool_result block on a user message.
# Translating only in the string-content branch below would forward the list-content form as an invalid
@@ -2539,32 +2549,45 @@ class ExternalProviderClient:
filtered.append({"role": "user", "content": [result_block]})
continue
if isinstance(content, list):
- # Translate OpenAI multimodal parts -> Anthropic native shapes: `image_url` -> `{type:"image",
- # source:...}`, and `input_document` -> `{type:"document", source:...}` (an Unsloth extension
- # mirroring Anthropic's document block, which supports PDFs as base64 or URL).
+ # preserve Unsloth input_document support when translating to Anthropic blocks.
anthropic_parts: list[dict[str, Any]] = (
[
block
for block in native_content
- if block.get("type") != "text"
- or _anthropic_text_is_sendable(block.get("text"))
+ if (
+ block.get("type") != "text"
+ or _anthropic_text_is_sendable(block.get("text"))
+ )
+ and (
+ block.get("type") != "compaction"
+ or _anthropic_supports_compaction(model)
+ )
]
if msg.get("role") == "assistant" and isinstance(native_content, list)
else []
)
+ if any(part.get("type") == "compaction" for part in anthropic_parts):
+ compaction_replayed = True
for part in content:
if part.get("type") == "text" and _anthropic_text_is_sendable(part.get("text")):
anthropic_parts.append({"type": "text", "text": part["text"]})
elif part.get("type") == "compaction":
- # Round-trip a prior turn's compaction block back onto this assistant message so Anthropic
- # skips re-compaction.
+ # replay compaction here to avoid compacting history twice.
summary = part.get("content") or ""
- if isinstance(summary, str) and summary:
- anthropic_parts.append({"type": "compaction", "content": summary})
+ if (
+ isinstance(summary, str)
+ and summary
+ and _anthropic_supports_compaction(model)
+ ):
+ compaction = {"type": "compaction", "content": summary}
+ encrypted = part.get("encrypted_content")
+ if isinstance(encrypted, str) and encrypted:
+ compaction["encrypted_content"] = encrypted
+ anthropic_parts.append(compaction)
+ compaction_replayed = True
elif part.get("type") == "image_url":
url = part.get("image_url", {}).get("url", "")
if url.startswith("data:"):
- # data:image/png;base64,<DATA> -> split header and data
header, _, b64data = url.partition(",")
media_type = header.split(";")[0].replace("data:", "") or "image/jpeg"
anthropic_parts.append(
@@ -2997,22 +3020,20 @@ class ExternalProviderClient:
}
)
body["tools"] = anthropic_tools
- # Reuse the thread's prior container so filesystem state persists. Stale ids 4xx and clear via
- # container_invalidated.
+ # reuse the prior container for filesystem state; stale IDs emit container_invalidated.
if anthropic_code_exec_container_id:
body["container"] = anthropic_code_exec_container_id
- # Server-side compaction (beta `compact-2026-01-12`). Clamps below-min thresholds to 50K so the request does
- # not 400.
+ # clamp Anthropic compaction thresholds to the supported range to avoid upstream 400s.
compaction_active = (
compaction_threshold is not None
and compaction_threshold > 0
and _anthropic_supports_compaction(model)
)
if compaction_active and compaction_threshold is not None:
- trigger_value = max(
- int(compaction_threshold),
- _ANTHROPIC_COMPACTION_MIN,
+ trigger_value = min(
+ max(int(compaction_threshold), _ANTHROPIC_COMPACTION_MIN),
+ _SERVER_COMPACTION_MAX,
)
body["context_management"] = {
"edits": [
@@ -3026,8 +3047,7 @@ class ExternalProviderClient:
]
}
- # fast_mode is Opus 5 / 4.8 only; silently drop elsewhere. Incompatible with the Priority service_tier (the
- # frontend gate prevents both at once; the backend lets Anthropic 400 if combined).
+ # fast mode is limited to Opus 5/4.8 and conflicts with the Priority service tier.
fast_mode_active = bool(fast_mode) and _anthropic_supports_fast_mode(model)
if fast_mode_active:
body["speed"] = "fast"
@@ -3065,14 +3085,16 @@ class ExternalProviderClient:
logger.info("Proxying Anthropic Messages API to %s (model=%s)", url, model)
request_headers = self._auth_headers()
- # Merge new beta flags onto whatever the registry contributed.
+ # preserve registry beta flags when adding request-specific flags.
existing_beta = request_headers.get("anthropic-beta", "").strip()
beta_parts = (
[p.strip() for p in existing_beta.split(",") if p.strip()] if existing_beta else []
)
if code_execution_enabled and _ANTHROPIC_CODE_EXECUTION_BETA not in beta_parts:
beta_parts.append(_ANTHROPIC_CODE_EXECUTION_BETA)
- if compaction_active and _ANTHROPIC_COMPACTION_BETA not in beta_parts:
+ if (
+ compaction_active or compaction_replayed
+ ) and _ANTHROPIC_COMPACTION_BETA not in beta_parts:
beta_parts.append(_ANTHROPIC_COMPACTION_BETA)
if fast_mode_active and _ANTHROPIC_FAST_MODE_BETA not in beta_parts:
beta_parts.append(_ANTHROPIC_FAST_MODE_BETA)
@@ -3439,6 +3461,9 @@ class ExternalProviderClient:
current_compaction = {
"content": seed if isinstance(seed, str) else "",
}
+ encrypted = content_block.get("encrypted_content")
+ if isinstance(encrypted, str) and encrypted:
+ current_compaction["encrypted_content"] = encrypted
elif event_type == "content_block_delta":
delta = event.get("delta", {})
@@ -3464,11 +3489,17 @@ class ExternalProviderClient:
elif delta_type == "citations_delta":
replay.setdefault("citations", []).append(delta["citation"])
elif delta_type == "compaction_delta":
+ content = delta.get("content")
+ if isinstance(content, str):
+ prior = replay.get("content")
+ replay["content"] = (
+ prior if isinstance(prior, str) else ""
+ ) + content
replay.update(
{
key: value
for key, value in delta.items()
- if key != "type"
+ if key not in ("type", "content")
}
)
if delta_type == "thinking_delta":
@@ -3488,19 +3519,22 @@ class ExternalProviderClient:
if text:
current_compaction["content"] += text
else:
- # First text after a thinking block closes the <think> tag opened above. Anthropic
- # emits a content_block_stop between blocks, but closing on the text_delta
- # transition is more forgiving if events arrive out of order.
+ # close thinking on text_delta to tolerate out-of-order events.
if thinking_open:
yield _content_chunk("</think>")
thinking_open = False
if text:
yield _content_chunk(text)
- # web_search citations: web_search_tool_result. User-doc citations:
- # citations_delta below.
+ elif (
+ delta_type == "compaction_delta" and current_compaction is not None
+ ):
+ summary = delta.get("content")
+ if isinstance(summary, str):
+ current_compaction["content"] += summary
+ encrypted = delta.get("encrypted_content")
+ if isinstance(encrypted, str) and encrypted:
+ current_compaction["encrypted_content"] = encrypted
elif delta_type == "citations_delta":
- # One citation per event; collapse onto a numbered footnote list and inject [N]
- # inline.
cit = delta.get("citation")
if isinstance(cit, dict):
key = _anthropic_citation_key(cit)
@@ -3619,15 +3653,22 @@ class ExternalProviderClient:
)
current_code_exec_use = None
elif current_compaction is not None:
- # End of a compaction block: emit a synthetic tool_event so the chat adapter persists
- # it onto the assistant message for next-turn round-trip.
+ # Anthropic can fail compaction when tools are defined and returns content:null. That
+ # block is a no-op even when it carries encrypted state: replaying it would discard
+ # the live history. OpenAI's encrypted-only item uses a different translator below.
compaction_blocks_seen += 1
- yield _emit_tool_event(
- {
- "type": "compaction_block",
- "content": current_compaction["content"],
- }
- )
+ summary = current_compaction.get("content")
+ if isinstance(summary, str) and summary:
+ yield _emit_tool_event(
+ {
+ "type": "compaction_block",
+ **current_compaction,
+ }
+ )
+ else:
+ # Do not let message_delta replay the failed native block through
+ # extra_content either; the rest of this turn still has to follow full history.
+ replay_blocks.pop(block_index, None)
current_compaction = None
elif current_code_exec_result is not None:
# End of a code-execution result block -- format the inner result into the text
@@ -5477,6 +5518,7 @@ class ExternalProviderClient:
tool_choice: Optional[Any] = None,
response_format: Optional[dict[str, Any]] = None,
stream: bool = True,
+ compaction_fallback: Optional[CompactionFallback] = None,
) -> AsyncGenerator[str, None]:
"""Call OpenAI's /v1/responses endpoint and translate its SSE stream back into OpenAI Chat
Completions chunk format. The Responses API uses a different request shape (``input`` not
@@ -5485,6 +5527,21 @@ class ExternalProviderClient:
/ ``top_k`` are not part of the Responses contract and are dropped here."""
import json as _json
+ # A deployment that rejected context_management once will reject it on every later Studio-tool turn too.
+ # Apply the same local fitting fallback up front and suppress the unsupported field for the rest of this
+ # client's run, rather than deliberately incurring another 400 before each continuation.
+ if (
+ self._responses_compaction_rejected
+ and compaction_threshold is not None
+ and compaction_threshold > 0
+ ):
+ if compaction_fallback is not None:
+ messages, max_tokens, truncation_line = await compaction_fallback(messages)
+ if truncation_line:
+ yield truncation_line
+ compaction_threshold = None
+ compaction_fallback = None
+
is_openai_cloud = _is_openai_family_cloud(self.base_url)
_responses_tool_choice_none = (
isinstance(tool_choice, str) and tool_choice.strip().lower() == "none"
@@ -5529,12 +5586,31 @@ class ExternalProviderClient:
instructions_parts.append(part["text"])
continue
- # Responses uses item-shape history: each assistant call is a `function_call` item and each role="tool"
- # follow-up a `function_call_output` keyed by call_id (the Chat Completions shape 400s).
+ if role == "assistant" and is_openai_cloud:
+ # A saved turn carries its compaction item as a content part, the tool loop on extra_content.
+ extra = msg.get("extra_content")
+ replayed = (
+ [extra.get("openai_responses_compaction")] if isinstance(extra, dict) else []
+ )
+ if isinstance(content, list):
+ replayed += [
+ part.get("encrypted_content")
+ for part in content
+ if part.get("type") == "compaction"
+ ]
+ replayed = [item for item in replayed if isinstance(item, str) and item]
+ if replayed:
+ # The item carries everything before it, and resending that would compact it again.
+ input_items = [{"type": "compaction", "encrypted_content": replayed[-1]}]
+ openai_replay_items = []
+ previous_response_id = None
+ if not content and not msg.get("tool_calls"):
+ continue
+
+ # Responses requires function_call items paired with function_call_output by call_id.
if role == "tool":
_call_id = msg.get("tool_call_id") or ""
- # If the matching assistant `function_call` was a server-side builtin we already dropped, drop the
- # follow-up too to avoid an orphan `function_call_output`.
+ # drop outputs for omitted builtins to avoid orphan function_call_output items.
if _call_id and _call_id in skipped_server_builtin_call_ids:
continue
if isinstance(content, list):
@@ -5830,9 +5906,7 @@ class ExternalProviderClient:
}
}
- # Opt into 24h prompt-cache retention (free, vs the default ~5-10 min). Gated on the cloud host because ollama
- # / llama.cpp / "custom" presets reach this path and 400 on the unknown field, and on the model because most
- # cloud families reject the value itself.
+ # 24h retention requires an OpenAI cloud model that accepts prompt_cache_retention.
if (
is_openai_cloud
and enable_prompt_caching is not False
@@ -5840,16 +5914,16 @@ class ExternalProviderClient:
):
body["prompt_cache_retention"] = "24h"
- # Server-side context compaction (OpenAI cloud only).
+ # server-side context compaction is available only on OpenAI cloud.
if is_openai_cloud and compaction_threshold is not None and compaction_threshold > 0:
body["context_management"] = [
{
"type": "compaction",
- "compact_threshold": int(compaction_threshold),
+ "compact_threshold": min(int(compaction_threshold), _SERVER_COMPACTION_MAX),
}
]
- # Map enabled_tools onto Responses-API server tools (cloud only; local OAI-compat backends 400 on these).
+ # only OpenAI cloud accepts Responses API server tools.
code_execution_enabled_openai = bool(
enabled_tools and "code_execution" in enabled_tools and is_openai_cloud
)
@@ -5860,7 +5934,7 @@ class ExternalProviderClient:
def _openai_image_generation_tool() -> dict[str, Any]:
tool: dict[str, Any] = {"type": "image_generation"}
if image_generation_has_reference:
- # Force edit mode so the prior call id is used as context.
+ # force edit mode so the prior call ID remains available as context.
tool["action"] = "edit"
return tool
@@ -6030,6 +6104,45 @@ class ExternalProviderClient:
and 400 <= response.status_code < 500
and _is_openai_container_expired_error(error_text)
)
+ if (
+ response.status_code == 400
+ and (
+ "compact_threshold" in error_text
+ or "context_management" in error_text
+ )
+ and body.pop("context_management", None) is not None
+ ):
+ self._responses_compaction_rejected = True
+ if compaction_fallback is not None:
+ (
+ fallback_messages,
+ fallback_max_tokens,
+ truncation_line,
+ ) = await compaction_fallback(messages)
+ await response.aclose()
+ if truncation_line:
+ yield truncation_line
+ async for fallback_line in self._stream_openai_responses(
+ messages = fallback_messages,
+ model = model,
+ temperature = temperature,
+ top_p = top_p,
+ max_tokens = fallback_max_tokens,
+ enable_thinking = enable_thinking,
+ reasoning_effort = reasoning_effort,
+ enabled_tools = enabled_tools,
+ enable_prompt_caching = enable_prompt_caching,
+ openai_code_exec_container_id = openai_code_exec_container_id,
+ compaction_threshold = None,
+ compaction_fallback = None,
+ tools = tools,
+ tool_choice = tool_choice,
+ response_format = response_format,
+ stream = stream,
+ ):
+ yield fallback_line
+ return
+ continue
if expired_container_4xx and not retried:
if stream:
yield (
@@ -6068,6 +6181,7 @@ class ExternalProviderClient:
tool_calls: list[dict[str, Any]] = []
reasoning_replay_items: list[dict[str, Any]] = []
url_citations: list[dict[str, Any]] = []
+ compaction_part: dict[str, Any] | None = None
for item in response_payload.get("output") or []:
if not isinstance(item, dict):
continue
@@ -6085,6 +6199,13 @@ class ExternalProviderClient:
reasoning_item = _sanitize_openai_reasoning_replay_item(item)
if reasoning_item:
reasoning_replay_items.append(reasoning_item)
+ elif item.get("type") == "compaction":
+ encrypted = item.get("encrypted_content")
+ if isinstance(encrypted, str) and encrypted:
+ compaction_part = {
+ "type": "compaction",
+ "encrypted_content": encrypted,
+ }
elif item.get("type") == "message":
content = item.get("content") or []
if isinstance(content, str):
@@ -6138,6 +6259,10 @@ class ExternalProviderClient:
"role": "assistant",
"content": visible_text or None,
}
+ if compaction_part is not None:
+ message["content"] = [compaction_part]
+ if visible_text:
+ message["content"].append({"type": "text", "text": visible_text})
if refusal_parts:
message["refusal"] = "".join(refusal_parts)
if tool_calls:
@@ -6602,12 +6727,19 @@ class ExternalProviderClient:
reasoning_open = True
yield _chunk_with_text(summary_text)
reasoning_emitted = True
+ elif item.get("type") == "compaction":
+ encrypted = item.get("encrypted_content")
+ if isinstance(encrypted, str) and encrypted:
+ yield _emit_tool_event(
+ {
+ "type": "compaction_block",
+ "encrypted_content": encrypted,
+ }
+ )
elif item.get("type") == "web_search_call":
- # done carries the action; emit tool_start + tool_end here. Citations are
- # aggregated and the last call's result is overwritten at response.completed.
+ # response.completed replaces this result with citations.
item_id = item.get("id", "") or (f"ws_{len(web_search_calls)}")
- # Overlay, do not replace: a partial done event would drop what the added event
- # carried.
+ # merge partial done events so fields from added events survive.
arguments = {
**web_search_calls.get(item_id, {}),
**_extract_web_search_action(item),
@@ -7744,7 +7876,13 @@ def _build_usage_chunk(
uncached_input = last_usage.get("input_tokens") or 0
cache_creation = last_usage.get("cache_creation_input_tokens") or 0
cache_read = last_usage.get("cache_read_input_tokens") or 0
- prompt_tokens = uncached_input + cache_creation + cache_read
+ # Anthropic reports provider-compaction work as separate usage.iterations entries and excludes
+ # it from the top-level input/output counts. Fold those billed iterations into the standard
+ # OpenAI-shaped totals so monitors and cost consumers do not undercount the turn.
+ compaction_input = last_usage.get("compaction_input_tokens") or 0
+ compaction_output = last_usage.get("compaction_output_tokens") or 0
+ prompt_tokens = uncached_input + cache_creation + cache_read + compaction_input
+ completion_tokens += compaction_output
if not (prompt_tokens or completion_tokens):
return None
usage_block: dict[str, Any] = {
@@ -7755,6 +7893,9 @@ def _build_usage_chunk(
"cache_creation_input_tokens": cache_creation,
"cache_read_input_tokens": cache_read,
}
+ if compaction_input or compaction_output:
+ usage_block["compaction_input_tokens"] = compaction_input
+ usage_block["compaction_output_tokens"] = compaction_output
# Forward the 5m/1h cache-write breakdown so cost calc applies the 2x 1h premium instead of defaulting to 5m
# on chat-style.
cc_breakdown = last_usage.get("cache_creation")
diff --git a/studio/backend/core/inference/external_tool_transport.py b/studio/backend/core/inference/external_tool_transport.py
index 548fcd9886f..f1c08d33701 100644
--- a/studio/backend/core/inference/external_tool_transport.py
+++ b/studio/backend/core/inference/external_tool_transport.py
@@ -17,7 +17,7 @@ import asyncio
import contextlib
import threading
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Awaitable, Callable
from typing import Any
from core.inference.external_provider import ExternalProviderClient
@@ -56,11 +56,17 @@ class OAICompatTransport:
*,
model: str,
continue_final_message: bool | None = None,
+ message_fitter: Callable[
+ [list[dict[str, Any]]],
+ Awaitable[tuple[list[dict[str, Any]], int | None, str | None]],
+ ]
+ | None = None,
**request_kwargs: Any,
) -> None:
self._client = client
self._model = model
self._continue_final_message = continue_final_message
+ self._message_fitter = message_fitter
self._request_kwargs = request_kwargs
# Anthropic can leave a hosted call pending beside a client call; its continuation accepts only tool results.
self.tool_result_only_continuation = client.provider_type == "anthropic"
@@ -104,25 +110,45 @@ class OAICompatTransport:
messages = normalized
elif self._initial_message_count is None:
self._initial_message_count = len(messages)
+ return self._cancellable(
+ self._stream_provider(messages, tools, tool_choice),
+ cancel_event,
+ )
+
+ async def _stream_provider(
+ self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None, tool_choice: Any
+ ) -> AsyncIterator[str]:
+ request_kwargs = dict(self._request_kwargs)
+ if self._message_fitter is not None:
+ messages, max_tokens, truncation_line = await self._message_fitter(messages)
+ request_kwargs["max_tokens"] = max_tokens
+ if truncation_line:
+ yield truncation_line
+
# "Resume the trailing assistant turn", so it is only ever true of the first request. Once a tool runs the
# conversation ends with a role="tool" result (or a role="user" no-op note), and vLLM / llama.cpp would splice
# the generation prompt off the end of *that* message: the model continues the tool output instead of answering
- # it, or the chat template raises and the server 400s. Re-read the tail every turn rather than replaying the
- # flag the transport was constructed with.
+ # it, or the chat template raises and the server 400s. Re-read the fitted tail every turn rather than replaying
+ # the flag the transport was constructed with.
continue_final_message = bool(self._continue_final_message) and bool(
messages and isinstance(messages[-1], dict) and messages[-1].get("role") == "assistant"
)
- return self._cancellable(
- self._client.stream_chat_completion(
- messages = messages,
- model = self._model,
- tools = tools,
- tool_choice = tool_choice,
- continue_final_message = continue_final_message,
- **self._request_kwargs,
- ),
- cancel_event,
+ upstream = self._client.stream_chat_completion(
+ messages = messages,
+ model = self._model,
+ tools = tools,
+ tool_choice = tool_choice,
+ continue_final_message = continue_final_message,
+ **request_kwargs,
)
+ try:
+ async for line in upstream:
+ yield line
+ finally:
+ aclose = getattr(upstream, "aclose", None)
+ if aclose is not None:
+ with contextlib.suppress(RuntimeError, GeneratorExit, StopAsyncIteration):
+ await aclose()
@staticmethod
async def _cancellable(
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index d7432ec4c1e..00232f86c32 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -1937,6 +1937,11 @@ def _sticky_compaction_state(
# Only a SUCCEEDED fit describes a boundary, but an explicit failure still rules.
if not truncation.get("fits"):
return 0, False
+ # A provider-generated summary boundary is display metadata, not a local-fit epoch. On a provider/model
+ # switch the opaque summary is deliberately withheld, so replaying its boundary here would discard the
+ # original turns without retaining their summary.
+ if truncation.get("summarized") is True:
+ return 0, False
# A boundary is valid only under the fit that will consume it, and the two
# directions fail differently.
#
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.py
index 81ede733b6a..0a005dcb1c9 100644
--- a/studio/backend/core/inference/studio_tool_loop.py
+++ b/studio/backend/core/inference/studio_tool_loop.py
@@ -557,6 +557,46 @@ class _Turn:
# Results from tools the PROVIDER ran this turn, keyed by call id so a repeated end event cannot record the same
# result twice
hosted_results: dict[str, dict[str, Any]] = field(default_factory = dict)
+ provider_compaction: dict[str, Any] | None = None
+
+ def compaction_replay_message(self) -> dict[str, Any] | None:
+ """Build one replay turn and remove Anthropic's native block from later metadata."""
+ replay = self.provider_compaction
+ extra = self.reasoning_extra
+ if replay is None or not isinstance(extra, dict):
+ return None if replay is None else {"role": "assistant", "content": [replay]}
+ anthropic = extra.get("anthropic")
+ native_content = anthropic.get("content") if isinstance(anthropic, dict) else None
+ if not isinstance(native_content, list):
+ return {"role": "assistant", "content": [replay]}
+ native_compactions = [
+ block
+ for block in native_content
+ if isinstance(block, dict) and block.get("type") == "compaction"
+ ]
+ if not native_compactions:
+ return {"role": "assistant", "content": [replay]}
+ self.reasoning_extra = {
+ **extra,
+ "anthropic": {
+ **anthropic,
+ "content": [
+ block
+ for block in native_content
+ if not (isinstance(block, dict) and block.get("type") == "compaction")
+ ],
+ },
+ }
+ return {
+ "role": "assistant",
+ "content": "",
+ "extra_content": {
+ "anthropic": {
+ **anthropic,
+ "content": [dict(native_compactions[-1])],
+ }
+ },
+ }
def note_hosted_tool_event(self, event: Any) -> None:
"""Record a provider-side tool call carried on ``_toolEvent``. These reach the client as
@@ -568,10 +608,21 @@ class _Turn:
unlabelled."""
if not isinstance(event, dict):
return
+ kind = event.get("type")
+ if kind == "compaction_block":
+ encrypted = event.get("encrypted_content")
+ content = event.get("content")
+ if isinstance(encrypted, str) and encrypted:
+ self.provider_compaction = {
+ "type": "compaction",
+ "encrypted_content": encrypted,
+ }
+ elif isinstance(content, str) and content:
+ self.provider_compaction = {"type": "compaction", "content": content}
+ return
call_id = event.get("tool_call_id")
if not isinstance(call_id, str) or not call_id:
return
- kind = event.get("type")
if kind not in ("tool_start", "tool_end"):
return
@@ -1189,6 +1240,34 @@ def _replayed_call_ids(conversation: list[dict[str, Any]]) -> set[str]:
return taken
+def _openai_compaction_item(event: Any) -> str | None:
+ if not isinstance(event, dict) or event.get("type") != "compaction_block":
+ return None
+ encrypted = event.get("encrypted_content")
+ return encrypted if isinstance(encrypted, str) and encrypted else None
+
+
+def _with_openai_compaction(
+ conversation: list[dict[str, Any]], compaction: tuple[list[dict[str, Any]], str] | None
+) -> list[dict[str, Any]]:
+ """Later rounds replay an OpenAI Responses compaction item after the messages it covers, or the provider compacts
+ the same history again."""
+ if compaction is None:
+ return conversation
+ sent, encrypted = compaction
+ # A continuation merges into the last message sent rather than appending, and that message is no longer covered.
+ covered = next(
+ (index for index, message in enumerate(sent) if conversation[index] is not message),
+ len(sent),
+ )
+ carrier = {
+ "role": "assistant",
+ "content": "",
+ "extra_content": {"openai_responses_compaction": encrypted},
+ }
+ return [*conversation[:covered], carrier, *conversation[covered:]]
+
+
def _append_user_turn(conversation: list[dict[str, Any]], content: str) -> None:
"""Append a user turn, merging into a trailing one so roles keep alternating. A turn whose only
calls were no-ops appends no assistant message, so a bare append would leave two user turns
@@ -1253,6 +1332,8 @@ async def stream_with_studio_tools(
) -> AsyncIterator[str]:
"""Stream a provider, execute requested Unsloth tools, continue to a final answer."""
conversation = [dict(message) for message in run.messages]
+ openai_compaction: tuple[list[dict[str, Any]], str] | None = None
+ resumes_partial = run.continue_final_message
# The image parts this run appends, so its cap never counts a caller's own
# attachments. Run-scoped, not turn-scoped: the cap is across the whole loop,
# and seeded with what promotion already put in the conversation.
@@ -1397,8 +1478,9 @@ async def stream_with_studio_tools(
if executed_any and turn_tool_choice not in ("auto", "none"):
turn_tool_choice = "auto"
+ sent_messages = list(conversation)
generator = transport.stream(
- messages = conversation,
+ messages = _with_openai_compaction(conversation, openai_compaction),
tools = active_tools if tools_available else None,
tool_choice = turn_tool_choice,
cancel_event = cancel_event,
@@ -1457,6 +1539,9 @@ async def stream_with_studio_tools(
if isinstance(extra, dict):
turn.reasoning_extra = extra
turn.note_hosted_tool_event(payload.get("_toolEvent"))
+ compaction = _openai_compaction_item(payload.get("_toolEvent"))
+ if compaction:
+ openai_compaction = (sent_messages, compaction)
if isinstance(choice.get("finish_reason"), str):
turn.finish_reason = choice["finish_reason"]
# Only a live healer can still promote a call this turn; once dormant, the wire already carries the
@@ -1567,6 +1652,21 @@ async def stream_with_studio_tools(
if policy.on_provider_turn_end is not None:
policy.on_provider_turn_end()
+ if turn.provider_compaction is not None:
+ compaction_message = turn.compaction_replay_message()
+ assert compaction_message is not None
+ system_messages = [
+ message
+ for message in conversation
+ if isinstance(message, dict) and message.get("role") == "system"
+ ]
+ conversation[:] = [
+ *system_messages,
+ compaction_message,
+ ]
+ # The partial this run resumed is inside the compaction now, and merging over the item would discard it.
+ resumes_partial = False
+
# Both of these mean the turn ended before the model finished saying what it wanted: "length" hit the token
# ceiling, "content_filter" had the output cut by the provider's own filter. Either way a call collected so
# far may be half-written, so it is described rather than run. "stop" is not in this set: llama.cpp and vLLM
@@ -1665,7 +1765,7 @@ async def stream_with_studio_tools(
stalled_message,
# A resumed partial is the same turn as what the model just added, so merge rather than
# append: appending puts a turn boundary mid-sentence.
- continue_final_message = run.continue_final_message,
+ continue_final_message = resumes_partial,
)
_append_user_turn(conversation, reprompt_to_act_message(tool_hint))
continue
@@ -2015,7 +2115,7 @@ async def stream_with_studio_tools(
append_assistant_turn(
conversation,
assistant_message,
- continue_final_message = run.continue_final_message,
+ continue_final_message = resumes_partial,
)
conversation.extend(tool_messages)
# Deferred to after the results so a no-op never splits a call from them, and merged into a trailing user turn
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index ce5fdf58790..f7bd6d3d10b 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -2243,19 +2243,17 @@ class ImageGenerationCallContentPart(BaseModel):
class CompactionContentPart(BaseModel):
- """Anthropic server-side compaction state, round-tripped on the next turn.
-
- Anthropic returns a ``compaction`` block on the assistant message; the next
- request must forward it back so Anthropic reuses the compaction state instead
- of re-summarising. See ``external_provider._stream_anthropic`` and
- https://platform.claude.com/docs/en/build-with-claude/compaction
- """
+ """round-trip Anthropic summaries and opaque OpenAI Responses compaction state."""
type: Literal["compaction"]
- content: str = Field(
- ...,
+ content: Optional[str] = Field(
+ None,
description = "Anthropic-produced summary of the compacted-away conversation prefix.",
)
+ encrypted_content: Optional[str] = Field(
+ None,
+ description = "OpenAI Responses compaction item, opaque.",
+ )
class InputAudio(BaseModel):
@@ -2753,7 +2751,8 @@ class ChatCompletionRequest(BaseModel):
"keeping the first and recent turns. 'truncate_oldest' provides a rolling "
"window for plain and Unsloth-tool chats by dropping complete oldest turns. "
"Both truncation policies preserve system messages and tool-call groups. "
- "MLX models honor 'truncate_oldest' only."
+ "MLX models honor 'truncate_oldest' only, as do external providers "
+ "given a compaction_threshold."
),
)
context_policy: Optional[Literal["checkpoint", "rolling"]] = Field(
@@ -2922,14 +2921,23 @@ class ChatCompletionRequest(BaseModel):
" - OpenAI cloud (api.openai.com) and Azure OpenAI Foundry "
"(*.openai.azure.com, *.services.ai.azure.com): attaches "
"`context_management:[{type:'compaction', compact_threshold:N}]` "
- "to /v1/responses. Effective floor is around 200k (OpenAI's "
- "canonical example); values below it surface "
- "`compact_threshold is not enabled` 400s upstream.\n"
- "Schema floor stays at ge=1 (any positive int) so the field is a "
- "silent no-op on non-cloud OpenAI-compatible bases (ollama / "
- "llama.cpp / vLLM) and every non-compaction-capable provider "
- "rather than returning 422 at request validation time. Per-"
- "provider floors are enforced in the corresponding stream helpers."
+ "to /v1/responses. A deployment that answers `compact_threshold "
+ "is not enabled` is retried without it.\n"
+ "Both cap the trigger at 200k.\n"
+ "Every other provider and model ignores it unless context_overflow "
+ "is truncate_oldest, in which case Unsloth drops the oldest turns "
+ "so the prompt and the reply fit within it before forwarding. "
+ "Per-provider floors are enforced in the corresponding stream helpers."
+ ),
+ )
+ context_window: Optional[int] = Field(
+ None,
+ ge = 1,
+ description = (
+ "[x-unsloth] The external model's context window, in tokens. When "
+ "Unsloth drops the oldest turns for a compaction_threshold, the prompt "
+ "also leaves room for max_tokens within it, and max_tokens is lowered "
+ "if it would leave the prompt less than half of the window."
),
)
openai_code_exec_container_id: Optional[str] = Field(
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index a29f12b79bf..a9fa9b58b0e 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3963,9 +3963,11 @@ from core.inference.providers import (
from core.inference.external_provider import (
ExternalProviderClient,
_is_openai_family_cloud,
+ compacts_server_side,
)
from core.inference.external_tool_transport import OAICompatTransport
from core.inference.sse_control_frames import (
+ _sse_payload,
is_ui_control_sse_line,
ServerToolCallStripper,
)
@@ -26829,10 +26831,7 @@ def _build_external_messages(
replay the required reasoning item.
- `image_generation_call`: Responses image reference. Forwarded for OpenAI
and custom Responses so follow-up image edits can reference prior images.
- - `compaction`: Anthropic-only synthetic part (round-trips server-side
- compaction state). Forwarded ONLY when provider_type=="anthropic";
- stripped elsewhere so the unknown part doesn't reach generic
- /chat/completions and 400 (DeepSeek, Mistral, Gemini, Kimi, OpenRouter).
+ - `compaction`: forwarded only to Anthropic, OpenAI, and custom Responses.
"""
document_provider = provider_type in _INPUT_DOCUMENT_PROVIDERS or (
provider_type == "custom" and api_type == "responses"
@@ -26841,11 +26840,7 @@ def _build_external_messages(
responses_native_parts = provider_type == "openai" or (
provider_type == "custom" and api_type == "responses"
)
- # `extra_content` carries the assistant's text-part `thoughtSignature`
- # round-trip on Gemini's native streamGenerateContent endpoint. Custom
- # Gemini OpenAI-compat gateways (LiteLLM etc.) route through
- # /chat/completions where the field is unknown and can be rejected -- gate
- # strictly on the Google-hosted Gemini base.
+ # emit `extra_content` only to endpoints that understand Gemini `thoughtSignature` metadata.
_native_gemini = False
if provider_type == "gemini" and base_url:
try:
@@ -26941,8 +26936,7 @@ def _build_external_messages(
return cleaned
def _openai_responses_part(item: Any) -> Optional[dict[str, Any]]:
- """Rebuild a forwarded OpenAI Responses assistant part (`reasoning` or
- `image_generation_call`); returns None for any other part type."""
+ """rebuild replayable OpenAI Responses assistant parts."""
if item.type == "reasoning":
reasoning: dict[str, Any] = {
"type": "reasoning",
@@ -26957,6 +26951,8 @@ def _build_external_messages(
if getattr(item, "response_id", None):
image_ref["response_id"] = item.response_id
return image_ref
+ if item.type == "compaction" and item.encrypted_content:
+ return {"type": "compaction", "encrypted_content": item.encrypted_content}
return None
result = []
@@ -27074,7 +27070,10 @@ def _build_external_messages(
# Anthropic stream helper forwards this as a native
# `compaction` block; every other provider would 400 on
# the unknown part, so gate by provider_type.
- parts.append({"type": "compaction", "content": part.content})
+ compaction = {"type": "compaction", "content": part.content}
+ if part.content and part.encrypted_content:
+ compaction["encrypted_content"] = part.encrypted_content
+ parts.append(compaction)
entry: dict[str, Any] = {"role": msg.role, "content": parts, **replay}
if msg.role == "assistant" and msg.tool_calls:
_tcs = _filter_tool_calls(msg.tool_calls)
@@ -27111,7 +27110,10 @@ def _build_external_messages(
):
preserved.append(_rp)
elif p.type == "compaction" and anthropic:
- preserved.append({"type": "compaction", "content": p.content})
+ compaction = {"type": "compaction", "content": p.content}
+ if p.content and p.encrypted_content:
+ compaction["encrypted_content"] = p.encrypted_content
+ preserved.append(compaction)
if msg.role == "assistant" and not preserved and not replay:
continue
if len(preserved) == 1 and preserved[0]["type"] == "text":
@@ -27318,7 +27320,7 @@ async def _stop_on_cancel(agen, cancel_event: threading.Event):
finally:
for task in (step, waiter):
if task is not None and not task.done():
- # Cancelling the pending read closes the upstream response inside ``agen``.
+ # cancelling the pending read closes the upstream response inside ``agen``.
task.cancel()
await asyncio.gather(task, return_exceptions = True)
try:
@@ -27327,6 +27329,111 @@ async def _stop_on_cancel(agen, cancel_event: threading.Event):
pass
+def _fit_external_context(
+ messages: list[dict],
+ payload,
+ *,
+ tools: Optional[list[dict]] = None,
+) -> tuple[list[dict], Optional[dict], Optional[int]]:
+ from core.inference.context_window import (
+ estimate_message_tokens_without_unpriced_media,
+ estimate_messages_tokens_conservative,
+ messages_without_unpriced_media,
+ prompt_budget,
+ )
+ from core.inference.llama_cpp import (
+ _boundary_metadata,
+ _compaction_fit_kwargs,
+ _fit_with_instruction_pins,
+ _keeps_compaction_boundary,
+ _records_boundary,
+ _sticky_compaction_state,
+ )
+
+ tool_tokens = _openai_llama_admission_injected_tool_tokens(tools)
+
+ def _count(fitted):
+ estimate_messages, image_parts = _openai_llama_admission_messages_for_estimate(fitted)
+ media_tokens = _openai_llama_admission_media_tokens(
+ payload,
+ message_image_parts = image_parts,
+ message_video_clips = _conversation_video_clips(fitted),
+ )
+ return (
+ estimate_messages_tokens_conservative(
+ messages_without_unpriced_media(estimate_messages)
+ )
+ + media_tokens
+ + tool_tokens
+ )
+
+ context_length = payload.compaction_threshold
+ max_tokens = _effective_max_tokens(payload)
+ window = payload.context_window
+ prompt_tokens = _count(messages)
+ if window and max_tokens:
+ # reserve the full reply cap while leaving at least half the window for the prompt.
+ margin = window // 32
+ if prompt_tokens + max_tokens + margin > window:
+ room = max(window - max_tokens, window // 2) - margin
+ max_tokens = min(max_tokens, window - room - margin)
+ # The largest context whose prompt_budget stays within room.
+ context_length = min(context_length, room + max_tokens, room * 4 // 3)
+ if prompt_tokens <= prompt_budget(context_length, max_tokens):
+ return messages, None, max_tokens
+ policy = _request_context_policy(payload)
+ ratio = _request_compaction_headroom_ratio(payload)
+ thread_id = payload.thread_id
+ # No archive to search here, so a checkpoint reset may not start and the fit stays rolling.
+ sticky, sticky_is_checkpoint = _sticky_compaction_state(
+ thread_id,
+ messages,
+ context_policy = policy,
+ can_reset = False,
+ compaction_headroom_ratio = ratio,
+ )
+ fitted, truncation = _fit_with_instruction_pins(
+ messages,
+ context_length = context_length,
+ max_tokens = max_tokens,
+ count_tokens = _count,
+ keeps_boundary = _keeps_compaction_boundary(thread_id),
+ recall_offered = False,
+ sticky_dropped = sticky,
+ sticky_is_checkpoint = sticky_is_checkpoint,
+ estimate_message = estimate_message_tokens_without_unpriced_media,
+ **_compaction_fit_kwargs(policy, ratio),
+ )
+ if truncation and _records_boundary(truncation):
+ truncation = {**truncation, **_boundary_metadata(fitted, messages, ratio)}
+ return fitted, truncation, max_tokens
+
+
+def _is_compaction_block_sse(line: str) -> bool:
+ if '"compaction_block"' not in line:
+ return False
+ event = (_sse_payload(line) or {}).get("_toolEvent")
+ return isinstance(event, dict) and event.get("type") == "compaction_block"
+
+
+def _provider_compaction_truncation(messages: list[dict]) -> dict:
+ latest_user = max(
+ (index for index, message in enumerate(messages) if message.get("role") == "user"),
+ default = 0,
+ )
+ summarized = sum(
+ 1
+ for message in messages[:latest_user]
+ if message.get("role") not in ("system", "developer")
+ )
+ return {
+ "dropped_messages": summarized,
+ "boundary_messages": summarized,
+ "fits": True,
+ "summarized": True,
+ }
+
+
async def _proxy_to_external_provider(
payload: ChatCompletionRequest,
request: Request,
@@ -28060,6 +28167,7 @@ async def _proxy_to_external_provider(
mcp_allowed = bool(payload.mcp_enabled),
)
run_studio_tool_loop = bool(external_studio_tools)
+ _external_fit_tools = external_studio_tools if run_studio_tool_loop else payload.tools
_refuse_unused_mcp_image(_mcp_image, _catalog_names(external_studio_tools))
if run_studio_tool_loop:
# Only once the catalog is known: mcp_enabled with no MCP tools enabled leaves this
@@ -28086,13 +28194,55 @@ async def _proxy_to_external_provider(
)
if _external_nudge:
chat_messages = _append_to_system_message(chat_messages, _external_nudge)
+ _provider_compacts = compacts_server_side(provider_type, base_url, api_type, model)
+ _external_truncation = None
+ _external_max_tokens = _effective_max_tokens(payload)
+ _external_context_fitter = None
+ _compaction_fallback = None
+ if payload.compaction_threshold and _rolling_context_policy(payload) is not None:
+
+ async def _external_context_fitter(messages):
+ nonlocal _external_truncation
+ fitted, truncation, fallback_max_tokens = await asyncio.to_thread(
+ _fit_external_context,
+ messages,
+ payload,
+ tools = _external_fit_tools,
+ )
+ if truncation and truncation.get("dropped_messages"):
+ _external_truncation = truncation
+ truncation_line = None
+ if (
+ truncation
+ and truncation.get("dropped_messages")
+ and not _non_stream_custom_responses
+ ):
+ truncation_line = _context_truncated_sse_chunk(
+ f"chatcmpl-{uuid.uuid4().hex}", model, truncation
+ ).rstrip("\n")
+ return fitted, fallback_max_tokens, truncation_line
+
+ if _provider_compacts and (provider_type == "openai" or api_type == "responses"):
+ _compaction_fallback = _external_context_fitter
+
+ if (
+ payload.compaction_threshold
+ and not _provider_compacts
+ and not run_studio_tool_loop
+ and _rolling_context_policy(payload) is not None
+ ):
+ chat_messages, _external_truncation, _external_max_tokens = await asyncio.to_thread(
+ _fit_external_context,
+ chat_messages,
+ payload,
+ tools = _external_fit_tools,
+ )
cancel_event = threading.Event()
cancel_keys = tuple(key for key in (payload.cancel_id, payload.session_id) if key)
async def _watch_disconnect() -> None:
- # A tool loop can sit for minutes inside execute_tool with no SSE line
- # arriving, so poll rather than waiting for the next yield to notice.
+ # tool execution may emit no SSE lines for minutes, so poll for disconnects.
while not cancel_event.is_set():
if await request.is_disconnected():
cancel_event.set()
@@ -28109,10 +28259,8 @@ async def _proxy_to_external_provider(
else payload.temperature
),
top_p = _top_p_explicit,
- # Honor max_completion_tokens when max_tokens is absent, so a
- # provider-routed request capped only by the newer field still gets
- # a limit instead of falling back to the provider default.
- max_tokens = _effective_max_tokens(payload),
+ # honor max_completion_tokens when max_tokens is absent to avoid provider defaults.
+ max_tokens = _external_max_tokens,
presence_penalty = payload.presence_penalty,
top_k = _top_k_explicit,
min_p = _min_p_explicit,
@@ -28125,6 +28273,7 @@ async def _proxy_to_external_provider(
anthropic_code_exec_container_id = payload.anthropic_code_exec_container_id,
prompt_cache_ttl = payload.prompt_cache_ttl,
compaction_threshold = payload.compaction_threshold,
+ compaction_fallback = _compaction_fallback,
fast_mode = payload.fast_mode,
response_format = _extract_response_format(payload),
thread_id = payload.thread_id,
@@ -28163,6 +28312,7 @@ async def _proxy_to_external_provider(
client,
model = model,
continue_final_message = _continue_final_message(payload),
+ message_fitter = (_external_context_fitter if not _provider_compacts else None),
enabled_tools = loop_hosted_tools or None,
stream = True,
**_provider_kwargs,
@@ -28238,9 +28388,18 @@ async def _proxy_to_external_provider(
try:
sent_done = False
stream_failed = False
+ if (
+ _external_truncation
+ and _external_truncation.get("dropped_messages")
+ and not _non_stream_custom_responses
+ ):
+ yield _context_truncated_sse_chunk(
+ f"chatcmpl-{uuid.uuid4().hex}", model, _external_truncation
+ )
+ provider_compaction_reported = False
async for line in gen:
if _is_openai_sse_done(line) and _managed_cut_short():
- # Before [DONE] reaches the monitor, which would record the reply completed.
+ # intercept [DONE] before the monitor records a cut-short reply as complete.
yield _fail_cut_short()
stream_failed = True
if managed is not None:
@@ -28248,8 +28407,7 @@ async def _proxy_to_external_provider(
monitor_event = _monitor_openai_sse_line(monitor_id, line)
if monitor_event is None:
try:
- # Only stamp a real delta stream: a stream:false response is one
- # full line, so end-to-end latency, not TTFT.
+ # stamp TTFT only for delta streams; stream:false reports total latency.
_monitor_openai_chunk(
monitor_id, json.loads(line), streaming = bool(payload.stream)
)
@@ -28271,23 +28429,30 @@ async def _proxy_to_external_provider(
yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
continue
if not _ui_events and run_studio_tool_loop:
- # Only inside the loop: on a plain proxy the calls are the caller's own.
+ # strip calls only in the loop because plain-proxy calls belong to the caller.
line = _tool_call_stripper.strip(line)
if line is None:
if _drop_keepalive.due():
yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
continue
yield f"{line}\n\n"
- # Parsed from the line itself, not from monitor_event: with the
- # monitor disabled the helper returns None for every line, and
- # trusting it would append a second [DONE] after the provider's.
+ if (
+ _provider_compacts
+ and not provider_compaction_reported
+ and _is_compaction_block_sse(line)
+ ):
+ provider_compaction_reported = True
+ yield _context_truncated_sse_chunk(
+ f"chatcmpl-{uuid.uuid4().hex}",
+ model,
+ _provider_compaction_truncation(chat_messages),
+ )
+ # inspect the line directly because a disabled monitor would duplicate [DONE].
if _is_openai_sse_done(line):
sent_done = True
if _non_stream_custom_responses:
return
- # The loop can end without opening the turn a withheld call promised, and the
- # reason removed with that call was this stream's last one. Before [DONE], where
- # the GGUF passthrough places its own synthetic finish.
+ # emit withheld terminal state before [DONE] if the loop did not open the promised turn.
_owed = _tool_call_stripper.owed_terminal_chunk()
if _owed is not None and not stream_failed:
managed_finish.see(_owed)
@@ -28391,6 +28556,13 @@ async def _proxy_to_external_provider(
error_message = (
_monitor_openai_error_message(content) if isinstance(content, dict) else None
)
+ if (
+ not error_message
+ and isinstance(content, dict)
+ and _external_truncation
+ and _external_truncation.get("dropped_messages")
+ ):
+ content["context_truncated"] = _external_truncation
retry_after_header = None
if error_message:
api_monitor.fail(monitor_id, error_message)
diff --git a/studio/backend/tests/test_anthropic_compaction.py b/studio/backend/tests/test_anthropic_compaction.py
index acc0acc2e02..c269d5e2884 100644
--- a/studio/backend/tests/test_anthropic_compaction.py
+++ b/studio/backend/tests/test_anthropic_compaction.py
@@ -127,6 +127,11 @@ def test_threshold_clamped_to_50k_minimum(monkeypatch):
assert captured["body"]["context_management"]["edits"][0]["trigger"]["value"] == 50_000
+def test_threshold_capped_at_200k(monkeypatch):
+ captured = _capture(monkeypatch, "claude-opus-4-7", 750_000)
+ assert captured["body"]["context_management"]["edits"][0]["trigger"]["value"] == 200_000
+
+
# ── beta header merge with code execution ────────────────────────────
@@ -426,6 +431,74 @@ def test_compaction_block_emitted_as_tool_event(monkeypatch):
assert "Here is my answer." in content_text, content_text
+def test_failed_compaction_block_is_not_replayed_or_persisted(monkeypatch):
+ def http_handler(request: httpx.Request) -> httpx.Response:
+ body = (
+ b"event: message_start\n"
+ b'data: {"type":"message_start","message":{"usage":{}}}\n\n'
+ b"event: content_block_start\n"
+ b'data: {"type":"content_block_start","index":0,'
+ b'"content_block":{"type":"compaction","content":null,'
+ b'"encrypted_content":"opaque-failed"}}\n\n'
+ b"event: content_block_stop\n"
+ b'data: {"type":"content_block_stop","index":0}\n\n'
+ b"event: message_delta\n"
+ b'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},'
+ b'"usage":{"input_tokens":100,"output_tokens":1}}\n\n'
+ b"event: message_stop\n"
+ b'data: {"type":"message_stop"}\n\n'
+ )
+ return httpx.Response(200, content = body, headers = {"content-type": "text/event-stream"})
+
+ monkeypatch.setattr(
+ ep_mod,
+ "_http_client",
+ httpx.AsyncClient(transport = httpx.MockTransport(http_handler)),
+ )
+ client = _make_client()
+ lines = _async_collect(
+ client._stream_anthropic(
+ messages = [{"role": "user", "content": "hi"}],
+ model = "claude-opus-4-7",
+ temperature = 0.7,
+ top_p = 0.95,
+ max_tokens = 1024,
+ compaction_threshold = 150_000,
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "terminal",
+ "description": "Run a command",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+ ],
+ )
+ )
+ _drive(client.close())
+
+ payloads = [
+ json.loads(line[len("data:") :])
+ for line in lines
+ if line.startswith("data:") and line[len("data:") :].strip() != "[DONE]"
+ ]
+ assert not any(
+ (payload.get("_toolEvent") or {}).get("type") == "compaction_block" for payload in payloads
+ )
+ native_blocks = [
+ block
+ for payload in payloads
+ for choice in payload.get("choices") or []
+ for block in (
+ ((choice.get("delta") or {}).get("extra_content") or {})
+ .get("anthropic", {})
+ .get("content", [])
+ )
+ ]
+ assert not any(block.get("type") == "compaction" for block in native_blocks)
+
+
def test_compaction_block_round_trips_through_outbound_messages(monkeypatch):
# The next turn's outbound body must forward a persisted
# {type:"compaction", content:"..."} block verbatim so the API recognises the state.
@@ -515,7 +588,11 @@ def test_build_external_messages_passes_compaction_for_anthropic_only():
{
"role": "assistant",
"content": [
- {"type": "compaction", "content": "prior summary"},
+ {
+ "type": "compaction",
+ "content": "prior summary",
+ "encrypted_content": "opaque-compaction",
+ },
{"type": "text", "text": "answer"},
],
}
@@ -524,7 +601,11 @@ def test_build_external_messages_passes_compaction_for_anthropic_only():
out = _build_external_messages(msgs, supports_vision = True, provider_type = "anthropic")
assert len(out) == 1
parts = out[0]["content"]
- assert parts[0] == {"type": "compaction", "content": "prior summary"}
+ assert parts[0] == {
+ "type": "compaction",
+ "content": "prior summary",
+ "encrypted_content": "opaque-compaction",
+ }
assert parts[1] == {"type": "text", "text": "answer"}
@@ -589,7 +670,11 @@ def test_build_external_messages_non_vision_anthropic_keeps_compaction():
{
"role": "assistant",
"content": [
- {"type": "compaction", "content": "prior summary"},
+ {
+ "type": "compaction",
+ "content": "prior summary",
+ "encrypted_content": "opaque-compaction",
+ },
{"type": "text", "text": "answer"},
],
}
@@ -597,8 +682,190 @@ def test_build_external_messages_non_vision_anthropic_keeps_compaction():
]
out = _build_external_messages(msgs, supports_vision = False, provider_type = "anthropic")
parts = out[0]["content"]
- assert {"type": "compaction", "content": "prior summary"} in parts
+ assert {
+ "type": "compaction",
+ "content": "prior summary",
+ "encrypted_content": "opaque-compaction",
+ } in parts
# Non-anthropic + non-vision -> compaction stripped, text collapsed
# back to a string.
out2 = _build_external_messages(msgs, supports_vision = False, provider_type = "deepseek")
assert out2[0]["content"] == "answer", out2
+
+
+def test_compaction_delta_summary_reaches_the_tool_event(monkeypatch):
+ def http_handler(request: httpx.Request) -> httpx.Response:
+ body = (
+ b"event: content_block_start\n"
+ b'data: {"type":"content_block_start","index":0,'
+ b'"content_block":{"type":"compaction","content":null}}\n\n'
+ b"event: content_block_delta\n"
+ b'data: {"type":"content_block_delta","index":0,'
+ b'"delta":{"type":"compaction_delta","content":"User is planning a trip.",'
+ b'"encrypted_content":"opaque-compaction"}}\n\n'
+ b"event: content_block_stop\n"
+ b'data: {"type":"content_block_stop","index":0}\n\n'
+ b"event: message_stop\n"
+ b'data: {"type":"message_stop"}\n\n'
+ )
+ return httpx.Response(200, content = body, headers = {"content-type": "text/event-stream"})
+
+ monkeypatch.setattr(
+ ep_mod,
+ "_http_client",
+ httpx.AsyncClient(transport = httpx.MockTransport(http_handler)),
+ )
+ client = _make_client()
+ lines = _async_collect(
+ client._stream_anthropic(
+ messages = [{"role": "user", "content": "hi"}],
+ model = "claude-sonnet-4-6",
+ temperature = 0.7,
+ top_p = 0.95,
+ max_tokens = 1024,
+ compaction_threshold = 150_000,
+ )
+ )
+ _drive(client.close())
+
+ events = [
+ json.loads(line[len("data:") :])["_toolEvent"]
+ for line in lines
+ if line.startswith("data:") and "compaction_block" in line
+ ]
+ assert events == [
+ {
+ "type": "compaction_block",
+ "content": "User is planning a trip.",
+ "encrypted_content": "opaque-compaction",
+ }
+ ]
+
+
+def _replay(monkeypatch, model: str, threshold) -> dict:
+ captured: dict = {}
+
+ def http_handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = json.loads(request.content.decode("utf-8"))
+ captured["headers"] = dict(request.headers)
+ return httpx.Response(
+ 200,
+ content = b'event: message_stop\ndata: {"type": "message_stop"}\n\n',
+ headers = {"content-type": "text/event-stream"},
+ )
+
+ monkeypatch.setattr(
+ ep_mod,
+ "_http_client",
+ httpx.AsyncClient(transport = httpx.MockTransport(http_handler)),
+ )
+ client = _make_client()
+
+ async def run():
+ async for _ in client.stream_chat_completion(
+ messages = [
+ {"role": "user", "content": "turn 1"},
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "compaction",
+ "content": "PRIOR SUMMARY",
+ "encrypted_content": "opaque-compaction",
+ },
+ {"type": "text", "text": "answer"},
+ ],
+ },
+ {"role": "user", "content": "turn 2"},
+ ],
+ model = model,
+ temperature = 0.7,
+ top_p = 0.95,
+ max_tokens = 32,
+ compaction_threshold = threshold,
+ ):
+ pass
+
+ _drive(run())
+ _drive(client.close())
+ return captured
+
+
+def test_a_replayed_compaction_block_keeps_its_beta_with_auto_compact_off(monkeypatch):
+ captured = _replay(monkeypatch, "claude-sonnet-4-6", None)
+ assistant = captured["body"]["messages"][1]
+ assert assistant["content"][0] == {
+ "type": "compaction",
+ "content": "PRIOR SUMMARY",
+ "encrypted_content": "opaque-compaction",
+ }
+ assert "compact-2026-01-12" in captured["headers"].get("anthropic-beta", "")
+ assert "context_management" not in captured["body"]
+
+
+def test_a_model_without_compaction_is_never_sent_a_compaction_block(monkeypatch):
+ captured = _replay(monkeypatch, "claude-haiku-4-5", 150_000)
+ assistant = captured["body"]["messages"][1]
+ assert [part["type"] for part in assistant["content"]] == ["text"]
+ assert "compact-2026-01-12" not in captured["headers"].get("anthropic-beta", "")
+
+
+def _native_replay(monkeypatch, model: str, threshold) -> dict:
+ captured: dict = {}
+
+ def http_handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = json.loads(request.content.decode("utf-8"))
+ captured["headers"] = dict(request.headers)
+ return httpx.Response(
+ 200,
+ content = b'event: message_stop\ndata: {"type": "message_stop"}\n\n',
+ headers = {"content-type": "text/event-stream"},
+ )
+
+ monkeypatch.setattr(
+ ep_mod,
+ "_http_client",
+ httpx.AsyncClient(transport = httpx.MockTransport(http_handler)),
+ )
+ client = _make_client()
+ native = [
+ {"type": "compaction", "content": "PRIOR SUMMARY"},
+ {"type": "text", "text": "answer"},
+ ]
+
+ async def run():
+ async for _ in client.stream_chat_completion(
+ messages = [
+ {"role": "user", "content": "turn 1"},
+ {
+ "role": "assistant",
+ "content": "answer",
+ "extra_content": {"anthropic": {"content": native}},
+ },
+ {"role": "user", "content": "turn 2"},
+ ],
+ model = model,
+ temperature = 0.7,
+ top_p = 0.95,
+ max_tokens = 32,
+ compaction_threshold = threshold,
+ ):
+ pass
+
+ _drive(run())
+ _drive(client.close())
+ return captured
+
+
+def test_a_replayed_native_compaction_block_keeps_its_beta_with_auto_compact_off(monkeypatch):
+ captured = _native_replay(monkeypatch, "claude-sonnet-4-6", None)
+ assistant = captured["body"]["messages"][1]
+ assert assistant["content"][0] == {"type": "compaction", "content": "PRIOR SUMMARY"}
+ assert "compact-2026-01-12" in captured["headers"].get("anthropic-beta", "")
+
+
+def test_a_model_without_compaction_is_never_sent_a_native_compaction_block(monkeypatch):
+ captured = _native_replay(monkeypatch, "claude-haiku-4-5", 150_000)
+ assistant = captured["body"]["messages"][1]
+ assert [part["type"] for part in assistant["content"]] == ["text"]
+ assert "compact-2026-01-12" not in captured["headers"].get("anthropic-beta", "")
diff --git a/studio/backend/tests/test_anthropic_studio_tools.py b/studio/backend/tests/test_anthropic_studio_tools.py
index e2471da8a73..a6b05c0152c 100644
--- a/studio/backend/tests/test_anthropic_studio_tools.py
+++ b/studio/backend/tests/test_anthropic_studio_tools.py
@@ -422,6 +422,156 @@ def test_native_compaction_delta_is_replayed_with_encrypted_content(monkeypatch)
assert bodies[-1]["messages"][0]["content"] == [{"type": "compaction", **summary}]
+def test_tool_follow_up_replays_native_compaction_once(monkeypatch):
+ bodies = []
+ summary = {"content": "Earlier conversation summary", "encrypted_content": "opaque-compaction"}
+ first_turn = [
+ *_block(
+ 0,
+ {"type": "compaction", "content": None},
+ {"type": "compaction_delta", "content": "Earlier conversation "},
+ {
+ "type": "compaction_delta",
+ "content": "summary",
+ "encrypted_content": summary["encrypted_content"],
+ },
+ ),
+ *_block(
+ 1,
+ {"type": "tool_use", "id": "toolu_a", "name": "python", "input": {}},
+ {"type": "input_json_delta", "partial_json": '{"query":"current"}'},
+ ),
+ *_finish("tool_use"),
+ ]
+
+ def handler(request):
+ bodies.append(json.loads(request.content))
+ return _response(first_turn if len(bodies) == 1 else _finish("end_turn"))
+
+ monkeypatch.setattr(loop, "execute_tool", lambda *_args, **_kwargs: "done")
+ monkeypatch.setattr(loop, "build_rag_autoinject", lambda *a, **k: None)
+ client = _client(monkeypatch, handler)
+
+ async def run():
+ try:
+ return [
+ line
+ async for line in loop.stream_with_studio_tools(
+ OAICompatTransport(
+ client,
+ model = "claude-sonnet-4-6",
+ temperature = 0.7,
+ top_p = 0.95,
+ max_tokens = 4096,
+ ),
+ run = loop.ToolLoopRun(
+ messages = [
+ {"role": "user", "content": "old question"},
+ {"role": "assistant", "content": "old answer"},
+ {"role": "user", "content": "current question"},
+ ]
+ ),
+ policy = loop.ToolLoopPolicy(
+ tools = TOOLS,
+ max_calls = 1,
+ timeout = 30,
+ permission_mode = "off",
+ confirm_calls = False,
+ bypass_permissions = False,
+ rag_scope = None,
+ auto_heal = False,
+ nudge_tool_calls = False,
+ ),
+ cancel_event = threading.Event(),
+ )
+ ]
+ finally:
+ await client.close()
+
+ asyncio.run(run())
+ assistant_parts = [
+ part
+ for message in bodies[1]["messages"]
+ if message["role"] == "assistant"
+ for part in message["content"]
+ ]
+ assert [part for part in assistant_parts if part["type"] == "compaction"] == [
+ {"type": "compaction", **summary}
+ ]
+ assert len([part for part in assistant_parts if part["type"] == "tool_use"]) == 1
+
+
+def test_failed_native_compaction_keeps_history_for_tool_follow_up(monkeypatch):
+ bodies = []
+ first_turn = [
+ *_block(
+ 0,
+ {
+ "type": "compaction",
+ "content": None,
+ "encrypted_content": "opaque-failed",
+ },
+ ),
+ *_block(
+ 1,
+ {"type": "tool_use", "id": "toolu_a", "name": "python", "input": {}},
+ {"type": "input_json_delta", "partial_json": '{"query":"current"}'},
+ ),
+ *_finish("tool_use"),
+ ]
+
+ def handler(request):
+ bodies.append(json.loads(request.content))
+ return _response(first_turn if len(bodies) == 1 else _finish("end_turn"))
+
+ monkeypatch.setattr(loop, "execute_tool", lambda *_args, **_kwargs: "done")
+ monkeypatch.setattr(loop, "build_rag_autoinject", lambda *a, **k: None)
+ client = _client(monkeypatch, handler)
+
+ async def run():
+ try:
+ return [
+ line
+ async for line in loop.stream_with_studio_tools(
+ OAICompatTransport(
+ client,
+ model = "claude-sonnet-4-6",
+ temperature = 0.7,
+ top_p = 0.95,
+ max_tokens = 4096,
+ ),
+ run = loop.ToolLoopRun(
+ messages = [
+ {"role": "user", "content": "old question"},
+ {"role": "assistant", "content": "old answer"},
+ {"role": "user", "content": "current question"},
+ ]
+ ),
+ policy = loop.ToolLoopPolicy(
+ tools = TOOLS,
+ max_calls = 1,
+ timeout = 30,
+ permission_mode = "off",
+ confirm_calls = False,
+ bypass_permissions = False,
+ rag_scope = None,
+ auto_heal = False,
+ nudge_tool_calls = False,
+ ),
+ cancel_event = threading.Event(),
+ )
+ ]
+ finally:
+ await client.close()
+
+ asyncio.run(run())
+ follow_up = json.dumps(bodies[1]["messages"])
+ assert "old question" in follow_up
+ assert "old answer" in follow_up
+ assert "current question" in follow_up
+ assert "opaque-failed" not in follow_up
+
+
def test_truncated_hosted_json_still_reports_length(monkeypatch):
events = [
*_block(
diff --git a/studio/backend/tests/test_conversation_recall_injection.py b/studio/backend/tests/test_conversation_recall_injection.py
index 17210bd6a0c..39fbf42bb16 100644
--- a/studio/backend/tests/test_conversation_recall_injection.py
+++ b/studio/backend/tests/test_conversation_recall_injection.py
@@ -697,6 +697,33 @@ def test_sticky_boundary_reads_the_flattened_metadata_shape(monkeypatch):
assert llama_cpp._sticky_compaction_boundary("t1") == 7
+def test_sticky_boundary_ignores_a_provider_summary(monkeypatch):
+ """A provider summary is useful only while its opaque block is replayed to that provider."""
+ from core.inference import llama_cpp
+
+ _fake_studio_db(
+ monkeypatch,
+ [
+ {
+ "role": "assistant",
+ "content": "a",
+ "metadata": {
+ "custom": {
+ "contextTruncation": {
+ "fits": True,
+ "dropped_messages": 7,
+ "boundary_messages": 7,
+ "summarized": True,
+ }
+ }
+ },
+ },
+ ],
+ )
+
+ assert llama_cpp._sticky_compaction_boundary("t1") == 0
+
+
def test_sticky_boundary_is_zero_without_a_thread_or_history(monkeypatch):
from core.inference import llama_cpp
diff --git a/studio/backend/tests/test_custom_provider_api_type.py b/studio/backend/tests/test_custom_provider_api_type.py
index daf04b65ef5..75b20fd11bd 100644
--- a/studio/backend/tests/test_custom_provider_api_type.py
+++ b/studio/backend/tests/test_custom_provider_api_type.py
@@ -164,7 +164,8 @@ def test_non_stream_route_returns_json_or_upstream_error(monkeypatch, upstream_s
"id": "resp_route",
"status": "completed",
"output": [
- {"type": "message", "content": [{"type": "output_text", "text": "Hello"}]}
+ {"type": "compaction", "encrypted_content": "enc_compacted"},
+ {"type": "message", "content": [{"type": "output_text", "text": "Hello"}]},
],
},
)
@@ -199,7 +200,10 @@ def test_non_stream_route_returns_json_or_upstream_error(monkeypatch, upstream_s
assert response.status_code == upstream_status
body = json.loads(response.body)
if upstream_status == 200:
- assert body["choices"][0]["message"]["content"] == "Hello"
+ assert body["choices"][0]["message"]["content"] == [
+ {"type": "compaction", "encrypted_content": "enc_compacted"},
+ {"type": "text", "text": "Hello"},
+ ]
assert monitor.snapshot()[0]["status"] == "completed"
else:
assert "rate limited" in body["error"]["message"]
@@ -207,6 +211,91 @@ def test_non_stream_route_returns_json_or_upstream_error(monkeypatch, upstream_s
assert monitor.active_count() == 0
[email protected]("server_compaction_rejected", [False, True])
+def test_non_stream_route_reports_local_context_truncation(monkeypatch, server_compaction_rejected):
+ from routes import inference
+
+ requests = []
+
+ def handle(request):
+ body = json.loads(request.content)
+ requests.append(body)
+ if server_compaction_rejected and "context_management" in body:
+ return httpx.Response(
+ 400,
+ json = {
+ "error": {
+ "message": "context_management is unavailable for this deployment",
+ "type": "invalid_request_error",
+ }
+ },
+ )
+ return httpx.Response(
+ 200,
+ json = {
+ "id": "resp_route",
+ "status": "completed",
+ "output": [{"type": "message", "content": [{"type": "output_text", "text": "Hi"}]}],
+ },
+ )
+
+ truncation = {"dropped_messages": 2, "boundary_messages": 2, "fits": True}
+
+ def fit(
+ messages,
+ _payload,
+ *,
+ tools = None,
+ ):
+ assert tools is None
+ return messages[-1:], truncation, 128
+
+ async def run():
+ async with httpx.AsyncClient(transport = httpx.MockTransport(handle)) as transport:
+ monkeypatch.setattr(ep, "_http_client", transport)
+ monkeypatch.setattr(inference, "_fit_external_context", fit)
+ monkeypatch.setattr(
+ inference, "compacts_server_side", lambda *_args: server_compaction_rejected
+ )
+ monkeypatch.setattr(
+ ep, "_is_openai_family_cloud", lambda _base_url: server_compaction_rejected
+ )
+ payload = ChatCompletionRequest(
+ messages = [
+ {"role": "user", "content": "old"},
+ {"role": "assistant", "content": "answer"},
+ {"role": "user", "content": "latest"},
+ ],
+ stream = False,
+ provider_type = "custom",
+ provider_base_url = "https://gateway.example/v1",
+ provider_api_type = "responses",
+ external_model = "gateway-model",
+ context_overflow = "truncate_oldest",
+ compaction_threshold = 6_000,
+ )
+
+ async def disconnected():
+ return False
+
+ request = SimpleNamespace(
+ headers = {},
+ state = SimpleNamespace(skip_api_monitor = True),
+ url = SimpleNamespace(path = "/v1/chat/completions"),
+ method = "POST",
+ is_disconnected = disconnected,
+ )
+ return await inference._proxy_to_external_provider(payload, request)
+
+ response = asyncio.run(run())
+ assert response.status_code == 200
+ body = json.loads(response.body)
+ assert body["context_truncated"] == truncation
+ assert "old" not in json.dumps(requests[-1]["input"])
+ assert "latest" in json.dumps(requests[-1]["input"])
+ assert len(requests) == (2 if server_compaction_rejected else 1)
+
+
def test_responses_follow_up_preserves_reasoning_metadata():
from routes.inference import _build_external_messages
diff --git a/studio/backend/tests/test_external_auto_compaction.py b/studio/backend/tests/test_external_auto_compaction.py
new file mode 100644
index 00000000000..8deb61fcc5b
--- /dev/null
+++ b/studio/backend/tests/test_external_auto_compaction.py
@@ -0,0 +1,402 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import json
+import sys
+from http.server import BaseHTTPRequestHandler
+from pathlib import Path
+
+from starlette.requests import Request
+
+import routes.inference as ri
+from core.inference import external_provider as ep_mod
+from core.inference.context_window import estimate_messages_tokens_conservative
+from models.inference import ChatCompletionRequest
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from test_external_provider_sampling_over_the_wire import _Handler, _run, _Server # noqa: E402
+
+
+_TURN = "word " * 400
+
+
+def _long_chat(turns: int = 12, turn: str = _TURN) -> list[dict]:
+ messages: list[dict] = [{"role": "system", "content": "Answer in French."}]
+ for index in range(turns):
+ messages.append({"role": "user", "content": f"question {index} {turn}"})
+ messages.append({"role": "assistant", "content": f"answer {index} {turn}"})
+ messages.append({"role": "user", "content": "latest question"})
+ return messages
+
+
+class _AnthropicCompactingHandler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *args, **kwargs) -> None:
+ return
+
+ events = [
+ {
+ "type": "content_block_start",
+ "index": 0,
+ "content_block": {"type": "compaction", "content": None},
+ },
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"type": "compaction_delta", "content": "Earlier: twelve questions."},
+ },
+ {"type": "content_block_stop", "index": 0},
+ {"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}},
+ {
+ "type": "content_block_delta",
+ "index": 1,
+ "delta": {"type": "text_delta", "text": "Bonjour"},
+ },
+ {"type": "content_block_stop", "index": 1},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {}},
+ {"type": "message_stop"},
+ ]
+
+ def do_POST(self) -> None: # noqa: N802
+ length = int(self.headers.get("Content-Length") or 0)
+ self.server.recorded.append(json.loads(self.rfile.read(length) or b"{}")) # type: ignore[attr-defined]
+ sse = "".join(
+ f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in self.events
+ ).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.send_header("Content-Length", str(len(sse)))
+ self.end_headers()
+ self.wfile.write(sse)
+
+
+class _AnthropicQuotingHandler(_AnthropicCompactingHandler):
+ events = [
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"type": "text_delta", "text": 'The event is called "compaction_block'},
+ },
+ {"type": "content_block_stop", "index": 0},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {}},
+ {"type": "message_stop"},
+ ]
+
+
+class _OpenAICompactionRejectingHandler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *args, **kwargs) -> None:
+ return
+
+ def do_POST(self) -> None: # noqa: N802
+ length = int(self.headers.get("Content-Length") or 0)
+ body = json.loads(self.rfile.read(length) or b"{}")
+ self.server.recorded.append(body) # type: ignore[attr-defined]
+ if "context_management" in body:
+ payload = json.dumps(
+ {
+ "error": {
+ "message": "context_management is unavailable for this deployment",
+ "type": "invalid_request_error",
+ }
+ }
+ ).encode()
+ self.send_response(400)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+ return
+
+ sse = (
+ b"event: response.completed\n"
+ b'data: {"type":"response.completed",'
+ b'"response":{"output":[],"usage":{"input_tokens":0,"output_tokens":0}}}\n\n'
+ )
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.send_header("Content-Length", str(len(sse)))
+ self.end_headers()
+ self.wfile.write(sse)
+
+
+def _proxy(
+ provider_type: str,
+ messages: list[dict],
+ handler = _Handler,
+ **fields,
+):
+ async def receive() -> dict:
+ return {"type": "http.disconnect"}
+
+ chunks: list[dict] = []
+ with _Server(handler = handler) as server:
+ payload = ChatCompletionRequest(
+ provider_type = provider_type,
+ provider_base_url = server.base_url,
+ messages = messages,
+ model = fields.pop("model", "a-model"),
+ stream = True,
+ max_tokens = fields.pop("max_tokens", 256),
+ **fields,
+ )
+ request = Request(
+ {
+ "type": "http",
+ "method": "POST",
+ "path": "/v1/chat/completions",
+ "headers": [(b"content-type", b"application/json")],
+ "query_string": b"",
+ },
+ receive,
+ )
+
+ async def go() -> None:
+ response = await ri._proxy_to_external_provider(payload, request)
+ async for part in response.body_iterator:
+ text = part.decode() if isinstance(part, bytes) else part
+ for line in text.splitlines():
+ body = line[len("data:") :].strip() if line.startswith("data:") else ""
+ if body and body != "[DONE]":
+ chunks.append(json.loads(body))
+
+ _run(go)
+ assert server.bodies, "the route never reached the provider"
+ return chunks, server.bodies[-1]
+
+
+def _truncations(chunks: list[dict]) -> list[dict]:
+ return [c["context_truncated"] for c in chunks if "context_truncated" in c]
+
+
+def test_auto_compact_drops_the_oldest_turns_before_a_provider_without_compaction():
+ chunks, sent = _proxy(
+ "openrouter",
+ _long_chat(),
+ context_overflow = "truncate_oldest",
+ compaction_threshold = 6_000,
+ )
+ roles = [m["role"] for m in sent["messages"]]
+ assert len(sent["messages"]) < len(_long_chat())
+ assert roles[0] == "system" and "Answer in French." in json.dumps(sent["messages"][0])
+ assert sent["messages"][-1]["content"] == "latest question"
+ [truncation] = _truncations(chunks)
+ assert truncation["fits"] is True
+ assert truncation["dropped_messages"] == len(_long_chat()) - len(sent["messages"])
+
+
+def test_auto_compact_off_forwards_the_whole_chat():
+ chunks, sent = _proxy("openrouter", _long_chat())
+ assert len(sent["messages"]) == len(_long_chat())
+ assert _truncations(chunks) == []
+
+
+def test_a_chat_within_the_threshold_is_forwarded_untouched():
+ short = _long_chat(turns = 1)
+ chunks, sent = _proxy(
+ "openrouter", short, context_overflow = "truncate_oldest", compaction_threshold = 6_000
+ )
+ assert len(sent["messages"]) == len(short)
+ assert _truncations(chunks) == []
+
+
+def test_a_provider_compaction_is_reported_as_a_summarized_compaction():
+ chat = _long_chat(turns = 2)
+ chunks, sent = _proxy(
+ "anthropic",
+ chat,
+ handler = _AnthropicCompactingHandler,
+ model = "claude-sonnet-4-6",
+ context_overflow = "truncate_oldest",
+ compaction_threshold = 150_000,
+ )
+ assert sent["context_management"]["edits"][0]["trigger"]["value"] == 150_000
+ assert len(sent["messages"]) == len(chat) - 1
+ [truncation] = _truncations(chunks)
+ assert truncation == {
+ "dropped_messages": 4,
+ "boundary_messages": 4,
+ "fits": True,
+ "summarized": True,
+ }
+
+
+def test_a_rejected_provider_compaction_falls_back_to_local_fitting(monkeypatch):
+ monkeypatch.setattr(ep_mod, "_is_openai_family_cloud", lambda _base_url: True)
+ monkeypatch.setattr(ri, "compacts_server_side", lambda *_args: True)
+ chat = _long_chat()
+ chunks, sent = _proxy(
+ "openai",
+ chat,
+ handler = _OpenAICompactionRejectingHandler,
+ model = "gpt-5.5",
+ context_overflow = "truncate_oldest",
+ compaction_threshold = 6_000,
+ )
+ serialized = json.dumps(sent["input"])
+ assert "context_management" not in sent
+ assert "question 0" not in serialized
+ assert "latest question" in serialized
+ [truncation] = _truncations(chunks)
+ assert truncation["fits"] is True
+ assert truncation["dropped_messages"] > 0
+
+
+def test_model_text_naming_a_compaction_block_is_not_a_compaction():
+ chunks, _ = _proxy(
+ "anthropic",
+ _long_chat(turns = 2),
+ handler = _AnthropicQuotingHandler,
+ model = "claude-sonnet-4-6",
+ context_overflow = "truncate_oldest",
+ compaction_threshold = 150_000,
+ )
+ assert _truncations(chunks) == []
+
+
+def test_the_trimmed_prompt_leaves_the_whole_reply_room_in_the_window():
+ chat = _long_chat(turns = 9, turn = "word " * 370)
+ assert 16_384 - 8_192 < estimate_messages_tokens_conservative(chat) < 9_216
+ chunks, sent = _proxy(
+ "openrouter",
+ chat,
+ max_tokens = 8_192,
+ context_overflow = "truncate_oldest",
+ compaction_threshold = 12_288,
+ context_window = 16_384,
+ )
+ assert sent["max_tokens"] == 8_192
+ assert estimate_messages_tokens_conservative(sent["messages"]) + 8_192 < 16_384
+ assert sent["messages"][-1]["content"] == "latest question"
+ [truncation] = _truncations(chunks)
+ assert truncation["dropped_messages"] == len(chat) - len(sent["messages"])
+
+
+def test_a_reply_cap_near_the_window_is_lowered_rather_than_emptying_the_chat():
+ chat = _long_chat(turns = 9, turn = "word " * 370)
+ _, sent = _proxy(
+ "openrouter",
+ chat,
+ max_tokens = 16_000,
+ context_overflow = "truncate_oldest",
+ compaction_threshold = 12_288,
+ context_window = 16_384,
+ )
+ assert sum(m["content"].startswith("question") for m in sent["messages"]) >= 3
+ assert sent["max_tokens"] <= 16_384 // 2
+ assert estimate_messages_tokens_conservative(sent["messages"]) + sent["max_tokens"] < 16_384
+
+
+def test_a_window_without_auto_compact_changes_nothing():
+ chat = _long_chat(turns = 9, turn = "word " * 370)
+ chunks, sent = _proxy("openrouter", chat, max_tokens = 16_000, context_window = 16_384)
+ assert sent["max_tokens"] == 16_000
+ assert len(sent["messages"]) == len(chat)
+ assert _truncations(chunks) == []
+
+
+def test_a_short_chat_keeps_a_reply_cap_past_half_the_window():
+ short = _long_chat(turns = 1)
+ chunks, sent = _proxy(
+ "openrouter",
+ short,
+ max_tokens = 12_000,
+ context_overflow = "truncate_oldest",
+ compaction_threshold = 12_288,
+ context_window = 16_384,
+ )
+ assert sent["max_tokens"] == 12_000
+ assert len(sent["messages"]) == len(short)
+ assert _truncations(chunks) == []
+
+
+def test_a_tool_enabled_chat_starts_from_the_saved_boundary(monkeypatch):
+ from core.inference import llama_cpp
+
+ monkeypatch.setattr(
+ llama_cpp,
+ "_sticky_compaction_state",
+ lambda thread_id, *a, **k: (20 if thread_id else 0, False),
+ )
+ monkeypatch.setattr(llama_cpp, "_keeps_compaction_boundary", lambda thread_id: False)
+
+ async def connected(self) -> bool:
+ return False
+
+ # The tool loop polls for a disconnect and would stop before reaching the provider.
+ monkeypatch.setattr(Request, "is_disconnected", connected)
+ _, sent = _proxy(
+ "openrouter",
+ _long_chat(),
+ thread_id = "saved-thread",
+ enable_tools = True,
+ enabled_tools = ["python"],
+ permission_mode = "off",
+ context_overflow = "truncate_oldest",
+ compaction_threshold = 6_000,
+ )
+ assert sent["tools"]
+ assert len(_long_chat()) - len(sent["messages"]) == 20
+
+
+def test_external_fit_reserves_image_embeddings():
+ messages = [
+ {"role": "system", "content": "Keep this."},
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "old image"},
+ {
+ "type": "image_url",
+ "image_url": {"url": "data:image/png;base64,cGljdHVyZQ=="},
+ },
+ ],
+ },
+ {"role": "assistant", "content": "old answer"},
+ {"role": "user", "content": "latest question"},
+ ]
+ payload = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "latest question"}],
+ provider_type = "openrouter",
+ model = "a-model",
+ context_overflow = "truncate_oldest",
+ compaction_threshold = 3_000,
+ context_window = 4_000,
+ max_tokens = 512,
+ )
+
+ fitted, truncation, _ = ri._fit_external_context(messages, payload)
+ assert truncation and truncation["dropped_messages"] == 2
+ assert fitted[-1]["content"] == "latest question"
+
+
+def test_external_fit_reserves_tool_schemas():
+ messages = _long_chat(turns = 2, turn = "word " * 80)
+ payload = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "latest question"}],
+ provider_type = "openrouter",
+ model = "a-model",
+ context_overflow = "truncate_oldest",
+ compaction_threshold = 3_000,
+ context_window = 4_000,
+ max_tokens = 512,
+ )
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "large_tool",
+ "description": "schema " * 1_200,
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+ ]
+
+ fitted, truncation, _ = ri._fit_external_context(messages, payload, tools = tools)
+ assert truncation and truncation["dropped_messages"] > 0
+ assert fitted[-1]["content"] == "latest question"
diff --git a/studio/backend/tests/test_external_provider_usage_chunk.py b/studio/backend/tests/test_external_provider_usage_chunk.py
index e8075b811c6..d17d7cfff2e 100644
--- a/studio/backend/tests/test_external_provider_usage_chunk.py
+++ b/studio/backend/tests/test_external_provider_usage_chunk.py
@@ -55,6 +55,26 @@ def test_build_usage_chunk_anthropic_shape():
assert usage["prompt_tokens_details"]["cached_tokens"] == 18901
+def test_build_usage_chunk_anthropic_includes_compaction_iteration_tokens():
+ line = _build_usage_chunk(
+ "chatcmpl-compaction",
+ "anthropic",
+ {
+ "input_tokens": 23_000,
+ "output_tokens": 1_000,
+ "compaction_input_tokens": 180_000,
+ "compaction_output_tokens": 3_500,
+ },
+ )
+ assert line is not None
+ usage = json.loads(line[len("data: ") :])["usage"]
+ assert usage["prompt_tokens"] == 203_000
+ assert usage["completion_tokens"] == 4_500
+ assert usage["total_tokens"] == 207_500
+ assert usage["compaction_input_tokens"] == 180_000
+ assert usage["compaction_output_tokens"] == 3_500
+
+
def test_build_usage_chunk_openai_shape():
line = _build_usage_chunk(
"chatcmpl-y",
diff --git a/studio/backend/tests/test_external_tool_name_and_usage.py b/studio/backend/tests/test_external_tool_name_and_usage.py
index 5e5ceb940d9..10918aa7999 100644
--- a/studio/backend/tests/test_external_tool_name_and_usage.py
+++ b/studio/backend/tests/test_external_tool_name_and_usage.py
@@ -393,3 +393,39 @@ def test_a_last_turn_without_timings_reports_none(executed, answer_turn, total):
assert len(reports) == 1
assert reports[0]["usage"]["total_tokens"] == total
assert "timings" not in reports[0]
+
+
+def test_a_provider_compaction_item_is_handed_to_the_next_round(executed):
+ compaction = "data: " + json.dumps(
+ {
+ "choices": [{"index": 0, "delta": {}, "finish_reason": None}],
+ "_toolEvent": {"type": "compaction_block", "encrypted_content": "gAAAA-opaque"},
+ }
+ )
+ transport = FakeTransport(
+ [[compaction, _name_fragment(0, "web_search"), _arguments(0, '{"query": "x"}'), _finish()]]
+ )
+ # As the real transport does: the event is this server's own frame, not a provider's forgery.
+ transport.sanitizes_provider_frames = True
+ _run(transport)
+ assert transport.requests[0]["messages"] == [{"role": "user", "content": "hi"}]
+ replayed = transport.requests[1]["messages"]
+ # The item stands in for the history it covers, so only the turn after it is resent.
+ assert [m["role"] for m in replayed] == ["assistant", "assistant", "assistant", "tool"]
+ assert replayed[0]["extra_content"] == {"openai_responses_compaction": "gAAAA-opaque"}
+ assert "hi" not in json.dumps(replayed)
+
+
+def test_a_reprompt_after_a_compacted_turn_stays_after_the_item(executed):
+ narration = "data: " + json.dumps(
+ {
+ "choices": [{"index": 0, "delta": {"content": "I'll search the web."}}],
+ "_toolEvent": {"type": "compaction_block", "encrypted_content": "gAAAA-opaque"},
+ }
+ )
+ transport = FakeTransport([[narration, _finish("stop")]])
+ transport.sanitizes_provider_frames = True
+ _run(transport, nudge_tool_calls = True)
+ replayed = transport.requests[1]["messages"]
+ assert [m["role"] for m in replayed] == ["assistant", "assistant", "user"]
+ assert "extra_content" in replayed[0] and "web_search" in replayed[2]["content"]
diff --git a/studio/backend/tests/test_external_tool_transport_cancel.py b/studio/backend/tests/test_external_tool_transport_cancel.py
index 967d0e8f9da..418fa2f2d34 100644
--- a/studio/backend/tests/test_external_tool_transport_cancel.py
+++ b/studio/backend/tests/test_external_tool_transport_cancel.py
@@ -100,3 +100,59 @@ def test_an_uncancelled_stream_relays_every_line():
assert client.torn_down
asyncio.run(scenario())
+
+
+def test_each_transport_turn_is_refitted_before_the_provider_call():
+ class RecordingClient:
+ provider_type = "custom"
+
+ def __init__(self) -> None:
+ self.requests: list[dict] = []
+
+ async def stream_chat_completion(self, **kwargs):
+ self.requests.append(kwargs)
+ yield "data: [DONE]"
+
+ async def scenario():
+ client = RecordingClient()
+ fitted_inputs: list[list[dict]] = []
+
+ async def fitter(messages):
+ fitted_inputs.append(messages)
+ return messages[-2:], 17, 'data: {"choices":[],"context_truncated":{}}'
+
+ transport = OAICompatTransport(
+ client,
+ model = "local-model",
+ max_tokens = 99,
+ message_fitter = fitter,
+ )
+ histories = [
+ [{"role": "user", "content": "first"}],
+ [
+ {"role": "user", "content": "first"},
+ {"role": "assistant", "content": "call"},
+ {"role": "tool", "content": "large result"},
+ ],
+ ]
+ relayed = []
+ for messages in histories:
+ relayed.append(
+ [
+ line
+ async for line in transport.stream(
+ messages = messages,
+ tools = None,
+ tool_choice = "auto",
+ cancel_event = threading.Event(),
+ )
+ ]
+ )
+
+ assert fitted_inputs == histories
+ assert client.requests[0]["messages"] == histories[0]
+ assert client.requests[1]["messages"] == histories[1][-2:]
+ assert [request["max_tokens"] for request in client.requests] == [17, 17]
+ assert all("context_truncated" in lines[0] for lines in relayed)
+
+ asyncio.run(scenario())
diff --git a/studio/backend/tests/test_external_tool_transport_continuation.py b/studio/backend/tests/test_external_tool_transport_continuation.py
index 44e4ae0980f..bdd5395a7f7 100644
--- a/studio/backend/tests/test_external_tool_transport_continuation.py
+++ b/studio/backend/tests/test_external_tool_transport_continuation.py
@@ -88,3 +88,44 @@ def test_continuation_flags_track_the_trailing_role(monkeypatch, messages, expec
_drive(run())
assert captured["body"].get("continue_final_message", False) is expected
assert ("add_generation_prompt" in captured["body"]) is expected
+
+
+def test_every_round_is_fitted_again(monkeypatch):
+ bodies: list[dict] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ bodies.append(json.loads(request.content.decode("utf-8")))
+ return httpx.Response(
+ 200,
+ content = b'data: {"choices":[{"delta":{"content":"ok"}}]}\n\ndata: [DONE]\n\n',
+ headers = {"content-type": "text/event-stream"},
+ )
+
+ monkeypatch.setattr(
+ ep_mod, "_http_client", httpx.AsyncClient(transport = httpx.MockTransport(handler))
+ )
+ client = ExternalProviderClient(
+ provider_type = "vllm", base_url = "http://self-hosted.example/v1", api_key = ""
+ )
+
+ async def fitter(messages):
+ return messages[1:], 7, None
+
+ transport = OAICompatTransport(
+ client, model = "local-model", max_tokens = 64, message_fitter = fitter
+ )
+
+ async def run():
+ for messages in (_ASSISTANT_TAIL, _TOOL_TAIL):
+ async for _ in transport.stream(
+ messages = messages, tools = None, tool_choice = "auto", cancel_event = threading.Event()
+ ):
+ pass
+ await client.close()
+
+ _drive(run())
+ assert [len(body["messages"]) for body in bodies] == [
+ len(_ASSISTANT_TAIL) - 1,
+ len(_TOOL_TAIL) - 1,
+ ]
+ assert [body["max_tokens"] for body in bodies] == [7, 7]
diff --git a/studio/backend/tests/test_openai_compaction.py b/studio/backend/tests/test_openai_compaction.py
index 15b5fb8561f..87494e17061 100644
--- a/studio/backend/tests/test_openai_compaction.py
+++ b/studio/backend/tests/test_openai_compaction.py
@@ -91,8 +91,7 @@ def test_cloud_openai_sets_compaction_block(monkeypatch):
def test_cloud_openai_below_default_threshold_passes_through(monkeypatch):
- # Unsloth doesn't clamp the OpenAI side -- the API accepts whatever the
- # caller sends, so a small probe like 60k still goes through.
+ # OpenAI accepts thresholds below the default without clamping.
captured = _capture(
monkeypatch,
base_url = "https://api.openai.com/v1",
@@ -103,20 +102,19 @@ def test_cloud_openai_below_default_threshold_passes_through(monkeypatch):
]
-# ── non-cloud bases drop the field ──────────────────────────────────
+def test_cloud_openai_threshold_capped_at_200k(monkeypatch):
+ captured = _capture(monkeypatch, base_url = "https://api.openai.com/v1", threshold = 750_000)
+ assert captured["body"]["context_management"] == [
+ {"type": "compaction", "compact_threshold": 200_000}
+ ]
def test_non_cloud_base_silently_drops_compaction(monkeypatch):
- # ollama / llama.cpp / "custom" presets collapse to provider="openai"
- # but lack context_management. Sending the field would 400 them, so it
- # must NOT appear on the wire.
+ # OpenAI-compatible local providers reject context_management.
captured = _capture_at_threshold(monkeypatch, base_url = "http://127.0.0.1:11434/v1")
assert "context_management" not in captured["body"]
-# ── Azure OpenAI Foundry is treated as cloud ────────────────────────
-
-
def test_azure_openai_base_url_carries_compaction_block(monkeypatch):
# Azure OpenAI Foundry exposes the same /v1/responses extensions
# (context_management, prompt_cache_retention, container shell) under
@@ -204,11 +202,7 @@ def test_chat_completion_request_accepts_any_positive_compaction_threshold():
}
)
- # Any positive int passes schema validation, including values that
- # are no-ops on the OpenAI cloud path. Intentional -- the OpenAI
- # helper drops the field on non-cloud bases and forwards as-is on
- # cloud bases; if it's below the model's effective floor, the upstream
- # API surfaces the error.
+ # positive thresholds stay schema-valid because providers enforce support and minimums.
for v in (1, 5_000, 9_999, 10_000, 200_000):
req = ChatCompletionRequest.model_validate(
{
@@ -218,3 +212,447 @@ def test_chat_completion_request_accepts_any_positive_compaction_threshold():
}
)
assert req.compaction_threshold == v
+
+
+def _stream(
+ monkeypatch,
+ handler,
+ *,
+ messages,
+ threshold = None,
+ base_url = "https://api.openai.com/v1",
+ enabled_tools = None,
+ compaction_fallback = None,
+):
+ monkeypatch.setattr(
+ ep_mod,
+ "_http_client",
+ httpx.AsyncClient(transport = httpx.MockTransport(handler)),
+ )
+
+ async def run():
+ client = ExternalProviderClient(
+ provider_type = "openai",
+ base_url = base_url,
+ api_key = "sk-test",
+ )
+ extra = {}
+ if enabled_tools is not None:
+ extra["enabled_tools"] = enabled_tools
+ if compaction_fallback is not None:
+ extra["compaction_fallback"] = compaction_fallback
+ lines = [
+ line
+ async for line in client.stream_chat_completion(
+ messages = messages,
+ model = "gpt-5.5",
+ temperature = 0.7,
+ top_p = 0.95,
+ max_tokens = 32,
+ compaction_threshold = threshold,
+ **extra,
+ )
+ ]
+ await client.close()
+ return lines
+
+ return _drive(run())
+
+
+_EMPTY_COMPLETED = (
+ b"event: response.completed\n"
+ b'data: {"type":"response.completed",'
+ b'"response":{"output":[],"usage":{"input_tokens":0,"output_tokens":0}}}\n\n'
+)
+
+
+def test_a_compaction_output_item_is_handed_to_the_client(monkeypatch):
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ content = (
+ b"event: response.output_item.done\n"
+ b'data: {"type":"response.output_item.done","output_index":0,'
+ b'"item":{"type":"compaction","id":"cmp_1","encrypted_content":"gAAAA-opaque"}}\n\n'
+ + _EMPTY_COMPLETED
+ ),
+ headers = {"content-type": "text/event-stream"},
+ )
+
+ lines = _stream(
+ monkeypatch, handler, messages = [{"role": "user", "content": "hi"}], threshold = 200_000
+ )
+ events = [
+ json.loads(line[len("data:") :])["_toolEvent"]
+ for line in lines
+ if line.startswith("data:") and "compaction_block" in line
+ ]
+ assert [event["encrypted_content"] for event in events] == ["gAAAA-opaque"]
+
+
+def test_a_replayed_compaction_item_replaces_the_history_it_covers(monkeypatch):
+ captured: dict = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = json.loads(request.content.decode("utf-8"))
+ return httpx.Response(
+ 200, content = _EMPTY_COMPLETED, headers = {"content-type": "text/event-stream"}
+ )
+
+ _stream(
+ monkeypatch,
+ handler,
+ messages = [
+ {"role": "system", "content": "Be brief."},
+ {"role": "user", "content": "turn 1"},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "compaction", "encrypted_content": "gAAAA-opaque"},
+ {"type": "text", "text": "answer 1"},
+ ],
+ },
+ {"role": "user", "content": "turn 2"},
+ ],
+ )
+ items = captured["body"]["input"]
+ assert items[0] == {"type": "compaction", "encrypted_content": "gAAAA-opaque"}
+ assert "turn 1" not in json.dumps(items)
+ assert "turn 2" in json.dumps(items)
+ assert captured["body"]["instructions"] == "Be brief."
+
+
+def test_a_replayed_compaction_item_clears_an_earlier_response_reference(monkeypatch):
+ captured: dict = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = json.loads(request.content.decode("utf-8"))
+ return httpx.Response(
+ 200, content = _EMPTY_COMPLETED, headers = {"content-type": "text/event-stream"}
+ )
+
+ _stream(
+ monkeypatch,
+ handler,
+ enabled_tools = ["image_generation"],
+ messages = [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "image_generation_call",
+ "id": "image_earlier",
+ "response_id": "resp_earlier",
+ }
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": [{"type": "compaction", "encrypted_content": "gAAAA-current"}],
+ },
+ {"role": "user", "content": "edit the current result"},
+ ],
+ )
+ assert "previous_response_id" not in captured["body"]
+ assert "image_earlier" not in json.dumps(captured["body"]["input"])
+
+
+def test_a_replayed_compaction_item_clears_earlier_manual_image_replay(monkeypatch):
+ captured: dict = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = json.loads(request.content.decode("utf-8"))
+ return httpx.Response(
+ 200, content = _EMPTY_COMPLETED, headers = {"content-type": "text/event-stream"}
+ )
+
+ _stream(
+ monkeypatch,
+ handler,
+ enabled_tools = ["image_generation"],
+ messages = [
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "reasoning", "id": "rs_earlier", "summary": []},
+ {"type": "image_generation_call", "id": "image_earlier"},
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": [{"type": "compaction", "encrypted_content": "gAAAA-current"}],
+ },
+ {"role": "user", "content": "continue"},
+ ],
+ )
+ serialized = json.dumps(captured["body"]["input"])
+ assert "rs_earlier" not in serialized
+ assert "image_earlier" not in serialized
+
+
+def test_a_deployment_without_compaction_is_retried_without_it(monkeypatch):
+ bodies: list = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content.decode("utf-8"))
+ bodies.append(body)
+ if "context_management" in body:
+ return httpx.Response(
+ 400,
+ json = {
+ "error": {
+ "message": "compact_threshold is not enabled.",
+ "type": "invalid_request_error",
+ "param": "compact_threshold",
+ "code": "unsupported_parameter",
+ }
+ },
+ )
+ return httpx.Response(
+ 200, content = _EMPTY_COMPLETED, headers = {"content-type": "text/event-stream"}
+ )
+
+ lines = _stream(
+ monkeypatch,
+ handler,
+ messages = [{"role": "user", "content": "hi"}],
+ threshold = 96_000,
+ base_url = "https://myres.openai.azure.com/openai/v1",
+ )
+ assert len(bodies) == 2
+ assert "context_management" not in bodies[1]
+ assert not any('"error"' in line for line in lines)
+
+
+def test_a_compaction_rejection_refits_history_before_retry(monkeypatch):
+ bodies: list[dict] = []
+ fallback_calls: list[list[dict]] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content.decode("utf-8"))
+ bodies.append(body)
+ if "context_management" in body:
+ return httpx.Response(
+ 400,
+ json = {
+ "error": {
+ "message": "context_management is unavailable for this deployment",
+ "type": "invalid_request_error",
+ }
+ },
+ )
+ return httpx.Response(
+ 200, content = _EMPTY_COMPLETED, headers = {"content-type": "text/event-stream"}
+ )
+
+ async def fallback(messages):
+ fallback_calls.append(messages)
+ fitted = [messages[0], messages[-1]]
+ notice = "data: " + json.dumps(
+ {
+ "id": "chatcmpl-fallback",
+ "object": "chat.completion.chunk",
+ "choices": [],
+ "context_truncated": {"dropped_messages": len(messages) - len(fitted)},
+ }
+ )
+ return fitted, 32, notice
+
+ messages = [
+ {"role": "system", "content": "Be concise."},
+ {"role": "user", "content": "old turn"},
+ {"role": "assistant", "content": "old answer"},
+ {"role": "user", "content": "latest turn"},
+ ]
+ lines = _stream(
+ monkeypatch,
+ handler,
+ messages = messages,
+ threshold = 96_000,
+ base_url = "https://myres.openai.azure.com/openai/v1",
+ compaction_fallback = fallback,
+ )
+ assert fallback_calls == [messages]
+ assert len(bodies) == 2
+ assert "context_management" not in bodies[1]
+ assert "old turn" not in json.dumps(bodies[1]["input"])
+ assert "latest turn" in json.dumps(bodies[1]["input"])
+ assert any("context_truncated" in line for line in lines)
+
+
+def test_a_compaction_rejection_is_remembered_across_tool_loop_turns(monkeypatch):
+ bodies: list[dict] = []
+ fallback_calls: list[list[dict]] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content.decode("utf-8"))
+ bodies.append(body)
+ if "context_management" in body:
+ return httpx.Response(
+ 400,
+ json = {
+ "error": {
+ "message": "context_management is unavailable for this deployment",
+ "type": "invalid_request_error",
+ }
+ },
+ )
+ return httpx.Response(
+ 200, content = _EMPTY_COMPLETED, headers = {"content-type": "text/event-stream"}
+ )
+
+ async def fallback(messages):
+ fallback_calls.append(messages)
+ return messages, 32, None
+
+ turns = [
+ [
+ {"role": "system", "content": "Be concise."},
+ {"role": "user", "content": "old turn"},
+ {"role": "user", "content": "first provider turn"},
+ ],
+ [
+ {"role": "system", "content": "Be concise."},
+ {"role": "user", "content": "old turn"},
+ {
+ "role": "assistant",
+ "content": "calling a Studio tool",
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "terminal", "arguments": "{}"},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "tool result"},
+ ],
+ ]
+ monkeypatch.setattr(
+ ep_mod,
+ "_http_client",
+ httpx.AsyncClient(transport = httpx.MockTransport(handler)),
+ )
+
+ async def run():
+ client = ExternalProviderClient(
+ provider_type = "openai",
+ base_url = "https://myres.openai.azure.com/openai/v1",
+ api_key = "sk-test",
+ )
+ for messages in turns:
+ async for _ in client.stream_chat_completion(
+ messages = messages,
+ model = "gpt-5.5",
+ max_tokens = 32,
+ compaction_threshold = 96_000,
+ compaction_fallback = fallback,
+ ):
+ pass
+ await client.close()
+
+ _drive(run())
+ assert fallback_calls == turns
+ assert len(bodies) == 3
+ assert "context_management" in bodies[0]
+ assert all("context_management" not in body for body in bodies[1:])
+
+
+def test_build_external_messages_passes_the_compaction_item_to_openai():
+ from models.inference import ChatMessage
+ from routes.inference import _build_external_messages
+
+ msgs = [
+ ChatMessage.model_validate(
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "compaction", "encrypted_content": "gAAAA-opaque"},
+ {"type": "text", "text": "answer"},
+ ],
+ }
+ )
+ ]
+ out = _build_external_messages(msgs, supports_vision = True, provider_type = "openai")
+ assert out[0]["content"][0] == {"type": "compaction", "encrypted_content": "gAAAA-opaque"}
+ anthropic = _build_external_messages(msgs, supports_vision = True, provider_type = "anthropic")
+ deepseek = _build_external_messages(msgs, supports_vision = True, provider_type = "deepseek")
+ for out in (anthropic, deepseek):
+ assert "gAAAA-opaque" not in json.dumps(out)
+
+
+def test_a_tool_round_compaction_item_replaces_the_history_it_covers(monkeypatch):
+ captured: dict = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = json.loads(request.content.decode("utf-8"))
+ return httpx.Response(
+ 200, content = _EMPTY_COMPLETED, headers = {"content-type": "text/event-stream"}
+ )
+
+ _stream(
+ monkeypatch,
+ handler,
+ messages = [
+ {"role": "user", "content": "turn 1"},
+ {
+ "role": "assistant",
+ "content": "",
+ "extra_content": {"openai_responses_compaction": "gAAAA-opaque"},
+ },
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "c1",
+ "type": "function",
+ "function": {"name": "lookup", "arguments": "{}"},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "found"},
+ ],
+ )
+ items = captured["body"]["input"]
+ assert items[0] == {"type": "compaction", "encrypted_content": "gAAAA-opaque"}
+ assert "turn 1" not in json.dumps(items)
+ assert [item["type"] for item in items[1:]] == ["function_call", "function_call_output"]
+
+
+def test_a_replayed_compaction_item_drops_the_image_chain_it_covers(monkeypatch):
+ captured: dict = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = json.loads(request.content.decode("utf-8"))
+ return httpx.Response(
+ 200, content = _EMPTY_COMPLETED, headers = {"content-type": "text/event-stream"}
+ )
+
+ _stream(
+ monkeypatch,
+ handler,
+ enabled_tools = ["image_generation"],
+ messages = [
+ {"role": "user", "content": "draw a cat"},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "image_generation_call", "id": "ig_1", "response_id": "resp_1"}
+ ],
+ },
+ {"role": "user", "content": "turn 2"},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "compaction", "encrypted_content": "gAAAA-opaque"},
+ {"type": "text", "text": "answer 2"},
+ ],
+ },
+ {"role": "user", "content": "turn 3"},
+ ],
+ )
+ body = captured["body"]
+ assert "previous_response_id" not in body
+ assert body["input"][0] == {"type": "compaction", "encrypted_content": "gAAAA-opaque"}
+ assert "ig_1" not in json.dumps(body["input"])
diff --git a/studio/backend/tests/test_studio_tool_loop.py b/studio/backend/tests/test_studio_tool_loop.py
index 721a5fc3109..0536d61bd11 100644
--- a/studio/backend/tests/test_studio_tool_loop.py
+++ b/studio/backend/tests/test_studio_tool_loop.py
@@ -139,6 +139,7 @@ def _run(
messages = None,
supports_vision = False,
mcp_image = None,
+ continue_final_message = False,
**policy_kwargs,
):
policy_fields = {
@@ -163,6 +164,7 @@ def _run(
thread_id = "t1",
tool_choice = tool_choice,
supports_vision = supports_vision,
+ continue_final_message = continue_final_message,
),
policy = ToolLoopPolicy(**policy_fields),
cancel_event = cancel_event,
@@ -248,6 +250,92 @@ def test_structured_call_executes_and_continues(executed):
assert follow_up[-1]["content"] == "RESULT<web_search>"
+def test_provider_compaction_replaces_history_before_tool_follow_up(executed):
+ transport = FakeTransport(
+ [
+ [
+ _sse(
+ {},
+ _toolEvent = {
+ "type": "compaction_block",
+ "encrypted_content": "opaque-current",
+ },
+ ),
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_a",
+ "function": {
+ "name": "web_search",
+ "arguments": '{"query":"current"}',
+ },
+ }
+ ]
+ }
+ ),
+ _sse(finish = "tool_calls"),
+ _DONE,
+ ],
+ [_sse({"content": "Done."}), _sse(finish = "stop"), _DONE],
+ ]
+ )
+ # ExternalProviderClient synthesizes this control frame after sanitizing the provider stream.
+ transport.sanitizes_provider_frames = True
+ _run(
+ transport,
+ messages = [
+ {"role": "system", "content": "Keep this instruction."},
+ {"role": "user", "content": "old question"},
+ {"role": "assistant", "content": "old answer"},
+ {"role": "user", "content": "current question"},
+ ],
+ )
+
+ follow_up = transport.requests[1]["messages"]
+ assert follow_up[0] == {"role": "system", "content": "Keep this instruction."}
+ assert follow_up[1] == {
+ "role": "assistant",
+ "content": "",
+ "extra_content": {"openai_responses_compaction": "opaque-current"},
+ }
+ serialized = json.dumps(follow_up)
+ assert "old question" not in serialized
+ assert "current question" not in serialized
+ assert [message["role"] for message in follow_up[-2:]] == ["assistant", "tool"]
+
+
+def test_a_resumed_reply_does_not_merge_over_the_compaction_it_follows(executed):
+ summary = {"type": "compaction", "content": "Earlier conversation summary"}
+ native = {"anthropic": {"content": [summary, {"type": "text", "text": " rest"}]}}
+ call = {"index": 0, "id": "call_a", "function": {"name": "web_search", "arguments": "{}"}}
+ transport = FakeTransport(
+ [
+ [
+ _sse({}, _toolEvent = {"type": "compaction_block", "content": summary["content"]}),
+ _sse({"content": " rest", "extra_content": native, "tool_calls": [call]}),
+ _sse(finish = "tool_calls"),
+ _DONE,
+ ],
+ [_sse({"content": "Done."}), _sse(finish = "stop"), _DONE],
+ ]
+ )
+ transport.sanitizes_provider_frames = True
+ _run(
+ transport,
+ messages = [
+ {"role": "user", "content": "question"},
+ {"role": "assistant", "content": "A partial"},
+ ],
+ continue_final_message = True,
+ )
+
+ follow_up = transport.requests[1]["messages"]
+ assert [message["role"] for message in follow_up] == ["assistant", "assistant", "tool"]
+ assert follow_up[0]["extra_content"]["anthropic"]["content"] == [summary]
+
+
def test_a_conversation_search_here_gets_the_active_branch(executed):
"""The provider loops share the local paths' tool catalogue.
diff --git a/studio/frontend/src/components/assistant-ui/compaction-notice.tsx b/studio/frontend/src/components/assistant-ui/compaction-notice.tsx
index 18125003041..b9782569e47 100644
--- a/studio/frontend/src/components/assistant-ui/compaction-notice.tsx
+++ b/studio/frontend/src/components/assistant-ui/compaction-notice.tsx
@@ -48,11 +48,15 @@ export const CompactionNotice: FC<{ truncation: ContextTruncation }> = ({
This conversation got long, so it was compacted.
</span>{" "}
<span>
- Older messages were dropped from the model&apos;s context to make room. {detail}
+ {truncation.summarized
+ ? "The provider summarized older messages to make room."
+ : "Older messages were dropped from the model's context to make room."}{" "}
+ {detail}
</span>
<span>
{" "}
- ({dropped} {dropped === 1 ? "message" : "messages"} dropped here
+ ({dropped} {dropped === 1 ? "message" : "messages"}{" "}
+ {truncation.summarized ? "summarized" : "dropped"} here
{recalled > 0
? `, ${recalled} earlier ${recalled === 1 ? "passage" : "passages"} recalled`
: ""}
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 618dada66ef..6de24c67f5d 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -176,6 +176,7 @@ import {
isContinuableContent,
isProviderReportedReason,
modeAllowsContinuation,
+ providerCompactionContinuationFields,
readContinuationSource,
readIncompleteInfo,
readTextThoughtSignature,
@@ -7506,6 +7507,7 @@ function useContinuation() {
partial,
...(carriedReasoning ? { reasoning: carriedReasoning, reasoningDuration } : {}),
...(thoughtSignature ? { thoughtSignature } : {}),
+ ...providerCompactionContinuationFields(metadata),
};
return aui.thread().startRun({
parentId: parent,
@@ -7513,7 +7515,15 @@ function useContinuation() {
custom: { [CONTINUATION_RUN_CONFIG_KEY]: request },
},
});
- }, [aui, messageId, partial, carriedReasoning, reasoningDuration, thoughtSignature]);
+ }, [
+ aui,
+ messageId,
+ partial,
+ carriedReasoning,
+ reasoningDuration,
+ thoughtSignature,
+ metadata,
+ ]);
return {
messageId,
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index e0e19483bd9..ce58c359274 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -110,6 +110,11 @@ import {
import { parseParamCountB } from "@/lib/model-size";
import { createLoadingToastIcon, toast } from "@/lib/toast";
import { notifyPromptQueueRunFailed } from "../utils/prompt-queue-boundary";
+import {
+ providerCompactionConnectionKey,
+ providerCompactionForTarget,
+ providerCompactionPart,
+} from "../utils/provider-compaction";
import {
adoptPreStreamRunReservation,
findPreStreamRunReservation,
@@ -118,7 +123,11 @@ import {
releasePreStreamRunReservation,
} from "../utils/pre-stream-run-reservation";
import { readThreadCreationClaim } from "../utils/chat-thread-creation-claim";
-import { ggufCompactionRequestFields } from "../utils/auto-compaction";
+import {
+ apiCompactionRequestFields,
+ ggufCompactionRequestFields,
+} from "../utils/auto-compaction";
+import { resolveModelCatalogEntry } from "../model-catalog";
import {
lengthIncompleteReason,
lengthStopCause,
@@ -154,6 +163,7 @@ import {
providerModelTakesMcpImages,
supportsProviderPromptCacheTtl,
supportsProviderPromptCaching,
+ toExternalBackendProviderType,
} from "../external-providers";
import {
@@ -270,6 +280,7 @@ import type {
OpenAIChatMessage,
OpenAIMessageContent,
OpenAIReasoningContentPart,
+ ProviderCompactionContentPart,
} from "../types/api";
import { modelReadsSamplingSeed, type ChatModelRow } from "../types/runtime";
import { loadFallbackNotice } from "../utils/mmproj-fallback";
@@ -1274,6 +1285,63 @@ function setAssistantOpenAIResponsesReasoning(
message.extra_content = { ...extra, openai_responses_reasoning: reasoning };
}
+function providerCompactionAssistant(
+ messages: SerializedMessage[],
+ afterToolCalls: number,
+): SerializedMessage | undefined {
+ const boundary =
+ Number.isInteger(afterToolCalls) && afterToolCalls >= 0
+ ? afterToolCalls
+ : 0;
+ let precedingToolCalls = 0;
+ let lastAssistant: SerializedMessage | undefined;
+ for (const message of messages) {
+ if (message.role !== "assistant") continue;
+ lastAssistant = message;
+ if (precedingToolCalls >= boundary) return message;
+ precedingToolCalls += message.tool_calls?.length ?? 0;
+ }
+ return lastAssistant;
+}
+
+/** The provider drops what came before its compaction, so it leads the subturn that produced it. */
+function withProviderCompaction(
+ message: RunMessage,
+ serialized: SerializedMessage[],
+ target: {
+ providerType: string | undefined;
+ modelId: string | undefined;
+ connectionKey: string | undefined;
+ },
+): SerializedMessage[] {
+ const custom = (
+ message as { metadata?: { custom?: Record<string, unknown> } }
+ ).metadata?.custom;
+ const compaction = providerCompactionForTarget(
+ custom,
+ target.providerType,
+ target.modelId,
+ target.connectionKey,
+ );
+ const assistant = providerCompactionAssistant(
+ serialized,
+ typeof custom?.providerCompactionAfterToolCalls === "number"
+ ? custom.providerCompactionAfterToolCalls
+ : 0,
+ );
+ if (!compaction || !assistant) return serialized;
+ const content = assistant.content;
+ assistant.content = [
+ compaction,
+ ...(typeof content === "string"
+ ? content
+ ? [{ type: "text" as const, text: content }]
+ : []
+ : (content ?? [])),
+ ];
+ return serialized;
+}
+
function attachAssistantThoughtSignature(
messages: SerializedMessage[],
thoughtSignature: string | undefined,
@@ -4895,6 +4963,12 @@ export function createOpenAIStreamAdapter(
}
const externalProvider =
externalRouting.kind === "external" ? externalRouting.provider : null;
+ const providerCompactionTargetConnectionKey =
+ providerCompactionConnectionKey(
+ externalProvider?.id,
+ externalProvider?.baseUrl,
+ externalProvider?.apiType,
+ );
const externalUsesStudioTools =
providerModelSupportsStudioTools(
@@ -5021,7 +5095,18 @@ export function createOpenAIStreamAdapter(
// toOpenAIMessages emits assistant tool_calls plus role="tool" follow-ups; the backend Gemini
// translator rebuilds the functionCall/functionResponse parts.
let outboundMessages = renderedMessages
- .flatMap((message) => toOpenAIMessages(message, replayReasoning))
+ .flatMap((message) => {
+ const serialized = toOpenAIMessages(message, replayReasoning);
+ return isExternalRequest
+ ? withProviderCompaction(message, serialized, {
+ providerType: toExternalBackendProviderType(
+ externalProvider?.providerType,
+ ),
+ modelId: externalSelection?.modelId,
+ connectionKey: providerCompactionTargetConnectionKey,
+ })
+ : serialized;
+ })
.filter((message): message is NonNullable<typeof message> =>
Boolean(message),
);
@@ -5072,11 +5157,26 @@ export function createOpenAIStreamAdapter(
});
throw new Error("A response that stopped mid-thought cannot be resumed here.");
}
+ const continuationCompaction = continuation
+ ? providerCompactionForTarget(
+ continuation,
+ toExternalBackendProviderType(externalProvider?.providerType),
+ externalSelection?.modelId,
+ providerCompactionTargetConnectionKey,
+ )
+ : null;
// The run's messages stop at the user turn, so the partial is appended here for the backend to resume.
if (continuation) {
outboundMessages.push({
role: "assistant",
- content: continuation.partial,
+ content: continuationCompaction
+ ? [
+ continuationCompaction,
+ ...(continuation.partial
+ ? [{ type: "text" as const, text: continuation.partial }]
+ : []),
+ ]
+ : continuation.partial,
...(resumedThought ? { reasoning_content: resumedThought } : {}),
});
// The original assistant message is not in this branch, so without its signature the history
@@ -5548,6 +5648,24 @@ export function createOpenAIStreamAdapter(
};
let codexRoundToolCallIds: string[] = [];
let contextTruncation: OpenAIChatChunk["context_truncated"];
+ let providerCompaction: ProviderCompactionContentPart | undefined =
+ continuationCompaction ?? undefined;
+ let providerCompactionAfterToolCalls: number | undefined =
+ continuationCompaction
+ ? continuation?.providerCompactionAfterToolCalls
+ : undefined;
+ let providerCompactionProviderType: string | undefined =
+ continuationCompaction
+ ? continuation?.providerCompactionProviderType
+ : undefined;
+ let providerCompactionModelId: string | undefined =
+ continuationCompaction
+ ? continuation?.providerCompactionModelId
+ : undefined;
+ let providerCompactionOriginConnectionKey: string | undefined =
+ continuationCompaction
+ ? continuation?.providerCompactionConnectionKey
+ : undefined;
const liveAssistantContent = () =>
buildAssistantContent(mergeContinuation(cumulativeText));
@@ -5561,6 +5679,11 @@ export function createOpenAIStreamAdapter(
openaiCodexReasoning: codexReasoningLedger,
openaiResponsesReasoning: openAIResponsesReasoningLedger,
contextTruncation,
+ providerCompaction,
+ providerCompactionAfterToolCalls,
+ providerCompactionProviderType,
+ providerCompactionModelId,
+ providerCompactionConnectionKey: providerCompactionOriginConnectionKey,
// A legacy (browser-tool / attachment / incognito) run that ends because you closed the tab has no
// server-side run to resume from, so its last streamed yield is what persists. Mark it an interruption
// — partial kept + Resume — instead of a silent blank/ambiguous state. Durable runs keep "cancelled":
@@ -6504,6 +6627,13 @@ export function createOpenAIStreamAdapter(
},
{ forceRefreshPublicKey },
)),
+ ...apiCompactionRequestFields({
+ autoCompactEnabled: runtime.autoCompactEnabled,
+ contextLength: resolveModelCatalogEntry(
+ externalProvider.providerType,
+ externalModelId,
+ )?.contextLength,
+ }),
// On every external request: OpenRouter's cache routing, and the prompt date unless Claude caches.
...(resolvedThreadId ? { thread_id: resolvedThreadId } : {}),
...(openaiCodeExecContainerId
@@ -6891,8 +7021,11 @@ export function createOpenAIStreamAdapter(
? "It got long, so older turns were removed from the model's " +
"context. They are saved and searchable, and relevant parts are " +
"brought back automatically."
- : "The full conversation is still visible and saved. " +
- "Unsloth removed complete older turns from this request so the chat can continue.",
+ : contextTruncation?.summarized
+ ? "The full conversation is still visible and saved. " +
+ "The provider summarized older turns so the chat can continue."
+ : "The full conversation is still visible and saved. " +
+ "Unsloth removed complete older turns from this request so the chat can continue.",
duration: 8000,
});
}
@@ -6965,6 +7098,28 @@ export function createOpenAIStreamAdapter(
}
continue;
}
+ if (toolEvent.type === "compaction_block") {
+ const nextCompaction = providerCompactionPart(toolEvent);
+ if (nextCompaction) {
+ providerCompaction = nextCompaction;
+ providerCompactionProviderType =
+ toExternalBackendProviderType(
+ externalProvider?.providerType,
+ );
+ providerCompactionModelId = externalSelection?.modelId;
+ providerCompactionOriginConnectionKey =
+ providerCompactionTargetConnectionKey;
+ // Compaction items arrive before the provider content they introduce. Remember
+ // how much of this stored run preceded it so replay does not put a later marker
+ // ahead of earlier Studio tool rounds that the marker already summarizes.
+ providerCompactionAfterToolCalls = toolCallParts.filter(
+ (part) =>
+ part.toolName !== "studio_load_skill" &&
+ toolCallPartSurvivesOpenAIReplay(part),
+ ).length;
+ }
+ continue;
+ }
if (toolEvent.type === "document_citations") {
// Convert citations_delta footnotes into Sources entries matching the inline [N] markers.
const cits = toolEvent.citations;
@@ -8286,6 +8441,12 @@ export function createOpenAIStreamAdapter(
openaiCodexReasoning: codexReasoningLedger,
openaiResponsesReasoning: openAIResponsesReasoningLedger,
contextTruncation,
+ providerCompaction,
+ providerCompactionAfterToolCalls,
+ providerCompactionProviderType,
+ providerCompactionModelId,
+ providerCompactionConnectionKey:
+ providerCompactionOriginConnectionKey,
incomplete: finalIncompleteReason
? { reason: finalIncompleteReason }
: undefined,
@@ -8455,6 +8616,12 @@ export function createOpenAIStreamAdapter(
custom: {
...reasoningDurationTracker.metadata(),
contextTruncation,
+ providerCompaction,
+ providerCompactionAfterToolCalls,
+ providerCompactionProviderType,
+ providerCompactionModelId,
+ providerCompactionConnectionKey:
+ providerCompactionOriginConnectionKey,
// Unfinished too, so it also offers Continue -- unless the provider already
// said why the model stopped.
incomplete: {
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 04856a48742..fb5741d0e87 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -173,6 +173,7 @@ import {
reconcileOrdinarySavedMessagesInView,
} from "./utils/saved-history-reconciliation";
import { createGenerationToolRecovery } from "./utils/generation-tool-recovery";
+import { providerCompactionConnectionKey } from "./utils/provider-compaction";
import { mergeContextTruncation } from "./utils/context-truncation";
import { registerLiveThreadView } from "./utils/live-thread-head";
import {
@@ -1539,8 +1540,11 @@ function scheduleGenerationRecovery(
}
// Replay from 0 re-delivers already-saved chunks: apply them, but publish nothing.
let advanced = false;
+ let recoveredProviderCompaction: ReturnType<
+ typeof toolRecovery.apply
+ >;
if (update.event?.type === "chunk") {
- toolRecovery.apply(
+ recoveredProviderCompaction = toolRecovery.apply(
update.event.payload,
raw.length,
update.event.seq,
@@ -1597,6 +1601,30 @@ function scheduleGenerationRecovery(
),
};
}
+ if (recoveredProviderCompaction) {
+ const sourceProviderType = update.run.requestPayload.provider_type;
+ const sourceModelId =
+ update.run.requestPayload.external_model ??
+ update.run.requestPayload.model;
+ currentMetadata = {
+ ...currentMetadata,
+ ...recoveredProviderCompaction,
+ providerCompactionProviderType:
+ typeof sourceProviderType === "string"
+ ? sourceProviderType
+ : undefined,
+ providerCompactionModelId:
+ typeof sourceModelId === "string"
+ ? sourceModelId
+ : undefined,
+ providerCompactionConnectionKey:
+ providerCompactionConnectionKey(
+ update.run.requestPayload.provider_id,
+ update.run.requestPayload.provider_base_url,
+ update.run.requestPayload.provider_api_type,
+ ),
+ };
+ }
if (chunk.quote_cut === true) quoteCut = true;
if (chunk.usage) recoveryUsage = chunk.usage;
if (chunk.timings) recoveryTimings = chunk.timings;
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index 1984ec21f4c..9b707c75b19 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -619,17 +619,22 @@ export type OpenAIImageGenerationCallContentPart = {
response_id?: string;
};
+export type ProviderCompactionContentPart = {
+ type: "compaction";
+ content?: string;
+ encrypted_content?: string;
+};
+
export type OpenAIMessageContentPart =
| { type: "text"; text: string }
| { type: "image_url"; image_url: { url: string } }
| OpenAIReasoningContentPart
- | OpenAIImageGenerationCallContentPart;
+ | OpenAIImageGenerationCallContentPart
+ | ProviderCompactionContentPart;
export type OpenAIMessageContent = string | OpenAIMessageContentPart[];
-/** OpenAI Chat Completions tool_call shape. Assistant turns echo function calls as `tool_calls`;
- * the matching result rides on a separate `role="tool"` message keyed by `tool_call_id`.
- * `extra_content.google.thought_signature` is the Gemini round-trip field. */
+/** OpenAI tool_calls pair by tool_call_id; Gemini uses extra_content.google.thought_signature */
export interface OpenAIToolCallPart {
id?: string;
type?: "function";
@@ -799,30 +804,23 @@ export interface OpenAIChatChunk {
// the problem.
irreducible_tokens?: number;
latest_turn_tokens?: number;
- // Whether `latest_turn_tokens` is a real count or the four-characters-a-token estimate the fit
- // falls back to. Only the counted one may be quoted as the turn's size.
+ // true when latest_turn_tokens is counted rather than estimated at four characters per token
latest_turn_exact?: boolean;
- // The floor both counts above carry: what a rendered prompt costs with no messages, which on a
- // tool-enabled request is the whole tool catalogue. Subtract it before comparing them, or the
- // catalogue is blamed on the turn.
+ // subtract message-free prompt cost so tools are not charged to the turn
shared_prompt_tokens?: number;
- // Where the compaction boundary sits in the messages THIS request was sent with. Absolute, unlike
- // dropped_messages, so re-sending it after a turn that refit several times cannot advance the
- // boundary past the turns actually evicted.
+ // absolute request boundary prevents repeated refits from advancing past evicted turns
boundary_messages?: number;
- // True when this fit started a new checkpoint, including within the current tool loop.
+ // true when this fit started a checkpoint, including inside the current tool loop
checkpoint_started?: boolean;
- // The text the boundary landed ON, so the count can be re-derived by position: a count is only
- // valid against the transcript it was counted on, and deleting an already evicted prompt
- // shortens that transcript.
+ // true when the provider summarized earlier turns instead of Unsloth dropping them
+ summarized?: boolean;
+ // boundary text lets the count be re-derived after deleting an already evicted prompt
boundary_anchor?: string;
- // How much extra trim the fit that set the boundary used. Replayed against the request's own
- // ratio, so a boundary cut under more headroom than the caller now asks for is discarded.
+ // discard a replayed boundary when its trim used more headroom than the current request
boundary_headroom_ratio?: number;
- // Whose message that is: in a tool loop the last one is often a tool result rather than anything the user typed.
+ // the latest tool-loop message may be a tool result rather than a user message
latest_turn_role?: string;
- // The prompt's share of the window (context_length minus the reply reserve), which is what one turn
- // must fit inside. Not re-derived here: the formula lives in the fit.
+ // prompt share of context_length after the reply reserve, calculated by the fit
prompt_target?: number;
};
}
diff --git a/studio/frontend/src/features/chat/utils/auto-compaction.ts b/studio/frontend/src/features/chat/utils/auto-compaction.ts
index 327bcf50c28..56719b2fceb 100644
--- a/studio/frontend/src/features/chat/utils/auto-compaction.ts
+++ b/studio/frontend/src/features/chat/utils/auto-compaction.ts
@@ -19,10 +19,34 @@ export function ggufCompactionRequestFields(options: {
} {
if (!options.isGguf && !options.isMlx) return {};
if (!options.autoCompactEnabled) {
- // An omitted field falls back to UNSLOTH_CONTEXT_OVERFLOW, which may still compact. "error" is an
- // explicit refusal of that fallback.
+ // explicit error avoids the UNSLOTH_CONTEXT_OVERFLOW fallback, which may compact
return { context_overflow: "error" };
}
- // No context_policy: the server applies UNSLOTH_CONTEXT_POLICY.
+ // omit context_policy so the server applies UNSLOTH_CONTEXT_POLICY
return { context_overflow: "truncate_oldest" };
}
+
+// Share of the window left free when compaction starts.
+const API_COMPACTION_HEADROOM = 0.25;
+// request schema ceiling for compaction_threshold
+const API_COMPACTION_THRESHOLD_MAX = 2_000_000;
+
+export function apiCompactionRequestFields(options: {
+ autoCompactEnabled: boolean;
+ contextLength: number | null | undefined;
+}): {
+ context_overflow?: "truncate_oldest";
+ compaction_threshold?: number;
+ context_window?: number;
+} {
+ const { autoCompactEnabled, contextLength } = options;
+ if (!autoCompactEnabled || !contextLength || contextLength <= 0) return {};
+ return {
+ context_overflow: "truncate_oldest",
+ compaction_threshold: Math.min(
+ API_COMPACTION_THRESHOLD_MAX,
+ Math.floor(contextLength * (1 - API_COMPACTION_HEADROOM)),
+ ),
+ context_window: contextLength,
+ };
+}
diff --git a/studio/frontend/src/features/chat/utils/continuation.ts b/studio/frontend/src/features/chat/utils/continuation.ts
index 6a1f612dc17..d34835f4f65 100644
--- a/studio/frontend/src/features/chat/utils/continuation.ts
+++ b/studio/frontend/src/features/chat/utils/continuation.ts
@@ -1,6 +1,9 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import type { ProviderCompactionContentPart } from "../types/api";
+import { providerCompactionPart } from "./provider-compaction.ts";
+
/** Resuming a response that stopped early (`length`, `cancelled`, `interrupted`): the conversation is re-sent
* with the partial as the final assistant turn plus `continue_final_message`, so the prompt ends mid-sentence
* and the new text is appended to the partial. */
@@ -377,8 +380,68 @@ export type ContinuationRequest = {
/** Gemini text-part thoughtSignature from the turn being resumed: the sibling run drops the
* original assistant message, so replaying it here keeps the history signed. */
thoughtSignature?: string;
+ providerCompaction?: ProviderCompactionContentPart;
+ providerCompactionAfterToolCalls?: number;
+ providerCompactionProviderType?: string;
+ providerCompactionModelId?: string;
+ providerCompactionConnectionKey?: string;
};
+type ProviderCompactionContinuationFields = Pick<
+ Required<ContinuationRequest>,
+ | "providerCompaction"
+ | "providerCompactionAfterToolCalls"
+ | "providerCompactionProviderType"
+ | "providerCompactionModelId"
+ | "providerCompactionConnectionKey"
+>;
+
+function providerCompactionFields(
+ value: unknown,
+): ProviderCompactionContinuationFields | Record<string, never> {
+ const fields = value as
+ | {
+ providerCompaction?: unknown;
+ providerCompactionAfterToolCalls?: unknown;
+ providerCompactionProviderType?: unknown;
+ providerCompactionModelId?: unknown;
+ providerCompactionConnectionKey?: unknown;
+ }
+ | undefined;
+ const compaction = providerCompactionPart(fields?.providerCompaction);
+ const boundary = fields?.providerCompactionAfterToolCalls;
+ const providerType = fields?.providerCompactionProviderType;
+ const modelId = fields?.providerCompactionModelId;
+ const connectionKey = fields?.providerCompactionConnectionKey;
+ if (
+ !compaction ||
+ !Number.isInteger(boundary) ||
+ (boundary as number) < 0 ||
+ typeof providerType !== "string" ||
+ !providerType ||
+ typeof modelId !== "string" ||
+ !modelId ||
+ typeof connectionKey !== "string" ||
+ !connectionKey
+ ) {
+ return {};
+ }
+ return {
+ providerCompaction: compaction,
+ providerCompactionAfterToolCalls: boundary as number,
+ providerCompactionProviderType: providerType,
+ providerCompactionModelId: modelId,
+ providerCompactionConnectionKey: connectionKey,
+ };
+}
+
+export function providerCompactionContinuationFields(
+ metadata: unknown,
+): ProviderCompactionContinuationFields | Record<string, never> {
+ const custom = (metadata as { custom?: unknown } | undefined)?.custom;
+ return providerCompactionFields(custom);
+}
+
/** Read a continuation request out of a run's `runConfig`, if it is one. */
export function readContinuationRequest(
runConfig: unknown,
@@ -391,6 +454,11 @@ export function readContinuationRequest(
reasoning?: unknown;
reasoningDuration?: unknown;
thoughtSignature?: unknown;
+ providerCompaction?: unknown;
+ providerCompactionAfterToolCalls?: unknown;
+ providerCompactionProviderType?: unknown;
+ providerCompactionModelId?: unknown;
+ providerCompactionConnectionKey?: unknown;
}
| undefined;
const partial = typeof request?.partial === "string" ? request.partial : "";
@@ -415,6 +483,7 @@ export function readContinuationRequest(
...(typeof signature === "string" && signature
? { thoughtSignature: signature }
: {}),
+ ...providerCompactionFields(request),
};
}
diff --git a/studio/frontend/src/features/chat/utils/generation-tool-recovery.ts b/studio/frontend/src/features/chat/utils/generation-tool-recovery.ts
index 807eda5f61e..ca663de330a 100644
--- a/studio/frontend/src/features/chat/utils/generation-tool-recovery.ts
+++ b/studio/frontend/src/features/chat/utils/generation-tool-recovery.ts
@@ -25,6 +25,10 @@ import {
} from "./document-citation-source";
import { mergeGoogleNativeParts } from "./google-native-parts";
import { extractMcpUiEnvelope } from "../mcp-apps/mcp-ui";
+import {
+ providerCompactionPart,
+ providerCompactionReplayToolCallCount,
+} from "./provider-compaction";
function record(value: unknown): Record<string, unknown> | undefined {
return value !== null && typeof value === "object" && !Array.isArray(value)
@@ -364,12 +368,24 @@ export function createGenerationToolRecovery(
if (
event?.type !== "tool_start" &&
event?.type !== "tool_end" &&
- event?.type !== "document_citations"
+ event?.type !== "document_citations" &&
+ event?.type !== "compaction_block"
) {
return;
}
if (seq <= appliedSeq) return;
appliedSeq = seq;
+ if (event.type === "compaction_block") {
+ const providerCompaction = providerCompactionPart(event);
+ if (!providerCompaction) return;
+ return {
+ providerCompaction,
+ providerCompactionAfterToolCalls:
+ providerCompactionReplayToolCallCount(
+ carried.map((entry) => entry.part),
+ ),
+ };
+ }
const backendId =
typeof event.tool_call_id === "string" ? event.tool_call_id : "";
if (event.tool_name === "deep_research") {
diff --git a/studio/frontend/src/features/chat/utils/provider-compaction.ts b/studio/frontend/src/features/chat/utils/provider-compaction.ts
new file mode 100644
index 00000000000..4e92425991b
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/provider-compaction.ts
@@ -0,0 +1,117 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { ProviderCompactionContentPart } from "../types/api";
+
+const SERVER_SIDE_BUILTIN_TOOL_NAMES = new Set([
+ "web_search",
+ "web_fetch",
+ "code_execution",
+ "image_generation",
+]);
+
+function record(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : null;
+}
+
+/** Opaque, stable identity for one saved connection at one endpoint. The endpoint itself stays out of message
+ * metadata, while a provider edit changes the key and invalidates provider-owned compaction state. */
+export function providerCompactionConnectionKey(
+ providerId: unknown,
+ baseUrl: unknown,
+ apiType: unknown,
+): string | undefined {
+ if (typeof providerId !== "string" || !providerId) return undefined;
+ const identity = JSON.stringify([
+ providerId,
+ typeof baseUrl === "string" ? baseUrl.trim() : "",
+ typeof apiType === "string" && apiType ? apiType : "chat_completions",
+ ]);
+ let hash = 14_695_981_039_346_656_037n;
+ for (let index = 0; index < identity.length; index += 1) {
+ hash ^= BigInt(identity.charCodeAt(index));
+ hash = BigInt.asUintN(64, hash * 1_099_511_628_211n);
+ }
+ return `v1:${hash.toString(16).padStart(16, "0")}`;
+}
+
+export function providerCompactionPart(
+ value: unknown,
+): ProviderCompactionContentPart | null {
+ if (!value || typeof value !== "object") return null;
+ const { content, encrypted_content } = value as Record<string, unknown>;
+ const compaction: ProviderCompactionContentPart = { type: "compaction" };
+ if (typeof content === "string" && content) {
+ compaction.content = content;
+ }
+ if (typeof encrypted_content === "string" && encrypted_content) {
+ compaction.encrypted_content = encrypted_content;
+ }
+ return compaction.content || compaction.encrypted_content ? compaction : null;
+}
+
+function providerCompactionMatchesTarget(
+ metadata: unknown,
+ providerType: string | undefined,
+ modelId: string | undefined,
+ connectionKey: string | undefined,
+): boolean {
+ const custom = record(metadata);
+ return (
+ typeof providerType === "string" &&
+ typeof modelId === "string" &&
+ typeof connectionKey === "string" &&
+ custom?.providerCompactionProviderType === providerType &&
+ custom.providerCompactionModelId === modelId &&
+ custom.providerCompactionConnectionKey === connectionKey
+ );
+}
+
+export function providerCompactionForTarget(
+ metadata: unknown,
+ providerType: string | undefined,
+ modelId: string | undefined,
+ connectionKey: string | undefined,
+): ProviderCompactionContentPart | null {
+ if (
+ !providerCompactionMatchesTarget(
+ metadata,
+ providerType,
+ modelId,
+ connectionKey,
+ )
+ ) {
+ return null;
+ }
+ return providerCompactionPart(record(metadata)?.providerCompaction);
+}
+
+/** Count only persisted calls that the OpenAI replay serializer will retain. */
+export function providerCompactionReplayToolCallCount(
+ values: readonly unknown[],
+): number {
+ return values.reduce<number>((count, value) => {
+ const part = record(value);
+ if (part?.type !== "tool-call" || part.toolName === "studio_load_skill") {
+ return count;
+ }
+
+ const args = record(part.args);
+ const google = record(args?.google);
+ const nativePart = google?.native_part;
+ const hasNativePart =
+ typeof nativePart === "object" && nativePart !== null;
+ const toolName =
+ typeof part.toolName === "string" ? part.toolName.toLowerCase() : "";
+ const isServerSideBuiltin =
+ SERVER_SIDE_BUILTIN_TOOL_NAMES.has(toolName) &&
+ (args?._server_tool === true || hasNativePart);
+
+ // Provider-hosted cards without a native Gemini part serialize to no assistant call.
+ // Native cards need no role=tool result; ordinary calls do.
+ if (isServerSideBuiltin) return hasNativePart ? count + 1 : count;
+ return part.result !== undefined && part.result !== null ? count + 1 : count;
+ }, 0);
+}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 4f478aa1505..1d6f0fdec1e 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -2234,7 +2234,7 @@ export const ar = {
rememberParamsPerModelHint:
"عند إيقافه، تستخدم جميع النماذج الإعدادات نفسها.",
autoCompactHint:
- "لمحادثات GGUF و MLX المحلية فقط. تُفهرس الأدوار التي تخرج من السياق ليتمكن النموذج من البحث عنها لاحقًا، ومع إعادة التعيين يُقتبس ما يتّسع من تعليماتك الدائمة بنصه الحرفي، مع تفضيل الأقدم والأحدث على ما بينهما. تتطلب الأرشفة محادثة محفوظة وفهرسًا متجهيًا؛ وبدونهما تُحذف الأدوار الأقدم. يعتمد على طول السياق الذي حددته، لا على ذاكرة VRAM المتاحة.",
+ "لمحادثات GGUF و MLX المحلية: تُفهرس الأدوار التي تخرج من السياق ليتمكن النموذج من البحث عنها لاحقًا، ومع إعادة التعيين يُقتبس ما يتّسع من تعليماتك الدائمة بنصه الحرفي، مع تفضيل الأقدم والأحدث على ما بينهما. تتطلب الأرشفة محادثة محفوظة وفهرسًا متجهيًا؛ وبدونهما تُحذف الأدوار الأقدم. يعتمد على طول السياق الذي حددته، لا على ذاكرة VRAM المتاحة. نماذج API: يلخّص المزوّد الأدوار الأقدم حيث يدعم ذلك، وإلا تُحذف الأدوار الأقدم عند اقتراب المحادثة من نافذة سياق النموذج المنشورة.",
pastedTextShortDescription:
"يصبح النص الملصق الذي يبلغ {count} حرفًا أو أكثر مرفقًا بصيغة .txt. يبقى النص الأقصر في مربع الرسالة.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 22d7f608462..c4a8b2a86f4 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -2272,7 +2272,7 @@ export const de = {
rememberParamsPerModelHint:
"Wenn deaktiviert, verwenden alle Modelle dieselben Einstellungen.",
autoCompactHint:
- "Nur lokale GGUF- und MLX-Chats. Verdrängte Runden werden indexiert, sodass das Modell sie zurückholen kann, und ein Reset zitiert die dauerhaft geltenden Anweisungen, die hineinpassen, wortgetreu und mit Vorrang für die ältesten und neuesten vor allem dazwischen. Archivieren setzt einen gespeicherten Chat und den Vektorindex voraus; ohne sie werden ältere Runden verworfen. Verwendet die eingestellte Kontextlänge, nicht den verfügbaren VRAM.",
+ "Lokale GGUF- und MLX-Chats: Verdrängte Runden werden indexiert, sodass das Modell sie zurückholen kann, und ein Reset zitiert die dauerhaft geltenden Anweisungen, die hineinpassen, wortgetreu und mit Vorrang für die ältesten und neuesten vor allem dazwischen. Archivieren setzt einen gespeicherten Chat und den Vektorindex voraus; ohne sie werden ältere Runden verworfen. Verwendet die eingestellte Kontextlänge, nicht den verfügbaren VRAM. API-Modelle: Der Anbieter fasst ältere Runden zusammen, wo er das unterstützt, sonst werden die ältesten Runden verworfen, sobald der Chat das veröffentlichte Kontextfenster des Modells erreicht.",
pastedTextShortDescription:
"Eingefügter Text ab {count} Zeichen wird als .txt-Datei angehängt. Kürzerer Text bleibt im Nachrichtenfeld.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index a1b196f5b39..3aa8316979d 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -2271,7 +2271,7 @@ export const en = {
"Override this setting from each chat's attachment menu.",
rememberParamsPerModelHint:
"When off, use the same settings for every model.",
- autoCompactHint: "Local GGUF and MLX chats only. Evicted turns are indexed so the model can search them back in, and a reset quotes back the standing instructions that fit, word for word, keeping the oldest and newest over the middle. Archiving needs a saved chat and the vector index; without them older turns are dropped. Uses the context length you set, not available VRAM.",
+ autoCompactHint: "Local GGUF and MLX chats: evicted turns are indexed so the model can search them back in, and a reset quotes back the standing instructions that fit, word for word, keeping the oldest and newest over the middle. Archiving needs a saved chat and the vector index; without them older turns are dropped. Uses the context length you set, not available VRAM. API models: the provider summarizes older turns where it can, otherwise the oldest turns are dropped as the chat nears the model's published context window.",
pastedTextShortDescription:
"Pastes of {count} characters or more become .txt attachments.",
pastedTextOffDescription: "Pasted text always stays in the message box.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 97ea8330d45..5385e3a03d7 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -2263,7 +2263,7 @@ export const es = {
rememberParamsPerModelHint:
"Al desactivarlo, todos los modelos usan los mismos ajustes.",
autoCompactHint:
- "Solo chats GGUF y MLX locales. Los turnos expulsados se indexan para que el modelo pueda recuperarlos, y un reinicio cita palabra por palabra las instrucciones permanentes que quepan, dando prioridad a las más antiguas y a las más recientes frente a las intermedias. Archivar requiere un chat guardado y el índice vectorial; sin ellos, los turnos antiguos se descartan. Usa la longitud de contexto configurada, no la VRAM disponible.",
+ "Chats GGUF y MLX locales: Los turnos expulsados se indexan para que el modelo pueda recuperarlos, y un reinicio cita palabra por palabra las instrucciones permanentes que quepan, dando prioridad a las más antiguas y a las más recientes frente a las intermedias. Archivar requiere un chat guardado y el índice vectorial; sin ellos, los turnos antiguos se descartan. Usa la longitud de contexto configurada, no la VRAM disponible. Modelos de API: el proveedor resume los turnos antiguos cuando lo admite; si no, se descartan los más antiguos cuando el chat se acerca a la ventana de contexto publicada del modelo.",
pastedTextShortDescription:
"El texto pegado de {count} caracteres o más se convierte en un adjunto .txt. El texto más corto queda en el cuadro de mensaje.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 29cd958f044..0f6d712b05a 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -2269,7 +2269,7 @@ export const fr = {
rememberParamsPerModelHint:
"Lorsque cette option est désactivée, tous les modèles utilisent les mêmes réglages.",
autoCompactHint:
- "Uniquement les chats GGUF et MLX locaux. Les échanges évincés sont indexés pour que le modèle puisse les retrouver, et une réinitialisation cite mot pour mot les instructions permanentes qui tiennent, en gardant les plus anciennes et les plus récentes plutôt que celles du milieu. L’archivage nécessite un chat enregistré et l’index vectoriel ; sans eux, les anciens échanges sont supprimés. Utilise la longueur de contexte définie, pas la VRAM disponible.",
+ "Chats GGUF et MLX locaux : Les échanges évincés sont indexés pour que le modèle puisse les retrouver, et une réinitialisation cite mot pour mot les instructions permanentes qui tiennent, en gardant les plus anciennes et les plus récentes plutôt que celles du milieu. L’archivage nécessite un chat enregistré et l’index vectoriel ; sans eux, les anciens échanges sont supprimés. Utilise la longueur de contexte définie, pas la VRAM disponible. Modèles d’API : le fournisseur résume les anciens échanges quand il le permet ; sinon, les plus anciens sont supprimés lorsque le chat approche de la fenêtre de contexte publiée du modèle.",
pastedTextShortDescription:
"Le texte collé de {count} caractères ou plus devient une pièce jointe .txt. Le texte plus court reste dans le champ de message.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 25c0bba8137..ecbbf490384 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -2240,7 +2240,7 @@ export const hi = {
rememberParamsPerModelHint:
"बंद होने पर सभी मॉडल एक ही सेटिंग इस्तेमाल करते हैं।",
autoCompactHint:
- "केवल लोकल GGUF और MLX चैट पर लागू। हटाए गए टर्न इंडेक्स किए जाते हैं ताकि मॉडल उन्हें दोबारा खोज सके, और रीसेट पर जितने स्थायी निर्देश समा सकें, वे हूबहू दोहरा दिए जाते हैं, जिनमें बीच वाले के बजाय सबसे पुराने और सबसे नए को प्राथमिकता मिलती है। आर्काइव के लिए सहेजी गई चैट और वेक्टर इंडेक्स ज़रूरी हैं; इनके बिना पुराने टर्न हटा दिए जाते हैं। उपलब्ध VRAM के बजाय आपके तय किए गए संदर्भ की लंबाई का उपयोग करता है।",
+ "लोकल GGUF और MLX चैट: हटाए गए टर्न इंडेक्स किए जाते हैं ताकि मॉडल उन्हें दोबारा खोज सके, और रीसेट पर जितने स्थायी निर्देश समा सकें, वे हूबहू दोहरा दिए जाते हैं, जिनमें बीच वाले के बजाय सबसे पुराने और सबसे नए को प्राथमिकता मिलती है। आर्काइव के लिए सहेजी गई चैट और वेक्टर इंडेक्स ज़रूरी हैं; इनके बिना पुराने टर्न हटा दिए जाते हैं। उपलब्ध VRAM के बजाय आपके तय किए गए संदर्भ की लंबाई का उपयोग करता है। API मॉडल: जहाँ प्रदाता समर्थन करता है वहाँ वह पुराने टर्न का सारांश बनाता है, अन्यथा चैट के मॉडल की प्रकाशित संदर्भ विंडो के करीब पहुँचने पर सबसे पुराने टर्न हटा दिए जाते हैं।",
pastedTextShortDescription:
"{count} या अधिक अक्षरों वाला पेस्ट किया गया टेक्स्ट .txt अटैचमेंट बन जाता है। छोटा टेक्स्ट संदेश बॉक्स में रहता है।",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 332896f929a..165ef23cd77 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -2228,7 +2228,7 @@ export const it = {
rememberParamsPerModelHint:
"Quando è disattivata, tutti i modelli usano le stesse impostazioni.",
autoCompactHint:
- "Solo chat GGUF e MLX locali. I turni rimossi vengono indicizzati perché il modello possa recuperarli, e un ripristino cita parola per parola le istruzioni permanenti che rientrano, privilegiando le più vecchie e le più recenti rispetto a quelle intermedie. L’archiviazione richiede una chat salvata e l’indice vettoriale; senza di essi i turni più vecchi vengono eliminati. Usa la lunghezza del contesto impostata, non la VRAM disponibile.",
+ "Chat GGUF e MLX locali: I turni rimossi vengono indicizzati perché il modello possa recuperarli, e un ripristino cita parola per parola le istruzioni permanenti che rientrano, privilegiando le più vecchie e le più recenti rispetto a quelle intermedie. L’archiviazione richiede una chat salvata e l’indice vettoriale; senza di essi i turni più vecchi vengono eliminati. Usa la lunghezza del contesto impostata, non la VRAM disponibile. Modelli API: il provider riassume i turni più vecchi quando lo supporta, altrimenti i più vecchi vengono eliminati quando la chat si avvicina alla finestra di contesto pubblicata del modello.",
pastedTextShortDescription:
"Il testo incollato di almeno {count} caratteri diventa un allegato .txt. Il testo più breve resta nel campo del messaggio.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index ac9ba9101e3..e1bc14147f4 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -2219,7 +2219,7 @@ export const ja = {
projectAttachmentsHint: "各チャットの添付メニューで個別に変更できます。",
rememberParamsPerModelHint:
"オフの場合、すべてのモデルで同じ設定を使います。",
- autoCompactHint: "ローカルの GGUF と MLX チャットのみ。文脈から外れたターンは索引化され、モデルが検索して取り出せます。リセットでは、収まる範囲の継続的な指示がそのままの文言で引き継がれ、途中のものより最も古いものと最も新しいものが優先されます。アーカイブには保存済みのチャットとベクトル索引が必要で、それらがない場合、古いターンは破棄されます。空きVRAMではなく、設定したコンテキスト長を基準にします。",
+ autoCompactHint: "ローカルの GGUF と MLX チャット:文脈から外れたターンは索引化され、モデルが検索して取り出せます。リセットでは、収まる範囲の継続的な指示がそのままの文言で引き継がれ、途中のものより最も古いものと最も新しいものが優先されます。アーカイブには保存済みのチャットとベクトル索引が必要で、それらがない場合、古いターンは破棄されます。空きVRAMではなく、設定したコンテキスト長を基準にします。API モデル:対応していればプロバイダーが古いターンを要約し、そうでなければチャットがモデルの公開コンテキスト長に近づいたときに最も古いターンが破棄されます。",
pastedTextShortDescription:
"{count}文字以上の貼り付けテキストは .txt 添付ファイルになります。短いテキストは入力欄に残ります。",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index fbf59635bd3..25ed3867188 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -2227,7 +2227,7 @@ export const ko = {
projectAttachmentsHint:
"각 채팅의 첨부 메뉴에서 이 설정을 개별적으로 변경할 수 있습니다.",
rememberParamsPerModelHint: "끄면 모든 모델에 같은 설정을 사용합니다.",
- autoCompactHint: "로컬 GGUF 및 MLX 채팅에만 적용됩니다. 밀려난 턴은 색인되어 모델이 다시 검색할 수 있고, 초기화 시에는 들어갈 수 있는 만큼의 계속 적용되는 지침이 원문 그대로 이어지며, 중간 것보다 가장 오래된 것과 가장 최근 것이 우선됩니다. 보관하려면 저장된 채팅과 벡터 색인이 필요하며, 없으면 오래된 턴은 그냥 삭제됩니다. 남은 VRAM이 아닌 설정한 컨텍스트 길이를 기준으로 합니다.",
+ autoCompactHint: "로컬 GGUF 및 MLX 채팅: 밀려난 턴은 색인되어 모델이 다시 검색할 수 있고, 초기화 시에는 들어갈 수 있는 만큼의 계속 적용되는 지침이 원문 그대로 이어지며, 중간 것보다 가장 오래된 것과 가장 최근 것이 우선됩니다. 보관하려면 저장된 채팅과 벡터 색인이 필요하며, 없으면 오래된 턴은 그냥 삭제됩니다. 남은 VRAM이 아닌 설정한 컨텍스트 길이를 기준으로 합니다. API 모델: 제공자가 지원하면 오래된 턴을 요약하고, 그렇지 않으면 채팅이 모델의 공개된 컨텍스트 창에 가까워질 때 가장 오래된 턴이 삭제됩니다.",
pastedTextShortDescription:
"붙여넣은 텍스트가 {count}자 이상이면 .txt 첨부 파일이 됩니다. 더 짧은 텍스트는 입력창에 남습니다.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 5123d5407ab..4ffd68f2209 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -2250,7 +2250,7 @@ export const ptBR = {
"Altere esta configuração para cada chat pelo menu de anexos.",
rememberParamsPerModelHint:
"Quando desativado, todos os modelos usam as mesmas configurações.",
- autoCompactHint: "Apenas chats GGUF e MLX locais. Os turnos removidos são indexados para que o modelo possa buscá-los de volta, e uma reinicialização cita palavra por palavra as instruções permanentes que couberem, priorizando as mais antigas e as mais recentes em vez das intermediárias. Arquivar exige um chat salvo e o índice vetorial; sem eles, os turnos antigos são descartados. Usa o tamanho de contexto definido, não a VRAM disponível.",
+ autoCompactHint: "Chats GGUF e MLX locais: Os turnos removidos são indexados para que o modelo possa buscá-los de volta, e uma reinicialização cita palavra por palavra as instruções permanentes que couberem, priorizando as mais antigas e as mais recentes em vez das intermediárias. Arquivar exige um chat salvo e o índice vetorial; sem eles, os turnos antigos são descartados. Usa o tamanho de contexto definido, não a VRAM disponível. Modelos de API: o provedor resume os turnos antigos quando oferece suporte; caso contrário, os mais antigos são descartados quando o chat se aproxima da janela de contexto publicada do modelo.",
pastedTextShortDescription:
"Texto colado com {count} caracteres ou mais vira um anexo .txt. Textos menores ficam na caixa de mensagem.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 7f137aa94f9..9e7c30601a6 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -2246,7 +2246,7 @@ export const ru = {
"Для отдельного чата настройку можно изменить в его меню вложений.",
rememberParamsPerModelHint:
"Если выключено, для всех моделей используются одинаковые настройки.",
- autoCompactHint: "Только локальные чаты GGUF и MLX. Вытесненные ходы индексируются, чтобы модель могла найти их снова, а сброс дословно приводит те постоянные инструкции, которые помещаются, отдавая предпочтение самым старым и самым новым, а не промежуточным. Для архивации нужны сохранённый чат и векторный индекс; без них старые ходы просто удаляются. Учитывает заданную длину контекста, а не доступную VRAM.",
+ autoCompactHint: "Локальные чаты GGUF и MLX: Вытесненные ходы индексируются, чтобы модель могла найти их снова, а сброс дословно приводит те постоянные инструкции, которые помещаются, отдавая предпочтение самым старым и самым новым, а не промежуточным. Для архивации нужны сохранённый чат и векторный индекс; без них старые ходы просто удаляются. Учитывает заданную длину контекста, а не доступную VRAM. Модели API: провайдер кратко пересказывает старые ходы, если поддерживает это, иначе самые старые ходы удаляются, когда чат приближается к опубликованному окну контекста модели.",
pastedTextShortDescription:
"Вставленный текст длиной от {count} символов становится вложением .txt. Более короткий текст остаётся в поле сообщения.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 611a5a7ec15..cbeb80bce1a 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -2195,7 +2195,7 @@ export const zhCN = {
},
projectAttachmentsHint: "可在各聊天的附件菜单中单独调整此设置。",
rememberParamsPerModelHint: "关闭后,所有模型使用同一套设置。",
- autoCompactHint: "仅适用于本地 GGUF 和 MLX 聊天。被移出的轮次会建立索引,模型可以再检索回来;重置时会原文保留放得下的长期指令,优先保留最早和最新的,而不是中间的。归档需要已保存的聊天和向量索引,两者缺一时较早的轮次会被直接丢弃。依据你设置的上下文长度,而不是可用显存。",
+ autoCompactHint: "本地 GGUF 和 MLX 聊天:被移出的轮次会建立索引,模型可以再检索回来;重置时会原文保留放得下的长期指令,优先保留最早和最新的,而不是中间的。归档需要已保存的聊天和向量索引,两者缺一时较早的轮次会被直接丢弃。依据你设置的上下文长度,而不是可用显存。API 模型:提供商支持时会对较早的轮次生成摘要,否则在聊天接近模型公布的上下文窗口时丢弃最早的轮次。",
pastedTextShortDescription:
"粘贴的文本达到 {count} 个字符时会转为 .txt 附件,较短的文本则保留在消息输入框中。",
pastedTextOffDescription:
diff --git a/studio/frontend/tests/auto-compaction-settings.test.ts b/studio/frontend/tests/auto-compaction-settings.test.ts
index b016b9469a2..7d0b74ebde3 100644
--- a/studio/frontend/tests/auto-compaction-settings.test.ts
+++ b/studio/frontend/tests/auto-compaction-settings.test.ts
@@ -3,13 +3,16 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { ggufCompactionRequestFields } from "../src/features/chat/utils/auto-compaction.ts";
+import ts from "typescript";
+import {
+ apiCompactionRequestFields,
+ ggufCompactionRequestFields,
+} from "../src/features/chat/utils/auto-compaction.ts";
import { readSrc } from "./helpers/kit.ts";
test("auto-compact on sends truncate_oldest and no policy of its own", () => {
- // No context_policy: the server applies UNSLOTH_CONTEXT_POLICY. Studio used to offer that
- // choice as a setting and no longer does, so this is the only shape an enabled request takes.
+ // the server applies UNSLOTH_CONTEXT_POLICY because Studio no longer exposes context_policy.
assert.deepEqual(
ggufCompactionRequestFields({ isGguf: true, autoCompactEnabled: true }),
{ context_overflow: "truncate_oldest" },
@@ -129,7 +132,7 @@ test("MLX chats opt in on the backend's own report and honor disabling auto comp
ggufCompactionRequestFields({ ...options, autoCompactEnabled: false }),
{ context_overflow: "error" },
);
- // loadedIsMlx, not a catalog row, as isGguf goes through isServedByLlamaCpp.
+ // loadedIsMlx is authoritative because isGguf already uses isServedByLlamaCpp.
const adapter = readSrc("features/chat/api/chat-adapter.ts");
assert.match(adapter, /isMlx: isMlxForCompaction/);
assert.match(
@@ -137,3 +140,202 @@ test("MLX chats opt in on the backend's own report and honor disabling auto comp
/isMlxForCompaction =\s*!isExternalModelId\(params\.checkpoint\) && runtime\.loadedIsMlx === true/,
);
});
+
+test("an API model compacts a quarter short of its published window and sends that window", () => {
+ assert.deepEqual(
+ apiCompactionRequestFields({ autoCompactEnabled: true, contextLength: 200_000 }),
+ {
+ context_overflow: "truncate_oldest",
+ compaction_threshold: 150_000,
+ context_window: 200_000,
+ },
+ );
+});
+
+test("a window past the request ceiling still sends a threshold the server accepts", () => {
+ assert.deepEqual(
+ apiCompactionRequestFields({ autoCompactEnabled: true, contextLength: 10_000_000 }),
+ {
+ context_overflow: "truncate_oldest",
+ compaction_threshold: 2_000_000,
+ context_window: 10_000_000,
+ },
+ );
+});
+
+test("an API model sends nothing with auto-compact off or no published window", () => {
+ assert.deepEqual(
+ apiCompactionRequestFields({ autoCompactEnabled: false, contextLength: 200_000 }),
+ {},
+ );
+ assert.deepEqual(
+ apiCompactionRequestFields({ autoCompactEnabled: true, contextLength: null }),
+ {},
+ );
+});
+
+test("the external request carries the window the model catalog publishes", async () => {
+ const { registerBundlerResolver, installLocalStorageFake } = await import(
+ "./helpers/kit.ts"
+ );
+ registerBundlerResolver();
+ installLocalStorageFake();
+ const { resolveModelCatalogEntry } = await import(
+ "../src/features/chat/model-catalog.ts"
+ );
+ const window = resolveModelCatalogEntry("anthropic", "claude-haiku-4-5")?.contextLength;
+ assert.equal(window, 200_000);
+
+ const adapter = readSrc("features/chat/api/chat-adapter.ts");
+ assert.match(
+ adapter,
+ /apiCompactionRequestFields\(\{\s*autoCompactEnabled: runtime\.autoCompactEnabled,\s*contextLength: resolveModelCatalogEntry\(\s*externalProvider\.providerType,\s*externalModelId,\s*\)\?\.contextLength,/,
+ );
+});
+
+test("a provider compaction is kept on the turn and replayed only to API models", () => {
+ const adapter = readSrc("features/chat/api/chat-adapter.ts");
+ assert.match(adapter, /toolEvent\.type === "compaction_block"/);
+ assert.match(adapter, /providerCompaction,\n/);
+ assert.match(
+ adapter,
+ /isExternalRequest\s*\?\s*withProviderCompaction\(message, serialized, \{[\s\S]*providerType: toExternalBackendProviderType\([\s\S]*externalProvider\?\.providerType,[\s\S]*modelId: externalSelection\?\.modelId,/,
+ );
+});
+
+test("provider compaction persistence keeps summary and encrypted state together", async () => {
+ const {
+ providerCompactionConnectionKey,
+ providerCompactionForTarget,
+ providerCompactionPart,
+ } =
+ await import("../src/features/chat/utils/provider-compaction.ts");
+
+ assert.deepEqual(
+ providerCompactionPart({
+ type: "compaction_block",
+ content: "Earlier conversation summary",
+ encrypted_content: "opaque-compaction",
+ }),
+ {
+ type: "compaction",
+ content: "Earlier conversation summary",
+ encrypted_content: "opaque-compaction",
+ },
+ );
+ const connectionKey = providerCompactionConnectionKey(
+ "provider-a",
+ "https://first.openai.azure.com/openai/v1",
+ "responses",
+ );
+ assert.ok(connectionKey);
+ const origin = {
+ providerCompaction: {
+ type: "compaction",
+ content: "summary",
+ encrypted_content: "opaque-compaction",
+ },
+ providerCompactionProviderType: "anthropic",
+ providerCompactionModelId: "claude-opus-4-7",
+ providerCompactionConnectionKey: connectionKey,
+ };
+ assert.deepEqual(
+ providerCompactionForTarget(
+ origin,
+ "anthropic",
+ "claude-opus-4-7",
+ connectionKey,
+ ),
+ origin.providerCompaction,
+ );
+ assert.equal(
+ providerCompactionForTarget(origin, "openai", "gpt-5.4", connectionKey),
+ null,
+ );
+ assert.equal(
+ providerCompactionForTarget(
+ origin,
+ "anthropic",
+ "claude-sonnet-5",
+ connectionKey,
+ ),
+ null,
+ );
+ assert.equal(
+ providerCompactionForTarget(
+ {},
+ "anthropic",
+ "claude-opus-4-7",
+ connectionKey,
+ ),
+ null,
+ );
+ assert.equal(
+ providerCompactionForTarget(
+ origin,
+ "anthropic",
+ "claude-opus-4-7",
+ providerCompactionConnectionKey(
+ "provider-b",
+ "https://first.openai.azure.com/openai/v1",
+ "responses",
+ ),
+ ),
+ null,
+ );
+ assert.equal(
+ providerCompactionForTarget(
+ origin,
+ "anthropic",
+ "claude-opus-4-7",
+ providerCompactionConnectionKey(
+ "provider-a",
+ "https://second.openai.azure.com/openai/v1",
+ "responses",
+ ),
+ ),
+ null,
+ );
+});
+
+test("provider compaction replay stays on the tool-loop subturn that produced it", () => {
+ const adapter = readSrc("features/chat/api/chat-adapter.ts");
+ const start = adapter.indexOf("function providerCompactionAssistant(");
+ assert.ok(start >= 0);
+ const declaration = adapter.slice(start, adapter.indexOf("\n}", start) + 2);
+ const providerCompactionAssistant = new Function(
+ `${ts.transpileModule(declaration, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText}; return providerCompactionAssistant;`,
+ )() as (
+ messages: Record<string, unknown>[],
+ afterToolCalls: number,
+ ) => Record<string, unknown> | undefined;
+
+ const first = {
+ role: "assistant",
+ content: null,
+ tool_calls: [{ id: "first" }],
+ };
+ const second = {
+ role: "assistant",
+ content: null,
+ tool_calls: [{ id: "second" }],
+ };
+ const final = { role: "assistant", content: "done" };
+ const replay = [
+ first,
+ { role: "tool", content: "one", tool_call_id: "first" },
+ second,
+ { role: "tool", content: "two", tool_call_id: "second" },
+ final,
+ ];
+
+ assert.equal(providerCompactionAssistant(replay, 0), first);
+ assert.equal(providerCompactionAssistant(replay, 1), second);
+ assert.equal(providerCompactionAssistant(replay, 2), final);
+ assert.match(
+ adapter,
+ /providerCompactionAfterToolCalls = toolCallParts\.filter\([\s\S]*toolCallPartSurvivesOpenAIReplay\(part\)[\s\S]*\)\.length/,
+ );
+});
diff --git a/studio/frontend/tests/chat-continuation.test.ts b/studio/frontend/tests/chat-continuation.test.ts
index 9c97c41e48b..13f53e5c10f 100644
--- a/studio/frontend/tests/chat-continuation.test.ts
+++ b/studio/frontend/tests/chat-continuation.test.ts
@@ -33,6 +33,7 @@ const {
joinContinuation,
modeAllowsContinuation,
noteRunStartedThisSession,
+ providerCompactionContinuationFields,
readContinuationRequest,
readIncompleteInfo,
readTextThoughtSignature,
@@ -480,6 +481,52 @@ test("a continuation request is read only when it carries text", () => {
assert.equal(readContinuationRequest(undefined), null);
});
+test("a continuation carries a complete provider compaction tuple", () => {
+ const fields = {
+ providerCompaction: {
+ type: "compaction",
+ content: "summary",
+ encrypted_content: "opaque",
+ },
+ providerCompactionAfterToolCalls: 0,
+ providerCompactionProviderType: "anthropic",
+ providerCompactionModelId: "claude-opus-4-7",
+ providerCompactionConnectionKey: "v1:connection-a",
+ };
+ assert.deepEqual(
+ providerCompactionContinuationFields({ custom: fields }),
+ fields,
+ );
+ assert.deepEqual(
+ readContinuationRequest({
+ custom: {
+ unslothContinuation: { partial: "half an answer", ...fields },
+ },
+ }),
+ { partial: "half an answer", ...fields },
+ );
+ assert.deepEqual(
+ readContinuationRequest({
+ custom: {
+ unslothContinuation: {
+ partial: "half an answer",
+ ...fields,
+ providerCompactionModelId: undefined,
+ },
+ },
+ }),
+ { partial: "half an answer" },
+ );
+ assert.match(
+ THREAD,
+ /\.\.\.providerCompactionContinuationFields\(metadata\)/,
+ );
+ assert.match(
+ CHAT_ADAPTER,
+ /const continuationCompaction = continuation[\s\S]*providerCompactionForTarget\([\s\S]*content: continuationCompaction/,
+ );
+});
+
test("a turn that called a tool cannot be continued", () => {
// The continuation runs as a sibling, so the call and its result are absent from
// the outbound history and the resumed text would have lost its evidence.
diff --git a/studio/frontend/tests/generation-tool-recovery.test.ts b/studio/frontend/tests/generation-tool-recovery.test.ts
index 7d0f3f6ca1e..cf253da57ad 100644
--- a/studio/frontend/tests/generation-tool-recovery.test.ts
+++ b/studio/frontend/tests/generation-tool-recovery.test.ts
@@ -23,6 +23,10 @@ const { createGenerationToolRecovery } = await import(
const { RUN_CHECKPOINT_INTERVAL_MS } = await import(
"../src/features/chat/utils/run-checkpoint-scheduler.ts"
);
+const {
+ providerCompactionConnectionKey,
+ providerCompactionReplayToolCallCount,
+} = await import("../src/features/chat/utils/provider-compaction.ts");
const start = (id = "call_0") => ({
type: "tool_start",
@@ -53,6 +57,76 @@ test("replay adds new cards and applies their results", () => {
);
});
+test("recovery keeps provider compaction at its tool-call boundary", () => {
+ const carried: Carried[] = [];
+ const replay = createGenerationToolRecovery(carried, "run").apply;
+ replay(
+ {
+ type: "tool_start",
+ tool_call_id: "hosted_0",
+ tool_name: "web_search",
+ arguments: { _server_tool: true },
+ },
+ 0,
+ 1,
+ );
+ replay(
+ { type: "tool_end", tool_call_id: "hosted_0", result: "hosted" },
+ 0,
+ 2,
+ );
+ replay(start(), 12, 3);
+ replay(end(), 20, 4);
+
+ assert.deepEqual(
+ replay(
+ {
+ _toolEvent: {
+ type: "compaction_block",
+ content: "Earlier conversation summary",
+ encrypted_content: "opaque-compaction",
+ },
+ },
+ 20,
+ 5,
+ ),
+ {
+ providerCompaction: {
+ type: "compaction",
+ content: "Earlier conversation summary",
+ encrypted_content: "opaque-compaction",
+ },
+ providerCompactionAfterToolCalls: 1,
+ },
+ );
+});
+
+test("provider compaction boundaries match replayable call serialization", () => {
+ assert.equal(
+ providerCompactionReplayToolCallCount([
+ {
+ type: "tool-call",
+ toolName: "studio_load_skill",
+ result: "loaded",
+ },
+ {
+ type: "tool-call",
+ toolName: "web_search",
+ args: { _server_tool: true },
+ result: "hosted",
+ },
+ {
+ type: "tool-call",
+ toolName: "web_search",
+ args: { google: { native_part: { functionCall: {} } } },
+ },
+ { type: "tool-call", toolName: "edit_file" },
+ { type: "tool-call", toolName: "edit_file", result: "ok" },
+ ]),
+ 2,
+ );
+});
+
test("replay resumes an existing card without duplicating it", () => {
const saved = {
type: "tool-call",
@@ -397,7 +471,15 @@ async function recoverRun(
assistantMessageId: "msg",
status: options.stallBefore ? "running" : "completed",
lastEventSeq: options.stallBefore ?? payloads.length,
- requestPayload: { model: "test", session_id: "saved-session" },
+ requestPayload: {
+ model: "claude-test",
+ provider_id: "provider-a",
+ provider_type: "anthropic",
+ provider_base_url: "https://api.anthropic.com/v1",
+ provider_api_type: "chat_completions",
+ external_model: "claude-test",
+ session_id: "saved-session",
+ },
createdAt: 1,
startedAt: 1,
completedAt: 100,
@@ -406,6 +488,7 @@ async function recoverRun(
...recovery,
...parser,
createGenerationToolRecovery,
+ providerCompactionConnectionKey,
RUN_CHECKPOINT_INTERVAL_MS,
generationRecoveries,
useChatRuntimeStore: { getState: () => runtime },
@@ -505,6 +588,41 @@ test("the recovery scheduler persists later tool events between reasoning groups
);
});
+test("the recovery scheduler persists provider compaction metadata", async () => {
+ const { snapshots } = await recoverRun(
+ [],
+ [
+ start(),
+ end(),
+ {
+ _toolEvent: {
+ type: "compaction_block",
+ content: "Earlier conversation summary",
+ encrypted_content: "opaque-compaction",
+ },
+ },
+ { choices: [{ delta: { content: "done" } }] },
+ ],
+ );
+ const metadata = snapshots.at(-1)?.metadata;
+ assert.deepEqual(metadata?.providerCompaction, {
+ type: "compaction",
+ content: "Earlier conversation summary",
+ encrypted_content: "opaque-compaction",
+ });
+ assert.equal(metadata?.providerCompactionAfterToolCalls, 1);
+ assert.equal(metadata?.providerCompactionProviderType, "anthropic");
+ assert.equal(metadata?.providerCompactionModelId, "claude-test");
+ assert.equal(
+ metadata?.providerCompactionConnectionKey,
+ providerCompactionConnectionKey(
+ "provider-a",
+ "https://api.anthropic.com/v1",
+ "chat_completions",
+ ),
+ );
+});
+
test("reopening a run that finished without the tab saves and renders only its end", async () => {
// The harness yields every update twice, allowing two settlements; production stops at one.
const payloads = Array.from({ length: 400 }, (_, index) => ({
diff --git a/tests/studio/test_cancelled_turn_history_prune.py b/tests/studio/test_cancelled_turn_history_prune.py
index f04a1c47dce..e98c2e48d80 100644
--- a/tests/studio/test_cancelled_turn_history_prune.py
+++ b/tests/studio/test_cancelled_turn_history_prune.py
@@ -98,6 +98,10 @@ def _send_path_slice() -> str:
return (
"export function buildSendPathOutbound(messages: any, isExternalRequest: boolean) {\n"
" const supportsStudioToolsForThisTurn = false, studioLocalCodeTools: string[] = [];\n"
+ # No test here carries provider compaction, so its replay target stays unset.
+ " const externalProvider = undefined, externalSelection = undefined;\n"
+ " const providerCompactionTargetConnectionKey = null;\n"
+ " const toExternalBackendProviderType = (providerType: any) => providerType;\n"
# The provider-dependent flag is covered by external-preserve-thinking.test.ts.
+ " const replayReasoning = !isExternalRequest;\n"
+ body