Skip to content

Automate browser based workflows with AI

feat(SKY-10559): reveal collapsed sidebar flyout on hover (#6270)

Suchintan29195537880c
diff --git a/skyvern-frontend/src/components/SidebarTreeNav.tsx b/skyvern-frontend/src/components/SidebarTreeNav.tsx
index 58d6e4d24..17a700726 100644
--- a/skyvern-frontend/src/components/SidebarTreeNav.tsx
+++ b/skyvern-frontend/src/components/SidebarTreeNav.tsx
@@ -133,6 +133,150 @@ function useIsActive() {
);
}
+// Open on hover only after a brief rest, so a cursor crossing the icon rail doesn't flash menus open.
+const FLYOUT_OPEN_DELAY_MS = 100;
+// Keep the flyout open briefly after the cursor leaves, so it can bridge the gap to the content.
+const FLYOUT_CLOSE_DELAY_MS = 120;
+
+function CollapsedNavItem({
+ item,
+ groupStorageKey,
+ triggerClassName,
+ iconClassName,
+ menuChildItemClassName,
+}: {
+ item: SidebarNavItem;
+ groupStorageKey: string;
+ triggerClassName: string;
+ iconClassName: string;
+ menuChildItemClassName: string;
+}) {
+ const [open, setOpen] = useState(false);
+ const hoverTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const clearHoverTimer = useCallback(() => {
+ if (hoverTimerRef.current !== null) {
+ clearTimeout(hoverTimerRef.current);
+ hoverTimerRef.current = null;
+ }
+ }, []);
+
+ const scheduleHover = useCallback(
+ (nextOpen: boolean, delay: number) => {
+ clearHoverTimer();
+ hoverTimerRef.current = setTimeout(() => {
+ hoverTimerRef.current = null;
+ setOpen(nextOpen);
+ }, delay);
+ },
+ [clearHoverTimer],
+ );
+
+ useEffect(() => {
+ return () => {
+ clearHoverTimer();
+ };
+ }, [clearHoverTimer]);
+
+ return (
+ <DropdownMenu open={open} onOpenChange={setOpen} modal={false}>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ title={item.label}
+ className={triggerClassName}
+ onMouseEnter={() => scheduleHover(true, FLYOUT_OPEN_DELAY_MS)}
+ onMouseLeave={() => scheduleHover(false, FLYOUT_CLOSE_DELAY_MS)}
+ >
+ <span className={iconClassName}>{item.icon}</span>
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ side="right"
+ align="start"
+ onMouseEnter={clearHoverTimer}
+ onMouseLeave={() => scheduleHover(false, FLYOUT_CLOSE_DELAY_MS)}
+ className="min-w-48 border-neutral-200 bg-white p-1 text-neutral-900 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-100"
+ >
+ <DropdownMenuItem asChild>
+ <Link
+ to={item.to}
+ className={cn(menuChildItemClassName, "font-semibold")}
+ >
+ <span className="flex size-3.5 shrink-0 items-center justify-center text-neutral-500 dark:text-neutral-400">
+ {item.icon}
+ </span>
+ <span className="min-w-0 flex-1 truncate">{item.label}</span>
+ {item.badge ? (
+ <span className="rounded bg-neutral-200 px-1.5 py-0.5 text-[9px] font-medium uppercase leading-none text-neutral-500 dark:bg-white/[0.06] dark:text-neutral-400">
+ {item.badge}
+ </span>
+ ) : null}
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ {(item.children ?? []).map((child) => {
+ const childKey = `${groupStorageKey}-${child.to ?? child.label}`;
+ const content = (
+ <>
+ {child.icon ? (
+ <span className="flex size-3.5 shrink-0 items-center justify-center text-neutral-500 dark:text-neutral-400">
+ {child.icon}
+ </span>
+ ) : null}
+ <span className="truncate">{child.label}</span>
+ </>
+ );
+
+ if (child.to && child.external) {
+ return (
+ <DropdownMenuItem key={childKey} asChild>
+ <a
+ href={child.to}
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={() => child.onClick?.()}
+ className={menuChildItemClassName}
+ >
+ {content}
+ </a>
+ </DropdownMenuItem>
+ );
+ }
+
+ if (child.to) {
+ return (
+ <DropdownMenuItem key={childKey} asChild>
+ <Link
+ to={child.to}
+ onClick={() => child.onClick?.()}
+ className={menuChildItemClassName}
+ >
+ {content}
+ </Link>
+ </DropdownMenuItem>
+ );
+ }
+
+ return (
+ <DropdownMenuItem
+ key={childKey}
+ disabled={child.disabled}
+ onSelect={(event) => {
+ event.preventDefault();
+ child.onClick?.();
+ }}
+ className={menuChildItemClassName}
+ >
+ {content}
+ </DropdownMenuItem>
+ );
+ })}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
function SidebarTreeNav({ items }: Props) {
const collapsed = useSidebarStore((state) => state.collapsed);
const isActive = useIsActive();
@@ -284,101 +428,13 @@ function SidebarTreeNav({ items }: Props) {
/>
</button>
) : hasChildren && collapsed ? (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <button
- type="button"
- title={item.label}
- className={topLevelClassName}
- >
- <span className={topLevelIconClassName}>{item.icon}</span>
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- side="right"
- align="start"
- className="min-w-48 border-neutral-200 bg-white p-1 text-neutral-900 dark:border-neutral-800 dark:bg-neutral-950 dark:text-neutral-100"
- >
- <DropdownMenuItem asChild>
- <Link
- to={item.to}
- className={cn(menuChildItemClassName, "font-semibold")}
- >
- <span className="flex size-3.5 shrink-0 items-center justify-center text-neutral-500 dark:text-neutral-400">
- {item.icon}
- </span>
- <span className="min-w-0 flex-1 truncate">
- {item.label}
- </span>
- {item.badge ? (
- <span className="rounded bg-neutral-200 px-1.5 py-0.5 text-[9px] font-medium uppercase leading-none text-neutral-500 dark:bg-white/[0.06] dark:text-neutral-400">
- {item.badge}
- </span>
- ) : null}
- </Link>
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- {(item.children ?? []).map((child) => {
- const childKey = `${groupStorageKey}-${
- child.to ?? child.label
- }`;
- const content = (
- <>
- {child.icon ? (
- <span className="flex size-3.5 shrink-0 items-center justify-center text-neutral-500 dark:text-neutral-400">
- {child.icon}
- </span>
- ) : null}
- <span className="truncate">{child.label}</span>
- </>
- );
-
- if (child.to && child.external) {
- return (
- <DropdownMenuItem key={childKey} asChild>
- <a
- href={child.to}
- target="_blank"
- rel="noopener noreferrer"
- onClick={() => child.onClick?.()}
- className={menuChildItemClassName}
- >
- {content}
- </a>
- </DropdownMenuItem>
- );
- }
-
- if (child.to) {
- return (
- <DropdownMenuItem key={childKey} asChild>
- <Link
- to={child.to}
- onClick={() => child.onClick?.()}
- className={menuChildItemClassName}
- >
- {content}
- </Link>
- </DropdownMenuItem>
- );
- }
-
- return (
- <DropdownMenuItem
- key={childKey}
- disabled={child.disabled}
- onSelect={(event) => {
- event.preventDefault();
- child.onClick?.();
- }}
- className={menuChildItemClassName}
- >
- {content}
- </DropdownMenuItem>
- );
- })}
- </DropdownMenuContent>
- </DropdownMenu>
+ <CollapsedNavItem
+ item={item}
+ groupStorageKey={groupStorageKey}
+ triggerClassName={topLevelClassName}
+ iconClassName={topLevelIconClassName}
+ menuChildItemClassName={menuChildItemClassName}
+ />
) : (
<Link
to={item.to}
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index c356b4ef1..4726914ab 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -10,11 +10,11 @@ import contextlib
import json
import re
import uuid
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
from opentelemetry import trace as otel_trace
@@ -124,6 +124,11 @@ _COPILOT_TURN_SPAN_NAME = "copilot.turn"
_USER_MESSAGE_PREVIEW_MAX_CHARS = 40
+@runtime_checkable
+class _AgentInstructionsContext(Protocol):
+ context: object
+
+
def _build_user_message_preview(message: str) -> str:
flattened = (message or "").replace("\r", " ").replace("\n", " ").strip()
redacted = redact_raw_secrets_for_prompt(flattened)
@@ -390,12 +395,32 @@ def _build_system_prompt(
)
-def _build_dynamic_system_prompt(tool_usage_guide: str, config: CopilotConfig) -> Any:
+def _runtime_verification_evidence_prompt(ctx: CopilotContext | None) -> str:
+ if ctx is None:
+ return ""
+ evidence = ctx.workflow_verification_evidence
+ rendered = evidence.render_prompt_block()
+ if not rendered:
+ return ""
+ return (
+ "\n\nRUNTIME VERIFICATION EVIDENCE:\n```yaml\n" + escape_code_fences(rendered) + "\n```\n"
+ "Use this structured state before choosing the next action. If "
+ "`full_workflow_verified` is false, choose an evidence-grounded next step: split an oversized block, "
+ "continue from observed current browser state, run only missing block labels, or report partial verification. "
+ "Do not claim end-to-end verification unless `full_workflow_verified` is true."
+ )
+
+
+def _build_dynamic_system_prompt(tool_usage_guide: str, config: CopilotConfig) -> Callable[[object, object], str]:
base_system_prompt = _build_system_prompt(tool_usage_guide=tool_usage_guide, config=config)
- def instructions(context: Any, _agent: Any) -> str:
- ctx = getattr(context, "context", None)
- policy = getattr(ctx, "request_policy", None)
+ def instructions(context: object, _agent: object) -> str:
+ if not isinstance(context, _AgentInstructionsContext):
+ return base_system_prompt
+ ctx = context.context
+ if not isinstance(ctx, CopilotContext):
+ return base_system_prompt
+ policy = ctx.request_policy
if not isinstance(policy, RequestPolicy):
return base_system_prompt
policy_summary = escape_code_fences(redact_raw_secrets_for_prompt(policy.prompt_summary()))
@@ -412,7 +437,7 @@ def _build_dynamic_system_prompt(tool_usage_guide: str, config: CopilotConfig) -
+ "and tell the user to store the redacted secret as a saved credential before testing. "
+ "If `resolved_credentials` are present, use those `credential_id` values."
)
- return prompt + _docs_answer_turn_directive(getattr(ctx, "turn_intent", None))
+ return prompt + _runtime_verification_evidence_prompt(ctx) + _docs_answer_turn_directive(ctx.turn_intent)
return instructions
@@ -623,6 +648,36 @@ _FAILURE_FOLLOW_UP = {
}
+def _partial_verification_response(ctx: CopilotContext) -> str | None:
+ evidence = ctx.workflow_verification_evidence
+ if not evidence.has_evidence():
+ return None
+ if evidence.full_workflow_verified:
+ return None
+
+ detail_parts: list[str] = []
+ if evidence.block_verified:
+ detail_parts.append("verified block(s): " + ", ".join(evidence.block_verified[:6]))
+ if evidence.live_page_state_verified:
+ page = evidence.page_title or evidence.current_url or "the current browser page"
+ detail_parts.append(f"verified current browser state: {page}")
+ if evidence.per_tool_budget_on_block:
+ detail_parts.append("per-tool budget hit on: " + ", ".join(evidence.per_tool_budget_on_block[:6]))
+ if evidence.unverified_block_labels:
+ detail_parts.append("unverified block(s): " + ", ".join(evidence.unverified_block_labels[:6]))
+
+ details = " ".join(detail_parts)
+ if details:
+ return (
+ "I saved a draft workflow and verified part of it, but the full workflow chain has not been "
+ f"verified end-to-end. {details}. Keep the draft to iterate on, or discard."
+ )
+ return (
+ "I saved a draft workflow, but the full workflow chain has not been verified end-to-end. "
+ "Keep the draft to iterate on, or discard."
+ )
+
+
def _rewrite_failed_test_response(user_response: str, ctx: CopilotContext) -> str:
has_keepable_draft = ctx.last_workflow is not None and bool(ctx.last_workflow_yaml)
keep_draft_affordance = " Keep the draft to iterate on, or discard." if has_keepable_draft else ""
@@ -659,6 +714,11 @@ def _rewrite_failed_test_response(user_response: str, ctx: CopilotContext) -> st
f"Failure: {failure_summary}.{follow_up}{keep_draft_affordance}"
)
+ if ctx.last_test_ok is True and ctx.last_full_workflow_test_ok is False and has_keepable_draft:
+ partial_reply = _partial_verification_response(ctx)
+ if partial_reply is not None:
+ return partial_reply
+
if ctx.last_test_ok is None and ctx.last_update_block_count is not None and ctx.last_workflow is not None:
if policy is not None and policy.raw_secret_handling == "redacted_draft":
return (
@@ -893,6 +953,80 @@ def _build_exit_result(
)
+def _build_goal_satisfied_exit_result(ctx: CopilotContext, global_llm_context: str | None) -> AgentResult:
+ # Bypass one extra LLM turn after a full workflow test already satisfies
+ # the diagnosis contract.
+ verified_workflow, verified_yaml = _verified_workflow_or_none(ctx)
+ user_response = "I created and tested the workflow successfully."
+ final_text, outcome = apply_repeated_reply_guard(
+ final_text=user_response,
+ attempted_kind=derive_response_kind(ctx.turn_intent),
+ blocked_signatures=ctx.blocked_reply_signatures,
+ terminal_reason="verified_goal_satisfied",
+ turn_intent=ctx.turn_intent,
+ 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"))
+ ],
+ )
+ structured = StructuredContext.from_json_str(global_llm_context)
+ structured.merge_turn_summary(ctx.tool_activity)
+ enriched_context = structured.to_json_str()
+ 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=True,
+ unvalidated=False,
+ )
+ output_policy_verdict = evaluate_output_policy(
+ request_policy=ctx.request_policy,
+ response_type="REPLY",
+ user_response=final_text,
+ global_llm_context=enriched_context,
+ workflow_yaml=verified_yaml,
+ has_workflow_proposal=verified_workflow is not None,
+ workflow_was_persisted=ctx.workflow_persisted,
+ workflow_attempted=True,
+ 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(
+ ctx,
+ user_response=final_text,
+ updated_workflow=verified_workflow,
+ global_llm_context=enriched_context or None,
+ response_type="REPLY",
+ workflow_yaml=verified_yaml,
+ workflow_was_persisted=ctx.workflow_persisted,
+ total_tokens=ctx.total_tokens_used,
+ proposal_disposition="auto_applicable",
+ turn_outcome=outcome,
+ turn_id=ctx.turn_id,
+ narrative_summary=ctx.narrative_summary,
+ ),
+ exit_site="verified_goal_satisfied",
+ )
+
+
_TIMEOUT_REPLY_DEFAULT = "I ran out of time processing your request. Here's what I have so far."
_TIMEOUT_REPLY_UNVALIDATED = (
"I ran out of time before I could finish testing. I have a draft workflow you can keep — "
@@ -2661,10 +2795,12 @@ async def _run_copilot_turn_impl(
from skyvern.cli.mcp_tools import mcp as skyvern_mcp
from skyvern.forge.sdk.copilot.enforcement import (
+ CopilotGoalSatisfied,
CopilotNonRetriableNavError,
CopilotTotalTimeoutError,
CopilotUnrecoverableToolError,
run_with_enforcement,
+ verified_goal_satisfied_context,
)
from skyvern.forge.sdk.copilot.hooks import CopilotRunHooks
from skyvern.forge.sdk.copilot.mcp_adapter import SkyvernOverlayMCPServer
@@ -2876,6 +3012,13 @@ async def _run_copilot_turn_impl(
prior_workflow_yaml=chat_request.workflow_yaml,
output_policy_diagnostics=_output_policy_diagnostics_from_guardrail_exception(exc),
)
+ except CopilotGoalSatisfied:
+ LOG.info(
+ "Copilot run stopped after verified goal satisfaction",
+ workflow_permanent_id=chat_request.workflow_permanent_id,
+ workflow_run_id=ctx.last_successful_run_blocks_workflow_run_id,
+ )
+ return _build_goal_satisfied_exit_result(ctx, global_llm_context)
except MaxTurnsExceeded:
return _build_max_turns_exit_result(ctx, global_llm_context)
except CopilotTotalTimeoutError:
@@ -2934,5 +3077,20 @@ async def _run_copilot_turn_impl(
exit_site="non_retriable_nav",
)
except Exception as e:
+ try:
+ goal_satisfied = verified_goal_satisfied_context(ctx)
+ except Exception:
+ LOG.error("Copilot agent error", error=str(e), exc_info=True)
+ return _build_unexpected_error_exit_result(ctx, global_llm_context, error=e)
+ if goal_satisfied:
+ # The Agents SDK can wrap exceptions raised from hooks; keep this
+ # fallback so a verified-goal stop is not rendered as a generic error.
+ LOG.info(
+ "Copilot run stopped after verified goal satisfaction from wrapped exception",
+ workflow_permanent_id=chat_request.workflow_permanent_id,
+ workflow_run_id=ctx.last_successful_run_blocks_workflow_run_id,
+ error_type=type(e).__name__,
+ )
+ return _build_goal_satisfied_exit_result(ctx, global_llm_context)
LOG.error("Copilot agent error", error=str(e), exc_info=True)
return _build_unexpected_error_exit_result(ctx, global_llm_context, error=e)
diff --git a/skyvern/forge/sdk/copilot/composition_evidence.py b/skyvern/forge/sdk/copilot/composition_evidence.py
index 22351fa15..d3a6676f0 100644
--- a/skyvern/forge/sdk/copilot/composition_evidence.py
+++ b/skyvern/forge/sdk/copilot/composition_evidence.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Any
+from typing import Any, Protocol
from urllib.parse import urljoin, urlparse
import yaml
@@ -13,11 +13,13 @@ except ImportError: # pragma: no cover - bs4 is a transitive dep but inspection
BeautifulSoup = None # type: ignore[assignment, misc]
from skyvern.forge.sdk.copilot.build_phase import BuildPhase
+from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
from skyvern.utils.yaml_loader import safe_load_no_dates
_BUILD_MODE_VALUES: frozenset[str] = frozenset({"build", "draft_only", "edit", "unknown"})
_PAGE_SHAPING_BLOCK_TYPES: frozenset[str] = frozenset({"navigation", "login"})
_PAGE_READING_BLOCK_TYPES: frozenset[str] = frozenset({"extraction"})
+_GOTO_URL_BLOCK_TYPE = "goto_url"
_SCHEMA_EVIDENCE_TOOL = "inspect_page_for_composition"
_STRUCTURED_BROWSER_EVIDENCE_TOOLS: frozenset[str] = frozenset({"evaluate"})
_POST_RUN_CONTINUATION_EVIDENCE_TOOLS: frozenset[str] = frozenset({"inspect_page_for_composition", "evaluate"})
@@ -46,6 +48,14 @@ _MAX_VISUAL_OMISSIONS = 5
_ANTI_BOT_SCAN_BYTES = 250_000
+class _PostRunCompositionContext(Protocol):
+ composition_page_evidence: dict[str, Any] | None
+ per_tool_budget_problem_block_labels: list[str]
+ workflow_verification_evidence: WorkflowVerificationEvidence
+ post_run_page_observation_after_failed_test: bool
+ last_failure_category_top: str | None
+
+
def _bounded_string(value: Any, max_chars: int) -> str:
if not isinstance(value, str):
return ""
@@ -309,6 +319,27 @@ def _new_page_reading_blocks(workflow_yaml: str | None, previous_workflow_yaml:
return blocks
+def _changed_goto_url_blocks(workflow_yaml: str | None, previous_workflow_yaml: str | None) -> list[dict[str, str]]:
+ previous_urls = {
+ (str(block.get("label") or ""), str(block.get("block_type") or "").strip().lower()): str(block.get("url") or "")
+ for block in _parse_workflow_blocks(previous_workflow_yaml)
+ }
+ blocks: list[dict[str, str]] = []
+ for block in _parse_workflow_blocks(workflow_yaml):
+ block_type = str(block.get("block_type") or "").strip().lower()
+ if block_type != _GOTO_URL_BLOCK_TYPE:
+ continue
+ label = str(block.get("label") or "<missing label>")
+ url = str(block.get("url") or "").strip()
+ if not url:
+ continue
+ prior_url = previous_urls.get((label, block_type))
+ if prior_url == url:
+ continue
+ blocks.append({"label": label, "url": url})
+ return blocks
+
+
def _format_page_block_findings(blocks: list[dict[str, str]]) -> str:
return ", ".join(f"{block['label']} ({block['block_type']})" for block in blocks[:5])
@@ -343,6 +374,61 @@ def _same_origin(left: str | None, right: str | None) -> bool:
return left_parsed.netloc.lower() == right_parsed.netloc.lower()
+def _same_url_ignoring_fragment(left: str | None, right: str | None) -> bool:
+ if not left or not right:
+ return False
+ try:
+ left_parsed = urlparse(left)
+ right_parsed = urlparse(right)
+ except Exception:
+ return False
+ return left_parsed._replace(fragment="").geturl() == right_parsed._replace(fragment="").geturl()
+
+
+def _post_run_recovery_state(ctx: _PostRunCompositionContext) -> bool:
+ if any(ctx.per_tool_budget_problem_block_labels):
+ return True
+ if any(ctx.workflow_verification_evidence.per_tool_budget_on_block):
+ return True
+ if ctx.post_run_page_observation_after_failed_test is True:
+ return True
+ return ctx.last_failure_category_top == "PER_TOOL_BUDGET"
+
+
+def _post_run_observed_url_goto_error(
+ ctx: _PostRunCompositionContext,
+ workflow_yaml: str | None,
+ previous_workflow_yaml: str | None,
+) -> str | None:
+ if not previous_workflow_yaml or not _post_run_recovery_state(ctx):
+ return None
+
+ evidence = ctx.composition_page_evidence
+ if not isinstance(evidence, dict) or evidence.get("observed_after_workflow_run") is not True:
+ return None
+ observed_url = evidence.get("current_url")
+ if not isinstance(observed_url, str) or not observed_url.strip():
+ return None
+
+ offending = [
+ block
+ for block in _changed_goto_url_blocks(workflow_yaml, previous_workflow_yaml)
+ if _same_url_ignoring_fragment(block.get("url"), observed_url)
+ ]
+ if not offending:
+ return None
+
+ labels = ", ".join(block["label"] for block in offending[:5])
+ return (
+ "Workflow validation failed: the draft is trying to persist a post-run browser URL as a new goto_url "
+ "block after an incomplete or budgeted run. That URL may encode record-specific, result-page, or "
+ "session state. Keep the reusable entrypoint and verified upstream blocks, then either extract from "
+ "the observed current page, split or replace the budgeted frontier into smaller reusable UI actions, "
+ "or report partial verification. "
+ f"Offending goto_url block(s): {labels}."
+ )
+
+
def _has_bounded_page_schema(evidence: dict[str, Any]) -> bool:
for key in ("forms", "navigation_targets", "result_containers", "challenge_controls"):
value = evidence.get(key)
@@ -397,6 +483,10 @@ def composition_page_evidence_error(ctx: Any, workflow_yaml: str | None) -> str
if not _mode_requires_evidence(ctx):
return None
previous_workflow_yaml = getattr(ctx, "workflow_yaml", None)
+ post_run_url_error = _post_run_observed_url_goto_error(ctx, workflow_yaml, previous_workflow_yaml)
+ if post_run_url_error:
+ return post_run_url_error
+
page_shaping_blocks = _new_page_shaping_blocks(workflow_yaml, previous_workflow_yaml)
page_reading_blocks = _new_page_reading_blocks(workflow_yaml, previous_workflow_yaml)
if not page_shaping_blocks and not page_reading_blocks:
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 9f3de1415..d2deb8a25 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -12,6 +12,7 @@ from typing_extensions import NotRequired, TypedDict
from skyvern.forge.sdk.copilot.build_phase import BuildPhase
from skyvern.forge.sdk.copilot.runtime import AgentContext
+from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
from skyvern.forge.sdk.workflow.models.workflow import Workflow
ResponseType = Literal["REPLY", "ASK_QUESTION", "REPLACE_WORKFLOW"]
@@ -351,6 +352,7 @@ class CopilotContext(AgentContext):
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)
+ workflow_verification_evidence: WorkflowVerificationEvidence = field(default_factory=WorkflowVerificationEvidence)
last_frontier_start_label: str | None = None
last_frontier_fingerprint: str | None = None
last_failure_signature: str | None = None
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index 52ea8d69c..cdeb32417 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -34,6 +34,7 @@ from skyvern.forge.sdk.copilot.config import (
SCREENSHOT_DROPPED_NUDGE,
CopilotConfig,
)
+from skyvern.forge.sdk.copilot.diagnosis_repair_contract import RepairNextAction
from skyvern.forge.sdk.copilot.failure_tracking import PER_TOOL_BUDGET_FAILURE_CATEGORY, normalize_failure_reason
from skyvern.forge.sdk.copilot.narration import TransitionKind
from skyvern.forge.sdk.copilot.output_policy import normalize_response_scaffolding
@@ -50,6 +51,7 @@ if TYPE_CHECKING:
from agents.agent import Agent
from agents.result import RunResultStreaming
+ from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.runtime import AgentContext
from skyvern.forge.sdk.routes.event_source_stream import EventSourceStream
@@ -207,6 +209,41 @@ class CopilotTotalTimeoutError(Exception):
"""Raised when the copilot agent exceeds the total allowed runtime."""
+class CopilotGoalSatisfied(Exception):
+ """Raised when a tool proves the workflow already satisfies the turn."""
+
+
+def latest_diagnosis_contract_satisfies_goal(ctx: CopilotContext) -> bool:
+ contract = ctx.latest_diagnosis_repair_contract
+ if contract is None:
+ return False
+ verification = contract.verification_result
+ repair_decision = contract.repair_decision
+ return (
+ verification.user_goal_satisfied is True
+ and verification.completion_contract_satisfied is True
+ and repair_decision.next_action is RepairNextAction.NO_CHANGE
+ )
+
+
+def verified_goal_satisfied_context(ctx: CopilotContext) -> bool:
+ return (
+ ctx.last_test_ok is True
+ and ctx.last_full_workflow_test_ok is True
+ and latest_diagnosis_contract_satisfies_goal(ctx)
+ and not _verified_goal_likely_needs_more_work(ctx)
+ )
+
+
+def _verified_goal_likely_needs_more_work(ctx: CopilotContext) -> bool:
+ block_count = ctx.last_update_block_count
+ if not isinstance(block_count, int):
+ return False
+ user_message = ctx.user_message
+ completion_contract = _request_completion_contract(ctx)
+ return _goal_likely_needs_more_blocks(user_message, block_count, completion_contract)
+
+
def _mark_copilot_total_timeout(ctx: Any) -> None:
ctx.copilot_total_timeout_exceeded = True
@@ -402,10 +439,10 @@ def _raise_if_unrecoverable_contract_stop(ctx: Any) -> None:
_ACTION_CATEGORIES: list[list[str]] = [
["navigate", "go to", "open", "visit"],
["download", "save", "export"],
- ["extract", "scrape", "collect", "gather", "get all"],
+ ["extract", "scrape", "collect", "gather", "get all", "grab", "capture", "retrieve", "pull"],
["login", "log in", "sign in", "authenticate"],
- ["search", "find", "look for", "look up"],
- ["fill", "enter", "type", "submit", "complete the form"],
+ ["search", "find", "look for", "look up", "check", "verify"],
+ ["fill", "enter", "type", "submit", "complete the form", "input"],
["click", "select", "choose", "pick"],
["upload", "attach"],
]
diff --git a/skyvern/forge/sdk/copilot/hooks.py b/skyvern/forge/sdk/copilot/hooks.py
index 877878bea..e08e1d90a 100644
--- a/skyvern/forge/sdk/copilot/hooks.py
+++ b/skyvern/forge/sdk/copilot/hooks.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+from collections.abc import Mapping
from typing import TYPE_CHECKING, Any
import structlog
@@ -11,11 +12,12 @@ from agents.lifecycle import RunHooksBase
from agents.run_context import RunContextWrapper
from agents.tool import Tool
+from skyvern.forge.sdk.copilot.enforcement import CopilotGoalSatisfied, verified_goal_satisfied_context
from skyvern.forge.sdk.copilot.output_utils import summarize_tool_result
from skyvern.forge.sdk.copilot.streaming_adapter import parse_tool_output
if TYPE_CHECKING:
- from skyvern.forge.sdk.copilot.runtime import AgentContext
+ from skyvern.forge.sdk.copilot.context import CopilotContext
LOG = structlog.get_logger()
@@ -25,12 +27,31 @@ LOG = structlog.get_logger()
_BLOCK_OUTPUT_TOOLS: frozenset[str] = frozenset(
{"run_blocks_and_collect_debug", "get_run_results", "update_and_run_blocks"}
)
+_VERIFIED_GOAL_CONTEXT_ATTRS: frozenset[str] = frozenset(
+ {
+ "last_test_ok",
+ "last_full_workflow_test_ok",
+ "last_update_block_count",
+ "latest_diagnosis_repair_contract",
+ "user_message",
+ }
+)
+
+
+def _tool_completion_satisfies_turn(ctx: CopilotContext, tool_name: str, parsed: Mapping[str, object]) -> bool:
+ if tool_name not in {"run_blocks_and_collect_debug", "update_and_run_blocks"}:
+ return False
+ if parsed.get("ok") is not True:
+ return False
+ if not all(hasattr(ctx, attr) for attr in _VERIFIED_GOAL_CONTEXT_ATTRS):
+ return False
+ return verified_goal_satisfied_context(ctx)
class CopilotRunHooks(RunHooksBase):
"""Record tool activity for StructuredContext.merge_turn_summary()."""
- def __init__(self, ctx: AgentContext) -> None:
+ def __init__(self, ctx: CopilotContext) -> None:
self._ctx = ctx
async def on_tool_end(
@@ -80,3 +101,14 @@ class CopilotRunHooks(RunHooksBase):
tool=getattr(tool, "name", None),
exc_info=True,
)
+ return
+
+ if _tool_completion_satisfies_turn(self._ctx, tool_name, parsed):
+ LOG.info(
+ "copilot tool satisfied goal; stopping agent loop",
+ tool_name=tool_name,
+ workflow_run_id=(parsed.get("data") or {}).get("workflow_run_id")
+ if isinstance(parsed.get("data"), dict)
+ else None,
+ )
+ raise CopilotGoalSatisfied()
diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.py
index 69722f167..802b56280 100644
--- a/skyvern/forge/sdk/copilot/output_utils.py
+++ b/skyvern/forge/sdk/copilot/output_utils.py
@@ -365,7 +365,8 @@ def summarize_tool_result(tool_name: str, result: dict[str, Any]) -> str:
if not result.get("ok", False):
return f"Failed: {_sanitize_failure_text(_extract_failure_message(result))}"
- data = result.get("data") or {}
+ raw_data = result.get("data")
+ data = raw_data if isinstance(raw_data, dict) else {}
if tool_name == "update_workflow":
return f"Workflow updated ({data.get('block_count', '?')} blocks)"
@@ -382,7 +383,7 @@ def summarize_tool_result(tool_name: str, result: dict[str, Any]) -> str:
return f"Block '{data.get('label', '?')}' is valid"
return "Block validation failed"
if tool_name == "run_blocks_and_collect_debug":
- if not isinstance(data, dict):
+ if not isinstance(raw_data, dict):
return "Run debug completed"
executed = data.get("executed_block_labels") or [b.get("label", "?") for b in data.get("blocks", [])]
status = data.get("overall_status", "?")
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index df6e78a04..d36ae65df 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -27,6 +27,7 @@ from skyvern.cli.core.session_manager import (
from skyvern.forge import app
from skyvern.forge.sdk.copilot.screenshot_utils import ScreenshotEntry
from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
+from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
from skyvern.forge.sdk.core import skyvern_context
from skyvern.library.skyvern_browser import SkyvernBrowser
@@ -124,6 +125,7 @@ class AgentContext:
verified_prefix_labels: list[str] = field(default_factory=list)
last_full_workflow_test_ok: bool = False
last_unverified_block_labels: list[str] = field(default_factory=list)
+ workflow_verification_evidence: WorkflowVerificationEvidence = field(default_factory=WorkflowVerificationEvidence)
# Enforcement state. Set lazily by streaming_adapter, tools, and
# failure_tracking; declared here so _check_enforcement can read them on a
diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.py
index 76728a7e1..8c45ad964 100644
--- a/skyvern/forge/sdk/copilot/tools.py
+++ b/skyvern/forge/sdk/copilot/tools.py
@@ -8,6 +8,7 @@ import json
import re
import time
from collections import Counter, defaultdict
+from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Literal
@@ -103,6 +104,7 @@ from skyvern.forge.sdk.copilot.turn_intent import (
TurnIntent,
TurnIntentMode,
)
+from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
from skyvern.forge.sdk.routes.workflow_copilot import _process_workflow_yaml
from skyvern.forge.sdk.settings_manager import SettingsManager
from skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPException
@@ -613,6 +615,45 @@ def _mark_pending_reconciliation_run(copilot_ctx: Any, workflow_run_id: str) ->
copilot_ctx.pending_reconciliation_requires_user_input = False
+def _workflow_verification_evidence(ctx: AgentContext) -> WorkflowVerificationEvidence:
+ return ctx.workflow_verification_evidence
+
+
+def _run_result_label_list(data: Mapping[str, object], key: str) -> list[str]:
+ values = data.get(key)
+ if not isinstance(values, list):
+ return []
+ return list(dict.fromkeys(str(value).strip() for value in values if str(value).strip()))
+
+
+def _run_result_blocks(data: Mapping[str, object]) -> list[Mapping[str, object]]:
+ blocks = data.get("blocks")
+ return [block for block in blocks if isinstance(block, dict)] if isinstance(blocks, list) else []
+
+
+def _completed_run_block_labels(data: Mapping[str, object]) -> list[str]:
+ labels = [
+ str(block.get("label") or "").strip()
+ for block in _run_result_blocks(data)
+ if _enum_or_string_name(block.get("status")) == WorkflowRunStatus.completed.value
+ ]
+ labels = list(dict.fromkeys(label for label in labels if label))
+ return labels or _run_result_label_list(data, "executed_block_labels")
+
+
+def _failed_run_block_labels(data: Mapping[str, object]) -> list[str]:
+ labels = [
+ str(block.get("label") or "").strip()
+ for block in _run_result_blocks(data)
+ if _enum_or_string_name(block.get("status")) in _FAILED_BLOCK_STATUSES
+ ]
+ labels = list(dict.fromkeys(label for label in labels if label))
+ if labels:
+ return labels
+ frontier = data.get("frontier_start_label")
+ return [frontier] if isinstance(frontier, str) and frontier.strip() else []
+
+
def _enum_or_string_name(value: Any) -> str:
raw = getattr(value, "value", value)
if not isinstance(raw, str):
@@ -1265,6 +1306,14 @@ def _mark_post_run_page_observed(ctx: AgentContext, *, source_tool: str, url: st
ctx.post_run_page_observation_url = url
ctx.post_run_page_observation_workflow_run_id = run_id
ctx.post_run_page_observation_after_failed_test = getattr(ctx, "last_test_ok", None) is False
+ evidence = _workflow_verification_evidence(ctx)
+ evidence.live_page_state_verified = True
+ evidence.verified_from_current_browser_state = True
+ evidence.workflow_run_id = run_id
+ if url:
+ evidence.current_url = url
+ evidence.current_url_observed_after_workflow_run = True
+ evidence.current_url_may_encode_runtime_state = bool(urlparse(url).query)
def _allows_post_run_current_page_inspection_budget_bypass(ctx: AgentContext, *, use_current_page: bool) -> bool:
@@ -4061,6 +4110,8 @@ def _record_composition_page_observation(
if not url:
return
_mark_post_run_page_observed(ctx, source_tool=source_tool, url=url)
+ if title:
+ _workflow_verification_evidence(ctx).page_title = title[:160]
existing = ctx.composition_page_evidence
if isinstance(existing, dict) and existing.get("source_tool") == "inspect_page_for_composition":
return
@@ -4947,6 +4998,48 @@ def _detect_non_retriable_nav_error(result: dict[str, Any]) -> str | None:
return next((reason for reason in iter_failure_reasons(result) if is_skip_inner_retry_error(reason)), None)
+def _update_verification_evidence_from_run_result(copilot_ctx: AgentContext, result: Mapping[str, object]) -> None:
+ evidence = _workflow_verification_evidence(copilot_ctx)
+ data_value = result.get("data")
+ data: Mapping[str, object] = data_value if isinstance(data_value, dict) else {}
+ run_ok = bool(result.get("ok", False))
+ full_workflow_verified = run_ok and copilot_ctx.last_full_workflow_test_ok is True
+ evidence.full_workflow_verified = full_workflow_verified
+ evidence.test_attempted_but_incomplete = not full_workflow_verified
+
+ run_id = data.get("workflow_run_id")
+ if isinstance(run_id, str) and run_id.strip():
+ evidence.workflow_run_id = run_id.strip()
+ current_url = _valid_runtime_anchor_url(data.get("current_url"))
+ if current_url is not None:
+ evidence.current_url = current_url
+ evidence.live_page_state_verified = True
+ if data.get("observed_after_workflow_run") is True:
+ evidence.current_url_observed_after_workflow_run = True
+ evidence.current_url_may_encode_runtime_state = bool(urlparse(current_url).query)
+ page_title = data.get("page_title")
+ if isinstance(page_title, str) and page_title.strip():
+ evidence.page_title = " ".join(page_title.split())[:160]
+
+ if run_ok:
+ evidence.merge_verified_blocks(_completed_run_block_labels(data))
+ unverified = list(copilot_ctx.last_unverified_block_labels or [])
+ evidence.unverified_block_labels = list(dict.fromkeys(str(label) for label in unverified if str(label)))
+ evidence.failed_block_labels = []
+ evidence.failure_reason = None
+ if evidence.unverified_block_labels:
+ evidence.verified_from_current_browser_state = True
+ return
+
+ failed_labels = _failed_run_block_labels(data)
+ evidence.failed_block_labels = failed_labels
+ if copilot_ctx.last_failure_category_top == PER_TOOL_BUDGET_FAILURE_CATEGORY:
+ evidence.merge_per_tool_budget_blocks(failed_labels)
+ failure_reason = copilot_ctx.last_test_failure_reason or result.get("error")
+ if isinstance(failure_reason, str) and failure_reason.strip():
+ evidence.failure_reason = " ".join(failure_reason.split())[:240]
+
+
def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:
run_ok = bool(result.get("ok", False))
data = result.get("data")
@@ -5026,6 +5119,7 @@ def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:
}
data["failure_categories"] = [anti_bot_category]
update_repeated_failure_state(copilot_ctx, result)
+ _update_verification_evidence_from_run_result(copilot_ctx, result)
return
if empty_data_blocks:
copilot_ctx.last_test_ok = None
@@ -5040,6 +5134,7 @@ def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:
# Clean-ish success (no scrape-fail pattern): reset the streak.
copilot_ctx.probable_site_block_streak_count = 0
update_repeated_failure_state(copilot_ctx, result)
+ _update_verification_evidence_from_run_result(copilot_ctx, result)
return
copilot_ctx.failed_test_nudge_count = 0
copilot_ctx.null_data_streak_count = 0
@@ -5060,6 +5155,7 @@ def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:
+ ", ".join(unverified[:8])
)
update_repeated_failure_state(copilot_ctx, result)
+ _update_verification_evidence_from_run_result(copilot_ctx, result)
return
copilot_ctx.last_failed_workflow_yaml = getattr(copilot_ctx, "workflow_yaml", None)
@@ -5082,6 +5178,7 @@ def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:
if result.get("error") and copilot_ctx.last_test_failure_reason is None:
copilot_ctx.last_test_failure_reason = str(result["error"])
update_repeated_failure_state(copilot_ctx, result)
+ _update_verification_evidence_from_run_result(copilot_ctx, result)
def _record_diagnosis_repair_contract(
@@ -6205,6 +6302,9 @@ async def _inspect_page_for_composition_impl(
"observed_after_workflow_run": True,
}
_mark_post_run_page_observed(copilot_ctx, source_tool="inspect_page_for_composition", url=current_url)
+ page_title = evidence.get("page_title")
+ if isinstance(page_title, str) and page_title:
+ _workflow_verification_evidence(copilot_ctx).page_title = page_title[:160]
copilot_ctx.page_inspection_calls_this_turn += 1
if bypass_budget_for_post_run_current_page:
@@ -6594,4 +6694,5 @@ NATIVE_TOOLS = [
get_run_results_tool,
update_and_run_blocks_tool,
discover_workflow_entrypoint_tool,
+ inspect_page_for_composition_tool,
]
diff --git a/skyvern/forge/sdk/copilot/verification_evidence.py b/skyvern/forge/sdk/copilot/verification_evidence.py
new file mode 100644
index 000000000..853ed2641
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/verification_evidence.py
@@ -0,0 +1,98 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+
+def _dedupe(values: list[str]) -> list[str]:
+ return list(dict.fromkeys(value for value in values if value))
+
+
+@dataclass
+class WorkflowVerificationEvidence:
+ full_workflow_verified: bool = False
+ block_verified: list[str] = field(default_factory=list)
+ live_page_state_verified: bool = False
+ test_attempted_but_incomplete: bool = False
+ per_tool_budget_on_block: list[str] = field(default_factory=list)
+ verified_from_current_browser_state: bool = False
+ current_url_observed_after_workflow_run: bool = False
+ current_url_may_encode_runtime_state: bool = False
+ current_url: str | None = None
+ page_title: str | None = None
+ workflow_run_id: str | None = None
+ unverified_block_labels: list[str] = field(default_factory=list)
+ failed_block_labels: list[str] = field(default_factory=list)
+ failure_reason: str | None = None
+
+ def merge_verified_blocks(self, labels: list[str]) -> None:
+ self.block_verified = _dedupe([*self.block_verified, *labels])
+
+ def merge_per_tool_budget_blocks(self, labels: list[str]) -> None:
+ self.per_tool_budget_on_block = _dedupe([*self.per_tool_budget_on_block, *labels])
+
+ def has_evidence(self) -> bool:
+ return bool(
+ self.full_workflow_verified
+ or self.block_verified
+ or self.live_page_state_verified
+ or self.test_attempted_but_incomplete
+ or self.per_tool_budget_on_block
+ or self.verified_from_current_browser_state
+ or self.current_url_observed_after_workflow_run
+ or self.current_url_may_encode_runtime_state
+ or self.current_url
+ or self.workflow_run_id
+ or self.unverified_block_labels
+ or self.failed_block_labels
+ or self.failure_reason
+ )
+
+ def to_trace_data(self) -> dict[str, bool | int]:
+ return {
+ "full_workflow_verified": self.full_workflow_verified,
+ "block_verified_count": len(self.block_verified),
+ "live_page_state_verified": self.live_page_state_verified,
+ "test_attempted_but_incomplete": self.test_attempted_but_incomplete,
+ "per_tool_budget_on_block_count": len(self.per_tool_budget_on_block),
+ "verified_from_current_browser_state": self.verified_from_current_browser_state,
+ "current_url_observed_after_workflow_run": self.current_url_observed_after_workflow_run,
+ "current_url_may_encode_runtime_state": self.current_url_may_encode_runtime_state,
+ "has_current_url": bool(self.current_url),
+ "has_workflow_run_id": bool(self.workflow_run_id),
+ "unverified_block_count": len(self.unverified_block_labels),
+ "failed_block_count": len(self.failed_block_labels),
+ "has_failure_reason": bool(self.failure_reason),
+ }
+
+ def render_prompt_block(self) -> str:
+ if not self.has_evidence():
+ return ""
+
+ lines = [
+ f"full_workflow_verified: {str(self.full_workflow_verified).lower()}",
+ f"live_page_state_verified: {str(self.live_page_state_verified).lower()}",
+ f"test_attempted_but_incomplete: {str(self.test_attempted_but_incomplete).lower()}",
+ f"verified_from_current_browser_state: {str(self.verified_from_current_browser_state).lower()}",
+ ]
+ if self.current_url_observed_after_workflow_run:
+ lines.append("current_url_observed_after_workflow_run: true")
+ if self.current_url_may_encode_runtime_state:
+ lines.append("current_url_may_encode_runtime_state: true")
+ for key, values in (
+ ("block_verified", self.block_verified),
+ ("per_tool_budget_on_block", self.per_tool_budget_on_block),
+ ("unverified_block_labels", self.unverified_block_labels),
+ ("failed_block_labels", self.failed_block_labels),
+ ):
+ if values:
+ lines.append(f"{key}:")
+ lines.extend(f" - {value}" for value in values[:12])
+ if self.current_url:
+ lines.append(f"current_url: {self.current_url}")
+ if self.page_title:
+ lines.append(f"page_title: {self.page_title}")
+ if self.workflow_run_id:
+ lines.append(f"workflow_run_id: {self.workflow_run_id}")
+ if self.failure_reason:
+ lines.append(f"failure_reason: {self.failure_reason}")
+ return "\n".join(lines)
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 82a7b3358..4475ee687 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -15,7 +15,16 @@ from skyvern.forge.sdk.api.llm.exceptions import LLMProviderError
from skyvern.forge.sdk.copilot import agent as agent_module
from skyvern.forge.sdk.copilot.build_phase import BuildPhase
from skyvern.forge.sdk.copilot.config import CopilotConfig
+from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (
+ DiagnosisInput,
+ DiagnosisRepairContract,
+ DiagnosisResult,
+ RepairDecision,
+ RepairNextAction,
+ VerificationResult,
+)
from skyvern.forge.sdk.copilot.enforcement import (
+ CopilotGoalSatisfied,
CopilotNonRetriableNavError,
CopilotTotalTimeoutError,
CopilotUnrecoverableToolError,
@@ -30,6 +39,7 @@ from skyvern.forge.sdk.copilot.request_policy import (
)
from skyvern.forge.sdk.copilot.turn_context import TranscriptContext, TurnContextOmission, TurnContextPacket
from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentMode
+from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
from skyvern.forge.sdk.schemas.workflow_copilot import (
WorkflowCopilotChatHistoryMessage,
WorkflowCopilotChatSender,
@@ -64,6 +74,18 @@ def _ctx(**overrides):
return CopilotContext(**defaults)
+def _verified_goal_contract(*, next_action: RepairNextAction = RepairNextAction.NO_CHANGE) -> DiagnosisRepairContract:
+ return DiagnosisRepairContract(
+ diagnosis_input=DiagnosisInput(source_tool="update_and_run_blocks"),
+ diagnosis_result=DiagnosisResult(),
+ repair_decision=RepairDecision(next_action=next_action),
+ verification_result=VerificationResult(
+ user_goal_satisfied=True,
+ completion_contract_satisfied=True,
+ ),
+ )
+
+
class TestFailedTestResponseNormalization:
def test_rewrite_failed_test_response_avoids_success_language(self) -> None:
from skyvern.forge.sdk.copilot.agent import _rewrite_failed_test_response
@@ -164,6 +186,90 @@ class TestFailedTestResponseNormalization:
assert ctx.last_test_ok is False
assert ctx.last_test_failure_reason == "net::ERR_NAME_NOT_RESOLVED"
+ def test_per_tool_budget_run_records_structured_verification_evidence(self) -> None:
+ from skyvern.forge.sdk.copilot.failure_tracking import PER_TOOL_BUDGET_FAILURE_CATEGORY
+ from skyvern.forge.sdk.copilot.tools import _record_run_blocks_result
+
+ ctx = _ctx(
+ last_workflow_yaml="""
+workflow_definition:
+ blocks:
+ - label: search_registry
+ block_type: navigation
+ - label: extract_results
+ block_type: extraction
+""",
+ )
+
+ _record_run_blocks_result(
+ ctx,
+ {
+ "ok": False,
+ "data": {
+ "workflow_run_id": "wr_budget",
+ "overall_status": "canceled",
+ "current_url": "https://example.com/lookup",
+ "page_title": "Example Lookup Registry",
+ "executed_block_labels": ["search_registry"],
+ "frontier_start_label": "search_registry",
+ "failure_categories": [{"category": PER_TOOL_BUDGET_FAILURE_CATEGORY}],
+ "blocks": [
+ {
+ "label": "search_registry",
+ "status": "canceled",
+ "failure_reason": "Per-tool-call budget exceeded while making progress.",
+ }
+ ],
+ },
+ },
+ )
+
+ evidence = ctx.workflow_verification_evidence
+ assert evidence.full_workflow_verified is False
+ assert evidence.test_attempted_but_incomplete is True
+ assert evidence.per_tool_budget_on_block == ["search_registry"]
+ assert evidence.live_page_state_verified is True
+ assert evidence.current_url == "https://example.com/lookup"
+ assert evidence.workflow_run_id == "wr_budget"
+
+ def test_current_state_block_run_records_partial_verification_evidence(self) -> None:
+ from skyvern.forge.sdk.copilot.tools import _record_run_blocks_result
+
+ ctx = _ctx(
+ last_workflow_yaml="""
+workflow_definition:
+ blocks:
+ - label: search_registry
+ block_type: navigation
+ - label: extract_results
+ block_type: extraction
+ - label: expand_results
+ block_type: navigation
+""",
+ verified_prefix_labels=["search_registry", "extract_results"],
+ )
+
+ _record_run_blocks_result(
+ ctx,
+ {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_extract",
+ "overall_status": "completed",
+ "current_url": "https://example.com/lookup",
+ "executed_block_labels": ["extract_results"],
+ "frontier_start_label": "extract_results",
+ "blocks": [{"label": "extract_results", "status": "completed"}],
+ },
+ },
+ )
+
+ evidence = ctx.workflow_verification_evidence
+ assert evidence.full_workflow_verified is False
+ assert evidence.block_verified == ["extract_results"]
+ assert evidence.verified_from_current_browser_state is True
+ assert evidence.unverified_block_labels == ["expand_results"]
+
def test_rewrite_includes_navigation_follow_up_when_category_matches(self) -> None:
from skyvern.forge.sdk.copilot.agent import _rewrite_failed_test_response
@@ -307,6 +413,56 @@ class TestFailedTestResponseNormalization:
assert "test failed" in rewritten.lower()
assert "keep the draft" in rewritten.lower()
+ def test_partial_verification_rewrite_uses_structured_evidence(self) -> None:
+ from skyvern.forge.sdk.copilot.agent import _rewrite_failed_test_response
+
+ ctx = _ctx(
+ last_workflow=object(),
+ last_workflow_yaml="title: drafted",
+ last_test_ok=True,
+ last_full_workflow_test_ok=False,
+ workflow_verification_evidence=WorkflowVerificationEvidence(
+ block_verified=["extract_results"],
+ live_page_state_verified=True,
+ verified_from_current_browser_state=True,
+ per_tool_budget_on_block=["search_registry"],
+ unverified_block_labels=["search_registry"],
+ page_title="Example Lookup Registry",
+ ),
+ )
+
+ rewritten = _rewrite_failed_test_response("I created and tested the workflow end-to-end.", ctx)
+
+ assert "created and tested" not in rewritten.lower()
+ assert "full workflow chain has not been verified end-to-end" in rewritten
+ assert "verified block(s): extract_results" in rewritten
+ assert "per-tool budget hit on: search_registry" in rewritten
+
+ def test_runtime_verification_evidence_prompt_surfaces_state_for_agent(self) -> None:
+ ctx = _ctx(
+ workflow_verification_evidence=WorkflowVerificationEvidence(
+ block_verified=["extract_results"],
+ live_page_state_verified=True,
+ test_attempted_but_incomplete=True,
+ per_tool_budget_on_block=["search_registry"],
+ verified_from_current_browser_state=True,
+ current_url_observed_after_workflow_run=True,
+ current_url_may_encode_runtime_state=True,
+ unverified_block_labels=["search_registry"],
+ current_url="https://example.com/lookup",
+ )
+ )
+
+ prompt = agent_module._runtime_verification_evidence_prompt(ctx)
+
+ assert "RUNTIME VERIFICATION EVIDENCE" in prompt
+ assert "full_workflow_verified: false" in prompt
+ assert "test_attempted_but_incomplete: true" in prompt
+ assert "current_url_observed_after_workflow_run: true" in prompt
+ assert "current_url_may_encode_runtime_state: true" in prompt
+ assert "per_tool_budget_on_block:" in prompt
+ assert "run only missing block labels" in prompt
+
class TestVerifiedWorkflowOrNone:
"""SKY-9143 strict invariant: a proposal surfaces only after a passing test this turn."""
@@ -373,6 +529,95 @@ class TestVerifiedWorkflowOrNone:
assert _verified_workflow_or_none(ctx) == (None, None)
+class TestVerifiedGoalSatisfiedStop:
+ @pytest.mark.asyncio
+ async def test_block_run_hook_stops_after_verified_goal_satisfied(self) -> None:
+ from skyvern.forge.sdk.copilot.hooks import CopilotRunHooks
+
+ ctx = _ctx(
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ latest_diagnosis_repair_contract=_verified_goal_contract(),
+ )
+ hook = CopilotRunHooks(ctx)
+ result = json.dumps(
+ {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_1",
+ "blocks": [{"label": "search", "output": {"status": "found"}}],
+ },
+ }
+ )
+
+ with pytest.raises(CopilotGoalSatisfied):
+ await hook.on_tool_end(
+ context=MagicMock(),
+ agent=MagicMock(),
+ tool=SimpleNamespace(name="update_and_run_blocks"),
+ result=result,
+ )
+
+ assert ctx.tool_activity[-1]["tool"] == "update_and_run_blocks"
+
+ def test_wrapped_goal_satisfied_error_context_is_recognized(self) -> None:
+ from skyvern.forge.sdk.copilot.enforcement import verified_goal_satisfied_context
+
+ ctx = _ctx(
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ latest_diagnosis_repair_contract=_verified_goal_contract(),
+ )
+
+ assert verified_goal_satisfied_context(ctx)
+
+ def test_wrapped_goal_satisfied_error_context_requires_no_change(self) -> None:
+ from skyvern.forge.sdk.copilot.enforcement import verified_goal_satisfied_context
+
+ ctx = _ctx(
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ latest_diagnosis_repair_contract=_verified_goal_contract(next_action=RepairNextAction.REPAIR),
+ )
+
+ assert not verified_goal_satisfied_context(ctx)
+
+ def test_verified_goal_satisfied_context_rejects_undercovered_workflow(self) -> None:
+ from skyvern.forge.sdk.copilot.enforcement import verified_goal_satisfied_context
+
+ ctx = _ctx(
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ last_update_block_count=1,
+ user_message=(
+ "go to https://example.com/lookup and check the requested credential "
+ "type for any sample record. I want to grab the credential name, id, expiration"
+ ),
+ latest_diagnosis_repair_contract=_verified_goal_contract(),
+ )
+
+ assert not verified_goal_satisfied_context(ctx)
+
+ def test_goal_satisfied_exit_result_surfaces_tested_workflow(self) -> None:
+ from skyvern.forge.sdk.copilot.agent import _build_goal_satisfied_exit_result
+
+ workflow = object()
+ ctx = _ctx(
+ last_workflow=workflow,
+ last_workflow_yaml="workflow_definition:\n blocks: []\n",
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ tool_activity=[{"tool": "update_and_run_blocks", "summary": "OK"}],
+ )
+
+ result = _build_goal_satisfied_exit_result(ctx, global_llm_context=None)
+
+ assert result.updated_workflow is workflow
+ assert result.workflow_yaml == "workflow_definition:\n blocks: []\n"
+ assert result.proposal_disposition == "auto_applicable"
+ assert "tested" in result.user_response.lower()
+
+
class TestSupersededAgentIntentGates:
def test_agent_no_longer_owns_request_policy_classification(self) -> None:
assert not hasattr(agent_module, "_user_requests_untested_workflow_draft")
@@ -1653,6 +1898,13 @@ class TestCredentialRefusalReachesAgent:
class TestNativeToolSurface:
+ def test_page_composition_evidence_repair_tool_is_native(self) -> None:
+ from skyvern.forge.sdk.copilot.tools import NATIVE_TOOLS
+
+ names = {tool.name for tool in NATIVE_TOOLS}
+
+ assert "inspect_page_for_composition" in names
+
@pytest.mark.parametrize("reason", ["workflow_credential_inputs_unbound", "credential_name_unresolved"])
def test_credential_deferred_draft_removes_update_workflow_tool(self, reason: str) -> None:
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
diff --git a/tests/unit/test_copilot_composition_evidence.py b/tests/unit/test_copilot_composition_evidence.py
index 5c088a1e9..88632b68f 100644
--- a/tests/unit/test_copilot_composition_evidence.py
+++ b/tests/unit/test_copilot_composition_evidence.py
@@ -14,6 +14,7 @@ from skyvern.forge.sdk.copilot.composition_evidence import (
parse_composition_html,
)
from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentMode
+from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
@dataclass
@@ -22,6 +23,10 @@ class _Ctx:
turn_intent: TurnIntent = field(default_factory=lambda: TurnIntent(mode=TurnIntentMode.BUILD))
composition_page_evidence: dict | None = None
workflow_yaml: str | None = None
+ per_tool_budget_problem_block_labels: list[str] = field(default_factory=list)
+ workflow_verification_evidence: WorkflowVerificationEvidence = field(default_factory=WorkflowVerificationEvidence)
+ post_run_page_observation_after_failed_test: bool = False
+ last_failure_category_top: str | None = None
def _yaml(*blocks: dict) -> str:
@@ -411,7 +416,7 @@ def test_composition_gate_accepts_structured_evaluate_same_origin_after_initial_
"forms": [{"fields": [_field("First Name", "firstName")], "submit_controls": []}],
}
ctx = _Ctx(composition_page_evidence=evidence)
- ctx.workflow_yaml = existing_yaml # type: ignore[attr-defined]
+ ctx.workflow_yaml = existing_yaml
error = composition_page_evidence_error(ctx, workflow_yaml)
@@ -448,7 +453,7 @@ def test_composition_gate_rejects_post_run_browser_observation_outside_inspectio
"observed_after_workflow_run": True,
}
ctx = _Ctx(composition_page_evidence=evidence)
- ctx.workflow_yaml = existing_yaml # type: ignore[attr-defined]
+ ctx.workflow_yaml = existing_yaml
error = composition_page_evidence_error(ctx, workflow_yaml)
@@ -487,7 +492,7 @@ def test_composition_gate_allows_structured_evaluate_evidence_for_same_origin_co
"observed_after_workflow_run": True,
}
ctx = _Ctx(composition_page_evidence=evidence)
- ctx.workflow_yaml = existing_yaml # type: ignore[attr-defined]
+ ctx.workflow_yaml = existing_yaml
error = composition_page_evidence_error(ctx, workflow_yaml)
@@ -524,7 +529,7 @@ def test_composition_gate_allows_post_run_current_page_schema_on_same_origin_con
"observed_after_workflow_run": True,
}
ctx = _Ctx(composition_page_evidence=evidence)
- ctx.workflow_yaml = existing_yaml # type: ignore[attr-defined]
+ ctx.workflow_yaml = existing_yaml
error = composition_page_evidence_error(ctx, workflow_yaml)
@@ -566,7 +571,7 @@ def test_composition_gate_allows_multiple_new_page_changing_blocks_from_one_obse
"observed_after_workflow_run": True,
}
ctx = _Ctx(composition_page_evidence=evidence)
- ctx.workflow_yaml = existing_yaml # type: ignore[attr-defined]
+ ctx.workflow_yaml = existing_yaml
error = composition_page_evidence_error(ctx, workflow_yaml)
@@ -608,7 +613,7 @@ def test_composition_gate_allows_extraction_added_with_new_page_changing_block()
"observed_after_workflow_run": True,
}
ctx = _Ctx(composition_page_evidence=evidence)
- ctx.workflow_yaml = existing_yaml # type: ignore[attr-defined]
+ ctx.workflow_yaml = existing_yaml
error = composition_page_evidence_error(ctx, workflow_yaml)
@@ -645,7 +650,133 @@ def test_composition_gate_allows_extraction_after_matching_current_page_evidence
"observed_after_workflow_run": True,
}
ctx = _Ctx(composition_page_evidence=evidence)
- ctx.workflow_yaml = existing_yaml # type: ignore[attr-defined]
+ ctx.workflow_yaml = existing_yaml
+
+ error = composition_page_evidence_error(ctx, workflow_yaml)
+
+ assert error is None
+
+
+def test_composition_gate_rejects_post_budget_result_url_as_new_goto_url() -> None:
+ existing_yaml = _yaml(
+ {"block_type": "goto_url", "label": "open_home", "url": "https://example.com/"},
+ {
+ "block_type": "navigation",
+ "label": "search_sample_record",
+ "url": "https://example.com/lookup",
+ "navigation_goal": "Fill the observed first-name and last-name fields and submit.",
+ },
+ )
+ workflow_yaml = _yaml(
+ {"block_type": "goto_url", "label": "open_home", "url": "https://example.com/"},
+ {
+ "block_type": "navigation",
+ "label": "search_sample_record",
+ "url": "https://example.com/lookup",
+ "navigation_goal": "Fill the observed first-name and last-name fields and submit.",
+ },
+ {
+ "block_type": "goto_url",
+ "label": "open_sample_record_detail",
+ "url": "https://example.com/lookup?record_id=494764",
+ },
+ {
+ "block_type": "extraction",
+ "label": "extract_credential_details",
+ "data_extraction_goal": "Extract visible credential details.",
+ },
+ )
+ evidence = {
+ "inspected_url": "current_page",
+ "current_url": "https://example.com/lookup?record_id=494764",
+ "result_containers": [{"selector": "#results"}],
+ "source_tool": "inspect_page_for_composition",
+ "observed_after_workflow_run": True,
+ }
+ ctx = _Ctx(composition_page_evidence=evidence)
+ ctx.workflow_yaml = existing_yaml
+ ctx.per_tool_budget_problem_block_labels = ["search_sample_record"]
+
+ error = composition_page_evidence_error(ctx, workflow_yaml)
+
+ assert error is not None
+ assert "post-run browser URL" in error
+ assert "open_sample_record_detail" in error
+ assert "split or replace the budgeted frontier" in error
+
+
+def test_composition_gate_rejects_post_budget_path_result_url_as_new_goto_url() -> None:
+ existing_yaml = _yaml(
+ {"block_type": "goto_url", "label": "open_lookup", "url": "https://example.com/lookup"},
+ {
+ "block_type": "navigation",
+ "label": "search_person",
+ "navigation_goal": "Submit the observed search form.",
+ },
+ )
+ workflow_yaml = _yaml(
+ {"block_type": "goto_url", "label": "open_lookup", "url": "https://example.com/lookup"},
+ {
+ "block_type": "navigation",
+ "label": "search_person",
+ "navigation_goal": "Submit the observed search form.",
+ },
+ {
+ "block_type": "goto_url",
+ "label": "open_result_detail",
+ "url": "https://example.com/results/494764",
+ },
+ )
+ evidence = {
+ "inspected_url": "current_page",
+ "current_url": "https://example.com/results/494764",
+ "source_tool": "inspect_page_for_composition",
+ "observed_after_workflow_run": True,
+ }
+ ctx = _Ctx(composition_page_evidence=evidence)
+ ctx.workflow_yaml = existing_yaml
+ ctx.per_tool_budget_problem_block_labels = ["search_person"]
+
+ error = composition_page_evidence_error(ctx, workflow_yaml)
+
+ assert error is not None
+ assert "open_result_detail" in error
+
+
+def test_composition_gate_allows_extraction_from_post_budget_current_page() -> None:
+ existing_yaml = _yaml(
+ {"block_type": "goto_url", "label": "open_home", "url": "https://example.com/"},
+ {
+ "block_type": "navigation",
+ "label": "search_sample_record",
+ "url": "https://example.com/lookup",
+ "navigation_goal": "Fill the observed first-name and last-name fields and submit.",
+ },
+ )
+ workflow_yaml = _yaml(
+ {"block_type": "goto_url", "label": "open_home", "url": "https://example.com/"},
+ {
+ "block_type": "navigation",
+ "label": "search_sample_record",
+ "url": "https://example.com/lookup",
+ "navigation_goal": "Fill the observed first-name and last-name fields and submit.",
+ },
+ {
+ "block_type": "extraction",
+ "label": "extract_visible_credentials",
+ "data_extraction_goal": "Extract credential details visible on the observed current page.",
+ },
+ )
+ evidence = {
+ "inspected_url": "current_page",
+ "current_url": "https://example.com/lookup?record_id=494764",
+ "result_containers": [{"selector": "#results"}],
+ "source_tool": "inspect_page_for_composition",
+ "observed_after_workflow_run": True,
+ }
+ ctx = _Ctx(composition_page_evidence=evidence)
+ ctx.workflow_yaml = existing_yaml
+ ctx.per_tool_budget_problem_block_labels = ["search_sample_record"]
error = composition_page_evidence_error(ctx, workflow_yaml)
@@ -682,7 +813,7 @@ def test_composition_gate_targets_nearest_url_before_new_page_block() -> None:
"source_tool": "inspect_page_for_composition",
}
ctx = _Ctx(composition_page_evidence=evidence)
- ctx.workflow_yaml = existing_yaml # type: ignore[attr-defined]
+ ctx.workflow_yaml = existing_yaml
error = composition_page_evidence_error(ctx, workflow_yaml)
@@ -713,7 +844,7 @@ def test_composition_gate_error_names_nearest_url_before_new_page_block() -> Non
},
)
ctx = _Ctx(composition_page_evidence=None)
- ctx.workflow_yaml = existing_yaml # type: ignore[attr-defined]
+ ctx.workflow_yaml = existing_yaml
error = composition_page_evidence_error(ctx, workflow_yaml)
@@ -739,7 +870,7 @@ def test_composition_gate_rejects_same_origin_browser_observation_before_run_con
"observed_after_workflow_run": False,
}
ctx = _Ctx(composition_page_evidence=evidence)
- ctx.workflow_yaml = existing_yaml # type: ignore[attr-defined]
+ ctx.workflow_yaml = existing_yaml
error = composition_page_evidence_error(ctx, workflow_yaml)
diff --git a/tests/unit/test_copilot_discovery.py b/tests/unit/test_copilot_discovery.py
index 543cefbc2..083d02d73 100644
--- a/tests/unit/test_copilot_discovery.py
+++ b/tests/unit/test_copilot_discovery.py
@@ -8,6 +8,7 @@ import pytest
from skyvern.forge.sdk.copilot import tools as tools_module
from skyvern.forge.sdk.copilot.tools import _discovery_walk, _inspect_page_for_composition_impl
+from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
class _Ctx:
@@ -17,6 +18,7 @@ class _Ctx:
self.discovery_step_count = 0
self.prior_page_inspection_calls_made = 0
self.page_inspection_calls_this_turn = 0
+ self.workflow_verification_evidence = WorkflowVerificationEvidence()
class _FailingNavigateServer:
diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.py
index 01cb5ddf3..6f9bae7de 100644
--- a/tests/unit/test_copilot_enforcement_pruning.py
+++ b/tests/unit/test_copilot_enforcement_pruning.py
@@ -32,6 +32,7 @@ from skyvern.forge.sdk.copilot.tools import (
_is_meaningful_extracted_data,
_record_run_blocks_result,
)
+from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
class _Ctx:
@@ -328,6 +329,7 @@ def _fresh_ctx_for_record() -> SimpleNamespace:
last_action_sequence_fingerprint=None,
repeated_action_fingerprint_streak_count=0,
copilot_total_timeout_exceeded=False,
+ workflow_verification_evidence=WorkflowVerificationEvidence(),
)
diff --git a/tests/unit/test_copilot_output_utils.py b/tests/unit/test_copilot_output_utils.py
index a47a174ba..b18da23ec 100644
--- a/tests/unit/test_copilot_output_utils.py
+++ b/tests/unit/test_copilot_output_utils.py
@@ -307,6 +307,16 @@ class TestSummarizeToolResult:
)
assert "3" in summary
+ def test_update_and_run_blocks_with_scalar_data_does_not_crash(self) -> None:
+ summary = self._summarize(
+ "update_and_run_blocks",
+ {
+ "ok": True,
+ "data": "workflow_run_skipped: verified_goal_already_satisfied",
+ },
+ )
+ assert summary == "OK"
+
def test_navigate_browser(self) -> None:
summary = self._summarize(
"navigate_browser",
diff --git a/tests/unit/test_copilot_per_tool_budget.py b/tests/unit/test_copilot_per_tool_budget.py
index a406b94ed..c4cf8273c 100644
--- a/tests/unit/test_copilot_per_tool_budget.py
+++ b/tests/unit/test_copilot_per_tool_budget.py
@@ -302,6 +302,10 @@ def test_final_reply_after_post_run_observation_bypasses_stale_budget_and_anti_b
observed_data={"text": "Credential Number: CRED-000123"},
)
+ evidence = ctx.workflow_verification_evidence
+ assert evidence.current_url_observed_after_workflow_run is True
+ assert evidence.current_url_may_encode_runtime_state is True
+
assert _check_enforcement(ctx, _reply_result("Observed result: CRED-000123 expires 01/31/2030.")) is None