Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Give the v1 Haiku 5.5 variant a Bedrock fallback (SKY-18088) (#8889)
Cindy Li878a5b9541f2
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.jsonindex 99aa79221..8db64e69f 100644--- a/docs/api-reference/openapi.json+++ b/docs/api-reference/openapi.json@@ -8019,7 +8019,7 @@],"title": "Terminate Criterion","description": "Condition that stops Apply. Omit to use the recipe default; null or empty text disables it.",- "default": "Terminate when the requested job posting explicitly states that it is expired, closed, filled, or no longer accepting applications. A missing Apply button, redirect, or HTTP 404 alone is insufficient."+ "default": "Terminate when the requested job posting explicitly states that it is expired, closed, filled, or no longer accepting applications. A missing Apply button or redirect alone is insufficient."},"error_code_mapping": {"anyOf": [@@ -8159,7 +8159,7 @@],"title": "Terminate Criterion","description": "Condition that stops Apply. Omit for the recipe default; empty text disables it.",- "default": "Terminate when the requested job posting explicitly states that it is expired, closed, filled, or no longer accepting applications. A missing Apply button, redirect, or HTTP 404 alone is insufficient."+ "default": "Terminate when the requested job posting explicitly states that it is expired, closed, filled, or no longer accepting applications. A missing Apply button or redirect alone is insufficient."},"error_code_mapping": {"anyOf": [diff --git a/fern/openapi/skyvern_openapi.json b/fern/openapi/skyvern_openapi.jsonindex b2b0152ac..94e1064a9 100644--- a/fern/openapi/skyvern_openapi.json+++ b/fern/openapi/skyvern_openapi.json@@ -7949,7 +7949,7 @@],"title": "Terminate Criterion","description": "Condition that stops Apply. Omit to use the recipe default; null or empty text disables it.",- "default": "Terminate when the requested job posting explicitly states that it is expired, closed, filled, or no longer accepting applications. A missing Apply button, redirect, or HTTP 404 alone is insufficient."+ "default": "Terminate when the requested job posting explicitly states that it is expired, closed, filled, or no longer accepting applications. A missing Apply button or redirect alone is insufficient."},"error_code_mapping": {"anyOf": [@@ -8064,7 +8064,7 @@],"title": "Terminate Criterion","description": "Condition that stops Apply. Omit for the recipe default; empty text disables it.",- "default": "Terminate when the requested job posting explicitly states that it is expired, closed, filled, or no longer accepting applications. A missing Apply button, redirect, or HTTP 404 alone is insufficient."+ "default": "Terminate when the requested job posting explicitly states that it is expired, closed, filled, or no longer accepting applications. A missing Apply button or redirect alone is insufficient."},"error_code_mapping": {"anyOf": [diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex c96de11d6..3b463f9f2 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -130,6 +130,7 @@ from skyvern.forge.sdk.copilot.enforcement import (CopilotNonRetriableNavError,_elapsed_run_seconds,artifact_health_blocked,+ budget_expired_reply_observation,outcome_fully_verified,raw_secret_reply_withheld_observation,run_final_reply_drain,@@ -246,6 +247,7 @@ from skyvern.forge.sdk.copilot.tools.run_execution import (WatchdogExitReason,finalize_build_test_result,hydrate_prior_run_packet,+ recorded_open_step_runs,reusable_origin_input_keys,run_workflow_end_to_end,)@@ -3254,6 +3256,11 @@ def _build_budget_expiry_exit_result(ctx: CopilotContext, global_llm_context: stattempted_kind=stopped_exit_response_kind(terminal_reason),blocked_signatures=ctx.blocked_reply_signatures,terminal_reason=terminal_reason,+ tool_calls=[+ str(entry.get("tool") or entry.get("name") or "")+ for entry in ctx.tool_activity+ if isinstance(entry, dict) and (entry.get("tool") or entry.get("name"))+ ],)staged_workflow = ctx.staged_workflow if ctx.has_staged_proposal else Nonestaged_workflow_yaml = ctx.staged_workflow_yaml if staged_workflow is not None else None@@ -3316,7 +3323,7 @@ def _build_cancelled_exit_result(ctx: CopilotContext, global_llm_context: str |return result-def _handle_budget_drain_exhausted(ctx: CopilotContext, global_llm_context: str | None) -> AgentResult:+def _record_budget_drain_exhausted(ctx: CopilotContext) -> None:ctx.copilot_max_turns_exceeded = Truestart_monotonic = ctx.copilot_run_start_monotonicLOG.warning(@@ -3326,7 +3333,6 @@ def _handle_budget_drain_exhausted(ctx: CopilotContext, global_llm_context: strelapsed_seconds=round(_elapsed_run_seconds(ctx, start_monotonic), 3) if start_monotonic is not None else 0.0,model_call_count=ctx.model_calls_this_turn,)- return _build_budget_expiry_exit_result(ctx, global_llm_context)def _build_unexpected_error_exit_result(@@ -3589,7 +3595,9 @@ async def _translate_to_agent_result(# Deferred tools.py imports here and below: tools.py -> routes.workflow_copilot -> this module (circular at import time).from skyvern.forge.sdk.copilot.tools import _process_workflow_yaml- budget_drain = ctx.budget_expiry_state.drain_attempted+ budget_drain = ctx.budget_expiry_state.drain_attempted or (+ final_reply and ctx.budget_expiry_state.source is not None+ )text = extract_final_text(result)if not text and budget_drain:return _build_budget_expiry_exit_result(ctx, global_llm_context)@@ -5734,6 +5742,39 @@ async def _run_copilot_turn_impl(LOG.warning("copilot_raw_secret_reply_reask_failed", error_type=type(reask_error).__name__)return _output_policy_blocked(exc)+ async def _reply_after_budget_expiry() -> AgentResult:+ # The hard backstop or an exhausted drain otherwise ends the turn with no reply at all,+ # so the model gets one final-reply call to report what it did before the turn ends.+ try:+ state = ctx.budget_expiry_state+ runs_not_in_history = await recorded_open_step_runs(ctx) if state.hard_backstop_reached else []+ reply = await _run_attempt(+ model_name,+ run_config,+ llm_key,+ is_fallback=False,+ final_reply=True,+ final_reply_observation=budget_expired_reply_observation(+ _budget_expiry_state_with_staged_draft(ctx), runs_not_in_history+ ),+ )+ return await _translate_to_agent_result(+ reply,+ ctx,+ global_llm_context,+ chat_request,+ organization_id,+ final_reply=True,+ )+ except asyncio.CancelledError:+ LOG.info("Copilot run cancelled")+ return _build_cancelled_exit_result(ctx, global_llm_context)+ except OutputGuardrailTripwireTriggered as reply_exc:+ return _output_policy_blocked(reply_exc)+ except Exception as reply_error:+ LOG.warning("copilot_budget_expiry_reply_failed", error_type=type(reply_error).__name__)+ return _build_budget_expiry_exit_result(ctx, global_llm_context)+try:from skyvern.forge.sdk.copilot.session_factory import create_copilot_session@@ -5821,9 +5862,10 @@ async def _run_copilot_turn_impl()return _build_turn_halt_exit_result(ctx, global_llm_context, exc.halt)except MaxTurnsExceeded:- return _handle_budget_drain_exhausted(ctx, global_llm_context)+ _record_budget_drain_exhausted(ctx)+ return await _reply_after_budget_expiry()except CopilotTotalTimeoutError:- return _build_budget_expiry_exit_result(ctx, global_llm_context)+ return await _reply_after_budget_expiry()except CopilotEmptyCompletionError as empty_error:if ((empty_error.retry_allowed and ctx.tool_calls_this_turn == 0)diff --git a/skyvern/forge/sdk/copilot/budget_expiry.py b/skyvern/forge/sdk/copilot/budget_expiry.pyindex 7dd15b032..2cef51c2c 100644--- a/skyvern/forge/sdk/copilot/budget_expiry.py+++ b/skyvern/forge/sdk/copilot/budget_expiry.py@@ -44,6 +44,41 @@ class BudgetExpiryObservation(BaseModel):)+class RecordedBlockState(BaseModel):+ model_config = ConfigDict(frozen=True)++ label: str+ status: str+ failure_reason: str | None = None+++class RecordedRunState(BaseModel):+ model_config = ConfigDict(frozen=True)++ workflow_run_id: str+ status: str | None+ failure_reason: str | None = None+ blocks: list[RecordedBlockState] = []+ earlier_blocks_not_shown: int = 0+++class BudgetExpiredReplyObservation(BaseModel):+ model_config = ConfigDict(frozen=True)++ budget_expired: Literal[True] = True+ source: BudgetExpirySource | None+ staged_draft: str | None+ stopped_waiting: bool+ runs_not_in_history: list[RecordedRunState]+ message: str = (+ "This turn's time is spent and nothing more can run in it. Call `reply` now with your final response for "+ "this turn; any other tool call will not run. staged_draft is the draft this turn holds. "+ "stopped_waiting means the turn stopped waiting for the step still in progress: that step's model response "+ "and tool results are not in your history, and the result of a browser action in it is unknown. The time "+ "limit does not stop runs: runs_not_in_history lists each run that step started, as its record reads now."+ )++class BudgetRunDenialData(TypedDict):budget_expired: Literal[True]run_dispatched: Literal[False]diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex 3f7591ecf..5da919e20 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -24,7 +24,10 @@ from openai.types.responses import ResponseFunctionToolCallfrom skyvern.config import settingsfrom skyvern.forge.sdk.copilot import streaming_adapterfrom skyvern.forge.sdk.copilot.budget_expiry import (+ BudgetExpiredReplyObservation,BudgetExpirySource,+ BudgetExpiryState,+ RecordedRunState,serialize_budget_expiry_observation,)from skyvern.forge.sdk.copilot.code_block_synthesis import (@@ -138,6 +141,9 @@ LOG = structlog.get_logger()TOTAL_TIMEOUT_SECONDS = settings.WORKFLOW_COPILOT_TOTAL_TIMEOUT_SECONDS or 900BUDGET_DRAIN_HEADROOM = 4HARD_BACKSTOP_ALLOWANCE_SECONDS = 90+# A turn whose budget is already spent may have no backstop time left for its one final reply, so+# that reply gets at least this long. Budget-drain reports that finished took a median 14s, p90 35s.+EXPIRED_TURN_REPLY_SECONDS = 60# Floor for the per-iteration ``wait_for`` deadline so an already-spent budget# never yields ``wait_for(timeout=0)`` (which raises immediately). Kept as a# constant so tests can shrink it instead of paying a full second per deadline.@@ -1341,6 +1347,7 @@ async def _run_streamed_with_deadline(iteration: int,*,watch_steer: bool = False,+ min_remaining_seconds: float | None = None,) -> Any:"""Run ``Runner.run_streamed`` + ``stream_to_sse`` under the hard watchdog.@@ -1352,11 +1359,12 @@ async def _run_streamed_with_deadline(credential card) can suspend it for the length of that wait.``MIN_DEADLINE_REMAINING_SECONDS`` floors ``remaining`` so a zero- timeout never panics on an already-spent budget.+ timeout never panics on an already-spent budget; ``min_remaining_seconds``+ raises that floor."""elapsed = _elapsed_run_seconds(ctx, start_time)remaining = max(- MIN_DEADLINE_REMAINING_SECONDS,+ MIN_DEADLINE_REMAINING_SECONDS if min_remaining_seconds is None else min_remaining_seconds,TOTAL_TIMEOUT_SECONDS + HARD_BACKSTOP_ALLOWANCE_SECONDS - elapsed,)with pending_operation("turn.stream", span=True):@@ -1457,13 +1465,22 @@ async def _run_drain(iteration: int,*,total_turns: int,+ min_remaining_seconds: float | None = None,) -> RunResultStreaming:"""One drain run. A response naming a tool that was not offered gets its results and one more run, within``total_turns`` model calls across both runs."""calls_before = ctx.model_calls_this_turntry:return await _run_streamed_with_deadline(- agent, observation, ctx, session, _SendTrackingStream(stream), runner_kwargs, start_time, iteration+ agent,+ observation,+ ctx,+ session,+ _SendTrackingStream(stream),+ runner_kwargs,+ start_time,+ iteration,+ min_remaining_seconds=min_remaining_seconds,)except ModelBehaviorError:if not await _save_unrun_call_results(agent, ctx, session, stream):@@ -1480,6 +1497,7 @@ async def _run_drain({**runner_kwargs, "max_turns": remaining_turns},start_time,iteration,+ min_remaining_seconds=min_remaining_seconds,)@@ -1540,6 +1558,18 @@ async def _run_budget_drain(return result+def budget_expired_reply_observation(state: BudgetExpiryState, runs_not_in_history: list[RecordedRunState]) -> str:+ return (+ NUDGE_SENTINEL+ + BudgetExpiredReplyObservation(+ source=state.source,+ staged_draft=state.staged_draft_id,+ stopped_waiting=state.hard_backstop_reached,+ runs_not_in_history=runs_not_in_history,+ ).model_dump_json()+ )++async def run_final_reply_drain(agent: Agent,ctx: CopilotContext,@@ -1552,7 +1582,7 @@ async def run_final_reply_drain() -> RunResultStreaming:state = ctx.budget_expiry_stateexpiry_snapshot = (state.source, state.hard_backstop_reached, ctx.copilot_total_timeout_exceeded)- LOG.info("copilot_final_reply_drain_started")+ LOG.info("copilot_final_reply_drain_started", budget_expiry_source=state.source)# Only `reply` is offered: any other call is rejected before its input checks run, and gets a result.reply_only = agent.clone(tools=[tool for tool in agent.tools if tool.name == REPLY_TOOL_NAME], mcp_servers=[])try:@@ -1566,6 +1596,7 @@ async def run_final_reply_drain(ctx.copilot_run_start_monotonic or time.monotonic(),0,total_turns=2,+ min_remaining_seconds=EXPIRED_TURN_REPLY_SECONDS if state.source is not None else None,)except CopilotTotalTimeoutError:# The hard backstop marks the turn budget-expired; this call is not a budget drain.diff --git a/skyvern/forge/sdk/copilot/hooks.py b/skyvern/forge/sdk/copilot/hooks.pyindex 5ac2af55c..c1c4184b2 100644--- a/skyvern/forge/sdk/copilot/hooks.py+++ b/skyvern/forge/sdk/copilot/hooks.py@@ -111,6 +111,7 @@ class CopilotRunHooks(RunHooksBase):self._ctx.model_calls_this_turn += 1if self._ctx.eval_mode == "browser_ablation" and isinstance(system_prompt, str):self._ctx.eval_prompt_sha256 = prompt_sha256(system_prompt)+ self._ctx.open_step_run_ids.clear()except Exception:LOG.warning("CopilotRunHooks.on_llm_start counting failed",diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex ccabc6380..8a8ac44a3 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -461,6 +461,9 @@ class AgentContext:# The deadline the current model stream runs under, published by the enforcement loop so a tool# that parks on a user decision can suspend it instead of being cancelled mid-question.model_stream_deadline: asyncio.Timeout | None = None+ # Runs started since the current model call began. The SDK saves a step to the session only once all of+ # its tools return, so after the hard backstop cuts a step these are the runs the session has no result for.+ open_step_run_ids: list[str] = field(default_factory=list)# True from on_llm_start to on_llm_end: no tool of that response has started, so aborting the# stream then discards only the call itself.model_call_in_flight: bool = Falsediff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.pyindex 523e0b304..bb8088f75 100644--- a/skyvern/forge/sdk/copilot/tools/run_execution.py+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py@@ -42,7 +42,7 @@ from skyvern.forge.sdk.copilot.authoring_parameter_binding import _literal_locatfrom skyvern.forge.sdk.copilot.blocker_signal import (stash_blocker_signal,)-from skyvern.forge.sdk.copilot.budget_expiry import budget_run_denial+from skyvern.forge.sdk.copilot.budget_expiry import RecordedBlockState, RecordedRunState, budget_run_denialfrom skyvern.forge.sdk.copilot.build_test_connect_failure import (SUPERSEDED_BY_NEWER_TEST_REASON,BuildTestConnectFailure,@@ -966,6 +966,40 @@ async def _recorded_watchdog_block_receipts(return recorded, results+async def recorded_open_step_runs(ctx: CopilotContext) -> list[RecordedRunState]:+ """Each run started in the step the turn stopped waiting for, as its record reads now."""+ runs: list[RecordedRunState] = []+ for workflow_run_id in ctx.open_step_run_ids:+ run = await _safe_read_workflow_run(workflow_run_id, ctx.organization_id, context="budget-expiry-reply")+ try:+ rows = await _chronological_run_block_rows(workflow_run_id, ctx.organization_id)+ except Exception:+ LOG.warning(+ "Failed to read the blocks of an unreported run", workflow_run_id=workflow_run_id, exc_info=True+ )+ rows = []+ blocks = [+ RecordedBlockState(label=row.label, status=row.status, failure_reason=row.failure_reason)+ for row in rows+ if row.label and row.status+ ]+ shown = blocks[-RUN_RESULTS_PAGE_ROWS:]+ state = RecordedRunState(+ workflow_run_id=workflow_run_id,+ status=str(run.status) if run is not None else None,+ failure_reason=run.failure_reason if run is not None else None,+ blocks=shown,+ earlier_blocks_not_shown=len(blocks) - len(shown),+ )+ # The same scrub a run tool's own result gets before the model reads it.+ runs.append(+ RecordedRunState.model_validate(+ redact_totp_runtime_values(scrub_secrets_from_structure(ctx, state.model_dump()))+ )+ )+ return runs++def _forget_browser_position(ctx: CopilotContext) -> None:"""Drop the claim about where the browser stopped, keeping the verified prefix itself."""ctx.verified_prefix_block_end_urls = {}@@ -981,6 +1015,7 @@ def _forget_interim_run_start(ctx: CopilotContext, workflow_run_id: str) -> Nonefor outcome in outcomesif not (is_interim_run_outcome(outcome) and outcome.workflow_run_id == workflow_run_id)]+ ctx.open_step_run_ids[:] = [run_id for run_id in ctx.open_step_run_ids if run_id != workflow_run_id]def _block_end_urls_by_label(run_block_rows: list[WorkflowRunBlock]) -> dict[str, str]:@@ -4234,6 +4269,9 @@ async def _run_blocks_and_collect_debug(run_submission_attempted = False# Set before a re-entry of this call, which owns the minted browser from then on.keep_run_session = False+ # Held, not re-read later: the turn clears it from the context as its stream unwinds, which can+ # happen before this call's own cancellation is delivered.+ turn_deadline = ctx.model_stream_deadlinetry:execution.recorded_settings = await _browser_execution_settings(workflow, ctx, run_session_id)@@ -4590,6 +4628,7 @@ async def _run_blocks_and_collect_debug(# the tool-return record supersedes this one.interim_run_id = workflow_run.workflow_run_idctx.run_outcome_trace.append(interim_run_start_outcome(interim_run_id))+ ctx.open_step_run_ids.append(interim_run_id)await _send_run_started_update(ctx, workflow_run.workflow_run_id)if dispatch_to_worker:@@ -4672,8 +4711,10 @@ async def _run_blocks_and_collect_debug(# Run setup / submission failed OR the tool was cancelled after the dispatch version was# created. The watchdog cleanup below never runs on this path, so soft-delete the version# here so it does not linger as the latest-by-permanent-id pointer. Catch BaseException so- # asyncio.CancelledError (the SDK tool timeout) also cleans the draft up.- if dispatch_draft_workflow_id is not None:+ # asyncio.CancelledError (the SDK tool timeout) also cleans the draft up. The turn's own deadline+ # leaves a submitted run's version in place, since the worker may already be loading it (ADR-0025).+ deadline_left_run = run_submission_attempted and turn_deadline is not None and turn_deadline.expired()+ if dispatch_draft_workflow_id is not None and not deadline_left_run:await _delete_dispatch_draft(dispatch_draft_workflow_id, ctx.organization_id)dispatch_draft_workflow_id = Noneif secret_run_session_lock is not None:@@ -4696,6 +4737,7 @@ async def _run_blocks_and_collect_debug(active_run_association: ActiveRunSessionAssociation | None = Nonerun_paused = False+ run_left_running = Falsetry:# Inside this try so a cancellation while publishing still reaches the browser lock release below.if run_detached_from_chat and debug_session_id and run_session_id:@@ -4936,6 +4978,11 @@ async def _run_blocks_and_collect_debug(# run to the ``finally`` below, which adopts the executor instead.if run_paused:raise+ # The turn's hard deadline ends the turn's wait for the run, never the run (ADR-0025): the+ # run stays with its executor and the turn's final reply reads its record.+ if turn_deadline is not None and turn_deadline.expired():+ run_left_running = True+ raise# The SDK's @function_tool(timeout=...) cancelled us mid-poll. Shield# the cleanup so the parent cancellation can't interrupt it mid-await.# If the shield itself is cancelled, fall back to a detached task@@ -4964,9 +5011,9 @@ async def _run_blocks_and_collect_debug(# poll loop — signal the run_task so we don't leak it. Dispatched runs have no in-process# task, so there is nothing to signal.if run_task is not None and not run_task.done():- if run_paused:- # The inline executor coroutine is what observes the approval and resumes the- # run, so it has to outlive this tool call instead of being cancelled.+ if run_paused or run_left_running:+ # The inline executor coroutine is the run itself (and what observes a pause's+ # approval), so it has to outlive this tool call instead of being cancelled.detached_task = asyncio.create_task(_retire_snapshot_after_execution(run_task,@@ -5221,9 +5268,9 @@ async def _run_blocks_and_collect_debug(return responsefinally:- # A paused run keeps its association so the pane still follows the run the person was- # asked to act on; the next run's generation replaces it.- if active_run_association is not None and not run_paused:+ # A paused or still-running run keeps its association so the pane still follows it; the next+ # run's generation replaces it.+ if active_run_association is not None and not (run_paused or run_left_running):try:await clear_active_run_session(organization_id=active_run_association.organization_id,diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.pyindex 91b1d0ab8..0253d933f 100644--- a/skyvern/forge/sdk/routes/workflow_copilot.py+++ b/skyvern/forge/sdk/routes/workflow_copilot.py@@ -76,7 +76,7 @@ from skyvern.forge.sdk.copilot.credential_pause import (start_manual_sign_in,)from skyvern.forge.sdk.copilot.credential_resolution import safe_admitted_url-from skyvern.forge.sdk.copilot.enforcement import TOTAL_TIMEOUT_SECONDS+from skyvern.forge.sdk.copilot.enforcement import EXPIRED_TURN_REPLY_SECONDS, TOTAL_TIMEOUT_SECONDSfrom skyvern.forge.sdk.copilot.goal_suggestion import suggest_goal_from_codefrom skyvern.forge.sdk.copilot.interruption import (INTERRUPTED_TERMINAL_REASON,@@ -227,7 +227,10 @@ _process_workflow_yaml = _copilot_process_workflow_yaml# Wall clock, unlike TOTAL_TIMEOUT_SECONDS: that budget excludes time parked in a# credential pause, so a legitimately live turn can outlast it in real time.RECONCILE_ABANDON_AFTER_SECONDS = (- TOTAL_TIMEOUT_SECONDS + settings.WORKFLOW_COPILOT_CREDENTIAL_PAUSE_TIMEOUT_SECONDS + 120+ TOTAL_TIMEOUT_SECONDS+ + settings.WORKFLOW_COPILOT_CREDENTIAL_PAUSE_TIMEOUT_SECONDS+ + EXPIRED_TURN_REPLY_SECONDS+ + 120)ALLOWED_WORKFLOW_COPILOT_AUDIO_CONTENT_TYPES = {"audio/mp4",diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.pyindex 1d9cb492b..035178370 100644--- a/tests/unit/test_copilot_agent_helpers.py+++ b/tests/unit/test_copilot_agent_helpers.py@@ -2479,6 +2479,8 @@ async def _run_tool_bearing_empty_completion_turn(runner_kwargs: dict[str, Any],start_time: float,iteration: int,+ *,+ min_remaining_seconds: float | None = None,) -> RunResultStreaming | SimpleNamespace:drain_calls.append(_DrainCall(@@ -2492,7 +2494,15 @@ async def _run_tool_bearing_empty_completion_turn()if drain_outcome is None:return await real_run_streamed_with_deadline(- agent, current_input, ctx, session, stream, runner_kwargs, start_time, iteration+ agent,+ current_input,+ ctx,+ session,+ stream,+ runner_kwargs,+ start_time,+ iteration,+ min_remaining_seconds=min_remaining_seconds,)if isinstance(drain_outcome, BaseException):raise drain_outcome@@ -7558,6 +7568,147 @@ class TestCopilotConfig:)assert blocked.result is blocked_result+ @staticmethod+ def _hit_hard_backstop(ctx: CopilotContext) -> None:+ ctx.tool_activity.append({"tool": "update_and_run_blocks", "summary": "run still going"})+ ctx.run_outcome_trace.append(interim_run_start_outcome("wr_left"))+ ctx.open_step_run_ids.append("wr_left")+ ctx.budget_expiry_state.hard_backstop_reached = True+ enforcement_module._mark_copilot_total_timeout(ctx, elapsed_seconds=990.0, iteration=3)++ @staticmethod+ def _exhaust_budget_drain(ctx: CopilotContext) -> None:+ ctx.tool_activity.append({"tool": "click", "summary": "clicked"})+ enforcement_module._mark_budget_expiry(ctx, "deadline")+ ctx.budget_expiry_state.begin_drain()+ ctx.budget_expiry_state.drain_active = False++ @staticmethod+ def _record_run_still_going(monkeypatch: pytest.MonkeyPatch) -> None:+ now = datetime.now(timezone.utc)+ monkeypatch.setattr(+ forge_app.DATABASE.workflow_runs,+ "get_workflow_run",+ AsyncMock(return_value=SimpleNamespace(status="running", failure_reason=None)),+ )+ monkeypatch.setattr(+ forge_app.DATABASE.observer,+ "get_workflow_run_blocks",+ AsyncMock(+ return_value=[+ WorkflowRunBlock(+ workflow_run_block_id=f"wrb_{label}",+ workflow_run_id="wr_left",+ organization_id="org-1",+ label=label,+ block_type=BlockType.CODE,+ status=status,+ created_at=now,+ modified_at=now,+ )+ # The repository returns rows newest first.+ for label, status in (("download_invoice", "running"), ("sign_in", "completed"))+ ]+ ),+ )++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("error", "expire", "stopped_waiting", "runs_not_in_history"),+ [+ pytest.param(+ CopilotTotalTimeoutError(),+ _hit_hard_backstop,+ True,+ [+ {+ "workflow_run_id": "wr_left",+ "status": "running",+ "failure_reason": None,+ "blocks": [+ {"label": "sign_in", "status": "completed", "failure_reason": None},+ {"label": "download_invoice", "status": "running", "failure_reason": None},+ ],+ "earlier_blocks_not_shown": 0,+ }+ ],+ id="hard_backstop",+ ),+ pytest.param(MaxTurnsExceeded("drain"), _exhaust_budget_drain, False, [], id="drain_exhausted"),+ ],+ )+ async def test_budget_expiry_without_a_report_gets_one_final_reply_from_the_recorded_runs(+ self,+ monkeypatch: pytest.MonkeyPatch,+ error: BaseException,+ expire: Callable[[CopilotContext], None],+ stopped_waiting: bool,+ runs_not_in_history: list[dict[str, Any]],+ ) -> None:+ report = "I saved the login draft. Its test run signed in and is still downloading the invoice."+ staged_workflow = MagicMock(workflow_id="w_draft")+ stage = _stage_proposal(staged_workflow)+ self._record_run_still_going(monkeypatch)++ def stage_then_expire(ctx: CopilotContext) -> None:+ stage(ctx)+ expire(ctx)++ run = await _run_tool_bearing_empty_completion_turn(+ monkeypatch,+ _fake_run_result({"type": "REPLY", "user_response": report}),+ attempts=(_EnforcementAttempt(error=error),),+ during_attempt=stage_then_expire,+ )++ [call] = run.drain_calls+ assert isinstance(call.current_input, str)+ observation = json.loads(call.current_input.removeprefix(NUDGE_SENTINEL))+ assert observation["budget_expired"] is True+ assert observation["staged_draft"] == "w_draft"+ assert observation["stopped_waiting"] is stopped_waiting+ assert observation["runs_not_in_history"] == runs_not_in_history+ assert call.model_settings.tool_choice is None+ assert call.max_turns == 1+ assert run.result.user_response == report+ assert run.result.staged_workflow is staged_workflow+ outcome = run.result.turn_outcome+ assert outcome is not None+ assert outcome.terminal_reason == "timeout"+ assert outcome.budget_expired is True+ assert outcome.budget_expiry_report_produced is True+ assert run.result.narrative_payload is not None+ assert run.result.narrative_payload["budgetExpiry"]["reportProduced"] is True++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "reply_outcome",+ [+ pytest.param(SimpleNamespace(final_output="", new_items=[]), id="empty"),+ pytest.param(RuntimeError("provider unavailable"), id="failed"),+ pytest.param(CopilotTotalTimeoutError(), id="reply_timed_out"),+ pytest.param(asyncio.CancelledError(), id="user_stopped_during_reply"),+ ],+ )+ async def test_budget_expiry_reply_that_fails_keeps_the_typed_no_report_fact(+ self, monkeypatch: pytest.MonkeyPatch, reply_outcome: SimpleNamespace | BaseException+ ) -> None:+ self._record_run_still_going(monkeypatch)+ run = await _run_tool_bearing_empty_completion_turn(+ monkeypatch,+ reply_outcome,+ attempts=(_EnforcementAttempt(error=CopilotTotalTimeoutError()),),+ during_attempt=self._hit_hard_backstop,+ )++ assert len(run.drain_calls) == 1+ assert run.result.user_response == ""+ outcome = run.result.turn_outcome+ assert outcome is not None+ assert outcome.terminal_reason == "timeout"+ assert outcome.budget_expiry_report_produced is False+ assert outcome.tool_calls == ["update_and_run_blocks"]+@staticmethoddef _withheld_reply(*reason_codes: OutputPolicyReason, user_response: str = "") -> OutputGuardrailTripwireTriggered:guardrail_result = MagicMock()diff --git a/tests/unit/test_copilot_budget_drain.py b/tests/unit/test_copilot_budget_drain.pyindex bb2797eaf..cfac729b7 100644--- a/tests/unit/test_copilot_budget_drain.py+++ b/tests/unit/test_copilot_budget_drain.py@@ -1,14 +1,17 @@from __future__ import annotations+import asyncioimport json+import timefrom datetime import UTC, datetimefrom types import SimpleNamespacefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMockimport pytest-from agents import function_tool+from agents import ModelSettings, function_toolfrom agents.exceptions import MaxTurnsExceeded+from agents.run_config import RunConfigfrom skyvern.forge.sdk.copilot import tools as tools_modulefrom skyvern.forge.sdk.copilot.agent import (@@ -18,7 +21,14 @@ from skyvern.forge.sdk.copilot.agent import ()from skyvern.forge.sdk.copilot.ask_user import QuestionInteraction, QuestionPart, QuestionResponsefrom skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal-from skyvern.forge.sdk.copilot.enforcement import BUDGET_DRAIN_HEADROOM, run_with_enforcement+from skyvern.forge.sdk.copilot.enforcement import (+ BUDGET_DRAIN_HEADROOM,+ EXPIRED_TURN_REPLY_SECONDS,+ HARD_BACKSTOP_ALLOWANCE_SECONDS,+ TOTAL_TIMEOUT_SECONDS,+ run_final_reply_drain,+ run_with_enforcement,+)from skyvern.forge.sdk.copilot.output_utils import extract_final_text, parse_final_responsefrom skyvern.forge.sdk.copilot.tools.run_execution import _run_blocks_and_collect_debugfrom skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcome@@ -369,6 +379,37 @@ def test_hard_backstop_preserves_staged_proposal_without_fallback() -> None:assert result.turn_outcome.budget_expiry_staged_draft_id == "wf_draft"+async def test_expired_turn_reply_gets_its_own_allowance_past_the_hard_backstop(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ ctx = make_copilot_ctx()+ ctx.budget_expiry_state.source = "deadline"+ ctx.copilot_run_start_monotonic = time.monotonic() - 2 * (TOTAL_TIMEOUT_SECONDS + HARD_BACKSTOP_ALLOWANCE_SECONDS)+ allowances: list[float] = []++ async def record_allowance(_result: Any, _stream: Any, stream_ctx: Any) -> None:+ when = stream_ctx.model_stream_deadline.when()+ allowances.append(when - asyncio.get_running_loop().time())++ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.enforcement.Runner.run_streamed", lambda *_args, **_kwargs: _result("")+ )+ monkeypatch.setattr("skyvern.forge.sdk.copilot.streaming_adapter.stream_to_sse", record_allowance)++ await run_final_reply_drain(+ MagicMock(),+ ctx,+ MagicMock(),+ session=None,+ hooks=MagicMock(),+ run_config=RunConfig(model_settings=ModelSettings(), tracing_disabled=True),+ )++ [allowance] = allowances+ assert allowance > EXPIRED_TURN_REPLY_SECONDS - 5++@pytest.mark.asyncio@pytest.mark.parametrize("expiry_boundary", ["model", "tool"])async def test_sdk_soft_deadline_preserves_pending_tool_and_drains_before_next_model(diff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.pyindex b5ea117b8..c1d516ff3 100644--- a/tests/unit/test_copilot_hooks.py+++ b/tests/unit/test_copilot_hooks.py@@ -3904,6 +3904,7 @@ def test_browser_overlays_are_covered_by_session_classification() -> None:async def test_lifecycle_hooks_count_model_calls_and_enforcement_passes() -> None:ctx = make_copilot_ctx()hooks = CopilotRunHooks(ctx)+ ctx.open_step_run_ids.append("wr_saved_with_its_step")await hooks.on_agent_start(MagicMock(), MagicMock())await hooks.on_llm_start(MagicMock(), MagicMock(), None, [])@@ -3911,6 +3912,8 @@ async def test_lifecycle_hooks_count_model_calls_and_enforcement_passes() -> Nonassert ctx.enforcement_pass_count == 1assert ctx.model_calls_this_turn == 2+ # The SDK saves a step before it starts the next model call, so that step's runs are in the session.+ assert ctx.open_step_run_ids == []@pytest.mark.asynciodiff --git a/tests/unit/test_copilot_watchdog.py b/tests/unit/test_copilot_watchdog.pyindex 3b4461f71..ea33a4ae8 100644--- a/tests/unit/test_copilot_watchdog.py+++ b/tests/unit/test_copilot_watchdog.py@@ -1003,6 +1003,73 @@ async def test_externally_cancelled_worker_run_still_cooperatively_cancels(harness["cooperative_cancel"].assert_awaited_once_with("wr_paused")[email protected]("dispatch_to_worker", [True, False], ids=["worker_run", "inline_run"])+async def test_the_turn_deadline_ends_the_wait_and_leaves_the_run_with_its_executor(+ monkeypatch: pytest.MonkeyPatch, dispatch_to_worker: bool+) -> None:+ """ADR-0025: the turn cap never cancels a run. The turn's hard deadline cancels this call's wait;+ the run keeps executing, and the turn still knows the cut step started it."""+ harness = await _install_run_harness(+ monkeypatch,+ workflow_yaml=_EXTRACTION_WORKFLOW_YAML,+ polled_status="running",+ dispatch_to_worker=dispatch_to_worker,+ )+ polling = asyncio.Event()++ async def _read_progress(_ctx: CopilotContext, _run_id: str) -> tuple[Any, datetime]:+ polling.set()+ return _fake_run(status="running"), datetime(2026, 4, 21, 12, 0, 0, tzinfo=UTC)++ monkeypatch.setattr(run_execution, "_read_progress_sources", _read_progress)+ monkeypatch.setattr(run_execution, "RUN_BLOCKS_POLL_INTERVAL_SECONDS", 3600)+ ctx = make_copilot_ctx(browser_session_id="pbs_chat")+ ctx.staged_workflow = harness["workflow"]+ ctx.frontier_resume_session_id = "pbs_run"+ before = set(run_execution._DETACHED_CLEANUP_TASKS)+ tool_calls: list[asyncio.Task[Any]] = []++ async def _turn_stream() -> None:+ # Shaped like _run_streamed_with_deadline over the SDK: the tool runs in its own task, the+ # stream's immediate cancel does not await it, and the deadline is cleared on the way out.+ try:+ async with asyncio.timeout(None) as deadline:+ ctx.model_stream_deadline = deadline+ tool_calls.append(+ asyncio.create_task(+ _run_blocks_and_collect_debug({"block_labels": ["extract_heading"], "parameters": {}}, ctx)+ )+ )+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ tool_calls[0].cancel()+ raise+ finally:+ ctx.model_stream_deadline = None++ turn = asyncio.create_task(_turn_stream())+ await asyncio.wait_for(polling.wait(), timeout=5)+ assert ctx.model_stream_deadline is not None+ ctx.model_stream_deadline.reschedule(asyncio.get_running_loop().time())+ with pytest.raises(TimeoutError):+ await turn+ with pytest.raises(asyncio.CancelledError):+ await tool_calls[0]++ harness["cooperative_cancel"].assert_not_awaited()+ harness["cancel_run_task"].assert_not_awaited()+ harness["clear"].assert_not_awaited()+ assert harness["executor_cancelled"] is False+ assert ctx.open_step_run_ids == ["wr_paused"]++ adopted = _adopted_detached_tasks(before)+ for task in adopted:+ task.cancel()+ await asyncio.gather(*adopted, return_exceptions=True)++def test_paused_result_records_last_test_ok_as_none() -> None:"""``None`` is the only honest value: at ``False`` the finalizer rewrites the reply into afailed test, and ``True`` would let an unapproved draft count as verified."""