Skip to content

Automate browser based workflows with AI

Add downloaded files tab to browser session detail page (#SKY-7500) (#4911)

Celal Zamanoğlu53db80ed8dcf
diff --git a/skyvern-frontend/src/router.tsx b/skyvern-frontend/src/router.tsx
index 9e527b788..8891f5ede 100644
--- a/skyvern-frontend/src/router.tsx
+++ b/skyvern-frontend/src/router.tsx
@@ -39,6 +39,7 @@ const router = createBrowserRouter([
{ index: true, element: <Navigate to="stream" replace /> },
{ path: "stream", element: <></> },
{ path: "recordings", element: <></> },
+ { path: "downloads", element: <></> },
],
},
{
diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSession.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSession.tsx
index abf4fffea..bc90540f0 100644
--- a/skyvern-frontend/src/routes/browserSessions/BrowserSession.tsx
+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSession.tsx
@@ -24,14 +24,19 @@ import { useCloseBrowserSessionMutation } from "@/routes/browserSessions/hooks/u
import { CopyText } from "@/routes/workflows/editor/Workspace";
import { type BrowserSession as BrowserSessionType } from "@/routes/workflows/types/browserSessionTypes";
+import { BrowserSessionDownloads } from "./BrowserSessionDownloads";
import { BrowserSessionVideo } from "./BrowserSessionVideo";
+type TabName = "stream" | "recordings" | "downloads";
+
function BrowserSession() {
const { browserSessionId } = useParams();
const location = useLocation();
- const activeTab = location.pathname.endsWith("/recordings")
+ const activeTab: TabName = location.pathname.endsWith("/recordings")
? "recordings"
- : "stream";
+ : location.pathname.endsWith("/downloads")
+ ? "downloads"
+ : "stream";
const [isDialogOpen, setIsDialogOpen] = useState(false);
const credentialGetter = useCredentialGetter();
@@ -133,6 +138,7 @@ function BrowserSession() {
options={[
{ label: "Stream", to: "stream" },
{ label: "Recordings", to: "recordings" },
+ { label: "Downloads", to: "downloads" },
]}
/>
@@ -191,7 +197,7 @@ function BrowserSession() {
/>
</div>
<div
- className="h-full w-full"
+ className="absolute left-0 top-0 h-full w-full"
style={{
visibility: activeTab === "recordings" ? "visible" : "hidden",
pointerEvents: activeTab === "recordings" ? "auto" : "none",
@@ -199,6 +205,15 @@ function BrowserSession() {
>
<BrowserSessionVideo />
</div>
+ <div
+ className="absolute left-0 top-0 h-full w-full"
+ style={{
+ visibility: activeTab === "downloads" ? "visible" : "hidden",
+ pointerEvents: activeTab === "downloads" ? "auto" : "none",
+ }}
+ >
+ <BrowserSessionDownloads />
+ </div>
</div>
</div>
<Outlet />
diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionDownloads.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionDownloads.tsx
new file mode 100644
index 000000000..82e1bee9d
--- /dev/null
+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionDownloads.tsx
@@ -0,0 +1,179 @@
+import { DownloadIcon, EyeOpenIcon, FileIcon } from "@radix-ui/react-icons";
+import { useQuery } from "@tanstack/react-query";
+import { useParams } from "react-router-dom";
+
+import { getClient } from "@/api/AxiosClient";
+import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { type BrowserSession } from "@/routes/workflows/types/browserSessionTypes";
+
+const PREVIEWABLE_EXTENSIONS = new Set([
+ "pdf",
+ "png",
+ "jpg",
+ "jpeg",
+ "gif",
+ "svg",
+ "webp",
+ "bmp",
+ "ico",
+ "txt",
+ "csv",
+ "json",
+ "xml",
+ "html",
+ "htm",
+ "mp4",
+ "webm",
+ "mp3",
+ "wav",
+ "ogg",
+]);
+
+function isPreviewable(filename: string): boolean {
+ const ext = filename.split(".").pop()?.toLowerCase() ?? "";
+ return PREVIEWABLE_EXTENSIONS.has(ext);
+}
+
+function downloadFile(url: string, filename: string) {
+ fetch(url)
+ .then((response) => response.blob())
+ .then((blob) => {
+ const blobUrl = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = blobUrl;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(blobUrl);
+ })
+ .catch(console.error);
+}
+
+function BrowserSessionDownloads() {
+ const { browserSessionId } = useParams();
+ const credentialGetter = useCredentialGetter();
+
+ const {
+ data: browserSession,
+ isLoading,
+ error,
+ } = useQuery<BrowserSession>({
+ queryKey: ["browserSession", browserSessionId],
+ queryFn: async () => {
+ const client = await getClient(credentialGetter, "sans-api-v1");
+ const response = await client.get(
+ `/browser_sessions/${browserSessionId}`,
+ );
+ return response.data;
+ },
+ enabled: !!browserSessionId,
+ });
+
+ const downloadedFiles = browserSession?.downloaded_files ?? [];
+
+ if (isLoading) {
+ return (
+ <div className="flex h-full w-full items-center justify-center">
+ <div className="text-lg">Loading downloads...</div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex h-full w-full items-center justify-center">
+ <div className="text-lg text-red-500">
+ Error loading downloads: {error.message}
+ </div>
+ </div>
+ );
+ }
+
+ if (downloadedFiles.length === 0) {
+ return (
+ <div className="flex h-full w-full items-center justify-center">
+ <div className="text-center">
+ <div className="mb-2 text-lg text-gray-500">No downloaded files</div>
+ <div className="text-sm text-gray-400">
+ Files downloaded during this browser session will appear here
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="h-full w-full overflow-auto p-4">
+ <div className="mb-4">
+ <h2 className="text-xl font-semibold">Downloaded Files</h2>
+ <p className="text-sm text-gray-500">
+ Files downloaded during this browser session
+ </p>
+ </div>
+
+ <div className="grid grid-cols-3 gap-3 lg:grid-cols-4 xl:grid-cols-5">
+ {downloadedFiles.map((file, index) => {
+ const urlPath = file.url.split("?")[0] ?? file.url;
+ const filename =
+ file.filename || urlPath.split("/").pop() || `File ${index + 1}`;
+ const previewable = file.url && isPreviewable(filename);
+
+ return (
+ <div
+ key={file.url || file.checksum || index}
+ className="flex flex-col items-center gap-2 rounded-lg border p-3"
+ >
+ <FileIcon className="size-7" />
+ <div className="w-full min-w-0 text-center">
+ <span className="block truncate text-xs" title={filename}>
+ {filename}
+ </span>
+ {file.modified_at && (
+ <div className="mt-0.5 text-xs text-gray-500">
+ {new Date(file.modified_at).toLocaleString()}
+ </div>
+ )}
+ </div>
+ {file.url && (
+ <div className="flex w-full gap-1.5">
+ {previewable ? (
+ <a
+ href={file.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="flex flex-1 items-center justify-center gap-1 rounded border px-2 py-1 text-xs hover:bg-muted"
+ title={`Preview ${filename}`}
+ >
+ <EyeOpenIcon className="size-3" />
+ Preview
+ </a>
+ ) : (
+ <button
+ disabled
+ className="flex flex-1 cursor-not-allowed items-center justify-center gap-1 rounded border px-2 py-1 text-xs opacity-40"
+ title="Preview not available for this file type"
+ >
+ <EyeOpenIcon className="size-3" />
+ Preview
+ </button>
+ )}
+ <button
+ onClick={() => downloadFile(file.url, filename)}
+ className="flex flex-1 items-center justify-center gap-1 rounded border px-2 py-1 text-xs hover:bg-muted"
+ title={`Download ${filename}`}
+ >
+ <DownloadIcon className="size-3" />
+ Download
+ </button>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+export { BrowserSessionDownloads };
diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionVideo.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionVideo.tsx
index 138b68e56..8b88e2f1d 100644
--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionVideo.tsx
+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionVideo.tsx
@@ -3,15 +3,9 @@ import { useParams } from "react-router-dom";
import { getClient } from "@/api/AxiosClient";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { type Recording } from "@/routes/workflows/types/browserSessionTypes";
import { artifactApiBaseUrl } from "@/util/env";
-interface Recording {
- url: string;
- checksum: string;
- filename: string;
- modified_at: string;
-}
-
function getRecordingUrl(url: string | null | undefined): string | null {
if (!url) {
return null;
diff --git a/skyvern-frontend/src/routes/workflows/components/WorkflowVisualComparisonDrawer.tsx b/skyvern-frontend/src/routes/workflows/components/WorkflowVisualComparisonDrawer.tsx
index 3d975983d..05b03153d 100644
--- a/skyvern-frontend/src/routes/workflows/components/WorkflowVisualComparisonDrawer.tsx
+++ b/skyvern-frontend/src/routes/workflows/components/WorkflowVisualComparisonDrawer.tsx
@@ -124,7 +124,10 @@ function getWorkflowElements(version: WorkflowVersion) {
extraHttpHeaders: version.extra_http_headers
? JSON.stringify(version.extra_http_headers)
: null,
- runWith: version.run_with,
+ runWith:
+ version.adaptive_caching && version.run_with === "code"
+ ? "code_v2"
+ : version.run_with,
scriptCacheKey: version.cache_key,
aiFallback: version.ai_fallback ?? true,
runSequentially: version.run_sequentially ?? false,
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index 064fb59fd..90ff81f9a 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -451,9 +451,13 @@ export function WorkflowCopilotChat({
max_screenshot_scrolls: saveData.settings.maxScreenshotScrolls,
totp_verification_url: saveData.workflow.totp_verification_url,
extra_http_headers: extraHttpHeaders,
- run_with: saveData.settings.runWith,
+ run_with:
+ saveData.settings.runWith === "code_v2"
+ ? "code"
+ : saveData.settings.runWith,
cache_key: normalizedKey,
ai_fallback: saveData.settings.aiFallback ?? true,
+ adaptive_caching: saveData.settings.runWith === "code_v2",
workflow_definition: {
version: saveData.workflowDefinitionVersion,
parameters: saveData.parameters,
diff --git a/skyvern-frontend/src/routes/workflows/debugger/Debugger.tsx b/skyvern-frontend/src/routes/workflows/debugger/Debugger.tsx
index cfb5b716a..a4dfcf2dc 100644
--- a/skyvern-frontend/src/routes/workflows/debugger/Debugger.tsx
+++ b/skyvern-frontend/src/routes/workflows/debugger/Debugger.tsx
@@ -71,7 +71,10 @@ function Debugger() {
extraHttpHeaders: workflow.extra_http_headers
? JSON.stringify(workflow.extra_http_headers)
: null,
- runWith: workflow.run_with,
+ runWith:
+ workflow.adaptive_caching && workflow.run_with === "code"
+ ? "code_v2"
+ : workflow.run_with,
scriptCacheKey: workflow.cache_key,
aiFallback: workflow.ai_fallback ?? true,
runSequentially: workflow.run_sequentially ?? false,
diff --git a/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.tsx
index 74db4448e..b938f8345 100644
--- a/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.tsx
@@ -72,7 +72,10 @@ function WorkflowEditor() {
extraHttpHeaders: workflow.extra_http_headers
? JSON.stringify(workflow.extra_http_headers)
: null,
- runWith: workflow.run_with,
+ runWith:
+ workflow.adaptive_caching && workflow.run_with === "code"
+ ? "code_v2"
+ : workflow.run_with,
scriptCacheKey: workflow.cache_key,
aiFallback: workflow.ai_fallback ?? true,
runSequentially: workflow.run_sequentially ?? false,
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index 29ffacec9..87b7670a5 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -1007,7 +1007,10 @@ function Workspace({
extraHttpHeaders: workflowData.extra_http_headers
? JSON.stringify(workflowData.extra_http_headers)
: null,
- runWith: workflowData.run_with ?? null,
+ runWith:
+ workflowData.adaptive_caching && workflowData.run_with === "code"
+ ? "code_v2"
+ : workflowData.run_with ?? null,
scriptCacheKey: workflowData.cache_key ?? null,
aiFallback: workflowData.ai_fallback ?? true,
runSequentially: workflowData.run_sequentially ?? false,
@@ -1054,7 +1057,10 @@ function Workspace({
extraHttpHeaders: selectedVersion.extra_http_headers
? JSON.stringify(selectedVersion.extra_http_headers)
: null,
- runWith: selectedVersion.run_with,
+ runWith:
+ selectedVersion.adaptive_caching && selectedVersion.run_with === "code"
+ ? "code_v2"
+ : selectedVersion.run_with,
scriptCacheKey: selectedVersion.cache_key,
aiFallback: selectedVersion.ai_fallback ?? true,
runSequentially: selectedVersion.run_sequentially ?? false,
@@ -1753,9 +1759,13 @@ function Workspace({
created_at: new Date().toISOString(),
modified_at: new Date().toISOString(),
deleted_at: null,
- run_with: saveData.settings.runWith,
+ run_with:
+ saveData.settings.runWith === "code_v2"
+ ? "code"
+ : saveData.settings.runWith,
cache_key: saveData.settings.scriptCacheKey,
ai_fallback: saveData.settings.aiFallback,
+ adaptive_caching: saveData.settings.runWith === "code_v2",
run_sequentially: saveData.settings.runSequentially,
sequential_key: saveData.settings.sequentialKey,
folder_id: null,
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/StartNode.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/StartNode.tsx
index b1b0f16c7..ea26a2f44 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/StartNode.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/StartNode/StartNode.tsx
@@ -307,6 +307,12 @@ function StartNode({ id, data, parentId }: NodeProps<StartNode>) {
Skyvern Agent
</SelectItem>
<SelectItem value="code">Code</SelectItem>
+ <SelectItem value="code_v2">
+ <span>Code 2.0</span>{" "}
+ <span className="text-xs italic text-yellow-400">
+ new
+ </span>
+ </SelectItem>
</SelectContent>
</Select>
</div>
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx
index 801c65386..e98f75ce9 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx
@@ -156,7 +156,10 @@ function getWorkflowElements(version: WorkflowVersion) {
extraHttpHeaders: version.extra_http_headers
? JSON.stringify(version.extra_http_headers)
: null,
- runWith: version.run_with,
+ runWith:
+ version.adaptive_caching && version.run_with === "code"
+ ? "code_v2"
+ : version.run_with,
scriptCacheKey: version.cache_key,
aiFallback: version.ai_fallback ?? true,
runSequentially: version.run_sequentially ?? false,
diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
index dbc9b5e81..5f7b073f9 100644
--- a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
@@ -3964,6 +3964,7 @@ function convert(workflow: WorkflowApiResponse): WorkflowCreateYAMLRequest {
is_saved_task: workflow.is_saved_task,
status: workflow.status,
run_with: workflow.run_with,
+ adaptive_caching: workflow.adaptive_caching ?? undefined,
cache_key: workflow.cache_key,
ai_fallback: workflow.ai_fallback ?? undefined,
run_sequentially: workflow.run_sequentially ?? undefined,
diff --git a/skyvern-frontend/src/routes/workflows/types/browserSessionTypes.ts b/skyvern-frontend/src/routes/workflows/types/browserSessionTypes.ts
index 6bb487dc1..8a80ad51a 100644
--- a/skyvern-frontend/src/routes/workflows/types/browserSessionTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/browserSessionTypes.ts
@@ -5,6 +5,7 @@ interface BrowserSession {
browser_address: string | null;
browser_session_id: string;
completed_at: string | null;
+ downloaded_files: DownloadedFile[] | null;
recordings: Recording[];
runnable_id: string | null;
runnable_type: string | null;
@@ -23,9 +24,17 @@ interface Recording {
modified_at: string;
}
+interface DownloadedFile {
+ url: string;
+ checksum: string | null;
+ filename: string | null;
+ modified_at: string | null;
+}
+
export {
type BrowserSession,
type BrowserSessionExtension,
type BrowserSessionType,
+ type DownloadedFile,
type Recording,
};
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
index 55e57917d..8d6eadc4e 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
@@ -600,9 +600,10 @@ export type WorkflowApiResponse = {
created_at: string;
modified_at: string;
deleted_at: string | null;
- run_with: string | null; // 'agent' or 'code'
+ run_with: string | null; // 'agent', 'code', or 'code_v2'
cache_key: string | null;
ai_fallback: boolean | null;
+ adaptive_caching: boolean | null;
run_sequentially: boolean | null;
sequential_key: string | null;
folder_id: string | null;
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
index 1d590bff2..275a2a114 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
@@ -18,6 +18,7 @@ export type WorkflowCreateYAMLRequest = {
run_with?: string | null;
cache_key?: string | null;
ai_fallback?: boolean;
+ adaptive_caching?: boolean;
run_sequentially?: boolean;
sequential_key?: string | null;
folder_id?: string | null;
diff --git a/skyvern-frontend/src/store/WorkflowHasChangesStore.ts b/skyvern-frontend/src/store/WorkflowHasChangesStore.ts
index e02bcc83c..c1251f7ff 100644
--- a/skyvern-frontend/src/store/WorkflowHasChangesStore.ts
+++ b/skyvern-frontend/src/store/WorkflowHasChangesStore.ts
@@ -142,9 +142,13 @@ const useWorkflowSave = (opts?: WorkflowSaveOpts) => {
max_screenshot_scrolls: saveData.settings.maxScreenshotScrolls,
totp_verification_url: saveData.workflow.totp_verification_url,
extra_http_headers: extraHttpHeaders,
- run_with: saveData.settings.runWith,
+ run_with:
+ saveData.settings.runWith === "code_v2"
+ ? "code"
+ : saveData.settings.runWith,
cache_key: normalizedKey,
ai_fallback: saveData.settings.aiFallback ?? true,
+ adaptive_caching: saveData.settings.runWith === "code_v2",
workflow_definition: {
version: saveData.workflowDefinitionVersion,
parameters: saveData.parameters,
diff --git a/skyvern/forge/prompts/skyvern/batch-form-fill-plan.j2 b/skyvern/forge/prompts/skyvern/batch-form-fill-plan.j2
new file mode 100644
index 000000000..fa722569d
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/batch-form-fill-plan.j2
@@ -0,0 +1,50 @@
+# Goal
+Plan values for form fields that need filling.
+
+# User's Goal
+{{ goal }}
+
+# Available Data
+{% if data and data is mapping and data.items()|list|length > 0 %}
+{% for key, value in data.items() %}
+- {{ key }}: {{ value }}
+{% endfor %}
+{% elif data %}
+{{ data }}
+{% endif %}
+
+# Form Fields
+{% for field in fields %}
+{{ loop.index }}. **{{ field.label }}** ({{ field.format_hint }})
+{%- if field.required %} [REQUIRED]{% endif %}
+{%- if field.placeholder %} — hint: "{{ field.placeholder }}"{% endif %}
+{%- if field.options %} — options: {{ field.options | join(", ") }}{% endif %}
+{% endfor %}
+
+# Rules
+## CRITICAL: You MUST provide a value for EVERY field unless noted below.
+- Return null ONLY for file upload fields or truly optional fields where no matching data exists in the context.
+- For choice fields (radio, dropdown, checkbox) with listed options: you MUST select an option. NEVER return null.
+- If no data matches a choice field, pick the most reasonable/common/default option.
+- If no data matches a text field, make a reasonable professional guess based on the context.
+
+## CRITICAL for choice fields (radio, dropdown, checkbox):
+- Return the EXACT option label text as listed in the options above. Do NOT rephrase or summarize.
+- Example: if options are "I am not a protected veteran", "I am a protected veteran" — return "I am not a protected veteran", NOT "No".
+- Example: if options are "Man", "Woman", "Non-binary", "Prefer not to say" — return "Man", NOT "Male".
+- Example: if options are "Decline to self-identify", "Yes, I have a disability" — return the exact text, NOT "No" or "Decline".
+- For checkboxes: return a JSON array of exact labels to check.
+
+## Format rules by field type
+- **Short text**: brief factual value (1-5 words). NEVER sentences or paragraphs.
+- **Email/URL/phone**: exact formatted value.
+- **Paragraph/essay**: 2-3 professional sentences using the available data context.
+- **Dropdown select**: pick EXACTLY ONE option from the listed options. Return the EXACT option label text as a string. NEVER return null.
+- **Single choice radio**: pick EXACTLY ONE option from the listed options. Return the EXACT option label. NEVER return null.
+- **Multi-select checkboxes**: return a JSON array of EXACT selected option labels. Pick ONLY relevant ones, NOT all. Select at least one if required.
+- **Single checkbox**: return true or false. NEVER return null.
+- **File upload**: return null (file uploads are handled separately).
+
+# Output Format
+JSON object mapping field number (string) to value. Return null only for file uploads or truly optional fields with no matching data:
+{"1": "2020", "2": "Other", "3": ["English", "Spanish"], "4": "A brief professional response.", "5": null}
diff --git a/skyvern/forge/prompts/skyvern/extract-applicant-parameters.j2 b/skyvern/forge/prompts/skyvern/extract-applicant-parameters.j2
new file mode 100644
index 000000000..f7b02343c
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/extract-applicant-parameters.j2
@@ -0,0 +1,33 @@
+# Goal
+Extract structured data from input text into canonical form field categories.
+
+# Input Text
+{{ input_text }}
+
+# Categories to Extract
+For each category below, extract the matching value from the input text. Return null if not found.
+
+{% for cat in categories %}
+{{ loop.index }}. **{{ cat.name }}** — {{ cat.prompt }}
+{% endfor %}
+
+# Rules
+- Extract EXACT values from the context — do NOT invent or hallucinate data.
+- For name, email, phone, URLs: extract the literal value.
+- For location: extract as "City, State" or "City, Country" format.
+- For work authorization, gender, race, veteran, disability: extract the stated answer or preference, or null if not mentioned.
+- For salary: extract the number or range as stated.
+- For cover letter / additional info: return null (these require generation, not extraction).
+- For referral source: return null unless explicitly stated.
+- If the context is ambiguous for a field, return null rather than guessing.
+
+# Output Format
+JSON object mapping category name to extracted value (or null):
+```json
+{
+ "full_name": "John Doe",
+ "email": "[email protected]",
+ "phone": null,
+ ...
+}
+```
diff --git a/skyvern/forge/prompts/skyvern/page-classify.j2 b/skyvern/forge/prompts/skyvern/page-classify.j2
new file mode 100644
index 000000000..095030fbc
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/page-classify.j2
@@ -0,0 +1,21 @@
+You are classifying the current state of a web page. Given the current URL and page text, determine which of the provided options best describes the page state.
+
+Current URL: `{{ current_url }}`
+
+Page text (first 2000 characters):
+```
+{{ extracted_text }}
+```
+
+Classify the page into ONE of the following options:
+{% for key, description in options.items() %}
+- "{{ key }}": {{ description }}
+{% endfor %}
+- "UNKNOWN": None of the above options match the current page state.
+
+Reply in JSON format:
+{
+ "reasoning": str, // Brief explanation of why you chose this classification
+ "classification": str, // One of the option keys listed above, or "UNKNOWN"
+ "confidence": float // 0.0 to 1.0
+}
diff --git a/skyvern/forge/prompts/skyvern/quality-audit.j2 b/skyvern/forge/prompts/skyvern/quality-audit.j2
new file mode 100644
index 000000000..9997ccec4
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/quality-audit.j2
@@ -0,0 +1,38 @@
+# Form Fill Quality Audit
+
+You are auditing a form that was automatically filled by a bot. Your job is to check whether the values entered are correct and in the right fields.
+
+# Applicant Data (source of truth)
+{{ data }}
+
+# Form Fields After Auto-Fill
+{% for field in fields %}
+{{ loop.index }}. **{{ field.label }}** (type: {{ field.type }})
+ Value: {{ field.value if field.value is not none and field.value != '' else "(empty)" }}
+{% endfor %}
+
+# Instructions
+For each field, evaluate:
+1. Is the value correct based on the applicant data?
+2. Is the value in the right field (not scrambled with another field)?
+3. Is the format appropriate (e.g., phone numbers look like phone numbers)?
+4. For choice fields (radio/dropdown): was a reasonable option selected?
+
+# Output Format
+Return a JSON object:
+{
+ "score": <number 0-100>,
+ "field_count": <number of fields audited>,
+ "correct_count": <number of fields filled correctly>,
+ "issues": [
+ {"field_number": 1, "field_label": "...", "expected": "...", "actual": "...", "severity": "critical|warning|minor", "problem": "..."}
+ ],
+ "summary": "<one-line overall assessment>"
+}
+
+Severity levels:
+- **critical**: wrong value in wrong field (scrambling), completely wrong data
+- **warning**: reasonable but imprecise value, suboptimal choice selection
+- **minor**: formatting issue, slightly different phrasing but correct intent
+
+If all fields look correct, return score=100, empty issues, and a positive summary.
diff --git a/skyvern/forge/prompts/skyvern/script-failure-triage.j2 b/skyvern/forge/prompts/skyvern/script-failure-triage.j2
new file mode 100644
index 000000000..2b213c80b
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/script-failure-triage.j2
@@ -0,0 +1,56 @@
+You are a failure triage analyst for a browser automation system. A cached script failed, and the AI agent fallback also failed. Determine whether improved script code could handle this failure.
+
+## Episode Details
+- **Block**: {{ block_label }}
+- **Script Error**: {{ error_message or "N/A" }}
+- **Page URL**: {{ page_url or "N/A" }}
+{% if agent_actions and agent_actions.failure_reason %}
+- **AI Fallback Failure**: {{ agent_actions.failure_reason }}
+{% endif %}
+{% if agent_actions and agent_actions.block_status %}
+- **Block Status**: {{ agent_actions.block_status }}
+{% endif %}
+
+{% if page_text_snapshot %}
+## Page Text (truncated)
+```
+{{ page_text_snapshot }}
+```
+{% endif %}
+
+{% if agent_actions and agent_actions.actions %}
+## AI Agent Actions (what it tried before failing)
+{% for a in agent_actions.actions %}
+{{ loop.index }}. {{ a.action_type }}: {{ a.intention or a.reasoning or "N/A" }} ({{ a.status }})
+{%- if a.field %} [field: {{ a.field }}]{% endif %}
+{% endfor %}
+{% endif %}
+
+{% if agent_actions and agent_actions.form_fields %}
+## Form Fields on Page
+{% for f in agent_actions.form_fields %}
+- {{ f.label or f.name or f.placeholder }} ({{ f.tag }}:{{ f.type }}{% if f.required %}, required{% endif %})
+{% endfor %}
+{% endif %}
+
+## Classification
+
+Respond with EXACTLY one line — either `CODE_FIXABLE` or `NOT_CODE_FIXABLE` — followed by a brief reason.
+
+**CODE_FIXABLE** — the script can be improved to handle this:
+- Wrong selectors for a different page layout or form variant
+- Unhandled widget (autocomplete dropdown, date picker, rich text editor)
+- Agent got stuck repeating the same action (value typed but didn't persist)
+- Max steps reached because of a single problematic field
+- Form validation errors that better input handling could avoid
+
+**NOT_CODE_FIXABLE** — no code change would help:
+- Website is down, returning 404/500, or page content is an error page
+- CAPTCHA or bot detection is blocking the page
+- Authentication/login failure (credentials issue, not a form issue)
+- Required data is completely missing and cannot be reasonably inferred
+- Rate limiting or IP blocking
+- Browser crash or network timeout
+- Job posting removed or expired
+
+Answer:
diff --git a/skyvern/forge/prompts/skyvern/script-reviewer-conditional.j2 b/skyvern/forge/prompts/skyvern/script-reviewer-conditional.j2
new file mode 100644
index 000000000..feaec1157
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/script-reviewer-conditional.j2
@@ -0,0 +1,70 @@
+You are a script optimizer for a browser automation system. Your job is to convert a conditional block's branch logic into pure Python code, eliminating the need for an LLM call at runtime.
+
+## MANDATORY RULES
+1. Return ONLY valid Python. No explanations, no markdown.
+2. Use 4-space indentation consistently.
+3. The function signature MUST be: `async def block_fn(page, context):`
+4. The function MUST return a dict with `"next_block_label"` (str) and `"branch_index"` (int).
+5. Access upstream block outputs and workflow parameters via `context.parameters['key']`.
+6. For Jinja-style expressions that check lengths, truthiness, or simple comparisons — translate directly to Python.
+7. If any branch expression requires subjective judgment, visual page inspection, or natural language understanding — return ONLY the string `CANNOT_CONVERT` (no code).
+8. The default/else branch should be the final `else` clause.
+
+## Conditional Block: `{{ block_label }}`
+
+### Branch Expressions (evaluated top-to-bottom, first True match wins)
+{% for branch in branches %}
+#### Branch {{ loop.index }}{% if branch.is_default %} (DEFAULT/ELSE){% endif %}
+
+- **Original expression**: `{{ branch.original_expression or "None (default branch)" }}`
+- **Rendered expression**: `{{ branch.rendered_expression or "N/A" }}`
+- **Result**: {{ branch.result }}
+- **Next block label**: `{{ branch.next_block_label }}`
+{% endfor %}
+
+## How conditional blocks work
+
+Each branch has an expression (Jinja2 template) that is rendered with runtime values and then evaluated.
+Common patterns:
+- `{{ "{{ data | length }}" }}` → checks length of extracted data
+- `{{ "{{ value }}" }} == true` → checks if a value is truthy
+- `{{ "{{ items }}" }} > 0` → numeric comparison
+- Default branch has no expression — it's the fallback when no other branch matches.
+
+The expressions reference values from `context.parameters` which contains both workflow input parameters and outputs from upstream blocks.
+
+## What to generate
+
+Write a Python function that:
+1. Reads the relevant values from `context.parameters`
+2. Evaluates the conditions in order (matching the branch evaluation order)
+3. Returns the appropriate `next_block_label` and `branch_index` for the first matching condition
+
+## Example
+
+Given branches:
+- Branch 0: `{{ "{{ extracted_data | length }}" }} == 0` → `no_results_handler`
+- Branch 1: (default) → `process_results`
+
+Generate:
+```python
+async def block_fn(page, context):
+ extracted_data = context.parameters.get('extracted_data', [])
+ if len(extracted_data) == 0:
+ return {"next_block_label": "no_results_handler", "branch_index": 0}
+ else:
+ return {"next_block_label": "process_results", "branch_index": 1}
+```
+
+## Output
+Return a JSON object with a single key `"code"` containing the complete function as a string.
+Use `\n` for newlines inside the string value. Example:
+
+```json
+{"code": "async def block_fn(page, context):\n data = context.parameters.get('key', [])\n if len(data) == 0:\n return {\"next_block_label\": \"label_a\", \"branch_index\": 0}\n else:\n return {\"next_block_label\": \"label_b\", \"branch_index\": 1}"}
+```
+
+If the conditions require subjective judgment or cannot be expressed as Python, return:
+```json
+{"code": "CANNOT_CONVERT"}
+```
diff --git a/skyvern/forge/prompts/skyvern/script-reviewer-extraction.j2 b/skyvern/forge/prompts/skyvern/script-reviewer-extraction.j2
new file mode 100644
index 000000000..2cdef1a8e
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/script-reviewer-extraction.j2
@@ -0,0 +1,177 @@
+You are a script reviewer for a browser automation system. Your job is to make a MINIMAL edit to a cached Python script that extracts data from a page, so it handles one new page state.
+
+## MANDATORY RULES
+1. Keep your code SHORT. Add only the minimum branching needed.
+2. Use 4-space indentation consistently. Never mix tabs and spaces.
+3. The existing code is CORRECT — do NOT remove or rewrite existing paths.
+4. Return ONLY valid Python. No explanations, no comments about what you changed.
+5. Every `page.classify()` MUST have an `else` branch that calls `await page.element_fallback(navigation_goal="...")` followed by a generic `page.extract()`.
+6. Add `text_patterns` derived from the page text in the episode data below.
+7. Keep classify option descriptions short (< 10 words) and mutually exclusive.
+8. **PARAMETER NAMES**:
+ a. The `{{ "{{ param }}" }}` placeholders in the extraction goal and the **Workflow Parameter Keys** below are the KNOWN parameters. Always use `context.parameters['param']` for these.
+ b. For form fields that need values but have NO matching parameter:
+ - **Essay/freeform questions** (textarea, "Why do you want to work here?", "Describe a problem you solved"): use `ai='proactive'` with a descriptive prompt. The AI will generate a brief, professional answer using the workflow's overall context. Do NOT hardcode `'N/A'`.
+ - **Short factual fields** (text inputs like "GitHub URL", "Portfolio"): use `ai='proactive'` with a prompt describing the field. The AI will provide a reasonable value or skip appropriately.
+ - **Dropdowns/radios with no parameter**: use `ai='fallback'` with a prompt (existing pattern — the AI picks the best option).
+ c. NEVER hardcode `value='N/A'` for any field. Either use a parameter value or let the AI fill it with `ai='proactive'`.
+
+## Key Difference for Extraction Blocks
+- Put `page.classify()` BEFORE `page.extract()` to choose the right extraction prompt for the current page state.
+- Each branch should use a different, focused extraction prompt tailored to that page state.
+- The `else` branch should use `page.element_fallback()` then a generic `page.extract()`.
+
+## Block Extraction Goal
+```
+{{ navigation_goal }}
+```
+{% if parameter_keys %}
+
+## Workflow Parameter Keys
+These are the KNOWN parameter names for `context.parameters[...]`:
+{% for key in parameter_keys %}
+- `{{ key }}`
+{% endfor %}
+For fields not covered by these parameters, use `ai='proactive'` with a descriptive prompt (see Rule 8b).
+{% endif %}
+
+## Existing Cached Code (DO NOT REMOVE ANY EXISTING PATHS)
+```python
+{{ existing_code }}
+```
+
+## Fallback Episode Details
+The cached code failed and the AI agent took over. Here is what happened:
+{% for episode in episodes %}
+### Episode {{ loop.index }}
+- **Block Label**: {{ episode.block_label }}
+- **Fallback Type**: {{ episode.fallback_type }}
+- **Error**: {{ episode.error_message or "N/A" }}
+- **Classify Result**: {{ episode.classify_result or "N/A" }}
+- **Page URL at failure**: {{ episode.page_url or "N/A" }}
+- **Page Text at failure** (use this to derive text_patterns):
+```
+{{ episode.page_text_snapshot or "N/A" }}
+```
+{% if episode.agent_actions is mapping and episode.agent_actions.form_fields is defined and episode.agent_actions.form_fields %}
+- **Form Fields on Failed Page** (use to understand what the page requires):
+{% for f in episode.agent_actions.form_fields %}
+ - {{ f.label or f.name or f.placeholder }} ({{ f.tag }}:{{ f.type }}{% if f.required %}, required{% endif %})
+{% endfor %}
+{% endif %}
+- **Agent Actions After Fallback**:
+{% if episode.agent_actions is mapping and episode.agent_actions.actions is defined %}
+{% for a in episode.agent_actions.actions %}
+ {{ loop.index }}. {{ a.action_type }}: {{ a.intention or a.reasoning or "N/A" }} ({{ a.status }})
+{%- if a.field %} [field: {{ a.field }}]{% endif %}
+{%- if a.element_attributes %} [attrs: {{ a.element_attributes | tojson }}]{% endif %}
+{% endfor %}
+{% elif episode.agent_actions is mapping and episode.agent_actions.navigation_goal is defined %}
+ Surgical fallback: "{{ episode.agent_actions.navigation_goal }}" — {{ episode.agent_actions.steps_taken }} steps, completed={{ episode.agent_actions.completed }}
+{% elif episode.agent_actions %}
+ {{ episode.agent_actions | tojson }}
+{% else %}
+ N/A
+{% endif %}
+{% endfor %}
+
+{% if stale_branches %}
+## Stale Branches (candidates for removal)
+The following classify branches have NOT been accessed in over 90 days. The website may have changed and these page states may no longer exist. Remove these `elif` branches from the code if they are no longer relevant. Keep the `else`/`element_fallback` branch — it will catch any truly unexpected states.
+
+{% for branch in stale_branches %}
+- `{{ branch.branch_key }}` — last accessed {{ branch.last_hit_at }}, {{ branch.hit_count }} total hits
+{% endfor %}
+{% endif %}
+
+{% if historical_episodes %}
+## Past Failures & Fixes (cross-run history)
+The following failures occurred in PREVIOUS runs. Learn from these — do NOT repeat the same mistakes.
+
+{% for h in historical_episodes %}
+### Past episode {{ loop.index }}
+- **Error**: {{ h.error_message or "N/A" }}
+- **Reviewer fix applied**: {{ h.reviewer_output or "No fix recorded" }}
+- **Did the AI fallback succeed?**: {{ "Yes" if h.fallback_succeeded else ("No" if h.fallback_succeeded is sameas false else "Unknown") }}
+{% endfor %}
+
+**Key takeaway:** If the same error appears above multiple times, the previous fixes did NOT solve it. Try a fundamentally different approach.
+{% endif %}
+
+## What to do
+
+1. Identify that the page was in a different state than what the extraction prompt expected.
+2. Add a `page.classify()` call BEFORE the `page.extract()` call.
+3. Keep the existing extraction in one branch. Add a new branch with a focused extraction prompt for the new page state.
+4. The `else` branch MUST call `await page.element_fallback(navigation_goal="...")` followed by a generic `page.extract()`.
+{% if stale_branches %}
+5. Remove `elif` branches for stale states listed above (keep the `else` branch).
+6. Remove corresponding entries from `options` and `text_patterns` in the `page.classify()` call.
+{% endif %}
+
+## Example of the pattern
+
+Before (linear extraction):
+```python
+async def block_fn(page, context):
+ result = await page.extract(prompt="Extract the business name and registration number")
+ return result
+```
+
+After (with classify + branched extraction):
+```python
+async def block_fn(page, context):
+ state = await page.classify(
+ options={"results": "search results with business data", "no_results": "no matching records found"},
+ text_patterns={"results": "Registration Number", "no_results": "No records found"},
+ )
+ if state == "results":
+ result = await page.extract(prompt="Extract the business name and registration number")
+ elif state == "no_results":
+ result = await page.extract(prompt="Extract the 'no results' message from the page")
+ else:
+ await page.element_fallback(navigation_goal="Navigate to a state where data can be extracted")
+ result = await page.extract(prompt="Extract any available business data from the page")
+ return result
+```
+
+## Available Methods (COMPLETE API — do NOT invent methods not listed here)
+
+### Navigation
+- `await page.goto(url)` — Navigate to a URL
+- `await page.reload_page()` — Reload the current page
+
+### Interaction
+- `await page.click(selector=, ai=, prompt=)` — Click an element
+- `await page.fill(selector=, value=, ai=, prompt=)` — Fill a text input
+- `await page.select_option(selector=, value=, ai=, prompt=)` — Select a dropdown option
+
+### Data Extraction & Classification
+- `await page.extract(prompt="...", schema={...})` — Extract structured data (returns dict)
+- `await page.validate(prompt="...")` — Validate a condition on the page
+- `await page.classify(options={...}, url_patterns={...}, text_patterns={...})` — Classify page state
+
+### Lifecycle
+- `await page.complete()` — Mark the task as complete
+- `await page.wait(timeout_ms=)` — Wait for a duration
+
+### AI Fallback
+- `await page.element_fallback(navigation_goal="...", max_steps=10)` — Hand off to AI agent
+
+### Properties
+- `page.url` — Current page URL (str property, free, no LLM call)
+
+### DO NOT USE (these do NOT exist and will crash)
+- ~~`page.completed`~~ — Does NOT exist. Use `await page.complete()`.
+- ~~`page.current_url`~~ — Does NOT exist. Use `page.url`.
+- ~~`page.navigate()`~~ — Does NOT exist. Use `await page.goto(url)`.
+- ~~`page.text`~~ / ~~`page.content`~~ / ~~`page.title`~~ — Do NOT exist. Use `page.extract()`.
+- ~~`page.get_url()`~~ — Does NOT exist. Use `page.url`.
+
+## Output
+Return ONLY the complete updated function in a ```python block. No text before or after.
+
+```python
+{{ function_signature }}
+ # Your updated code here
+```
diff --git a/skyvern/forge/prompts/skyvern/script-reviewer-form-filling.j2 b/skyvern/forge/prompts/skyvern/script-reviewer-form-filling.j2
new file mode 100644
index 000000000..9a0b7e937
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/script-reviewer-form-filling.j2
@@ -0,0 +1,254 @@
+You are a script reviewer for a browser automation system that fills forms.
+Your job is to maintain a FIELD_MAP dictionary that maps form field labels to parameter keys and fill strategies, then call `page.fill_form(FIELD_MAP, context)` to fill the form dynamically.
+
+## MANDATORY RULES
+1. Output a FIELD_MAP dict + a function that calls `page.fill_form(FIELD_MAP, context)`.
+2. When a new label variant is found for an existing field, ADD it to that entry's `"labels"` list — never create a duplicate entry.
+3. When a new field is found that maps to a workflow parameter, add a new entry with `"param": "<key>"`.
+4. When a new field has NO matching parameter, add an entry with `"ai": "proactive"` and a descriptive prompt.
+5. NEVER use `page.classify()` in form-filling blocks.
+6. field_map keys are descriptive snake_case names (e.g., `"full_name"`, `"phone"`).
+ The `"labels"` list contains all known label variants for fuzzy matching.
+7. Use 4-space indentation consistently. Never mix tabs and spaces.
+8. Return ONLY valid Python. No explanations, no comments about what you changed.
+9. **PARAMETER NAMES — CRITICAL**:
+ a. The **Workflow Parameter Keys** section below lists EVERY valid parameter name.
+ `context.parameters['key']` is ONLY allowed when `key` appears in that list.
+ b. **NEVER INVENT parameter names.** If a form field does not have a matching
+ parameter key, use `"ai": "proactive"` instead.
+ c. NEVER hardcode `value='N/A'` for any field.
+10. Keep your code SHORT. The FIELD_MAP is data, not code — it should stay compact.
+
+## FIELD_MAP Entry Format
+Each entry in FIELD_MAP is a dict with these keys:
+- `"param"`: parameter key in `context.parameters` (or `None` if AI fills it)
+- `"action"`: `"fill"` | `"select"` | `"fill_autocomplete"` | `"click"` | `"upload_file"` — this is a **semantic intent**, not a literal method name. `fill_form()` automatically adapts the actual browser method based on the HTML element type found on the page. For example, `"action": "select"` will use `select_option()` for `<select>` dropdowns, `click()` for radio buttons, and iterate with `click()` for checkbox groups — all without changing the FIELD_MAP.
+- `"labels"`: list of known label variants (lowercase) for fuzzy matching against page fields
+- `"prompt"`: AI prompt describing what to fill
+- `"ai"`: (optional) `"fallback"` (default when param exists) or `"proactive"` (AI generates value)
+
+## Block Navigation Goal
+```
+{{ navigation_goal }}
+```
+{% if parameter_keys %}
+
+## Workflow Parameter Keys
+These are the KNOWN parameter names for `context.parameters[...]`:
+{% for key in parameter_keys %}
+- `{{ key }}`
+{% endfor %}
+For fields not covered by these parameters, use `"ai": "proactive"` with a descriptive prompt (see Rule 9b).
+{% endif %}
+
+## Existing Cached Code
+```python
+{{ existing_code }}
+```
+
+## Fallback Episode Details
+The cached code failed and the AI agent took over. Here is what happened:
+{% for episode in episodes %}
+### Episode {{ loop.index }}
+- **Block Label**: {{ episode.block_label }}
+- **Fallback Type**: {{ episode.fallback_type }}
+- **Error**: {{ episode.error_message or "N/A" }}
+- **Page URL at failure**: {{ episode.page_url or "N/A" }}
+- **Page Text at failure**:
+```
+{{ episode.page_text_snapshot or "N/A" }}
+```
+{% if episode.agent_actions is mapping and episode.agent_actions.form_fields is defined and episode.agent_actions.form_fields %}
+- **Form Fields on Failed Page** (use to update FIELD_MAP labels):
+{% for f in episode.agent_actions.form_fields %}
+ - {{ f.label or f.name or f.placeholder }} ({{ f.tag }}:{{ f.type }}{% if f.required %}, required{% endif %})
+{% endfor %}
+{% endif %}
+- **Agent Actions After Fallback** (use to map fields to params/actions):
+{% if episode.agent_actions is mapping and episode.agent_actions.actions is defined %}
+{% for a in episode.agent_actions.actions %}
+ {{ loop.index }}. {{ a.action_type }}: {{ a.intention or a.reasoning or "N/A" }} ({{ a.status }})
+{%- if a.field %} [field: {{ a.field }}]{% endif %}
+{%- if a.element_attributes %} [attrs: {{ a.element_attributes | tojson }}]{% endif %}
+{% endfor %}
+{% elif episode.agent_actions is mapping and episode.agent_actions.navigation_goal is defined %}
+ Surgical fallback: "{{ episode.agent_actions.navigation_goal }}" — {{ episode.agent_actions.steps_taken }} steps, completed={{ episode.agent_actions.completed }}
+{% elif episode.agent_actions %}
+ {{ episode.agent_actions | tojson }}
+{% else %}
+ N/A
+{% endif %}
+{% endfor %}
+
+{% if stale_branches %}
+## Stale Branches (candidates for removal)
+{% for branch in stale_branches %}
+- `{{ branch.branch_key }}` — last accessed {{ branch.last_hit_at }}, {{ branch.hit_count }} total hits
+{% endfor %}
+{% endif %}
+
+{% if historical_episodes %}
+## Past Failures & Fixes (cross-run history)
+The following failures occurred in PREVIOUS runs. Learn from these — do NOT repeat the same mistakes.
+
+{% for h in historical_episodes %}
+### Past episode {{ loop.index }}
+- **Error**: {{ h.error_message or "N/A" }}
+- **Reviewer fix applied**: {{ h.reviewer_output or "No fix recorded" }}
+- **Did the AI fallback succeed?**: {{ "Yes" if h.fallback_succeeded else ("No" if h.fallback_succeeded is sameas false else "Unknown") }}
+{% endfor %}
+
+**Key takeaway:** If the same error appears above multiple times, the previous fixes did NOT solve it. Try a fundamentally different approach.
+{% endif %}
+
+## Canonical Field Matching (IMPORTANT — read before modifying FIELD_MAP)
+The system has built-in canonical matching that automatically handles standard form fields.
+Do NOT add FIELD_MAP entries for any of these standard categories — they are matched automatically:
+- **Identity**: full name, email, phone
+- **Location/Company**: current location, current company
+- **Links**: linkedin, portfolio/website/github
+- **Content**: cover letter, resume
+- **Compensation/Dates**: salary expectation, start date, graduation year
+- **Experience/Education**: years of experience, education level
+- **Demographics (EEO)**: gender, race/ethnicity, veteran status, disability
+- **Other standard**: work authorization, referral source
+
+Only add FIELD_MAP entries for truly **custom/company-specific** fields that don't fit any standard category above.
+
+## What to do
+1. Compare the episode's form fields to the existing FIELD_MAP.
+2. For each field in the episode, first check if it matches a standard category listed above. If it does, do NOT add it to FIELD_MAP — canonical matching handles it automatically.
+3. For each truly custom field NOT covered by canonical matching and NOT in the FIELD_MAP, add a new entry.
+4. For each field that IS in the FIELD_MAP but with a different label, add the new label to that entry's `"labels"` list.
+5. Map fields to workflow parameter keys where possible. For fields with no matching parameter, use `"ai": "proactive"`.
+6. For autocomplete/typeahead fields (location, city, address), use `"action": "fill_autocomplete"`.
+7. Output the complete updated function with the updated FIELD_MAP.
+
+## How to translate agent actions into FIELD_MAP entries
+
+| Agent Action | FIELD_MAP Entry |
+|-------------|-----------------|
+| `input_text: Full name` [field: full_name] | `"full_name": {"param": "full_name", "action": "fill", "labels": ["full name", "name"], "prompt": "Fill the full name"}` |
+| `input_text: Location` (autocomplete) | `"location": {"param": "current_location", "action": "fill_autocomplete", "labels": ["location", "current location"], "prompt": "Fill the location"}` |
+| `select_option: Country` | `"country": {"param": None, "action": "select", "ai": "proactive", "labels": ["country"], "prompt": "Select the country"}` |
+| `input_text: Cover letter` (no param) | `"cover_letter": {"param": None, "action": "fill", "ai": "proactive", "labels": ["cover letter", "why are you interested"], "prompt": "Write a brief professional cover letter"}` |
+| `click: Areas of focus` (checkboxes) | `"areas_of_focus": {"param": None, "action": "select", "ai": "proactive", "labels": ["top 3 areas", "areas of focus", "specialization"], "prompt": "Select the applicant's top areas of focus"}` |
+| `click: Gender` (radio buttons) | `"gender": {"param": None, "action": "select", "ai": "proactive", "labels": ["gender", "what best describes your gender"], "prompt": "Select the applicant's gender"}` |
+
+**Note on checkbox/radio groups**: `scan_form_fields()` returns checkbox/radio groups as a single entry with `type: "checkbox_group"` or `"radio_group"` and an `options` list. Use `"action": "select"` for these — `fill_form()` will automatically iterate over options using `click()` per option.
+
+## CRITICAL: URL Navigation
+The function MUST start with `await page.goto(url)` before calling `fill_form()`.
+If the existing code already has a `page.goto(...)` call, KEEP IT. If it doesn't, ADD one using
+the URL from the block's `url` field or from the navigation_goal context.
+
+## Example output
+
+```python
+{{ function_signature }}
+ await page.goto(context.parameters.get('job_url', ''))
+ FIELD_MAP = {
+ "full_name": {
+ "param": "full_name",
+ "action": "fill",
+ "labels": ["full name", "name", "your name", "candidate name"],
+ "prompt": "Fill the applicant's full name",
+ },
+ "email": {
+ "param": "email",
+ "action": "fill",
+ "labels": ["email", "email address", "e-mail"],
+ "prompt": "Fill the applicant's email address",
+ },
+ "location": {
+ "param": "current_location",
+ "action": "fill_autocomplete",
+ "labels": ["location", "current location", "city", "where are you based"],
+ "prompt": "Fill the applicant's current location",
+ },
+ "cover_letter": {
+ "param": None,
+ "action": "fill",
+ "ai": "proactive",
+ "labels": ["cover letter", "why are you interested", "additional information"],
+ "prompt": "Write a brief, professional cover letter (2-3 sentences)",
+ },
+ "areas_of_focus": {
+ "param": None,
+ "action": "select",
+ "ai": "proactive",
+ "labels": ["top 3 areas you've focused on", "areas of focus", "specialization"],
+ "prompt": "Select the applicant's top 3 areas of focus based on applicant context.",
+ },
+ "gender": {
+ "param": None,
+ "action": "select",
+ "ai": "proactive",
+ "labels": ["gender", "what best describes your gender"],
+ "prompt": "Select the applicant's gender based on applicant context.",
+ },
+ }
+ await page.fill_form(FIELD_MAP, context, navigation_goal="{{ navigation_goal }}")
+ # Post-fill fixups for fields needing special handling:
+ await page.upload_file(prompt="Upload resume/CV", files=context.parameters.get('resume', ''))
+ await page.complete()
+```
+
+## Post-fill_form fixups (optional)
+After `page.fill_form(FIELD_MAP, context)`, you MAY add individual page method calls
+for fields that need special handling beyond what fill_form provides:
+
+- `await page.upload_file(prompt="Upload resume", files=context.parameters.get('resume', ''))` — for file upload fields
+- `await page.fill(selector='...', value='...', ai='fallback', prompt='...')` — for fields needing specific selectors
+- `await page.select_option(selector='...', value='...', ai='fallback', prompt='...')` — for dropdowns needing specific handling
+- `await page.click(selector='...', ai='fallback', prompt='...')` — for buttons/checkboxes
+
+Use fixups when:
+- A field requires `upload_file` (file inputs)
+- A field consistently fails with `fill_form` and works better with a specific selector
+- The reviewer has enough evidence from episodes that a direct call is more reliable
+
+Do NOT use fixups as a first resort — prefer FIELD_MAP entries. Use fixups only when FIELD_MAP + fill_form can't handle the field.
+
+## Available Methods (COMPLETE API — do NOT invent methods not listed here)
+
+### Form Filling
+- `await page.fill_form(field_map, context, navigation_goal="...")` — Scan page fields, match to FIELD_MAP, fill each field
+- `await page.scan_form_fields()` — Scan for form fields (called internally by fill_form)
+
+### Interaction
+- `await page.click(selector=, ai=, prompt=)` — Click an element
+- `await page.fill(selector=, value=, ai=, prompt=)` — Fill a text input
+- `await page.fill_autocomplete(selector=, value=, ai=, prompt=)` — Fill autocomplete/typeahead input
+- `await page.select_option(selector=, value=, ai=, prompt=)` — Select a dropdown option
+- `await page.upload_file(selector=, files=, ai=, prompt=)` — Upload a file
+
+### Data Extraction & Classification
+- `await page.extract(prompt="...", schema={...})` — Extract structured data (returns dict)
+- `await page.validate(prompt="...")` — Validate a condition on the page
+
+### Navigation & Lifecycle
+- `await page.goto(url)` — Navigate to a URL
+- `await page.complete()` — Mark the task as complete
+- `await page.wait(timeout_ms=)` — Wait for a duration
+
+### AI Fallback
+- `await page.element_fallback(navigation_goal="...", max_steps=10)` — Hand off to AI agent
+
+### Properties
+- `page.url` — Current page URL (str property, free, no LLM call)
+
+### DO NOT USE (these do NOT exist and will crash)
+- ~~`page.completed`~~ — Does NOT exist. Use `await page.complete()`.
+- ~~`page.current_url`~~ — Does NOT exist. Use `page.url`.
+- ~~`page.navigate()`~~ — Does NOT exist. Use `await page.goto(url)`.
+- ~~`page.text`~~ / ~~`page.content`~~ / ~~`page.title`~~ — Do NOT exist. Use `page.extract()`.
+- ~~`page.get_url()`~~ — Does NOT exist. Use `page.url`.
+
+## Output
+Return ONLY the complete updated function in a ```python block. No text before or after.
+
+```python
+{{ function_signature }}
+ # Your updated FIELD_MAP and fill_form call here
+```
diff --git a/skyvern/forge/prompts/skyvern/script-reviewer.j2 b/skyvern/forge/prompts/skyvern/script-reviewer.j2
new file mode 100644
index 000000000..f6d9e4a10
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/script-reviewer.j2
@@ -0,0 +1,450 @@
+You are a script reviewer for a browser automation system. Your job is to update a cached Python script so it handles a new page variant that caused it to fail.
+
+## MANDATORY RULES
+1. Keep your code SHORT. Add only the minimum branching needed.
+2. Use 4-space indentation consistently. Never mix tabs and spaces.
+3. Return ONLY valid Python. No explanations, no comments about what you changed.
+4. Every `page.classify()` MUST have an `else` branch that calls `await page.element_fallback(navigation_goal="...")`.
+5. Add `text_patterns` derived from the page text in the episode data below.
+6. Keep classify option descriptions short (< 10 words) and mutually exclusive.
+7. **SEMANTIC SELECTORS**: Use `ai='fallback'` with label-based selectors — NEVER copy xpaths from other branches. Build selectors using `:has-text()` (case-insensitive substring match). Examples: `selector='label:has-text("Full name") input'`, `selector='button:has-text("Submit")'`. If no semantic selector is possible (complex widgets), use `ai='fallback'` with only a `prompt=`.
+8. **ACCUMULATE SELECTORS**: NEVER remove a working selector. When the same field has different labels across variants (e.g. "Website" vs "URL"), use comma-separated CSS selectors: `selector='label:has-text("Website") input, label:has-text("URL") input'`. The first match wins.
+9. **PARAMETER NAMES — CRITICAL**:
+ a. The **Workflow Parameter Keys** section below lists EVERY valid parameter name. `context.parameters['key']` is ONLY allowed when `key` appears in that list.
+ b. **NEVER INVENT parameter names.** If a form field does not have a matching parameter key, do NOT create a `context.parameters['made_up_name']` reference. This will crash at runtime with a KeyError.
+ c. For form fields that have NO matching parameter key:
+ - **If the navigation goal describes a deterministic condition** (threshold, status check, string match, comparison) that decides the value → write Python code to compute it (see "Deterministic Logic" section below). This is FREE — no LLM call.
+ - **Essay/freeform questions** (textarea, "Why do you want to work here?"): use `ai='proactive'` with a descriptive prompt. The AI generates an answer from the workflow's overall context at runtime.
+ - **Short factual fields** (text inputs like "How did you hear about us?"): use `ai='proactive'` with a prompt describing the field.
+ - **Dropdowns/radios with subjective choice**: use `ai='fallback'` with a prompt (the AI picks the best option).
+ d. NEVER hardcode `value='N/A'` for any field.
+ e. **Wrong** (crashes — `how_heard_about_job` is not a workflow parameter):
+ ```python
+ await page.fill(selector='...', value=context.parameters['how_heard_about_job'], ai='fallback', prompt='...')
+ ```
+ **Correct** (AI fills the field at runtime using workflow context):
+ ```python
+ await page.fill(selector='...', ai='proactive', prompt='Select how you heard about this job')
+ ```
+10. **URL PATTERNS**: When different variants come from different URL hosts or paths, add `url_patterns` to the `page.classify()` call for FREE Tier-0 disambiguation. Use regex on the URL path: `url_patterns={"variant_a": "example\\.com/form-a"}`. URL patterns are checked BEFORE text patterns and cost nothing.
+
+## Block Navigation Goal
+```
+{{ navigation_goal }}
+```
+{% if parameter_keys %}
+
+## Workflow Parameter Keys
+These are the KNOWN parameter names for `context.parameters[...]`:
+{% for key in parameter_keys %}
+- `{{ key }}`
+{% endfor %}
+For fields not covered by these parameters: use Python code if the value is deterministic (see "Deterministic Logic"), or `ai='proactive'` if it requires subjective judgment (see Rule 9c).
+{% endif %}
+
+## Existing Cached Code
+```python
+{{ existing_code }}
+```
+
+## Fallback Episode Details
+The cached code failed and the AI agent took over. Here is what happened:
+{% for episode in episodes %}
+### Episode {{ loop.index }}
+- **Block Label**: {{ episode.block_label }}
+- **Fallback Type**: {{ episode.fallback_type }}
+- **Error**: {{ episode.error_message or "N/A" }}
+- **Classify Result**: {{ episode.classify_result or "N/A" }}
+{% if episode.classify_result and episode.classify_result != "N/A" %}
+ ⚠️ The classify matched `{{ episode.classify_result }}` but its branch actions STILL FAILED. Update selectors for this branch using the episode data below.
+{% endif %}
+- **Page URL at failure**: {{ episode.page_url or "N/A" }}
+- **Page Text at failure** (use this to derive text_patterns):
+```
+{{ episode.page_text_snapshot or "N/A" }}
+```
+{% if episode.agent_actions is mapping and episode.agent_actions.form_fields is defined and episode.agent_actions.form_fields %}
+- **Form Fields on Failed Page** (use to understand what the page requires):
+{% for f in episode.agent_actions.form_fields %}
+ - {{ f.label or f.name or f.placeholder }} ({{ f.tag }}:{{ f.type }}{% if f.required %}, required{% endif %})
+{% endfor %}
+{% endif %}
+- **Agent Actions After Fallback** (use these to write the NEW branch actions):
+{% if episode.agent_actions is mapping and episode.agent_actions.actions is defined %}
+{% for a in episode.agent_actions.actions %}
+ {{ loop.index }}. {{ a.action_type }}: {{ a.intention or a.reasoning or "N/A" }} ({{ a.status }})
+{%- if a.field %} [field: {{ a.field }}]{% endif %}
+{%- if a.element_tag %} [tag: {{ a.element_tag }}]{% endif %}
+{%- if a.element_text %} [text: "{{ a.element_text }}"]{% endif %}
+{%- if a.css_suggestion %} **[USE THIS SELECTOR: `{{ a.css_suggestion }}`]**{% endif %}
+{%- if a.all_attributes %} [attrs: {{ a.all_attributes | tojson }}]{% endif %}
+{%- if not a.all_attributes and a.element_attributes %} [attrs: {{ a.element_attributes | tojson }}]{% endif %}
+{% endfor %}
+{% elif episode.agent_actions is mapping and episode.agent_actions.navigation_goal is defined %}
+ Surgical fallback: "{{ episode.agent_actions.navigation_goal }}" — {{ episode.agent_actions.steps_taken }} steps, completed={{ episode.agent_actions.completed }}
+{% elif episode.agent_actions %}
+ {{ episode.agent_actions | tojson }}
+{% else %}
+ N/A
+{% endif %}
+{% endfor %}
+
+{% if stale_branches %}
+## Stale Branches (candidates for removal)
+The following classify branches have NOT been accessed in over 90 days. The website may have changed and these page states may no longer exist. Remove these `elif` branches from the code if they are no longer relevant. Keep the `else`/`element_fallback` branch — it will catch any truly unexpected states.
+
+{% for branch in stale_branches %}
+- `{{ branch.branch_key }}` — last accessed {{ branch.last_hit_at }}, {{ branch.hit_count }} total hits
+{% endfor %}
+{% endif %}
+
+{% if historical_episodes %}
+## Past Failures & Fixes (cross-run history)
+The following failures occurred in PREVIOUS runs and were already reviewed. Learn from these patterns — do NOT repeat the same mistakes.
+
+{% for h in historical_episodes %}
+### Past episode {{ loop.index }}
+- **Error**: {{ h.error_message or "N/A" }}
+- **Reviewer fix applied**: {{ h.reviewer_output or "No fix recorded" }}
+- **Did the AI fallback succeed?**: {{ "Yes" if h.fallback_succeeded else ("No" if h.fallback_succeeded is sameas false else "Unknown") }}
+{% endfor %}
+
+**Key takeaway:** If the same error appears above multiple times, the previous fixes did NOT solve it. Try a fundamentally different approach instead of repeating the same pattern.
+{% endif %}
+
+## What to do
+
+{% for episode in episodes %}
+{% if episode.classify_result and episode.classify_result != "N/A" and episode.classify_result != "UNKNOWN" %}
+### Handling episode with existing branch `{{ episode.classify_result }}`
+The classify routed to `{{ episode.classify_result }}` but its actions failed. Update the branch's selectors:
+1. Keep existing selectors — ADD new label variants with comma-separated CSS selectors.
+2. Use the `[attrs: ...]` data from agent actions to find the field's label on the new variant.
+3. If the branch doesn't handle the page state at all, create a NEW `elif` branch with `text_patterns`.
+{% else %}
+### Adding a new branch
+1. Add a `page.classify()` call at the branch point (or update the existing one with a new option).
+2. Use semantic selectors with `ai='fallback'` for the new branch's actions.
+3. The `else` branch MUST call `await page.element_fallback(navigation_goal="...")`.
+4. Use the **Page Text at failure** to populate `text_patterns` for reliable classification.
+{% endif %}
+{% endfor %}
+
+## How to translate agent actions into code
+
+The Agent Actions show what the AI did on the failed page. Translate each action into code.
+
+### Using suggested selectors (PREFERRED)
+When an action has `[USE THIS SELECTOR: ...]`, use that selector directly — it was computed from the actual element the AI interacted with:
+
+```
+Action: input_text: Enter search term [USE THIS SELECTOR: `input[aria-label="Search Wikipedia"]`]
+Code: await page.fill(selector='input[aria-label="Search Wikipedia"]', value=..., ai='fallback', prompt='Enter search term')
+```
+
+### Building selectors from attributes
+When no suggested selector is available, build one from the element's `[tag]`, `[text]`, and `[attrs]`:
+
+| Agent Action | Code |
+|-------------|------|
+| `input_text: Full name` [tag: input] [attrs: {"name": "name"}] | `await page.fill(selector='input[name="name"]', value=context.parameters['full_name'], ai='fallback', prompt='Fill the full name field')` |
+| `input_text: Location` (autocomplete/typeahead) | `await page.fill_autocomplete(selector='label:has-text("Location") input', value=context.parameters['current_location'], ai='fallback', prompt='Fill the location')` |
+| `select_option: Location` [tag: select] [attrs: {"name": "location"}] | `await page.select_option(selector='select[name="location"]', ai='fallback', prompt='Select the first location option')` |
+| `click: Submit` [tag: button] [text: "Submit"] | `await page.click(selector='button:has-text("Submit")', ai='fallback', prompt='Click Submit')` |
+| `click: Gender option` (no tag/attrs) | `await page.click(ai='fallback', prompt='Select the first gender option')` |
+| `complete: ...` | `await page.complete()` |
+
+### Selector priority (most reliable first)
+1. `#id` — if the element has a stable `id` attribute (not auto-generated hex/numeric IDs)
+2. `[data-testid="..."]` — stable testing attribute
+3. `tag[aria-label="..."]` — accessibility attribute
+4. `tag[name="..."]` — form element name
+5. `tag[placeholder="..."]` — visible hint text
+6. `tag:has-text("...")` — visible text content (use for buttons/links)
+7. `label:has-text("...") input` — input nested inside a label element
+
+**Accumulating selectors across variants:** If the existing code has `selector='input[name="email"]'` and the new variant's agent action shows a field with `aria-label="Email address"`, update to: `selector='input[name="email"], input[aria-label="Email address"]'`
+
+**Mapping to code — check the Workflow Parameter Keys list FIRST:**
+- If the field maps to a known parameter key → use `value=context.parameters['key']` with `ai='fallback'`
+- If the navigation goal describes a deterministic condition for the value → write Python code to compute it (see "Deterministic Logic" section)
+- If the value requires subjective judgment or content generation → use `ai='proactive'` with a descriptive prompt, NO `value=` argument
+- Skip `complete` actions — add `await page.complete()` at the end of the function instead.
+
+### Fields with no matching workflow parameter (use `ai='proactive'`, NO `value=`)
+
+**Essay question (textarea):**
+```python
+await page.fill(
+ selector='label:has-text("Why are you interested?") textarea',
+ ai='proactive',
+ prompt='Write a brief, professional answer (2-3 sentences) about interest in this role and company',
+)
+```
+
+**Short factual field (dropdown, "how did you hear", etc.):**
+```python
+await page.select_option(
+ selector='label:has-text("How did you hear about this job?") select',
+ ai='proactive',
+ prompt='Select how you heard about this job posting',
+)
+```
+{% if stale_branches %}
+
+### Stale branch cleanup
+Remove `elif` branches for stale states listed above (keep the `else` branch).
+Remove corresponding entries from `options` and `text_patterns` in the `page.classify()` call.
+{% endif %}
+
+## Deterministic Logic — use Python code, NOT AI
+
+When the navigation goal describes conditional logic that can be evaluated with Python, **write it as code** instead of using `ai='proactive'`. Code is free (zero LLM calls), instant, and deterministic. Only use AI for decisions that require subjective judgment or visual understanding of the page.
+
+**Write as CODE** (deterministic — the answer can be computed):
+- Extracted page data drives the next action: "if application status is Approved, click Continue; if Denied, click Appeal"
+- Threshold / comparison: "if the cart total exceeds $500, apply the bulk discount code"
+- String matching: "if the product category contains 'Enterprise', select the annual plan"
+- Count-based: "if there are more than 20 results, paginate; otherwise extract all"
+- Presence checks: "if there is no 'State' field, skip to the next section"
+
+**Use AI** (`ai='proactive'`) (subjective — requires judgment):
+- Content generation: "write a professional cover letter paragraph"
+- Ambiguous choices: "pick the most relevant job category"
+- Visual understanding: "select the option that best matches the company logo"
+
+### How to implement deterministic branching
+
+Use `page.extract()` to pull data from the page, then branch with plain Python:
+
+```python
+# Extract structured data, then branch on it
+result = await page.extract(
+ prompt='What is the application status shown on this page?',
+ schema={'type': 'object', 'properties': {
+ 'status': {'type': 'string', 'enum': ['approved', 'denied', 'pending']}
+ }}
+)
+status = result.get('status', '')
+if status == 'approved':
+ await page.click(selector='button:has-text("Continue")', ai='fallback', prompt='Click Continue')
+elif status == 'denied':
+ await page.click(selector='button:has-text("Appeal")', ai='fallback', prompt='Click Appeal')
+else:
+ await page.element_fallback(navigation_goal="Handle the application outcome")
+```
+
+```python
+# Extract a number, compare against a threshold
+result = await page.extract(
+ prompt='What is the cart total amount in dollars?',
+ schema={'type': 'object', 'properties': {'total': {'type': 'number'}}}
+)
+if result.get('total', 0) > 500:
+ await page.fill(
+ selector='input[aria-label="Discount code"], label:has-text("Promo") input',
+ value='BULK500', ai='fallback', prompt='Enter the bulk discount code',
+ )
+```
+
+```python
+# Check current URL to decide what to do
+url = page.url
+if '/checkout/shipping' in url:
+ await page.fill(selector='label:has-text("Address") input', value=context.parameters['address'], ai='fallback', prompt='Fill shipping address')
+elif '/checkout/payment' in url:
+ await page.fill(selector='label:has-text("Card number") input', value=context.parameters['card_number'], ai='fallback', prompt='Fill card number')
+else:
+ await page.element_fallback(navigation_goal="Complete the current checkout step")
+```
+
+**Key principle:** `page.extract()` + Python `if/else` replaces `ai='proactive'` whenever the decision logic is spelled out in the navigation goal. Use `ai='fallback'` only on the **selector** (free when it resolves), never on the **value** when the value is computable.
+
+**Do NOT combine deterministic logic with `page.classify()` for the same condition.** If you use `page.extract()` + Python `if/else` to determine a value, that is the complete solution — adding a redundant `page.classify()` wastes an LLM call for something already computed. Use `page.classify()` only for page-variant disambiguation (layout differences), not for branching on extracted data.
+
+## When to use page.classify() — and when NOT to
+
+`page.classify()` costs an LLM call. Only use it when the page layout/state is genuinely unknown. **Do NOT use classify when:**
+
+1. **You just navigated to a known URL** — After `page.goto('https://...')`, you know what page you're on. Don't classify it.
+2. **The page state is deterministic from code** — If Python logic (URL check, time check, extracted data) already determines what to do, don't add a classify call.
+3. **There is only one possible page state** — A classify with a single option is pointless. Just write the code directly.
+
+**DO use classify when:**
+1. The page can genuinely be in multiple layout states (e.g., different website versions, A/B tests, logged-in vs logged-out).
+2. A previous action (search, form submission) may land on different result pages.
+
+**Rule of thumb:** If you can determine the page state from `page.url` or from data you already extracted, use Python `if/else` instead of classify.
+
+## Example: Before and After
+
+Before (xpaths duplicated across variant branches):
+```python
+async def block_fn(page, context):
+ state = await page.classify(
+ options={"variant_a": "standard form layout", "variant_b": "alternate form layout"},
+ text_patterns={"variant_a": "Apply Now", "variant_b": "Submit Application"},
+ )
+ if state == "variant_a":
+ await page.fill(selector='xpath=//div[1]/input[1]', value=context.parameters['full_name'])
+ await page.fill(selector='xpath=//div[2]/input[1]', value=context.parameters['email'])
+ await page.fill(selector='xpath=//div[3]/input[1]', value=context.parameters['phone'])
+ await page.select_option(selector='xpath=//div[4]/select[1]', value='Option A')
+ await page.click(selector='xpath=//button[@type="submit"]')
+ elif state == "variant_b":
+ await page.fill(selector='xpath=//form/input[@name="name"]', value=context.parameters['full_name'])
+ await page.fill(selector='xpath=//form/input[@name="email"]', value=context.parameters['email'])
+ await page.fill(selector='xpath=//form/input[@name="tel"]', value=context.parameters['phone'])
+ await page.click(selector='xpath=//form/button[1]')
+ else:
+ await page.element_fallback(navigation_goal="Fill out the application form")
+ await page.complete()
+```
+
+After (common fields with accumulative selectors above classify, only structural extras inside branches):
+```python
+async def block_fn(page, context):
+ # Common fields — selectors accumulate across variants (comma = OR)
+ await page.fill(
+ selector='label:has-text("Full name") input, label:has-text("Name") input',
+ value=context.parameters['full_name'],
+ ai='fallback', prompt='Fill the full name field',
+ )
+ await page.fill(
+ selector='label:has-text("Email") input',
+ value=context.parameters['email'],
+ ai='fallback', prompt='Fill the email field',
+ )
+ await page.fill(
+ selector='label:has-text("Phone") input',
+ value=context.parameters['phone'],
+ ai='fallback', prompt='Fill the phone number field',
+ )
+
+ # Only variant_a has a Location dropdown
+ state = await page.classify(
+ options={"has_location": "page has location dropdown", "no_location": "no location dropdown"},
+ url_patterns={"has_location": "example\\.com/form-a", "no_location": "example\\.com/form-b"},
+ text_patterns={"has_location": "Location", "no_location": "Submit Application"},
+ )
+ if state == "has_location":
+ await page.select_option(
+ selector='label:has-text("Location") select',
+ ai='fallback', prompt='Select the first location option',
+ )
+ elif state == "no_location":
+ pass
+ else:
+ await page.element_fallback(navigation_goal="Handle any extra fields on the form")
+
+ await page.click(
+ selector='button:has-text("Submit")', ai='fallback', prompt='Click the submit button',
+ )
+ await page.complete()
+```
+
+## Available Methods (COMPLETE API — do NOT invent methods not listed here)
+
+### Navigation
+- `await page.goto(url)` — Navigate to a URL
+- `await page.reload_page()` — Reload the current page
+
+### Interaction
+- `await page.click(selector=, ai=, prompt=)` — Click an element
+- `await page.hover(selector=, ai=, prompt=)` — Hover over an element
+- `await page.fill(selector=, value=, ai=, prompt=)` — Fill a text input
+- `await page.fill_autocomplete(selector=, value=, ai=, prompt=)` — Fill an autocomplete/typeahead input (see below)
+- `await page.select_option(selector=, value=, ai=, prompt=)` — Select a dropdown option
+- `await page.upload_file(selector=, files=, ai=, prompt=)` — Upload a file
+- `await page.scroll(direction=)` — Scroll the page
+- `await page.keypress(key=)` — Press a keyboard key
+
+### Data Extraction & Classification
+- `await page.extract(prompt="...", schema={...})` — Extract structured data (returns dict)
+- `await page.validate(prompt="...")` — Validate a condition on the page
+- `await page.classify(options={...}, url_patterns={...}, text_patterns={...})` — Classify page state
+
+### Lifecycle
+- `await page.complete()` — Mark the task as complete (call at the end)
+- `await page.wait(timeout_ms=)` — Wait for a duration
+- `await page.solve_captcha()` — Solve a CAPTCHA on the page
+
+### AI Fallback
+- `await page.element_fallback(navigation_goal="...", max_steps=10)` — Hand off to AI agent
+
+### Properties
+- `page.url` — Current page URL (str property, free, no LLM call)
+
+### DO NOT USE (these do NOT exist and will crash at runtime)
+- ~~`page.completed`~~ — Does NOT exist. Use `await page.complete()` to finish.
+- ~~`page.current_url`~~ — Does NOT exist. Use `page.url` instead.
+- ~~`page.navigate()`~~ — Does NOT exist. Use `await page.goto(url)`.
+- ~~`page.text`~~ / ~~`page.content`~~ / ~~`page.title`~~ — Do NOT exist. Use `await page.extract()` to read page data.
+- ~~`page.get_url()`~~ — Does NOT exist. Use `page.url`.
+
+### Selector Patterns & AI Modes
+- Use `ai='fallback'` with `selector=` and `prompt=` — selector is tried first (free), AI only if all selectors miss
+- Selector patterns: `label:has-text("LABEL") input`, `label:has-text("LABEL") select`, `button:has-text("TEXT")`
+- Comma-separated selectors act as OR: `'selector-A, selector-B'` — first match wins
+- `:has-text()` is a case-insensitive substring match
+- **Python stdlib** — You can `import` any standard library module (`re`, `datetime`, `json`, `math`, etc.). Place imports at the top of your output, before the function definition.
+
+### CSS Selector Syntax — CRITICAL
+A **space** between two selectors is a **descendant combinator** (child inside parent) — NOT "or".
+A **comma** between two selectors means **"or"** (try both, first match wins).
+
+| Syntax | Meaning | Example |
+|--------|---------|---------|
+| `A, B` | **OR** — match A or B | `button:has-text("Search"), input[type="submit"]` |
+| `A B` | **DESCENDANT** — B inside A | `label:has-text("Name") input` (input inside a label) |
+
+**Common mistake** (WRONG — means "input inside a button", matches nothing):
+```
+button:has-text("Search") input[type="submit"]
+```
+**Correct** (OR — tries button first, then input):
+```
+button:has-text("Search"), input[type="submit"]
+```
+
+The ONLY valid use of space-separated selectors is the `label:has-text("...") input` pattern where the input is genuinely a child of the label element. **Never combine two independent elements with a space.**
+
+### Selector Specificity
+Avoid overly generic selectors on content-heavy pages:
+- **Too generic**: `a:has-text("Lepton")` — may match multiple links (e.g., sidebar, footer, related articles)
+- **Better**: `#search-results a:has-text("Lepton")`, or use a more specific parent: `table a:has-text("Lepton")`
+- If you cannot determine a unique parent, use `ai='fallback'` with a descriptive `prompt=` that disambiguates (e.g., "Click the first search result link for Lepton")
+
+### Autocomplete / Typeahead Fields
+Use `page.fill_autocomplete()` instead of `page.fill()` for inputs where typing triggers a dropdown and the user must select an option (e.g., Google Places location autocomplete, city/address pickers, company name typeaheads). Signs of an autocomplete field:
+- The agent actions show the agent typed a value but it didn't persist, or the agent got stuck retrying
+- The field is labeled "Location", "City", "Address", or similar
+- The page text or form fields mention autocomplete behavior
+
+```python
+# Autocomplete with a known parameter value
+await page.fill_autocomplete(
+ selector='label:has-text("Current location") input',
+ value=context.parameters['current_location'],
+ ai='fallback',
+ prompt='Fill the current location of the applicant',
+)
+
+# Autocomplete where AI generates the value
+await page.fill_autocomplete(
+ selector='label:has-text("City") input',
+ ai='proactive',
+ prompt='Fill the city where the applicant is based',
+)
+```
+
+`fill_autocomplete()` has the same signature as `fill()` plus an optional `option_selector` parameter if the dropdown uses non-standard markup. It types character-by-character, waits for the dropdown, and clicks the best matching option automatically.
+
+## Output
+Return a JSON object with a single key `"code"` containing the complete updated function as a string.
+The function must start with `{{ function_signature }}` and contain the updated implementation.
+Use `\n` for newlines inside the string value. Example:
+
+```json
+{"code": "{{ function_signature }}\n # Your updated code here\n await page.complete()"}
+```
diff --git a/skyvern/forge/prompts/skyvern/select-from-group.j2 b/skyvern/forge/prompts/skyvern/select-from-group.j2
new file mode 100644
index 000000000..f3d4419b8
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/select-from-group.j2
@@ -0,0 +1,29 @@
+Given this form field and context, which option(s) should be selected?
+
+Field label: {{ label }}
+Field type: {{ field_type }}
+
+Options:
+{% for opt in options %}
+{{ loop.index }}. {{ opt }}
+{% endfor %}
+
+{% if data %}
+Applicant Data:
+{% if data is mapping %}
+{% for key, value in data.items() %}
+- {{ key }}: {{ value }}
+{% endfor %}
+{% else %}
+{{ data }}
+{% endif %}
+{% endif %}
+
+{% if goal %}
+Navigation Goal: {{ goal }}
+{% endif %}
+
+Return ONLY a JSON object: {"selected": [1]} for single choice, {"selected": [1, 3]} for multi-select.
+Use 1-based indices matching the option numbers above.
+For radio buttons (single choice), return exactly one index.
+For checkboxes (multi-select), return one or more indices.