Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix: resolve 3 CodeQL alerts in extract_form_fields.js (#5198)
Shuchang Zheng236c6cb37759
diff --git a/fern/openapi/skyvern_openapi.json b/fern/openapi/skyvern_openapi.jsonindex 55baa62a9..8cd60deb0 100644--- a/fern/openapi/skyvern_openapi.json+++ b/fern/openapi/skyvern_openapi.json@@ -3833,6 +3833,292 @@}}},+ "/v1/sdk/run_action": {+ "post": {+ "tags": [+ "SDK"+ ],+ "summary": "Run an SDK action",+ "description": "Execute a single SDK action with the specified parameters",+ "operationId": "run_sdk_action_v1_sdk_run_action_post",+ "parameters": [+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RunSdkActionRequest"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RunSdkActionResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "x-fern-sdk-method-name": "run_sdk_action"+ }+ },+ "/api/v1/billing/checkout": {+ "post": {+ "summary": "Create Checkout Session",+ "description": "Create a Stripe Checkout Session for subscribing to a tier.\n\nFrontend should redirect the user to the returned URL.\nAfter successful checkout, Stripe will send a webhook that we handle\nto store the subscription and initialize billing state.\n\nReturns 400 if org already has an active subscription (use portal instead).",+ "operationId": "create_checkout_session_api_v1_billing_checkout_post",+ "parameters": [+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CheckoutSubscriptionRequest"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CheckoutSessionResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/billing/portal": {+ "post": {+ "summary": "Create Portal Session",+ "description": "Create a Stripe Customer Portal session for managing subscription.\n\nFrontend should redirect the user to the returned URL.\nThe portal allows users to:\n- Update payment methods\n- Upgrade/downgrade plans\n- Cancel subscription\n- View invoices",+ "operationId": "create_portal_session_api_v1_billing_portal_post",+ "parameters": [+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PortalSessionResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/billing/state": {+ "get": {+ "summary": "Get Organization Billing",+ "operationId": "get_organization_billing_api_v1_billing_state_get",+ "parameters": [+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/BillingStateResponse"+ },+ {+ "type": "null"+ }+ ],+ "title": "Response Get Organization Billing Api V1 Billing State Get"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/billing/change-tier": {+ "post": {+ "summary": "Change Tier",+ "description": "Redirect to Stripe Portal for tier changes.\nPortal handles proration based on configured settings:\n- Upgrades: Immediate proration charge\n- Downgrades: Apply at end of billing period",+ "operationId": "change_tier_api_v1_billing_change_tier_post",+ "parameters": [+ {+ "name": "x-api-key",+ "in": "header",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",+ "title": "X-Api-Key"+ },+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChangeTierRequest"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChangeTierResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },"/api/v1/schedules": {"get": {"tags": [@@ -4537,6 +4823,41 @@],"title": "AWSSecretParameterYAML"},+ "ActAction": {+ "properties": {+ "type": {+ "type": "string",+ "const": "ai_act",+ "title": "Type",+ "default": "ai_act"+ },+ "intention": {+ "type": "string",+ "title": "Intention",+ "description": "Natural language prompt for the action",+ "default": ""+ },+ "data": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "title": "Data",+ "description": "Additional context data"+ }+ },+ "type": "object",+ "title": "ActAction",+ "description": "AI act action parameters."+ },"Action": {"properties": {"action_type": {@@ -5877,7 +6198,117 @@"username_key","password_key"],- "title": "AzureVaultCredentialParameterYAML"+ "title": "AzureVaultCredentialParameterYAML"+ },+ "BillingStateResponse": {+ "properties": {+ "billing_id": {+ "type": "string",+ "title": "Billing Id"+ },+ "organization_id": {+ "type": "string",+ "title": "Organization Id"+ },+ "plan_tier": {+ "$ref": "#/components/schemas/PlanTier"+ },+ "current_period_start": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "Current Period Start"+ },+ "current_period_end": {+ "anyOf": [+ {+ "type": "string",+ "format": "date-time"+ },+ {+ "type": "null"+ }+ ],+ "title": "Current Period End"+ },+ "included_credits_this_period": {+ "type": "integer",+ "title": "Included Credits This Period"+ },+ "credits_consumed_this_period": {+ "type": "integer",+ "title": "Credits Consumed This Period"+ },+ "cached_credits_consumed_this_period": {+ "type": "integer",+ "title": "Cached Credits Consumed This Period"+ },+ "overage_enabled": {+ "type": "boolean",+ "title": "Overage Enabled"+ },+ "browser_uptime_seconds_consumed": {+ "type": "integer",+ "title": "Browser Uptime Seconds Consumed"+ },+ "topup_credits_total": {+ "type": "integer",+ "title": "Topup Credits Total"+ },+ "topup_credits_used": {+ "type": "integer",+ "title": "Topup Credits Used"+ },+ "topup_credits_remaining": {+ "type": "integer",+ "title": "Topup Credits Remaining"+ },+ "credits_remaining": {+ "type": "integer",+ "title": "Credits Remaining"+ },+ "cancel_at_period_end": {+ "type": "boolean",+ "title": "Cancel At Period End",+ "default": false+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "title": "Created At"+ },+ "modified_at": {+ "type": "string",+ "format": "date-time",+ "title": "Modified At"+ }+ },+ "type": "object",+ "required": [+ "billing_id",+ "organization_id",+ "plan_tier",+ "current_period_start",+ "current_period_end",+ "included_credits_this_period",+ "credits_consumed_this_period",+ "cached_credits_consumed_this_period",+ "overage_enabled",+ "browser_uptime_seconds_consumed",+ "topup_credits_total",+ "topup_credits_used",+ "topup_credits_remaining",+ "credits_remaining",+ "created_at",+ "modified_at"+ ],+ "title": "BillingStateResponse"},"BitwardenCreditCardDataParameter": {"properties": {@@ -6875,6 +7306,131 @@"title": "BrowserSessionResponse","description": "Response model for browser session information."},+ "ChangeTierRequest": {+ "properties": {+ "tier": {+ "$ref": "#/components/schemas/PlanTier"+ }+ },+ "type": "object",+ "required": [+ "tier"+ ],+ "title": "ChangeTierRequest"+ },+ "ChangeTierResponse": {+ "properties": {+ "status": {+ "type": "string",+ "title": "Status"+ },+ "tier": {+ "type": "string",+ "title": "Tier"+ },+ "redirect_url": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Redirect Url"+ }+ },+ "type": "object",+ "required": [+ "status",+ "tier"+ ],+ "title": "ChangeTierResponse"+ },+ "CheckoutSessionResponse": {+ "properties": {+ "id": {+ "type": "string",+ "title": "Id"+ },+ "url": {+ "type": "string",+ "title": "Url"+ }+ },+ "type": "object",+ "required": [+ "id",+ "url"+ ],+ "title": "CheckoutSessionResponse"+ },+ "CheckoutSubscriptionRequest": {+ "properties": {+ "tier": {+ "$ref": "#/components/schemas/PlanTier"+ }+ },+ "type": "object",+ "required": [+ "tier"+ ],+ "title": "CheckoutSubscriptionRequest"+ },+ "ClickAction": {+ "properties": {+ "type": {+ "type": "string",+ "const": "ai_click",+ "title": "Type",+ "default": "ai_click"+ },+ "selector": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Selector",+ "description": "CSS selector for the element",+ "default": ""+ },+ "intention": {+ "type": "string",+ "title": "Intention",+ "description": "The intention or goal of the click",+ "default": ""+ },+ "data": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "title": "Data",+ "description": "Additional context data"+ },+ "timeout": {+ "type": "number",+ "title": "Timeout",+ "description": "Timeout in milliseconds",+ "default": 10000+ }+ },+ "type": "object",+ "title": "ClickAction",+ "description": "Click action parameters."+ },"ClickContext": {"properties": {"thought": {@@ -8216,6 +8772,88 @@],"title": "Extensions"},+ "ExtractAction": {+ "properties": {+ "type": {+ "type": "string",+ "const": "extract",+ "title": "Type",+ "default": "extract"+ },+ "prompt": {+ "type": "string",+ "title": "Prompt",+ "description": "Extraction prompt",+ "default": ""+ },+ "extract_schema": {+ "anyOf": [+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "items": {},+ "type": "array"+ },+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Extract Schema",+ "description": "Schema for extraction"+ },+ "error_code_mapping": {+ "anyOf": [+ {+ "additionalProperties": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "title": "Error Code Mapping",+ "description": "Error code mapping for extraction"+ },+ "intention": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Intention",+ "description": "The intention or goal of the extraction"+ },+ "data": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "title": "Data",+ "description": "Additional context data"+ }+ },+ "type": "object",+ "title": "ExtractAction",+ "description": "Extract data action parameters."+ },"ExtractionBlock": {"properties": {"label": {@@ -11250,6 +11888,97 @@"type": "object","title": "InputOrSelectContext"},+ "InputTextAction": {+ "properties": {+ "type": {+ "type": "string",+ "const": "ai_input_text",+ "title": "Type",+ "default": "ai_input_text"+ },+ "selector": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Selector",+ "description": "CSS selector for the element",+ "default": ""+ },+ "value": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Value",+ "description": "Value to input",+ "default": ""+ },+ "intention": {+ "type": "string",+ "title": "Intention",+ "description": "The intention or goal of the input",+ "default": ""+ },+ "data": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "title": "Data",+ "description": "Additional context data"+ },+ "totp_identifier": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Totp Identifier",+ "description": "TOTP identifier for input_text actions"+ },+ "totp_url": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Totp Url",+ "description": "TOTP URL for input_text actions"+ },+ "timeout": {+ "type": "number",+ "title": "Timeout",+ "description": "Timeout in milliseconds",+ "default": 10000+ }+ },+ "type": "object",+ "title": "InputTextAction",+ "description": "Input text action parameters."+ },"JinjaBranchCriteria": {"properties": {"criteria_type": {@@ -11281,6 +12010,25 @@"title": "JinjaBranchCriteria","description": "Jinja2-templated branch criteria (only supported criteria type for now)."},+ "LocateElementAction": {+ "properties": {+ "type": {+ "type": "string",+ "const": "locate_element",+ "title": "Type",+ "default": "locate_element"+ },+ "prompt": {+ "type": "string",+ "title": "Prompt",+ "description": "Natural language prompt to locate an element",+ "default": ""+ }+ },+ "type": "object",+ "title": "LocateElementAction",+ "description": "Locate element action parameters."+ },"LoginBlock": {"properties": {"label": {@@ -13213,7 +13961,31 @@"chrome","stealth-chromium"],- "title": "PersistentBrowserType"+ "title": "PersistentBrowserType"+ },+ "PlanTier": {+ "type": "string",+ "enum": [+ "free",+ "hobby",+ "pro",+ "enterprise"+ ],+ "title": "PlanTier",+ "description": "Self-serve subscription tiers. Enterprise customers use manual billing (bypass)."+ },+ "PortalSessionResponse": {+ "properties": {+ "url": {+ "type": "string",+ "title": "Url"+ }+ },+ "type": "object",+ "required": [+ "url"+ ],+ "title": "PortalSessionResponse"},"PrintPageBlock": {"properties": {@@ -13465,6 +14237,53 @@],"title": "PrintPageBlockYAML"},+ "PromptAction": {+ "properties": {+ "type": {+ "type": "string",+ "const": "prompt",+ "title": "Type",+ "default": "prompt"+ },+ "prompt": {+ "type": "string",+ "title": "Prompt",+ "description": "The prompt to send to the LLM"+ },+ "response_schema": {+ "anyOf": [+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "title": "Response Schema",+ "description": "Optional JSON schema to structure the response"+ },+ "model": {+ "anyOf": [+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "title": "Model",+ "description": "Optional model configuration"+ }+ },+ "type": "object",+ "required": [+ "prompt"+ ],+ "title": "PromptAction",+ "description": "Prompt action parameters."+ },"PromptBranchCriteria": {"properties": {"criteria_type": {@@ -13558,6 +14377,130 @@],"title": "RunEngine"},+ "RunSdkActionRequest": {+ "properties": {+ "url": {+ "type": "string",+ "title": "Url",+ "description": "The URL where the action should be executed"+ },+ "browser_session_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Browser Session Id",+ "description": "The browser session ID"+ },+ "browser_address": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Browser Address",+ "description": "The browser address"+ },+ "workflow_run_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Workflow Run Id",+ "description": "Optional workflow run ID to continue an existing workflow run"+ },+ "action": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/ClickAction"+ },+ {+ "$ref": "#/components/schemas/InputTextAction"+ },+ {+ "$ref": "#/components/schemas/SelectOptionAction"+ },+ {+ "$ref": "#/components/schemas/UploadFileAction"+ },+ {+ "$ref": "#/components/schemas/ActAction"+ },+ {+ "$ref": "#/components/schemas/ExtractAction"+ },+ {+ "$ref": "#/components/schemas/LocateElementAction"+ },+ {+ "$ref": "#/components/schemas/ValidateAction"+ },+ {+ "$ref": "#/components/schemas/PromptAction"+ }+ ],+ "title": "Action",+ "description": "The action to execute with its specific parameters",+ "discriminator": {+ "propertyName": "type",+ "mapping": {+ "ai_act": "#/components/schemas/ActAction",+ "ai_click": "#/components/schemas/ClickAction",+ "ai_input_text": "#/components/schemas/InputTextAction",+ "ai_select_option": "#/components/schemas/SelectOptionAction",+ "ai_upload_file": "#/components/schemas/UploadFileAction",+ "extract": "#/components/schemas/ExtractAction",+ "locate_element": "#/components/schemas/LocateElementAction",+ "prompt": "#/components/schemas/PromptAction",+ "validate": "#/components/schemas/ValidateAction"+ }+ }+ }+ },+ "type": "object",+ "required": [+ "url",+ "action"+ ],+ "title": "RunSdkActionRequest",+ "description": "Request to run a single SDK action."+ },+ "RunSdkActionResponse": {+ "properties": {+ "workflow_run_id": {+ "type": "string",+ "title": "Workflow Run Id",+ "description": "The workflow run ID used for this action"+ },+ "result": {+ "anyOf": [+ {},+ {+ "type": "null"+ }+ ],+ "title": "Result",+ "description": "The result from the action (e.g., selector, value, extracted data)"+ }+ },+ "type": "object",+ "required": [+ "workflow_run_id"+ ],+ "title": "RunSdkActionResponse",+ "description": "Response from running an SDK action."+ },"RunStatus": {"type": "string","enum": [@@ -13784,6 +14727,73 @@"type": "object","title": "SelectOption"},+ "SelectOptionAction": {+ "properties": {+ "type": {+ "type": "string",+ "const": "ai_select_option",+ "title": "Type",+ "default": "ai_select_option"+ },+ "selector": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Selector",+ "description": "CSS selector for the element",+ "default": ""+ },+ "value": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Value",+ "description": "Value to select",+ "default": ""+ },+ "intention": {+ "type": "string",+ "title": "Intention",+ "description": "The intention or goal of the selection",+ "default": ""+ },+ "data": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "title": "Data",+ "description": "Additional context data"+ },+ "timeout": {+ "type": "number",+ "title": "Timeout",+ "description": "Timeout in milliseconds",+ "default": 10000+ }+ },+ "type": "object",+ "title": "SelectOptionAction",+ "description": "Select option action parameters."+ },"SendEmailBlock": {"properties": {"label": {@@ -16129,6 +17139,73 @@"title": "UpdateWorkflowFolderRequest","description": "Request model for updating a workflow's folder assignment"},+ "UploadFileAction": {+ "properties": {+ "type": {+ "type": "string",+ "const": "ai_upload_file",+ "title": "Type",+ "default": "ai_upload_file"+ },+ "selector": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Selector",+ "description": "CSS selector for the element",+ "default": ""+ },+ "file_url": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "File Url",+ "description": "File URL for upload",+ "default": ""+ },+ "intention": {+ "type": "string",+ "title": "Intention",+ "description": "The intention or goal of the upload",+ "default": ""+ },+ "data": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "title": "Data",+ "description": "Additional context data"+ },+ "timeout": {+ "type": "number",+ "title": "Timeout",+ "description": "Timeout in milliseconds",+ "default": 10000+ }+ },+ "type": "object",+ "title": "UploadFileAction",+ "description": "Upload file action parameters."+ },"UploadFileResponse": {"properties": {"s3_uri": {@@ -16664,6 +17741,40 @@],"title": "UserDefinedError"},+ "ValidateAction": {+ "properties": {+ "type": {+ "type": "string",+ "const": "validate",+ "title": "Type",+ "default": "validate"+ },+ "prompt": {+ "type": "string",+ "title": "Prompt",+ "description": "Validation criteria or condition to check"+ },+ "model": {+ "anyOf": [+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "title": "Model",+ "description": "Optional model configuration"+ }+ },+ "type": "object",+ "required": [+ "prompt"+ ],+ "title": "ValidateAction",+ "description": "Validate action parameters."+ },"ValidationBlock": {"properties": {"label": {diff --git a/skyvern-frontend/src/api/types.ts b/skyvern-frontend/src/api/types.tsindex bc3c1a279..3ab529286 100644--- a/skyvern-frontend/src/api/types.ts+++ b/skyvern-frontend/src/api/types.ts@@ -254,6 +254,33 @@ export interface AzureClientSecretCredentialResponse {token: AzureOrganizationAuthToken;}+export interface BitwardenCredential {+ email: string;+ master_password: string;+}++export interface BitwardenCredentialSafe {+ email: string;+}++export interface BitwardenOrganizationAuthToken {+ id: string;+ organization_id: string;+ credential: BitwardenCredentialSafe;+ created_at: string;+ modified_at: string;+ token_type: string;+ valid: boolean;+}++export interface CreateBitwardenCredentialRequest {+ credential: BitwardenCredential;+}++export interface BitwardenCredentialResponse {+ token: BitwardenOrganizationAuthToken;+}+export interface CustomCredentialServiceConfig {api_base_url: string;api_token: string;diff --git a/skyvern-frontend/src/components/BitwardenCredentialForm.tsx b/skyvern-frontend/src/components/BitwardenCredentialForm.tsxnew file mode 100644index 000000000..81d6902a6--- /dev/null+++ b/skyvern-frontend/src/components/BitwardenCredentialForm.tsx@@ -0,0 +1,188 @@+import { useEffect, useState } from "react";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import * as z from "zod";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/components/ui/form";+import { useBitwardenCredential } from "@/hooks/useBitwardenCredential";+import { EyeOpenIcon, EyeClosedIcon } from "@radix-ui/react-icons";++const BitwardenCredentialSchema = z+ .object({+ email: z+ .string()+ .min(1, "Email is required")+ .email("Must be a valid email"),+ master_password: z.string().min(1, "Master password is required"),+ })+ .strict();++const formSchema = z+ .object({+ credential: BitwardenCredentialSchema,+ })+ .strict();++type FormData = z.infer<typeof formSchema>;++export function BitwardenCredentialForm() {+ const [showMasterPassword, setShowMasterPassword] = useState(false);+ const {+ bitwardenOrganizationAuthToken,+ isLoading,+ createOrUpdateToken,+ isUpdating,+ } = useBitwardenCredential();++ const form = useForm<FormData>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ credential: {+ email: bitwardenOrganizationAuthToken?.credential?.email || "",+ master_password: "",+ },+ },+ });++ const onSubmit = (data: FormData) => {+ createOrUpdateToken(data);+ };++ useEffect(() => {+ if (bitwardenOrganizationAuthToken?.credential) {+ form.reset({+ credential: {+ email: bitwardenOrganizationAuthToken.credential.email,+ master_password: "",+ },+ });+ }+ }, [bitwardenOrganizationAuthToken, form]);++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <div>+ <h3 className="text-lg font-medium">Bitwarden Credential</h3>+ <p className="text-sm text-muted-foreground">+ Configure your Bitwarden credentials to give access to your+ Bitwarden vault.+ </p>+ </div>+ {bitwardenOrganizationAuthToken && (+ <div className="flex items-center gap-2">+ <span className="text-sm text-muted-foreground">Status:</span>+ <span+ className={`text-sm ${bitwardenOrganizationAuthToken.valid ? "text-green-600" : "text-red-600"}`}+ >+ {bitwardenOrganizationAuthToken.valid ? "Active" : "Inactive"}+ </span>+ </div>+ )}+ </div>++ <Form {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">+ <FormField+ control={form.control}+ name="credential.email"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Email</FormLabel>+ <div className="relative">+ <FormControl>+ <Input+ {...field}+ type="email"+ placeholder="[email protected]"+ disabled={isLoading || isUpdating}+ />+ </FormControl>+ </div>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="credential.master_password"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Master Password</FormLabel>+ <div className="relative">+ <FormControl>+ <Input+ {...field}+ type={showMasterPassword ? "text" : "password"}+ placeholder="master_password"+ disabled={isLoading || isUpdating}+ />+ </FormControl>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"+ onClick={() => setShowMasterPassword((v) => !v)}+ disabled={isLoading || isUpdating}+ >+ {showMasterPassword ? (+ <EyeClosedIcon className="h-4 w-4" />+ ) : (+ <EyeOpenIcon className="h-4 w-4" />+ )}+ </Button>+ </div>+ <FormMessage />+ {bitwardenOrganizationAuthToken && (+ <p className="text-xs text-muted-foreground">+ Master password is not displayed for security. Enter it+ again to update your credential.+ </p>+ )}+ </FormItem>+ )}+ />++ <div className="flex items-center gap-4">+ <Button type="submit" disabled={isLoading || isUpdating}>+ {isUpdating ? "Updating..." : "Update Credential"}+ </Button>+ {bitwardenOrganizationAuthToken && (+ <div className="text-sm text-muted-foreground">+ Last updated:{" "}+ {new Date(+ bitwardenOrganizationAuthToken.modified_at,+ ).toLocaleDateString()}+ </div>+ )}+ </div>+ </form>+ </Form>++ {bitwardenOrganizationAuthToken && (+ <div className="rounded-md bg-muted p-4">+ <h4 className="mb-2 text-sm font-medium">Credential Information</h4>+ <div className="space-y-1 text-sm text-muted-foreground">+ <div>ID: {bitwardenOrganizationAuthToken.id}</div>+ <div>Type: {bitwardenOrganizationAuthToken.token_type}</div>+ <div>+ Created:{" "}+ {new Date(+ bitwardenOrganizationAuthToken.created_at,+ ).toLocaleDateString()}+ </div>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/skyvern-frontend/src/hooks/useBitwardenCredential.ts b/skyvern-frontend/src/hooks/useBitwardenCredential.tsnew file mode 100644index 000000000..4aeb0da67--- /dev/null+++ b/skyvern-frontend/src/hooks/useBitwardenCredential.ts@@ -0,0 +1,69 @@+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { getClient } from "@/api/AxiosClient";+import { useCredentialGetter } from "./useCredentialGetter";+import {+ BitwardenCredentialResponse,+ BitwardenOrganizationAuthToken,+ CreateBitwardenCredentialRequest,+} from "@/api/types";+import { useToast } from "@/components/ui/use-toast";++export function useBitwardenCredential() {+ const credentialGetter = useCredentialGetter();+ const queryClient = useQueryClient();+ const { toast } = useToast();++ const { data: bitwardenOrganizationAuthToken, isLoading } =+ useQuery<BitwardenOrganizationAuthToken>({+ queryKey: ["bitwardenOrganizationAuthToken"],+ queryFn: async () => {+ const client = await getClient(credentialGetter, "sans-api-v1");+ return await client+ .get("/credentials/bitwarden/get")+ .then((response) => response.data.token)+ .catch((error: unknown) => {+ const status = (error as { response?: { status?: number } })+ ?.response?.status;+ if (status === 404) return null;+ throw error;+ });+ },+ });++ const createOrUpdateTokenMutation = useMutation({+ mutationFn: async (data: CreateBitwardenCredentialRequest) => {+ const client = await getClient(credentialGetter, "sans-api-v1");+ return await client+ .post("/credentials/bitwarden/create", data)+ .then((response) => response.data as BitwardenCredentialResponse);+ },+ onSuccess: () => {+ queryClient.invalidateQueries({+ queryKey: ["bitwardenOrganizationAuthToken"],+ });+ toast({+ title: "Success",+ description: "Bitwarden credential updated successfully",+ });+ },+ onError: (error: unknown) => {+ const message =+ (error as { response?: { data?: { detail?: string } } })?.response?.data+ ?.detail ||+ (error as Error)?.message ||+ "Failed to update Bitwarden credential";+ toast({+ title: "Error",+ description: message,+ variant: "destructive",+ });+ },+ });++ return {+ bitwardenOrganizationAuthToken,+ isLoading,+ createOrUpdateToken: createOrUpdateTokenMutation.mutate,+ isUpdating: createOrUpdateTokenMutation.isPending,+ };+}diff --git a/skyvern-frontend/src/routes/settings/Settings.tsx b/skyvern-frontend/src/routes/settings/Settings.tsxindex 6cb16190d..e75b0190c 100644--- a/skyvern-frontend/src/routes/settings/Settings.tsx+++ b/skyvern-frontend/src/routes/settings/Settings.tsx@@ -17,6 +17,7 @@ import {import { getRuntimeApiKey } from "@/util/env";import { HiddenCopyableInput } from "@/components/ui/hidden-copyable-input";import { OnePasswordTokenForm } from "@/components/OnePasswordTokenForm";+import { BitwardenCredentialForm } from "@/components/BitwardenCredentialForm";import { AzureClientSecretCredentialTokenForm } from "@/components/AzureClientSecretCredentialTokenForm";import { CustomCredentialServiceConfigForm } from "@/components/CustomCredentialServiceConfigForm";import { useVersionQuery } from "@/hooks/useVersionQuery";@@ -92,6 +93,18 @@ function Settings() {<OnePasswordTokenForm /></CardContent></Card>+ <Card>+ <CardHeader className="border-b-2">+ <CardTitle className="text-lg">Bitwarden Integration</CardTitle>+ <CardDescription>+ Configure your Bitwarden account credentials to use your own vault+ for credential management.+ </CardDescription>+ </CardHeader>+ <CardContent className="p-8">+ <BitwardenCredentialForm />+ </CardContent>+ </Card><Card><CardHeader className="border-b-2"><CardTitle className="text-lg">Azure Integration</CardTitle>diff --git a/skyvern/cli/quickstart.py b/skyvern/cli/quickstart.pyindex 7a90d0eb2..4b4d4e321 100644--- a/skyvern/cli/quickstart.py+++ b/skyvern/cli/quickstart.py@@ -159,23 +159,6 @@ def quickstart(docker_compose: bool = typer.Option(False, "--docker-compose", help="Use Docker Compose for full setup"),) -> None:"""Quickstart command to set up and run Skyvern with one command."""- # Check Docker- with console.status("Checking Docker installation...") as status:- docker_available = check_docker()- if docker_available:- status.update("✅ Docker is installed and running")- else:- if not database_string:- console.print(- Panel(- "[bold red]Docker is not installed or not running.[/bold red]\n"- "Please install Docker and start it before running quickstart.\n"- "Get Docker from: [link]https://www.docker.com/get-started[/link]",- border_style="red",- )- )- raise typer.Exit(1)-# Run initializationconsole.print(Panel("[bold green]🚀 Starting Skyvern Quickstart[/bold green]", border_style="green"))@@ -183,6 +166,16 @@ def quickstart(docker_compose_available = check_docker_compose_file()if docker_compose:+ if not check_docker():+ console.print(+ Panel(+ "[bold red]Docker is not installed or not running.[/bold red]\n"+ "Docker Compose requires Docker to be running.\n"+ "Get Docker from: [link]https://www.docker.com/get-started[/link]",+ border_style="red",+ )+ )+ raise typer.Exit(1)if not docker_compose_available:console.print(Panel(@@ -197,7 +190,7 @@ def quickstart(return# If Docker Compose file exists, offer the choice- if docker_compose_available and docker_available and not database_string:+ if docker_compose_available and check_docker() and not database_string:console.print("\n[bold blue]Setup Method[/bold blue]")console.print("Docker Compose file detected. Choose your setup method:\n")console.print(" [cyan]1.[/cyan] [green]Docker Compose (Recommended)[/green] - Full containerized setup")diff --git a/skyvern/core/script_generations/canonical_fields.py b/skyvern/core/script_generations/canonical_fields.pydeleted file mode 100644index 630141611..000000000--- a/skyvern/core/script_generations/canonical_fields.py+++ /dev/null@@ -1,317 +0,0 @@-"""Canonical form field categories for keyword-based matching.--Instead of growing FIELD_MAP with every label variant, this module defines-~20 canonical categories with keyword lists. ``match_field_to_category``-scores a page field label against all categories and returns the best match-(or ``None``).-"""--from __future__ import annotations--import re-from dataclasses import dataclass, field--# Stop words stripped during normalization-_STOP_WORDS = frozenset(- {- "the",- "a",- "an",- "your",- "you",- "please",- "enter",- "provide",- "what",- "is",- "are",- "do",- "does",- "of",- "for",- "to",- "in",- "on",- "at",- "by",- "with",- "this",- "that",- "us",- "our",- "we",- "my",- "me",- "i",- }-)--_NON_ALPHA = re.compile(r"[^a-z0-9\s]")---def _normalize(text: str) -> str:- """Lowercase, strip punctuation, remove stop words.-- Hyphens are replaced with spaces (so "e-mail" → "e mail") while other- punctuation is removed entirely (so "what's" → "whats").- """- text = text.lower().replace("-", " ")- text = _NON_ALPHA.sub("", text)- return " ".join(w for w in text.split() if w not in _STOP_WORDS)---@dataclass(frozen=True)-class CanonicalCategory:- name: str- keywords: frozenset[str]- negative_keywords: frozenset[str] = field(default_factory=frozenset)- param: str | None = None- action: str = "fill"- prompt: str = ""- # Maps semantic intent (e.g. "no") to common option label substrings.- # Used by _resolve_fallback_value to match planner output like "No" to- # actual option text like "I am not a protected veteran".- value_mappings: tuple[tuple[str, tuple[str, ...]], ...] = ()---# ----------------------------------------------------------------------------# Category registry-# -----------------------------------------------------------------------------CANONICAL_CATEGORIES: list[CanonicalCategory] = [- CanonicalCategory(- name="full_name",- keywords=frozenset({"full name", "name"}),- negative_keywords=frozenset(- {- "company",- "employer",- "school",- "university",- "linkedin",- "user",- "login",- "first",- "last",- "surname",- "family",- }- ),- param="full_name",- action="fill",- prompt="Fill the applicant's full name",- ),- CanonicalCategory(- name="first_name",- keywords=frozenset({"first name"}),- negative_keywords=frozenset({"company", "employer"}),- param="first_name",- action="fill",- prompt="Fill the applicant's first name",- ),- CanonicalCategory(- name="last_name",- keywords=frozenset({"last name", "surname", "family name"}),- negative_keywords=frozenset({"company", "employer"}),- param="last_name",- action="fill",- prompt="Fill the applicant's last name",- ),- CanonicalCategory(- name="email",- keywords=frozenset({"email", "e-mail", "email address"}),- param="email",- action="fill",- prompt="Fill the applicant's email address",- ),- CanonicalCategory(- name="phone",- keywords=frozenset({"phone", "telephone", "mobile", "phone number", "cell"}),- param="phone",- action="fill",- prompt="Fill the applicant's phone number",- ),- CanonicalCategory(- name="resume",- keywords=frozenset({"resume", "cv", "curriculum"}),- param="resume",- action="upload_file",- prompt="Upload the applicant's resume",- ),- CanonicalCategory(- name="current_location",- keywords=frozenset({"location", "city", "based", "current location", "where"}),- negative_keywords=frozenset({"job", "office", "company", "position", "role", "birth"}),- param="current_location",- action="fill_autocomplete",- prompt="Fill the applicant's current location",- ),- CanonicalCategory(- name="current_company",- keywords=frozenset({"current company", "employer", "company name", "where do you work", "current employer"}),- negative_keywords=frozenset({"location", "city"}),- param="current_company",- action="fill",- prompt="Fill the applicant's current company",- ),- CanonicalCategory(- name="linkedin",- keywords=frozenset({"linkedin", "linkedin url", "linkedin profile"}),- param="linkedin",- action="fill",- prompt="Fill the applicant's LinkedIn URL",- ),- CanonicalCategory(- name="portfolio",- keywords=frozenset({"portfolio", "website", "github", "personal site", "personal url"}),- negative_keywords=frozenset({"linkedin"}),- param="portfolio",- action="fill",- prompt="Fill the applicant's portfolio or website URL",- ),- CanonicalCategory(- name="cover_letter",- keywords=frozenset({"cover letter", "why interested", "motivation", "additional information", "anything else"}),- action="fill",- prompt="Write a brief, professional cover letter (2-3 sentences)",- ),- CanonicalCategory(- name="salary_expectation",- keywords=frozenset({"salary", "compensation", "pay", "desired salary", "expected salary"}),- action="fill",- prompt="Fill the applicant's salary expectation",- ),- CanonicalCategory(- name="work_authorization",- keywords=frozenset({"authorized", "legally", "sponsorship", "visa", "work permit", "authorization"}),- action="select",- prompt="Answer the work authorization question based on applicant context",- value_mappings=(- ("yes", ("yes", "authorized", "i am authorized", "legally authorized")),- ("no", ("no", "not authorized", "i am not authorized", "require sponsorship")),- ),- ),- CanonicalCategory(- name="start_date",- keywords=frozenset({"start date", "availability", "when can you start", "available", "earliest start"}),- negative_keywords=frozenset({"graduation", "salary", "end"}),- action="fill",- prompt="Fill the applicant's start date or availability",- ),- CanonicalCategory(- name="years_experience",- keywords=frozenset({"years experience", "years of experience", "how long", "experience level"}),- action="fill",- prompt="Fill the applicant's years of experience",- ),- CanonicalCategory(- name="education_level",- keywords=frozenset({"degree", "education", "university", "school", "highest degree"}),- negative_keywords=frozenset({"graduation", "year"}),- action="fill",- prompt="Fill the applicant's education level or degree",- ),- CanonicalCategory(- name="graduation_year",- keywords=frozenset({"graduation", "grad year", "year graduated", "graduation date"}),- action="fill",- prompt="Fill the applicant's graduation year",- ),- CanonicalCategory(- name="gender",- keywords=frozenset({"gender", "sex", "identify", "gender identity"}),- action="select",- prompt="Select the applicant's gender based on applicant context",- value_mappings=(- ("male", ("man", "male", "he", "him")),- ("female", ("woman", "female", "she", "her")),- ("nonbinary", ("non-binary", "nonbinary", "non binary", "genderqueer")),- ("decline", ("decline", "prefer not", "not to say", "don't wish")),- ),- ),- CanonicalCategory(- name="race_ethnicity",- keywords=frozenset({"race", "ethnicity", "ethnic", "racial"}),- action="select",- prompt="Select the applicant's race/ethnicity based on applicant context",- ),- CanonicalCategory(- name="veteran_status",- keywords=frozenset({"veteran", "military", "served", "protected veteran"}),- action="select",- prompt="Select the applicant's veteran status based on applicant context",- value_mappings=(- ("no", ("i am not a protected veteran", "i am not a veteran", "not a veteran", "no")),- ("yes", ("i am a protected veteran", "i am a veteran", "veteran", "yes")),- ("decline", ("i don't wish to answer", "decline to self-identify", "i prefer not to answer", "prefer not")),- ),- ),- CanonicalCategory(- name="disability",- keywords=frozenset({"disability", "accommodation", "impairment", "disabled"}),- action="select",- prompt="Select the applicant's disability status based on applicant context",- value_mappings=(- ("no", ("i do not have a disability", "i don't have a disability", "no, i don't", "no disability", "no")),- ("yes", ("yes, i have a disability", "i have a disability", "yes")),- ("decline", ("i don't wish to answer", "decline to self-identify", "prefer not to answer", "prefer not")),- ),- ),- CanonicalCategory(- name="referral_source",- keywords=frozenset(- {"how did you hear", "referral", "referral source", "where did you find", "how did you find"}- ),- negative_keywords=frozenset({"salary", "visa", "location"}),- action="select",- prompt="Select or fill the referral source (e.g. 'Other')",- ),-]--_CATEGORY_BY_NAME: dict[str, CanonicalCategory] = {c.name: c for c in CANONICAL_CATEGORIES}---def get_category(name: str) -> CanonicalCategory | None:- """Look up a canonical category by name."""- return _CATEGORY_BY_NAME.get(name)---def match_field_to_category(field_label: str) -> CanonicalCategory | None:- """Score *field_label* against all canonical categories and return the best match.-- Returns ``None`` when no category matches (i.e. the field is truly custom).-- Matching algorithm:- 1. Normalize the label (lowercase, strip punctuation, remove stop words).- 2. For each category, check negative keywords first (any hit → skip).- 3. Score by counting how many of the category's keywords (also normalized)- appear in the normalized label as substrings.- 4. Return the category with the highest score (minimum 1 keyword hit).- """- normalized = _normalize(field_label)- if not normalized:- return None-- best: CanonicalCategory | None = None- best_score = 0-- for cat in CANONICAL_CATEGORIES:- # Check negative keywords on the *original* (lowered) label so- # stop-word removal doesn't hide exclusion terms.- label_lower = field_label.lower()- if any(neg in label_lower for neg in cat.negative_keywords):- continue-- score = 0- for kw in cat.keywords:- # Normalize the keyword too so multi-word keywords with stop words- # (e.g. "how did you hear") still match normalized labels.- norm_kw = _normalize(kw)- if norm_kw and norm_kw in normalized:- score += 1-- if score > best_score:- best_score = score- best = cat-- return bestdiff --git a/skyvern/core/script_generations/extract_form_fields.js b/skyvern/core/script_generations/extract_form_fields.jsnew file mode 100644index 000000000..edff14fad--- /dev/null+++ b/skyvern/core/script_generations/extract_form_fields.js@@ -0,0 +1,285 @@+() => {+ const fields = [];+ const seen = new Set();+ let _counter = 0;++ function isVisible(el) {+ if (!el) return false;+ const style = window.getComputedStyle(el);+ return (+ style.display !== "none" &&+ style.visibility !== "hidden" &&+ style.opacity !== "0" &&+ el.offsetWidth > 0 &&+ el.offsetHeight > 0+ );+ }++ function getLabel(el) {+ if (el.id) {+ const lbl = document.querySelector('label[for="' + el.id + '"]');+ if (lbl) return lbl.textContent.trim();+ }+ const parentLabel = el.closest("label");+ if (parentLabel) return parentLabel.textContent.trim();+ if (el.getAttribute("aria-label")) return el.getAttribute("aria-label");+ const labelledBy = el.getAttribute("aria-labelledby");+ if (labelledBy) {+ const ref = document.getElementById(labelledBy);+ if (ref) return ref.textContent.trim();+ }+ if (el.placeholder) return el.placeholder;+ return null;+ }++ function buildSelector(el, label) {+ const tag = el.tagName.toLowerCase();+ const elType = (el.getAttribute("type") || "").toLowerCase();+ const vis = elType === "file" ? "" : ":visible";+ if (el.name) return tag + '[name="' + el.name + '"]' + vis;+ if (el.id) return "#" + el.id + vis;+ if (label && label.length < 80) {+ const escapedLabel = label+ .replace(/\\/g, "\\\\")+ .replace(/"/g, '\\"')+ .replace(/'/g, "\\'");+ const parentLabel = el.closest("label");+ if (+ parentLabel ||+ (el.id && document.querySelector('label[for="' + el.id + '"]'))+ ) {+ return "label:has-text('" + escapedLabel + "') " + tag + ":visible";+ }+ if (el.getAttribute("aria-label")) {+ return tag + '[aria-label="' + escapedLabel + '"]:visible';+ }+ }+ return null;+ }++ function buildOptionSelector(el) {+ if (el.id) return "#" + el.id;+ const tag = el.tagName.toLowerCase();+ const name = el.name;+ const value = el.value;+ if (name && value)+ return tag + '[name="' + name + '"][value="' + value + '"]';+ if (name) return tag + '[name="' + name + '"]';+ return null;+ }++ function getGroupLabel(elements) {+ if (!elements.length) return null;+ const first = elements[0];++ const fieldset = first.closest("fieldset");+ if (fieldset) {+ const legend = fieldset.querySelector("legend");+ if (legend) return legend.textContent.trim();+ }++ let questionContainer = first.parentElement;+ for (let i = 0; i < 6 && questionContainer; i++) {+ const labelEl = questionContainer.querySelector(+ ".application-label, .question-label, .field-label, " ++ '[class*="label"]:not(label), legend, ' ++ '[data-qa="question-text"], [class*="question-text"]',+ );+ if (labelEl) {+ const text = labelEl.textContent.trim();+ if (+ text &&+ text.length < 300 &&+ elements.some((el) => questionContainer.contains(el))+ ) {+ return text;+ }+ }+ questionContainer = questionContainer.parentElement;+ }++ let ancestor = first.parentElement;+ const allInAncestor = () =>+ elements.every((el) => ancestor && ancestor.contains(el));+ while (ancestor && !allInAncestor()) {+ ancestor = ancestor.parentElement;+ }+ if (ancestor) {+ if (ancestor.getAttribute("aria-label"))+ return ancestor.getAttribute("aria-label");+ const lblBy = ancestor.getAttribute("aria-labelledby");+ if (lblBy) {+ const ref = document.getElementById(lblBy);+ if (ref) return ref.textContent.trim();+ }+ let prev = ancestor.previousElementSibling;+ while (prev) {+ const tagName = prev.tagName.toLowerCase();+ if (+ [+ "label",+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "p",+ "span",+ "div",+ ].includes(tagName)+ ) {+ const text = prev.textContent.trim();+ if (text && text.length > 3 && text.length < 300) return text;+ }+ prev = prev.previousElementSibling;+ }+ }++ return getLabel(first);+ }++ const elements = document.querySelectorAll("input, select, textarea");+ const checkRadioGroups = {};++ for (const el of elements) {+ const type = (el.getAttribute("type") || "").toLowerCase();+ if (["hidden", "submit", "button", "image", "reset"].includes(type))+ continue;+ if (type !== "file" && !isVisible(el)) continue;++ if (type === "checkbox" || type === "radio") {+ if (el.name) {+ if (!checkRadioGroups[el.name]) {+ checkRadioGroups[el.name] = { type: type, elements: [] };+ }+ checkRadioGroups[el.name].elements.push(el);+ } else {+ let container = el.parentElement;+ while (container && container !== document.body) {+ const siblings = container.querySelectorAll(+ 'input[type="' + type + '"]',+ );+ if (siblings.length >= 2) break;+ container = container.parentElement;+ }+ if (container && container !== document.body) {+ if (!container._groupKey) {+ container._groupKey =+ "__nameless_" ++ type ++ "_" ++ Math.random().toString(36).slice(2, 8);+ }+ const gk = container._groupKey;+ if (!checkRadioGroups[gk]) {+ checkRadioGroups[gk] = { type: type, elements: [] };+ }+ if (!checkRadioGroups[gk].elements.includes(el)) {+ checkRadioGroups[gk].elements.push(el);+ }+ } else {+ const label = getLabel(el);+ const selector = buildSelector(el, label);+ if (selector) {+ fields.push({+ label: label || null,+ selector: selector,+ tag: "input",+ type: type,+ name: null,+ required: el.required || false,+ placeholder: null,+ });+ }+ }+ }+ continue;+ }++ const uid =+ el.name ||+ el.id ||+ el.getAttribute("aria-label") ||+ "__anon_" + _counter++;+ if (seen.has(uid)) continue;+ seen.add(uid);++ const label = getLabel(el);+ const selector = buildSelector(el, label);+ if (!selector) continue;++ fields.push({+ label: label || null,+ selector: selector,+ tag: el.tagName.toLowerCase(),+ type:+ type ||+ (el.tagName.toLowerCase() === "select"+ ? "select"+ : el.tagName.toLowerCase() === "textarea"+ ? "textarea"+ : "text"),+ name: el.name || null,+ required: el.required || false,+ placeholder: el.placeholder || null,+ });++ if (el.tagName.toLowerCase() === "select") {+ const selectOptions = [];+ for (const opt of el.options) {+ const optText = opt.textContent.trim();+ if (+ !opt.value ||+ opt.value === "" ||+ optText === "" ||+ optText === "--"+ )+ continue;+ selectOptions.push({+ label: optText,+ value: opt.value,+ });+ }+ if (selectOptions.length > 0) {+ fields[fields.length - 1].options = selectOptions;+ }+ }+ }++ for (const [groupKey, group] of Object.entries(checkRadioGroups)) {+ const els = group.elements;+ if (seen.has(groupKey)) continue;+ seen.add(groupKey);++ const groupLabel = getGroupLabel(els);+ const firstSelector =+ buildOptionSelector(els[0]) || buildSelector(els[0], getLabel(els[0]));+ if (!firstSelector) continue;++ const options = [];+ for (const el of els) {+ const optLabel = getLabel(el) || el.value || null;+ const optSelector = buildOptionSelector(el);+ if (!optSelector) continue;+ options.push({+ label: optLabel,+ value: el.value || null,+ selector: optSelector,+ });+ }++ const groupType = group.type === "radio" ? "radio_group" : "checkbox_group";+ fields.push({+ label: groupLabel || null,+ selector: firstSelector,+ tag: "input",+ type: groupType,+ name: els[0].name || null,+ required: els[0].required || false,+ placeholder: null,+ options: options,+ });+ }+ return fields;+};diff --git a/skyvern/core/script_generations/generate_script.py b/skyvern/core/script_generations/generate_script.pyindex 52f2f4e43..f70275f49 100644--- a/skyvern/core/script_generations/generate_script.py+++ b/skyvern/core/script_generations/generate_script.py@@ -486,7 +486,7 @@ def _annotate_multi_field_totp_sequence(actions: list[dict[str, Any]]) -> list[dreturn actions-def _safe_name(label: str) -> str:+def safe_name(label: str) -> str:s = "".join(c if c.isalnum() else "_" for c in label).lower()if not s or s[0].isdigit() or keyword.iskeyword(s):s = f"_{s}"@@ -587,7 +587,7 @@ def _workflow_decorator(wf_req: dict[str, Any]) -> cst.Decorator:)-def _make_decorator(block_label: str, block: dict[str, Any]) -> cst.Decorator:+def make_decorator(block_label: str, block: dict[str, Any]) -> cst.Decorator:kwargs = [cst.Arg(keyword=cst.Name("cache_key"),@@ -1034,88 +1034,16 @@ def _build_form_filling_block_fn(actions: list[dict[str, Any]],value_to_param: dict[str, str] | None = None,) -> FunctionDef:- """Generate a FIELD_MAP-based block function from V1 actions.+ """Generate a form-filling block function that uses page.fill_form().- Instead of procedural page.fill()/page.select_option() calls, produces a- FIELD_MAP dictionary + page.fill_form() call for dynamic form filling.+ Produces a simple function that calls page.fill_form(context.parameters)+ which internally uses LLM-based field mapping (extract → map → fill)."""- name = _safe_name(block.get("label") or block.get("title") or f"block_{block.get('workflow_run_block_id')}")+ name = safe_name(block.get("label") or block.get("title") or f"block_{block.get('workflow_run_block_id')}")cache_key = block.get("label") or block.get("title") or f"block_{block.get('workflow_run_block_id')}"- # Build FIELD_MAP entries from actions- field_map_lines: list[str] = []- seen_keys: set[str] = set()-navigation_goal = block.get("navigation_goal") or "Fill out the form"- for act in actions:- action_type = act.get("action_type")- if action_type not in (ActionType.INPUT_TEXT, ActionType.SELECT_OPTION):- continue-- intention = act.get("intention") or act.get("reasoning") or ""- # field_name is set by hydrate_input_text_actions_with_field_names()- # but may not match actual workflow parameter keys. Use value_to_param- # to look up the real parameter key from the literal value.- field_name = act.get("field_name")-- # Look up the actual workflow parameter key via the literal action value- actual_param: str | None = None- if value_to_param:- if action_type == ActionType.INPUT_TEXT:- literal_value = act.get("text", "")- elif action_type == ActionType.SELECT_OPTION:- option = act.get("option", {})- literal_value = option.get("value") or option.get("label") or ""- else:- literal_value = ""- if literal_value and literal_value in value_to_param:- actual_param = value_to_param[literal_value]-- # Determine the snake_case key for this field- if field_name:- key = sanitize_variable_name(field_name)- elif intention:- key = sanitize_variable_name(intention[:40])- else:- continue-- if key in seen_keys:- continue- seen_keys.add(key)-- # Determine action type for FIELD_MAP- if action_type == ActionType.SELECT_OPTION:- fm_action = "select"- else:- fm_action = "fill"-- # Build the label from intention/reasoning- label = intention.lower().strip() if intention else key.replace("_", " ")- if len(label) > 60:- label = label[:60]-- # Use actual_param (from value_to_param lookup) if found, else fall back to field_name.- # If neither exists, this field has no parameter → use ai='proactive'.- param = actual_param or field_name- param_str = repr(param) if param else "None"- ai_str = repr("proactive") if not param else repr("fallback")- prompt = intention or f"Fill the {key.replace('_', ' ')} field"-- entry = (- f" {repr(key)}: {{\n"- f' "param": {param_str},\n'- f' "action": {repr(fm_action)},\n'- f' "ai": {ai_str},\n'- f' "labels": [{repr(label)}],\n'- f' "prompt": {repr(prompt)},\n'- f" }},"- )- field_map_lines.append(entry)-- # Build the function body as a string, then parse it- field_map_body = "\n".join(field_map_lines)-# Include page.goto(url) if the block has a URL, just like _build_block_fn doesgoto_line = ""if block.get("url"):@@ -1124,12 +1052,7 @@ def _build_form_filling_block_fn(func_code = (f"async def {name}(page: SkyvernPage, context: RunContext):\n"f"{goto_line}"- f" FIELD_MAP = {{\n"- f"{field_map_body}\n"- f" }}\n"- f" await page.fill_form(FIELD_MAP, context, navigation_goal={repr(navigation_goal)})\n"- f" if not await page.structural_validate():\n"- f" await page.complete()\n"+ f" await page.fill_form(context.parameters, prompt={repr(navigation_goal)})\n")# Parse and add decorator@@ -1138,10 +1061,19 @@ def _build_form_filling_block_fn(assert isinstance(func_def, FunctionDef)# Add the @skyvern.cached decorator- decorated = func_def.with_changes(decorators=[_make_decorator(cache_key, block)])+ decorated = func_def.with_changes(decorators=[make_decorator(cache_key, block)])return decorated+def _detect_block_ats_platform(block: dict[str, Any]) -> str | None:+ """Check if a block's URL belongs to a known ATS platform.++ Delegates to app.AGENT_FUNCTION which is overridden in cloud builds.+ Returns None in OSS (no ATS detection).+ """+ return app.AGENT_FUNCTION.detect_ats_platform(block.get("url", ""))++def _build_block_fn(block: dict[str, Any],actions: list[dict[str, Any]],@@ -1149,11 +1081,25 @@ def _build_block_fn(use_semantic_selectors: bool = False,is_in_for_loop: bool = False,) -> FunctionDef:+ # Check for platform-specific pipeline (cloud-only; returns None in OSS)+ if use_semantic_selectors:+ ats_platform = _detect_block_ats_platform(block)+ if ats_platform:+ pipeline_fn = app.AGENT_FUNCTION.build_ats_pipeline_block_fn(block, ats_platform)+ if pipeline_fn:+ LOG.info(+ "Code 2.0: platform detected, generating optimized pipeline",+ ats_platform=ats_platform,+ block_label=block.get("label"),+ block_url=block.get("url"),+ )+ return pipeline_fn+# Check if this block is form-filling (4+ input_text/select actions)if use_semantic_selectors and _is_form_filling_block(actions):return _build_form_filling_block_fn(block, actions, value_to_param)- name = _safe_name(block.get("label") or block.get("title") or f"block_{block.get('workflow_run_block_id')}")+ name = safe_name(block.get("label") or block.get("title") or f"block_{block.get('workflow_run_block_id')}")cache_key = block.get("label") or block.get("title") or f"block_{block.get('workflow_run_block_id')}"body_stmts: list[cst.BaseStatement] = []@@ -1216,7 +1162,7 @@ def _build_block_fn(Param(name=Name("context"), annotation=cst.Annotation(cst.Name("RunContext"))),]),- decorators=[_make_decorator(cache_key, block)],+ decorators=[make_decorator(cache_key, block)],body=cst.IndentedBlock(body_stmts),returns=None,asynchronous=cst.Asynchronous(),@@ -1226,7 +1172,7 @@ def _build_block_fn(def _build_task_v2_block_fn(block: dict[str, Any], child_blocks: list[dict[str, Any]]) -> FunctionDef:"""Build a cached function for task_v2 blocks that calls child workflow sub-tasks."""cache_key = block.get("label") or block.get("title") or f"block_{block.get('workflow_run_block_id')}"- name = _safe_name(block.get("label") or block.get("title") or f"block_{block.get('workflow_run_block_id')}")+ name = safe_name(block.get("label") or block.get("title") or f"block_{block.get('workflow_run_block_id')}")body_stmts: list[cst.BaseStatement] = []# Add calls to child workflow sub-tasks@@ -1251,7 +1197,7 @@ def _build_task_v2_block_fn(block: dict[str, Any], child_blocks: list[dict[str,Param(name=Name("context"), annotation=cst.Annotation(cst.Name("RunContext"))),]),- decorators=[_make_decorator(cache_key, block)],+ decorators=[make_decorator(cache_key, block)],body=cst.IndentedBlock(body_stmts),returns=None,asynchronous=cst.Asynchronous(),diff --git a/skyvern/core/script_generations/run_initializer.py b/skyvern/core/script_generations/run_initializer.pyindex 1a529ca7a..e533aee51 100644--- a/skyvern/core/script_generations/run_initializer.py+++ b/skyvern/core/script_generations/run_initializer.py@@ -5,7 +5,6 @@ import structlogfrom cachetools import TTLCachefrom pydantic import BaseModel-from skyvern.core.script_generations.canonical_fields import CANONICAL_CATEGORIESfrom skyvern.core.script_generations.script_skyvern_page import ScriptSkyvernPage, script_run_context_managerfrom skyvern.core.script_generations.skyvern_page import RunContext, SkyvernPagefrom skyvern.forge import app@@ -23,6 +22,9 @@ _extraction_cache: TTLCache[str, dict[str, str | None]] = TTLCache(maxsize=256,async def _extract_canonical_values(parameters: dict[str, Any]) -> dict[str, str | None]:"""Extract canonical field values from ALL parameters — no magic names.+ Canonical categories are provided by cloud via AgentFunction. In OSS builds+ this returns an empty dict (no categories registered).+Strategy:1. Direct mapping: if a parameter key matches a canonical category's paramname (e.g., "email" → email category), use the value directly. No LLM needed.@@ -32,7 +34,7 @@ async def _extract_canonical_values(parameters: dict[str, Any]) -> dict[str, strReturns a dict keyed by canonical category name -> extracted value (or None)."""result: dict[str, str | None] = {}- param_to_category = {c.param: c.name for c in CANONICAL_CATEGORIES if c.param}+ param_to_category = {c.param: c.name for c in app.AGENT_FUNCTION.get_canonical_categories() if c.param}text_blobs: list[str] = []for key, value in parameters.items():@@ -50,7 +52,7 @@ async def _extract_canonical_values(parameters: dict[str, Any]) -> dict[str, str# LLM extraction for remaining categoriesif text_blobs:- remaining_cats = [c for c in CANONICAL_CATEGORIES if c.name not in result]+ remaining_cats = [c for c in app.AGENT_FUNCTION.get_canonical_categories() if c.name not in result]if remaining_cats:combined_text = "\n\n".join(text_blobs)llm_result = await _llm_extract_from_text(combined_text, remaining_cats)diff --git a/skyvern/core/script_generations/skyvern_page.py b/skyvern/core/script_generations/skyvern_page.pyindex 3e0b7fdde..314ee5e7c 100644--- a/skyvern/core/script_generations/skyvern_page.py+++ b/skyvern/core/script_generations/skyvern_page.py@@ -2,18 +2,19 @@ from __future__ import annotationsimport asyncioimport copy-import os+import json as _jsonimport reimport uuidfrom dataclasses import dataclass+from pathlib import Pathfrom typing import TYPE_CHECKING, Any, Callable, Literal, overloadimport structlogfrom playwright.async_api import Locator, Pagefrom skyvern.config import settings-from skyvern.core.script_generations.canonical_fields import get_category, match_field_to_categoryfrom skyvern.core.script_generations.skyvern_page_ai import SkyvernPageAi+from skyvern.exceptions import ScriptTerminationExceptionfrom skyvern.forge import appfrom skyvern.forge.prompts import prompt_enginefrom skyvern.forge.sdk.api.files import download_file as download_file_from_url@@ -28,6 +29,16 @@ if TYPE_CHECKING:LOG = structlog.get_logger()+_EXTRACT_FORM_FIELDS_JS: str | None = None+++def _get_extract_form_fields_js() -> str:+ global _EXTRACT_FORM_FIELDS_JS+ if _EXTRACT_FORM_FIELDS_JS is None:+ js_path = Path(__file__).parent / "extract_form_fields.js"+ _EXTRACT_FORM_FIELDS_JS = js_path.read_text()+ return _EXTRACT_FORM_FIELDS_JS+@dataclassclass ActionMetadata:@@ -1288,7 +1299,7 @@ class SkyvernPage(Page):text_patterns=text_patterns,)- async def scan_form_fields(self) -> list[dict[str, Any]]:+ async def extract_form_fields(self) -> list[dict[str, Any]]:"""Scan the page for visible form fields using DOM inspection (no LLM).Two-pass approach:@@ -1305,356 +1316,427 @@ class SkyvernPage(Page):"tag": "input", "type": "checkbox_group", "name": "field0", "required": False,"options": [{"label": "Engineering", "value": "Engineering", "selector": "..."}]}]"""- return await self.page.evaluate(- """() => {- const fields = [];- const seen = new Set();-- function isVisible(el) {- if (!el) return false;- const style = window.getComputedStyle(el);- return style.display !== 'none' && style.visibility !== 'hidden'- && style.opacity !== '0' && el.offsetWidth > 0 && el.offsetHeight > 0;- }+ return await self.page.evaluate(_get_extract_form_fields_js())- function getLabel(el) {- if (el.id) {- const lbl = document.querySelector('label[for="' + el.id + '"]');- if (lbl) return lbl.textContent.trim();- }- const parentLabel = el.closest('label');- if (parentLabel) return parentLabel.textContent.trim();- if (el.getAttribute('aria-label')) return el.getAttribute('aria-label');- const labelledBy = el.getAttribute('aria-labelledby');- if (labelledBy) {- const ref = document.getElementById(labelledBy);- if (ref) return ref.textContent.trim();- }- if (el.placeholder) return el.placeholder;- return null;- }+ async def dynamic_field_map(+ self,+ form_fields: list[dict[str, Any]],+ data: dict[str, Any],+ *,+ prompt: str | None = None,+ ) -> dict[int, str | list | bool | None]:+ """Map data to form fields via a single cheap text-only LLM call.- function buildSelector(el, label) {- const tag = el.tagName.toLowerCase();- // Prefer stable attribute selectors over fragile label text.- // name/id selectors survive DOM re-renders and label text changes.- if (el.name) return tag + '[name="' + el.name + '"]:visible';- if (el.id) return '#' + el.id + ':visible';- if (label && label.length < 80) {- const escapedLabel = label.replace(/'/g, "\\\\'");- const parentLabel = el.closest('label');- if (parentLabel || (el.id && document.querySelector('label[for="' + el.id + '"]'))) {- return 'label:has-text(\\'' + escapedLabel + '\\') ' + tag + ':visible';- }- if (el.getAttribute('aria-label')) {- return tag + '[aria-label="' + escapedLabel + '"]:visible';- }- }- return null;- }+ One LLM call sees ALL fields + ALL data and produces a complete mapping —+ no deterministic matching, no caching, no accumulated state.- function buildOptionSelector(el) {- if (el.id) return '#' + el.id;- const tag = el.tagName.toLowerCase();- const name = el.name;- const value = el.value;- if (name && value) return tag + '[name="' + name + '"][value="' + value + '"]';- if (name) return tag + '[name="' + name + '"]';- return null;- }+ Args:+ form_fields: Output of :meth:`extract_form_fields`.+ data: Flat dict of data keys/values to map to form fields.- // Find the group-level label for a set of checkbox/radio elements- function getGroupLabel(elements) {- if (!elements.length) return null;- const first = elements[0];+ Returns:+ Mapping of 0-based field index -> value to fill (or None to skip).+ """+ if not form_fields or not data:+ return {}- // 1. <fieldset><legend> wrapping the group- const fieldset = first.closest('fieldset');- if (fieldset) {- const legend = fieldset.querySelector('legend');- if (legend) return legend.textContent.trim();+ # Build field descriptions for the LLM+ field_descs: list[dict[str, Any]] = []+ for field in form_fields:+ label = field.get("label") or field.get("name") or field.get("placeholder") or "unknown"+ field_type = field.get("type", "text")+ options: list[str] | None = None+ if field.get("options"):+ options = [o.get("label") or o.get("value", "") for o in field["options"]]+ field_descs.append(+ {+ "label": label,+ "type": field_type,+ "required": field.get("required", False),+ "placeholder": field.get("placeholder"),+ "options": options,}+ )- // 2. Find nearest common ancestor, then look for a heading/label before it- let ancestor = first.parentElement;- const allInAncestor = () => elements.every(el => ancestor && ancestor.contains(el));- while (ancestor && !allInAncestor()) {- ancestor = ancestor.parentElement;- }- if (ancestor) {- // aria-label on container- if (ancestor.getAttribute('aria-label')) return ancestor.getAttribute('aria-label');- // aria-labelledby on container- const lblBy = ancestor.getAttribute('aria-labelledby');- if (lblBy) {- const ref = document.getElementById(lblBy);- if (ref) return ref.textContent.trim();- }- // Look for heading or label element immediately before the container- let prev = ancestor.previousElementSibling;- if (prev) {- const tagName = prev.tagName.toLowerCase();- if (['label', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'div'].includes(tagName)) {- const text = prev.textContent.trim();- if (text && text.length < 200) return text;- }- }- }+ prompt_text = prompt_engine.load_prompt(+ template="form-field-mapper",+ form_fields=field_descs,+ data=data,+ prompt=prompt,+ )- // 3. Fall back to the first element's label- return getLabel(first);- }+ try:+ skyvern_ctx = skyvern_context.current()+ org_id = skyvern_ctx.organization_id if skyvern_ctx else None+ if skyvern_ctx:+ skyvern_ctx.script_llm_call_count += 1- const elements = document.querySelectorAll('input, select, textarea');- // Collect checkbox/radio inputs for pass 2- const checkRadioGroups = {};-- for (const el of elements) {- const type = (el.getAttribute('type') || '').toLowerCase();- if (['hidden', 'submit', 'button', 'image', 'reset'].includes(type)) continue;- if (!isVisible(el)) continue;-- // Pass 2 collection: group checkboxes/radios by shared name attribute.- // Checkboxes/radios without a name can't be reliably grouped —- // emit them as individual fields (type: "checkbox" / "radio").- if (type === 'checkbox' || type === 'radio') {- if (el.name) {- if (!checkRadioGroups[el.name]) {- checkRadioGroups[el.name] = { type: type, elements: [] };- }- checkRadioGroups[el.name].elements.push(el);- } else {- // Individual checkbox/radio without a name — emit directly- const label = getLabel(el);- const selector = buildSelector(el, label);- if (selector) {- fields.push({- label: label || null,- selector: selector,- tag: 'input',- type: type,- name: null,- required: el.required || false,- placeholder: null,- });- }- }- continue;- }+ json_response = await app.SECONDARY_LLM_API_HANDLER(+ prompt=prompt_text,+ prompt_name="form-field-mapper",+ organization_id=org_id,+ )- // Pass 1: non-checkbox/non-radio elements- const uid = el.name || el.id || el.getAttribute('aria-label') || Math.random().toString();- if (seen.has(uid)) continue;- seen.add(uid);-- const label = getLabel(el);- const selector = buildSelector(el, label);- if (!selector) continue;-- fields.push({- label: label || null,- selector: selector,- tag: el.tagName.toLowerCase(),- type: type || (el.tagName.toLowerCase() === 'select' ? 'select' : el.tagName.toLowerCase() === 'textarea' ? 'textarea' : 'text'),- name: el.name || null,- required: el.required || false,- placeholder: el.placeholder || null,- });-- // Collect <select> options for batch planning- if (el.tagName.toLowerCase() === 'select') {- const selectOptions = [];- for (const opt of el.options) {- const optText = opt.textContent.trim();- if (!opt.value || opt.value === '' || optText === '' || optText === '--') continue;- selectOptions.push({- label: optText,- value: opt.value,- });- }- if (selectOptions.length > 0) {- fields[fields.length - 1].options = selectOptions;- }- }- }+ if not isinstance(json_response, dict):+ LOG.warning(+ "dynamic_field_map: LLM returned non-dict",+ response_type=type(json_response).__name__,+ )+ raise ValueError(f"LLM returned {type(json_response).__name__} instead of dict")- // Pass 2: emit grouped checkbox/radio entries- for (const [groupKey, group] of Object.entries(checkRadioGroups)) {- const els = group.elements;- if (seen.has(groupKey)) continue;- seen.add(groupKey);-- const groupLabel = getGroupLabel(els);- const firstSelector = buildOptionSelector(els[0]) || buildSelector(els[0], getLabel(els[0]));- if (!firstSelector) continue;-- const options = [];- for (const el of els) {- const optLabel = getLabel(el) || el.value || null;- const optSelector = buildOptionSelector(el);- if (!optSelector) continue;- options.push({- label: optLabel,- value: el.value || null,- selector: optSelector,- });- }+ result: dict[int, Any] = {}+ for k, v in json_response.items():+ if v is None:+ continue+ try:+ idx = int(k) - 1 # 1-indexed prompt -> 0-indexed+ if 0 <= idx < len(form_fields):+ result[idx] = v+ except (ValueError, TypeError):+ LOG.warning("dynamic_field_map: non-numeric key in LLM response", key=k)+ LOG.info("dynamic_field_map: mapped fields", mapped=len(result), total=len(form_fields))+ return result- const groupType = group.type === 'radio' ? 'radio_group' : 'checkbox_group';- fields.push({- label: groupLabel || null,- selector: firstSelector,- tag: 'input',- type: groupType,- name: els[0].name || null,- required: els[0].required || false,- placeholder: null,- options: options,- });- }- return fields;- }"""- )+ except Exception:+ LOG.warning("dynamic_field_map: LLM call failed", exc_info=True)+ raise- async def fill_form(+ async def fill_from_mapping(self,- field_map: dict[str, dict],- context: Any,- *,- navigation_goal: str = "Fill out the form",+ form_fields: list[dict[str, Any]],+ mapping: dict[int, str | list | bool | None],+ data: dict[str, Any] | None = None,) -> None:- """Scan page for form fields and fill them using the field_map.-- Two-pass structural anti-scrambling approach:- - Pass 1: Resolve canonical extracted values and direct parameter values.- These fields are removed from the batch planner's view entirely.- - Pass 2: Batch plan ONLY unresolved fields (the planner can't scramble- canonical values because it never sees them).- - Pass 3: Fill everything.-- field_map keys are descriptive snake_case names (e.g., "full_name", "phone").- field_map values are dicts with:- - "param": parameter key in context.parameters (or None)- - "action": "fill" | "select" | "fill_autocomplete" | "click" | "upload_file"- - "ai": optional, "fallback" | "proactive" (default: "fallback" when param exists, "proactive" otherwise)- - "prompt": AI prompt for this field- - "labels": list of known label variants (used for fuzzy matching)-- Fields found on page but NOT in field_map are filled with ai='proactive'.- """- fields = await self.scan_form_fields()+ """Fill form fields using a pre-computed mapping from :meth:`dynamic_field_map`.- LOG.info(- "fill_form: scanned page fields",- field_count=len(fields),- field_map_size=len(field_map),- )+ Iterates over the mapping and fills each field using the appropriate+ browser method based on field type. No LLM calls — pure execution.- # PASS 1: Structurally resolve canonical + direct-param fields- resolved: dict[int, tuple[Any, dict]] = {} # i -> (value, entry)- unresolved_fields: list[tuple[int, dict, dict | None]] = [] # (i, field, matched_entry)+ Args:+ form_fields: Output of :meth:`extract_form_fields`.+ mapping: Output of :meth:`dynamic_field_map` (index -> value).+ data: Original data dict for post-fill file upload matching.+ """+ ai_fallback_count = 0+ max_ai_fallbacks = 10- for i, field in enumerate(fields):- matched_entry = self._match_field_to_map(field, field_map, context)+ def _budget_available() -> bool:+ nonlocal ai_fallback_count+ if ai_fallback_count >= max_ai_fallbacks:+ LOG.warning("fill_from_mapping: AI fallback budget exhausted", count=ai_fallback_count)+ return False+ ai_fallback_count += 1+ return True- # Canonical extracted value → structural fill, skip batch planner- if matched_entry and matched_entry.get("_extracted_value") is not None:- LOG.info(- "fill_form: structurally resolved (canonical)",- field_label=field.get("label"),- category=matched_entry.get("_canonical"),- value_preview=str(matched_entry["_extracted_value"])[:40],- )- resolved[i] = (matched_entry["_extracted_value"], matched_entry)+ for idx, value in sorted(mapping.items()):+ if idx >= len(form_fields) or value is None:continue- # Direct param value → structural fill, skip batch planner- if matched_entry:- param = matched_entry.get("param")- direct_value = context.parameters.get(param) if param else None- if direct_value:- LOG.info(- "fill_form: structurally resolved (param)",- field_label=field.get("label"),- param=param,- )- resolved[i] = (direct_value, matched_entry)- continue-- unresolved_fields.append((i, field, matched_entry))-- LOG.info(- "fill_form: structural resolution complete",- resolved_count=len(resolved),- unresolved_count=len(unresolved_fields),- )+ field = form_fields[idx]+ selector = field.get("selector", "")+ field_type = field.get("type", "text")+ field_tag = field.get("tag", "input")+ label = field.get("label") or field.get("name") or "unknown"- # PASS 2: Batch plan ONLY unresolved fields (no canonical fields in the prompt)- planned_values: dict[int, Any] | None = None- if unresolved_fields:- only_fields = [f for _, f, _ in unresolved_fields]- planned_values = await self._batch_plan_form_values(only_fields, field_map, context, navigation_goal)+ try:+ if field_type in ("radio_group", "checkbox_group"):+ if isinstance(value, str):+ try:+ parsed = _json.loads(value)+ selected = (+ [str(v).lower().strip() for v in parsed]+ if isinstance(parsed, list)+ else [value.lower().strip()]+ )+ except (ValueError, TypeError):+ selected = [value.lower().strip()]+ elif isinstance(value, list):+ selected = [str(v).lower().strip() for v in value]+ else:+ selected = [str(value).lower().strip()]- # PASS 3: Fill everything (with error tracking for element retry)- # Pre-build lookup: original field index -> (unresolved_idx, matched_entry)- original_to_unresolved: dict[int, tuple[int, dict | None]] = {- fi: (ui, entry) for ui, (fi, _, entry) in enumerate(unresolved_fields)- }+ options = field.get("options", [])+ opt_labels = [(o.get("label") or o.get("value", "")).lower().strip() for o in options]- failed_fields: list[tuple[int, dict]] = [] # (field_index, field) pairs that failed+ matched_any = False+ for sel_label in selected:+ for oi, ol in enumerate(opt_labels):+ # Exact match, or substring match with min length 3 to avoid+ # false positives (e.g., "No" matching "None of the above")+ if (+ sel_label == ol+ or (len(sel_label) >= 3 and sel_label in ol)+ or (len(ol) >= 3 and ol in sel_label)+ ):+ await self.click(selector=options[oi]["selector"], ai=None)+ matched_any = True+ break- for i, field in enumerate(fields):- try:- if i in resolved:- value, entry = resolved[i]- await self._fill_with_planned_value(field, value, entry, navigation_goal=navigation_goal)- elif i in original_to_unresolved:- unresolved_idx, matched = original_to_unresolved[i]- if planned_values and unresolved_idx in planned_values:- await self._fill_with_planned_value(- field, planned_values[unresolved_idx], matched, navigation_goal=navigation_goal+ if not matched_any:+ # No option text-matched — use AI fallback (Code 2.0 style)+ LOG.info(+ "fill_from_mapping: no option matched for group, using AI fallback",+ field_label=label,+ intended_value=str(value)[:100],+ available_options=[o[:50] for o in opt_labels],)- elif matched:- # Try to resolve a value from param/extracted before falling back to per-field AI- fallback_value = self._resolve_fallback_value(field, matched, context)- if fallback_value is not None:- await self._fill_with_planned_value(- field, fallback_value, matched, navigation_goal=navigation_goal+ if _budget_available():+ try:+ self._track_ai_call()+ prompt = f"For the question '{label}', select the option closest to '{value}'"+ await self.click(selector=selector, ai="fallback", prompt=prompt)+ except Exception:+ LOG.warning(+ "fill_from_mapping: AI fallback for radio/checkbox group failed, skipping",+ field_label=label,+ )++ elif field_tag == "select":+ locator = self.page.locator(selector)+ try:+ await locator.select_option(label=str(value), timeout=settings.BROWSER_ACTION_TIMEOUT_MS)+ except Exception:+ try:+ await locator.select_option(str(value), timeout=settings.BROWSER_ACTION_TIMEOUT_MS)+ except Exception:+ # Dropdown value didn't match — AI fallback (Code 2.0 style)+ LOG.info(+ "fill_from_mapping: select option not found, using AI fallback",+ field_label=label,+ intended_value=str(value)[:100],)- else:- await self._fill_matched_field(field, matched, context, navigation_goal)- else:- await self._fill_unknown_field(field, navigation_goal)+ if _budget_available():+ try:+ self._track_ai_call()+ prompt = f"Select '{value}' from the '{label}' dropdown"+ await self.select_option(selector=selector, ai="fallback", prompt=prompt)+ except Exception:+ LOG.warning(+ "fill_from_mapping: select AI fallback failed, skipping", field_label=label+ )++ elif field_type in ("checkbox", "radio"):+ if value and str(value).lower() not in ("false", "no", "0", "skip"):+ await self.click(selector=selector, ai=None)++ elif field_type == "file":+ await self.upload_file(+ selector=selector,+ files=str(value),+ ai="fallback",+ prompt=f"Upload file for {label}",+ )+else:- await self._fill_unknown_field(field, navigation_goal)+ await self.fill(selector=selector, value=str(value), ai=None)+except Exception:LOG.warning(- "fill_form: field failed during pass 3, will retry",- field_label=field.get("label"),- field_index=i,+ "fill_from_mapping: field fill failed, trying AI fallback",+ field_label=label,+ field_type=field_type,+ field_index=idx,exc_info=True,)- failed_fields.append((i, field))-- # PASS 4: Element retry of failed fields only (prevents full-block AI fallback)- if failed_fields:- LOG.info(- "fill_form: retrying failed fields with AI",- failed_count=len(failed_fields),- )- for i, field in failed_fields:+ # Field-type-aware AI fallback (Code 2.0 — selector + fallback, not proactive)+ if not _budget_available():+ continuetry:- await self._fill_unknown_field(field, navigation_goal)+ self._track_ai_call()+ if field_type in ("radio_group", "checkbox_group"):+ prompt = f"Select '{value}' for the question '{label}'"+ await self.click(selector=selector, ai="fallback", prompt=prompt)+ elif field_type in ("radio", "checkbox"):+ prompt = f"Click the '{label}' option to select '{value}'"+ await self.click(selector=selector, ai="fallback", prompt=prompt)+ elif field_tag == "select":+ prompt = f"Select '{value}' from the '{label}' dropdown"+ await self.select_option(selector=selector, ai="fallback", prompt=prompt)+ else:+ prompt = f"Fill the '{label}' field with: {value}"+ await self.fill(selector=selector, ai="fallback", prompt=prompt)except Exception:- LOG.warning(- "fill_form: element retry also failed",- field_label=field.get("label"),- exc_info=True,- )+ LOG.warning("fill_from_mapping: AI fallback also failed", field_label=label, exc_info=True)++ # Post-fill: handle unmapped file upload fields by matching URL parameters+ # LLMs often return null for file fields even when a matching URL parameter exists.+ # This catches those cases by scanning for file fields that weren't in the mapping+ # and trying to match them against URL-like parameter values.+ if data:+ url_params = {k: v for k, v in data.items() if isinstance(v, str) and v.startswith("http")}+ file_fields = [(i, f) for i, f in enumerate(form_fields) if f.get("type") == "file"]+ unmapped_files = [(i, f) for i, f in file_fields if i not in mapping]+ LOG.info(+ "fill_from_mapping: file upload check",+ url_params_count=len(url_params),+ url_param_keys=list(url_params.keys()) if url_params else [],+ file_field_count=len(file_fields),+ unmapped_file_count=len(unmapped_files),+ unmapped_file_labels=[(f.get("label") or f.get("name") or "?")[:50] for _, f in unmapped_files],+ )+ if url_params:+ for idx, field in enumerate(form_fields):+ if field.get("type") != "file" or idx in mapping:+ continue+ field_label = (field.get("label") or "").lower()+ field_name = (field.get("name") or "").lower()+ selector = field.get("selector", "")+ if not selector:+ continue+ # Try to match file field name/label against parameter keys+ for param_key, param_url in url_params.items():+ pk = param_key.lower()+ if (+ pk == field_name # "resume" == "resume"+ or (len(pk) >= 3 and pk in field_name) # "resume" in "resume-upload"+ or (len(field_name) >= 3 and field_name in pk) # "doc" in "resume_doc"+ or (field_label and len(pk) >= 3 and pk in field_label)+ ):+ LOG.info(+ "fill_from_mapping: matched URL param to file field",+ param_key=param_key,+ field_label=field_label,+ )+ try:+ await self.upload_file(+ selector=selector,+ files=param_url,+ ai=None,+ )+ except Exception:+ LOG.warning(+ "fill_from_mapping: file upload failed",+ field_label=field_label,+ param_url=param_url[:100],+ exc_info=True,+ )+ break++ async def validate_mapping(+ self,+ form_fields: list[dict[str, Any]],+ mapping: dict[int, str | list | bool | None],+ prompt: str | None,+ ) -> bool:+ """Validate the field mapping against the user's prompt/instructions.++ Makes one LLM call that sees the prompt (user instructions),+ the form fields, and what was mapped to each field. Returns True if+ the run should complete, False if it should terminate.++ This catches user directives like "terminate if you can't answer the+ security clearance question" or "never fabricate answers — fail if+ data is missing for required fields."++ Args:+ form_fields: Output of :meth:`extract_form_fields`.+ mapping: Output of :meth:`dynamic_field_map`.+ prompt: The user's instructions/prompt for this automation.++ Returns:+ True to complete, False to terminate.+ """+ if not prompt:+ return True++ # Build a summary of what was mapped+ field_summary: list[str] = []+ for i, field in enumerate(form_fields):+ label = field.get("label") or field.get("name") or f"field_{i}"+ field_type = field.get("type", "text")+ required = field.get("required", False)+ value = mapping.get(i)+ if value is not None:+ field_summary.append(f"- {label} ({field_type}{'*' if required else ''}): {str(value)[:100]}")+ else:+ field_summary.append(f"- {label} ({field_type}{'*' if required else ''}): [NOT FILLED]")++ prompt_text = (+ "You are validating a job application form that was filled automatically.\n\n"+ "# User Instructions\n"+ f"```\n{prompt}\n```\n\n"+ "# Form Fields and Values\n" + "\n".join(field_summary) + "\n\n"+ "# Task\n"+ "Review the filled values against the user instructions above.\n"+ "Decide whether this application should COMPLETE or TERMINATE.\n\n"+ "TERMINATE only if:\n"+ "- The user instructions EXPLICITLY say to terminate/fail/stop for a specific condition, "+ "and that condition is met (e.g., 'terminate if work authorization is unknown')\n"+ "- The user instructions say 'do not submit', 'don't submit', 'don't click submit', "+ "or similar — this means they are testing and want to stop before submission\n"+ "- Do NOT terminate just because some fields are [NOT FILLED] — that's normal for "+ "optional fields or file uploads without matching data\n\n"+ "COMPLETE if:\n"+ "- The user didn't specify any termination conditions (DEFAULT — most cases)\n"+ "- All explicit user termination conditions are satisfied\n"+ "- Fields are filled reasonably given the available data\n"+ "- Some fields being [NOT FILLED] is OK as long as no user instruction says otherwise\n\n"+ "# Output\n"+ 'Return JSON: {"decision": "complete"} or {"decision": "terminate", "reason": "brief explanation"}\n'+ )++ try:+ skyvern_ctx = skyvern_context.current()+ org_id = skyvern_ctx.organization_id if skyvern_ctx else None+ if skyvern_ctx:+ skyvern_ctx.script_llm_call_count += 1++ result = await app.SECONDARY_LLM_API_HANDLER(+ prompt=prompt_text,+ prompt_name="form-validate-mapping",+ organization_id=org_id,+ )++ decision = result.get("decision", "complete") if isinstance(result, dict) else "complete"++ if decision == "terminate":+ reason = result.get("reason", "Validation failed") if isinstance(result, dict) else "Validation failed"+ LOG.info(+ "validate_mapping: TERMINATE",+ reason=reason,+ prompt=prompt[:200],+ )+ return False++ LOG.info("validate_mapping: COMPLETE")+ return True++ except Exception:+ LOG.warning("validate_mapping: validation call failed, defaulting to complete", exc_info=True)+ return True++ async def fill_form(+ self,+ data: dict[str, Any],+ *,+ prompt: str = "Fill out the form",+ ) -> None:+ """Scan page for form fields, map data to fields via LLM, and fill them.++ This is the primary SDK interface for form filling. It composes:+ 1. extract_form_fields() — scan all fields from the DOM (free)+ 2. dynamic_field_map() — one LLM call to map data to fields+ 3. validate_mapping() — one LLM call to check user conditions+ 4. fill_from_mapping() — fill via CSS selectors with AI fallback++ Args:+ data: Dict of data keys/values to fill into the form.+ prompt: User instructions for how to fill the form.+ """+ form_fields = await self.extract_form_fields()++ LOG.info(+ "fill_form: extracted fields",+ field_count=len(form_fields),+ data_keys=list(data.keys())[:10],+ )++ mapping = await self.dynamic_field_map(form_fields, data, prompt=prompt)++ if not await self.validate_mapping(form_fields, mapping, prompt):+ raise ScriptTerminationException("fill_form validation failed: user termination conditions not met")- # QUALITY AUDIT: LLM-based verification (test-only, gated by env var)- if os.environ.get("SCRIPT_QUALITY_AUDIT"):- await self.quality_audit(context, navigation_goal)+ await self.fill_from_mapping(form_fields, mapping, data=data)def _match_field_to_map(self,@@ -1711,8 +1793,8 @@ class SkyvernPage(Page):if best_match:return best_match- # Priority 3: Canonical category match- category = match_field_to_category(field_label)+ # Priority 3: Canonical category match (cloud-only; returns None in OSS)+ category = app.AGENT_FUNCTION.match_field_to_canonical_category(field_label)if category:# Build a synthetic entry from the canonical categoryextracted_value = None@@ -1803,7 +1885,7 @@ class SkyvernPage(Page):# matches any of the mapping_labels (handles "prefer not to answer" -> decline).category_name = entry.get("_canonical")if category_name:- cat_obj = get_category(category_name)+ cat_obj = app.AGENT_FUNCTION.get_canonical_category(category_name)if cat_obj and cat_obj.value_mappings:for mapping_key, mapping_labels in cat_obj.value_mappings:key_matches = mapping_key in candidate_str or candidate_str in mapping_keydiff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex eabd57446..007105e81 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -2,7 +2,7 @@ import asyncioimport copyimport hashlibfrom datetime import timedelta-from typing import Dict, List+from typing import Any, Dict, Listimport structlogfrom playwright.async_api import Frame, Page@@ -625,3 +625,42 @@ class AgentFunction:OSS returns empty string (no hardening)."""return ""++ def detect_ats_platform(self, url_or_domain: str | None) -> str | None:+ """Detect if a URL belongs to a known ATS platform.++ Returns a platform key (e.g., "lever") or None.+ Override in cloud to provide platform detection.+ """+ return None++ def match_field_to_canonical_category(self, field_label: str) -> Any:+ """Match a form field label to a canonical category for zero-LLM matching.++ Returns a CanonicalCategory object or None.+ Override in cloud to provide canonical field matching.+ """+ return None++ def get_canonical_category(self, name: str) -> Any:+ """Look up a canonical category by name.++ Returns a CanonicalCategory object or None.+ Override in cloud to provide canonical category lookup.+ """+ return None++ def build_ats_pipeline_block_fn(self, block: dict, ats_platform: str) -> Any:+ """Build an ATS-optimized script block for a detected platform.++ Returns a libcst FunctionDef or None.+ Override in cloud to provide the pipeline code generator.+ """+ return None++ def get_canonical_categories(self) -> list:+ """Return the list of all canonical categories.++ Returns an empty list in OSS. Override in cloud.+ """+ return []diff --git a/skyvern/forge/prompts/skyvern/form-field-mapper.j2 b/skyvern/forge/prompts/skyvern/form-field-mapper.j2new file mode 100644index 000000000..77255f787--- /dev/null+++ b/skyvern/forge/prompts/skyvern/form-field-mapper.j2@@ -0,0 +1,60 @@+# Goal+You are filling out a form. Map the provided data to every form field on the page.+{% if prompt %}++# User Instructions+The following instructions were provided by the user who created this automation.+Follow these instructions when deciding how to fill fields — they take priority over default behavior.+```+{{ prompt }}+```+{% endif %}++# Provided Data+{% for key, value in data.items() %}+- **{{ key }}**: {{ value }}+{% endfor %}++# Form Fields on Page+{% for field in form_fields %}+{{ loop.index }}. **{{ field.label or "(unlabeled)" }}** ({{ field.type }})+{%- if field.required %} [REQUIRED]{% endif %}+{%- if field.placeholder %} — hint: "{{ field.placeholder }}"{% endif %}+{%- if field.options %} — options: [{{ field.options | join(", ") }}]{% endif %}+{% endfor %}++# Instructions++For EVERY field above, decide the correct value from the provided data.++## CRITICAL — Common mistakes to avoid+- **graduation_year** maps to graduation/graduation date fields. Do NOT put other data (like additional_info) into graduation fields.+- **additional_info** is a generic note — it goes ONLY into "Additional information" or "Cover letter" textareas, NEVER into specific fields like graduation date, name, or phone.+- **needs_sponsorship** answers sponsorship questions DIRECTLY: if needs_sponsorship = "No", then "Will you require sponsorship?" → "No". Do NOT invert it.+- **authorized_to_work** answers authorization questions DIRECTLY: if authorized_to_work = "Yes", then "Are you authorized to work?" → "Yes".+- Each data key should map to at most ONE field. Never reuse the same value for unrelated fields.++## Text fields+- Match semantically: "email" data → "Email address" field, "phone" → "Phone number", "graduation_year" → "Expected graduation date", etc.+- For fields with no matching data (e.g., "Twitter URL" when no twitter data exists), return null.++## Choice fields (dropdown, radio, checkbox)+- Return the EXACT option text from the options list. Do NOT rephrase, abbreviate, 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".+- For EEO/demographic fields with no matching data, pick the "Decline to self-identify" or "I do not want to answer" option.+- For checkboxes, return a JSON array of the exact option labels to check.+- For Yes/No radio buttons: match the provided data value directly. If the data says "Yes", select "Yes". If "No", select "No".++## File upload fields (type: file)+- Look for URL values in the provided data that match file upload fields. For example: a parameter named "resume" with a URL value like "https://example.com/resume.pdf" should be mapped to a "Resume/CV" file upload field.+- Return the URL string as the value — the system will download and upload the file.+- If no matching URL exists in the provided data, return null.++## Fields with no matching data+- For REQUIRED text fields with no matching data, write a brief professional response (1-2 sentences) based on the available data context.+- For OPTIONAL fields with no matching data, return null.++# Output Format+JSON object mapping field number (1-indexed string) to the value to fill.+Return null for file uploads and optional fields with no matching data.+Example: {"1": "John Smith", "2": "[email protected]", "3": null, "4": "Yes", "5": ["Front-end", "Back-end"]}diff --git a/skyvern/forge/prompts/skyvern/script-reviewer-form-filling.j2 b/skyvern/forge/prompts/skyvern/script-reviewer-form-filling.j2index ab02c882f..33d544ac2 100644--- a/skyvern/forge/prompts/skyvern/script-reviewer-form-filling.j2+++ b/skyvern/forge/prompts/skyvern/script-reviewer-form-filling.j2@@ -1,8 +1,8 @@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.+Your job is to produce a function that calls `page.fill_form(context.parameters, prompt="...")` to fill the form dynamically.## MANDATORY RULES-1. Output a FIELD_MAP dict + a function that calls `page.fill_form(FIELD_MAP, context)`.+1. Output a function that calls `page.fill_form(context.parameters, prompt="...")`.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.@@ -146,7 +146,7 @@ When the error or page text suggests the page wasn't ready for interaction, the| `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.+**Note on checkbox/radio groups**: `extract_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 NavigationThe function MUST start with `await page.goto(url)` before calling `fill_form()`.@@ -199,14 +199,14 @@ the URL from the block's `url` field or from the navigation_goal context."prompt": "Select the applicant's gender based on applicant context.",},}- await page.fill_form(FIELD_MAP, context, navigation_goal="{{ navigation_goal }}")+ await page.fill_form(context.parameters, prompt="{{ 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+After `page.fill_form(context.parameters, prompt="...")`, you MAY add individual page method callsfor 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@@ -219,13 +219,13 @@ Use fixups when:- 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.+Do NOT use fixups as a first resort — prefer letting fill_form handle fields. Use fixups only when 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)+- `await page.fill_form(data, prompt="...")` — Scan page fields, map data via LLM, fill all fields+- `await page.extract_form_fields()` — Scan for form fields (called internally by fill_form)### Interaction- `await page.click(selector=, ai=, prompt=)` — Click an elementdiff --git a/skyvern/forge/sdk/db/agent_db.py b/skyvern/forge/sdk/db/agent_db.pyindex 8977d65a3..77e964861 100644--- a/skyvern/forge/sdk/db/agent_db.py+++ b/skyvern/forge/sdk/db/agent_db.py@@ -116,6 +116,8 @@ from skyvern.forge.sdk.schemas.organization_bitwarden_collections import Organizfrom skyvern.forge.sdk.schemas.organizations import (AzureClientSecretCredential,AzureOrganizationAuthToken,+ BitwardenCredential,+ BitwardenOrganizationAuthToken,Organization,OrganizationAuthToken,)@@ -1303,13 +1305,24 @@ class AgentDB(BaseAlchemyDB):token_type: Literal["azure_client_secret_credential"],) -> AzureOrganizationAuthToken | None: ...+ @overload+ async def get_valid_org_auth_token( # type: ignore+ self,+ organization_id: str,+ token_type: Literal["bitwarden_credential"],+ ) -> BitwardenOrganizationAuthToken | None: ...+async def get_valid_org_auth_token(self,organization_id: str,token_type: Literal[- "api", "onepassword_service_account", "azure_client_secret_credential", "custom_credential_service"+ "api",+ "onepassword_service_account",+ "azure_client_secret_credential",+ "custom_credential_service",+ "bitwarden_credential",],- ) -> OrganizationAuthToken | AzureOrganizationAuthToken | None:+ ) -> OrganizationAuthToken | AzureOrganizationAuthToken | BitwardenOrganizationAuthToken | None:try:async with self.Session() as session:if token := (@@ -1395,13 +1408,17 @@ class AgentDB(BaseAlchemyDB):self,organization_id: str,token_type: OrganizationAuthTokenType,- token: str | AzureClientSecretCredential,+ token: str | AzureClientSecretCredential | BitwardenCredential,encrypted_method: EncryptMethod | None = None,- ) -> OrganizationAuthToken:+ ) -> OrganizationAuthToken | AzureOrganizationAuthToken | BitwardenOrganizationAuthToken:if token_type is OrganizationAuthTokenType.azure_client_secret_credential:if not isinstance(token, AzureClientSecretCredential):raise TypeError("Expected AzureClientSecretCredential for this token_type")plaintext_token = token.model_dump_json()+ elif token_type is OrganizationAuthTokenType.bitwarden_credential:+ if not isinstance(token, BitwardenCredential):+ raise TypeError("Expected BitwardenCredential for this token_type")+ plaintext_token = token.model_dump_json()else:if not isinstance(token, str):raise TypeError("Expected str token for this token_type")@@ -1450,6 +1467,55 @@ class AgentDB(BaseAlchemyDB):LOG.error("UnexpectedError", exc_info=True)raise+ async def replace_org_auth_token(+ self,+ organization_id: str,+ token_type: OrganizationAuthTokenType,+ token: str | AzureClientSecretCredential | BitwardenCredential,+ encrypted_method: EncryptMethod | None = None,+ ) -> OrganizationAuthToken | AzureOrganizationAuthToken | BitwardenOrganizationAuthToken:+ """Atomically invalidate existing tokens and create a new one in a single transaction."""+ if token_type is OrganizationAuthTokenType.azure_client_secret_credential:+ if not isinstance(token, AzureClientSecretCredential):+ raise TypeError("Expected AzureClientSecretCredential for this token_type")+ plaintext_token = token.model_dump_json()+ elif token_type is OrganizationAuthTokenType.bitwarden_credential:+ if not isinstance(token, BitwardenCredential):+ raise TypeError("Expected BitwardenCredential for this token_type")+ plaintext_token = token.model_dump_json()+ else:+ if not isinstance(token, str):+ raise TypeError("Expected str token for this token_type")+ plaintext_token = token++ encrypted_token = ""+ if encrypted_method is not None:+ encrypted_token = await encryptor.encrypt(plaintext_token, encrypted_method)+ plaintext_token = ""++ async with self.Session() as session:+ # Invalidate existing tokens+ await session.execute(+ update(OrganizationAuthTokenModel)+ .filter_by(organization_id=organization_id)+ .filter_by(token_type=token_type)+ .filter_by(valid=True)+ .values(valid=False)+ )+ # Create new token+ auth_token = OrganizationAuthTokenModel(+ organization_id=organization_id,+ token_type=token_type,+ token=plaintext_token,+ encrypted_token=encrypted_token,+ encrypted_method=encrypted_method.value if encrypted_method is not None else "",+ )+ session.add(auth_token)+ await session.commit()+ await session.refresh(auth_token)++ return await convert_to_organization_auth_token(auth_token, token_type)+async def get_artifacts_for_task_v2(self,task_v2_id: str,diff --git a/skyvern/forge/sdk/db/enums.py b/skyvern/forge/sdk/db/enums.pyindex 3f758d43c..a0267d16f 100644--- a/skyvern/forge/sdk/db/enums.py+++ b/skyvern/forge/sdk/db/enums.py@@ -6,6 +6,7 @@ class OrganizationAuthTokenType(StrEnum):onepassword_service_account = "onepassword_service_account"azure_client_secret_credential = "azure_client_secret_credential"custom_credential_service = "custom_credential_service"+ bitwarden_credential = "bitwarden_credential"class TaskType(StrEnum):diff --git a/skyvern/forge/sdk/db/utils.py b/skyvern/forge/sdk/db/utils.pyindex f839956d1..d772f3ada 100644--- a/skyvern/forge/sdk/db/utils.py+++ b/skyvern/forge/sdk/db/utils.py@@ -36,6 +36,8 @@ from skyvern.forge.sdk.models import Step, StepStatusfrom skyvern.forge.sdk.schemas.organizations import (AzureClientSecretCredential,AzureOrganizationAuthToken,+ BitwardenCredential,+ BitwardenOrganizationAuthToken,Organization,OrganizationAuthToken,)@@ -287,7 +289,7 @@ def convert_to_organization(org_model: OrganizationModel) -> Organization:async def convert_to_organization_auth_token(org_auth_token: OrganizationAuthTokenModel, token_type: str-) -> OrganizationAuthToken | AzureOrganizationAuthToken:+) -> OrganizationAuthToken | AzureOrganizationAuthToken | BitwardenOrganizationAuthToken:token = org_auth_token.tokenif org_auth_token.encrypted_token and org_auth_token.encrypted_method:token = await encryptor.decrypt(org_auth_token.encrypted_token, EncryptMethod(org_auth_token.encrypted_method))@@ -303,6 +305,17 @@ async def convert_to_organization_auth_token(created_at=org_auth_token.created_at,modified_at=org_auth_token.modified_at,)+ elif token_type == OrganizationAuthTokenType.bitwarden_credential:+ credential = BitwardenCredential.model_validate_json(token)+ return BitwardenOrganizationAuthToken(+ id=org_auth_token.id,+ organization_id=org_auth_token.organization_id,+ token_type=OrganizationAuthTokenType(org_auth_token.token_type),+ credential=credential,+ valid=org_auth_token.valid,+ created_at=org_auth_token.created_at,+ modified_at=org_auth_token.modified_at,+ )else:return OrganizationAuthToken(id=org_auth_token.id,diff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.pyindex b04bee8df..5c6018779 100644--- a/skyvern/forge/sdk/routes/credentials.py+++ b/skyvern/forge/sdk/routes/credentials.py@@ -71,7 +71,12 @@ from skyvern.forge.sdk.schemas.credentials import ()from skyvern.forge.sdk.schemas.organizations import (AzureClientSecretCredentialResponse,+ BitwardenCredentialResponse,+ BitwardenCredentialSafe,+ BitwardenOrganizationAuthToken,+ BitwardenOrganizationAuthTokenSafe,CreateAzureClientSecretCredentialRequest,+ CreateBitwardenCredentialRequest,CreateCustomCredentialServiceConfigRequest,CreateOnePasswordTokenRequest,CreateOnePasswordTokenResponse,@@ -1504,6 +1509,119 @@ async def update_onepassword_token()+def _to_safe_bitwarden_response(auth_token: BitwardenOrganizationAuthToken) -> BitwardenCredentialResponse:+ """Strip master_password from the response for security."""+ safe_token = BitwardenOrganizationAuthTokenSafe(+ id=auth_token.id,+ organization_id=auth_token.organization_id,+ token_type=auth_token.token_type,+ valid=auth_token.valid,+ created_at=auth_token.created_at,+ modified_at=auth_token.modified_at,+ credential=BitwardenCredentialSafe(email=auth_token.credential.email),+ )+ return BitwardenCredentialResponse(token=safe_token)+++@base_router.get(+ "/credentials/bitwarden/get",+ response_model=BitwardenCredentialResponse,+ summary="Get Bitwarden credential",+ description="Retrieves the current Bitwarden credential for the organization. The master_password is never returned for security.",+ include_in_schema=False,+)+@base_router.get(+ "/credentials/bitwarden/get/",+ response_model=BitwardenCredentialResponse,+ include_in_schema=False,+)+async def get_bitwarden_credential(+ current_org: Organization = Depends(org_auth_service.get_current_org),+) -> BitwardenCredentialResponse:+ """+ Get the current Bitwarden credential for the organization.+ """+ try:+ auth_token = await app.DATABASE.get_valid_org_auth_token(+ organization_id=current_org.organization_id,+ token_type=OrganizationAuthTokenType.bitwarden_credential.value,+ )+ if not auth_token:+ raise HTTPException(+ status_code=404,+ detail="No Bitwarden credential found for this organization",+ )++ return _to_safe_bitwarden_response(auth_token)++ except HTTPException:+ raise+ except Exception as e:+ LOG.error(+ "Failed to get Bitwarden credential",+ organization_id=current_org.organization_id,+ error=str(e),+ exc_info=True,+ )+ raise HTTPException(+ status_code=500,+ detail="Failed to get Bitwarden credential",+ )+++@base_router.post(+ "/credentials/bitwarden/create",+ response_model=BitwardenCredentialResponse,+ summary="Create or update Bitwarden credential",+ description="Creates or updates a Bitwarden credential for the current organization. Only one valid credential is allowed per organization.",+ include_in_schema=False,+)+@base_router.post(+ "/credentials/bitwarden/create/",+ response_model=BitwardenCredentialResponse,+ include_in_schema=False,+)+async def update_bitwarden_credential(+ request: CreateBitwardenCredentialRequest,+ current_org: Organization = Depends(org_auth_service.get_current_org),+) -> BitwardenCredentialResponse:+ """+ Create or update a Bitwarden credential for the current organization.++ Only one valid Bitwarden credential exists per organization.+ If a valid credential already exists, it will be invalidated before creating the new one.+ """+ try:+ # Atomically invalidate old + create new in a single transaction+ auth_token = await app.DATABASE.replace_org_auth_token(+ organization_id=current_org.organization_id,+ token_type=OrganizationAuthTokenType.bitwarden_credential,+ token=request.credential,+ )++ LOG.info(+ "Created or updated Bitwarden credential",+ organization_id=current_org.organization_id,+ token_id=auth_token.id,+ )++ return _to_safe_bitwarden_response(auth_token)++ except HTTPException:+ raise+ except Exception as e:+ LOG.error(+ "Failed to create or update Bitwarden credential",+ organization_id=current_org.organization_id,+ error=str(e),+ exc_info=True,+ )+ raise HTTPException(+ status_code=500,+ detail="Failed to create or update Bitwarden credential",+ )++@base_router.get("/credentials/azure_credential/get",response_model=AzureClientSecretCredentialResponse,diff --git a/skyvern/forge/sdk/routes/sdk.py b/skyvern/forge/sdk/routes/sdk.pyindex 060ee53f7..97e5e0727 100644--- a/skyvern/forge/sdk/routes/sdk.py+++ b/skyvern/forge/sdk/routes/sdk.py@@ -33,6 +33,7 @@ LOG = structlog.get_logger()summary="Run an SDK action",description="Execute a single SDK action with the specified parameters",tags=["SDK"],+ include_in_schema=False,openapi_extra={"x-fern-sdk-method-name": "run_sdk_action",},diff --git a/skyvern/forge/sdk/schemas/organizations.py b/skyvern/forge/sdk/schemas/organizations.pyindex 36ef7dd62..59e733462 100644--- a/skyvern/forge/sdk/schemas/organizations.py+++ b/skyvern/forge/sdk/schemas/organizations.py@@ -1,6 +1,6 @@from datetime import datetime-from pydantic import BaseModel, ConfigDict, Field+from pydantic import BaseModel, ConfigDict, EmailStr, Fieldfrom skyvern.forge.sdk.db.enums import OrganizationAuthTokenType@@ -46,6 +46,48 @@ class AzureOrganizationAuthToken(OrganizationAuthTokenBase):credential: AzureClientSecretCredential+class BitwardenCredential(BaseModel):+ email: EmailStr = Field(..., description="Bitwarden account email")+ master_password: str = Field(..., min_length=1, description="Bitwarden master password")+++class BitwardenCredentialSafe(BaseModel):+ """Response-safe view of BitwardenCredential — master_password is never returned."""++ email: EmailStr+++class BitwardenOrganizationAuthToken(OrganizationAuthTokenBase):+ """Represents OrganizationAuthToken for Bitwarden; defined by 2 fields: email and master_password"""++ credential: BitwardenCredential+++class BitwardenOrganizationAuthTokenSafe(OrganizationAuthTokenBase):+ """Response-safe view — omits master_password for security."""++ credential: BitwardenCredentialSafe+++class CreateBitwardenCredentialRequest(BaseModel):+ """Request model for creating or updating a Bitwarden credential."""++ credential: BitwardenCredential+++class BitwardenCredentialResponse(BaseModel):+ """Response model for Bitwarden credential operations.++ The master_password is never returned in API responses for security.+ To update credentials, submit a new POST request with the full credential.+ """++ token: BitwardenOrganizationAuthTokenSafe = Field(+ ...,+ description="The Bitwarden credential (master_password redacted for security)",+ )++class CreateOnePasswordTokenRequest(BaseModel):"""Request model for creating or updating a 1Password service account token."""diff --git a/skyvern/forge/sdk/services/bitwarden.py b/skyvern/forge/sdk/services/bitwarden.pyindex 3a817f722..2349736a9 100644--- a/skyvern/forge/sdk/services/bitwarden.py+++ b/skyvern/forge/sdk/services/bitwarden.py@@ -184,8 +184,8 @@ class BitwardenService:shell_subprocess = Nonetry:async with asyncio.timeout(timeout):- shell_subprocess = await asyncio.create_subprocess_shell(- " ".join(command),+ shell_subprocess = await asyncio.create_subprocess_exec(+ *command,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,env=env,@@ -240,6 +240,7 @@ class BitwardenService:item_id: str | None = None,max_retries: int = settings.BITWARDEN_MAX_RETRIES,timeout: int = settings.BITWARDEN_TIMEOUT_SECONDS,+ email: str | None = None,) -> dict[str, str]:"""Get the secret value from the Bitwarden CLI.@@ -267,6 +268,7 @@ class BitwardenService:collection_id=collection_id,item_id=item_id,timeout=timeout,+ email=email,)except BitwardenAccessDeniedError as e:raise e@@ -308,12 +310,13 @@ class BitwardenService:collection_id: str | None = None,item_id: str | None = None,timeout: int = 60,+ email: str | None = None,) -> dict[str, str]:"""Get the secret value from the Bitwarden CLI."""try:- await BitwardenService.login(client_id, client_secret)+ await BitwardenService.login(client_id, client_secret, email=email, master_password=master_password)await BitwardenService.sync()session_key = await BitwardenService.unlock(master_password)@@ -440,6 +443,7 @@ class BitwardenService:remaining_retries: int = settings.BITWARDEN_MAX_RETRIES,timeout: int = settings.BITWARDEN_TIMEOUT_SECONDS,fail_reasons: list[str] = [],+ email: str | None = None,) -> dict[str, str]:"""Get the secret value from the Bitwarden CLI.@@ -459,6 +463,7 @@ class BitwardenService:collection_id=collection_id,identity_key=identity_key,identity_fields=identity_fields,+ email=email,)except BitwardenAccessDeniedError as e:raise e@@ -483,6 +488,7 @@ class BitwardenService:# Double the timeout for the next retrytimeout=timeout * 2,fail_reasons=fail_reasons + [f"{type(e).__name__}: {str(e)}"],+ email=email,)@staticmethod@@ -495,12 +501,13 @@ class BitwardenService:identity_fields: list[str],bw_organization_id: str | None,bw_collection_ids: list[str] | None,+ email: str | None = None,) -> dict[str, str]:"""Get the sensitive information from the Bitwarden CLI."""try:- await BitwardenService.login(client_id, client_secret)+ await BitwardenService.login(client_id, client_secret, email=email, master_password=master_password)await BitwardenService.sync()session_key = await BitwardenService.unlock(master_password)@@ -565,16 +572,28 @@ class BitwardenService:await BitwardenService.logout()@staticmethod- async def login(client_id: str | None, client_secret: str | None) -> None:+ async def login(+ client_id: str | None,+ client_secret: str | None,+ email: str | None = None,+ master_password: str | None = None,+ ) -> None:"""Log in to the Bitwarden CLI.++ Supports two auth modes:+ 1. Email + master_password (preferred when available)+ 2. API key (client_id + client_secret) via --apikey flag"""+ bw_email = email or settings.BITWARDEN_EMAIL+ bw_master_password = master_password or settings.BITWARDEN_MASTER_PASSWORDenv = {"BW_CLIENTID": client_id or "","BW_CLIENTSECRET": client_secret or "",+ "BW_PASSWORD": bw_master_password or "",}- if settings.BITWARDEN_EMAIL and settings.BITWARDEN_MASTER_PASSWORD:- login_command = ["bw", "login", settings.BITWARDEN_EMAIL, settings.BITWARDEN_MASTER_PASSWORD]+ if bw_email and bw_master_password:+ login_command = ["bw", "login", bw_email, "--passwordenv", "BW_PASSWORD"]else:login_command = ["bw", "login", "--apikey"]login_result = await BitwardenService.run_command(login_command, env)@@ -647,12 +666,13 @@ class BitwardenService:bw_collection_ids: list[str] | None,collection_id: str,item_id: str,+ email: str | None = None,) -> dict[str, str]:"""Get the credit card data from the Bitwarden CLI."""try:- await BitwardenService.login(client_id, client_secret)+ await BitwardenService.login(client_id, client_secret, email=email, master_password=master_password)await BitwardenService.sync()session_key = await BitwardenService.unlock(master_password)@@ -725,6 +745,7 @@ class BitwardenService:item_id: str,remaining_retries: int = settings.BITWARDEN_MAX_RETRIES,fail_reasons: list[str] = [],+ email: str | None = None,) -> dict[str, str]:"""Get the credit card data from the Bitwarden CLI.@@ -744,6 +765,7 @@ class BitwardenService:bw_collection_ids=bw_collection_ids,collection_id=collection_id,item_id=item_id,+ email=email,)except BitwardenAccessDeniedError as e:raise e@@ -765,6 +787,7 @@ class BitwardenService:item_id=item_id,remaining_retries=remaining_retries,fail_reasons=fail_reasons + [f"{type(e).__name__}: {str(e)}"],+ email=email,)@staticmethoddiff --git a/skyvern/forge/sdk/workflow/context_manager.py b/skyvern/forge/sdk/workflow/context_manager.pyindex c43bdca1d..592684a2b 100644--- a/skyvern/forge/sdk/workflow/context_manager.py+++ b/skyvern/forge/sdk/workflow/context_manager.py@@ -605,13 +605,40 @@ class WorkflowRunContext:if item.notes:self._add_secret_parameter_value(parameter, "notes", item.notes)- async def register_bitwarden_login_credential_parameter_value(+ async def _get_bitwarden_credentials(self,- parameter: BitwardenLoginCredentialParameter,organization: Organization,- ) -> None:+ parameter: BitwardenLoginCredentialParameter+ | BitwardenSensitiveInformationParameter+ | BitwardenCreditCardDataParameter,+ ) -> tuple[str | None, str | None, str | None, str | None]:+ """Get Bitwarden credentials, checking org-level token first, then falling back to env vars / AWS secrets.++ Returns: (client_id, client_secret, master_password, email)++ Priority order:+ 1. Per-org Bitwarden credential (from organization_auth_tokens table) — always wins if present+ 2. Global env vars (BITWARDEN_CLIENT_ID, etc.) or AWS secrets (from workflow parameter keys)++ When an org-level token is configured with email auth, client_id and client_secret will be None+ and the email will be used for `bw login <email> --passwordenv BW_PASSWORD`. To fall back to+ env vars / AWS secrets for a specific workflow, the org-level credential must be deleted.+ """+ # Check for per-org Bitwarden credential first+ org_bw_token = await app.DATABASE.get_valid_org_auth_token(+ organization_id=organization.organization_id,+ token_type=OrganizationAuthTokenType.bitwarden_credential.value,+ )+ if org_bw_token:+ return (+ None, # client_id — not used in email auth+ None, # client_secret — not used in email auth+ org_bw_token.credential.master_password,+ org_bw_token.credential.email,+ )++ # Fall back to env vars / AWS secretstry:- # Get the Bitwarden login credentials from AWS secretsclient_id = settings.BITWARDEN_CLIENT_ID or await self._aws_client.get_secret(parameter.bitwarden_client_id_aws_secret_key)@@ -625,9 +652,20 @@ class WorkflowRunContext:LOG.error(f"Failed to get Bitwarden login credentials from AWS secrets. Error: {e}")raise e- if not client_id and not settings.BITWARDEN_EMAIL:+ return client_id, client_secret, master_password, None++ async def register_bitwarden_login_credential_parameter_value(+ self,+ parameter: BitwardenLoginCredentialParameter,+ organization: Organization,+ ) -> None:+ client_id, client_secret, master_password, email = await self._get_bitwarden_credentials(+ organization, parameter+ )++ if not client_id and not email and not settings.BITWARDEN_EMAIL:raise ValueError("Bitwarden client ID not found")- if not client_secret and not settings.BITWARDEN_EMAIL:+ if not client_secret and not email and not settings.BITWARDEN_EMAIL:raise ValueError("Bitwarden client secret not found")if not master_password:raise ValueError("Bitwarden master password not found")@@ -650,6 +688,7 @@ class WorkflowRunContext:url,collection_id=collection_id,item_id=item_id,+ email=email,)if secret_credentials:self.secrets[BitwardenConstants.BW_ORGANIZATION_ID] = organization.bw_organization_id@@ -740,24 +779,13 @@ class WorkflowRunContext:parameter: BitwardenSensitiveInformationParameter,organization: Organization,) -> None:- try:- # Get the Bitwarden login credentials from AWS secrets- client_id = settings.BITWARDEN_CLIENT_ID or await self._aws_client.get_secret(- parameter.bitwarden_client_id_aws_secret_key- )- client_secret = settings.BITWARDEN_CLIENT_SECRET or await self._aws_client.get_secret(- parameter.bitwarden_client_secret_aws_secret_key- )- master_password = settings.BITWARDEN_MASTER_PASSWORD or await self._aws_client.get_secret(- parameter.bitwarden_master_password_aws_secret_key- )- except Exception as e:- LOG.error(f"Failed to get Bitwarden login credentials from AWS secrets. Error: {e}")- raise e+ client_id, client_secret, master_password, email = await self._get_bitwarden_credentials(+ organization, parameter+ )- if not client_id and not settings.BITWARDEN_EMAIL:+ if not client_id and not email and not settings.BITWARDEN_EMAIL:raise ValueError("Bitwarden client ID not found")- if not client_secret and not settings.BITWARDEN_EMAIL:+ if not client_secret and not email and not settings.BITWARDEN_EMAIL:raise ValueError("Bitwarden client secret not found")if not master_password:raise ValueError("Bitwarden master password not found")@@ -780,6 +808,7 @@ class WorkflowRunContext:collection_id,bitwarden_identity_key,parameter.bitwarden_identity_fields,+ email=email,)if sensitive_values:self.secrets[BitwardenConstants.BW_ORGANIZATION_ID] = organization.bw_organization_id@@ -809,24 +838,13 @@ class WorkflowRunContext:parameter: BitwardenCreditCardDataParameter,organization: Organization,) -> None:- try:- # Get the Bitwarden login credentials from AWS secrets- client_id = settings.BITWARDEN_CLIENT_ID or await self._aws_client.get_secret(- parameter.bitwarden_client_id_aws_secret_key- )- client_secret = settings.BITWARDEN_CLIENT_SECRET or await self._aws_client.get_secret(- parameter.bitwarden_client_secret_aws_secret_key- )- master_password = settings.BITWARDEN_MASTER_PASSWORD or await self._aws_client.get_secret(- parameter.bitwarden_master_password_aws_secret_key- )- except Exception as e:- LOG.error(f"Failed to get Bitwarden login credentials from AWS secrets. Error: {e}")- raise e+ client_id, client_secret, master_password, email = await self._get_bitwarden_credentials(+ organization, parameter+ )- if not client_id and not settings.BITWARDEN_EMAIL:+ if not client_id and not email and not settings.BITWARDEN_EMAIL:raise ValueError("Bitwarden client ID not found")- if not client_secret and not settings.BITWARDEN_EMAIL:+ if not client_secret and not email and not settings.BITWARDEN_EMAIL:raise ValueError("Bitwarden client secret not found")if not master_password:raise ValueError("Bitwarden master password not found")@@ -850,6 +868,7 @@ class WorkflowRunContext:organization.bw_collection_ids,collection_id,item_id,+ email=email,)if not credit_card_data:raise ValueError("Credit card data not found in Bitwarden")diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 5e2cee47e..98d2e0b46 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -5227,9 +5227,9 @@ class WorkflowService:) -> bool:"""Determine whether this run should attempt to execute cached scripts.- Priority: run-level run_with > workflow-level run_with > default (agent).- The adaptive_caching flag does NOT independently force code mode — it only- controls whether a code run uses v1 or v2 (see is_adaptive_caching()).+ Priority: run-level run_with > workflow-level run_with > adaptive_caching fallback > default (agent).+ When adaptive_caching is enabled at the workflow level and no explicit run_with+ is set, the run defaults to code mode so cached scripts are actually used."""if workflow_run.run_with in ("code", "code_v2"):return True@@ -5237,5 +5237,10 @@ class WorkflowService:return Falseif workflow.run_with in ("code", "code_v2"):return True- # workflow.run_with is "agent" or null — default to agent+ if workflow.run_with == "agent":+ return False+ # No explicit run_with on either workflow or run — fall back to+ # adaptive_caching: if the workflow has caching enabled, run code.+ if workflow.adaptive_caching:+ return Truereturn Falsediff --git a/skyvern/services/script_reviewer.py b/skyvern/services/script_reviewer.pyindex 755767f51..f67c0d0b9 100644--- a/skyvern/services/script_reviewer.py+++ b/skyvern/services/script_reviewer.py@@ -38,9 +38,12 @@ _ALLOWED_PAGE_API: frozenset[str] = frozenset("extract","validate","classify",- "scan_form_fields",+ "extract_form_fields",# Form filling"fill_form",+ "dynamic_field_map",+ "fill_from_mapping",+ "validate_mapping",# Lifecycle"complete","wait",diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.pyindex 7349df596..7d7493c00 100644--- a/skyvern/services/script_service.py+++ b/skyvern/services/script_service.py@@ -1752,6 +1752,11 @@ async def run_task()return output+ except ScriptTerminationException:+ # Explicit termination from script (e.g., ATS validation failure).+ # Do NOT fall back to AI — the script intentionally terminated.+ LOG.info("Script requested termination. Not falling back to AI.")+ raiseexcept Exception as e:LOG.exception("Failed to run task block. Falling back to AI run.")await _fallback_to_ai_run(diff --git a/skyvern/services/workflow_script_service.py b/skyvern/services/workflow_script_service.pyindex 7de732f84..552fc309a 100644--- a/skyvern/services/workflow_script_service.py+++ b/skyvern/services/workflow_script_service.py@@ -192,12 +192,23 @@ async def get_workflow_script(# Auto-enrich with domain when using the default cache key.# This ensures the same workflow running against different sites gets- # separate cached scripts (e.g., "default:fanr.gov.ae" vs "default:search.gov.hk").+ # separate cached scripts. For known platform patterns, a platform-level+ # key is used instead of the domain so all employers on the same platform+ # share one cached script.if rendered_cache_key_value in ("default", ""):domain = _extract_first_block_domain(workflow, parameters)if domain:+ ats_platform = app.AGENT_FUNCTION.detect_ats_platform(domain)+ if ats_platform:+ LOG.info(+ "Code 2.0: platform detected, using platform-level cache key",+ ats_platform=ats_platform,+ original_domain=domain,+ workflow_permanent_id=workflow.workflow_permanent_id,+ )+ cache_segment = ats_platform if ats_platform else domainrendered_cache_key_value = (- f"{rendered_cache_key_value}:{domain}" if rendered_cache_key_value else domain+ f"{rendered_cache_key_value}:{cache_segment}" if rendered_cache_key_value else cache_segment)# Namespace adaptive caching (Code 2.0) scripts with :v2 suffix so theydiff --git a/tests/unit/test_should_run_script.py b/tests/unit/test_should_run_script.pyindex ce5364e5d..6f44f81f6 100644--- a/tests/unit/test_should_run_script.py+++ b/tests/unit/test_should_run_script.py@@ -1,8 +1,8 @@"""Tests for WorkflowService.should_run_script() and script reviewer gating.Verifies the priority chain:- run-level run_with > workflow-level run_with > default (agent).-adaptive_caching alone does NOT force code mode.+ run-level run_with > workflow-level run_with > adaptive_caching fallback > default (agent).+When adaptive_caching=True and no explicit run_with is set, the run defaults to code mode.Also verifies that the script reviewer only fires when the script was actuallyexecuted (should_run_script=True), not merely when adaptive caching is enabled.@@ -57,7 +57,7 @@ def service():class TestShouldRunScript:- """Run-level run_with takes priority, then workflow-level, then defaults to agent."""+ """Run-level run_with takes priority, then workflow-level, then adaptive_caching fallback, then agent."""def test_run_code_overrides_workflow_agent(self, service):wf = _make_workflow(run_with="agent")@@ -74,6 +74,12 @@ class TestShouldRunScript:wr = _make_run(run_with="agent")assert service.should_run_script(wf, wr) is False+ def test_run_agent_overrides_adaptive_caching(self, service):+ """Explicit run-level agent overrides adaptive_caching fallback."""+ wf = _make_workflow(run_with=None, adaptive_caching=True)+ wr = _make_run(run_with="agent")+ assert service.should_run_script(wf, wr) is False+def test_workflow_code_with_null_run(self, service):wf = _make_workflow(run_with="code")wr = _make_run(run_with=None)@@ -84,23 +90,23 @@ class TestShouldRunScript:wr = _make_run(run_with=None)assert service.should_run_script(wf, wr) is False- def test_both_null_defaults_to_agent(self, service):- """When neither workflow nor run specifies run_with, default to agent (no code)."""- wf = _make_workflow(run_with=None)+ def test_workflow_agent_overrides_adaptive_caching(self, service):+ """Explicit workflow-level agent takes priority over adaptive_caching."""+ wf = _make_workflow(run_with="agent", adaptive_caching=True)wr = _make_run(run_with=None)assert service.should_run_script(wf, wr) is False- def test_adaptive_caching_alone_does_not_force_code(self, service):- """adaptive_caching=True with run_with=null should NOT force code mode (SKY-8390)."""- wf = _make_workflow(run_with=None, adaptive_caching=True)+ def test_both_null_defaults_to_agent(self, service):+ """When neither workflow nor run specifies run_with and no adaptive_caching, default to agent."""+ wf = _make_workflow(run_with=None)wr = _make_run(run_with=None)assert service.should_run_script(wf, wr) is False- def test_adaptive_caching_with_workflow_agent_does_not_force_code(self, service):- """adaptive_caching=True with explicit run_with=agent should NOT force code."""- wf = _make_workflow(run_with="agent", adaptive_caching=True)+ def test_adaptive_caching_defaults_to_code(self, service):+ """adaptive_caching=True with run_with=null should default to code mode."""+ wf = _make_workflow(run_with=None, adaptive_caching=True)wr = _make_run(run_with=None)- assert service.should_run_script(wf, wr) is False+ assert service.should_run_script(wf, wr) is Truedef test_adaptive_caching_with_workflow_code_runs_code(self, service):"""adaptive_caching=True with run_with=code should run code (v1→v2 upgrade is separate)."""@@ -127,7 +133,7 @@ class TestScriptReviewerGate:[("code_v2", True, True),("code_v2", False, True), # is_adaptive_caching=True for code_v2 regardless- (None, True, False), # the key case: adaptive caching on but script not executed+ (None, True, True), # adaptive_caching=True defaults to code mode now(None, False, False),("agent", True, False),("agent", False, False),