Skip to content

Automate browser based workflows with AI

SKY-12163 (part 2) Stabilize typed request-slot contracts (#7448)

Andrew Neilsona0702c323614
diff --git a/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx b/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx
index d15da9d62..f3050c1d1 100644
--- a/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx
+++ b/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx
@@ -239,108 +239,6 @@ describe("RunHistory run tags", () => {
expect(await screen.findByRole("menu")).not.toBeNull();
expect(row.hasAttribute("data-row-active")).toBe(true);
});
-
- it("selects only workflow runs and supports shift-range bulk actions", () => {
- render(<RunHistory />, { wrapper });
-
- const first = screen.getByRole("checkbox", { name: "Select My Run" });
- const second = screen.getByRole("checkbox", { name: "Select Second Run" });
- expect(
- screen.queryByRole("checkbox", { name: "Select Task Run" }),
- ).toBeNull();
-
- fireEvent.click(first.parentElement!);
- fireEvent.click(second.parentElement!, { shiftKey: true });
-
- expect(
- screen.getByRole("toolbar", { name: "Bulk actions" }).textContent,
- ).toContain("2 selected");
-
- fireEvent.contextMenu(screen.getByRole("row", { name: /tsk_1 Task Run/ }));
- expect(screen.queryByRole("menu")).toBeNull();
- });
-
- it("hides selection when workflow tagging is disabled", () => {
- flagState.taggingEnabled = false;
- render(<RunHistory />, { wrapper });
-
- expect(screen.queryByLabelText(/^Select /)).toBeNull();
- });
-
- it("does not restore selection after the tagging flag is toggled", () => {
- const view = render(<RunHistory />, { wrapper });
- fireEvent.click(
- screen.getByRole("checkbox", { name: "Select My Run" }).parentElement!,
- );
-
- flagState.taggingEnabled = false;
- view.rerender(<RunHistory />);
- flagState.taggingEnabled = true;
- view.rerender(<RunHistory />);
-
- expect(screen.queryByRole("toolbar", { name: "Bulk actions" })).toBeNull();
- });
-
- it("opens the tag context menu from a workflow-run row", async () => {
- render(<RunHistory />, { wrapper });
-
- const row = screen.getByRole("row", { name: /wr_1 My Run/ });
- fireEvent.contextMenu(row);
-
- expect(await screen.findByRole("menu")).not.toBeNull();
- expect(row.hasAttribute("data-row-active")).toBe(true);
- });
-
- it("selects only workflow runs and supports shift-range bulk actions", () => {
- render(<RunHistory />, { wrapper });
-
- const first = screen.getByRole("checkbox", { name: "Select My Run" });
- const second = screen.getByRole("checkbox", { name: "Select Second Run" });
- expect(
- screen.queryByRole("checkbox", { name: "Select Task Run" }),
- ).toBeNull();
-
- fireEvent.click(first.parentElement!);
- fireEvent.click(second.parentElement!, { shiftKey: true });
-
- expect(
- screen.getByRole("toolbar", { name: "Bulk actions" }).textContent,
- ).toContain("2 selected");
-
- fireEvent.contextMenu(screen.getByRole("row", { name: /tsk_1 Task Run/ }));
- expect(screen.queryByRole("menu")).toBeNull();
- });
-
- it("hides selection when workflow tagging is disabled", () => {
- flagState.taggingEnabled = false;
- render(<RunHistory />, { wrapper });
-
- expect(screen.queryByLabelText(/^Select /)).toBeNull();
- });
-
- it("does not restore selection after the tagging flag is toggled", () => {
- const view = render(<RunHistory />, { wrapper });
- fireEvent.click(
- screen.getByRole("checkbox", { name: "Select My Run" }).parentElement!,
- );
-
- flagState.taggingEnabled = false;
- view.rerender(<RunHistory />);
- flagState.taggingEnabled = true;
- view.rerender(<RunHistory />);
-
- expect(screen.queryByRole("toolbar", { name: "Bulk actions" })).toBeNull();
- });
-
- it("opens the tag context menu from a workflow-run row", async () => {
- render(<RunHistory />, { wrapper });
-
- const row = screen.getByRole("row", { name: /wr_1 My Run/ });
- fireEvent.contextMenu(row);
-
- expect(await screen.findByRole("menu")).not.toBeNull();
- expect(row.hasAttribute("data-row-active")).toBe(true);
- });
});
describe("RunHistory tag filter control", () => {
diff --git a/skyvern-frontend/src/routes/history/RunHistory.tsx b/skyvern-frontend/src/routes/history/RunHistory.tsx
index 92e541be3..dd5f34fda 100644
--- a/skyvern-frontend/src/routes/history/RunHistory.tsx
+++ b/skyvern-frontend/src/routes/history/RunHistory.tsx
@@ -476,7 +476,7 @@ function RunHistory() {
className="max-w-0 truncate"
title={run.title ?? undefined}
>
- <div className="flex min-w-0 flex-col gap-1">
+ <div className="flex min-w-0 items-center gap-2">
<div className="min-w-0 truncate">{titleContent}</div>
{taggingEnabled && runTags && runTags.length > 0 ? (
<TagChipList
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx
index 0eb98e46c..434f8ff50 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx
@@ -262,46 +262,6 @@ describe("WorkflowPage run tags", () => {
expect(screen.queryByLabelText(/^Select /)).toBeNull();
});
-
- it("shift-selects runs and exposes bulk tag actions", () => {
- renderWorkflowPage();
-
- const first = screen.getByRole("checkbox", { name: "Select wr_1" });
- const second = screen.getByRole("checkbox", { name: "Select wr_2" });
- fireEvent.click(first.parentElement!);
- fireEvent.click(second.parentElement!, { shiftKey: true });
-
- expect(
- screen.getByRole("toolbar", { name: "Bulk actions" }).textContent,
- ).toContain("2 selected");
- });
-
- it("hides selection when workflow tagging is disabled", () => {
- flagState.taggingEnabled = false;
- renderWorkflowPage();
-
- expect(screen.queryByLabelText(/^Select /)).toBeNull();
- });
-
- it("shift-selects runs and exposes bulk tag actions", () => {
- renderWorkflowPage();
-
- const first = screen.getByRole("checkbox", { name: "Select wr_1" });
- const second = screen.getByRole("checkbox", { name: "Select wr_2" });
- fireEvent.click(first.parentElement!);
- fireEvent.click(second.parentElement!, { shiftKey: true });
-
- expect(
- screen.getByRole("toolbar", { name: "Bulk actions" }).textContent,
- ).toContain("2 selected");
- });
-
- it("hides selection when workflow tagging is disabled", () => {
- flagState.taggingEnabled = false;
- renderWorkflowPage();
-
- expect(screen.queryByLabelText(/^Select /)).toBeNull();
- });
});
describe("WorkflowPage tag filter control", () => {
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
index c93a38ddb..a252938a4 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
@@ -470,7 +470,7 @@ function WorkflowPage() {
/>
)}
<TableCell className="font-mono text-xs text-muted-foreground">
- <div className="flex min-w-0 flex-col gap-1">
+ <div className="flex min-w-0 items-center gap-2">
<span className="min-w-0 truncate">
{workflowRunId}
</span>
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx
index 10960fe90..6192cffa4 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx
@@ -271,11 +271,11 @@ beforeEach(() => {
});
describe("RunView view toggles", () => {
- test("renders the shared run tag editor", () => {
+ test("does not render run tags in Studio Overview", () => {
seedCompletedRun();
- const { getByTestId } = renderRunView();
+ const { queryByTestId } = renderRunView();
- expect(getByTestId("run-tags-editor").dataset.workflowRunId).toBe("wr_1");
+ expect(queryByTestId("run-tags-editor")).toBeNull();
});
test("defaults to the Timeline view with the timeline and step detail", () => {
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx
index 65b30d459..e5d4e5b67 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx
@@ -14,7 +14,6 @@ import { useRunViewStore } from "@/store/RunViewStore";
import { useStudioBrowserStore } from "@/store/useStudioBrowserStore";
import { useWorkflowBlockSearchStore } from "@/store/WorkflowBlockSearchStore";
import { isRecord } from "@/util/utils";
-import { RunTagsEditor } from "@/routes/tasks/components/tagging/RunTagsEditor";
import { useWorkflowRunTimelineQuery } from "../../hooks/useWorkflowRunTimelineQuery";
import { useWorkflowRunWithWorkflowQuery } from "../../hooks/useWorkflowRunWithWorkflowQuery";
@@ -340,11 +339,6 @@ export function RunView({
<WorkflowRunVerificationCodeForm
workflowRunId={workflowRun.workflow_run_id}
/>
- <RunTagsEditor
- workflowRunId={workflowRun.workflow_run_id}
- className="shrink-0"
- />
-
{provisioning ? (
<div className="flex shrink-0 items-center gap-2 rounded-md border border-border bg-slate-elevation2 px-3 py-1.5 text-xs text-muted-foreground">
<ClockIcon className="h-3.5 w-3.5 shrink-0" />
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index 1c95f6da7..2f601c25f 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -1117,6 +1117,10 @@ class AgentFunction:
async def post_cache_step_execution(self, task: Task, step: Step) -> None:
return
+ async def post_code_block_execution(self, task: Task, step: Step) -> None:
+ """Billing seam for a code block's container task; called only after a successful execution."""
+ return
+
async def wait_for_challenge_solver(self, page: Page) -> None:
"""Wait for a cloud-managed challenge solver if one is attached to the page."""
return None
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-request-slots.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-request-slots.j2
new file mode 100644
index 000000000..ae8d47f72
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-request-slots.j2
@@ -0,0 +1,29 @@
+Classify the request-owned output slots for the latest Workflow Copilot turn. Return only JSON.
+
+Schema-valid examples:
+{"version":"1","slots":[{"source_id":"u0","source_quote":"required_columns","plane":"definition","pinability":"shapeless_valid"}]}
+{"version":"1","slots":[{"source_id":"u0","source_quote":"processed record count","plane":"run","pinability":"shapeless_valid"}]}
+{"version":"1","slots":[{"source_id":"u0","source_quote":"status must equal complete","plane":"run","pinability":"pinned"}]}
+
+Rules:
+- Return version exactly "1" and at least one slot.
+- For every request-owned output member, copy the smallest unique exact quote that identifies it from one supplied user source. Return that source_id and quote exactly; the server owns paths, IDs, order, and count.
+- An output member is a value the user asks the workflow to expose in its returned or defined output contract. A task, action, navigation goal, or evidence-gathering instruction is not a separate output member merely because the workflow performs or classifies it. Include its result only when the user separately asks to expose that value and it is not already represented by a more explicit requested output member.
+- Context outside the supplied user sources may inform plane and pinability, but it is never an anchor source.
+- Use plane "definition" for a stable property the workflow definition must establish.
+- Use plane "run" for a value or state that a workflow execution must observe or return.
+- pinability is required on every slot:
+ - pinned: the request itself fixes an exact expected value or exact supported expected shape.
+ - shapeless_valid: the output is valid without fixing an exact value or supported shape. Evidence-decided discovery questions, including whether questions, use this value and never a guessed polarity. A boolean or classification answer space alone never supplies a request-fixed polarity and is not pinned.
+ - unpinnable: the requested output cannot be safely bound to a satisfiable output criterion.
+- Include every request-owned output member exactly once. Do not emit paths, path segments, IDs, aliases, labels, counts, expected values, explanations, or unknown fields.
+- Do not infer slots from sampled page shapes or non-user context. Do not normalize, rename, or paraphrase source quotes.
+
+Ordered, deduplicated user request sources:
+```{{ request_sources }}```
+Workflow context (non-authoritative):
+```{{ workflow_context }}```
+Latest assistant turn (non-authoritative):
+```{{ latest_assistant_turn }}```
+Bounded global context (non-authoritative):
+```{{ global_context }}```
diff --git a/skyvern/forge/sdk/copilot/request_slots.py b/skyvern/forge/sdk/copilot/request_slots.py
new file mode 100644
index 000000000..85174bd56
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/request_slots.py
@@ -0,0 +1,458 @@
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+import re
+import time
+import unicodedata
+from enum import StrEnum
+from typing import Literal
+
+import structlog
+from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
+
+from skyvern.forge.prompts import prompt_engine
+from skyvern.forge.sdk.api.llm.api_handler import LLMAPIHandler
+from skyvern.forge.sdk.api.llm.exceptions import EmptyLLMResponseError, InvalidLLMResponseFormat
+from skyvern.forge.sdk.copilot.context import sanitize_global_llm_context_for_prompt
+from skyvern.forge.sdk.copilot.llm_errors import is_retriable_llm_error
+from skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_prompt
+from skyvern.utils.strings import escape_code_fences
+
+LOG = structlog.get_logger()
+PROMPT_NAME = "workflow-copilot-request-slots"
+_DEFAULT_TIMEOUT_SECONDS = 30.0
+_MAX_REQUEST_PROMPT_CHARS = 8_192
+_MAX_WORKFLOW_PROMPT_CHARS = 4_096
+_MAX_TRANSCRIPT_ANCHOR_PROMPT_CHARS = 1_000
+_MAX_RETAINED_HISTORY_PROMPT_ITEMS = 4
+_MAX_GLOBAL_CONTEXT_PROMPT_CHARS = 2_048
+_MAX_SOURCE_QUOTE_CHARS = 1_024
+_MAX_CLASSIFIER_ATTEMPTS = 4
+_SOURCE_ID_PATTERN = re.compile(r"^u(?:0|[1-9][0-9]?)$")
+_PATH_SEGMENT_PATTERN = re.compile(r"^[a-z][a-z0-9_]{0,63}$")
+_REQUEST_SLOT_PATH_PATTERN = re.compile(r"^request_slot_[0-9a-f]{48}_[0-9]{2}$")
+
+
+class RequestSlotPlane(StrEnum):
+ DEFINITION = "definition"
+ RUN = "run"
+
+
+class RequestSlotPinability(StrEnum):
+ PINNED = "pinned"
+ SHAPELESS_VALID = "shapeless_valid"
+ UNPINNABLE = "unpinnable"
+
+
+class RequestSlotProducerFailureKind(StrEnum):
+ MISSING_HANDLER = "missing_handler"
+ PROMPT_RENDER_ERROR = "prompt_render_error"
+ TIMEOUT = "timeout"
+ PROVIDER_ERROR = "provider_error"
+ EMPTY_OUTPUT = "empty_output"
+ INVALID_OUTPUT = "invalid_output"
+ INCONSISTENT_OUTPUT = "inconsistent_output"
+
+
+class RequestSlotProducerInputV1(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ version: Literal["1"]
+ latest_request: str = Field(max_length=16_384)
+ workflow_context: str = Field(max_length=32_768)
+ earliest_user_turn: str = Field(max_length=4_096)
+ latest_prior_user_turn: str = Field(max_length=4_096)
+ latest_assistant_turn: str = Field(max_length=4_096)
+ retained_history: tuple[str, ...] = Field(max_length=8)
+ global_context: str = Field(max_length=32_768)
+
+ @field_validator("retained_history")
+ @classmethod
+ def _validate_retained_history(cls, entries: tuple[str, ...]) -> tuple[str, ...]:
+ if any(not entry.strip() or len(entry) > 4_096 for entry in entries):
+ raise ValueError("retained history entries must be non-empty and at most 4096 characters")
+ return entries
+
+
+class RequestSlotSourceV1(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ source_id: str = Field(min_length=2, max_length=3, pattern=_SOURCE_ID_PATTERN.pattern)
+ order: int = Field(ge=0, le=63)
+ text: str = Field(min_length=1, max_length=_MAX_REQUEST_PROMPT_CHARS)
+
+ @model_validator(mode="after")
+ def _validate_server_owned_identity(self) -> RequestSlotSourceV1:
+ if self.source_id != f"u{self.order}":
+ raise ValueError("source_id must derive from source order")
+ return self
+
+
+class RequestSlotDeclarationV1(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ source_id: str = Field(min_length=2, max_length=3, pattern=_SOURCE_ID_PATTERN.pattern)
+ source_quote: str = Field(min_length=1, max_length=_MAX_SOURCE_QUOTE_CHARS)
+ plane: RequestSlotPlane
+ pinability: RequestSlotPinability
+
+ @field_validator("source_quote")
+ @classmethod
+ def _validate_source_quote(cls, quote: str) -> str:
+ if not quote.strip():
+ raise ValueError("source_quote must contain non-whitespace request text")
+ return quote
+
+
+class RequestSlotEnvelopeV1(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ version: Literal["1"]
+ slots: tuple[RequestSlotDeclarationV1, ...] = Field(min_length=1, max_length=64)
+
+
+def _request_digest(version: str, sources: tuple[RequestSlotSourceV1, ...]) -> str:
+ encoded = json.dumps(
+ [version, [[source.source_id, source.text] for source in sources]],
+ ensure_ascii=True,
+ separators=(",", ":"),
+ ).encode()
+ return hashlib.sha256(encoded).hexdigest()
+
+
+def _canonical_path(request_digest: str, ordinal: int) -> tuple[str, tuple[str, str]]:
+ leaf = f"request_slot_{request_digest[:48]}_{ordinal:02d}"
+ return f"output.{leaf}", ("output", leaf)
+
+
+def _slot_id(version: str, request_digest: str, ordinal: int, plane: RequestSlotPlane) -> str:
+ encoded = json.dumps(
+ [version, request_digest, ordinal, plane.value],
+ ensure_ascii=True,
+ separators=(",", ":"),
+ ).encode()
+ return hashlib.sha256(encoded).hexdigest()
+
+
+class CanonicalRequestSlotV1(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ slot_id: str = Field(min_length=64, max_length=64, pattern=r"^[0-9a-f]{64}$")
+ canonical_path: str = Field(min_length=1, max_length=71)
+ path_segments: tuple[str, str]
+ ordinal: int = Field(ge=0, le=63)
+ source_id: str = Field(min_length=2, max_length=3, pattern=_SOURCE_ID_PATTERN.pattern)
+ source_start: int = Field(ge=0, le=_MAX_REQUEST_PROMPT_CHARS)
+ source_end: int = Field(ge=1, le=_MAX_REQUEST_PROMPT_CHARS)
+ plane: RequestSlotPlane
+ pinability: RequestSlotPinability
+
+ @field_validator("path_segments")
+ @classmethod
+ def _validate_path_segments(cls, segments: tuple[str, str]) -> tuple[str, str]:
+ if any(_PATH_SEGMENT_PATTERN.fullmatch(segment) is None for segment in segments):
+ raise ValueError("path segments must be lowercase identifiers of at most 64 characters")
+ if segments[0] != "output" or _REQUEST_SLOT_PATH_PATTERN.fullmatch(segments[1]) is None:
+ raise ValueError("canonical request-slot paths must use the server-owned namespace")
+ return segments
+
+ @model_validator(mode="after")
+ def _validate_derived_fields(self) -> CanonicalRequestSlotV1:
+ if self.source_end <= self.source_start:
+ raise ValueError("source_end must be greater than source_start")
+ if self.canonical_path != ".".join(self.path_segments):
+ raise ValueError("canonical_path must derive from path_segments")
+ return self
+
+
+class RequestSlotContractV1(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ version: Literal["1"]
+ request_digest: str = Field(min_length=64, max_length=64, pattern=r"^[0-9a-f]{64}$")
+ slots: tuple[CanonicalRequestSlotV1, ...] = Field(min_length=1, max_length=64)
+ count: int = Field(ge=1, le=64)
+
+ @model_validator(mode="after")
+ def _validate_derived_membership(self) -> RequestSlotContractV1:
+ if self.count != len(self.slots):
+ raise ValueError("count must derive from slot membership")
+ if [slot.ordinal for slot in self.slots] != list(range(self.count)):
+ raise ValueError("slot ordinals must be contiguous and in canonical order")
+ if len({slot.canonical_path for slot in self.slots}) != self.count:
+ raise ValueError("slot membership contains a canonical path collision")
+ if len({slot.slot_id for slot in self.slots}) != self.count:
+ raise ValueError("slot membership contains a canonical slot identity collision")
+
+ previous: CanonicalRequestSlotV1 | None = None
+ for slot in self.slots:
+ expected_path, expected_segments = _canonical_path(self.request_digest, slot.ordinal)
+ if slot.canonical_path != expected_path or slot.path_segments != expected_segments:
+ raise ValueError("canonical path must derive from request digest and ordinal")
+ if slot.slot_id != _slot_id(self.version, self.request_digest, slot.ordinal, slot.plane):
+ raise ValueError("slot_id must derive from version, request digest, ordinal, and plane")
+ if previous is not None:
+ previous_order = int(previous.source_id[1:])
+ current_order = int(slot.source_id[1:])
+ if (current_order, slot.source_start, slot.source_end) < (
+ previous_order,
+ previous.source_start,
+ previous.source_end,
+ ):
+ raise ValueError("slot membership must be in request-source order")
+ if current_order == previous_order and slot.source_start < previous.source_end:
+ raise ValueError("slot membership contains overlapping source anchors")
+ previous = slot
+ return self
+
+
+class RequestSlotProducerResult(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ status: Literal["success", "failure"]
+ attempts: int = Field(ge=0, le=_MAX_CLASSIFIER_ATTEMPTS)
+ contract: RequestSlotContractV1 | None = None
+ failure_kind: RequestSlotProducerFailureKind | None = None
+
+ @model_validator(mode="after")
+ def _validate_exclusive_result(self) -> RequestSlotProducerResult:
+ if self.status == "success":
+ if self.contract is None or self.failure_kind is not None or self.attempts == 0:
+ raise ValueError("success requires a contract, at least one attempt, and no failure")
+ elif self.contract is not None or self.failure_kind is None:
+ raise ValueError("failure requires a failure kind and no contract")
+ return self
+
+ @classmethod
+ def success(cls, contract: RequestSlotContractV1, *, attempts: int) -> RequestSlotProducerResult:
+ return cls(status="success", attempts=attempts, contract=contract)
+
+ @classmethod
+ def failure(
+ cls,
+ failure_kind: RequestSlotProducerFailureKind,
+ *,
+ attempts: int,
+ ) -> RequestSlotProducerResult:
+ return cls(status="failure", attempts=attempts, failure_kind=failure_kind)
+
+
+def _middle_truncate(text: str, cap: int) -> str:
+ if len(text) <= cap:
+ return text
+ keep = max(cap - 32, 16)
+ head_len = keep // 2
+ tail_len = keep - head_len
+ omitted = len(text) - keep
+ return f"{text[:head_len]}<…{omitted} chars truncated…>{text[-tail_len:]}"
+
+
+def _safe_prompt_text(value: str, limit: int) -> str:
+ normalized = unicodedata.normalize("NFKC", value)
+ bounded = normalized if len(normalized) <= limit * 4 else normalized[: limit * 2] + normalized[-limit * 2 :]
+ escaped = escape_code_fences(redact_raw_secrets_for_prompt(bounded))
+ return _middle_truncate(escaped, limit)
+
+
+def request_slot_sources(request: RequestSlotProducerInputV1) -> tuple[RequestSlotSourceV1, ...]:
+ candidates = [
+ _safe_prompt_text(request.earliest_user_turn, _MAX_TRANSCRIPT_ANCHOR_PROMPT_CHARS),
+ *(
+ _safe_prompt_text(entry, _MAX_TRANSCRIPT_ANCHOR_PROMPT_CHARS)
+ for entry in request.retained_history[:_MAX_RETAINED_HISTORY_PROMPT_ITEMS]
+ ),
+ _safe_prompt_text(request.latest_prior_user_turn, _MAX_TRANSCRIPT_ANCHOR_PROMPT_CHARS),
+ _safe_prompt_text(request.latest_request, _MAX_REQUEST_PROMPT_CHARS),
+ ]
+ retained_reversed: list[str] = []
+ seen: set[str] = set()
+ for text in reversed(candidates):
+ if not text.strip() or text in seen:
+ continue
+ seen.add(text)
+ retained_reversed.append(text)
+ retained = tuple(reversed(retained_reversed))
+ return tuple(
+ RequestSlotSourceV1(source_id=f"u{order}", order=order, text=text) for order, text in enumerate(retained)
+ )
+
+
+def request_slot_source_text(request: RequestSlotProducerInputV1, slot: CanonicalRequestSlotV1) -> str:
+ source = next(
+ (candidate for candidate in request_slot_sources(request) if candidate.source_id == slot.source_id), None
+ )
+ if source is None or slot.source_end > len(source.text):
+ raise ValueError("canonical slot does not dereference against the request source set")
+ return source.text[slot.source_start : slot.source_end]
+
+
+def canonicalize_request_slots(
+ *,
+ request: RequestSlotProducerInputV1,
+ envelope: RequestSlotEnvelopeV1,
+) -> RequestSlotContractV1:
+ if request.version != envelope.version:
+ raise ValueError("request and response contract versions must match")
+ sources = request_slot_sources(request)
+ source_by_id = {source.source_id: source for source in sources}
+ resolved: list[tuple[RequestSlotDeclarationV1, RequestSlotSourceV1, int, int]] = []
+ for declaration in envelope.slots:
+ source = source_by_id.get(declaration.source_id)
+ if source is None:
+ raise ValueError(f"unknown request source: {declaration.source_id}")
+ start = source.text.find(declaration.source_quote)
+ if start < 0:
+ raise ValueError(f"source quote is not present in {declaration.source_id}")
+ if source.text.find(declaration.source_quote, start + 1) >= 0:
+ raise ValueError(f"source quote is not unique in {declaration.source_id}")
+ resolved.append((declaration, source, start, start + len(declaration.source_quote)))
+
+ resolved.sort(key=lambda item: (item[1].order, item[2], item[3]))
+ previous: tuple[RequestSlotDeclarationV1, RequestSlotSourceV1, int, int] | None = None
+ for item in resolved:
+ if previous is not None and item[1].source_id == previous[1].source_id and item[2] < previous[3]:
+ raise ValueError(f"source anchors overlap in {item[1].source_id}")
+ previous = item
+
+ digest = _request_digest(envelope.version, sources)
+ canonical_slots: list[CanonicalRequestSlotV1] = []
+ seen_paths: set[str] = set()
+ seen_slot_ids: set[str] = set()
+ for ordinal, (declaration, source, start, end) in enumerate(resolved):
+ canonical_path, path_segments = _canonical_path(digest, ordinal)
+ slot_id = _slot_id(envelope.version, digest, ordinal, declaration.plane)
+ if canonical_path in seen_paths:
+ raise ValueError(f"canonical request-slot path collision: {canonical_path}")
+ if slot_id in seen_slot_ids:
+ raise ValueError(f"canonical request-slot identity collision: {canonical_path}")
+ seen_paths.add(canonical_path)
+ seen_slot_ids.add(slot_id)
+ canonical_slots.append(
+ CanonicalRequestSlotV1(
+ slot_id=slot_id,
+ canonical_path=canonical_path,
+ path_segments=path_segments,
+ ordinal=ordinal,
+ source_id=source.source_id,
+ source_start=start,
+ source_end=end,
+ plane=declaration.plane,
+ pinability=declaration.pinability,
+ )
+ )
+ return RequestSlotContractV1(
+ version=envelope.version,
+ request_digest=digest,
+ slots=tuple(canonical_slots),
+ count=len(canonical_slots),
+ )
+
+
+def _render_prompt(request: RequestSlotProducerInputV1) -> str:
+ safe_global_context = sanitize_global_llm_context_for_prompt(request.global_context)
+ sources = request_slot_sources(request)
+ return prompt_engine.load_prompt(
+ template=PROMPT_NAME,
+ request_sources=json.dumps(
+ [source.model_dump(mode="json") for source in sources],
+ ensure_ascii=True,
+ separators=(",", ":"),
+ ),
+ workflow_context=_safe_prompt_text(request.workflow_context, _MAX_WORKFLOW_PROMPT_CHARS),
+ latest_assistant_turn=_safe_prompt_text(request.latest_assistant_turn, _MAX_TRANSCRIPT_ANCHOR_PROMPT_CHARS),
+ global_context=_safe_prompt_text(safe_global_context, _MAX_GLOBAL_CONTEXT_PROMPT_CHARS),
+ )
+
+
+def _is_empty_output(raw: object) -> bool:
+ return raw is None or (isinstance(raw, str) and not raw.strip())
+
+
+def _parse_envelope(raw: object) -> RequestSlotEnvelopeV1 | None:
+ try:
+ payload = raw if isinstance(raw, str) else json.dumps(raw)
+ return RequestSlotEnvelopeV1.model_validate_json(payload)
+ except (TypeError, ValueError, ValidationError):
+ return None
+
+
+def request_slot_contracts_agree(
+ first: RequestSlotContractV1,
+ second: RequestSlotContractV1,
+) -> bool:
+ if first.version != second.version or first.request_digest != second.request_digest or first.count != second.count:
+ return False
+ return all(
+ first_slot.ordinal == second_slot.ordinal
+ and first_slot.source_id == second_slot.source_id
+ and first_slot.plane == second_slot.plane
+ and first_slot.pinability == second_slot.pinability
+ and first_slot.source_start < second_slot.source_end
+ and second_slot.source_start < first_slot.source_end
+ for first_slot, second_slot in zip(first.slots, second.slots, strict=True)
+ )
+
+
+async def produce_request_slots(
+ *,
+ request: RequestSlotProducerInputV1,
+ handler: LLMAPIHandler | None,
+ timeout_seconds: float = _DEFAULT_TIMEOUT_SECONDS,
+) -> RequestSlotProducerResult:
+ if handler is None:
+ return RequestSlotProducerResult.failure(RequestSlotProducerFailureKind.MISSING_HANDLER, attempts=0)
+ try:
+ prompt = _render_prompt(request)
+ except Exception as exc:
+ LOG.warning("request-slot prompt render failed", error=str(exc))
+ return RequestSlotProducerResult.failure(RequestSlotProducerFailureKind.PROMPT_RENDER_ERROR, attempts=0)
+
+ deadline = time.monotonic() + max(timeout_seconds, 0.0)
+ last_failure = RequestSlotProducerFailureKind.INVALID_OUTPUT
+ candidate_contract: RequestSlotContractV1 | None = None
+ for attempt in range(1, _MAX_CLASSIFIER_ATTEMPTS + 1):
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return RequestSlotProducerResult.failure(RequestSlotProducerFailureKind.TIMEOUT, attempts=attempt - 1)
+ try:
+ raw = await asyncio.wait_for(
+ handler(prompt=prompt, prompt_name=PROMPT_NAME),
+ timeout=remaining,
+ )
+ except asyncio.TimeoutError:
+ return RequestSlotProducerResult.failure(RequestSlotProducerFailureKind.TIMEOUT, attempts=attempt)
+ except EmptyLLMResponseError:
+ last_failure = RequestSlotProducerFailureKind.EMPTY_OUTPUT
+ continue
+ except InvalidLLMResponseFormat:
+ last_failure = RequestSlotProducerFailureKind.INVALID_OUTPUT
+ continue
+ except Exception as exc:
+ if attempt < _MAX_CLASSIFIER_ATTEMPTS and is_retriable_llm_error(exc):
+ continue
+ if time.monotonic() >= deadline:
+ return RequestSlotProducerResult.failure(RequestSlotProducerFailureKind.TIMEOUT, attempts=attempt)
+ LOG.warning("request-slot classifier provider failed", error=str(exc), attempt=attempt)
+ return RequestSlotProducerResult.failure(RequestSlotProducerFailureKind.PROVIDER_ERROR, attempts=attempt)
+
+ if _is_empty_output(raw):
+ last_failure = RequestSlotProducerFailureKind.EMPTY_OUTPUT
+ continue
+ envelope = _parse_envelope(raw)
+ if envelope is None:
+ last_failure = RequestSlotProducerFailureKind.INVALID_OUTPUT
+ continue
+ try:
+ contract = canonicalize_request_slots(request=request, envelope=envelope)
+ except ValueError:
+ last_failure = RequestSlotProducerFailureKind.INVALID_OUTPUT
+ continue
+ if candidate_contract is not None and request_slot_contracts_agree(candidate_contract, contract):
+ return RequestSlotProducerResult.success(candidate_contract, attempts=attempt)
+ candidate_contract = contract
+
+ if candidate_contract is not None:
+ last_failure = RequestSlotProducerFailureKind.INCONSISTENT_OUTPUT
+ return RequestSlotProducerResult.failure(last_failure, attempts=_MAX_CLASSIFIER_ATTEMPTS)
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index e12356601..2c5ae1455 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -4632,9 +4632,9 @@ async def wrapper({default_args}):
block_label=self.label,
)
- # A prompt-bearing code block gets a task v1 + step so its recorded calls render through
- # the standard action/artifact timeline and the agent can later take over on failure.
- # Promptless blocks have no task and persist neither actions nor screenshots.
+ # Every code block gets a container task v1 + step so its recorded calls render through
+ # the standard action/artifact timeline and are billable; on prompt-bearing blocks the
+ # task also seats a later agent takeover on failure.
recorder = CodeBlockActionRecording(
code_block=self,
page=page,
diff --git a/skyvern/forge/sdk/workflow/models/code_block_recording.py b/skyvern/forge/sdk/workflow/models/code_block_recording.py
index 0c7e783f4..65df87131 100644
--- a/skyvern/forge/sdk/workflow/models/code_block_recording.py
+++ b/skyvern/forge/sdk/workflow/models/code_block_recording.py
@@ -66,9 +66,7 @@ class CodeBlockActionRecording:
return self.recording_page.last_recorded_exception()
async def create_task_and_step(self) -> None:
- """Create the task/step that can anchor recorded actions for prompt-bearing blocks."""
- if not self._code_block.prompt:
- return
+ """Create the container task/step that anchors recorded actions (promptless blocks included)."""
try:
self._task, self._step = await app.agent.create_task_and_step_from_code_block(
code_block=self._code_block,
@@ -191,3 +189,16 @@ class CodeBlockActionRecording:
workflow_run_block_id=self._workflow_run_block_id,
exc_info=True,
)
+ if not success or self._step is None:
+ return
+ # Billing counts the action rows persist() wrote, so this must stay after persist on every
+ # success path; best-effort like the rest of recording — never change the block outcome.
+ try:
+ await app.AGENT_FUNCTION.post_code_block_execution(self._task, self._step)
+ except Exception:
+ LOG.warning(
+ "Code block billing hook failed",
+ workflow_run_block_id=self._workflow_run_block_id,
+ task_id=self._task.task_id,
+ exc_info=True,
+ )
diff --git a/tests/unit/test_copilot_request_slots.py b/tests/unit/test_copilot_request_slots.py
new file mode 100644
index 000000000..bdc5268b5
--- /dev/null
+++ b/tests/unit/test_copilot_request_slots.py
@@ -0,0 +1,673 @@
+from __future__ import annotations
+
+import asyncio
+import json
+
+import pytest
+from pydantic import BaseModel, ValidationError
+
+from skyvern.forge.sdk.api.llm.exceptions import EmptyLLMResponseError, InvalidLLMResponseFormat
+from skyvern.forge.sdk.copilot import request_slots as request_slots_module
+from skyvern.forge.sdk.copilot.request_slots import (
+ CanonicalRequestSlotV1,
+ RequestSlotContractV1,
+ RequestSlotDeclarationV1,
+ RequestSlotEnvelopeV1,
+ RequestSlotPinability,
+ RequestSlotPlane,
+ RequestSlotProducerFailureKind,
+ RequestSlotProducerInputV1,
+ RequestSlotProducerResult,
+ RequestSlotSourceV1,
+ canonicalize_request_slots,
+ produce_request_slots,
+ request_slot_contracts_agree,
+ request_slot_source_text,
+ request_slot_sources,
+)
+
+
+def _input(**overrides: object) -> RequestSlotProducerInputV1:
+ values: dict[str, object] = {
+ "version": "1",
+ "latest_request": "Return whether a public form exists and the recommended next action.",
+ "workflow_context": "name: public path validation",
+ "earliest_user_turn": "User requested a validation-only workflow.",
+ "latest_prior_user_turn": "Keep the workflow reusable.",
+ "latest_assistant_turn": "I can validate the public path.",
+ "retained_history": ("user: Do not submit anything.",),
+ "global_context": '{"user_goal": "validate the public path"}',
+ }
+ values.update(overrides)
+ return RequestSlotProducerInputV1.model_validate(values)
+
+
+def _source_id(request: RequestSlotProducerInputV1, quote: str) -> str:
+ matches = [source.source_id for source in request_slot_sources(request) if quote in source.text]
+ assert len(matches) == 1, (quote, matches)
+ return matches[0]
+
+
+def _response(
+ request: RequestSlotProducerInputV1,
+ *slots: tuple[str, str, str],
+) -> dict[str, object]:
+ return {
+ "version": "1",
+ "slots": [
+ {
+ "source_id": _source_id(request, quote),
+ "source_quote": quote,
+ "plane": plane,
+ "pinability": pinability,
+ }
+ for quote, plane, pinability in slots
+ ],
+ }
+
+
+def _envelope(
+ request: RequestSlotProducerInputV1,
+ *slots: tuple[str, str, str],
+) -> RequestSlotEnvelopeV1:
+ return RequestSlotEnvelopeV1.model_validate_json(json.dumps(_response(request, *slots)))
+
+
+def _identity(contract: RequestSlotContractV1) -> tuple[tuple[str, str, str, str], ...]:
+ return tuple(
+ (slot.slot_id, slot.canonical_path, slot.plane.value, slot.pinability.value) for slot in contract.slots
+ )
+
+
+def _anchor_texts(request: RequestSlotProducerInputV1, contract: RequestSlotContractV1) -> list[str]:
+ return [request_slot_source_text(request, slot) for slot in contract.slots]
+
+
+def test_request_slot_models_are_strict_bounded_and_model_cannot_name_paths() -> None:
+ request = _input()
+ source_id = _source_id(request, "public form")
+ valid_declaration = {
+ "source_id": source_id,
+ "source_quote": "public form",
+ "plane": "run",
+ "pinability": "shapeless_valid",
+ }
+
+ with pytest.raises(ValidationError):
+ RequestSlotProducerInputV1.model_validate({"version": "2", "latest_request": "Build it"})
+ with pytest.raises(ValidationError):
+ RequestSlotProducerInputV1.model_validate({"version": "1", "latest_request": "x" * 16_385})
+ with pytest.raises(ValidationError):
+ RequestSlotDeclarationV1.model_validate({**valid_declaration, "path_segments": ["output", "public_form"]})
+ with pytest.raises(ValidationError):
+ RequestSlotDeclarationV1.model_validate(
+ {key: value for key, value in valid_declaration.items() if key != "pinability"}
+ )
+ with pytest.raises(ValidationError):
+ RequestSlotDeclarationV1.model_validate({**valid_declaration, "source_id": "latest_request"})
+ with pytest.raises(ValidationError):
+ RequestSlotDeclarationV1.model_validate({**valid_declaration, "source_quote": ""})
+ with pytest.raises(ValidationError):
+ RequestSlotDeclarationV1.model_validate({**valid_declaration, "plane": "unknown"})
+ with pytest.raises(ValidationError):
+ RequestSlotDeclarationV1.model_validate({**valid_declaration, "pinability": "maybe"})
+ with pytest.raises(ValidationError):
+ RequestSlotSourceV1.model_validate({"source_id": "u1", "order": 0, "text": "Return status."})
+ with pytest.raises(ValidationError):
+ RequestSlotEnvelopeV1.model_validate({"version": "1", "slots": []})
+ with pytest.raises(ValidationError):
+ RequestSlotProducerResult.model_validate({"status": "success", "attempts": 1})
+
+
+def test_request_slot_input_requires_explicit_context_fields_but_allows_empty_values() -> None:
+ payload = _input().model_dump()
+ for field_name in (
+ "latest_request",
+ "workflow_context",
+ "earliest_user_turn",
+ "latest_prior_user_turn",
+ "latest_assistant_turn",
+ "retained_history",
+ "global_context",
+ ):
+ with pytest.raises(ValidationError):
+ RequestSlotProducerInputV1.model_validate(
+ {key: value for key, value in payload.items() if key != field_name}
+ )
+
+ empty = RequestSlotProducerInputV1.model_validate(
+ {
+ "version": "1",
+ "latest_request": "",
+ "workflow_context": "",
+ "earliest_user_turn": "",
+ "latest_prior_user_turn": "",
+ "latest_assistant_turn": "",
+ "retained_history": (),
+ "global_context": "",
+ }
+ )
+ assert request_slot_sources(empty) == ()
+
+
+ ("model", "payload"),
+ [
+ (RequestSlotProducerInputV1, {"version": "1", "latest_request": b"Build it"}),
+ (
+ RequestSlotDeclarationV1,
+ {"source_id": "u0", "source_quote": b"status", "plane": "run", "pinability": "pinned"},
+ ),
+ (
+ RequestSlotSourceV1,
+ {"source_id": "u0", "order": 0.0, "text": "Return status."},
+ ),
+ (
+ RequestSlotContractV1,
+ {"version": "1", "request_digest": "0" * 64, "slots": (), "count": 1.0},
+ ),
+ (
+ RequestSlotProducerResult,
+ {"status": "failure", "attempts": 1.0, "failure_kind": RequestSlotProducerFailureKind.INVALID_OUTPUT},
+ ),
+ ],
+)
+def test_public_v1_models_reject_coercible_values(model: type[BaseModel], payload: dict[str, object]) -> None:
+ with pytest.raises(ValidationError):
+ model.model_validate(payload)
+
+
+def test_request_sources_are_user_owned_chronological_deduplicated_and_server_named() -> None:
+ request = _input(
+ earliest_user_turn="Return invoice_number.",
+ retained_history=("Return invoice_number.", "Return due_date."),
+ latest_prior_user_turn="Return invoice_number.",
+ latest_request="Also return status.",
+ workflow_context="output.workflow_decoy",
+ latest_assistant_turn="Return output.assistant_decoy",
+ global_context='{"output":"global_decoy"}',
+ )
+
+ sources = request_slot_sources(request)
+
+ assert [source.source_id for source in sources] == ["u0", "u1", "u2"]
+ assert [source.text for source in sources] == [
+ "Return due_date.",
+ "Return invoice_number.",
+ "Also return status.",
+ ]
+ assert all("decoy" not in source.text for source in sources)
+
+
+def test_canonicalization_derives_server_owned_paths_ids_count_and_source_spans() -> None:
+ request = _input(latest_request="Return the public form status and recommended next action.")
+ envelope = _envelope(
+ request,
+ ("recommended next action", "run", "shapeless_valid"),
+ ("public form status", "definition", "pinned"),
+ )
+
+ contract = canonicalize_request_slots(request=request, envelope=envelope)
+
+ assert contract.count == 2
+ assert [slot.ordinal for slot in contract.slots] == [0, 1]
+ assert [slot.canonical_path.rsplit("_", 1)[-1] for slot in contract.slots] == ["00", "01"]
+ assert all(slot.canonical_path.startswith("output.request_slot_") for slot in contract.slots)
+ assert all(len(slot.slot_id) == 64 for slot in contract.slots)
+ assert [slot.plane for slot in contract.slots] == [RequestSlotPlane.DEFINITION, RequestSlotPlane.RUN]
+ assert [slot.pinability for slot in contract.slots] == [
+ RequestSlotPinability.PINNED,
+ RequestSlotPinability.SHAPELESS_VALID,
+ ]
+ assert _anchor_texts(request, contract) == ["public form status", "recommended next action"]
+ assert contract == RequestSlotContractV1.model_validate(contract.model_dump())
+
+
+ ("latest_request", "quotes", "error"),
+ [
+ ("Return status.", ("missing",), "not present"),
+ ("Return status and status.", ("status",), "not unique"),
+ ("Return public form exists.", ("public form exists", "form exists"), "overlap"),
+ ],
+)
+def test_canonicalization_rejects_missing_ambiguous_and_overlapping_anchors(
+ latest_request: str,
+ quotes: tuple[str, ...],
+ error: str,
+) -> None:
+ request = _input(latest_request=latest_request)
+ source_id = request_slot_sources(request)[-1].source_id
+ envelope = RequestSlotEnvelopeV1.model_validate_json(
+ json.dumps(
+ {
+ "version": "1",
+ "slots": [
+ {
+ "source_id": source_id,
+ "source_quote": quote,
+ "plane": "run",
+ "pinability": "shapeless_valid",
+ }
+ for quote in quotes
+ ],
+ }
+ )
+ )
+
+ with pytest.raises(ValueError, match=error):
+ canonicalize_request_slots(request=request, envelope=envelope)
+
+
+def test_canonicalization_rejects_unknown_source_and_context_only_anchor() -> None:
+ request = _input(latest_request="Return status.", workflow_context="output.workflow_decoy")
+ for source_id, source_quote in (("u99", "status"), (request_slot_sources(request)[-1].source_id, "workflow_decoy")):
+ envelope = RequestSlotEnvelopeV1.model_validate_json(
+ json.dumps(
+ {
+ "version": "1",
+ "slots": [
+ {
+ "source_id": source_id,
+ "source_quote": source_quote,
+ "plane": "run",
+ "pinability": "shapeless_valid",
+ }
+ ],
+ }
+ )
+ )
+ with pytest.raises(ValueError):
+ canonicalize_request_slots(request=request, envelope=envelope)
+
+
+def test_response_order_and_quote_boundary_variation_do_not_change_identity() -> None:
+ request = _input(
+ latest_request=(
+ "Return a structured summary showing whether a public form exists, whether the path is login-only, "
+ "the visible page/path label, and the recommended next action."
+ )
+ )
+ response_shapes = [
+ (
+ ("whether a public form exists", "run", "shapeless_valid"),
+ ("whether the path is login-only", "run", "shapeless_valid"),
+ ("the visible page/path label", "run", "shapeless_valid"),
+ ("the recommended next action", "run", "shapeless_valid"),
+ ),
+ (
+ ("recommended next action", "run", "shapeless_valid"),
+ ("page/path label", "run", "shapeless_valid"),
+ ("path is login-only", "run", "shapeless_valid"),
+ ("a public form exists", "run", "shapeless_valid"),
+ ),
+ (
+ ("visible page/path label", "run", "shapeless_valid"),
+ ("public form exists", "run", "shapeless_valid"),
+ ("recommended next action", "run", "shapeless_valid"),
+ ("login-only", "run", "shapeless_valid"),
+ ),
+ ]
+
+ contracts = [
+ canonicalize_request_slots(request=request, envelope=_envelope(request, *response_shape))
+ for response_shape in response_shapes
+ ]
+
+ assert contracts[0].count == contracts[1].count == contracts[2].count == 4
+ assert _identity(contracts[0]) == _identity(contracts[1]) == _identity(contracts[2])
+ for contract in contracts:
+ anchors = _anchor_texts(request, contract)
+ assert any("public form" in anchor for anchor in anchors)
+ assert any("login-only" in anchor for anchor in anchors)
+ assert any("page/path label" in anchor for anchor in anchors)
+ assert any("recommended next action" in anchor for anchor in anchors)
+
+
+def test_contract_agreement_detects_membership_that_opaque_identity_does_not_encode() -> None:
+ request = _input(latest_request="Return alpha and beta.")
+ alpha = canonicalize_request_slots(
+ request=request,
+ envelope=_envelope(request, ("alpha", "run", "shapeless_valid")),
+ )
+ beta = canonicalize_request_slots(
+ request=request,
+ envelope=_envelope(request, ("beta", "run", "shapeless_valid")),
+ )
+
+ assert _identity(alpha) == _identity(beta)
+ assert not request_slot_contracts_agree(alpha, beta)
+
+
+def test_pinability_is_not_identity_but_plane_is() -> None:
+ request = _input(latest_request="Return status.")
+ pinned = canonicalize_request_slots(
+ request=request,
+ envelope=_envelope(request, ("status", "run", "pinned")),
+ ).slots[0]
+ unpinnable = canonicalize_request_slots(
+ request=request,
+ envelope=_envelope(request, ("status", "run", "unpinnable")),
+ ).slots[0]
+ definition = canonicalize_request_slots(
+ request=request,
+ envelope=_envelope(request, ("status", "definition", "pinned")),
+ ).slots[0]
+
+ assert pinned.canonical_path == unpinnable.canonical_path == definition.canonical_path
+ assert pinned.slot_id == unpinnable.slot_id
+ assert pinned.slot_id != definition.slot_id
+ assert pinned.pinability != unpinnable.pinability
+
+
+def test_canonical_models_reject_tampered_server_fields() -> None:
+ request = _input(latest_request="Return status.")
+ contract = canonicalize_request_slots(
+ request=request,
+ envelope=_envelope(request, ("status", "run", "shapeless_valid")),
+ )
+ slot = contract.slots[0]
+
+ with pytest.raises(ValidationError):
+ CanonicalRequestSlotV1.model_validate({**slot.model_dump(), "canonical_path": "output.login_only"})
+ with pytest.raises(ValidationError):
+ RequestSlotContractV1.model_validate({**contract.model_dump(), "count": 99})
+
+
+async def test_producer_retries_invalid_fresh_payload_then_succeeds() -> None:
+ request = _input(latest_request="Return status.")
+ responses = [
+ {
+ "version": "1",
+ "slots": [{"source_id": _source_id(request, "status"), "source_quote": "status", "plane": "run"}],
+ },
+ _response(request, ("status", "run", "shapeless_valid")),
+ _response(request, ("status", "run", "shapeless_valid")),
+ ]
+
+ async def handler(prompt: str, prompt_name: str, **_: object) -> dict[str, object]:
+ assert prompt_name == "workflow-copilot-request-slots"
+ return responses.pop(0)
+
+ result = await produce_request_slots(request=request, handler=handler, timeout_seconds=1.0)
+
+ assert result.status == "success"
+ assert result.attempts == 3
+ assert result.contract is not None
+ assert result.contract.slots[0].pinability == RequestSlotPinability.SHAPELESS_VALID
+ assert responses == []
+
+
+async def test_producer_requires_source_overlap_agreement_before_success() -> None:
+ request = _input(latest_request="Return whether a public form exists.")
+ responses = [
+ _response(request, ("whether a public form exists", "run", "shapeless_valid")),
+ _response(request, ("public form exists", "run", "shapeless_valid")),
+ ]
+
+ async def handler(prompt: str, prompt_name: str, **_: object) -> dict[str, object]:
+ return responses.pop(0)
+
+ result = await produce_request_slots(request=request, handler=handler, timeout_seconds=1.0)
+
+ assert result.status == "success"
+ assert result.attempts == 2
+ assert result.contract is not None
+ assert request_slot_source_text(request, result.contract.slots[0]) == "whether a public form exists"
+ assert responses == []
+
+
+async def test_producer_retries_disagreement_until_consecutive_contracts_agree() -> None:
+ request = _input(latest_request="Return alpha and beta.")
+ responses = [
+ _response(request, ("alpha", "run", "shapeless_valid")),
+ _response(
+ request,
+ ("alpha", "run", "shapeless_valid"),
+ ("beta", "run", "shapeless_valid"),
+ ),
+ _response(
+ request,
+ ("alpha", "run", "shapeless_valid"),
+ ("beta", "run", "shapeless_valid"),
+ ),
+ ]
+
+ async def handler(prompt: str, prompt_name: str, **_: object) -> dict[str, object]:
+ return responses.pop(0)
+
+ result = await produce_request_slots(request=request, handler=handler, timeout_seconds=1.0)
+
+ assert result.status == "success"
+ assert result.attempts == 3
+ assert result.contract is not None
+ assert result.contract.count == 2
+ assert responses == []
+
+
+async def test_producer_requires_plane_and_pinability_agreement() -> None:
+ request = _input(latest_request="Return status.")
+ responses = [
+ _response(request, ("status", "definition", "pinned")),
+ _response(request, ("status", "run", "shapeless_valid")),
+ _response(request, ("status", "run", "shapeless_valid")),
+ ]
+
+ async def handler(prompt: str, prompt_name: str, **_: object) -> dict[str, object]:
+ return responses.pop(0)
+
+ result = await produce_request_slots(request=request, handler=handler, timeout_seconds=1.0)
+
+ assert result.status == "success"
+ assert result.attempts == 3
+ assert result.contract is not None
+ assert result.contract.slots[0].plane == RequestSlotPlane.RUN
+ assert result.contract.slots[0].pinability == RequestSlotPinability.SHAPELESS_VALID
+ assert responses == []
+
+
+async def test_producer_can_recover_from_an_a_b_a_sequence_without_majority_minting() -> None:
+ request = _input(latest_request="Return alpha and beta.")
+ responses = [
+ _response(request, ("alpha", "run", "shapeless_valid")),
+ _response(
+ request,
+ ("alpha", "run", "shapeless_valid"),
+ ("beta", "run", "shapeless_valid"),
+ ),
+ _response(request, ("alpha", "run", "shapeless_valid")),
+ _response(request, ("alpha", "run", "shapeless_valid")),
+ ]
+
+ async def handler(prompt: str, prompt_name: str, **_: object) -> dict[str, object]:
+ return responses.pop(0)
+
+ result = await produce_request_slots(request=request, handler=handler, timeout_seconds=1.0)
+
+ assert result.status == "success"
+ assert result.attempts == 4
+ assert result.contract is not None
+ assert result.contract.count == 1
+ assert responses == []
+
+
+async def test_producer_degrades_when_only_nonconsecutive_valid_shapes_agree() -> None:
+ request = _input(latest_request="Return alpha and beta.")
+ responses = [
+ _response(request, ("alpha", "run", "shapeless_valid")),
+ _response(
+ request,
+ ("alpha", "run", "shapeless_valid"),
+ ("beta", "run", "shapeless_valid"),
+ ),
+ _response(request, ("alpha", "run", "shapeless_valid")),
+ _response(
+ request,
+ ("alpha", "run", "shapeless_valid"),
+ ("beta", "run", "shapeless_valid"),
+ ),
+ ]
+
+ async def handler(prompt: str, prompt_name: str, **_: object) -> dict[str, object]:
+ return responses.pop(0)
+
+ result = await produce_request_slots(request=request, handler=handler, timeout_seconds=1.0)
+
+ assert result == RequestSlotProducerResult.failure(
+ RequestSlotProducerFailureKind.INCONSISTENT_OUTPUT,
+ attempts=4,
+ )
+ assert responses == []
+
+
+ ("exception", "failure_kind"),
+ [
+ (EmptyLLMResponseError(""), RequestSlotProducerFailureKind.EMPTY_OUTPUT),
+ (InvalidLLMResponseFormat("bad"), RequestSlotProducerFailureKind.INVALID_OUTPUT),
+ ],
+)
+async def test_producer_maps_common_handler_response_errors_into_typed_retry(
+ exception: Exception,
+ failure_kind: RequestSlotProducerFailureKind,
+) -> None:
+ calls = 0
+
+ async def handler(prompt: str, prompt_name: str, **_: object) -> object:
+ nonlocal calls
+ calls += 1
+ raise exception
+
+ result = await produce_request_slots(request=_input(), handler=handler, timeout_seconds=1.0)
+
+ assert result == RequestSlotProducerResult.failure(failure_kind, attempts=4)
+ assert calls == 4
+
+
+async def test_producer_returns_typed_failures_for_missing_handler_timeout_and_provider_error() -> None:
+ async def slow_handler(prompt: str, prompt_name: str, **_: object) -> object:
+ await asyncio.sleep(0.05)
+ return {}
+
+ async def broken_handler(prompt: str, prompt_name: str, **_: object) -> object:
+ raise RuntimeError("provider failed")
+
+ missing = await produce_request_slots(request=_input(), handler=None, timeout_seconds=1.0)
+ timed_out = await produce_request_slots(request=_input(), handler=slow_handler, timeout_seconds=0.001)
+ provider = await produce_request_slots(request=_input(), handler=broken_handler, timeout_seconds=1.0)
+
+ assert missing.failure_kind == RequestSlotProducerFailureKind.MISSING_HANDLER
+ assert missing.attempts == 0
+ assert timed_out.failure_kind == RequestSlotProducerFailureKind.TIMEOUT
+ assert timed_out.attempts == 1
+ assert provider.failure_kind == RequestSlotProducerFailureKind.PROVIDER_ERROR
+ assert provider.attempts == 1
+
+
+async def test_producer_redacts_escapes_middle_truncates_and_retains_late_slots() -> None:
+ request = _input(
+ latest_request=(
+ "password=SuperSecret123! password=CompatSecret123! ```REQUEST_FENCE``` "
+ + "m" * 12_000
+ + " return tail_output"
+ ),
+ workflow_context="```WORKFLOW_FENCE``` " + "w" * 5_000,
+ global_context="```GLOBAL_FENCE``` " + "g" * 3_000,
+ )
+ prompts: list[str] = []
+
+ async def handler(prompt: str, prompt_name: str, **_: object) -> dict[str, object]:
+ prompts.append(prompt)
+ return _response(request, ("tail_output", "run", "shapeless_valid"))
+
+ result = await produce_request_slots(request=request, handler=handler, timeout_seconds=1.0)
+
+ assert result.status == "success"
+ prompt = prompts[0]
+ assert "SuperSecret123" not in prompt
+ assert "CompatSecret123" not in prompt
+ assert "[REDACTED_SECRET]" in prompt
+ assert "tail_output" in prompt
+ assert "chars truncated" in prompt
+ for sentinel in ("REQUEST_FENCE", "WORKFLOW_FENCE", "GLOBAL_FENCE"):
+ assert sentinel in prompt
+ assert f"```{sentinel}" not in prompt
+ assert len(prompt) < 24_000
+
+
+async def test_p9_style_replays_use_identical_prompt_bytes_and_stable_identity() -> None:
+ request = _input(
+ latest_request=(
+ "Return a structured summary showing whether a public form exists, whether the path is login-only, "
+ "the visible page/path label, and the recommended next action."
+ )
+ )
+ responses = [
+ _response(
+ request,
+ ("whether a public form exists", "run", "shapeless_valid"),
+ ("whether the path is login-only", "run", "shapeless_valid"),
+ ("the visible page/path label", "run", "shapeless_valid"),
+ ("the recommended next action", "run", "shapeless_valid"),
+ ),
+ _response(
+ request,
+ ("recommended next action", "run", "shapeless_valid"),
+ ("page/path label", "run", "shapeless_valid"),
+ ("path is login-only", "run", "shapeless_valid"),
+ ("public form exists", "run", "shapeless_valid"),
+ ),
+ _response(
+ request,
+ ("login-only", "run", "shapeless_valid"),
+ ("public form exists", "run", "shapeless_valid"),
+ ("visible page/path label", "run", "shapeless_valid"),
+ ("recommended next action", "run", "shapeless_valid"),
+ ),
+ ]
+ prompts: list[bytes] = []
+ contracts: list[RequestSlotContractV1] = []
+
+ for raw_response in responses:
+
+ async def handler(prompt: str, prompt_name: str, **_: object) -> dict[str, object]:
+ prompts.append(prompt.encode())
+ return raw_response
+
+ result = await produce_request_slots(request=request, handler=handler, timeout_seconds=1.0)
+ assert result.contract is not None
+ contracts.append(result.contract)
+
+ assert all(prompt == prompts[0] for prompt in prompts)
+ assert len(prompts) == 6
+ assert _identity(contracts[0]) == _identity(contracts[1]) == _identity(contracts[2])
+ assert [contract.count for contract in contracts] == [4, 4, 4]
+ for contract in contracts:
+ anchors = _anchor_texts(request, contract)
+ assert sum("public form" in anchor for anchor in anchors) == 1
+ assert sum("login-only" in anchor for anchor in anchors) == 1
+ assert sum("page/path label" in anchor for anchor in anchors) == 1
+ assert sum("recommended next action" in anchor for anchor in anchors) == 1
+
+
+def test_contract_namespace_never_collides_with_legacy_semantic_paths() -> None:
+ request = _input(latest_request="Return whether the path is login-only.")
+ contract = canonicalize_request_slots(
+ request=request,
+ envelope=_envelope(request, ("path is login-only", "run", "shapeless_valid")),
+ )
+
+ assert contract.slots[0].canonical_path != "output.login_only"
+ assert contract.slots[0].canonical_path != "output.path_is_login_only"
+ assert contract.slots[0].canonical_path.startswith("output.request_slot_")
+ assert request_slots_module.PROMPT_NAME == "workflow-copilot-request-slots"
diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.py
index 631b6115c..d2aa9a08c 100644
--- a/tests/unit/workflow/test_code_block_recorder.py
+++ b/tests/unit/workflow/test_code_block_recorder.py
@@ -420,10 +420,12 @@ def _patch_execute_environment(
"create_action": AsyncMock(return_value=None),
"update_task": AsyncMock(return_value=None),
"update_step": AsyncMock(return_value=None),
+ "billing_hook": AsyncMock(return_value=None),
}
monkeypatch.setattr(
"skyvern.forge.sdk.workflow.models.block.app.AGENT_FUNCTION.validate_code_block", validate_code_block
)
+ monkeypatch.setattr(app.AGENT_FUNCTION, "post_code_block_execution", mocks["billing_hook"], raising=False)
monkeypatch.setattr(CodeBlock, "get_or_create_browser_state", get_browser_state)
monkeypatch.setattr(app.BROWSER_MANAGER, "get_for_workflow_run", lambda *args, **kwargs: browser_state)
monkeypatch.setattr(CodeBlock, "get_workflow_run_context", lambda *args: context)
@@ -632,8 +634,8 @@ async def test_self_heal_decline_finalizes_seat_failed(monkeypatch: pytest.Monke
@pytest.mark.asyncio
-async def test_goalless_code_block_creates_no_task_or_actions(monkeypatch: pytest.MonkeyPatch) -> None:
- """Without a goal there is no task to hang actions on, so none are created or persisted."""
+async def test_goalless_code_block_creates_task_and_persists_actions(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A goalless block still gets a container task so its page activity is visible and billable."""
page = FakePage()
context = FakeWorkflowRunContext()
mocks = _patch_execute_environment(monkeypatch, page, context)
@@ -642,13 +644,15 @@ async def test_goalless_code_block_creates_no_task_or_actions(monkeypatch: pytes
result = await block.execute(workflow_run_id="wr_test", workflow_run_block_id="wrb_test", organization_id="o_test")
assert result.success is True
- assert mocks["create_task_and_step"].await_count == 0
- assert mocks["create_action"].await_count == 0
+ assert mocks["create_task_and_step"].await_count == 1
+ actions = _created_actions(mocks)
+ assert [a.action_type for a in actions] == [ActionType.CLICK]
+ assert all(a.task_id == "tsk_code" and a.step_id == "stp_code" for a in actions)
@pytest.mark.asyncio
-async def test_goalless_code_block_skips_screenshots(monkeypatch: pytest.MonkeyPatch) -> None:
- """No task means screenshots would have no action row to anchor to, so don't take orphan ones."""
+async def test_goalless_code_block_takes_screenshots(monkeypatch: pytest.MonkeyPatch) -> None:
+ """With a container task now created for goalless blocks, screenshots anchor like goal blocks."""
page = FakePage()
context = FakeWorkflowRunContext()
mocks = _patch_execute_environment(monkeypatch, page, context)
@@ -657,7 +661,60 @@ async def test_goalless_code_block_skips_screenshots(monkeypatch: pytest.MonkeyP
result = await block.execute(workflow_run_id="wr_test", workflow_run_block_id="wrb_test", organization_id="o_test")
assert result.success is True
- assert mocks["create_artifact"].await_count == 0
+ assert mocks["create_artifact"].await_count == 1
+
+
+async def test_code_block_success_invokes_billing_hook(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A successful code block invokes post_code_block_execution with its container task + step, after persist."""
+ page = FakePage()
+ context = FakeWorkflowRunContext()
+ mocks = _patch_execute_environment(monkeypatch, page, context)
+
+ block = _make_code_block("await page.locator('#go').click()\nvalue = 'ok'", goal="go")
+ result = await block.execute(workflow_run_id="wr_test", workflow_run_block_id="wrb_test", organization_id="o_test")
+
+ assert result.success is True
+ mocks["billing_hook"].assert_awaited_once()
+ task, step = mocks["billing_hook"].await_args.args
+ assert task.task_id == "tsk_code"
+ assert step.step_id == "stp_code"
+ # Billing counts persisted action rows, so the hook must fire after persist.
+ assert mocks["create_action"].await_count == 1
+
+
+async def test_code_block_failure_skips_billing_hook(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A failed code block is not billed."""
+
+ class ExplodingLocator(FakeLocator):
+ async def click(self, **kwargs): # noqa: ANN003, ANN201
+ raise RuntimeError("element detached")
+
+ page = FakePage()
+ page.inner = ExplodingLocator()
+ context = FakeWorkflowRunContext()
+ mocks = _patch_execute_environment(monkeypatch, page, context)
+
+ block = _make_code_block("await page.locator('#x').click()", goal="go")
+ result = await block.execute(workflow_run_id="wr_test", workflow_run_block_id="wrb_test", organization_id="o_test")
+
+ assert result.success is False
+ assert mocks["billing_hook"].await_count == 0
+
+
+async def test_billing_hook_failure_does_not_fail_block(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Billing is best-effort at this seam: a hook error must never change the block outcome."""
+ page = FakePage()
+ context = FakeWorkflowRunContext()
+ mocks = _patch_execute_environment(monkeypatch, page, context)
+ mocks["billing_hook"].side_effect = RuntimeError("billing backend down")
+
+ block = _make_code_block("value = 'ok'", goal="go")
+ result = await block.execute(workflow_run_id="wr_test", workflow_run_block_id="wrb_test", organization_id="o_test")
+
+ assert result.success is True
@pytest.mark.asyncio