Skip to content

Automate browser based workflows with AI

SKY-10346: Preserve continuation blocker signals (PR 8/12) (#6259)

Andrew Neilson31592ba51446
diff --git a/skyvern/forge/failure_classifier.py b/skyvern/forge/failure_classifier.py
index c0fdbdc68..1cdc63af6 100644
--- a/skyvern/forge/failure_classifier.py
+++ b/skyvern/forge/failure_classifier.py
@@ -37,12 +37,14 @@ def classify_from_failure_reason(
_antibot_keywords = [
"captcha",
"cloudflare",
+ "turnstile",
"bot detect",
"bot block",
"ip block",
"request block",
"anti-bot",
"human verification",
+ "verify you are human",
]
# "access denied" is ambiguous: it can be bot blocking OR auth failure.
# Only treat it as bot detection when there are no auth-related keywords nearby.
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
index 880edc79e..06038a20b 100644
--- a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
@@ -34,7 +34,7 @@ WORKFLOW-FIRST EXECUTION PATH (INCREMENTAL):
Default path for build/debug requests:
1. Do NOT draft the full workflow upfront.
2. Start by adding only the next navigation block needed to inspect or advance the target website from the current state.
-3. Call update_and_run_blocks with the workflow YAML and the current block chain. The tool preserves verified prefix state and reruns only from the earliest invalidated block, so passing the full chain is cheap and unambiguous.
+3. Call update_and_run_blocks with the complete workflow YAML and the next test frontier. For workflows with several page-changing stages, keep the complete reusable YAML but pass only the next 1-2 unverified labels in `block_labels`; shrink the test frontier, not the YAML.
4. Use run evidence (overall_status, block statuses, failure_reason, failure_categories, action_trace_summary, current_url/page_title, and the failure screenshot when included) to decide whether the task still looks fixable. For heavier diagnosis (per-block action traces, per-block output, failed-block screenshots), call get_run_results. For live-page inspection, use the direct browser tools.
6. If fixable, keep known-good blocks and add/refine only the next block, then repeat.
7. If not fixable, stop and explain the specific evidence to the user.
@@ -44,7 +44,8 @@ Continue iterating until one of these is true:
1. You have a completed workflow proposal that covers the user's full requested outcome and the latest test run is successful.
2. You have strong evidence from the latest run that the request is infeasible on the target site.
3. You are blocked by missing required user input (for example: missing credential, unresolved ambiguity, or required human-only value).
-4. The latest run evidence reports that a user-supplied input is itself invalid (for example: requested dates are in the past, requested identifier or location does not exist, or a search returned zero matches for an exact-match user value). Stop on the first run that reports this and respond with ASK_QUESTION naming the offending value and asking the user for a corrected one. Do NOT keep retrying with different selectors, URLs, or block orderings. This branch does NOT cover transient retry-able failures (network errors, anti-bot/WAF/CAPTCHA, timeouts, element-not-found mid-flow) — handle those via the FEASIBILITY CHECK and ANTI-BOT / WAF BLOCK HANDLING guidance below.
+4. The latest run evidence reports that a user-supplied input is itself invalid and a non-empty match is required to complete the workflow (for example: requested dates are in the past, or the user asked for a specific existing identifier/location/person and the site says that exact value does not exist). Stop on the first run that reports this and respond with ASK_QUESTION naming the offending value and asking the user for a corrected one. Do NOT keep retrying with different selectors, URLs, or block orderings. This branch does NOT cover transient retry-able failures (network errors, anti-bot/WAF/CAPTCHA, timeouts, element-not-found mid-flow) — handle those via the FEASIBILITY CHECK and ANTI-BOT / WAF BLOCK HANDLING guidance below.
+5. The user requested result handling conditionally (for example: "if any", "if there are any", "if results exist", "if available") and the latest run reached the searched/filtered results state with zero matches. Treat the no-results path as a valid terminal workflow state: do not ask for a corrected value, do not retry alternate selectors or inputs, and reply that the workflow was tested through the no-results outcome. Set `goal_reached: true` only if the workflow reached the searched/filtered state and captured the no-results evidence.
REQUEST POLICY: WORKFLOW CREDENTIAL INPUTS UNBOUND.
When the request-policy summary shows `clarification_reason: workflow_credential_inputs_unbound` (set by the input guardrail when the workflow references credential parameters whose keys resolve to unset workflow inputs), the run-tool is blocked but `allow_update_workflow` remains true. Call `update_workflow` to land the user's edit, then REPLY with: `"I applied your requested change. I couldn't test the modified workflow because I couldn't find the required credentials — please add them via the Credentials UI, then I can try again."` Keep the unvalidated draft surfaced so the user can accept/reject. If you call `update_and_run_blocks`, the run step is skipped automatically (the tool result will include `data.skipped_run=true` and `data.skip_reason="workflow_credential_inputs_unbound"`); use the same REPLY framing.
@@ -56,11 +57,15 @@ Prefer workflow-run evidence first. Use navigate_browser, get_browser_screenshot
3. You need to validate a specific UI hypothesis before changing the workflow.
PAGE EVIDENCE POLICY:
-Use the Skyvern MCP browser tools to fill knowledge gaps while building, editing, or debugging a workflow. The purpose is to make workflow composition evidence-based, not to add defensive verification blocks for every website shape.
+Use the Skyvern MCP browser tools to fill knowledge gaps while building, editing, or debugging a workflow. The purpose is to make your workflow composition evidence-based, not to add defensive verification blocks for every website shape.
- Do not invent website-specific paths, query parameters, form fields, result affordances, or page structure from memory. Ground them in user-supplied information, run evidence, or live MCP observations.
- Treat `goto_url` as a page-loading block. A current results URL can be useful evidence, but do not assume it is a reusable entrypoint when it may encode session-only state.
-- For form/search/result pages, inspect when you do not know the real controls or result layout. Use `inspect_page_for_composition`, `evaluate`, `get_browser_screenshot`, or targeted interaction tools as needed, then compose normal workflow blocks from the observed page.
+- For form/search/result pages, inspect when you do not know the real controls or result layout. Use `inspect_page_for_composition(target_url="current_page")`, `evaluate`, `get_browser_screenshot`, or targeted interaction tools as needed, then compose normal workflow blocks from the observed page.
+- Treat each successful run or browser observation as evidence for the current page state only. Do not author downstream row expansion or extraction that depends on a future page state until you have run the next page-changing block and inspected the reached page. If the visible results already contain the requested values, add extraction from that observed page; if an expansion is required first, add and run the expansion block before adding extraction.
- Add `validation` blocks only when the reusable workflow's task actually includes a durable check. Do not add validation or extra navigation blocks just to double-check the shape of a site before each action.
+- If page evidence shows anti-bot or challenge controls, account for that in the normal action block that reaches/submits the challenged state. Use `get_browser_screenshot` when DOM evidence identifies a challenge but does not expose the visible challenge affordance. Prefer explicit challenge handling available to Skyvern over blind waits; if the latest run shows the challenge cannot be solved, stop and report the observed blocker instead of retrying the same flow.
+- If a state-application block hits a per-tool budget, do not rerun the same navigation label unchanged. First read the budgeted run with `get_run_results`. If it reports a current URL or the browser is still on an advanced page, inspect `current_page`; answer from visible result/no-result evidence when possible, and only split/replace/run a smaller UI block after inspection shows a real missing state change.
+- When you already have a verified prefix or a live browser page that advanced beyond the workflow's entrypoint, continue from that evidence. Do not turn the observed current page into a new workflow entrypoint and rerun the whole workflow from the start. Preserve unchanged upstream labels and text, and pass `block_labels` for only the missing downstream frontier.
CRITICAL RULES WHEN USING DIRECT BROWSER TOOLS:
- If you call navigate_browser, you MUST call at least one observation tool (evaluate, get_browser_screenshot, click, type_text, scroll, select_option, press_key, or console_messages) before responding.
@@ -84,7 +89,7 @@ Do not judge feasibility from URL names or assumptions -- base it on the latest
BUILD-TEST-FIX WORKFLOW (ONE NEXT BLOCK AT A TIME):
When building or modifying workflows, follow this cycle:
-1. **Build next step**: Use get_block_schema, then call update_and_run_blocks with the workflow YAML and the current block chain (combines update + test in one call; the tool reruns only the invalidated frontier).
+1. **Build next step**: Use get_block_schema, then call update_and_run_blocks with the complete workflow YAML and the next small test frontier in `block_labels` (combines update + test in one call; the tool reruns only the invalidated or first unverified frontier).
2. **Review results**: Check overall_status, per-block status and failure_reason, failure_categories, action_trace_summary, current_url/page_title, and the failure screenshot when present. For deeper inspection, call get_run_results.
3. **Decide**: Fix current blocks, or stop as infeasible with evidence, or append the next block if current chain is good.
4. **Verify state**: Use get_browser_screenshot after runs when visual confirmation helps diagnosis.
@@ -144,10 +149,12 @@ IMPORTANT WORKFLOW RULES:
- "validation" for completion checks.
- "login" for authentication flows.
- "wait" for explicit pauses between blocks.
- - "goto_url" for direct URL navigation and grounded URL-state shortcuts.
-* Prefer a `goto_url` URL-parameter shortcut over a click-driven `navigation` block when requested state (dates, destination, search terms, stable search params) maps to a URL that is supplied by the user, observed on the site, present in a link/form/action URL, or follows a same-site pattern visible in context. Do NOT invent website-specific paths or query parameters from memory. For URL-encoded dynamic page state, `goto_url` may bootstrap the page but must be followed by a persisted verification block before extraction: use `code` for DOM checks, `validation` for semantic/visual checks, or `navigation` when missing state must be changed through the UI. Put any follow-up actions in subsequent blocks, and verify dynamic URL-state shortcuts from the live page before extraction.
-* Commit a draft workflow as soon as you have a plausible block sequence and a target URL/selector. This same commit-early rule applies when an existing workflow draft needs a well-scoped additive edit and the user has supplied a clear condition plus action target (for example, if a condition is met, go to that URL): update the YAML and call `update_and_run_blocks` instead of answering with a prose-only block outline or asking for confirmation. Do NOT walk the search UI step-by-step or fetch page contents through `evaluate`/`fetch` before the first `update_and_run_blocks` call when a `goto_url` to a likely page can be tested directly. For URL-known form/search composition, `inspect_page_for_composition` is the context-gathering exception: use it to observe the page schema before authoring downstream form/search blocks. Page introspection through direct browser tools is a fallback after a block run fails or returns ambiguous evidence, not preparation for the first run.
-* Keep `navigation_goal` to ONE atomic action per block. You MUST split into separate blocks if your `navigation_goal` would cover more than one of: (a) a search-form input, (b) a date or filter selection, (c) a results-page click into a detail view, (d) a final extraction. Conjunctions like "and"/"then"/commas separating distinct UI actions inside a single `navigation_goal` are a strong signal you are bundling — decompose. The verifier checks every sub-condition after each step, so bundled goals return "continue" until the budget exhausts. When one request maps to several sub-tasks and no `goto_url` shortcut applies, decompose into one block per sub-task chained via `next_block_label`. The final stage of search → click → extract should be an `extraction` block, not another `navigation`.
+ - "goto_url" for direct URL navigation grounded in user-provided or observed same-site URLs.
+* Use `goto_url` for direct URL navigation and for URL patterns grounded in user-provided values or observed same-site evidence. Do NOT invent website-specific paths or query parameters from memory. Put follow-up UI actions in subsequent normal workflow blocks.
+* When revising after a run, do not replace a discovered/user-requested entrypoint with the browser's current results URL just because it worked once. Current URLs often contain server/session state; preserve the reusable path and use current-page evidence to improve downstream blocks.
+* Commit a draft workflow as soon as you have enough evidence for a plausible reusable block sequence. Use Skyvern MCP inspection tools before mutation when they are needed to resolve uncertainty about the page, especially URL-known form/search composition. When an existing workflow draft needs a well-scoped additive edit, update the YAML with update_workflow or update_and_run_blocks using a clear condition plus action target instead of answering with a prose-only block outline. Do not ask for confirmation when the workflow can be updated and tested.
+* Keep `navigation_goal` scoped to one coherent page state change grounded in observed evidence, not one guessed site model and not one block per field. Do not pre-author row/detail expansion from the user's words alone: first run or inspect your way to the actual results page, then use live result-page evidence to decide whether expansion controls exist. If requested details are already visible or no explicit expansion affordance is observed, skip the expansion block and go straight to an `extraction` block. The final stage of visible results -> extract should still use an `extraction` block for data capture, not another `navigation` block.
+* Save the complete reusable workflow, but run only a small verified frontier when the workflow has several page-changing stages. `update_and_run_blocks` accepts the full YAML plus a subset of `block_labels`; for form/search workflows, first run the entry/form-state frontier, then continue with submit/results, then expansion/extraction. After a verified prefix or a budgeted run that leaves the browser on a later page, preserve the upstream workflow text and run only the missing downstream labels. Do not remove later blocks from the YAML just to shorten a test; do not submit a long chain of all blocks at once when each stage can be verified independently.
* Set `complete_criterion` on every decomposed `navigation` block to the observable post-action page state — without it, smaller blocks still return vague "continue" verdicts.
* Use descriptive, unique labels for blocks (snake_case format).
* Reference parameters using Jinja2 syntax: {% raw %}{{ parameters.param_key }}{% endraw %}
@@ -200,7 +207,7 @@ COMPOSITION PAGE INSPECTION:
* After page evidence shows a real required input the user did not supply, use `ASK_QUESTION` and name the observed field/control that needs input.
* After page evidence shows enough fields and controls, compose and run from those observed fields. Preserve the observed field/control granularity in the block goal; do not collapse distinct controls or required choices into a generic field the page does not expose.
* Treat observed page evidence as grounding context for the next standard workflow block, not as content to paste into YAML. Use it to make `navigation` or `action` interaction goals and `extraction` goals precise.
-* When the user asks to expand result rows/details, the expansion step also needs evidence. Prefer inspecting the reached result page before final extraction; result table toggles are often empty/icon-only first-column cells, `[aria-expanded]` controls, `[role="button"]` controls, buttons, or links, not necessarily text labels like "expand."
+* When the user asks to expand result rows/details, the expansion step also needs result-page evidence. Do not author or run an expansion block before you have reached or inspected the results page; if the requested details are already visible, or if no `[aria-expanded]`, `[role="button"]`, button, link, or clearly clickable row affordance is observed, omit the expansion block and proceed to extraction from the visible results.
* Use direct browser inspection tools after a run when the page shape is still ambiguous. Do not ask the user to describe the page structure when Copilot can inspect it.
WORKFLOW SUBMISSION RULE:
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index a9bf86a31..c356b4ef1 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -694,7 +694,12 @@ def _shape_ask_question_response(user_response: str, ctx: CopilotContext) -> str
def _verified_workflow_or_none(ctx: CopilotContext) -> tuple[Any, str | None]:
"""Surface a proposal only when it passed a test this turn AND yaml is on hand."""
- if ctx.last_workflow is not None and ctx.last_workflow_yaml and ctx.last_test_ok is True:
+ if (
+ ctx.last_workflow is not None
+ and ctx.last_workflow_yaml
+ and ctx.last_test_ok is True
+ and ctx.last_full_workflow_test_ok is True
+ ):
return ctx.last_workflow, ctx.last_workflow_yaml
return None, None
@@ -824,6 +829,41 @@ def _build_exit_result(
blocked_signatures=ctx.blocked_reply_signatures,
terminal_reason=terminal_reason or ("cancel" if cancelled else None),
)
+ workflow_attempted = ctx.last_update_block_count is not None or ctx.last_test_ok is not None
+ output_kind = derive_output_kind(
+ response_type="REPLY",
+ request_policy=ctx.request_policy,
+ updated_workflow=verified_workflow,
+ workflow_was_persisted=ctx.workflow_persisted,
+ workflow_attempted=workflow_attempted,
+ unvalidated=False,
+ )
+ output_policy_verdict = evaluate_output_policy(
+ request_policy=ctx.request_policy,
+ response_type="REPLY",
+ user_response=final_text,
+ global_llm_context=global_llm_context,
+ workflow_yaml=verified_yaml,
+ has_workflow_proposal=verified_workflow is not None,
+ workflow_was_persisted=ctx.workflow_persisted,
+ workflow_attempted=workflow_attempted,
+ unvalidated=False,
+ output_kind=output_kind,
+ )
+ if not output_policy_verdict.allowed:
+ return _build_output_policy_blocked_result(
+ ctx,
+ output_policy_verdict,
+ prior_global_llm_context=global_llm_context,
+ prior_workflow_yaml=verified_yaml,
+ output_policy_diagnostics=build_output_policy_diagnostics(
+ raw_verdict=output_policy_verdict,
+ final_verdict=output_policy_verdict,
+ final_output_kind=_blocked_final_output_kind(output_policy_verdict),
+ hard_block_reason_codes=list(output_policy_verdict.reason_codes),
+ soft_rewrite_reason_codes=[],
+ ),
+ )
return _finalize_result_with_blocker_override(
ctx,
_make_agent_result(
@@ -972,6 +1012,8 @@ def _finalize_result_with_blocker_override(
local_signal = getattr(ctx, "blocker_signal", None)
if not isinstance(local_signal, CopilotToolBlockerSignal):
return result
+ if not local_signal.renders_final_reply:
+ return result
rendered_reply, rendered_resp_type = _render_blocker_reply(local_signal, exit_site=exit_site)
@@ -1087,7 +1129,18 @@ def _workflow_block_count(ctx: CopilotContext) -> int | None:
def _clean_recorded_failure_text(value: Any, max_chars: int = 240) -> str:
# Caller-owned sentence templates add punctuation around these fragments.
- return clean_recorded_failure_text(value, max_chars=max_chars).rstrip(".")
+ text = clean_recorded_failure_text(value, max_chars=max_chars).rstrip(".")
+ if not text:
+ return ""
+ verdict = evaluate_output_policy(
+ request_policy=None,
+ response_type="REPLY",
+ user_response=text,
+ output_kind=CopilotOutputKind.INFORMATIONAL_ANSWER,
+ )
+ if OutputPolicyReason.INTERNAL_TOOL_INSTRUCTION_LEAK in verdict.reason_codes:
+ return "The previous workflow run did not finish before the turn budget expired"
+ return text
def _recorded_failure_summary(ctx: CopilotContext) -> tuple[str, str]:
@@ -1103,6 +1156,30 @@ def _recorded_failure_summary(ctx: CopilotContext) -> tuple[str, str]:
return reason, status_sentence
+def _recorded_failure_is_internal_tool_instruction(ctx: CopilotContext) -> bool:
+ contract = ctx.latest_diagnosis_repair_contract
+ if contract is None:
+ candidates: tuple[object, ...] = (ctx.last_test_failure_reason,)
+ else:
+ candidates = (
+ contract.verification_result.remaining_blocker,
+ contract.diagnosis_result.root_cause_summary,
+ ctx.last_test_failure_reason,
+ )
+ for value in candidates:
+ if not isinstance(value, str) or not value.strip():
+ continue
+ verdict = evaluate_output_policy(
+ request_policy=None,
+ response_type="REPLY",
+ user_response=value,
+ output_kind=CopilotOutputKind.INFORMATIONAL_ANSWER,
+ )
+ if OutputPolicyReason.INTERNAL_TOOL_INSTRUCTION_LEAK in verdict.reason_codes:
+ return True
+ return False
+
+
def _specific_missing_context_question(value: Any) -> str:
question = _clean_recorded_failure_text(value, max_chars=320)
if not question:
@@ -1191,7 +1268,9 @@ def _last_good_failure_reply(ctx: CopilotContext, tested_reply: str) -> str:
return f"{tested_reply} The latest attempted change did not verify: {reason}.{status_sentence}"
-def _recorded_failure_reply(ctx: CopilotContext, *, cancelled: bool = False) -> str | None:
+def _recorded_failure_reply(
+ ctx: CopilotContext, *, cancelled: bool = False, internal_tool_instruction_failure: bool | None = None
+) -> str | None:
if cancelled or ctx.last_test_ok is True:
return None
@@ -1222,7 +1301,9 @@ def _recorded_failure_reply(ctx: CopilotContext, *, cancelled: bool = False) ->
or getattr(ctx, "last_test_ok", None) is not None
or getattr(diagnosis_input, "workflow_run_id", None)
)
- test_failed = ctx.last_test_ok is False or run_status == "failed"
+ if internal_tool_instruction_failure is None:
+ internal_tool_instruction_failure = _recorded_failure_is_internal_tool_instruction(ctx)
+ test_failed = (ctx.last_test_ok is False or run_status == "failed") and not internal_tool_instruction_failure
unrecoverable_stop = next_action == "stop" or failure_type == "unrecoverable_tool_error"
if getattr(ctx, "last_workflow", None) is not None:
@@ -1258,7 +1339,10 @@ def _build_wip_exit_result(
terminal_reason: str | None = None,
) -> AgentResult:
"""Selected non-success exits surface the most recent successfully parsed workflow."""
- recorded_failure_reply = _recorded_failure_reply(ctx, cancelled=cancelled)
+ internal_tool_instruction_failure = _recorded_failure_is_internal_tool_instruction(ctx)
+ recorded_failure_reply = _recorded_failure_reply(
+ ctx, cancelled=cancelled, internal_tool_instruction_failure=internal_tool_instruction_failure
+ )
effective_terminal = terminal_reason or ("cancel" if cancelled else None)
def _guard(text: str) -> tuple[str, TurnOutcome]:
@@ -1310,12 +1394,15 @@ def _build_wip_exit_result(
if (
ctx.last_workflow is not None
and ctx.last_workflow_yaml
- and ctx.last_test_ok is not False
+ and (ctx.last_test_ok is not False or internal_tool_instruction_failure)
and not ctx.last_test_suspicious_success
):
- unvalidated = ctx.last_test_ok is not True
+ full_test_ok = ctx.last_test_ok is True and ctx.last_full_workflow_test_ok is True
+ unvalidated = not full_test_ok
if unvalidated and recorded_failure_reply:
reply = recorded_failure_reply
+ if internal_tool_instruction_failure:
+ reply = _ensure_unvalidated_proposal_affordance(reply)
else:
reply = unvalidated_reply if unvalidated else tested_reply
final_text, outcome = _guard(reply)
@@ -1478,8 +1565,9 @@ async def _translate_to_agent_result(
# Bind the signal to a local so the proposal-cascade gating below can't
# desync from the inline override if ctx mutates mid-translate.
local_blocker_signal = ctx.blocker_signal if isinstance(ctx.blocker_signal, CopilotToolBlockerSignal) else None
- blocker_active = local_blocker_signal is not None
- if local_blocker_signal is not None:
+ render_blocker_reply = local_blocker_signal is not None and local_blocker_signal.renders_final_reply
+ blocker_active = render_blocker_reply
+ if local_blocker_signal is not None and render_blocker_reply:
# Override only user-visible text + resp_type so REPLACE_WORKFLOW and ASK_QUESTION gating skip the model's side-effect path; the shim is the sole renderer.
rendered_reply, rendered_resp_type = _render_blocker_reply(local_blocker_signal)
user_response = rendered_reply
@@ -1526,6 +1614,8 @@ async def _translate_to_agent_result(
_record_banned_block_reject_span,
_stale_block_metadata_message,
_timing_only_challenge_wait_reject_message,
+ composition_page_evidence_error,
+ workflow_target_url,
)
wait_block_error = _timing_only_challenge_wait_reject_message(ctx, workflow_yaml)
@@ -1543,6 +1633,16 @@ async def _translate_to_agent_result(
user_response = f"{user_response}\n\n(Note: {_stale_block_metadata_message(stale_metadata)})"
ctx.last_test_ok = None
workflow_yaml = ""
+ composition_evidence_error = composition_page_evidence_error(ctx, workflow_yaml)
+ if composition_evidence_error:
+ LOG.info(
+ "copilot inline composition page evidence rejected workflow",
+ workflow_permanent_id=ctx.workflow_permanent_id,
+ target_url=workflow_target_url(workflow_yaml),
+ )
+ user_response = f"{user_response}\n\n(Note: {composition_evidence_error})"
+ ctx.last_test_ok = None
+ workflow_yaml = ""
if workflow_yaml:
try:
last_workflow = _process_workflow_yaml(
@@ -2174,10 +2274,11 @@ def _build_output_policy_blocked_result(
prior_workflow_yaml: str | None,
output_policy_diagnostics: dict[str, Any] | None = None,
) -> AgentResult:
- # A blocker turn never ships a proposal; hard-block OUTPUT_POLICY + a
- # set blocker_signal both drop the preserved draft.
+ # A blocker turn whose signal owns final rendering never ships a proposal;
+ # steering-only blockers should still flow through normal output-policy
+ # salvage so internal tool text is scrubbed and saved drafts can surface.
local_blocker_signal = ctx.blocker_signal if isinstance(ctx.blocker_signal, CopilotToolBlockerSignal) else None
- blocker_active = local_blocker_signal is not None
+ blocker_active = local_blocker_signal is not None and local_blocker_signal.renders_final_reply
preserved_workflow = (
ctx.last_workflow if ctx.last_workflow is not None and ctx.last_workflow_yaml and not blocker_active else None
)
@@ -2522,6 +2623,7 @@ async def _run_copilot_turn_impl(
# and `update_and_run_blocks`, never from a model emission.
prior_structured_context = StructuredContext.from_json_str(global_llm_context)
ctx.prior_discovery_calls_made = prior_structured_context.discovery_calls_made
+ ctx.prior_page_inspection_calls_made = prior_structured_context.page_inspection_calls_made
ctx.build_phase = initial_build_phase(
ctx.turn_intent,
chat_request.message or "",
@@ -2533,6 +2635,7 @@ async def _run_copilot_turn_impl(
build_phase=ctx.build_phase.value,
workflow_permanent_id=chat_request.workflow_permanent_id,
prior_discovery_calls_made=ctx.prior_discovery_calls_made,
+ prior_page_inspection_calls_made=ctx.prior_page_inspection_calls_made,
)
# Preflight feasibility classifier — fires on every turn so mid-session pivots
diff --git a/skyvern/forge/sdk/copilot/blocker_signal.py b/skyvern/forge/sdk/copilot/blocker_signal.py
index 4dbe8982c..2be227420 100644
--- a/skyvern/forge/sdk/copilot/blocker_signal.py
+++ b/skyvern/forge/sdk/copilot/blocker_signal.py
@@ -76,6 +76,7 @@ class CopilotToolBlockerSignal(BaseModel):
recovery_hint: RecoveryHint
cleared_by_tools: frozenset[str] = Field(default_factory=frozenset)
preserves_workflow_draft: bool = False
+ renders_final_reply: bool = True
internal_reason_code: str | None = None
blocked_tool: str | None = None
@@ -105,6 +106,7 @@ def to_trace_data(signal: CopilotToolBlockerSignal) -> dict[str, Any]:
"blocker_kind": signal.blocker_kind,
"recovery_hint": signal.recovery_hint,
"cleared_by_tools": sorted(signal.cleared_by_tools),
+ "renders_final_reply": signal.renders_final_reply,
"internal_reason_code": signal.internal_reason_code,
"blocked_tool": signal.blocked_tool,
"classifier_mode": signal.classifier_mode,
@@ -117,9 +119,41 @@ class _BlockerSignalCtx(Protocol):
blocker_signal: CopilotToolBlockerSignal | None
+_LOOP_PROGRESS_TOOL_SUCCESS_REASON_CODES = frozenset(
+ {
+ "loop_detected_credential_or_parameter_misconfig",
+ "loop_detected_repeated_failed_step",
+ "loop_detected_generic",
+ }
+)
+_LOOP_PROGRESS_TOOLS = frozenset(
+ {
+ "discover_workflow_entrypoint",
+ "evaluate",
+ "get_browser_screenshot",
+ "get_run_results",
+ "inspect_page_for_composition",
+ "navigate_browser",
+ "run_blocks_and_collect_debug",
+ "update_and_run_blocks",
+ "update_workflow",
+ }
+)
+
+
+def _tool_success_clears_signal(signal: CopilotToolBlockerSignal, succeeded_tool_name: str) -> bool:
+ if succeeded_tool_name in signal.cleared_by_tools:
+ return True
+ if signal.internal_reason_code == "loop_detected_consecutive_same_tool":
+ return True
+ if signal.internal_reason_code in _LOOP_PROGRESS_TOOL_SUCCESS_REASON_CODES:
+ return succeeded_tool_name in _LOOP_PROGRESS_TOOLS
+ return False
+
+
def maybe_clear_blocker_signal_on_tool_success(ctx: _BlockerSignalCtx, succeeded_tool_name: str) -> None:
signal = getattr(ctx, "blocker_signal", None)
- if isinstance(signal, CopilotToolBlockerSignal) and succeeded_tool_name in signal.cleared_by_tools:
+ if isinstance(signal, CopilotToolBlockerSignal) and _tool_success_clears_signal(signal, succeeded_tool_name):
ctx.blocker_signal = None
diff --git a/skyvern/forge/sdk/copilot/build_phase.py b/skyvern/forge/sdk/copilot/build_phase.py
index b3e5b813b..d1630e6d1 100644
--- a/skyvern/forge/sdk/copilot/build_phase.py
+++ b/skyvern/forge/sdk/copilot/build_phase.py
@@ -217,7 +217,7 @@ def _phase_blocker_signal(ctx: Any, tool_name: str) -> CopilotToolBlockerSignal
),
user_facing_reason="I need to know what site to work on before I can browse there. What URL should I use?",
recovery_hint="ask_user_clarifying",
- cleared_by_tools=frozenset(),
+ cleared_by_tools=frozenset({"discover_workflow_entrypoint", "update_workflow", "update_and_run_blocks"}),
internal_reason_code="build_phase_browser_blocked_pre_compose",
blocked_tool=tool_name,
)
@@ -232,7 +232,7 @@ def _phase_blocker_signal(ctx: Any, tool_name: str) -> CopilotToolBlockerSignal
),
user_facing_reason="I need to know what site to work on before I can build a workflow. What URL should I use?",
recovery_hint="ask_user_clarifying",
- cleared_by_tools=frozenset(),
+ cleared_by_tools=frozenset({"discover_workflow_entrypoint", "update_workflow", "update_and_run_blocks"}),
internal_reason_code="build_phase_mutation_blocked_pre_compose",
blocked_tool=tool_name,
)
diff --git a/skyvern/forge/sdk/copilot/config.py b/skyvern/forge/sdk/copilot/config.py
index b0ae05152..b5a389d2f 100644
--- a/skyvern/forge/sdk/copilot/config.py
+++ b/skyvern/forge/sdk/copilot/config.py
@@ -7,7 +7,7 @@ from dataclasses import dataclass, field
from skyvern.config import settings
DEFAULT_PROMPT_TEMPLATE = "workflow-copilot-agent.j2"
-DEFAULT_MAX_TURNS = 25
+DEFAULT_MAX_TURNS = 35
DEFAULT_TOKEN_BUDGET = 90_000
SCREENSHOT_DROPPED_NUDGE = (
@@ -35,9 +35,10 @@ POST_NAVIGATE_NUDGE = (
POST_INTERMEDIATE_SUCCESS_NUDGE = (
"STOP — do NOT respond to the user yet. "
"Your workflow only covers a subset of what the user asked for. "
- "You MUST add the next block now: call update_and_run_blocks with the current "
- "block chain. The tool preserves verified prefix state and reruns only the "
- "invalidated frontier, so passing the full chain is cheap. "
+ "You MUST add the next block now: call update_and_run_blocks with the complete "
+ "workflow YAML, but pass only the next 1-2 unverified block labels when the "
+ "workflow has several page-changing stages. Keep later blocks in the YAML; "
+ "shrink only the block_labels test frontier. "
"Only respond to the user when every distinct action they requested is covered "
"by a workflow block, or you have clear evidence that continuing is infeasible."
)
@@ -175,19 +176,24 @@ POST_PER_TOOL_BUDGET_NUDGE = (
"Do NOT retry the same chain. Do NOT change navigation_goal wording or "
"selectors hoping it will run faster.\n"
"1. Call get_run_results for the budgeted run. If it shows a navigation "
- "block was canceled or failed, do NOT run that same label again unchanged; "
- "split or replace it first.\n"
- "2. Shrink the requested block_labels list to the first 1-2 unverified "
+ "block was canceled or failed, do NOT run that same label again unchanged.\n"
+ "2. If get_run_results includes a current_url, inspect the current page "
+ 'before running anything else. Use inspect_page_for_composition(target_url="current_page"), '
+ "evaluate, or get_browser_screenshot. If the requested answer or a no-results "
+ "state is visible, answer from that evidence instead of rerunning the search.\n"
+ "3. If inspection shows a real missing state change, split or replace the "
+ "oversized block and shrink the requested block_labels list to the first 1-2 unverified "
"blocks. The verified-prefix optimization will replay any earlier blocks "
"from cached state without re-running the browser, so passing a smaller "
"frontier is cheap.\n"
- "3. For page-state work, prefer a code or validation block to verify DOM "
- "state, active chips, checked controls, field values, or URL deltas. Use a "
- "navigation block only when missing state must be changed through the UI, "
- "and keep it to one atomic action.\n"
- "4. Test the smaller frontier. If it succeeds, extend by one block at a "
+ "4. For page-state work, inspect the live page evidence already gathered "
+ "or use browser inspection tools before deciding what is missing. Use a "
+ "validation block only when the reusable workflow needs a durable semantic "
+ "or visual check; use navigation only when missing state must be changed "
+ "through the UI.\n"
+ "5. Test the smaller frontier. If it succeeds, extend by one block at a "
"time on subsequent calls.\n"
- "5. If your workflow only has 1-2 blocks and one block is still hitting "
+ "6. If your workflow only has 1-2 blocks and one block is still hitting "
"the budget, the single block is too ambitious — either narrow its scope, "
"replace it with DOM/state verification plus smaller actions, or reply "
"with a blocker explanation."
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 16f4048c1..9f3de1415 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -101,6 +101,7 @@ class StructuredContext(BaseModel):
# AgentResult.global_llm_context — finalized deterministically at every
# AgentResult exit by `finalize_discovery_counter_in_global_llm_context`.
discovery_calls_made: int = 0
+ page_inspection_calls_made: int = 0
def to_json_str(self) -> str:
return self.model_dump_json(indent=2)
@@ -185,10 +186,13 @@ def finalize_discovery_counter_in_global_llm_context(ctx: Any, raw_context: str
"""
prior = int(getattr(ctx, "prior_discovery_calls_made", 0) or 0)
this_turn = int(getattr(ctx, "discovery_calls_this_turn", 0) or 0)
- if not raw_context and this_turn == 0:
+ prior_inspections = int(getattr(ctx, "prior_page_inspection_calls_made", 0) or 0)
+ inspections_this_turn = int(getattr(ctx, "page_inspection_calls_this_turn", 0) or 0)
+ if not raw_context and this_turn == 0 and inspections_this_turn == 0:
return None
sc = StructuredContext.from_json_str(raw_context)
sc.discovery_calls_made = prior + this_turn
+ sc.page_inspection_calls_made = prior_inspections + inspections_this_turn
return sc.to_json_str()
@@ -300,6 +304,13 @@ class CopilotContext(AgentContext):
# retry" requests.
pending_reconciliation_run_id: str | None = None
pending_reconciliation_requires_user_input: bool = False
+ # Block-running tools make their own run context available for same-turn
+ # reporting. This is deliberately not persisted across turns. The
+ # successful variant is kept for "default to the last clean result"; the
+ # generic variant allows the agent to re-read the same failed/canceled run
+ # after a watchdog reconciliation read has cleared the retry guard.
+ last_run_blocks_workflow_run_id: str | None = None
+ last_successful_run_blocks_workflow_run_id: 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
@@ -321,6 +332,12 @@ class CopilotContext(AgentContext):
# label away from navigation. Prevents rerunning the same oversized
# navigation block unchanged.
per_tool_budget_problem_block_labels: list[str] = field(default_factory=list)
+ # Armed when a PER_TOOL_BUDGET run leaves the browser on a meaningful page.
+ # The next block-running call must be preceded by page inspection so the
+ # agent recovers from observed state instead of replaying the same search.
+ post_budget_page_inspection_required: bool = False
+ post_budget_page_inspection_url: str | None = None
+ post_budget_page_inspection_run_id: str | None = None
# Per-request frontier state. `verified_block_outputs` and
# `verified_prefix_labels` are populated ONLY from fully-successful runs —
@@ -329,8 +346,11 @@ class CopilotContext(AgentContext):
# 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)
+ verified_prefix_current_url: str | None = None
last_requested_block_labels: list[str] = field(default_factory=list)
last_executed_block_labels: list[str] = field(default_factory=list)
+ last_full_workflow_test_ok: bool = False
+ last_unverified_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
@@ -382,6 +402,8 @@ class CopilotContext(AgentContext):
# Hydrated from inbound StructuredContext.discovery_calls_made at turn start.
prior_discovery_calls_made: int = 0
discovery_calls_this_turn: int = 0
+ prior_page_inspection_calls_made: int = 0
+ page_inspection_calls_this_turn: int = 0
discovery_step_count: int = 0
discovery_started_monotonic: float | None = None
discovery_evidence_trail: list[dict[str, Any]] = field(default_factory=list)
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index 0a109808a..250685630 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -89,10 +89,10 @@ MAX_PROBABLE_SITE_BLOCK_STOP_NUDGES = 2
# trips fall through to the repeated-frontier escalation path.
MAX_PER_TOOL_BUDGET_NUDGES = 2
MIN_BLOCKS_FOR_AUTO_COMPLETE = 10
-TOTAL_TIMEOUT_SECONDS = 600
+TOTAL_TIMEOUT_SECONDS = 900
# Belt-and-braces cap alongside the elapsed-time budget. Per-nudge caps
# already prevent individual branches from looping; this stops a brand-new
-# enforcement rule that forgets its own counter from spinning within 600s.
+# enforcement rule that forgets its own counter from spinning within 900s.
MAX_ITERATIONS = 50
SCREENSHOT_SENTINEL = "[copilot:screenshot] "
NUDGE_SENTINEL = "[copilot:nudge] "
@@ -681,9 +681,16 @@ def _check_enforcement(
):
return _nudge(config, "post_update")
- # A budget-trip is a structural problem (chain too long), not a
- # workflow-shape problem — emit the targeted "split the chain" advice
- # before the generic repeated-frontier and failed-test paths can fire.
+ # If the last run had confirmed challenge evidence, do not misdiagnose a
+ # challenge-solving loop as a long-chain budgeting problem.
+ if _needs_failed_test_nudge(ctx) and getattr(ctx, "last_test_anti_bot", None):
+ ctx.failed_test_nudge_count += 1
+ return _nudge(config, "post_anti_bot_failed_test")
+
+ # A budget-trip without challenge evidence is a structural problem (chain
+ # too long), not a workflow-shape problem — emit the targeted "split the
+ # chain" advice before the generic repeated-frontier and failed-test paths
+ # can fire.
if _needs_per_tool_budget_nudge(ctx):
ctx.per_tool_budget_nudge_count = _get_int(ctx, "per_tool_budget_nudge_count") + 1
return _nudge(config, "post_per_tool_budget")
@@ -717,8 +724,6 @@ def _check_enforcement(
if _needs_failed_test_nudge(ctx):
ctx.failed_test_nudge_count += 1
- if getattr(ctx, "last_test_anti_bot", None):
- return _nudge(config, "post_anti_bot_failed_test")
return _nudge(config, "post_failed_test")
# Response-time gate: peek at the model's final output to tell ASK_QUESTION
diff --git a/skyvern/forge/sdk/copilot/loop_detection.py b/skyvern/forge/sdk/copilot/loop_detection.py
index d4091d032..f4f81c609 100644
--- a/skyvern/forge/sdk/copilot/loop_detection.py
+++ b/skyvern/forge/sdk/copilot/loop_detection.py
@@ -20,13 +20,32 @@ from collections.abc import Iterable, Mapping, MutableMapping
from typing import Any
from skyvern.forge.failure_classifier import classify_from_failure_reason
-from skyvern.forge.sdk.copilot.blocker_signal import maybe_clear_blocker_signal_on_tool_success
+from skyvern.forge.sdk.copilot.blocker_signal import (
+ clear_blocker_signal_for_reason_codes,
+ maybe_clear_blocker_signal_on_tool_success,
+)
MAX_CONSECUTIVE_SAME_TOOL = 3
MAX_REPEATED_FAILED_STEP = 3
LOOP_DETECTED_MARKER = "LOOP DETECTED:"
ARGUMENT_INSENSITIVE_FAILURE_TOOLS = frozenset({"run_blocks_and_collect_debug", "update_and_run_blocks"})
ARGUMENT_INSENSITIVE_FAILURE_CATEGORIES = frozenset({"CREDENTIAL_ERROR", "PARAMETER_BINDING_ERROR"})
+RECONCILIATION_PROGRESS_TOOL_NAMES = frozenset(
+ {
+ "click",
+ "evaluate",
+ "get_browser_screenshot",
+ "inspect_page_for_composition",
+ "press_key",
+ "run_blocks_and_collect_debug",
+ "scroll",
+ "select_option",
+ "type_text",
+ "update_and_run_blocks",
+ "update_workflow",
+ }
+)
+RECONCILIATION_REQUIRES_INPUT_REASON_CODES = frozenset({"tool_error_pending_reconciliation_requires_input"})
def detect_tool_loop(
@@ -231,6 +250,13 @@ def record_tool_step_result_for_ctx(
# Strict ``is True`` check: a malformed result dict missing ``ok`` entirely
# must not be treated as success and accidentally clear a blocker signal.
if result.get("ok") is True:
+ if (
+ getattr(ctx, "pending_reconciliation_requires_user_input", False)
+ and tool_name in RECONCILIATION_PROGRESS_TOOL_NAMES
+ ):
+ ctx.pending_reconciliation_requires_user_input = False
+ ctx.pending_reconciliation_run_id = None
+ clear_blocker_signal_for_reason_codes(ctx, RECONCILIATION_REQUIRES_INPUT_REASON_CODES)
maybe_clear_blocker_signal_on_tool_success(ctx, tool_name)
diff --git a/skyvern/forge/sdk/copilot/output_policy.py b/skyvern/forge/sdk/copilot/output_policy.py
index 77d1cf4eb..46f134469 100644
--- a/skyvern/forge/sdk/copilot/output_policy.py
+++ b/skyvern/forge/sdk/copilot/output_policy.py
@@ -42,6 +42,10 @@ _INTERNAL_TOOL_INSTRUCTION_MARKERS = (
)
_INTERNAL_TOOL_RETRY_PHRASES = ("do not retry", "do not re-invoke")
_INTERNAL_TOOL_RETRY_CONTEXT_MARKERS = (
+ "block running tool",
+ "block running tools",
+ "block-running tool",
+ "block-running tools",
"get_run_results",
"update_and_run_blocks",
"tool call",
diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.py
index 588d40439..17581be56 100644
--- a/skyvern/forge/sdk/copilot/tools.py
+++ b/skyvern/forge/sdk/copilot/tools.py
@@ -946,8 +946,12 @@ def _late_block_running_call_signal(ctx: AgentContext, tool_name: str) -> Copilo
elif isinstance(last_failed_workflow_yaml, str) and last_failed_workflow_yaml:
agent_steering = (
f"Less than {COPILOT_FINAL_REPLY_RESERVE_SECONDS} seconds remain in this Copilot turn "
- "after the previous workflow run failed. Do NOT retry block-running tools; reply to the user "
- "with the failure evidence gathered so far and make clear that any draft workflow is unverified."
+ "after the previous workflow run failed. Do NOT retry block-running tools. Use only existing "
+ "run evidence and quick browser inspection tools such as get_run_results, evaluate, or "
+ "get_browser_screenshot if one more read is needed. If the current page contains the requested "
+ "answer, answer from that observed page evidence. If evidence is incomplete, report exactly "
+ "which browser state was verified and which requested data remains unverified. Never repeat "
+ "this tool-error text as the user-facing answer."
)
else:
agent_steering = (
@@ -967,6 +971,7 @@ def _late_block_running_call_signal(ctx: AgentContext, tool_name: str) -> Copilo
# earlier in the turn should still surface — only the chat reply
# is overridden by the renderer.
preserves_workflow_draft=True,
+ renders_final_reply=False,
internal_reason_code="tool_error_late_block_running",
blocked_tool=tool_name,
)
diff --git a/tests/unit/test_copilot_agent_blocker_renderer.py b/tests/unit/test_copilot_agent_blocker_renderer.py
index 7340127b5..1064774ca 100644
--- a/tests/unit/test_copilot_agent_blocker_renderer.py
+++ b/tests/unit/test_copilot_agent_blocker_renderer.py
@@ -240,6 +240,33 @@ def test_shim_preserves_workflow_draft_when_signal_opts_in() -> None:
assert overridden.user_response != ctx.blocker_signal.user_facing_reason
+def test_shim_keeps_model_reply_when_signal_opts_out_of_final_rendering() -> None:
+ """Some tool guards are steering-only: they block a tool call but still let
+ the model answer from evidence already gathered in the turn."""
+ ctx = _ctx()
+ ctx.blocker_signal = CopilotToolBlockerSignal(
+ blocker_kind="tool_error",
+ agent_steering_text="Stop tool use and answer from gathered evidence.",
+ user_facing_reason="I'm running out of time on this turn. I'll wrap up with what I have so far.",
+ recovery_hint="stop",
+ cleared_by_tools=frozenset(),
+ preserves_workflow_draft=True,
+ renders_final_reply=False,
+ internal_reason_code="tool_error_late_block_running",
+ blocked_tool="update_and_run_blocks",
+ )
+ result = AgentResult(
+ user_response="Observed result: TEST-CRED-123 expired on 01/01/2030.",
+ updated_workflow=None,
+ global_llm_context=None,
+ workflow_yaml=None,
+ )
+
+ overridden = _finalize_result_with_blocker_override(ctx, result)
+
+ assert overridden is result
+
+
def test_preserved_draft_forces_review_untested_even_when_input_was_auto_applicable() -> None:
"""A blocker turn must never auto-apply the draft, even if the pre-override
result was tagged ``auto_applicable``. The user has to explicitly accept."""
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 15f52dfb6..49c00f5f4 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -293,7 +293,12 @@ class TestVerifiedWorkflowOrNone:
from skyvern.forge.sdk.copilot.agent import _verified_workflow_or_none
wf = self._wf()
- ctx = _ctx(last_workflow=wf, last_workflow_yaml="foo: bar", last_test_ok=True)
+ ctx = _ctx(
+ last_workflow=wf,
+ last_workflow_yaml="foo: bar",
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ )
assert _verified_workflow_or_none(ctx) == (wf, "foo: bar")
def test_zeros_when_test_failed(self) -> None:
@@ -865,7 +870,12 @@ workflow_definition:
monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._process_workflow_yaml", boom)
- ctx = _ctx(last_workflow=tested_wf, last_workflow_yaml="tested: yaml", last_test_ok=True)
+ ctx = _ctx(
+ last_workflow=tested_wf,
+ last_workflow_yaml="tested: yaml",
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ )
result = _fake_run_result(
{"type": "REPLACE_WORKFLOW", "user_response": "here", "workflow_yaml": "::: not yaml"}
)
@@ -1185,6 +1195,7 @@ workflow_definition:
last_workflow=wf,
last_workflow_yaml="title: drafted",
last_test_ok=True,
+ last_full_workflow_test_ok=True,
last_update_block_count=3,
)
result = _fake_run_result({"type": "REPLY", "user_response": "All set."})
@@ -1203,6 +1214,7 @@ workflow_definition:
last_workflow=wf,
last_workflow_yaml="title: drafted",
last_test_ok=True,
+ last_full_workflow_test_ok=True,
last_update_block_count=3,
)
result = _fake_run_result({"type": "REPLY", "user_response": "All set.", "goal_reached": True})
@@ -1370,7 +1382,12 @@ workflow_definition:
def test_unbacked_workflow_claim_not_rewritten_when_proposal_exists(self) -> None:
wf = SimpleNamespace(name="drafted")
- ctx = _ctx(last_workflow=wf, last_workflow_yaml="title: drafted", last_test_ok=True)
+ ctx = _ctx(
+ last_workflow=wf,
+ last_workflow_yaml="title: drafted",
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ )
result = _fake_run_result({"type": "REPLY", "user_response": "Here's the workflow."})
agent_result = asyncio.run(
agent_module._translate_to_agent_result(
diff --git a/tests/unit/test_copilot_agent_prompt_chat_history_resolution.py b/tests/unit/test_copilot_agent_prompt_chat_history_resolution.py
index 9597d6ead..1985c50d8 100644
--- a/tests/unit/test_copilot_agent_prompt_chat_history_resolution.py
+++ b/tests/unit/test_copilot_agent_prompt_chat_history_resolution.py
@@ -87,3 +87,12 @@ def test_workflow_credential_inputs_unbound_branch_teaches_reply_framing() -> No
assert "I applied your requested change. I couldn't test the modified workflow" in rendered
assert "add them via the Credentials UI" in rendered
assert 'data.skip_reason="workflow_credential_inputs_unbound"' in rendered
+
+
+def test_prompt_treats_conditional_zero_results_as_terminal_evidence() -> None:
+ rendered = _render_agent_prompt()
+
+ assert 'The user requested result handling conditionally (for example: "if any"' in rendered
+ assert "Treat the no-results path as a valid terminal workflow state" in rendered
+ assert "do not ask for a corrected value" in rendered
+ assert "Set `goal_reached: true` only if the workflow reached the searched/filtered state" in rendered
diff --git a/tests/unit/test_copilot_blocker_lifecycle.py b/tests/unit/test_copilot_blocker_lifecycle.py
index b42fbae27..a6bf1ae49 100644
--- a/tests/unit/test_copilot_blocker_lifecycle.py
+++ b/tests/unit/test_copilot_blocker_lifecycle.py
@@ -50,12 +50,12 @@ def test_recoverable_blocker_does_not_clear_on_unrelated_tool_success() -> None:
assert ctx.blocker_signal is signal
-def test_loop_blocker_stays_sticky_on_any_success() -> None:
+def test_loop_blocker_clears_on_progress_tool_success() -> None:
ctx = _ctx()
signal = _signal(kind="loop_detected", cleared_by=frozenset(), reason="loop_detected_generic")
ctx.blocker_signal = signal
record_tool_step_result_for_ctx(ctx, "update_workflow", {"workflow_yaml": "y"}, {"ok": True})
- assert ctx.blocker_signal is signal
+ assert ctx.blocker_signal is None
def test_terminal_tool_error_stays_sticky_on_any_success() -> None:
diff --git a/tests/unit/test_copilot_blocker_signal.py b/tests/unit/test_copilot_blocker_signal.py
index 3ef635473..6b3de24d1 100644
--- a/tests/unit/test_copilot_blocker_signal.py
+++ b/tests/unit/test_copilot_blocker_signal.py
@@ -56,6 +56,7 @@ def test_to_trace_data_surfaces_internal_fields() -> None:
assert trace["blocker_kind"] == "authority_denied"
assert trace["classifier_mode"] == "docs_answer"
assert trace["cleared_by_tools"] == ["a", "b"]
+ assert trace["renders_final_reply"] is True
assert trace["extra"] == {}
@@ -117,6 +118,28 @@ def test_maybe_clear_on_tool_success_empty_set_keeps_signal() -> None:
assert ctx.blocker_signal is signal
+def test_maybe_clear_on_tool_success_clears_consecutive_tool_loop_after_progress() -> None:
+ ctx = _Ctx()
+ ctx.blocker_signal = _make(kind="loop_detected", internal_reason_code="loop_detected_consecutive_same_tool")
+ maybe_clear_blocker_signal_on_tool_success(ctx, "get_browser_screenshot")
+ assert ctx.blocker_signal is None
+
+
+def test_maybe_clear_on_tool_success_clears_loop_after_workflow_progress() -> None:
+ ctx = _Ctx()
+ ctx.blocker_signal = _make(kind="loop_detected", internal_reason_code="loop_detected_repeated_failed_step")
+ maybe_clear_blocker_signal_on_tool_success(ctx, "update_and_run_blocks")
+ assert ctx.blocker_signal is None
+
+
+def test_maybe_clear_on_tool_success_keeps_loop_for_metadata_only_success() -> None:
+ ctx = _Ctx()
+ signal = _make(kind="loop_detected", internal_reason_code="loop_detected_repeated_failed_step")
+ ctx.blocker_signal = signal
+ maybe_clear_blocker_signal_on_tool_success(ctx, "list_credentials")
+ assert ctx.blocker_signal is signal
+
+
def test_clear_for_reason_codes_matches() -> None:
ctx = _Ctx()
ctx.blocker_signal = _make(internal_reason_code="tool_error_pending_reconciliation_no_input")
diff --git a/tests/unit/test_copilot_build_phase.py b/tests/unit/test_copilot_build_phase.py
index d01f27c35..c42464e9f 100644
--- a/tests/unit/test_copilot_build_phase.py
+++ b/tests/unit/test_copilot_build_phase.py
@@ -270,14 +270,14 @@ def test_phase_tool_error_returns_none_when_phase_attr_missing() -> None:
BuildPhase.INITIAL,
"build_phase_browser_blocked_pre_compose",
"ask_user_clarifying",
- frozenset(),
+ frozenset({"discover_workflow_entrypoint", "update_workflow", "update_and_run_blocks"}),
),
(
"update_workflow",
BuildPhase.INITIAL,
"build_phase_mutation_blocked_pre_compose",
"ask_user_clarifying",
- frozenset(),
+ frozenset({"discover_workflow_entrypoint", "update_workflow", "update_and_run_blocks"}),
),
],
)
diff --git a/tests/unit/test_copilot_context.py b/tests/unit/test_copilot_context.py
index e8a1948d4..33afb5f6c 100644
--- a/tests/unit/test_copilot_context.py
+++ b/tests/unit/test_copilot_context.py
@@ -101,8 +101,12 @@ class TestCopilotContext:
frontier_fields = {
"verified_block_outputs",
"verified_prefix_labels",
+ "verified_prefix_current_url",
+ "last_run_blocks_workflow_run_id",
"last_requested_block_labels",
"last_executed_block_labels",
+ "last_full_workflow_test_ok",
+ "last_unverified_block_labels",
"last_frontier_start_label",
"last_frontier_fingerprint",
"last_failure_signature",
@@ -126,8 +130,12 @@ class TestCopilotContext:
)
assert ctx.verified_block_outputs == {}
assert ctx.verified_prefix_labels == []
+ assert ctx.verified_prefix_current_url is None
+ assert ctx.last_run_blocks_workflow_run_id is None
assert ctx.last_requested_block_labels == []
assert ctx.last_executed_block_labels == []
+ assert ctx.last_full_workflow_test_ok is False
+ assert ctx.last_unverified_block_labels == []
assert ctx.last_frontier_start_label is None
assert ctx.last_frontier_fingerprint is None
assert ctx.last_failure_signature is None
diff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.py
index ea15a15b7..13ed614e6 100644
--- a/tests/unit/test_copilot_hooks.py
+++ b/tests/unit/test_copilot_hooks.py
@@ -315,6 +315,8 @@ class TestMCPFailedStepLoopDetection:
browser_context = SimpleNamespace(
pages=[raw_page],
on=MagicMock(),
+ _impl_obj=SimpleNamespace(_close_was_called=False, _closed=False),
+ browser=SimpleNamespace(is_connected=lambda: True),
)
browser_state = SimpleNamespace(browser_context=browser_context)
persistent_session_manager = SimpleNamespace(
diff --git a/tests/unit/test_copilot_output_policy.py b/tests/unit/test_copilot_output_policy.py
index a22006c5a..5734377a7 100644
--- a/tests/unit/test_copilot_output_policy.py
+++ b/tests/unit/test_copilot_output_policy.py
@@ -8,6 +8,7 @@ from unittest.mock import MagicMock, patch
import pytest
from skyvern.forge.sdk.copilot import agent as agent_module
+from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.output_policy import (
CopilotOutputKind,
@@ -1222,6 +1223,82 @@ def test_translate_to_agent_result_blocks_raw_secret_final_text() -> None:
assert "DO NOT PROVIDE RAW LOGIN/PASSWORD" in agent_result.user_response
+def test_output_policy_blocks_late_block_running_instruction_leak() -> None:
+ verdict = evaluate_output_policy(
+ request_policy=_policy(),
+ response_type="REPLY",
+ user_response=(
+ "Less than 90 seconds remain in this Copilot turn after the previous workflow run failed. "
+ "Do NOT retry block-running tools."
+ ),
+ )
+
+ assert OutputPolicyReason.INTERNAL_TOOL_INSTRUCTION_LEAK in verdict.reason_codes
+
+
+def test_translate_scrubs_late_block_running_leak_and_preserves_draft() -> None:
+ ctx = _ctx()
+ saved_workflow = object()
+ ctx.last_workflow = saved_workflow
+ ctx.last_workflow_yaml = "workflow_definition:\n blocks: []\n"
+ ctx.blocker_signal = CopilotToolBlockerSignal(
+ blocker_kind="tool_error",
+ agent_steering_text="Stop tool use and answer from gathered evidence.",
+ user_facing_reason="I'm running out of time on this turn. I'll wrap up with what I have so far.",
+ recovery_hint="stop",
+ cleared_by_tools=frozenset(),
+ preserves_workflow_draft=True,
+ renders_final_reply=False,
+ internal_reason_code="tool_error_late_block_running",
+ blocked_tool="update_and_run_blocks",
+ )
+
+ agent_result = asyncio.run(
+ agent_module._translate_to_agent_result(
+ _fake_run_result(
+ {
+ "type": "REPLY",
+ "user_response": (
+ "Less than 90 seconds remain in this Copilot turn after the previous workflow run failed. "
+ "Do NOT retry block-running tools."
+ ),
+ }
+ ),
+ ctx,
+ global_llm_context=None,
+ chat_request=_chat_request(),
+ organization_id="org-1",
+ )
+ )
+
+ assert agent_result.updated_workflow is saved_workflow
+ assert agent_result.clear_proposed_workflow is False
+ assert agent_result.proposal_disposition == "review_untested"
+ assert "Do NOT retry" not in agent_result.user_response
+ assert "workflow draft is still saved" in agent_result.user_response
+
+
+def test_timeout_exit_scrubs_recorded_late_block_running_leak_and_preserves_draft() -> None:
+ ctx = _ctx()
+ saved_workflow = object()
+ ctx.last_workflow = saved_workflow
+ ctx.last_workflow_yaml = "workflow_definition:\n blocks: []\n"
+ ctx.last_update_block_count = 5
+ ctx.last_test_ok = False
+ ctx.last_test_failure_reason = (
+ "Less than 90 seconds remain in this Copilot turn after the previous workflow run failed. "
+ "Do NOT retry block-running tools."
+ )
+
+ agent_result = agent_module._build_timeout_exit_result(ctx, global_llm_context=None)
+
+ assert agent_result.updated_workflow is saved_workflow
+ assert agent_result.clear_proposed_workflow is False
+ assert agent_result.proposal_disposition == "review_untested"
+ assert "Do NOT retry" not in agent_result.user_response
+ assert "draft workflow proposal" in agent_result.user_response
+
+
def test_translate_to_agent_result_rewrites_unbacked_workflow_claim() -> None:
result = _fake_run_result({"type": "REPLY", "user_response": "I've drafted a workflow for you."})
diff --git a/tests/unit/test_copilot_timeout_wip.py b/tests/unit/test_copilot_timeout_wip.py
index f886e0420..484365139 100644
--- a/tests/unit/test_copilot_timeout_wip.py
+++ b/tests/unit/test_copilot_timeout_wip.py
@@ -44,6 +44,7 @@ def _ctx(
ctx.last_workflow = last_workflow
ctx.last_workflow_yaml = last_workflow_yaml
ctx.last_test_ok = last_test_ok
+ ctx.last_full_workflow_test_ok = last_test_ok is True
ctx.last_test_suspicious_success = last_test_suspicious_success
ctx.copilot_total_timeout_exceeded = False
ctx.workflow_persisted = last_workflow is not None
@@ -297,6 +298,27 @@ class TestBuildUnexpectedErrorExitResult:
"Browser session was no longer reachable. Last run status: running."
)
+ def test_failed_test_scrubs_recorded_internal_tool_instruction(self) -> None:
+ wf = MagicMock(name="wf")
+ ctx = _ctx(last_workflow=wf, last_workflow_yaml="version: '1.0'", last_test_ok=False)
+ ctx.last_update_block_count = 3
+ ctx.latest_diagnosis_repair_contract = _blocker_contract(
+ "Less than 90 seconds remain in this Copilot turn after the previous workflow run failed. "
+ "Do NOT retry block-running tools. Use only existing run evidence and quick browser inspection.",
+ run_status="canceled",
+ )
+
+ result = _build_unexpected_error_exit_result(ctx, global_llm_context=None)
+
+ assert result.user_response.startswith(
+ "I built a 3-block draft and tested it, but the test couldn't finish: "
+ "The previous workflow run did not finish before the turn budget expired. "
+ "Last run status: canceled."
+ )
+ assert "draft workflow proposal" in result.user_response
+ assert "Do NOT" not in result.user_response
+ assert "block-running tools" not in result.user_response
+
def test_aborted_test_surfaces_unvalidated_draft_with_recorded_blocker_reply(self) -> None:
wf = MagicMock(name="wf")
ctx = _ctx(last_workflow=wf, last_workflow_yaml="version: '1.0'", last_test_ok=None)
diff --git a/tests/unit/test_copilot_tool_loop_error_block_running.py b/tests/unit/test_copilot_tool_loop_error_block_running.py
index ec70ecae7..1552a0cd9 100644
--- a/tests/unit/test_copilot_tool_loop_error_block_running.py
+++ b/tests/unit/test_copilot_tool_loop_error_block_running.py
@@ -64,16 +64,19 @@ def test_block_running_tool_is_blocked_by_repeated_action_streak() -> None:
def test_block_running_tool_blocks_late_retry_after_failed_workflow() -> None:
ctx = _ctx(
last_failed_workflow_yaml="version: '1.0'",
- copilot_run_start_monotonic=time.monotonic() - 540,
+ copilot_run_start_monotonic=time.monotonic()
+ - (TOTAL_TIMEOUT_SECONDS - COPILOT_FINAL_REPLY_RESERVE_SECONDS + 10),
)
msg = _tool_loop_error(ctx, "update_and_run_blocks")
assert msg is not None
+ assert ctx.blocker_signal.renders_final_reply is False
assert "less than 90 seconds" in msg.lower()
assert "Do NOT retry" in msg
- assert "reply to the user" in msg
- assert "any draft workflow is unverified" in msg
+ assert "quick browser inspection tools" in msg
+ assert "answer from that observed page evidence" in msg
+ assert "Never repeat this tool-error text" in msg
def test_late_retry_guard_allows_latter_half_calls_when_reply_room_remains() -> None:
@@ -89,7 +92,8 @@ def test_block_running_tool_blocks_late_continuation_after_successful_prefix() -
ctx = _ctx(
last_workflow_yaml="version: '1.0'",
last_test_ok=True,
- copilot_run_start_monotonic=time.monotonic() - 540,
+ copilot_run_start_monotonic=time.monotonic()
+ - (TOTAL_TIMEOUT_SECONDS - COPILOT_FINAL_REPLY_RESERVE_SECONDS + 10),
)
msg = _tool_loop_error(ctx, "update_and_run_blocks")
diff --git a/tests/unit/test_failure_classifier.py b/tests/unit/test_failure_classifier.py
index 538a71f87..e9b46064e 100644
--- a/tests/unit/test_failure_classifier.py
+++ b/tests/unit/test_failure_classifier.py
@@ -31,6 +31,7 @@ class TestAntiBotDetection:
"Access denied by WAF",
"Anti-bot system triggered",
"Human verification required",
+ "Cloudflare Turnstile still says verify you are human",
"The current page shows an 'Access Denied' error",
"Access Denied - website blocked the request",
],