/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/fork-of-dont-use-stagehand@1.13.0/dist/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
var __create=Object.create,__defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropNames=Object.getOwnPropertyNames,__getOwnPropSymbols=Object.getOwnPropertySymbols,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__reflectGet=Reflect.get,__defNormalProp=(e,t,n)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,__spreadValues=(e,t)=>{for(var n in t||(t={}))__hasOwnProp.call(t,n)&&__defNormalProp(e,n,t[n]);if(__getOwnPropSymbols)for(var n of __getOwnPropSymbols(t))__propIsEnum.call(t,n)&&__defNormalProp(e,n,t[n]);return e},__spreadProps=(e,t)=>__defProps(e,__getOwnPropDescs(t)),__objRest=(e,t)=>{var n={};for(var r in e)__hasOwnProp.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&__getOwnPropSymbols)for(var r of __getOwnPropSymbols(e))t.indexOf(r)<0&&__propIsEnum.call(e,r)&&(n[r]=e[r]);return n},__export=(e,t)=>{for(var n in t)__defProp(e,n,{get:t[n],enumerable:!0})},__copyProps=(e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let s of __getOwnPropNames(t))__hasOwnProp.call(e,s)||s===n||__defProp(e,s,{get:()=>t[s],enumerable:!(r=__getOwnPropDesc(t,s))||r.enumerable});return e},__toESM=(e,t,n)=>(n=null!=e?__create(__getProtoOf(e)):{},__copyProps(!t&&e&&e.__esModule?n:__defProp(n,"default",{value:e,enumerable:!0}),e)),__toCommonJS=e=>__copyProps(__defProp({},"__esModule",{value:!0}),e),__superGet=(e,t,n)=>__reflectGet(__getProtoOf(e),n,t),__async=(e,t,n)=>new Promise(((r,s)=>{var o=e=>{try{a(n.next(e))}catch(e){s(e)}},i=e=>{try{a(n.throw(e))}catch(e){s(e)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,i);a((n=n.apply(e,t)).next())})),index_exports={};__export(index_exports,{AnnotatedScreenshotText:()=>AnnotatedScreenshotText,AvailableModelSchema:()=>AvailableModelSchema,LLMClient:()=>LLMClient,PlaywrightCommandException:()=>PlaywrightCommandException,PlaywrightCommandMethodNotSupportedException:()=>PlaywrightCommandMethodNotSupportedException,Stagehand:()=>Stagehand,defaultExtractSchema:()=>defaultExtractSchema}),module.exports=__toCommonJS(index_exports);var import_sdk3=require("@browserbasehq/sdk"),import_test2=require("@playwright/test"),import_crypto2=require("crypto"),import_dotenv=__toESM(require("dotenv")),import_fs=__toESM(require("fs")),import_os=__toESM(require("os")),import_path=__toESM(require("path")),StagehandContext=class e{constructor(e,t){this.intContext=e,this.stagehand=t}static init(t,n){return __async(this,null,(function*(){const r=new Proxy(t,{get:(e,t)=>e[t]});return new e(r,n)}))}get context(){return this.intContext}},import_sdk=require("@browserbasehq/sdk"),import_test=require("@playwright/test"),import_zod=require("zod"),defaultExtractSchema=import_zod.z.object({extraction:import_zod.z.string()}),PlaywrightCommandException=class extends Error{constructor(e){super(e),this.name="PlaywrightCommandException"}},PlaywrightCommandMethodNotSupportedException=class extends Error{constructor(e){super(e),this.name="PlaywrightCommandMethodNotSupportedException"}},fs=__toESM(require("fs")),path=__toESM(require("path")),crypto=__toESM(require("crypto")),BaseCache=class{constructor(e,t=path.join(process.cwd(),"tmp",".cache"),n="cache.json"){this.CACHE_MAX_AGE_MS=6048e5,this.CLEANUP_PROBABILITY=.01,this.LOCK_TIMEOUT_MS=1e3,this.lockAcquired=!1,this.lockAcquireFailures=0,this.requestIdToUsedHashes={},this.logger=e,this.cacheDir=t,this.cacheFile=path.join(t,n),this.lockFile=path.join(t,"cache.lock"),this.ensureCacheDirectory(),this.setupProcessHandlers()}setupProcessHandlers(){const e=()=>{this.releaseLock(),process.exit()};process.on("exit",e),process.on("SIGINT",e),process.on("SIGTERM",e),process.on("uncaughtException",(t=>{this.logger({category:"base_cache",message:"uncaught exception",level:2,auxiliary:{error:{value:t.message,type:"string"},trace:{value:t.stack,type:"string"}}}),this.lockAcquired&&e()}))}ensureCacheDirectory(){fs.existsSync(this.cacheDir)||(fs.mkdirSync(this.cacheDir,{recursive:!0}),this.logger({category:"base_cache",message:"created cache directory",level:1,auxiliary:{cacheDir:{value:this.cacheDir,type:"string"}}}))}createHash(e){return crypto.createHash("sha256").update(JSON.stringify(e)).digest("hex")}sleep(e){return new Promise((t=>setTimeout(t,e)))}acquireLock(){return __async(this,null,(function*(){const e=Date.now();for(;Date.now()-e<this.LOCK_TIMEOUT_MS;)try{if(fs.existsSync(this.lockFile)){Date.now()-fs.statSync(this.lockFile).mtimeMs>this.LOCK_TIMEOUT_MS&&(fs.unlinkSync(this.lockFile),this.logger({category:"base_cache",message:"Stale lock file removed",level:1}))}return fs.writeFileSync(this.lockFile,process.pid.toString(),{flag:"wx"}),this.lockAcquireFailures=0,this.lockAcquired=!0,this.logger({category:"base_cache",message:"Lock acquired",level:1}),!0}catch(e){this.logger({category:"base_cache",message:"error acquiring lock",level:2,auxiliary:{trace:{value:e.stack,type:"string"},message:{value:e.message,type:"string"}}}),yield this.sleep(5)}return this.logger({category:"base_cache",message:"Failed to acquire lock after timeout",level:2}),this.lockAcquireFailures++,this.lockAcquireFailures>=3&&(this.logger({category:"base_cache",message:"Failed to acquire lock 3 times in a row. Releasing lock manually.",level:1}),this.releaseLock()),!1}))}releaseLock(){try{fs.existsSync(this.lockFile)&&(fs.unlinkSync(this.lockFile),this.logger({category:"base_cache",message:"Lock released",level:1})),this.lockAcquired=!1}catch(e){this.logger({category:"base_cache",message:"error releasing lock",level:2,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}})}}cleanupStaleEntries(){return __async(this,null,(function*(){if(yield this.acquireLock())try{const e=this.readCache(),t=Date.now();let n=0;for(const[r,s]of Object.entries(e))t-s.timestamp>this.CACHE_MAX_AGE_MS&&(delete e[r],n++);n>0&&(this.writeCache(e),this.logger({category:"llm_cache",message:"cleaned up stale cache entries",level:1,auxiliary:{entriesRemoved:{value:n.toString(),type:"integer"}}}))}catch(e){this.logger({category:"llm_cache",message:"error during cache cleanup",level:2,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}})}finally{this.releaseLock()}else this.logger({category:"llm_cache",message:"failed to acquire lock for cleanup",level:2})}))}readCache(){if(fs.existsSync(this.cacheFile))try{const e=fs.readFileSync(this.cacheFile,"utf-8");return JSON.parse(e)}catch(e){return this.logger({category:"base_cache",message:"error reading cache file. resetting cache.",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}}),this.resetCache(),{}}return{}}writeCache(e){try{fs.writeFileSync(this.cacheFile,JSON.stringify(e,null,2)),this.logger({category:"base_cache",message:"Cache written to file",level:1})}catch(e){this.logger({category:"base_cache",message:"error writing cache file",level:2,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}})}finally{this.releaseLock()}}get(e,t){return __async(this,null,(function*(){if(!(yield this.acquireLock()))return this.logger({category:"base_cache",message:"Failed to acquire lock for getting cache",level:2}),null;try{const n=this.createHash(e),r=this.readCache();return r[n]?(this.trackRequestIdUsage(t,n),r[n].data):null}catch(e){return this.logger({category:"base_cache",message:"error getting cache. resetting cache.",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}}),this.resetCache(),null}finally{this.releaseLock()}}))}set(e,t,n){return __async(this,null,(function*(){if(yield this.acquireLock())try{const r=this.createHash(e),s=this.readCache();s[r]={data:t,timestamp:Date.now(),requestId:n},this.writeCache(s),this.trackRequestIdUsage(n,r)}catch(e){this.logger({category:"base_cache",message:"error setting cache. resetting cache.",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}}),this.resetCache()}finally{this.releaseLock(),Math.random()<this.CLEANUP_PROBABILITY&&this.cleanupStaleEntries()}else this.logger({category:"base_cache",message:"Failed to acquire lock for setting cache",level:2})}))}delete(e){return __async(this,null,(function*(){if(yield this.acquireLock())try{const t=this.createHash(e),n=this.readCache();n[t]?(delete n[t],this.writeCache(n)):this.logger({category:"base_cache",message:"Cache entry not found to delete",level:1})}catch(e){this.logger({category:"base_cache",message:"error removing cache entry",level:2,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}})}finally{this.releaseLock()}else this.logger({category:"base_cache",message:"Failed to acquire lock for removing cache entry",level:2})}))}trackRequestIdUsage(e,t){var n;null!=(n=this.requestIdToUsedHashes)[e]||(n[e]=[]),this.requestIdToUsedHashes[e].push(t)}deleteCacheForRequestId(e){return __async(this,null,(function*(){var t;if(yield this.acquireLock())try{const n=this.readCache(),r=null!=(t=this.requestIdToUsedHashes[e])?t:[];let s=0;for(const e of r)n[e]&&(delete n[e],s++);s>0?this.writeCache(n):this.logger({category:"base_cache",message:"no cache entries found for requestId",level:1,auxiliary:{requestId:{value:e,type:"string"}}}),delete this.requestIdToUsedHashes[e]}catch(t){this.logger({category:"base_cache",message:"error deleting cache for requestId",level:2,auxiliary:{error:{value:t.message,type:"string"},trace:{value:t.stack,type:"string"},requestId:{value:e,type:"string"}}})}finally{this.releaseLock()}else this.logger({category:"base_cache",message:"Failed to acquire lock for deleting cache",level:2})}))}resetCache(){try{fs.writeFileSync(this.cacheFile,"{}"),this.requestIdToUsedHashes={}}catch(e){this.logger({category:"base_cache",message:"error resetting cache",level:2,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}})}finally{this.releaseLock()}}},ActionCache=class e extends BaseCache{constructor(e,t,n){super(e,t,n||"action_cache.json")}addActionStep(e){return __async(this,arguments,(function*({url:e,action:t,previousSelectors:n,playwrightCommand:r,componentString:s,xpaths:o,newStepString:i,completed:a,requestId:l}){this.logger({category:"action_cache",message:"adding action step to cache",level:1,auxiliary:{action:{value:t,type:"string"},requestId:{value:l,type:"string"},url:{value:e,type:"string"},previousSelectors:{value:JSON.stringify(n),type:"object"}}}),yield this.set({url:e,action:t,previousSelectors:n},{playwrightCommand:r,componentString:s,xpaths:o,newStepString:i,completed:a,previousSelectors:n,action:t},l)}))}getActionStep(t){return __async(this,arguments,(function*({url:t,action:n,previousSelectors:r,requestId:s}){const o=yield __superGet(e.prototype,this,"get").call(this,{url:t,action:n,previousSelectors:r},s);return o||null}))}removeActionStep(t){return __async(this,null,(function*(){yield __superGet(e.prototype,this,"delete").call(this,t)}))}clearAction(t){return __async(this,null,(function*(){yield __superGet(e.prototype,this,"deleteCacheForRequestId").call(this,t),this.logger({category:"action_cache",message:"cleared action for ID",level:1,auxiliary:{requestId:{value:t,type:"string"}}})}))}resetCache(){return __async(this,null,(function*(){yield __superGet(e.prototype,this,"resetCache").call(this),this.logger({category:"action_cache",message:"Action cache has been reset.",level:1})}))}},import_zod2=require("zod"),actSystemPrompt="\n# Instructions\nYou are a browser automation assistant. Your job is to accomplish the user's goal across multiple model calls by running playwright commands.\n\n## Input\nYou will receive:\n1. the user's overall goal\n2. the steps that you've taken so far\n3. a list of active DOM elements in this chunk to consider to get closer to the goal. \n4. Optionally, a list of variable names that the user has provided that you may use to accomplish the goal. To use the variables, you must use the special <|VARIABLE_NAME|> syntax.\n5. Optionally, custom instructions will be provided by the user. If the user's instructions are not relevant to the current task, ignore them. Otherwise, make sure to adhere to them.\n\n\n## Your Goal / Specification\nYou have 2 tools that you can call: doAction, and skipSection. Do action only performs Playwright actions. Do exactly what the user's goal is. Do not perform any other actions or exceed the scope of the goal.\nIf the user's goal will be accomplished after running the playwright action, set completed to true. Better to have completed set to true if your are not sure.\n\nNote 1: If there is a popup on the page for cookies or advertising that has nothing to do with the goal, try to close it first before proceeding. As this can block the goal from being completed.\nNote 2: Sometimes what your are looking for is hidden behind and element you need to interact with. For example, sliders, buttons, etc...\n\nAgain, if the user's goal will be accomplished after running the playwright action, set completed to true. Also, if the user provides custom instructions, it is imperative that you follow them no matter what.\n",verifyActCompletionSystemPrompt="\nYou are a browser automation assistant. The job has given you a goal and a list of steps that have been taken so far. Your job is to determine if the user's goal has been completed based on the provided information.\n\n# Input\nYou will receive:\n1. The user's goal: A clear description of what the user wants to achieve.\n2. Steps taken so far: A list of actions that have been performed up to this point.\n\n# Your Task\nAnalyze the provided information to determine if the user's goal has been fully completed.\n\n# Output\nReturn a boolean value:\n- true: If the goal has been definitively completed based on the steps taken and the current page.\n- false: If the goal has not been completed or if there's any uncertainty about its completion.\n\n# Important Considerations\n- False positives are okay. False negatives are not okay.\n- Look for evidence of errors on the page or something having gone wrong in completing the goal. If one does not exist, return true.\n";function buildVerifyActCompletionSystemPrompt(){return{role:"system",content:verifyActCompletionSystemPrompt}}function buildVerifyActCompletionUserPrompt(e,t="None",n){let r=`\n# My Goal\n${e}\n\n# Steps You've Taken So Far\n${t}\n`;return n&&(r+=`\n# Active DOM Elements on the current page\n${n}\n`),{role:"user",content:r}}function buildUserInstructionsString(e){return e?`\n\n# Custom Instructions Provided by the User\n    \nPlease keep the user's instructions in mind when performing actions. If the user's instructions are not relevant to the current task, ignore them.\n\nUser Instructions:\n${e}`:""}function buildActSystemPrompt(e){return{role:"system",content:[actSystemPrompt,buildUserInstructionsString(e)].filter(Boolean).join("\n\n")}}function buildActUserPrompt(e,t="None",n,r){let s=`\n# My Goal\n${e}\n\n# Steps You've Taken So Far\n${t}\n\n# Current Active Dom Elements\n${n}\n`;return r&&Object.keys(r).length>0&&(s+=`\n# Variables\n${Object.keys(r).map((e=>`<|${e.toUpperCase()}|>`)).join("\n")}\n`),{role:"user",content:s}}var actTools=[{type:"function",name:"doAction",description:"execute the next playwright step that directly accomplishes the goal",parameters:{type:"object",required:["method","element","args","step","completed"],properties:{method:{type:"string",description:"The playwright function to call."},element:{type:"number",description:"The element number to act on"},args:{type:"array",description:"The required arguments",items:{type:"string",description:"The argument to pass to the function"}},step:{type:"string",description:"human readable description of the step that is taken in the past tense. Please be very detailed."},why:{type:"string",description:"why is this step taken? how does it advance the goal?"},completed:{type:"boolean",description:"true if the goal should be accomplished after this step"}}}},{type:"function",name:"skipSection",description:"skips this area of the webpage because the current goal cannot be accomplished here",parameters:{type:"object",properties:{reason:{type:"string",description:"reason that no action is taken"}}}}];function buildExtractSystemPrompt(e=!1,t=!0,n){const r=t?"A text representation of a webpage to extract information from.":"A list of DOM elements to extract from.",s=`\nPrint the exact text from the ${t?"text-rendered webpage":"DOM elements"} with all symbols, characters, and endlines as is.\nPrint null or an empty string if no new information is found.\n  `.trim(),o=e?"\nONLY print the content using the print_extracted_data tool provided.\nONLY print the content using the print_extracted_data tool provided.\n  ".trim():"",i=t?"Once you are given the text-rendered webpage, \n    you must thoroughly and meticulously analyze it. Be very careful to ensure that you\n    do not miss any important information.":"",a=buildUserInstructionsString(n);return{role:"system",content:`You are extracting content on behalf of a user.\n  If a user asks you to extract a 'list' of information, or 'all' information, \n  YOU MUST EXTRACT ALL OF THE INFORMATION THAT THE USER REQUESTS.\n   \n  You will be given:\n1. An instruction\n2. ${r}\n\n${s}\n${o}${i?`\n\n${i}`:""}${a?`\n\n${a}`:""}`.replace(/\s+/g," ")}}function buildExtractUserPrompt(e,t,n=!1){let r=`Instruction: ${e}\nDOM: ${t}`;return n&&(r+="\nONLY print the content using the print_extracted_data tool provided.\nONLY print the content using the print_extracted_data tool provided."),{role:"user",content:r}}var refineSystemPrompt="You are tasked with refining and filtering information for the final output based on newly extracted and previously extracted content. Your responsibilities are:\n1. Remove exact duplicates for elements in arrays and objects.\n2. For text fields, append or update relevant text if the new content is an extension, replacement, or continuation.\n3. For non-text fields (e.g., numbers, booleans), update with new values if they differ.\n4. Add any completely new fields or objects ONLY IF they correspond to the provided schema.\n\nReturn the updated content that includes both the previous content and the new, non-duplicate, or extended information.";function buildRefineSystemPrompt(){return{role:"system",content:refineSystemPrompt}}function buildRefineUserPrompt(e,t,n){return{role:"user",content:`Instruction: ${e}\nPreviously extracted content: ${JSON.stringify(t,null,2)}\nNewly extracted content: ${JSON.stringify(n,null,2)}\nRefined content:`}}var metadataSystemPrompt="You are an AI assistant tasked with evaluating the progress and completion status of an extraction task.\nAnalyze the extraction response and determine if the task is completed or if more information is needed.\n\nStrictly abide by the following criteria:\n1. Once the instruction has been satisfied by the current extraction response, ALWAYS set completion status to true and stop processing, regardless of remaining chunks.\n2. Only set completion status to false if BOTH of these conditions are true:\n   - The instruction has not been satisfied yet\n   - There are still chunks left to process (chunksTotal > chunksSeen)";function buildMetadataSystemPrompt(){return{role:"system",content:metadataSystemPrompt}}function buildMetadataPrompt(e,t,n,r){return{role:"user",content:`Instruction: ${e}\nExtracted content: ${JSON.stringify(t,null,2)}\nchunksSeen: ${n}\nchunksTotal: ${r}`}}function buildObserveSystemPrompt(e,t=!1){return{role:"system",content:[`\nYou are helping the user automate the browser by finding elements based on what the user wants to observe in the page.\nYou will be given:\n1. a instruction of elements to observe\n2. ${t?"a hierarchical accessibility tree showing the semantic structure of the page. The tree is a hybrid of the DOM and the accessibility tree.":"a numbered list of possible elements"}\n\nReturn an array of elements that match the instruction if they exist, otherwise return an empty array.`.replace(/\s+/g," "),buildUserInstructionsString(e)].filter(Boolean).join("\n\n")}}function buildObserveUserMessage(e,t,n=!1){return{role:"user",content:`instruction: ${e}\n${n?"Accessibility Tree":"DOM"}: ${t}`}}function verifyActCompletion(e){return __async(this,arguments,(function*({goal:e,steps:t,llmClient:n,domElements:r,logger:s,requestId:o}){const i=import_zod2.z.object({completed:import_zod2.z.boolean().describe("true if the goal is accomplished")}),a=yield n.createChatCompletion({options:{messages:[buildVerifyActCompletionSystemPrompt(),buildVerifyActCompletionUserPrompt(e,t,r)],temperature:.1,top_p:1,frequency_penalty:0,presence_penalty:0,response_model:{name:"Verification",schema:i},requestId:o},logger:s});return a&&"object"==typeof a?void 0===a.completed?(s({category:"VerifyAct",message:"Missing 'completed' field in response"}),!1):a.completed:(s({category:"VerifyAct",message:"Unexpected response format: "+JSON.stringify(a)}),!1)}))}function fillInVariables(e,t){let n=e;return Object.entries(t).forEach((([e,t])=>{const r=`<|${e.toUpperCase()}|>`;n=n.replace(r,t)})),n}function act(e){return __async(this,arguments,(function*({action:e,domElements:t,steps:n,llmClient:r,retries:s=0,logger:o,requestId:i,variables:a,userProvidedInstructions:l}){const c=[buildActSystemPrompt(l),buildActUserPrompt(e,n,t,a)],u=(yield r.createChatCompletion({options:{messages:c,temperature:.1,top_p:1,frequency_penalty:0,presence_penalty:0,tool_choice:"auto",tools:actTools,requestId:i},logger:o})).choices[0].message.tool_calls;return u&&u.length>0?"skipSection"===u[0].function.name?null:JSON.parse(u[0].function.arguments):s>=2?(o({category:"Act",message:"No tool calls found in response"}),null):act({action:e,domElements:t,steps:n,llmClient:r,retries:s+1,logger:o,requestId:i})}))}function extract(e){return __async(this,arguments,(function*({instruction:e,previouslyExtractedContent:t,domElements:n,schema:r,llmClient:s,chunksSeen:o,chunksTotal:i,requestId:a,logger:l,isUsingTextExtract:c,userProvidedInstructions:u}){const d="anthropic"===s.type,h=yield s.createChatCompletion({options:{messages:[buildExtractSystemPrompt(d,c,u),buildExtractUserPrompt(e,n,d)],response_model:{schema:r,name:"Extraction"},temperature:.1,top_p:1,frequency_penalty:0,presence_penalty:0,requestId:a},logger:l}),g=yield s.createChatCompletion({options:{messages:[buildRefineSystemPrompt(),buildRefineUserPrompt(e,t,h)],response_model:{schema:r,name:"RefinedExtraction"},temperature:.1,top_p:1,frequency_penalty:0,presence_penalty:0,requestId:a},logger:l}),m=import_zod2.z.object({progress:import_zod2.z.string().describe("progress of what has been extracted so far, as concise as possible"),completed:import_zod2.z.boolean().describe("true if the goal is now accomplished. Use this conservatively, only when you are sure that the goal has been completed.")}),p=yield s.createChatCompletion({options:{messages:[buildMetadataSystemPrompt(),buildMetadataPrompt(e,g,o,i)],response_model:{name:"Metadata",schema:m},temperature:.1,top_p:1,frequency_penalty:0,presence_penalty:0,requestId:a},logger:l});return __spreadProps(__spreadValues({},g),{metadata:p})}))}function observe(e){return __async(this,arguments,(function*({instruction:e,domElements:t,llmClient:n,requestId:r,isUsingAccessibilityTree:s,userProvidedInstructions:o,logger:i,returnAction:a=!1}){var l,c;const u=import_zod2.z.object({elements:import_zod2.z.array(import_zod2.z.object(__spreadValues({elementId:import_zod2.z.number().describe("the number of the element"),description:import_zod2.z.string().describe(s?"a description of the accessible element and its purpose":"a description of the element and what it is relevant for")},a?{method:import_zod2.z.string().describe("the candidate method/action to interact with the element. Select one of the available Playwright interaction methods."),arguments:import_zod2.z.array(import_zod2.z.string().describe("the arguments to pass to the method. For example, for a click, the arguments are empty, but for a fill, the arguments are the value to fill in."))}:{}))).describe(s?"an array of accessible elements that match the instruction":"an array of elements that match the instruction")});return{elements:null!=(c=null==(l=(yield n.createChatCompletion({options:{messages:[buildObserveSystemPrompt(o,s),buildObserveUserMessage(e,t,s)],response_model:{schema:u,name:"Observation"},temperature:.1,top_p:1,frequency_penalty:0,presence_penalty:0,requestId:r},logger:i})).elements)?void 0:l.map((e=>{const t={elementId:Number(e.elementId),description:String(e.description)};return a?__spreadProps(__spreadValues({},t),{method:String(e.method),arguments:e.arguments}):t})))?c:[]}}))}var import_crypto=__toESM(require("crypto")),HEURISTIC_CHAR_WIDTH=5;function generateId(e){return import_crypto.default.createHash("sha256").update(e).digest("hex")}function formatText(e,t){const n=[...e].sort(((e,t)=>e.bottom_left.y-t.bottom_left.y)),r=new Map;for(const e of n){let t;for(const n of r.keys())if(Math.abs(n-e.bottom_left.y)<1){t=n;break}void 0!==t?r.get(t).push(e):r.set(e.bottom_left.y,[e])}const s=Array.from(r.keys()).sort(((e,t)=>e-t)),o=[];for(const e of s){const t=r.get(e);t.sort(((e,t)=>e.bottom_left.x-t.bottom_left.x));const n=groupWordsInSentence(t);o.push(n)}let i=0;for(const e of o){let n=0;for(const r of e){const e=Math.round(r.bottom_left_normalized.x*(t/HEURISTIC_CHAR_WIDTH))+r.text.length;e>n&&(n=e)}n>i&&(i=n)}i+=20;const a=Math.max(i,1),l=o.map((e=>Math.min(...e.map((e=>e.bottom_left.y))))),c=[];for(let e=1;e<l.length;e++)c.push(l[e]-l[e-1]);const u=c.length>0?median(c):0;let d=[],h=-1;for(let e=0;e<o.length;e++){if(0===e)h++,ensureLineExists(d,h,a);else{const t=l[e]-l[e-1];let n=0;u>0&&t>1.2*u&&(n=Math.max(Math.round(t/u)-1,0));for(let e=0;e<n;e++)h++,ensureLineExists(d,h,a);h++,ensureLineExists(d,h,a)}const n=o[e];for(const e of n){const n=e.text,r=Math.round(e.bottom_left_normalized.x*(t/HEURISTIC_CHAR_WIDTH));for(let e=0;e<n.length;e++){const t=r+e;t<a&&(d[h][t]=n[e])}}}d=d.map((e=>{const t=e.join("");return Array.from(t.trimEnd())}));let g=d.map((e=>e.join(""))).join("\n");return g=g.trimEnd(),g="-".repeat(a)+"\n"+g+"\n"+"-".repeat(a),g}function ensureLineExists(e,t,n){for(;t>=e.length;)e.push(new Array(n).fill(" "))}function groupWordsInSentence(e){const t=[];let n=[];for(const r of e){if(0===n.length){n.push(r);continue}const e=1,s=n[n.length-1],o=s.width/s.text.length*e,i=r.bottom_left.x<=s.bottom_left.x+s.width+o;if(Math.abs(r.height-n[0].height)<=4&&i)n.push(r);else if(n.length>0){const e=createGroupedAnnotation(n);e.text.length>0&&(t.push(e),n=[r])}}if(n.length>0){const e=createGroupedAnnotation(n);t.push(e)}return t}function createGroupedAnnotation(e){let t="";for(const n of e)[".",",",'"',"'",":",";","!","?","{","}","’","”"].includes(n.text)?t+=n.text:t+=""!==t?" "+n.text:n.text;const n=/[a-zA-Z0-9]/.test(t),r=median(e.map((e=>e.height)));return n&&r>25&&(t="**"+t+"**"),{text:t,bottom_left:{x:e[0].bottom_left.x,y:e[0].bottom_left.y},bottom_left_normalized:{x:e[0].bottom_left_normalized.x,y:e[0].bottom_left_normalized.y},width:e.reduce(((e,t)=>e+t.width),0),height:e[0].height}}function median(e){if(0===e.length)return 0;const t=[...e].sort(((e,t)=>e-t)),n=Math.floor(t.length/2);return t.length%2==0?(t[n-1]+t[n])/2:t[n]}function logLineToString(e){var t;try{const n=e.timestamp||(new Date).toISOString();return(null==(t=e.auxiliary)?void 0:t.error)?`${n}::[stagehand:${e.category}] ${e.message}\n ${e.auxiliary.error.value}\n ${e.auxiliary.trace.value}`:`${n}::[stagehand:${e.category}] ${e.message} ${e.auxiliary?JSON.stringify(e.auxiliary):""}`}catch(e){return console.error("Error logging line:",e),"error logging line"}}function validateZodSchema(e,t){try{return e.parse(t),!0}catch(e){return!1}}function drawObserveOverlay(e,t){return __async(this,null,(function*(){const n=t.map((e=>e.selector)).filter((e=>"xpath="!==e));yield e.evaluate((e=>{e.forEach((e=>{let t;if(e.startsWith("xpath=")){const n=e.substring(6);t=document.evaluate(n,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}else t=document.querySelector(e);if(t instanceof HTMLElement){const e=document.createElement("div");e.setAttribute("stagehandObserve","true");const n=t.getBoundingClientRect();e.style.position="absolute",e.style.left=n.left+"px",e.style.top=n.top+"px",e.style.width=n.width+"px",e.style.height=n.height+"px",e.style.backgroundColor="rgba(255, 255, 0, 0.3)",e.style.pointerEvents="none",e.style.zIndex="10000",document.body.appendChild(e)}}))}),n)}))}function clearOverlays(e){return __async(this,null,(function*(){yield e.evaluate((()=>{document.querySelectorAll('[stagehandObserve="true"]').forEach((e=>{const t=e.parentNode;for(;e.firstChild;)null==t||t.insertBefore(e.firstChild,e);null==t||t.removeChild(e)}))}))}))}var StagehandActHandler=class{constructor({verbose:e,llmProvider:t,enableCaching:n,logger:r,stagehandPage:s,userProvidedInstructions:o,selfHeal:i}){this.verbose=e,this.llmProvider=t,this.enableCaching=n,this.logger=r,this.actionCache=n?new ActionCache(this.logger):void 0,this.actions={},this.stagehandPage=s,this.userProvidedInstructions=o,this.selfHeal=i}actFromObserveResult(e){return __async(this,null,(function*(){var t;this.logger({category:"action",message:"Performing act from an ObserveResult",level:1,auxiliary:{observeResult:{value:JSON.stringify(e),type:"object"}}});const n=e.method,r=null!=(t=e.arguments)?t:[],s=e.selector.replace("xpath=","");try{return yield this._performPlaywrightMethod(n,r,s),{success:!0,message:`Action [${n}] performed successfully on selector: ${s}`,action:e.description||`ObserveResult action (${n})`}}catch(t){if(!this.selfHeal)return this.logger({category:"action",message:"Error performing act from an ObserveResult",level:1,auxiliary:{error:{value:t.message,type:"string"},trace:{value:t.stack,type:"string"}}}),{success:!1,message:`Failed to perform act: ${t.message}`,action:e.description||`ObserveResult action (${n})`};this.logger({category:"action",message:"Error performing act from an ObserveResult. Trying again with regular act method",level:1,auxiliary:{error:{value:t.message,type:"string"},trace:{value:t.stack,type:"string"},observeResult:{value:JSON.stringify(e),type:"object"}}});try{const t=e.description.toLowerCase().startsWith(n.toLowerCase())?e.description:n?`${n} ${e.description}`:e.description;yield this.stagehandPage.act(t)}catch(t){return this.logger({category:"action",message:"Error performing act from an ObserveResult",level:1,auxiliary:{error:{value:t.message,type:"string"},trace:{value:t.stack,type:"string"}}}),{success:!1,message:`Failed to perform act: ${t.message}`,action:e.description||`ObserveResult action (${n})`}}}}))}_recordAction(e,t){return __async(this,null,(function*(){const n=generateId(e);return this.actions[n]={result:t,action:e},n}))}_verifyActionCompletion(e){return __async(this,arguments,(function*({completed:e,requestId:t,action:n,steps:r,llmClient:s,domSettleTimeoutMs:o}){if(!e)return!1;yield this.stagehandPage._waitForSettledDom(o);let i=s;(s.modelName.startsWith("o1")||s.modelName.startsWith("o3"))&&(i=this.llmProvider.getClient("gpt-4o",s.clientOptions));const{outputString:a}=yield this.stagehandPage.page.evaluate((()=>window.processAllOfDom()));let l=!1;return e&&(this.logger({category:"action",message:"action marked as completed, verifying if this is true...",level:1,auxiliary:{action:{value:n,type:"string"}}}),l=yield verifyActCompletion({goal:n,steps:r,llmProvider:this.llmProvider,llmClient:i,domElements:a,logger:this.logger,requestId:t}),this.logger({category:"action",message:"action completion verification result",level:1,auxiliary:{action:{value:n,type:"string"},result:{value:l.toString(),type:"boolean"}}})),l}))}_performPlaywrightMethod(e,t,n,r){return __async(this,null,(function*(){var s,o,i,a;const l=this.stagehandPage.page.locator(`xpath=${n}`).first(),c=this.stagehandPage.page.url();if(this.logger({category:"action",message:"performing playwright method",level:2,auxiliary:{xpath:{value:n,type:"string"},method:{value:e,type:"string"}}}),"scrollIntoView"===e){this.logger({category:"action",message:"scrolling element into view",level:2,auxiliary:{xpath:{value:n,type:"string"}}});try{yield l.evaluate((e=>{e.scrollIntoView({behavior:"smooth",block:"center"})})).catch((e=>{this.logger({category:"action",message:"error scrolling element into view",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"},xpath:{value:n,type:"string"}}})}))}catch(e){throw this.logger({category:"action",message:"error scrolling element into view",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"},xpath:{value:n,type:"string"}}}),new PlaywrightCommandException(e.message)}}else if("fill"===e||"type"===e)try{yield l.fill(""),yield l.click();const e=null==(s=t[0])?void 0:s.toString();for(const t of e)yield this.stagehandPage.page.keyboard.type(t,{delay:50*Math.random()+25})}catch(e){throw this.logger({category:"action",message:"error filling element",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"},xpath:{value:n,type:"string"}}}),new PlaywrightCommandException(e.message)}else if("press"===e)try{const e=null==(o=t[0])?void 0:o.toString();yield this.stagehandPage.page.keyboard.press(e)}catch(e){throw this.logger({category:"action",message:"error pressing key",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"},key:{value:null!=(a=null==(i=t[0])?void 0:i.toString())?a:"unknown",type:"string"}}}),new PlaywrightCommandException(e.message)}else if("click"===e){this.logger({category:"action",message:"page URL before click",level:2,auxiliary:{url:{value:this.stagehandPage.page.url(),type:"string"}}});try{const e=yield l.evaluate((e=>e instanceof HTMLInputElement&&"radio"===e.type)),r=t.length?t[0]:void 0;if(e){const e=yield l.evaluate((e=>e.id));let t;e&&(t=this.stagehandPage.page.locator(`label[for="${e}"]`)),(!t||(yield t.count())<1)&&(t=this.stagehandPage.page.locator(`xpath=${n}/ancestor::label`).first()),(yield t.count())<1&&(t=l.locator("xpath=following-sibling::label").first(),(yield t.count())<1&&(t=l.locator("xpath=preceding-sibling::label").first())),(yield t.count())>0?yield t.click(r):yield l.click(r)}else{const e=t.length?t[0]:void 0;yield l.click(e)}}catch(r){throw this.logger({category:"action",message:"error performing click",level:1,auxiliary:{error:{value:r.message,type:"string"},trace:{value:r.stack,type:"string"},xpath:{value:n,type:"string"},method:{value:e,type:"string"},args:{value:JSON.stringify(t),type:"object"}}}),new PlaywrightCommandException(r.message)}this.logger({category:"action",message:"clicking element, checking for page navigation",level:1,auxiliary:{xpath:{value:n,type:"string"}}});const s=yield Promise.race([new Promise((e=>{this.stagehandPage.context.once("page",(t=>e(t))),setTimeout((()=>e(null)),1500)}))]);this.logger({category:"action",message:"clicked element",level:1,auxiliary:{newOpenedTab:{value:s?"opened a new tab":"no new tabs opened",type:"string"}}}),s&&(this.logger({category:"action",message:"new page detected (new tab) with URL",level:1,auxiliary:{url:{value:s.url(),type:"string"}}}),yield s.close(),yield this.stagehandPage.page.goto(s.url()),yield this.stagehandPage.page.waitForLoadState("domcontentloaded"),yield this.stagehandPage._waitForSettledDom(r)),yield Promise.race([this.stagehandPage.page.waitForLoadState("networkidle"),new Promise((e=>setTimeout(e,5e3)))]).catch((e=>{this.logger({category:"action",message:"network idle timeout hit",level:1,auxiliary:{trace:{value:e.stack,type:"string"},message:{value:e.message,type:"string"}}})})),this.logger({category:"action",message:"finished waiting for (possible) page navigation",level:1}),this.stagehandPage.page.url()!==c&&this.logger({category:"action",message:"new page detected with URL",level:1,auxiliary:{url:{value:this.stagehandPage.page.url(),type:"string"}}})}else{if("function"!=typeof l[e])throw this.logger({category:"action",message:"chosen method is invalid",level:1,auxiliary:{method:{value:e,type:"string"}}}),new PlaywrightCommandMethodNotSupportedException(`Method ${e} not supported`);this.logger({category:"action",message:"page URL before action",level:2,auxiliary:{url:{value:this.stagehandPage.page.url(),type:"string"}}});try{yield l[e](...t.map((e=>(null==e?void 0:e.toString())||"")))}catch(r){throw this.logger({category:"action",message:"error performing method",level:1,auxiliary:{error:{value:r.message,type:"string"},trace:{value:r.stack,type:"string"},xpath:{value:n,type:"string"},method:{value:e,type:"string"},args:{value:JSON.stringify(t),type:"object"}}}),new PlaywrightCommandException(r.message)}}yield this.stagehandPage._waitForSettledDom(r)}))}_getComponentString(e){return __async(this,null,(function*(){return yield e.evaluate((e=>{const t=e.cloneNode(!0),n=["type","name","placeholder","aria-label","role","href","title","alt"];Array.from(t.attributes).forEach((e=>{n.includes(e.name)||t.removeAttribute(e.name)}));return t.outerHTML.trim().replace(/\s+/g," ")}))}))}getElement(e,t=5e3){return __async(this,null,(function*(){try{const n=this.stagehandPage.page.locator(`xpath=${e}`).first();return yield n.waitFor({state:"attached",timeout:t}),n}catch(n){return this.logger({category:"action",message:"element not found within timeout",level:1,auxiliary:{xpath:{value:e,type:"string"},timeout_ms:{value:t.toString(),type:"integer"}}}),null}}))}_checkIfCachedStepIsValid_oneXpath(e){return __async(this,null,(function*(){this.logger({category:"action",message:"checking if cached step is valid",level:1,auxiliary:{xpath:{value:e.xpath,type:"string"},savedComponentString:{value:e.savedComponentString,type:"string"}}});try{const t=yield this.getElement(e.xpath);if(!t)return this.logger({category:"action",message:"locator not found for xpath",level:1,auxiliary:{xpath:{value:e.xpath,type:"string"}}}),!1;this.logger({category:"action",message:"locator element",level:1,auxiliary:{componentString:{value:yield this._getComponentString(t),type:"string"}}});const n=yield this._getComponentString(t);if(this.logger({category:"action",message:"current text",level:1,auxiliary:{componentString:{value:n,type:"string"}}}),!n||!e.savedComponentString)return this.logger({category:"action",message:"current text or cached text is undefined",level:1}),!1;const r=n.trim().replace(/\s+/g," "),s=e.savedComponentString.trim().replace(/\s+/g," ");return r===s||(this.logger({category:"action",message:"current text and cached text do not match",level:1,auxiliary:{currentText:{value:r,type:"string"},cachedText:{value:s,type:"string"}}}),!1)}catch(e){return this.logger({category:"action",message:"error checking if cached step is valid",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}}),!1}}))}_getValidCachedStepXpath(e){return __async(this,null,(function*(){const t=[...e.xpaths].reverse();for(const n of t){if(yield this._checkIfCachedStepIsValid_oneXpath({xpath:n,savedComponentString:e.savedComponentString}))return n}return null}))}_runCachedActionIfAvailable(e){return __async(this,arguments,(function*({action:e,previousSelectors:t,requestId:n,steps:r,chunksSeen:s,llmClient:o,retries:i,variables:a,domSettleTimeoutMs:l}){var c,u;if(!this.enableCaching)return null;const d={url:this.stagehandPage.page.url(),action:e,previousSelectors:t,requestId:n};this.logger({category:"action",message:"checking action cache",level:1,auxiliary:{cacheObj:{value:JSON.stringify(d),type:"object"}}});const h=yield this.actionCache.getActionStep(d);if(!h)return this.logger({category:"action",message:"action cache miss",level:1,auxiliary:{cacheObj:{value:JSON.stringify(d),type:"object"}}}),null;this.logger({category:"action",message:"action cache semi-hit",level:1,auxiliary:{playwrightCommand:{value:JSON.stringify(h.playwrightCommand),type:"object"}}});try{const u=yield this._getValidCachedStepXpath({xpaths:h.xpaths,savedComponentString:h.componentString});if(this.logger({category:"action",message:"cached action step is valid",level:1,auxiliary:{validXpath:{value:u,type:"string"}}}),!u)return this.logger({category:"action",message:"cached action step is invalid, removing...",level:1,auxiliary:{cacheObj:{value:JSON.stringify(d),type:"object"}}}),yield null==(c=this.actionCache)?void 0:c.removeActionStep(d),null;if(this.logger({category:"action",message:"action cache hit",level:1,auxiliary:{playwrightCommand:{value:JSON.stringify(h.playwrightCommand),type:"object"}}}),h.playwrightCommand.args=h.playwrightCommand.args.map((e=>fillInVariables(e,a))),yield this._performPlaywrightMethod(h.playwrightCommand.method,h.playwrightCommand.args,u,l),r+=h.newStepString,yield this.stagehandPage.page.evaluate((({chunksSeen:e})=>window.processDom(e)),{chunksSeen:s}),h.completed){const t=yield this._verifyActionCompletion({completed:!0,llmClient:o,steps:r,requestId:n,action:e,domSettleTimeoutMs:l});if(this.logger({category:"action",message:"action completion verification result from cache",level:1,auxiliary:{actionCompleted:{value:t.toString(),type:"boolean"}}}),t)return{success:!0,message:"action completed successfully using cached step",action:e}}return this.act({action:e,steps:r,chunksSeen:s,llmClient:o,retries:i,requestId:n,variables:a,previousSelectors:[...t,h.xpaths[0]],skipActionCacheForThisStep:!1,domSettleTimeoutMs:l})}catch(e){return this.logger({category:"action",message:"error performing cached action step",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}}),yield null==(u=this.actionCache)?void 0:u.removeActionStep(d),null}}))}act(e){return __async(this,arguments,(function*({action:e,steps:t="",chunksSeen:n,llmClient:r,retries:s=0,requestId:o,variables:i,previousSelectors:a,skipActionCacheForThisStep:l=!1,domSettleTimeoutMs:c}){var u,d;try{if(yield this.stagehandPage._waitForSettledDom(c),yield this.stagehandPage.startDomDebug(),this.enableCaching&&!l){const l=yield this._runCachedActionIfAvailable({action:e,previousSelectors:a,requestId:o,steps:t,chunksSeen:n,llmClient:r,retries:s,variables:i,domSettleTimeoutMs:c});return null!==l?l:this.act({action:e,steps:t,chunksSeen:n,llmClient:r,retries:s,requestId:o,variables:i,previousSelectors:a,skipActionCacheForThisStep:!0,domSettleTimeoutMs:c})}this.logger({category:"action",message:"running / continuing action",level:2,auxiliary:{action:{value:e,type:"string"},pageUrl:{value:this.stagehandPage.page.url(),type:"string"}}}),this.logger({category:"action",message:"processing DOM",level:2});const{outputString:h,selectorMap:g,chunk:m,chunks:p}=yield this.stagehandPage.page.evaluate((({chunksSeen:e})=>window.processDom(e)),{chunksSeen:n});this.logger({category:"action",message:"looking at chunk",level:1,auxiliary:{chunk:{value:m.toString(),type:"integer"},chunks:{value:p.length.toString(),type:"integer"},chunksSeen:{value:n.length.toString(),type:"integer"},chunksLeft:{value:(p.length-n.length).toString(),type:"integer"}}});const y=yield act({action:e,domElements:h,steps:t,llmClient:r,logger:this.logger,requestId:o,variables:i,userProvidedInstructions:this.userProvidedInstructions});if(this.logger({category:"action",message:"received response from LLM",level:1,auxiliary:{response:{value:JSON.stringify(y),type:"object"}}}),yield this.stagehandPage.cleanupDomDebug(),!y)return n.length+1<p.length?(n.push(m),this.logger({category:"action",message:"no action found in current chunk",level:1,auxiliary:{chunksSeen:{value:n.length.toString(),type:"integer"}}}),this.act({action:e,steps:t+(t.endsWith("\n")?"":"\n")+"## Step: Scrolled to another section\n",chunksSeen:n,llmClient:r,requestId:o,variables:i,previousSelectors:a,skipActionCacheForThisStep:l,domSettleTimeoutMs:c})):(this.enableCaching&&(this.llmProvider.cleanRequestCache(o),null==(u=this.actionCache)||u.deleteCacheForRequestId(o)),{success:!1,message:"Action was not able to be completed.",action:e});const f=y.element,v=g[f],b=y.method,_=y.args,w=(null==(d=h.split("\n").find((e=>e.startsWith(`${f}:`))))?void 0:d.split(":")[1])||"Element not found";this.logger({category:"action",message:"executing method",level:1,auxiliary:{method:{value:b,type:"string"},elementId:{value:f.toString(),type:"integer"},xpaths:{value:JSON.stringify(v),type:"object"},args:{value:JSON.stringify(_),type:"object"}}});try{const s=this.stagehandPage.page.url();let l=null,u=null;for(const e of v){const t=this.stagehandPage.page.locator(`xpath=${e}`).first();try{yield t.waitFor({state:"attached",timeout:2e3}),l=e,u=t;break}catch(t){this.logger({category:"action",message:"XPath not yet located; moving on",level:1,auxiliary:{xpath:{value:e,type:"string"},error:{value:t.message,type:"string"}}})}}if(!l||!u)throw new Error("None of the provided XPaths could be located.");const d=this.stagehandPage.page.url(),h=yield this._getComponentString(u),g=[..._];i&&g.forEach(((e,t)=>{"string"==typeof e&&(_[t]=fillInVariables(e,i))})),yield this._performPlaywrightMethod(b,_,l,c);const m=(t.endsWith("\n")?"":"\n")+`## Step: ${y.step}\n  Element: ${w}\n  Action: ${y.method}\n  Reasoning: ${y.why}\n`;t+=m,this.enableCaching&&this.actionCache.addActionStep({action:e,url:d,previousSelectors:a,playwrightCommand:{method:b,args:g.map((e=>(null==e?void 0:e.toString())||""))},componentString:h,requestId:o,xpaths:v,newStepString:m,completed:y.completed}).catch((e=>{this.logger({category:"action",message:"error adding action step to cache",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}})})),this.stagehandPage.page.url()!==s&&(t+=`  Result (Important): Page URL changed from ${s} to ${this.stagehandPage.page.url()}\n\n`);return(yield this._verifyActionCompletion({completed:y.completed,requestId:o,action:e,steps:t,llmClient:r,domSettleTimeoutMs:c}).catch((e=>(this.logger({category:"action",message:"error verifying action completion. Assuming action completed.",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}}),!0))))?(this.logger({category:"action",message:"action completed successfully",level:1}),yield this._recordAction(e,y.step),{success:!0,message:`Action completed successfully: ${t}${y.step}`,action:e}):(this.logger({category:"action",message:"continuing to next action step",level:1}),this.act({action:e,steps:t,llmClient:r,chunksSeen:n,requestId:o,variables:i,previousSelectors:[...a,l],skipActionCacheForThisStep:!1,domSettleTimeoutMs:c}))}catch(u){return this.logger({category:"action",message:"error performing action - d",level:1,auxiliary:{error:{value:u.message,type:"string"},trace:{value:u.stack,type:"string"},retries:{value:s.toString(),type:"integer"}}}),s<2?this.act({action:e,steps:t,llmClient:r,retries:s+1,chunksSeen:n,requestId:o,variables:i,previousSelectors:a,skipActionCacheForThisStep:l,domSettleTimeoutMs:c}):(yield this._recordAction(e,""),this.enableCaching&&(this.llmProvider.cleanRequestCache(o),this.actionCache.deleteCacheForRequestId(o)),{success:!1,message:"error performing action - a",action:e})}}catch(t){return this.logger({category:"action",message:"error performing action - b",level:1,auxiliary:{error:{value:t.message,type:"string"},trace:{value:t.stack,type:"string"}}}),this.enableCaching&&(this.llmProvider.cleanRequestCache(o),this.actionCache.deleteCacheForRequestId(o)),{success:!1,message:`Error performing action - C: ${t.message}`,action:e}}}))}},PROXIMITY_THRESHOLD=15,StagehandExtractHandler=class{constructor({stagehand:e,logger:t,stagehandPage:n,userProvidedInstructions:r}){this.stagehand=e,this.logger=t,this.stagehandPage=n,this.userProvidedInstructions=r}extract(e){return __async(this,arguments,(function*({instruction:e,schema:t,content:n={},chunksSeen:r=[],llmClient:s,requestId:o,domSettleTimeoutMs:i,useTextExtract:a=!1}){return a?this.textExtract({instruction:e,schema:t,content:n,llmClient:s,requestId:o,domSettleTimeoutMs:i}):this.domExtract({instruction:e,schema:t,content:n,chunksSeen:r,llmClient:s,requestId:o,domSettleTimeoutMs:i})}))}textExtract(e){return __async(this,arguments,(function*({instruction:e,schema:t,content:n={},llmClient:r,requestId:s,domSettleTimeoutMs:o}){this.logger({category:"extraction",message:"starting extraction",level:1,auxiliary:{instruction:{value:e,type:"string"}}}),yield this.stagehandPage._waitForSettledDom(o),yield this.stagehandPage.startDomDebug();const i=yield this.stagehandPage.page.evaluate((()=>window.storeDOM())),{selectorMap:a}=yield this.stagehand.page.evaluate((()=>window.processAllOfDom()));this.logger({category:"extraction",message:`received output from processAllOfDom. selectorMap has ${Object.keys(a).length} entries`,level:1}),yield this.stagehand.page.evaluate((()=>window.createTextBoundingBoxes()));const l=yield this.stagehand.page.evaluate((()=>window.innerWidth)),c=yield this.stagehand.page.evaluate((()=>window.innerHeight)),u=[];for(const e of Object.values(a)){const t=e[0],n=yield this.stagehandPage.page.evaluate((e=>window.getElementBoundingBoxes(e)),t);for(const e of n){const t={x:e.left,y:e.top+e.height},n={x:e.left/l,y:(e.top+e.height)/c},r={text:e.text,bottom_left:t,bottom_left_normalized:n,width:e.width,height:e.height};r.text.length>0&&u.push(r)}}const d=new Map;for(const e of u)d.has(e.text)||d.set(e.text,[]),d.get(e.text).push(e);const h=[];for(const[e,t]of d.entries())for(const n of t){h.some((t=>{if(t.text!==e)return!1;const r=t.bottom_left.x-n.bottom_left.x,s=t.bottom_left.y-n.bottom_left.y;return Math.hypot(r,s)<PROXIMITY_THRESHOLD}))||h.push(n)}yield this.stagehandPage.page.evaluate((e=>window.restoreDOM(e)),i);const g=formatText(h,l),m=yield extract({instruction:e,previouslyExtractedContent:n,domElements:g,schema:t,chunksSeen:1,chunksTotal:1,llmClient:r,requestId:s,userProvidedInstructions:this.userProvidedInstructions,logger:this.logger}),p=m,{metadata:{completed:y}}=p,f=__objRest(p,["metadata"]);return yield this.stagehandPage.cleanupDomDebug(),this.logger({category:"extraction",message:"received extraction response",auxiliary:{extraction_response:{value:JSON.stringify(m),type:"object"}}}),y?this.logger({category:"extraction",message:"extraction completed successfully",level:1,auxiliary:{extraction_response:{value:JSON.stringify(m),type:"object"}}}):this.logger({category:"extraction",message:"extraction incomplete after processing all data",level:1,auxiliary:{extraction_response:{value:JSON.stringify(m),type:"object"}}}),f}))}domExtract(e){return __async(this,arguments,(function*({instruction:e,schema:t,content:n={},chunksSeen:r=[],llmClient:s,requestId:o,domSettleTimeoutMs:i}){this.logger({category:"extraction",message:"starting extraction using old approach",level:1,auxiliary:{instruction:{value:e,type:"string"}}}),yield this.stagehandPage._waitForSettledDom(i),yield this.stagehandPage.startDomDebug();const{outputString:a,chunk:l,chunks:c}=yield this.stagehand.page.evaluate((e=>window.processDom(null!=e?e:[])),r);this.logger({category:"extraction",message:"received output from processDom.",auxiliary:{chunk:{value:l.toString(),type:"integer"},chunks_left:{value:(c.length-r.length).toString(),type:"integer"},chunks_total:{value:c.length.toString(),type:"integer"}}});const u=yield extract({instruction:e,previouslyExtractedContent:n,domElements:a,schema:t,llmClient:s,chunksSeen:r.length,chunksTotal:c.length,requestId:o,isUsingTextExtract:!1,userProvidedInstructions:this.userProvidedInstructions,logger:this.logger}),d=u,{metadata:{completed:h}}=d,g=__objRest(d,["metadata"]);return yield this.stagehandPage.cleanupDomDebug(),this.logger({category:"extraction",message:"received extraction response",auxiliary:{extraction_response:{value:JSON.stringify(u),type:"object"}}}),r.push(l),h||r.length===c.length?(this.logger({category:"extraction",message:"got response",auxiliary:{extraction_response:{value:JSON.stringify(u),type:"object"}}}),g):(this.logger({category:"extraction",message:"continuing extraction",auxiliary:{extraction_response:{value:JSON.stringify(u),type:"object"}}}),yield this.stagehandPage._waitForSettledDom(i),this.domExtract({instruction:e,schema:t,content:g,chunksSeen:r,llmClient:s,domSettleTimeoutMs:i}))}))}};function formatSimplifiedTree(e,t=0){var n;let r=`${"  ".repeat(t)}[${e.nodeId}] ${e.role}${e.name?`: ${e.name}`:""}\n`;return(null==(n=e.children)?void 0:n.length)&&(r+=e.children.map((e=>formatSimplifiedTree(e,t+1))).join("")),r}function cleanStructuralNodes(e,t,n){return __async(this,null,(function*(){if(e.nodeId&&parseInt(e.nodeId)<0)return null;if(!e.children||0===e.children.length)return"generic"===e.role||"none"===e.role?null:e;const r=e.children.map((e=>cleanStructuralNodes(e,t,n))),s=(yield Promise.all(r)).filter((e=>null!==e));if("generic"===e.role||"none"===e.role){if(1===s.length)return s[0];if(0===s.length)return null}if(t&&n&&void 0!==e.backendDOMNodeId&&("generic"===e.role||"none"===e.role))try{const{object:r}=yield t.sendCDP("DOM.resolveNode",{backendNodeId:e.backendDOMNodeId});if(r&&r.objectId)try{const{result:n}=yield t.sendCDP("Runtime.callFunctionOn",{objectId:r.objectId,functionDeclaration:'\n              function() {\n                return this.tagName ? this.tagName.toLowerCase() : "";\n              }\n            ',returnByValue:!0});(null==n?void 0:n.value)&&(e.role=n.value)}catch(t){n({category:"observation",message:`Could not fetch tagName for node ${e.backendDOMNodeId}`,level:2,auxiliary:{error:{value:t.message,type:"string"}}})}}catch(t){n({category:"observation",message:`Could not resolve DOM node ID ${e.backendDOMNodeId}`,level:2,auxiliary:{error:{value:t.message,type:"string"}}})}return s.length>0?__spreadProps(__spreadValues({},e),{children:s}):e}))}function buildHierarchicalTree(e,t,n){return __async(this,null,(function*(){const r=new Map,s=[];e.forEach((e=>{if(parseInt(e.nodeId,10)<0)return;const t=e.childIds&&e.childIds.length>0,n=e.name&&""!==e.name.trim(),s="none"!==e.role&&"generic"!==e.role&&"InlineTextBox"!==e.role;(n||t||s)&&r.set(e.nodeId,__spreadValues(__spreadValues(__spreadValues(__spreadValues({role:e.role,nodeId:e.nodeId},n&&{name:e.name}),e.description&&{description:e.description}),e.value&&{value:e.value}),void 0!==e.backendDOMNodeId&&{backendDOMNodeId:e.backendDOMNodeId}))})),e.forEach((e=>{if("Iframe"===e.role){const t={role:e.role,nodeId:e.nodeId};s.push(t)}if(e.parentId&&r.has(e.nodeId)){const t=r.get(e.parentId),n=r.get(e.nodeId);t&&n&&(t.children||(t.children=[]),t.children.push(n))}}));const o=e.filter((e=>!e.parentId&&r.has(e.nodeId))).map((e=>r.get(e.nodeId))).filter(Boolean).map((e=>cleanStructuralNodes(e,t,n))),i=(yield Promise.all(o)).filter(Boolean),a=i.map((e=>formatSimplifiedTree(e))).join("\n");return{tree:i,simplified:a,iframes:s}}))}function getAccessibilityTree(e,t){return __async(this,null,(function*(){yield e.enableCDP("Accessibility");try{const n=yield findScrollableElementIds(e),{nodes:r}=yield e.sendCDP("Accessibility.getFullAXTree"),s=Date.now(),o=yield buildHierarchicalTree(r.map((e=>{var t,r,s,o;let i=(null==(t=e.role)?void 0:t.value)||"";return n.has(e.backendDOMNodeId)&&(i="generic"===i||"none"===i?"scrollable":i?`scrollable, ${i}`:"scrollable"),{role:i,name:null==(r=e.name)?void 0:r.value,description:null==(s=e.description)?void 0:s.value,value:null==(o=e.value)?void 0:o.value,nodeId:e.nodeId,backendDOMNodeId:e.backendDOMNodeId,parentId:e.parentId,childIds:e.childIds}})),e,t);return t({category:"observation",message:`got accessibility tree in ${Date.now()-s}ms`,level:1}),o}catch(e){throw t({category:"observation",message:"Error getting accessibility tree",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}}),e}finally{yield e.disableCDP("Accessibility")}}))}var functionString='\nfunction getNodePath(el) {\n  if (!el || (el.nodeType !== Node.ELEMENT_NODE && el.nodeType !== Node.TEXT_NODE)) {\n    console.log("el is not a valid node type");\n    return "";\n  }\n\n  const parts = [];\n  let current = el;\n\n  while (current && (current.nodeType === Node.ELEMENT_NODE || current.nodeType === Node.TEXT_NODE)) {\n    let index = 0;\n    let hasSameTypeSiblings = false;\n    const siblings = current.parentElement\n      ? Array.from(current.parentElement.childNodes)\n      : [];\n\n    for (let i = 0; i < siblings.length; i++) {\n      const sibling = siblings[i];\n      if (\n        sibling.nodeType === current.nodeType &&\n        sibling.nodeName === current.nodeName\n      ) {\n        index = index + 1;\n        hasSameTypeSiblings = true;\n        if (sibling.isSameNode(current)) {\n          break;\n        }\n      }\n    }\n\n    if (!current || !current.parentNode) break;\n    if (current.nodeName.toLowerCase() === "html"){\n      parts.unshift("html");\n      break;\n    }\n\n    // text nodes are handled differently in XPath\n    if (current.nodeName !== "#text") {\n      const tagName = current.nodeName.toLowerCase();\n      const pathIndex = hasSameTypeSiblings ? `[${index}]` : "";\n      parts.unshift(`${tagName}${pathIndex}`);\n    }\n    \n    current = current.parentElement;\n  }\n\n  return parts.length ? `/${parts.join("/")}` : "";\n}';function getXPathByResolvedObjectId(e,t){return __async(this,null,(function*(){const{result:n}=yield e.send("Runtime.callFunctionOn",{objectId:t,functionDeclaration:`function() {\n      ${functionString}\n      return getNodePath(this);\n    }`,returnByValue:!0});return n.value||""}))}function findScrollableElementIds(e){return __async(this,null,(function*(){const t=yield e.page.evaluate((()=>window.getScrollableElementXpaths())),n=new Set;for(const r of t){if(!r)continue;const{result:t}=yield e.sendCDP("Runtime.evaluate",{expression:`\n        (function() {\n          const res = document.evaluate(${JSON.stringify(r)}, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);\n          return res.singleNodeValue;\n        })();\n      `,returnByValue:!1});if(null==t?void 0:t.objectId){const{node:r}=yield e.sendCDP("DOM.describeNode",{objectId:t.objectId});(null==r?void 0:r.backendNodeId)&&n.add(r.backendNodeId)}}return n}))}var StagehandObserveHandler=class{constructor({stagehand:e,logger:t,stagehandPage:n,userProvidedInstructions:r}){this.stagehand=e,this.logger=t,this.stagehandPage=n,this.userProvidedInstructions=r,this.observations={}}_recordObservation(e,t){return __async(this,null,(function*(){const n=generateId(e);return this.observations[n]={result:t,instruction:e},n}))}observe(e){return __async(this,arguments,(function*({instruction:e,llmClient:t,requestId:n,returnAction:r,onlyVisible:s,drawOverlay:o}){e||(e="Find elements that can be used for any future actions in the page. These may be navigation links, related pages, section/subsection links, buttons, or other interactive elements. Be comprehensive: if there are multiple elements that may be relevant for future actions, return all of them."),this.logger({category:"observation",message:"starting observation",level:1,auxiliary:{instruction:{value:e,type:"string"}}});let i,a={},l=[];const c=!s;if(c){yield this.stagehandPage._waitForSettledDom();const e=yield getAccessibilityTree(this.stagehandPage,this.logger);this.logger({category:"observation",message:"Getting accessibility tree data",level:1}),i=e.simplified,l=e.iframes}else{const e=yield this.stagehand.page.evaluate((()=>window.processAllOfDom().then((e=>e))));({outputString:i,selectorMap:a}=e)}const u=yield observe({instruction:e,domElements:i,llmClient:t,requestId:n,userProvidedInstructions:this.userProvidedInstructions,logger:this.logger,isUsingAccessibilityTree:c,returnAction:r});l.length>0&&l.forEach((e=>{u.elements.push({elementId:Number(e.nodeId),description:"an iframe",method:"not-supported",arguments:[]})}));const d=yield Promise.all(u.elements.map((e=>__async(this,null,(function*(){const t=e,{elementId:n}=t,r=__objRest(t,["elementId"]);if(c){this.logger({category:"observation",message:"Getting xpath for element",level:1,auxiliary:{elementId:{value:n.toString(),type:"string"}}});const e={backendNodeId:n},{object:t}=yield this.stagehandPage.sendCDP("DOM.resolveNode",e);t&&t.objectId||this.logger({category:"observation",message:`Invalid object ID returned for element: ${n}`,level:1});const s=yield getXPathByResolvedObjectId(yield this.stagehandPage.getCDPClient(),t.objectId);return s&&""!==s||this.logger({category:"observation",message:`Empty xpath returned for element: ${n}`,level:1}),__spreadProps(__spreadValues({},r),{selector:`xpath=${s}`})}return __spreadProps(__spreadValues({},r),{selector:`xpath=${a[n][0]}`})})))));return yield this.stagehandPage.cleanupDomDebug(),this.logger({category:"observation",message:"found elements",level:1,auxiliary:{elements:{value:JSON.stringify(d),type:"object"}}}),o&&(yield drawObserveOverlay(this.stagehandPage.page,d)),yield this._recordObservation(e,d),d}))}},BROWSERBASE_REGION_DOMAIN={"us-west-2":"wss://connect.usw2.browserbase.com","us-east-1":"wss://connect.use1.browserbase.com","eu-central-1":"wss://connect.euc1.browserbase.com","ap-southeast-1":"wss://connect.apse1.browserbase.com"},StagehandPage=class e{constructor(e,t,n,r,s,o){this.cdpClient=null,this.intPage=Object.assign(e,{act:()=>{throw new Error("You seem to be calling `act` on a page in an uninitialized `Stagehand` object. Ensure you are running `await stagehand.init()` on the Stagehand object before referencing the `page` object.")},extract:()=>{throw new Error("You seem to be calling `extract` on a page in an uninitialized `Stagehand` object. Ensure you are running `await stagehand.init()` on the Stagehand object before referencing the `page` object.")},observe:()=>{throw new Error("You seem to be calling `observe` on a page in an uninitialized `Stagehand` object. Ensure you are running `await stagehand.init()` on the Stagehand object before referencing the `page` object.")},on:()=>{throw new Error("You seem to be referencing a page in an uninitialized `Stagehand` object. Ensure you are running `await stagehand.init()` on the Stagehand object before referencing the `page` object.")}}),this.stagehand=t,this.intContext=n,this.llmClient=r,this.api=o,this.userProvidedInstructions=s,this.llmClient&&(this.actHandler=new StagehandActHandler({verbose:this.stagehand.verbose,llmProvider:this.stagehand.llmProvider,enableCaching:this.stagehand.enableCaching,logger:this.stagehand.logger,stagehandPage:this,stagehandContext:this.intContext,llmClient:r,userProvidedInstructions:s,selfHeal:this.stagehand.selfHeal}),this.extractHandler=new StagehandExtractHandler({stagehand:this.stagehand,logger:this.stagehand.logger,stagehandPage:this,userProvidedInstructions:s}),this.observeHandler=new StagehandObserveHandler({stagehand:this.stagehand,logger:this.stagehand.logger,stagehandPage:this,userProvidedInstructions:s}))}_refreshPageFromAPI(){return __async(this,null,(function*(){if(!this.api)return;const t=this.stagehand.browserbaseSessionID;if(!t)throw new Error("No Browserbase session ID found");const n=new import_sdk.Browserbase({apiKey:process.env.BROWSERBASE_API_KEY}),r=yield n.sessions.retrieve(t),s=`${BROWSERBASE_REGION_DOMAIN[r.region]||"wss://connect.browserbase.com"}?apiKey=${process.env.BROWSERBASE_API_KEY}&sessionId=${t}`,o=(yield import_test.chromium.connectOverCDP(s)).contexts()[0].pages()[0],i=yield new e(o,this.stagehand,this.intContext,this.llmClient,this.userProvidedInstructions,this.api).init();this.intPage=i.page,this.stagehand.debugDom&&(yield this.intPage.evaluate((e=>window.showChunks=e),this.stagehand.debugDom)),yield this.intPage.waitForLoadState("domcontentloaded"),yield this._waitForSettledDom()}))}init(){return __async(this,null,(function*(){const t=this.intPage,n=this.stagehand;return this.intPage=new Proxy(t,{get:(r,s)=>{if("goto"===s)return(e,r)=>__async(this,null,(function*(){const s=this.api?yield this.api.goto(e,r):yield t.goto(e,r);return this.api?yield this._refreshPageFromAPI():(n.debugDom&&(yield t.evaluate((e=>window.showChunks=e),n.debugDom)),yield this.intPage.waitForLoadState("domcontentloaded"),yield this._waitForSettledDom()),s}));if(this.llmClient){if("act"===s)return e=>__async(this,null,(function*(){return this.act(e)}));if("extract"===s)return e=>__async(this,null,(function*(){return this.extract(e)}));if("observe"===s)return e=>__async(this,null,(function*(){return this.observe(e)}))}else if("act"===s||"extract"===s||"observe"===s)return()=>{throw new Error("No LLM API key or LLM Client configured. An LLM API key or a custom LLM Client is required to use act, extract, or observe.")};return"on"===s?(t,r)=>"popup"===t?this.context.on("page",(t=>__async(this,null,(function*(){const s=yield StagehandContext.init(t.context(),n),o=new e(t,n,s,this.llmClient);yield o.init(),r(o.page)})))):this.context.on(t,r):r[s]}}),yield this._waitForSettledDom(),this}))}get page(){return this.intPage}get context(){return this.intContext.context}_waitForSettledDom(e){return __async(this,null,(function*(){try{const t=null!=e?e:this.stagehand.domSettleTimeoutMs;let n;yield this.page.waitForLoadState("domcontentloaded");const r=new Promise((e=>{n=setTimeout((()=>{this.stagehand.log({category:"dom",message:"DOM settle timeout exceeded, continuing anyway",level:1,auxiliary:{timeout_ms:{value:t.toString(),type:"integer"}}}),e()}),t)}));try{yield Promise.race([this.page.evaluate((()=>new Promise((e=>{"function"==typeof window.waitForDomSettle?window.waitForDomSettle().then(e):(console.warn("waitForDomSettle is not defined, considering DOM as settled"),e())})))),this.page.waitForLoadState("domcontentloaded"),this.page.waitForSelector("body"),r])}finally{clearTimeout(n)}}catch(e){this.stagehand.log({category:"dom",message:"Error in waitForSettledDom",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}})}}))}startDomDebug(){return __async(this,null,(function*(){if(this.stagehand.debugDom)try{yield this.page.evaluate((()=>{"function"==typeof window.debugDom?window.debugDom():this.stagehand.log({category:"dom",message:"debugDom is not defined",level:1})})).catch((()=>{}))}catch(e){this.stagehand.log({category:"dom",message:"Error in startDomDebug",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}})}}))}cleanupDomDebug(){return __async(this,null,(function*(){this.stagehand.debugDom&&(yield this.page.evaluate((()=>window.cleanupDebug())).catch((()=>{})))}))}act(e){return __async(this,null,(function*(){if(!this.actHandler)throw new Error("Act handler not initialized");if(yield clearOverlays(this.page),"object"==typeof e&&null!==e){if("selector"in e&&"method"in e){const t=e;return this.actHandler.actFromObserveResult(t)}if(!("action"in e))throw new Error("Invalid argument. Valid arguments are: a string, an ActOptions object, or an ObserveResult WITH 'selector' and 'method' fields.")}else{if("string"!=typeof e)throw new Error("Invalid argument: you may have called act with an empty ObserveResult.\nValid arguments are: a string, an ActOptions object, or an ObserveResult WITH 'selector' and 'method' fields.");e={action:e}}const{action:t,modelName:n,modelClientOptions:r,useVision:s,variables:o={},domSettleTimeoutMs:i}=e;if(void 0!==s&&this.stagehand.log({category:"deprecation",message:"Warning: vision is not supported in this version of Stagehand",level:1}),this.api){const t=yield this.api.act(e);return yield this._refreshPageFromAPI(),t}const a=Math.random().toString(36).substring(2),l=n?this.stagehand.llmProvider.getClient(n,r):this.llmClient;return this.stagehand.log({category:"act",message:"running act",level:1,auxiliary:{action:{value:t,type:"string"},requestId:{value:a,type:"string"},modelName:{value:l.modelName,type:"string"}}}),this.actHandler.act({action:t,llmClient:l,chunksSeen:[],requestId:a,variables:o,previousSelectors:[],skipActionCacheForThisStep:!1,domSettleTimeoutMs:i}).catch((e=>(this.stagehand.log({category:"act",message:"error acting",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}}),{success:!1,message:`Internal error: Error acting: ${e.message}`,action:t})))}))}extract(e){return __async(this,null,(function*(){if(!this.extractHandler)throw new Error("Extract handler not initialized");yield clearOverlays(this.page);const t="string"==typeof e?{instruction:e,schema:defaultExtractSchema}:e,{instruction:n,schema:r,modelName:s,modelClientOptions:o,domSettleTimeoutMs:i,useTextExtract:a}=t;if(this.api)return this.api.extract(t);const l=Math.random().toString(36).substring(2),c=s?this.stagehand.llmProvider.getClient(s,o):this.llmClient;return this.stagehand.log({category:"extract",message:"running extract",level:1,auxiliary:{instruction:{value:n,type:"string"},requestId:{value:l,type:"string"},modelName:{value:c.modelName,type:"string"}}}),this.extractHandler.extract({instruction:n,schema:r,llmClient:c,requestId:l,domSettleTimeoutMs:i,useTextExtract:a}).catch((e=>{throw this.stagehand.log({category:"extract",message:"error extracting",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}}),this.stagehand.enableCaching&&this.stagehand.llmProvider.cleanRequestCache(l),e}))}))}observe(e){return __async(this,null,(function*(){if(!this.observeHandler)throw new Error("Observe handler not initialized");yield clearOverlays(this.page);const t="string"==typeof e?{instruction:e}:e||{},{instruction:n,modelName:r,modelClientOptions:s,useVision:o,domSettleTimeoutMs:i,returnAction:a=!0,onlyVisible:l=!1,useAccessibilityTree:c,drawOverlay:u}=t;if(void 0!==c)throw this.stagehand.log({category:"deprecation",message:"useAccessibilityTree is deprecated.\n  To use accessibility tree as context:\n    1. Set onlyVisible to false (default)\n    2. Don't declare useAccessibilityTree",level:1}),new Error("useAccessibilityTree is deprecated. Use onlyVisible instead.");if(void 0!==o&&this.stagehand.log({category:"deprecation",message:"Warning: vision is not supported in this version of Stagehand",level:1}),this.api)return this.api.observe(t);const d=Math.random().toString(36).substring(2),h=r?this.stagehand.llmProvider.getClient(r,s):this.llmClient;return this.stagehand.log({category:"observe",message:"running observe",level:1,auxiliary:{instruction:{value:n,type:"string"},requestId:{value:d,type:"string"},modelName:{value:h.modelName,type:"string"},onlyVisible:{value:l?"true":"false",type:"boolean"}}}),this.observeHandler.observe({instruction:n,llmClient:h,requestId:d,domSettleTimeoutMs:i,returnAction:a,onlyVisible:l,drawOverlay:u}).catch((e=>{throw this.stagehand.log({category:"observe",message:"error observing",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"},requestId:{value:d,type:"string"},instruction:{value:n,type:"string"}}}),this.stagehand.enableCaching&&this.stagehand.llmProvider.cleanRequestCache(d),e}))}))}getCDPClient(){return __async(this,null,(function*(){return this.cdpClient||(this.cdpClient=yield this.context.newCDPSession(this.page)),this.cdpClient}))}sendCDP(e,t){return __async(this,null,(function*(){return(yield this.getCDPClient()).send(e,t||{})}))}enableCDP(e){return __async(this,null,(function*(){yield this.sendCDP(`${e}.enable`,{})}))}disableCDP(e){return __async(this,null,(function*(){yield this.sendCDP(`${e}.disable`,{})}))}},import_zod_to_json_schema=__toESM(require("zod-to-json-schema")),StagehandAPI=class{constructor({apiKey:e,projectId:t,logger:n}){this.apiKey=e,this.projectId=t,this.logger=n}init(e){return __async(this,arguments,(function*({modelName:e,modelApiKey:t,domSettleTimeoutMs:n,verbose:r,debugDom:s,systemPrompt:o,browserbaseSessionCreateParams:i}){const a=yield this.request("/healthcheck");if(401===a.status)throw new Error("Unauthorized. Ensure you provided a valid API key and that it is whitelisted.");if(200!==a.status)throw new Error(`Unknown error: ${a.status}`);const l=yield this.request("/sessions/start",{method:"POST",body:JSON.stringify({modelName:e,domSettleTimeoutMs:n,verbose:r,debugDom:s,systemPrompt:o,browserbaseSessionCreateParams:i}),headers:{"x-model-api-key":t}});if(200!==l.status)throw console.log(yield l.text()),new Error(`Unknown error: ${l.status}`);const c=yield l.json();if(!1===c.success)throw new Error(c.message);return this.sessionId=c.data.sessionId,c.data}))}act(e){return __async(this,null,(function*(){return this.execute({method:"act",args:__spreadValues({},e)})}))}extract(e){return __async(this,null,(function*(){const t=(0,import_zod_to_json_schema.default)(e.schema);return this.execute({method:"extract",args:__spreadProps(__spreadValues({},e),{schemaDefinition:t})})}))}observe(e){return __async(this,null,(function*(){return this.execute({method:"observe",args:__spreadValues({},e)})}))}goto(e,t){return __async(this,null,(function*(){return this.execute({method:"navigate",args:{url:e,options:t}})}))}end(){return __async(this,null,(function*(){return this.execute({method:"end"})}))}execute(e){return __async(this,arguments,(function*({method:e,args:t,params:n}){const r=new URLSearchParams(n).toString(),s=`/sessions/${this.sessionId}/${e}${r?`?${r}`:""}`,o=yield this.request(s,{method:"POST",body:JSON.stringify(t)});if(!o.ok){const e=yield o.text();throw new Error(`HTTP error! status: ${o.status}, body: ${e}`)}if(!o.body)throw new Error("Response body is null");const i=o.body.getReader(),a=new TextDecoder;let l="";for(;;){const{value:e,done:t}=yield i.read();if(t&&!l)return null;l+=a.decode(e,{stream:!0});const n=l.split("\n\n");l=n.pop()||"";for(const e of n)if(e.startsWith("data: "))try{const t=JSON.parse(e.slice(6));if("system"===t.type){if("error"===t.data.status)throw new Error(t.data.error);if("finished"===t.data.status)return t.data.result}else"log"===t.type&&this.logger(t.data.message)}catch(e){throw console.error("Error parsing event data:",e),new Error("Failed to parse server response")}if(t)break}}))}request(e){return __async(this,arguments,(function*(e,t={}){const n={"x-bb-api-key":this.apiKey,"x-bb-project-id":this.projectId,"x-bb-session-id":this.sessionId,"x-stream-response":"true"};"POST"===t.method&&t.body&&(n["Content-Type"]="application/json");return yield fetch(`${process.env.STAGEHAND_API_URL}${e}`,__spreadProps(__spreadValues({},t),{headers:__spreadValues(__spreadValues({},n),t.headers)}))}))}},scriptContent='(() => {\n  // lib/dom/xpathUtils.ts\n  function getParentElement(node) {\n    return isElementNode(node) ? node.parentElement : node.parentNode;\n  }\n  function getCombinations(attributes, size) {\n    const results = [];\n    function helper(start, combo) {\n      if (combo.length === size) {\n        results.push([...combo]);\n        return;\n      }\n      for (let i = start; i < attributes.length; i++) {\n        combo.push(attributes[i]);\n        helper(i + 1, combo);\n        combo.pop();\n      }\n    }\n    helper(0, []);\n    return results;\n  }\n  function isXPathFirstResultElement(xpath, target) {\n    try {\n      const result = document.evaluate(\n        xpath,\n        document.documentElement,\n        null,\n        XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n        null\n      );\n      return result.snapshotItem(0) === target;\n    } catch (error) {\n      console.warn(`Invalid XPath expression: ${xpath}`, error);\n      return false;\n    }\n  }\n  function escapeXPathString(value) {\n    if (value.includes("\'")) {\n      if (value.includes(\'"\')) {\n        return "concat(" + value.split(/(\'+)/).map((part) => {\n          if (part === "\'") {\n            return `"\'"`;\n          } else if (part.startsWith("\'") && part.endsWith("\'")) {\n            return `"${part}"`;\n          } else {\n            return `\'${part}\'`;\n          }\n        }).join(",") + ")";\n      } else {\n        return `"${value}"`;\n      }\n    } else {\n      return `\'${value}\'`;\n    }\n  }\n  async function generateXPathsForElement(element) {\n    if (!element) return [];\n    const [complexXPath, standardXPath, idBasedXPath] = await Promise.all([\n      generateComplexXPath(element),\n      generateStandardXPath(element),\n      generatedIdBasedXPath(element)\n    ]);\n    return [standardXPath, ...idBasedXPath ? [idBasedXPath] : [], complexXPath];\n  }\n  async function generateComplexXPath(element) {\n    const parts = [];\n    let currentElement = element;\n    while (currentElement && (isTextNode(currentElement) || isElementNode(currentElement))) {\n      if (isElementNode(currentElement)) {\n        const el = currentElement;\n        let selector = el.tagName.toLowerCase();\n        const attributePriority = [\n          "data-qa",\n          "data-component",\n          "data-role",\n          "role",\n          "aria-role",\n          "type",\n          "name",\n          "aria-label",\n          "placeholder",\n          "title",\n          "alt"\n        ];\n        const attributes = attributePriority.map((attr) => {\n          let value = el.getAttribute(attr);\n          if (attr === "href-full" && value) {\n            value = el.getAttribute("href");\n          }\n          return value ? { attr: attr === "href-full" ? "href" : attr, value } : null;\n        }).filter((attr) => attr !== null);\n        let uniqueSelector = "";\n        for (let i = 1; i <= attributes.length; i++) {\n          const combinations = getCombinations(attributes, i);\n          for (const combo of combinations) {\n            const conditions = combo.map((a) => `@${a.attr}=${escapeXPathString(a.value)}`).join(" and ");\n            const xpath2 = `//${selector}[${conditions}]`;\n            if (isXPathFirstResultElement(xpath2, el)) {\n              uniqueSelector = xpath2;\n              break;\n            }\n          }\n          if (uniqueSelector) break;\n        }\n        if (uniqueSelector) {\n          parts.unshift(uniqueSelector.replace("//", ""));\n          break;\n        } else {\n          const parent = getParentElement(el);\n          if (parent) {\n            const siblings = Array.from(parent.children).filter(\n              (sibling) => sibling.tagName === el.tagName\n            );\n            const index = siblings.indexOf(el) + 1;\n            selector += siblings.length > 1 ? `[${index}]` : "";\n          }\n          parts.unshift(selector);\n        }\n      }\n      currentElement = getParentElement(currentElement);\n    }\n    const xpath = "//" + parts.join("/");\n    return xpath;\n  }\n  async function generateStandardXPath(element) {\n    const parts = [];\n    while (element && (isTextNode(element) || isElementNode(element))) {\n      let index = 0;\n      let hasSameTypeSiblings = false;\n      const siblings = element.parentElement ? Array.from(element.parentElement.childNodes) : [];\n      for (let i = 0; i < siblings.length; i++) {\n        const sibling = siblings[i];\n        if (sibling.nodeType === element.nodeType && sibling.nodeName === element.nodeName) {\n          index = index + 1;\n          hasSameTypeSiblings = true;\n          if (sibling.isSameNode(element)) {\n            break;\n          }\n        }\n      }\n      if (element.nodeName !== "#text") {\n        const tagName = element.nodeName.toLowerCase();\n        const pathIndex = hasSameTypeSiblings ? `[${index}]` : "";\n        parts.unshift(`${tagName}${pathIndex}`);\n      }\n      element = element.parentElement;\n    }\n    return parts.length ? `/${parts.join("/")}` : "";\n  }\n  async function generatedIdBasedXPath(element) {\n    if (isElementNode(element) && element.id) {\n      return `//*[@id=\'${element.id}\']`;\n    }\n    return null;\n  }\n\n  // lib/dom/utils.ts\n  async function waitForDomSettle() {\n    return new Promise((resolve) => {\n      const createTimeout = () => {\n        return setTimeout(() => {\n          resolve();\n        }, 2e3);\n      };\n      let timeout = createTimeout();\n      const observer = new MutationObserver(() => {\n        clearTimeout(timeout);\n        timeout = createTimeout();\n      });\n      observer.observe(window.document.body, { childList: true, subtree: true });\n    });\n  }\n  window.waitForDomSettle = waitForDomSettle;\n  function calculateViewportHeight() {\n    return Math.ceil(window.innerHeight * 0.75);\n  }\n  function canElementScroll(elem) {\n    if (typeof elem.scrollTo !== "function") {\n      console.warn("canElementScroll: .scrollTo is not a function.");\n      return false;\n    }\n    try {\n      const originalTop = elem.scrollTop;\n      elem.scrollTo({\n        top: originalTop + 100,\n        left: 0,\n        behavior: "instant"\n      });\n      if (elem.scrollTop === originalTop) {\n        throw new Error("scrollTop did not change");\n      }\n      elem.scrollTo({\n        top: originalTop,\n        left: 0,\n        behavior: "instant"\n      });\n      return true;\n    } catch (error) {\n      console.warn("canElementScroll error:", error.message || error);\n      return false;\n    }\n  }\n\n  // lib/dom/GlobalPageContainer.ts\n  var GlobalPageContainer = class {\n    getViewportHeight() {\n      return calculateViewportHeight();\n    }\n    getScrollHeight() {\n      return document.documentElement.scrollHeight;\n    }\n    async scrollTo(offset) {\n      await new Promise((resolve) => setTimeout(resolve, 1500));\n      window.scrollTo({ top: offset, left: 0, behavior: "smooth" });\n      await this.waitForScrollEnd();\n    }\n    async waitForScrollEnd() {\n      return new Promise((resolve) => {\n        let scrollEndTimer;\n        const handleScroll = () => {\n          clearTimeout(scrollEndTimer);\n          scrollEndTimer = window.setTimeout(() => {\n            window.removeEventListener("scroll", handleScroll);\n            resolve();\n          }, 100);\n        };\n        window.addEventListener("scroll", handleScroll, { passive: true });\n        handleScroll();\n      });\n    }\n  };\n\n  // lib/dom/ElementContainer.ts\n  var ElementContainer = class {\n    constructor(el) {\n      this.el = el;\n    }\n    getViewportHeight() {\n      return this.el.clientHeight;\n    }\n    getScrollHeight() {\n      return this.el.scrollHeight;\n    }\n    async scrollTo(offset) {\n      await new Promise((resolve) => setTimeout(resolve, 1500));\n      this.el.scrollTo({ top: offset, left: 0, behavior: "smooth" });\n      await this.waitForScrollEnd();\n    }\n    async waitForScrollEnd() {\n      return new Promise((resolve) => {\n        let scrollEndTimer;\n        const handleScroll = () => {\n          clearTimeout(scrollEndTimer);\n          scrollEndTimer = window.setTimeout(() => {\n            this.el.removeEventListener("scroll", handleScroll);\n            resolve();\n          }, 100);\n        };\n        this.el.addEventListener("scroll", handleScroll, { passive: true });\n        handleScroll();\n      });\n    }\n  };\n\n  // lib/dom/containerFactory.ts\n  function createStagehandContainer(obj) {\n    if (obj instanceof Window) {\n      return new GlobalPageContainer();\n    } else {\n      return new ElementContainer(obj);\n    }\n  }\n\n  // lib/dom/process.ts\n  function isElementNode(node) {\n    return node.nodeType === Node.ELEMENT_NODE;\n  }\n  function isTextNode(node) {\n    return node.nodeType === Node.TEXT_NODE && Boolean(node.textContent?.trim());\n  }\n  function getScrollableElements(topN) {\n    const docEl = document.documentElement;\n    const scrollableElements = [docEl];\n    const allElements = document.querySelectorAll("*");\n    for (const elem of allElements) {\n      const style = window.getComputedStyle(elem);\n      const overflowY = style.overflowY;\n      const isPotentiallyScrollable = overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay";\n      if (isPotentiallyScrollable) {\n        const candidateScrollDiff = elem.scrollHeight - elem.clientHeight;\n        if (candidateScrollDiff > 0 && canElementScroll(elem)) {\n          scrollableElements.push(elem);\n        }\n      }\n    }\n    scrollableElements.sort((a, b) => b.scrollHeight - a.scrollHeight);\n    if (topN !== void 0) {\n      return scrollableElements.slice(0, topN);\n    }\n    return scrollableElements;\n  }\n  async function getScrollableElementXpaths(topN) {\n    const scrollableElems = getScrollableElements(topN);\n    const xpaths = [];\n    for (const elem of scrollableElems) {\n      const allXPaths = await generateXPathsForElement(elem);\n      const firstXPath = allXPaths?.[0] || "";\n      xpaths.push(firstXPath);\n    }\n    return xpaths;\n  }\n  async function processDom(chunksSeen) {\n    const { chunk, chunksArray } = await pickChunk(chunksSeen);\n    const container = createStagehandContainer(window);\n    const { outputString, selectorMap } = await processElements(\n      chunk,\n      true,\n      0,\n      container\n    );\n    console.log(\n      `Stagehand (Browser Process): Extracted dom elements:\n${outputString}`\n    );\n    return {\n      outputString,\n      selectorMap,\n      chunk,\n      chunks: chunksArray\n    };\n  }\n  async function processAllOfDom() {\n    console.log("Stagehand (Browser Process): Processing all of DOM");\n    const mainScrollableElements = getScrollableElements(1);\n    const mainScrollable = mainScrollableElements[0];\n    const container = mainScrollable === document.documentElement ? createStagehandContainer(window) : createStagehandContainer(mainScrollable);\n    const viewportHeight = container.getViewportHeight();\n    const documentHeight = container.getScrollHeight();\n    const totalChunks = Math.ceil(documentHeight / viewportHeight);\n    let index = 0;\n    const results = [];\n    for (let chunk = 0; chunk < totalChunks; chunk++) {\n      const result = await processElements(chunk, true, index, container);\n      results.push(result);\n      index += Object.keys(result.selectorMap).length;\n    }\n    await container.scrollTo(0);\n    const allOutputString = results.map((result) => result.outputString).join("");\n    const allSelectorMap = results.reduce(\n      (acc, result) => ({ ...acc, ...result.selectorMap }),\n      {}\n    );\n    console.log(\n      `Stagehand (Browser Process): All dom elements: ${allOutputString}`\n    );\n    return {\n      outputString: allOutputString,\n      selectorMap: allSelectorMap\n    };\n  }\n  var xpathCache = /* @__PURE__ */ new Map();\n  async function processElements(chunk, scrollToChunk = true, indexOffset = 0, container) {\n    console.time("processElements:total");\n    const stagehandContainer = container ?? createStagehandContainer(window);\n    const viewportHeight = stagehandContainer.getViewportHeight();\n    const totalScrollHeight = stagehandContainer.getScrollHeight();\n    const chunkHeight = viewportHeight * chunk;\n    const maxScrollTop = totalScrollHeight - viewportHeight;\n    const offsetTop = Math.min(chunkHeight, maxScrollTop);\n    if (scrollToChunk) {\n      console.time("processElements:scroll");\n      await stagehandContainer.scrollTo(offsetTop);\n      console.timeEnd("processElements:scroll");\n    }\n    console.log("Stagehand (Browser Process): Generating candidate elements");\n    console.time("processElements:findCandidates");\n    const DOMQueue = [...document.body.childNodes];\n    const candidateElements = [];\n    while (DOMQueue.length > 0) {\n      const element = DOMQueue.pop();\n      let shouldAddElement = false;\n      if (element && isElementNode(element)) {\n        const childrenCount = element.childNodes.length;\n        for (let i = childrenCount - 1; i >= 0; i--) {\n          const child = element.childNodes[i];\n          DOMQueue.push(child);\n        }\n        if (isInteractiveElement(element)) {\n          if (isActive(element) && isVisible(element)) {\n            shouldAddElement = true;\n          }\n        }\n        if (isLeafElement(element)) {\n          if (isActive(element) && isVisible(element)) {\n            shouldAddElement = true;\n          }\n        }\n      }\n      if (element && isTextNode(element) && isTextVisible(element)) {\n        shouldAddElement = true;\n      }\n      if (shouldAddElement) {\n        candidateElements.push(element);\n      }\n    }\n    console.timeEnd("processElements:findCandidates");\n    const selectorMap = {};\n    let outputString = "";\n    console.log(\n      `Stagehand (Browser Process): Processing candidate elements: ${candidateElements.length}`\n    );\n    console.time("processElements:processCandidates");\n    console.time("processElements:generateXPaths");\n    const xpathLists = await Promise.all(\n      candidateElements.map(async (element) => {\n        if (xpathCache.has(element)) {\n          return xpathCache.get(element);\n        }\n        const xpaths = await generateXPathsForElement(element);\n        xpathCache.set(element, xpaths);\n        return xpaths;\n      })\n    );\n    console.timeEnd("processElements:generateXPaths");\n    candidateElements.forEach((element, index) => {\n      const xpaths = xpathLists[index];\n      let elementOutput = "";\n      if (isTextNode(element)) {\n        const textContent = element.textContent?.trim();\n        if (textContent) {\n          elementOutput += `${index + indexOffset}:${textContent}\n`;\n        }\n      } else if (isElementNode(element)) {\n        const tagName = element.tagName.toLowerCase();\n        const attributes = collectEssentialAttributes(element);\n        const openingTag = `<${tagName}${attributes ? " " + attributes : ""}>`;\n        const closingTag = `</${tagName}>`;\n        const textContent = element.textContent?.trim() || "";\n        elementOutput += `${index + indexOffset}:${openingTag}${textContent}${closingTag}\n`;\n      }\n      outputString += elementOutput;\n      selectorMap[index + indexOffset] = xpaths;\n    });\n    console.timeEnd("processElements:processCandidates");\n    console.timeEnd("processElements:total");\n    return {\n      outputString,\n      selectorMap\n    };\n  }\n  function collectEssentialAttributes(element) {\n    const essentialAttributes = [\n      "id",\n      "class",\n      "href",\n      "src",\n      "aria-label",\n      "aria-name",\n      "aria-role",\n      "aria-description",\n      "aria-expanded",\n      "aria-haspopup",\n      "type",\n      "value"\n    ];\n    const attrs = essentialAttributes.map((attr) => {\n      const value = element.getAttribute(attr);\n      return value ? `${attr}="${value}"` : "";\n    }).filter((attr) => attr !== "");\n    Array.from(element.attributes).forEach((attr) => {\n      if (attr.name.startsWith("data-")) {\n        attrs.push(`${attr.name}="${attr.value}"`);\n      }\n    });\n    return attrs.join(" ");\n  }\n  function storeDOM() {\n    const originalDOM = document.body.cloneNode(true);\n    console.log("DOM state stored.");\n    return originalDOM.outerHTML;\n  }\n  function restoreDOM(storedDOM) {\n    console.log("Restoring DOM");\n    if (storedDOM) {\n      document.body.innerHTML = storedDOM;\n    } else {\n      console.error("No DOM state was provided.");\n    }\n  }\n  function createTextBoundingBoxes() {\n    const style = document.createElement("style");\n    document.head.appendChild(style);\n    if (style.sheet) {\n      style.sheet.insertRule(\n        `\n      .stagehand-highlighted-word, .stagehand-space {\n        border: 0px solid orange;\n        display: inline-block !important;\n        visibility: visible;\n      }\n    `,\n        0\n      );\n      style.sheet.insertRule(\n        `\n        code .stagehand-highlighted-word, code .stagehand-space,\n        pre .stagehand-highlighted-word, pre .stagehand-space {\n          white-space: pre-wrap;\n          display: inline !important;\n      }\n     `,\n        1\n      );\n    }\n    function applyHighlighting(root) {\n      root.querySelectorAll("body *").forEach((element) => {\n        if (element.closest(".stagehand-nav, .stagehand-marker")) {\n          return;\n        }\n        if (["SCRIPT", "STYLE", "IFRAME", "INPUT"].includes(element.tagName)) {\n          return;\n        }\n        const childNodes = Array.from(element.childNodes);\n        childNodes.forEach((node) => {\n          if (node.nodeType === 3 && node.textContent?.trim().length > 0) {\n            const textContent = node.textContent.replace(/\\u00A0/g, " ");\n            const tokens = textContent.split(/(\\s+)/g);\n            const fragment = document.createDocumentFragment();\n            const parentIsCode = element.tagName === "CODE";\n            tokens.forEach((token) => {\n              const span = document.createElement("span");\n              span.textContent = token;\n              if (parentIsCode) {\n                span.style.whiteSpace = "pre-wrap";\n                span.style.display = "inline";\n              }\n              span.className = token.trim().length === 0 ? "stagehand-space" : "stagehand-highlighted-word";\n              fragment.appendChild(span);\n            });\n            if (fragment.childNodes.length > 0 && node.parentNode) {\n              element.insertBefore(fragment, node);\n              node.remove();\n            }\n          }\n        });\n      });\n    }\n    applyHighlighting(document);\n    document.querySelectorAll("iframe").forEach((iframe) => {\n      try {\n        iframe.contentWindow?.postMessage({ action: "highlight" }, "*");\n      } catch (error) {\n        console.error("Error accessing iframe content: ", error);\n      }\n    });\n  }\n  function getElementBoundingBoxes(xpath) {\n    const element = document.evaluate(\n      xpath,\n      document,\n      null,\n      XPathResult.FIRST_ORDERED_NODE_TYPE,\n      null\n    ).singleNodeValue;\n    if (!element) return [];\n    const isValidText = (text) => text && text.trim().length > 0;\n    let dropDownElem = element.querySelector("option[selected]");\n    if (!dropDownElem) {\n      dropDownElem = element.querySelector("option");\n    }\n    if (dropDownElem) {\n      const elemText = dropDownElem.textContent || "";\n      if (isValidText(elemText)) {\n        const parentRect = element.getBoundingClientRect();\n        return [\n          {\n            text: elemText.trim(),\n            top: parentRect.top + window.scrollY,\n            left: parentRect.left + window.scrollX,\n            width: parentRect.width,\n            height: parentRect.height\n          }\n        ];\n      } else {\n        return [];\n      }\n    }\n    let placeholderText = "";\n    if ((element.tagName.toLowerCase() === "input" || element.tagName.toLowerCase() === "textarea") && element.placeholder) {\n      placeholderText = element.placeholder;\n    } else if (element.tagName.toLowerCase() === "a") {\n      placeholderText = "";\n    } else if (element.tagName.toLowerCase() === "img") {\n      placeholderText = element.alt || "";\n    }\n    const words = element.querySelectorAll(\n      ".stagehand-highlighted-word"\n    );\n    const boundingBoxes = Array.from(words).map((word) => {\n      const rect = word.getBoundingClientRect();\n      return {\n        text: word.innerText || "",\n        top: rect.top + window.scrollY,\n        left: rect.left + window.scrollX,\n        width: rect.width,\n        height: rect.height * 0.75\n      };\n    }).filter(\n      (box) => box.width > 0 && box.height > 0 && box.top >= 0 && box.left >= 0 && isValidText(box.text)\n    );\n    if (boundingBoxes.length === 0) {\n      const elementRect = element.getBoundingClientRect();\n      return [\n        {\n          text: placeholderText,\n          top: elementRect.top + window.scrollY,\n          left: elementRect.left + window.scrollX,\n          width: elementRect.width,\n          height: elementRect.height * 0.75\n        }\n      ];\n    }\n    return boundingBoxes;\n  }\n  window.processDom = processDom;\n  window.processAllOfDom = processAllOfDom;\n  window.processElements = processElements;\n  window.storeDOM = storeDOM;\n  window.restoreDOM = restoreDOM;\n  window.createTextBoundingBoxes = createTextBoundingBoxes;\n  window.getElementBoundingBoxes = getElementBoundingBoxes;\n  window.createStagehandContainer = createStagehandContainer;\n  window.getScrollableElementXpaths = getScrollableElementXpaths;\n  var leafElementDenyList = ["SVG", "IFRAME", "SCRIPT", "STYLE", "LINK"];\n  var interactiveElementTypes = [\n    "A",\n    "BUTTON",\n    "DETAILS",\n    "EMBED",\n    "INPUT",\n    "LABEL",\n    "MENU",\n    "MENUITEM",\n    "OBJECT",\n    "SELECT",\n    "TEXTAREA",\n    "SUMMARY"\n  ];\n  var interactiveRoles = [\n    "button",\n    "menu",\n    "menuitem",\n    "link",\n    "checkbox",\n    "radio",\n    "slider",\n    "tab",\n    "tabpanel",\n    "textbox",\n    "combobox",\n    "grid",\n    "listbox",\n    "option",\n    "progressbar",\n    "scrollbar",\n    "searchbox",\n    "switch",\n    "tree",\n    "treeitem",\n    "spinbutton",\n    "tooltip"\n  ];\n  var interactiveAriaRoles = ["menu", "menuitem", "button"];\n  var isVisible = (element) => {\n    const rect = element.getBoundingClientRect();\n    if (rect.width === 0 || rect.height === 0 || rect.top < 0 || rect.top > window.innerHeight) {\n      return false;\n    }\n    if (!isTopElement(element, rect)) {\n      return false;\n    }\n    const visible = element.checkVisibility({\n      checkOpacity: true,\n      checkVisibilityCSS: true\n    });\n    return visible;\n  };\n  var isTextVisible = (element) => {\n    const range = document.createRange();\n    range.selectNodeContents(element);\n    const rect = range.getBoundingClientRect();\n    if (rect.width === 0 || rect.height === 0 || rect.top < 0 || rect.top > window.innerHeight) {\n      return false;\n    }\n    const parent = element.parentElement;\n    if (!parent) {\n      return false;\n    }\n    const visible = parent.checkVisibility({\n      checkOpacity: true,\n      checkVisibilityCSS: true\n    });\n    return visible;\n  };\n  function isTopElement(elem, rect) {\n    const points = [\n      { x: rect.left + rect.width * 0.25, y: rect.top + rect.height * 0.25 },\n      { x: rect.left + rect.width * 0.75, y: rect.top + rect.height * 0.25 },\n      { x: rect.left + rect.width * 0.25, y: rect.top + rect.height * 0.75 },\n      { x: rect.left + rect.width * 0.75, y: rect.top + rect.height * 0.75 },\n      { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }\n    ];\n    return points.some((point) => {\n      const topEl = document.elementFromPoint(point.x, point.y);\n      let current = topEl;\n      while (current && current !== document.body) {\n        if (current.isSameNode(elem)) {\n          return true;\n        }\n        current = current.parentElement;\n      }\n      return false;\n    });\n  }\n  var isActive = (element) => {\n    if (element.hasAttribute("disabled") || element.hasAttribute("hidden") || element.getAttribute("aria-disabled") === "true") {\n      return false;\n    }\n    return true;\n  };\n  var isInteractiveElement = (element) => {\n    const elementType = element.tagName;\n    const elementRole = element.getAttribute("role");\n    const elementAriaRole = element.getAttribute("aria-role");\n    return elementType && interactiveElementTypes.includes(elementType) || elementRole && interactiveRoles.includes(elementRole) || elementAriaRole && interactiveAriaRoles.includes(elementAriaRole);\n  };\n  var isLeafElement = (element) => {\n    if (element.textContent === "") {\n      return false;\n    }\n    if (element.childNodes.length === 0) {\n      return !leafElementDenyList.includes(element.tagName);\n    }\n    if (element.childNodes.length === 1 && isTextNode(element.childNodes[0])) {\n      return true;\n    }\n    return false;\n  };\n  async function pickChunk(chunksSeen) {\n    const viewportHeight = calculateViewportHeight();\n    const documentHeight = document.documentElement.scrollHeight;\n    const chunks = Math.ceil(documentHeight / viewportHeight);\n    const chunksArray = Array.from({ length: chunks }, (_, i) => i);\n    const chunksRemaining = chunksArray.filter((chunk2) => {\n      return !chunksSeen.includes(chunk2);\n    });\n    const currentScrollPosition = window.scrollY;\n    const closestChunk = chunksRemaining.reduce((closest, current) => {\n      const currentChunkTop = viewportHeight * current;\n      const closestChunkTop = viewportHeight * closest;\n      return Math.abs(currentScrollPosition - currentChunkTop) < Math.abs(currentScrollPosition - closestChunkTop) ? current : closest;\n    }, chunksRemaining[0]);\n    const chunk = closestChunk;\n    if (chunk === void 0) {\n      throw new Error(`No chunks remaining to check: ${chunksRemaining}`);\n    }\n    return {\n      chunk,\n      chunksArray\n    };\n  }\n\n  // lib/dom/debug.ts\n  async function debugDom() {\n    window.chunkNumber = 0;\n    const { selectorMap: multiSelectorMap } = await window.processElements(\n      window.chunkNumber\n    );\n    const selectorMap = multiSelectorMapToSelectorMap(multiSelectorMap);\n    drawChunk(selectorMap);\n  }\n  function multiSelectorMapToSelectorMap(multiSelectorMap) {\n    return Object.fromEntries(\n      Object.entries(multiSelectorMap).map(([key, selectors]) => [\n        Number(key),\n        selectors[0]\n      ])\n    );\n  }\n  function drawChunk(selectorMap) {\n    if (!window.showChunks) return;\n    cleanupMarkers();\n    Object.values(selectorMap).forEach((selector) => {\n      const element = document.evaluate(\n        selector,\n        document,\n        null,\n        XPathResult.FIRST_ORDERED_NODE_TYPE,\n        null\n      ).singleNodeValue;\n      if (element) {\n        let rect;\n        if (element.nodeType === Node.ELEMENT_NODE) {\n          rect = element.getBoundingClientRect();\n        } else {\n          const range = document.createRange();\n          range.selectNodeContents(element);\n          rect = range.getBoundingClientRect();\n        }\n        const color = "grey";\n        const overlay = document.createElement("div");\n        overlay.style.position = "absolute";\n        overlay.style.left = `${rect.left + window.scrollX}px`;\n        overlay.style.top = `${rect.top + window.scrollY}px`;\n        overlay.style.padding = "2px";\n        overlay.style.width = `${rect.width}px`;\n        overlay.style.height = `${rect.height}px`;\n        overlay.style.backgroundColor = color;\n        overlay.className = "stagehand-marker";\n        overlay.style.opacity = "0.3";\n        overlay.style.zIndex = "1000000000";\n        overlay.style.border = "1px solid";\n        overlay.style.pointerEvents = "none";\n        document.body.appendChild(overlay);\n      }\n    });\n  }\n  async function cleanupDebug() {\n    cleanupMarkers();\n  }\n  function cleanupMarkers() {\n    const markers = document.querySelectorAll(".stagehand-marker");\n    markers.forEach((marker) => {\n      marker.remove();\n    });\n  }\n  window.debugDom = debugDom;\n  window.cleanupDebug = cleanupDebug;\n})();\n',LLMCache=class e extends BaseCache{constructor(e,t,n){super(e,t,n||"llm_calls.json")}get(t,n){return __async(this,null,(function*(){return yield __superGet(e.prototype,this,"get").call(this,t,n)}))}set(t,n,r){return __async(this,null,(function*(){yield __superGet(e.prototype,this,"set").call(this,t,n,r),this.logger({category:"llm_cache",message:"Cache miss - saved new response",level:1})}))}},import_sdk2=__toESM(require("@anthropic-ai/sdk")),import_zod_to_json_schema2=require("zod-to-json-schema"),AnnotatedScreenshotText="This is a screenshot of the current page state with the elements annotated on it. Each element id is annotated with a number to the top left of it. Duplicate annotations at the same location are under each other vertically.",LLMClient=class{constructor(e,t){this.modelName=e,this.userProvidedInstructions=t}},AnthropicClient=class extends LLMClient{constructor({enableCaching:e=!1,cache:t,modelName:n,clientOptions:r,userProvidedInstructions:s}){super(n),this.type="anthropic",this.client=new import_sdk2.default(r),this.cache=t,this.enableCaching=e,this.modelName=n,this.clientOptions=r,this.userProvidedInstructions=s}createChatCompletion(e){return __async(this,arguments,(function*({options:e,retries:t,logger:n}){var r,s;const o=__spreadValues({},e);delete o.image,n({category:"anthropic",message:"creating chat completion",level:1,auxiliary:{options:{value:JSON.stringify(o),type:"object"}}});const i={model:this.modelName,messages:e.messages,temperature:e.temperature,image:e.image,response_model:e.response_model,tools:e.tools,retries:t};if(this.enableCaching){const t=yield this.cache.get(i,e.requestId);if(t)return n({category:"llm_cache",message:"LLM cache hit - returning cached response",level:1,auxiliary:{cachedResponse:{value:JSON.stringify(t),type:"object"},requestId:{value:e.requestId,type:"string"},cacheOptions:{value:JSON.stringify(i),type:"object"}}}),t;n({category:"llm_cache",message:"LLM cache miss - no cached response found",level:1,auxiliary:{cacheOptions:{value:JSON.stringify(i),type:"object"},requestId:{value:e.requestId,type:"string"}}})}const a=e.messages.find((e=>{if("system"===e.role){if("string"==typeof e.content)return!0;if(Array.isArray(e.content))return e.content.every((e=>"image_url"!==e.type))}return!1})),l=e.messages.filter((e=>"system"!==e.role)).map((e=>"string"==typeof e.content?{role:e.role,content:e.content}:{role:e.role,content:e.content.map((e=>{if("image_url"in e){return{type:"image",source:{type:"base64",media_type:"image/jpeg",data:e.image_url.url}}}return{type:"text",text:e.text}}))}));if(e.image){const t={role:"user",content:[{type:"image",source:{type:"base64",media_type:"image/jpeg",data:e.image.buffer.toString("base64")}}]};e.image.description&&Array.isArray(t.content)&&t.content.push({type:"text",text:e.image.description}),l.push(t)}let c,u=null==(r=e.tools)?void 0:r.map((e=>({name:e.name,description:e.description,input_schema:{type:"object",properties:e.parameters.properties,required:e.parameters.required}})));if(e.response_model){const t=(0,import_zod_to_json_schema2.zodToJsonSchema)(e.response_model.schema),{properties:n,required:r}=extractSchemaProperties(t);c={name:"print_extracted_data",description:"Prints the extracted data based on the provided schema.",input_schema:{type:"object",properties:n,required:r}}}c&&(u=null!=u?u:[],u.push(c));const d=yield this.client.messages.create({model:this.modelName,max_tokens:e.maxTokens||8192,messages:l,tools:u,system:a?a.content:void 0,temperature:e.temperature});n({category:"anthropic",message:"response",level:1,auxiliary:{response:{value:JSON.stringify(d),type:"object"},requestId:{value:e.requestId,type:"string"}}});const h={id:d.id,object:"chat.completion",created:Date.now(),model:d.model,choices:[{index:0,message:{role:"assistant",content:(null==(s=d.content.find((e=>"text"===e.type)))?void 0:s.text)||null,tool_calls:d.content.filter((e=>"tool_use"===e.type)).map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.input)}})))},finish_reason:d.stop_reason}],usage:{prompt_tokens:d.usage.input_tokens,completion_tokens:d.usage.output_tokens,total_tokens:d.usage.input_tokens+d.usage.output_tokens}};if(n({category:"anthropic",message:"transformed response",level:1,auxiliary:{transformedResponse:{value:JSON.stringify(h),type:"object"},requestId:{value:e.requestId,type:"string"}}}),e.response_model){const r=d.content.find((e=>"tool_use"===e.type));if(r&&"input"in r){const t=r.input;return this.enableCaching&&this.cache.set(i,t,e.requestId),t}if(!t||t<5)return this.createChatCompletion({options:e,logger:n,retries:(null!=t?t:0)+1});throw n({category:"anthropic",message:"error creating chat completion",level:1,auxiliary:{requestId:{value:e.requestId,type:"string"}}}),new Error("Create Chat Completion Failed: No tool use with input in response")}return this.enableCaching&&(this.cache.set(i,h,e.requestId),n({category:"anthropic",message:"cached response",level:1,auxiliary:{requestId:{value:e.requestId,type:"string"},transformedResponse:{value:JSON.stringify(h),type:"object"},cacheOptions:{value:JSON.stringify(i),type:"object"}}})),h}))}},extractSchemaProperties=e=>{var t;const n=(null==(t=e.definitions)?void 0:t.MySchema)||e;return{properties:n.properties,required:n.required}},import_openai=__toESM(require("openai")),import_zod3=require("openai/helpers/zod"),import_zod_to_json_schema3=__toESM(require("zod-to-json-schema")),OpenAIClient=class extends LLMClient{constructor({enableCaching:e=!1,cache:t,modelName:n,clientOptions:r}){super(n),this.type="openai",this.clientOptions=r,this.client=new import_openai.default(r),this.cache=t,this.enableCaching=e,this.modelName=n}createChatCompletion(e){return __async(this,arguments,(function*({options:e,logger:t,retries:n=3}){var r,s,o;let i=e,a=!1;if(this.modelName.startsWith("o1")||this.modelName.startsWith("o3")){let{tool_choice:e,top_p:t,frequency_penalty:n,presence_penalty:o,temperature:l}=i;if(r=i,({tool_choice:e,top_p:t,frequency_penalty:n,presence_penalty:o,temperature:l}=r),i=__objRest(r,["tool_choice","top_p","frequency_penalty","presence_penalty","temperature"]),i.messages=i.messages.map((e=>__spreadProps(__spreadValues({},e),{role:"user"}))),i.tools&&i.response_model)throw new Error("Cannot use both tool and response_model for o1 models");if(i.tools){let{tools:e}=i;s=i,({tools:e}=s),i=__objRest(s,["tools"]),a=!0,i.messages.push({role:"user",content:`You have the following tools available to you:\n${JSON.stringify(e)}\n\n          Respond with the following zod schema format to use a method: {\n            "name": "<tool_name>",\n            "arguments": <tool_args>\n          }\n          \n          Do not include any other text or formattings like \`\`\` in your response. Just the JSON object.`})}}if(i.temperature&&(this.modelName.startsWith("o1")||this.modelName.startsWith("o3")))throw new Error("Temperature is not supported for o1 models");const l=i,{image:c,requestId:u}=l,d=__objRest(l,["image","requestId"]);t({category:"openai",message:"creating chat completion",level:1,auxiliary:{options:{value:JSON.stringify(__spreadProps(__spreadValues({},d),{requestId:u})),type:"object"},modelName:{value:this.modelName,type:"string"}}});const h={model:this.modelName,messages:i.messages,temperature:i.temperature,top_p:i.top_p,frequency_penalty:i.frequency_penalty,presence_penalty:i.presence_penalty,image:c,response_model:i.response_model};if(this.enableCaching){const e=yield this.cache.get(h,i.requestId);if(e)return t({category:"llm_cache",message:"LLM cache hit - returning cached response",level:1,auxiliary:{requestId:{value:i.requestId,type:"string"},cachedResponse:{value:JSON.stringify(e),type:"object"}}}),e;t({category:"llm_cache",message:"LLM cache miss - no cached response found",level:1,auxiliary:{requestId:{value:i.requestId,type:"string"}}})}if(i.image){const e={role:"user",content:[{type:"image_url",image_url:{url:`data:image/jpeg;base64,${i.image.buffer.toString("base64")}`}},...i.image.description?[{type:"text",text:i.image.description}]:[]]};i.messages.push(e)}let g;if(i.response_model)if(this.modelName.startsWith("o1")||this.modelName.startsWith("o3"))try{const e=JSON.stringify((0,import_zod_to_json_schema3.default)(i.response_model.schema));i.messages.push({role:"user",content:`Respond in this zod schema format:\n${e}\n\n\n          Do not include any other text, formatting or markdown in your output. Do not include \`\`\` or \`\`\`json in your response. Only the JSON object itself.`})}catch(e){if(t({category:"openai",message:"Failed to parse response model schema",level:0}),n>0)return this.createChatCompletion({options:i,logger:t,retries:n-1});throw e}else g=(0,import_zod3.zodResponseFormat)(i.response_model.schema,i.response_model.name);const m=__spreadProps(__spreadValues({},d),{model:this.modelName}),{response_model:p}=m,y=__objRest(m,["response_model"]);t({category:"openai",message:"creating chat completion",level:1,auxiliary:{openAiOptions:{value:JSON.stringify(y),type:"object"}}});const f=i.messages.map((e=>{if(Array.isArray(e.content)){const t=e.content.map((e=>{if("image_url"in e){return{image_url:{url:e.image_url.url},type:"image_url"}}return{text:e.text,type:"text"}}));if("system"===e.role){return __spreadProps(__spreadValues({},e),{role:"system",content:t.filter((e=>"text"===e.type))})}if("user"===e.role){return __spreadProps(__spreadValues({},e),{role:"user",content:t})}return __spreadProps(__spreadValues({},e),{role:"assistant",content:t.filter((e=>"text"===e.type))})}return{role:"user",content:e.content}})),v=__spreadProps(__spreadValues({},y),{model:this.modelName,messages:f,response_format:g,stream:!1,tools:null==(o=i.tools)?void 0:o.map((e=>({function:{name:e.name,description:e.description,parameters:e.parameters},type:"function"})))}),b=yield this.client.chat.completions.create(v);if(a)try{const e=JSON.parse(b.choices[0].message.content);b.choices[0].message.tool_calls=[{function:{name:e.name,arguments:JSON.stringify(e.arguments)},type:"function",id:"-1"}],b.choices[0].message.content=null}catch(e){if(t({category:"openai",message:"Failed to parse tool call response",level:0,auxiliary:{error:{value:e.message,type:"string"},content:{value:b.choices[0].message.content,type:"string"}}}),n>0)return this.createChatCompletion({options:i,logger:t,retries:n-1});throw e}if(t({category:"openai",message:"response",level:1,auxiliary:{response:{value:JSON.stringify(b),type:"object"},requestId:{value:u,type:"string"}}}),i.response_model){const e=b.choices[0].message.content,r=JSON.parse(e);if(!validateZodSchema(i.response_model.schema,r)){if(n>0)return this.createChatCompletion({options:i,logger:t,retries:n-1});throw new Error("Invalid response schema")}return this.enableCaching&&this.cache.set(h,__spreadValues({},r),i.requestId),r}return this.enableCaching&&(t({category:"llm_cache",message:"caching response",level:1,auxiliary:{requestId:{value:i.requestId,type:"string"},cacheOptions:{value:JSON.stringify(h),type:"object"},response:{value:JSON.stringify(b),type:"object"}}}),this.cache.set(h,b,i.requestId)),b}))}},modelToProviderMap={"gpt-4o":"openai","gpt-4o-mini":"openai","gpt-4o-2024-08-06":"openai","gpt-4o-2024-11-20":"openai","gpt-4o-2024-05-13":"openai","o1-mini":"openai","o1-preview":"openai","o3-mini":"openai","claude-3-5-sonnet-latest":"anthropic","claude-3-5-sonnet-20240620":"anthropic","claude-3-5-sonnet-20241022":"anthropic"},LLMProvider=class{constructor(e,t){this.logger=e,this.enableCaching=t,this.cache=t?new LLMCache(e):void 0}cleanRequestCache(e){this.enableCaching&&(this.logger({category:"llm_cache",message:"cleaning up cache",level:1,auxiliary:{requestId:{value:e,type:"string"}}}),this.cache.deleteCacheForRequestId(e))}getClient(e,t){const n=modelToProviderMap[e];if(!n)throw new Error(`Unsupported model: ${e}`);switch(n){case"openai":return new OpenAIClient({logger:this.logger,enableCaching:this.enableCaching,cache:this.cache,modelName:e,clientOptions:t});case"anthropic":return new AnthropicClient({logger:this.logger,enableCaching:this.enableCaching,cache:this.cache,modelName:e,clientOptions:t});default:throw new Error(`Unsupported provider: ${n}`)}}static getModelProvider(e){return modelToProviderMap[e]}},import_zod4=require("zod"),AvailableModelSchema=import_zod4.z.enum(["gpt-4o","gpt-4o-mini","gpt-4o-2024-11-20","gpt-4o-2024-08-06","gpt-4o-2024-05-13","claude-3-5-sonnet-latest","claude-3-5-sonnet-20241022","claude-3-5-sonnet-20240620","o1-mini","o1-preview","o3-mini"]);import_dotenv.default.config({path:".env"});var DEFAULT_MODEL_NAME="gpt-4o",BROWSERBASE_REGION_DOMAIN2={"us-west-2":"wss://connect.usw2.browserbase.com","us-east-1":"wss://connect.use1.browserbase.com","eu-central-1":"wss://connect.euc1.browserbase.com","ap-southeast-1":"wss://connect.apse1.browserbase.com"};function getBrowser(e,t,n="LOCAL",r=!1,s,o,i,a){return __async(this,null,(function*(){var l,c,u,d,h,g,m,p,y,f,v,b,_,w,x,S,E,C;if("BROWSERBASE"===n&&(e||(s({category:"init",message:"BROWSERBASE_API_KEY is required to use BROWSERBASE env. Defaulting to LOCAL.",level:0}),n="LOCAL"),t||s({category:"init",message:"BROWSERBASE_PROJECT_ID is required for some Browserbase features that may not work without it.",level:1})),"BROWSERBASE"===n){if(!e)throw new Error("BROWSERBASE_API_KEY is required.");let r,a,l,c;const u=new import_sdk3.Browserbase({apiKey:e});if(i)try{const t=yield u.sessions.retrieve(i);if("RUNNING"!==t.status)throw new Error(`Session ${i} is not running (status: ${t.status})`);l=i;c=`${BROWSERBASE_REGION_DOMAIN2[t.region]||"wss://connect.browserbase.com"}?apiKey=${e}&sessionId=${l}`,s({category:"init",message:"resuming existing browserbase session...",level:1,auxiliary:{sessionId:{value:l,type:"string"}}})}catch(e){throw s({category:"init",message:"failed to resume session",level:1,auxiliary:{error:{value:e.message,type:"string"},trace:{value:e.stack,type:"string"}}}),e}else{if(s({category:"init",message:"creating new browserbase session...",level:0}),!t)throw new Error("BROWSERBASE_PROJECT_ID is required for new Browserbase sessions.");const e=yield u.sessions.create(__spreadValues({projectId:t},o));l=e.id,c=e.connectUrl,s({category:"init",message:"created new browserbase session",level:1,auxiliary:{sessionId:{value:l,type:"string"}}})}const d=yield import_test2.chromium.connectOverCDP(c),{debuggerUrl:h}=yield u.sessions.debug(l);r=h,a=`https://www.browserbase.com/sessions/${l}`,s({category:"init",message:i?"browserbase session resumed":"browserbase session started",level:0,auxiliary:{sessionUrl:{value:a,type:"string"},debugUrl:{value:r,type:"string"},sessionId:{value:l,type:"string"}}});const g=d.contexts()[0];return{browser:d,context:g,debugUrl:r,sessionUrl:a,sessionId:l,env:n}}{s({category:"init",message:"launching local browser",level:0,auxiliary:{headless:{value:r.toString(),type:"boolean"}}}),a&&s({category:"init",message:"local browser launch options",level:0,auxiliary:{localLaunchOptions:{value:JSON.stringify(a),type:"string"}}});let e=null==a?void 0:a.userDataDir;if(!e){const t=import_path.default.join(import_os.default.tmpdir(),"stagehand");import_fs.default.existsSync(t)||import_fs.default.mkdirSync(t,{recursive:!0});const n=import_fs.default.mkdtempSync(import_path.default.join(t,"ctx_"));import_fs.default.mkdirSync(import_path.default.join(n,"userdir/Default"),{recursive:!0});const r={plugins:{always_open_pdf_externally:!0}};import_fs.default.writeFileSync(import_path.default.join(n,"userdir/Default/Preferences"),JSON.stringify(r)),e=import_path.default.join(n,"userdir")}let t=null==a?void 0:a.downloadsPath;t||(t=import_path.default.join(process.cwd(),"downloads"),import_fs.default.mkdirSync(t,{recursive:!0}));const n=yield import_test2.chromium.launchPersistentContext(e,{acceptDownloads:null==(l=null==a?void 0:a.acceptDownloads)||l,headless:null!=(c=null==a?void 0:a.headless)?c:r,viewport:{width:null!=(d=null==(u=null==a?void 0:a.viewport)?void 0:u.width)?d:1250,height:null!=(g=null==(h=null==a?void 0:a.viewport)?void 0:h.height)?g:800},locale:null!=(m=null==a?void 0:a.locale)?m:"en-US",timezoneId:null!=(p=null==a?void 0:a.timezoneId)?p:"America/New_York",deviceScaleFactor:null!=(y=null==a?void 0:a.deviceScaleFactor)?y:1,args:null!=(f=null==a?void 0:a.args)?f:["--enable-webgl","--use-gl=swiftshader","--enable-accelerated-2d-canvas","--disable-blink-features=AutomationControlled","--disable-web-security"],bypassCSP:null==(v=null==a?void 0:a.bypassCSP)||v,proxy:null==a?void 0:a.proxy,geolocation:null==a?void 0:a.geolocation,hasTouch:null==(b=null==a?void 0:a.hasTouch)||b,ignoreHTTPSErrors:null==(_=null==a?void 0:a.ignoreHTTPSErrors)||_,permissions:null==a?void 0:a.permissions,recordHar:null==a?void 0:a.recordHar,recordVideo:null==a?void 0:a.recordVideo,tracesDir:null==a?void 0:a.tracesDir,extraHTTPHeaders:null==a?void 0:a.extraHTTPHeaders,chromiumSandbox:null!=(w=null==a?void 0:a.chromiumSandbox)&&w,devtools:null!=(x=null==a?void 0:a.devtools)&&x,env:null==a?void 0:a.env,executablePath:null==a?void 0:a.executablePath,handleSIGHUP:null==(S=null==a?void 0:a.handleSIGHUP)||S,handleSIGINT:null==(E=null==a?void 0:a.handleSIGINT)||E,handleSIGTERM:null==(C=null==a?void 0:a.handleSIGTERM)||C,ignoreDefaultArgs:null==a?void 0:a.ignoreDefaultArgs});return(null==a?void 0:a.cookies)&&n.addCookies(a.cookies),s({category:"init",message:"local browser started successfully."}),yield applyStealthScripts(n),{context:n,contextPath:e,env:"LOCAL"}}}))}function applyStealthScripts(e){return __async(this,null,(function*(){yield e.addInitScript((()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}}),Object.defineProperty(navigator,"languages",{get:()=>["en-US","en"]}),Object.defineProperty(navigator,"plugins",{get:()=>[1,2,3,4,5]}),delete window.__playwright,delete window.__pw_manual,delete window.__PW_inspect,Object.defineProperty(navigator,"headless",{get:()=>!1});const e=window.navigator.permissions.query;window.navigator.permissions.query=t=>"notifications"===t.name?Promise.resolve({state:Notification.permission}):e(t)}))}))}var defaultLogger=e=>__async(void 0,null,(function*(){console.log(logLineToString(e))})),Stagehand=class{constructor({env:e,apiKey:t,projectId:n,verbose:r,debugDom:s,llmProvider:o,llmClient:i,headless:a,logger:l,browserbaseSessionCreateParams:c,domSettleTimeoutMs:u,enableCaching:d,browserbaseSessionID:h,modelName:g,modelClientOptions:m,systemPrompt:p,useAPI:y,localBrowserLaunchOptions:f,selfHeal:v=!0}={env:"BROWSERBASE"}){if(this.pending_logs_to_send_to_browserbase=[],this.is_processing_browserbase_logs=!1,this.externalLogger=l||defaultLogger,this.enableCaching=null!=d?d:process.env.ENABLE_CACHING&&"true"===process.env.ENABLE_CACHING,this.llmProvider=o||new LLMProvider(this.logger,this.enableCaching),this.intEnv=e,this.apiKey=null!=t?t:process.env.BROWSERBASE_API_KEY,this.projectId=null!=n?n:process.env.BROWSERBASE_PROJECT_ID,this.verbose=null!=r?r:0,this.debugDom=null!=s&&s,i)this.llmClient=i;else try{this.llmClient=this.llmProvider.getClient(null!=g?g:DEFAULT_MODEL_NAME,m)}catch(e){this.llmClient=void 0}if(this.domSettleTimeoutMs=null!=u?u:3e4,this.headless=null!=a&&a,this.browserbaseSessionCreateParams=c,this.browserbaseSessionID=h,this.userProvidedInstructions=p,this.usingAPI=null!=y&&y,this.modelName=null!=g?g:DEFAULT_MODEL_NAME,this.usingAPI&&"LOCAL"===e)throw new Error("API mode can only be used with BROWSERBASE environment");if(this.usingAPI&&!process.env.STAGEHAND_API_URL)throw new Error("STAGEHAND_API_URL is required when using the API. Please set it in your environment variables.");this.selfHeal=v,this.localBrowserLaunchOptions=f}get logger(){return e=>{this.log(e)}}get page(){if(!this.stagehandPage)throw new Error("Stagehand not initialized. Make sure to await stagehand.init() first.");return this.stagehandPage.page}get env(){return"BROWSERBASE"===this.intEnv&&this.apiKey&&this.projectId?"BROWSERBASE":"LOCAL"}get context(){if(!this.stagehandContext)throw new Error("Stagehand not initialized. Make sure to await stagehand.init() first.");return this.stagehandContext.context}init(e){return __async(this,null,(function*(){if(e&&console.warn("Passing parameters to init() is deprecated and will be removed in the next major version. Use constructor options instead."),this.usingAPI){this.apiClient=new StagehandAPI({apiKey:this.apiKey,projectId:this.projectId,logger:this.logger});const{sessionId:e}=yield this.apiClient.init({modelName:this.modelName,modelApiKey:"openai"===LLMProvider.getModelProvider(this.modelName)?process.env.OPENAI_API_KEY:process.env.ANTHROPIC_API_KEY,domSettleTimeoutMs:this.domSettleTimeoutMs,verbose:this.verbose,debugDom:this.debugDom,systemPrompt:this.userProvidedInstructions,browserbaseSessionCreateParams:this.browserbaseSessionCreateParams});this.browserbaseSessionID=e}const{context:t,debugUrl:n,sessionUrl:r,contextPath:s,sessionId:o,env:i}=yield getBrowser(this.apiKey,this.projectId,this.env,this.headless,this.logger,this.browserbaseSessionCreateParams,this.browserbaseSessionID,this.localBrowserLaunchOptions).catch((e=>{console.error("Error in init:",e);return{context:void 0,debugUrl:void 0,sessionUrl:void 0,sessionId:void 0,env:this.env}}));this.intEnv=i,this.contextPath=s,this.stagehandContext=yield StagehandContext.init(t,this);const a=this.context.pages()[0];return this.stagehandPage=yield new StagehandPage(a,this,this.stagehandContext,this.llmClient,this.userProvidedInstructions,this.apiClient).init(),this.headless&&(yield this.page.setViewportSize({width:1280,height:720})),yield this.context.addInitScript({content:scriptContent}),this.browserbaseSessionID=o,{debugUrl:n,sessionUrl:r,sessionId:o}}))}initFromPage(e){return __async(this,arguments,(function*({page:e}){console.warn("initFromPage is deprecated and will be removed in the next major version. To instantiate from a page, use `browserbaseSessionID` in the constructor."),this.stagehandPage=yield new StagehandPage(e,this,this.stagehandContext,this.llmClient).init(),this.stagehandContext=yield StagehandContext.init(e.context(),this);const t=this.page.goto.bind(this.page);return this.page.goto=(e,n)=>__async(this,null,(function*(){const r=yield t(e,n);return this.debugDom&&(yield this.page.evaluate((()=>window.showChunks=this.debugDom))),yield this.page.waitForLoadState("domcontentloaded"),yield this.stagehandPage._waitForSettledDom(),r})),this.headless&&(yield this.page.setViewportSize({width:1280,height:720})),yield this.context.addInitScript({content:scriptContent}),{context:this.context}}))}log(e){var t;e.level=null!=(t=e.level)?t:1,this.externalLogger&&this.externalLogger(e),this.pending_logs_to_send_to_browserbase.push(__spreadProps(__spreadValues({},e),{id:(0,import_crypto2.randomUUID)()})),this._run_browserbase_log_processing_cycle()}_run_browserbase_log_processing_cycle(){return __async(this,null,(function*(){if(this.is_processing_browserbase_logs)return;this.is_processing_browserbase_logs=!0;const e=[...this.pending_logs_to_send_to_browserbase];for(const t of e)yield this._log_to_browserbase(t);this.is_processing_browserbase_logs=!1}))}_log_to_browserbase(e){return __async(this,null,(function*(){var t;e.level=null!=(t=e.level)?t:1,this.stagehandPage&&this.verbose>=e.level&&(yield this.page.evaluate((e=>{const t=logLineToString(e);e.message.toLowerCase().includes("trace")||e.message.toLowerCase().includes("error:")?console.error(t):console.log(t)}),e).then((()=>{this.pending_logs_to_send_to_browserbase=this.pending_logs_to_send_to_browserbase.filter((t=>t.id!==e.id))})).catch((()=>{})))}))}act(e){return __async(this,null,(function*(){return yield this.stagehandPage.act(e)}))}extract(e){return __async(this,null,(function*(){return yield this.stagehandPage.extract(e)}))}observe(e){return __async(this,null,(function*(){return yield this.stagehandPage.observe(e)}))}close(){return __async(this,null,(function*(){if(this.apiClient)yield this.apiClient.end();else if(yield this.context.close(),this.contextPath)try{import_fs.default.rmSync(this.contextPath,{recursive:!0,force:!0})}catch(e){console.error("Error deleting context directory:",e)}}))}};
//# sourceMappingURL=/sm/b451b456359ac48233fffd55e91a5345bd98cb439752cb42c9aa8d3602cedc3a.map