Skip to content

Automate browser based workflows with AI

feat(SKY-8879) copilot-stack/09: CopilotContext + session/model bridge (#5526)

Andrew Neilsondbf9e6104d12
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 24f7abc65..d6a7b730c 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -3,9 +3,14 @@
from __future__ import annotations
import re
+from dataclasses import dataclass, field
+from typing import Any
from pydantic import BaseModel, Field
+from skyvern.forge.sdk.copilot.runtime import AgentContext
+from skyvern.forge.sdk.workflow.models.workflow import Workflow
+
class UrlVisit(BaseModel):
url: str
@@ -93,3 +98,100 @@ class StructuredContext(BaseModel):
self.fields_filled = self.fields_filled[-40:]
if len(self.credentials_checked) > 50:
self.credentials_checked = self.credentials_checked[-40:]
+
+
+@dataclass
+class AgentResult:
+ user_response: str
+ updated_workflow: Workflow | None
+ global_llm_context: str | None
+ response_type: str = "REPLY"
+ workflow_yaml: str | None = None
+ workflow_was_persisted: bool = False
+ # Feasibility-gate fast-path sets this True so the route can null any
+ # previously-persisted proposed_workflow. Regular in-loop ASK_QUESTION
+ # responses leave it False, preserving in-progress drafts.
+ clear_proposed_workflow: bool = False
+
+
+@dataclass
+class CopilotContext(AgentContext):
+ """Unified context for the copilot agent run.
+
+ Extends AgentContext with enforcement state, tool tracking, and
+ workflow state needed by the SDK-based agent loop.
+
+ Field-shadowing note: the enforcement / workflow / frontier state fields
+ declared below are intentionally redeclared on this subclass. The parent
+ ``AgentContext`` (in ``runtime.py``) still carries the same names with the
+ same defaults for legacy paths that instantiate ``AgentContext`` directly.
+ Python's MRO resolves to the child's declaration when a ``CopilotContext``
+ instance is used — that's the desired behavior here. Stripping the
+ duplicates from the parent is tracked in SKY-8974; until that lands, if
+ you add a new field here, keep the defaults in sync with the parent to
+ avoid drift.
+ """
+
+ # Enforcement state
+ navigate_called: bool = False
+ observation_after_navigate: bool = False
+ navigate_enforcement_done: bool = False
+ update_workflow_called: bool = False
+ test_after_update_done: bool = False
+ post_update_nudge_count: int = 0
+ coverage_nudge_count: int = 0
+ format_nudge_count: int = 0
+ user_message: str = ""
+
+ # Tool tracking
+ consecutive_tool_tracker: list[str] = field(default_factory=list)
+ tool_activity: list[dict[str, Any]] = field(default_factory=list)
+
+ # Workflow state
+ last_workflow: Workflow | None = None
+ last_workflow_yaml: str | None = None
+ workflow_persisted: bool = False
+ last_update_block_count: int | None = None
+ last_test_ok: bool | None = None
+ last_test_failure_reason: str | None = None
+ failed_test_nudge_count: int = 0
+ explore_without_workflow_nudge_count: int = 0
+ last_failed_workflow_yaml: str | None = None
+ # Consecutive test runs whose data-producing blocks completed with no
+ # meaningful output (missing, empty, or all-null fields). Resets when a
+ # run produces real data. Used to escalate when the agent is stuck
+ # retrying extraction against a page that doesn't contain the data.
+ null_data_streak_count: int = 0
+
+ # Per-request frontier state. `verified_block_outputs` and
+ # `verified_prefix_labels` are populated ONLY from fully-successful runs —
+ # a single failed block in the executed suffix leaves the prior verified
+ # state untouched, because the browser session is now in post-failure
+ # state and the prefix labels can no longer be trusted as an anchor.
+ verified_block_outputs: dict[str, Any] = field(default_factory=dict)
+ verified_prefix_labels: list[str] = field(default_factory=list)
+ last_requested_block_labels: list[str] = field(default_factory=list)
+ last_executed_block_labels: list[str] = field(default_factory=list)
+ last_frontier_start_label: str | None = None
+ last_frontier_fingerprint: str | None = None
+ last_failure_signature: str | None = None
+ repeated_failure_streak_count: int = 0
+ # Highest streak level at which we've already emitted a repeated-failure
+ # nudge. Prevents the warn nudge from re-firing every turn while the
+ # streak is still at 2, and guarantees the stop nudge fires exactly once
+ # when the streak reaches 3.
+ repeated_failure_nudge_emitted_at_streak: int = 0
+ last_failure_category_top: str | None = None
+ # Hash of the ordered (action_type, element_id) tuples from the last run's
+ # action trace. When the same fingerprint repeats run-over-run with no
+ # intervening success, the agent is stuck re-firing the same clicks/inputs —
+ # typically because a captcha/popup/anti-bot is blocking progress. The
+ # streak counter drives the hard-abort short-circuit in _tool_loop_error.
+ # ``pending_action_sequence_fingerprint`` holds the fingerprint of the run
+ # that JUST completed, computed by ``_run_blocks_and_collect_debug`` before
+ # action_trace is stripped. ``update_repeated_failure_state`` compares it
+ # to ``last_action_sequence_fingerprint`` (the prior run's fingerprint),
+ # updates the streak, then promotes pending → last.
+ last_action_sequence_fingerprint: str | None = None
+ pending_action_sequence_fingerprint: str | None = None
+ repeated_action_fingerprint_streak_count: int = 0
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index 5b22fe74f..a0a50084e 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -6,13 +6,10 @@ import copy
import json
import re
import time
-from dataclasses import replace
from typing import TYPE_CHECKING, Any
import structlog
-from agents import RunConfig
from agents.run import Runner
-from agents.run_config import CallModelData, ModelInputData
from skyvern.forge.sdk.copilot.output_utils import extract_final_text, parse_final_response
from skyvern.forge.sdk.copilot.screenshot_utils import ScreenshotEntry
@@ -66,6 +63,10 @@ KEEP_RECENT_TOOL_OUTPUTS = 3
_RECENT_TOOL_OUTPUT_CHAR_CAP = 2000
_TOOL_OUTPUT_SUMMARIZE_THRESHOLD = 300
_TOOL_OUTPUT_TRUNCATION_SUFFIX = "\n... [older tool output truncated]"
+# Head-truncation marker for the recent tool-output window. Kept on a
+# module-level constant so session_factory can import the same string and
+# the two paths stay in sync if the wording ever changes.
+_TOOL_OUTPUT_HEAD_TRUNCATION_SUFFIX = "\n... [truncated]"
POST_UPDATE_NUDGE = (
"You updated the workflow but did not test it. "
@@ -640,7 +641,7 @@ def _prune_input_list(items: list[Any]) -> list[Any]:
if isinstance(output, str):
if i in recent_fco_set:
new_output = (
- output[:_RECENT_TOOL_OUTPUT_CHAR_CAP] + "\n... [truncated]"
+ output[:_RECENT_TOOL_OUTPUT_CHAR_CAP] + _TOOL_OUTPUT_HEAD_TRUNCATION_SUFFIX
if len(output) > _RECENT_TOOL_OUTPUT_CHAR_CAP
else output
)
@@ -834,30 +835,6 @@ class _SendTrackingStream:
await self._inner.close()
-async def _session_pruning_filter(data: CallModelData[Any]) -> ModelInputData:
- """call_model_input_filter hook: applies _prune_input_list to the input the
- Agents SDK materializes from session history on every model call. Keeps
- session-backed runs under the context budget."""
- model_data = data.model_data
- pruned = _prune_input_list(list(model_data.input))
- return ModelInputData(input=pruned, instructions=model_data.instructions)
-
-
-def _build_run_config(existing: RunConfig | None) -> RunConfig:
- """Return a RunConfig that carries the session pruning filter, merging with
- any RunConfig a caller already provided. If the caller already set their
- own ``call_model_input_filter``, respect it.
-
- Never mutates the caller's RunConfig — a shared default passed in from
- elsewhere would otherwise leak filter state across unrelated runs.
- """
- if existing is None:
- return RunConfig(call_model_input_filter=_session_pruning_filter)
- if existing.call_model_input_filter is not None:
- return existing
- return replace(existing, call_model_input_filter=_session_pruning_filter)
-
-
async def run_with_enforcement(
agent: Agent,
initial_input: str | list,
@@ -870,7 +847,6 @@ async def run_with_enforcement(
from skyvern.forge.sdk.copilot.streaming_adapter import stream_to_sse
session = runner_kwargs.pop("session", None)
- runner_kwargs["run_config"] = _build_run_config(runner_kwargs.get("run_config"))
current_input: str | list = initial_input
start_time = time.monotonic()
iteration = 0
diff --git a/skyvern/forge/sdk/copilot/failure_tracking.py b/skyvern/forge/sdk/copilot/failure_tracking.py
index 70f309586..8dec25667 100644
--- a/skyvern/forge/sdk/copilot/failure_tracking.py
+++ b/skyvern/forge/sdk/copilot/failure_tracking.py
@@ -25,7 +25,7 @@ import json
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
- from skyvern.forge.sdk.copilot.agent import CopilotContext
+ from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.workflow.models.workflow import WorkflowDefinition
_FAILURE_REASON_MAX_CHARS = 200
diff --git a/skyvern/forge/sdk/copilot/model_resolver.py b/skyvern/forge/sdk/copilot/model_resolver.py
new file mode 100644
index 000000000..4a7da5a87
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/model_resolver.py
@@ -0,0 +1,157 @@
+"""Bridge Skyvern LLM config to OpenAI Agents SDK model + RunConfig.
+
+Known limitations (to be addressed in the wiring commit that activates this
+bridge):
+
+* ``resolve_model_config`` takes only ``llm_api_handler`` and has no
+ ``prompt_name`` input, so prompt-specific thinking-budget tuning applied by
+ ``api_handler_factory`` for certain prompt / model combinations cannot be
+ reproduced here.
+* ``LLMRouterConfig`` (fallback chains) is rejected. Production configs like
+ ``GEMINI_3_0_FLASH_WITH_FALLBACK_GPT5`` cannot run through the SDK bridge
+ yet. Direct ``LLMConfig`` entries only.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import structlog
+from agents.extensions.models.litellm_provider import LitellmProvider
+from agents.model_settings import ModelSettings
+from agents.models.interface import Model
+from agents.run_config import RunConfig
+
+from skyvern.config import settings
+from skyvern.forge.sdk.api.llm.config_registry import LLMConfigRegistry
+from skyvern.forge.sdk.api.llm.exceptions import InvalidLLMConfigError
+from skyvern.forge.sdk.api.llm.models import LLMConfig, LLMRouterConfig
+from skyvern.forge.sdk.copilot.session_factory import (
+ copilot_call_model_input_filter,
+ copilot_session_input_callback,
+)
+from skyvern.forge.sdk.copilot.tracing_setup import is_tracing_enabled
+
+LOG = structlog.get_logger()
+
+# Keys in litellm_params that are routed elsewhere (top-level kwargs to
+# LitellmModel or the dedicated ModelSettings.extra_headers slot), so they
+# don't count as "unrouted" when we log dropped keys.
+_TOP_LEVEL_ROUTED_FIELDS = frozenset({"api_base", "api_key", "extra_headers"})
+
+# LiteLLMParams fields that LiteLLM consumes as call-level kwargs (splatted
+# via ``extra_args`` by the Agents SDK into ``litellm.acompletion(**kwargs)``).
+_EXTRA_ARGS_FIELDS = frozenset(
+ {
+ "api_version",
+ "model_info",
+ "vertex_credentials",
+ "vertex_location",
+ "timeout",
+ }
+)
+
+# LiteLLMParams fields that end up as provider-specific payload-body entries
+# (routed via ``ModelSettings.extra_body`` → request JSON body).
+_EXTRA_BODY_FIELDS = frozenset({"thinking", "thinking_level", "service_tier"})
+
+
+def resolve_model_config(llm_api_handler: Any) -> tuple[str, RunConfig, str, bool]:
+ """Map Skyvern llm_key to OpenAI Agents SDK model string + RunConfig.
+
+ Returns (model_name, run_config, llm_key, supports_vision).
+ """
+ llm_key = getattr(llm_api_handler, "llm_key", None) or settings.LLM_KEY
+ config = LLMConfigRegistry.get_config(llm_key)
+
+ if isinstance(config, LLMRouterConfig):
+ raise InvalidLLMConfigError(
+ f"llm_key '{llm_key}' uses LLMRouterConfig which is not yet supported. "
+ "Use a non-router LLMConfig llm_key instead."
+ )
+
+ extra_body: dict[str, Any] = {}
+ extra_args: dict[str, Any] = {}
+ extra_headers: dict[str, str] | None = None
+ base_url: str | None = None
+ api_key: str | None = None
+
+ if config.reasoning_effort:
+ extra_body["reasoning_effort"] = config.reasoning_effort
+
+ if isinstance(config, LLMConfig) and config.litellm_params:
+ lp = config.litellm_params
+ base_url = lp.get("api_base")
+ api_key = lp.get("api_key")
+
+ for key in _EXTRA_ARGS_FIELDS:
+ val = lp.get(key)
+ if val is not None:
+ extra_args[key] = val
+
+ for key in _EXTRA_BODY_FIELDS:
+ val = lp.get(key)
+ if val is not None:
+ extra_body[key] = val
+
+ headers = lp.get("extra_headers")
+ if headers:
+ extra_headers = dict(headers)
+
+ # Warn if litellm_params has keys we don't explicitly route. Covers both
+ # future additions to the LiteLLMParams TypedDict and runtime-only keys
+ # (typos, dynamically-injected values). Without this, such keys are
+ # silently dropped and the call proceeds with a subset of the intended
+ # config.
+ known_keys = _EXTRA_ARGS_FIELDS | _EXTRA_BODY_FIELDS | _TOP_LEVEL_ROUTED_FIELDS
+ unrouted = sorted(k for k in lp.keys() if k not in known_keys)
+ if unrouted:
+ LOG.warning(
+ "litellm_params contains keys not routed by resolve_model_config; they will be dropped",
+ llm_key=llm_key,
+ unrouted_keys=unrouted,
+ )
+
+ # Default timeout parity with the non-SDK handler (api_handler_factory:
+ # injects settings.LLM_CONFIG_TIMEOUT when litellm_params has no timeout).
+ if "timeout" not in extra_args:
+ extra_args["timeout"] = settings.LLM_CONFIG_TIMEOUT
+
+ model_settings = ModelSettings(
+ temperature=config.temperature,
+ max_tokens=config.max_completion_tokens or config.max_tokens,
+ extra_body=extra_body or None,
+ extra_args=extra_args or None,
+ extra_headers=extra_headers,
+ )
+
+ provider = CopilotLitellmProvider(base_url=base_url, api_key=api_key)
+
+ run_config = RunConfig(
+ model_provider=provider,
+ model_settings=model_settings,
+ tracing_disabled=not is_tracing_enabled(),
+ session_input_callback=copilot_session_input_callback,
+ call_model_input_filter=copilot_call_model_input_filter,
+ )
+
+ return config.model_name, run_config, llm_key, config.supports_vision
+
+
+class CopilotLitellmProvider(LitellmProvider):
+ """LitellmProvider that passes per-run base_url/api_key to LitellmModel."""
+
+ def __init__(self, base_url: str | None = None, api_key: str | None = None):
+ super().__init__()
+ self._base_url = base_url
+ self._api_key = api_key
+
+ def get_model(self, model_name: str | None) -> Model:
+ from agents.extensions.models.litellm_model import LitellmModel
+ from agents.models.default_models import get_default_model
+
+ return LitellmModel(
+ model=model_name or get_default_model(),
+ base_url=self._base_url,
+ api_key=self._api_key,
+ )
diff --git a/skyvern/forge/sdk/copilot/session_factory.py b/skyvern/forge/sdk/copilot/session_factory.py
new file mode 100644
index 000000000..e8c566471
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/session_factory.py
@@ -0,0 +1,239 @@
+"""Session management for the copilot agent — SQLiteSession + callbacks."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import structlog
+from agents.memory.sqlite_session import SQLiteSession
+from agents.run_config import CallModelData, ModelInputData
+
+from skyvern.forge.sdk.copilot.enforcement import (
+ _RECENT_TOOL_OUTPUT_CHAR_CAP,
+ _TOOL_OUTPUT_HEAD_TRUNCATION_SUFFIX,
+ KEEP_RECENT_TOOL_OUTPUTS,
+ SCREENSHOT_PLACEHOLDER,
+ TOKEN_BUDGET,
+ _summarize_tool_arguments,
+ _summarize_tool_output,
+ aggressive_prune,
+ estimate_tokens,
+ is_screenshot_message,
+ is_synthetic_user_message,
+)
+
+LOG = structlog.get_logger()
+
+RECENT_REAL_TURNS = 2
+TOOL_OUTPUT_TRUNCATE_EMERGENCY = 300
+
+
+def create_copilot_session(chat_id: str) -> SQLiteSession:
+ """Create an in-memory SQLiteSession scoped to a single copilot request."""
+ return SQLiteSession(session_id=chat_id, db_path=":memory:")
+
+
+def _item_field(item: Any, name: str) -> Any:
+ """Read *name* from an item that is either a dict or attr-style object."""
+ if isinstance(item, dict):
+ return item.get(name)
+ return getattr(item, name, None)
+
+
+def _replace_item_field(item: Any, name: str, value: Any) -> Any:
+ """Return *item* with *name* set to *value*. Dict items get a shallow copy;
+ attr-style items are mutated in place. When setattr fails (frozen dataclass
+ / __slots__ object), the item is returned unmodified and we log a warning
+ so a budget overrun from a silently-unpatched item shows up in the logs
+ instead of disappearing."""
+ if isinstance(item, dict):
+ return {**item, name: value}
+ try:
+ setattr(item, name, value)
+ except (AttributeError, TypeError) as exc:
+ LOG.warning(
+ "Failed to rewrite session item field; leaving it as-is",
+ field=name,
+ item_type=type(item).__name__,
+ error=str(exc),
+ )
+ return item
+
+
+def _compact_tool_items(items: list[Any]) -> list[Any]:
+ """Compact older function_call_output and function_call items using the
+ same KEEP_RECENT_TOOL_OUTPUTS rule as ``enforcement._prune_input_list``.
+
+ The last ``KEEP_RECENT_TOOL_OUTPUTS`` items in each category stay full
+ (head-truncated only if very large). Older items get the JSON synopsis
+ compression. This is the session-path mirror of the non-session
+ ``_prune_input_list`` behavior, so first-turn transcripts with a long
+ tool chain get compacted just like the non-session path."""
+ fco_indices = [i for i, it in enumerate(items) if _item_field(it, "type") == "function_call_output"]
+ fc_indices = [i for i, it in enumerate(items) if _item_field(it, "type") == "function_call"]
+ recent_fco_set = set(fco_indices[-KEEP_RECENT_TOOL_OUTPUTS:]) if fco_indices else set()
+ recent_fc_set = set(fc_indices[-KEEP_RECENT_TOOL_OUTPUTS:]) if fc_indices else set()
+
+ result: list[Any] = []
+ for i, item in enumerate(items):
+ item_type = _item_field(item, "type")
+ if item_type == "function_call_output":
+ output = _item_field(item, "output")
+ if isinstance(output, str):
+ if i in recent_fco_set:
+ new_output = (
+ output[:_RECENT_TOOL_OUTPUT_CHAR_CAP] + _TOOL_OUTPUT_HEAD_TRUNCATION_SUFFIX
+ if len(output) > _RECENT_TOOL_OUTPUT_CHAR_CAP
+ else output
+ )
+ else:
+ new_output = _summarize_tool_output(output)
+ if new_output != output:
+ item = _replace_item_field(item, "output", new_output)
+ elif item_type == "function_call" and i not in recent_fc_set:
+ args = _item_field(item, "arguments")
+ if isinstance(args, str):
+ new_args = _summarize_tool_arguments(args)
+ if new_args != args:
+ item = _replace_item_field(item, "arguments", new_args)
+ result.append(item)
+ return result
+
+
+def copilot_session_input_callback(
+ history_items: list[Any],
+ new_items: list[Any],
+) -> list[Any]:
+ """Combine session history with new input, pruning older tool output/call
+ payloads in the middle region.
+
+ Keeps the original goal (first item) at full fidelity and preserves the
+ last ``RECENT_REAL_TURNS`` real user turns. Within the remaining middle
+ region, older ``function_call_output`` / ``function_call`` items are
+ compacted using the same ``KEEP_RECENT_TOOL_OUTPUTS`` rule that
+ ``enforcement._prune_input_list`` uses in the non-session path, so
+ first-turn transcripts with a long tool chain get compacted identically
+ regardless of user-turn count.
+ """
+ if not history_items:
+ return new_items
+
+ boundary = _find_real_user_boundary(history_items, recent_turns=RECENT_REAL_TURNS)
+ # Partitioning rules:
+ # * boundary >= 1 — the helper found ``recent_turns`` real user messages.
+ # items[1:boundary] is the "middle" to compact; items[boundary:] is the
+ # recent region we keep as-is. When boundary == 1 the middle slice is
+ # empty, which is correct (no items between the goal and the recent
+ # region). The prior form also appended history_items[1:] to recent,
+ # which double-emitted every non-goal item — fixed here.
+ # * boundary == 0 — first-turn shape (fewer real users than recent_turns).
+ # Treat everything after the goal as "middle" so the KEEP_RECENT_TOOL_OUTPUTS
+ # compaction inside _compact_tool_items can still fire on the long tool
+ # chain. Recent is empty.
+ if boundary >= 1:
+ middle = history_items[1:boundary]
+ recent = history_items[boundary:]
+ else:
+ middle = history_items[1:]
+ recent = []
+
+ pruned_middle = _compact_tool_items(middle)
+ pruned_middle = [
+ {"role": "user", "content": SCREENSHOT_PLACEHOLDER} if is_screenshot_message(item) else item
+ for item in pruned_middle
+ ]
+
+ return [history_items[0]] + pruned_middle + list(recent) + list(new_items)
+
+
+def copilot_call_model_input_filter(data: CallModelData[Any]) -> ModelInputData:
+ """Token-budget enforcement applied just before each model call.
+
+ Graduated pruning:
+ 1. Compact older tool outputs + function-call arguments using the
+ KEEP_RECENT_TOOL_OUTPUTS rule (mirrors ``enforcement._prune_input_list``).
+ 2. If still over budget: drop all screenshots except the most recent.
+ 3. If still over budget: truncate ALL tool outputs to 300 chars.
+ 4. If still over budget: aggressive prune as last resort.
+ """
+ model_data = data.model_data
+ items = list(model_data.input)
+
+ if not items:
+ return ModelInputData(input=items, instructions=model_data.instructions)
+
+ est = estimate_tokens(items)
+ LOG.info("Token estimate before filtering", tokens=est)
+
+ # Re-run compaction here even though ``copilot_session_input_callback``
+ # already compacted on session merge. The KEEP_RECENT_TOOL_OUTPUTS window
+ # shifts whenever new items get appended — an output that was "recent" on
+ # the previous turn may now be old enough to summarize. Cheap to re-run
+ # (pure function over the item list), idempotent on already-compact items.
+ items = _compact_tool_items(items)
+
+ est = estimate_tokens(items)
+ if est <= TOKEN_BUDGET:
+ LOG.info("Within budget after tool trim", tokens=est)
+ return ModelInputData(input=items, instructions=model_data.instructions)
+
+ # Layer 2: Drop all screenshots except the most recent
+ screenshot_indices = [i for i, item in enumerate(items) if is_screenshot_message(item)]
+ if len(screenshot_indices) > 1:
+ drop_indices = set(screenshot_indices[:-1])
+ items = [
+ {"role": "user", "content": SCREENSHOT_PLACEHOLDER} if i in drop_indices else item
+ for i, item in enumerate(items)
+ ]
+
+ est = estimate_tokens(items)
+ if est <= TOKEN_BUDGET:
+ LOG.info("Within budget after screenshot drop", tokens=est)
+ return ModelInputData(input=items, instructions=model_data.instructions)
+
+ # Layer 3: Truncate ALL tool outputs to 300 chars
+ items = [_truncate_tool_output(item, TOOL_OUTPUT_TRUNCATE_EMERGENCY) for item in items]
+
+ est = estimate_tokens(items)
+ if est <= TOKEN_BUDGET:
+ LOG.info("Within budget after emergency truncation", tokens=est)
+ return ModelInputData(input=items, instructions=model_data.instructions)
+
+ # Layer 4: Aggressive prune as last resort
+ LOG.warning("Aggressive prune needed", tokens=est, budget=TOKEN_BUDGET)
+ items = aggressive_prune(items)
+
+ est = estimate_tokens(items)
+ LOG.info("Final token estimate after aggressive prune", tokens=est)
+ return ModelInputData(input=items, instructions=model_data.instructions)
+
+
+def _truncate_tool_output(item: Any, max_chars: int) -> Any:
+ """Truncate a function_call_output item's output if it exceeds max_chars.
+
+ Handles both dict and attr-style items via the shared ``_item_field`` /
+ ``_replace_item_field`` helpers so Layer 3 emergency truncation stays
+ consistent with the KEEP_RECENT_TOOL_OUTPUTS path in ``_compact_tool_items``.
+ """
+ if _item_field(item, "type") != "function_call_output":
+ return item
+ output = _item_field(item, "output")
+ if isinstance(output, str) and len(output) > max_chars:
+ return _replace_item_field(item, "output", output[:max_chars] + _TOOL_OUTPUT_HEAD_TRUNCATION_SUFFIX)
+ return item
+
+
+def _find_real_user_boundary(items: list[Any], recent_turns: int = 2) -> int:
+ """Find the boundary index separating old items from recent ones.
+
+ Counts only real user messages (not screenshots or nudges) when walking
+ backward. Returns 0 if fewer than ``recent_turns`` real user messages exist.
+ """
+ real_count = 0
+ for i in range(len(items) - 1, -1, -1):
+ item = items[i]
+ if _item_field(item, "role") == "user" and not is_synthetic_user_message(item):
+ real_count += 1
+ if real_count >= recent_turns:
+ return i
+ return 0
diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.py
index bf5cca9c6..59fe8202d 100644
--- a/skyvern/forge/sdk/copilot/tools.py
+++ b/skyvern/forge/sdk/copilot/tools.py
@@ -18,6 +18,7 @@ from pydantic import ValidationError
from skyvern.forge import app
from skyvern.forge.failure_classifier import classify_from_failure_reason
from skyvern.forge.sdk.artifact.models import ArtifactType
+from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.failure_tracking import (
_canonical_block_config,
compute_action_sequence_fingerprint,
@@ -663,7 +664,7 @@ def _seed_for_frontier(
async def _run_blocks_and_collect_debug(
params: dict[str, Any],
- ctx: AgentContext,
+ ctx: CopilotContext,
*,
labels_to_execute: list[str] | None = None,
block_outputs_to_seed: dict[str, Any] | None = None,