shiplightai 0.1.95 → 0.1.96

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var Hl=Object.defineProperty;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var xt=(e,t)=>{for(var i in t)Hl(e,i,{get:t[i],enumerable:!0})};function Y(){return za.getConfig()}var Wl,za,Si,te=v(()=>{"use strict";Wl=class{constructor(){this.config=this.getDefaultConfig()}getDefaultConfig(){return{logLevel:1,debugAgent:!1,testResultsJsonPath:void 0,consoleLogsPath:void 0}}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e}}resetConfig(){this.config=this.getDefaultConfig()}get(e){return this.config[e]}set(e,t){this.config[e]=t}},za=new Wl,Si=za});var jl,Ul,f,B=v(()=>{"use strict";te();jl=class{getLevel(){return Si.get("logLevel")}isStderrOnly(){return Si.get("stderrOnly")===!0}debug(...e){this.getLevel()<=0&&(this.isStderrOnly()?console.error("[DEBUG]",...e):console.log("[DEBUG]",...e))}info(...e){this.getLevel()<=1&&(this.isStderrOnly()?console.error("[INFO]",...e):console.log("[INFO]",...e))}log(...e){this.info(...e)}warn(...e){this.getLevel()<=2&&console.warn("[WARN]",...e)}error(...e){this.getLevel()<=3&&console.error("[ERROR]",...e)}setLevel(e){Si.set("logLevel",e)}},Ul=new jl,f=Ul});import{appendFileSync as Va}from"fs";var Bl,T,ae=v(()=>{"use strict";te();Bl=class{constructor(){this.initialized=!1}init(){if(this.initialized)return;let e=Y().agentLogPath;if(e)try{Va(e,`
1
+ var Hl=Object.defineProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var xt=(e,t)=>{for(var i in t)Hl(e,i,{get:t[i],enumerable:!0})};function Y(){return za.getConfig()}var Wl,za,Si,te=b(()=>{"use strict";Wl=class{constructor(){this.config=this.getDefaultConfig()}getDefaultConfig(){return{logLevel:1,debugAgent:!1,testResultsJsonPath:void 0,consoleLogsPath:void 0}}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e}}resetConfig(){this.config=this.getDefaultConfig()}get(e){return this.config[e]}set(e,t){this.config[e]=t}},za=new Wl,Si=za});var jl,Ul,f,B=b(()=>{"use strict";te();jl=class{getLevel(){return Si.get("logLevel")}isStderrOnly(){return Si.get("stderrOnly")===!0}debug(...e){this.getLevel()<=0&&(this.isStderrOnly()?console.error("[DEBUG]",...e):console.log("[DEBUG]",...e))}info(...e){this.getLevel()<=1&&(this.isStderrOnly()?console.error("[INFO]",...e):console.log("[INFO]",...e))}log(...e){this.info(...e)}warn(...e){this.getLevel()<=2&&console.warn("[WARN]",...e)}error(...e){this.getLevel()<=3&&console.error("[ERROR]",...e)}setLevel(e){Si.set("logLevel",e)}},Ul=new jl,f=Ul});import{appendFileSync as Va}from"fs";var Bl,T,ae=b(()=>{"use strict";te();Bl=class{constructor(){this.initialized=!1}init(){if(this.initialized)return;let e=Y().agentLogPath;if(e)try{Va(e,`
2
2
  === Agent Execution Log ===
3
3
  Started: ${new Date().toISOString()}
4
4
 
@@ -11,7 +11,7 @@ ${e}`)}prompt(e,t){this.section("LLM Prompt"),this.log(`System Prompt:
11
11
  ${e}`),this.log(`
12
12
  User Prompt:
13
13
  ${t}`)}response(e){this.log(`LLM Response:
14
- ${e}`)}error(e,t){this.log(`ERROR: ${e}`),t&&(this.log(`Error details: ${t.message}`),t.stack&&this.log(`Stack: ${t.stack}`))}isEnabled(){return!!Y().agentLogPath}},T=new Bl});var Nn,Gl,Kl,zl,Xa,Ei,On,Ja,Ln,ve=v(()=>{"use strict";Nn=Object.defineProperty,Gl=Object.getOwnPropertyDescriptor,Kl=Object.getOwnPropertyNames,zl=Object.prototype.hasOwnProperty,Xa=(e,t)=>()=>(e&&(t=e(e=0)),t),Ei=(e,t)=>{for(var i in t)Nn(e,i,{get:t[i],enumerable:!0})},On=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Kl(t))!zl.call(e,a)&&a!==i&&Nn(e,a,{get:()=>t[a],enumerable:!(n=Gl(t,a))||n.enumerable});return e},Ja=(e,t,i)=>(On(e,t,"default"),i&&On(i,t,"default")),Ln=e=>On(Nn({},"__esModule",{value:!0}),e)});function R(e,t){return t??e?.getActionSettings()?.action_timeout_ms??Rn}function Vl(e){return e.replace(/\r\n/g," ").replace(/\n/g," ").replace(/\r/g," ").trim()}function F(e,t){let i=Ne(t);return i?new Function("page",`return ${i}`)(e):null}async function Dn(e,t=[]){let i=e;for(let n of t){let a=await i.locator(n).elementHandle();if(!a)return null;let o=await a.contentFrame();if(await a.dispose(),!o)return null;i=o}return i}function Xl(e){let t={action_data:e.action_data};return e.locator&&(t.locator=e.locator),e.xpath&&(t.xpath=e.xpath),e.frame_path&&(t.frame_path=e.frame_path),t}function Jl(e){let t=e.frame_path;return!t||t.length===0?"page":`page.frameLocator('${t[0]}')`}function Yl(e){let t=e.xpath;return typeof t=="string"&&t.trim()?!t.startsWith("xpath=")&&!t.startsWith("/")&&!t.startsWith("//")?`xpath=//${t}`:t.startsWith("xpath=")?t:`xpath=${t}`:null}function Ne(e){let t=Jl(e),i=e.locator;if(typeof i=="string"&&i.trim())return i=i.trim(),i.endsWith("first()")?`${t}.${i}`:`${t}.${i}.first()`;let n=Yl(e);if(n){let a=JSON.stringify(n);return`${t}.locator(${a}).first()`}return null}var Ti,_t,Rn,pe,C,G=v(()=>{"use strict";ve();Ti={};Ei(Ti,{ACTION_TIMEOUT:()=>Rn,GOTO_TIMEOUT:()=>pe,LOCATOR_TIMEOUT:()=>_t,getActionTimeoutMs:()=>R,getFrameContext:()=>Dn,getLocator:()=>F,getMinimalActionEntity:()=>Xl,getPageLocatorExpression:()=>Ne,sanitizeForComment:()=>Vl});C=Xa(()=>{_t=5e3,Rn=1e4,pe=2e4})});async function Fn(e,t,i=[],n=[]){try{let a=await Dn(e,i);if(!a)return f.warn(`Could not find frame context for xpath: ${t}`),null;let o=null;if(n.length>0){let s=n[0];if(!s)return f.warn(`Missing shadow host xpath for element: ${t}`),null;let l=a.locator(`xpath=${Ya(s)}`),c=ql(t);if(o=await(c?l.locator(`css=${c}`):l.locator(`xpath=${Ya(t)}`)).elementHandle({timeout:_t}),!o)return f.warn(`Could not find shadow DOM element with xpath: ${t}`),null}else if(o=await a.locator(`xpath=${t}`).elementHandle({timeout:_t}),!o)return f.warn(`Could not find element with xpath: ${t}`),null;let r=await a.evaluate(s=>typeof playwright<"u"&&playwright.generateLocator?playwright.generateLocator(s):null,o);return await o.dispose(),r?(f.debug(`Generated locator for ${t}: ${r}`),r):(f.debug("playwright.generateLocator is not available (PWDEBUG=console not set), using xpath fallback"),null)}catch(a){return f.error(`Error in pickBestLocator: ${a}`),null}}async function Hn(e,t){try{let i=await(await t.ownerFrame()??e).evaluate(n=>typeof playwright<"u"&&playwright.generateLocator?playwright.generateLocator(n):null,t);return await t.dispose(),i?(f.debug(`Generated locator: ${i}`),i):(f.debug("playwright.generateLocator is not available (PWDEBUG=console not set), using xpath fallback"),null)}catch(i){return f.error(`Error in pickBestLocator: ${i}`),null}}function Ya(e){let t=e.trim();return t.startsWith("/")||t.startsWith("(")||t.startsWith(".")?t:`//${t}`}function ql(e){let t=e.trim().replace(/^\/+/,"");if(!t)return null;let i=t.split("/").filter(Boolean),n=[];for(let a of i){let o=a.match(/^([a-zA-Z][\w-]*)(?:\[(\d+)\])?$/);if(!o)return null;let r=o[1].toLowerCase(),s=o[2]?`:nth-of-type(${o[2]})`:"";n.push(`${r}${s}`)}return n.join(" > ")}var Be=v(()=>{"use strict";B();G();C()});async function kt(e,t,i){await e.evaluate(()=>{document.getElementById("playwright-highlight-container")?.remove(),window._highlightCleanupFunctions&&(window._highlightCleanupFunctions.forEach(l=>l()),window._highlightCleanupFunctions=[])});let n=await e.screenshot({type:"png",fullPage:!1}),{default:a}=await import("sharp"),o=a(n),{width:r=0,height:s=0}=await o.metadata();return T.log(`Screenshot actual: ${r}x${s}, viewport: ${t}x${i}`),(r!==t||s!==i?await o.resize(t,i).png().toBuffer():n).toString("base64")}async function xe(e,t,i){let n=await e.evaluateHandle(r=>document.elementFromPoint(r.x,r.y),{x:t,y:i}),a=n.asElement();if(!a)throw await n.dispose(),new Error(`No element found at (${t}, ${i})`);let o=await a.boundingBox();if(!o)throw await n.dispose(),new Error(`Element at (${t}, ${i}) has no bounding box`);return{relative_x:t-(o.x+o.width/2),relative_y:i-(o.y+o.height/2),element:a}}async function Ai(e,t){if(!t)return{xpath:void 0,locator:void 0,frame_path:[]};let i=await t.evaluate(a=>{let o=[],r=a;for(;r&&r.nodeType===Node.ELEMENT_NODE;){let s=1,l=r.previousElementSibling;for(;l;)l.tagName===r.tagName&&s++,l=l.previousElementSibling;o.unshift(`${r.tagName.toLowerCase()}[${s}]`),r=r.parentElement}return o.length?`/${o.join("/")}`:null}).catch(()=>null),n=await Hn(e,t);return{xpath:i??void 0,locator:n??void 0,frame_path:[]}}function $i(e,t,i){return{action_description:e,action_data:t,locator:i.locator??void 0,xpath:i.xpath??void 0,frame_path:i.frame_path}}var et=v(()=>{"use strict";ae();Be()});function tc(e){return e.startsWith(Zl)}function Ge(e,t){let i=t?.trim();return i?ic(i):tc(e)?Ql:ec}function ic(e){return e.endsWith("/")?e.slice(0,-1):e}var Zl,Ql,ec,tt=v(()=>{"use strict";Zl="shp_",Ql="https://nova-api.shiplight.ai",ec="https://api.shiplight.ai"});function qa(e,t){return`${Ge(e,t)}/llm/v1`}function Za(e,t){return`${Ge(e,t)}/llm/v1`}function Qa(e,t){return`${Ge(e,t)}/llm/v1beta`}function eo(e,t){return`${Ge(e,t)}/llm`}var Le=v(()=>{"use strict";tt()});import{createGoogleGenerativeAI as to}from"@ai-sdk/google";import{createVertex as nc}from"@ai-sdk/google-vertex";function Mi(){let e=(Y().env||{}).GOOGLE_GENAI_USE_VERTEXAI;return e==="True"||e==="true"}function no(e){let t=Y().env||{};if(Mi()){let a=t.GOOGLE_CLOUD_PROJECT;if(!a)throw new Error("GOOGLE_CLOUD_PROJECT is required when using Vertex AI");let o=e.startsWith("gemini-3")?"global":t.GOOGLE_CLOUD_LOCATION;if(!o)throw new Error("GOOGLE_CLOUD_LOCATION is required when using Vertex AI");return f.debug(`Using Vertex AI provider: model=${e}, location=${o}`),nc({project:a,location:o})(e)}let i=t.GOOGLE_API_KEY;if(i)return f.debug(`Using Google AI provider (API key): model=${e}`),to({apiKey:i})(e);let n=t.SHIPLIGHT_API_TOKEN;if(n){let a=Qa(n,t.SHIPLIGHT_API_URL);return f.debug(`Using Shiplight LLM proxy (Google): model=${e}, baseURL=${a}`),to({apiKey:n,baseURL:a})(e)}throw new Error("Google API key is missing. Set GOOGLE_API_KEY in SDK config or environment.")}function ao(e,t){let i={thinkingConfig:{thinkingBudget:512,includeThoughts:!0}},n={thinkingConfig:{thinkingLevel:"minimal",includeThoughts:!0},mediaResolution:io.MEDIA_RESOLUTION_HIGH},a;switch(t){case"gemini-3-flash-preview":a={...n};break;default:a={...i},e===1&&(a.mediaResolution=io.MEDIA_RESOLUTION_HIGH)}return Mi()?{vertex:a}:{google:a}}var io,it=v(()=>{"use strict";Le();B();te();io={MEDIA_RESOLUTION_HIGH:"MEDIA_RESOLUTION_HIGH",MEDIA_RESOLUTION_MEDIUM:"MEDIA_RESOLUTION_MEDIUM",MEDIA_RESOLUTION_LOW:"MEDIA_RESOLUTION_LOW"}});import{GoogleGenAI as ac,Environment as oc}from"@google/genai";function ge(e,t){return Math.round(e/1e3*t)}async function sc(e,t,i,n,a){let o=null,r=null;try{switch(t){case"click_at":{let s=ge(i.x,n),l=ge(i.y,a),c=await xe(e,s,l);o={action_name:"click_by_coordinates",kwargs:{relative_x:c.relative_x,relative_y:c.relative_y}},r=c.element;break}case"right_click_at":{let s=ge(i.x,n),l=ge(i.y,a),c=await xe(e,s,l);o={action_name:"right_click_by_coordinates",kwargs:{relative_x:c.relative_x,relative_y:c.relative_y}},r=c.element;break}case"double_click_at":{let s=ge(i.x,n),l=ge(i.y,a),c=await xe(e,s,l);o={action_name:"double_click_by_coordinates",kwargs:{relative_x:c.relative_x,relative_y:c.relative_y}},r=c.element;break}case"drag_and_drop":{let s=ge(i.x,n),l=ge(i.y,a),c=ge(i.destination_x,n),d=ge(i.destination_y,a),u=await xe(e,s,l);o={action_name:"drag_drop",kwargs:{relative_x:u.relative_x,relative_y:u.relative_y,delta_x:c-s,delta_y:d-l}},r=u.element;break}default:T.log(`Unsupported Gemini function: ${t}`)}}catch(s){T.error(`Error mapping Gemini action "${t}"`,s)}return{action_data:o,locatorInfo:await Ai(e,r)}}async function ro(e){let{statement:t,page:i,screenshotB64:n,viewportWidth:a,viewportHeight:o,modelId:r}=e,s=r||lc,l=Y(),c;if(Mi()){let b=l.env?.GOOGLE_CLOUD_PROJECT;if(!b)return{status:"error",error:"GOOGLE_CLOUD_PROJECT is required when using Vertex AI."};let x=l.env?.GOOGLE_CLOUD_LOCATION??"global";c={vertexai:!0,project:b,location:x}}else{let b=l.env?.GOOGLE_API_KEY;if(b)f.debug(`Using Google AI provider (API key): model=${s}`),c={apiKey:b};else{let x=l.env?.SHIPLIGHT_API_TOKEN;if(x){let S=eo(x,l.env?.SHIPLIGHT_API_URL);f.debug(`Using Shiplight LLM proxy (Google CUA): model=${s}, baseUrl=${S}`),c={apiKey:x,httpOptions:{baseUrl:S}}}else return{status:"error",error:"Google API key is missing. Set GOOGLE_API_KEY in SDK config or environment."}}}let d=new ac(c);T.log(`Sending request to Gemini CUA (model=${s})...`);let u=await d.models.generateContent({model:s,contents:[{role:"user",parts:[{text:`Execute this action: ${t}`},{inlineData:{mimeType:"image/png",data:n}}]}],config:{tools:[{computerUse:{environment:oc.ENVIRONMENT_BROWSER,excludedPredefinedFunctions:["search","type_text_at","scroll_document","navigate","go_back","go_forward","key_combination","hover_at","scroll_at"]}},{functionDeclarations:rc}],temperature:.1}});T.log("Received response from Gemini CUA");let m=u.candidates?.[0];if(!m)return{status:"error",error:"No candidates in Gemini response"};let p=m.content?.parts?.find(b=>b.functionCall);if(!p)return{status:"error",reasoning:m.content?.parts?.filter(b=>b.text).map(b=>b.text).join(" ")||"No action generated",error:"No function call in Gemini response"};let{name:w,args:g}=p.functionCall;T.log(`Generated function call: ${w} with args ${JSON.stringify(g)}`),f.debug(`Generated function call: ${w} with args ${JSON.stringify(g)}`);let{action_data:y,locatorInfo:h}=await sc(i,w,g,a,o);return y?{status:"success",actionEntity:$i(t,y,h),reasoning:"Action generated successfully using Gemini computer use",goalAccomplished:!0}:{status:"error",error:`Unsupported or invalid Gemini action: ${w}`}}var oo,rc,lc,Ii=v(()=>{"use strict";et();ae();it();Le();B();te();oo={type:"object",properties:{x:{type:"integer",description:"X coordinate in the 0-1000 normalized space."},y:{type:"integer",description:"Y coordinate in the 0-1000 normalized space."}},required:["x","y"]},rc=[{name:"right_click_at",description:"Right-click at the given normalized coordinate.",parameters:oo},{name:"double_click_at",description:"Double-click at the given normalized coordinate.",parameters:oo}];lc="gemini-3-flash-preview"});function lo(e){return e!=null&&typeof e=="object"}function nt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function so(e){return typeof e=="string"?e:void 0}function cc(e){let t,i;return Array.isArray(e)?(t=nt(e[0]),i=nt(e[1])):lo(e)&&(t=nt(e.x),i=nt(e.y)),t===void 0||i===void 0?null:{x:t,y:i}}function co(e){if(!lo(e))return{};let t=Array.isArray(e.path)?e.path.map(cc).filter(i=>i!==null):void 0;return{type:so(e.type),x:nt(e.x),y:nt(e.y),button:so(e.button),path:t}}var Ci=v(()=>{"use strict"});import dc from"openai";async function uc(e,t){let i=co(t),n=null,a=null;switch(i.type){case"click":{if(i.x===void 0||i.y===void 0)break;let o=i.button==="right"?"right_click_by_coordinates":"click_by_coordinates",r=await xe(e,i.x,i.y);n={action_name:o,kwargs:{relative_x:r.relative_x,relative_y:r.relative_y}},a=r.element;break}case"double_click":{if(i.x===void 0||i.y===void 0)break;let o=await xe(e,i.x,i.y);n={action_name:"double_click_by_coordinates",kwargs:{relative_x:o.relative_x,relative_y:o.relative_y}},a=o.element;break}case"drag":{if(!i.path||i.path.length<2)break;let o=i.path[0],r=i.path[i.path.length-1],s=await xe(e,o.x,o.y);n={action_name:"drag_drop",kwargs:{relative_x:s.relative_x,relative_y:s.relative_y,delta_x:r.x-o.x,delta_y:r.y-o.y}},a=s.element;break}}return{action_data:n,locatorInfo:await Ai(e,a)}}async function ho(e){let{statement:t,page:i,viewportWidth:n,viewportHeight:a,modelId:o}=e,r=o||hc,s=await kt(i,n,a),l=Y(),c=l.env?.OPENAI_API_KEY;if(!c)return{status:"error",error:"OPENAI_API_KEY not found in SDK env config."};let d=l.env?.OPENAI_BASE_URL,u=new dc({apiKey:c,...d&&{baseURL:d}}),m=u.responses.create.bind(u.responses);T.log(`Sending request to OpenAI CUA (model=${r})...`);let p=[{role:"user",content:[{type:"input_text",text:t},{type:"input_image",detail:"original",image_url:`data:image/png;base64,${s}`}]}];async function w(x,S){let E={model:r,tools:[mc],input:x,temperature:.1};return S&&(E.previous_response_id=S),m(E)}let g=await w(p,void 0),y;for(let x=0;x<uo;x++){T.log(`Received response from OpenAI CUA (turn ${x+1})`);let S=g.output.find(O=>O.type==="computer_call");if(!S)return{status:"error",reasoning:g.output_text||"Invalid action generation response",error:"No computer_call in OpenAI response"};let E=S.actions??[];if(E.length>1&&T.log(`[openai CUA] dropping ${E.length-1} batched action(s); only the first is executed`),y=E[0],!y)return{status:"error",error:"OpenAI CUA returned a computer_call with no actions"};if(y.type!=="screenshot")break;s=await kt(i,n,a);let $=[{type:"computer_call_output",call_id:S.call_id,output:{type:"computer_screenshot",image_url:`data:image/png;base64,${s}`,detail:"original"}}];g=await w($,g.id)}if(!y)return{status:"error",error:"OpenAI CUA loop ended without an action"};if(y.type==="screenshot")return{status:"error",error:`OpenAI CUA kept requesting screenshots after ${uo} turns`};T.log(`Generated action: ${JSON.stringify(y)}`);let{action_data:h,locatorInfo:b}=await uc(i,y);return h?{status:"success",actionEntity:$i(t,h,b),reasoning:"Action generated successfully using OpenAI computer use",goalAccomplished:!0}:{status:"error",error:`Failed to map OpenAI action: ${JSON.stringify(y)}`}}var hc,mc,uo,Pi=v(()=>{"use strict";Ci();et();ae();te();hc="gpt-5.4",mc={type:"computer"},uo=4});import{APICallError as mo,RetryError as pc}from"ai";function go(){let e=Y().env?.WEB_AGENT_LLM_TIMEOUT_MS;if(e===void 0||e==="")return po;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<0?po:t}function fo(e,t){let i=[e,t].filter(n=>!!n);if(i.length!==0)return i.length===1?i[0]:AbortSignal.any(i)}function gc(e){if(mo.isInstance(e))return e.statusCode;if(pc.isInstance(e)&&mo.isInstance(e.lastError))return e.lastError.statusCode}function Wn(e){let t=gc(e);return!(t===400||t===422)}async function at(e,t,i){if(e.length===0)throw new Error("runWithModelFallback: no models provided");let n;for(let a=0;a<e.length;a++){let o=e[a];try{return await t(o)}catch(r){if(n=r,a===e.length-1||fc(r)||!Wn(r))throw r;i?.(o,e[a+1],r)}}throw n}function fc(e){return e?.name==="AI_NoObjectGeneratedError"}var po,De=v(()=>{"use strict";te();po=15e4});function Re(e){let t=e.indexOf(":");if(t>0){let i=e.slice(0,t);if(wc.has(i))return{provider:i,modelId:e.slice(t+1)}}return{provider:void 0,modelId:e}}var wc,Ke=v(()=>{"use strict";wc=new Set(["anthropic","google","openai","vertex","azure","bedrock"])});function bc(e){return e.startsWith("gemini-")?"google":"openai"}async function ot(e,t,i={}){let{page:n}=t,a=n.viewportSize();if(!a)return{status:"error",error:"Viewport size not available"};let{width:o,height:r}=a;T.log(`Viewport: ${o}x${r}`);let s=await kt(n,o,r),l=t.agentServices.getComputerUseModel();if(!l)return{status:"error",error:"No computer use model configured"};let c=[l,...t.agentServices.getComputerUseFallbackModels().filter(d=>d!==l)];try{return await at(c,d=>{let{modelId:u}=Re(d),m=bc(u),p=yc[m];return T.log(`Using CUA provider: ${m} (model: ${u})`),p({statement:e,page:n,screenshotB64:s,viewportWidth:o,viewportHeight:r,modelId:u})},(d,u)=>T.log(`CUA model ${d} unavailable; falling back to ${u}`))}catch(d){return T.error("CUA provider threw an error",d),{status:"error",error:d.message??"CUA provider failed"}}}var yc,rt=v(()=>{"use strict";Ii();Pi();et();De();ae();Ke();yc={google:ro,openai:ho}});import{zodToJsonSchema as vc}from"zod-to-json-schema";function Oi(e){let t=vc(e,{$refStrategy:"none"});if(t.$schema&&delete t.$schema,t.type!=="object")throw new Error(`Schema must be a Zod object schema, got type: ${t.type}`);return St(t),t}function St(e){if(!(typeof e!="object"||e===null)){if(e.type==="object"&&(e.additionalProperties=!1,e.properties)){let t=Object.keys(e.properties);e.required=t;for(let i of Object.values(e.properties))St(i)}e.type==="array"&&e.items&&St(e.items);for(let t of["anyOf","oneOf","allOf"])Array.isArray(e[t])&&e[t].forEach(St);for(let[t,i]of Object.entries(e))typeof i=="object"&&i!==null&&!["properties","items","anyOf","oneOf","allOf"].includes(t)&&St(i)}}var Et=v(()=>{"use strict"});var jn,Ni=v(()=>{"use strict";Et();jn=class{constructor(e){this.registry=e}getToolDefinitions(){return this.registry.getTools().filter(e=>e.availability.openai).map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:Oi(e.schema),strict:!0}}))}getToolDefinitionsFiltered(e){let t=new Set(e);return this.registry.getTools().filter(i=>t.has(i.name)&&i.availability.openai).map(i=>({type:"function",function:{name:i.name,description:i.description,parameters:Oi(i.schema),strict:!0}}))}toJSON(){return this.getToolDefinitions()}getToolDefinition(e){let t=this.registry.get(e);if(t)return{type:"function",function:{name:t.name,description:t.description,parameters:Oi(t.schema),strict:!0}}}getToolCount(){return this.registry.size()}getToolNames(){return this.registry.getToolNames()}}});function xc(e,t){let i=new Map;for(let l of t)l.hash&&l.url?i.set(l.hash,l.url):l.uuid&&l.url&&i.set(l.uuid,l.url);let n=/!\[([^\]]*)\]\(image:([a-f0-9]{64}|[a-zA-Z0-9\-]+)\)/g,a=[],o=0,r;for(;(r=n.exec(e))!==null;){let l=e.slice(o,r.index);l&&a.push({type:"text",text:l});let c=r[2];i.has(c)?a.push({type:"image",image:new URL(i.get(c))}):a.push({type:"text",text:r[0]}),o=r.index+r[0].length}let s=e.slice(o);return s&&a.push({type:"text",text:s}),a.length===0&&a.push({type:"text",text:e}),a}function _c(e){let t=[];for(let i of e){let n=i.content||"",a=i.images||[],o=xc(n,a);t.length>0&&o.length>0&&t.push({type:"text",text:`
14
+ ${e}`)}error(e,t){this.log(`ERROR: ${e}`),t&&(this.log(`Error details: ${t.message}`),t.stack&&this.log(`Stack: ${t.stack}`))}isEnabled(){return!!Y().agentLogPath}},T=new Bl});var Nn,Gl,Kl,zl,Xa,Ei,On,Ja,Ln,ve=b(()=>{"use strict";Nn=Object.defineProperty,Gl=Object.getOwnPropertyDescriptor,Kl=Object.getOwnPropertyNames,zl=Object.prototype.hasOwnProperty,Xa=(e,t)=>()=>(e&&(t=e(e=0)),t),Ei=(e,t)=>{for(var i in t)Nn(e,i,{get:t[i],enumerable:!0})},On=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Kl(t))!zl.call(e,a)&&a!==i&&Nn(e,a,{get:()=>t[a],enumerable:!(n=Gl(t,a))||n.enumerable});return e},Ja=(e,t,i)=>(On(e,t,"default"),i&&On(i,t,"default")),Ln=e=>On(Nn({},"__esModule",{value:!0}),e)});function R(e,t){return t??e?.getActionSettings()?.action_timeout_ms??Rn}function Vl(e){return e.replace(/\r\n/g," ").replace(/\n/g," ").replace(/\r/g," ").trim()}function F(e,t){let i=Ne(t);return i?new Function("page",`return ${i}`)(e):null}async function Dn(e,t=[]){let i=e;for(let n of t){let a=await i.locator(n).elementHandle();if(!a)return null;let o=await a.contentFrame();if(await a.dispose(),!o)return null;i=o}return i}function Xl(e){let t={action_data:e.action_data};return e.locator&&(t.locator=e.locator),e.xpath&&(t.xpath=e.xpath),e.frame_path&&(t.frame_path=e.frame_path),t}function Jl(e){let t=e.frame_path;return!t||t.length===0?"page":`page.frameLocator('${t[0]}')`}function Yl(e){let t=e.xpath;return typeof t=="string"&&t.trim()?!t.startsWith("xpath=")&&!t.startsWith("/")&&!t.startsWith("//")?`xpath=//${t}`:t.startsWith("xpath=")?t:`xpath=${t}`:null}function Ne(e){let t=Jl(e),i=e.locator;if(typeof i=="string"&&i.trim())return i=i.trim(),i.endsWith("first()")?`${t}.${i}`:`${t}.${i}.first()`;let n=Yl(e);if(n){let a=JSON.stringify(n);return`${t}.locator(${a}).first()`}return null}var Ti,_t,Rn,pe,P,G=b(()=>{"use strict";ve();Ti={};Ei(Ti,{ACTION_TIMEOUT:()=>Rn,GOTO_TIMEOUT:()=>pe,LOCATOR_TIMEOUT:()=>_t,getActionTimeoutMs:()=>R,getFrameContext:()=>Dn,getLocator:()=>F,getMinimalActionEntity:()=>Xl,getPageLocatorExpression:()=>Ne,sanitizeForComment:()=>Vl});P=Xa(()=>{_t=5e3,Rn=1e4,pe=2e4})});async function Fn(e,t,i=[],n=[]){try{let a=await Dn(e,i);if(!a)return f.warn(`Could not find frame context for xpath: ${t}`),null;let o=null;if(n.length>0){let s=n[0];if(!s)return f.warn(`Missing shadow host xpath for element: ${t}`),null;let l=a.locator(`xpath=${Ya(s)}`),c=ql(t);if(o=await(c?l.locator(`css=${c}`):l.locator(`xpath=${Ya(t)}`)).elementHandle({timeout:_t}),!o)return f.warn(`Could not find shadow DOM element with xpath: ${t}`),null}else if(o=await a.locator(`xpath=${t}`).elementHandle({timeout:_t}),!o)return f.warn(`Could not find element with xpath: ${t}`),null;let r=await a.evaluate(s=>typeof playwright<"u"&&playwright.generateLocator?playwright.generateLocator(s):null,o);return await o.dispose(),r?(f.debug(`Generated locator for ${t}: ${r}`),r):(f.debug("playwright.generateLocator is not available (PWDEBUG=console not set), using xpath fallback"),null)}catch(a){return f.error(`Error in pickBestLocator: ${a}`),null}}async function Hn(e,t){try{let i=await(await t.ownerFrame()??e).evaluate(n=>typeof playwright<"u"&&playwright.generateLocator?playwright.generateLocator(n):null,t);return await t.dispose(),i?(f.debug(`Generated locator: ${i}`),i):(f.debug("playwright.generateLocator is not available (PWDEBUG=console not set), using xpath fallback"),null)}catch(i){return f.error(`Error in pickBestLocator: ${i}`),null}}function Ya(e){let t=e.trim();return t.startsWith("/")||t.startsWith("(")||t.startsWith(".")?t:`//${t}`}function ql(e){let t=e.trim().replace(/^\/+/,"");if(!t)return null;let i=t.split("/").filter(Boolean),n=[];for(let a of i){let o=a.match(/^([a-zA-Z][\w-]*)(?:\[(\d+)\])?$/);if(!o)return null;let r=o[1].toLowerCase(),s=o[2]?`:nth-of-type(${o[2]})`:"";n.push(`${r}${s}`)}return n.join(" > ")}var Ge=b(()=>{"use strict";B();G();P()});async function kt(e,t,i){await e.evaluate(()=>{document.getElementById("playwright-highlight-container")?.remove(),window._highlightCleanupFunctions&&(window._highlightCleanupFunctions.forEach(l=>l()),window._highlightCleanupFunctions=[])});let n=await e.screenshot({type:"png",fullPage:!1}),{default:a}=await import("sharp"),o=a(n),{width:r=0,height:s=0}=await o.metadata();return T.log(`Screenshot actual: ${r}x${s}, viewport: ${t}x${i}`),(r!==t||s!==i?await o.resize(t,i).png().toBuffer():n).toString("base64")}async function xe(e,t,i){let n=await e.evaluateHandle(r=>document.elementFromPoint(r.x,r.y),{x:t,y:i}),a=n.asElement();if(!a)throw await n.dispose(),new Error(`No element found at (${t}, ${i})`);let o=await a.boundingBox();if(!o)throw await n.dispose(),new Error(`Element at (${t}, ${i}) has no bounding box`);return{relative_x:t-(o.x+o.width/2),relative_y:i-(o.y+o.height/2),element:a}}async function Ai(e,t){if(!t)return{xpath:void 0,locator:void 0,frame_path:[]};let i=await t.evaluate(a=>{let o=[],r=a;for(;r&&r.nodeType===Node.ELEMENT_NODE;){let s=1,l=r.previousElementSibling;for(;l;)l.tagName===r.tagName&&s++,l=l.previousElementSibling;o.unshift(`${r.tagName.toLowerCase()}[${s}]`),r=r.parentElement}return o.length?`/${o.join("/")}`:null}).catch(()=>null),n=await Hn(e,t);return{xpath:i??void 0,locator:n??void 0,frame_path:[]}}function $i(e,t,i){return{action_description:e,action_data:t,locator:i.locator??void 0,xpath:i.xpath??void 0,frame_path:i.frame_path}}var tt=b(()=>{"use strict";ae();Ge()});function tc(e){return e.startsWith(Zl)}function Ke(e,t){let i=t?.trim();return i?ic(i):tc(e)?Ql:ec}function ic(e){return e.endsWith("/")?e.slice(0,-1):e}var Zl,Ql,ec,it=b(()=>{"use strict";Zl="shp_",Ql="https://nova-api.shiplight.ai",ec="https://api.shiplight.ai"});function qa(e,t){return`${Ke(e,t)}/llm/v1`}function Za(e,t){return`${Ke(e,t)}/llm/v1`}function Qa(e,t){return`${Ke(e,t)}/llm/v1beta`}function eo(e,t){return`${Ke(e,t)}/llm`}var Le=b(()=>{"use strict";it()});import{createGoogleGenerativeAI as to}from"@ai-sdk/google";import{createVertex as nc}from"@ai-sdk/google-vertex";function Mi(){let e=(Y().env||{}).GOOGLE_GENAI_USE_VERTEXAI;return e==="True"||e==="true"}function no(e){let t=Y().env||{};if(Mi()){let a=t.GOOGLE_CLOUD_PROJECT;if(!a)throw new Error("GOOGLE_CLOUD_PROJECT is required when using Vertex AI");let o=e.startsWith("gemini-3")?"global":t.GOOGLE_CLOUD_LOCATION;if(!o)throw new Error("GOOGLE_CLOUD_LOCATION is required when using Vertex AI");return f.debug(`Using Vertex AI provider: model=${e}, location=${o}`),nc({project:a,location:o})(e)}let i=t.GOOGLE_API_KEY;if(i)return f.debug(`Using Google AI provider (API key): model=${e}`),to({apiKey:i})(e);let n=t.SHIPLIGHT_API_TOKEN;if(n){let a=Qa(n,t.SHIPLIGHT_API_URL);return f.debug(`Using Shiplight LLM proxy (Google): model=${e}, baseURL=${a}`),to({apiKey:n,baseURL:a})(e)}throw new Error("Google API key is missing. Set GOOGLE_API_KEY in SDK config or environment.")}function ao(e,t){let i={thinkingConfig:{thinkingBudget:512,includeThoughts:!0}},n={thinkingConfig:{thinkingLevel:"minimal",includeThoughts:!0},mediaResolution:io.MEDIA_RESOLUTION_HIGH},a;switch(t){case"gemini-3-flash-preview":a={...n};break;default:a={...i},e===1&&(a.mediaResolution=io.MEDIA_RESOLUTION_HIGH)}return Mi()?{vertex:a}:{google:a}}var io,nt=b(()=>{"use strict";Le();B();te();io={MEDIA_RESOLUTION_HIGH:"MEDIA_RESOLUTION_HIGH",MEDIA_RESOLUTION_MEDIUM:"MEDIA_RESOLUTION_MEDIUM",MEDIA_RESOLUTION_LOW:"MEDIA_RESOLUTION_LOW"}});import{GoogleGenAI as ac,Environment as oc}from"@google/genai";function ge(e,t){return Math.round(e/1e3*t)}async function sc(e,t,i,n,a){let o=null,r=null;try{switch(t){case"click_at":{let s=ge(i.x,n),l=ge(i.y,a),c=await xe(e,s,l);o={action_name:"click_by_coordinates",kwargs:{relative_x:c.relative_x,relative_y:c.relative_y}},r=c.element;break}case"right_click_at":{let s=ge(i.x,n),l=ge(i.y,a),c=await xe(e,s,l);o={action_name:"right_click_by_coordinates",kwargs:{relative_x:c.relative_x,relative_y:c.relative_y}},r=c.element;break}case"double_click_at":{let s=ge(i.x,n),l=ge(i.y,a),c=await xe(e,s,l);o={action_name:"double_click_by_coordinates",kwargs:{relative_x:c.relative_x,relative_y:c.relative_y}},r=c.element;break}case"drag_and_drop":{let s=ge(i.x,n),l=ge(i.y,a),c=ge(i.destination_x,n),d=ge(i.destination_y,a),u=await xe(e,s,l);o={action_name:"drag_drop",kwargs:{relative_x:u.relative_x,relative_y:u.relative_y,delta_x:c-s,delta_y:d-l}},r=u.element;break}default:T.log(`Unsupported Gemini function: ${t}`)}}catch(s){T.error(`Error mapping Gemini action "${t}"`,s)}return{action_data:o,locatorInfo:await Ai(e,r)}}async function ro(e){let{statement:t,page:i,screenshotB64:n,viewportWidth:a,viewportHeight:o,modelId:r}=e,s=r||lc,l=Y(),c;if(Mi()){let v=l.env?.GOOGLE_CLOUD_PROJECT;if(!v)return{status:"error",error:"GOOGLE_CLOUD_PROJECT is required when using Vertex AI."};let _=l.env?.GOOGLE_CLOUD_LOCATION??"global";c={vertexai:!0,project:v,location:_}}else{let v=l.env?.GOOGLE_API_KEY;if(v)f.debug(`Using Google AI provider (API key): model=${s}`),c={apiKey:v};else{let _=l.env?.SHIPLIGHT_API_TOKEN;if(_){let x=eo(_,l.env?.SHIPLIGHT_API_URL);f.debug(`Using Shiplight LLM proxy (Google CUA): model=${s}, baseUrl=${x}`),c={apiKey:_,httpOptions:{baseUrl:x}}}else return{status:"error",error:"Google API key is missing. Set GOOGLE_API_KEY in SDK config or environment."}}}let d=new ac(c);T.log(`Sending request to Gemini CUA (model=${s})...`);let u=await d.models.generateContent({model:s,contents:[{role:"user",parts:[{text:`Execute this action: ${t}`},{inlineData:{mimeType:"image/png",data:n}}]}],config:{tools:[{computerUse:{environment:oc.ENVIRONMENT_BROWSER,excludedPredefinedFunctions:["search","type_text_at","scroll_document","navigate","go_back","go_forward","key_combination","hover_at","scroll_at"]}},{functionDeclarations:rc}],temperature:.1}});T.log("Received response from Gemini CUA");let m=u.candidates?.[0];if(!m)return{status:"error",error:"No candidates in Gemini response"};let p=m.content?.parts?.find(v=>v.functionCall);if(!p)return{status:"error",reasoning:m.content?.parts?.filter(v=>v.text).map(v=>v.text).join(" ")||"No action generated",error:"No function call in Gemini response"};let{name:w,args:g}=p.functionCall;T.log(`Generated function call: ${w} with args ${JSON.stringify(g)}`),f.debug(`Generated function call: ${w} with args ${JSON.stringify(g)}`);let{action_data:y,locatorInfo:h}=await sc(i,w,g,a,o);return y?{status:"success",actionEntity:$i(t,y,h),reasoning:"Action generated successfully using Gemini computer use",goalAccomplished:!0}:{status:"error",error:`Unsupported or invalid Gemini action: ${w}`}}var oo,rc,lc,Ii=b(()=>{"use strict";tt();ae();nt();Le();B();te();oo={type:"object",properties:{x:{type:"integer",description:"X coordinate in the 0-1000 normalized space."},y:{type:"integer",description:"Y coordinate in the 0-1000 normalized space."}},required:["x","y"]},rc=[{name:"right_click_at",description:"Right-click at the given normalized coordinate.",parameters:oo},{name:"double_click_at",description:"Double-click at the given normalized coordinate.",parameters:oo}];lc="gemini-3-flash-preview"});function lo(e){return e!=null&&typeof e=="object"}function at(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function so(e){return typeof e=="string"?e:void 0}function cc(e){let t,i;return Array.isArray(e)?(t=at(e[0]),i=at(e[1])):lo(e)&&(t=at(e.x),i=at(e.y)),t===void 0||i===void 0?null:{x:t,y:i}}function co(e){if(!lo(e))return{};let t=Array.isArray(e.path)?e.path.map(cc).filter(i=>i!==null):void 0;return{type:so(e.type),x:at(e.x),y:at(e.y),button:so(e.button),path:t}}var Ci=b(()=>{"use strict"});import dc from"openai";async function uc(e,t){let i=co(t),n=null,a=null;switch(i.type){case"click":{if(i.x===void 0||i.y===void 0)break;let o=i.button==="right"?"right_click_by_coordinates":"click_by_coordinates",r=await xe(e,i.x,i.y);n={action_name:o,kwargs:{relative_x:r.relative_x,relative_y:r.relative_y}},a=r.element;break}case"double_click":{if(i.x===void 0||i.y===void 0)break;let o=await xe(e,i.x,i.y);n={action_name:"double_click_by_coordinates",kwargs:{relative_x:o.relative_x,relative_y:o.relative_y}},a=o.element;break}case"drag":{if(!i.path||i.path.length<2)break;let o=i.path[0],r=i.path[i.path.length-1],s=await xe(e,o.x,o.y);n={action_name:"drag_drop",kwargs:{relative_x:s.relative_x,relative_y:s.relative_y,delta_x:r.x-o.x,delta_y:r.y-o.y}},a=s.element;break}}return{action_data:n,locatorInfo:await Ai(e,a)}}async function ho(e){let{statement:t,page:i,viewportWidth:n,viewportHeight:a,modelId:o}=e,r=o||hc,s=await kt(i,n,a),l=Y(),c=l.env?.OPENAI_API_KEY;if(!c)return{status:"error",error:"OPENAI_API_KEY not found in SDK env config."};let d=l.env?.OPENAI_BASE_URL,u=new dc({apiKey:c,...d&&{baseURL:d}}),m=u.responses.create.bind(u.responses);T.log(`Sending request to OpenAI CUA (model=${r})...`);let p=[{role:"user",content:[{type:"input_text",text:t},{type:"input_image",detail:"original",image_url:`data:image/png;base64,${s}`}]}];async function w(_,x){let E={model:r,tools:[mc],input:_,temperature:.1};return x&&(E.previous_response_id=x),m(E)}let g=await w(p,void 0),y;for(let _=0;_<uo;_++){T.log(`Received response from OpenAI CUA (turn ${_+1})`);let x=g.output.find(I=>I.type==="computer_call");if(!x)return{status:"error",reasoning:g.output_text||"Invalid action generation response",error:"No computer_call in OpenAI response"};let E=x.actions??[];if(E.length>1&&T.log(`[openai CUA] dropping ${E.length-1} batched action(s); only the first is executed`),y=E[0],!y)return{status:"error",error:"OpenAI CUA returned a computer_call with no actions"};if(y.type!=="screenshot")break;s=await kt(i,n,a);let $=[{type:"computer_call_output",call_id:x.call_id,output:{type:"computer_screenshot",image_url:`data:image/png;base64,${s}`,detail:"original"}}];g=await w($,g.id)}if(!y)return{status:"error",error:"OpenAI CUA loop ended without an action"};if(y.type==="screenshot")return{status:"error",error:`OpenAI CUA kept requesting screenshots after ${uo} turns`};T.log(`Generated action: ${JSON.stringify(y)}`);let{action_data:h,locatorInfo:v}=await uc(i,y);return h?{status:"success",actionEntity:$i(t,h,v),reasoning:"Action generated successfully using OpenAI computer use",goalAccomplished:!0}:{status:"error",error:`Failed to map OpenAI action: ${JSON.stringify(y)}`}}var hc,mc,uo,Pi=b(()=>{"use strict";Ci();tt();ae();te();hc="gpt-5.4",mc={type:"computer"},uo=4});import{APICallError as mo,RetryError as pc}from"ai";function go(){let e=Y().env?.WEB_AGENT_LLM_TIMEOUT_MS;if(e===void 0||e==="")return po;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<0?po:t}function fo(e,t){let i=[e,t].filter(n=>!!n);if(i.length!==0)return i.length===1?i[0]:AbortSignal.any(i)}function gc(e){if(mo.isInstance(e))return e.statusCode;if(pc.isInstance(e)&&mo.isInstance(e.lastError))return e.lastError.statusCode}function Wn(e){let t=gc(e);return!(t===400||t===422)}async function ot(e,t,i){if(e.length===0)throw new Error("runWithModelFallback: no models provided");let n;for(let a=0;a<e.length;a++){let o=e[a];try{return await t(o)}catch(r){if(n=r,a===e.length-1||fc(r)||!Wn(r))throw r;i?.(o,e[a+1],r)}}throw n}function fc(e){return e?.name==="AI_NoObjectGeneratedError"}var po,De=b(()=>{"use strict";te();po=15e4});function Re(e){let t=e.indexOf(":");if(t>0){let i=e.slice(0,t);if(wc.has(i))return{provider:i,modelId:e.slice(t+1)}}return{provider:void 0,modelId:e}}var wc,ze=b(()=>{"use strict";wc=new Set(["anthropic","google","openai","vertex","azure","bedrock"])});function bc(e){return e.startsWith("gemini-")?"google":"openai"}async function rt(e,t,i={}){let{page:n}=t,a=n.viewportSize();if(!a)return{status:"error",error:"Viewport size not available"};let{width:o,height:r}=a;T.log(`Viewport: ${o}x${r}`);let s=await kt(n,o,r),l=t.agentServices.getComputerUseModel();if(!l)return{status:"error",error:"No computer use model configured"};let c=[l,...t.agentServices.getComputerUseFallbackModels().filter(d=>d!==l)];try{return await ot(c,d=>{let{modelId:u}=Re(d),m=bc(u),p=yc[m];return T.log(`Using CUA provider: ${m} (model: ${u})`),p({statement:e,page:n,screenshotB64:s,viewportWidth:o,viewportHeight:r,modelId:u})},(d,u)=>T.log(`CUA model ${d} unavailable; falling back to ${u}`))}catch(d){return T.error("CUA provider threw an error",d),{status:"error",error:d.message??"CUA provider failed"}}}var yc,st=b(()=>{"use strict";Ii();Pi();tt();De();ae();ze();yc={google:ro,openai:ho}});import{zodToJsonSchema as vc}from"zod-to-json-schema";function Oi(e){let t=vc(e,{$refStrategy:"none"});if(t.$schema&&delete t.$schema,t.type!=="object")throw new Error(`Schema must be a Zod object schema, got type: ${t.type}`);return St(t),t}function St(e){if(!(typeof e!="object"||e===null)){if(e.type==="object"&&(e.additionalProperties=!1,e.properties)){let t=Object.keys(e.properties);e.required=t;for(let i of Object.values(e.properties))St(i)}e.type==="array"&&e.items&&St(e.items);for(let t of["anyOf","oneOf","allOf"])Array.isArray(e[t])&&e[t].forEach(St);for(let[t,i]of Object.entries(e))typeof i=="object"&&i!==null&&!["properties","items","anyOf","oneOf","allOf"].includes(t)&&St(i)}}var Et=b(()=>{"use strict"});var jn,Ni=b(()=>{"use strict";Et();jn=class{constructor(e){this.registry=e}getToolDefinitions(){return this.registry.getTools().filter(e=>e.availability.openai).map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:Oi(e.schema),strict:!0}}))}getToolDefinitionsFiltered(e){let t=new Set(e);return this.registry.getTools().filter(i=>t.has(i.name)&&i.availability.openai).map(i=>({type:"function",function:{name:i.name,description:i.description,parameters:Oi(i.schema),strict:!0}}))}toJSON(){return this.getToolDefinitions()}getToolDefinition(e){let t=this.registry.get(e);if(t)return{type:"function",function:{name:t.name,description:t.description,parameters:Oi(t.schema),strict:!0}}}getToolCount(){return this.registry.size()}getToolNames(){return this.registry.getToolNames()}}});function xc(e,t){let i=new Map;for(let l of t)l.hash&&l.url?i.set(l.hash,l.url):l.uuid&&l.url&&i.set(l.uuid,l.url);let n=/!\[([^\]]*)\]\(image:([a-f0-9]{64}|[a-zA-Z0-9\-]+)\)/g,a=[],o=0,r;for(;(r=n.exec(e))!==null;){let l=e.slice(o,r.index);l&&a.push({type:"text",text:l});let c=r[2];i.has(c)?a.push({type:"file",mediaType:"image",data:new URL(i.get(c))}):a.push({type:"text",text:r[0]}),o=r.index+r[0].length}let s=e.slice(o);return s&&a.push({type:"text",text:s}),a.length===0&&a.push({type:"text",text:e}),a}function _c(e){let t=[];for(let i of e){let n=i.content||"",a=i.images||[],o=xc(n,a);t.length>0&&o.length>0&&t.push({type:"text",text:`
15
15
 
16
16
  `}),t.push(...o)}return t}function Li(e,t=wo){if(t){let i=_c(e);if(i.length===0)return[];let n={type:"text",text:`
17
17
 
@@ -33,11 +33,14 @@ Below are expert curated knowledge that are retrieved from the knowledge base; A
33
33
 
34
34
  </retrieved_knowledge>
35
35
 
36
- `}]:[]}}function yo(e,t=wo){if(!t)return 0;let i=0;for(let n of e)n.images&&(i+=n.images.length);return i}var wo,Tt=v(()=>{"use strict";wo=!1});function kc(){let e=new Date,t=new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"short"}).formatToParts(e),i=t.find(d=>d.type==="year").value,n=t.find(d=>d.type==="month").value,a=t.find(d=>d.type==="day").value,o=t.find(d=>d.type==="hour").value,r=t.find(d=>d.type==="minute").value,s=t.find(d=>d.type==="second").value,l=t.find(d=>d.type==="timeZoneName").value,c=String(e.getMilliseconds()).padStart(3,"0");return`${i}-${n}-${a} ${o}:${r}:${s}.${c} ${l}`}function bo(e){return`# Your Role
36
+ `}]:[]}}function yo(e,t=wo){if(!t)return 0;let i=0;for(let n of e)n.images&&(i+=n.images.length);return i}var wo,Tt=b(()=>{"use strict";wo=!1});function kc(){let e=new Date,t=new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"short"}).formatToParts(e),i=t.find(d=>d.type==="year").value,n=t.find(d=>d.type==="month").value,a=t.find(d=>d.type==="day").value,o=t.find(d=>d.type==="hour").value,r=t.find(d=>d.type==="minute").value,s=t.find(d=>d.type==="second").value,l=t.find(d=>d.type==="timeZoneName").value,c=String(e.getMilliseconds()).padStart(3,"0");return`${i}-${n}-${a} ${o}:${r}:${s}.${c} ${l}`}function bo(e){return`# Your Role
37
37
  You are part of a end-to-end testing system that is designed to automate the testing of a website. Given an instruction in natural language, your job is to translate it into an action in the predefined actions. The instruction might not match any action in the predefined actions or might require to interact with an element that is not on the page. It's your job to detect these cases and return an empty action.
38
38
 
39
39
  # Rules
40
40
  ## Action Selection Rules
41
+ - Before selecting the requested action, inspect the current webpage state and determine whether the requested state is already satisfied.
42
+ - If the requested state is already satisfied, do not repeat or reverse the interaction. Instead, select the \`wait\` action for 1 second and set \`completes_instruction\` to true. This rule applies even when the instruction directly names an action, such as "enter the username".
43
+ - For conditional instructions, if the condition for performing the action is false because the desired state is already satisfied, select the \`wait\` action for 1 second and set \`completes_instruction\` to true.
41
44
  - If the instruction requires a specific action, you must select that action. If no action matches the specific action, you must return an empty action so that testing system can aware of the situation.
42
45
  - If asked to do nothing or ignore the instruction or something similar, you must select \`wait\` action of 1 second.
43
46
  - If asked to verify something, you must select \`verify\` action.
@@ -68,6 +71,25 @@ Follow the rules above strictly.
68
71
  ${e}
69
72
 
70
73
  # Examples
74
+ Examples when the requested state is already satisfied:
75
+ instruction: "Enter the username"
76
+ current webpage state: The username field already contains the requested username.
77
+ {
78
+ "thought": "The username field already contains the requested username, so the requested state is already satisfied. I will not enter it again.",
79
+ "description": "The username is already entered; wait without changing it.",
80
+ "action": {"wait": {"seconds": 1}},
81
+ "completes_instruction": true
82
+ }
83
+
84
+ instruction: "If the username is empty, enter the username"
85
+ current webpage state: The username field is not empty and already contains the requested username.
86
+ {
87
+ "thought": "The username field is not empty and already contains the requested username, so the condition for entering it is false. I will not enter it again.",
88
+ "description": "The username is already entered; wait without changing it.",
89
+ "action": {"wait": {"seconds": 1}},
90
+ "completes_instruction": true
91
+ }
92
+
71
93
  Example of \`verify\` action:
72
94
  instruction: "Verify that the page title is 'Home'"
73
95
  {
@@ -117,7 +139,7 @@ ${e.tabsText}
117
139
 
118
140
  ## Interactive elements from current page:
119
141
  ${e.elementsText}
120
- `;if(d.push({type:"text",text:u}),r&&e.slicedScreenshotsBase64)for(let p of e.slicedScreenshotsBase64)d.push({type:"text",text:"The following images provided are sliced screenshots of the current webpage, with interactive elements highlighted. The element index label locate at the top right corner of the bounding box."}),d.push({type:"image",image:p});else o&&(d.push({type:"text",text:"The following image provided is a screenshot of the current webpage, with interactive elements highlighted. The element index label locate at the top right corner of the bounding box."}),d.push({type:"image",image:o}));if(a&&a.length>0){let p=Li(a,l);d.push(...p)}let m="";if(m+=`
142
+ `;if(d.push({type:"text",text:u}),r&&e.slicedScreenshotsBase64)for(let p of e.slicedScreenshotsBase64)d.push({type:"text",text:"The following images provided are sliced screenshots of the current webpage, with interactive elements highlighted. The element index label locate at the top right corner of the bounding box."}),d.push({type:"file",mediaType:"image/png",data:p});else o&&(d.push({type:"text",text:"The following image provided is a screenshot of the current webpage, with interactive elements highlighted. The element index label locate at the top right corner of the bounding box."}),d.push({type:"file",mediaType:"image/png",data:o}));if(a&&a.length>0){let p=Li(a,l);d.push(...p)}let m="";if(m+=`
121
143
  Current local time is ${s}.
122
144
  `,i&&Object.keys(i).length>0){let p=[];for(let w of Object.keys(i))if(c?.has(w))p.push(` - ${w}: [SENSITIVE - value hidden]`);else{let g=i[w],y=typeof g=="string"?g:JSON.stringify(g);p.push(` - ${w}: "${y}"`)}m+=`
123
145
  ## Available Data Placeholders
@@ -133,14 +155,14 @@ To use them, write Jinja-like template syntax: {{ placeholder_name }}
133
155
  `}if(n&&n.length>0){let p=Sc(n);m+=`
134
156
  `+p}return m+=`
135
157
  Based on the above information, please determine the right action to accomplish the task.
136
- `,d.push({type:"text",text:m}),d}var Di=v(()=>{"use strict";Tt()});async function Ec(e){let t=e.context().pages(),i=null,n=[];for(let o=0;o<t.length;o++){let r=t[o];r===e&&(i=o);let s="(title unavailable)";try{s=await Promise.race([r.title(),new Promise((c,d)=>setTimeout(()=>d(new Error("timeout")),1e3))])}catch{}let l=`Tab ${o}: ${r.url()}`;s&&(l+=` - ${s.slice(0,50)}`),n.push(l)}let a=n.length>0?n.join(`
158
+ `,d.push({type:"text",text:m}),d}var Di=b(()=>{"use strict";Tt()});async function Ec(e){let t=e.context().pages(),i=null,n=[];for(let o=0;o<t.length;o++){let r=t[o];r===e&&(i=o);let s="(title unavailable)";try{s=await Promise.race([r.title(),new Promise((c,d)=>setTimeout(()=>d(new Error("timeout")),1e3))])}catch{}let l=`Tab ${o}: ${r.url()}`;s&&(l+=` - ${s.slice(0,50)}`),n.push(l)}let a=n.length>0?n.join(`
137
159
  `):"";return{currentTabText:i!==null?`Current tab: ${i}
138
- `:"",tabsText:a}}async function Tc(e,t){let{currentTabText:i,tabsText:n}=await Ec(e);return{elementsText:t,currentUrl:e.url(),currentTitle:await e.title(),currentTabText:i,tabsText:n}}async function Ri(e,t){let{page:i,domService:n,agentServices:a}=e,o=typeof t=="boolean"?{useCleanScreenshot:t}:t||{},r=a.getInteractiveClassNames(),s=a.getIframeFallbackDomains(),{domState:l,screenshotBase64:c,slicedScreenshotsBase64:d}=await n.getClickableElementsWithScreenshot(i,{interactiveClassNames:r,playwrightFrameFallbackDomains:s,useCleanScreenshot:o.useCleanScreenshot,useSlicedScreenshots:o.useSlicedScreenshots,resizeSlicedScreenshots:o.resizeSlicedScreenshots,useAccessibilityTree:o.useAccessibilityTree,actionIntent:o.actionIntent}),u=l.elementTree.clickableElementsToString(),m=await Tc(i,u);return d&&(m.slicedScreenshotsBase64=d),{domTree:u,screenshotBase64:c,slicedScreenshotsBase64:d,domState:l,pageContext:m}}var At=v(()=>{"use strict"});import{z as me}from"zod";var Un,V,_e=v(()=>{"use strict";Un=class{constructor(){this.tools=new Map}register(e){if(this.tools.has(e.name))throw new Error(`Tool '${e.name}' is already registered`);let t={name:e.name,description:e.description,schema:e.schema,execute:e.execute,usesElementIndex:e.usesElementIndex??!1,availability:{openai:e.availability?.openai??!0,mcp:e.availability?.mcp??!0}};this.tools.set(e.name,t)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getToolNames(){return Array.from(this.tools.keys())}getTools(){return Array.from(this.tools.values())}async execute(e,t,i){let n=this.tools.get(e);if(!n)throw new Error(`Tool not found: ${e}`);try{let a=t?.description,o={...t};delete o.description;let r=n.schema.parse(o),s={...i,actionDescription:a};return await n.execute(r,s)}catch(a){if(a instanceof me.ZodError){let o=a.issues.map(r=>`${r.path.join(".")}: ${r.message}`).join(", ");return{success:!1,error:`Invalid arguments for tool '${e}': ${o}`,actionEntity:{action_description:t?.description||`${e} (validation failed)`,action_data:{action_name:e,kwargs:t},feedback:`Validation error: ${o}`}}}throw a}}clear(){this.tools.clear()}size(){return this.tools.size}buildActionUnionSchema(){let e=this.getTools().filter(t=>t.availability.openai);return this.buildUnionSchemaFromTools(e)}buildActionUnionSchemaForTools(e,t=!1){let i=new Set(e),n=this.getTools().filter(a=>i.has(a.name));return this.buildUnionSchemaFromTools(n,t)}buildUnionSchemaFromTools(e,t=!1){if(e.length===0)return me.object({done:me.any()});let i=e.map(r=>{let s=r.schema;if(t&&s instanceof me.ZodObject){let l=s._def.shape();s=me.object({...l,description:me.string().describe("Semantic, human-readable description of the action")})}if(s instanceof me.ZodObject){let l=s._def.shape();Object.keys(l).length===0&&(s=me.object({_empty:me.boolean().optional()}))}return me.object({[r.name]:s})});if(i.length===1)return i[0];let[n,a,...o]=i;return me.union([n,a,...o])}},V=new Un});function ke(e,t){if(!e||typeof e!="object")return null;let i=e;return{prompt_tokens:i.promptTokens||i.inputTokens||0,completion_tokens:i.completionTokens||i.outputTokens||0,total_tokens:i.totalTokens||0,model:Re(t).modelId}}var Fe=v(()=>{"use strict";Ke()});import{createAnthropic as xo}from"@ai-sdk/anthropic";import{createVertexAnthropic as Ac}from"@ai-sdk/google-vertex/anthropic";function $c(e){if(!e)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Mc(){return $c(Y().env?.ANTHROPIC_MODELS_USE_VERTEXAI)}function _o(e){let t=Y();if(Mc()){let a=t.env?.GOOGLE_CLOUD_PROJECT,o=t.env?.GOOGLE_CLOUD_LOCATION;if(!a)throw new Error("GOOGLE_CLOUD_PROJECT is required when ANTHROPIC_MODELS_USE_VERTEXAI is enabled");if(!o)throw new Error("GOOGLE_CLOUD_LOCATION is required when ANTHROPIC_MODELS_USE_VERTEXAI is enabled");return f.debug(`Using Anthropic via Vertex AI provider: model=${e}, project=${a}, location=${o}`),Ac({project:a,location:o})(e)}let i=t.env?.ANTHROPIC_API_KEY;if(i)return f.debug(`Using Anthropic provider: model=${e}`),xo({apiKey:i})(e);let n=t.env?.SHIPLIGHT_API_TOKEN;if(n){let a=Za(n,t.env?.SHIPLIGHT_API_URL);return f.debug(`Using Shiplight LLM proxy (Anthropic): model=${e}, baseURL=${a}`),xo({apiKey:n,baseURL:a})(e)}throw new Error("ANTHROPIC_API_KEY not configured in SDK config")}function ko(e){return/^claude-(opus-4-[0-6]|sonnet-4-[0-6]|haiku-[34]|[23])/.test(e)}function Bn(e){return{anthropic:{structuredOutputMode:"jsonTool"}}}var $t=v(()=>{"use strict";Le();B();te()});import{createOpenAI as So}from"@ai-sdk/openai";function Eo(e){let t=Y(),i=t.env?.OPENAI_API_KEY;if(i){let a=t.env?.OPENAI_BASE_URL;return f.debug(`Using OpenAI provider: model=${e}${a?`, baseURL=${a}`:""}`),So({apiKey:i,baseURL:a})(e)}let n=t.env?.SHIPLIGHT_API_TOKEN;if(n){let a=qa(n,t.env?.SHIPLIGHT_API_URL);return f.debug(`Using Shiplight LLM proxy (OpenAI): model=${e}, baseURL=${a}`),So({apiKey:n,baseURL:a})(e)}throw new Error("OPENAI_API_KEY not configured in SDK config")}function To(e){return{}}var Mt=v(()=>{"use strict";Le();B();te()});function Gn(e){if(e.startsWith("claude-"))return"anthropic";if(e.startsWith("gemini-"))return"google";if(Ic.test(e))return"openai"}function fe(e){let{provider:t,modelId:i}=Re(e),n=t??Gn(i);if(!n)throw new Error(`Cannot determine provider for model: ${e}. Use a known model prefix (claude-*, gemini-*, gpt-*) or specify a provider (e.g., "openai:${i}", "azure:${i}", "bedrock:${i}").`);if(!i)throw new Error(`Empty model ID in model string: "${e}". Specify a model after the provider prefix (e.g., "${n}:gpt-5.4-mini").`);let a=Ao[n];if(!a)throw new Error(`Provider "${n}" is not yet implemented. Supported providers: ${Object.keys(Ao).join(", ")}. See packages/sdk-core/src/agent/llm/DESIGN.md for the roadmap.`);return a(i)}function we(e,t){let{provider:i,modelId:n}=Re(e),a=i??Gn(n);return a==="anthropic"||a==="vertex"?Bn(n):a==="openai"||a==="azure"?To(n):a==="bedrock"?n.startsWith("anthropic.")?Bn(n):{}:ao(t,n)}function Se(e,t){let i=t??0,{provider:n,modelId:a}=Re(e),o=n??Gn(a),r;if((o==="anthropic"||o==="vertex")&&a.startsWith("claude-"))r=a;else if(o==="bedrock"){let s=a.match(/^(?:[a-z]{2}\.)?anthropic\.(claude-.+)$/);s&&(r=s[1])}return r!==void 0?ko(r)?i:void 0:i}var Ic,Ao,Ee=v(()=>{"use strict";$t();it();Mt();Ke();Ic=/^(gpt-|o\d|chatgpt-)/;Ao={anthropic:_o,google:no,openai:Eo}});async function X(e,t){if(t<0)return;let{page:i,domService:n}=e;return(e.domState||await n.getClickableElements(i)).selectorMap.get(t)}function Cc(e){let t=e.split("/").filter(a=>a);if(t.length===0)return"*";let i=t[t.length-1],n=i.match(/^(\w+)(?:\[(\d+)\])?$/);if(n){let[,a,o]=n;return o?`${a}:nth-of-type(${o})`:a}return i}function Pc(e,t=!0){try{let i=Cc(e.xpath);if(e.attributes.class&&t){let a=/^[a-zA-Z_][a-zA-Z0-9_-]*$/,o=e.attributes.class.split(/\s+/);for(let r of o)r.trim()&&a.test(r)&&(i+=`.${r}`)}let n=new Set(["id","name","type","placeholder","aria-label","aria-labelledby","aria-describedby","role","for","autocomplete","required","readonly","alt","title","target"]);t&&["data-id","data-qa","data-cy","data-testid","data-handlepos"].forEach(a=>n.add(a));for(let[a,o]of Object.entries(e.attributes)){if(a==="class"||!a.trim()||!n.has(a))continue;let r=a.replace(/:/g,"\\:");if(o==="")i+=`[${r}]`;else if(/["'<>`\n\r\t]/.test(o)){let s=o;o.includes(`
160
+ `:"",tabsText:a}}async function Tc(e,t){let{currentTabText:i,tabsText:n}=await Ec(e);return{elementsText:t,currentUrl:e.url(),currentTitle:await e.title(),currentTabText:i,tabsText:n}}async function Ri(e,t){let{page:i,domService:n,agentServices:a}=e,o=typeof t=="boolean"?{useCleanScreenshot:t}:t||{},r=a.getInteractiveClassNames(),s=a.getIframeFallbackDomains(),{domState:l,screenshotBase64:c,slicedScreenshotsBase64:d}=await n.getClickableElementsWithScreenshot(i,{interactiveClassNames:r,playwrightFrameFallbackDomains:s,useCleanScreenshot:o.useCleanScreenshot,useSlicedScreenshots:o.useSlicedScreenshots,resizeSlicedScreenshots:o.resizeSlicedScreenshots,useAccessibilityTree:o.useAccessibilityTree,actionIntent:o.actionIntent}),u=l.elementTree.clickableElementsToString(),m=await Tc(i,u);return d&&(m.slicedScreenshotsBase64=d),{domTree:u,screenshotBase64:c,slicedScreenshotsBase64:d,domState:l,pageContext:m}}var At=b(()=>{"use strict"});import{z as me}from"zod";var Un,V,_e=b(()=>{"use strict";Un=class{constructor(){this.tools=new Map}register(e){if(this.tools.has(e.name))throw new Error(`Tool '${e.name}' is already registered`);let t={name:e.name,description:e.description,schema:e.schema,execute:e.execute,resolveArgs:e.resolveArgs,redactErrorText:e.redactErrorText,usesElementIndex:e.usesElementIndex??!1,availability:{openai:e.availability?.openai??!0,mcp:e.availability?.mcp??!0}};this.tools.set(e.name,t)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getToolNames(){return Array.from(this.tools.keys())}getTools(){return Array.from(this.tools.values())}async execute(e,t,i){let n=this.tools.get(e);if(!n)throw new Error(`Tool not found: ${e}`);try{let a=t?.description,o={...t};delete o.description;let r=n.resolveArgs?n.resolveArgs(o):o,s=n.schema.parse(r),l={...i,actionDescription:a,...n.resolveArgs?{rawArgs:o}:{}};return await n.execute(s,l)}catch(a){if(a instanceof me.ZodError){let o=(n.redactErrorText??(r=>r))(a.issues.map(r=>`${r.path.join(".")}: ${r.message}`).join(", "));return{success:!1,error:`Invalid arguments for tool '${e}': ${o}`,actionEntity:{action_description:t?.description||`${e} (validation failed)`,action_data:{action_name:e,kwargs:t},feedback:`Validation error: ${o}`}}}throw a}}clear(){this.tools.clear()}size(){return this.tools.size}buildActionUnionSchema(){let e=this.getTools().filter(t=>t.availability.openai);return this.buildUnionSchemaFromTools(e)}buildActionUnionSchemaForTools(e,t=!1){let i=new Set(e),n=this.getTools().filter(a=>i.has(a.name));return this.buildUnionSchemaFromTools(n,t)}buildUnionSchemaFromTools(e,t=!1){if(e.length===0)return me.object({done:me.any()});let i=e.map(r=>{let s=r.schema;if(t&&s instanceof me.ZodObject){let l=s._def.shape();s=me.object({...l,description:me.string().describe("Semantic, human-readable description of the action")})}if(s instanceof me.ZodObject){let l=s._def.shape();Object.keys(l).length===0&&(s=me.object({_empty:me.boolean().optional()}))}return me.object({[r.name]:s})});if(i.length===1)return i[0];let[n,a,...o]=i;return me.union([n,a,...o])}},V=new Un});function ke(e,t){if(!e||typeof e!="object")return null;let i=e;return{prompt_tokens:i.promptTokens||i.inputTokens||0,completion_tokens:i.completionTokens||i.outputTokens||0,total_tokens:i.totalTokens||0,model:Re(t).modelId}}var Fe=b(()=>{"use strict";ze()});import{createAnthropic as xo}from"@ai-sdk/anthropic";import{createVertexAnthropic as Ac}from"@ai-sdk/google-vertex/anthropic";function $c(e){if(!e)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Mc(){return $c(Y().env?.ANTHROPIC_MODELS_USE_VERTEXAI)}function _o(e){let t=Y();if(Mc()){let a=t.env?.GOOGLE_CLOUD_PROJECT,o=t.env?.GOOGLE_CLOUD_LOCATION;if(!a)throw new Error("GOOGLE_CLOUD_PROJECT is required when ANTHROPIC_MODELS_USE_VERTEXAI is enabled");if(!o)throw new Error("GOOGLE_CLOUD_LOCATION is required when ANTHROPIC_MODELS_USE_VERTEXAI is enabled");return f.debug(`Using Anthropic via Vertex AI provider: model=${e}, project=${a}, location=${o}`),Ac({project:a,location:o})(e)}let i=t.env?.ANTHROPIC_API_KEY;if(i)return f.debug(`Using Anthropic provider: model=${e}`),xo({apiKey:i})(e);let n=t.env?.SHIPLIGHT_API_TOKEN;if(n){let a=Za(n,t.env?.SHIPLIGHT_API_URL);return f.debug(`Using Shiplight LLM proxy (Anthropic): model=${e}, baseURL=${a}`),xo({apiKey:n,baseURL:a})(e)}throw new Error("ANTHROPIC_API_KEY not configured in SDK config")}function ko(e){return/^claude-(opus-4-[0-6]|sonnet-4-[0-6]|haiku-[34]|[23])/.test(e)}function Bn(e){return{anthropic:{structuredOutputMode:"jsonTool"}}}var $t=b(()=>{"use strict";Le();B();te()});import{createOpenAI as So}from"@ai-sdk/openai";function Eo(e){let t=Y(),i=t.env?.OPENAI_API_KEY;if(i){let a=t.env?.OPENAI_BASE_URL;return f.debug(`Using OpenAI provider: model=${e}${a?`, baseURL=${a}`:""}`),So({apiKey:i,baseURL:a})(e)}let n=t.env?.SHIPLIGHT_API_TOKEN;if(n){let a=qa(n,t.env?.SHIPLIGHT_API_URL);return f.debug(`Using Shiplight LLM proxy (OpenAI): model=${e}, baseURL=${a}`),So({apiKey:n,baseURL:a})(e)}throw new Error("OPENAI_API_KEY not configured in SDK config")}function To(e){return{}}var Mt=b(()=>{"use strict";Le();B();te()});function Gn(e){if(e.startsWith("claude-"))return"anthropic";if(e.startsWith("gemini-"))return"google";if(Ic.test(e))return"openai"}function fe(e){let{provider:t,modelId:i}=Re(e),n=t??Gn(i);if(!n)throw new Error(`Cannot determine provider for model: ${e}. Use a known model prefix (claude-*, gemini-*, gpt-*) or specify a provider (e.g., "openai:${i}", "azure:${i}", "bedrock:${i}").`);if(!i)throw new Error(`Empty model ID in model string: "${e}". Specify a model after the provider prefix (e.g., "${n}:gpt-5.4-mini").`);let a=Ao[n];if(!a)throw new Error(`Provider "${n}" is not yet implemented. Supported providers: ${Object.keys(Ao).join(", ")}. See packages/sdk-core/src/agent/llm/DESIGN.md for the roadmap.`);return a(i)}function we(e,t){let{provider:i,modelId:n}=Re(e),a=i??Gn(n);return a==="anthropic"||a==="vertex"?Bn(n):a==="openai"||a==="azure"?To(n):a==="bedrock"?n.startsWith("anthropic.")?Bn(n):{}:ao(t,n)}function Se(e,t){let i=t??0,{provider:n,modelId:a}=Re(e),o=n??Gn(a),r;if((o==="anthropic"||o==="vertex")&&a.startsWith("claude-"))r=a;else if(o==="bedrock"){let s=a.match(/^(?:[a-z]{2}\.)?anthropic\.(claude-.+)$/);s&&(r=s[1])}return r!==void 0?ko(r)?i:void 0:i}var Ic,Ao,Ee=b(()=>{"use strict";$t();nt();Mt();ze();Ic=/^(gpt-|o\d|chatgpt-)/;Ao={anthropic:_o,google:no,openai:Eo}});async function X(e,t){if(t<0)return;let{page:i,domService:n}=e;return(e.domState||await n.getClickableElements(i)).selectorMap.get(t)}function Cc(e){let t=e.split("/").filter(a=>a);if(t.length===0)return"*";let i=t[t.length-1],n=i.match(/^(\w+)(?:\[(\d+)\])?$/);if(n){let[,a,o]=n;return o?`${a}:nth-of-type(${o})`:a}return i}function Pc(e,t=!0){try{let i=Cc(e.xpath);if(e.attributes.class&&t){let a=/^[a-zA-Z_][a-zA-Z0-9_-]*$/,o=e.attributes.class.split(/\s+/);for(let r of o)r.trim()&&a.test(r)&&(i+=`.${r}`)}let n=new Set(["id","name","type","placeholder","aria-label","aria-labelledby","aria-describedby","role","for","autocomplete","required","readonly","alt","title","target"]);t&&["data-id","data-qa","data-cy","data-testid","data-handlepos"].forEach(a=>n.add(a));for(let[a,o]of Object.entries(e.attributes)){if(a==="class"||!a.trim()||!n.has(a))continue;let r=a.replace(/:/g,"\\:");if(o==="")i+=`[${r}]`;else if(/["'<>`\n\r\t]/.test(o)){let s=o;o.includes(`
139
161
  `)&&(s=o.split(`
140
- `)[0]),s=s.replace(/\s+/g," ").trim();let l=s.replace(/"/g,'\\"');i+=`[${r}*="${l}"]`}else i+=`[${r}="${o}"]`}return i}catch{return`${e.tagName||"*"}[highlight_index='${e.highlightIndex}']`}}function Oc(e){let t=e.attributes;if(t.title)return`iframe[title="${t.title.replace(/"/g,'\\"')}"]`;if(t.id)return`iframe#${t.id}`;if(t.name)return`iframe[name="${t.name.replace(/"/g,'\\"')}"]`;if(t.src){try{let i=new URL(t.src);if(i.protocol==="chrome-extension:")return`iframe[src^="${i.origin}"]`}catch{}return`iframe[src="${t.src.replace(/"/g,'\\"')}"]`}return Pc(e,!1)}function $o(e){let t=[],i=e;for(;i&&i.parent!==null;){let o=i.parent;t.push(o),i=o}t.reverse();let n=[],a=t.filter(o=>o.tagName==="iframe");for(let o of a){let r=Oc(o);f.debug("[frame-path] iframe attrs:",JSON.stringify(o.attributes),"\u2192",r),n.push(r)}return n}async function j(e,t){let i=null,n=$o(t);return t.xpath&&(i=await Fn(e,t.xpath,n,t.shadowHostXPaths??[])),{locator:i||void 0,xpath:i?void 0:t.xpath,frame_path:n}}var Z=v(()=>{"use strict";Be();B()});import{generateText as Nc,NoObjectGeneratedError as Lc,Output as Dc}from"ai";import{z as Fi}from"zod";function Rc(e){let t=e.toLowerCase();return[/\b(type|enter|input|fill|write|set)\b/,/\b(text|value|field|box)\b.*\b(to|with|as)\b/,/\b(username|password|email|search|query)\b/].some(i=>i.test(t))?"input":[/\bscroll\b/,/\b(scroll|swipe)\s*(up|down|left|right)\b/,/\b(page|move)\s*(down|up)\b/].some(i=>i.test(t))?"scroll":[/\b(click|tap|press|select|choose|pick|check|toggle)\b/,/\b(open|close|submit|confirm|cancel|dismiss)\b/,/\b(button|link|menu|dropdown|checkbox|radio)\b/].some(i=>i.test(t))?"click":"all"}function Fc(e){if(!e)return null;if(e instanceof URL)return e.href;if(typeof e=="object"&&e.href)return String(e.href);if(typeof e=="object"&&typeof e.toString=="function"){let t=e.toString();if(t.startsWith("http://")||t.startsWith("https://"))return t}return typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://"))?e:null}function Hc(e){return e.map(t=>({role:t.role,content:Array.isArray(t.content)?t.content.map(i=>{if(i.type==="image"){let n=i.image,a=Fc(n);if(a)return{type:"image",file:a};let o=typeof n=="string"?n:"";return{type:"image",file:o.startsWith("data:")?o:`data:image/png;base64,${o}`}}return{type:"text",text:i.text}}):t.content}))}async function Mo(e,t,i={}){let{page:n,agentServices:a}=t,o=a.getModel(),r=a.retrieveKnowledges(e).catch(N=>(T.log(`Failed to retrieve knowledges: ${N.message}`),[])),s=a.isSlicedScreenshotsEnabled(),l=a.isResizeSlicedScreenshotsEnabled(),c=a.isKnowledgeImagesEnabled(),d=a.isAccessibilityTreeEnabled(),u=a.isActionIntentFilteringEnabled(),m=u?Rc(e):"all";u&&m!=="all"&&T.log(`Action intent filtering: detected '${m}' intent from statement`);let{screenshotBase64:p,domState:w,pageContext:g}=await Ri(t,{useSlicedScreenshots:s,resizeSlicedScreenshots:l,useAccessibilityTree:d,actionIntent:m});t.domState=w;let y=new jn(V).getToolDefinitions().map(N=>{let z=N.function;return`${z.name}: ${z.description}
162
+ `)[0]),s=s.replace(/\s+/g," ").trim();let l=s.replace(/"/g,'\\"');i+=`[${r}*="${l}"]`}else i+=`[${r}="${o}"]`}return i}catch{return`${e.tagName||"*"}[highlight_index='${e.highlightIndex}']`}}function Oc(e){let t=e.attributes;if(t.title)return`iframe[title="${t.title.replace(/"/g,'\\"')}"]`;if(t.id)return`iframe#${t.id}`;if(t.name)return`iframe[name="${t.name.replace(/"/g,'\\"')}"]`;if(t.src){try{let i=new URL(t.src);if(i.protocol==="chrome-extension:")return`iframe[src^="${i.origin}"]`}catch{}return`iframe[src="${t.src.replace(/"/g,'\\"')}"]`}return Pc(e,!1)}function $o(e){let t=[],i=e;for(;i&&i.parent!==null;){let o=i.parent;t.push(o),i=o}t.reverse();let n=[],a=t.filter(o=>o.tagName==="iframe");for(let o of a){let r=Oc(o);f.debug("[frame-path] iframe attrs:",JSON.stringify(o.attributes),"\u2192",r),n.push(r)}return n}async function j(e,t){let i=null,n=$o(t);return t.xpath&&(i=await Fn(e,t.xpath,n,t.shadowHostXPaths??[])),{locator:i||void 0,xpath:i?void 0:t.xpath,frame_path:n}}var Z=b(()=>{"use strict";Ge();B()});import{generateText as Nc,NoObjectGeneratedError as Lc,Output as Dc}from"ai";import{z as Fi}from"zod";function Rc(e){let t=e.toLowerCase();return[/\b(type|enter|input|fill|write|set)\b/,/\b(text|value|field|box)\b.*\b(to|with|as)\b/,/\b(username|password|email|search|query)\b/].some(i=>i.test(t))?"input":[/\bscroll\b/,/\b(scroll|swipe)\s*(up|down|left|right)\b/,/\b(page|move)\s*(down|up)\b/].some(i=>i.test(t))?"scroll":[/\b(click|tap|press|select|choose|pick|check|toggle)\b/,/\b(open|close|submit|confirm|cancel|dismiss)\b/,/\b(button|link|menu|dropdown|checkbox|radio)\b/].some(i=>i.test(t))?"click":"all"}function Fc(e){if(!e)return null;if(e instanceof URL)return e.href;if(typeof e=="object"&&e.href)return String(e.href);if(typeof e=="object"&&typeof e.toString=="function"){let t=e.toString();if(t.startsWith("http://")||t.startsWith("https://"))return t}return typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://"))?e:null}function Hc(e){return e.map(t=>({role:t.role,content:Array.isArray(t.content)?t.content.map(i=>{if(i.type==="file"){let n=i.data,a=Fc(n);if(a)return{type:"image",file:a};let o=typeof n=="string"?n:"";return{type:"image",file:o.startsWith("data:")?o:`data:image/png;base64,${o}`}}return{type:"text",text:i.text}}):t.content}))}async function Mo(e,t,i={}){let{page:n,agentServices:a}=t,o=a.getModel(),r=a.retrieveKnowledges(e).catch(N=>(T.log(`Failed to retrieve knowledges: ${N.message}`),[])),s=a.isSlicedScreenshotsEnabled(),l=a.isResizeSlicedScreenshotsEnabled(),c=a.isKnowledgeImagesEnabled(),d=a.isAccessibilityTreeEnabled(),u=a.isActionIntentFilteringEnabled(),m=u?Rc(e):"all";u&&m!=="all"&&T.log(`Action intent filtering: detected '${m}' intent from statement`);let{screenshotBase64:p,domState:w,pageContext:g}=await Ri(t,{useSlicedScreenshots:s,resizeSlicedScreenshots:l,useAccessibilityTree:d,actionIntent:m});t.domState=w;let y=new jn(V).getToolDefinitions().map(N=>{let z=N.function;return`${z.name}: ${z.description}
141
163
  Parameters: ${JSON.stringify(z.parameters,null,2)}`}).join(`
142
164
 
143
- `),h=bo(y),b=await r,x=vo(g,e,t.variables,t.executionHistory,b.length>0?b:void 0,p,s,void 0,c,t.sensitiveKeys),S=[];i.chatHistory&&i.chatHistory.length>0&&i.chatHistory.forEach(N=>{N.role==="user"?S.push({role:"user",content:N.content}):N.role==="assistant"&&S.push({role:"assistant",content:N.content})}),S.push({role:"user",content:x});let E=Hc(S),$=V.buildActionUnionSchema(),O=Fi.object({thought:Fi.string().describe("Step by step reasoning of your decision making process").optional().default(""),description:Fi.string().describe("Detailed description of the action to be performed").optional().default(""),action:$,completes_instruction:Fi.boolean().describe("Whether this action completes the given instruction").optional().default(!0)}),D=Array.isArray(x)?x.filter(N=>N.type==="image").length:0,I=[o,...a.getFallbackModels().filter(N=>N!==o)],H=o,K;try{K=await at(I,N=>{H=N;let z=Se(N,i.temperature);return Nc({model:fe(N),system:h,messages:S,...z!==void 0?{temperature:z}:{},output:Dc.object({schema:O}),providerOptions:we(N,D),maxRetries:4})},(N,z)=>T.log(`Action-gen model ${N} unavailable; falling back to ${z}`))}catch(N){if(Lc.isInstance(N)){let z={},Qe=!1;if(N.text!=null)try{z=JSON.parse(N.text),Qe=!0}catch{}let Oe=z.thought||z.description||"",ja=Oe.length>300?`${Oe.slice(0,300)}\u2026`:Oe,Fl=!z.action||typeof z.action=="object"&&Object.keys(z.action).length===0,Ua=[],Ba=ke(N.usage,H);Ba&&Ua.push(Ba);let Ga={systemPrompt:h,userPrompt:E,rawLlmResponse:N.text??"",tokenUsages:Ua};if(Qe&&Fl)return{status:"error",reasoning:Oe||"No matching element/action found",goalAccomplished:z.completes_instruction??!1,error:ja?`No matching element/action: ${ja}`:"Agent did not generate any action (no matching element found)",debugInfo:Ga};let Ka=Qe?"Action generation failed: the model returned an action that did not match any known action schema.":"Action generation failed: the model returned a response that could not be parsed as a valid action.";return{status:"error",reasoning:Oe||Ka,goalAccomplished:z.completes_instruction??!1,error:Ka,debugInfo:Ga}}throw N}if(K.output==null){let N=K.finishReason,z=N==="length"?"Action generation failed: the model response was truncated before a complete action could be produced (token limit reached).":N==="content-filter"?"Action generation failed: the model response was blocked by a content filter.":`Action generation failed: the model stopped before producing an action (finishReason=${N??"unknown"}).`,Qe=[],Oe=ke(K.usage,H);return Oe&&Qe.push(Oe),{status:"error",reasoning:"",goalAccomplished:!1,error:z,debugInfo:{systemPrompt:h,userPrompt:E,rawLlmResponse:K.text??"",tokenUsages:Qe}}}let Q=K.reasoningText;f.info(`Action Generation Reasoning: ${Q}`);let U=K.output,J=JSON.stringify(U,null,2);f.info(`Generate Action Raw Output: ${J}`);let he=[],qe=ke(K.usage,H);qe&&he.push(qe);let Ie={systemPrompt:h,userPrompt:E,rawLlmResponse:J,tokenUsages:he},be=U.thought||"",Ce=U.description||"",Ze=U.action||{},W=U.completes_instruction||!1;if(!Ze||Object.keys(Ze).length===0)return{status:"error",reasoning:be||Ce||"No action generated",goalAccomplished:W,error:"Agent did not generate any action",debugInfo:Ie};let q=Object.keys(Ze)[0];if(q==="done")return{status:"error",reasoning:be||Ce||"Task marked as done",goalAccomplished:W,error:"Agent indicated task is done without generating an action",debugInfo:Ie};if(q==="perform_accurate_operation")return await ot(e,t,i);if(!W){let N="Can't complete the instruction in one action";return{status:"error",reasoning:be||Ce||N,goalAccomplished:!1,error:N,debugInfo:Ie}}let ee=Ze[q]||{},Pe={};if(typeof ee.element_index=="number"){let N=ee.element_index;if(N<0)return{status:"error",reasoning:be||Ce||"No action generated",goalAccomplished:W,error:"Agent did not generate any action",debugInfo:Ie};let z=w.selectorMap.get(N);z&&(Pe=await j(n,z))}let Wa=Ce;return q==="verify"&&(Wa=e,ee.statement=e),{status:"success",actionEntity:{...Pe,action_description:Wa||be||`${q}(${JSON.stringify(ee)})`,action_data:{action_name:q,kwargs:ee}},reasoning:be||Ce,goalAccomplished:W,debugInfo:Ie}}var Hi=v(()=>{"use strict";rt();Ni();De();Di();At();_e();ae();Fe();Ee();Z();B()});import{generateText as Wc,Output as jc}from"ai";import{z as Wi}from"zod";function Uc(e){if(!e)return null;if(e instanceof URL)return e.href;if(typeof e=="object"&&e.href)return String(e.href);if(typeof e=="object"&&typeof e.toString=="function"){let t=e.toString();if(t.startsWith("http://")||t.startsWith("https://"))return t}return typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://"))?e:null}async function Kn(e,t,i={}){return i.usePureVision?ot(e,t,i):Mo(e,t,i)}function Gc(){let e=new Date,t=e.toLocaleDateString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/Los_Angeles"}),i=e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZoneName:"short",timeZone:"America/Los_Angeles"});return{dateString:t,timeString:i}}function Kc(){return`# Role
165
+ `),h=bo(y),v=await r,_=vo(g,e,t.variables,t.executionHistory,v.length>0?v:void 0,p,s,void 0,c,t.sensitiveKeys),x=[];i.chatHistory&&i.chatHistory.length>0&&i.chatHistory.forEach(N=>{N.role==="user"?x.push({role:"user",content:N.content}):N.role==="assistant"&&x.push({role:"assistant",content:N.content})}),x.push({role:"user",content:_});let E=Hc(x),$=V.buildActionUnionSchema(),I=Fi.object({thought:Fi.string().describe("Step by step reasoning of your decision making process").optional().default(""),description:Fi.string().describe("Detailed description of the action to be performed").optional().default(""),action:$,completes_instruction:Fi.boolean().describe("Whether this action completes the given instruction").optional().default(!0)}),D=Array.isArray(_)?_.filter(N=>N.type==="file").length:0,C=[o,...a.getFallbackModels().filter(N=>N!==o)],H=o,K;try{K=await ot(C,N=>{H=N;let z=Se(N,i.temperature);return Nc({model:fe(N),instructions:h,messages:x,...z!==void 0?{temperature:z}:{},output:Dc.object({schema:I}),providerOptions:we(N,D),maxRetries:4})},(N,z)=>T.log(`Action-gen model ${N} unavailable; falling back to ${z}`))}catch(N){if(Lc.isInstance(N)){let z={},et=!1;if(N.text!=null)try{z=JSON.parse(N.text),et=!0}catch{}let Oe=z.thought||z.description||"",ja=Oe.length>300?`${Oe.slice(0,300)}\u2026`:Oe,Fl=!z.action||typeof z.action=="object"&&Object.keys(z.action).length===0,Ua=[],Ba=ke(N.usage,H);Ba&&Ua.push(Ba);let Ga={systemPrompt:h,userPrompt:E,rawLlmResponse:N.text??"",tokenUsages:Ua};if(et&&Fl)return{status:"error",reasoning:Oe||"No matching element/action found",goalAccomplished:z.completes_instruction??!1,error:ja?`No matching element/action: ${ja}`:"Agent did not generate any action (no matching element found)",debugInfo:Ga};let Ka=et?"Action generation failed: the model returned an action that did not match any known action schema.":"Action generation failed: the model returned a response that could not be parsed as a valid action.";return{status:"error",reasoning:Oe||Ka,goalAccomplished:z.completes_instruction??!1,error:Ka,debugInfo:Ga}}throw N}if(K.output==null){let N=K.finishReason,z=N==="length"?"Action generation failed: the model response was truncated before a complete action could be produced (token limit reached).":N==="content-filter"?"Action generation failed: the model response was blocked by a content filter.":`Action generation failed: the model stopped before producing an action (finishReason=${N??"unknown"}).`,et=[],Oe=ke(K.usage,H);return Oe&&et.push(Oe),{status:"error",reasoning:"",goalAccomplished:!1,error:z,debugInfo:{systemPrompt:h,userPrompt:E,rawLlmResponse:K.text??"",tokenUsages:et}}}let Q=K.reasoningText;f.info(`Action Generation Reasoning: ${Q}`);let U=K.output,J=JSON.stringify(U,null,2);f.info(`Generate Action Raw Output: ${J}`);let he=[],Ze=ke(K.usage,H);Ze&&he.push(Ze);let Ie={systemPrompt:h,userPrompt:E,rawLlmResponse:J,tokenUsages:he},be=U.thought||"",Ce=U.description||"",Qe=U.action||{},W=U.completes_instruction||!1;if(!Qe||Object.keys(Qe).length===0)return{status:"error",reasoning:be||Ce||"No action generated",goalAccomplished:W,error:"Agent did not generate any action",debugInfo:Ie};let q=Object.keys(Qe)[0];if(q==="done")return{status:"error",reasoning:be||Ce||"Task marked as done",goalAccomplished:W,error:"Agent indicated task is done without generating an action",debugInfo:Ie};if(q==="perform_accurate_operation")return await rt(e,t,i);if(!W){let N="Can't complete the instruction in one action";return{status:"error",reasoning:be||Ce||N,goalAccomplished:!1,error:N,debugInfo:Ie}}let ee=Qe[q]||{},Pe={};if(typeof ee.element_index=="number"){let N=ee.element_index;if(N<0)return{status:"error",reasoning:be||Ce||"No action generated",goalAccomplished:W,error:"Agent did not generate any action",debugInfo:Ie};let z=w.selectorMap.get(N);z&&(Pe=await j(n,z))}let Wa=Ce;return q==="verify"&&(Wa=e,ee.statement=e),{status:"success",actionEntity:{...Pe,action_description:Wa||be||`${q}(${JSON.stringify(ee)})`,action_data:{action_name:q,kwargs:ee}},reasoning:be||Ce,goalAccomplished:W,debugInfo:Ie}}var Hi=b(()=>{"use strict";st();Ni();De();Di();At();_e();ae();Fe();Ee();Z();B()});import{generateText as Wc,Output as jc}from"ai";import{z as Wi}from"zod";function Uc(e){if(!e)return null;if(e instanceof URL)return e.href;if(typeof e=="object"&&e.href)return String(e.href);if(typeof e=="object"&&typeof e.toString=="function"){let t=e.toString();if(t.startsWith("http://")||t.startsWith("https://"))return t}return typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://"))?e:null}async function Kn(e,t,i={}){return i.usePureVision?rt(e,t,i):Mo(e,t,i)}function Gc(){let e=new Date,t=e.toLocaleDateString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/Los_Angeles"}),i=e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZoneName:"short",timeZone:"America/Los_Angeles"});return{dateString:t,timeString:i}}function Kc(){return`# Role
144
166
  You are an experienced QA person for web applications.
145
167
  You are tasked to verify the validity of a given statement based on the screenshot and element tree of a web page.
146
168
  `}async function Io(e,t,i={}){let{page:n,executionHistory:a}=t,o=t.agentServices.getModel();try{let r=t.agentServices.isSlicedScreenshotsEnabled(),s=t.agentServices.isResizeSlicedScreenshotsEnabled(),l=t.agentServices.isKnowledgeImagesEnabled(),c=t.agentServices.isAccessibilityTreeEnabled(),{domTree:d,screenshotBase64:u,slicedScreenshotsBase64:m,domState:p,pageContext:w}=await Ri(t,{useCleanScreenshot:i.useCleanScreenshotForAssertion,useSlicedScreenshots:r,resizeSlicedScreenshots:s,useAccessibilityTree:c});t.domState=p;let g="";a&&a.length>0&&(g=`
@@ -148,7 +170,7 @@ You are tasked to verify the validity of a given statement based on the screensh
148
170
  ${a.map(([W,q],ee)=>`${ee+1}. Action: ${W}
149
171
  Result: ${q}`).join(`
150
172
  `)}
151
- `);let{dateString:y,timeString:h}=Gc(),b=`
173
+ `);let{dateString:y,timeString:h}=Gc(),v=`
152
174
  # User statement
153
175
  "${e}"
154
176
 
@@ -167,22 +189,22 @@ ${d}
167
189
 
168
190
  ## Screenshot
169
191
  ${r&&m?"The following images are sliced screenshots of the current webpage (left, middle, right sections).":"The image provided is a screenshot of the current webpage."}
170
- `,x="";if(t.variables&&Object.keys(t.variables).length>0){let W=[];for(let q of Object.keys(t.variables))if(!t.sensitiveKeys?.has(q)){let ee=t.variables[q],Pe=typeof ee=="string"?ee:JSON.stringify(ee);W.push(` - ${q}: "${Pe}"`)}W.length>0&&(x=`
192
+ `,_="";if(t.variables&&Object.keys(t.variables).length>0){let W=[];for(let q of Object.keys(t.variables))if(!t.sensitiveKeys?.has(q)){let ee=t.variables[q],Pe=typeof ee=="string"?ee:JSON.stringify(ee);W.push(` - ${q}: "${Pe}"`)}W.length>0&&(_=`
171
193
  ## Available Variables
172
194
  The following non-sensitive variables are available:
173
195
  ${W.join(`
174
- `)}`)}let S=`
175
- ${x}
196
+ `)}`)}let x=`
197
+ ${_}
176
198
  ${g}
177
199
 
178
200
  Today is ${y}. Current local time is ${h}.
179
201
  Based on the above information, please determine if the statement is true.
180
- `,E=await t.agentServices.retrieveKnowledges(e),$=[{type:"text",text:b}],O=0;if(r&&m&&m.length>0)for(let W of m)$.push({type:"image",image:W}),O++;else $.push({type:"image",image:u}),O=1;if(E&&E.length>0){let W=Li(E,l);$.push(...W)}$.push({type:"text",text:S});let D=E?yo(E,l):0,I=O+D,H=Kc(),K=[o,...t.agentServices.getFallbackModels().filter(W=>W!==o)],Q=o,U=await at(K,W=>{Q=W;let q=Se(W,i.temperature);return Wc({model:fe(W),system:H,messages:[{role:"user",content:$}],output:jc.object({schema:Bc}),...q!==void 0?{temperature:q}:{},providerOptions:we(W,I)})}),{conclusion:J,explanation:he}=U.output,qe=JSON.stringify(U.output,null,2),Ie=[],be=ke(U.usage,Q);be&&Ie.push(be);let Ce=[{role:"user",content:$.map(W=>{if(W.type==="text")return{type:"text",text:W.text};if(W.type==="image"){let q=W.image,ee=Uc(q);if(ee)return{type:"image",file:ee};let Pe=typeof q=="string"?q:"";return{type:"image",file:Pe.startsWith("data:")?Pe:`data:image/png;base64,${Pe}`}}return{type:"text",text:"[unknown content type]"}})}],Ze={systemPrompt:H,userPrompt:Ce,rawLlmResponse:qe,screenshotWithSom:u,tokenUsages:Ie,retrievedKnowledges:E&&E.length>0?E:void 0,elementTree:d};return{success:J==="true",explanation:he,debugInfo:Ze}}catch(r){return{success:!1,error:r.message}}}var Bc,ji=v(()=>{"use strict";Hi();rt();De();At();Tt();Fe();Ee();Bc=Wi.object({screenshotDescription:Wi.string().describe(`Description of the screenshot content, listing out key elements along with their Set of Mark indices,
202
+ `,E=await t.agentServices.retrieveKnowledges(e),$=[{type:"text",text:v}],I=0;if(r&&m&&m.length>0)for(let W of m)$.push({type:"file",mediaType:"image/png",data:W}),I++;else $.push({type:"file",mediaType:"image/png",data:u}),I=1;if(E&&E.length>0){let W=Li(E,l);$.push(...W)}$.push({type:"text",text:x});let D=E?yo(E,l):0,C=I+D,H=Kc(),K=[o,...t.agentServices.getFallbackModels().filter(W=>W!==o)],Q=o,U=await ot(K,W=>{Q=W;let q=Se(W,i.temperature);return Wc({model:fe(W),instructions:H,messages:[{role:"user",content:$}],output:jc.object({schema:Bc}),...q!==void 0?{temperature:q}:{},providerOptions:we(W,C)})}),{conclusion:J,explanation:he}=U.output,Ze=JSON.stringify(U.output,null,2),Ie=[],be=ke(U.usage,Q);be&&Ie.push(be);let Ce=[{role:"user",content:$.map(W=>{if(W.type==="text")return{type:"text",text:W.text};if(W.type==="file"){let q=W.data,ee=Uc(q);if(ee)return{type:"image",file:ee};let Pe=typeof q=="string"?q:"";return{type:"image",file:Pe.startsWith("data:")?Pe:`data:image/png;base64,${Pe}`}}return{type:"text",text:"[unknown content type]"}})}],Qe={systemPrompt:H,userPrompt:Ce,rawLlmResponse:Ze,screenshotWithSom:u,tokenUsages:Ie,retrievedKnowledges:E&&E.length>0?E:void 0,elementTree:d};return{success:J==="true",explanation:he,debugInfo:Qe}}catch(r){return{success:!1,error:r.message}}}var Bc,ji=b(()=>{"use strict";Hi();st();De();At();Tt();Fe();Ee();Bc=Wi.object({screenshotDescription:Wi.string().describe(`Description of the screenshot content, listing out key elements along with their Set of Mark indices,
181
203
  and a description of their location: formatting example: [12] A red button with text "Submit", next to [11]
182
204
  [45] A modal dialog titled "Confirmation",
183
- in the center of the screen`),explanation:Wi.string().describe("Step by step reasoning explaining your conclusion about the statement"),conclusion:Wi.enum(["true","false","unknown"]).describe("Whether the statement is true, false, or unknown if you cannot make a conclusion")})});async function Po(){let{default:e}=await import("sharp");return e}async function zn(e,t){let i=await Po(),n=await i(e).metadata(),a=n.width||0,o=n.height||0;if(a===0||o===0)throw new Error("Invalid image dimensions");let r=o,s=0,l=Math.floor((a-r)/2),c=Math.max(0,a-r),d=(w,g)=>{let y=i(e).extract({left:w,top:0,width:g,height:r});return t?.resize&&(y=y.resize(Co,Co)),y.png().toBuffer()},[u,m,p]=await Promise.all([d(s,Math.min(r,a)),d(l,Math.min(r,a-l)),d(c,Math.min(r,a-c))]);return[u,m,p]}async function Oo(e){let t=(await Po())(e),i=await t.metadata(),n=i.width||0,a=i.height||0;if(n===0||a===0)throw new Error("Invalid image dimensions");let{data:o}=await t.grayscale().raw().toBuffer({resolveWithObject:!0}),r=[];for(let s=0;s<a;s++){r[s]=[];for(let l=0;l<n;l++)r[s][l]=o[s*n+l]}return{pixels:r,width:n,height:a}}var Co,It=v(()=>{"use strict";Co=768});function No(e,t){return e.length>t?e.slice(0,t)+"...":e}var Ct=v(()=>{"use strict"});var Lo,Do,Pt=v(()=>{"use strict";Lo=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","data-id","data-testid","data-test-id","data-handlepos","data-item-id"],Do={"react-flow__(\\S+)":"$1"}});var Ro,Ot,Te,st=v(()=>{"use strict";Ct();Pt();Ro=class{constructor(e,t=null){this.isVisible=e,this.parent=t}},Ot=class extends Ro{constructor(e,t,i=null){super(t,i),this.text=e,this.type="TEXT_NODE"}hasParentWithHighlightIndex(){let e=this.parent;for(;e!==null;){if(e.highlightIndex!==null)return!0;e=e.parent}return!1}isParentInViewport(){return this.parent===null?!1:this.parent.isInViewport}isParentTopElement(){return this.parent===null?!1:this.parent.isTopElement}},Te=class Ui extends Ro{constructor(t,i,n,a,o,r=!1,s=!1,l=!1,c=!1,d=!1,u=!1,m=null,p=null,w=null,g=null,y=[],h=null){super(o,h),this.tagName=t,this.xpath=i,this.attributes=n,this.children=a,this.isInteractive=r,this.isScrollable=s,this.markAsClickable=l,this.isTopElement=c,this.isInViewport=d,this.shadowRoot=u,this.highlightIndex=m,this.viewportCoordinates=p,this.pageCoordinates=w,this.viewportInfo=g,this.isNew=null,this.shadowHostXPaths=y}getAllTextTillNextClickableElement(t=-1){let i=[],n=(a,o)=>{if(!(t!==-1&&o>t)&&!(a instanceof Ui&&a!==this&&a.highlightIndex!==null)){if(a instanceof Ot)i.push(a.text);else if(a instanceof Ui)for(let r of a.children)n(r,o+1)}};return n(this,0),i.join(`
184
- `).trim()}clickableElementsToString(t){let i=t?.includeAttributes??Lo,n=t?.includeClassesWithRename??Do,a=[],o=(r,s)=>{let l=s,c=" ".repeat(s);if(r instanceof Ui){if(r.highlightIndex!==null){l+=1;let d=r.isScrollable?"":r.getAllTextTillNextClickableElement(),u=null;if(i.length>0){let h={};for(let S of Object.keys(r.attributes))if(i.includes(S)){let E=r.attributes[S].trim();E!==""&&(h[S]=E)}let b=i.filter(S=>S in h);if(b.length>1){let S=new Set,E={};for(let $ of b){let O=h[$];O.length>5&&(O in E?S.add($):E[O]=$)}for(let $ of S)delete h[$]}r.tagName===h.role&&delete h.role;let x=["aria-label","placeholder","title"];for(let S of x)h[S]&&h[S].trim().toLowerCase()===d.trim().toLowerCase()&&delete h[S];Object.keys(h).length>0&&(u=Object.entries(h).map(([S,E])=>`${S}=${No(E,200)}`).join(" "))}let m=r.isNew?`*[${r.highlightIndex}]`:`[${r.highlightIndex}]`,p=[];if(Object.keys(n).length>0&&r.attributes.class){let h=r.attributes.class.split(/\s+/);for(let b of h)for(let[x,S]of Object.entries(n))try{let E=new RegExp(`^${x}$`);if(b.match(E)){let $=b.replace(E,S);$&&p.push($);break}}catch{continue}}let w=r.isScrollable?" (SCROLLABLE)":"",g=r.markAsClickable?" (CLICKABLE)":"",y=`${c}${m}${w}${g}<${r.tagName}`;if(p.length>0&&(y+=` ${p.join(" ")}`),u&&(y+=` ${u}`),d){let h=d.trim();u||(y+=" "),y+=`>${h}`}else u||(y+=" ");y+=" />",a.push(y)}else{let d=["data-testid","data-test-id"].filter(u=>r.attributes[u]);d.length>0&&(l+=1,a.push(`${c}<${r.tagName} ${d.map(u=>`${u}="${r.attributes[u]}"`).join(" ")} />`))}for(let d of r.children)o(d,l)}else if(r instanceof Ot){if(r.hasParentWithHighlightIndex())return;r.parent&&r.parent.isVisible&&r.parent.isTopElement&&a.push(`${c}${r.text}`)}};return o(this,0),a.join(`
185
- `)}}});var Vn,Xn,Jn,Yn,Nt=v(()=>{"use strict";Vn=new Set(["button","link","textbox","checkbox","radio","combobox","listbox","menuitem","menuitemcheckbox","menuitemradio","option","tab","switch","slider","spinbutton","searchbox","scrollbar","treeitem","gridcell"]),Xn=new Set(["click","mousedown","mouseup","dblclick","pointerdown","pointerup","touchstart","touchend"]),Jn=["[onclick]","[onmousedown]","[ontouchstart]","div","span","li","tr","td","[role]",'[class*="btn"]','[class*="button"]','[class*="click"]',"[data-action]","[data-click]"],Yn=500});function Xc(e){return e==="about:blank"||e==="chrome://newtab/"||e==="edge://newtab/"||e==="about:newtab"}var zc,Vc,He,ze=v(()=>{"use strict";It();st();Nt();B();zc=`(
205
+ in the center of the screen`),explanation:Wi.string().describe("Step by step reasoning explaining your conclusion about the statement"),conclusion:Wi.enum(["true","false","unknown"]).describe("Whether the statement is true, false, or unknown if you cannot make a conclusion")})});async function Po(){let{default:e}=await import("sharp");return e}async function zn(e,t){let i=await Po(),n=await i(e).metadata(),a=n.width||0,o=n.height||0;if(a===0||o===0)throw new Error("Invalid image dimensions");let r=o,s=0,l=Math.floor((a-r)/2),c=Math.max(0,a-r),d=(w,g)=>{let y=i(e).extract({left:w,top:0,width:g,height:r});return t?.resize&&(y=y.resize(Co,Co)),y.png().toBuffer()},[u,m,p]=await Promise.all([d(s,Math.min(r,a)),d(l,Math.min(r,a-l)),d(c,Math.min(r,a-c))]);return[u,m,p]}async function Oo(e){let t=(await Po())(e),i=await t.metadata(),n=i.width||0,a=i.height||0;if(n===0||a===0)throw new Error("Invalid image dimensions");let{data:o}=await t.grayscale().raw().toBuffer({resolveWithObject:!0}),r=[];for(let s=0;s<a;s++){r[s]=[];for(let l=0;l<n;l++)r[s][l]=o[s*n+l]}return{pixels:r,width:n,height:a}}var Co,It=b(()=>{"use strict";Co=768});function No(e,t){return e.length>t?e.slice(0,t)+"...":e}var Ct=b(()=>{"use strict"});var Lo,Do,Pt=b(()=>{"use strict";Lo=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","data-id","data-testid","data-test-id","data-handlepos","data-item-id"],Do={"react-flow__(\\S+)":"$1"}});var Ro,Ot,Te,lt=b(()=>{"use strict";Ct();Pt();Ro=class{constructor(e,t=null){this.isVisible=e,this.parent=t}},Ot=class extends Ro{constructor(e,t,i=null){super(t,i),this.text=e,this.type="TEXT_NODE"}hasParentWithHighlightIndex(){let e=this.parent;for(;e!==null;){if(e.highlightIndex!==null)return!0;e=e.parent}return!1}isParentInViewport(){return this.parent===null?!1:this.parent.isInViewport}isParentTopElement(){return this.parent===null?!1:this.parent.isTopElement}},Te=class Ui extends Ro{constructor(t,i,n,a,o,r=!1,s=!1,l=!1,c=!1,d=!1,u=!1,m=null,p=null,w=null,g=null,y=[],h=null){super(o,h),this.tagName=t,this.xpath=i,this.attributes=n,this.children=a,this.isInteractive=r,this.isScrollable=s,this.markAsClickable=l,this.isTopElement=c,this.isInViewport=d,this.shadowRoot=u,this.highlightIndex=m,this.viewportCoordinates=p,this.pageCoordinates=w,this.viewportInfo=g,this.isNew=null,this.shadowHostXPaths=y}getAllTextTillNextClickableElement(t=-1){let i=[],n=(a,o)=>{if(!(t!==-1&&o>t)&&!(a instanceof Ui&&a!==this&&a.highlightIndex!==null)){if(a instanceof Ot)i.push(a.text);else if(a instanceof Ui)for(let r of a.children)n(r,o+1)}};return n(this,0),i.join(`
206
+ `).trim()}clickableElementsToString(t){let i=t?.includeAttributes??Lo,n=t?.includeClassesWithRename??Do,a=[],o=(r,s)=>{let l=s,c=" ".repeat(s);if(r instanceof Ui){if(r.highlightIndex!==null){l+=1;let d=r.isScrollable?"":r.getAllTextTillNextClickableElement(),u=null;if(i.length>0){let h={};for(let x of Object.keys(r.attributes))if(i.includes(x)){let E=r.attributes[x].trim();E!==""&&(h[x]=E)}let v=i.filter(x=>x in h);if(v.length>1){let x=new Set,E={};for(let $ of v){let I=h[$];I.length>5&&(I in E?x.add($):E[I]=$)}for(let $ of x)delete h[$]}r.tagName===h.role&&delete h.role;let _=["aria-label","placeholder","title"];for(let x of _)h[x]&&h[x].trim().toLowerCase()===d.trim().toLowerCase()&&delete h[x];Object.keys(h).length>0&&(u=Object.entries(h).map(([x,E])=>`${x}=${No(E,200)}`).join(" "))}let m=r.isNew?`*[${r.highlightIndex}]`:`[${r.highlightIndex}]`,p=[];if(Object.keys(n).length>0&&r.attributes.class){let h=r.attributes.class.split(/\s+/);for(let v of h)for(let[_,x]of Object.entries(n))try{let E=new RegExp(`^${_}$`);if(v.match(E)){let $=v.replace(E,x);$&&p.push($);break}}catch{continue}}let w=r.isScrollable?" (SCROLLABLE)":"",g=r.markAsClickable?" (CLICKABLE)":"",y=`${c}${m}${w}${g}<${r.tagName}`;if(p.length>0&&(y+=` ${p.join(" ")}`),u&&(y+=` ${u}`),d){let h=d.trim();u||(y+=" "),y+=`>${h}`}else u||(y+=" ");y+=" />",a.push(y)}else{let d=["data-testid","data-test-id"].filter(u=>r.attributes[u]);d.length>0&&(l+=1,a.push(`${c}<${r.tagName} ${d.map(u=>`${u}="${r.attributes[u]}"`).join(" ")} />`))}for(let d of r.children)o(d,l)}else if(r instanceof Ot){if(r.hasParentWithHighlightIndex())return;r.parent&&r.parent.isVisible&&r.parent.isTopElement&&a.push(`${c}${r.text}`)}};return o(this,0),a.join(`
207
+ `)}}});var Vn,Xn,Jn,Yn,Nt=b(()=>{"use strict";Vn=new Set(["button","link","textbox","checkbox","radio","combobox","listbox","menuitem","menuitemcheckbox","menuitemradio","option","tab","switch","slider","spinbutton","searchbox","scrollbar","treeitem","gridcell"]),Xn=new Set(["click","mousedown","mouseup","dblclick","pointerdown","pointerup","touchstart","touchend"]),Jn=["[onclick]","[onmousedown]","[ontouchstart]","div","span","li","tr","td","[role]",'[class*="btn"]','[class*="button"]','[class*="click"]',"[data-action]","[data-click]"],Yn=500});function Xc(e){return e==="about:blank"||e==="chrome://newtab/"||e==="edge://newtab/"||e==="about:newtab"}var zc,Vc,He,Ve=b(()=>{"use strict";It();lt();Nt();B();zc=`(
186
208
  args = {
187
209
  doHighlightElements: true,
188
210
  focusHighlightIndex: -1,
@@ -3998,7 +4020,7 @@ Based on the above information, please determine if the statement is true.
3998
4020
  // Return element data from boxes phase for use in labels phase
3999
4021
  elementData: phase === 'boxes' ? collectedElementData : undefined,
4000
4022
  };
4001
- })`;He=class{normalizeDomain(e){let t=e.trim().toLowerCase();if(!t)return"";try{if(t.includes("://"))return new URL(t).hostname.toLowerCase()}catch{return""}return t.split("/")[0].split(":")[0]}isConfiguredIframeFallbackDomain(e,t){let i;try{i=new URL(e).hostname.toLowerCase()}catch{return!1}for(let n of t){let a=this.normalizeDomain(n);if(a&&(i===a||i.endsWith(`.${a}`)))return!0}return!1}shouldProcessWithPlaywrightFrameFallback(e,t){if(!e.inaccessibleFrame)return!1;let i=e.attributes?.src;return i?i.startsWith("chrome-extension://")?!0:this.isConfiguredIframeFallbackDomain(i,t):!1}constructor(e={}){f.debug("\u{1F333} Initializing DomService with options:",e),this.useDomTreeTs=e.useDomTreeTs??!1,this.domTreeRoot=e.domTreeRoot??"body",this.jsCode=this.useDomTreeTs?Vc:zc}async getClickableElements(e,t={}){let{highlightElements:i=!0,focusElement:n=-1,viewportExpansion:a=0,interactiveClassNames:o=[],playwrightFrameFallbackDomains:r=[],alwaysHighlightFileInput:s=!1,sameRectIoUThreshold:l,actionIntent:c="all"}=t,[d,u]=await this.buildDomTree(e,i,n,a,o,r,s,l,c);return{elementTree:d,selectorMap:u}}async getClickableElementsWithScreenshot(e,t={}){if(t.useAccessibilityTree)return this.getClickableElementsWithAXTree(e,t);let i;t.useCleanScreenshot&&(i=await e.screenshot({type:"png",fullPage:!1}));let n=await this.getClickableElements(e,t);if(await e.waitForTimeout(100),t.useCleanScreenshot||(i=await e.screenshot({type:"png",fullPage:!1})),await this.removeHighlights(e,t.playwrightFrameFallbackDomains||[]),!i)throw new Error("Failed to capture screenshot: screenshot buffer is undefined");let a=i.toString("base64"),o;if(t.useSlicedScreenshots)try{o=(await zn(i,{resize:t.resizeSlicedScreenshots})).map(r=>r.toString("base64"))}catch(r){f.warn("Failed to slice screenshot:",r)}return{domState:n,screenshotBase64:a,screenshot:i,slicedScreenshotsBase64:o}}async getClickableElementsWithAXTree(e,t={}){f.debug("\u{1F333} Using CDP Accessibility Tree for element detection");let i;t.useCleanScreenshot&&(i=await e.screenshot({type:"png",fullPage:!1}));let n=await e.context().newCDPSession(e),{nodes:a}=await n.send("Accessibility.getFullAXTree",{depth:-1});f.debug(`\u{1F4CA} Got ${a.length} AXNodes from accessibility tree`);let o=a.filter(h=>{if(h.ignored)return!1;let b=h.role?.value;return!(!b||!Vn.has(b)||h.properties?.find(x=>x.name==="disabled")?.value?.value||!h.backendDOMNodeId)});f.debug(`\u2705 Found ${o.length} interactive elements from AXTree`);let r=a.filter(h=>h.role?.value==="button");f.debug(`\u{1F518} Total buttons in AXTree: ${r.length}`);for(let h of r){let b=[];h.ignored&&b.push("ignored"),h.backendDOMNodeId||b.push("no-backendDOMNodeId"),h.properties?.find(x=>x.name==="disabled")?.value?.value&&b.push("disabled"),f.debug(` - "${h.name?.value||"(no name)"}" ${b.length>0?`[SKIPPED: ${b.join(", ")}]`:"[INCLUDED]"}`)}let s=new Set(o.map(h=>h.backendDOMNodeId)),l=await this.getElementsWithEventListeners(n,t.eventListenerLimit??500),c=0;for(let h of l)s.has(h.backendNodeId)||(o.push({nodeId:`synthetic-${h.backendNodeId}`,ignored:!1,backendDOMNodeId:h.backendNodeId,role:{type:"role",value:"generic"},name:{type:"string",value:""},properties:[{name:"eventListeners",value:{type:"string",value:h.eventTypes.join(",")}}]}),s.add(h.backendNodeId),c++);f.debug(`\u{1F3AF} Added ${c} elements from event listeners (total: ${o.length})`);let d=await this.resolveAXNodesToDOM(n,o),u=d.filter(h=>h.isVisible&&h.isInViewport&&h.isTopElement&&h.boundingRect),m=d.filter(h=>!(h.isVisible&&h.isInViewport&&h.isTopElement&&h.boundingRect));if(m.length>0){f.debug(`\u{1F6AB} Filtered out ${m.length} elements:`);for(let h of m){let b=[];h.isVisible||b.push("not-visible"),h.isInViewport||b.push("not-in-viewport"),h.isTopElement||b.push("not-top-element"),h.boundingRect||b.push("no-bounding-rect"),f.debug(` - <${h.tagName}> "${h.axNode.name?.value||""}" [${b.join(", ")}]`)}}f.debug(`\u{1F441}\uFE0F ${u.length} elements are visible and in viewport`);let{domState:p,highlightIndex:w}=await this.buildDomStateFromAXTree(u);t.highlightElements!==!1&&w>0&&(await this.renderHighlightsForAXElements(e,u.slice(0,w)),await e.waitForTimeout(100)),t.useCleanScreenshot||(i=await e.screenshot({type:"png",fullPage:!1})),await this.removeHighlights(e,t.playwrightFrameFallbackDomains||[]);try{await n.detach()}catch{}if(!i)throw new Error("Failed to capture screenshot: screenshot buffer is undefined");let g=i.toString("base64"),y;if(t.useSlicedScreenshots)try{y=(await zn(i,{resize:t.resizeSlicedScreenshots})).map(h=>h.toString("base64"))}catch(h){f.warn("Failed to slice screenshot:",h)}return{domState:p,screenshotBase64:g,screenshot:i,slicedScreenshotsBase64:y}}async resolveAXNodesToDOM(e,t){let i=[],n=t.map(o=>o.backendDOMNodeId).filter(o=>o!==void 0);if(n.length===0)return i;let a=[];for(let o of n)try{let{object:r}=await e.send("DOM.resolveNode",{backendNodeId:o});a.push(r.objectId||null)}catch{a.push(null)}for(let o=0;o<t.length;o++){let r=t[o],s=a[o];if(s)try{let{result:l}=await e.send("Runtime.callFunctionOn",{objectId:s,functionDeclaration:`function() {
4023
+ })`;He=class{normalizeDomain(e){let t=e.trim().toLowerCase();if(!t)return"";try{if(t.includes("://"))return new URL(t).hostname.toLowerCase()}catch{return""}return t.split("/")[0].split(":")[0]}isConfiguredIframeFallbackDomain(e,t){let i;try{i=new URL(e).hostname.toLowerCase()}catch{return!1}for(let n of t){let a=this.normalizeDomain(n);if(a&&(i===a||i.endsWith(`.${a}`)))return!0}return!1}shouldProcessWithPlaywrightFrameFallback(e,t){if(!e.inaccessibleFrame)return!1;let i=e.attributes?.src;return i?i.startsWith("chrome-extension://")?!0:this.isConfiguredIframeFallbackDomain(i,t):!1}constructor(e={}){f.debug("\u{1F333} Initializing DomService with options:",e),this.useDomTreeTs=e.useDomTreeTs??!1,this.domTreeRoot=e.domTreeRoot??"body",this.jsCode=this.useDomTreeTs?Vc:zc}async getClickableElements(e,t={}){let{highlightElements:i=!0,focusElement:n=-1,viewportExpansion:a=0,interactiveClassNames:o=[],playwrightFrameFallbackDomains:r=[],alwaysHighlightFileInput:s=!1,sameRectIoUThreshold:l,actionIntent:c="all"}=t,[d,u]=await this.buildDomTree(e,i,n,a,o,r,s,l,c);return{elementTree:d,selectorMap:u}}async getClickableElementsWithScreenshot(e,t={}){if(t.useAccessibilityTree)return this.getClickableElementsWithAXTree(e,t);let i;t.useCleanScreenshot&&(i=await e.screenshot({type:"png",fullPage:!1}));let n=await this.getClickableElements(e,t);if(await e.waitForTimeout(100),t.useCleanScreenshot||(i=await e.screenshot({type:"png",fullPage:!1})),await this.removeHighlights(e,t.playwrightFrameFallbackDomains||[]),!i)throw new Error("Failed to capture screenshot: screenshot buffer is undefined");let a=i.toString("base64"),o;if(t.useSlicedScreenshots)try{o=(await zn(i,{resize:t.resizeSlicedScreenshots})).map(r=>r.toString("base64"))}catch(r){f.warn("Failed to slice screenshot:",r)}return{domState:n,screenshotBase64:a,screenshot:i,slicedScreenshotsBase64:o}}async getClickableElementsWithAXTree(e,t={}){f.debug("\u{1F333} Using CDP Accessibility Tree for element detection");let i;t.useCleanScreenshot&&(i=await e.screenshot({type:"png",fullPage:!1}));let n=await e.context().newCDPSession(e),{nodes:a}=await n.send("Accessibility.getFullAXTree",{depth:-1});f.debug(`\u{1F4CA} Got ${a.length} AXNodes from accessibility tree`);let o=a.filter(h=>{if(h.ignored)return!1;let v=h.role?.value;return!(!v||!Vn.has(v)||h.properties?.find(_=>_.name==="disabled")?.value?.value||!h.backendDOMNodeId)});f.debug(`\u2705 Found ${o.length} interactive elements from AXTree`);let r=a.filter(h=>h.role?.value==="button");f.debug(`\u{1F518} Total buttons in AXTree: ${r.length}`);for(let h of r){let v=[];h.ignored&&v.push("ignored"),h.backendDOMNodeId||v.push("no-backendDOMNodeId"),h.properties?.find(_=>_.name==="disabled")?.value?.value&&v.push("disabled"),f.debug(` - "${h.name?.value||"(no name)"}" ${v.length>0?`[SKIPPED: ${v.join(", ")}]`:"[INCLUDED]"}`)}let s=new Set(o.map(h=>h.backendDOMNodeId)),l=await this.getElementsWithEventListeners(n,t.eventListenerLimit??500),c=0;for(let h of l)s.has(h.backendNodeId)||(o.push({nodeId:`synthetic-${h.backendNodeId}`,ignored:!1,backendDOMNodeId:h.backendNodeId,role:{type:"role",value:"generic"},name:{type:"string",value:""},properties:[{name:"eventListeners",value:{type:"string",value:h.eventTypes.join(",")}}]}),s.add(h.backendNodeId),c++);f.debug(`\u{1F3AF} Added ${c} elements from event listeners (total: ${o.length})`);let d=await this.resolveAXNodesToDOM(n,o),u=d.filter(h=>h.isVisible&&h.isInViewport&&h.isTopElement&&h.boundingRect),m=d.filter(h=>!(h.isVisible&&h.isInViewport&&h.isTopElement&&h.boundingRect));if(m.length>0){f.debug(`\u{1F6AB} Filtered out ${m.length} elements:`);for(let h of m){let v=[];h.isVisible||v.push("not-visible"),h.isInViewport||v.push("not-in-viewport"),h.isTopElement||v.push("not-top-element"),h.boundingRect||v.push("no-bounding-rect"),f.debug(` - <${h.tagName}> "${h.axNode.name?.value||""}" [${v.join(", ")}]`)}}f.debug(`\u{1F441}\uFE0F ${u.length} elements are visible and in viewport`);let{domState:p,highlightIndex:w}=await this.buildDomStateFromAXTree(u);t.highlightElements!==!1&&w>0&&(await this.renderHighlightsForAXElements(e,u.slice(0,w)),await e.waitForTimeout(100)),t.useCleanScreenshot||(i=await e.screenshot({type:"png",fullPage:!1})),await this.removeHighlights(e,t.playwrightFrameFallbackDomains||[]);try{await n.detach()}catch{}if(!i)throw new Error("Failed to capture screenshot: screenshot buffer is undefined");let g=i.toString("base64"),y;if(t.useSlicedScreenshots)try{y=(await zn(i,{resize:t.resizeSlicedScreenshots})).map(h=>h.toString("base64"))}catch(h){f.warn("Failed to slice screenshot:",h)}return{domState:p,screenshotBase64:g,screenshot:i,slicedScreenshotsBase64:y}}async resolveAXNodesToDOM(e,t){let i=[],n=t.map(o=>o.backendDOMNodeId).filter(o=>o!==void 0);if(n.length===0)return i;let a=[];for(let o of n)try{let{object:r}=await e.send("DOM.resolveNode",{backendNodeId:o});a.push(r.objectId||null)}catch{a.push(null)}for(let o=0;o<t.length;o++){let r=t[o],s=a[o];if(s)try{let{result:l}=await e.send("Runtime.callFunctionOn",{objectId:s,functionDeclaration:`function() {
4002
4024
  const el = this;
4003
4025
  const rect = el.getBoundingClientRect();
4004
4026
  const rects = el.getClientRects();
@@ -4082,36 +4104,36 @@ Based on the above information, please determine if the statement is true.
4082
4104
  } : null,
4083
4105
  clientRects: clientRectsArray
4084
4106
  };
4085
- }`,returnByValue:!0});l.value&&i.push({axNode:r,...l.value})}catch(l){f.debug(`Failed to resolve element: ${l}`)}}return i}async getElementsWithEventListeners(e,t=Yn){let i=[];try{let{root:n}=await e.send("DOM.getDocument",{depth:0}),a=Jn.join(","),{nodeIds:o}=await e.send("DOM.querySelectorAll",{nodeId:n.nodeId,selector:a});f.debug(`\u{1F50D} Checking ${Math.min(o.length,t)} elements for event listeners`);for(let r of o.slice(0,t))try{let{object:s}=await e.send("DOM.resolveNode",{nodeId:r});if(!s.objectId)continue;let{listeners:l}=await e.send("DOMDebugger.getEventListeners",{objectId:s.objectId}),c=l.filter(d=>Xn.has(d.type));if(c.length>0){let{node:d}=await e.send("DOM.describeNode",{nodeId:r});i.push({backendNodeId:d.backendNodeId,eventTypes:c.map(u=>u.type)})}await e.send("Runtime.releaseObject",{objectId:s.objectId})}catch{}f.debug(`\u2705 Found ${i.length} elements with interaction event listeners`)}catch(n){f.warn("Failed to get elements with event listeners:",n)}return i}async buildDomStateFromAXTree(e){let t=new Map,i=new Te("body","/body",{},[],!0,!1,!1,!1,!0,!0,!1,null),n=0;for(let a of e){let o=a.axNode.role?.value||"",r=a.axNode.name?.value||"",s=["button","link","menuitem","tab","switch"].includes(o),l=new Te(a.tagName,a.xpath,a.attributes,[],a.isVisible,!0,o==="scrollbar",s,a.isTopElement,a.isInViewport,!1,n,a.boundingRect?{topLeft:{x:a.boundingRect.x,y:a.boundingRect.y},topRight:{x:a.boundingRect.x+a.boundingRect.width,y:a.boundingRect.y},bottomLeft:{x:a.boundingRect.x,y:a.boundingRect.y+a.boundingRect.height},bottomRight:{x:a.boundingRect.x+a.boundingRect.width,y:a.boundingRect.y+a.boundingRect.height},center:{x:a.boundingRect.x+a.boundingRect.width/2,y:a.boundingRect.y+a.boundingRect.height/2},width:a.boundingRect.width,height:a.boundingRect.height}:null,null,null,[],i);if(r){let c=new Ot(r,!0,l);l.children.push(c)}i.children.push(l),t.set(n,l),n++}return{domState:{elementTree:i,selectorMap:t},highlightIndex:n}}async renderHighlightsForAXElements(e,t){let i=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];await e.evaluate(({elements:n,colors:a})=>{let o="playwright-highlight-container",r=document.getElementById(o);r||(r=document.createElement("div"),r.id=o,r.style.position="fixed",r.style.pointerEvents="none",r.style.top="0",r.style.left="0",r.style.width="100%",r.style.height="100%",r.style.zIndex="2147483647",r.style.backgroundColor="transparent",document.body.appendChild(r)),n.forEach((s,l)=>{if(!s.boundingRect)return;let c=a[l%a.length],d=s.boundingRect,u=document.createElement("div");u.style.position="fixed",u.style.border=`1px solid ${c}`,u.style.backgroundColor="transparent",u.style.pointerEvents="none",u.style.boxSizing="border-box",u.style.top=`${d.y}px`,u.style.left=`${d.x}px`,u.style.width=`${d.width}px`,u.style.height=`${d.height}px`,r.appendChild(u);let m=document.createElement("div");m.style.position="fixed",m.style.background=c,m.style.color="white",m.style.padding="1px 4px",m.style.borderRadius="4px",m.style.fontSize=l>=100?"8px":"12px",m.textContent=String(l);let p=Math.max(0,d.y-16),w=Math.max(0,Math.min(d.x+d.width-20,window.innerWidth-25));m.style.top=`${p}px`,m.style.left=`${w}px`,r.appendChild(m)})},{elements:t,colors:i})}async removeHighlights(e,t=[]){let i=()=>{let n=document.getElementById("playwright-highlight-container");n&&n.remove(),window._highlightCleanupFunctions&&(window._highlightCleanupFunctions.forEach(a=>a()),window._highlightCleanupFunctions=[])};try{await e.evaluate(i),f.debug("\u2705 Highlights removed from page")}catch(n){f.warn("Failed to remove highlights:",n.message)}for(let n of e.frames()){let a=n.url();if(!(!a.startsWith("chrome-extension://")&&!this.isConfiguredIframeFallbackDomain(a,t)))try{await n.evaluate(i)}catch{}}}async getCrossOriginIframes(e){let t=await e.locator("iframe").filter({hasNot:e.locator(":visible")}).evaluateAll(s=>s.map(l=>l.src)),i=s=>{try{let l=new URL(s);return["doubleclick.net","adroll.com","googletagmanager.com"].some(c=>l.hostname.includes(c))}catch{return!1}},n=e.url(),a=new URL(n).hostname,o=e.frames(),r=[];for(let s of o){let l=s.url();try{let c=new URL(l).hostname;c&&c!==a&&!t.includes(l)&&!i(l)&&r.push(l)}catch{continue}}return r}async buildDomTree(e,t,i,n,a,o,r,s,l="all"){if(await e.evaluate("1+1")!==2)throw new Error("The page cannot evaluate javascript code properly");if(Xc(e.url()))return[new Te("body","",{},[],!1,!1,!1,!1,!1,!1,!1,null),new Map];let c={doHighlightElements:t,focusHighlightIndex:i,viewportExpansion:n,debugMode:!1,interactiveClassNames:a,alwaysHighlightFileInput:r,sameRectIoUThreshold:s,actionIntent:l,domTreeRoot:this.domTreeRoot};f.debug(`\u{1F527} Starting JavaScript DOM analysis for ${e.url().slice(0,50)}...`);let d,u=null;if(this.useDomTreeTs&&t)try{let y={...c,phase:"boxes",grayscaleImage:null},h=await e.evaluate(({code:O,argsObj:D})=>new Function("return "+O)()(D),{code:this.jsCode,argsObj:y});f.debug(`\u{1F4E6} Phase 1: Drew ${h.elementData?.length||0} bounding boxes`);let b=await e.screenshot({type:"png",fullPage:!1});f.debug("\u{1F4F8} Captured screenshot with bounding boxes");let x=performance.now(),S=await Oo(b);u=S.pixels;let E=Math.round(performance.now()-x);f.debug(`\u{1F5BC}\uFE0F Generated grayscale image (${S.width}x${S.height}) in ${E}ms`);let $={...c,phase:"labels",grayscaleImage:u,elementData:h.elementData};d=await e.evaluate(({code:O,argsObj:D})=>new Function("return "+O)()(D),{code:this.jsCode,argsObj:$}),d.map=h.map,d.rootId=h.rootId,d.highlightCount=h.highlightCount,d.perfMetrics=h.perfMetrics,f.debug("\u2705 Phase 2: Labels placed using grayscale-based positioning")}catch(y){f.warn("Two-phase rendering failed, falling back to legacy mode:",y.message),u=null;let h={...c,grayscaleImage:null};d=await e.evaluate(({code:b,argsObj:x})=>new Function("return "+b)()(x),{code:this.jsCode,argsObj:h}),f.debug("\u2705 JavaScript DOM analysis completed (legacy mode)")}else try{d=await e.evaluate(({code:y,argsObj:h})=>new Function("return "+y)()(h),{code:this.jsCode,argsObj:c}),f.debug("\u2705 JavaScript DOM analysis completed")}catch(y){throw f.error("Error evaluating JavaScript:",y.message),y}if(!d||typeof d!="object")throw f.error("JavaScript returned invalid result:",d),new Error("JavaScript DOM analysis returned invalid result");if(!d.map||!d.rootId)throw f.error("JavaScript result missing map or rootId:",JSON.stringify(d,null,2)),new Error("JavaScript result missing required fields (map or rootId)");if(l!=="all"&&d.highlightCount===0){f.debug(`\u26A0\uFE0F No elements matched intent '${l}', falling back to 'all'`);let y={...c,actionIntent:"all"};d=await e.evaluate(({code:h,argsObj:b})=>new Function("return "+h)()(b),{code:this.jsCode,argsObj:y})}let m=Object.entries(d.map).filter(([,y])=>y.tagName==="iframe");f.debug(`\u{1F50D} [ext-iframe] Total iframe nodes in map: ${m.length}`);for(let[y,h]of m){let b=h;f.debug(`\u{1F50D} [ext-iframe] iframe node id=${y} src=${b.attributes?.src} inaccessibleFrame=${b.inaccessibleFrame}`)}let p=e.frames();f.debug(`\u{1F50D} [ext-iframe] Playwright frames count: ${p.length}`);for(let y of p)f.debug(`\u{1F50D} [ext-iframe] Playwright frame url=${y.url()}`);let w=[];for(let[y,h]of Object.entries(d.map)){let b=h;this.shouldProcessWithPlaywrightFrameFallback(b,o)&&w.push({nodeId:y,src:b.attributes.src})}if(f.debug(`\u{1F50D} [ext-iframe] Inaccessible fallback iframes found: ${w.length}`),w.length>0){f.debug(`\u{1F50C} Found ${w.length} inaccessible iframe(s) for Playwright fallback, processing`);let y=-1;for(let h of Object.values(d.map)){let b=h;b.highlightIndex!=null&&(y=Math.max(y,b.highlightIndex))}f.debug(`\u{1F50D} [ext-iframe] Main page max highlight index: ${y}`);for(let h=0;h<w.length;h++){let{nodeId:b,src:x}=w[h];f.debug(`\u{1F50D} [ext-iframe] Processing fallback iframe [${h}]: ${x}`);let S=D=>{try{let I=new URL(D);if(I.protocol==="chrome-extension:"&&I.hostname)return`chrome-extension://${I.hostname}`;let H=I.origin;return H==="null"?null:H}catch{return null}},E=S(x);f.debug(`\u{1F50D} [ext-iframe] iframe src origin=${E??"null"}`);let $=null,O=e.frames().find(D=>{let I=D.url();if(I===x)return $="exact",f.debug(`\u{1F50D} [ext-iframe] Candidate frame matched by exact URL: ${I}`),!0;let H=S(I);return f.debug(`\u{1F50D} [ext-iframe] Candidate frame compare url=${I} origin=${H??"null"} vs srcOrigin=${E??"null"}`),E&&H===E?($="origin",f.debug(`\u{1F50D} [ext-iframe] Candidate frame matched by origin: ${I}`),!0):!1});if(!O){f.debug(`\u26A0\uFE0F [ext-iframe] No Playwright frame found for fallback iframe: ${x}`),f.debug(`\u26A0\uFE0F [ext-iframe] Available frame URLs: ${e.frames().map(D=>D.url()).join(", ")}`);continue}f.debug(`\u{1F50D} [ext-iframe] Found matching Playwright frame for: ${x} (frame url: ${O.url()})`);try{let D={...c,initialHighlightIndex:y+1,domTreeRoot:"body"};f.debug(`\u{1F50D} [ext-iframe] Running dom-tree in extension frame with initialHighlightIndex=${D.initialHighlightIndex}`);let I=await O.evaluate(({code:U,argsObj:J})=>new Function("return "+U)()(J),{code:this.jsCode,argsObj:D});if(f.debug(`\u{1F50D} [ext-iframe] frameEval result: map size=${Object.keys(I?.map??{}).length} rootId=${I?.rootId}`),!I?.map||!I.rootId){f.debug("\u26A0\uFE0F [ext-iframe] frameEval missing map or rootId, skipping");continue}let H=Object.values(I.map).filter(U=>U.highlightIndex!=null);f.debug(`\u{1F50D} [ext-iframe] Interactive elements in extension frame: ${H.length}`);for(let U of H){let J=U;f.debug(`\u{1F50D} [ext-iframe] - <${J.tagName}> highlightIndex=${J.highlightIndex} text="${J.children?.length?"...":""}"`)}for(let U of Object.values(I.map)){let J=U;J.highlightIndex!=null&&(y=Math.max(y,J.highlightIndex))}let K=`ext_${h}_`;for(let[U,J]of Object.entries(I.map)){let he={...J};he.children&&(he.children=he.children.map(qe=>`${K}${qe}`)),d.map[`${K}${U}`]=he}let Q=d.map[b];Q?(Q.children=[...Q.children||[],`${K}${I.rootId}`],f.debug(`\u{1F50D} [ext-iframe] Attached frame root to iframe node ${b}`)):f.debug(`\u26A0\uFE0F [ext-iframe] iframe node ${b} not found in map`),f.debug(`\u2705 Merged fallback iframe content from: ${x}`)}catch(D){f.warn(`Failed to process fallback iframe ${x}:`,D)}}}if(d&&d.perfMetrics){let y=d.perfMetrics.nodeMetrics?.totalNodes??0,h=0;if(d.map)for(let x of Object.values(d.map))typeof x=="object"&&x!==null&&x.isInteractive&&h++;let b=e.url().length>50?e.url().slice(0,50)+"...":e.url();f.debug(`\u{1F50E} Ran buildDOMTree.js interactive element detection on: ${b} interactive=${h}/${y}`)}f.debug("\u{1F504} Starting TypeScript DOM tree construction...");let g=await this.constructDomTree(d);return f.debug("\u2705 TypeScript DOM tree construction completed"),g}async constructDomTree(e){let t=e.map,i=e.rootId,n=new Map,a=new Map,o=new Map;for(let[s,l]of Object.entries(t)){let[c,d]=this.parseNode(l);c!==null&&(a.set(s,c),o.set(s,d),c instanceof Te&&c.highlightIndex!==null&&n.set(c.highlightIndex,c))}for(let[s,l]of o){let c=a.get(s);if(c instanceof Te)for(let d of l){let u=a.get(d);u&&(u.parent=c,c.children.push(u))}}let r=a.get(i);if(!r||!(r instanceof Te))throw new Error("Failed to parse HTML to dictionary");return[r,n]}parseNode(e){if(!e)return[null,[]];if(e.type==="TEXT_NODE")return[new Ot(e.text,e.isVisible,null),[]];let t=null;e.viewport&&(t={width:e.viewport.width,height:e.viewport.height,scrollX:e.viewport.scrollX,scrollY:e.viewport.scrollY});let i=e.shadowHostXPaths??[],n=new Te(e.tagName,e.xpath,e.attributes||{},[],e.isVisible??!1,e.isInteractive??!1,e.isScrollable??!1,e.markAsClickable??!1,e.isTopElement??!1,e.isInViewport??!1,e.shadowRoot??!1,e.highlightIndex??null,e.viewportCoordinates??null,e.pageCoordinates??null,t,i,null),a=e.children||[];return[n,a]}}});import{z as Jc}from"zod";var Fo,ag,Bi=v(()=>{"use strict";Fo=class{async execute(e,t){await e.waitForLoadState("networkidle",{timeout:5e3}).catch(()=>{}),await e.waitForLoadState("domcontentloaded")}transpile(e){return["await page.waitForLoadState('domcontentloaded');"]}},ag=Jc.object({})});var Ho,Gi=v(()=>{"use strict";G();C();Ho=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");if(typeof n.kwargs.relative_x=="number"&&typeof n.kwargs.relative_y=="number"){let a=F(e,t);if(a){await a.waitFor({state:"attached",timeout:R(i,t.action_data?.kwargs?.timeout_ms)});let o=await a.boundingBox();if(o){let r=o.x+n.kwargs.relative_x+o.width/2,s=o.y+n.kwargs.relative_y+o.height/2;await e.mouse.move(r,s),await e.waitForTimeout(200),await e.mouse.click(r,s,{button:"right",delay:100}),await e.waitForTimeout(200)}}else throw new Error("Element-anchored coordinates provided but no locator found")}else if(typeof n.kwargs.x=="number"&&typeof n.kwargs.y=="number")await e.mouse.move(n.kwargs.x,n.kwargs.y),await e.waitForTimeout(200),await e.mouse.click(n.kwargs.x,n.kwargs.y,{button:"right"}),await e.waitForTimeout(200);else throw new Error("Missing or invalid coordinates")}transpile(e){let t=e.action_data?.kwargs||{},i=[];return typeof t.relative_x=="number"&&typeof t.relative_y=="number"?(i.push(`action_data: { kwargs: { relative_x: ${t.relative_x}, relative_y: ${t.relative_y} } }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`)):typeof t.x=="number"&&typeof t.y=="number"&&i.push(`action_data: { kwargs: { x: ${t.x}, y: ${t.y} } }`),['await agent.execAction("right_click_by_coordinates", page, {',...i.map(n=>` ${n},`),"});"]}}});var Wo,Ki=v(()=>{"use strict";G();C();Wo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.keys;if(!a||typeof a!="string")throw new Error("Missing or invalid keys for send keys on element action");let o=F(e,t),r=R(i,t.action_data?.kwargs?.timeout_ms);if(o)await o.press(a,{timeout:r}),await e.waitForTimeout(500);else throw new Error("No locator found for send keys on element action")}transpile(e){let t=Ne(e);if(!t){let a=e.action_data?.kwargs?.keys||"";return['await agent.execAction("send_keys_on_element", page, {',` action_data: { kwargs: { keys: ${JSON.stringify(a)} } },`,"});"]}let i=e.action_data?.kwargs?.keys||"",n=R();return[`await ${t}.press(${JSON.stringify(i)}, { timeout: ${n} });`]}}});var jo,zi=v(()=>{"use strict";jo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.code;if(!a)throw new Error("Missing code for js_action");let o=i.agent;if(!o)throw new Error("Agent not initialized on AgentServices \u2014 js_action requires an agent reference");await new Function("page","agent",`
4107
+ }`,returnByValue:!0});l.value&&i.push({axNode:r,...l.value})}catch(l){f.debug(`Failed to resolve element: ${l}`)}}return i}async getElementsWithEventListeners(e,t=Yn){let i=[];try{let{root:n}=await e.send("DOM.getDocument",{depth:0}),a=Jn.join(","),{nodeIds:o}=await e.send("DOM.querySelectorAll",{nodeId:n.nodeId,selector:a});f.debug(`\u{1F50D} Checking ${Math.min(o.length,t)} elements for event listeners`);for(let r of o.slice(0,t))try{let{object:s}=await e.send("DOM.resolveNode",{nodeId:r});if(!s.objectId)continue;let{listeners:l}=await e.send("DOMDebugger.getEventListeners",{objectId:s.objectId}),c=l.filter(d=>Xn.has(d.type));if(c.length>0){let{node:d}=await e.send("DOM.describeNode",{nodeId:r});i.push({backendNodeId:d.backendNodeId,eventTypes:c.map(u=>u.type)})}await e.send("Runtime.releaseObject",{objectId:s.objectId})}catch{}f.debug(`\u2705 Found ${i.length} elements with interaction event listeners`)}catch(n){f.warn("Failed to get elements with event listeners:",n)}return i}async buildDomStateFromAXTree(e){let t=new Map,i=new Te("body","/body",{},[],!0,!1,!1,!1,!0,!0,!1,null),n=0;for(let a of e){let o=a.axNode.role?.value||"",r=a.axNode.name?.value||"",s=["button","link","menuitem","tab","switch"].includes(o),l=new Te(a.tagName,a.xpath,a.attributes,[],a.isVisible,!0,o==="scrollbar",s,a.isTopElement,a.isInViewport,!1,n,a.boundingRect?{topLeft:{x:a.boundingRect.x,y:a.boundingRect.y},topRight:{x:a.boundingRect.x+a.boundingRect.width,y:a.boundingRect.y},bottomLeft:{x:a.boundingRect.x,y:a.boundingRect.y+a.boundingRect.height},bottomRight:{x:a.boundingRect.x+a.boundingRect.width,y:a.boundingRect.y+a.boundingRect.height},center:{x:a.boundingRect.x+a.boundingRect.width/2,y:a.boundingRect.y+a.boundingRect.height/2},width:a.boundingRect.width,height:a.boundingRect.height}:null,null,null,[],i);if(r){let c=new Ot(r,!0,l);l.children.push(c)}i.children.push(l),t.set(n,l),n++}return{domState:{elementTree:i,selectorMap:t},highlightIndex:n}}async renderHighlightsForAXElements(e,t){let i=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];await e.evaluate(({elements:n,colors:a})=>{let o="playwright-highlight-container",r=document.getElementById(o);r||(r=document.createElement("div"),r.id=o,r.style.position="fixed",r.style.pointerEvents="none",r.style.top="0",r.style.left="0",r.style.width="100%",r.style.height="100%",r.style.zIndex="2147483647",r.style.backgroundColor="transparent",document.body.appendChild(r)),n.forEach((s,l)=>{if(!s.boundingRect)return;let c=a[l%a.length],d=s.boundingRect,u=document.createElement("div");u.style.position="fixed",u.style.border=`1px solid ${c}`,u.style.backgroundColor="transparent",u.style.pointerEvents="none",u.style.boxSizing="border-box",u.style.top=`${d.y}px`,u.style.left=`${d.x}px`,u.style.width=`${d.width}px`,u.style.height=`${d.height}px`,r.appendChild(u);let m=document.createElement("div");m.style.position="fixed",m.style.background=c,m.style.color="white",m.style.padding="1px 4px",m.style.borderRadius="4px",m.style.fontSize=l>=100?"8px":"12px",m.textContent=String(l);let p=Math.max(0,d.y-16),w=Math.max(0,Math.min(d.x+d.width-20,window.innerWidth-25));m.style.top=`${p}px`,m.style.left=`${w}px`,r.appendChild(m)})},{elements:t,colors:i})}async removeHighlights(e,t=[]){let i=()=>{let n=document.getElementById("playwright-highlight-container");n&&n.remove(),window._highlightCleanupFunctions&&(window._highlightCleanupFunctions.forEach(a=>a()),window._highlightCleanupFunctions=[])};try{await e.evaluate(i),f.debug("\u2705 Highlights removed from page")}catch(n){f.warn("Failed to remove highlights:",n.message)}for(let n of e.frames()){let a=n.url();if(!(!a.startsWith("chrome-extension://")&&!this.isConfiguredIframeFallbackDomain(a,t)))try{await n.evaluate(i)}catch{}}}async getCrossOriginIframes(e){let t=await e.locator("iframe").filter({hasNot:e.locator(":visible")}).evaluateAll(s=>s.map(l=>l.src)),i=s=>{try{let l=new URL(s);return["doubleclick.net","adroll.com","googletagmanager.com"].some(c=>l.hostname.includes(c))}catch{return!1}},n=e.url(),a=new URL(n).hostname,o=e.frames(),r=[];for(let s of o){let l=s.url();try{let c=new URL(l).hostname;c&&c!==a&&!t.includes(l)&&!i(l)&&r.push(l)}catch{continue}}return r}async buildDomTree(e,t,i,n,a,o,r,s,l="all"){if(await e.evaluate("1+1")!==2)throw new Error("The page cannot evaluate javascript code properly");if(Xc(e.url()))return[new Te("body","",{},[],!1,!1,!1,!1,!1,!1,!1,null),new Map];let c={doHighlightElements:t,focusHighlightIndex:i,viewportExpansion:n,debugMode:!1,interactiveClassNames:a,alwaysHighlightFileInput:r,sameRectIoUThreshold:s,actionIntent:l,domTreeRoot:this.domTreeRoot};f.debug(`\u{1F527} Starting JavaScript DOM analysis for ${e.url().slice(0,50)}...`);let d,u=null;if(this.useDomTreeTs&&t)try{let y={...c,phase:"boxes",grayscaleImage:null},h=await e.evaluate(({code:I,argsObj:D})=>new Function("return "+I)()(D),{code:this.jsCode,argsObj:y});f.debug(`\u{1F4E6} Phase 1: Drew ${h.elementData?.length||0} bounding boxes`);let v=await e.screenshot({type:"png",fullPage:!1});f.debug("\u{1F4F8} Captured screenshot with bounding boxes");let _=performance.now(),x=await Oo(v);u=x.pixels;let E=Math.round(performance.now()-_);f.debug(`\u{1F5BC}\uFE0F Generated grayscale image (${x.width}x${x.height}) in ${E}ms`);let $={...c,phase:"labels",grayscaleImage:u,elementData:h.elementData};d=await e.evaluate(({code:I,argsObj:D})=>new Function("return "+I)()(D),{code:this.jsCode,argsObj:$}),d.map=h.map,d.rootId=h.rootId,d.highlightCount=h.highlightCount,d.perfMetrics=h.perfMetrics,f.debug("\u2705 Phase 2: Labels placed using grayscale-based positioning")}catch(y){f.warn("Two-phase rendering failed, falling back to legacy mode:",y.message),u=null;let h={...c,grayscaleImage:null};d=await e.evaluate(({code:v,argsObj:_})=>new Function("return "+v)()(_),{code:this.jsCode,argsObj:h}),f.debug("\u2705 JavaScript DOM analysis completed (legacy mode)")}else try{d=await e.evaluate(({code:y,argsObj:h})=>new Function("return "+y)()(h),{code:this.jsCode,argsObj:c}),f.debug("\u2705 JavaScript DOM analysis completed")}catch(y){throw f.error("Error evaluating JavaScript:",y.message),y}if(!d||typeof d!="object")throw f.error("JavaScript returned invalid result:",d),new Error("JavaScript DOM analysis returned invalid result");if(!d.map||!d.rootId)throw f.error("JavaScript result missing map or rootId:",JSON.stringify(d,null,2)),new Error("JavaScript result missing required fields (map or rootId)");if(l!=="all"&&d.highlightCount===0){f.debug(`\u26A0\uFE0F No elements matched intent '${l}', falling back to 'all'`);let y={...c,actionIntent:"all"};d=await e.evaluate(({code:h,argsObj:v})=>new Function("return "+h)()(v),{code:this.jsCode,argsObj:y})}let m=Object.entries(d.map).filter(([,y])=>y.tagName==="iframe");f.debug(`\u{1F50D} [ext-iframe] Total iframe nodes in map: ${m.length}`);for(let[y,h]of m){let v=h;f.debug(`\u{1F50D} [ext-iframe] iframe node id=${y} src=${v.attributes?.src} inaccessibleFrame=${v.inaccessibleFrame}`)}let p=e.frames();f.debug(`\u{1F50D} [ext-iframe] Playwright frames count: ${p.length}`);for(let y of p)f.debug(`\u{1F50D} [ext-iframe] Playwright frame url=${y.url()}`);let w=[];for(let[y,h]of Object.entries(d.map)){let v=h;this.shouldProcessWithPlaywrightFrameFallback(v,o)&&w.push({nodeId:y,src:v.attributes.src})}if(f.debug(`\u{1F50D} [ext-iframe] Inaccessible fallback iframes found: ${w.length}`),w.length>0){f.debug(`\u{1F50C} Found ${w.length} inaccessible iframe(s) for Playwright fallback, processing`);let y=-1;for(let h of Object.values(d.map)){let v=h;v.highlightIndex!=null&&(y=Math.max(y,v.highlightIndex))}f.debug(`\u{1F50D} [ext-iframe] Main page max highlight index: ${y}`);for(let h=0;h<w.length;h++){let{nodeId:v,src:_}=w[h];f.debug(`\u{1F50D} [ext-iframe] Processing fallback iframe [${h}]: ${_}`);let x=D=>{try{let C=new URL(D);if(C.protocol==="chrome-extension:"&&C.hostname)return`chrome-extension://${C.hostname}`;let H=C.origin;return H==="null"?null:H}catch{return null}},E=x(_);f.debug(`\u{1F50D} [ext-iframe] iframe src origin=${E??"null"}`);let $=null,I=e.frames().find(D=>{let C=D.url();if(C===_)return $="exact",f.debug(`\u{1F50D} [ext-iframe] Candidate frame matched by exact URL: ${C}`),!0;let H=x(C);return f.debug(`\u{1F50D} [ext-iframe] Candidate frame compare url=${C} origin=${H??"null"} vs srcOrigin=${E??"null"}`),E&&H===E?($="origin",f.debug(`\u{1F50D} [ext-iframe] Candidate frame matched by origin: ${C}`),!0):!1});if(!I){f.debug(`\u26A0\uFE0F [ext-iframe] No Playwright frame found for fallback iframe: ${_}`),f.debug(`\u26A0\uFE0F [ext-iframe] Available frame URLs: ${e.frames().map(D=>D.url()).join(", ")}`);continue}f.debug(`\u{1F50D} [ext-iframe] Found matching Playwright frame for: ${_} (frame url: ${I.url()})`);try{let D={...c,initialHighlightIndex:y+1,domTreeRoot:"body"};f.debug(`\u{1F50D} [ext-iframe] Running dom-tree in extension frame with initialHighlightIndex=${D.initialHighlightIndex}`);let C=await I.evaluate(({code:U,argsObj:J})=>new Function("return "+U)()(J),{code:this.jsCode,argsObj:D});if(f.debug(`\u{1F50D} [ext-iframe] frameEval result: map size=${Object.keys(C?.map??{}).length} rootId=${C?.rootId}`),!C?.map||!C.rootId){f.debug("\u26A0\uFE0F [ext-iframe] frameEval missing map or rootId, skipping");continue}let H=Object.values(C.map).filter(U=>U.highlightIndex!=null);f.debug(`\u{1F50D} [ext-iframe] Interactive elements in extension frame: ${H.length}`);for(let U of H){let J=U;f.debug(`\u{1F50D} [ext-iframe] - <${J.tagName}> highlightIndex=${J.highlightIndex} text="${J.children?.length?"...":""}"`)}for(let U of Object.values(C.map)){let J=U;J.highlightIndex!=null&&(y=Math.max(y,J.highlightIndex))}let K=`ext_${h}_`;for(let[U,J]of Object.entries(C.map)){let he={...J};he.children&&(he.children=he.children.map(Ze=>`${K}${Ze}`)),d.map[`${K}${U}`]=he}let Q=d.map[v];Q?(Q.children=[...Q.children||[],`${K}${C.rootId}`],f.debug(`\u{1F50D} [ext-iframe] Attached frame root to iframe node ${v}`)):f.debug(`\u26A0\uFE0F [ext-iframe] iframe node ${v} not found in map`),f.debug(`\u2705 Merged fallback iframe content from: ${_}`)}catch(D){f.warn(`Failed to process fallback iframe ${_}:`,D)}}}if(d&&d.perfMetrics){let y=d.perfMetrics.nodeMetrics?.totalNodes??0,h=0;if(d.map)for(let _ of Object.values(d.map))typeof _=="object"&&_!==null&&_.isInteractive&&h++;let v=e.url().length>50?e.url().slice(0,50)+"...":e.url();f.debug(`\u{1F50E} Ran buildDOMTree.js interactive element detection on: ${v} interactive=${h}/${y}`)}f.debug("\u{1F504} Starting TypeScript DOM tree construction...");let g=await this.constructDomTree(d);return f.debug("\u2705 TypeScript DOM tree construction completed"),g}async constructDomTree(e){let t=e.map,i=e.rootId,n=new Map,a=new Map,o=new Map;for(let[s,l]of Object.entries(t)){let[c,d]=this.parseNode(l);c!==null&&(a.set(s,c),o.set(s,d),c instanceof Te&&c.highlightIndex!==null&&n.set(c.highlightIndex,c))}for(let[s,l]of o){let c=a.get(s);if(c instanceof Te)for(let d of l){let u=a.get(d);u&&(u.parent=c,c.children.push(u))}}let r=a.get(i);if(!r||!(r instanceof Te))throw new Error("Failed to parse HTML to dictionary");return[r,n]}parseNode(e){if(!e)return[null,[]];if(e.type==="TEXT_NODE")return[new Ot(e.text,e.isVisible,null),[]];let t=null;e.viewport&&(t={width:e.viewport.width,height:e.viewport.height,scrollX:e.viewport.scrollX,scrollY:e.viewport.scrollY});let i=e.shadowHostXPaths??[],n=new Te(e.tagName,e.xpath,e.attributes||{},[],e.isVisible??!1,e.isInteractive??!1,e.isScrollable??!1,e.markAsClickable??!1,e.isTopElement??!1,e.isInViewport??!1,e.shadowRoot??!1,e.highlightIndex??null,e.viewportCoordinates??null,e.pageCoordinates??null,t,i,null),a=e.children||[];return[n,a]}}});import{z as Jc}from"zod";var Fo,ag,Bi=b(()=>{"use strict";Fo=class{async execute(e,t){await e.waitForLoadState("networkidle",{timeout:5e3}).catch(()=>{}),await e.waitForLoadState("domcontentloaded")}transpile(e){return["await page.waitForLoadState('domcontentloaded');"]}},ag=Jc.object({})});var Ho,Gi=b(()=>{"use strict";G();P();Ho=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");if(typeof n.kwargs.relative_x=="number"&&typeof n.kwargs.relative_y=="number"){let a=F(e,t);if(a){await a.waitFor({state:"attached",timeout:R(i,t.action_data?.kwargs?.timeout_ms)});let o=await a.boundingBox();if(o){let r=o.x+n.kwargs.relative_x+o.width/2,s=o.y+n.kwargs.relative_y+o.height/2;await e.mouse.move(r,s),await e.waitForTimeout(200),await e.mouse.click(r,s,{button:"right",delay:100}),await e.waitForTimeout(200)}}else throw new Error("Element-anchored coordinates provided but no locator found")}else if(typeof n.kwargs.x=="number"&&typeof n.kwargs.y=="number")await e.mouse.move(n.kwargs.x,n.kwargs.y),await e.waitForTimeout(200),await e.mouse.click(n.kwargs.x,n.kwargs.y,{button:"right"}),await e.waitForTimeout(200);else throw new Error("Missing or invalid coordinates")}transpile(e){let t=e.action_data?.kwargs||{},i=[];return typeof t.relative_x=="number"&&typeof t.relative_y=="number"?(i.push(`action_data: { kwargs: { relative_x: ${t.relative_x}, relative_y: ${t.relative_y} } }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`)):typeof t.x=="number"&&typeof t.y=="number"&&i.push(`action_data: { kwargs: { x: ${t.x}, y: ${t.y} } }`),['await agent.execAction("right_click_by_coordinates", page, {',...i.map(n=>` ${n},`),"});"]}}});var Wo,Ki=b(()=>{"use strict";G();P();Wo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.keys;if(!a||typeof a!="string")throw new Error("Missing or invalid keys for send keys on element action");let o=F(e,t),r=R(i,t.action_data?.kwargs?.timeout_ms);if(o)await o.press(a,{timeout:r}),await e.waitForTimeout(500);else throw new Error("No locator found for send keys on element action")}transpile(e){let t=Ne(e);if(!t){let a=e.action_data?.kwargs?.keys||"";return['await agent.execAction("send_keys_on_element", page, {',` action_data: { kwargs: { keys: ${JSON.stringify(a)} } },`,"});"]}let i=e.action_data?.kwargs?.keys||"",n=R();return[`await ${t}.press(${JSON.stringify(i)}, { timeout: ${n} });`]}}});var jo,zi=b(()=>{"use strict";jo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.code;if(!a)throw new Error("Missing code for js_action");let o=i.agent;if(!o)throw new Error("Agent not initialized on AgentServices \u2014 js_action requires an agent reference");await new Function("page","agent",`
4086
4108
  return (async () => {
4087
4109
  ${a}
4088
4110
  })();
4089
4111
  `)(e,o)}transpile(e){let t=e.action_data?.kwargs?.code;return t?t.split(`
4090
- `):["// Skipping js_action: missing code"]}}});import*as Yc from"playwright/test";import{default as qc}from"playwright/test";var We,lt=v(()=>{"use strict";ve();We={};Ei(We,{default:()=>qc});Ja(We,Yc)});import{z as Uo}from"zod";var Bo,vg,Vi=v(()=>{"use strict";lt();Bo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.code;if(!a)throw new Error("Missing code for js_code action");let o=i.agent;if(!o)throw new Error("Agent not initialized on AgentServices \u2014 js_code requires an agent reference");await new Function("page","expect","agent",`
4112
+ `):["// Skipping js_action: missing code"]}}});import*as Yc from"playwright/test";import{default as qc}from"playwright/test";var We,ct=b(()=>{"use strict";ve();We={};Ei(We,{default:()=>qc});Ja(We,Yc)});import{z as Uo}from"zod";var Bo,vg,Vi=b(()=>{"use strict";ct();Bo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.code;if(!a)throw new Error("Missing code for js_code action");let o=i.agent;if(!o)throw new Error("Agent not initialized on AgentServices \u2014 js_code requires an agent reference");await new Function("page","expect","agent",`
4091
4113
  return (async () => {
4092
4114
  ${a}
4093
4115
  })();
4094
4116
  `)(e,We.expect,o)}transpile(e){let t=e.action_data?.kwargs?.code;if(!t)return["// Skipping js_code: missing code"];let i=["{"],n=t.split(`
4095
- `);for(let a of n)i.push(` ${a}`);return i.push("}"),i}},vg=Uo.object({code:Uo.string().describe("JavaScript code to execute in the browser context")})});var Go,Xi=v(()=>{"use strict";G();C();Go=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");if(typeof n.kwargs.relative_x=="number"&&typeof n.kwargs.relative_y=="number"){let a=F(e,t);if(a){await a.waitFor({state:"attached",timeout:R(i,t.action_data?.kwargs?.timeout_ms)});let o=await a.boundingBox();if(o){let r=o.x+n.kwargs.relative_x+o.width/2,s=o.y+n.kwargs.relative_y+o.height/2;await e.mouse.dblclick(r,s,{delay:50}),await e.waitForTimeout(200)}}else throw new Error("Element-anchored coordinates provided but no locator found")}else if(typeof n.kwargs.x=="number"&&typeof n.kwargs.y=="number")await e.mouse.dblclick(n.kwargs.x,n.kwargs.y),await e.waitForTimeout(200);else throw new Error("Missing or invalid coordinates")}transpile(e){let t=e.action_data?.kwargs||{},i=[];return typeof t.relative_x=="number"&&typeof t.relative_y=="number"?(i.push(`action_data: { kwargs: { relative_x: ${t.relative_x}, relative_y: ${t.relative_y} } }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`)):typeof t.x=="number"&&typeof t.y=="number"&&i.push(`action_data: { kwargs: { x: ${t.x}, y: ${t.y} } }`),['await agent.execAction("double_click_by_coordinates", page, {',...i.map(n=>` ${n},`),"});"]}}});var Ko,Ji=v(()=>{"use strict";G();C();Ko=class{async execute(e,t,i){let n=i.getActionSettings().drag_drop_steps??10,a=t.action_data;if(!a)throw new Error("Action data not found");let o=a.kwargs,r=[o.coord_source_x,o.coord_source_y],s=[o.coord_target_x,o.coord_target_y];if(typeof o.relative_x=="number"&&typeof o.relative_y=="number"&&typeof o.delta_x=="number"&&typeof o.delta_y=="number"){let l=F(e,t);if(!l)throw new Error("No locator found for drag_drop action with element-anchored coordinates");await l.waitFor({state:"attached",timeout:R(i,t.action_data?.kwargs?.timeout_ms)});let c=await(await l).boundingBox();if(!c)throw new Error("Could not get bounding box for drag_drop element");let d=c.x+o.relative_x+c.width/2,u=c.y+o.relative_y+c.height/2,m=d+o.delta_x,p=u+o.delta_y;await e.mouse.move(d,u),await e.mouse.down(),n>0?await e.mouse.move(m,p,{steps:n}):await e.mouse.move(m,p),await e.mouse.up()}else if(r.every(l=>typeof l=="number")&&s.every(l=>typeof l=="number")){let[l,c]=r,[d,u]=s;await e.mouse.move(l,c),await e.mouse.down(),n>0?await e.mouse.move(d,u,{steps:n}):await e.mouse.move(d,u),await e.mouse.up()}else throw new Error("Missing coordinates for drag_drop action: requires either element-anchored coordinates with delta, or full absolute coordinates");await e.waitForTimeout(500)}transpile(e){let t=e.action_data?.kwargs||{},i=[],n={};return typeof t.relative_x=="number"&&(n.relative_x=t.relative_x),typeof t.relative_y=="number"&&(n.relative_y=t.relative_y),typeof t.delta_x=="number"&&(n.delta_x=t.delta_x),typeof t.delta_y=="number"&&(n.delta_y=t.delta_y),typeof t.coord_source_x=="number"&&(n.coord_source_x=t.coord_source_x),typeof t.coord_source_y=="number"&&(n.coord_source_y=t.coord_source_y),typeof t.coord_target_x=="number"&&(n.coord_target_x=t.coord_target_x),typeof t.coord_target_y=="number"&&(n.coord_target_y=t.coord_target_y),i.push(`action_data: { kwargs: ${JSON.stringify(n)} }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`),['await agent.execAction("drag_drop", page, {',...i.map(a=>` ${a},`),"});"]}}});var zo,Yi=v(()=>{"use strict";zo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=this.generateFunctionCallCode(n.kwargs);if(!a)throw new Error("Missing function name for function action");let o=i.agent;if(!o)throw new Error("Agent not initialized on AgentServices \u2014 FunctionAction requires an agent reference");await new Function("page","agent",`
4117
+ `);for(let a of n)i.push(` ${a}`);return i.push("}"),i}},vg=Uo.object({code:Uo.string().describe("JavaScript code to execute in the browser context")})});var Go,Xi=b(()=>{"use strict";G();P();Go=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");if(typeof n.kwargs.relative_x=="number"&&typeof n.kwargs.relative_y=="number"){let a=F(e,t);if(a){await a.waitFor({state:"attached",timeout:R(i,t.action_data?.kwargs?.timeout_ms)});let o=await a.boundingBox();if(o){let r=o.x+n.kwargs.relative_x+o.width/2,s=o.y+n.kwargs.relative_y+o.height/2;await e.mouse.dblclick(r,s,{delay:50}),await e.waitForTimeout(200)}}else throw new Error("Element-anchored coordinates provided but no locator found")}else if(typeof n.kwargs.x=="number"&&typeof n.kwargs.y=="number")await e.mouse.dblclick(n.kwargs.x,n.kwargs.y),await e.waitForTimeout(200);else throw new Error("Missing or invalid coordinates")}transpile(e){let t=e.action_data?.kwargs||{},i=[];return typeof t.relative_x=="number"&&typeof t.relative_y=="number"?(i.push(`action_data: { kwargs: { relative_x: ${t.relative_x}, relative_y: ${t.relative_y} } }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`)):typeof t.x=="number"&&typeof t.y=="number"&&i.push(`action_data: { kwargs: { x: ${t.x}, y: ${t.y} } }`),['await agent.execAction("double_click_by_coordinates", page, {',...i.map(n=>` ${n},`),"});"]}}});var Ko,Ji=b(()=>{"use strict";G();P();Ko=class{async execute(e,t,i){let n=i.getActionSettings().drag_drop_steps??10,a=t.action_data;if(!a)throw new Error("Action data not found");let o=a.kwargs,r=[o.coord_source_x,o.coord_source_y],s=[o.coord_target_x,o.coord_target_y];if(typeof o.relative_x=="number"&&typeof o.relative_y=="number"&&typeof o.delta_x=="number"&&typeof o.delta_y=="number"){let l=F(e,t);if(!l)throw new Error("No locator found for drag_drop action with element-anchored coordinates");await l.waitFor({state:"attached",timeout:R(i,t.action_data?.kwargs?.timeout_ms)});let c=await(await l).boundingBox();if(!c)throw new Error("Could not get bounding box for drag_drop element");let d=c.x+o.relative_x+c.width/2,u=c.y+o.relative_y+c.height/2,m=d+o.delta_x,p=u+o.delta_y;await e.mouse.move(d,u),await e.mouse.down(),n>0?await e.mouse.move(m,p,{steps:n}):await e.mouse.move(m,p),await e.mouse.up()}else if(r.every(l=>typeof l=="number")&&s.every(l=>typeof l=="number")){let[l,c]=r,[d,u]=s;await e.mouse.move(l,c),await e.mouse.down(),n>0?await e.mouse.move(d,u,{steps:n}):await e.mouse.move(d,u),await e.mouse.up()}else throw new Error("Missing coordinates for drag_drop action: requires either element-anchored coordinates with delta, or full absolute coordinates");await e.waitForTimeout(500)}transpile(e){let t=e.action_data?.kwargs||{},i=[],n={};return typeof t.relative_x=="number"&&(n.relative_x=t.relative_x),typeof t.relative_y=="number"&&(n.relative_y=t.relative_y),typeof t.delta_x=="number"&&(n.delta_x=t.delta_x),typeof t.delta_y=="number"&&(n.delta_y=t.delta_y),typeof t.coord_source_x=="number"&&(n.coord_source_x=t.coord_source_x),typeof t.coord_source_y=="number"&&(n.coord_source_y=t.coord_source_y),typeof t.coord_target_x=="number"&&(n.coord_target_x=t.coord_target_x),typeof t.coord_target_y=="number"&&(n.coord_target_y=t.coord_target_y),i.push(`action_data: { kwargs: ${JSON.stringify(n)} }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`),['await agent.execAction("drag_drop", page, {',...i.map(a=>` ${a},`),"});"]}}});var zo,Yi=b(()=>{"use strict";zo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=this.generateFunctionCallCode(n.kwargs);if(!a)throw new Error("Missing function name for function action");let o=i.agent;if(!o)throw new Error("Agent not initialized on AgentServices \u2014 FunctionAction requires an agent reference");await new Function("page","agent",`
4096
4118
  return (async () => {
4097
4119
  ${a}
4098
4120
  })();
4099
- `)(e,o)}transpile(e){let t=this.generateFunctionCallCode(e.action_data?.kwargs||{});return t?[t.endsWith(";")?t:`${t};`]:["// Skipping function: missing functionName"]}generateFunctionCallCode(e){let t=e.functionName;if(!t)return null;let i;if(Array.isArray(e.args))i=e.args.map(String);else if(Array.isArray(e.parameterNames)){let r=e.parameterValues||[];i=e.parameterNames.map((s,l)=>l<r.length?String(r[l]):"undefined")}else return`await ${t}()`;if(i.length===0)return`await ${t}()`;let n=["page","testContext","request","agent"],a=["undefined","null","true","false"],o=i.map(r=>n.includes(r)||a.includes(r)||/^-?\d+(\.\d+)?$/.test(r)?r:r.startsWith("$")?`agent.agentServices.readVariable('${r.substring(1)}')`:`"${r}"`);return`await ${t}(${o.join(", ")})`}}});var qi=v(()=>{"use strict";st()});var Vo,Lt=v(()=>{"use strict";Vo=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.SILENT=4]="SILENT",e))(Vo||{})});var ct={};xt(ct,{evaluateStatement:()=>en,executeAction:()=>Dt,executeStep:()=>Qi,generateActionStep:()=>Zi,runTask:()=>tn});var dt=v(()=>{"use strict";Rt();ji();Hi();rt();Ii();Pi();Ci();et();Ni();De();Di();At();Tt();_e();Et();qi();ze();It();st();Ct();Pt();Nt();ae();Fe();Ee();$t();it();Mt();Le();tt();Ke();Z();Be();B();te();Lt();G();ve()});import{z as Xo}from"zod";var Jo,vf,nn=v(()=>{"use strict";Jo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.statement;if(!a)throw new Error("Missing statement for ai_step");let{runTask:o}=await Promise.resolve().then(()=>(dt(),ct)),r=await o(a,e,i);if(r.status!=="success")throw new Error(r.error||"Task execution failed")}transpile(e,t){let i=e.action_data?.kwargs?.statement;return i?[`await agent.run(page, ${JSON.stringify(i)}, '${t||""}');`]:["// Skipping ai_step: missing statement"]}},vf=Xo.object({statement:Xo.string().describe('The complete step to execute (e.g., "fill in the login form and submit")')})});var Yo,an=v(()=>{"use strict";G();C();Yo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");if(typeof n.kwargs.relative_x=="number"&&typeof n.kwargs.relative_y=="number"){let a=F(e,t);if(a){await a.waitFor({state:"attached",timeout:R(i,t.action_data?.kwargs?.timeout_ms)});let o=await a.boundingBox();if(o){let r=o.x+n.kwargs.relative_x+o.width/2,s=o.y+n.kwargs.relative_y+o.height/2;await e.mouse.move(r,s),await e.waitForTimeout(200),await e.mouse.click(r,s),await e.waitForTimeout(500)}}else throw new Error("Element-anchored coordinates provided but no locator found")}else if(typeof n.kwargs.x=="number"&&typeof n.kwargs.y=="number")await e.mouse.move(n.kwargs.x,n.kwargs.y),await e.waitForTimeout(200),await e.mouse.click(n.kwargs.x,n.kwargs.y),await e.waitForTimeout(500);else throw new Error("Missing or invalid coordinates")}transpile(e){let t=e.action_data?.kwargs||{},i=[];return typeof t.relative_x=="number"&&typeof t.relative_y=="number"?(i.push(`action_data: { kwargs: { relative_x: ${t.relative_x}, relative_y: ${t.relative_y} } }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`)):typeof t.x=="number"&&typeof t.y=="number"&&i.push(`action_data: { kwargs: { x: ${t.x}, y: ${t.y} } }`),['await agent.execAction("click_by_coordinates", page, {',...i.map(n=>` ${n},`),"});"]}}});import{z as qo}from"zod";var Zo,Af,on=v(()=>{"use strict";Zo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.statement;if(!a)throw new Error("Missing statement for ai_action");let o=n.kwargs.use_pure_vision,{executeStep:r}=await Promise.resolve().then(()=>(dt(),ct)),s=await r(a,e,i,{usePureVision:o});if(s.status!=="success")throw new Error(s.error||"Action execution failed")}transpile(e,t){let i=e.action_data?.kwargs?.statement;if(!i)return["// Skipping ai_action: missing statement"];let n=JSON.stringify(i),a=e.action_data?.kwargs?.use_pure_vision;return[`await agent.execute(page, ${n}, '${t||""}', ${a});`]}},Af=qo.object({statement:qo.string().describe('The action to perform (e.g., "click the submit button")')})});import{z as Qo}from"zod";function tr(e,t){e.register({name:"switch_tab",description:"Switch to a different browser tab by index (0-based).",schema:Zc,async execute(i,n){let a=i.tab_index,{page:o,agentServices:r,actionDescription:s}=n;try{let l={action_description:s||`Switch to tab ${a}`,action_data:{action_name:"switch_tab",kwargs:{page_id:a}}};return await t.execute(o,l,r),{success:!0,actionEntity:l,message:`Switched to tab ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:(s||`Switch to tab ${a}`)+" (failed)",action_data:{action_name:"switch_tab",kwargs:{page_id:a}},feedback:l.message}}}}})}var er,Zc,Ft=v(()=>{"use strict";er=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.page_id??n.kwargs.tab_index??0;if(typeof a=="number"){let o=e.context().pages(),r=a===-1?o.length-1:a;if(i){let s=await i.switchTab(r);await s.waitForLoadState("load",{timeout:15e3}).catch(()=>{}),await s.waitForTimeout(500)}}else throw new Error("Missing page_id for switch_tab action")}transpile(e){return['await agent.execAction("switch_tab", page, {',` action_data: { kwargs: { page_id: ${e.action_data?.kwargs?.page_id??e.action_data?.kwargs?.tab_index??0} } },`,"});"]}},Zc=Qo.object({tab_index:Qo.number().int().nonnegative().describe("Index of the tab to switch to (0-based). Use 0 for first tab, 1 for second, etc.")})});import Qc from"fs";async function ir(e,t,i,n){let{useFileInput:a,timeout:o,mockShowOpenFilePicker:r}=n;if(r){f.info("Using mockShowOpenFilePicker approach");let s=i.map(l=>({path:l,buffer:new Uint8Array(Qc.readFileSync(l))}));await e.evaluate(l=>{window.__pw_showOpenFilePicker_mock_files=l},s),await t.click({timeout:o}),await e.waitForTimeout(3e3),await e.evaluate(()=>{delete window.__pw_showOpenFilePicker_mock_files})}else if(a)f.info("Using direct file input approach"),await t.setInputFiles(i,{timeout:o}),await e.waitForTimeout(3e3);else{f.info("Using file chooser approach");let s=e.waitForEvent("filechooser",{timeout:o});s.catch(()=>{}),await t.click({timeout:o}),await(await s).setFiles(i),await e.waitForTimeout(3e3)}f.info(`Successfully uploaded ${i.length} file(s)`)}var Ht=v(()=>{"use strict";B()});import{z as ie}from"zod";async function ed(e,t,i={},n){return{...await j(t,e),action_description:n||"Upload file to element",action_data:{action_name:"upload_file",kwargs:{...i}}}}function nr(e,t){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:"upload_file",kwargs:t},feedback:"Element not found in DOM"}}function or(e,t){e.register({name:"upload_file",description:'Click on target element (usually contains hints like "Upload file" or "Choose file" etc.) to trigger the file upload dialog, and choose the files to upload',schema:td,usesElementIndex:!0,async execute(i,n){let{element_index:a,paths:o}=i,{page:r,agentServices:s,actionDescription:l}=n;try{let c=await X(n,a);if(!c)return{success:!1,error:`File input element with index ${a} not found`,actionEntity:nr(l||`Upload file to element ${a}`,{index:a,paths:o})};let d=await ed(c,r,{paths:o},l);return await t.execute(r,d,s),{success:!0,actionEntity:d,message:`Uploaded file to element ${a}`}}catch(c){return{success:!1,error:c.message,actionEntity:nr(l||`Upload file to element ${a}`,{index:a,paths:o})}}}})}var ar,td,Wf,Wt=v(()=>{"use strict";Ht();Z();G();C();ar=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=[];if(n.kwargs.paths?a=Array.isArray(n.kwargs.paths)?n.kwargs.paths:[n.kwargs.paths]:n.kwargs.path&&(a=Array.isArray(n.kwargs.path)?n.kwargs.path:[n.kwargs.path]),a.length===0)throw new Error("No file paths provided for upload_file action");await i.downloadTestDataFiles(a);let o=a.map(c=>i.getTestDataFilePath(c)),r=F(e,t);if(!r)throw new Error("Missing locator for upload_file action");let s=n.kwargs.use_file_input||!1,l=i.getActionSettings().mock_show_open_file_picker??!1;await ir(e,r,o,{useFileInput:s,timeout:R(i,t.action_data?.kwargs?.timeout_ms),mockShowOpenFilePicker:l})}transpile(e){let t=e.action_data?.kwargs||{},i=[],n={};return t.paths?n.paths=t.paths:t.path&&(n.path=t.path),t.use_file_input&&(n.use_file_input=!0),i.push(`action_data: { kwargs: ${JSON.stringify(n)} }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`),['await agent.execAction("upload_file", page, {',...i.map(a=>` ${a},`),"});"]}};td=ie.object({element_index:ie.number().int().describe("Index of the target element to trigger the file upload dialog"),paths:ie.union([ie.string(),ie.array(ie.string())]).describe('Path to a file, relative to the test project root (e.g. "fixtures/data.csv"), or an array of such paths.'),timeout_ms:ie.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")});Wf=ie.object({element_index:ie.number().int().describe("Index of the file input element"),paths:ie.union([ie.string(),ie.array(ie.string())]).describe('Path to a file, relative to the test project root (e.g. "fixtures/data.csv"), or an array of such paths.'),timeout_ms:ie.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as rr}from"zod";function lr(e,t){e.register({name:"wait",description:"Wait for a specified number of seconds before continuing.",schema:id,async execute(i,n){let{seconds:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l={action_description:s||`Wait ${a} seconds`,action_data:{action_name:"wait",kwargs:{seconds:a}}};return await t.execute(o,l,r),{success:!0,actionEntity:l,message:`Waited ${a} seconds`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:(s||`Wait ${a} seconds`)+" (failed)",action_data:{action_name:"wait",kwargs:{seconds:a}},feedback:l.message}}}}})}var sr,id,jt=v(()=>{"use strict";sr=class{async execute(e,t){let i=t.action_data;if(!i)throw new Error("Action data not found");let n=i.kwargs.seconds||1;await e.waitForTimeout(n*1e3)}transpile(e){return[`await page.waitForTimeout(${(e.action_data?.kwargs?.seconds||1)*1e3});`]}},id=rr.object({seconds:rr.number().positive().describe("Number of seconds to wait")})});import{z as cr}from"zod";function ur(e,t){e.register({name:"wait_for_download_complete",description:"Wait for an in-progress download to complete.",schema:nd,async execute(i,n){let{timeout_seconds:a=10}=i,{page:o,agentServices:r}=n;try{let s={action_description:`Wait for download to complete (timeout: ${a}s)`,action_data:{action_name:"wait_for_download_complete",kwargs:{timeout_seconds:a}}};return await t.execute(o,s,r),{success:!0,actionEntity:s,message:"Download completed"}}catch(s){return{success:!1,error:s.message,actionEntity:{action_description:"Wait for download to complete (failed)",action_data:{action_name:"wait_for_download_complete",kwargs:{timeout_seconds:a}},feedback:s.message}}}}})}var dr,nd,Ut=v(()=>{"use strict";dr=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.timeout_seconds||10;await i.waitForDownloadComplete(e,a)}transpile(e){return['await agent.execAction("wait_for_download_complete", page, {',` action_data: { kwargs: { timeout_seconds: ${e.action_data?.kwargs?.timeout_seconds||10} } },`,"});"]}},nd=cr.object({timeout_seconds:cr.number().positive().optional().describe("Maximum time in seconds to wait for download to complete (default: 10)")})});import{z as _}from"zod";import"yaml";import"uuid";import"yaml";import"uuid";function gr(e){if(e!==null&&typeof e=="object"){for(let t of Object.values(e))gr(t);Object.freeze(e)}return e}var sn,mr,qf,pr,ad,od,rn,Zf,Qf,qn,Zn,rd,hr,sd,Bt,ld,cd,dd,le,ud,hd,tw,hw,yw,md,bw,pd,vw,je=v(()=>{"use strict";ve();sn=(e=>(e.JS_CODE="JS_CODE",e.AI_MODE="AI_MODE",e))(sn||{}),mr=112,qf=1080-mr,pr=(e=>(e.Chromium="chromium",e.Firefox="firefox",e.Webkit="webkit",e))(pr||{}),ad={"Blackberry PlayBook":{name:"Blackberry PlayBook",userAgent:"Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/26.0 Safari/536.2+",screen:{width:600,height:1024},viewport:{width:600,height:1024},deviceScaleFactor:1,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"BlackBerry Z30":{name:"BlackBerry Z30",userAgent:"Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/26.0 Mobile Safari/537.10+",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy Note 3":{name:"Galaxy Note 3",userAgent:"Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.0 Mobile Safari/534.30",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy Note II":{name:"Galaxy Note II",userAgent:"Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.0 Mobile Safari/534.30",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy S III":{name:"Galaxy S III",userAgent:"Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.0 Mobile Safari/534.30",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy S5":{name:"Galaxy S5",userAgent:"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy S8":{name:"Galaxy S8",userAgent:"Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:740},viewport:{width:360,height:740},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy S9+":{name:"Galaxy S9+",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:320,height:658},viewport:{width:320,height:658},deviceScaleFactor:4.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy S24":{name:"Galaxy S24",userAgent:"Mozilla/5.0 (Linux; Android 14; SM-S921U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:780},viewport:{width:360,height:780},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy A55":{name:"Galaxy A55",userAgent:"Mozilla/5.0 (Linux; Android 14; SM-A556B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:480,height:1040},viewport:{width:480,height:1040},deviceScaleFactor:2.25,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy Tab S4":{name:"Galaxy Tab S4",userAgent:"Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:712,height:1138},viewport:{width:712,height:1138},deviceScaleFactor:2.25,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy Tab S9":{name:"Galaxy Tab S9",userAgent:"Mozilla/5.0 (Linux; Android 14; SM-X710) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:640,height:1024},viewport:{width:640,height:1024},deviceScaleFactor:2.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"iPad (gen 5)":{name:"iPad (gen 5)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:768,height:1024},viewport:{width:768,height:1024},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad (gen 6)":{name:"iPad (gen 6)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:768,height:1024},viewport:{width:768,height:1024},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad (gen 7)":{name:"iPad (gen 7)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:810,height:1080},viewport:{width:810,height:1080},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad (gen 11)":{name:"iPad (gen 11)",userAgent:"Mozilla/5.0 (iPad; CPU OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/19E241 Safari/604.1",screen:{width:656,height:944},viewport:{width:656,height:944},deviceScaleFactor:2.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad Mini":{name:"iPad Mini",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:768,height:1024},viewport:{width:768,height:1024},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad Pro 11":{name:"iPad Pro 11",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:834,height:1194},viewport:{width:834,height:1194},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 6":{name:"iPhone 6",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 6 Plus":{name:"iPhone 6 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:414,height:736},viewport:{width:414,height:736},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 7":{name:"iPhone 7",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 7 Plus":{name:"iPhone 7 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:414,height:736},viewport:{width:414,height:736},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 8":{name:"iPhone 8",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 8 Plus":{name:"iPhone 8 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:414,height:736},viewport:{width:414,height:736},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone SE":{name:"iPhone SE",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.0 Mobile/14E304 Safari/602.1",screen:{width:320,height:568},viewport:{width:320,height:568},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone SE (3rd gen)":{name:"iPhone SE (3rd gen)",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.0 Mobile/19E241 Safari/602.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone X":{name:"iPhone X",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:812},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone XR":{name:"iPhone XR",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:414,height:896},viewport:{width:414,height:896},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 11":{name:"iPhone 11",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:414,height:896},viewport:{width:414,height:715},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 11 Pro":{name:"iPhone 11 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:635},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 11 Pro Max":{name:"iPhone 11 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:414,height:896},viewport:{width:414,height:715},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12":{name:"iPhone 12",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12 Pro":{name:"iPhone 12 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12 Pro Max":{name:"iPhone 12 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:428,height:926},viewport:{width:428,height:746},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12 Mini":{name:"iPhone 12 Mini",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:629},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13":{name:"iPhone 13",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13 Pro":{name:"iPhone 13 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13 Pro Max":{name:"iPhone 13 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:428,height:926},viewport:{width:428,height:746},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13 Mini":{name:"iPhone 13 Mini",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:629},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14":{name:"iPhone 14",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14 Plus":{name:"iPhone 14 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:428,height:926},viewport:{width:428,height:746},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14 Pro":{name:"iPhone 14 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:393,height:852},viewport:{width:393,height:660},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14 Pro Max":{name:"iPhone 14 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:430,height:932},viewport:{width:430,height:740},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15":{name:"iPhone 15",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:393,height:852},viewport:{width:393,height:659},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15 Plus":{name:"iPhone 15 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:430,height:932},viewport:{width:430,height:739},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15 Pro":{name:"iPhone 15 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:393,height:852},viewport:{width:393,height:659},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15 Pro Max":{name:"iPhone 15 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:430,height:932},viewport:{width:430,height:739},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Kindle Fire HDX":{name:"Kindle Fire HDX",userAgent:"Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",screen:{width:800,height:1280},viewport:{width:800,height:1280},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"LG Optimus L70":{name:"LG Optimus L70",userAgent:"Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:384,height:640},viewport:{width:384,height:640},deviceScaleFactor:1.25,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Microsoft Lumia 550":{name:"Microsoft Lumia 550",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36 Edge/14.14263",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Microsoft Lumia 950":{name:"Microsoft Lumia 950",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36 Edge/14.14263",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:4,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 10":{name:"Nexus 10",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:800,height:1280},viewport:{width:800,height:1280},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 4":{name:"Nexus 4",userAgent:"Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:384,height:640},viewport:{width:384,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 5":{name:"Nexus 5",userAgent:"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 5X":{name:"Nexus 5X",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:732},viewport:{width:412,height:732},deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 6":{name:"Nexus 6",userAgent:"Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:732},viewport:{width:412,height:732},deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 6P":{name:"Nexus 6P",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:732},viewport:{width:412,height:732},deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 7":{name:"Nexus 7",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:600,height:960},viewport:{width:600,height:960},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nokia Lumia 520":{name:"Nokia Lumia 520",userAgent:"Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)",screen:{width:320,height:533},viewport:{width:320,height:533},deviceScaleFactor:1.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nokia N9":{name:"Nokia N9",userAgent:"Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13",screen:{width:480,height:854},viewport:{width:480,height:854},deviceScaleFactor:1,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Pixel 2":{name:"Pixel 2",userAgent:"Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:411,height:731},viewport:{width:411,height:731},deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 2 XL":{name:"Pixel 2 XL",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:411,height:823},viewport:{width:411,height:823},deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 3":{name:"Pixel 3",userAgent:"Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:393,height:786},viewport:{width:393,height:786},deviceScaleFactor:2.75,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 4":{name:"Pixel 4",userAgent:"Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:353,height:745},viewport:{width:353,height:745},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 4a (5G)":{name:"Pixel 4a (5G)",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:892},viewport:{width:412,height:765},deviceScaleFactor:2.63,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 5":{name:"Pixel 5",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:393,height:851},viewport:{width:393,height:727},deviceScaleFactor:2.75,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 7":{name:"Pixel 7",userAgent:"Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:915},viewport:{width:412,height:839},deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Moto G4":{name:"Moto G4",userAgent:"Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Desktop Chrome HiDPI":{name:"Desktop Chrome HiDPI",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Edge HiDPI":{name:"Desktop Edge HiDPI",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Firefox HiDPI":{name:"Desktop Firefox HiDPI",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:142.0.1) Gecko/20100101 Firefox/142.0.1",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"firefox"},"Desktop Safari":{name:"Desktop Safari",userAgent:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"webkit"},"Desktop Chrome":{name:"Desktop Chrome",displayName:"Playwright Chromium",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1920,height:1080},viewport:{width:1920,height:1080},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Chrome Medium Resolution":{name:"Desktop Chrome Medium Resolution",displayName:"Playwright Chromium",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1280,height:720},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Chrome (Branded)":{name:"Desktop Chrome (Branded)",displayName:"Google Chrome",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1920,height:1080},viewport:{width:1920,height:1080},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"chrome"},"Desktop Chrome Medium Resolution (Branded)":{name:"Desktop Chrome Medium Resolution (Branded)",displayName:"Google Chrome",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1280,height:720},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"chrome"},"Desktop Edge":{name:"Desktop Edge",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1920,height:1080},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Edge (Branded)":{name:"Desktop Edge (Branded)",displayName:"Microsoft Edge",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1920,height:1080},viewport:{width:1920,height:1080},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"msedge"},"Desktop Edge Medium Resolution (Branded)":{name:"Desktop Edge Medium Resolution (Branded)",displayName:"Microsoft Edge",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1280,height:720},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"msedge"},"Desktop Firefox":{name:"Desktop Firefox",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:142.0.1) Gecko/20100101 Firefox/142.0.1",screen:{width:1920,height:1080},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"firefox"}},od={desktop:["Desktop Chrome","Desktop Chrome Medium Resolution","Desktop Chrome (Branded)","Desktop Chrome Medium Resolution (Branded)","Desktop Edge (Branded)","Desktop Edge Medium Resolution (Branded)","Desktop Safari"],mobile:["iPhone 15 Pro Max","iPhone 15 Pro","iPhone 15 Plus","iPhone 15","iPhone 14 Pro Max","iPhone 14 Pro","iPhone 14 Plus","iPhone 14","iPhone 13 Pro Max","iPhone 13 Pro","iPhone 13","iPhone 13 Mini","iPhone 12 Pro Max","iPhone 12 Pro","iPhone 12","iPhone 12 Mini","iPhone 11 Pro Max","iPhone 11 Pro","iPhone 11","iPhone XR","iPhone X","iPhone SE (3rd gen)","iPhone SE","iPhone 8 Plus","iPhone 8","iPhone 7 Plus","iPhone 7","iPhone 6 Plus","iPhone 6","Galaxy S24","Galaxy A55","Galaxy S9+","Galaxy S8","Galaxy S5","Galaxy Note 3","Galaxy Note II","Galaxy S III","Pixel 7","Pixel 5","Pixel 4a (5G)","Pixel 4","Pixel 3","Pixel 2 XL","Pixel 2","Nexus 6P","Nexus 6","Nexus 5X","Nexus 5","Nexus 4","Moto G4","LG Optimus L70","Microsoft Lumia 950","Microsoft Lumia 550","Nokia Lumia 520","Nokia N9","BlackBerry Z30"]},rn=(e,t=!1)=>{let i=["chromium"];return t&&i.push("webkit"),od[e].map(n=>ad[n]).filter(n=>n.defaultBrowserType&&i.includes(n.defaultBrowserType))},Zf={desktop:{label:"Desktop",type:"desktop",devices:rn("desktop")},mobile:{label:"Mobile Web",type:"mobile",devices:rn("mobile")}},Qf={desktop:{label:"Desktop",type:"desktop",devices:rn("desktop",!0)},mobile:{label:"Mobile Web",type:"mobile",devices:rn("mobile",!0)}},qn=(e=>(e.PASSWORD="password",e.OAUTH2="oauth2",e.SSO="sso",e.API="api",e))(qn||{}),Zn=(e=>(e.SMS="sms",e.EMAIL="email",e.TOTP="totp",e))(Zn||{}),rd=_.enum(["JS_CODE","AI_MODE"]),hr=_.object({type:rd,expression:_.string()}),sd=_.enum(["DRAFT","STEP","ACTION","IF_ELSE","WHILE_LOOP"]),Bt=_.object({uid:_.string(),type:sd,comment:_.string().optional()}),ld=_.object({action_data:_.object({action_name:_.string(),kwargs:_.record(_.any()).optional(),args:_.array(_.any()).optional()}),action_description:_.string().optional(),url:_.string().optional(),xpath:_.string().nullable().optional(),locator:_.string().nullable().optional(),css_selector:_.string().nullable().optional(),unique_selector:_.string().nullable().optional(),element_index:_.number().nullable().optional(),frame_path:_.array(_.any()).optional(),artifacts:_.record(_.any()).optional(),feedback:_.string().optional(),original_browser_use_action:_.any().optional()}).passthrough(),cd=Bt.extend({type:_.literal("DRAFT"),description:_.string()}),dd=Bt.extend({type:_.literal("ACTION"),description:_.string(),action_entity:ld.optional(),locator:_.string().optional(),use_pure_vision:_.boolean().optional()}),le=_.lazy(()=>_.union([cd,dd,Bt.extend({type:_.literal("STEP"),description:_.string().optional().default(""),statements:_.array(le),reference_id:_.number().optional(),template_path:_.string().optional(),template_params:_.record(_.string()).optional()}),Bt.extend({type:_.literal("IF_ELSE"),description:_.string().optional(),condition:hr,then:_.array(le),else:_.array(le).optional()}),Bt.extend({type:_.literal("WHILE_LOOP"),description:_.string().optional(),condition:hr,body:_.array(le),timeout_ms:_.number().optional()})])),ud=_.object({name:_.string(),statements:_.array(le),teardown:_.array(le).optional(),skip:_.union([_.boolean(),_.string()]).optional(),timeout:_.number().optional(),fail:_.union([_.boolean(),_.string()]).optional(),only:_.boolean().optional(),slow:_.boolean().optional()}),hd=_.object({tests:_.array(ud).min(1),beforeAll:_.array(le).optional(),afterAll:_.array(le).optional(),beforeEach:_.array(le).optional(),afterEach:_.array(le).optional()}),tw=_.object({comment:_.string().optional(),version:_.string().optional(),goal:_.string().optional(),url:_.string().optional(),baseURL:_.string().optional(),final_feedback:_.string().optional(),completed:_.boolean().optional(),success:_.boolean().optional(),statements:_.array(le).optional(),teardown:_.array(le).optional(),last_modified_at:_.string().optional(),testGroup:hd.optional()}).refine(e=>e.testGroup!==void 0?e.goal===void 0&&(e.statements===void 0||e.statements.length===0):e.goal!==void 0,{message:"TestFlow must have either goal/statements (single test) or testGroup (suite), not both"}),hw=1024*1024,yw=Object.freeze(["lite","standard","pro"]),md=1,bw=Object.freeze(["WEB_AGENT_MODEL","WEB_AGENT_FALLBACK_MODELS","COMPUTER_USE_MODEL"]),pd=gr({version:md,defaultTier:"lite",tiers:{lite:{webagent:{primary:"google:gemini-3-flash-preview",fallbacks:["anthropic:claude-haiku-4-5","openai:gpt-5.6-luna"]}},standard:{webagent:{primary:"google:gemini-3.5-flash",fallbacks:["anthropic:claude-sonnet-5","openai:gpt-5.6-terra"]}},pro:{webagent:{primary:"anthropic:claude-opus-4-8",fallbacks:["openai:gpt-5.6-sol","anthropic:claude-opus-4-7"]}}},computerUse:{primary:"google:gemini-3-flash-preview",fallbacks:[]}});vw=Object.freeze([...pd.tiers.standard.webagent.fallbacks])});var ut=v(()=>{"use strict"});async function bd(e,t){let i=new Set,n=Date.now(),a=new Set(["document","stylesheet","image","font","script","iframe"]),o=new Set(["text/html","text/css","application/javascript","image/","font/","application/json"]),r=["analytics","tracking","telemetry","beacon","metrics","doubleclick","adsystem","adserver","advertising","facebook.com/plugins","platform.twitter","linkedin.com/embed","livechat","zendesk","intercom","crisp.chat","hotjar","push-notifications","onesignal","pushwoosh","heartbeat","ping","alive","webrtc","rtmp://","wss://","cloudfront.net","fastly.net"],s=u=>{let m=u.toLowerCase();return m.startsWith("data:")||m.startsWith("blob:")?!0:r.some(p=>m.includes(p))},l=u=>{let m=u.resourceType(),p=u.url();if(!a.has(m)||s(p))return;let w=u.headers();w.purpose==="prefetch"||["video","audio"].includes(w["sec-fetch-dest"])||(i.add(u),n=Date.now())},c=async u=>{let m=u.request();if(!i.has(m))return;let p=(u.headers()["content-type"]||"").toLowerCase();if(["streaming","video","audio","webm","mp4","event-stream","websocket","protobuf"].some(g=>p.includes(g))){i.delete(m);return}if(![...o].some(g=>p.startsWith(g))){i.delete(m);return}let w=u.headers()["content-length"];if(w)try{if(parseInt(w,10)>5*1024*1024){i.delete(m);return}}catch{}i.delete(m),n=Date.now()},d=Date.now()-yd;for(let u of await e.requests()){let m=u.resourceType(),p=u.url(),w=u.timing();a.has(m)&&!s(p)&&w.responseEnd===-1&&w.startTime>=d&&(i.add(u),n=Date.now())}f.debug(`[waitForStableNetwork] Pre-populated ${i.size} in-flight requests`),e.on("request",l),e.on("response",c);try{let u=Date.now(),m=wd;for(;;){await new Promise(w=>setTimeout(w,100));let p=Date.now();if(i.size===0&&p-n>=m){f.debug(`[waitForStableNetwork] Network idle after ${p-u}ms`);break}if(p-u>t){f.debug(`[waitForStableNetwork] Max wait time exceeded (${t}ms), pending: ${i.size}`);break}}}finally{e.removeListener("request",l),e.removeListener("response",c)}}async function ht(e,t=fd,i=gd){let n=Date.now();try{await Promise.all([e.waitForLoadState("load",{timeout:t}).catch(()=>{}),bd(e,t)])}catch(r){throw r instanceof Error?new Error(`Failed during network stabilization: ${r.message}`):new Error("An unknown error occurred during network stabilization.")}let a=Date.now()-n,o=Math.max(i-a,0);o>0&&await new Promise(r=>setTimeout(r,o))}var gd,fd,wd,yd,Ae=v(()=>{"use strict";ut();B();gd=.5*1e3,fd=30*1e3,wd=1*1e3,yd=3*1e3});async function Qn(e,t,i=60){let n=Math.min(i,300),a=250,o=Date.now(),r=o+n*1e3;f.info(`Waiting for JS condition (timeout: ${n}s)`);let s=0,l=0,c,d;for(;;){try{if(s++,await t())return f.info("JS wait condition met"),{met:!0,evalCount:s,errorCount:l,lastError:c,elapsedMs:Date.now()-o}}catch(u){l++;let m=u.message;c=m,m!==d&&(f.warn(`Error evaluating JS wait condition: ${m}`),d=m)}if(Date.now()>r)return f.warn("Timeout waiting for JS condition"),{met:!1,evalCount:s,errorCount:l,lastError:c,elapsedMs:Date.now()-o};await e.waitForTimeout(a)}}function ea(e){let t=(e.elapsedMs/1e3).toFixed(1);if(e.met){let n=`${e.evalCount} evaluation${e.evalCount===1?"":"s"}`;return`Condition met after ${t}s (${n})`}if(e.evalCount>0&&e.errorCount===e.evalCount)return`Condition never evaluated successfully (${e.evalCount} attempts, all errored) \u2014 the expression is likely invalid: ${e.lastError}. Waited the full ${t}s \u2014 continuing`;let i=e.errorCount>0?`, ${e.errorCount} errored`:"";return`Condition not met within ${t}s (evaluated ${e.evalCount} times${i}) \u2014 continuing`}var mt=v(()=>{"use strict";Ae();B()});import{z as ta}from"zod";async function wr(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.condition;if(!a)throw new Error("Missing condition for ai_wait_until");let o=n.kwargs.timeout_seconds||60,r=Math.min(o,300);if(n.kwargs.condition_type===sn.JS_CODE){let u=typeof n.kwargs.js=="string"?n.kwargs.js:a,m;try{m=new Function("page","expect","agent",`
4121
+ `)(e,o)}transpile(e){let t=this.generateFunctionCallCode(e.action_data?.kwargs||{});return t?[t.endsWith(";")?t:`${t};`]:["// Skipping function: missing functionName"]}generateFunctionCallCode(e){let t=e.functionName;if(!t)return null;let i;if(Array.isArray(e.args))i=e.args.map(String);else if(Array.isArray(e.parameterNames)){let r=e.parameterValues||[];i=e.parameterNames.map((s,l)=>l<r.length?String(r[l]):"undefined")}else return`await ${t}()`;if(i.length===0)return`await ${t}()`;let n=["page","testContext","request","agent"],a=["undefined","null","true","false"],o=i.map(r=>n.includes(r)||a.includes(r)||/^-?\d+(\.\d+)?$/.test(r)?r:r.startsWith("$")?`agent.agentServices.readVariable('${r.substring(1)}')`:`"${r}"`);return`await ${t}(${o.join(", ")})`}}});var qi=b(()=>{"use strict";lt()});var Vo,Lt=b(()=>{"use strict";Vo=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.SILENT=4]="SILENT",e))(Vo||{})});var dt={};xt(dt,{evaluateStatement:()=>en,executeAction:()=>Dt,executeStep:()=>Qi,generateActionStep:()=>Zi,runTask:()=>tn});var ut=b(()=>{"use strict";Rt();ji();Hi();st();Ii();Pi();Ci();tt();Ni();De();Di();At();Tt();_e();Et();qi();Ve();It();lt();Ct();Pt();Nt();ae();Fe();Ee();$t();nt();Mt();Le();it();ze();Z();Ge();B();te();Lt();G();ve()});import{z as Xo}from"zod";var Jo,vf,nn=b(()=>{"use strict";Jo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.statement;if(!a)throw new Error("Missing statement for ai_step");let{runTask:o}=await Promise.resolve().then(()=>(ut(),dt)),r=await o(a,e,i);if(r.status!=="success")throw new Error(r.error||"Task execution failed")}transpile(e,t){let i=e.action_data?.kwargs?.statement;return i?[`await agent.run(page, ${JSON.stringify(i)}, '${t||""}');`]:["// Skipping ai_step: missing statement"]}},vf=Xo.object({statement:Xo.string().describe('The complete step to execute (e.g., "fill in the login form and submit")')})});var Yo,an=b(()=>{"use strict";G();P();Yo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");if(typeof n.kwargs.relative_x=="number"&&typeof n.kwargs.relative_y=="number"){let a=F(e,t);if(a){await a.waitFor({state:"attached",timeout:R(i,t.action_data?.kwargs?.timeout_ms)});let o=await a.boundingBox();if(o){let r=o.x+n.kwargs.relative_x+o.width/2,s=o.y+n.kwargs.relative_y+o.height/2;await e.mouse.move(r,s),await e.waitForTimeout(200),await e.mouse.click(r,s),await e.waitForTimeout(500)}}else throw new Error("Element-anchored coordinates provided but no locator found")}else if(typeof n.kwargs.x=="number"&&typeof n.kwargs.y=="number")await e.mouse.move(n.kwargs.x,n.kwargs.y),await e.waitForTimeout(200),await e.mouse.click(n.kwargs.x,n.kwargs.y),await e.waitForTimeout(500);else throw new Error("Missing or invalid coordinates")}transpile(e){let t=e.action_data?.kwargs||{},i=[];return typeof t.relative_x=="number"&&typeof t.relative_y=="number"?(i.push(`action_data: { kwargs: { relative_x: ${t.relative_x}, relative_y: ${t.relative_y} } }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`)):typeof t.x=="number"&&typeof t.y=="number"&&i.push(`action_data: { kwargs: { x: ${t.x}, y: ${t.y} } }`),['await agent.execAction("click_by_coordinates", page, {',...i.map(n=>` ${n},`),"});"]}}});import{z as qo}from"zod";var Zo,Af,on=b(()=>{"use strict";Zo=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.statement;if(!a)throw new Error("Missing statement for ai_action");let o=n.kwargs.use_pure_vision,{executeStep:r}=await Promise.resolve().then(()=>(ut(),dt)),s=await r(a,e,i,{usePureVision:o});if(s.status!=="success")throw new Error(s.error||"Action execution failed")}transpile(e,t){let i=e.action_data?.kwargs?.statement;if(!i)return["// Skipping ai_action: missing statement"];let n=JSON.stringify(i),a=e.action_data?.kwargs?.use_pure_vision;return[`await agent.execute(page, ${n}, '${t||""}', ${a});`]}},Af=qo.object({statement:qo.string().describe('The action to perform (e.g., "click the submit button")')})});import{z as Qo}from"zod";function tr(e,t){e.register({name:"switch_tab",description:"Switch to a different browser tab by index (0-based).",schema:Zc,async execute(i,n){let a=i.tab_index,{page:o,agentServices:r,actionDescription:s}=n;try{let l={action_description:s||`Switch to tab ${a}`,action_data:{action_name:"switch_tab",kwargs:{page_id:a}}};return await t.execute(o,l,r),{success:!0,actionEntity:l,message:`Switched to tab ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:(s||`Switch to tab ${a}`)+" (failed)",action_data:{action_name:"switch_tab",kwargs:{page_id:a}},feedback:l.message}}}}})}var er,Zc,Ft=b(()=>{"use strict";er=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.page_id??n.kwargs.tab_index??0;if(typeof a=="number"){let o=e.context().pages(),r=a===-1?o.length-1:a;if(i){let s=await i.switchTab(r);await s.waitForLoadState("load",{timeout:15e3}).catch(()=>{}),await s.waitForTimeout(500)}}else throw new Error("Missing page_id for switch_tab action")}transpile(e){return['await agent.execAction("switch_tab", page, {',` action_data: { kwargs: { page_id: ${e.action_data?.kwargs?.page_id??e.action_data?.kwargs?.tab_index??0} } },`,"});"]}},Zc=Qo.object({tab_index:Qo.number().int().nonnegative().describe("Index of the tab to switch to (0-based). Use 0 for first tab, 1 for second, etc.")})});import Qc from"fs";async function ir(e,t,i,n){let{useFileInput:a,timeout:o,mockShowOpenFilePicker:r}=n;if(r){f.info("Using mockShowOpenFilePicker approach");let s=i.map(l=>({path:l,buffer:new Uint8Array(Qc.readFileSync(l))}));await e.evaluate(l=>{window.__pw_showOpenFilePicker_mock_files=l},s),await t.click({timeout:o}),await e.waitForTimeout(3e3),await e.evaluate(()=>{delete window.__pw_showOpenFilePicker_mock_files})}else if(a)f.info("Using direct file input approach"),await t.setInputFiles(i,{timeout:o}),await e.waitForTimeout(3e3);else{f.info("Using file chooser approach");let s=e.waitForEvent("filechooser",{timeout:o});s.catch(()=>{}),await t.click({timeout:o}),await(await s).setFiles(i),await e.waitForTimeout(3e3)}f.info(`Successfully uploaded ${i.length} file(s)`)}var Ht=b(()=>{"use strict";B()});import{z as ie}from"zod";async function ed(e,t,i={},n){return{...await j(t,e),action_description:n||"Upload file to element",action_data:{action_name:"upload_file",kwargs:{...i}}}}function nr(e,t){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:"upload_file",kwargs:t},feedback:"Element not found in DOM"}}function or(e,t){e.register({name:"upload_file",description:'Click on target element (usually contains hints like "Upload file" or "Choose file" etc.) to trigger the file upload dialog, and choose the files to upload',schema:td,usesElementIndex:!0,async execute(i,n){let{element_index:a,paths:o}=i,{page:r,agentServices:s,actionDescription:l}=n;try{let c=await X(n,a);if(!c)return{success:!1,error:`File input element with index ${a} not found`,actionEntity:nr(l||`Upload file to element ${a}`,{index:a,paths:o})};let d=await ed(c,r,{paths:o},l);return await t.execute(r,d,s),{success:!0,actionEntity:d,message:`Uploaded file to element ${a}`}}catch(c){return{success:!1,error:c.message,actionEntity:nr(l||`Upload file to element ${a}`,{index:a,paths:o})}}}})}var ar,td,Wf,Wt=b(()=>{"use strict";Ht();Z();G();P();ar=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=[];if(n.kwargs.paths?a=Array.isArray(n.kwargs.paths)?n.kwargs.paths:[n.kwargs.paths]:n.kwargs.path&&(a=Array.isArray(n.kwargs.path)?n.kwargs.path:[n.kwargs.path]),a.length===0)throw new Error("No file paths provided for upload_file action");await i.downloadTestDataFiles(a);let o=a.map(c=>i.getTestDataFilePath(c)),r=F(e,t);if(!r)throw new Error("Missing locator for upload_file action");let s=n.kwargs.use_file_input||!1,l=i.getActionSettings().mock_show_open_file_picker??!1;await ir(e,r,o,{useFileInput:s,timeout:R(i,t.action_data?.kwargs?.timeout_ms),mockShowOpenFilePicker:l})}transpile(e){let t=e.action_data?.kwargs||{},i=[],n={};return t.paths?n.paths=t.paths:t.path&&(n.path=t.path),t.use_file_input&&(n.use_file_input=!0),i.push(`action_data: { kwargs: ${JSON.stringify(n)} }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`),['await agent.execAction("upload_file", page, {',...i.map(a=>` ${a},`),"});"]}};td=ie.object({element_index:ie.number().int().describe("Index of the target element to trigger the file upload dialog"),paths:ie.union([ie.string(),ie.array(ie.string())]).describe('Path to a file, relative to the test project root (e.g. "fixtures/data.csv"), or an array of such paths.'),timeout_ms:ie.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")});Wf=ie.object({element_index:ie.number().int().describe("Index of the file input element"),paths:ie.union([ie.string(),ie.array(ie.string())]).describe('Path to a file, relative to the test project root (e.g. "fixtures/data.csv"), or an array of such paths.'),timeout_ms:ie.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as rr}from"zod";function lr(e,t){e.register({name:"wait",description:"Wait for a specified number of seconds before continuing.",schema:id,async execute(i,n){let{seconds:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l={action_description:s||`Wait ${a} seconds`,action_data:{action_name:"wait",kwargs:{seconds:a}}};return await t.execute(o,l,r),{success:!0,actionEntity:l,message:`Waited ${a} seconds`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:(s||`Wait ${a} seconds`)+" (failed)",action_data:{action_name:"wait",kwargs:{seconds:a}},feedback:l.message}}}}})}var sr,id,jt=b(()=>{"use strict";sr=class{async execute(e,t){let i=t.action_data;if(!i)throw new Error("Action data not found");let n=i.kwargs.seconds||1;await e.waitForTimeout(n*1e3)}transpile(e){return[`await page.waitForTimeout(${(e.action_data?.kwargs?.seconds||1)*1e3});`]}},id=rr.object({seconds:rr.number().positive().describe("Number of seconds to wait")})});import{z as cr}from"zod";function ur(e,t){e.register({name:"wait_for_download_complete",description:"Wait for an in-progress download to complete.",schema:nd,async execute(i,n){let{timeout_seconds:a=10}=i,{page:o,agentServices:r}=n;try{let s={action_description:`Wait for download to complete (timeout: ${a}s)`,action_data:{action_name:"wait_for_download_complete",kwargs:{timeout_seconds:a}}};return await t.execute(o,s,r),{success:!0,actionEntity:s,message:"Download completed"}}catch(s){return{success:!1,error:s.message,actionEntity:{action_description:"Wait for download to complete (failed)",action_data:{action_name:"wait_for_download_complete",kwargs:{timeout_seconds:a}},feedback:s.message}}}}})}var dr,nd,Ut=b(()=>{"use strict";dr=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.timeout_seconds||10;await i.waitForDownloadComplete(e,a)}transpile(e){return['await agent.execAction("wait_for_download_complete", page, {',` action_data: { kwargs: { timeout_seconds: ${e.action_data?.kwargs?.timeout_seconds||10} } },`,"});"]}},nd=cr.object({timeout_seconds:cr.number().positive().optional().describe("Maximum time in seconds to wait for download to complete (default: 10)")})});import{z as k}from"zod";import"yaml";import"uuid";import"uuid";import"yaml";function gr(e){if(e!==null&&typeof e=="object"){for(let t of Object.values(e))gr(t);Object.freeze(e)}return e}var sn,mr,qf,pr,ad,od,rn,Zf,Qf,qn,Zn,rd,hr,sd,Bt,ld,cd,dd,le,ud,hd,tw,hw,yw,md,bw,pd,vw,je=b(()=>{"use strict";ve();sn=(e=>(e.JS_CODE="JS_CODE",e.AI_MODE="AI_MODE",e))(sn||{}),mr=112,qf=1080-mr,pr=(e=>(e.Chromium="chromium",e.Firefox="firefox",e.Webkit="webkit",e))(pr||{}),ad={"Blackberry PlayBook":{name:"Blackberry PlayBook",userAgent:"Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/26.0 Safari/536.2+",screen:{width:600,height:1024},viewport:{width:600,height:1024},deviceScaleFactor:1,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"BlackBerry Z30":{name:"BlackBerry Z30",userAgent:"Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/26.0 Mobile Safari/537.10+",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy Note 3":{name:"Galaxy Note 3",userAgent:"Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.0 Mobile Safari/534.30",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy Note II":{name:"Galaxy Note II",userAgent:"Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.0 Mobile Safari/534.30",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy S III":{name:"Galaxy S III",userAgent:"Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.0 Mobile Safari/534.30",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy S5":{name:"Galaxy S5",userAgent:"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy S8":{name:"Galaxy S8",userAgent:"Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:740},viewport:{width:360,height:740},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy S9+":{name:"Galaxy S9+",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:320,height:658},viewport:{width:320,height:658},deviceScaleFactor:4.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy S24":{name:"Galaxy S24",userAgent:"Mozilla/5.0 (Linux; Android 14; SM-S921U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:780},viewport:{width:360,height:780},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy A55":{name:"Galaxy A55",userAgent:"Mozilla/5.0 (Linux; Android 14; SM-A556B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:480,height:1040},viewport:{width:480,height:1040},deviceScaleFactor:2.25,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy Tab S4":{name:"Galaxy Tab S4",userAgent:"Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:712,height:1138},viewport:{width:712,height:1138},deviceScaleFactor:2.25,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy Tab S9":{name:"Galaxy Tab S9",userAgent:"Mozilla/5.0 (Linux; Android 14; SM-X710) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:640,height:1024},viewport:{width:640,height:1024},deviceScaleFactor:2.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"iPad (gen 5)":{name:"iPad (gen 5)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:768,height:1024},viewport:{width:768,height:1024},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad (gen 6)":{name:"iPad (gen 6)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:768,height:1024},viewport:{width:768,height:1024},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad (gen 7)":{name:"iPad (gen 7)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:810,height:1080},viewport:{width:810,height:1080},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad (gen 11)":{name:"iPad (gen 11)",userAgent:"Mozilla/5.0 (iPad; CPU OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/19E241 Safari/604.1",screen:{width:656,height:944},viewport:{width:656,height:944},deviceScaleFactor:2.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad Mini":{name:"iPad Mini",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:768,height:1024},viewport:{width:768,height:1024},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad Pro 11":{name:"iPad Pro 11",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:834,height:1194},viewport:{width:834,height:1194},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 6":{name:"iPhone 6",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 6 Plus":{name:"iPhone 6 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:414,height:736},viewport:{width:414,height:736},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 7":{name:"iPhone 7",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 7 Plus":{name:"iPhone 7 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:414,height:736},viewport:{width:414,height:736},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 8":{name:"iPhone 8",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 8 Plus":{name:"iPhone 8 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:414,height:736},viewport:{width:414,height:736},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone SE":{name:"iPhone SE",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.0 Mobile/14E304 Safari/602.1",screen:{width:320,height:568},viewport:{width:320,height:568},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone SE (3rd gen)":{name:"iPhone SE (3rd gen)",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.0 Mobile/19E241 Safari/602.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone X":{name:"iPhone X",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:812},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone XR":{name:"iPhone XR",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:414,height:896},viewport:{width:414,height:896},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 11":{name:"iPhone 11",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:414,height:896},viewport:{width:414,height:715},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 11 Pro":{name:"iPhone 11 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:635},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 11 Pro Max":{name:"iPhone 11 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:414,height:896},viewport:{width:414,height:715},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12":{name:"iPhone 12",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12 Pro":{name:"iPhone 12 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12 Pro Max":{name:"iPhone 12 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:428,height:926},viewport:{width:428,height:746},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12 Mini":{name:"iPhone 12 Mini",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:629},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13":{name:"iPhone 13",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13 Pro":{name:"iPhone 13 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13 Pro Max":{name:"iPhone 13 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:428,height:926},viewport:{width:428,height:746},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13 Mini":{name:"iPhone 13 Mini",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:629},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14":{name:"iPhone 14",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14 Plus":{name:"iPhone 14 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:428,height:926},viewport:{width:428,height:746},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14 Pro":{name:"iPhone 14 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:393,height:852},viewport:{width:393,height:660},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14 Pro Max":{name:"iPhone 14 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:430,height:932},viewport:{width:430,height:740},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15":{name:"iPhone 15",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:393,height:852},viewport:{width:393,height:659},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15 Plus":{name:"iPhone 15 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:430,height:932},viewport:{width:430,height:739},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15 Pro":{name:"iPhone 15 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:393,height:852},viewport:{width:393,height:659},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15 Pro Max":{name:"iPhone 15 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:430,height:932},viewport:{width:430,height:739},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Kindle Fire HDX":{name:"Kindle Fire HDX",userAgent:"Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",screen:{width:800,height:1280},viewport:{width:800,height:1280},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"LG Optimus L70":{name:"LG Optimus L70",userAgent:"Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:384,height:640},viewport:{width:384,height:640},deviceScaleFactor:1.25,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Microsoft Lumia 550":{name:"Microsoft Lumia 550",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36 Edge/14.14263",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Microsoft Lumia 950":{name:"Microsoft Lumia 950",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36 Edge/14.14263",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:4,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 10":{name:"Nexus 10",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:800,height:1280},viewport:{width:800,height:1280},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 4":{name:"Nexus 4",userAgent:"Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:384,height:640},viewport:{width:384,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 5":{name:"Nexus 5",userAgent:"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 5X":{name:"Nexus 5X",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:732},viewport:{width:412,height:732},deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 6":{name:"Nexus 6",userAgent:"Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:732},viewport:{width:412,height:732},deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 6P":{name:"Nexus 6P",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:732},viewport:{width:412,height:732},deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 7":{name:"Nexus 7",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:600,height:960},viewport:{width:600,height:960},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nokia Lumia 520":{name:"Nokia Lumia 520",userAgent:"Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)",screen:{width:320,height:533},viewport:{width:320,height:533},deviceScaleFactor:1.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nokia N9":{name:"Nokia N9",userAgent:"Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13",screen:{width:480,height:854},viewport:{width:480,height:854},deviceScaleFactor:1,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Pixel 2":{name:"Pixel 2",userAgent:"Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:411,height:731},viewport:{width:411,height:731},deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 2 XL":{name:"Pixel 2 XL",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:411,height:823},viewport:{width:411,height:823},deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 3":{name:"Pixel 3",userAgent:"Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:393,height:786},viewport:{width:393,height:786},deviceScaleFactor:2.75,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 4":{name:"Pixel 4",userAgent:"Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:353,height:745},viewport:{width:353,height:745},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 4a (5G)":{name:"Pixel 4a (5G)",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:892},viewport:{width:412,height:765},deviceScaleFactor:2.63,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 5":{name:"Pixel 5",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:393,height:851},viewport:{width:393,height:727},deviceScaleFactor:2.75,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 7":{name:"Pixel 7",userAgent:"Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:915},viewport:{width:412,height:839},deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Moto G4":{name:"Moto G4",userAgent:"Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Desktop Chrome HiDPI":{name:"Desktop Chrome HiDPI",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Edge HiDPI":{name:"Desktop Edge HiDPI",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Firefox HiDPI":{name:"Desktop Firefox HiDPI",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:142.0.1) Gecko/20100101 Firefox/142.0.1",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"firefox"},"Desktop Safari":{name:"Desktop Safari",userAgent:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"webkit"},"Desktop Chrome":{name:"Desktop Chrome",displayName:"Playwright Chromium",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1920,height:1080},viewport:{width:1920,height:1080},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Chrome Medium Resolution":{name:"Desktop Chrome Medium Resolution",displayName:"Playwright Chromium",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1280,height:720},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Chrome (Branded)":{name:"Desktop Chrome (Branded)",displayName:"Google Chrome",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1920,height:1080},viewport:{width:1920,height:1080},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"chrome"},"Desktop Chrome Medium Resolution (Branded)":{name:"Desktop Chrome Medium Resolution (Branded)",displayName:"Google Chrome",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1280,height:720},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"chrome"},"Desktop Edge":{name:"Desktop Edge",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1920,height:1080},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Edge (Branded)":{name:"Desktop Edge (Branded)",displayName:"Microsoft Edge",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1920,height:1080},viewport:{width:1920,height:1080},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"msedge"},"Desktop Edge Medium Resolution (Branded)":{name:"Desktop Edge Medium Resolution (Branded)",displayName:"Microsoft Edge",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1280,height:720},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"msedge"},"Desktop Firefox":{name:"Desktop Firefox",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:142.0.1) Gecko/20100101 Firefox/142.0.1",screen:{width:1920,height:1080},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"firefox"}},od={desktop:["Desktop Chrome","Desktop Chrome Medium Resolution","Desktop Chrome (Branded)","Desktop Chrome Medium Resolution (Branded)","Desktop Edge (Branded)","Desktop Edge Medium Resolution (Branded)","Desktop Safari"],mobile:["iPhone 15 Pro Max","iPhone 15 Pro","iPhone 15 Plus","iPhone 15","iPhone 14 Pro Max","iPhone 14 Pro","iPhone 14 Plus","iPhone 14","iPhone 13 Pro Max","iPhone 13 Pro","iPhone 13","iPhone 13 Mini","iPhone 12 Pro Max","iPhone 12 Pro","iPhone 12","iPhone 12 Mini","iPhone 11 Pro Max","iPhone 11 Pro","iPhone 11","iPhone XR","iPhone X","iPhone SE (3rd gen)","iPhone SE","iPhone 8 Plus","iPhone 8","iPhone 7 Plus","iPhone 7","iPhone 6 Plus","iPhone 6","Galaxy S24","Galaxy A55","Galaxy S9+","Galaxy S8","Galaxy S5","Galaxy Note 3","Galaxy Note II","Galaxy S III","Pixel 7","Pixel 5","Pixel 4a (5G)","Pixel 4","Pixel 3","Pixel 2 XL","Pixel 2","Nexus 6P","Nexus 6","Nexus 5X","Nexus 5","Nexus 4","Moto G4","LG Optimus L70","Microsoft Lumia 950","Microsoft Lumia 550","Nokia Lumia 520","Nokia N9","BlackBerry Z30"]},rn=(e,t=!1)=>{let i=["chromium"];return t&&i.push("webkit"),od[e].map(n=>ad[n]).filter(n=>n.defaultBrowserType&&i.includes(n.defaultBrowserType))},Zf={desktop:{label:"Desktop",type:"desktop",devices:rn("desktop")},mobile:{label:"Mobile Web",type:"mobile",devices:rn("mobile")}},Qf={desktop:{label:"Desktop",type:"desktop",devices:rn("desktop",!0)},mobile:{label:"Mobile Web",type:"mobile",devices:rn("mobile",!0)}},qn=(e=>(e.PASSWORD="password",e.OAUTH2="oauth2",e.SSO="sso",e.API="api",e))(qn||{}),Zn=(e=>(e.SMS="sms",e.EMAIL="email",e.TOTP="totp",e))(Zn||{}),rd=k.enum(["JS_CODE","AI_MODE"]),hr=k.object({type:rd,expression:k.string()}),sd=k.enum(["DRAFT","STEP","ACTION","IF_ELSE","WHILE_LOOP"]),Bt=k.object({uid:k.string(),type:sd,comment:k.string().optional()}),ld=k.object({action_data:k.object({action_name:k.string(),kwargs:k.record(k.any()).optional(),args:k.array(k.any()).optional()}),action_description:k.string().optional(),url:k.string().optional(),xpath:k.string().nullable().optional(),locator:k.string().nullable().optional(),css_selector:k.string().nullable().optional(),unique_selector:k.string().nullable().optional(),element_index:k.number().nullable().optional(),frame_path:k.array(k.any()).optional(),artifacts:k.record(k.any()).optional(),feedback:k.string().optional(),original_browser_use_action:k.any().optional()}).passthrough(),cd=Bt.extend({type:k.literal("DRAFT"),description:k.string()}),dd=Bt.extend({type:k.literal("ACTION"),description:k.string(),action_entity:ld.optional(),locator:k.string().optional(),use_pure_vision:k.boolean().optional()}),le=k.lazy(()=>k.union([cd,dd,Bt.extend({type:k.literal("STEP"),description:k.string().optional().default(""),statements:k.array(le),reference_id:k.number().optional(),template_path:k.string().optional(),template_params:k.record(k.string()).optional()}),Bt.extend({type:k.literal("IF_ELSE"),description:k.string().optional(),condition:hr,then:k.array(le),else:k.array(le).optional()}),Bt.extend({type:k.literal("WHILE_LOOP"),description:k.string().optional(),condition:hr,body:k.array(le),timeout_ms:k.number().optional()})])),ud=k.object({name:k.string(),statements:k.array(le),teardown:k.array(le).optional(),skip:k.union([k.boolean(),k.string()]).optional(),timeout:k.number().optional(),fail:k.union([k.boolean(),k.string()]).optional(),only:k.boolean().optional(),slow:k.boolean().optional()}),hd=k.object({tests:k.array(ud).min(1),beforeAll:k.array(le).optional(),afterAll:k.array(le).optional(),beforeEach:k.array(le).optional(),afterEach:k.array(le).optional()}),tw=k.object({comment:k.string().optional(),version:k.string().optional(),goal:k.string().optional(),url:k.string().optional(),baseURL:k.string().optional(),final_feedback:k.string().optional(),completed:k.boolean().optional(),success:k.boolean().optional(),statements:k.array(le).optional(),teardown:k.array(le).optional(),last_modified_at:k.string().optional(),testGroup:hd.optional()}).refine(e=>e.testGroup!==void 0?e.goal===void 0&&(e.statements===void 0||e.statements.length===0):e.goal!==void 0,{message:"TestFlow must have either goal/statements (single test) or testGroup (suite), not both"}),hw=1024*1024,yw=Object.freeze(["lite","standard","pro"]),md=1,bw=Object.freeze(["WEB_AGENT_MODEL","WEB_AGENT_FALLBACK_MODELS","COMPUTER_USE_MODEL"]),pd=gr({version:md,defaultTier:"lite",tiers:{lite:{webagent:{primary:"google:gemini-3-flash-preview",fallbacks:["anthropic:claude-haiku-4-5","openai:gpt-5.6-luna"]}},standard:{webagent:{primary:"google:gemini-3.5-flash",fallbacks:["anthropic:claude-sonnet-5","openai:gpt-5.6-terra"]}},pro:{webagent:{primary:"anthropic:claude-opus-4-8",fallbacks:["openai:gpt-5.6-sol","anthropic:claude-opus-4-7"]}}},computerUse:{primary:"google:gemini-3-flash-preview",fallbacks:[]}});vw=Object.freeze([...pd.tiers.standard.webagent.fallbacks])});var ht=b(()=>{"use strict"});async function bd(e,t){let i=new Set,n=Date.now(),a=new Set(["document","stylesheet","image","font","script","iframe"]),o=new Set(["text/html","text/css","application/javascript","image/","font/","application/json"]),r=["analytics","tracking","telemetry","beacon","metrics","doubleclick","adsystem","adserver","advertising","facebook.com/plugins","platform.twitter","linkedin.com/embed","livechat","zendesk","intercom","crisp.chat","hotjar","push-notifications","onesignal","pushwoosh","heartbeat","ping","alive","webrtc","rtmp://","wss://","cloudfront.net","fastly.net"],s=u=>{let m=u.toLowerCase();return m.startsWith("data:")||m.startsWith("blob:")?!0:r.some(p=>m.includes(p))},l=u=>{let m=u.resourceType(),p=u.url();if(!a.has(m)||s(p))return;let w=u.headers();w.purpose==="prefetch"||["video","audio"].includes(w["sec-fetch-dest"])||(i.add(u),n=Date.now())},c=async u=>{let m=u.request();if(!i.has(m))return;let p=(u.headers()["content-type"]||"").toLowerCase();if(["streaming","video","audio","webm","mp4","event-stream","websocket","protobuf"].some(g=>p.includes(g))){i.delete(m);return}if(![...o].some(g=>p.startsWith(g))){i.delete(m);return}let w=u.headers()["content-length"];if(w)try{if(parseInt(w,10)>5*1024*1024){i.delete(m);return}}catch{}i.delete(m),n=Date.now()},d=Date.now()-yd;for(let u of await e.requests()){let m=u.resourceType(),p=u.url(),w=u.timing();a.has(m)&&!s(p)&&w.responseEnd===-1&&w.startTime>=d&&(i.add(u),n=Date.now())}f.debug(`[waitForStableNetwork] Pre-populated ${i.size} in-flight requests`),e.on("request",l),e.on("response",c);try{let u=Date.now(),m=wd;for(;;){await new Promise(w=>setTimeout(w,100));let p=Date.now();if(i.size===0&&p-n>=m){f.debug(`[waitForStableNetwork] Network idle after ${p-u}ms`);break}if(p-u>t){f.debug(`[waitForStableNetwork] Max wait time exceeded (${t}ms), pending: ${i.size}`);break}}}finally{e.removeListener("request",l),e.removeListener("response",c)}}async function mt(e,t=fd,i=gd){let n=Date.now();try{await Promise.all([e.waitForLoadState("load",{timeout:t}).catch(()=>{}),bd(e,t)])}catch(r){throw r instanceof Error?new Error(`Failed during network stabilization: ${r.message}`):new Error("An unknown error occurred during network stabilization.")}let a=Date.now()-n,o=Math.max(i-a,0);o>0&&await new Promise(r=>setTimeout(r,o))}var gd,fd,wd,yd,Ae=b(()=>{"use strict";ht();B();gd=.5*1e3,fd=30*1e3,wd=1*1e3,yd=3*1e3});async function Qn(e,t,i=60){let n=Math.min(i,300),a=250,o=Date.now(),r=o+n*1e3;f.info(`Waiting for JS condition (timeout: ${n}s)`);let s=0,l=0,c,d;for(;;){try{if(s++,await t())return f.info("JS wait condition met"),{met:!0,evalCount:s,errorCount:l,lastError:c,elapsedMs:Date.now()-o}}catch(u){l++;let m=u.message;c=m,m!==d&&(f.warn(`Error evaluating JS wait condition: ${m}`),d=m)}if(Date.now()>r)return f.warn("Timeout waiting for JS condition"),{met:!1,evalCount:s,errorCount:l,lastError:c,elapsedMs:Date.now()-o};await e.waitForTimeout(a)}}function ea(e){let t=(e.elapsedMs/1e3).toFixed(1);if(e.met){let n=`${e.evalCount} evaluation${e.evalCount===1?"":"s"}`;return`Condition met after ${t}s (${n})`}if(e.evalCount>0&&e.errorCount===e.evalCount)return`Condition never evaluated successfully (${e.evalCount} attempts, all errored) \u2014 the expression is likely invalid: ${e.lastError}. Waited the full ${t}s \u2014 continuing`;let i=e.errorCount>0?`, ${e.errorCount} errored`:"";return`Condition not met within ${t}s (evaluated ${e.evalCount} times${i}) \u2014 continuing`}var pt=b(()=>{"use strict";Ae();B()});import{z as ta}from"zod";async function wr(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.condition;if(!a)throw new Error("Missing condition for ai_wait_until");let o=n.kwargs.timeout_seconds||60,r=Math.min(o,300);if(n.kwargs.condition_type===sn.JS_CODE){let u=typeof n.kwargs.js=="string"?n.kwargs.js:a,m;try{m=new Function("page","expect","agent",`
4100
4122
  return (async () => (${u}))();
4101
- `)}catch(w){return await e.waitForTimeout(r*1e3),{met:!1,message:`Condition could not be parsed as JavaScript: ${w.message}. Waited the full ${r}s \u2014 continuing`}}let p=await Qn(e,()=>m(e,We.expect,i.agent),r);return{met:p.met,message:ea(p)}}let s=r*1e3,l=5e3,c=Date.now(),{evaluateStatement:d}=await Promise.resolve().then(()=>(dt(),ct));for(;Date.now()-c<s;){if((await d(a,e,i,{})).success)return{met:!0,message:`Condition met: ${a}`};await e.waitForTimeout(l)}return{met:!1,message:`Condition not met within ${r}s: ${a} \u2014 continuing`}}function br(e){e.register({name:"ai_wait_until",description:'Wait until a specific condition is met on the page (e.g., "page loads", "spinner disappears", "button becomes enabled"). Use this instead of wait when the goal is to wait for something to happen rather than waiting a fixed duration.',schema:vd,async execute(t,i){let{condition:n,timeout_seconds:a=60}=t,{page:o,agentServices:r}=i;try{let s={action_description:`Wait until: ${n}`,action_data:{action_name:"ai_wait_until",kwargs:{condition:n,timeout_seconds:a}}},l=await wr(o,s,r);return l.met||r.addNote?.(l.message),{success:!0,actionEntity:s,message:l.message}}catch(s){return{success:!1,error:s.message,actionEntity:{action_description:`Wait until: ${n} (failed)`,action_data:{action_name:"ai_wait_until",kwargs:{condition:n,timeout_seconds:a}},feedback:s.message}}}}})}var yr,vd,Gt=v(()=>{"use strict";lt();je();mt();B();yr=class{async execute(e,t,i){let n=await wr(e,t,i);n.met||(f.warn(n.message),i.addNote?.(n.message))}transpile(e,t){let i=e.action_data?.kwargs?.condition,n=e.action_data?.kwargs?.timeout_seconds||60;if(!i)return["// Skipping ai_wait_until: missing condition"];if(e.action_data?.kwargs?.condition_type===sn.JS_CODE){let a=e.action_data?.kwargs?.js,o=typeof a=="string"?a:i,r=typeof a=="string"?`, ${JSON.stringify(i)}`:"";return[`await agent.waitForJs(page, async () => (${o}), ${n}, '${t}'${r});`]}return[`await agent.waitUntilCondition(page, ${JSON.stringify(i)}, ${n}, '${t}');`]}},vd=ta.object({condition:ta.string().describe('The condition to wait for (e.g., "the loading spinner disappears")'),timeout_seconds:ta.number().positive().optional().describe("Timeout in seconds (default: 60)")})});import{z as ia}from"zod";function xr(e,t){e.register({name:"save_variable",description:"Save a value to a named variable for later use in the test.",schema:xd,async execute(i,n){let{name:a,value:o}=i,{page:r,agentServices:s}=n;try{let l={action_description:`Save variable "${a}" = "${o}"`,action_data:{action_name:"save_variable",kwargs:{name:a,value:o}}};return await t.execute(r,l,s),{success:!0,actionEntity:l,message:`Saved variable "${a}"`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:`Save variable "${a}" (failed)`,action_data:{action_name:"save_variable",kwargs:{name:a,value:o}},feedback:l.message}}}}})}var vr,xd,Kt=v(()=>{"use strict";vr=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.name,o=n.kwargs.value;if(!a||o===void 0)throw new Error("Missing variable name or value for save_variable");a.startsWith("$")&&(a=a.slice(1)),i.saveVariable(a,o)}transpile(e){let t=e.action_data?.kwargs?.name||"",i=e.action_data?.kwargs?.value;return['await agent.execAction("save_variable", page, {',` action_data: { kwargs: { name: ${JSON.stringify(t)}, value: ${JSON.stringify(i)} } },`,"});"]}},xd=ia.object({name:ia.string().describe("Variable name to save"),value:ia.string().describe("Value to save in the variable")})});import{z as na}from"zod";async function _d(e,t,i={}){return{action_description:t,action_data:{action_name:e,kwargs:{...i}}}}function kd(e,t,i){return{action_description:`${e} (failed)`,action_data:{action_name:t,kwargs:i},feedback:"Scroll failed!"}}function _r(e,t){e.register({name:"scroll",description:"Scroll the page by specified number of pages (set down=True to scroll down, down=False to scroll up, num_pages=number of pages to scroll like 0.5 for half page, 1.0 for one page, etc.). ",schema:Sd,async execute(i,n){let{down:a,num_pages:o}=i,{page:r,agentServices:s,actionDescription:l}=n;try{let c=l||`Scroll ${a?"down":"up"} ${o} page(s)`,d=await _d("scroll",c,{down:a,num_pages:o});return await t.execute(r,d,s),{success:!0,actionEntity:d,message:`Scrolled ${a?"down":"up"} ${o} page(s)`}}catch(c){return{success:!1,error:c.message,actionEntity:kd(l||`Scroll ${a?"down":"up"} ${o} page(s)`,"scroll",{down:a,num_pages:o})}}}})}var zt,Sd,Vt=v(()=>{"use strict";zt=class{async execute(e,t){let i=t.action_data;if(!i)throw new Error("Action data not found");let n=i.kwargs.down??!0,a=i.kwargs.num_pages??1,o=n?1:-1;await e.evaluate(`window.scrollBy(0, window.innerHeight * ${a} * ${o})`)}transpile(e){let t=e.action_data?.kwargs?.down??!0;return[`await page.evaluate('window.scrollBy(0, window.innerHeight * ${(e.action_data?.kwargs?.num_pages??1)*(t?1:-1)})');`]}};Sd=na.object({down:na.boolean().describe("True to scroll down, False to scroll up"),num_pages:na.number().nonnegative().describe("Number of pages to scroll (0.5 = half page, 1.0 = one page, etc.)")})});import{z as Xt}from"zod";async function Ed(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function kr(e,t,i){return{action_description:`${e} (failed)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function Er(e,t){e.register({name:"scroll_on_element",description:"Scroll on a scrollable element horizontally and vertically.",schema:Td,usesElementIndex:!0,async execute(i,n){let{element_index:a,delta_x:o,delta_y:r}=i,{page:s,agentServices:l}=n;try{let c=await X(n,a);if(!c)return{success:!1,error:`Element with index ${a} not found`,actionEntity:kr(`Scroll on element ${a} horizontally: ${o}px, vertically: ${r}px`,"scroll_on_element",{index:a,delta_x:o,delta_y:r})};let d=await Ed("scroll_on_element",`Scroll on element ${a} horizontally: ${o}px, vertically: ${r}px`,c,s,{delta_x:o,delta_y:r});return await t.execute(s,d,l),{success:!0,actionEntity:d,message:`Scrolled on element ${a} horizontally: ${o}px, vertically: ${r}px`}}catch(c){return{success:!1,error:c.message,actionEntity:kr(`Scroll on element ${a} horizontally: ${o}px, vertically: ${r}px`,"scroll_on_element",{index:a,delta_x:o,delta_y:r})}}}})}var Sr,Td,Jt=v(()=>{"use strict";Z();G();C();Sr=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.delta_x||0,o=n.kwargs.delta_y||0,r=F(e,t),s=R(i,t.action_data?.kwargs?.timeout_ms);if(r)await r.hover({timeout:s}),await e.mouse.wheel(a,o);else throw new Error("No locator found for scroll_on_element action")}transpile(e){let t=Ne(e);if(!t){let a=e.action_data?.kwargs?.delta_x||0,o=e.action_data?.kwargs?.delta_y||0;return['await agent.execAction("scroll_on_element", page, {',` action_data: { kwargs: { delta_x: ${a}, delta_y: ${o} } },`,"});"]}let i=e.action_data?.kwargs?.delta_x||0,n=e.action_data?.kwargs?.delta_y||0;return[`await ${t}.hover({ timeout: ${R()} });`,`await page.mouse.wheel(${i}, ${n});`]}};Td=Xt.object({element_index:Xt.number().int().describe("Index of the scrollable element"),delta_x:Xt.number().optional().describe("The number of pixels to scroll horizontally. Positive values scroll right, negative values scroll left."),delta_y:Xt.number().optional().describe("The number of pixels to scroll vertically. Positive values scroll down, negative values scroll up."),timeout_ms:Xt.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as Tr}from"zod";function $r(e,t){e.register({name:"scroll_to_text",description:"Scroll the page until specified text becomes visible.",schema:Ad,async execute(i,n){let{text:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l={action_description:s||`Scroll to text "${a}"`,action_data:{action_name:"scroll_to_text",kwargs:{text:a}}};return await t.execute(o,l,r),{success:!0,actionEntity:l,message:`Scrolled to text "${a}"`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:(s||`Scroll to text "${a}"`)+" (failed)",action_data:{action_name:"scroll_to_text",kwargs:{text:a}},feedback:l.message}}}}})}var Ar,Ad,Yt=v(()=>{"use strict";Ar=class{async execute(e,t){let i=t.action_data;if(!i)throw new Error("Action data not found");let n=i.kwargs.text;if(n)await e.getByText(n,{exact:!1}).first().scrollIntoViewIfNeeded(),await e.waitForTimeout(500);else throw new Error("Missing text for scroll_to_text action")}transpile(e){let t=e.action_data?.kwargs?.text||"";return[`await page.getByText(${JSON.stringify(t)}, { exact: false }).first().scrollIntoViewIfNeeded();`]}},Ad=Tr.object({text:Tr.string().describe("Text to scroll to on the page")})});import{z as ln}from"zod";async function $d(e,t,i,n){return{...await j(t,e),action_description:n||`Select option "${i}"`,action_data:{action_name:"select_dropdown_option",kwargs:{text:i}}}}function Mr(e,t){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:"select_dropdown_option",kwargs:t},feedback:"Element not found in DOM"}}function Cr(e,t){e.register({name:"select_dropdown_option",description:"Select an option from a dropdown/select element by value, label, or index.",schema:Md,usesElementIndex:!0,async execute(i,n){let{element_index:a,option:o}=i,{page:r,agentServices:s,actionDescription:l}=n;try{let c=await X(n,a);if(!c)return{success:!1,error:`Dropdown element with index ${a} not found`,actionEntity:Mr(l||`Select option in dropdown ${a}`,{index:a,option:o})};let d=await $d(c,r,o,l);return await t.execute(r,d,s),{success:!0,actionEntity:d,message:`Selected option "${o}" in dropdown ${a}`}}catch(c){return{success:!1,error:c.message,actionEntity:Mr(`Select option in dropdown ${a}`,{index:a,option:o})}}}})}var Ir,Md,qt=v(()=>{"use strict";Z();G();C();Ir=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.text||n.kwargs.option,o=F(e,t),r=R(i,t.action_data?.kwargs?.timeout_ms);if(o&&a)await o.selectOption(a,{timeout:r});else throw new Error("Missing locator or option label for select_dropdown_option action")}transpile(e){let t=e.action_data?.kwargs?.text||e.action_data?.kwargs?.option||"",i=[];return i.push(`action_data: { kwargs: { text: ${JSON.stringify(t)} } }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`),['await agent.execAction("select_dropdown_option", page, {',...i.map(n=>` ${n},`),"});"]}};Md=ln.object({element_index:ln.number().int().describe("Index of the dropdown/select element"),option:ln.string().describe("Option value, label, or index to select"),timeout_ms:ln.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as cn}from"zod";async function Id(e,t,i,n){return{...await j(i,t),action_description:e,action_data:{action_name:"set_date_for_native_date_picker",kwargs:{date:n}}}}function aa(e,t){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:"set_date_for_native_date_picker",kwargs:t},feedback:"Element not found in DOM"}}function Or(e,t){e.register({name:"set_date_for_native_date_picker",description:`Set a date in a native HTML date picker input (<input type="date">).
4123
+ `)}catch(w){return await e.waitForTimeout(r*1e3),{met:!1,message:`Condition could not be parsed as JavaScript: ${w.message}. Waited the full ${r}s \u2014 continuing`}}let p=await Qn(e,()=>m(e,We.expect,i.agent),r);return{met:p.met,message:ea(p)}}let s=r*1e3,l=5e3,c=Date.now(),{evaluateStatement:d}=await Promise.resolve().then(()=>(ut(),dt));for(;Date.now()-c<s;){if((await d(a,e,i,{})).success)return{met:!0,message:`Condition met: ${a}`};await e.waitForTimeout(l)}return{met:!1,message:`Condition not met within ${r}s: ${a} \u2014 continuing`}}function br(e){e.register({name:"ai_wait_until",description:'Wait until a specific condition is met on the page (e.g., "page loads", "spinner disappears", "button becomes enabled"). Use this instead of wait when the goal is to wait for something to happen rather than waiting a fixed duration.',schema:vd,async execute(t,i){let{condition:n,timeout_seconds:a=60}=t,{page:o,agentServices:r}=i;try{let s={action_description:`Wait until: ${n}`,action_data:{action_name:"ai_wait_until",kwargs:{condition:n,timeout_seconds:a}}},l=await wr(o,s,r);return l.met||r.addNote?.(l.message),{success:!0,actionEntity:s,message:l.message}}catch(s){return{success:!1,error:s.message,actionEntity:{action_description:`Wait until: ${n} (failed)`,action_data:{action_name:"ai_wait_until",kwargs:{condition:n,timeout_seconds:a}},feedback:s.message}}}}})}var yr,vd,Gt=b(()=>{"use strict";ct();je();pt();B();yr=class{async execute(e,t,i){let n=await wr(e,t,i);n.met||(f.warn(n.message),i.addNote?.(n.message))}transpile(e,t){let i=e.action_data?.kwargs?.condition,n=e.action_data?.kwargs?.timeout_seconds||60;if(!i)return["// Skipping ai_wait_until: missing condition"];if(e.action_data?.kwargs?.condition_type===sn.JS_CODE){let a=e.action_data?.kwargs?.js,o=typeof a=="string"?a:i,r=typeof a=="string"?`, ${JSON.stringify(i)}`:"";return[`await agent.waitForJs(page, async () => (${o}), ${n}, '${t}'${r});`]}return[`await agent.waitUntilCondition(page, ${JSON.stringify(i)}, ${n}, '${t}');`]}},vd=ta.object({condition:ta.string().describe('The condition to wait for (e.g., "the loading spinner disappears")'),timeout_seconds:ta.number().positive().optional().describe("Timeout in seconds (default: 60)")})});import{z as ia}from"zod";function xr(e,t){e.register({name:"save_variable",description:"Save a value to a named variable for later use in the test.",schema:xd,async execute(i,n){let{name:a,value:o}=i,{page:r,agentServices:s}=n;try{let l={action_description:`Save variable "${a}" = "${o}"`,action_data:{action_name:"save_variable",kwargs:{name:a,value:o}}};return await t.execute(r,l,s),{success:!0,actionEntity:l,message:`Saved variable "${a}"`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:`Save variable "${a}" (failed)`,action_data:{action_name:"save_variable",kwargs:{name:a,value:o}},feedback:l.message}}}}})}var vr,xd,Kt=b(()=>{"use strict";vr=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.name,o=n.kwargs.value;if(!a||o===void 0)throw new Error("Missing variable name or value for save_variable");a.startsWith("$")&&(a=a.slice(1)),i.saveVariable(a,o)}transpile(e){let t=e.action_data?.kwargs?.name||"",i=e.action_data?.kwargs?.value;return['await agent.execAction("save_variable", page, {',` action_data: { kwargs: { name: ${JSON.stringify(t)}, value: ${JSON.stringify(i)} } },`,"});"]}},xd=ia.object({name:ia.string().describe("Variable name to save"),value:ia.string().describe("Value to save in the variable")})});import{z as na}from"zod";async function _d(e,t,i={}){return{action_description:t,action_data:{action_name:e,kwargs:{...i}}}}function kd(e,t,i){return{action_description:`${e} (failed)`,action_data:{action_name:t,kwargs:i},feedback:"Scroll failed!"}}function _r(e,t){e.register({name:"scroll",description:"Scroll the page by specified number of pages (set down=True to scroll down, down=False to scroll up, num_pages=number of pages to scroll like 0.5 for half page, 1.0 for one page, etc.). ",schema:Sd,async execute(i,n){let{down:a,num_pages:o}=i,{page:r,agentServices:s,actionDescription:l}=n;try{let c=l||`Scroll ${a?"down":"up"} ${o} page(s)`,d=await _d("scroll",c,{down:a,num_pages:o});return await t.execute(r,d,s),{success:!0,actionEntity:d,message:`Scrolled ${a?"down":"up"} ${o} page(s)`}}catch(c){return{success:!1,error:c.message,actionEntity:kd(l||`Scroll ${a?"down":"up"} ${o} page(s)`,"scroll",{down:a,num_pages:o})}}}})}var zt,Sd,Vt=b(()=>{"use strict";zt=class{async execute(e,t){let i=t.action_data;if(!i)throw new Error("Action data not found");let n=i.kwargs.down??!0,a=i.kwargs.num_pages??1,o=n?1:-1;await e.evaluate(`window.scrollBy(0, window.innerHeight * ${a} * ${o})`)}transpile(e){let t=e.action_data?.kwargs?.down??!0;return[`await page.evaluate('window.scrollBy(0, window.innerHeight * ${(e.action_data?.kwargs?.num_pages??1)*(t?1:-1)})');`]}};Sd=na.object({down:na.boolean().describe("True to scroll down, False to scroll up"),num_pages:na.number().nonnegative().describe("Number of pages to scroll (0.5 = half page, 1.0 = one page, etc.)")})});import{z as Xt}from"zod";async function Ed(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function kr(e,t,i){return{action_description:`${e} (failed)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function Er(e,t){e.register({name:"scroll_on_element",description:"Scroll on a scrollable element horizontally and vertically.",schema:Td,usesElementIndex:!0,async execute(i,n){let{element_index:a,delta_x:o,delta_y:r}=i,{page:s,agentServices:l}=n;try{let c=await X(n,a);if(!c)return{success:!1,error:`Element with index ${a} not found`,actionEntity:kr(`Scroll on element ${a} horizontally: ${o}px, vertically: ${r}px`,"scroll_on_element",{index:a,delta_x:o,delta_y:r})};let d=await Ed("scroll_on_element",`Scroll on element ${a} horizontally: ${o}px, vertically: ${r}px`,c,s,{delta_x:o,delta_y:r});return await t.execute(s,d,l),{success:!0,actionEntity:d,message:`Scrolled on element ${a} horizontally: ${o}px, vertically: ${r}px`}}catch(c){return{success:!1,error:c.message,actionEntity:kr(`Scroll on element ${a} horizontally: ${o}px, vertically: ${r}px`,"scroll_on_element",{index:a,delta_x:o,delta_y:r})}}}})}var Sr,Td,Jt=b(()=>{"use strict";Z();G();P();Sr=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.delta_x||0,o=n.kwargs.delta_y||0,r=F(e,t),s=R(i,t.action_data?.kwargs?.timeout_ms);if(r)await r.hover({timeout:s}),await e.mouse.wheel(a,o);else throw new Error("No locator found for scroll_on_element action")}transpile(e){let t=Ne(e);if(!t){let a=e.action_data?.kwargs?.delta_x||0,o=e.action_data?.kwargs?.delta_y||0;return['await agent.execAction("scroll_on_element", page, {',` action_data: { kwargs: { delta_x: ${a}, delta_y: ${o} } },`,"});"]}let i=e.action_data?.kwargs?.delta_x||0,n=e.action_data?.kwargs?.delta_y||0;return[`await ${t}.hover({ timeout: ${R()} });`,`await page.mouse.wheel(${i}, ${n});`]}};Td=Xt.object({element_index:Xt.number().int().describe("Index of the scrollable element"),delta_x:Xt.number().optional().describe("The number of pixels to scroll horizontally. Positive values scroll right, negative values scroll left."),delta_y:Xt.number().optional().describe("The number of pixels to scroll vertically. Positive values scroll down, negative values scroll up."),timeout_ms:Xt.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as Tr}from"zod";function $r(e,t){e.register({name:"scroll_to_text",description:"Scroll the page until specified text becomes visible.",schema:Ad,async execute(i,n){let{text:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l={action_description:s||`Scroll to text "${a}"`,action_data:{action_name:"scroll_to_text",kwargs:{text:a}}};return await t.execute(o,l,r),{success:!0,actionEntity:l,message:`Scrolled to text "${a}"`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:(s||`Scroll to text "${a}"`)+" (failed)",action_data:{action_name:"scroll_to_text",kwargs:{text:a}},feedback:l.message}}}}})}var Ar,Ad,Yt=b(()=>{"use strict";Ar=class{async execute(e,t){let i=t.action_data;if(!i)throw new Error("Action data not found");let n=i.kwargs.text;if(n)await e.getByText(n,{exact:!1}).first().scrollIntoViewIfNeeded(),await e.waitForTimeout(500);else throw new Error("Missing text for scroll_to_text action")}transpile(e){let t=e.action_data?.kwargs?.text||"";return[`await page.getByText(${JSON.stringify(t)}, { exact: false }).first().scrollIntoViewIfNeeded();`]}},Ad=Tr.object({text:Tr.string().describe("Text to scroll to on the page")})});import{z as ln}from"zod";async function $d(e,t,i,n){return{...await j(t,e),action_description:n||`Select option "${i}"`,action_data:{action_name:"select_dropdown_option",kwargs:{text:i}}}}function Mr(e,t){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:"select_dropdown_option",kwargs:t},feedback:"Element not found in DOM"}}function Cr(e,t){e.register({name:"select_dropdown_option",description:"Select an option from a dropdown/select element by value, label, or index.",schema:Md,usesElementIndex:!0,async execute(i,n){let{element_index:a,option:o}=i,{page:r,agentServices:s,actionDescription:l}=n;try{let c=await X(n,a);if(!c)return{success:!1,error:`Dropdown element with index ${a} not found`,actionEntity:Mr(l||`Select option in dropdown ${a}`,{index:a,option:o})};let d=await $d(c,r,o,l);return await t.execute(r,d,s),{success:!0,actionEntity:d,message:`Selected option "${o}" in dropdown ${a}`}}catch(c){return{success:!1,error:c.message,actionEntity:Mr(`Select option in dropdown ${a}`,{index:a,option:o})}}}})}var Ir,Md,qt=b(()=>{"use strict";Z();G();P();Ir=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.text||n.kwargs.option,o=F(e,t),r=R(i,t.action_data?.kwargs?.timeout_ms);if(o&&a)await o.selectOption(a,{timeout:r});else throw new Error("Missing locator or option label for select_dropdown_option action")}transpile(e){let t=e.action_data?.kwargs?.text||e.action_data?.kwargs?.option||"",i=[];return i.push(`action_data: { kwargs: { text: ${JSON.stringify(t)} } }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`),['await agent.execAction("select_dropdown_option", page, {',...i.map(n=>` ${n},`),"});"]}};Md=ln.object({element_index:ln.number().int().describe("Index of the dropdown/select element"),option:ln.string().describe("Option value, label, or index to select"),timeout_ms:ln.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as cn}from"zod";async function Id(e,t,i,n){return{...await j(i,t),action_description:e,action_data:{action_name:"set_date_for_native_date_picker",kwargs:{date:n}}}}function aa(e,t){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:"set_date_for_native_date_picker",kwargs:t},feedback:"Element not found in DOM"}}function Or(e,t){e.register({name:"set_date_for_native_date_picker",description:`Set a date in a native HTML date picker input (<input type="date">).
4102
4124
 
4103
4125
  IMPORTANT: ONLY use this action for input elements that have type="date" attribute (native HTML date picker).
4104
4126
  Do NOT use it for custom/non-native date pickers
4105
4127
 
4106
- The date must be in YYYY-MM-DD format (e.g., 2024-03-15).`,schema:Cd,usesElementIndex:!0,async execute(i,n){let{element_index:a,date:o}=i,{page:r,agentServices:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Date picker element with index ${a} not found`,actionEntity:aa(`Set date to ${o} on element ${a}`,{index:a,date:o})};let c=l.attributes.type;if(c!=="date")return{success:!1,error:`Element ${a} is not a native date picker (type="${c}"). This action only works with <input type="date">.`,actionEntity:aa(`Set date to ${o} on element ${a}`,{index:a,date:o})};let d=await Id(`Set date to ${o} on element ${a}`,l,r,o);return await t.execute(r,d,s),{success:!0,actionEntity:d,message:`Set date to ${o} on element ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:aa(`Set date to ${o} on element ${a}`,{index:a,date:o})}}}})}var Pr,Cd,Zt=v(()=>{"use strict";Z();G();C();Pr=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.date;if(!a)throw new Error("Date value is required");if(!/^\d{4}-\d{2}-\d{2}$/.test(a))throw new Error(`Invalid date format: ${a}. Expected format: YYYY-MM-DD (e.g., 2024-03-15)`);let o=i.replaceVariables(String(a)),r=F(e,t);if(r){let s=await r.getAttribute("type").catch(()=>null);if(s&&s!=="date")throw new Error(`Element is not a native date picker (type="${s}"). This action only works with <input type="date">. For custom date pickers, use AI-powered actions.`);await r.fill(o,{timeout:R(i,t.action_data?.kwargs?.timeout_ms)})}else throw new Error("No locator found for set_date_for_native_date_picker action")}transpile(e){let t=e.action_data?.kwargs?.date??"",i=[];return i.push(`action_data: { kwargs: { date: ${JSON.stringify(t)} } }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`),['await agent.execAction("set_date_for_native_date_picker", page, {',...i.map(n=>` ${n},`),"});"]}};Cd=cn.object({element_index:cn.number().int().describe("Index of the native date picker input element"),date:cn.string().regex(/^\d{4}-\d{2}-\d{2}$/).describe("Date in YYYY-MM-DD format (e.g., 2024-03-15)"),timeout_ms:cn.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as oa}from"zod";async function Pd(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function Nr(e,t,i){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function Lr(e,t){e.register({name:"hover",description:"Hover over an interactive element.",schema:Od,usesElementIndex:!0,async execute(i,n){let{element_index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Element with index ${a} not found.`,actionEntity:Nr(`Hover element ${a}`,"hover",{index:a})};let c=s||`Hover over element ${a}`,d=await Pd("hover",c,l,o);return await t.execute(o,d,r),{success:!0,actionEntity:d,message:`Hovered over element ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:Nr(`Hover element ${a}`,"hover",{index:a})}}}})}var ra,Od,Qt=v(()=>{"use strict";Z();G();C();ra=class{async execute(e,t,i){let n=F(e,t),a=R(i,t.action_data?.kwargs?.timeout_ms);if(n){await n.waitFor({state:"attached",timeout:a});let o=await n.elementHandle();if(!o)throw new Error("Unable to obtain element handle for hover action");let r=await o.boundingBox();if(!r)throw new Error("Unable to determine bounding box for hover action");let s=r.x+r.width/2,l=r.y+r.height/2;await e.mouse.move(s,l)}else throw new Error("No locator found for hover action")}transpile(e){let t=[];return e.locator?t.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&t.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&t.push(`frame_path: ${JSON.stringify(e.frame_path)}`),t.length===0?['await agent.execAction("hover", page, {});']:['await agent.execAction("hover", page, {',...t.map(i=>` ${i},`),"});"]}};Od=oa.object({element_index:oa.number().int().describe("Index of the element to hover over"),timeout_ms:oa.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as dn}from"zod";async function Nd(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function Dr(e,t,i){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function Rr(e,t){e.register({name:"input_text",description:"Type text into an input field. To replace existing content, use clear_input first.",schema:Ld,usesElementIndex:!0,async execute(i,n){let{element_index:a,text:o}=i,{page:r,agentServices:s,actionDescription:l}=n;try{let c=await X(n,a);if(!c)return{success:!1,error:`Input element with index ${a} not found`,actionEntity:Dr(l||`Input text to element ${a}`,"input_text",{index:a,text:o})};let d=l||`Input text to element ${a}`,u=await Nd("input_text",d,c,r,{text:o});return await t.execute(r,u,s),{success:!0,actionEntity:u,message:`Input text to element ${a}`}}catch(c){return{success:!1,error:c.message,actionEntity:Dr(`Input text to element ${a}`,"input_text",{index:a,text:o})}}}})}var sa,Ld,ei=v(()=>{"use strict";Z();G();C();sa=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.text??n.kwargs.value??"",o=i.replaceVariables(String(a)),r=F(e,t),s=R(i,t.action_data?.kwargs?.timeout_ms);if(r){await r.evaluate(c=>{c.value&&(c.value="")},null,{timeout:s}),await r.click({timeout:s}),await e.waitForTimeout(200);let l=i.getActionSettings().type_delay;l!==void 0?await e.keyboard.type(o,{delay:l}):await e.keyboard.type(o)}else throw new Error("No locator found for input_text action")}transpile(e){let t=e.action_data?.kwargs?.text??e.action_data?.kwargs?.value??"",i=[];return i.push(`action_data: { kwargs: { text: ${JSON.stringify(t)} } }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`),['await agent.execAction("input_text", page, {',...i.map(n=>` ${n},`),"});"]}};Ld=dn.object({element_index:dn.number().int().describe("Index of the input element"),text:dn.string().describe("Text to type into the input. To use a placeholder, write {{ placeholder_name }} using exact placeholder name. Use clear_input first if you want to replace existing content."),timeout_ms:dn.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as Fr}from"zod";function Hr(e,t){e.register({name:"press",description:"Press a single keyboard key or key combination. Supports combinations like `Control+A` for select all. Does NOT support sequences - call this action multiple times to press keys in sequence.",schema:Dd,async execute(i,n){let{keys:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l={action_description:s||`Press keys "${a}"`,action_data:{action_name:"press",kwargs:{keys:a}}};return await t.execute(o,l,r),{success:!0,actionEntity:l,message:`Pressed keys "${a}"`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:(s||`Press keys "${a}"`)+" (failed)",action_data:{action_name:"press",kwargs:{keys:a}},feedback:l.message}}}}})}var la,Dd,ti=v(()=>{"use strict";la=class{async execute(e,t){let i=t.action_data;if(!i)throw new Error("Action data not found");let n=i.kwargs.keys;if(!n||typeof n!="string")throw new Error("Missing or invalid keys for press action");await e.keyboard.press(n),await e.waitForTimeout(500)}transpile(e){let t=e.action_data?.kwargs?.keys;return[`await page.keyboard.press(${JSON.stringify(t)});`]}},Dd=Fr.object({keys:Fr.string().describe("A single key or key combination to press (e.g. Escape, Backspace, Insert, PageDown, Delete, Tab, Enter). Key combinations like `Control+o`, `Control+Shift+T`, `ControlOrMeta+a` are supported. Note: This does NOT support sequences - to press multiple keys in sequence (e.g., Control+A then Backspace), call this action multiple times.")})});import{z as Rd}from"zod";function jr(e,t){e.register({name:"reload_page",description:"Reload the current page. WARNING: This will reset any in-progress forms or multi-step flows (like login). Only use when you need to refresh stale data or clear a stuck state. Do NOT use during login, checkout, or form submission flows.",schema:Fd,async execute(i,n){let{page:a,agentServices:o}=n;try{let r={action_description:"Reload page",action_data:{action_name:"reload_page",kwargs:{}}};return await t.execute(a,r,o),{success:!0,actionEntity:r,message:`Reloaded ${a.url()}`}}catch(r){return{success:!1,error:r.message,actionEntity:{action_description:"Reload page (failed)",action_data:{action_name:"reload_page",kwargs:{}},feedback:r.message}}}}})}var Wr,Fd,ii=v(()=>{"use strict";G();C();Wr=class{async execute(e,t){await e.reload({timeout:pe}),await e.waitForLoadState("load",{timeout:pe}),await e.waitForTimeout(1e3)}transpile(e){return['await agent.execAction("reload_page", page, {});']}},Fd=Rd.object({})});import{z as ca}from"zod";async function Hd(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function Ur(e,t,i){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function Br(e,t){e.register({name:"right_click",description:"Right-click an interactive element.",schema:Wd,usesElementIndex:!0,async execute(i,n){let{element_index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Element with index ${a} not found.`,actionEntity:Ur(`Right-click element ${a}`,"right_click",{index:a})};let c=s||`Right-click element ${a}`,d=await Hd("right_click",c,l,o);return await t.execute(o,d,r),{success:!0,actionEntity:d,message:`Right-clicked element ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:Ur(`Right-click element ${a}`,"right_click",{index:a})}}}})}var da,Wd,ni=v(()=>{"use strict";Z();G();C();da=class{async execute(e,t,i){let n=F(e,t),a=R(i,t.action_data?.kwargs?.timeout_ms);if(n)await n.click({button:"right",timeout:a});else throw new Error("No locator found for right_click action")}transpile(e){let t=[];return e.locator?t.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&t.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&t.push(`frame_path: ${JSON.stringify(e.frame_path)}`),t.length===0?['await agent.execAction("right_click", page, {});']:['await agent.execAction("right_click", page, {',...t.map(i=>` ${i},`),"});"]}};Wd=ca.object({element_index:ca.number().int().describe("Index of the element to right-click"),timeout_ms:ca.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as ua}from"zod";async function jd(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function Gr(e,t,i){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function Kr(e,t){e.register({name:"double_click",description:"Double-click an interactive element.",schema:Ud,usesElementIndex:!0,async execute(i,n){let{element_index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Element with index ${a} not found.`,actionEntity:Gr(`Double-click element ${a}`,"double_click",{index:a})};let c=s||`Double-click element ${a}`,d=await jd("double_click",c,l,o);return await t.execute(o,d,r),{success:!0,actionEntity:d,message:`Double-clicked element ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:Gr(`Double-click element ${a}`,"double_click",{index:a})}}}})}var ha,Ud,ai=v(()=>{"use strict";Z();G();C();ha=class{async execute(e,t,i){let n=F(e,t),a=R(i,t.action_data?.kwargs?.timeout_ms);if(n)await n.dblclick({timeout:a});else throw new Error("No locator found for double_click action")}transpile(e){let t=[];return e.locator?t.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&t.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&t.push(`frame_path: ${JSON.stringify(e.frame_path)}`),t.length===0?['await agent.execAction("double_click", page, {});']:['await agent.execAction("double_click", page, {',...t.map(i=>` ${i},`),"});"]}};Ud=ua.object({element_index:ua.number().int().describe("Index of the element to double-click"),timeout_ms:ua.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as zr}from"zod";function Xr(e,t){e.register({name:"generate_2fa_code",description:'Generate a 2FA code from an OTP secret key. The code is saved to the "otp_code" variable. To use the otp_code, you must use `$otp_code` to access it.',schema:Bd,async execute(i,n){let{otp_secret_key:a}=i,{page:o,agentServices:r}=n;try{let s={action_description:"Generate 2FA code",action_data:{action_name:"generate_2fa_code",kwargs:{otp_secret_key:a}}};return await t.execute(o,s,r),{success:!0,actionEntity:s,message:'Generated 2FA code and saved to variable "otp_code"'}}catch(s){return{success:!1,error:s.message,actionEntity:{action_description:"Generate 2FA code (failed)",action_data:{action_name:"generate_2fa_code",kwargs:{otp_secret_key:a}},feedback:s.message}}}}})}var Vr,Bd,oi=v(()=>{"use strict";Vr=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.otp_secret_key;if(!a)throw new Error("Missing otp_secret_key for generate_2fa_code");let o=i.replaceVariables(String(a)),r=await i.generate2faCode(o);i.saveVariable("otp_code",r)}transpile(e){let t=e.action_data?.kwargs?.otp_secret_key||"";return['await agent.execAction("generate_2fa_code", page, {',` action_data: { kwargs: { otp_secret_key: ${JSON.stringify(t)} } },`,"});"]}},Bd=zr.object({otp_secret_key:zr.string().describe("The OTP secret key to generate the 2FA code from")})});import{z as Jr}from"zod";async function Gd(e,t,i){return{...await j(t,e),action_description:i||"Get dropdown options",action_data:{action_name:"get_dropdown_options",kwargs:{}}}}function Yr(e,t){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:"get_dropdown_options",kwargs:t},feedback:"Element not found in DOM"}}function Zr(e,t){e.register({name:"get_dropdown_options",description:"Get all options from a native dropdown",schema:Kd,usesElementIndex:!0,async execute(i,n){let{element_index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Dropdown element with index ${a} not found`,actionEntity:Yr(s||`Get options from dropdown ${a}`,{index:a})};let c=await Gd(l,o,s);return await t.execute(o,c,r),{success:!0,actionEntity:c,message:c.feedback||"No options found"}}catch(l){return{success:!1,error:l.message,actionEntity:Yr(s||`Get options from dropdown ${a}`,{index:a})}}}})}var qr,Kd,ri=v(()=>{"use strict";Z();qr=class{async execute(e,t,i){if(!t.xpath)throw new Error("XPath not found in action entity");let n=[];for(let a of e.frames())try{let o=await a.evaluate(r=>{let s=document.evaluate(r,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return s?{options:Array.from(s.options).map(l=>({text:l.text,value:l.value,index:l.index})),id:s.id,name:s.name}:null},t.xpath);if(o){let r=[];for(let s of o.options){let l=JSON.stringify(s.text);r.push(`${s.index}: text=${l}`)}n.push(...r)}}catch{}if(n.length>0){let a=n.join(`
4128
+ The date must be in YYYY-MM-DD format (e.g., 2024-03-15).`,schema:Cd,usesElementIndex:!0,async execute(i,n){let{element_index:a,date:o}=i,{page:r,agentServices:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Date picker element with index ${a} not found`,actionEntity:aa(`Set date to ${o} on element ${a}`,{index:a,date:o})};let c=l.attributes.type;if(c!=="date")return{success:!1,error:`Element ${a} is not a native date picker (type="${c}"). This action only works with <input type="date">.`,actionEntity:aa(`Set date to ${o} on element ${a}`,{index:a,date:o})};let d=await Id(`Set date to ${o} on element ${a}`,l,r,o);return await t.execute(r,d,s),{success:!0,actionEntity:d,message:`Set date to ${o} on element ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:aa(`Set date to ${o} on element ${a}`,{index:a,date:o})}}}})}var Pr,Cd,Zt=b(()=>{"use strict";Z();G();P();Pr=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.date;if(!a)throw new Error("Date value is required");if(!/^\d{4}-\d{2}-\d{2}$/.test(a))throw new Error(`Invalid date format: ${a}. Expected format: YYYY-MM-DD (e.g., 2024-03-15)`);let o=i.replaceVariables(String(a)),r=F(e,t);if(r){let s=await r.getAttribute("type").catch(()=>null);if(s&&s!=="date")throw new Error(`Element is not a native date picker (type="${s}"). This action only works with <input type="date">. For custom date pickers, use AI-powered actions.`);await r.fill(o,{timeout:R(i,t.action_data?.kwargs?.timeout_ms)})}else throw new Error("No locator found for set_date_for_native_date_picker action")}transpile(e){let t=e.action_data?.kwargs?.date??"",i=[];return i.push(`action_data: { kwargs: { date: ${JSON.stringify(t)} } }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`),['await agent.execAction("set_date_for_native_date_picker", page, {',...i.map(n=>` ${n},`),"});"]}};Cd=cn.object({element_index:cn.number().int().describe("Index of the native date picker input element"),date:cn.string().regex(/^\d{4}-\d{2}-\d{2}$/).describe("Date in YYYY-MM-DD format (e.g., 2024-03-15)"),timeout_ms:cn.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as oa}from"zod";async function Pd(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function Nr(e,t,i){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function Lr(e,t){e.register({name:"hover",description:"Hover over an interactive element.",schema:Od,usesElementIndex:!0,async execute(i,n){let{element_index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Element with index ${a} not found.`,actionEntity:Nr(`Hover element ${a}`,"hover",{index:a})};let c=s||`Hover over element ${a}`,d=await Pd("hover",c,l,o);return await t.execute(o,d,r),{success:!0,actionEntity:d,message:`Hovered over element ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:Nr(`Hover element ${a}`,"hover",{index:a})}}}})}var ra,Od,Qt=b(()=>{"use strict";Z();G();P();ra=class{async execute(e,t,i){let n=F(e,t),a=R(i,t.action_data?.kwargs?.timeout_ms);if(n){await n.waitFor({state:"attached",timeout:a});let o=await n.elementHandle();if(!o)throw new Error("Unable to obtain element handle for hover action");let r=await o.boundingBox();if(!r)throw new Error("Unable to determine bounding box for hover action");let s=r.x+r.width/2,l=r.y+r.height/2;await e.mouse.move(s,l)}else throw new Error("No locator found for hover action")}transpile(e){let t=[];return e.locator?t.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&t.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&t.push(`frame_path: ${JSON.stringify(e.frame_path)}`),t.length===0?['await agent.execAction("hover", page, {});']:['await agent.execAction("hover", page, {',...t.map(i=>` ${i},`),"});"]}};Od=oa.object({element_index:oa.number().int().describe("Index of the element to hover over"),timeout_ms:oa.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as dn}from"zod";async function Nd(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function Dr(e,t,i){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function Rr(e,t){e.register({name:"input_text",description:"Type text into an input field. To replace existing content, use clear_input first.",schema:Ld,usesElementIndex:!0,async execute(i,n){let{element_index:a,text:o}=i,{page:r,agentServices:s,actionDescription:l}=n;try{let c=await X(n,a);if(!c)return{success:!1,error:`Input element with index ${a} not found`,actionEntity:Dr(l||`Input text to element ${a}`,"input_text",{index:a,text:o})};let d=l||`Input text to element ${a}`,u=await Nd("input_text",d,c,r,{text:o});return await t.execute(r,u,s),{success:!0,actionEntity:u,message:`Input text to element ${a}`}}catch(c){return{success:!1,error:c.message,actionEntity:Dr(`Input text to element ${a}`,"input_text",{index:a,text:o})}}}})}var sa,Ld,ei=b(()=>{"use strict";Z();G();P();sa=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.text??n.kwargs.value??"",o=i.replaceVariables(String(a)),r=F(e,t),s=R(i,t.action_data?.kwargs?.timeout_ms);if(r){await r.evaluate(c=>{c.value&&(c.value="")},null,{timeout:s}),await r.click({timeout:s}),await e.waitForTimeout(200);let l=i.getActionSettings().type_delay;l!==void 0?await e.keyboard.type(o,{delay:l}):await e.keyboard.type(o)}else throw new Error("No locator found for input_text action")}transpile(e){let t=e.action_data?.kwargs?.text??e.action_data?.kwargs?.value??"",i=[];return i.push(`action_data: { kwargs: { text: ${JSON.stringify(t)} } }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`),['await agent.execAction("input_text", page, {',...i.map(n=>` ${n},`),"});"]}};Ld=dn.object({element_index:dn.number().int().describe("Index of the input element"),text:dn.string().describe("Text to type into the input. To use a placeholder, write {{ placeholder_name }} using exact placeholder name. Use clear_input first if you want to replace existing content."),timeout_ms:dn.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as Fr}from"zod";function Hr(e,t){e.register({name:"press",description:"Press a single keyboard key or key combination. Supports combinations like `Control+A` for select all. Does NOT support sequences - call this action multiple times to press keys in sequence.",schema:Dd,async execute(i,n){let{keys:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l={action_description:s||`Press keys "${a}"`,action_data:{action_name:"press",kwargs:{keys:a}}};return await t.execute(o,l,r),{success:!0,actionEntity:l,message:`Pressed keys "${a}"`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:(s||`Press keys "${a}"`)+" (failed)",action_data:{action_name:"press",kwargs:{keys:a}},feedback:l.message}}}}})}var la,Dd,ti=b(()=>{"use strict";la=class{async execute(e,t){let i=t.action_data;if(!i)throw new Error("Action data not found");let n=i.kwargs.keys;if(!n||typeof n!="string")throw new Error("Missing or invalid keys for press action");await e.keyboard.press(n),await e.waitForTimeout(500)}transpile(e){let t=e.action_data?.kwargs?.keys;return[`await page.keyboard.press(${JSON.stringify(t)});`]}},Dd=Fr.object({keys:Fr.string().describe("A single key or key combination to press (e.g. Escape, Backspace, Insert, PageDown, Delete, Tab, Enter). Key combinations like `Control+o`, `Control+Shift+T`, `ControlOrMeta+a` are supported. Note: This does NOT support sequences - to press multiple keys in sequence (e.g., Control+A then Backspace), call this action multiple times.")})});import{z as Rd}from"zod";function jr(e,t){e.register({name:"reload_page",description:"Reload the current page. WARNING: This will reset any in-progress forms or multi-step flows (like login). Only use when you need to refresh stale data or clear a stuck state. Do NOT use during login, checkout, or form submission flows.",schema:Fd,async execute(i,n){let{page:a,agentServices:o}=n;try{let r={action_description:"Reload page",action_data:{action_name:"reload_page",kwargs:{}}};return await t.execute(a,r,o),{success:!0,actionEntity:r,message:`Reloaded ${a.url()}`}}catch(r){return{success:!1,error:r.message,actionEntity:{action_description:"Reload page (failed)",action_data:{action_name:"reload_page",kwargs:{}},feedback:r.message}}}}})}var Wr,Fd,ii=b(()=>{"use strict";G();P();Wr=class{async execute(e,t){await e.reload({timeout:pe}),await e.waitForLoadState("load",{timeout:pe}),await e.waitForTimeout(1e3)}transpile(e){return['await agent.execAction("reload_page", page, {});']}},Fd=Rd.object({})});import{z as ca}from"zod";async function Hd(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function Ur(e,t,i){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function Br(e,t){e.register({name:"right_click",description:"Right-click an interactive element.",schema:Wd,usesElementIndex:!0,async execute(i,n){let{element_index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Element with index ${a} not found.`,actionEntity:Ur(`Right-click element ${a}`,"right_click",{index:a})};let c=s||`Right-click element ${a}`,d=await Hd("right_click",c,l,o);return await t.execute(o,d,r),{success:!0,actionEntity:d,message:`Right-clicked element ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:Ur(`Right-click element ${a}`,"right_click",{index:a})}}}})}var da,Wd,ni=b(()=>{"use strict";Z();G();P();da=class{async execute(e,t,i){let n=F(e,t),a=R(i,t.action_data?.kwargs?.timeout_ms);if(n)await n.click({button:"right",timeout:a});else throw new Error("No locator found for right_click action")}transpile(e){let t=[];return e.locator?t.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&t.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&t.push(`frame_path: ${JSON.stringify(e.frame_path)}`),t.length===0?['await agent.execAction("right_click", page, {});']:['await agent.execAction("right_click", page, {',...t.map(i=>` ${i},`),"});"]}};Wd=ca.object({element_index:ca.number().int().describe("Index of the element to right-click"),timeout_ms:ca.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as ua}from"zod";async function jd(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function Gr(e,t,i){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function Kr(e,t){e.register({name:"double_click",description:"Double-click an interactive element.",schema:Ud,usesElementIndex:!0,async execute(i,n){let{element_index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Element with index ${a} not found.`,actionEntity:Gr(`Double-click element ${a}`,"double_click",{index:a})};let c=s||`Double-click element ${a}`,d=await jd("double_click",c,l,o);return await t.execute(o,d,r),{success:!0,actionEntity:d,message:`Double-clicked element ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:Gr(`Double-click element ${a}`,"double_click",{index:a})}}}})}var ha,Ud,ai=b(()=>{"use strict";Z();G();P();ha=class{async execute(e,t,i){let n=F(e,t),a=R(i,t.action_data?.kwargs?.timeout_ms);if(n)await n.dblclick({timeout:a});else throw new Error("No locator found for double_click action")}transpile(e){let t=[];return e.locator?t.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&t.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&t.push(`frame_path: ${JSON.stringify(e.frame_path)}`),t.length===0?['await agent.execAction("double_click", page, {});']:['await agent.execAction("double_click", page, {',...t.map(i=>` ${i},`),"});"]}};Ud=ua.object({element_index:ua.number().int().describe("Index of the element to double-click"),timeout_ms:ua.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as zr}from"zod";function Xr(e,t){e.register({name:"generate_2fa_code",description:'Generate a 2FA code from an OTP secret key. The code is saved to the "otp_code" variable. To use the otp_code, you must use `$otp_code` to access it.',schema:Bd,async execute(i,n){let{otp_secret_key:a}=i,{page:o,agentServices:r}=n;try{let s={action_description:"Generate 2FA code",action_data:{action_name:"generate_2fa_code",kwargs:{otp_secret_key:a}}};return await t.execute(o,s,r),{success:!0,actionEntity:s,message:'Generated 2FA code and saved to variable "otp_code"'}}catch(s){return{success:!1,error:s.message,actionEntity:{action_description:"Generate 2FA code (failed)",action_data:{action_name:"generate_2fa_code",kwargs:{otp_secret_key:a}},feedback:s.message}}}}})}var Vr,Bd,oi=b(()=>{"use strict";Vr=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.otp_secret_key;if(!a)throw new Error("Missing otp_secret_key for generate_2fa_code");let o=i.replaceVariables(String(a)),r=await i.generate2faCode(o);i.saveVariable("otp_code",r)}transpile(e){let t=e.action_data?.kwargs?.otp_secret_key||"";return['await agent.execAction("generate_2fa_code", page, {',` action_data: { kwargs: { otp_secret_key: ${JSON.stringify(t)} } },`,"});"]}},Bd=zr.object({otp_secret_key:zr.string().describe("The OTP secret key to generate the 2FA code from")})});import{z as Jr}from"zod";async function Gd(e,t,i){return{...await j(t,e),action_description:i||"Get dropdown options",action_data:{action_name:"get_dropdown_options",kwargs:{}}}}function Yr(e,t){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:"get_dropdown_options",kwargs:t},feedback:"Element not found in DOM"}}function Zr(e,t){e.register({name:"get_dropdown_options",description:"Get all options from a native dropdown",schema:Kd,usesElementIndex:!0,async execute(i,n){let{element_index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Dropdown element with index ${a} not found`,actionEntity:Yr(s||`Get options from dropdown ${a}`,{index:a})};let c=await Gd(l,o,s);return await t.execute(o,c,r),{success:!0,actionEntity:c,message:c.feedback||"No options found"}}catch(l){return{success:!1,error:l.message,actionEntity:Yr(s||`Get options from dropdown ${a}`,{index:a})}}}})}var qr,Kd,ri=b(()=>{"use strict";Z();qr=class{async execute(e,t,i){if(!t.xpath)throw new Error("XPath not found in action entity");let n=[];for(let a of e.frames())try{let o=await a.evaluate(r=>{let s=document.evaluate(r,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return s?{options:Array.from(s.options).map(l=>({text:l.text,value:l.value,index:l.index})),id:s.id,name:s.name}:null},t.xpath);if(o){let r=[];for(let s of o.options){let l=JSON.stringify(s.text);r.push(`${s.index}: text=${l}`)}n.push(...r)}}catch{}if(n.length>0){let a=n.join(`
4107
4129
  `);a+=`
4108
- Use the exact text string in select_dropdown_option`,i.addNote(a)}else i.addNote("No options found in any frame for dropdown")}transpile(e){let t=[];return e.xpath&&t.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&t.push(`frame_path: ${JSON.stringify(e.frame_path)}`),t.length===0?['await agent.execAction("get_dropdown_options", page, {});']:['await agent.execAction("get_dropdown_options", page, {',...t.map(i=>` ${i},`),"});"]}};Kd=Jr.object({element_index:Jr.number().int().describe("Index of the dropdown/select element")})});import{z as zd}from"zod";function es(e,t){e.register({name:"go_back",description:"Navigate back to the previous page in browser history.",schema:Vd,async execute(i,n){let{page:a,agentServices:o,actionDescription:r}=n;try{let s={action_description:r||"Go back",action_data:{action_name:"go_back",kwargs:{}}};return await t.execute(a,s,o),{success:!0,actionEntity:s,message:"Navigated back"}}catch(s){return{success:!1,error:s.message,actionEntity:{action_description:(r||"Go back")+" (failed)",action_data:{action_name:"go_back",kwargs:{}},feedback:s.message}}}}})}var Qr,Vd,si=v(()=>{"use strict";G();C();Qr=class{async execute(e,t){await e.goBack({timeout:pe}),await e.waitForLoadState("load",{timeout:pe}),await e.waitForTimeout(1e3)}transpile(e){return['await agent.execAction("go_back", page, {});']}},Vd=zd.object({})});import{z as un}from"zod";function ts(e,t){e.register({name:"go_to_url",description:"Navigate to a specific URL. Use this to visit web pages. Set new_tab=true to open in a new tab.",schema:Xd,async execute(i,n){let{url:a,new_tab:o,timeout_seconds:r}=i,{page:s,agentServices:l,actionDescription:c}=n,d={url:a,new_tab:o??!1};r!==void 0&&(d.timeout_seconds=r);let u=r?` (timeout: ${r}s)`:"";try{let m=o?`Open ${a} in new tab`:`Navigate to ${a}`,p={action_description:c||m,action_data:{action_name:"go_to_url",kwargs:d}};return await t.execute(s,p,l),{success:!0,actionEntity:p,message:(o?`Opened ${a} in new tab`:`Navigated to ${a}`)+u}}catch(m){let p=o?`Open ${a} in new tab`:`Navigate to ${a}`;return{success:!1,error:m.message,actionEntity:{action_description:(c||p)+" (failed)",action_data:{action_name:"go_to_url",kwargs:d},feedback:m.message}}}}})}var ma,Xd,li=v(()=>{"use strict";G();C();ma=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.url;if(!a)throw new Error("Missing URL for go_to_url action");let o=n.kwargs.new_tab===!0,r=i.replaceVariables(String(a));if(r.startsWith("/")){let c=e.url(),d=null;try{let u=new URL(c);u.origin&&u.origin!=="null"&&(d=u.origin)}catch{}d&&(r=d+r)}let s=n.kwargs.timeout_seconds?n.kwargs.timeout_seconds*1e3:pe,l=e;o&&(l=await e.context().newPage(),i.setPage(l)),await l.goto(r,{timeout:s})}transpile(e){let t=e.action_data?.kwargs?.url||"",i=e.action_data?.kwargs?.new_tab===!0,n=e.action_data?.kwargs?.timeout_seconds,a=[`url: ${JSON.stringify(t)}`];return i&&a.push("new_tab: true"),n&&a.push(`timeout_seconds: ${n}`),['await agent.execAction("go_to_url", page, {',` action_data: { kwargs: { ${a.join(", ")} } },`,"});"]}},Xd=un.object({url:un.string().describe('URL to navigate to (HTTP/HTTPS URL, or a path like "/home")'),new_tab:un.boolean().optional().describe("If true, open the URL in a new tab instead of the current page. Default is false."),timeout_seconds:un.number().positive().optional().describe("Navigation timeout in seconds. Default is 20 seconds.")})});import{parse as Jd}from"@babel/parser";function is(e){if(!e.trim())return!1;try{return Jd(e,{sourceType:"module",plugins:["typescript"]}),!0}catch{return!1}}var hn=v(()=>{"use strict"});import{z as ns}from"zod";function as(e,t){e.register({name:"verify",description:"Verify that a statement is true based on the current page state. Use this to check assertions about the page content, element visibility, or any condition.",schema:Yd,async execute(i,n){let{statement:a}=i,{page:o,agentServices:r}=n;try{let s={action_description:`${a}`,action_data:{action_name:"verify",kwargs:{statement:a}}};return await t.execute(o,s,r),{success:!0,actionEntity:s,message:`Assertion verified: ${a}`}}catch(s){return{success:!1,error:s.message,actionEntity:{action_description:`Verify: ${a} (failed)`,action_data:{action_name:"verify",kwargs:{statement:a}},feedback:s.message}}}},availability:{openai:!0,mcp:!0}})}var mn,Yd,ci=v(()=>{"use strict";lt();hn();B();mn=class{async execute(e,t,i){let n=t.action_data?.kwargs,a=typeof n?.code=="string",o=a?n?.statement||t.action_description:t.action_description||n?.statement;if(a&&o){let d=Date.now();try{await this.executeJSAssertion(e,n.code,i),f.info(`[VERIFY:JS] \u2713 ${((Date.now()-d)/1e3).toFixed(1)}s: ${o}`),i.addNote(`Assertion passed: ${o}`);return}catch(u){let m=((Date.now()-d)/1e3).toFixed(1);f.info(`[VERIFY:JS\u2192AI] JS failed ${m}s (${u instanceof Error?u.message:String(u)}), falling back to AI: ${o}`)}}else if(a){let d=Date.now();await this.executeJSAssertion(e,n.code,i),f.info(`[VERIFY:JS] \u2713 ${((Date.now()-d)/1e3).toFixed(1)}s: ${o||"js-only"}`),i.addNote(`Assertion passed: ${o||"js-only"}`);return}if(!o)throw new Error("Missing statement or code for verify action");let r=Date.now();f.info(`[VERIFY:AI] Evaluating: ${o}`);let{evaluateStatement:s}=await Promise.resolve().then(()=>(dt(),ct)),l=await s(o,e,i,{useCleanScreenshotForAssertion:!0}),c=l.explanation||l.error||(l.success?`Assertion passed: ${o}`:"Assertion failed");if(i.addNote(c),!l.success)throw f.info(`[VERIFY:AI] \u2717 ${((Date.now()-r)/1e3).toFixed(1)}s: ${o}`),new Error(l.error||l.explanation||"Assertion failed");f.info(`[VERIFY:AI] \u2713 ${((Date.now()-r)/1e3).toFixed(1)}s: ${o}`)}async executeJSAssertion(e,t,i){let n=i.agent;if(!n)throw new Error("Agent not initialized on AgentServices \u2014 ai_assert requires an agent reference");try{await new Function("page","expect","agent",`
4130
+ Use the exact text string in select_dropdown_option`,i.addNote(a)}else i.addNote("No options found in any frame for dropdown")}transpile(e){let t=[];return e.xpath&&t.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&t.push(`frame_path: ${JSON.stringify(e.frame_path)}`),t.length===0?['await agent.execAction("get_dropdown_options", page, {});']:['await agent.execAction("get_dropdown_options", page, {',...t.map(i=>` ${i},`),"});"]}};Kd=Jr.object({element_index:Jr.number().int().describe("Index of the dropdown/select element")})});import{z as zd}from"zod";function es(e,t){e.register({name:"go_back",description:"Navigate back to the previous page in browser history.",schema:Vd,async execute(i,n){let{page:a,agentServices:o,actionDescription:r}=n;try{let s={action_description:r||"Go back",action_data:{action_name:"go_back",kwargs:{}}};return await t.execute(a,s,o),{success:!0,actionEntity:s,message:"Navigated back"}}catch(s){return{success:!1,error:s.message,actionEntity:{action_description:(r||"Go back")+" (failed)",action_data:{action_name:"go_back",kwargs:{}},feedback:s.message}}}}})}var Qr,Vd,si=b(()=>{"use strict";G();P();Qr=class{async execute(e,t){await e.goBack({timeout:pe}),await e.waitForLoadState("load",{timeout:pe}),await e.waitForTimeout(1e3)}transpile(e){return['await agent.execAction("go_back", page, {});']}},Vd=zd.object({})});import{z as un}from"zod";function ts(e,t){e.register({name:"go_to_url",description:"Navigate to a specific URL. Use this to visit web pages. Set new_tab=true to open in a new tab.",schema:Xd,async execute(i,n){let{url:a,new_tab:o,timeout_seconds:r}=i,{page:s,agentServices:l,actionDescription:c}=n,d={url:a,new_tab:o??!1};r!==void 0&&(d.timeout_seconds=r);let u=r?` (timeout: ${r}s)`:"";try{let m=o?`Open ${a} in new tab`:`Navigate to ${a}`,p={action_description:c||m,action_data:{action_name:"go_to_url",kwargs:d}};return await t.execute(s,p,l),{success:!0,actionEntity:p,message:(o?`Opened ${a} in new tab`:`Navigated to ${a}`)+u}}catch(m){let p=o?`Open ${a} in new tab`:`Navigate to ${a}`;return{success:!1,error:m.message,actionEntity:{action_description:(c||p)+" (failed)",action_data:{action_name:"go_to_url",kwargs:d},feedback:m.message}}}}})}var ma,Xd,li=b(()=>{"use strict";G();P();ma=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.url;if(!a)throw new Error("Missing URL for go_to_url action");let o=n.kwargs.new_tab===!0,r=i.replaceVariables(String(a));if(r.startsWith("/")){let c=e.url(),d=null;try{let u=new URL(c);u.origin&&u.origin!=="null"&&(d=u.origin)}catch{}d&&(r=d+r)}let s=n.kwargs.timeout_seconds?n.kwargs.timeout_seconds*1e3:pe,l=e;o&&(l=await e.context().newPage(),i.setPage(l)),await l.goto(r,{timeout:s})}transpile(e){let t=e.action_data?.kwargs?.url||"",i=e.action_data?.kwargs?.new_tab===!0,n=e.action_data?.kwargs?.timeout_seconds,a=[`url: ${JSON.stringify(t)}`];return i&&a.push("new_tab: true"),n&&a.push(`timeout_seconds: ${n}`),['await agent.execAction("go_to_url", page, {',` action_data: { kwargs: { ${a.join(", ")} } },`,"});"]}},Xd=un.object({url:un.string().describe('URL to navigate to (HTTP/HTTPS URL, or a path like "/home")'),new_tab:un.boolean().optional().describe("If true, open the URL in a new tab instead of the current page. Default is false."),timeout_seconds:un.number().positive().optional().describe("Navigation timeout in seconds. Default is 20 seconds.")})});import{parse as Jd}from"@babel/parser";function is(e){if(!e.trim())return!1;try{return Jd(e,{sourceType:"module",plugins:["typescript"]}),!0}catch{return!1}}var hn=b(()=>{"use strict"});import{z as ns}from"zod";function as(e,t){e.register({name:"verify",description:"Verify that a statement is true based on the current page state. Use this to check assertions about the page content, element visibility, or any condition.",schema:Yd,async execute(i,n){let{statement:a}=i,{page:o,agentServices:r}=n;try{let s={action_description:`${a}`,action_data:{action_name:"verify",kwargs:{statement:a}}};return await t.execute(o,s,r),{success:!0,actionEntity:s,message:`Assertion verified: ${a}`}}catch(s){return{success:!1,error:s.message,actionEntity:{action_description:`Verify: ${a} (failed)`,action_data:{action_name:"verify",kwargs:{statement:a}},feedback:s.message}}}},availability:{openai:!0,mcp:!0}})}var mn,Yd,ci=b(()=>{"use strict";ct();hn();B();mn=class{async execute(e,t,i){let n=t.action_data?.kwargs,a=typeof n?.code=="string",o=a?n?.statement||t.action_description:t.action_description||n?.statement;if(a&&o){let d=Date.now();try{await this.executeJSAssertion(e,n.code,i),f.info(`[VERIFY:JS] \u2713 ${((Date.now()-d)/1e3).toFixed(1)}s: ${o}`),i.addNote(`Assertion passed: ${o}`);return}catch(u){let m=((Date.now()-d)/1e3).toFixed(1);f.info(`[VERIFY:JS\u2192AI] JS failed ${m}s (${u instanceof Error?u.message:String(u)}), falling back to AI: ${o}`)}}else if(a){let d=Date.now();await this.executeJSAssertion(e,n.code,i),f.info(`[VERIFY:JS] \u2713 ${((Date.now()-d)/1e3).toFixed(1)}s: ${o||"js-only"}`),i.addNote(`Assertion passed: ${o||"js-only"}`);return}if(!o)throw new Error("Missing statement or code for verify action");let r=Date.now();f.info(`[VERIFY:AI] Evaluating: ${o}`);let{evaluateStatement:s}=await Promise.resolve().then(()=>(ut(),dt)),l=await s(o,e,i,{useCleanScreenshotForAssertion:!0}),c=l.explanation||l.error||(l.success?`Assertion passed: ${o}`:"Assertion failed");if(i.addNote(c),!l.success)throw f.info(`[VERIFY:AI] \u2717 ${((Date.now()-r)/1e3).toFixed(1)}s: ${o}`),new Error(l.error||l.explanation||"Assertion failed");f.info(`[VERIFY:AI] \u2713 ${((Date.now()-r)/1e3).toFixed(1)}s: ${o}`)}async executeJSAssertion(e,t,i){let n=i.agent;if(!n)throw new Error("Agent not initialized on AgentServices \u2014 ai_assert requires an agent reference");try{await new Function("page","expect","agent",`
4109
4131
  return (async () => {
4110
4132
  ${t}
4111
4133
  })();
4112
4134
  `)(e,We.expect,n)}catch(a){throw new Error(`Assertion failed: ${a instanceof Error?a.message:String(a)}`)}}transpile(e,t){let i=e.action_data?.kwargs,n=typeof i?.code=="string",a=n?i?.statement||e.action_description:e.action_description||i?.statement,o=JSON.stringify(t||"");if(n){let r=i.code;if(!is(r))return[`throw new Error("Invalid assertion code syntax: " + ${JSON.stringify(r)});`];if(a){let s=r.split(`
4113
4135
  `),l=JSON.stringify(a);return["{ const _t = Date.now(); try {",...s.map(c=>` ${c}`),` console.log(\`[VERIFY:JS] \u2713 \${((Date.now()-_t)/1000).toFixed(1)}s: ${l}\`);`,"} catch (_e) {",` console.log(\`[VERIFY:JS\u2192AI] JS failed \${((Date.now()-_t)/1000).toFixed(1)}s: (\${_e instanceof Error ? _e.message : String(_e)}), falling back to AI: ${l}\`);`,` await agent.assert(page, ${l}, ${o});`,"} }"]}return r.split(`
4114
- `)}return a?[`await agent.assert(page, ${JSON.stringify(a)}, ${o});`]:["// Skipping verify: missing statement or code"]}},Yd=ns.object({statement:ns.string().describe('The nature language statement to verify (e.g., "The login was successful")')})});import{z as pa}from"zod";function rs(e,t){e.register({name:"ai_extract",description:"Use AI to extract information from the page and save it to a variable. MCP-only tool.",schema:qd,async execute(i,n){let{element_description:a,variable_name:o}=i,{page:r,agentServices:s}=n;try{let l={action_description:`Extract ${a} to ${o}`,action_data:{action_name:"ai_extract",kwargs:{element_description:a,variable_name:o}}};return await t.execute(r,l,s),{success:!0,actionEntity:l,message:`Extracted ${a} to ${o}`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:`Extract ${a} (failed)`,action_data:{action_name:"ai_extract",kwargs:{element_description:a,variable_name:o}},feedback:l.message}}}},availability:{openai:!1,mcp:!0}})}var os,qd,di=v(()=>{"use strict";os=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.element_description,o=n.kwargs.variable_name;if(!a||!o)throw new Error("Missing element_description or variable_name for ai_extract");let r=`Extract ${a} and save to ${o}`,{executeStep:s}=await Promise.resolve().then(()=>(dt(),ct)),l=await s(r,e,i);if(l.status!=="success")throw new Error(l.error||"Extraction failed")}transpile(e,t){let i=e.action_data?.kwargs?.element_description,n=e.action_data?.kwargs?.variable_name;if(!i||!n)return["// Skipping ai_extract: missing element_description or variable_name"];let a=JSON.stringify(i),o=JSON.stringify(n);return[`await agent.extract(page, ${a}, ${o}, '${t||""}');`]}},qd=pa.object({element_description:pa.string().describe('Description of the element to extract (e.g., "the price of the product")'),variable_name:pa.string().describe("Name of the variable to store the extracted value")})});import{z as ga}from"zod";async function Zd(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function ss(e,t,i){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function cs(e,t){e.register({name:"clear_input",description:"Clear the contents of an input field, textarea, or other editable element.",schema:Qd,usesElementIndex:!0,async execute(i,n){let{element_index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Input element with index ${a} not found`,actionEntity:ss(s||`Clear element ${a}`,"clear_input",{index:a})};let c=s||`Clear element ${a}`,d=await Zd("clear_input",c,l,o);return await t.execute(o,d,r),{success:!0,actionEntity:d,message:`Cleared element ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:ss(`Clear element ${a}`,"clear_input",{index:a})}}}})}var ls,Qd,ui=v(()=>{"use strict";Z();G();C();ls=class{async execute(e,t,i){let n=F(e,t),a=R(i,t.action_data?.kwargs?.timeout_ms);if(n)await n.click({timeout:a}),await e.keyboard.press("ControlOrMeta+a"),await e.waitForTimeout(200),await e.keyboard.press("Backspace"),await e.waitForTimeout(200);else throw new Error("No locator found for clear_input action")}transpile(e){let t=[];return e.locator?t.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&t.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&t.push(`frame_path: ${JSON.stringify(e.frame_path)}`),t.length===0?['await agent.execAction("clear_input", page, {});']:['await agent.execAction("clear_input", page, {',...t.map(i=>` ${i},`),"});"]}};Qd=ga.object({element_index:ga.number().int().describe("Index of the input element to clear"),timeout_ms:ga.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as fa}from"zod";async function eu(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function ds(e,t,i){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function us(e,t){e.register({name:"click",description:"Click an interactive element.",schema:tu,usesElementIndex:!0,async execute(i,n){let{element_index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Element with index ${a} not found.`,actionEntity:ds(`Click element ${a}`,"click",{index:a})};let c=s||`Click element ${a}`,d=await eu("click",c,l,o);return await t.execute(o,d,r),{success:!0,actionEntity:d,message:`Clicked element ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:ds(`Click element ${a}`,"click",{index:a})}}}})}var pn,tu,hi=v(()=>{"use strict";Z();G();C();pn=class{async execute(e,t,i){let n=F(e,t),a=R(i,t.action_data?.kwargs?.timeout_ms);if(n)await n.click({timeout:a});else throw new Error("No locator found for click action")}transpile(e){let t=Ne(e);if(!t)return['await agent.execAction("click", page, {});'];let i=R();return[`await ${t}.click({ timeout: ${i} });`]}};tu=fa.object({element_index:fa.number().int().describe("Index of the element to click (0-based). Return -1 if no element found"),timeout_ms:fa.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as hs}from"zod";function ps(e,t){e.register({name:"close_tab",description:"Close a browser tab by index. If no index is specified, closes the current tab.",schema:iu,async execute(i,n){let{index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l={action_description:s||`Close tab ${a}`,action_data:{action_name:"close_tab",kwargs:{page_id:a}}};return await t.execute(o,l,r),{success:!0,actionEntity:l,message:`Closed tab ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:(s||"Close tab")+" (failed)",action_data:{action_name:"close_tab",kwargs:{}},feedback:l.message}}}}})}var ms,iu,mi=v(()=>{"use strict";ms=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.page_id??n.kwargs.index;if(a===void 0&&(a=e.context().pages().indexOf(e)),typeof a=="number"){if(a===0)throw new Error("Cannot close the first tab (page_id 0). Skipping close_tab action.");i&&await i.closeTab(a)}else throw new Error("Missing page_id for close_tab action")}transpile(e){let t=e.action_data?.kwargs?.page_id;return t=t??e.action_data?.kwargs?.index,['await agent.execAction("close_tab", page, {',` action_data: { kwargs: { page_id: ${t} } },`,"});"]}},iu=hs.object({index:hs.number().int().nonnegative().optional().describe("Index of the tab to close (0-based). Defaults to current tab if not specified.")})});import{z as wa}from"zod";function fs(e,t){e.register({name:"done",description:"Mark the current task as complete. Use when you have finished all requested actions.",schema:nu,async execute(i,n){let{page:a,agentServices:o}=n;try{let r={action_description:"Task completed",action_data:{action_name:"done",kwargs:{}}};return await t.execute(a,r,o),{success:!0,actionEntity:r,message:"Task marked as complete"}}catch(r){return{success:!1,error:r.message,actionEntity:{action_description:"Task completed (failed)",action_data:{action_name:"done",kwargs:{}},feedback:r.message}}}}})}var gs,nu,pi=v(()=>{"use strict";gs=class{async execute(e,t){}transpile(e){return["// Done - no action needed"]}},nu=wa.object({success:wa.boolean().describe("Whether the task was completed successfully"),summary:wa.string().describe("Summary of what was accomplished or why it failed")})});var au,ou,Ve,gn=v(()=>{"use strict";au=["ai_action","ai_step","ai_assert","ai_extract","ai_wait_until","verify","assert"],ou=["js_code","function","wait","wait_for_download_complete","wait_for_page_ready","extract_email_content","extract_activation_code"],Ve=class{static isAiAction(e){let t=e.action_data?.action_name;return!t||(t==="verify"||t==="ai_assert"||t==="assert")&&e.action_data?.kwargs?.code?!1:au.includes(t)}static getAiStatement(e){let t=e.action_data?.action_name;if(!t)return null;let i=e.action_data?.kwargs||{};switch(t){case"ai_action":case"ai_step":return i.statement||null;case"verify":case"ai_assert":case"assert":return i.statement||e.action_description||null;case"ai_extract":let n=i.element_description,a=i.variable_name;return n&&a?`Extract ${n} and save to ${a}`:null;case"ai_wait_until":return i.condition||null;default:return null}}static canSelfHeal(e){let t=e.action_data?.action_name;return!t||(t==="verify"||t==="ai_assert"||t==="assert")&&e.action_data?.kwargs?.code?!1:!ou.includes(t)}}});var ya,ba,gi,va=v(()=>{"use strict";Bi();Gi();Ki();zi();Vi();Xi();Ji();Yi();nn();an();on();Ft();Wt();jt();Ut();Gt();Kt();Vt();Jt();Yt();qt();Zt();Qt();ei();ti();ii();ni();ai();oi();ri();si();li();ci();di();ui();hi();mi();pi();gn();G();ve();ya=class A{static registerAction(t,i){A.actions.set(t,i)}constructor(){A.initialized||(this.registerBuiltinActions(),A.initialized=!0)}registerBuiltinActions(){A.registerAction("go_to_url",new ma),A.registerAction("go_back",new Qr),A.registerAction("reload_page",new Wr),A.registerAction("close_tab",new ms),A.registerAction("switch_tab",new er),A.registerAction("click",new pn),A.registerAction("hover",new ra),A.registerAction("right_click",new da),A.registerAction("double_click",new ha),A.registerAction("click_by_coordinates",new Yo),A.registerAction("right_click_by_coordinates",new Ho),A.registerAction("double_click_by_coordinates",new Go),A.registerAction("drag_drop",new Ko),A.registerAction("input_text",new sa),A.registerAction("clear_input",new ls),A.registerAction("press",new la),A.registerAction("send_keys_on_element",new Wo),A.registerAction("scroll_on_element",new Sr),A.registerAction("scroll_to_text",new Ar),A.registerAction("scroll",new zt),A.registerAction("upload_file",new ar),A.registerAction("wait_for_download_complete",new dr),A.registerAction("get_dropdown_options",new qr),A.registerAction("select_dropdown_option",new Ir),A.registerAction("set_date_for_native_date_picker",new Pr),A.registerAction("verify",new mn),A.registerAction("ai_action",new Zo),A.registerAction("ai_extract",new os),A.registerAction("ai_step",new Jo),A.registerAction("ai_wait_until",new yr),A.registerAction("generate_2fa_code",new Vr),A.registerAction("wait",new sr),A.registerAction("wait_for_page_ready",new Fo),A.registerAction("save_variable",new vr),A.registerAction("js_code",new Bo),A.registerAction("js_action",new jo),A.registerAction("function",new zo),A.registerAction("done",new gs),A.registerAction("click_element",new pn),A.registerAction("click_element_by_index",new pn),A.registerAction("hover_element_by_index",new ra),A.registerAction("right_click_on_element",new da),A.registerAction("double_click_on_element",new ha),A.registerAction("scroll_down",new zt),A.registerAction("scroll_up",new zt),A.registerAction("scroll_element",new zt),A.registerAction("send_keys",new la),A.registerAction("open_tab",new ma),A.registerAction("fill",new sa),A.registerAction("ai_assert",new mn),A.registerAction("assert",new mn)}getAction(t){return A.actions.get(t)}hasAction(t){return A.actions.has(t)}getActionNames(){return Array.from(A.actions.keys())}async execute(t,i,n){if(!n)throw new Error("AgentServices not found");let a=i.action_data?.action_name;if(!a)throw new Error("Action name not found in action_data");let o=this.getAction(a);if(!o)throw new Error(`Unknown action: ${a}`);await o.execute(t,i,n)}transpile(t,i,n){let{sanitizeForComment:a}=(C(),Ln(Ti)),o=t.action_description||"",r=t.action_data?.action_name||"",s=this.getAction(r);if(!s)return[`// ${i}: Unknown action: ${r}`];let l=s.transpile(t,i);if(Ve.isAiAction(t))return[`// ${i}: ${a(o)}`,"page = agent.agentServices.validatePage(page);",...l];let c=JSON.stringify(o),d=l.map(p=>` ${p}`),u=Ve.canSelfHeal(t),m=n?JSON.stringify(n):"undefined";return[`// ${i}: ${a(o)}`,"page = agent.agentServices.validatePage(page);","await agent.step(page, async () => {",...d,`}, ${c}, '${i}', ${m}, ${u});`]}transpileUncachedAction(t,i,n=!1,a=!1,o){let{sanitizeForComment:r}=(C(),Ln(Ti));if(!t)return[`// ${i}: Skipping - no description`];let s=JSON.stringify(t);if(a){let l=o?`, { stmtUid: ${JSON.stringify(o)} }`:"";return[`// ${i}: ${r(t)}`,"page = agent.agentServices.validatePage(page);",`await agent.run(page, ${s}, '${i}'${l});`]}return[`// ${i}: ${r(t)}`,"page = agent.agentServices.validatePage(page);",`await agent.execute(page, ${s}, '${i}', ${n});`]}};ya.actions=new Map,ya.initialized=!1;ba=ya,gi=ba});var fn={};xt(fn,{ActionHandler:()=>ba,default:()=>gi});var wn=v(()=>{"use strict";va();Bi();Gi();Ki();zi();Vi();Xi();Ji();Yi();nn();an();on();Ft();Wt();jt();Ut();Gt();Kt();Vt();Jt();Yt();qt();Zt();Qt();ei();ti();ii();ni();ai();oi();ri();si();li();ci();lt();di();ui();hi();mi();pi();hn();Ht();Z();Be();je();mt();Ae();ut();B();te();Lt();gn();G();ve()});import{z as fi}from"zod";function yn(e,t,i){let n=()=>e.stepHistory.length===0?"":`**Recent Steps**:
4136
+ `)}return a?[`await agent.assert(page, ${JSON.stringify(a)}, ${o});`]:["// Skipping verify: missing statement or code"]}},Yd=ns.object({statement:ns.string().describe('The nature language statement to verify (e.g., "The login was successful")')})});import{z as pa}from"zod";function rs(e,t){e.register({name:"ai_extract",description:"Use AI to extract information from the page and save it to a variable. MCP-only tool.",schema:qd,async execute(i,n){let{element_description:a,variable_name:o}=i,{page:r,agentServices:s}=n;try{let l={action_description:`Extract ${a} to ${o}`,action_data:{action_name:"ai_extract",kwargs:{element_description:a,variable_name:o}}};return await t.execute(r,l,s),{success:!0,actionEntity:l,message:`Extracted ${a} to ${o}`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:`Extract ${a} (failed)`,action_data:{action_name:"ai_extract",kwargs:{element_description:a,variable_name:o}},feedback:l.message}}}},availability:{openai:!1,mcp:!0}})}var os,qd,di=b(()=>{"use strict";os=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.element_description,o=n.kwargs.variable_name;if(!a||!o)throw new Error("Missing element_description or variable_name for ai_extract");let r=`Extract ${a} and save to ${o}`,{executeStep:s}=await Promise.resolve().then(()=>(ut(),dt)),l=await s(r,e,i);if(l.status!=="success")throw new Error(l.error||"Extraction failed")}transpile(e,t){let i=e.action_data?.kwargs?.element_description,n=e.action_data?.kwargs?.variable_name;if(!i||!n)return["// Skipping ai_extract: missing element_description or variable_name"];let a=JSON.stringify(i),o=JSON.stringify(n);return[`await agent.extract(page, ${a}, ${o}, '${t||""}');`]}},qd=pa.object({element_description:pa.string().describe('Description of the element to extract (e.g., "the price of the product")'),variable_name:pa.string().describe("Name of the variable to store the extracted value")})});import{z as ga}from"zod";async function Zd(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function ss(e,t,i){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function cs(e,t){e.register({name:"clear_input",description:"Clear the contents of an input field, textarea, or other editable element.",schema:Qd,usesElementIndex:!0,async execute(i,n){let{element_index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Input element with index ${a} not found`,actionEntity:ss(s||`Clear element ${a}`,"clear_input",{index:a})};let c=s||`Clear element ${a}`,d=await Zd("clear_input",c,l,o);return await t.execute(o,d,r),{success:!0,actionEntity:d,message:`Cleared element ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:ss(`Clear element ${a}`,"clear_input",{index:a})}}}})}var ls,Qd,ui=b(()=>{"use strict";Z();G();P();ls=class{async execute(e,t,i){let n=F(e,t),a=R(i,t.action_data?.kwargs?.timeout_ms);if(n)await n.click({timeout:a}),await e.keyboard.press("ControlOrMeta+a"),await e.waitForTimeout(200),await e.keyboard.press("Backspace"),await e.waitForTimeout(200);else throw new Error("No locator found for clear_input action")}transpile(e){let t=[];return e.locator?t.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&t.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&t.push(`frame_path: ${JSON.stringify(e.frame_path)}`),t.length===0?['await agent.execAction("clear_input", page, {});']:['await agent.execAction("clear_input", page, {',...t.map(i=>` ${i},`),"});"]}};Qd=ga.object({element_index:ga.number().int().describe("Index of the input element to clear"),timeout_ms:ga.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as fa}from"zod";async function eu(e,t,i,n,a={}){return{...await j(n,i),action_description:t,action_data:{action_name:e,kwargs:{...a}}}}function ds(e,t,i){return{action_description:`${e} (failed - element not found)`,action_data:{action_name:t,kwargs:i},feedback:"Element not found in DOM"}}function us(e,t){e.register({name:"click",description:"Click an interactive element.",schema:tu,usesElementIndex:!0,async execute(i,n){let{element_index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l=await X(n,a);if(!l)return{success:!1,error:`Element with index ${a} not found.`,actionEntity:ds(`Click element ${a}`,"click",{index:a})};let c=s||`Click element ${a}`,d=await eu("click",c,l,o);return await t.execute(o,d,r),{success:!0,actionEntity:d,message:`Clicked element ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:ds(`Click element ${a}`,"click",{index:a})}}}})}var pn,tu,hi=b(()=>{"use strict";Z();G();P();pn=class{async execute(e,t,i){let n=F(e,t),a=R(i,t.action_data?.kwargs?.timeout_ms);if(n)await n.click({timeout:a});else throw new Error("No locator found for click action")}transpile(e){let t=Ne(e);if(!t)return['await agent.execAction("click", page, {});'];let i=R();return[`await ${t}.click({ timeout: ${i} });`]}};tu=fa.object({element_index:fa.number().int().describe("Index of the element to click (0-based). Return -1 if no element found"),timeout_ms:fa.number().optional().describe("Per-action timeout in ms. Overrides the default 5s action timeout.")})});import{z as hs}from"zod";function ps(e,t){e.register({name:"close_tab",description:"Close a browser tab by index. If no index is specified, closes the current tab.",schema:iu,async execute(i,n){let{index:a}=i,{page:o,agentServices:r,actionDescription:s}=n;try{let l={action_description:s||`Close tab ${a}`,action_data:{action_name:"close_tab",kwargs:{page_id:a}}};return await t.execute(o,l,r),{success:!0,actionEntity:l,message:`Closed tab ${a}`}}catch(l){return{success:!1,error:l.message,actionEntity:{action_description:(s||"Close tab")+" (failed)",action_data:{action_name:"close_tab",kwargs:{}},feedback:l.message}}}}})}var ms,iu,mi=b(()=>{"use strict";ms=class{async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=n.kwargs.page_id??n.kwargs.index;if(a===void 0&&(a=e.context().pages().indexOf(e)),typeof a=="number"){if(a===0)throw new Error("Cannot close the first tab (page_id 0). Skipping close_tab action.");i&&await i.closeTab(a)}else throw new Error("Missing page_id for close_tab action")}transpile(e){let t=e.action_data?.kwargs?.page_id;return t=t??e.action_data?.kwargs?.index,['await agent.execAction("close_tab", page, {',` action_data: { kwargs: { page_id: ${t} } },`,"});"]}},iu=hs.object({index:hs.number().int().nonnegative().optional().describe("Index of the tab to close (0-based). Defaults to current tab if not specified.")})});import{z as wa}from"zod";function fs(e,t){e.register({name:"done",description:"Mark the current task as complete. Use when you have finished all requested actions.",schema:nu,async execute(i,n){let{page:a,agentServices:o}=n;try{let r={action_description:"Task completed",action_data:{action_name:"done",kwargs:{}}};return await t.execute(a,r,o),{success:!0,actionEntity:r,message:"Task marked as complete"}}catch(r){return{success:!1,error:r.message,actionEntity:{action_description:"Task completed (failed)",action_data:{action_name:"done",kwargs:{}},feedback:r.message}}}}})}var gs,nu,pi=b(()=>{"use strict";gs=class{async execute(e,t){}transpile(e){return["// Done - no action needed"]}},nu=wa.object({success:wa.boolean().describe("Whether the task was completed successfully"),summary:wa.string().describe("Summary of what was accomplished or why it failed")})});var au,ou,Xe,gn=b(()=>{"use strict";au=["ai_action","ai_step","ai_assert","ai_extract","ai_wait_until","verify","assert"],ou=["js_code","function","wait","wait_for_download_complete","wait_for_page_ready","extract_email_content","extract_activation_code"],Xe=class{static isAiAction(e){let t=e.action_data?.action_name;return!t||(t==="verify"||t==="ai_assert"||t==="assert")&&e.action_data?.kwargs?.code?!1:au.includes(t)}static getAiStatement(e){let t=e.action_data?.action_name;if(!t)return null;let i=e.action_data?.kwargs||{};switch(t){case"ai_action":case"ai_step":return i.statement||null;case"verify":case"ai_assert":case"assert":return i.statement||e.action_description||null;case"ai_extract":let n=i.element_description,a=i.variable_name;return n&&a?`Extract ${n} and save to ${a}`:null;case"ai_wait_until":return i.condition||null;default:return null}}static canSelfHeal(e){let t=e.action_data?.action_name;return!t||(t==="verify"||t==="ai_assert"||t==="assert")&&e.action_data?.kwargs?.code?!1:!ou.includes(t)}}});var ya,ba,gi,va=b(()=>{"use strict";Bi();Gi();Ki();zi();Vi();Xi();Ji();Yi();nn();an();on();Ft();Wt();jt();Ut();Gt();Kt();Vt();Jt();Yt();qt();Zt();Qt();ei();ti();ii();ni();ai();oi();ri();si();li();ci();di();ui();hi();mi();pi();gn();G();ve();ya=class A{static registerAction(t,i){A.actions.set(t,i)}constructor(){A.initialized||(this.registerBuiltinActions(),A.initialized=!0)}registerBuiltinActions(){A.registerAction("go_to_url",new ma),A.registerAction("go_back",new Qr),A.registerAction("reload_page",new Wr),A.registerAction("close_tab",new ms),A.registerAction("switch_tab",new er),A.registerAction("click",new pn),A.registerAction("hover",new ra),A.registerAction("right_click",new da),A.registerAction("double_click",new ha),A.registerAction("click_by_coordinates",new Yo),A.registerAction("right_click_by_coordinates",new Ho),A.registerAction("double_click_by_coordinates",new Go),A.registerAction("drag_drop",new Ko),A.registerAction("input_text",new sa),A.registerAction("clear_input",new ls),A.registerAction("press",new la),A.registerAction("send_keys_on_element",new Wo),A.registerAction("scroll_on_element",new Sr),A.registerAction("scroll_to_text",new Ar),A.registerAction("scroll",new zt),A.registerAction("upload_file",new ar),A.registerAction("wait_for_download_complete",new dr),A.registerAction("get_dropdown_options",new qr),A.registerAction("select_dropdown_option",new Ir),A.registerAction("set_date_for_native_date_picker",new Pr),A.registerAction("verify",new mn),A.registerAction("ai_action",new Zo),A.registerAction("ai_extract",new os),A.registerAction("ai_step",new Jo),A.registerAction("ai_wait_until",new yr),A.registerAction("generate_2fa_code",new Vr),A.registerAction("wait",new sr),A.registerAction("wait_for_page_ready",new Fo),A.registerAction("save_variable",new vr),A.registerAction("js_code",new Bo),A.registerAction("js_action",new jo),A.registerAction("function",new zo),A.registerAction("done",new gs),A.registerAction("click_element",new pn),A.registerAction("click_element_by_index",new pn),A.registerAction("hover_element_by_index",new ra),A.registerAction("right_click_on_element",new da),A.registerAction("double_click_on_element",new ha),A.registerAction("scroll_down",new zt),A.registerAction("scroll_up",new zt),A.registerAction("scroll_element",new zt),A.registerAction("send_keys",new la),A.registerAction("open_tab",new ma),A.registerAction("fill",new sa),A.registerAction("ai_assert",new mn),A.registerAction("assert",new mn)}getAction(t){return A.actions.get(t)}hasAction(t){return A.actions.has(t)}getActionNames(){return Array.from(A.actions.keys())}async execute(t,i,n){if(!n)throw new Error("AgentServices not found");let a=i.action_data?.action_name;if(!a)throw new Error("Action name not found in action_data");let o=this.getAction(a);if(!o)throw new Error(`Unknown action: ${a}`);await o.execute(t,i,n)}transpile(t,i,n){let{sanitizeForComment:a}=(P(),Ln(Ti)),o=t.action_description||"",r=t.action_data?.action_name||"",s=this.getAction(r);if(!s)return[`// ${i}: Unknown action: ${r}`];let l=s.transpile(t,i);if(Xe.isAiAction(t))return[`// ${i}: ${a(o)}`,"page = agent.agentServices.validatePage(page);",...l];let c=JSON.stringify(o),d=l.map(p=>` ${p}`),u=Xe.canSelfHeal(t),m=n?JSON.stringify(n):"undefined";return[`// ${i}: ${a(o)}`,"page = agent.agentServices.validatePage(page);","await agent.step(page, async () => {",...d,`}, ${c}, '${i}', ${m}, ${u});`]}transpileUncachedAction(t,i,n=!1,a=!1,o){let{sanitizeForComment:r}=(P(),Ln(Ti));if(!t)return[`// ${i}: Skipping - no description`];let s=JSON.stringify(t);if(a){let l=o?`, { stmtUid: ${JSON.stringify(o)} }`:"";return[`// ${i}: ${r(t)}`,"page = agent.agentServices.validatePage(page);",`await agent.run(page, ${s}, '${i}'${l});`]}return[`// ${i}: ${r(t)}`,"page = agent.agentServices.validatePage(page);",`await agent.execute(page, ${s}, '${i}', ${n});`]}};ya.actions=new Map,ya.initialized=!1;ba=ya,gi=ba});var fn={};xt(fn,{ActionHandler:()=>ba,default:()=>gi});var wn=b(()=>{"use strict";va();Bi();Gi();Ki();zi();Vi();Xi();Ji();Yi();nn();an();on();Ft();Wt();jt();Ut();Gt();Kt();Vt();Jt();Yt();qt();Zt();Qt();ei();ti();ii();ni();ai();oi();ri();si();li();ci();ct();di();ui();hi();mi();pi();hn();Ht();Z();Ge();je();pt();Ae();ht();B();te();Lt();gn();G();ve()});import{z as fi}from"zod";function yn(e,t,i){let n=()=>e.stepHistory.length===0?"":`**Recent Steps**:
4115
4137
  ${e.stepHistory.slice(-3).map(l=>{let c=`${l.outcome.success?"\u2713":"\u2717"} Step ${l.stepNumber}: ${l.goal}`;if(l.actions.length>1)l.actions.forEach((d,u)=>{let m=d.action_description||"Unknown action";c+=`
4116
4138
  \u2192 Action ${u+1}: ${m}`});else if(l.actions.length===1){let d=l.actions[0]?.action_description||"Unknown action";c+=`
4117
4139
  \u2192 ${d}`}if(!l.outcome.success&&l.outcome.error){let d=l.outcome.error.substring(0,100);c+=`
@@ -4284,13 +4306,13 @@ ${m}
4284
4306
  **Current Goal Examples:**
4285
4307
  - "Add the product to the cart"
4286
4308
  - "Find more product listings and extract details from the next 5 items on the page"
4287
- ${p}`.trim()}var vn=v(()=>{"use strict";_e()});var xn,xa=v(()=>{"use strict";vn();ae();xn=class{constructor(e){this.messages=[],this.systemPrompt=e}getMessages(){return{system:this.systemPrompt,messages:[...this.messages]}}addStateMessage(e,t,i,n,a,o={}){let{executionHistory:r,placeholderData:s,sensitiveKeys:l,isFinalStep:c,finalStepWarning:d}=o,u=[],m=yn(a,e,t);if(u.push({type:"text",text:m}),u.push({type:"text",text:`## CURRENT PAGE STATE
4309
+ ${p}`.trim()}var vn=b(()=>{"use strict";_e()});var xn,xa=b(()=>{"use strict";vn();ae();xn=class{constructor(e){this.messages=[],this.systemPrompt=e}getMessages(){return{system:this.systemPrompt,messages:[...this.messages]}}addStateMessage(e,t,i,n,a,o={}){let{executionHistory:r,placeholderData:s,sensitiveKeys:l,isFinalStep:c,finalStepWarning:d}=o,u=[],m=yn(a,e,t);if(u.push({type:"text",text:m}),u.push({type:"text",text:`## CURRENT PAGE STATE
4288
4310
 
4289
4311
  **Interactive Elements**:
4290
4312
  ${i}`}),r&&Array.isArray(r)&&r.length>0){let p=r.map(([w,g],y)=>`${y+1}. ${w} \u2192 ${g}`);u.push({type:"text",text:`## EXECUTION HISTORY (from test)
4291
4313
 
4292
4314
  ${p.join(`
4293
- `)}`})}if(s&&Object.keys(s).length>0){T.log("Adding placeholder data description");let p=this.getPlaceholderDataDescription(s,l);T.log(`Placeholder data description: ${p}`),p&&u.push({type:"text",text:p})}c&&d&&u.push({type:"text",text:d}),u.push({type:"image",image:n}),T.log(`Adding state message: ${u.length} parts`),this.messages.push({role:"user",content:u})}addAssistantMessage(e){this.messages.push({role:"assistant",content:e})}addTextMessage(e,t){this.messages.push({role:e,content:t})}getMessageCount(){return this.messages.length}clear(){this.messages=[]}getRecentMessages(e){return this.messages.slice(-e)}updateSystemPrompt(e){this.systemPrompt=e}addAssistantMessageWithToolCalls(e){this.messages.push({role:"assistant",content:e.map(t=>({type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:t.input}))})}addToolResponseMessage(e,t,i){this.messages.push({role:"tool",content:[{type:"tool-result",toolCallId:t,toolName:i,output:typeof e=="string"?{type:"text",value:e}:{type:"json",value:e}}]})}getPlaceholderDataDescription(e,t){let i=[];for(let a of Object.keys(e))if(e[a])if(t?.has(a))i.push(` - ${a}: [SENSITIVE - value hidden]`);else{let o=e[a],r=typeof o=="string"?o:JSON.stringify(o);i.push(` - ${a}: "${r}"`)}if(i.length===0)return"";let n=`## DATA PLACEHOLDERS
4315
+ `)}`})}if(s&&Object.keys(s).length>0){T.log("Adding placeholder data description");let p=this.getPlaceholderDataDescription(s,l);T.log(`Placeholder data description: ${p}`),p&&u.push({type:"text",text:p})}c&&d&&u.push({type:"text",text:d}),u.push({type:"file",mediaType:"image/png",data:n}),T.log(`Adding state message: ${u.length} parts`),this.messages.push({role:"user",content:u})}addAssistantMessage(e){this.messages.push({role:"assistant",content:e})}addTextMessage(e,t){this.messages.push({role:e,content:t})}getMessageCount(){return this.messages.length}clear(){this.messages=[]}getRecentMessages(e){return this.messages.slice(-e)}updateSystemPrompt(e){this.systemPrompt=e}addAssistantMessageWithToolCalls(e){this.messages.push({role:"assistant",content:e.map(t=>({type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:t.input}))})}addToolResponseMessage(e,t,i){this.messages.push({role:"tool",content:[{type:"tool-result",toolCallId:t,toolName:i,output:typeof e=="string"?{type:"text",value:e}:{type:"json",value:e}}]})}getPlaceholderDataDescription(e,t){let i=[];for(let a of Object.keys(e))if(e[a])if(t?.has(a))i.push(` - ${a}: [SENSITIVE - value hidden]`);else{let o=e[a],r=typeof o=="string"?o:JSON.stringify(o);i.push(` - ${a}: "${r}"`)}if(i.length===0)return"";let n=`## DATA PLACEHOLDERS
4294
4316
 
4295
4317
  `;return n+=`The following placeholders are available for use in your actions:
4296
4318
  `,n+=`${i.join(`
@@ -4300,19 +4322,19 @@ ${p.join(`
4300
4322
  `,n+=`- Use the EXACT placeholder name as shown above
4301
4323
  `,n+=`- Do NOT use the actual value directly in the action
4302
4324
  `,n+=`- The values shown are for context only to help you understand what data is available
4303
- `,n+='- In action descriptions, describe what the placeholder represents in natural language (e.g., "Type the first user name" instead of "Type {{ firstUserName }}")',n}}});import{generateText as su}from"ai";async function bs(e,t,i={}){let n=Date.now();if(i.maxSteps!==void 0&&i.maxSteps<=0)throw new Error(`maxSteps must be >= 1, got ${i.maxSteps}`);let a=i.maxSteps??15,o=3,r=t.agentServices.getModel(),s=[r,...t.agentServices.getFallbackModels().filter(x=>x!==r)],l=0,c=r,d=t.domService||new He(t.agentServices.getDomServiceOptions()),u={...t,domService:d};T.init(),T.section("Task Execution Started"),T.log(`Task: ${e}`),T.log(`Max steps: ${a}`),T.log(`Model: ${s.length>1?s.join(" \u2192 "):r}`);let m={currentStep:0,maxSteps:a,consecutiveFailures:0,maxFailures:o,lastFailReason:null,stepHistory:[],memory:[],lastGoal:null,lastEvaluation:null},p=[],w=bn(i.customPrompt),g=new xn(w);T.log(`System prompt length: ${w.length} chars`);let y=!1,h="",b=[];try{for(i.onEvent?.({type:"start",task:e,maxSteps:a});m.currentStep<a;){if(i.abortSignal?.aborted)throw new Error("Task aborted by user");m.currentStep++;let x=Date.now();T.section(`Step ${m.currentStep}/${a}`),T.log(`URL: ${u.page.url()}`),i.onEvent?.({type:"step_start",step:m.currentStep});try{T.log("Waiting for page to stabilize..."),await ht(u.page),T.log("Page stabilized")}catch{T.log("Page stabilization timed out, continuing anyway")}let S;try{T.log("Preparing context (DOM + screenshot)...");let H=u.agentServices.getInteractiveClassNames(),K=u.agentServices.getIframeFallbackDomains();S=await ys(u.page,u.domService,H,K),T.log("Context prepared")}catch(H){if(H.message.includes("Execution context was destroyed")){T.log("Page navigating, waiting for load..."),await ht(u.page);let K=u.agentServices.getInteractiveClassNames(),Q=u.agentServices.getIframeFallbackDomains();S=await ys(u.page,u.domService,K,Q)}else throw T.error("Error preparing context",H),H}g.addStateMessage(e,S.currentUrl,S.domTree,S.screenshotBase64,m,{isFinalStep:m.currentStep===a-1,placeholderData:t.variables,sensitiveKeys:t.sensitiveKeys});let E=await cu(g,s,l,i,S.screenshotBase64);if(typeof E.modelIndexUsed=="number"&&(l=E.modelIndexUsed,c=s[E.modelIndexUsed]??c),E.tokenUsages&&E.tokenUsages.length>0&&p.push(...E.tokenUsages),!E.stepOutput){if(T.error("Failed to get valid LLM response"),m.consecutiveFailures++,m.consecutiveFailures>=o){h="Reached the maximum allowed consecutive failures. Most recent error: Unable to get a valid response from the language model.";break}continue}let $=E.stepOutput;mu(m.currentStep,a,$);let O=await uu($,u,S.domState,m.currentStep,i.onEvent,S.screenshotBase64,E.debugInfo);b.push(...O.actionEntities);let D=hu(m.currentStep,$,O,m,x,E.debugInfo,E.tokenUsages),I=Date.now()-x;if(i.onEvent?.({type:"step_complete",step:m.currentStep,duration:I}),m.consecutiveFailures>=o){T.error(`Too many consecutive failures (${m.consecutiveFailures}), stopping`),h=`Reached the maximum allowed consecutive failures. Most recent error: ${m.lastFailReason}`;break}if(O.doneResult){y=O.doneResult.success,h=O.doneResult.summary;break}if(O.completesInstruction){y=!0,h="Instruction completed";break}}return m.currentStep>=a&&!y&&(h="Reached the maximum allowed steps."),i.onEvent?.({type:"complete",totalSteps:m.currentStep,duration:Date.now()-n}),T.log(`Build success result: summary=${h}, completed=${y}, actions=${b.length}, tokens=${p.length}`),pu(m,b,y,h,n,p,c)}catch(x){let S=x.message;return T.error(`Task execution failed: ${S}`,x),i.onEvent?.({type:"error",error:S,recoverable:!1}),gu(m,S,n,p,c)}}async function ys(e,t,i,n){let{domState:a,screenshotBase64:o}=await t.getClickableElementsWithScreenshot(e,{interactiveClassNames:i,playwrightFrameFallbackDomains:n}),r=a.elementTree.clickableElementsToString();return{currentUrl:e.url(),domTree:r,screenshotBase64:o,domState:a}}function lu(e){return e.map(t=>({role:t.role,content:Array.isArray(t.content)?t.content.map(i=>{if(i.type==="image"){let n=i.image,a=typeof n=="string"?n:"";return{type:"image",file:a.startsWith("data:")?a:`data:image/png;base64,${a}`}}return{type:"text",text:i.text}}):t.content}))}async function cu(e,t,i,n,a){let{messages:o}=e.getMessages(),r=0;for(let d of o)Array.isArray(d.content)&&(r+=d.content.filter(u=>u.type==="image").length);let s=go(),l=3,c=Math.max(0,Math.min(i,t.length-1));for(let d=c;d<t.length;d++){let u=t[d],m=d===t.length-1,p=we(u,r),w=Se(u,n.temperature);try{for(let g=0;g<l;g++){let{system:y,messages:h}=e.getMessages(),b={model:fe(u),system:y,messages:h,providerOptions:p};w!==void 0&&(b.temperature=w);let x=new AbortController,S=s>0?setTimeout(()=>x.abort(),s):void 0,E=fo(n.abortSignal,s>0?x.signal:void 0);E&&(b.abortSignal=E);let $;try{let J=Date.now();d===c?T.log(`Calling LLM (${u})...`):T.log(`Calling LLM (${u}) [fallback ${d}/${t.length-1}]...`),$=await su(b);let he=Date.now()-J;T.llmCall(u,he,$.usage)}finally{S&&clearTimeout(S)}let O=$,D=O.usage,I=O.reasoningText;I&&(T.thinking(I),n.onEvent?.({type:"thinking",text:I})),e.addAssistantMessage($.text);let H={systemPrompt:y,userPrompt:lu(h),rawLlmResponse:$.text,reasoningContent:I,screenshotWithSom:a},K=[],Q=ke(D,u);Q&&K.push(Q);let U=du($.text);if(!U){if(g<l-1){T.log(`Attempt ${g+1}/${l}: Failed to parse response, retrying...`),e.addTextMessage("user","Your response was not valid JSON. Please respond with a properly formatted JSON object according to the expected format.");continue}return T.error("All parsing attempts failed"),{stepOutput:null,debugInfo:H,tokenUsages:K,modelIndexUsed:d}}return{stepOutput:U,debugInfo:H,tokenUsages:K,modelIndexUsed:d}}}catch(g){if(n.abortSignal?.aborted)throw g;if(!m&&Wn(g)){T.log(`Model "${u}" failed (${g.message}); falling back to "${t[d+1]}"`);continue}throw T.error("All LLM call attempts failed",g),g}}return{stepOutput:null}}function du(e){let t=e.trim();t.startsWith("```json")?t=t.replace(/^```json\s*/,"").replace(/\s*```\s*$/,""):t.startsWith("```")&&(t=t.replace(/^```\s*/,"").replace(/\s*```\s*$/,""));try{let i=JSON.parse(t);if(!i.current_goal)return T.error("Missing required field: current_goal"),null;if(!i.actions||!Array.isArray(i.actions)||i.actions.length===0)return T.error("Missing required field: actions (must be non-empty array)"),null;for(let n of i.actions){if(!n.action_name)return T.error("Action missing required field: action_name"),null;if(!n.description)return T.error("Action missing required field: description"),null}return i}catch(i){return T.error(`Failed to parse LLM JSON response: ${t.substring(0,500)}`),T.error(`Parse error: ${i.message}`),null}}async function uu(e,t,i,n,a,o,r){let s=[],l=!0,c=null;T.log(`Using pre-captured DOM state with ${i.selectorMap.size} elements for ${e.actions.length} action(s)`);let d=null,u={...t,domState:i},m=o;for(let p of e.actions){if(p.action_name==="done"){d={success:p.kwargs.success??!0,summary:p.kwargs.summary||p.kwargs.text||"Task completed"};break}let w={},g=p.kwargs?.element_index??p.kwargs?.index;if(typeof g=="number"){let h=i.selectorMap.get(g);h&&(w=await j(t.page,h))}let y={...w,action_description:p.description,action_data:{action_name:p.action_name,kwargs:p.kwargs}};try{let h=await V.execute(p.action_name,p.kwargs,u);p.action_name==="perform_accurate_operation"&&(y=h.actionEntity);let b=await u.agentServices.getCurrentPage();if(b&&(u.page=b,t.page=u.page),h?.success===!1){l=!1,T.log("Action failed, stopping execution of remaining actions in this step"),c=h.error||"Action execution failed";break}s.push(y),a?.({type:"action",action_entity:y,step:n,debugInfo:r})}catch(h){l=!1,c=h.message,T.error(`Action execution failed: ${h.message}`);break}}return{allSuccess:l,failReason:c,actionEntities:s,doneResult:d,completesInstruction:e.completes_instruction??!1}}function hu(e,t,i,n,a,o,r){let s={stepNumber:e,thinking:t.thinking,evaluation:t.evaluation_previous_goal,memory:t.memory,goal:t.current_goal,actions:i.actionEntities,timestamp:a,duration:Date.now()-a,outcome:{success:i.allSuccess},debugInfo:o,tokenUsages:r};if(n.lastGoal=t.current_goal,t.evaluation_previous_goal&&(n.lastEvaluation=t.evaluation_previous_goal),t.memory&&t.memory.trim()){let l=t.memory.trim();n.memory.includes(l)||(n.memory.push(l),n.memory.length>10&&(n.memory=n.memory.slice(-10)))}return i.allSuccess?(n.consecutiveFailures=0,n.lastFailReason=null):(n.consecutiveFailures++,n.lastFailReason=i.failReason),n.stepHistory.push(s),s}function mu(e,t,i){if(T.log(`Step ${e}/${t}`),i.thinking&&T.log(`Thinking: ${i.thinking}`),i.evaluation_previous_goal&&T.log(`Evaluation: ${i.evaluation_previous_goal}`),i.memory&&T.log(`Memory: ${i.memory}`),T.log(`Goal: ${i.current_goal}`),i.actions.length===1){let n=i.actions[0];T.log(`Action: ${n.action_name}(${JSON.stringify(n.kwargs)}) - ${n.description}`)}else T.log(`Actions (${i.actions.length}):`),i.actions.forEach((n,a)=>{T.log(` ${a+1}. ${n.action_name}(${JSON.stringify(n.kwargs)}) - ${n.description}`)})}function pu(e,t,i,n,a,o,r){let s=o.reduce((d,u)=>d+u.prompt_tokens,0),l=o.reduce((d,u)=>d+u.completion_tokens,0),c=o.reduce((d,u)=>d+u.total_tokens,0);return{success:!0,completed:i,summary:n,trajectory:{steps:e.currentStep,actions:t,stepRecords:e.stepHistory},metadata:{totalSteps:e.currentStep,totalDuration:Date.now()-a,model:r,successfulSteps:e.stepHistory.filter(d=>d.outcome.success).length,failedSteps:e.stepHistory.filter(d=>!d.outcome.success).length,promptTokens:s,completionTokens:l,totalTokens:c,tokenUsages:o}}}function gu(e,t,i,n,a){let o=n.reduce((l,c)=>l+c.prompt_tokens,0),r=n.reduce((l,c)=>l+c.completion_tokens,0),s=n.reduce((l,c)=>l+c.total_tokens,0);return{success:!1,completed:!1,error:t,trajectory:{steps:e.currentStep,actions:[],stepRecords:e.stepHistory},metadata:{totalSteps:e.currentStep,totalDuration:Date.now()-i,model:a,successfulSteps:e.stepHistory.filter(l=>l.outcome.success).length,failedSteps:e.stepHistory.filter(l=>!l.outcome.success).length,promptTokens:o,completionTokens:r,totalTokens:s,tokenUsages:n}}}var vs=v(()=>{"use strict";xa();vn();De();_e();ze();ae();Fe();Ee();Z();Ae()});var xs={};xt(xs,{TaskMessageManager:()=>xn,formatFinalStepWarning:()=>ws,formatTaskContext:()=>yn,getBrowserTaskJSONPrompt:()=>bn,runTaskLoop:()=>bs});var _s=v(()=>{"use strict";vs();xa();vn();De();_e();qi();ze();It();st();Ct();Pt();Nt();ae();Fe();Ee();$t();it();Mt();Le();tt();Ke();Z();Be();Ae();ut();B();te();Lt();G();ve()});async function Dt(e,t){try{if(!e.action_data)return{success:!1,error:"Action entity missing action_data"};let{action_name:i,kwargs:n}=e.action_data;if(V.has(i)){let a=await V.execute(i,n,t),o=a?.success!==!1,r=a?.error||a?.message;return{success:o,error:o?void 0:r}}else{let{page:a,agentServices:o}=t;return await(await fu()).execute(a,e,o),{success:!0,error:void 0}}}catch(i){return{success:!1,error:i.message}}}async function fu(){if(_n)return _n;let e=await Promise.resolve().then(()=>(wn(),fn));return _n=new e.default,_n}async function Zi(e,t,i,n={},a){let o=a||{page:t,agentServices:i,domService:new He(i.getDomServiceOptions()),executionHistory:n.executionHistory,variables:n.variables,sensitiveKeys:n.sensitiveKeys},r=i.replaceVariables(e),s=await Kn(r,o,n);return s.status==="error"?{status:"error",completed:s.goalAccomplished||!1,actionEntities:[],explanation:s.reasoning,error:s.error,debugInfo:s.debugInfo}:{status:"success",completed:s.goalAccomplished||!1,actionEntities:s.actionEntity?[s.actionEntity]:[],explanation:s.reasoning,debugInfo:s.debugInfo}}async function Qi(e,t,i,n={},a){let o=a||{page:t,agentServices:i,domService:new He(i.getDomServiceOptions()),executionHistory:n.executionHistory,variables:n.variables,sensitiveKeys:n.sensitiveKeys},r=i.replaceVariables(e),s=await Kn(r,o,n);if(s.status==="error"||!s.actionEntity)return{status:"error",completed:s.goalAccomplished||!1,actionEntities:[],explanation:s.reasoning,error:s.error||"No action generated",debugInfo:s.debugInfo};let{actionEntity:l,reasoning:c,goalAccomplished:d,debugInfo:u}=s,m=await Dt(l,o);return m.success?(c&&i.addNote(c),{status:"success",completed:d||!1,actionEntities:[l],explanation:c,debugInfo:u}):{status:"error",completed:!1,actionEntities:[l],error:m.error||"Action execution failed",debugInfo:u}}async function en(e,t,i,n={}){let a={page:t,agentServices:i,domService:new He(i.getDomServiceOptions()),executionHistory:n.executionHistory,variables:n.variables,sensitiveKeys:n.sensitiveKeys},o=i.replaceVariables(e);return n.useCleanScreenshotForAssertion??(n.useCleanScreenshotForAssertion=i.isUseCleanScreenshotForAssertion()),Io(o,a,n)}async function tn(e,t,i,n,a={}){let{runTaskLoop:o}=await Promise.resolve().then(()=>(_s(),xs)),r=n?l=>{n(l)}:void 0,s=await o(e,{page:t,agentServices:i,domService:void 0,executionHistory:a.executionHistory,variables:a.variables,sensitiveKeys:a.sensitiveKeys},{maxSteps:a.maxSteps,onEvent:r,abortSignal:a.abortSignal});return{status:s.success?"success":"error",completed:s.completed,actionEntities:s.trajectory.actions,explanation:s.summary,error:s.error,tokenUsages:s.metadata.tokenUsages}}var _n,Rt=v(()=>{"use strict";ji();_e();ze();_n=null});var ka=v(()=>{"use strict";ae();Ae()});import{z as k}from"zod";var Bs,Ea,Gs,gt,Ks,zs,Vs,re,Xs,Sn,Ta,Aa=v(()=>{"use strict";Bs=k.enum(["JS_CODE","AI_MODE"]),Ea=k.object({type:Bs,expression:k.string()}),Gs=k.enum(["DRAFT","STEP","ACTION","IF_ELSE","WHILE_LOOP"]),gt=k.object({uid:k.string(),type:Gs,comment:k.string().optional()}),Ks=k.object({action_data:k.object({action_name:k.string(),kwargs:k.record(k.any()).optional(),args:k.array(k.any()).optional()}),action_description:k.string().optional(),url:k.string().optional(),xpath:k.string().nullable().optional(),locator:k.string().nullable().optional(),css_selector:k.string().nullable().optional(),unique_selector:k.string().nullable().optional(),element_index:k.number().nullable().optional(),frame_path:k.array(k.any()).optional(),artifacts:k.record(k.any()).optional(),feedback:k.string().optional(),original_browser_use_action:k.any().optional()}).passthrough(),zs=gt.extend({type:k.literal("DRAFT"),description:k.string()}),Vs=gt.extend({type:k.literal("ACTION"),description:k.string(),action_entity:Ks.optional(),locator:k.string().optional(),use_pure_vision:k.boolean().optional()}),re=k.lazy(()=>k.union([zs,Vs,gt.extend({type:k.literal("STEP"),description:k.string().optional().default(""),statements:k.array(re),reference_id:k.number().optional(),template_path:k.string().optional(),template_params:k.record(k.string()).optional()}),gt.extend({type:k.literal("IF_ELSE"),description:k.string().optional(),condition:Ea,then:k.array(re),else:k.array(re).optional()}),gt.extend({type:k.literal("WHILE_LOOP"),description:k.string().optional(),condition:Ea,body:k.array(re),timeout_ms:k.number().optional()})])),Xs=k.object({name:k.string(),statements:k.array(re),teardown:k.array(re).optional(),skip:k.union([k.boolean(),k.string()]).optional(),timeout:k.number().optional(),fail:k.union([k.boolean(),k.string()]).optional(),only:k.boolean().optional(),slow:k.boolean().optional()}),Sn=k.object({tests:k.array(Xs).min(1),beforeAll:k.array(re).optional(),afterAll:k.array(re).optional(),beforeEach:k.array(re).optional(),afterEach:k.array(re).optional()}),Ta=k.object({comment:k.string().optional(),version:k.string().optional(),goal:k.string().optional(),url:k.string().optional(),baseURL:k.string().optional(),final_feedback:k.string().optional(),completed:k.boolean().optional(),success:k.boolean().optional(),statements:k.array(re).optional(),teardown:k.array(re).optional(),last_modified_at:k.string().optional(),testGroup:Sn.optional()}).refine(e=>e.testGroup!==void 0?e.goal===void 0&&(e.statements===void 0||e.statements.length===0):e.goal!==void 0,{message:"TestFlow must have either goal/statements (single test) or testGroup (suite), not both"})});import{stringify as dT,parse as Zs,parseAllDocuments as uT,parseDocument as Uu,Document as Qs,isMap as wt,isSeq as se}from"yaml";import{v4 as ce}from"uuid";function En(e,t){let i={...t?.test_case_id!==void 0?{test_case_id:t.test_case_id}:{},...t?.name?{name:t.name}:{},...t?.tags&&t.tags.length>0?{tags:t.tags}:{},...t?.skip!==void 0?{skip:t.skip}:{},...t?.fail!==void 0?{fail:t.fail}:{},...t?.only?{only:t.only}:{},...t?.slow?{slow:t.slow}:{},goal:e.goal??"",url:e.url,base_url:e.baseURL,...t?.timeout!==void 0?{timeout:t.timeout}:{},...t?.settings&&Object.keys(t.settings).length>0?{settings:t.settings}:{},...t?.use&&Object.keys(t.use).length>0?{use:t.use}:{},...t?.beforeEach&&t.beforeEach.length>0?{beforeEach:t.beforeEach}:{},...t?.afterEach&&t.afterEach.length>0?{afterEach:t.afterEach}:{},...t?.parameters&&t.parameters.length>0?{parameters:t.parameters}:{},statements:(e.statements??[]).map(de)};return e.final_feedback&&(i.final_feedback=e.final_feedback),e.teardown&&e.teardown.length>0&&(i.teardown=e.teardown.map(de)),i}function Ma(e,t){if(e.testGroup)return tl(e,t);let i=En(e,t),n=new Qs(i),a=n.contents?.get("tags",!0);return se(a)&&(a.flow=!0),e.comment&&(n.commentBefore=e.comment),Js(n,e.statements??[]),e.teardown&&Js(n,e.teardown,"teardown"),n.toString(el)}function Js(e,t,i="statements"){let n=e.contents;if(!n||!wt(n))return;let a=n.get(i,!0);se(a)&&bi(a,t)}function bi(e,t){for(let i=0;i<Math.min(e.items.length,t.length);i++){let n=t[i],a=e.items[i];if(i>0&&(a.spaceBefore=!0),n.comment&&(i===0?e.commentBefore=n.comment:a.commentBefore=n.comment),wt(a)){let o=a;if(n.type==="STEP"){let r=o.get("statements",!0);se(r)&&bi(r,n.statements)}else if(n.type==="IF_ELSE"){let r=o.get("THEN",!0);se(r)&&bi(r,n.then);let s=o.get("ELSE",!0);se(s)&&n.else&&bi(s,n.else)}else if(n.type==="WHILE_LOOP"){let r=o.get("DO",!0);se(r)&&bi(r,n.body)}}}}function tl(e,t){let i=e.testGroup;if(!i)throw new Error("suiteToYaml requires a TestFlow with testGroup");let n={};t?.test_case_id!==void 0&&(n.test_case_id=t.test_case_id),t?.name&&(n.name=t.name),t?.tags&&t.tags.length>0&&(n.tags=t.tags),t?.use&&Object.keys(t.use).length>0&&(n.use=t.use),t?.settings&&Object.keys(t.settings).length>0&&(n.settings=t.settings);let a={};e.baseURL&&(a.base_url=e.baseURL),i.beforeAll&&i.beforeAll.length>0&&(a.beforeAll=i.beforeAll.map(de)),i.beforeEach&&i.beforeEach.length>0&&(a.beforeEach=i.beforeEach.map(de)),i.afterEach&&i.afterEach.length>0&&(a.afterEach=i.afterEach.map(de)),i.afterAll&&i.afterAll.length>0&&(a.afterAll=i.afterAll.map(de)),a.tests=i.tests.map(s=>{let l={name:s.name};return s.skip!==void 0&&(l.skip=s.skip),s.timeout!==void 0&&(l.timeout=s.timeout),s.fail!==void 0&&(l.fail=s.fail),s.only!==void 0&&(l.only=s.only),s.slow!==void 0&&(l.slow=s.slow),l.statements=s.statements.map(de),s.teardown&&s.teardown.length>0&&(l.teardown=s.teardown.map(de)),l}),n.suite=a;let o=new Qs(n),r=o.contents?.get("tags",!0);return se(r)&&(r.flow=!0),o.toString(el)}function de(e){switch(e.type){case"DRAFT":return Bu(e);case"ACTION":return Gu(e);case"STEP":return Ku(e);case"IF_ELSE":return zu(e);case"WHILE_LOOP":return Vu(e)}}function Bu(e){return{intent:e.description}}function Gu(e){let t=e.action_entity?.action_data?.action_name??e.action_entity?.action?.action_name,i=e.action_entity?.action_data?.kwargs??e.action_entity?.action?.kwargs;if(t==="verify"){let s=i?.statement;if(typeof s=="string"&&!e.action_entity?.locator&&!e.action_entity?.xpath){let l=i?.code;return typeof l=="string"&&l.trim()?{VERIFY:s,js:l}:{VERIFY:s}}}if(t==="go_to_url"){let s=i?.url;if(typeof s=="string"&&!e.action_entity?.locator&&!e.action_entity?.xpath){let l={URL:s};return i?.new_tab===!0&&(l.new_tab=!0),typeof i?.timeout_seconds=="number"&&(l.timeout_seconds=i.timeout_seconds),l}}if(t==="js_action"){let s=i?.code;if(typeof s=="string"&&s.trim()&&e.description)return{description:e.description,js:s}}if(t==="ai_wait_until"){let s=i?.condition;if(typeof s=="string"){let l=typeof i?.js=="string"&&i.js.trim()?i.js:void 0,c={};if(l)c.WAIT_UNTIL=s,c.js=l;else{let d=i?.condition_type==="JS_CODE"?"JS_CODE":"AI_MODE";c.WAIT_UNTIL=Ia({type:d,expression:s})}return typeof i?.timeout_seconds=="number"&&i.timeout_seconds!==60&&(c.timeout_seconds=i.timeout_seconds),c}}if(t==="wait"){let s=i?.seconds,c={WAIT:e.description||`Wait ${s}s`};return typeof s=="number"&&(c.seconds=s),c}if(t==="js_code"){let s=i?.code;if(typeof s=="string"&&!e.action_entity?.locator&&!e.action_entity?.xpath)return{description:e.description||"Code block",js:s}}if(!e.action_entity)return{intent:e.description};let n=e.action_entity.action_data??e.action_entity.action;if(!n)return{intent:e.description};let a={intent:e.description,action:n.action_name},o=e.locator??e.action_entity.locator;o&&(a.locator=o);let r=e.action_entity.xpath;if(r&&(a.xpath=r),e.use_pure_vision&&(a.use_pure_vision=!0),n.kwargs&&Object.keys(n.kwargs).length>0)for(let[s,l]of Object.entries(n.kwargs))s!=="uid"&&(s==="statement"&&(t==="ai_action"||t==="ai_step")||(a[s]=l));return n.args&&n.args.length>0&&(a.args=n.args),a}function Ku(e){if(e.template_path){let i={template:e.template_path};return e.template_params&&Object.keys(e.template_params).length>0&&(i.params=e.template_params),i}let t={STEP:e.description,statements:e.statements.map(de)};return e.reference_id!==void 0&&(t.reference_id=e.reference_id),t}function zu(e){let t={IF:Ia(e.condition),THEN:e.then.map(de)};return e.else&&e.else.length>0&&(t.ELSE=e.else.map(de)),t}function Vu(e){let t={WHILE:Ia(e.condition),DO:e.body.map(de)};return e.timeout_ms!==void 0&&(t.timeout_ms=e.timeout_ms),t}function Ia(e){return e.type==="JS_CODE"?`js:${e.expression}`:e.expression}function Ca(e){try{let t=Zs(e);if(!t||typeof t!="object")return{};let i={};return typeof t.test_case_id=="number"&&Number.isFinite(t.test_case_id)&&(i.test_case_id=t.test_case_id),typeof t.template_id=="number"&&Number.isFinite(t.template_id)&&(i.template_id=t.template_id),typeof t.name=="string"&&t.name.trim()&&(i.name=t.name.trim()),typeof t.timeout=="number"&&Number.isFinite(t.timeout)&&(i.timeout=t.timeout),t.settings&&typeof t.settings=="object"&&!Array.isArray(t.settings)&&(i.settings=t.settings),t.use&&typeof t.use=="object"&&!Array.isArray(t.use)&&(i.use=t.use),Array.isArray(t.tags)&&t.tags.every(n=>typeof n=="string")&&(i.tags=t.tags),(typeof t.skip=="boolean"||typeof t.skip=="string")&&(i.skip=t.skip),(typeof t.fail=="boolean"||typeof t.fail=="string")&&(i.fail=t.fail),t.only===!0&&(i.only=!0),t.slow===!0&&(i.slow=!0),Array.isArray(t.beforeEach)&&t.beforeEach.length>0&&(i.beforeEach=t.beforeEach),Array.isArray(t.afterEach)&&t.afterEach.length>0&&(i.afterEach=t.afterEach),Array.isArray(t.parameters)&&t.parameters.length>0&&(i.parameters=t.parameters),i}catch{return{}}}function $a(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map($a);let t=e,i=Object.keys(t);if(i.length===1){let a=i[0];if(a.startsWith("{ ")&&a.endsWith(" }")&&t[a]===null)return`{{${a.slice(2,-2)}}}`}let n={};for(let[a,o]of Object.entries(t))n[a]=$a(o);return n}function Me(e){if(e.length>Ys)throw new Error(`YAML input too large (${e.length} bytes, max ${Ys})`);let t=$a(Zs(e));if(!t||typeof t!="object")throw new Error("Invalid YAML: expected an object at root level");if(t.suite)return Xu(t);let i={version:"1.3.0",goal:t.goal,url:t.url,baseURL:t.base_url,statements:ue(t.statements??[])};t.final_feedback&&(i.final_feedback=t.final_feedback),t.teardown&&Array.isArray(t.teardown)&&(i.teardown=ue(t.teardown));let n=Ta.safeParse(i);if(!n.success)throw new Error(`Invalid TestFlow after YAML conversion: ${JSON.stringify(n.error.errors)}`);let a=n.data;return Tn(e,a),a}function Xu(e){let t=e.suite;if(!t||typeof t!="object")throw new Error("Invalid suite: expected an object");let i=t.tests;if(!Array.isArray(i)||i.length===0)throw new Error('Suite must have a non-empty "tests" array');let a={tests:i.map(s=>{if(!s.name)throw new Error('Each test in a suite must have a "name" field');if(!Array.isArray(s.statements)||s.statements.length===0)throw new Error(`Suite test "${s.name}" must have a non-empty "statements" array`);let l={name:s.name,statements:ue(s.statements)};return Array.isArray(s.teardown)&&s.teardown.length>0&&(l.teardown=ue(s.teardown)),s.skip!==void 0&&(l.skip=s.skip),typeof s.timeout=="number"&&(l.timeout=s.timeout),s.fail!==void 0&&(l.fail=s.fail),s.only===!0&&(l.only=!0),s.slow===!0&&(l.slow=!0),l})};Array.isArray(t.beforeAll)&&t.beforeAll.length>0&&(a.beforeAll=ue(t.beforeAll)),Array.isArray(t.afterAll)&&t.afterAll.length>0&&(a.afterAll=ue(t.afterAll)),Array.isArray(t.beforeEach)&&t.beforeEach.length>0&&(a.beforeEach=ue(t.beforeEach)),Array.isArray(t.afterEach)&&t.afterEach.length>0&&(a.afterEach=ue(t.afterEach));let o=Sn.safeParse(a);if(!o.success)throw new Error(`Invalid TestGroup: ${JSON.stringify(o.error.errors)}`);return{version:"1.3.0",baseURL:t.base_url||void 0,testGroup:o.data}}function ue(e){if(!Array.isArray(e))throw new Error("Expected an array of statements");return e.map(Ju)}function Ju(e){if(typeof e=="string")throw new Error(`Plain string statements are not supported. Use an object with a "desc" key instead. Example: { "desc": "${e}" }`);if(typeof e!="object"||e===null)throw new Error(`Invalid statement: expected object, got ${typeof e}`);let t=e;if("IF"in t)return Yu(t);if("WHILE"in t)return qu(t);if("STEP"in t)return Zu(t);if("VERIFY"in t){let i=t.VERIFY,n={statement:typeof i=="string"?i:String(i)};return typeof t.js=="string"&&(n.code=t.js),{uid:ce(),type:"ACTION",description:String(i),action_entity:{action_description:String(i),action_data:{action_name:"verify",kwargs:n}}}}if("URL"in t){let i=t.URL,n=t.new_tab===!0?!0:void 0,a=typeof t.timeout_seconds=="number"?t.timeout_seconds:void 0,o={url:typeof i=="string"?i:String(i)};return n&&(o.new_tab=!0),a!==void 0&&(o.timeout_seconds=a),{uid:ce(),type:"ACTION",description:`Navigate to ${i}`,action_entity:{action_description:`Navigate to ${i}`,action_data:{action_name:"go_to_url",kwargs:o}}}}if("WAIT_UNTIL"in t){let i=typeof t.WAIT_UNTIL=="string"?t.WAIT_UNTIL:String(t.WAIT_UNTIL),n=Pa(i),a=typeof t.timeout_seconds=="number"?t.timeout_seconds:60;if(typeof t.js=="string"){if(n.type==="JS_CODE")throw new Error('WAIT_UNTIL cannot combine a "js:"-prefixed condition with a sibling "js:" key \u2014 put the intent in WAIT_UNTIL and the expression in js:');return{uid:ce(),type:"ACTION",description:`Wait until: ${i}`,action_entity:{action_description:`Wait until: ${i}`,action_data:{action_name:"ai_wait_until",kwargs:{condition:i,condition_type:"JS_CODE",js:t.js,timeout_seconds:a}}}}}return{uid:ce(),type:"ACTION",description:`Wait until: ${n.expression}`,action_entity:{action_description:`Wait until: ${n.expression}`,action_data:{action_name:"ai_wait_until",kwargs:{condition:n.expression,condition_type:n.type,timeout_seconds:a}}}}}if("WAIT"in t){let i=t.WAIT,n=typeof t.seconds=="number"?t.seconds:3;return{uid:ce(),type:"ACTION",description:typeof i=="string"?i:`Wait ${n}s`,action_entity:{action_description:typeof i=="string"?i:`Wait ${n}s`,action_data:{action_name:"wait",kwargs:{seconds:n}}}}}if("CODE"in t){let i=t.CODE;if(i==null)throw new Error('CODE statement has no code. Use "CODE: |" followed by indented code on the next line.');let n=typeof t.description=="string"?t.description:"Code block";return{uid:ce(),type:"ACTION",description:n,action_entity:{action_description:n,action_data:{action_name:"js_code",kwargs:{code:typeof i=="string"?i:String(i)}}}}}if("js"in t&&!("VERIFY"in t)&&!("action"in t)){if("intent"in t||"desc"in t)throw new Error("A `js:` statement uses `description:`, not `intent:`. Raw JS does not self-heal \u2014 use `description: + js:` for code, or express it as a structured action (`intent:` + `action:`/`locator:`) to keep self-healing.");let i=typeof t.description=="string"&&t.description.trim()!==""?t.description:"Code block",n=t.js;return{uid:ce(),type:"ACTION",description:i,action_entity:{action_description:i,action_data:{action_name:"js_code",kwargs:{code:typeof n=="string"?n:String(n)}}}}}if("call"in t&&typeof t.call=="string"){let{call:i,...n}=t;return qs({...n,action:"function",functionName:i})}if("action"in t)return qs(t);if("intent"in t&&typeof t.intent=="string"||"desc"in t&&typeof t.desc=="string")return{uid:ce(),type:"DRAFT",description:typeof t.intent=="string"?t.intent:t.desc};throw new Error(`Cannot infer statement type from object: ${JSON.stringify(t)}`)}function Pa(e){if(typeof e!="string")throw new Error(`Condition must be a string, got ${typeof e}`);return e.startsWith("js:")?{type:"JS_CODE",expression:e.slice(3)}:{type:"AI_MODE",expression:e}}function Yu(e){let t=Pa(e.IF),i=e.THEN;if(!Array.isArray(i))throw new Error("IF_ELSE requires a THEN array");let n={uid:ce(),type:"IF_ELSE",condition:t,then:ue(i)};return"ELSE"in e&&Array.isArray(e.ELSE)&&(n.else=ue(e.ELSE)),n}function qu(e){let t=Pa(e.WHILE),i=e.DO;if(!Array.isArray(i))throw new Error("WHILE_LOOP requires a DO array");let n={uid:ce(),type:"WHILE_LOOP",condition:t,body:ue(i)};return typeof e.timeout_ms=="number"&&(n.timeout_ms=e.timeout_ms),n}function Zu(e){let t=typeof e.STEP=="string"?e.STEP:"";if(!Array.isArray(e.statements))throw new Error("STEP requires a statements array");let i={uid:ce(),type:"STEP",description:t,statements:ue(e.statements)};if(typeof e.reference_id=="number"&&(i.reference_id=e.reference_id),typeof e.template_path=="string"&&(i.template_path=e.template_path),e.template_params&&typeof e.template_params=="object"&&!Array.isArray(e.template_params)){let n=e.template_params,a={};for(let[o,r]of Object.entries(n))a[o]=String(r);i.template_params=a}return i}function qs(e){let t=typeof e.action=="string"?e.action:String(e.action),i=typeof e.intent=="string"?e.intent:typeof e.desc=="string"?e.desc:"",n=typeof e.locator=="string"?e.locator:void 0,a=typeof e.xpath=="string"?e.xpath:void 0,o=typeof e.use_pure_vision=="boolean"?e.use_pure_vision:void 0,r={};for(let[c,d]of Object.entries(e))Qu.has(c)||(r[c]=d);t==="verify"&&typeof r.js=="string"&&(r.code=r.js,delete r.js),(t==="ai_action"||t==="ai_step")&&(r.statement===void 0&&(r.statement=i),o&&(r.use_pure_vision=!0));let s={action_description:i,action_data:{action_name:t,kwargs:Object.keys(r).length>0?r:{}}};n&&(s.locator=n),a&&(s.xpath=a);let l={uid:ce(),type:"ACTION",description:i,action_entity:s};return o&&(l.use_pure_vision=!0),l}function Tn(e,t){let i;try{i=Uu(e)}catch{return}let n=i.contents;if(!n||!wt(n))return;if(i.commentBefore)t.comment=i.commentBefore;else{let l=n.items?.[0];l?.key&&l.key.commentBefore&&(t.comment=l.key.commentBefore)}let a=n,o=a.get("statements",!0);se(o)&&t.statements&&ft(o,t.statements);let r=a.get("teardown",!0);se(r)&&t.teardown&&ft(r,t.teardown)}function ft(e,t){e.commentBefore&&t.length>0&&(t[0].comment=e.commentBefore);for(let i=0;i<Math.min(e.items.length,t.length);i++){let n=e.items[i];n.commentBefore&&!(i===0&&e.commentBefore)&&(t[i].comment=n.commentBefore);let a=t[i];if(a.type==="STEP"&&wt(n)){let o=n.get("statements",!0);se(o)&&ft(o,a.statements)}else if(a.type==="IF_ELSE"&&wt(n)){let o=n.get("THEN",!0);se(o)&&ft(o,a.then);let r=n.get("ELSE",!0);se(r)&&a.else&&ft(r,a.else)}else if(a.type==="WHILE_LOOP"&&wt(n)){let o=n.get("DO",!0);se(o)&&ft(o,a.body)}}}var el,Ys,Qu,An=v(()=>{"use strict";Aa();el={lineWidth:120,defaultKeyType:"PLAIN",defaultStringType:"PLAIN"};Ys=1024*1024;Qu=new Set(["action","intent","desc","locator","xpath","use_pure_vision"])});import{parse as fT,stringify as wT}from"yaml";var il=v(()=>{"use strict";An()});var $n=v(()=>{"use strict"});var nl=v(()=>{"use strict";An();$n()});var al=v(()=>{"use strict";$n()});var Xe,ol=v(()=>{"use strict";Xe=(e=>(e.DRAFT="DRAFT",e.STEP="STEP",e.ACTION="ACTION",e.IF_ELSE="IF_ELSE",e.WHILE_LOOP="WHILE_LOOP",e))(Xe||{})});import{v4 as AT}from"uuid";var rl=v(()=>{"use strict"});var Mn=v(()=>{"use strict"});var sl=v(()=>{"use strict";Mn()});var ll=v(()=>{"use strict";Mn()});var cl,ah,dl,ul,vi,oh,rh,hl=v(()=>{"use strict";cl=112,ah=1080-cl,dl={"Blackberry PlayBook":{name:"Blackberry PlayBook",userAgent:"Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/26.0 Safari/536.2+",screen:{width:600,height:1024},viewport:{width:600,height:1024},deviceScaleFactor:1,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"BlackBerry Z30":{name:"BlackBerry Z30",userAgent:"Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/26.0 Mobile Safari/537.10+",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy Note 3":{name:"Galaxy Note 3",userAgent:"Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.0 Mobile Safari/534.30",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy Note II":{name:"Galaxy Note II",userAgent:"Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.0 Mobile Safari/534.30",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy S III":{name:"Galaxy S III",userAgent:"Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.0 Mobile Safari/534.30",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy S5":{name:"Galaxy S5",userAgent:"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy S8":{name:"Galaxy S8",userAgent:"Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:740},viewport:{width:360,height:740},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy S9+":{name:"Galaxy S9+",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:320,height:658},viewport:{width:320,height:658},deviceScaleFactor:4.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy S24":{name:"Galaxy S24",userAgent:"Mozilla/5.0 (Linux; Android 14; SM-S921U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:780},viewport:{width:360,height:780},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy A55":{name:"Galaxy A55",userAgent:"Mozilla/5.0 (Linux; Android 14; SM-A556B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:480,height:1040},viewport:{width:480,height:1040},deviceScaleFactor:2.25,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy Tab S4":{name:"Galaxy Tab S4",userAgent:"Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:712,height:1138},viewport:{width:712,height:1138},deviceScaleFactor:2.25,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy Tab S9":{name:"Galaxy Tab S9",userAgent:"Mozilla/5.0 (Linux; Android 14; SM-X710) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:640,height:1024},viewport:{width:640,height:1024},deviceScaleFactor:2.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"iPad (gen 5)":{name:"iPad (gen 5)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:768,height:1024},viewport:{width:768,height:1024},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad (gen 6)":{name:"iPad (gen 6)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:768,height:1024},viewport:{width:768,height:1024},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad (gen 7)":{name:"iPad (gen 7)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:810,height:1080},viewport:{width:810,height:1080},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad (gen 11)":{name:"iPad (gen 11)",userAgent:"Mozilla/5.0 (iPad; CPU OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/19E241 Safari/604.1",screen:{width:656,height:944},viewport:{width:656,height:944},deviceScaleFactor:2.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad Mini":{name:"iPad Mini",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:768,height:1024},viewport:{width:768,height:1024},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad Pro 11":{name:"iPad Pro 11",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:834,height:1194},viewport:{width:834,height:1194},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 6":{name:"iPhone 6",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 6 Plus":{name:"iPhone 6 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:414,height:736},viewport:{width:414,height:736},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 7":{name:"iPhone 7",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 7 Plus":{name:"iPhone 7 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:414,height:736},viewport:{width:414,height:736},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 8":{name:"iPhone 8",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 8 Plus":{name:"iPhone 8 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:414,height:736},viewport:{width:414,height:736},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone SE":{name:"iPhone SE",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.0 Mobile/14E304 Safari/602.1",screen:{width:320,height:568},viewport:{width:320,height:568},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone SE (3rd gen)":{name:"iPhone SE (3rd gen)",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.0 Mobile/19E241 Safari/602.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone X":{name:"iPhone X",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:812},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone XR":{name:"iPhone XR",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:414,height:896},viewport:{width:414,height:896},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 11":{name:"iPhone 11",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:414,height:896},viewport:{width:414,height:715},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 11 Pro":{name:"iPhone 11 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:635},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 11 Pro Max":{name:"iPhone 11 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:414,height:896},viewport:{width:414,height:715},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12":{name:"iPhone 12",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12 Pro":{name:"iPhone 12 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12 Pro Max":{name:"iPhone 12 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:428,height:926},viewport:{width:428,height:746},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12 Mini":{name:"iPhone 12 Mini",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:629},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13":{name:"iPhone 13",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13 Pro":{name:"iPhone 13 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13 Pro Max":{name:"iPhone 13 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:428,height:926},viewport:{width:428,height:746},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13 Mini":{name:"iPhone 13 Mini",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:629},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14":{name:"iPhone 14",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14 Plus":{name:"iPhone 14 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:428,height:926},viewport:{width:428,height:746},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14 Pro":{name:"iPhone 14 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:393,height:852},viewport:{width:393,height:660},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14 Pro Max":{name:"iPhone 14 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:430,height:932},viewport:{width:430,height:740},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15":{name:"iPhone 15",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:393,height:852},viewport:{width:393,height:659},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15 Plus":{name:"iPhone 15 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:430,height:932},viewport:{width:430,height:739},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15 Pro":{name:"iPhone 15 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:393,height:852},viewport:{width:393,height:659},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15 Pro Max":{name:"iPhone 15 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:430,height:932},viewport:{width:430,height:739},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Kindle Fire HDX":{name:"Kindle Fire HDX",userAgent:"Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",screen:{width:800,height:1280},viewport:{width:800,height:1280},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"LG Optimus L70":{name:"LG Optimus L70",userAgent:"Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:384,height:640},viewport:{width:384,height:640},deviceScaleFactor:1.25,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Microsoft Lumia 550":{name:"Microsoft Lumia 550",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36 Edge/14.14263",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Microsoft Lumia 950":{name:"Microsoft Lumia 950",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36 Edge/14.14263",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:4,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 10":{name:"Nexus 10",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:800,height:1280},viewport:{width:800,height:1280},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 4":{name:"Nexus 4",userAgent:"Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:384,height:640},viewport:{width:384,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 5":{name:"Nexus 5",userAgent:"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 5X":{name:"Nexus 5X",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:732},viewport:{width:412,height:732},deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 6":{name:"Nexus 6",userAgent:"Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:732},viewport:{width:412,height:732},deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 6P":{name:"Nexus 6P",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:732},viewport:{width:412,height:732},deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 7":{name:"Nexus 7",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:600,height:960},viewport:{width:600,height:960},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nokia Lumia 520":{name:"Nokia Lumia 520",userAgent:"Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)",screen:{width:320,height:533},viewport:{width:320,height:533},deviceScaleFactor:1.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nokia N9":{name:"Nokia N9",userAgent:"Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13",screen:{width:480,height:854},viewport:{width:480,height:854},deviceScaleFactor:1,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Pixel 2":{name:"Pixel 2",userAgent:"Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:411,height:731},viewport:{width:411,height:731},deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 2 XL":{name:"Pixel 2 XL",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:411,height:823},viewport:{width:411,height:823},deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 3":{name:"Pixel 3",userAgent:"Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:393,height:786},viewport:{width:393,height:786},deviceScaleFactor:2.75,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 4":{name:"Pixel 4",userAgent:"Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:353,height:745},viewport:{width:353,height:745},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 4a (5G)":{name:"Pixel 4a (5G)",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:892},viewport:{width:412,height:765},deviceScaleFactor:2.63,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 5":{name:"Pixel 5",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:393,height:851},viewport:{width:393,height:727},deviceScaleFactor:2.75,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 7":{name:"Pixel 7",userAgent:"Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:915},viewport:{width:412,height:839},deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Moto G4":{name:"Moto G4",userAgent:"Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Desktop Chrome HiDPI":{name:"Desktop Chrome HiDPI",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Edge HiDPI":{name:"Desktop Edge HiDPI",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Firefox HiDPI":{name:"Desktop Firefox HiDPI",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:142.0.1) Gecko/20100101 Firefox/142.0.1",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"firefox"},"Desktop Safari":{name:"Desktop Safari",userAgent:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"webkit"},"Desktop Chrome":{name:"Desktop Chrome",displayName:"Playwright Chromium",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1920,height:1080},viewport:{width:1920,height:1080},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Chrome Medium Resolution":{name:"Desktop Chrome Medium Resolution",displayName:"Playwright Chromium",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1280,height:720},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Chrome (Branded)":{name:"Desktop Chrome (Branded)",displayName:"Google Chrome",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1920,height:1080},viewport:{width:1920,height:1080},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"chrome"},"Desktop Chrome Medium Resolution (Branded)":{name:"Desktop Chrome Medium Resolution (Branded)",displayName:"Google Chrome",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1280,height:720},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"chrome"},"Desktop Edge":{name:"Desktop Edge",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1920,height:1080},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Edge (Branded)":{name:"Desktop Edge (Branded)",displayName:"Microsoft Edge",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1920,height:1080},viewport:{width:1920,height:1080},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"msedge"},"Desktop Edge Medium Resolution (Branded)":{name:"Desktop Edge Medium Resolution (Branded)",displayName:"Microsoft Edge",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1280,height:720},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"msedge"},"Desktop Firefox":{name:"Desktop Firefox",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:142.0.1) Gecko/20100101 Firefox/142.0.1",screen:{width:1920,height:1080},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"firefox"}},ul={desktop:["Desktop Chrome","Desktop Chrome Medium Resolution","Desktop Chrome (Branded)","Desktop Chrome Medium Resolution (Branded)","Desktop Edge (Branded)","Desktop Edge Medium Resolution (Branded)","Desktop Safari"],mobile:["iPhone 15 Pro Max","iPhone 15 Pro","iPhone 15 Plus","iPhone 15","iPhone 14 Pro Max","iPhone 14 Pro","iPhone 14 Plus","iPhone 14","iPhone 13 Pro Max","iPhone 13 Pro","iPhone 13","iPhone 13 Mini","iPhone 12 Pro Max","iPhone 12 Pro","iPhone 12","iPhone 12 Mini","iPhone 11 Pro Max","iPhone 11 Pro","iPhone 11","iPhone XR","iPhone X","iPhone SE (3rd gen)","iPhone SE","iPhone 8 Plus","iPhone 8","iPhone 7 Plus","iPhone 7","iPhone 6 Plus","iPhone 6","Galaxy S24","Galaxy A55","Galaxy S9+","Galaxy S8","Galaxy S5","Galaxy Note 3","Galaxy Note II","Galaxy S III","Pixel 7","Pixel 5","Pixel 4a (5G)","Pixel 4","Pixel 3","Pixel 2 XL","Pixel 2","Nexus 6P","Nexus 6","Nexus 5X","Nexus 5","Nexus 4","Moto G4","LG Optimus L70","Microsoft Lumia 950","Microsoft Lumia 550","Nokia Lumia 520","Nokia N9","BlackBerry Z30"]},vi=(e,t=!1)=>{let i=["chromium"];return t&&i.push("webkit"),ul[e].map(n=>dl[n]).filter(n=>n.defaultBrowserType&&i.includes(n.defaultBrowserType))},oh={desktop:{label:"Desktop",type:"desktop",devices:vi("desktop")},mobile:{label:"Mobile Web",type:"mobile",devices:vi("mobile")}},rh={desktop:{label:"Desktop",type:"desktop",devices:vi("desktop",!0)},mobile:{label:"Mobile Web",type:"mobile",devices:vi("mobile",!0)}}});var ml=v(()=>{"use strict"});var pl=v(()=>{"use strict"});var gl=v(()=>{"use strict"});var fl=v(()=>{"use strict"});var wl=v(()=>{"use strict"});function bl(e){if(e!==null&&typeof e=="object"){for(let t of Object.values(e))bl(t);Object.freeze(e)}return e}var sh,yl,lh,Oa,Na=v(()=>{"use strict";sh=Object.freeze(["lite","standard","pro"]),yl=1,lh=Object.freeze(["WEB_AGENT_MODEL","WEB_AGENT_FALLBACK_MODELS","COMPUTER_USE_MODEL"]),Oa=bl({version:yl,defaultTier:"lite",tiers:{lite:{webagent:{primary:"google:gemini-3-flash-preview",fallbacks:["anthropic:claude-haiku-4-5","openai:gpt-5.6-luna"]}},standard:{webagent:{primary:"google:gemini-3.5-flash",fallbacks:["anthropic:claude-sonnet-5","openai:gpt-5.6-terra"]}},pro:{webagent:{primary:"anthropic:claude-opus-4-8",fallbacks:["openai:gpt-5.6-sol","anthropic:claude-opus-4-7"]}}},computerUse:{primary:"google:gemini-3-flash-preview",fallbacks:[]}})});var hh,vl=v(()=>{"use strict";Na();hh=Object.freeze([...Oa.tiers.standard.webagent.fallbacks])});var xl=v(()=>{"use strict"});var yt=v(()=>{"use strict";il();nl();An();Aa();al();$n();ol();rl();sl();ll();Mn();hl();ml();pl();gl();fl();wl();vl();Na();xl()});import{stringify as n$}from"yaml";import La from"node:path";import{createHash as wh}from"crypto";import{parse as yh,stringify as Al}from"yaml";import{readFileSync as bh,existsSync as vh}from"fs";import{resolve as Da,dirname as xh}from"path";import{parse as kl,stringify as _h}from"yaml";function gh(e){let t=e.frame_path;return!t||t.length===0?"page":`page.frameLocator('${t[0]}')`}function fh(e){let t=e.xpath;return typeof t=="string"&&t.trim()?!t.startsWith("xpath=")&&!t.startsWith("/")&&!t.startsWith("//")?`xpath=//${t}`:t.startsWith("xpath=")?t:`xpath=${t}`:null}function Tl(e){let t=gh(e),i=e.locator;if(typeof i=="string"&&i.trim())return i=i.trim(),i.endsWith("first()")?`${t}.${i}`:`${t}.${i}.first()`;let n=fh(e);if(n){let a=JSON.stringify(n);return`${t}.locator(${a}).first()`}return null}function M(e,t){ne.set(e,t)}function Je(e,t,i=[]){let n=[...i];return t.locator?n.push(`locator: ${JSON.stringify(t.locator)}`):t.xpath&&n.push(`xpath: ${JSON.stringify(t.xpath)}`),t.frame_path&&t.frame_path.length>0&&n.push(`frame_path: ${JSON.stringify(t.frame_path)}`),n.length===0?[`await agent.execAction("${e}", page, {});`]:[`await agent.execAction("${e}", page, {`,...n.map(a=>` ${a},`),"});"]}function Ra(e,t){let i=t.action_data?.kwargs||{},n=[];return typeof i.relative_x=="number"&&typeof i.relative_y=="number"?(n.push(`action_data: { kwargs: { relative_x: ${i.relative_x}, relative_y: ${i.relative_y} } }`),t.locator?n.push(`locator: ${JSON.stringify(t.locator)}`):t.xpath&&n.push(`xpath: ${JSON.stringify(t.xpath)}`),t.frame_path&&t.frame_path.length>0&&n.push(`frame_path: ${JSON.stringify(t.frame_path)}`)):typeof i.x=="number"&&typeof i.y=="number"&&n.push(`action_data: { kwargs: { x: ${i.x}, y: ${i.y} } }`),[`await agent.execAction("${e}", page, {`,...n.map(a=>` ${a},`),"});"]}function _l(e){let t=e.functionName;if(!t)return null;let i=Array.isArray(e.args)?e.args.map(String):Array.isArray(e.parameterValues)?e.parameterValues.map(String):[];if(i.length===0)return`await ${t}()`;let n=["page","testContext","request","agent"],a=["undefined","null","true","false"],o=i.map(r=>n.includes(r)||a.includes(r)||/^-?\d+(\.\d+)?$/.test(r)?r:r.startsWith("$")?`agent.agentServices.readVariable('${r.substring(1)}')`:`"${r}"`);return`await ${t}(${o.join(", ")})`}function $l(e,t,i){let n={expandingPaths:new Set([Da(t)]),depth:0,referencedPaths:new Set,basePath:i},a={...e};Array.isArray(a.statements)&&(a.statements=Ue(a.statements,t,n)),Array.isArray(a.teardown)&&(a.teardown=Ue(a.teardown,t,n));for(let o of["beforeAll","afterAll","beforeEach","afterEach"])Array.isArray(a[o])&&(a[o]=Ue(a[o],t,n));return{doc:a,referencedTemplatePaths:Array.from(n.referencedPaths)}}function Ue(e,t,i){let n=[];for(let a of e)if(kh(a)){let o=Sh(a,t,i);n.push(o)}else n.push(Eh(a,t,i));return n}function kh(e){return typeof e=="object"&&e!==null&&typeof e.template=="string"}function Sh(e,t,i){if(i.depth>=Sl)throw new Error(`Template expansion exceeded maximum depth of ${Sl}. Check for deeply nested or circular template references.`);let n=Da(xh(t),e.template),a=!vh(n)&&i.basePath?Da(i.basePath,e.template):n;if(i.expandingPaths.has(a))throw new Error(`Circular template reference detected: ${a} is already being expanded. Stack: ${Array.from(i.expandingPaths).join(" \u2192 ")} \u2192 ${a}`);i.referencedPaths.add(a);let o;try{o=bh(a,"utf-8")}catch(w){throw new Error(`Failed to read template file: ${a} (referenced from ${t}): ${w.message}`)}let r=kl(o);if(!r||typeof r!="object")throw new Error(`Invalid template file: ${a} \u2014 expected a YAML object`);let s=r.params||[],l=e.params||{};for(let w of s)if(!(w in l))throw new Error(`Template ${e.template} requires param "${w}" but it was not provided. Required params: [${s.join(", ")}]`);let c=r.statements;if(!Array.isArray(c))throw new Error(`Template ${e.template} must have a "statements" array`);if(Object.keys(l).length>0){let g=_h(c);for(let[y,h]of Object.entries(l))g=g.split(`<<${y}>>`).join(String(h));c=kl(g)}let d={expandingPaths:new Set([...i.expandingPaths,a]),depth:i.depth+1,referencedPaths:i.referencedPaths},u=Ue(c,a,d),p={STEP:r.name||e.template.replace(/\.yaml$/,"").split("/").pop()||e.template,template_path:e.template,statements:u};return Object.keys(l).length>0&&(p.template_params=l),p}function Eh(e,t,i){if(typeof e!="object"||e===null)return e;let n={...e};return Array.isArray(n.statements)&&(n.statements=Ue(n.statements,t,i)),Array.isArray(n.THEN)&&(n.THEN=Ue(n.THEN,t,i)),Array.isArray(n.ELSE)&&(n.ELSE=Ue(n.ELSE,t,i)),Array.isArray(n.DO)&&(n.DO=Ue(n.DO,t,i)),n}function Il(e,t,i){let n=yh(e),a=n?.name,o=n?.tags,r=n?.use;if(n&&(n.name!==void 0||n.tags!==void 0||n.use!==void 0)&&(delete n.name,delete n.tags,delete n.use),n?.suite){if(n.goal||n.statements)throw new Ml('YAML file cannot have both "suite" and top-level "goal"/"statements". Use either suite format or single-test format.');return Ah(n,a,o,r,t,i)}return Th(n,a,o,r,t,i)}function Th(e,t,i,n,a,o){let r=e?.beforeEach,s=e?.afterEach,l=Cl(e?.parameters),c=e?.timeout,d=e?.skip,u=e?.fail,m=e?.only,p=e?.slow;if(e&&(delete e.beforeEach,delete e.afterEach,delete e.parameters,delete e.timeout,delete e.skip,delete e.fail,delete e.only,delete e.slow),e?.url)throw new Ml(`The "url" field is not supported in local YAML tests. Use "base_url: ${e.url}" and add "- URL: /" as the first statement instead.`);e&&!e.goal&&t&&(e.goal=t);let w=[];if(a&&e&&typeof e=="object"){let h=$l(e,a,o);e=h.doc,w=h.referencedTemplatePaths}let g=Al(e),y=Me(g);return a&&(bt(y.statements??[],a,"main"),y.teardown&&bt(y.teardown,a,"teardown")),{testFlow:y,name:t,tags:i,use:n,beforeEach:r,afterEach:s,parameters:l,timeout:c,skip:d,fail:u,only:m,slow:p,referencedTemplatePaths:w}}function Ah(e,t,i,n,a,o){let r=e.suite;if(!Array.isArray(r.tests)||r.tests.length===0)throw new Error('Suite must have a non-empty "tests" array.');let s=r.beforeAll,l=r.afterAll,c=r.beforeEach,d=r.afterEach,u=[],m=r.tests.map(g=>{if(!g.name)throw new Error('Each test in a suite must have a "name" field.');if(!Array.isArray(g.statements)||g.statements.length===0)throw new Error(`Suite test "${g.name}" must have a non-empty "statements" array.`);let y={goal:g.name,statements:g.statements};g.teardown&&(y.teardown=g.teardown);let h=[],b=y;if(a&&typeof y=="object"){let $=$l(y,a,o);b=$.doc,h=$.referencedTemplatePaths,u.push(...h)}let x=Al(b),S=Me(x),E=Cl(g.parameters);return{testFlow:S,name:g.name,tags:Array.isArray(g.tags)?g.tags:void 0,parameters:E,timeout:g.timeout,skip:g.skip,fail:g.fail,only:g.only,slow:g.slow}}),p=r.base_url,w=p?{...n,baseURL:p}:n;return{suite:{beforeAll:s,afterAll:l,beforeEach:c,afterEach:d,tests:m},name:t,tags:i,use:w,referencedTemplatePaths:u}}function Cl(e){if(!(!Array.isArray(e)||e.length===0))return e.map((t,i)=>{if(!t.name)throw new Error(`Parameter set at index ${i} must have a "name" field.`);if(!t.values||typeof t.values!="object")throw new Error(`Parameter set "${t.name}" must have a "values" object.`);return{name:t.name,values:t.values}})}function bt(e,t,i){for(let n=0;n<e.length;n++){let a=e[n],o=`${i}.${n}`,r=a.description||"";if(a.uid=$h(t,o,r),a.type===Xe.STEP)bt(a.statements,t,o);else if(a.type===Xe.IF_ELSE){let s=a;bt(s.then,t,`${o}.then`),s.else&&bt(s.else,t,`${o}.else`)}else a.type===Xe.WHILE_LOOP&&bt(a.body,t,`${o}.body`)}}function $h(e,t,i){let n=wh("sha256").update(`${e}:${t}:${i}`).digest("hex");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20,32)}`}var El,ne,Sl,Ml,Pl=v(()=>{"use strict";yt();yt();yt();yt();El=5e3;ne=new Map;M("click",e=>{let t=Tl(e);if(!t)return['await agent.execAction("click", page, {});'];let i=e.action_data?.kwargs?.timeout_ms??El;return[`await ${t}.click({ timeout: ${i} });`]});M("click_element",ne.get("click"));M("click_element_by_index",ne.get("click"));M("double_click",e=>Je("double_click",e));M("double_click_on_element",ne.get("double_click"));M("right_click",e=>Je("right_click",e));M("right_click_on_element",ne.get("right_click"));M("hover",e=>Je("hover",e));M("hover_element_by_index",ne.get("hover"));M("input_text",e=>{let t=e.action_data?.kwargs?.text??e.action_data?.kwargs?.value??"";return Je("input_text",e,[`action_data: { kwargs: { text: ${JSON.stringify(t)} } }`])});M("fill",ne.get("input_text"));M("clear_input",e=>Je("clear_input",e));M("press",e=>{let t=e.action_data?.kwargs?.keys;return[`await page.keyboard.press(${JSON.stringify(t)});`]});M("send_keys",ne.get("press"));M("send_keys_on_element",e=>{let t=Tl(e),i=e.action_data?.kwargs?.keys||"";if(!t)return['await agent.execAction("send_keys_on_element", page, {',` action_data: { kwargs: { keys: ${JSON.stringify(i)} } },`,"});"];let n=e.action_data?.kwargs?.timeout_ms??El;return[`await ${t}.press(${JSON.stringify(i)}, { timeout: ${n} });`]});M("select_dropdown_option",e=>{let t=e.action_data?.kwargs?.text||e.action_data?.kwargs?.option||"";return Je("select_dropdown_option",e,[`action_data: { kwargs: { text: ${JSON.stringify(t)} } }`])});M("scroll",e=>{let t=e.action_data?.kwargs?.down??!0;return[`await page.evaluate('window.scrollBy(0, window.innerHeight * ${(e.action_data?.kwargs?.num_pages??1)*(t?1:-1)})');`]});M("scroll_down",ne.get("scroll"));M("scroll_up",ne.get("scroll"));M("scroll_element",ne.get("scroll"));M("scroll_to_text",e=>{let t=e.action_data?.kwargs?.text||"";return[`await page.getByText(${JSON.stringify(t)}, { exact: false }).first().scrollIntoViewIfNeeded();`]});M("scroll_on_element",e=>Je("scroll_on_element",e,[`action_data: { kwargs: ${JSON.stringify(e.action_data?.kwargs||{})} }`]));M("go_to_url",e=>{let t=e.action_data?.kwargs?.url||"";return e.action_data?.kwargs?.new_tab===!0?['await agent.execAction("go_to_url", page, {',` action_data: { kwargs: { url: ${JSON.stringify(t)}, new_tab: true } },`,"});"]:['await agent.execAction("go_to_url", page, {',` action_data: { kwargs: { url: ${JSON.stringify(t)} } },`,"});"]});M("open_tab",ne.get("go_to_url"));M("go_back",()=>['await agent.execAction("go_back", page, {});']);M("reload_page",()=>['await agent.execAction("reload_page", page, {});']);M("wait",e=>[`await page.waitForTimeout(${(e.action_data?.kwargs?.seconds||1)*1e3});`]);M("wait_for_page_ready",()=>["await page.waitForLoadState('domcontentloaded');"]);M("verify",(e,t)=>{let i=e.action_data?.kwargs,n=typeof i?.code=="string",a=n?i?.statement||e.action_description:e.action_description||i?.statement;if(n&&a){let r=i.code.split(`
4325
+ `,n+='- In action descriptions, describe what the placeholder represents in natural language (e.g., "Type the first user name" instead of "Type {{ firstUserName }}")',n}}});import{generateText as su}from"ai";async function bs(e,t,i={}){let n=Date.now();if(i.maxSteps!==void 0&&i.maxSteps<=0)throw new Error(`maxSteps must be >= 1, got ${i.maxSteps}`);let a=i.maxSteps??15,o=3,r=t.agentServices.getModel(),s=[r,...t.agentServices.getFallbackModels().filter(_=>_!==r)],l=0,c=r,d=t.domService||new He(t.agentServices.getDomServiceOptions()),u={...t,domService:d};T.init(),T.section("Task Execution Started"),T.log(`Task: ${e}`),T.log(`Max steps: ${a}`),T.log(`Model: ${s.length>1?s.join(" \u2192 "):r}`);let m={currentStep:0,maxSteps:a,consecutiveFailures:0,maxFailures:o,lastFailReason:null,stepHistory:[],memory:[],lastGoal:null,lastEvaluation:null},p=[],w=bn(i.customPrompt),g=new xn(w);T.log(`System prompt length: ${w.length} chars`);let y=!1,h="",v=[];try{for(i.onEvent?.({type:"start",task:e,maxSteps:a});m.currentStep<a;){if(i.abortSignal?.aborted)throw new Error("Task aborted by user");m.currentStep++;let _=Date.now();T.section(`Step ${m.currentStep}/${a}`),T.log(`URL: ${u.page.url()}`),i.onEvent?.({type:"step_start",step:m.currentStep});try{T.log("Waiting for page to stabilize..."),await mt(u.page),T.log("Page stabilized")}catch{T.log("Page stabilization timed out, continuing anyway")}let x;try{T.log("Preparing context (DOM + screenshot)...");let H=u.agentServices.getInteractiveClassNames(),K=u.agentServices.getIframeFallbackDomains();x=await ys(u.page,u.domService,H,K),T.log("Context prepared")}catch(H){if(H.message.includes("Execution context was destroyed")){T.log("Page navigating, waiting for load..."),await mt(u.page);let K=u.agentServices.getInteractiveClassNames(),Q=u.agentServices.getIframeFallbackDomains();x=await ys(u.page,u.domService,K,Q)}else throw T.error("Error preparing context",H),H}g.addStateMessage(e,x.currentUrl,x.domTree,x.screenshotBase64,m,{isFinalStep:m.currentStep===a-1,placeholderData:t.variables,sensitiveKeys:t.sensitiveKeys});let E=await cu(g,s,l,i,x.screenshotBase64);if(typeof E.modelIndexUsed=="number"&&(l=E.modelIndexUsed,c=s[E.modelIndexUsed]??c),E.tokenUsages&&E.tokenUsages.length>0&&p.push(...E.tokenUsages),!E.stepOutput){if(T.error("Failed to get valid LLM response"),m.consecutiveFailures++,m.consecutiveFailures>=o){h="Reached the maximum allowed consecutive failures. Most recent error: Unable to get a valid response from the language model.";break}continue}let $=E.stepOutput;mu(m.currentStep,a,$);let I=await uu($,u,x.domState,m.currentStep,i.onEvent,x.screenshotBase64,E.debugInfo);v.push(...I.actionEntities);let D=hu(m.currentStep,$,I,m,_,E.debugInfo,E.tokenUsages),C=Date.now()-_;if(i.onEvent?.({type:"step_complete",step:m.currentStep,duration:C}),m.consecutiveFailures>=o){T.error(`Too many consecutive failures (${m.consecutiveFailures}), stopping`),h=`Reached the maximum allowed consecutive failures. Most recent error: ${m.lastFailReason}`;break}if(I.doneResult){y=I.doneResult.success,h=I.doneResult.summary;break}if(I.completesInstruction){y=!0,h="Instruction completed";break}}return m.currentStep>=a&&!y&&(h="Reached the maximum allowed steps."),i.onEvent?.({type:"complete",totalSteps:m.currentStep,duration:Date.now()-n}),T.log(`Build success result: summary=${h}, completed=${y}, actions=${v.length}, tokens=${p.length}`),pu(m,v,y,h,n,p,c)}catch(_){let x=_.message;return T.error(`Task execution failed: ${x}`,_),i.onEvent?.({type:"error",error:x,recoverable:!1}),gu(m,x,n,p,c)}}async function ys(e,t,i,n){let{domState:a,screenshotBase64:o}=await t.getClickableElementsWithScreenshot(e,{interactiveClassNames:i,playwrightFrameFallbackDomains:n}),r=a.elementTree.clickableElementsToString();return{currentUrl:e.url(),domTree:r,screenshotBase64:o,domState:a}}function lu(e){return e.map(t=>({role:t.role,content:Array.isArray(t.content)?t.content.map(i=>{if(i.type==="file"){let n=i.data,a=typeof n=="string"?n:"";return{type:"image",file:a.startsWith("data:")?a:`data:image/png;base64,${a}`}}return{type:"text",text:i.text}}):t.content}))}async function cu(e,t,i,n,a){let{messages:o}=e.getMessages(),r=0;for(let d of o)Array.isArray(d.content)&&(r+=d.content.filter(u=>u.type==="file").length);let s=go(),l=3,c=Math.max(0,Math.min(i,t.length-1));for(let d=c;d<t.length;d++){let u=t[d],m=d===t.length-1,p=we(u,r),w=Se(u,n.temperature);try{for(let g=0;g<l;g++){let{system:y,messages:h}=e.getMessages(),v={model:fe(u),instructions:y,messages:h,providerOptions:p};w!==void 0&&(v.temperature=w);let _=new AbortController,x=s>0?setTimeout(()=>_.abort(),s):void 0,E=fo(n.abortSignal,s>0?_.signal:void 0);E&&(v.abortSignal=E);let $;try{let J=Date.now();d===c?T.log(`Calling LLM (${u})...`):T.log(`Calling LLM (${u}) [fallback ${d}/${t.length-1}]...`),$=await su(v);let he=Date.now()-J;T.llmCall(u,he,$.usage)}finally{x&&clearTimeout(x)}let I=$,D=I.usage,C=I.reasoningText;C&&(T.thinking(C),n.onEvent?.({type:"thinking",text:C})),e.addAssistantMessage($.text);let H={systemPrompt:y,userPrompt:lu(h),rawLlmResponse:$.text,reasoningContent:C,screenshotWithSom:a},K=[],Q=ke(D,u);Q&&K.push(Q);let U=du($.text);if(!U){if(g<l-1){T.log(`Attempt ${g+1}/${l}: Failed to parse response, retrying...`),e.addTextMessage("user","Your response was not valid JSON. Please respond with a properly formatted JSON object according to the expected format.");continue}return T.error("All parsing attempts failed"),{stepOutput:null,debugInfo:H,tokenUsages:K,modelIndexUsed:d}}return{stepOutput:U,debugInfo:H,tokenUsages:K,modelIndexUsed:d}}}catch(g){if(n.abortSignal?.aborted)throw g;if(!m&&Wn(g)){T.log(`Model "${u}" failed (${g.message}); falling back to "${t[d+1]}"`);continue}throw T.error("All LLM call attempts failed",g),g}}return{stepOutput:null}}function du(e){let t=e.trim();t.startsWith("```json")?t=t.replace(/^```json\s*/,"").replace(/\s*```\s*$/,""):t.startsWith("```")&&(t=t.replace(/^```\s*/,"").replace(/\s*```\s*$/,""));try{let i=JSON.parse(t);if(!i.current_goal)return T.error("Missing required field: current_goal"),null;if(!i.actions||!Array.isArray(i.actions)||i.actions.length===0)return T.error("Missing required field: actions (must be non-empty array)"),null;for(let n of i.actions){if(!n.action_name)return T.error("Action missing required field: action_name"),null;if(!n.description)return T.error("Action missing required field: description"),null}return i}catch(i){return T.error(`Failed to parse LLM JSON response: ${t.substring(0,500)}`),T.error(`Parse error: ${i.message}`),null}}async function uu(e,t,i,n,a,o,r){let s=[],l=!0,c=null;T.log(`Using pre-captured DOM state with ${i.selectorMap.size} elements for ${e.actions.length} action(s)`);let d=null,u={...t,domState:i},m=o;for(let p of e.actions){if(p.action_name==="done"){d={success:p.kwargs.success??!0,summary:p.kwargs.summary||p.kwargs.text||"Task completed"};break}let w={},g=p.kwargs?.element_index??p.kwargs?.index;if(typeof g=="number"){let h=i.selectorMap.get(g);h&&(w=await j(t.page,h))}let y={...w,action_description:p.description,action_data:{action_name:p.action_name,kwargs:p.kwargs}};try{let h=await V.execute(p.action_name,p.kwargs,u);p.action_name==="perform_accurate_operation"&&(y=h.actionEntity);let v=await u.agentServices.getCurrentPage();if(v&&(u.page=v,t.page=u.page),h?.success===!1){l=!1,T.log("Action failed, stopping execution of remaining actions in this step"),c=h.error||"Action execution failed";break}s.push(y),a?.({type:"action",action_entity:y,step:n,debugInfo:r})}catch(h){l=!1,c=h.message,T.error(`Action execution failed: ${h.message}`);break}}return{allSuccess:l,failReason:c,actionEntities:s,doneResult:d,completesInstruction:e.completes_instruction??!1}}function hu(e,t,i,n,a,o,r){let s={stepNumber:e,thinking:t.thinking,evaluation:t.evaluation_previous_goal,memory:t.memory,goal:t.current_goal,actions:i.actionEntities,timestamp:a,duration:Date.now()-a,outcome:{success:i.allSuccess},debugInfo:o,tokenUsages:r};if(n.lastGoal=t.current_goal,t.evaluation_previous_goal&&(n.lastEvaluation=t.evaluation_previous_goal),t.memory&&t.memory.trim()){let l=t.memory.trim();n.memory.includes(l)||(n.memory.push(l),n.memory.length>10&&(n.memory=n.memory.slice(-10)))}return i.allSuccess?(n.consecutiveFailures=0,n.lastFailReason=null):(n.consecutiveFailures++,n.lastFailReason=i.failReason),n.stepHistory.push(s),s}function mu(e,t,i){if(T.log(`Step ${e}/${t}`),i.thinking&&T.log(`Thinking: ${i.thinking}`),i.evaluation_previous_goal&&T.log(`Evaluation: ${i.evaluation_previous_goal}`),i.memory&&T.log(`Memory: ${i.memory}`),T.log(`Goal: ${i.current_goal}`),i.actions.length===1){let n=i.actions[0];T.log(`Action: ${n.action_name}(${JSON.stringify(n.kwargs)}) - ${n.description}`)}else T.log(`Actions (${i.actions.length}):`),i.actions.forEach((n,a)=>{T.log(` ${a+1}. ${n.action_name}(${JSON.stringify(n.kwargs)}) - ${n.description}`)})}function pu(e,t,i,n,a,o,r){let s=o.reduce((d,u)=>d+u.prompt_tokens,0),l=o.reduce((d,u)=>d+u.completion_tokens,0),c=o.reduce((d,u)=>d+u.total_tokens,0);return{success:!0,completed:i,summary:n,trajectory:{steps:e.currentStep,actions:t,stepRecords:e.stepHistory},metadata:{totalSteps:e.currentStep,totalDuration:Date.now()-a,model:r,successfulSteps:e.stepHistory.filter(d=>d.outcome.success).length,failedSteps:e.stepHistory.filter(d=>!d.outcome.success).length,promptTokens:s,completionTokens:l,totalTokens:c,tokenUsages:o}}}function gu(e,t,i,n,a){let o=n.reduce((l,c)=>l+c.prompt_tokens,0),r=n.reduce((l,c)=>l+c.completion_tokens,0),s=n.reduce((l,c)=>l+c.total_tokens,0);return{success:!1,completed:!1,error:t,trajectory:{steps:e.currentStep,actions:[],stepRecords:e.stepHistory},metadata:{totalSteps:e.currentStep,totalDuration:Date.now()-i,model:a,successfulSteps:e.stepHistory.filter(l=>l.outcome.success).length,failedSteps:e.stepHistory.filter(l=>!l.outcome.success).length,promptTokens:o,completionTokens:r,totalTokens:s,tokenUsages:n}}}var vs=b(()=>{"use strict";xa();vn();De();_e();Ve();ae();Fe();Ee();Z();Ae()});var xs={};xt(xs,{TaskMessageManager:()=>xn,formatFinalStepWarning:()=>ws,formatTaskContext:()=>yn,getBrowserTaskJSONPrompt:()=>bn,runTaskLoop:()=>bs});var _s=b(()=>{"use strict";vs();xa();vn();De();_e();qi();Ve();It();lt();Ct();Pt();Nt();ae();Fe();Ee();$t();nt();Mt();Le();it();ze();Z();Ge();Ae();ht();B();te();Lt();G();ve()});async function Dt(e,t){try{if(!e.action_data)return{success:!1,error:"Action entity missing action_data"};let{action_name:i,kwargs:n}=e.action_data;if(V.has(i)){let a=await V.execute(i,n,t),o=a?.success!==!1,r=a?.error||a?.message;return{success:o,error:o?void 0:r}}else{let{page:a,agentServices:o}=t;return await(await fu()).execute(a,e,o),{success:!0,error:void 0}}}catch(i){return{success:!1,error:i.message}}}async function fu(){if(_n)return _n;let e=await Promise.resolve().then(()=>(wn(),fn));return _n=new e.default,_n}async function Zi(e,t,i,n={},a){let o=a||{page:t,agentServices:i,domService:new He(i.getDomServiceOptions()),executionHistory:n.executionHistory,variables:n.variables,sensitiveKeys:n.sensitiveKeys},r=i.replaceVariables(e),s=await Kn(r,o,n);return s.status==="error"?{status:"error",completed:s.goalAccomplished||!1,actionEntities:[],explanation:s.reasoning,error:s.error,debugInfo:s.debugInfo}:{status:"success",completed:s.goalAccomplished||!1,actionEntities:s.actionEntity?[s.actionEntity]:[],explanation:s.reasoning,debugInfo:s.debugInfo}}async function Qi(e,t,i,n={},a){let o=a||{page:t,agentServices:i,domService:new He(i.getDomServiceOptions()),executionHistory:n.executionHistory,variables:n.variables,sensitiveKeys:n.sensitiveKeys},r=i.replaceVariables(e),s=await Kn(r,o,n);if(s.status==="error"||!s.actionEntity)return{status:"error",completed:s.goalAccomplished||!1,actionEntities:[],explanation:s.reasoning,error:s.error||"No action generated",debugInfo:s.debugInfo};let{actionEntity:l,reasoning:c,goalAccomplished:d,debugInfo:u}=s,m=await Dt(l,o);return m.success?(c&&i.addNote(c),{status:"success",completed:d||!1,actionEntities:[l],explanation:c,debugInfo:u}):{status:"error",completed:!1,actionEntities:[l],error:m.error||"Action execution failed",debugInfo:u}}async function en(e,t,i,n={}){let a={page:t,agentServices:i,domService:new He(i.getDomServiceOptions()),executionHistory:n.executionHistory,variables:n.variables,sensitiveKeys:n.sensitiveKeys},o=i.replaceVariables(e);return n.useCleanScreenshotForAssertion??(n.useCleanScreenshotForAssertion=i.isUseCleanScreenshotForAssertion()),Io(o,a,n)}async function tn(e,t,i,n,a={}){let{runTaskLoop:o}=await Promise.resolve().then(()=>(_s(),xs)),r=n?l=>{n(l)}:void 0,s=await o(e,{page:t,agentServices:i,domService:void 0,executionHistory:a.executionHistory,variables:a.variables,sensitiveKeys:a.sensitiveKeys},{maxSteps:a.maxSteps,onEvent:r,abortSignal:a.abortSignal});return{status:s.success?"success":"error",completed:s.completed,actionEntities:s.trajectory.actions,explanation:s.summary,error:s.error,tokenUsages:s.metadata.tokenUsages}}var _n,Rt=b(()=>{"use strict";ji();_e();Ve();_n=null});var ka=b(()=>{"use strict";ae();Ae()});var Bs=b(()=>{"use strict"});var Gs=b(()=>{"use strict"});var Ks=b(()=>{"use strict"});var Sn=b(()=>{"use strict"});import{z as S}from"zod";var zs,Ea,Vs,ft,Xs,Js,Ys,re,qs,En,Ta,Aa=b(()=>{"use strict";zs=S.enum(["JS_CODE","AI_MODE"]),Ea=S.object({type:zs,expression:S.string()}),Vs=S.enum(["DRAFT","STEP","ACTION","IF_ELSE","WHILE_LOOP"]),ft=S.object({uid:S.string(),type:Vs,comment:S.string().optional()}),Xs=S.object({action_data:S.object({action_name:S.string(),kwargs:S.record(S.any()).optional(),args:S.array(S.any()).optional()}),action_description:S.string().optional(),url:S.string().optional(),xpath:S.string().nullable().optional(),locator:S.string().nullable().optional(),css_selector:S.string().nullable().optional(),unique_selector:S.string().nullable().optional(),element_index:S.number().nullable().optional(),frame_path:S.array(S.any()).optional(),artifacts:S.record(S.any()).optional(),feedback:S.string().optional(),original_browser_use_action:S.any().optional()}).passthrough(),Js=ft.extend({type:S.literal("DRAFT"),description:S.string()}),Ys=ft.extend({type:S.literal("ACTION"),description:S.string(),action_entity:Xs.optional(),locator:S.string().optional(),use_pure_vision:S.boolean().optional()}),re=S.lazy(()=>S.union([Js,Ys,ft.extend({type:S.literal("STEP"),description:S.string().optional().default(""),statements:S.array(re),reference_id:S.number().optional(),template_path:S.string().optional(),template_params:S.record(S.string()).optional()}),ft.extend({type:S.literal("IF_ELSE"),description:S.string().optional(),condition:Ea,then:S.array(re),else:S.array(re).optional()}),ft.extend({type:S.literal("WHILE_LOOP"),description:S.string().optional(),condition:Ea,body:S.array(re),timeout_ms:S.number().optional()})])),qs=S.object({name:S.string(),statements:S.array(re),teardown:S.array(re).optional(),skip:S.union([S.boolean(),S.string()]).optional(),timeout:S.number().optional(),fail:S.union([S.boolean(),S.string()]).optional(),only:S.boolean().optional(),slow:S.boolean().optional()}),En=S.object({tests:S.array(qs).min(1),beforeAll:S.array(re).optional(),afterAll:S.array(re).optional(),beforeEach:S.array(re).optional(),afterEach:S.array(re).optional()}),Ta=S.object({comment:S.string().optional(),version:S.string().optional(),goal:S.string().optional(),url:S.string().optional(),baseURL:S.string().optional(),final_feedback:S.string().optional(),completed:S.boolean().optional(),success:S.boolean().optional(),statements:S.array(re).optional(),teardown:S.array(re).optional(),last_modified_at:S.string().optional(),testGroup:En.optional()}).refine(e=>e.testGroup!==void 0?e.goal===void 0&&(e.statements===void 0||e.statements.length===0):e.goal!==void 0,{message:"TestFlow must have either goal/statements (single test) or testGroup (suite), not both"})});import{stringify as pT,parse as tl,parseAllDocuments as gT,parseDocument as Uu,Document as il,isMap as yt,isSeq as se}from"yaml";import{v4 as ce}from"uuid";function Tn(e,t){let i={...t?.test_case_id!==void 0?{test_case_id:t.test_case_id}:{},...t?.name?{name:t.name}:{},...t?.tags&&t.tags.length>0?{tags:t.tags}:{},...t?.skip!==void 0?{skip:t.skip}:{},...t?.fail!==void 0?{fail:t.fail}:{},...t?.only?{only:t.only}:{},...t?.slow?{slow:t.slow}:{},goal:e.goal??"",url:e.url,base_url:e.baseURL,...t?.timeout!==void 0?{timeout:t.timeout}:{},...t?.settings&&Object.keys(t.settings).length>0?{settings:t.settings}:{},...t?.use&&Object.keys(t.use).length>0?{use:t.use}:{},...t?.beforeEach&&t.beforeEach.length>0?{beforeEach:t.beforeEach}:{},...t?.afterEach&&t.afterEach.length>0?{afterEach:t.afterEach}:{},...t?.parameters&&t.parameters.length>0?{parameters:t.parameters}:{},statements:(e.statements??[]).map(de)};return e.final_feedback&&(i.final_feedback=e.final_feedback),e.teardown&&e.teardown.length>0&&(i.teardown=e.teardown.map(de)),i}function Ma(e,t){if(e.testGroup)return al(e,t);let i=Tn(e,t),n=new il(i),a=n.contents?.get("tags",!0);return se(a)&&(a.flow=!0),e.comment&&(n.commentBefore=e.comment),Zs(n,e.statements??[]),e.teardown&&Zs(n,e.teardown,"teardown"),n.toString(nl)}function Zs(e,t,i="statements"){let n=e.contents;if(!n||!yt(n))return;let a=n.get(i,!0);se(a)&&bi(a,t)}function bi(e,t){for(let i=0;i<Math.min(e.items.length,t.length);i++){let n=t[i],a=e.items[i];if(i>0&&(a.spaceBefore=!0),n.comment&&(i===0?e.commentBefore=n.comment:a.commentBefore=n.comment),yt(a)){let o=a;if(n.type==="STEP"){let r=o.get("statements",!0);se(r)&&bi(r,n.statements)}else if(n.type==="IF_ELSE"){let r=o.get("THEN",!0);se(r)&&bi(r,n.then);let s=o.get("ELSE",!0);se(s)&&n.else&&bi(s,n.else)}else if(n.type==="WHILE_LOOP"){let r=o.get("DO",!0);se(r)&&bi(r,n.body)}}}}function al(e,t){let i=e.testGroup;if(!i)throw new Error("suiteToYaml requires a TestFlow with testGroup");let n={};t?.test_case_id!==void 0&&(n.test_case_id=t.test_case_id),t?.name&&(n.name=t.name),t?.tags&&t.tags.length>0&&(n.tags=t.tags),t?.use&&Object.keys(t.use).length>0&&(n.use=t.use),t?.settings&&Object.keys(t.settings).length>0&&(n.settings=t.settings);let a={};e.baseURL&&(a.base_url=e.baseURL),i.beforeAll&&i.beforeAll.length>0&&(a.beforeAll=i.beforeAll.map(de)),i.beforeEach&&i.beforeEach.length>0&&(a.beforeEach=i.beforeEach.map(de)),i.afterEach&&i.afterEach.length>0&&(a.afterEach=i.afterEach.map(de)),i.afterAll&&i.afterAll.length>0&&(a.afterAll=i.afterAll.map(de)),a.tests=i.tests.map(s=>{let l={name:s.name};return s.skip!==void 0&&(l.skip=s.skip),s.timeout!==void 0&&(l.timeout=s.timeout),s.fail!==void 0&&(l.fail=s.fail),s.only!==void 0&&(l.only=s.only),s.slow!==void 0&&(l.slow=s.slow),l.statements=s.statements.map(de),s.teardown&&s.teardown.length>0&&(l.teardown=s.teardown.map(de)),l}),n.suite=a;let o=new il(n),r=o.contents?.get("tags",!0);return se(r)&&(r.flow=!0),o.toString(nl)}function de(e){switch(e.type){case"DRAFT":return Bu(e);case"ACTION":return Gu(e);case"STEP":return Ku(e);case"IF_ELSE":return zu(e);case"WHILE_LOOP":return Vu(e)}}function Bu(e){return{intent:e.description}}function Gu(e){let t=e.action_entity?.action_data?.action_name??e.action_entity?.action?.action_name,i=e.action_entity?.action_data?.kwargs??e.action_entity?.action?.kwargs;if(t==="verify"){let s=i?.statement;if(typeof s=="string"&&!e.action_entity?.locator&&!e.action_entity?.xpath){let l=i?.code;return typeof l=="string"&&l.trim()?{VERIFY:s,js:l}:{VERIFY:s}}}if(t==="go_to_url"){let s=i?.url;if(typeof s=="string"&&!e.action_entity?.locator&&!e.action_entity?.xpath){let l={URL:s};return i?.new_tab===!0&&(l.new_tab=!0),typeof i?.timeout_seconds=="number"&&(l.timeout_seconds=i.timeout_seconds),l}}if(t==="js_action"){let s=i?.code;if(typeof s=="string"&&s.trim()&&e.description)return{description:e.description,js:s}}if(t==="ai_wait_until"){let s=i?.condition;if(typeof s=="string"){let l=typeof i?.js=="string"&&i.js.trim()?i.js:void 0,c={};if(l)c.WAIT_UNTIL=s,c.js=l;else{let d=i?.condition_type==="JS_CODE"?"JS_CODE":"AI_MODE";c.WAIT_UNTIL=Ia({type:d,expression:s})}return typeof i?.timeout_seconds=="number"&&i.timeout_seconds!==60&&(c.timeout_seconds=i.timeout_seconds),c}}if(t==="wait"){let s=i?.seconds,c={WAIT:e.description||`Wait ${s}s`};return typeof s=="number"&&(c.seconds=s),c}if(t==="js_code"){let s=i?.code;if(typeof s=="string"&&!e.action_entity?.locator&&!e.action_entity?.xpath)return{description:e.description||"Code block",js:s}}if(!e.action_entity)return{intent:e.description};let n=e.action_entity.action_data??e.action_entity.action;if(!n)return{intent:e.description};if(n.action_name==="function"&&typeof n.kwargs?.functionName=="string"&&n.kwargs.functionName.includes("#")&&!Array.isArray(n.kwargs.parameterNames)&&!Array.isArray(n.kwargs.parameterValues)&&(!Array.isArray(n.args)||n.args.length===0)){let s={intent:e.description,call:n.kwargs.functionName};return Array.isArray(n.kwargs.args)&&n.kwargs.args.length>0&&(s.args=n.kwargs.args),s}let a={intent:e.description,action:n.action_name},o=e.locator??e.action_entity.locator;o&&(a.locator=o);let r=e.action_entity.xpath;if(r&&(a.xpath=r),e.use_pure_vision&&(a.use_pure_vision=!0),n.kwargs&&Object.keys(n.kwargs).length>0)for(let[s,l]of Object.entries(n.kwargs))s!=="uid"&&(s==="statement"&&(t==="ai_action"||t==="ai_step")||(a[s]=l));return n.args&&n.args.length>0&&(a.args=n.args),a}function Ku(e){if(e.template_path){let i={template:e.template_path};return e.template_params&&Object.keys(e.template_params).length>0&&(i.params=e.template_params),i}let t={STEP:e.description,statements:e.statements.map(de)};return e.reference_id!==void 0&&(t.reference_id=e.reference_id),t}function zu(e){let t={IF:Ia(e.condition),THEN:e.then.map(de)};return e.else&&e.else.length>0&&(t.ELSE=e.else.map(de)),t}function Vu(e){let t={WHILE:Ia(e.condition),DO:e.body.map(de)};return e.timeout_ms!==void 0&&(t.timeout_ms=e.timeout_ms),t}function Ia(e){return e.type==="JS_CODE"?`js:${e.expression}`:e.expression}function Ca(e){try{let t=tl(e);if(!t||typeof t!="object")return{};let i={};return typeof t.test_case_id=="number"&&Number.isFinite(t.test_case_id)&&(i.test_case_id=t.test_case_id),typeof t.template_id=="number"&&Number.isFinite(t.template_id)&&(i.template_id=t.template_id),typeof t.name=="string"&&t.name.trim()&&(i.name=t.name.trim()),typeof t.timeout=="number"&&Number.isFinite(t.timeout)&&(i.timeout=t.timeout),t.settings&&typeof t.settings=="object"&&!Array.isArray(t.settings)&&(i.settings=t.settings),t.use&&typeof t.use=="object"&&!Array.isArray(t.use)&&(i.use=t.use),Array.isArray(t.tags)&&t.tags.every(n=>typeof n=="string")&&(i.tags=t.tags),(typeof t.skip=="boolean"||typeof t.skip=="string")&&(i.skip=t.skip),(typeof t.fail=="boolean"||typeof t.fail=="string")&&(i.fail=t.fail),t.only===!0&&(i.only=!0),t.slow===!0&&(i.slow=!0),Array.isArray(t.beforeEach)&&t.beforeEach.length>0&&(i.beforeEach=t.beforeEach),Array.isArray(t.afterEach)&&t.afterEach.length>0&&(i.afterEach=t.afterEach),Array.isArray(t.parameters)&&t.parameters.length>0&&(i.parameters=t.parameters),i}catch{return{}}}function $a(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map($a);let t=e,i=Object.keys(t);if(i.length===1){let a=i[0];if(a.startsWith("{ ")&&a.endsWith(" }")&&t[a]===null)return`{{${a.slice(2,-2)}}}`}let n={};for(let[a,o]of Object.entries(t))n[a]=$a(o);return n}function Me(e){if(e.length>Qs)throw new Error(`YAML input too large (${e.length} bytes, max ${Qs})`);let t=$a(tl(e));if(!t||typeof t!="object")throw new Error("Invalid YAML: expected an object at root level");if(t.suite)return Xu(t);let i={version:"1.3.0",goal:t.goal,url:t.url,baseURL:t.base_url,statements:ue(t.statements??[])};t.final_feedback&&(i.final_feedback=t.final_feedback),t.teardown&&Array.isArray(t.teardown)&&(i.teardown=ue(t.teardown));let n=Ta.safeParse(i);if(!n.success)throw new Error(`Invalid TestFlow after YAML conversion: ${JSON.stringify(n.error.errors)}`);let a=n.data;return An(e,a),a}function Xu(e){let t=e.suite;if(!t||typeof t!="object")throw new Error("Invalid suite: expected an object");let i=t.tests;if(!Array.isArray(i)||i.length===0)throw new Error('Suite must have a non-empty "tests" array');let a={tests:i.map(s=>{if(!s.name)throw new Error('Each test in a suite must have a "name" field');if(!Array.isArray(s.statements)||s.statements.length===0)throw new Error(`Suite test "${s.name}" must have a non-empty "statements" array`);let l={name:s.name,statements:ue(s.statements)};return Array.isArray(s.teardown)&&s.teardown.length>0&&(l.teardown=ue(s.teardown)),s.skip!==void 0&&(l.skip=s.skip),typeof s.timeout=="number"&&(l.timeout=s.timeout),s.fail!==void 0&&(l.fail=s.fail),s.only===!0&&(l.only=!0),s.slow===!0&&(l.slow=!0),l})};Array.isArray(t.beforeAll)&&t.beforeAll.length>0&&(a.beforeAll=ue(t.beforeAll)),Array.isArray(t.afterAll)&&t.afterAll.length>0&&(a.afterAll=ue(t.afterAll)),Array.isArray(t.beforeEach)&&t.beforeEach.length>0&&(a.beforeEach=ue(t.beforeEach)),Array.isArray(t.afterEach)&&t.afterEach.length>0&&(a.afterEach=ue(t.afterEach));let o=En.safeParse(a);if(!o.success)throw new Error(`Invalid TestGroup: ${JSON.stringify(o.error.errors)}`);return{version:"1.3.0",baseURL:t.base_url||void 0,testGroup:o.data}}function ue(e){if(!Array.isArray(e))throw new Error("Expected an array of statements");return e.map(Ju)}function Ju(e){if(typeof e=="string")throw new Error(`Plain string statements are not supported. Use an object with a "desc" key instead. Example: { "desc": "${e}" }`);if(typeof e!="object"||e===null)throw new Error(`Invalid statement: expected object, got ${typeof e}`);let t=e;if("IF"in t)return Yu(t);if("WHILE"in t)return qu(t);if("STEP"in t)return Zu(t);if("VERIFY"in t){let i=t.VERIFY,n={statement:typeof i=="string"?i:String(i)};return typeof t.js=="string"&&(n.code=t.js),{uid:ce(),type:"ACTION",description:String(i),action_entity:{action_description:String(i),action_data:{action_name:"verify",kwargs:n}}}}if("URL"in t){let i=t.URL,n=t.new_tab===!0?!0:void 0,a=typeof t.timeout_seconds=="number"?t.timeout_seconds:void 0,o={url:typeof i=="string"?i:String(i)};return n&&(o.new_tab=!0),a!==void 0&&(o.timeout_seconds=a),{uid:ce(),type:"ACTION",description:`Navigate to ${i}`,action_entity:{action_description:`Navigate to ${i}`,action_data:{action_name:"go_to_url",kwargs:o}}}}if("WAIT_UNTIL"in t){let i=typeof t.WAIT_UNTIL=="string"?t.WAIT_UNTIL:String(t.WAIT_UNTIL),n=Pa(i),a=typeof t.timeout_seconds=="number"?t.timeout_seconds:60;if(typeof t.js=="string"){if(n.type==="JS_CODE")throw new Error('WAIT_UNTIL cannot combine a "js:"-prefixed condition with a sibling "js:" key \u2014 put the intent in WAIT_UNTIL and the expression in js:');return{uid:ce(),type:"ACTION",description:`Wait until: ${i}`,action_entity:{action_description:`Wait until: ${i}`,action_data:{action_name:"ai_wait_until",kwargs:{condition:i,condition_type:"JS_CODE",js:t.js,timeout_seconds:a}}}}}return{uid:ce(),type:"ACTION",description:`Wait until: ${n.expression}`,action_entity:{action_description:`Wait until: ${n.expression}`,action_data:{action_name:"ai_wait_until",kwargs:{condition:n.expression,condition_type:n.type,timeout_seconds:a}}}}}if("WAIT"in t){let i=t.WAIT,n=typeof t.seconds=="number"?t.seconds:3;return{uid:ce(),type:"ACTION",description:typeof i=="string"?i:`Wait ${n}s`,action_entity:{action_description:typeof i=="string"?i:`Wait ${n}s`,action_data:{action_name:"wait",kwargs:{seconds:n}}}}}if("CODE"in t){let i=t.CODE;if(i==null)throw new Error('CODE statement has no code. Use "CODE: |" followed by indented code on the next line.');let n=typeof t.description=="string"?t.description:"Code block";return{uid:ce(),type:"ACTION",description:n,action_entity:{action_description:n,action_data:{action_name:"js_code",kwargs:{code:typeof i=="string"?i:String(i)}}}}}if("js"in t&&!("VERIFY"in t)&&!("action"in t)){if("intent"in t||"desc"in t)throw new Error("A `js:` statement uses `description:`, not `intent:`. Raw JS does not self-heal \u2014 use `description: + js:` for code, or express it as a structured action (`intent:` + `action:`/`locator:`) to keep self-healing.");let i=typeof t.description=="string"&&t.description.trim()!==""?t.description:"Code block",n=t.js;return{uid:ce(),type:"ACTION",description:i,action_entity:{action_description:i,action_data:{action_name:"js_code",kwargs:{code:typeof n=="string"?n:String(n)}}}}}if("call"in t&&typeof t.call=="string"){let{call:i,...n}=t;return el({...n,action:"function",functionName:i})}if("action"in t)return el(t);if("intent"in t&&typeof t.intent=="string"||"desc"in t&&typeof t.desc=="string")return{uid:ce(),type:"DRAFT",description:typeof t.intent=="string"?t.intent:t.desc};throw new Error(`Cannot infer statement type from object: ${JSON.stringify(t)}`)}function Pa(e){if(typeof e!="string")throw new Error(`Condition must be a string, got ${typeof e}`);return e.startsWith("js:")?{type:"JS_CODE",expression:e.slice(3)}:{type:"AI_MODE",expression:e}}function Yu(e){let t=Pa(e.IF),i=e.THEN;if(!Array.isArray(i))throw new Error("IF_ELSE requires a THEN array");let n={uid:ce(),type:"IF_ELSE",condition:t,then:ue(i)};return"ELSE"in e&&Array.isArray(e.ELSE)&&(n.else=ue(e.ELSE)),n}function qu(e){let t=Pa(e.WHILE),i=e.DO;if(!Array.isArray(i))throw new Error("WHILE_LOOP requires a DO array");let n={uid:ce(),type:"WHILE_LOOP",condition:t,body:ue(i)};return typeof e.timeout_ms=="number"&&(n.timeout_ms=e.timeout_ms),n}function Zu(e){let t=typeof e.STEP=="string"?e.STEP:"";if(!Array.isArray(e.statements))throw new Error("STEP requires a statements array");let i={uid:ce(),type:"STEP",description:t,statements:ue(e.statements)};if(typeof e.reference_id=="number"&&(i.reference_id=e.reference_id),typeof e.template_path=="string"&&(i.template_path=e.template_path),e.template_params&&typeof e.template_params=="object"&&!Array.isArray(e.template_params)){let n=e.template_params,a={};for(let[o,r]of Object.entries(n))a[o]=String(r);i.template_params=a}return i}function el(e){let t=typeof e.action=="string"?e.action:String(e.action),i=typeof e.intent=="string"?e.intent:typeof e.desc=="string"?e.desc:"",n=typeof e.locator=="string"?e.locator:void 0,a=typeof e.xpath=="string"?e.xpath:void 0,o=typeof e.use_pure_vision=="boolean"?e.use_pure_vision:void 0,r={};for(let[c,d]of Object.entries(e))Qu.has(c)||(r[c]=d);t==="verify"&&typeof r.js=="string"&&(r.code=r.js,delete r.js),(t==="ai_action"||t==="ai_step")&&(r.statement===void 0&&(r.statement=i),o&&(r.use_pure_vision=!0));let s={action_description:i,action_data:{action_name:t,kwargs:Object.keys(r).length>0?r:{}}};n&&(s.locator=n),a&&(s.xpath=a);let l={uid:ce(),type:"ACTION",description:i,action_entity:s};return o&&(l.use_pure_vision=!0),l}function An(e,t){let i;try{i=Uu(e)}catch{return}let n=i.contents;if(!n||!yt(n))return;if(i.commentBefore)t.comment=i.commentBefore;else{let l=n.items?.[0];l?.key&&l.key.commentBefore&&(t.comment=l.key.commentBefore)}let a=n,o=a.get("statements",!0);se(o)&&t.statements&&wt(o,t.statements);let r=a.get("teardown",!0);se(r)&&t.teardown&&wt(r,t.teardown)}function wt(e,t){e.commentBefore&&t.length>0&&(t[0].comment=e.commentBefore);for(let i=0;i<Math.min(e.items.length,t.length);i++){let n=e.items[i];n.commentBefore&&!(i===0&&e.commentBefore)&&(t[i].comment=n.commentBefore);let a=t[i];if(a.type==="STEP"&&yt(n)){let o=n.get("statements",!0);se(o)&&wt(o,a.statements)}else if(a.type==="IF_ELSE"&&yt(n)){let o=n.get("THEN",!0);se(o)&&wt(o,a.then);let r=n.get("ELSE",!0);se(r)&&a.else&&wt(r,a.else)}else if(a.type==="WHILE_LOOP"&&yt(n)){let o=n.get("DO",!0);se(o)&&wt(o,a.body)}}}var nl,Qs,Qu,$n=b(()=>{"use strict";Aa();nl={lineWidth:120,defaultKeyType:"PLAIN",defaultStringType:"PLAIN"};Qs=1024*1024;Qu=new Set(["action","intent","desc","locator","xpath","use_pure_vision"])});var ol=b(()=>{"use strict";Sn();$n()});var rl=b(()=>{"use strict";Sn()});import{v4 as ST}from"uuid";var sl=b(()=>{"use strict"});import{parse as $T,stringify as MT}from"yaml";var ll=b(()=>{"use strict";$n()});var Je,cl=b(()=>{"use strict";Je=(e=>(e.DRAFT="DRAFT",e.STEP="STEP",e.ACTION="ACTION",e.IF_ELSE="IF_ELSE",e.WHILE_LOOP="WHILE_LOOP",e))(Je||{})});var Mn=b(()=>{"use strict"});var dl=b(()=>{"use strict";Mn()});var ul=b(()=>{"use strict";Mn()});var hl,ah,ml,pl,vi,oh,rh,gl=b(()=>{"use strict";hl=112,ah=1080-hl,ml={"Blackberry PlayBook":{name:"Blackberry PlayBook",userAgent:"Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/26.0 Safari/536.2+",screen:{width:600,height:1024},viewport:{width:600,height:1024},deviceScaleFactor:1,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"BlackBerry Z30":{name:"BlackBerry Z30",userAgent:"Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/26.0 Mobile Safari/537.10+",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy Note 3":{name:"Galaxy Note 3",userAgent:"Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.0 Mobile Safari/534.30",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy Note II":{name:"Galaxy Note II",userAgent:"Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.0 Mobile Safari/534.30",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy S III":{name:"Galaxy S III",userAgent:"Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/26.0 Mobile Safari/534.30",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Galaxy S5":{name:"Galaxy S5",userAgent:"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy S8":{name:"Galaxy S8",userAgent:"Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:740},viewport:{width:360,height:740},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy S9+":{name:"Galaxy S9+",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:320,height:658},viewport:{width:320,height:658},deviceScaleFactor:4.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy S24":{name:"Galaxy S24",userAgent:"Mozilla/5.0 (Linux; Android 14; SM-S921U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:780},viewport:{width:360,height:780},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy A55":{name:"Galaxy A55",userAgent:"Mozilla/5.0 (Linux; Android 14; SM-A556B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:480,height:1040},viewport:{width:480,height:1040},deviceScaleFactor:2.25,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy Tab S4":{name:"Galaxy Tab S4",userAgent:"Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:712,height:1138},viewport:{width:712,height:1138},deviceScaleFactor:2.25,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Galaxy Tab S9":{name:"Galaxy Tab S9",userAgent:"Mozilla/5.0 (Linux; Android 14; SM-X710) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:640,height:1024},viewport:{width:640,height:1024},deviceScaleFactor:2.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"iPad (gen 5)":{name:"iPad (gen 5)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:768,height:1024},viewport:{width:768,height:1024},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad (gen 6)":{name:"iPad (gen 6)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:768,height:1024},viewport:{width:768,height:1024},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad (gen 7)":{name:"iPad (gen 7)",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:810,height:1080},viewport:{width:810,height:1080},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad (gen 11)":{name:"iPad (gen 11)",userAgent:"Mozilla/5.0 (iPad; CPU OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/19E241 Safari/604.1",screen:{width:656,height:944},viewport:{width:656,height:944},deviceScaleFactor:2.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad Mini":{name:"iPad Mini",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:768,height:1024},viewport:{width:768,height:1024},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPad Pro 11":{name:"iPad Pro 11",userAgent:"Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:834,height:1194},viewport:{width:834,height:1194},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 6":{name:"iPhone 6",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 6 Plus":{name:"iPhone 6 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:414,height:736},viewport:{width:414,height:736},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 7":{name:"iPhone 7",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 7 Plus":{name:"iPhone 7 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:414,height:736},viewport:{width:414,height:736},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 8":{name:"iPhone 8",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 8 Plus":{name:"iPhone 8 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:414,height:736},viewport:{width:414,height:736},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone SE":{name:"iPhone SE",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.0 Mobile/14E304 Safari/602.1",screen:{width:320,height:568},viewport:{width:320,height:568},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone SE (3rd gen)":{name:"iPhone SE (3rd gen)",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/26.0 Mobile/19E241 Safari/602.1",screen:{width:375,height:667},viewport:{width:375,height:667},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone X":{name:"iPhone X",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/26.0 Mobile/15A372 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:812},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone XR":{name:"iPhone XR",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:414,height:896},viewport:{width:414,height:896},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 11":{name:"iPhone 11",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:414,height:896},viewport:{width:414,height:715},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 11 Pro":{name:"iPhone 11 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:635},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 11 Pro Max":{name:"iPhone 11 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:414,height:896},viewport:{width:414,height:715},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12":{name:"iPhone 12",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12 Pro":{name:"iPhone 12 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12 Pro Max":{name:"iPhone 12 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:428,height:926},viewport:{width:428,height:746},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 12 Mini":{name:"iPhone 12 Mini",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:629},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13":{name:"iPhone 13",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13 Pro":{name:"iPhone 13 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13 Pro Max":{name:"iPhone 13 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:428,height:926},viewport:{width:428,height:746},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 13 Mini":{name:"iPhone 13 Mini",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:375,height:812},viewport:{width:375,height:629},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14":{name:"iPhone 14",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:390,height:844},viewport:{width:390,height:664},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14 Plus":{name:"iPhone 14 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:428,height:926},viewport:{width:428,height:746},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14 Pro":{name:"iPhone 14 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:393,height:852},viewport:{width:393,height:660},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 14 Pro Max":{name:"iPhone 14 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:430,height:932},viewport:{width:430,height:740},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15":{name:"iPhone 15",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:393,height:852},viewport:{width:393,height:659},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15 Plus":{name:"iPhone 15 Plus",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:430,height:932},viewport:{width:430,height:739},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15 Pro":{name:"iPhone 15 Pro",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:393,height:852},viewport:{width:393,height:659},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"iPhone 15 Pro Max":{name:"iPhone 15 Pro Max",userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",screen:{width:430,height:932},viewport:{width:430,height:739},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Kindle Fire HDX":{name:"Kindle Fire HDX",userAgent:"Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",screen:{width:800,height:1280},viewport:{width:800,height:1280},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"LG Optimus L70":{name:"LG Optimus L70",userAgent:"Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:384,height:640},viewport:{width:384,height:640},deviceScaleFactor:1.25,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Microsoft Lumia 550":{name:"Microsoft Lumia 550",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36 Edge/14.14263",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Microsoft Lumia 950":{name:"Microsoft Lumia 950",userAgent:"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36 Edge/14.14263",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:4,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 10":{name:"Nexus 10",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:800,height:1280},viewport:{width:800,height:1280},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 4":{name:"Nexus 4",userAgent:"Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:384,height:640},viewport:{width:384,height:640},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 5":{name:"Nexus 5",userAgent:"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 5X":{name:"Nexus 5X",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:732},viewport:{width:412,height:732},deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 6":{name:"Nexus 6",userAgent:"Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:732},viewport:{width:412,height:732},deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 6P":{name:"Nexus 6P",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:732},viewport:{width:412,height:732},deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nexus 7":{name:"Nexus 7",userAgent:"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:600,height:960},viewport:{width:600,height:960},deviceScaleFactor:2,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nokia Lumia 520":{name:"Nokia Lumia 520",userAgent:"Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)",screen:{width:320,height:533},viewport:{width:320,height:533},deviceScaleFactor:1.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Nokia N9":{name:"Nokia N9",userAgent:"Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13",screen:{width:480,height:854},viewport:{width:480,height:854},deviceScaleFactor:1,isMobile:!0,hasTouch:!0,defaultBrowserType:"webkit"},"Pixel 2":{name:"Pixel 2",userAgent:"Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:411,height:731},viewport:{width:411,height:731},deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 2 XL":{name:"Pixel 2 XL",userAgent:"Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:411,height:823},viewport:{width:411,height:823},deviceScaleFactor:3.5,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 3":{name:"Pixel 3",userAgent:"Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:393,height:786},viewport:{width:393,height:786},deviceScaleFactor:2.75,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 4":{name:"Pixel 4",userAgent:"Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:353,height:745},viewport:{width:353,height:745},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 4a (5G)":{name:"Pixel 4a (5G)",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:892},viewport:{width:412,height:765},deviceScaleFactor:2.63,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 5":{name:"Pixel 5",userAgent:"Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:393,height:851},viewport:{width:393,height:727},deviceScaleFactor:2.75,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Pixel 7":{name:"Pixel 7",userAgent:"Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:412,height:915},viewport:{width:412,height:839},deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Moto G4":{name:"Moto G4",userAgent:"Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Mobile Safari/537.36",screen:{width:360,height:640},viewport:{width:360,height:640},deviceScaleFactor:3,isMobile:!0,hasTouch:!0,defaultBrowserType:"chromium"},"Desktop Chrome HiDPI":{name:"Desktop Chrome HiDPI",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Edge HiDPI":{name:"Desktop Edge HiDPI",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Firefox HiDPI":{name:"Desktop Firefox HiDPI",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:142.0.1) Gecko/20100101 Firefox/142.0.1",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"firefox"},"Desktop Safari":{name:"Desktop Safari",userAgent:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15",screen:{width:1792,height:1120},viewport:{width:1280,height:720},deviceScaleFactor:2,isMobile:!1,hasTouch:!1,defaultBrowserType:"webkit"},"Desktop Chrome":{name:"Desktop Chrome",displayName:"Playwright Chromium",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1920,height:1080},viewport:{width:1920,height:1080},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Chrome Medium Resolution":{name:"Desktop Chrome Medium Resolution",displayName:"Playwright Chromium",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1280,height:720},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Chrome (Branded)":{name:"Desktop Chrome (Branded)",displayName:"Google Chrome",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1920,height:1080},viewport:{width:1920,height:1080},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"chrome"},"Desktop Chrome Medium Resolution (Branded)":{name:"Desktop Chrome Medium Resolution (Branded)",displayName:"Google Chrome",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36",screen:{width:1280,height:720},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"chrome"},"Desktop Edge":{name:"Desktop Edge",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1920,height:1080},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium"},"Desktop Edge (Branded)":{name:"Desktop Edge (Branded)",displayName:"Microsoft Edge",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1920,height:1080},viewport:{width:1920,height:1080},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"msedge"},"Desktop Edge Medium Resolution (Branded)":{name:"Desktop Edge Medium Resolution (Branded)",displayName:"Microsoft Edge",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.16 Safari/537.36 Edg/141.0.7390.16",screen:{width:1280,height:720},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"chromium",channel:"msedge"},"Desktop Firefox":{name:"Desktop Firefox",userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:142.0.1) Gecko/20100101 Firefox/142.0.1",screen:{width:1920,height:1080},viewport:{width:1280,height:720},deviceScaleFactor:1,isMobile:!1,hasTouch:!1,defaultBrowserType:"firefox"}},pl={desktop:["Desktop Chrome","Desktop Chrome Medium Resolution","Desktop Chrome (Branded)","Desktop Chrome Medium Resolution (Branded)","Desktop Edge (Branded)","Desktop Edge Medium Resolution (Branded)","Desktop Safari"],mobile:["iPhone 15 Pro Max","iPhone 15 Pro","iPhone 15 Plus","iPhone 15","iPhone 14 Pro Max","iPhone 14 Pro","iPhone 14 Plus","iPhone 14","iPhone 13 Pro Max","iPhone 13 Pro","iPhone 13","iPhone 13 Mini","iPhone 12 Pro Max","iPhone 12 Pro","iPhone 12","iPhone 12 Mini","iPhone 11 Pro Max","iPhone 11 Pro","iPhone 11","iPhone XR","iPhone X","iPhone SE (3rd gen)","iPhone SE","iPhone 8 Plus","iPhone 8","iPhone 7 Plus","iPhone 7","iPhone 6 Plus","iPhone 6","Galaxy S24","Galaxy A55","Galaxy S9+","Galaxy S8","Galaxy S5","Galaxy Note 3","Galaxy Note II","Galaxy S III","Pixel 7","Pixel 5","Pixel 4a (5G)","Pixel 4","Pixel 3","Pixel 2 XL","Pixel 2","Nexus 6P","Nexus 6","Nexus 5X","Nexus 5","Nexus 4","Moto G4","LG Optimus L70","Microsoft Lumia 950","Microsoft Lumia 550","Nokia Lumia 520","Nokia N9","BlackBerry Z30"]},vi=(e,t=!1)=>{let i=["chromium"];return t&&i.push("webkit"),pl[e].map(n=>ml[n]).filter(n=>n.defaultBrowserType&&i.includes(n.defaultBrowserType))},oh={desktop:{label:"Desktop",type:"desktop",devices:vi("desktop")},mobile:{label:"Mobile Web",type:"mobile",devices:vi("mobile")}},rh={desktop:{label:"Desktop",type:"desktop",devices:vi("desktop",!0)},mobile:{label:"Mobile Web",type:"mobile",devices:vi("mobile",!0)}}});var fl=b(()=>{"use strict"});var wl=b(()=>{"use strict"});function bl(e){if(e!==null&&typeof e=="object"){for(let t of Object.values(e))bl(t);Object.freeze(e)}return e}var sh,yl,lh,Oa,Na=b(()=>{"use strict";sh=Object.freeze(["lite","standard","pro"]),yl=1,lh=Object.freeze(["WEB_AGENT_MODEL","WEB_AGENT_FALLBACK_MODELS","COMPUTER_USE_MODEL"]),Oa=bl({version:yl,defaultTier:"lite",tiers:{lite:{webagent:{primary:"google:gemini-3-flash-preview",fallbacks:["anthropic:claude-haiku-4-5","openai:gpt-5.6-luna"]}},standard:{webagent:{primary:"google:gemini-3.5-flash",fallbacks:["anthropic:claude-sonnet-5","openai:gpt-5.6-terra"]}},pro:{webagent:{primary:"anthropic:claude-opus-4-8",fallbacks:["openai:gpt-5.6-sol","anthropic:claude-opus-4-7"]}}},computerUse:{primary:"google:gemini-3-flash-preview",fallbacks:[]}})});var hh,vl=b(()=>{"use strict";Na();hh=Object.freeze([...Oa.tiers.standard.webagent.fallbacks])});var xl=b(()=>{"use strict"});var bt=b(()=>{"use strict";Bs();Gs();Ks();ol();rl();sl();Sn();ll();$n();Aa();cl();dl();ul();Mn();gl();fl();wl();vl();Na();xl()});import{stringify as n$}from"yaml";import La from"node:path";import{createHash as wh}from"crypto";import{parse as yh,stringify as Al}from"yaml";import{readFileSync as bh,existsSync as vh}from"fs";import{resolve as Da,dirname as xh}from"path";import{parse as kl,stringify as _h}from"yaml";function gh(e){let t=e.frame_path;return!t||t.length===0?"page":`page.frameLocator('${t[0]}')`}function fh(e){let t=e.xpath;return typeof t=="string"&&t.trim()?!t.startsWith("xpath=")&&!t.startsWith("/")&&!t.startsWith("//")?`xpath=//${t}`:t.startsWith("xpath=")?t:`xpath=${t}`:null}function Tl(e){let t=gh(e),i=e.locator;if(typeof i=="string"&&i.trim())return i=i.trim(),i.endsWith("first()")?`${t}.${i}`:`${t}.${i}.first()`;let n=fh(e);if(n){let a=JSON.stringify(n);return`${t}.locator(${a}).first()`}return null}function M(e,t){ne.set(e,t)}function Ye(e,t,i=[]){let n=[...i];return t.locator?n.push(`locator: ${JSON.stringify(t.locator)}`):t.xpath&&n.push(`xpath: ${JSON.stringify(t.xpath)}`),t.frame_path&&t.frame_path.length>0&&n.push(`frame_path: ${JSON.stringify(t.frame_path)}`),n.length===0?[`await agent.execAction("${e}", page, {});`]:[`await agent.execAction("${e}", page, {`,...n.map(a=>` ${a},`),"});"]}function Ra(e,t){let i=t.action_data?.kwargs||{},n=[];return typeof i.relative_x=="number"&&typeof i.relative_y=="number"?(n.push(`action_data: { kwargs: { relative_x: ${i.relative_x}, relative_y: ${i.relative_y} } }`),t.locator?n.push(`locator: ${JSON.stringify(t.locator)}`):t.xpath&&n.push(`xpath: ${JSON.stringify(t.xpath)}`),t.frame_path&&t.frame_path.length>0&&n.push(`frame_path: ${JSON.stringify(t.frame_path)}`)):typeof i.x=="number"&&typeof i.y=="number"&&n.push(`action_data: { kwargs: { x: ${i.x}, y: ${i.y} } }`),[`await agent.execAction("${e}", page, {`,...n.map(a=>` ${a},`),"});"]}function _l(e){let t=e.functionName;if(!t)return null;let i=Array.isArray(e.args)?e.args.map(String):Array.isArray(e.parameterValues)?e.parameterValues.map(String):[];if(i.length===0)return`await ${t}()`;let n=["page","testContext","request","agent"],a=["undefined","null","true","false"],o=i.map(r=>n.includes(r)||a.includes(r)||/^-?\d+(\.\d+)?$/.test(r)?r:r.startsWith("$")?`agent.agentServices.readVariable('${r.substring(1)}')`:`"${r}"`);return`await ${t}(${o.join(", ")})`}function $l(e,t,i){let n={expandingPaths:new Set([Da(t)]),depth:0,referencedPaths:new Set,basePath:i},a={...e};Array.isArray(a.statements)&&(a.statements=Ue(a.statements,t,n)),Array.isArray(a.teardown)&&(a.teardown=Ue(a.teardown,t,n));for(let o of["beforeAll","afterAll","beforeEach","afterEach"])Array.isArray(a[o])&&(a[o]=Ue(a[o],t,n));return{doc:a,referencedTemplatePaths:Array.from(n.referencedPaths)}}function Ue(e,t,i){let n=[];for(let a of e)if(kh(a)){let o=Sh(a,t,i);n.push(o)}else n.push(Eh(a,t,i));return n}function kh(e){return typeof e=="object"&&e!==null&&typeof e.template=="string"}function Sh(e,t,i){if(i.depth>=Sl)throw new Error(`Template expansion exceeded maximum depth of ${Sl}. Check for deeply nested or circular template references.`);let n=Da(xh(t),e.template),a=!vh(n)&&i.basePath?Da(i.basePath,e.template):n;if(i.expandingPaths.has(a))throw new Error(`Circular template reference detected: ${a} is already being expanded. Stack: ${Array.from(i.expandingPaths).join(" \u2192 ")} \u2192 ${a}`);i.referencedPaths.add(a);let o;try{o=bh(a,"utf-8")}catch(w){throw new Error(`Failed to read template file: ${a} (referenced from ${t}): ${w.message}`)}let r=kl(o);if(!r||typeof r!="object")throw new Error(`Invalid template file: ${a} \u2014 expected a YAML object`);let s=r.params||[],l=e.params||{};for(let w of s)if(!(w in l))throw new Error(`Template ${e.template} requires param "${w}" but it was not provided. Required params: [${s.join(", ")}]`);let c=r.statements;if(!Array.isArray(c))throw new Error(`Template ${e.template} must have a "statements" array`);if(Object.keys(l).length>0){let g=_h(c);for(let[y,h]of Object.entries(l))g=g.split(`<<${y}>>`).join(String(h));c=kl(g)}let d={expandingPaths:new Set([...i.expandingPaths,a]),depth:i.depth+1,referencedPaths:i.referencedPaths},u=Ue(c,a,d),p={STEP:r.name||e.template.replace(/\.yaml$/,"").split("/").pop()||e.template,template_path:e.template,statements:u};return Object.keys(l).length>0&&(p.template_params=l),p}function Eh(e,t,i){if(typeof e!="object"||e===null)return e;let n={...e};return Array.isArray(n.statements)&&(n.statements=Ue(n.statements,t,i)),Array.isArray(n.THEN)&&(n.THEN=Ue(n.THEN,t,i)),Array.isArray(n.ELSE)&&(n.ELSE=Ue(n.ELSE,t,i)),Array.isArray(n.DO)&&(n.DO=Ue(n.DO,t,i)),n}function Il(e,t,i){let n=yh(e),a=n?.name,o=n?.tags,r=n?.use;if(n&&(n.name!==void 0||n.tags!==void 0||n.use!==void 0)&&(delete n.name,delete n.tags,delete n.use),n?.suite){if(n.goal||n.statements)throw new Ml('YAML file cannot have both "suite" and top-level "goal"/"statements". Use either suite format or single-test format.');return Ah(n,a,o,r,t,i)}return Th(n,a,o,r,t,i)}function Th(e,t,i,n,a,o){let r=e?.beforeEach,s=e?.afterEach,l=Cl(e?.parameters),c=e?.timeout,d=e?.skip,u=e?.fail,m=e?.only,p=e?.slow;if(e&&(delete e.beforeEach,delete e.afterEach,delete e.parameters,delete e.timeout,delete e.skip,delete e.fail,delete e.only,delete e.slow),e?.url)throw new Ml(`The "url" field is not supported in local YAML tests. Use "base_url: ${e.url}" and add "- URL: /" as the first statement instead.`);e&&!e.goal&&t&&(e.goal=t);let w=[];if(a&&e&&typeof e=="object"){let h=$l(e,a,o);e=h.doc,w=h.referencedTemplatePaths}let g=Al(e),y=Me(g);return a&&(Be(y.statements??[],a,"main"),y.teardown&&Be(y.teardown,a,"teardown")),{testFlow:y,name:t,tags:i,use:n,beforeEach:r,afterEach:s,parameters:l,timeout:c,skip:d,fail:u,only:m,slow:p,referencedTemplatePaths:w}}function Ah(e,t,i,n,a,o){let r=e.suite;if(!Array.isArray(r.tests)||r.tests.length===0)throw new Error('Suite must have a non-empty "tests" array.');let s=r.beforeAll,l=r.afterAll,c=r.beforeEach,d=r.afterEach,u=[],m=r.tests.map((g,y)=>{if(!g.name)throw new Error('Each test in a suite must have a "name" field.');if(!Array.isArray(g.statements)||g.statements.length===0)throw new Error(`Suite test "${g.name}" must have a non-empty "statements" array.`);let h={goal:g.name,statements:g.statements};g.teardown&&(h.teardown=g.teardown);let v=[],_=h;if(a&&typeof h=="object"){let I=$l(h,a,o);_=I.doc,v=I.referencedTemplatePaths,u.push(...v)}let x=Al(_),E=Me(x);if(a){let I=`tests[${y}]`;Be(E.statements??[],a,I),E.teardown&&Be(E.teardown,a,`${I}.teardown`)}let $=Cl(g.parameters);return{testFlow:E,name:g.name,tags:Array.isArray(g.tags)?g.tags:void 0,parameters:$,timeout:g.timeout,skip:g.skip,fail:g.fail,only:g.only,slow:g.slow}}),p=r.base_url,w=p?{...n,baseURL:p}:n;return{suite:{beforeAll:s,afterAll:l,beforeEach:c,afterEach:d,tests:m},name:t,tags:i,use:w,referencedTemplatePaths:u}}function Cl(e){if(!(!Array.isArray(e)||e.length===0))return e.map((t,i)=>{if(!t.name)throw new Error(`Parameter set at index ${i} must have a "name" field.`);if(!t.values||typeof t.values!="object")throw new Error(`Parameter set "${t.name}" must have a "values" object.`);return{name:t.name,values:t.values}})}function Be(e,t,i){for(let n=0;n<e.length;n++){let a=e[n],o=`${i}.${n}`,r=a.description||"";if(a.uid=$h(t,o,r),a.type===Je.STEP)Be(a.statements,t,o);else if(a.type===Je.IF_ELSE){let s=a;Be(s.then,t,`${o}.then`),s.else&&Be(s.else,t,`${o}.else`)}else a.type===Je.WHILE_LOOP&&Be(a.body,t,`${o}.body`)}}function $h(e,t,i){let n=wh("sha256").update(`${e}:${t}:${i}`).digest("hex");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20,32)}`}var El,ne,Sl,Ml,Pl=b(()=>{"use strict";bt();bt();bt();bt();El=5e3;ne=new Map;M("click",e=>{let t=Tl(e);if(!t)return['await agent.execAction("click", page, {});'];let i=e.action_data?.kwargs?.timeout_ms??El;return[`await ${t}.click({ timeout: ${i} });`]});M("click_element",ne.get("click"));M("click_element_by_index",ne.get("click"));M("double_click",e=>Ye("double_click",e));M("double_click_on_element",ne.get("double_click"));M("right_click",e=>Ye("right_click",e));M("right_click_on_element",ne.get("right_click"));M("hover",e=>Ye("hover",e));M("hover_element_by_index",ne.get("hover"));M("input_text",e=>{let t=e.action_data?.kwargs?.text??e.action_data?.kwargs?.value??"";return Ye("input_text",e,[`action_data: { kwargs: { text: ${JSON.stringify(t)} } }`])});M("fill",ne.get("input_text"));M("clear_input",e=>Ye("clear_input",e));M("press",e=>{let t=e.action_data?.kwargs?.keys;return[`await page.keyboard.press(${JSON.stringify(t)});`]});M("send_keys",ne.get("press"));M("send_keys_on_element",e=>{let t=Tl(e),i=e.action_data?.kwargs?.keys||"";if(!t)return['await agent.execAction("send_keys_on_element", page, {',` action_data: { kwargs: { keys: ${JSON.stringify(i)} } },`,"});"];let n=e.action_data?.kwargs?.timeout_ms??El;return[`await ${t}.press(${JSON.stringify(i)}, { timeout: ${n} });`]});M("select_dropdown_option",e=>{let t=e.action_data?.kwargs?.text||e.action_data?.kwargs?.option||"";return Ye("select_dropdown_option",e,[`action_data: { kwargs: { text: ${JSON.stringify(t)} } }`])});M("scroll",e=>{let t=e.action_data?.kwargs?.down??!0;return[`await page.evaluate('window.scrollBy(0, window.innerHeight * ${(e.action_data?.kwargs?.num_pages??1)*(t?1:-1)})');`]});M("scroll_down",ne.get("scroll"));M("scroll_up",ne.get("scroll"));M("scroll_element",ne.get("scroll"));M("scroll_to_text",e=>{let t=e.action_data?.kwargs?.text||"";return[`await page.getByText(${JSON.stringify(t)}, { exact: false }).first().scrollIntoViewIfNeeded();`]});M("scroll_on_element",e=>Ye("scroll_on_element",e,[`action_data: { kwargs: ${JSON.stringify(e.action_data?.kwargs||{})} }`]));M("go_to_url",e=>{let t=e.action_data?.kwargs?.url||"";return e.action_data?.kwargs?.new_tab===!0?['await agent.execAction("go_to_url", page, {',` action_data: { kwargs: { url: ${JSON.stringify(t)}, new_tab: true } },`,"});"]:['await agent.execAction("go_to_url", page, {',` action_data: { kwargs: { url: ${JSON.stringify(t)} } },`,"});"]});M("open_tab",ne.get("go_to_url"));M("go_back",()=>['await agent.execAction("go_back", page, {});']);M("reload_page",()=>['await agent.execAction("reload_page", page, {});']);M("wait",e=>[`await page.waitForTimeout(${(e.action_data?.kwargs?.seconds||1)*1e3});`]);M("wait_for_page_ready",()=>["await page.waitForLoadState('domcontentloaded');"]);M("verify",(e,t)=>{let i=e.action_data?.kwargs,n=typeof i?.code=="string",a=n?i?.statement||e.action_description:e.action_description||i?.statement;if(n&&a){let r=i.code.split(`
4304
4326
  `),s=JSON.stringify(a);return["{ const _t = Date.now(); try {",...r.map(l=>` ${l}`),` console.log(\`[VERIFY:JS] \u2713 \${((Date.now()-_t)/1000).toFixed(1)}s: ${s}\`);`,"} catch (_e) {",` console.log(\`[VERIFY:JS\u2192AI] JS failed \${((Date.now()-_t)/1000).toFixed(1)}s: (\${_e instanceof Error ? _e.message : String(_e)}), falling back to AI: ${s}\`);`,` await agent.assert(page, ${s}, ${JSON.stringify(t||"")});`,"} }"]}return n?i.code.split(`
4305
4327
  `):a?[`await agent.assert(page, ${JSON.stringify(a)}, ${JSON.stringify(t||"")});`]:["// Skipping verify: missing statement or code"]});M("ai_assert",ne.get("verify"));M("assert",ne.get("verify"));M("ai_action",(e,t)=>{let i=e.action_data?.kwargs?.statement;if(!i)return["// Skipping ai_action: missing statement"];let n=JSON.stringify(i),a=e.action_data?.kwargs?.use_pure_vision;return[`await agent.execute(page, ${n}, '${t||""}', ${a});`]});M("ai_step",(e,t)=>{let i=e.action_data?.kwargs?.statement;return i?[`await agent.run(page, ${JSON.stringify(i)}, '${t||""}');`]:["// Skipping ai_step: missing statement"]});M("ai_extract",(e,t)=>{let i=e.action_data?.kwargs?.element_description,n=e.action_data?.kwargs?.variable_name;if(!i||!n)return["// Skipping ai_extract: missing element_description or variable_name"];let a=JSON.stringify(i),o=JSON.stringify(n);return[`await agent.extract(page, ${a}, ${o}, '${t||""}');`]});M("ai_wait_until",(e,t)=>{let i=e.action_data?.kwargs?.condition,n=e.action_data?.kwargs?.timeout_seconds||60;if(!i)return["// Skipping ai_wait_until: missing condition"];if(e.action_data?.kwargs?.condition_type==="JS_CODE"){let o=e.action_data?.kwargs?.js,r=typeof o=="string"?o:i,s=typeof o=="string"?`, ${JSON.stringify(i)}`:"";return[`await agent.waitForJs(page, async () => (${r}), ${n}, '${t||""}'${s});`]}return[`await agent.waitUntilCondition(page, ${JSON.stringify(i)}, ${n}, '${t||""}');`]});M("save_variable",e=>{let t=e.action_data?.kwargs?.name||"",i=e.action_data?.kwargs?.value;return['await agent.execAction("save_variable", page, {',` action_data: { kwargs: { name: ${JSON.stringify(t)}, value: ${JSON.stringify(i)} } },`,"});"]});M("js_code",e=>{let t=e.action_data?.kwargs?.code;if(!t)return["// Skipping js_code: missing code"];let i=["{"],n=t.split(`
4306
4328
  `);for(let a of n)i.push(` ${a}`);return i.push("}"),i});M("function",(e,t,i)=>{let n=e.action_data?.kwargs||{},a=n.functionName;if(a&&a.includes("#")){let[r,s]=a.split("#");if(r&&s){let l=r.replace(/\.(ts|js|mjs)$/,"");if(La.isAbsolute(r))return[`throw new Error(${JSON.stringify(`Absolute paths are not supported in call: references. Use a path relative to the project root (got: "${r}")`)})`];if(!l.startsWith(".")&&i?.projectRoot&&i?.yamlDir){let m=La.resolve(i.projectRoot,l),p=La.relative(i.yamlDir,m).replace(/\\/g,"/");l=p.startsWith("..")?p:"./"+p}let c=`import { ${s} } from '${l}';`;i?.imports?.add(c);let d={...n,functionName:s},u=_l(d);return u?[u.endsWith(";")?u:`${u};`]:["// Skipping function: invalid export pattern"]}}let o=_l(n);return o?[o.endsWith(";")?o:`${o};`]:["// Skipping function: missing functionName"]});M("generate_2fa_code",e=>{let t=e.action_data?.kwargs?.otp_secret_key||"";return['await agent.execAction("generate_2fa_code", page, {',` action_data: { kwargs: { otp_secret_key: ${JSON.stringify(t)} } },`,"});"]});M("upload_file",e=>{let t=e.action_data?.kwargs||{},i=[],n={};return t.paths?n.paths=t.paths:t.path&&(n.path=t.path),t.use_file_input&&(n.use_file_input=!0),i.push(`action_data: { kwargs: ${JSON.stringify(n)} }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`),['await agent.execAction("upload_file", page, {',...i.map(a=>` ${a},`),"});"]});M("wait_for_download_complete",e=>['await agent.execAction("wait_for_download_complete", page, {',` action_data: { kwargs: { timeout_seconds: ${e.action_data?.kwargs?.timeout_seconds||10} } },`,"});"]);M("switch_tab",e=>['await agent.execAction("switch_tab", page, {',` action_data: { kwargs: { page_id: ${e.action_data?.kwargs?.page_id??e.action_data?.kwargs?.tab_index??0} } },`,"});"]);M("close_tab",e=>{let t=e.action_data?.kwargs?.page_id;return t=t??e.action_data?.kwargs?.index,['await agent.execAction("close_tab", page, {',` action_data: { kwargs: { page_id: ${t} } },`,"});"]});M("set_date_for_native_date_picker",e=>{let t=e.action_data?.kwargs?.date??"",i=[];return i.push(`action_data: { kwargs: { date: ${JSON.stringify(t)} } }`),e.locator?i.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&i.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&i.push(`frame_path: ${JSON.stringify(e.frame_path)}`),['await agent.execAction("set_date_for_native_date_picker", page, {',...i.map(n=>` ${n},`),"});"]});M("done",()=>["// Done - no action needed"]);M("click_by_coordinates",e=>Ra("click_by_coordinates",e));M("right_click_by_coordinates",e=>Ra("right_click_by_coordinates",e));M("double_click_by_coordinates",e=>Ra("double_click_by_coordinates",e));M("drag_drop",e=>{let t=e.action_data?.kwargs||{},i={};typeof t.relative_x=="number"&&(i.relative_x=t.relative_x),typeof t.relative_y=="number"&&(i.relative_y=t.relative_y),typeof t.delta_x=="number"&&(i.delta_x=t.delta_x),typeof t.delta_y=="number"&&(i.delta_y=t.delta_y),typeof t.coord_source_x=="number"&&(i.coord_source_x=t.coord_source_x),typeof t.coord_source_y=="number"&&(i.coord_source_y=t.coord_source_y),typeof t.coord_target_x=="number"&&(i.coord_target_x=t.coord_target_x),typeof t.coord_target_y=="number"&&(i.coord_target_y=t.coord_target_y);let n=[`action_data: { kwargs: ${JSON.stringify(i)} }`];return e.locator?n.push(`locator: ${JSON.stringify(e.locator)}`):e.xpath&&n.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&n.push(`frame_path: ${JSON.stringify(e.frame_path)}`),['await agent.execAction("drag_drop", page, {',...n.map(a=>` ${a},`),"});"]});M("get_dropdown_options",e=>{let t=[];return e.xpath&&t.push(`xpath: ${JSON.stringify(e.xpath)}`),e.frame_path&&e.frame_path.length>0&&t.push(`frame_path: ${JSON.stringify(e.frame_path)}`),t.length===0?['await agent.execAction("get_dropdown_options", page, {});']:['await agent.execAction("get_dropdown_options", page, {',...t.map(i=>` ${i},`),"});"]});M("extract_email_content",e=>{let t=e.action_data?.kwargs||{};return['await agent.execAction("extract_email_content", page, {',` action_data: { kwargs: ${JSON.stringify(t)} },`,"});"]});M("js_action",e=>{let t=e.action_data?.kwargs?.code;return t?t.split(`
4307
- `):["// Skipping js_action: missing code"]});Sl=5;Ml=class extends Error{constructor(e){super(e),this.name="YamlValidationError"}}});var Nl={};xt(Nl,{createTestFlowRouter:()=>Ch});import{Router as Mh}from"express";import*as L from"fs/promises";import*as P from"path";import{stringify as ki,parse as vt}from"yaml";function xi(e){return e.map(t=>{if(t.type==="ACTION"&&t.action_entity){let i=t.action_entity,n=i.action_data??i.action,a=n?.kwargs?Object.fromEntries(Object.entries(n.kwargs).filter(([r])=>r!=="element_index")):n?.kwargs,o={...i};if(delete o.xpath,n&&a!==void 0){let r={...n,kwargs:a};i.action_data?o.action_data=r:o.action=r}return{...t,action_entity:o}}return t.type==="STEP"?{...t,statements:xi(t.statements)}:t.type==="IF_ELSE"?{...t,then:xi(t.then),...t.else?{else:xi(t.else)}:{}}:t.type==="WHILE_LOOP"?{...t,body:xi(t.body)}:t})}function Ye(e){if(!e||e.length===0)return[];let i=ki({goal:"_hook",statements:e});return Me(i).statements??[]}async function Ol(e){try{let t=await L.readdir(e,{withFileTypes:!0});for(let i of t)if(!(i.name==="node_modules"||i.name.startsWith("."))&&(i.isFile()&&i.name.endsWith(".test.yaml")||i.isDirectory()&&await Ol(P.join(e,i.name))))return!0}catch{}return!1}function In(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e.charCodeAt(i),t=Math.imul(t,16777619)>>>0;return t%2147483647+1}async function Ih(e){let t=new Map,i;try{i=await L.readdir(e)}catch(n){if(n.code==="ENOENT")return t;throw n}for(let n of i.filter(a=>a.endsWith(".yaml")))try{let a=P.join(e,n),r=vt(await L.readFile(a,"utf-8"))?.name??P.basename(n,".yaml");t.set(In(r),`templates/${n}`)}catch{}return t}function Fa(e,t){if(Array.isArray(e))return e.map(o=>Fa(o,t));if(!e||typeof e!="object")return e;let i=e,n={};for(let[o,r]of Object.entries(i))n[o]=Fa(r,t);let a=typeof i.reference_id=="number"?i.reference_id:void 0;if(a!==void 0&&typeof n.template_path!="string"){let o=t.get(a);o&&(n.template_path=o,delete n.reference_id)}return n}function Cn(e){return En({statements:e}).statements}async function _i(e,t){for(let i of e)if(i.type==="STEP"){if(i.template_path&&i.statements.length>0){let n=P.join(t,i.template_path);try{let a=vt(await L.readFile(n,"utf-8"))??{};a.statements=Cn(i.statements),await L.writeFile(n,ki(a),"utf-8")}catch{}}await _i(i.statements,t)}else i.type==="IF_ELSE"?(await _i(i.then,t),i.else&&await _i(i.else,t)):i.type==="WHILE_LOOP"&&await _i(i.body,t)}function Ch(e){let{initialDir:t,initialFile:i,projectRoot:n,onFileSelected:a}=e,o=Mh();function r(){return P.join(n??t,"fixtures")}o.get("/api/files",async(l,c)=>{try{let d=typeof l.query.dir=="string"?l.query.dir:t,u=P.resolve(d),m=await L.readdir(u,{withFileTypes:!0}),p=[];for(let g of m)if(g.name!=="node_modules"&&!g.name.startsWith("."))if(g.isDirectory()){let y=P.join(u,g.name);await Ol(y)&&p.push({name:g.name,type:"directory",path:y})}else g.isFile()&&g.name.endsWith(".test.yaml")&&p.push({name:g.name,type:"file",path:P.join(u,g.name)});p.sort((g,y)=>g.type!==y.type?g.type==="directory"?-1:1:g.name.localeCompare(y.name));let w=P.dirname(u);c.json({dir:u,parent:w!==u?w:null,entries:p,initialFile:i??null,projectRoot:n??t})}catch(d){console.error("[debugger] Error listing files:",d),c.status(500).json({error:d.message})}});function s(l){if(typeof l=="string"&&l){let c=P.resolve(l);return c.endsWith(".test.yaml")?{filePath:c}:{error:"File must be a .test.yaml file"}}return i?{filePath:i}:{error:"No file specified. Pass ?file= parameter."}}return o.get("/api/test-flow",async(l,c)=>{let d=s(l.query.file);if("error"in d)return c.status(400).json({error:d.error});let u=d.filePath;try{a?.(u);let m=await L.readFile(u,"utf-8"),p=await L.stat(u),w=Ca(m),g=Il(m,u,n);if(g.suite){let y=g.suite,h={tests:y.tests.map(x=>({name:x.name,statements:x.testFlow.statements??[],teardown:x.testFlow.teardown,skip:x.skip,timeout:x.timeout,fail:x.fail,only:x.only,slow:x.slow})),beforeAll:Ye(y.beforeAll),afterAll:Ye(y.afterAll),beforeEach:Ye(y.beforeEach),afterEach:Ye(y.afterEach)},b={version:"1.3.0",baseURL:g.use?.baseURL,testGroup:h};c.json({isSuite:!0,testFlow:b,metadata:w,name:g.name,tags:g.tags,use:g.use,filePath:u,fileName:P.basename(u),lastModified:p.mtimeMs})}else{let y=g.testFlow;Tn(m,y),c.json({isSuite:!1,testFlow:y,metadata:w,name:g.name,tags:g.tags,use:g.use,parameters:g.parameters,filePath:u,fileName:P.basename(u),lastModified:p.mtimeMs})}}catch(m){if(m.code==="ENOENT")return c.status(404).json({error:`File not found: ${u}`});console.error("[debugger] Error loading test flow:",m),c.status(500).json({error:m.message})}}),o.put("/api/test-flow",async(l,c)=>{try{let d=s(l.query.file);if("error"in d)return c.status(400).json({error:d.error});let u=d.filePath,{testFlow:m,metadata:p}=l.body;if(!m)return c.status(400).json({error:"testFlow is required"});let w=P.join(n??t,"templates"),g=await Ih(w),y=Fa(m,g),h=xi(y.statements??[]),b={...y,statements:h},x=n??t,S=[b.statements??[],b.teardown??[],...b.testGroup?.tests?.flatMap(D=>[D.statements,...D.teardown?[D.teardown]:[]])??[],...b.testGroup?.beforeEach?[b.testGroup.beforeEach]:[],...b.testGroup?.afterEach?[b.testGroup.afterEach]:[]];for(let D of S)await _i(D,x);let E=Ma(b,p),$=u+".tmp";await L.writeFile($,E,"utf-8"),await L.rename($,u);let O=await L.stat(u);c.json({success:!0,lastModified:O.mtimeMs})}catch(d){console.error("[debugger] Error saving test flow:",d),c.status(500).json({error:d.message})}}),o.get("/api/fixtures",async(l,c)=>{try{let d=r();try{let m=(await L.readdir(d,{withFileTypes:!0})).filter(p=>p.isFile()).map(p=>p.name).sort();c.json({files:m,dir:d})}catch(u){if(u.code==="ENOENT")c.json({files:[],dir:d});else throw u}}catch(d){console.error("[debugger] Error listing fixtures:",d),c.status(500).json({error:d.message})}}),o.post("/api/fixtures",async(l,c)=>{try{let d=r();await L.mkdir(d,{recursive:!0});let{name:u,content:m}=l.body;if(!u||!m)return c.status(400).json({error:"name and content are required"});let p=P.basename(u);if(!p)return c.status(400).json({error:"Invalid file name"});let w=P.join(d,p);await L.writeFile(w,Buffer.from(m,"base64")),c.json({fileName:p})}catch(d){console.error("[debugger] Error saving fixture:",d),c.status(500).json({error:d.message})}}),o.get("/api/functions",async(l,c)=>{let d=P.join(n??t,"helpers"),u;try{u=await L.readdir(d)}catch(g){return g.code==="ENOENT"?c.json([]):(console.error("[debugger] Error reading helpers dir:",g),c.status(500).json({error:g.message}))}let m=u.filter(g=>/\.(ts|js|mjs)$/.test(g)),p=[],w=1;for(let g of m){let y=await L.readFile(P.join(d,g),"utf-8"),h=/export\s+async\s+function\s+(\w+)\s*(\([^)]*\))/g,b;for(;(b=h.exec(y))!==null;){let[,x,S]=b,E=S.replace(/\s*:\s*[^,)]+/g,"");p.push({id:w++,name:`helpers/${g}#${x}`,description:"",status:"Active",code:`async function ${x}${E} {}`})}}c.json(p)}),o.get("/api/reusable-steps",async(l,c)=>{let d=P.join(n??t,"templates"),u;try{u=await L.readdir(d)}catch(w){return w.code==="ENOENT"?c.json([]):(console.error("[debugger] Error reading templates dir:",w),c.status(500).json({error:w.message}))}let m=u.filter(w=>w.endsWith(".yaml")).sort(),p=[];for(let w of m)try{let g=await L.readFile(P.join(d,w),"utf-8"),y=vt(g);if(!y||typeof y!="object")continue;let h=y.name??P.basename(w,".yaml"),b=y.description??"",x=Ye(y.statements);p.push({id:In(h),organizationId:"local",name:h,description:b,statements:x})}catch(g){console.error(`[debugger] Error parsing template ${w}:`,g)}c.json(p)}),o.post("/api/reusable-steps/exists/:name",async(l,c)=>{let d=P.join(n??t,"templates"),u=decodeURIComponent(l.params.name).toLowerCase(),m;try{m=await L.readdir(d)}catch(p){return p.code==="ENOENT"?c.json(!1):c.status(500).json({error:p.message})}for(let p of m.filter(w=>w.endsWith(".yaml")))try{let w=await L.readFile(P.join(d,p),"utf-8");if((vt(w)?.name??P.basename(p,".yaml")).toLowerCase()===u)return c.json(!0)}catch{}c.json(!1)}),o.post("/api/reusable-steps",async(l,c)=>{let d=P.join(n??t,"templates"),{reusableStep:u}=l.body??{};if(!u?.name||!Array.isArray(u.statements))return c.status(400).json({error:"reusableStep.name and reusableStep.statements are required"});await L.mkdir(d,{recursive:!0});let m=u.name.replace(/[/\\:*?"<>|]/g,"-").trim(),p=P.join(d,`${m}.yaml`),w={name:u.name,statements:Cn(u.statements)};u.description&&(w.description=u.description),await L.writeFile(p,ki(w),"utf-8"),c.json({id:In(u.name),organizationId:"local",name:u.name,description:u.description??"",statements:u.statements})}),o.put("/api/reusable-steps/:id/update",async(l,c)=>{let d=parseInt(l.params.id,10),u=P.join(n??t,"templates"),m;try{m=await L.readdir(u)}catch(p){return p.code==="ENOENT"?c.status(404).json({error:"Templates directory not found"}):c.status(500).json({error:p.message})}for(let p of m.filter(w=>w.endsWith(".yaml")))try{let w=P.join(u,p),g=vt(await L.readFile(w,"utf-8"))??{},y=g.name??P.basename(p,".yaml");if(In(y)!==d)continue;let h=l.body??{};return h.description!==void 0&&(g.description=h.description),h.statements!==void 0&&(g.statements=Cn(h.statements)),await L.writeFile(w,ki(g),"utf-8"),c.json({id:d,organizationId:"local",...g,statements:h.statements!==void 0?h.statements:Ye(g.statements)})}catch{}c.status(404).json({error:`Template with id ${d} not found`})}),o.put("/api/templates/:name",async(l,c)=>{let d=P.join(n??t,"templates"),u=decodeURIComponent(l.params.name),m;try{m=await L.readdir(d)}catch(p){return p.code==="ENOENT"?c.status(404).json({error:"Templates directory not found"}):c.status(500).json({error:p.message})}for(let p of m.filter(w=>w.endsWith(".yaml")))try{let w=P.join(d,p),g=vt(await L.readFile(w,"utf-8"))??{};if((g.name??P.basename(p,".yaml"))!==u)continue;let h=l.body??{};return h.name!==void 0&&(g.name=h.name),h.description!==void 0&&(g.description=h.description),h.statements!==void 0&&(g.statements=Cn(h.statements)),await L.writeFile(w,ki(g),"utf-8"),c.json({organizationId:"local",...g,statements:h.statements!==void 0?h.statements:Ye(g.statements)})}catch{}c.status(404).json({error:`Template "${u}" not found`})}),o.get("/api/test-results",async(l,c)=>{let d=s(l.query.file);if("error"in d)return c.status(400).json({error:d.error});let u=n??t,m=P.basename(d.filePath,".test.yaml"),p=P.join(u,".shiplight","artifacts",m),w=[],g=null;try{let y=await L.readdir(p,{withFileTypes:!0});for(let h of y)if(h.isDirectory()){let b=P.join(p,h.name),x=await L.readdir(b);for(let S of x.filter(E=>/\.(png|jpe?g|webp)$/i.test(E))){let E=P.relative(p,P.join(b,S)),$=h.name.match(/^(.+?)_(before|after)$/),O=$?$[1]:h.name,D=$?$[2]:"screenshot";w.push({url:`/api/report-assets/${m}/${E}`,label:D,stepId:O})}}else/\.(webm|mp4)$/i.test(h.name)&&(g||(g=`/api/report-assets/${m}/${h.name}`));w.sort((h,b)=>h.stepId!==b.stepId?(h.stepId??"").localeCompare(b.stepId??""):h.label.localeCompare(b.label))}catch{}if(w.length===0&&!g)return c.status(404).json({error:"No test results found"});c.json({videoPath:g,screenshots:w})}),o}var Ll=v(()=>{"use strict";yt();Pl()});var Dl={};xt(Dl,{createIntRunnerRouter:()=>Oh});import{Router as Ph}from"express";function Oh(e){let t=Ph();return t.get("/api/browser-cdp",async(i,n)=>{let a=e.getCdpEndpoint();if(!a)return n.status(404).json({error:"No browser running. Start a debug session first."});n.json({cdpUrl:a})}),t.post("/api/int-runner/create-session",async(i,n)=>{try{let a=i.body.startingUrl||i.body.testFlow?.url||i.body.urlOverride,o=i.body.testFilePath,r=await e.createSession({startingUrl:a,testFilePath:o});n.json({status:"success",sessionId:r.sessionId,searchParams:""})}catch(a){console.error("[debugger] create-session error:",a),n.status(500).json({status:"error",message:a.message})}}),t.post("/api/int-runner/login",async(i,n)=>{try{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});let o=await e.executeLogin(a.sessionId);n.json(o)}catch(a){console.error("[debugger] login error:",a),n.status(500).json({status:"error",details:a.message})}}),t.post("/api/int-runner/liveview-url",async(i,n)=>{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});n.json({liveviewUrl:"",browserWsUrl:""})}),t.post("/api/int-runner/end-debug",async(i,n)=>{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});n.json({status:"success"})}),t.post("/api/int-runner/start-debug",async(i,n)=>{try{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});let o=await e.startDebug(a.sessionId);n.json({status:"success",...o})}catch(a){console.error("[debugger] start-debug error:",a),n.status(500).json({status:"error",message:a.message})}}),t.post("/api/int-runner/execute-action",async(i,n)=>{try{let{session:a,actionEntity:o,stepId:r,withSelfHealing:s,stmtUid:l,executionHistory:c}=i.body;if(!a?.sessionId||!o)return n.status(400).json({status:"error",message:"Missing session or actionEntity"});let d=await e.executeAction(a.sessionId,o,r,{withSelfHealing:s,stmtUid:l,executionHistory:c});n.json(d)}catch(a){console.error("[debugger] execute-action error:",a),n.status(500).json({status:"error",details:a.message})}}),t.post("/api/int-runner/run-step",async(i,n)=>{let{session:a,statement:o,stepId:r,executionHistory:s}=i.body;if(!a?.sessionId||!o)return n.status(400).json({success:!1,message:"Session and statement required"});n.setHeader("Content-Type","text/event-stream"),n.setHeader("Cache-Control","no-cache"),n.setHeader("Connection","keep-alive"),n.flushHeaders();let l=c=>{n.write(`data: ${JSON.stringify(c)}
4329
+ `):["// Skipping js_action: missing code"]});Sl=5;Ml=class extends Error{constructor(e){super(e),this.name="YamlValidationError"}}});var Nl={};xt(Nl,{createTestFlowRouter:()=>Ch});import{Router as Mh}from"express";import*as L from"fs/promises";import*as O from"path";import{stringify as ki,parse as vt}from"yaml";function xi(e){return e.map(t=>{if(t.type==="ACTION"&&t.action_entity){let i=t.action_entity,n=i.action_data??i.action,a=n?.kwargs?Object.fromEntries(Object.entries(n.kwargs).filter(([r])=>r!=="element_index")):n?.kwargs,o={...i};if(delete o.xpath,n&&a!==void 0){let r={...n,kwargs:a};i.action_data?o.action_data=r:o.action=r}return{...t,action_entity:o}}return t.type==="STEP"?{...t,statements:xi(t.statements)}:t.type==="IF_ELSE"?{...t,then:xi(t.then),...t.else?{else:xi(t.else)}:{}}:t.type==="WHILE_LOOP"?{...t,body:xi(t.body)}:t})}function qe(e){if(!e||e.length===0)return[];let i=ki({goal:"_hook",statements:e});return Me(i).statements??[]}async function Ol(e){try{let t=await L.readdir(e,{withFileTypes:!0});for(let i of t)if(!(i.name==="node_modules"||i.name.startsWith("."))&&(i.isFile()&&i.name.endsWith(".test.yaml")||i.isDirectory()&&await Ol(O.join(e,i.name))))return!0}catch{}return!1}function In(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e.charCodeAt(i),t=Math.imul(t,16777619)>>>0;return t%2147483647+1}async function Ih(e){let t=new Map,i;try{i=await L.readdir(e)}catch(n){if(n.code==="ENOENT")return t;throw n}for(let n of i.filter(a=>a.endsWith(".yaml")))try{let a=O.join(e,n),r=vt(await L.readFile(a,"utf-8"))?.name??O.basename(n,".yaml");t.set(In(r),`templates/${n}`)}catch{}return t}function Fa(e,t){if(Array.isArray(e))return e.map(o=>Fa(o,t));if(!e||typeof e!="object")return e;let i=e,n={};for(let[o,r]of Object.entries(i))n[o]=Fa(r,t);let a=typeof i.reference_id=="number"?i.reference_id:void 0;if(a!==void 0&&typeof n.template_path!="string"){let o=t.get(a);o&&(n.template_path=o,delete n.reference_id)}return n}function Cn(e){return Tn({statements:e}).statements}async function _i(e,t){for(let i of e)if(i.type==="STEP"){if(i.template_path&&i.statements.length>0){let n=O.join(t,i.template_path);try{let a=vt(await L.readFile(n,"utf-8"))??{};a.statements=Cn(i.statements),await L.writeFile(n,ki(a),"utf-8")}catch{}}await _i(i.statements,t)}else i.type==="IF_ELSE"?(await _i(i.then,t),i.else&&await _i(i.else,t)):i.type==="WHILE_LOOP"&&await _i(i.body,t)}function Ch(e){let{initialDir:t,initialFile:i,projectRoot:n,onFileSelected:a}=e,o=Mh();function r(){return O.join(n??t,"fixtures")}o.get("/api/files",async(l,c)=>{try{let d=typeof l.query.dir=="string"?l.query.dir:t,u=O.resolve(d),m=await L.readdir(u,{withFileTypes:!0}),p=[];for(let g of m)if(g.name!=="node_modules"&&!g.name.startsWith("."))if(g.isDirectory()){let y=O.join(u,g.name);await Ol(y)&&p.push({name:g.name,type:"directory",path:y})}else g.isFile()&&g.name.endsWith(".test.yaml")&&p.push({name:g.name,type:"file",path:O.join(u,g.name)});p.sort((g,y)=>g.type!==y.type?g.type==="directory"?-1:1:g.name.localeCompare(y.name));let w=O.dirname(u);c.json({dir:u,parent:w!==u?w:null,entries:p,initialFile:i??null,projectRoot:n??t})}catch(d){console.error("[debugger] Error listing files:",d),c.status(500).json({error:d.message})}});function s(l){if(typeof l=="string"&&l){let c=O.resolve(l);return c.endsWith(".test.yaml")?{filePath:c}:{error:"File must be a .test.yaml file"}}return i?{filePath:i}:{error:"No file specified. Pass ?file= parameter."}}return o.get("/api/test-flow",async(l,c)=>{let d=s(l.query.file);if("error"in d)return c.status(400).json({error:d.error});let u=d.filePath;try{a?.(u);let m=await L.readFile(u,"utf-8"),p=await L.stat(u),w=Ca(m),g=Il(m,u,n);if(g.suite){let y=g.suite,h={tests:y.tests.map(_=>({name:_.name,statements:_.testFlow.statements??[],teardown:_.testFlow.teardown,skip:_.skip,timeout:_.timeout,fail:_.fail,only:_.only,slow:_.slow})),beforeAll:qe(y.beforeAll),afterAll:qe(y.afterAll),beforeEach:qe(y.beforeEach),afterEach:qe(y.afterEach)},v={version:"1.3.0",baseURL:g.use?.baseURL,testGroup:h};c.json({isSuite:!0,testFlow:v,metadata:w,name:g.name,tags:g.tags,use:g.use,filePath:u,fileName:O.basename(u),lastModified:p.mtimeMs})}else{let y=g.testFlow;An(m,y),c.json({isSuite:!1,testFlow:y,metadata:w,name:g.name,tags:g.tags,use:g.use,parameters:g.parameters,filePath:u,fileName:O.basename(u),lastModified:p.mtimeMs})}}catch(m){if(m.code==="ENOENT")return c.status(404).json({error:`File not found: ${u}`});console.error("[debugger] Error loading test flow:",m),c.status(500).json({error:m.message})}}),o.put("/api/test-flow",async(l,c)=>{try{let d=s(l.query.file);if("error"in d)return c.status(400).json({error:d.error});let u=d.filePath,{testFlow:m,metadata:p}=l.body;if(!m)return c.status(400).json({error:"testFlow is required"});let w=O.join(n??t,"templates"),g=await Ih(w),y=Fa(m,g),h=xi(y.statements??[]),v={...y,statements:h},_=n??t,x=[v.statements??[],v.teardown??[],...v.testGroup?.tests?.flatMap(D=>[D.statements,...D.teardown?[D.teardown]:[]])??[],...v.testGroup?.beforeEach?[v.testGroup.beforeEach]:[],...v.testGroup?.afterEach?[v.testGroup.afterEach]:[]];for(let D of x)await _i(D,_);let E=Ma(v,p),$=u+".tmp";await L.writeFile($,E,"utf-8"),await L.rename($,u);let I=await L.stat(u);c.json({success:!0,lastModified:I.mtimeMs})}catch(d){console.error("[debugger] Error saving test flow:",d),c.status(500).json({error:d.message})}}),o.get("/api/fixtures",async(l,c)=>{try{let d=r();try{let m=(await L.readdir(d,{withFileTypes:!0})).filter(p=>p.isFile()).map(p=>p.name).sort();c.json({files:m,dir:d})}catch(u){if(u.code==="ENOENT")c.json({files:[],dir:d});else throw u}}catch(d){console.error("[debugger] Error listing fixtures:",d),c.status(500).json({error:d.message})}}),o.post("/api/fixtures",async(l,c)=>{try{let d=r();await L.mkdir(d,{recursive:!0});let{name:u,content:m}=l.body;if(!u||!m)return c.status(400).json({error:"name and content are required"});let p=O.basename(u);if(!p)return c.status(400).json({error:"Invalid file name"});let w=O.join(d,p);await L.writeFile(w,Buffer.from(m,"base64")),c.json({fileName:p})}catch(d){console.error("[debugger] Error saving fixture:",d),c.status(500).json({error:d.message})}}),o.get("/api/functions",async(l,c)=>{let d=O.join(n??t,"helpers"),u;try{u=await L.readdir(d)}catch(g){return g.code==="ENOENT"?c.json([]):(console.error("[debugger] Error reading helpers dir:",g),c.status(500).json({error:g.message}))}let m=u.filter(g=>/\.(ts|js|mjs)$/.test(g)),p=[],w=1;for(let g of m){let y=await L.readFile(O.join(d,g),"utf-8"),h=/export\s+async\s+function\s+(\w+)\s*(\([^)]*\))/g,v;for(;(v=h.exec(y))!==null;){let[,_,x]=v,E=x.replace(/\s*:\s*[^,)]+/g,"");p.push({id:w++,name:`helpers/${g}#${_}`,description:"",status:"Active",code:`async function ${_}${E} {}`})}}c.json(p)}),o.get("/api/reusable-steps",async(l,c)=>{let d=O.join(n??t,"templates"),u;try{u=await L.readdir(d)}catch(w){return w.code==="ENOENT"?c.json([]):(console.error("[debugger] Error reading templates dir:",w),c.status(500).json({error:w.message}))}let m=u.filter(w=>w.endsWith(".yaml")).sort(),p=[];for(let w of m)try{let g=await L.readFile(O.join(d,w),"utf-8"),y=vt(g);if(!y||typeof y!="object")continue;let h=y.name??O.basename(w,".yaml"),v=y.description??"",_=qe(y.statements);p.push({id:In(h),organizationId:"local",name:h,description:v,statements:_})}catch(g){console.error(`[debugger] Error parsing template ${w}:`,g)}c.json(p)}),o.post("/api/reusable-steps/exists/:name",async(l,c)=>{let d=O.join(n??t,"templates"),u=decodeURIComponent(l.params.name).toLowerCase(),m;try{m=await L.readdir(d)}catch(p){return p.code==="ENOENT"?c.json(!1):c.status(500).json({error:p.message})}for(let p of m.filter(w=>w.endsWith(".yaml")))try{let w=await L.readFile(O.join(d,p),"utf-8");if((vt(w)?.name??O.basename(p,".yaml")).toLowerCase()===u)return c.json(!0)}catch{}c.json(!1)}),o.post("/api/reusable-steps",async(l,c)=>{let d=O.join(n??t,"templates"),{reusableStep:u}=l.body??{};if(!u?.name||!Array.isArray(u.statements))return c.status(400).json({error:"reusableStep.name and reusableStep.statements are required"});await L.mkdir(d,{recursive:!0});let m=u.name.replace(/[/\\:*?"<>|]/g,"-").trim(),p=O.join(d,`${m}.yaml`),w={name:u.name,statements:Cn(u.statements)};u.description&&(w.description=u.description),await L.writeFile(p,ki(w),"utf-8"),c.json({id:In(u.name),organizationId:"local",name:u.name,description:u.description??"",statements:u.statements})}),o.put("/api/reusable-steps/:id/update",async(l,c)=>{let d=parseInt(l.params.id,10),u=O.join(n??t,"templates"),m;try{m=await L.readdir(u)}catch(p){return p.code==="ENOENT"?c.status(404).json({error:"Templates directory not found"}):c.status(500).json({error:p.message})}for(let p of m.filter(w=>w.endsWith(".yaml")))try{let w=O.join(u,p),g=vt(await L.readFile(w,"utf-8"))??{},y=g.name??O.basename(p,".yaml");if(In(y)!==d)continue;let h=l.body??{};return h.description!==void 0&&(g.description=h.description),h.statements!==void 0&&(g.statements=Cn(h.statements)),await L.writeFile(w,ki(g),"utf-8"),c.json({id:d,organizationId:"local",...g,statements:h.statements!==void 0?h.statements:qe(g.statements)})}catch{}c.status(404).json({error:`Template with id ${d} not found`})}),o.put("/api/templates/:name",async(l,c)=>{let d=O.join(n??t,"templates"),u=decodeURIComponent(l.params.name),m;try{m=await L.readdir(d)}catch(p){return p.code==="ENOENT"?c.status(404).json({error:"Templates directory not found"}):c.status(500).json({error:p.message})}for(let p of m.filter(w=>w.endsWith(".yaml")))try{let w=O.join(d,p),g=vt(await L.readFile(w,"utf-8"))??{};if((g.name??O.basename(p,".yaml"))!==u)continue;let h=l.body??{};return h.name!==void 0&&(g.name=h.name),h.description!==void 0&&(g.description=h.description),h.statements!==void 0&&(g.statements=Cn(h.statements)),await L.writeFile(w,ki(g),"utf-8"),c.json({organizationId:"local",...g,statements:h.statements!==void 0?h.statements:qe(g.statements)})}catch{}c.status(404).json({error:`Template "${u}" not found`})}),o.get("/api/test-results",async(l,c)=>{let d=s(l.query.file);if("error"in d)return c.status(400).json({error:d.error});let u=n??t,m=O.basename(d.filePath,".test.yaml"),p=O.join(u,".shiplight","artifacts",m),w=[],g=null;try{let y=await L.readdir(p,{withFileTypes:!0});for(let h of y)if(h.isDirectory()){let v=O.join(p,h.name),_=await L.readdir(v);for(let x of _.filter(E=>/\.(png|jpe?g|webp)$/i.test(E))){let E=O.relative(p,O.join(v,x)),$=h.name.match(/^(.+?)_(before|after)$/),I=$?$[1]:h.name,D=$?$[2]:"screenshot";w.push({url:`/api/report-assets/${m}/${E}`,label:D,stepId:I})}}else/\.(webm|mp4)$/i.test(h.name)&&(g||(g=`/api/report-assets/${m}/${h.name}`));w.sort((h,v)=>h.stepId!==v.stepId?(h.stepId??"").localeCompare(v.stepId??""):h.label.localeCompare(v.label))}catch{}if(w.length===0&&!g)return c.status(404).json({error:"No test results found"});c.json({videoPath:g,screenshots:w})}),o}var Ll=b(()=>{"use strict";bt();Pl()});var Dl={};xt(Dl,{createIntRunnerRouter:()=>Oh});import{Router as Ph}from"express";function Oh(e){let t=Ph();return t.get("/api/browser-cdp",async(i,n)=>{let a=e.getCdpEndpoint();if(!a)return n.status(404).json({error:"No browser running. Start a debug session first."});n.json({cdpUrl:a})}),t.post("/api/int-runner/create-session",async(i,n)=>{try{let a=i.body.startingUrl||i.body.testFlow?.url||i.body.urlOverride,o=i.body.testFilePath,r=await e.createSession({startingUrl:a,testFilePath:o});n.json({status:"success",sessionId:r.sessionId,searchParams:""})}catch(a){console.error("[debugger] create-session error:",a),n.status(500).json({status:"error",message:a.message})}}),t.post("/api/int-runner/login",async(i,n)=>{try{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});let o=await e.executeLogin(a.sessionId);n.json(o)}catch(a){console.error("[debugger] login error:",a),n.status(500).json({status:"error",details:a.message})}}),t.post("/api/int-runner/liveview-url",async(i,n)=>{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});n.json({liveviewUrl:"",browserWsUrl:""})}),t.post("/api/int-runner/end-debug",async(i,n)=>{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});n.json({status:"success"})}),t.post("/api/int-runner/start-debug",async(i,n)=>{try{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});let o=await e.startDebug(a.sessionId);n.json({status:"success",...o})}catch(a){console.error("[debugger] start-debug error:",a),n.status(500).json({status:"error",message:a.message})}}),t.post("/api/int-runner/execute-action",async(i,n)=>{try{let{session:a,actionEntity:o,stepId:r,withSelfHealing:s,stmtUid:l,executionHistory:c}=i.body;if(!a?.sessionId||!o)return n.status(400).json({status:"error",message:"Missing session or actionEntity"});let d=await e.executeAction(a.sessionId,o,r,{withSelfHealing:s,stmtUid:l,executionHistory:c});n.json(d)}catch(a){console.error("[debugger] execute-action error:",a),n.status(500).json({status:"error",details:a.message})}}),t.post("/api/int-runner/run-step",async(i,n)=>{let{session:a,statement:o,stepId:r,executionHistory:s}=i.body;if(!a?.sessionId||!o)return n.status(400).json({success:!1,message:"Session and statement required"});n.setHeader("Content-Type","text/event-stream"),n.setHeader("Cache-Control","no-cache"),n.setHeader("Connection","keep-alive"),n.flushHeaders();let l=c=>{n.write(`data: ${JSON.stringify(c)}
4308
4330
 
4309
4331
  `)};try{await e.runStep(a.sessionId,o,r,l,s)}catch(c){l({type:"error",data:{message:c.message}})}finally{n.end()}}),t.post("/api/int-runner/execute-step",async(i,n)=>{let{session:a,statement:o,stepId:r,executionHistory:s,maxSteps:l}=i.body;if(!a?.sessionId||!o)return n.status(400).json({success:!1,message:"Session and statement required"});n.setHeader("Content-Type","text/event-stream"),n.setHeader("Cache-Control","no-cache"),n.setHeader("Connection","keep-alive"),n.flushHeaders();let c=d=>{n.write(`data: ${JSON.stringify(d)}
4310
4332
 
4311
4333
  `)};try{await e.runStep(a.sessionId,o,r,c,s)}catch(d){c({type:"error",data:{message:d.message}})}finally{n.end()}}),t.post("/api/int-runner/stop-run-step",async(i,n)=>{try{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});let o=e.stopRunStep(a.sessionId);n.json({status:"success",aborted:o})}catch(a){console.error("[debugger] stop-run-step error:",a),n.status(500).json({status:"error",aborted:!1,details:a.message})}}),t.post("/api/int-runner/evaluate",async(i,n)=>{try{let{session:a,statement:o,stepId:r,executionHistory:s}=i.body;if(!a?.sessionId||!o)return n.status(400).json({status:"error",message:"Missing session or statement"});let l=await e.evaluate(a.sessionId,o,s);n.json(l)}catch(a){console.error("[debugger] evaluate error:",a),n.status(500).json({status:"error",conclusion:"unknown",explanation:a.message})}}),t.post("/api/int-runner/generate-action",async(i,n)=>{try{let{session:a,statement:o,stepId:r,executionHistory:s,usePureVision:l,includeDebugInfo:c}=i.body;if(!a?.sessionId||!o)return n.status(400).json({status:"error",message:"Missing session or statement"});let d=await e.generateAction(a.sessionId,o,r,{executionHistory:s,usePureVision:l,includeDebugInfo:c});n.json(d)}catch(a){console.error("[debugger] generate-action error:",a),n.status(500).json({status:"error",details:a.message})}}),t.post("/api/int-runner/screenshot",async(i,n)=>{try{let{session:a,s3Path:o}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});let r;if(o){let l=o.split("/").pop()?.replace(/\.png$/,"");l&&(r=l)}let s=await e.takeScreenshot(a.sessionId,r);n.json({status:"success",...s})}catch(a){console.error("[debugger] screenshot error:",a),n.status(500).json({status:"error",message:a.message})}}),t.get("/api/int-runner/session-artifacts",async(i,n)=>{try{let a=e.getSessionArtifacts?.("default")??{screenshots:[]};n.json(a)}catch(a){n.status(500).json({status:"error",message:a.message})}}),t.post("/api/int-runner/start-recorder",async(i,n)=>{let{session:a,testIdAttributeName:o}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});n.setHeader("Content-Type","text/event-stream"),n.setHeader("Cache-Control","no-cache"),n.setHeader("Connection","keep-alive"),n.flushHeaders();let r=s=>{n.write(`data: ${JSON.stringify(s)}
4312
4334
 
4313
- `)};try{await e.startRecorder(a.sessionId,r,o)}catch(s){r({type:"error",data:{message:s.message}})}finally{n.end()}}),t.post("/api/int-runner/stop-recorder",async(i,n)=>{try{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});await e.stopRecorder(a.sessionId),n.json({status:"success"})}catch(a){console.error("[debugger] stop-recorder error:",a),n.status(500).json({status:"error",details:a.message})}}),t.post("/api/int-runner/terminate-session",async(i,n)=>{try{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});await e.terminateSession(a.sessionId),n.json({status:"success",details:`Session ${a.sessionId} terminated`})}catch(a){console.error("[debugger] terminate-session error:",a),n.status(500).json({status:"error",details:a.message})}}),t.post("/api/int-runner/session-status",async(i,n)=>{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"timed_out"});n.json({status:"active",remainingSeconds:9999})}),t}var Rl=v(()=>{"use strict"});import Ha from"express";import Pn from"path";import*as oe from"path";import*as pt from"fs/promises";import{pathToFileURL as Fu}from"url";import*as Us from"os";import{parse as Hu}from"yaml";import{expect as Wu}from"@playwright/test";B();B();Rt();rt();import{z as ks}from"zod";var wu=ks.object({instruction:ks.string().describe('The instruction of the operation to perform. Can only include one operation. Do not inlcude element indexes just describe the element, e.g. "select the text "Hello, world!" in "Hello, world!""')});function Ss(e){e.register({name:"perform_accurate_operation",description:"Perform an operation that requires accurate interaction like dragging or interacting with a specific area of an element. Only use this action when neccecary.",schema:wu,usesElementIndex:!1,async execute(t,i){let{instruction:n}=t,a={page:i.page,agentServices:i.agentServices,domService:i.domService},o=await ot(n,a,{});if(o.status==="error"||!o.actionEntity)return{success:!1,actionEntity:{action_description:n,action_data:{action_name:"perform_accurate_operation",kwargs:{instruction:n}}},error:o.error||"Failed to generate action"};let{actionEntity:r}=o,s=await Dt(r,a);return{success:s.success,actionEntity:r,message:s.success?`Successfully executed action: ${r.action_data?.action_name}`:void 0,error:s.error}}})}Ee();B();import{generateText as yu}from"ai";import{convert as bu}from"html-to-text";async function vu(e,t,i){let{apiKey:n,domain:a}=e;if(!n)throw new Error("Mailgun configuration missing. Please provide apiKey and domain");let o=!!e.baseURL,r=e.baseURL||"https://api.mailgun.net",s=e.authHeader||`Basic ${Buffer.from(`api:${n}`).toString("base64")}`,l=[];try{let c=o?`${r}/events`:`${r}/v3/${a}/events`,d={event:"accepted",limit:"10",ascending:"yes",recipient:t};if(i.from_email&&(d.from=i.from_email),i.since)d.begin=Math.floor(i.since/1e3).toString();else{let p=new Date(Date.now()-6e5);d.begin=Math.floor(p.getTime()/1e3).toString()}f.info(`Mailgun params: ${JSON.stringify(d)}`);let u=await fetch(c+"?"+new URLSearchParams(d),{method:"GET",headers:{Authorization:s}});if(!u.ok){let p=await u.text();throw new Error(`Mailgun events API error: ${p}`)}let m=(await u.json()).items||[];for(let p of m.slice(0,10)){if(p.event!=="accepted")continue;let w=(p.storage||{}).url;if(f.info(`message_url: ${w}`),!w){let h=(p.message||{}).headers||{},b=h.subject||"",x=h.from||"",S=h.to||"";if(i.from_email&&!x.toLowerCase().includes(i.from_email.toLowerCase())||i.to_email&&!S.toLowerCase().includes(i.to_email.toLowerCase())||i.subject&&!b.toLowerCase().includes(i.subject.toLowerCase()))continue;l.push({subject:b,from:x,to:S,date:new Date(p.timestamp*1e3).toUTCString(),body:"Message body not available (Mailgun storage disabled)",message_id:h["message-id"]||""});continue}let g=w.split("/"),y=g[g.length-1];if(f.info(`Storage key: ${y}`),y){let h=o?`${r}/messages/${y}`:`${r}/v3/domains/${a}/messages/${y}`;try{let b=await fetch(h,{method:"GET",headers:{Authorization:s,Accept:"application/json"}});if(b.ok){let x=await b.json(),S=x.Subject||"",E=x.From||"",$=x.To||"",O=x.Date||"",D=x["Message-Id"]||"";f.info(`subject: ${S}`),f.info(`from_addr: ${E}`),f.info(`to_addr: ${$}`),f.info(`date: ${O}`),f.info(`message_id: ${D}`);let I=x["body-html"]||x["body-plain"]||"";if(I&&I.includes("<")&&(I=bu(I)),f.info(`Body: ${I.substring(0,200)}...`),i.from_email&&!E.toLowerCase().includes(i.from_email.toLowerCase())||i.to_email&&!$.toLowerCase().includes(i.to_email.toLowerCase())||i.subject&&!S.toLowerCase().includes(i.subject.toLowerCase())||i.body_contains&&!I.toLowerCase().includes(i.body_contains.toLowerCase()))continue;l.push({subject:S,from:E,to:$,date:O,body:I,message_id:D});continue}else f.warn(`Messages API returned ${b.status}`)}catch(b){f.warn(`Failed to parse JSON response: ${b}`)}}try{let h=await fetch(w,{method:"GET",headers:{Authorization:s}});if(!h.ok){f.warn(`Could not fetch stored message: ${h.status}`);continue}let b=await h.text();f.info(`Fallback: Raw email length: ${b.length}`);let x=b.split(`
4314
- `),S=!0,E={},$="";for(let Q=0;Q<x.length;Q++){let U=x[Q];if(U.trim()===""&&S){S=!1;continue}if(S){let J=U.match(/^([^:]+):\s*(.+)$/);J&&(E[J[1].toLowerCase()]=J[2])}else $+=U+`
4315
- `}let O=E.subject||"",D=E.from||"",I=E.to||"",H=E.date||"",K=E["message-id"]||"";if(i.from_email&&!D.toLowerCase().includes(i.from_email.toLowerCase())||i.to_email&&!I.toLowerCase().includes(i.to_email.toLowerCase())||i.subject&&!O.toLowerCase().includes(i.subject.toLowerCase())||i.body_contains&&!$.toLowerCase().includes(i.body_contains.toLowerCase()))continue;l.push({subject:O,from:D,to:I,date:H,body:$.trim(),message_id:K})}catch(h){f.warn(`Error fetching raw message: ${h}`)}}if(l.length>0){try{l.sort((w,g)=>{let y=new Date(w.date).getTime();return new Date(g.date).getTime()-y})}catch{}let p=l[0];return f.info(`Returning most recent email: ${p.subject}`),[p]}return l}catch(c){throw f.error(`Error fetching emails from Mailgun: ${c.message}`),new Error(`Error fetching emails from Mailgun: ${c.message}`)}}function xu(e,t){if(e==="verification_code")return`You are analyzing an email to extract an OTP (One-Time Password) or verification code.
4335
+ `)};try{await e.startRecorder(a.sessionId,r,o)}catch(s){r({type:"error",data:{message:s.message}})}finally{n.end()}}),t.post("/api/int-runner/stop-recorder",async(i,n)=>{try{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});await e.stopRecorder(a.sessionId),n.json({status:"success"})}catch(a){console.error("[debugger] stop-recorder error:",a),n.status(500).json({status:"error",details:a.message})}}),t.post("/api/int-runner/terminate-session",async(i,n)=>{try{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"error",message:"Missing session"});await e.terminateSession(a.sessionId),n.json({status:"success",details:`Session ${a.sessionId} terminated`})}catch(a){console.error("[debugger] terminate-session error:",a),n.status(500).json({status:"error",details:a.message})}}),t.post("/api/int-runner/session-status",async(i,n)=>{let{session:a}=i.body;if(!a?.sessionId)return n.status(400).json({status:"timed_out"});n.json({status:"active",remainingSeconds:9999})}),t}var Rl=b(()=>{"use strict"});import Ha from"express";import Pn from"path";import*as oe from"path";import*as gt from"fs/promises";import{pathToFileURL as Fu}from"url";import*as Us from"os";import{parse as Hu}from"yaml";import{expect as Wu}from"@playwright/test";B();B();Rt();st();import{z as ks}from"zod";var wu=ks.object({instruction:ks.string().describe('The instruction of the operation to perform. Can only include one operation. Do not inlcude element indexes just describe the element, e.g. "select the text "Hello, world!" in "Hello, world!""')});function Ss(e){e.register({name:"perform_accurate_operation",description:"Perform an operation that requires accurate interaction like dragging or interacting with a specific area of an element. Only use this action when neccecary.",schema:wu,usesElementIndex:!1,async execute(t,i){let{instruction:n}=t,a={page:i.page,agentServices:i.agentServices,domService:i.domService},o=await rt(n,a,{});if(o.status==="error"||!o.actionEntity)return{success:!1,actionEntity:{action_description:n,action_data:{action_name:"perform_accurate_operation",kwargs:{instruction:n}}},error:o.error||"Failed to generate action"};let{actionEntity:r}=o,s=await Dt(r,a);return{success:s.success,actionEntity:r,message:s.success?`Successfully executed action: ${r.action_data?.action_name}`:void 0,error:s.error}}})}Ee();B();import{generateText as yu}from"ai";import{convert as bu}from"html-to-text";async function vu(e,t,i){let{apiKey:n,domain:a}=e;if(!n)throw new Error("Mailgun configuration missing. Please provide apiKey and domain");let o=!!e.baseURL,r=e.baseURL||"https://api.mailgun.net",s=e.authHeader||`Basic ${Buffer.from(`api:${n}`).toString("base64")}`,l=[];try{let c=o?`${r}/events`:`${r}/v3/${a}/events`,d={event:"accepted",limit:"10",ascending:"yes",recipient:t};if(i.from_email&&(d.from=i.from_email),i.since)d.begin=Math.floor(i.since/1e3).toString();else{let p=new Date(Date.now()-6e5);d.begin=Math.floor(p.getTime()/1e3).toString()}f.info(`Mailgun params: ${JSON.stringify(d)}`);let u=await fetch(c+"?"+new URLSearchParams(d),{method:"GET",headers:{Authorization:s}});if(!u.ok){let p=await u.text();throw new Error(`Mailgun events API error: ${p}`)}let m=(await u.json()).items||[];for(let p of m.slice(0,10)){if(p.event!=="accepted")continue;let w=(p.storage||{}).url;if(f.info(`message_url: ${w}`),!w){let h=(p.message||{}).headers||{},v=h.subject||"",_=h.from||"",x=h.to||"";if(i.from_email&&!_.toLowerCase().includes(i.from_email.toLowerCase())||i.to_email&&!x.toLowerCase().includes(i.to_email.toLowerCase())||i.subject&&!v.toLowerCase().includes(i.subject.toLowerCase()))continue;l.push({subject:v,from:_,to:x,date:new Date(p.timestamp*1e3).toUTCString(),body:"Message body not available (Mailgun storage disabled)",message_id:h["message-id"]||""});continue}let g=w.split("/"),y=g[g.length-1];if(f.info(`Storage key: ${y}`),y){let h=o?`${r}/messages/${y}`:`${r}/v3/domains/${a}/messages/${y}`;try{let v=await fetch(h,{method:"GET",headers:{Authorization:s,Accept:"application/json"}});if(v.ok){let _=await v.json(),x=_.Subject||"",E=_.From||"",$=_.To||"",I=_.Date||"",D=_["Message-Id"]||"";f.info(`subject: ${x}`),f.info(`from_addr: ${E}`),f.info(`to_addr: ${$}`),f.info(`date: ${I}`),f.info(`message_id: ${D}`);let C=_["body-html"]||_["body-plain"]||"";if(C&&C.includes("<")&&(C=bu(C)),f.info(`Body: ${C.substring(0,200)}...`),i.from_email&&!E.toLowerCase().includes(i.from_email.toLowerCase())||i.to_email&&!$.toLowerCase().includes(i.to_email.toLowerCase())||i.subject&&!x.toLowerCase().includes(i.subject.toLowerCase())||i.body_contains&&!C.toLowerCase().includes(i.body_contains.toLowerCase()))continue;l.push({subject:x,from:E,to:$,date:I,body:C,message_id:D});continue}else f.warn(`Messages API returned ${v.status}`)}catch(v){f.warn(`Failed to parse JSON response: ${v}`)}}try{let h=await fetch(w,{method:"GET",headers:{Authorization:s}});if(!h.ok){f.warn(`Could not fetch stored message: ${h.status}`);continue}let v=await h.text();f.info(`Fallback: Raw email length: ${v.length}`);let _=v.split(`
4336
+ `),x=!0,E={},$="";for(let Q=0;Q<_.length;Q++){let U=_[Q];if(U.trim()===""&&x){x=!1;continue}if(x){let J=U.match(/^([^:]+):\s*(.+)$/);J&&(E[J[1].toLowerCase()]=J[2])}else $+=U+`
4337
+ `}let I=E.subject||"",D=E.from||"",C=E.to||"",H=E.date||"",K=E["message-id"]||"";if(i.from_email&&!D.toLowerCase().includes(i.from_email.toLowerCase())||i.to_email&&!C.toLowerCase().includes(i.to_email.toLowerCase())||i.subject&&!I.toLowerCase().includes(i.subject.toLowerCase())||i.body_contains&&!$.toLowerCase().includes(i.body_contains.toLowerCase()))continue;l.push({subject:I,from:D,to:C,date:H,body:$.trim(),message_id:K})}catch(h){f.warn(`Error fetching raw message: ${h}`)}}if(l.length>0){try{l.sort((w,g)=>{let y=new Date(w.date).getTime();return new Date(g.date).getTime()-y})}catch{}let p=l[0];return f.info(`Returning most recent email: ${p.subject}`),[p]}return l}catch(c){throw f.error(`Error fetching emails from Mailgun: ${c.message}`),new Error(`Error fetching emails from Mailgun: ${c.message}`)}}function xu(e,t){if(e==="verification_code")return`You are analyzing an email to extract an OTP (One-Time Password) or verification code.
4316
4338
 
4317
4339
  Please carefully examine the email content and look for:
4318
4340
  1. Numeric codes (usually 4-8 digits)
@@ -4386,10 +4408,10 @@ To: ${m.to}
4386
4408
  Date: ${m.date}
4387
4409
 
4388
4410
  Body:
4389
- ${m.body}`,w=await ku(p,a,t.model,t.extraction_type);f.info(`Extracted content: ${w}`),w&&w!=="NOT_FOUND"&&u.push({content:w,email_subject:m.subject,email_from:m.from,email_date:m.date})}if(u.length>0){let m=u[0],p=`$email_${t.extraction_type}`;t.extraction_type==="custom"?p="$email_extracted_content":t.extraction_type==="activation_link"?p="$email_magic_link":t.extraction_type==="verification_code"&&(p="$email_otp_code");let w=(new Date().getTime()-o.getTime())/1e3;return f.info(`Successfully extracted content after ${s} attempts in ${w.toFixed(1)} seconds`),{data:m.content,result_variable:p,status:"success",message:`Successfully extracted content from email: ${m.email_subject.substring(0,50)}... (attempts: ${s})`}}else f.info(`Found emails but no extractable content in attempt ${s}`)}else f.info(`No emails found in attempt ${s}`)}catch(c){f.warn(`Error in polling attempt ${s}: ${c.message}`)}if(new Date(Date.now()+n*1e3)>=r){f.info("Not enough time for another polling attempt");break}f.info(`Waiting ${n} seconds before next attempt...`),await new Promise(c=>setTimeout(c,n*1e3))}let l=(new Date().getTime()-o.getTime())/1e3;return{data:void 0,status:"error",message:`No emails with extractable content found after ${s} attempts over ${l.toFixed(1)} seconds`}}catch(a){return f.error(`Error extracting email content: ${a.message}`),{data:void 0,status:"error",message:`Error extracting email content: ${a.message}`}}}tt();B();te();import{z as $e}from"zod";function Ts(e){switch(e){case"verification_code":return"email_otp_code";case"activation_link":return"email_magic_link";case"custom":return"email_extracted_content";default:return"email_content"}}var As=class{getMailgunConfig(){let e=Y().env||{};if(e.MAILGUN_API_KEY)return{apiKey:e.MAILGUN_API_KEY,domain:e.MAILGUN_DOMAIN||""};let t=e.SHIPLIGHT_API_TOKEN;if(t){let i=`${Ge(t,e.SHIPLIGHT_API_URL)}/mailgun`;return f.debug(`[extract_email_content] Using Shiplight proxy for Mailgun: ${i}`),{apiKey:t,domain:e.MAILGUN_DOMAIN||"",baseURL:i,authHeader:`Bearer ${t}`}}}async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=this.getMailgunConfig();if(!a)throw new Error("Mailgun configuration not provided. Please configure MAILGUN_API_KEY and MAILGUN_DOMAIN, or set SHIPLIGHT_API_TOKEN to route through the Shiplight proxy.");let o=n.kwargs,r=i.getModel?.()||"gemini-2.5-pro",s=await Es(a,{model:r,forward_email:o.forward_email,extraction_type:o.extraction_type,prompt:o.prompt,filters:{from_email:o.filter_from_email,to_email:o.filter_to_email,subject:o.filter_subject,body_contains:o.filter_body_contains},timeout:o.timeout});if(s.status==="success"&&s.data){let l=s.result_variable?.replace(/^\$/,"")||Ts(o.extraction_type);i.variableStore.set(l,s.data),f.info(`[extract_email_content] Extracted and saved to ${l}`)}else throw new Error(s.message||"Failed to extract email content")}transpile(e){let t=e.action_data?.kwargs||{};return['await agent.execAction("extract_email_content", page, {',` action_data: { kwargs: ${JSON.stringify(t)} },`,"});"]}},Su=$e.object({forward_email:$e.string().describe("Email address where emails are forwarded to (Mailgun inbox)"),extraction_type:$e.enum(["verification_code","activation_link","custom"]).describe("Type of content to extract: verification_code for OTP codes, activation_link for magic links, custom for custom prompts"),prompt:$e.string().optional().describe("Custom extraction prompt (required when extraction_type is custom)"),filter_from_email:$e.string().optional().describe("Filter emails by sender address"),filter_to_email:$e.string().optional().describe("Filter emails by recipient address"),filter_subject:$e.string().optional().describe("Filter emails by subject (partial match)"),filter_body_contains:$e.string().optional().describe("Filter emails by body content (partial match)"),timeout:$e.number().optional().describe("Timeout in seconds for polling (default: 60)")});function $s(e,t){e.register({name:"extract_email_content",description:"Extract verification codes, magic links, or custom content from emails received via Mailgun. Polls the Mailgun inbox for matching emails and uses AI to extract the requested content.",schema:Su,async execute(i,n){let{forward_email:a,extraction_type:o,prompt:r,filter_from_email:s,filter_to_email:l,filter_subject:c,filter_body_contains:d,timeout:u}=i,{page:m,agentServices:p}=n;f.info(`[extract_email_content] Extracting ${o} from ${a}`);try{let w={action_description:`Extract ${o} from email`,action_data:{action_name:"extract_email_content",kwargs:{forward_email:a,extraction_type:o,prompt:r,filter_from_email:s,filter_to_email:l,filter_subject:c,filter_body_contains:d,timeout:u}}};await t.execute(m,w,p);let g=Ts(o);return{success:!0,actionEntity:w,message:`Extracted ${o} and saved to $${g}`}}catch(w){return{success:!1,error:w.message,actionEntity:{action_description:`Extract ${o} from email (failed)`,action_data:{action_name:"extract_email_content",kwargs:{forward_email:a,extraction_type:o,prompt:r,filter_from_email:s,filter_to_email:l,filter_subject:c,filter_body_contains:d,timeout:u}},feedback:w.message}}}}})}Ft();Wt();jt();Ut();Gt();Kt();Vt();Jt();Yt();qt();Zt();Qt();ei();ti();ii();ni();ai();oi();ri();si();li();ci();di();ui();hi();mi();pi();var kn=null;async function ye(){if(kn)return kn;let e=(await Promise.resolve().then(()=>(wn(),fn))).default;return kn=new e,kn}async function Ms(e){let t=await ye(),i=t.getAction("click"),n=t.getAction("hover"),a=t.getAction("right_click"),o=t.getAction("double_click");return us(e,i),Lr(e,n),Br(e,a),Kr(e,o),"Click, hover, double-click, right-click, or drag elements"}async function Is(e){let t=await ye(),i=t.getAction("go_to_url"),n=t.getAction("go_back"),a=t.getAction("reload_page");return ts(e,i),es(e,n),jr(e,a),"Navigate to URLs, go back, or reload the page"}async function Cs(e){let t=await ye(),i=t.getAction("clear_input"),n=t.getAction("input_text"),a=t.getAction("press");return cs(e,i),Rr(e,n),Hr(e,a),"Type text into inputs, clear input values, or press keyboard keys"}async function Ps(e){let t=await ye(),i=t.getAction("scroll_on_element"),n=t.getAction("scroll_to_text"),a=t.getAction("scroll");return Er(e,i),$r(e,n),_r(e,a),"Scroll the page or scroll to specific text/elements"}async function Os(e){let t=await ye(),i=t.getAction("close_tab"),n=t.getAction("switch_tab");return ps(e,i),tr(e,n),"Switch between browser tabs or close tabs"}async function Ns(e){let t=await ye(),i=t.getAction("upload_file"),n=t.getAction("wait_for_download_complete");return or(e,i),ur(e,n),"Upload files or wait for downloads to complete"}async function Ls(e){let t=await ye(),i=t.getAction("get_dropdown_options"),n=t.getAction("select_dropdown_option"),a=t.getAction("set_date_for_native_date_picker");return Zr(e,i),Cr(e,n),Or(e,a),"Get dropdown options, select dropdown values, or set date for native date picker input"}async function Ds(e){let t=await ye(),i=t.getAction("wait"),n=t.getAction("save_variable"),a=t.getAction("done");return lr(e,i),xr(e,n),fs(e,a),Ss(e),"Wait for conditions, save variables, or complete tasks"}async function Rs(e){let t=(await ye()).getAction("generate_2fa_code");Xr(e,t);let i=new As;return(await Promise.resolve().then(()=>(wn(),fn))).default.registerAction("extract_email_content",i),$s(e,i),"Generate 2FA codes or extract email/activation codes"}async function Fs(e){let t=await ye(),i=t.getAction("verify"),n=t.getAction("ai_extract");return as(e,i),rs(e,n),br(e),"Perform AI-powered assertions, extractions, or wait conditions"}_e();var Eu=[Ms(V),Is(V),Cs(V),Ps(V),Os(V),Ns(V),Ls(V),Ds(V),Fs(V),Rs(V)],r0=Promise.all(Eu);Et();je();Ae();ut();B();import{chromium as T0,firefox as A0,webkit as $0}from"playwright";import{execFileSync as Hs}from"child_process";import*as Ws from"fs";import*as js from"path";function Iu(){if(process.platform==="win32"){let i=Hs("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine | ConvertTo-Json -Compress"],{encoding:"utf-8",timeout:1e4}),n=JSON.parse(i.trim());return(Array.isArray(n)?n:[n]).filter(a=>a!==null&&typeof a=="object").filter(a=>typeof a.ProcessId=="number").map(a=>({pid:a.ProcessId,ppid:typeof a.ParentProcessId=="number"?a.ParentProcessId:0,args:typeof a.CommandLine=="string"?a.CommandLine:""}))}let e=Hs("ps",["-axo","pid=,ppid=,args="],{encoding:"utf-8"}),t=[];for(let i of e.split(`
4411
+ ${m.body}`,w=await ku(p,a,t.model,t.extraction_type);f.info(`Extracted content: ${w}`),w&&w!=="NOT_FOUND"&&u.push({content:w,email_subject:m.subject,email_from:m.from,email_date:m.date})}if(u.length>0){let m=u[0],p=`$email_${t.extraction_type}`;t.extraction_type==="custom"?p="$email_extracted_content":t.extraction_type==="activation_link"?p="$email_magic_link":t.extraction_type==="verification_code"&&(p="$email_otp_code");let w=(new Date().getTime()-o.getTime())/1e3;return f.info(`Successfully extracted content after ${s} attempts in ${w.toFixed(1)} seconds`),{data:m.content,result_variable:p,status:"success",message:`Successfully extracted content from email: ${m.email_subject.substring(0,50)}... (attempts: ${s})`}}else f.info(`Found emails but no extractable content in attempt ${s}`)}else f.info(`No emails found in attempt ${s}`)}catch(c){f.warn(`Error in polling attempt ${s}: ${c.message}`)}if(new Date(Date.now()+n*1e3)>=r){f.info("Not enough time for another polling attempt");break}f.info(`Waiting ${n} seconds before next attempt...`),await new Promise(c=>setTimeout(c,n*1e3))}let l=(new Date().getTime()-o.getTime())/1e3;return{data:void 0,status:"error",message:`No emails with extractable content found after ${s} attempts over ${l.toFixed(1)} seconds`}}catch(a){return f.error(`Error extracting email content: ${a.message}`),{data:void 0,status:"error",message:`Error extracting email content: ${a.message}`}}}it();B();te();import{z as $e}from"zod";function Ts(e){switch(e){case"verification_code":return"email_otp_code";case"activation_link":return"email_magic_link";case"custom":return"email_extracted_content";default:return"email_content"}}var As=class{getMailgunConfig(){let e=Y().env||{};if(e.MAILGUN_API_KEY)return{apiKey:e.MAILGUN_API_KEY,domain:e.MAILGUN_DOMAIN||""};let t=e.SHIPLIGHT_API_TOKEN;if(t){let i=`${Ke(t,e.SHIPLIGHT_API_URL)}/mailgun`;return f.debug(`[extract_email_content] Using Shiplight proxy for Mailgun: ${i}`),{apiKey:t,domain:e.MAILGUN_DOMAIN||"",baseURL:i,authHeader:`Bearer ${t}`}}}async execute(e,t,i){let n=t.action_data;if(!n)throw new Error("Action data not found");let a=this.getMailgunConfig();if(!a)throw new Error("Mailgun configuration not provided. Please configure MAILGUN_API_KEY and MAILGUN_DOMAIN, or set SHIPLIGHT_API_TOKEN to route through the Shiplight proxy.");let o=n.kwargs,r=i.getModel?.()||"gemini-2.5-pro",s=await Es(a,{model:r,forward_email:o.forward_email,extraction_type:o.extraction_type,prompt:o.prompt,filters:{from_email:o.filter_from_email,to_email:o.filter_to_email,subject:o.filter_subject,body_contains:o.filter_body_contains},timeout:o.timeout});if(s.status==="success"&&s.data){let l=s.result_variable?.replace(/^\$/,"")||Ts(o.extraction_type);i.variableStore.set(l,s.data),f.info(`[extract_email_content] Extracted and saved to ${l}`)}else throw new Error(s.message||"Failed to extract email content")}transpile(e){let t=e.action_data?.kwargs||{};return['await agent.execAction("extract_email_content", page, {',` action_data: { kwargs: ${JSON.stringify(t)} },`,"});"]}},Su=$e.object({forward_email:$e.string().describe("Email address where emails are forwarded to (Mailgun inbox)"),extraction_type:$e.enum(["verification_code","activation_link","custom"]).describe("Type of content to extract: verification_code for OTP codes, activation_link for magic links, custom for custom prompts"),prompt:$e.string().optional().describe("Custom extraction prompt (required when extraction_type is custom)"),filter_from_email:$e.string().optional().describe("Filter emails by sender address"),filter_to_email:$e.string().optional().describe("Filter emails by recipient address"),filter_subject:$e.string().optional().describe("Filter emails by subject (partial match)"),filter_body_contains:$e.string().optional().describe("Filter emails by body content (partial match)"),timeout:$e.number().optional().describe("Timeout in seconds for polling (default: 60)")});function $s(e,t){e.register({name:"extract_email_content",description:"Extract verification codes, magic links, or custom content from emails received via Mailgun. Polls the Mailgun inbox for matching emails and uses AI to extract the requested content.",schema:Su,async execute(i,n){let{forward_email:a,extraction_type:o,prompt:r,filter_from_email:s,filter_to_email:l,filter_subject:c,filter_body_contains:d,timeout:u}=i,{page:m,agentServices:p}=n;f.info(`[extract_email_content] Extracting ${o} from ${a}`);try{let w={action_description:`Extract ${o} from email`,action_data:{action_name:"extract_email_content",kwargs:{forward_email:a,extraction_type:o,prompt:r,filter_from_email:s,filter_to_email:l,filter_subject:c,filter_body_contains:d,timeout:u}}};await t.execute(m,w,p);let g=Ts(o);return{success:!0,actionEntity:w,message:`Extracted ${o} and saved to $${g}`}}catch(w){return{success:!1,error:w.message,actionEntity:{action_description:`Extract ${o} from email (failed)`,action_data:{action_name:"extract_email_content",kwargs:{forward_email:a,extraction_type:o,prompt:r,filter_from_email:s,filter_to_email:l,filter_subject:c,filter_body_contains:d,timeout:u}},feedback:w.message}}}}})}Ft();Wt();jt();Ut();Gt();Kt();Vt();Jt();Yt();qt();Zt();Qt();ei();ti();ii();ni();ai();oi();ri();si();li();ci();di();ui();hi();mi();pi();var kn=null;async function ye(){if(kn)return kn;let e=(await Promise.resolve().then(()=>(wn(),fn))).default;return kn=new e,kn}async function Ms(e){let t=await ye(),i=t.getAction("click"),n=t.getAction("hover"),a=t.getAction("right_click"),o=t.getAction("double_click");return us(e,i),Lr(e,n),Br(e,a),Kr(e,o),"Click, hover, double-click, right-click, or drag elements"}async function Is(e){let t=await ye(),i=t.getAction("go_to_url"),n=t.getAction("go_back"),a=t.getAction("reload_page");return ts(e,i),es(e,n),jr(e,a),"Navigate to URLs, go back, or reload the page"}async function Cs(e){let t=await ye(),i=t.getAction("clear_input"),n=t.getAction("input_text"),a=t.getAction("press");return cs(e,i),Rr(e,n),Hr(e,a),"Type text into inputs, clear input values, or press keyboard keys"}async function Ps(e){let t=await ye(),i=t.getAction("scroll_on_element"),n=t.getAction("scroll_to_text"),a=t.getAction("scroll");return Er(e,i),$r(e,n),_r(e,a),"Scroll the page or scroll to specific text/elements"}async function Os(e){let t=await ye(),i=t.getAction("close_tab"),n=t.getAction("switch_tab");return ps(e,i),tr(e,n),"Switch between browser tabs or close tabs"}async function Ns(e){let t=await ye(),i=t.getAction("upload_file"),n=t.getAction("wait_for_download_complete");return or(e,i),ur(e,n),"Upload files or wait for downloads to complete"}async function Ls(e){let t=await ye(),i=t.getAction("get_dropdown_options"),n=t.getAction("select_dropdown_option"),a=t.getAction("set_date_for_native_date_picker");return Zr(e,i),Cr(e,n),Or(e,a),"Get dropdown options, select dropdown values, or set date for native date picker input"}async function Ds(e){let t=await ye(),i=t.getAction("wait"),n=t.getAction("save_variable"),a=t.getAction("done");return lr(e,i),xr(e,n),fs(e,a),Ss(e),"Wait for conditions, save variables, or complete tasks"}async function Rs(e){let t=(await ye()).getAction("generate_2fa_code");Xr(e,t);let i=new As;return(await Promise.resolve().then(()=>(wn(),fn))).default.registerAction("extract_email_content",i),$s(e,i),"Generate 2FA codes or extract email/activation codes"}async function Fs(e){let t=await ye(),i=t.getAction("verify"),n=t.getAction("ai_extract");return as(e,i),rs(e,n),br(e),"Perform AI-powered assertions, extractions, or wait conditions"}_e();var Eu=[Ms(V),Is(V),Cs(V),Ps(V),Os(V),Ns(V),Ls(V),Ds(V),Fs(V),Rs(V)],r0=Promise.all(Eu);Et();je();Ae();ht();B();import{chromium as T0,firefox as A0,webkit as $0}from"playwright";import{execFileSync as Hs}from"child_process";import*as Ws from"fs";import*as js from"path";function Iu(){if(process.platform==="win32"){let i=Hs("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,CommandLine | ConvertTo-Json -Compress"],{encoding:"utf-8",timeout:1e4}),n=JSON.parse(i.trim());return(Array.isArray(n)?n:[n]).filter(a=>a!==null&&typeof a=="object").filter(a=>typeof a.ProcessId=="number").map(a=>({pid:a.ProcessId,ppid:typeof a.ParentProcessId=="number"?a.ParentProcessId:0,args:typeof a.CommandLine=="string"?a.CommandLine:""}))}let e=Hs("ps",["-axo","pid=,ppid=,args="],{encoding:"utf-8"}),t=[];for(let i of e.split(`
4390
4412
  `)){let n=i.trimStart().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&t.push({pid:parseInt(n[1],10),ppid:parseInt(n[2],10),args:n[3]})}return t}function Cu(e){let t=Iu(),i=new Set([e]),n=!0;for(;n;){n=!1;for(let a of t)!i.has(a.pid)&&i.has(a.ppid)&&(i.add(a.pid),n=!0)}for(let a of t){if(a.pid===e||!i.has(a.pid)||!/chrome|chromium/i.test(a.args))continue;let o=a.args.match(/--user-data-dir=(?:"([^"]+)"|(\S+))/);if(o)return o[1]??o[2]}return null}async function Pu(e,t){let i=js.join(e,"DevToolsActivePort"),n=Date.now()+t;for(;Date.now()<n;){try{let a=Ws.readFileSync(i,"utf-8").trim(),[o,r]=a.split(`
4391
- `),s=parseInt(o,10);if(Number.isFinite(s)&&s>0&&typeof r=="string"&&r.startsWith("/"))return{port:s,wsPath:r}}catch{}await new Promise(a=>setTimeout(a,100))}throw new Error(`Timed out waiting for ${i} \u2014 Chromium never exposed DevTools`)}async function _a(e,t=3e4){let i=Cu(e);if(!i)throw new Error(`No Chromium descendant of pid ${e} with --user-data-dir found. Did you launch with --remote-debugging-port=0 and is the browser still running?`);let{port:n,wsPath:a}=await Pu(i,t);return`ws://127.0.0.1:${n}${a}`}je();var Ou=(e=>(e.Desktop="desktop",e.Mobile="mobile",e))(Ou||{});var wi=(e=>(e.Started="started",e.Action="action",e.Completion="completion",e.Error="error",e.Aborted="aborted",e.Keepalive="keepalive",e))(wi||{});Rt();ze();ka();ae();je();mt();Ae();B();import{generateSync as Y0,createGuardrails as Lu}from"otplib";var q0=Lu({MIN_SECRET_BYTES:1});Fe();Ee();import{generateText as ik}from"ai";var nk=20*1024*1024;Ht();je();mt();B();Rt();ji();Hi();rt();Ii();Pi();Ci();et();Ni();De();Di();At();Tt();_e();Et();qi();ze();It();st();Ct();Pt();Nt();ka();ae();Fe();Ee();$t();it();Mt();Le();tt();Ke();va();Bi();Gi();Ki();zi();Vi();Xi();Ji();Yi();nn();an();on();Ft();Wt();jt();Ut();Gt();Kt();Vt();Jt();Yt();qt();Zt();Qt();ei();ti();ii();ni();ai();oi();ri();si();li();ci();lt();di();ui();hi();mi();pi();hn();Ht();Z();Be();je();mt();Ae();ut();B();te();Lt();gn();G();ve();function Sa(e){if(!e)return;let t=e.getAll(),i=e.getAllSensitiveKeys();if(i.size===0)return t;let n={};for(let[a,o]of Object.entries(t))n[a]=i.has(a)?"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022":o;return n}function ju(e,t,i){let n=e.startsWith(".")?t:i??process.cwd();return oe.resolve(n,e)}var yi=class{page;agent;testContext;testDir=process.cwd();projectRoot;sessionId="pw-"+Math.random().toString(36).slice(2,10);abortController=null;recorderStopResolver;recorderEnabled=!1;screenshotHistory=[];yamlFilePath;artifactsDir;constructor(t,i,n,a,o){this.page=t,this.agent=i,this.testContext=o,this.projectRoot=a,n&&(this.agent._getContext().testDataDir=n)}cdpEndpoint=null;setCdpEndpoint(t){this.cdpEndpoint=t}getCdpEndpoint(){if(this.cdpEndpoint)return this.cdpEndpoint;let t=this.page.context().browser();if(!t)return null;let i=t.wsEndpoint?.();return typeof i=="string"?i:null}async createSession(t){if(t?.testFilePath){this.testDir=oe.dirname(t.testFilePath),this.yamlFilePath=t.testFilePath;let i=this.projectRoot??this.testDir,n=oe.basename(t.testFilePath,".test.yaml");if(this.artifactsDir=oe.join(i,".shiplight","artifacts",n),t.testFilePath.endsWith(".test.yaml"))try{let a=await pt.readFile(t.testFilePath,"utf-8"),r=Hu(a)?.parameters;if(r&&r.length>0&&r[0].values)for(let[s,l]of Object.entries(r[0].values))this.agent.agentServices.saveVariable(s,l)}catch{}}return{sessionId:this.sessionId}}async executeLogin(t){return{status:"success",details:"Handled by Playwright"}}async ensureBrowser(t){return{page:this.page,liveviewUrl:""}}async startDebug(t){return{sessionId:this.sessionId,liveviewUrl:"",browserWsUrl:""}}async executeAction(t,i,n,a){let o=i.action_data||i.action;if(!o)throw new Error("ActionEntity has no action_data");console.error(`[pw-sandbox] executeAction stepId=${JSON.stringify(n)} action_name=${JSON.stringify(o.action_name)} locator=${JSON.stringify(i.locator)} kwargs=${JSON.stringify(o.kwargs)}`);let r=this.agent.agentServices.validatePage(this.page);if(o.action_name==="js_code"&&n==="prelude"){if(r.url()==="about:blank"){let p=o.kwargs?.code?.match(/PLAYWRIGHT_STARTING_URL \|\| '([^']*)'/)?.[1];p&&await r.goto(p,{waitUntil:"domcontentloaded"})}return{status:"success"}}if(o.action_name==="js_code"&&o.kwargs?.isSync===!0)return this.executeCode(t,o.kwargs.code||"");if(o.action_name==="function"&&o.kwargs?.functionName?.includes("#"))return this.executeFunction(o.kwargs);let s=a?.stmtUid;s&&this.agent.getNewActionEntities().delete(s);let l;if(Ve.isAiAction(i)){let g=new gi().transpile(i,n,s).join(`
4392
- `),y=new Function("page","agent",`return (async () => { ${g} })();`);try{await y(r,this.agent),l={actionGenerationDebugInfo:this.agent._getContext()?.lastActionDebugInfo}}catch(h){let b=this.agent._getContext();return{status:"error",details:this.agent.getAgentNote()||h.message,actionGenerationDebugInfo:b?.lastActionDebugInfo,testContext:Sa(b?.variableStore)}}}else{let p=i.action_description||o.action_name,w=!!a?.withSelfHealing&&Ve.canSelfHeal(i);l=await this.agent.step(r,async()=>{await this.agent.execAction(o.action_name,r,i)},p,n,s,w)}let c=this.agent.getAgentNote(),u=this.agent._getContext()?.variableStore,m={...l,status:"success",testContext:Sa(u)};if(c&&(m.details=c),s){let p=this.agent.getNewActionEntities().get(s);if(p){let{element_index:w,...g}=p.action_data?.kwargs||{};m.newActionEntity={...p,action_data:p.action_data?{...p.action_data,kwargs:g}:p.action_data}}}return m}async runStep(t,i,n,a,o){let r=[];this.abortController=new AbortController;try{let s=await this.agent.run(this.agent.agentServices.validatePage(this.page),i,n,{onAction:c=>{r.push(c),a({type:wi.Action,data:{action_entity:c}})}}),l=this.agent._getContext()?.variableStore;return a({type:wi.Completion,data:{success:s?.success??!0,details:s?.details,testContext:Sa(l)}}),{success:s?.success??!0,actions:r,details:s?.details}}finally{this.abortController=null}}async executeFunction(t){let i=t.functionName,[n,a]=i.split("#");try{if(oe.isAbsolute(n))return{status:"error",details:`Absolute paths are not supported in call: references. Use a path relative to the project root (got: "${n}")`};let o=ju(n,this.testDir,this.projectRoot),s=(await import(Fu(o).href))[a];if(typeof s!="function")return{status:"error",details:`Export "${a}" not found or not a function in ${n}`};let c=s.toString().match(/\(([^)]*)\)/),d=c&&c[1].trim()?c[1].split(",").map(b=>b.split(":")[0].trim().replace(/\?$/,"")):[],u=Array.isArray(t.parameterNames)?t.parameterNames.map(String):[],m=Array.isArray(t.parameterValues)?t.parameterValues.map(String):Array.isArray(t.args)?t.args.map(String):[],p={};u.forEach((b,x)=>{let S=b.split(":")[0].trim();p[S]=m[x]??""});let w=["page","agent","request","testContext"],g=this.agent.agentServices.validatePage(this.page),y=d.map(b=>{if(b==="page")return g;if(b==="agent")return this.agent;if(b==="request")return this.page.context().request;if(b==="testContext")return this.testContext;let x=p[b]??"";return x.startsWith("$")?this.agent.agentServices.readVariable(x.substring(1)):x}),h=d.length>0?y:m.map(b=>b==="page"?g:b==="agent"?this.agent:b==="request"?this.page.context().request:b==="testContext"?this.testContext:b.startsWith("$")?this.agent.agentServices.readVariable(b.substring(1)):b);return await s(...h),{status:"success"}}catch(o){let r=o instanceof Error?o.message:String(o);return{status:"error",details:`Function call failed: ${i} \u2014 ${r}`}}}async executeCode(t,i){try{return{status:"success",result:await new Function("page","expect","agent",`return (async () => { return (${i}); })();`)(this.agent.agentServices.validatePage(this.page),Wu,this.agent)}}catch(n){return{status:"error",details:n instanceof Error?n.message:String(n)}}}stopRunStep(t){return this.abortController?(this.abortController.abort(),!0):!1}async evaluate(t,i,n){try{let a=await this.agent.evaluate(this.agent.agentServices.validatePage(this.page),i);return{status:"success",conclusion:a?"true":"false",explanation:a?`Condition met: ${i}`:`Condition not met: ${i}`}}catch(a){return{status:"error",conclusion:"unknown",explanation:a.message}}}async generateAction(t,i,n,a){let o=await this.agent.generate(this.agent.agentServices.validatePage(this.page),i,n,a?.usePureVision),r=o.actions?.[0];return r?{status:"success",action:r,explanation:o.details,debugInfo:o.debugInfo,completes_instruction:o.success}:{status:"error",explanation:o.details||"Failed to generate action",debugInfo:o.debugInfo}}async takeScreenshot(t,i){let n=await this.agent.agentServices.validatePage(this.page).screenshot(),a=i??`debug-${this.screenshotHistory.length}`,o;if(this.artifactsDir){let r=oe.join(this.artifactsDir,a.replace(/\./g,"-"));await pt.mkdir(r,{recursive:!0}),o=oe.join(r,"screenshot.png")}else o=oe.join(Us.tmpdir(),`shiplight-screenshot-${Date.now()}.png`);return await pt.writeFile(o,n),this.screenshotHistory.push({stepId:a,path:o}),{screenshot:n.toString("base64"),screenshotPath:o}}getSessionArtifacts(t){return{outputDir:this.artifactsDir,screenshots:[...this.screenshotHistory]}}async startRecorder(t,i,n){let a=this.page.context(),o=new Promise(s=>{this.recorderStopResolver=s}),r={actionAdded:(s,l,c)=>{i({type:"actionAdded",action:l.action,code:c,timestamp:Date.now()})},actionUpdated:(s,l,c)=>{i({type:"actionUpdated",action:l.action,code:c,timestamp:Date.now()})},signalAdded:(s,l)=>{i({type:"signal",signal:l.signal,timestamp:Date.now()})}};if(this.recorderEnabled)a._onRecorderEventSink=r,await this.page.evaluate(()=>window.__pw_recorderSetMode?.("recording")).catch(()=>{});else{let s="x-pw-overlay { display: none !important; }";await a.addInitScript(`(() => {
4413
+ `),s=parseInt(o,10);if(Number.isFinite(s)&&s>0&&typeof r=="string"&&r.startsWith("/"))return{port:s,wsPath:r}}catch{}await new Promise(a=>setTimeout(a,100))}throw new Error(`Timed out waiting for ${i} \u2014 Chromium never exposed DevTools`)}async function _a(e,t=3e4){let i=Cu(e);if(!i)throw new Error(`No Chromium descendant of pid ${e} with --user-data-dir found. Did you launch with --remote-debugging-port=0 and is the browser still running?`);let{port:n,wsPath:a}=await Pu(i,t);return`ws://127.0.0.1:${n}${a}`}je();var Ou=(e=>(e.Desktop="desktop",e.Mobile="mobile",e))(Ou||{});var wi=(e=>(e.Started="started",e.Action="action",e.Completion="completion",e.Error="error",e.Aborted="aborted",e.Keepalive="keepalive",e))(wi||{});Rt();Ve();ka();ae();je();pt();Ae();B();import{generateSync as Y0,createGuardrails as Lu}from"otplib";var q0=Lu({MIN_SECRET_BYTES:1});Fe();Ee();import{generateText as ik}from"ai";var nk=20*1024*1024;Ht();je();pt();B();Rt();ji();Hi();st();Ii();Pi();Ci();tt();Ni();De();Di();At();Tt();_e();Et();qi();Ve();It();lt();Ct();Pt();Nt();ka();ae();Fe();Ee();$t();nt();Mt();Le();it();ze();va();Bi();Gi();Ki();zi();Vi();Xi();Ji();Yi();nn();an();on();Ft();Wt();jt();Ut();Gt();Kt();Vt();Jt();Yt();qt();Zt();Qt();ei();ti();ii();ni();ai();oi();ri();si();li();ci();ct();di();ui();hi();mi();pi();hn();Ht();Z();Ge();je();pt();Ae();ht();B();te();Lt();gn();G();ve();function Sa(e){if(!e)return;let t=e.getAll(),i=e.getAllSensitiveKeys();if(i.size===0)return t;let n={};for(let[a,o]of Object.entries(t))n[a]=i.has(a)?"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022":o;return n}function ju(e,t,i){let n=e.startsWith(".")?t:i??process.cwd();return oe.resolve(n,e)}var yi=class{page;agent;testContext;testDir=process.cwd();projectRoot;sessionId="pw-"+Math.random().toString(36).slice(2,10);abortController=null;recorderStopResolver;recorderEnabled=!1;screenshotHistory=[];yamlFilePath;artifactsDir;constructor(t,i,n,a,o){this.page=t,this.agent=i,this.testContext=o,this.projectRoot=a,n&&(this.agent._getContext().testDataDir=n)}cdpEndpoint=null;setCdpEndpoint(t){this.cdpEndpoint=t}getCdpEndpoint(){if(this.cdpEndpoint)return this.cdpEndpoint;let t=this.page.context().browser();if(!t)return null;let i=t.wsEndpoint?.();return typeof i=="string"?i:null}async createSession(t){if(t?.testFilePath){this.testDir=oe.dirname(t.testFilePath),this.yamlFilePath=t.testFilePath;let i=this.projectRoot??this.testDir,n=oe.basename(t.testFilePath,".test.yaml");if(this.artifactsDir=oe.join(i,".shiplight","artifacts",n),t.testFilePath.endsWith(".test.yaml"))try{let a=await gt.readFile(t.testFilePath,"utf-8"),r=Hu(a)?.parameters;if(r&&r.length>0&&r[0].values)for(let[s,l]of Object.entries(r[0].values))this.agent.agentServices.saveVariable(s,l)}catch{}}return{sessionId:this.sessionId}}async executeLogin(t){return{status:"success",details:"Handled by Playwright"}}async ensureBrowser(t){return{page:this.page,liveviewUrl:""}}async startDebug(t){return{sessionId:this.sessionId,liveviewUrl:"",browserWsUrl:""}}async executeAction(t,i,n,a){let o=i.action_data||i.action;if(!o)throw new Error("ActionEntity has no action_data");console.error(`[pw-sandbox] executeAction stepId=${JSON.stringify(n)} action_name=${JSON.stringify(o.action_name)} locator=${JSON.stringify(i.locator)} kwargs=${JSON.stringify(o.kwargs)}`);let r=this.agent.agentServices.validatePage(this.page);if(o.action_name==="js_code"&&n==="prelude"){if(r.url()==="about:blank"){let p=o.kwargs?.code?.match(/PLAYWRIGHT_STARTING_URL \|\| '([^']*)'/)?.[1];p&&await r.goto(p,{waitUntil:"domcontentloaded"})}return{status:"success"}}if(o.action_name==="js_code"&&o.kwargs?.isSync===!0)return this.executeCode(t,o.kwargs.code||"");if(o.action_name==="function"&&o.kwargs?.functionName?.includes("#"))return this.executeFunction(o.kwargs,o.args);let s=a?.stmtUid;s&&this.agent.getNewActionEntities().delete(s);let l;if(Xe.isAiAction(i)){let g=new gi().transpile(i,n,s).join(`
4414
+ `),y=new Function("page","agent",`return (async () => { ${g} })();`);try{await y(r,this.agent),l={actionGenerationDebugInfo:this.agent._getContext()?.lastActionDebugInfo}}catch(h){let v=this.agent._getContext();return{status:"error",details:this.agent.getAgentNote()||h.message,actionGenerationDebugInfo:v?.lastActionDebugInfo,testContext:Sa(v?.variableStore)}}}else{let p=i.action_description||o.action_name,w=!!a?.withSelfHealing&&Xe.canSelfHeal(i);l=await this.agent.step(r,async()=>{await this.agent.execAction(o.action_name,r,i)},p,n,s,w)}let c=this.agent.getAgentNote(),u=this.agent._getContext()?.variableStore,m={...l,status:"success",testContext:Sa(u)};if(c&&(m.details=c),s){let p=this.agent.getNewActionEntities().get(s);if(p){let{element_index:w,...g}=p.action_data?.kwargs||{};m.newActionEntity={...p,action_data:p.action_data?{...p.action_data,kwargs:g}:p.action_data}}}return m}async runStep(t,i,n,a,o){let r=[];this.abortController=new AbortController;try{let s=await this.agent.run(this.agent.agentServices.validatePage(this.page),i,n,{onAction:c=>{r.push(c),a({type:wi.Action,data:{action_entity:c}})}}),l=this.agent._getContext()?.variableStore;return a({type:wi.Completion,data:{success:s?.success??!0,details:s?.details,testContext:Sa(l)}}),{success:s?.success??!0,actions:r,details:s?.details}}finally{this.abortController=null}}async executeFunction(t,i){let n=t.functionName,[a,o]=n.split("#");try{if(oe.isAbsolute(a))return{status:"error",details:`Absolute paths are not supported in call: references. Use a path relative to the project root (got: "${a}")`};let r=ju(a,this.testDir,this.projectRoot),l=(await import(Fu(r).href))[o];if(typeof l!="function")return{status:"error",details:`Export "${o}" not found or not a function in ${a}`};let d=l.toString().match(/\(([^)]*)\)/),u=d&&d[1].trim()?d[1].split(",").map(x=>x.split(":")[0].trim().replace(/\?$/,"")):[],m=Array.isArray(t.args)?t.args:void 0,p=Array.isArray(t.parameterNames)?t.parameterNames.map(String):[],w=Array.isArray(t.parameterValues)?t.parameterValues:Array.isArray(i)?i:[],g={};p.forEach((x,E)=>{let $=x.split(":")[0].trim();g[$]=w[E]??""});let y=this.agent.agentServices.validatePage(this.page),h=x=>x==="page"?y:x==="agent"?this.agent:x==="request"?this.page.context().request:x==="testContext"?this.testContext:typeof x=="string"&&x.startsWith("$")?this.agent.agentServices.readVariable(x.substring(1)):x,v=u.map(x=>{if(x==="page")return y;if(x==="agent")return this.agent;if(x==="request")return this.page.context().request;if(x==="testContext")return this.testContext;let E=g[x]??"";return h(E)}),_=m&&m.length>0?m.map(h):u.length>0?v:w.map(h);return await l(..._),{status:"success"}}catch(r){let s=r instanceof Error?r.message:String(r);return{status:"error",details:`Function call failed: ${n} \u2014 ${s}`}}}async executeCode(t,i){try{return{status:"success",result:await new Function("page","expect","agent",`return (async () => { return (${i}); })();`)(this.agent.agentServices.validatePage(this.page),Wu,this.agent)}}catch(n){return{status:"error",details:n instanceof Error?n.message:String(n)}}}stopRunStep(t){return this.abortController?(this.abortController.abort(),!0):!1}async evaluate(t,i,n){try{let a=await this.agent.evaluate(this.agent.agentServices.validatePage(this.page),i);return{status:"success",conclusion:a?"true":"false",explanation:a?`Condition met: ${i}`:`Condition not met: ${i}`}}catch(a){return{status:"error",conclusion:"unknown",explanation:a.message}}}async generateAction(t,i,n,a){let o=await this.agent.generate(this.agent.agentServices.validatePage(this.page),i,n,a?.usePureVision),r=o.actions?.[0];return r?{status:"success",action:r,explanation:o.details,debugInfo:o.debugInfo,completes_instruction:o.success}:{status:"error",explanation:o.details||"Failed to generate action",debugInfo:o.debugInfo}}async takeScreenshot(t,i){let n=await this.agent.agentServices.validatePage(this.page).screenshot(),a=i??`debug-${this.screenshotHistory.length}`,o;if(this.artifactsDir){let r=oe.join(this.artifactsDir,a.replace(/\./g,"-"));await gt.mkdir(r,{recursive:!0}),o=oe.join(r,"screenshot.png")}else o=oe.join(Us.tmpdir(),`shiplight-screenshot-${Date.now()}.png`);return await gt.writeFile(o,n),this.screenshotHistory.push({stepId:a,path:o}),{screenshot:n.toString("base64"),screenshotPath:o}}getSessionArtifacts(t){return{outputDir:this.artifactsDir,screenshots:[...this.screenshotHistory]}}async startRecorder(t,i,n){let a=this.page.context(),o=new Promise(s=>{this.recorderStopResolver=s}),r={actionAdded:(s,l,c)=>{i({type:"actionAdded",action:l.action,code:c,timestamp:Date.now()})},actionUpdated:(s,l,c)=>{i({type:"actionUpdated",action:l.action,code:c,timestamp:Date.now()})},signalAdded:(s,l)=>{i({type:"signal",signal:l.signal,timestamp:Date.now()})}};if(this.recorderEnabled)a._onRecorderEventSink=r,await this.page.evaluate(()=>window.__pw_recorderSetMode?.("recording")).catch(()=>{});else{let s="x-pw-overlay { display: none !important; }";await a.addInitScript(`(() => {
4393
4415
  const orig = Element.prototype.attachShadow;
4394
4416
  Element.prototype.attachShadow = function(init) {
4395
4417
  const shadow = orig.call(this, init);