shiplightai 0.1.25 → 0.1.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/agentHelpers-UJJ2M5QO.js +3 -0
  2. package/dist/{agentLogin-J2342DF2.js → agentLogin-IIER6KDC.js} +1 -1
  3. package/dist/{chunk-7TAH76YI.js → chunk-BQCZFA7S.js} +1 -1
  4. package/dist/{chunk-YTXNWA2O.js → chunk-JZB7Y7PT.js} +5 -5
  5. package/dist/chunk-LWNM7LR6.js +5 -0
  6. package/dist/{chunk-YHOTGR6H.js → chunk-S7EB7HNN.js} +2 -2
  7. package/dist/{chunk-AZT2TSHD.js → chunk-SFYF2Y6H.js} +12 -12
  8. package/dist/{chunk-BDIWRQLE.js → chunk-SSJRUBTH.js} +1 -1
  9. package/dist/chunk-T2JTBHI7.js +3 -0
  10. package/dist/{chunk-YDR4P3GA.js → chunk-T3H4NEVX.js} +1 -1
  11. package/dist/{chunk-XQZ4FULT.js → chunk-TZU7BU5P.js} +2 -2
  12. package/dist/cjs/fixture.cjs +122 -122
  13. package/dist/cjs/index.cjs +168 -168
  14. package/dist/cjs/reporter.cjs +4 -3
  15. package/dist/cli.js +3 -2
  16. package/dist/dist-7FN57CHM.js +3 -0
  17. package/dist/fixture.d.ts +17 -2
  18. package/dist/fixture.js +1 -1
  19. package/dist/{handler-ESLITK6N.js → handler-N7MN6JWY.js} +1 -1
  20. package/dist/index.js +1 -1
  21. package/dist/reporter.js +7 -6
  22. package/dist/static/assets/index-1KGAG7Bo.css +1 -0
  23. package/dist/static/assets/index-DNgiGgCi.js +12 -0
  24. package/dist/static/assets/index-DNgiGgCi.js.map +1 -0
  25. package/dist/static/assets/index-oUGsby9o.js +1478 -0
  26. package/dist/static/assets/index-oUGsby9o.js.map +1 -0
  27. package/dist/static/index.html +17 -0
  28. package/dist/{task-WKQB2YDZ.js → task-SVMN3OEI.js} +1 -1
  29. package/package.json +2 -1
  30. package/dist/agentHelpers-BEU5CFJJ.js +0 -3
  31. package/dist/chunk-DJDHFWEV.js +0 -3
  32. package/dist/chunk-S6IZG6S3.js +0 -5
  33. package/dist/dist-TC3HQUYV.js +0 -3
@@ -0,0 +1,3 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ const require = __createRequire(import.meta.url);
3
+ import{d as t,e as o,f as r,g as p,h as i}from"./chunk-TZU7BU5P.js";import"./chunk-BQCZFA7S.js";import"./chunk-T3H4NEVX.js";import"./chunk-YU3XZJIJ.js";import"./chunk-LWNM7LR6.js";import"./chunk-T2JTBHI7.js";import"./chunk-CSINHOOD.js";export{p as evaluateStatement,t as executeAction,r as executeStep,o as generateActionStep,i as runTask};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  const require = __createRequire(import.meta.url);
3
- import{j as a,m as o,n as t,o as i,p as r,q as s,r as e}from"./chunk-BDIWRQLE.js";import"./chunk-YHOTGR6H.js";import"./chunk-YDR4P3GA.js";import"./chunk-DJDHFWEV.js";import"./chunk-CSINHOOD.js";export{a as LoginType,o as checkLocators,r as createUnsignedInContext,e as generateAndValidateLoginLocators,s as generateValidationLocators,i as validateLogin,t as validateLoginLocators};
3
+ import{j as a,m as o,n as t,o as i,p as r,q as s,r as e}from"./chunk-SSJRUBTH.js";import"./chunk-S7EB7HNN.js";import"./chunk-T3H4NEVX.js";import"./chunk-T2JTBHI7.js";import"./chunk-CSINHOOD.js";export{a as LoginType,o as checkLocators,r as createUnsignedInContext,e as generateAndValidateLoginLocators,s as generateValidationLocators,i as validateLogin,t as validateLoginLocators};
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  const require = __createRequire(import.meta.url);
3
- import{a as lg}from"./chunk-YU3XZJIJ.js";import{b as Sn,c as le}from"./chunk-DJDHFWEV.js";import{a as _e,c as te,d as Fa}from"./chunk-CSINHOOD.js";var Qa=te((BI,Iu)=>{"use strict";var So=Object.prototype.hasOwnProperty,Cu=Object.prototype.toString,_u=Object.defineProperty,wu=Object.getOwnPropertyDescriptor,Eu=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Cu.call(e)==="[object Array]"},Tu=function(e){if(!e||Cu.call(e)!=="[object Object]")return!1;var r=So.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&So.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var o;for(o in e);return typeof o>"u"||So.call(e,o)},xu=function(e,r){_u&&r.name==="__proto__"?_u(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},Su=function(e,r){if(r==="__proto__")if(So.call(e,r)){if(wu)return wu(e,r).value}else return;return e[r]};Iu.exports=function t(){var e,r,n,o,a,i,s=arguments[0],l=1,u=arguments.length,p=!1;for(typeof s=="boolean"&&(p=s,s=arguments[1]||{},l=2),(s==null||typeof s!="object"&&typeof s!="function")&&(s={});l<u;++l)if(e=arguments[l],e!=null)for(r in e)n=Su(s,r),o=Su(e,r),s!==o&&(p&&o&&(Tu(o)||(a=Eu(o)))?(a?(a=!1,i=n&&Eu(n)?n:[]):i=n&&Tu(n)?n:{},xu(s,{name:r,newValue:t(p,i,o)})):typeof o<"u"&&xu(s,{name:r,newValue:o}));return s}});var Au=te((VI,iv)=>{iv.exports={name:"gaxios",version:"7.1.3",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2",rimraf:"^5.0.1"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}});var Ru=te((zI,ku)=>{"use strict";var sv=Au();ku.exports={pkg:sv}});var ri=te(Ct=>{"use strict";var Nu=Ct&&Ct.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ct,"__esModule",{value:!0});Ct.GaxiosError=Ct.GAXIOS_ERROR_SYMBOL=void 0;Ct.defaultErrorRedactor=Mu;var Ou=Nu(Qa()),lv=Nu(Ru()),ei=lv.default.pkg;Ct.GAXIOS_ERROR_SYMBOL=Symbol.for(`${ei.name}-gaxios-error`);var ti=class t extends Error{config;response;code;status;error;[Ct.GAXIOS_ERROR_SYMBOL]=ei.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Ct.GAXIOS_ERROR_SYMBOL in e&&e[Ct.GAXIOS_ERROR_SYMBOL]===ei.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,r,n,o){if(super(e,{cause:o}),this.config=r,this.response=n,this.error=o instanceof Error?o:void 0,this.config=(0,Ou.default)(!0,{},r),this.response&&(this.response.config=(0,Ou.default)(!0,{},this.response.config)),this.response){try{this.response.data=cv(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,r="The request failed"){let n=r;if(typeof e.data=="string"&&(n=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){n="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:n;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,a="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let s of e.data.error.errors)typeof s=="object"&&"message"in s&&typeof s.message=="string"&&i.push(s.message);return Object.assign({message:i.join(`
3
+ import{a as lg}from"./chunk-YU3XZJIJ.js";import{b as Sn,d as le}from"./chunk-T2JTBHI7.js";import{a as _e,c as te,d as Fa}from"./chunk-CSINHOOD.js";var Qa=te((BI,Iu)=>{"use strict";var So=Object.prototype.hasOwnProperty,Cu=Object.prototype.toString,_u=Object.defineProperty,wu=Object.getOwnPropertyDescriptor,Eu=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Cu.call(e)==="[object Array]"},Tu=function(e){if(!e||Cu.call(e)!=="[object Object]")return!1;var r=So.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&So.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var o;for(o in e);return typeof o>"u"||So.call(e,o)},xu=function(e,r){_u&&r.name==="__proto__"?_u(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},Su=function(e,r){if(r==="__proto__")if(So.call(e,r)){if(wu)return wu(e,r).value}else return;return e[r]};Iu.exports=function t(){var e,r,n,o,a,i,s=arguments[0],l=1,u=arguments.length,p=!1;for(typeof s=="boolean"&&(p=s,s=arguments[1]||{},l=2),(s==null||typeof s!="object"&&typeof s!="function")&&(s={});l<u;++l)if(e=arguments[l],e!=null)for(r in e)n=Su(s,r),o=Su(e,r),s!==o&&(p&&o&&(Tu(o)||(a=Eu(o)))?(a?(a=!1,i=n&&Eu(n)?n:[]):i=n&&Tu(n)?n:{},xu(s,{name:r,newValue:t(p,i,o)})):typeof o<"u"&&xu(s,{name:r,newValue:o}));return s}});var Au=te((VI,iv)=>{iv.exports={name:"gaxios",version:"7.1.3",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2",rimraf:"^5.0.1"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}});var Ru=te((zI,ku)=>{"use strict";var sv=Au();ku.exports={pkg:sv}});var ri=te(Ct=>{"use strict";var Nu=Ct&&Ct.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ct,"__esModule",{value:!0});Ct.GaxiosError=Ct.GAXIOS_ERROR_SYMBOL=void 0;Ct.defaultErrorRedactor=Mu;var Ou=Nu(Qa()),lv=Nu(Ru()),ei=lv.default.pkg;Ct.GAXIOS_ERROR_SYMBOL=Symbol.for(`${ei.name}-gaxios-error`);var ti=class t extends Error{config;response;code;status;error;[Ct.GAXIOS_ERROR_SYMBOL]=ei.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Ct.GAXIOS_ERROR_SYMBOL in e&&e[Ct.GAXIOS_ERROR_SYMBOL]===ei.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,r,n,o){if(super(e,{cause:o}),this.config=r,this.response=n,this.error=o instanceof Error?o:void 0,this.config=(0,Ou.default)(!0,{},r),this.response&&(this.response.config=(0,Ou.default)(!0,{},this.response.config)),this.response){try{this.response.data=cv(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,r="The request failed"){let n=r;if(typeof e.data=="string"&&(n=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){n="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:n;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,a="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let s of e.data.error.errors)typeof s=="object"&&"message"in s&&typeof s.message=="string"&&i.push(s.message);return Object.assign({message:i.join(`
4
4
  `)||n,code:a,status:o},e.data.error)}return Object.assign({message:n,code:a,status:o},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};Ct.GaxiosError=ti;function cv(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function Mu(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function r(a){a&&a.forEach((i,s)=>{(/^authentication$/i.test(s)||/^authorization$/i.test(s)||/secret/i.test(s))&&a.set(s,e)})}function n(a,i){if(typeof a=="object"&&a!==null&&typeof a[i]=="string"){let s=a[i];(/grant_type=/i.test(s)||/assertion=/i.test(s)||/secret/i.test(s))&&(a[i]=e)}}function o(a){!a||typeof a!="object"||(a instanceof FormData||a instanceof URLSearchParams||"forEach"in a&&"set"in a?a.forEach((i,s)=>{(["grant_type","assertion"].includes(s)||/secret/.test(s))&&a.set(s,e)}):("grant_type"in a&&(a.grant_type=e),"assertion"in a&&(a.assertion=e),"client_secret"in a&&(a.client_secret=e)))}return t.config&&(r(t.config.headers),n(t.config,"data"),o(t.config.data),n(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(Mu({config:t.response.config}),r(t.response.headers),t.response.bodyUsed&&(n(t.response,"data"),o(t.response.data))),t}});var Du=te(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.getRetryConfig=uv;async function uv(t){let e=Pu(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let r=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||r,t.config.retryConfig=e,!await(e.shouldRetry||dv)(t))return{shouldRetry:!1,config:t.config};let o=pv(e);t.config.retryConfig.currentRetryAttempt+=1;let a=e.retryBackoff?e.retryBackoff(t,o):new Promise(i=>{setTimeout(i,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await a,{shouldRetry:!0,config:t.config}}function dv(t){let e=Pu(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let r=!1;for(let[n,o]of e.statusCodesToRetry){let a=t.response.status;if(a>=n&&a<=o){r=!0;break}}if(!r)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function Pu(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function pv(t){let r=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,n=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(r,n,t.maxRetryDelay)}});var ai=te(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.GaxiosInterceptorManager=void 0;var oi=class extends Set{};Co.GaxiosInterceptorManager=oi});var Fu=te(Xr=>{"use strict";var hv=Xr&&Xr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Yr;Object.defineProperty(Xr,"__esModule",{value:!0});Xr.Gaxios=void 0;var fv=hv(Qa()),mv=_e("https"),Fr=ri(),gv=Du(),ju=_e("stream"),Lu=ai(),yv=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),vv=204,Io=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Lu.GaxiosInterceptorManager,response:new Lu.GaxiosInterceptorManager}}fetch(...e){let r=e[0],n=e[1],o,a=new Headers;return typeof r=="string"?o=new URL(r):r instanceof URL?o=r:r&&r.url&&(o=new URL(r.url)),r&&typeof r=="object"&&"headers"in r&&Yr.mergeHeaders(a,r.headers),n&&Yr.mergeHeaders(a,new Headers(n.headers)),typeof r=="object"&&!(r instanceof URL)?this.request({...n,...r,headers:a,url:o}):this.request({...n,headers:a,url:o})}async request(e={}){let r=await this.#n(e);return r=await this.#t(r),this.#r(this._request(r))}async _defaultAdapter(e){let r=e.fetchImplementation||this.defaults.fetchImplementation||await Yr.#l(),n={...e};delete n.data;let o=await r(e.url,n),a=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:a}}),Object.assign(o,{config:e,data:a})}async _request(e){try{let r;if(e.adapter?r=await e.adapter(e,this._defaultAdapter.bind(this)):r=await this._defaultAdapter(e),!e.validateStatus(r.status)){if(e.responseType==="stream"){let o=[];for await(let a of r.data)o.push(a);r.data=o.toString()}let n=Fr.GaxiosError.extractAPIErrorFromResponse(r,`Request failed with status code ${r.status}`);throw new Fr.GaxiosError(n?.message,e,r,n)}return r}catch(r){let n;r instanceof Fr.GaxiosError?n=r:r instanceof Error?n=new Fr.GaxiosError(r.message,e,void 0,r):n=new Fr.GaxiosError("Unexpected Gaxios Error",e,void 0,r);let{shouldRetry:o,config:a}=await(0,gv.getRetryConfig)(n);if(o&&a)return n.config.retryConfig.currentRetryAttempt=a.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(n),n}}async getResponseData(e,r){if(r.status===vv)return"";if(e.maxContentLength&&r.headers.has("content-length")&&e.maxContentLength<Number.parseInt(r.headers?.get("content-length")||""))throw new Fr.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(r,{config:e}));switch(e.responseType){case"stream":return r.body;case"json":{let n=await r.text();try{return JSON.parse(n)}catch{return n}}case"arraybuffer":return r.arrayBuffer();case"blob":return r.blob();case"text":return r.text();default:return this.getResponseDataFromContentType(r)}}#e(e,r=[]){let n=new URL(e),o=[...r],a=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let i of a)o.push(i.trim());for(let i of o)if(i instanceof RegExp){if(i.test(n.toString()))return!1}else if(i instanceof URL){if(i.origin===n.origin)return!1}else if(i.startsWith("*.")||i.startsWith(".")){let s=i.replace(/^\*\./,".");if(n.hostname.endsWith(s))return!1}else if(i===n.origin||i===n.hostname||i===n.href)return!1;return!0}async#t(e){let r=Promise.resolve(e);for(let n of this.interceptors.request.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#r(e){let r=Promise.resolve(e);for(let n of this.interceptors.response.values())n&&(r=r.then(n.resolved,n.rejected));return r}async#n(e){let r=new Headers(this.defaults.headers);Yr.mergeHeaders(r,e.headers);let n=(0,fv.default)(!0,{},this.defaults,e);if(!n.url)throw new Error("URL is required.");if(n.baseURL&&(n.url=new URL(n.url,n.baseURL)),n.url=new URL(n.url),n.params)if(n.paramsSerializer){let i=n.paramsSerializer(n.params);i.startsWith("?")&&(i=i.slice(1));let s=n.url.toString().includes("?")?"&":"?";n.url=n.url+s+i}else{let i=n.url instanceof URL?n.url:new URL(n.url);for(let[s,l]of new URLSearchParams(n.params))i.searchParams.append(s,l);n.url=i}typeof e.maxContentLength=="number"&&(n.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(n.follow=e.maxRedirects);let o=typeof n.data=="string"||n.data instanceof ArrayBuffer||n.data instanceof Blob||globalThis.File&&n.data instanceof File||n.data instanceof FormData||n.data instanceof ju.Readable||n.data instanceof ReadableStream||n.data instanceof String||n.data instanceof URLSearchParams||ArrayBuffer.isView(n.data)||["Blob","File","FormData"].includes(n.data?.constructor?.name||"");if(n.multipart?.length){let i=await yv();r.set("content-type",`multipart/related; boundary=${i}`),n.body=ju.Readable.from(this.getMultipartRequest(n.multipart,i))}else o?n.body=n.data:typeof n.data=="object"?r.get("Content-Type")==="application/x-www-form-urlencoded"?n.body=n.paramsSerializer?n.paramsSerializer(n.data):new URLSearchParams(n.data):(r.has("content-type")||r.set("content-type","application/json"),n.body=JSON.stringify(n.data)):n.data&&(n.body=n.data);n.validateStatus=n.validateStatus||this.validateStatus,n.responseType=n.responseType||"unknown",!r.has("accept")&&n.responseType==="json"&&r.set("accept","application/json");let a=n.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!n.agent)if(a&&this.#e(n.url,n.noProxy)){let i=await Yr.#s();this.agentCache.has(a)?n.agent=this.agentCache.get(a):(n.agent=new i(a,{cert:n.cert,key:n.key}),this.agentCache.set(a,n.agent))}else n.cert&&n.key&&(this.agentCache.has(n.key)?n.agent=this.agentCache.get(n.key):(n.agent=new mv.Agent({cert:n.cert,key:n.key}),this.agentCache.set(n.key,n.agent)));return typeof n.errorRedactor!="function"&&n.errorRedactor!==!1&&(n.errorRedactor=Fr.defaultErrorRedactor),n.body&&!("duplex"in n)&&(n.duplex="half"),this.#o(n),Object.assign(n,{headers:r,url:n.url instanceof URL?n.url:new URL(n.url)})}#o(e){if(e.timeout){let r=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,r]):e.signal=r}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let r=e.headers.get("Content-Type");if(r===null)return e.text();if(r=r.toLowerCase(),r.includes("application/json")){let n=await e.text();try{n=JSON.parse(n)}catch{}return n}else return r.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,r){let n=`--${r}--`;for(let o of e){let a=o.headers.get("Content-Type")||"application/octet-stream";yield`--${r}\r
5
5
  Content-Type: ${a}\r
6
6
  \r
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  const require = __createRequire(import.meta.url);
3
- import{a as Yt,b as Nr,c as pe,d as Dr,e as $r,f as Cr,g as Br,h as Pr,i as Or,l as Rr,o as Xt,r as qr}from"./chunk-BDIWRQLE.js";import{a as Pe,c as Zu,d as Ir,e as Jt,f as Me,g as He,h as Ue}from"./chunk-XQZ4FULT.js";import{A as Ar,B as Lr,a as er,b as tr,c as ur,d as rr,e as ir,f as ar,g as nr,h as sr,i as or,j as cr,k as lr,l as dr,m as fr,n as hr,o as pr,p as mr,q as gr,r as br,s as xr,t as wr,u as yr,v as vr,w as kr,x as Sr,y as Tr,z as Er}from"./chunk-AZT2TSHD.js";import{a as Gt,b as _r,d as zt,g as Kt,h as qe}from"./chunk-YHOTGR6H.js";import{a as Oe,b as O,c as Vt,d as Wt,f as Qu,n as Re}from"./chunk-7TAH76YI.js";import{a as S}from"./chunk-YDR4P3GA.js";import{b as jt,c as o}from"./chunk-DJDHFWEV.js";import{a as nn,c as X,d as Xu}from"./chunk-CSINHOOD.js";var zi=X((wl,Gi)=>{"use strict";var Ws=function(t){return Gs(t)&&!zs(t)};function Gs(e){return!!e&&typeof e=="object"}function zs(e){var t=Object.prototype.toString.call(e);return t==="[object RegExp]"||t==="[object Date]"||Ys(e)}var Ks=typeof Symbol=="function"&&Symbol.for,Js=Ks?Symbol.for("react.element"):60103;function Ys(e){return e.$$typeof===Js}function Xs(e){return Array.isArray(e)?[]:{}}function De(e,t){return t.clone!==!1&&t.isMergeableObject(e)?fe(Xs(e),e,t):e}function Zs(e,t,u){return e.concat(t).map(function(r){return De(r,u)})}function Qs(e,t){if(!t.customMerge)return fe;var u=t.customMerge(e);return typeof u=="function"?u:fe}function eo(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}function Vi(e){return Object.keys(e).concat(eo(e))}function Wi(e,t){try{return t in e}catch{return!1}}function to(e,t){return Wi(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))}function uo(e,t,u){var r={};return u.isMergeableObject(e)&&Vi(e).forEach(function(i){r[i]=De(e[i],u)}),Vi(t).forEach(function(i){to(e,i)||(Wi(e,i)&&u.isMergeableObject(t[i])?r[i]=Qs(i,u)(e[i],t[i],u):r[i]=De(t[i],u))}),r}function fe(e,t,u){u=u||{},u.arrayMerge=u.arrayMerge||Zs,u.isMergeableObject=u.isMergeableObject||Ws,u.cloneUnlessOtherwiseSpecified=De;var r=Array.isArray(t),i=Array.isArray(e),a=r===i;return a?r?u.arrayMerge(e,t,u):uo(e,t,u):De(t,u)}fe.all=function(t,u){if(!Array.isArray(t))throw new Error("first argument should be an array");return t.reduce(function(r,i){return fe(r,i,u)},{})};var ro=fe;Gi.exports=ro});var ya=X(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});function g0(e){return e&&typeof e=="object"&&"default"in e?e.default:e}var wa=g0(nn("crypto")),b0=(e,t,u)=>wa.createHmac(e,Buffer.from(t,"hex")).update(Buffer.from(u,"hex")).digest().toString("hex"),x0=(e,t)=>wa.randomBytes(e).toString(t);Et.createDigest=b0;Et.createRandomBytes=x0});var ka=X(Du=>{"use strict";var w0="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",va=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];function y0(e){var t=Math.floor(e.length/5);return e.length%5===0?t:t+1}Du.encode=function(e){Buffer.isBuffer(e)||(e=new Buffer(e));for(var t=0,u=0,r=0,i=0,a=new Buffer(y0(e)*8);t<e.length;){var n=e[t];r>3?(i=n&255>>r,r=(r+5)%8,i=i<<r|(t+1<e.length?e[t+1]:0)>>8-r,t++):(i=n>>8-(r+5)&31,r=(r+5)%8,r===0&&t++),a[u]=w0.charCodeAt(i),u++}for(t=u;t<a.length;t++)a[t]=61;return a};Du.decode=function(e){var t=0,u=0,r,i=0;Buffer.isBuffer(e)||(e=new Buffer(e));for(var a=new Buffer(Math.ceil(e.length*5/8)),n=0;n<e.length&&e[n]!==61;n++){var s=e[n]-48;if(s<va.length)u=va[s],t<=3?(t=(t+5)%8,t===0?(r|=u,a[i]=r,i++,r=0):r|=255&u<<8-t):(t=(t+5)%8,r|=255&u>>>t,a[i]=r,i++,r=255&u<<8-t);else throw new Error("Invalid input - it is not base32 encoded string")}return a.slice(0,i)}});var Ta=X($u=>{"use strict";var Sa=ka();$u.encode=Sa.encode;$u.decode=Sa.decode});var Aa=X(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});function v0(e){return e&&typeof e=="object"&&"default"in e?e.default:e}var Ea=v0(Ta()),k0=(e,t)=>Ea.decode(e).toString(t),S0=(e,t)=>Ea.encode(Buffer.from(e,t).toString("ascii")).toString().replace(/=/g,"");At.keyDecoder=k0;At.keyEncoder=S0});var Ka=X(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});function $t(e){return Object.keys(e).map(t=>e[t])}(function(e){e.SHA1="sha1",e.SHA256="sha256",e.SHA512="sha512"})(m.HashAlgorithms||(m.HashAlgorithms={}));var _t=$t(m.HashAlgorithms);(function(e){e.ASCII="ascii",e.BASE64="base64",e.HEX="hex",e.LATIN1="latin1",e.UTF8="utf8"})(m.KeyEncodings||(m.KeyEncodings={}));var Cu=$t(m.KeyEncodings);(function(e){e.HOTP="hotp",e.TOTP="totp"})(m.Strategy||(m.Strategy={}));var Bu=$t(m.Strategy),Ct=()=>{throw new Error("Please provide an options.createDigest implementation.")};function Ru(e){return/^(\d+)$/.test(e)}function qu(e,t,u){return e.length>=t?e:`${Array(t+1).join(u)}${e}`.slice(-1*t)}function Mu(e){let t=`otpauth://${e.type}/{labelPrefix}:{accountName}?secret={secret}{query}`,u=[];if(Bu.indexOf(e.type)<0)throw new Error(`Expecting options.type to be one of ${Bu.join(", ")}. Received ${e.type}.`);if(e.type==="hotp"){if(e.counter==null||typeof e.counter!="number")throw new Error('Expecting options.counter to be a number when options.type is "hotp".');u.push(`&counter=${e.counter}`)}return e.type==="totp"&&e.step&&u.push(`&period=${e.step}`),e.digits&&u.push(`&digits=${e.digits}`),e.algorithm&&u.push(`&algorithm=${e.algorithm.toUpperCase()}`),e.issuer&&u.push(`&issuer=${encodeURIComponent(e.issuer)}`),t.replace("{labelPrefix}",encodeURIComponent(e.issuer||e.accountName)).replace("{accountName}",encodeURIComponent(e.accountName)).replace("{secret}",e.secret).replace("{query}",u.join(""))}var It=class e{constructor(t={}){this._defaultOptions=Object.freeze({...t}),this._options=Object.freeze({})}create(t={}){return new e(t)}clone(t={}){let u=this.create({...this._defaultOptions,...t});return u.options=this._options,u}get options(){return Object.freeze({...this._defaultOptions,...this._options})}set options(t){this._options=Object.freeze({...this._options,...t})}allOptions(){return this.options}resetOptions(){this._options=Object.freeze({})}};function Hu(e){if(typeof e.createDigest!="function")throw new Error("Expecting options.createDigest to be a function.");if(typeof e.createHmacKey!="function")throw new Error("Expecting options.createHmacKey to be a function.");if(typeof e.digits!="number")throw new Error("Expecting options.digits to be a number.");if(!e.algorithm||_t.indexOf(e.algorithm)<0)throw new Error(`Expecting options.algorithm to be one of ${_t.join(", ")}. Received ${e.algorithm}.`);if(!e.encoding||Cu.indexOf(e.encoding)<0)throw new Error(`Expecting options.encoding to be one of ${Cu.join(", ")}. Received ${e.encoding}.`)}var _a=(e,t,u)=>Buffer.from(t,u).toString("hex");function Ia(){return{algorithm:m.HashAlgorithms.SHA1,createHmacKey:_a,createDigest:Ct,digits:6,encoding:m.KeyEncodings.ASCII}}function Na(e){let t={...Ia(),...e};return Hu(t),Object.freeze(t)}function Da(e){let t=e.toString(16);return qu(t,16,"0")}function $a(e,t){let u=Buffer.from(e,"hex"),r=u[u.length-1]&15,a=((u[r]&127)<<24|(u[r+1]&255)<<16|(u[r+2]&255)<<8|u[r+3]&255)%Math.pow(10,t);return qu(String(a),t,"0")}function T0(e,t,u){let r=Da(t),i=u.createHmacKey(u.algorithm,e,u.encoding);return u.createDigest(u.algorithm,i,r)}function Bt(e,t,u){let r=u.digest||T0(e,t,u);return $a(r,u.digits)}function Ca(e,t,u,r){if(!Ru(e))return!1;let i=Bt(t,u,r);return e===i}function Ba(e,t,u,r,i){return Mu({algorithm:i.algorithm,digits:i.digits,type:m.Strategy.HOTP,accountName:e,counter:r,issuer:t,secret:u})}var Nt=class e extends It{create(t={}){return new e(t)}allOptions(){return Na(this.options)}generate(t,u){return Bt(t,u,this.allOptions())}check(t,u,r){return Ca(t,u,r,this.allOptions())}verify(t){if(typeof t!="object")throw new Error("Expecting argument 0 of verify to be an object");return this.check(t.token,t.secret,t.counter)}keyuri(t,u,r,i){return Ba(t,u,r,i,this.allOptions())}};function Pa(e){if(typeof e=="number")return[Math.abs(e),Math.abs(e)];if(Array.isArray(e)){let[t,u]=e;if(typeof t=="number"&&typeof u=="number")return[Math.abs(t),Math.abs(u)]}throw new Error("Expecting options.window to be an number or [number, number].")}function Uu(e){if(Hu(e),Pa(e.window),typeof e.epoch!="number")throw new Error("Expecting options.epoch to be a number.");if(typeof e.step!="number")throw new Error("Expecting options.step to be a number.")}var Lt=(e,t,u)=>{let r=e.length,i=Buffer.from(e,t).toString("hex");if(r<u){let a=new Array(u-r+1).join(i);return Buffer.from(a,"hex").slice(0,u).toString("hex")}return i},Fu=(e,t,u)=>{switch(e){case m.HashAlgorithms.SHA1:return Lt(t,u,20);case m.HashAlgorithms.SHA256:return Lt(t,u,32);case m.HashAlgorithms.SHA512:return Lt(t,u,64);default:throw new Error(`Expecting algorithm to be one of ${_t.join(", ")}. Received ${e}.`)}};function Oa(){return{algorithm:m.HashAlgorithms.SHA1,createDigest:Ct,createHmacKey:Fu,digits:6,encoding:m.KeyEncodings.ASCII,epoch:Date.now(),step:30,window:0}}function Ra(e){let t={...Oa(),...e};return Uu(t),Object.freeze(t)}function qa(e,t){return Math.floor(e/t/1e3)}function Pt(e,t){let u=qa(t.epoch,t.step);return Bt(e,u,t)}function La(e,t,u,r){let i=[];if(r===0)return i;for(let a=1;a<=r;a++){let n=t*a*u;i.push(e+n)}return i}function Ma(e,t,u){let r=Pa(u),i=t*1e3;return{current:e,past:La(e,-1,i,r[0]),future:La(e,1,i,r[1])}}function ju(e,t,u){if(!Ru(e))return!1;let r=Pt(t,u);return e===r}function Pu(e,t,u,r){let i=null;return e.some((a,n)=>ju(t,u,{...r,epoch:a})?(i=n+1,!0):!1),i}function Vu(e,t,u){if(ju(e,t,u))return 0;let r=Ma(u.epoch,u.step,u.window),i=Pu(r.past,e,t,u);return i!==null?i*-1:Pu(r.future,e,t,u)}function Wu(e,t){return Math.floor(e/1e3)%t}function Ha(e,t){return t-Wu(e,t)}function Ua(e,t,u,r){return Mu({algorithm:r.algorithm,digits:r.digits,step:r.step,type:m.Strategy.TOTP,accountName:e,issuer:t,secret:u})}var Dt=class e extends Nt{create(t={}){return new e(t)}allOptions(){return Ra(this.options)}generate(t){return Pt(t,this.allOptions())}checkDelta(t,u){return Vu(t,u,this.allOptions())}check(t,u){return typeof this.checkDelta(t,u)=="number"}verify(t){if(typeof t!="object")throw new Error("Expecting argument 0 of verify to be an object");return this.check(t.token,t.secret)}timeRemaining(){let t=this.allOptions();return Ha(t.epoch,t.step)}timeUsed(){let t=this.allOptions();return Wu(t.epoch,t.step)}keyuri(t,u,r){return Ua(t,u,r,this.allOptions())}};function Fa(e){if(Uu(e),typeof e.keyDecoder!="function")throw new Error("Expecting options.keyDecoder to be a function.");if(e.keyEncoder&&typeof e.keyEncoder!="function")throw new Error("Expecting options.keyEncoder to be a function.")}function ja(){return{algorithm:m.HashAlgorithms.SHA1,createDigest:Ct,createHmacKey:Fu,digits:6,encoding:m.KeyEncodings.HEX,epoch:Date.now(),step:30,window:0}}function Va(e){let t={...ja(),...e};return Fa(t),Object.freeze(t)}function Gu(e,t){return t.keyEncoder(e,t.encoding)}function Ot(e,t){return t.keyDecoder(e,t.encoding)}function Wa(e,t){let u=t.createRandomBytes(e,t.encoding);return Gu(u,t)}function Ga(e,t){return Pt(Ot(e,t),t)}function za(e,t,u){return Vu(e,Ot(t,u),u)}var Ou=class e extends Dt{create(t={}){return new e(t)}allOptions(){return Va(this.options)}generate(t){return Ga(t,this.allOptions())}checkDelta(t,u){return za(t,u,this.allOptions())}encode(t){return Gu(t,this.allOptions())}decode(t){return Ot(t,this.allOptions())}generateSecret(t=10){return Wa(t,this.allOptions())}};m.Authenticator=Ou;m.HASH_ALGORITHMS=_t;m.HOTP=Nt;m.KEY_ENCODINGS=Cu;m.OTP=It;m.STRATEGY=Bu;m.TOTP=Dt;m.authenticatorCheckWithWindow=za;m.authenticatorDecoder=Ot;m.authenticatorDefaultOptions=ja;m.authenticatorEncoder=Gu;m.authenticatorGenerateSecret=Wa;m.authenticatorOptionValidator=Fa;m.authenticatorOptions=Va;m.authenticatorToken=Ga;m.createDigestPlaceholder=Ct;m.hotpCheck=Ca;m.hotpCounter=Da;m.hotpCreateHmacKey=_a;m.hotpDefaultOptions=Ia;m.hotpDigestToToken=$a;m.hotpKeyuri=Ba;m.hotpOptions=Na;m.hotpOptionsValidator=Hu;m.hotpToken=Bt;m.isTokenValid=Ru;m.keyuri=Mu;m.objectValues=$t;m.padStart=qu;m.totpCheck=ju;m.totpCheckByEpoch=Pu;m.totpCheckWithWindow=Vu;m.totpCounter=qa;m.totpCreateHmacKey=Fu;m.totpDefaultOptions=Oa;m.totpEpochAvailable=Ma;m.totpKeyuri=Ua;m.totpOptions=Ra;m.totpOptionsValidator=Uu;m.totpPadSecret=Lt;m.totpTimeRemaining=Ha;m.totpTimeUsed=Wu;m.totpToken=Pt});var Ya=X($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});var Rt=ya(),Ja=Aa(),zu=Ka(),E0=new zu.HOTP({createDigest:Rt.createDigest}),A0=new zu.TOTP({createDigest:Rt.createDigest}),L0=new zu.Authenticator({createDigest:Rt.createDigest,createRandomBytes:Rt.createRandomBytes,keyDecoder:Ja.keyDecoder,keyEncoder:Ja.keyEncoder});$e.authenticator=L0;$e.hotp=E0;$e.totp=A0});var Za=X(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var Xa=Ya();Object.keys(Xa).forEach(function(e){e!=="default"&&Object.defineProperty(Ku,e,{enumerable:!0,get:function(){return Xa[e]}})})});import*as Mr from"fs/promises";import*as Fe from"vm";function Hr(e,t,u,r=!1){if(e[t])if(r)o.info(`Overriding existing function: ${t}`),delete e[t];else{o.error(`The name ${t} is already defined in the global scope`);return}try{let i;if(Fe.isContext(e)?i=new Fe.Script(u,{importModuleDynamically:async a=>await import(a)}).runInContext(e):i=(0,eval)(u),typeof i!="function")throw new Error("The injected code must be a function");e[t]=i}catch(i){o.error(`Error injecting user function ${t}: ${i.message}`)}}async function sn(e,t,u=!1){try{let r=await Mr.readFile(t,"utf8"),i=JSON.parse(r);o.info(`Loading ${Object.keys(i).length} user functions...`);for(let[a,n]of Object.entries(i))Hr(e,a,n,u)}catch(r){throw o.error("Failed to load user functions:",r),r}}import*as Zt from"fs/promises";async function on(e){try{let t=await Zt.readFile(e,"utf8"),u=JSON.parse(t);return o.info(`Loaded ${u.length} knowledges from file`),u}catch(t){if(t.code==="ENOENT")return o.debug("No knowledges file found"),[];throw o.error("Failed to load knowledges:",t),t}}async function cn(e){try{let t=await Zt.readFile(e,"utf8"),u=JSON.parse(t);return o.info(`Loaded ${u.length} knowledge mappings from file`),u}catch(t){if(t.code==="ENOENT")return o.debug("No knowledge mappings file found"),[];throw o.error("Failed to load knowledge mappings:",t),t}}async function ln(e,t){if(!e.body)throw new Error("Response body is null");let u=e.body.getReader(),r=new TextDecoder,i="";try{for(;;){let{done:a,value:n}=await u.read();if(a)break;i+=r.decode(n,{stream:!0});let s=i.split(`
3
+ import{a as Yt,b as Nr,c as pe,d as Dr,e as $r,f as Cr,g as Br,h as Pr,i as Or,l as Rr,o as Xt,r as qr}from"./chunk-SSJRUBTH.js";import{a as Pe,c as Zu,d as Ir,e as Jt,f as Me,g as He,h as Ue}from"./chunk-TZU7BU5P.js";import{A as Ar,B as Lr,a as er,b as tr,c as ur,d as rr,e as ir,f as ar,g as nr,h as sr,i as or,j as cr,k as lr,l as dr,m as fr,n as hr,o as pr,p as mr,q as gr,r as br,s as xr,t as wr,u as yr,v as vr,w as kr,x as Sr,y as Tr,z as Er}from"./chunk-SFYF2Y6H.js";import{a as Gt,b as _r,d as zt,g as Kt,h as qe}from"./chunk-S7EB7HNN.js";import{a as Oe,b as O,c as Vt,d as Wt,f as Qu,n as Re}from"./chunk-BQCZFA7S.js";import{a as S}from"./chunk-T3H4NEVX.js";import{b as jt,d as o}from"./chunk-T2JTBHI7.js";import{a as nn,c as X,d as Xu}from"./chunk-CSINHOOD.js";var zi=X((wl,Gi)=>{"use strict";var Ws=function(t){return Gs(t)&&!zs(t)};function Gs(e){return!!e&&typeof e=="object"}function zs(e){var t=Object.prototype.toString.call(e);return t==="[object RegExp]"||t==="[object Date]"||Ys(e)}var Ks=typeof Symbol=="function"&&Symbol.for,Js=Ks?Symbol.for("react.element"):60103;function Ys(e){return e.$$typeof===Js}function Xs(e){return Array.isArray(e)?[]:{}}function De(e,t){return t.clone!==!1&&t.isMergeableObject(e)?fe(Xs(e),e,t):e}function Zs(e,t,u){return e.concat(t).map(function(r){return De(r,u)})}function Qs(e,t){if(!t.customMerge)return fe;var u=t.customMerge(e);return typeof u=="function"?u:fe}function eo(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}function Vi(e){return Object.keys(e).concat(eo(e))}function Wi(e,t){try{return t in e}catch{return!1}}function to(e,t){return Wi(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))}function uo(e,t,u){var r={};return u.isMergeableObject(e)&&Vi(e).forEach(function(i){r[i]=De(e[i],u)}),Vi(t).forEach(function(i){to(e,i)||(Wi(e,i)&&u.isMergeableObject(t[i])?r[i]=Qs(i,u)(e[i],t[i],u):r[i]=De(t[i],u))}),r}function fe(e,t,u){u=u||{},u.arrayMerge=u.arrayMerge||Zs,u.isMergeableObject=u.isMergeableObject||Ws,u.cloneUnlessOtherwiseSpecified=De;var r=Array.isArray(t),i=Array.isArray(e),a=r===i;return a?r?u.arrayMerge(e,t,u):uo(e,t,u):De(t,u)}fe.all=function(t,u){if(!Array.isArray(t))throw new Error("first argument should be an array");return t.reduce(function(r,i){return fe(r,i,u)},{})};var ro=fe;Gi.exports=ro});var ya=X(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});function g0(e){return e&&typeof e=="object"&&"default"in e?e.default:e}var wa=g0(nn("crypto")),b0=(e,t,u)=>wa.createHmac(e,Buffer.from(t,"hex")).update(Buffer.from(u,"hex")).digest().toString("hex"),x0=(e,t)=>wa.randomBytes(e).toString(t);Et.createDigest=b0;Et.createRandomBytes=x0});var ka=X(Du=>{"use strict";var w0="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",va=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];function y0(e){var t=Math.floor(e.length/5);return e.length%5===0?t:t+1}Du.encode=function(e){Buffer.isBuffer(e)||(e=new Buffer(e));for(var t=0,u=0,r=0,i=0,a=new Buffer(y0(e)*8);t<e.length;){var n=e[t];r>3?(i=n&255>>r,r=(r+5)%8,i=i<<r|(t+1<e.length?e[t+1]:0)>>8-r,t++):(i=n>>8-(r+5)&31,r=(r+5)%8,r===0&&t++),a[u]=w0.charCodeAt(i),u++}for(t=u;t<a.length;t++)a[t]=61;return a};Du.decode=function(e){var t=0,u=0,r,i=0;Buffer.isBuffer(e)||(e=new Buffer(e));for(var a=new Buffer(Math.ceil(e.length*5/8)),n=0;n<e.length&&e[n]!==61;n++){var s=e[n]-48;if(s<va.length)u=va[s],t<=3?(t=(t+5)%8,t===0?(r|=u,a[i]=r,i++,r=0):r|=255&u<<8-t):(t=(t+5)%8,r|=255&u>>>t,a[i]=r,i++,r=255&u<<8-t);else throw new Error("Invalid input - it is not base32 encoded string")}return a.slice(0,i)}});var Ta=X($u=>{"use strict";var Sa=ka();$u.encode=Sa.encode;$u.decode=Sa.decode});var Aa=X(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});function v0(e){return e&&typeof e=="object"&&"default"in e?e.default:e}var Ea=v0(Ta()),k0=(e,t)=>Ea.decode(e).toString(t),S0=(e,t)=>Ea.encode(Buffer.from(e,t).toString("ascii")).toString().replace(/=/g,"");At.keyDecoder=k0;At.keyEncoder=S0});var Ka=X(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});function $t(e){return Object.keys(e).map(t=>e[t])}(function(e){e.SHA1="sha1",e.SHA256="sha256",e.SHA512="sha512"})(m.HashAlgorithms||(m.HashAlgorithms={}));var _t=$t(m.HashAlgorithms);(function(e){e.ASCII="ascii",e.BASE64="base64",e.HEX="hex",e.LATIN1="latin1",e.UTF8="utf8"})(m.KeyEncodings||(m.KeyEncodings={}));var Cu=$t(m.KeyEncodings);(function(e){e.HOTP="hotp",e.TOTP="totp"})(m.Strategy||(m.Strategy={}));var Bu=$t(m.Strategy),Ct=()=>{throw new Error("Please provide an options.createDigest implementation.")};function Ru(e){return/^(\d+)$/.test(e)}function qu(e,t,u){return e.length>=t?e:`${Array(t+1).join(u)}${e}`.slice(-1*t)}function Mu(e){let t=`otpauth://${e.type}/{labelPrefix}:{accountName}?secret={secret}{query}`,u=[];if(Bu.indexOf(e.type)<0)throw new Error(`Expecting options.type to be one of ${Bu.join(", ")}. Received ${e.type}.`);if(e.type==="hotp"){if(e.counter==null||typeof e.counter!="number")throw new Error('Expecting options.counter to be a number when options.type is "hotp".');u.push(`&counter=${e.counter}`)}return e.type==="totp"&&e.step&&u.push(`&period=${e.step}`),e.digits&&u.push(`&digits=${e.digits}`),e.algorithm&&u.push(`&algorithm=${e.algorithm.toUpperCase()}`),e.issuer&&u.push(`&issuer=${encodeURIComponent(e.issuer)}`),t.replace("{labelPrefix}",encodeURIComponent(e.issuer||e.accountName)).replace("{accountName}",encodeURIComponent(e.accountName)).replace("{secret}",e.secret).replace("{query}",u.join(""))}var It=class e{constructor(t={}){this._defaultOptions=Object.freeze({...t}),this._options=Object.freeze({})}create(t={}){return new e(t)}clone(t={}){let u=this.create({...this._defaultOptions,...t});return u.options=this._options,u}get options(){return Object.freeze({...this._defaultOptions,...this._options})}set options(t){this._options=Object.freeze({...this._options,...t})}allOptions(){return this.options}resetOptions(){this._options=Object.freeze({})}};function Hu(e){if(typeof e.createDigest!="function")throw new Error("Expecting options.createDigest to be a function.");if(typeof e.createHmacKey!="function")throw new Error("Expecting options.createHmacKey to be a function.");if(typeof e.digits!="number")throw new Error("Expecting options.digits to be a number.");if(!e.algorithm||_t.indexOf(e.algorithm)<0)throw new Error(`Expecting options.algorithm to be one of ${_t.join(", ")}. Received ${e.algorithm}.`);if(!e.encoding||Cu.indexOf(e.encoding)<0)throw new Error(`Expecting options.encoding to be one of ${Cu.join(", ")}. Received ${e.encoding}.`)}var _a=(e,t,u)=>Buffer.from(t,u).toString("hex");function Ia(){return{algorithm:m.HashAlgorithms.SHA1,createHmacKey:_a,createDigest:Ct,digits:6,encoding:m.KeyEncodings.ASCII}}function Na(e){let t={...Ia(),...e};return Hu(t),Object.freeze(t)}function Da(e){let t=e.toString(16);return qu(t,16,"0")}function $a(e,t){let u=Buffer.from(e,"hex"),r=u[u.length-1]&15,a=((u[r]&127)<<24|(u[r+1]&255)<<16|(u[r+2]&255)<<8|u[r+3]&255)%Math.pow(10,t);return qu(String(a),t,"0")}function T0(e,t,u){let r=Da(t),i=u.createHmacKey(u.algorithm,e,u.encoding);return u.createDigest(u.algorithm,i,r)}function Bt(e,t,u){let r=u.digest||T0(e,t,u);return $a(r,u.digits)}function Ca(e,t,u,r){if(!Ru(e))return!1;let i=Bt(t,u,r);return e===i}function Ba(e,t,u,r,i){return Mu({algorithm:i.algorithm,digits:i.digits,type:m.Strategy.HOTP,accountName:e,counter:r,issuer:t,secret:u})}var Nt=class e extends It{create(t={}){return new e(t)}allOptions(){return Na(this.options)}generate(t,u){return Bt(t,u,this.allOptions())}check(t,u,r){return Ca(t,u,r,this.allOptions())}verify(t){if(typeof t!="object")throw new Error("Expecting argument 0 of verify to be an object");return this.check(t.token,t.secret,t.counter)}keyuri(t,u,r,i){return Ba(t,u,r,i,this.allOptions())}};function Pa(e){if(typeof e=="number")return[Math.abs(e),Math.abs(e)];if(Array.isArray(e)){let[t,u]=e;if(typeof t=="number"&&typeof u=="number")return[Math.abs(t),Math.abs(u)]}throw new Error("Expecting options.window to be an number or [number, number].")}function Uu(e){if(Hu(e),Pa(e.window),typeof e.epoch!="number")throw new Error("Expecting options.epoch to be a number.");if(typeof e.step!="number")throw new Error("Expecting options.step to be a number.")}var Lt=(e,t,u)=>{let r=e.length,i=Buffer.from(e,t).toString("hex");if(r<u){let a=new Array(u-r+1).join(i);return Buffer.from(a,"hex").slice(0,u).toString("hex")}return i},Fu=(e,t,u)=>{switch(e){case m.HashAlgorithms.SHA1:return Lt(t,u,20);case m.HashAlgorithms.SHA256:return Lt(t,u,32);case m.HashAlgorithms.SHA512:return Lt(t,u,64);default:throw new Error(`Expecting algorithm to be one of ${_t.join(", ")}. Received ${e}.`)}};function Oa(){return{algorithm:m.HashAlgorithms.SHA1,createDigest:Ct,createHmacKey:Fu,digits:6,encoding:m.KeyEncodings.ASCII,epoch:Date.now(),step:30,window:0}}function Ra(e){let t={...Oa(),...e};return Uu(t),Object.freeze(t)}function qa(e,t){return Math.floor(e/t/1e3)}function Pt(e,t){let u=qa(t.epoch,t.step);return Bt(e,u,t)}function La(e,t,u,r){let i=[];if(r===0)return i;for(let a=1;a<=r;a++){let n=t*a*u;i.push(e+n)}return i}function Ma(e,t,u){let r=Pa(u),i=t*1e3;return{current:e,past:La(e,-1,i,r[0]),future:La(e,1,i,r[1])}}function ju(e,t,u){if(!Ru(e))return!1;let r=Pt(t,u);return e===r}function Pu(e,t,u,r){let i=null;return e.some((a,n)=>ju(t,u,{...r,epoch:a})?(i=n+1,!0):!1),i}function Vu(e,t,u){if(ju(e,t,u))return 0;let r=Ma(u.epoch,u.step,u.window),i=Pu(r.past,e,t,u);return i!==null?i*-1:Pu(r.future,e,t,u)}function Wu(e,t){return Math.floor(e/1e3)%t}function Ha(e,t){return t-Wu(e,t)}function Ua(e,t,u,r){return Mu({algorithm:r.algorithm,digits:r.digits,step:r.step,type:m.Strategy.TOTP,accountName:e,issuer:t,secret:u})}var Dt=class e extends Nt{create(t={}){return new e(t)}allOptions(){return Ra(this.options)}generate(t){return Pt(t,this.allOptions())}checkDelta(t,u){return Vu(t,u,this.allOptions())}check(t,u){return typeof this.checkDelta(t,u)=="number"}verify(t){if(typeof t!="object")throw new Error("Expecting argument 0 of verify to be an object");return this.check(t.token,t.secret)}timeRemaining(){let t=this.allOptions();return Ha(t.epoch,t.step)}timeUsed(){let t=this.allOptions();return Wu(t.epoch,t.step)}keyuri(t,u,r){return Ua(t,u,r,this.allOptions())}};function Fa(e){if(Uu(e),typeof e.keyDecoder!="function")throw new Error("Expecting options.keyDecoder to be a function.");if(e.keyEncoder&&typeof e.keyEncoder!="function")throw new Error("Expecting options.keyEncoder to be a function.")}function ja(){return{algorithm:m.HashAlgorithms.SHA1,createDigest:Ct,createHmacKey:Fu,digits:6,encoding:m.KeyEncodings.HEX,epoch:Date.now(),step:30,window:0}}function Va(e){let t={...ja(),...e};return Fa(t),Object.freeze(t)}function Gu(e,t){return t.keyEncoder(e,t.encoding)}function Ot(e,t){return t.keyDecoder(e,t.encoding)}function Wa(e,t){let u=t.createRandomBytes(e,t.encoding);return Gu(u,t)}function Ga(e,t){return Pt(Ot(e,t),t)}function za(e,t,u){return Vu(e,Ot(t,u),u)}var Ou=class e extends Dt{create(t={}){return new e(t)}allOptions(){return Va(this.options)}generate(t){return Ga(t,this.allOptions())}checkDelta(t,u){return za(t,u,this.allOptions())}encode(t){return Gu(t,this.allOptions())}decode(t){return Ot(t,this.allOptions())}generateSecret(t=10){return Wa(t,this.allOptions())}};m.Authenticator=Ou;m.HASH_ALGORITHMS=_t;m.HOTP=Nt;m.KEY_ENCODINGS=Cu;m.OTP=It;m.STRATEGY=Bu;m.TOTP=Dt;m.authenticatorCheckWithWindow=za;m.authenticatorDecoder=Ot;m.authenticatorDefaultOptions=ja;m.authenticatorEncoder=Gu;m.authenticatorGenerateSecret=Wa;m.authenticatorOptionValidator=Fa;m.authenticatorOptions=Va;m.authenticatorToken=Ga;m.createDigestPlaceholder=Ct;m.hotpCheck=Ca;m.hotpCounter=Da;m.hotpCreateHmacKey=_a;m.hotpDefaultOptions=Ia;m.hotpDigestToToken=$a;m.hotpKeyuri=Ba;m.hotpOptions=Na;m.hotpOptionsValidator=Hu;m.hotpToken=Bt;m.isTokenValid=Ru;m.keyuri=Mu;m.objectValues=$t;m.padStart=qu;m.totpCheck=ju;m.totpCheckByEpoch=Pu;m.totpCheckWithWindow=Vu;m.totpCounter=qa;m.totpCreateHmacKey=Fu;m.totpDefaultOptions=Oa;m.totpEpochAvailable=Ma;m.totpKeyuri=Ua;m.totpOptions=Ra;m.totpOptionsValidator=Uu;m.totpPadSecret=Lt;m.totpTimeRemaining=Ha;m.totpTimeUsed=Wu;m.totpToken=Pt});var Ya=X($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});var Rt=ya(),Ja=Aa(),zu=Ka(),E0=new zu.HOTP({createDigest:Rt.createDigest}),A0=new zu.TOTP({createDigest:Rt.createDigest}),L0=new zu.Authenticator({createDigest:Rt.createDigest,createRandomBytes:Rt.createRandomBytes,keyDecoder:Ja.keyDecoder,keyEncoder:Ja.keyEncoder});$e.authenticator=L0;$e.hotp=E0;$e.totp=A0});var Za=X(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var Xa=Ya();Object.keys(Xa).forEach(function(e){e!=="default"&&Object.defineProperty(Ku,e,{enumerable:!0,get:function(){return Xa[e]}})})});import*as Mr from"fs/promises";import*as Fe from"vm";function Hr(e,t,u,r=!1){if(e[t])if(r)o.info(`Overriding existing function: ${t}`),delete e[t];else{o.error(`The name ${t} is already defined in the global scope`);return}try{let i;if(Fe.isContext(e)?i=new Fe.Script(u,{importModuleDynamically:async a=>await import(a)}).runInContext(e):i=(0,eval)(u),typeof i!="function")throw new Error("The injected code must be a function");e[t]=i}catch(i){o.error(`Error injecting user function ${t}: ${i.message}`)}}async function sn(e,t,u=!1){try{let r=await Mr.readFile(t,"utf8"),i=JSON.parse(r);o.info(`Loading ${Object.keys(i).length} user functions...`);for(let[a,n]of Object.entries(i))Hr(e,a,n,u)}catch(r){throw o.error("Failed to load user functions:",r),r}}import*as Zt from"fs/promises";async function on(e){try{let t=await Zt.readFile(e,"utf8"),u=JSON.parse(t);return o.info(`Loaded ${u.length} knowledges from file`),u}catch(t){if(t.code==="ENOENT")return o.debug("No knowledges file found"),[];throw o.error("Failed to load knowledges:",t),t}}async function cn(e){try{let t=await Zt.readFile(e,"utf8"),u=JSON.parse(t);return o.info(`Loaded ${u.length} knowledge mappings from file`),u}catch(t){if(t.code==="ENOENT")return o.debug("No knowledge mappings file found"),[];throw o.error("Failed to load knowledge mappings:",t),t}}async function ln(e,t){if(!e.body)throw new Error("Response body is null");let u=e.body.getReader(),r=new TextDecoder,i="";try{for(;;){let{done:a,value:n}=await u.read();if(a)break;i+=r.decode(n,{stream:!0});let s=i.split(`
4
4
  `);i=s.pop()||"";for(let c of s){let l=null;if(c.startsWith("data: "))try{let f=c.slice(6);f.trim()&&(l=JSON.parse(f))}catch(f){console.error(`Failed to parse SSE event: ${c}`,f);continue}l&&t(l)}}}finally{u.releaseLock()}}import{z as Ur}from"zod";var dn=Ur.object({instruction:Ur.string().describe('The instruction of the operation to perform. Can only include one operation. Do not inlcude element indexes just describe the element, e.g. "select the text "Hello, world!" in "Hello, world!""')});function Fr(e){e.register({name:"perform_accurate_operation",description:"Perform an operation that requires accurate interaction like dragging or interacting with a specific area of an element. Only use this action when neccecary.",schema:dn,usesElementIndex:!1,async execute(t,u){let{instruction:r}=t,i={page:u.page,agentServices:u.agentServices,domService:u.domService},a=await Zu(r,i,{});if(a.status==="error"||!a.actionEntity)return{success:!1,actionEntity:{action_description:r,action_data:{action_name:"perform_accurate_operation",kwargs:{instruction:r}}},error:a.error||"Failed to generate action"};let{actionEntity:n}=a,s=await Ir(n,i);return{success:s.success,actionEntity:n,message:s.success?`Successfully executed action: ${n.action_data?.action_name}`:void 0,error:s.error}}})}var T;(function(e){e.Root="root",e.Text="text",e.Directive="directive",e.Comment="comment",e.Script="script",e.Style="style",e.Tag="tag",e.CDATA="cdata",e.Doctype="doctype"})(T||(T={}));function jr(e){return e.type===T.Tag||e.type===T.Script||e.type===T.Style}var Vr=T.Root,Wr=T.Text,Gr=T.Directive,zr=T.Comment,Kr=T.Script,Jr=T.Style,Yr=T.Tag,Xr=T.CDATA,Zr=T.Doctype;var je=class{constructor(){this.parent=null,this.prev=null,this.next=null,this.startIndex=null,this.endIndex=null}get parentNode(){return this.parent}set parentNode(t){this.parent=t}get previousSibling(){return this.prev}set previousSibling(t){this.prev=t}get nextSibling(){return this.next}set nextSibling(t){this.next=t}cloneNode(t=!1){return ti(this,t)}},me=class extends je{constructor(t){super(),this.data=t}get nodeValue(){return this.data}set nodeValue(t){this.data=t}},te=class extends me{constructor(){super(...arguments),this.type=T.Text}get nodeType(){return 3}},ge=class extends me{constructor(){super(...arguments),this.type=T.Comment}get nodeType(){return 8}},be=class extends me{constructor(t,u){super(u),this.name=t,this.type=T.Directive}get nodeType(){return 1}},xe=class extends je{constructor(t){super(),this.children=t}get firstChild(){var t;return(t=this.children[0])!==null&&t!==void 0?t:null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(t){this.children=t}},we=class extends xe{constructor(){super(...arguments),this.type=T.CDATA}get nodeType(){return 4}},ue=class extends xe{constructor(){super(...arguments),this.type=T.Root}get nodeType(){return 9}},ye=class extends xe{constructor(t,u,r=[],i=t==="script"?T.Script:t==="style"?T.Style:T.Tag){super(r),this.name=t,this.attribs=u,this.type=i}get nodeType(){return 1}get tagName(){return this.name}set tagName(t){this.name=t}get attributes(){return Object.keys(this.attribs).map(t=>{var u,r;return{name:t,value:this.attribs[t],namespace:(u=this["x-attribsNamespace"])===null||u===void 0?void 0:u[t],prefix:(r=this["x-attribsPrefix"])===null||r===void 0?void 0:r[t]}})}};function W(e){return jr(e)}function eu(e){return e.type===T.CDATA}function Ve(e){return e.type===T.Text}function tu(e){return e.type===T.Comment}function fn(e){return e.type===T.Directive}function ei(e){return e.type===T.Root}function ti(e,t=!1){let u;if(Ve(e))u=new te(e.data);else if(tu(e))u=new ge(e.data);else if(W(e)){let r=t?Qt(e.children):[],i=new ye(e.name,{...e.attribs},r);r.forEach(a=>a.parent=i),e.namespace!=null&&(i.namespace=e.namespace),e["x-attribsNamespace"]&&(i["x-attribsNamespace"]={...e["x-attribsNamespace"]}),e["x-attribsPrefix"]&&(i["x-attribsPrefix"]={...e["x-attribsPrefix"]}),u=i}else if(eu(e)){let r=t?Qt(e.children):[],i=new we(r);r.forEach(a=>a.parent=i),u=i}else if(ei(e)){let r=t?Qt(e.children):[],i=new ue(r);r.forEach(a=>a.parent=i),e["x-mode"]&&(i["x-mode"]=e["x-mode"]),u=i}else if(fn(e)){let r=new be(e.name,e.data);e["x-name"]!=null&&(r["x-name"]=e["x-name"],r["x-publicId"]=e["x-publicId"],r["x-systemId"]=e["x-systemId"]),u=r}else throw new Error(`Not implemented yet: ${e.type}`);return u.startIndex=e.startIndex,u.endIndex=e.endIndex,e.sourceCodeLocation!=null&&(u.sourceCodeLocation=e.sourceCodeLocation),u}function Qt(e){let t=e.map(u=>ti(u,!0));for(let u=1;u<t.length;u++)t[u].prev=t[u-1],t[u-1].next=t[u];return t}var ui={withStartIndices:!1,withEndIndices:!1,xmlMode:!1},re=class{constructor(t,u,r){this.dom=[],this.root=new ue(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null,typeof u=="function"&&(r=u,u=ui),typeof t=="object"&&(u=t,t=void 0),this.callback=t??null,this.options=u??ui,this.elementCB=r??null}onparserinit(t){this.parser=t}onreset(){this.dom=[],this.root=new ue(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){this.done||(this.done=!0,this.parser=null,this.handleCallback(null))}onerror(t){this.handleCallback(t)}onclosetag(){this.lastNode=null;let t=this.tagStack.pop();this.options.withEndIndices&&(t.endIndex=this.parser.endIndex),this.elementCB&&this.elementCB(t)}onopentag(t,u){let r=this.options.xmlMode?T.Tag:void 0,i=new ye(t,u,void 0,r);this.addNode(i),this.tagStack.push(i)}ontext(t){let{lastNode:u}=this;if(u&&u.type===T.Text)u.data+=t,this.options.withEndIndices&&(u.endIndex=this.parser.endIndex);else{let r=new te(t);this.addNode(r),this.lastNode=r}}oncomment(t){if(this.lastNode&&this.lastNode.type===T.Comment){this.lastNode.data+=t;return}let u=new ge(t);this.addNode(u),this.lastNode=u}oncommentend(){this.lastNode=null}oncdatastart(){let t=new te(""),u=new we([t]);this.addNode(u),t.parent=u,this.lastNode=t}oncdataend(){this.lastNode=null}onprocessinginstruction(t,u){let r=new be(t,u);this.addNode(r)}handleCallback(t){if(typeof this.callback=="function")this.callback(t,this.dom);else if(t)throw t}addNode(t){let u=this.tagStack[this.tagStack.length-1],r=u.children[u.children.length-1];this.options.withStartIndices&&(t.startIndex=this.parser.startIndex),this.options.withEndIndices&&(t.endIndex=this.parser.endIndex),u.children.push(t),r&&(t.prev=r,r.next=t),t.parent=u,this.lastNode=null}};var hn=/\n/g;function pn(e){let t=[...e.matchAll(hn)].map(r=>r.index||0);t.unshift(-1);let u=uu(t,0,t.length);return r=>ii(u,r)}function uu(e,t,u){if(u-t==1)return{offset:e[t],index:t+1};let r=Math.ceil((t+u)/2),i=uu(e,t,r),a=uu(e,r,u);return{offset:i.offset,low:i,high:a}}function ii(e,t){return function(u){return Object.prototype.hasOwnProperty.call(u,"index")}(e)?{line:e.index,column:t-e.offset}:ii(e.high.offset<t?e.high:e.low,t)}function ru(e,t="",u={}){let r=typeof t!="string"?t:u,i=typeof t=="string"?t:"",a=e.map(mn),n=!!r.lineNumbers;return function(s,c=0){let l=n?pn(s):()=>({line:0,column:0}),f=c,b=[];e:for(;f<s.length;){let x=!1;for(let h of a){h.regex.lastIndex=f;let g=h.regex.exec(s);if(g&&g[0].length>0){if(!h.discard){let v=l(f),w=typeof h.replace=="string"?g[0].replace(new RegExp(h.regex.source,h.regex.flags),h.replace):g[0];b.push({state:i,name:h.name,text:w,offset:f,len:g[0].length,line:v.line,column:v.column})}if(f=h.regex.lastIndex,x=!0,h.push){let v=h.push(s,f);b.push(...v.tokens),f=v.offset}if(h.pop)break e;break}}if(!x)break}return{tokens:b,offset:f,complete:s.length<=f}}}function mn(e,t){return{...e,regex:gn(e,t)}}function gn(e,t){if(e.name.length===0)throw new Error(`Rule #${t} has empty name, which is not allowed.`);if(function(u){return Object.prototype.hasOwnProperty.call(u,"regex")}(e))return function(u){if(u.global)throw new Error(`Regular expression /${u.source}/${u.flags} contains the global flag, which is not allowed.`);return u.sticky?u:new RegExp(u.source,u.flags+"y")}(e.regex);if(function(u){return Object.prototype.hasOwnProperty.call(u,"str")}(e)){if(e.str.length===0)throw new Error(`Rule #${t} ("${e.name}") has empty "str" property, which is not allowed.`);return new RegExp(ri(e.str),"y")}return new RegExp(ri(e.name),"y")}function ri(e){return e.replace(/[-[\]{}()*+!<=:?./\\^$|#\s,]/g,"\\$&")}function j(e,t){return(u,r)=>{let i=r,a;return r<u.tokens.length?(a=e(u.tokens[r],u,r),a!==void 0&&i++):t?.(u,r),a===void 0?{matched:!1}:{matched:!0,position:i,value:a}}}function iu(e,t){return e.matched?{matched:!0,position:e.position,value:t(e.value,e.position)}:e}function We(e,t){return e.matched?t(e):e}function D(e,t){return(u,r)=>iu(e(u,r),(i,a)=>t(i,u,r,a))}function ve(e,t){return(u,r)=>{let i=e(u,r);return i.matched?i:{matched:!0,position:r,value:t}}}function ie(...e){return(t,u)=>{for(let r of e){let i=r(t,u);if(i.matched)return i}return{matched:!1}}}function Z(e,t){return(u,r)=>{let i=e(u,r);return i.matched?i:t(u,r)}}function bn(e,t){return(u,r)=>{let i=[],a=!0;do{let n=e(u,r);n.matched&&t(n.value,i.length+1,u,r,n.position)?(i.push(n.value),r=n.position):a=!1}while(a);return{matched:!0,position:r,value:i}}}function Ge(e){return bn(e,()=>!0)}function ai(e){return $(e,Ge(e),(t,u)=>[t,...u])}function $(e,t,u){return(r,i)=>We(e(r,i),a=>iu(t(r,a.position),(n,s)=>u(a.value,n,r,i,s)))}function ni(e,t){return $(e,t,u=>u)}function au(e,t){return $(e,t,(u,r)=>r)}function ze(e,t,u,r){return(i,a)=>We(e(i,a),n=>We(t(i,n.position),s=>iu(u(i,s.position),(c,l)=>r(n.value,s.value,c,i,a,l))))}function nu(e,t,u){return ze(e,t,u,(r,i)=>i)}function xn(...e){return(t,u)=>{let r=[],i=u;for(let a of e){let n=a(t,i);if(n.matched)r.push(n.value),i=n.position;else return{matched:!1}}return{matched:!0,position:i,value:r}}}function si(...e){return wn(xn(...e))}function wn(e){return D(e,t=>t.flatMap(u=>u))}function yn(e,t){return(u,r)=>{let i=!0,a=e,n=r;do{let s=t(a,u,n)(u,n);s.matched?(a=s.value,n=s.position):i=!1}while(i);return{matched:!0,position:n,value:a}}}function vn(e,t,u){return yn(e,r=>D(t,(i,a,n,s)=>u(r,i,a,n,s)))}function su(e,t,u){return kn(e,r=>vn(r,$(t,u,(i,a)=>[i,a]),(i,[a,n])=>a(i,n)))}function kn(e,t){return(u,r)=>We(e(u,r),i=>t(i.value,u,r,i.position)(u,i.position))}var Tn="(?:[ \\t\\r\\n\\f]*)",hi="(?:\\n|\\r\\n|\\r|\\f)",Ye="[^\\x00-\\x7F]",Te="(?:\\\\[0-9a-f]{1,6}(?:\\r\\n|[ \\n\\r\\t\\f])?)",Ee="(?:\\\\[^\\n\\r\\f0-9a-f])",En=`(?:[_a-z]|${Ye}|${Te}|${Ee})`,pi=`(?:[_a-z0-9-]|${Ye}|${Te}|${Ee})`,An=`(?:${pi}+)`,Ln=`(?:[-]?${En}${pi}*)`,_n=`'([^\\n\\r\\f\\\\']|\\\\${hi}|${Ye}|${Te}|${Ee})*'`,In=`"([^\\n\\r\\f\\\\"]|\\\\${hi}|${Ye}|${Te}|${Ee})*"`,Nn=ru([{name:"ws",regex:new RegExp(Tn)},{name:"hash",regex:new RegExp(`#${An}`,"i")},{name:"ident",regex:new RegExp(Ln,"i")},{name:"str1",regex:new RegExp(_n,"i")},{name:"str2",regex:new RegExp(In,"i")},{name:"*"},{name:"."},{name:","},{name:"["},{name:"]"},{name:"="},{name:">"},{name:"|"},{name:"+"},{name:"~"},{name:"^"},{name:"$"}]),Dn=ru([{name:"unicode",regex:new RegExp(Te,"i")},{name:"escape",regex:new RegExp(Ee,"i")},{name:"any",regex:new RegExp("[\\s\\S]","i")}]);function mi([e,t,u],[r,i,a]){return[e+r,t+i,u+a]}function $n(e){return e.reduce(mi,[0,0,0])}var Cn=j(e=>e.name==="unicode"?String.fromCodePoint(parseInt(e.text.slice(1),16)):void 0),Bn=j(e=>e.name==="escape"?e.text.slice(1):void 0),Pn=j(e=>e.name==="any"?e.text:void 0),On=D(Ge(ie(Cn,Bn,Pn)),e=>e.join(""));function lu(e){let t=Dn(e);return On({tokens:t.tokens,options:void 0},0).value}function A(e){return j(t=>t.name===e?!0:void 0)}var du=j(e=>e.name==="ws"?null:void 0),ou=ve(du,null);function ne(e){return nu(ou,e,ou)}var Se=j(e=>e.name==="ident"?lu(e.text):void 0),Rn=j(e=>e.name==="hash"?lu(e.text.slice(1)):void 0),qn=j(e=>e.name.startsWith("str")?lu(e.text.slice(1,-1)):void 0),gi=ni(ve(Se,""),A("|")),fu=Z($(gi,Se,(e,t)=>({name:t,namespace:e})),D(Se,e=>({name:e,namespace:null}))),Mn=Z($(gi,A("*"),e=>({type:"universal",namespace:e,specificity:[0,0,0]})),D(A("*"),()=>({type:"universal",namespace:null,specificity:[0,0,0]}))),Hn=D(fu,({name:e,namespace:t})=>({type:"tag",name:e,namespace:t,specificity:[0,0,1]})),Un=$(A("."),Se,(e,t)=>({type:"class",name:t,specificity:[0,1,0]})),Fn=D(Rn,e=>({type:"id",name:e,specificity:[1,0,0]})),oi=j(e=>{if(e.name==="ident"){if(e.text==="i"||e.text==="I")return"i";if(e.text==="s"||e.text==="S")return"s"}}),jn=Z($(qn,ve(au(ou,oi),null),(e,t)=>({value:e,modifier:t})),$(Se,ve(au(du,oi),null),(e,t)=>({value:e,modifier:t}))),Vn=ie(D(A("="),()=>"="),$(A("~"),A("="),()=>"~="),$(A("|"),A("="),()=>"|="),$(A("^"),A("="),()=>"^="),$(A("$"),A("="),()=>"$="),$(A("*"),A("="),()=>"*=")),Wn=ze(A("["),ne(fu),A("]"),(e,{name:t,namespace:u})=>({type:"attrPresence",name:t,namespace:u,specificity:[0,1,0]})),Gn=nu(A("["),ze(ne(fu),Vn,ne(jn),({name:e,namespace:t},u,{value:r,modifier:i})=>({type:"attrValue",name:e,namespace:t,matcher:u,value:r,modifier:i,specificity:[0,1,0]})),A("]")),zn=Z(Wn,Gn),Kn=Z(Mn,Hn),ci=ie(Fn,Un,zn),li=D(Z(si(Kn,Ge(ci)),ai(ci)),e=>({type:"compound",list:e,specificity:$n(e.map(t=>t.specificity))})),Jn=ie(D(A(">"),()=>">"),D(A("+"),()=>"+"),D(A("~"),()=>"~"),$(A("|"),A("|"),()=>"||")),Yn=Z(ne(Jn),D(du,()=>" ")),cu=su(li,D(Yn,e=>(t,u)=>({type:"compound",list:[...u.list,{type:"combinator",combinator:e,left:t,specificity:t.specificity}],specificity:mi(t.specificity,u.specificity)})),li),J0=su(D(cu,e=>({type:"list",list:[e]})),D(ne(A(",")),()=>(e,t)=>({type:"list",list:[...e.list,t]})),cu);function Xn(e,t){if(!(typeof t=="string"||t instanceof String))throw new Error("Expected a selector string. Actual input is not a string!");let u=Nn(t);if(!u.complete)throw new Error(`The input "${t}" was only partially tokenized, stopped at offset ${u.offset}!
5
5
  `+di(t,u.offset));let r=ne(e)({tokens:u.tokens,options:void 0},0);if(!r.matched)throw new Error(`No match for "${t}" input!`);if(r.position<u.tokens.length){let i=u.tokens[r.position];throw new Error(`The input "${t}" was only partially parsed, stopped at offset ${i.offset}!
6
6
  `+di(t,i.offset,i.len))}return r.value}function di(e,t,u=1){return`${e.replace(/(\t)|(\r)|(\n)/g,(r,i,a)=>i?"\u2409":a?"\u240D":"\u240A")}
@@ -96,10 +96,10 @@ To: ${x.to}
96
96
  Date: ${x.date}
97
97
 
98
98
  Body:
99
- ${x.body}`,g=await Qo(h,i,t.model);o.info(`Extracted content: ${g}`),g&&g!=="NOT_FOUND"&&b.push({content:g,email_subject:x.subject,email_from:x.from,email_date:x.date})}if(b.length>0){let x=b[0],h=`$email_${t.extraction_type}`;t.extraction_type==="custom"?h="$email_extracted_content":t.extraction_type==="activation_link"?h="$email_magic_link":t.extraction_type==="verification_code"&&(h="$email_otp_code");let g=(new Date().getTime()-a.getTime())/1e3;return o.info(`Successfully extracted content after ${s} attempts in ${g.toFixed(1)} seconds`),{data:x.content,result_variable:h,status:"success",message:`Successfully extracted content from email: ${x.email_subject.substring(0,50)}... (attempts: ${s})`}}else o.info(`Found emails but no extractable content in attempt ${s}`)}else o.info(`No emails found in attempt ${s}`)}catch(l){o.warn(`Error in polling attempt ${s}: ${l.message}`)}if(new Date(Date.now()+r*1e3)>=n){o.info("Not enough time for another polling attempt");break}o.info(`Waiting ${r} seconds before next attempt...`),await new Promise(l=>setTimeout(l,r*1e3))}let c=(new Date().getTime()-a.getTime())/1e3;return{data:void 0,status:"error",message:`No emails with extractable content found after ${s} attempts over ${c.toFixed(1)} seconds`}}catch(i){return o.error(`Error extracting email content: ${i.message}`),{data:void 0,status:"error",message:`Error extracting email content: ${i.message}`}}}import{z as Y}from"zod";function ca(e){switch(e){case"verification_code":return"email_otp_code";case"activation_link":return"email_magic_link";case"custom":return"email_extracted_content";default:return"email_content"}}var la=class{getMailgunConfig(){let e=jt().env||{};if(e.MAILGUN_API_KEY)return{apiKey:e.MAILGUN_API_KEY,domain:e.MAILGUN_DOMAIN||""}}async execute(e,t,u){let r=t.action_data;if(!r)throw new Error("Action data not found");let i=this.getMailgunConfig();if(!i)throw new Error("Mailgun configuration not provided. Please configure MAILGUN_API_KEY and MAILGUN_DOMAIN in SDK config.");let a=r.kwargs,n=u.getModel?.()||"gemini-2.5-pro",s=await oa(i,{model:n,forward_email:a.forward_email,extraction_type:a.extraction_type,prompt:a.prompt,filters:{from_email:a.filter_from_email,to_email:a.filter_to_email,subject:a.filter_subject,body_contains:a.filter_body_contains},timeout:a.timeout});if(s.status==="success"&&s.data){let c=s.result_variable?.replace(/^\$/,"")||ca(a.extraction_type);u.variableStore.set(c,s.data),o.info(`[extract_email_content] Extracted and saved to ${c}`)}else throw new Error(s.message||"Failed to extract email content")}transpile(e){let t=e.action_data?.kwargs||{};return['await agent.execAction("extract_email_content", page, {',` action_data: { kwargs: ${JSON.stringify(t)} },`,"});"]}},e0=Y.object({forward_email:Y.string().describe("Email address where emails are forwarded to (Mailgun inbox)"),extraction_type:Y.enum(["verification_code","activation_link","custom"]).describe("Type of content to extract: verification_code for OTP codes, activation_link for magic links, custom for custom prompts"),prompt:Y.string().optional().describe("Custom extraction prompt (required when extraction_type is custom)"),filter_from_email:Y.string().optional().describe("Filter emails by sender address"),filter_to_email:Y.string().optional().describe("Filter emails by recipient address"),filter_subject:Y.string().optional().describe("Filter emails by subject (partial match)"),filter_body_contains:Y.string().optional().describe("Filter emails by body content (partial match)"),timeout:Y.number().optional().describe("Timeout in seconds for polling (default: 60)")});function da(e,t){e.register({name:"extract_email_content",description:"Extract verification codes, magic links, or custom content from emails received via Mailgun. Polls the Mailgun inbox for matching emails and uses AI to extract the requested content.",schema:e0,async execute(u,r){let{forward_email:i,extraction_type:a,prompt:n,filter_from_email:s,filter_to_email:c,filter_subject:l,filter_body_contains:f,timeout:b}=u,{page:x,agentServices:h}=r;o.info(`[extract_email_content] Extracting ${a} from ${i}`);try{let g={action_description:`Extract ${a} from email`,action_data:{action_name:"extract_email_content",kwargs:{forward_email:i,extraction_type:a,prompt:n,filter_from_email:s,filter_to_email:c,filter_subject:l,filter_body_contains:f,timeout:b}}};await t.execute(x,g,h);let v=ca(a);return{success:!0,actionEntity:g,message:`Extracted ${a} and saved to $${v}`}}catch(g){return{success:!1,error:g.message,actionEntity:{action_description:`Extract ${a} from email (failed)`,action_data:{action_name:"extract_email_content",kwargs:{forward_email:i,extraction_type:a,prompt:n,filter_from_email:s,filter_to_email:c,filter_subject:l,filter_body_contains:f,timeout:b}},feedback:g.message}}}}})}var ft=null;async function V(){if(ft)return ft;let e=(await import("./handler-ESLITK6N.js")).default;return ft=new e,ft}async function ht(e){let t=await V(),u=t.getAction("click"),r=t.getAction("hover"),i=t.getAction("right_click"),a=t.getAction("double_click");return Lr(e,u),xr(e,r),lr(e,i),kr(e,a),"Click, hover, double-click, right-click, or drag elements"}async function pt(e){let t=await V(),u=t.getAction("go_to_url"),r=t.getAction("go_back"),i=t.getAction("reload_page");return br(e,u),gr(e,r),cr(e,i),"Navigate to URLs, go back, or reload the page"}async function mt(e){let t=await V(),u=t.getAction("clear_input"),r=t.getAction("input_text"),i=t.getAction("press");return Ar(e,u),wr(e,r),or(e,i),"Type text into inputs, clear input values, or press keyboard keys"}async function gt(e){let t=await V(),u=t.getAction("scroll_on_element"),r=t.getAction("scroll_to_text"),i=t.getAction("scroll");return hr(e,u),pr(e,r),fr(e,i),"Scroll the page or scroll to specific text/elements"}async function bt(e){let t=await V(),u=t.getAction("close_tab"),r=t.getAction("switch_tab");return yr(e,u),rr(e,r),"Switch between browser tabs or close tabs"}async function xt(e){let t=await V(),u=t.getAction("upload_file"),r=t.getAction("wait_for_download_complete");return ar(e,u),sr(e,r),"Upload files or wait for downloads to complete"}async function wt(e){let t=await V(),u=t.getAction("get_dropdown_options"),r=t.getAction("select_dropdown_option"),i=t.getAction("set_date_for_native_date_picker");return mr(e,u),tr(e,r),ur(e,i),"Get dropdown options, select dropdown values, or set date for native date picker input"}async function yt(e){let t=await V(),u=t.getAction("wait"),r=t.getAction("save_variable"),i=t.getAction("done");return nr(e,u),dr(e,r),vr(e,i),Fr(e),"Wait for conditions, save variables, or complete tasks"}async function vt(e){let t=(await V()).getAction("generate_2fa_code");Sr(e,t);let u=new la;return(await import("./handler-ESLITK6N.js")).default.registerAction("extract_email_content",u),da(e,u),"Generate 2FA codes or extract email/activation codes"}async function kt(e){let t=await V(),u=t.getAction("verify"),r=t.getAction("ai_extract"),i=t.getAction("ai_wait_until");return Tr(e,u),Er(e,r),er(e,i),"Perform AI-powered assertions, extractions, or wait conditions"}async function fa(e){let[t,u,r,i,a,n,s,c,l,f]=await Promise.all([ht(e),pt(e),mt(e),gt(e),bt(e),xt(e),wt(e),yt(e),vt(e),kt(e)]);return{mouse:t,navigation:u,input:r,scroll:i,tabs:a,files:n,forms:s,utility:c,auth:l,ai:f}}function ha(e){return[`- Mouse: ${e.mouse}`,`- Navigation: ${e.navigation}`,`- Input: ${e.input}`,`- Scroll: ${e.scroll}`,`- Tabs: ${e.tabs}`,`- Files: ${e.files}`,`- Forms: ${e.forms}`,`- Utility: ${e.utility}`,`- Auth: ${e.auth}`,`- AI: ${e.ai}`].join(`
99
+ ${x.body}`,g=await Qo(h,i,t.model);o.info(`Extracted content: ${g}`),g&&g!=="NOT_FOUND"&&b.push({content:g,email_subject:x.subject,email_from:x.from,email_date:x.date})}if(b.length>0){let x=b[0],h=`$email_${t.extraction_type}`;t.extraction_type==="custom"?h="$email_extracted_content":t.extraction_type==="activation_link"?h="$email_magic_link":t.extraction_type==="verification_code"&&(h="$email_otp_code");let g=(new Date().getTime()-a.getTime())/1e3;return o.info(`Successfully extracted content after ${s} attempts in ${g.toFixed(1)} seconds`),{data:x.content,result_variable:h,status:"success",message:`Successfully extracted content from email: ${x.email_subject.substring(0,50)}... (attempts: ${s})`}}else o.info(`Found emails but no extractable content in attempt ${s}`)}else o.info(`No emails found in attempt ${s}`)}catch(l){o.warn(`Error in polling attempt ${s}: ${l.message}`)}if(new Date(Date.now()+r*1e3)>=n){o.info("Not enough time for another polling attempt");break}o.info(`Waiting ${r} seconds before next attempt...`),await new Promise(l=>setTimeout(l,r*1e3))}let c=(new Date().getTime()-a.getTime())/1e3;return{data:void 0,status:"error",message:`No emails with extractable content found after ${s} attempts over ${c.toFixed(1)} seconds`}}catch(i){return o.error(`Error extracting email content: ${i.message}`),{data:void 0,status:"error",message:`Error extracting email content: ${i.message}`}}}import{z as Y}from"zod";function ca(e){switch(e){case"verification_code":return"email_otp_code";case"activation_link":return"email_magic_link";case"custom":return"email_extracted_content";default:return"email_content"}}var la=class{getMailgunConfig(){let e=jt().env||{};if(e.MAILGUN_API_KEY)return{apiKey:e.MAILGUN_API_KEY,domain:e.MAILGUN_DOMAIN||""}}async execute(e,t,u){let r=t.action_data;if(!r)throw new Error("Action data not found");let i=this.getMailgunConfig();if(!i)throw new Error("Mailgun configuration not provided. Please configure MAILGUN_API_KEY and MAILGUN_DOMAIN in SDK config.");let a=r.kwargs,n=u.getModel?.()||"gemini-2.5-pro",s=await oa(i,{model:n,forward_email:a.forward_email,extraction_type:a.extraction_type,prompt:a.prompt,filters:{from_email:a.filter_from_email,to_email:a.filter_to_email,subject:a.filter_subject,body_contains:a.filter_body_contains},timeout:a.timeout});if(s.status==="success"&&s.data){let c=s.result_variable?.replace(/^\$/,"")||ca(a.extraction_type);u.variableStore.set(c,s.data),o.info(`[extract_email_content] Extracted and saved to ${c}`)}else throw new Error(s.message||"Failed to extract email content")}transpile(e){let t=e.action_data?.kwargs||{};return['await agent.execAction("extract_email_content", page, {',` action_data: { kwargs: ${JSON.stringify(t)} },`,"});"]}},e0=Y.object({forward_email:Y.string().describe("Email address where emails are forwarded to (Mailgun inbox)"),extraction_type:Y.enum(["verification_code","activation_link","custom"]).describe("Type of content to extract: verification_code for OTP codes, activation_link for magic links, custom for custom prompts"),prompt:Y.string().optional().describe("Custom extraction prompt (required when extraction_type is custom)"),filter_from_email:Y.string().optional().describe("Filter emails by sender address"),filter_to_email:Y.string().optional().describe("Filter emails by recipient address"),filter_subject:Y.string().optional().describe("Filter emails by subject (partial match)"),filter_body_contains:Y.string().optional().describe("Filter emails by body content (partial match)"),timeout:Y.number().optional().describe("Timeout in seconds for polling (default: 60)")});function da(e,t){e.register({name:"extract_email_content",description:"Extract verification codes, magic links, or custom content from emails received via Mailgun. Polls the Mailgun inbox for matching emails and uses AI to extract the requested content.",schema:e0,async execute(u,r){let{forward_email:i,extraction_type:a,prompt:n,filter_from_email:s,filter_to_email:c,filter_subject:l,filter_body_contains:f,timeout:b}=u,{page:x,agentServices:h}=r;o.info(`[extract_email_content] Extracting ${a} from ${i}`);try{let g={action_description:`Extract ${a} from email`,action_data:{action_name:"extract_email_content",kwargs:{forward_email:i,extraction_type:a,prompt:n,filter_from_email:s,filter_to_email:c,filter_subject:l,filter_body_contains:f,timeout:b}}};await t.execute(x,g,h);let v=ca(a);return{success:!0,actionEntity:g,message:`Extracted ${a} and saved to $${v}`}}catch(g){return{success:!1,error:g.message,actionEntity:{action_description:`Extract ${a} from email (failed)`,action_data:{action_name:"extract_email_content",kwargs:{forward_email:i,extraction_type:a,prompt:n,filter_from_email:s,filter_to_email:c,filter_subject:l,filter_body_contains:f,timeout:b}},feedback:g.message}}}}})}var ft=null;async function V(){if(ft)return ft;let e=(await import("./handler-N7MN6JWY.js")).default;return ft=new e,ft}async function ht(e){let t=await V(),u=t.getAction("click"),r=t.getAction("hover"),i=t.getAction("right_click"),a=t.getAction("double_click");return Lr(e,u),xr(e,r),lr(e,i),kr(e,a),"Click, hover, double-click, right-click, or drag elements"}async function pt(e){let t=await V(),u=t.getAction("go_to_url"),r=t.getAction("go_back"),i=t.getAction("reload_page");return br(e,u),gr(e,r),cr(e,i),"Navigate to URLs, go back, or reload the page"}async function mt(e){let t=await V(),u=t.getAction("clear_input"),r=t.getAction("input_text"),i=t.getAction("press");return Ar(e,u),wr(e,r),or(e,i),"Type text into inputs, clear input values, or press keyboard keys"}async function gt(e){let t=await V(),u=t.getAction("scroll_on_element"),r=t.getAction("scroll_to_text"),i=t.getAction("scroll");return hr(e,u),pr(e,r),fr(e,i),"Scroll the page or scroll to specific text/elements"}async function bt(e){let t=await V(),u=t.getAction("close_tab"),r=t.getAction("switch_tab");return yr(e,u),rr(e,r),"Switch between browser tabs or close tabs"}async function xt(e){let t=await V(),u=t.getAction("upload_file"),r=t.getAction("wait_for_download_complete");return ar(e,u),sr(e,r),"Upload files or wait for downloads to complete"}async function wt(e){let t=await V(),u=t.getAction("get_dropdown_options"),r=t.getAction("select_dropdown_option"),i=t.getAction("set_date_for_native_date_picker");return mr(e,u),tr(e,r),ur(e,i),"Get dropdown options, select dropdown values, or set date for native date picker input"}async function yt(e){let t=await V(),u=t.getAction("wait"),r=t.getAction("save_variable"),i=t.getAction("done");return nr(e,u),dr(e,r),vr(e,i),Fr(e),"Wait for conditions, save variables, or complete tasks"}async function vt(e){let t=(await V()).getAction("generate_2fa_code");Sr(e,t);let u=new la;return(await import("./handler-N7MN6JWY.js")).default.registerAction("extract_email_content",u),da(e,u),"Generate 2FA codes or extract email/activation codes"}async function kt(e){let t=await V(),u=t.getAction("verify"),r=t.getAction("ai_extract"),i=t.getAction("ai_wait_until");return Tr(e,u),Er(e,r),er(e,i),"Perform AI-powered assertions, extractions, or wait conditions"}async function fa(e){let[t,u,r,i,a,n,s,c,l,f]=await Promise.all([ht(e),pt(e),mt(e),gt(e),bt(e),xt(e),wt(e),yt(e),vt(e),kt(e)]);return{mouse:t,navigation:u,input:r,scroll:i,tabs:a,files:n,forms:s,utility:c,auth:l,ai:f}}function ha(e){return[`- Mouse: ${e.mouse}`,`- Navigation: ${e.navigation}`,`- Input: ${e.input}`,`- Scroll: ${e.scroll}`,`- Tabs: ${e.tabs}`,`- Files: ${e.files}`,`- Forms: ${e.forms}`,`- Utility: ${e.utility}`,`- Auth: ${e.auth}`,`- AI: ${e.ai}`].join(`
100
100
  `)}var t0=[ht(O),pt(O),mt(O),gt(O),bt(O),xt(O),wt(O),yt(O),kt(O),vt(O)],u0=Promise.all(t0);async function r0(){await u0}function i0(){return O}function a0(e=!0){let t=new Oe;return e&&(ht(t),pt(t),mt(t),gt(t),bt(t),xt(t),wt(t),vt(t),yt(t),kt(t)),t}async function n0(){let e=new Oe,t=await fa(e),u=ha(t);return{registry:e,capabilities:t,summary:u}}function s0(){return["- Mouse: Click, hover, double-click, right-click or drag on elements","- Navigation: Navigate to URLs, go back, or reload the page","- Input: Type text into inputs, clear input fields, or press keyboard keys","- Scroll: Scroll the page or scroll to specific text/elements","- Tabs: Switch between browser tabs or close tabs","- Files: Upload files or wait for downloads to complete","- Forms: Get dropdown options or select dropdown values","- Utility: Wait for conditions, save variables, or complete tasks","- Auth: Generate 2FA codes or extract email/activation codes","- AI: Perform AI-powered verifications, extractions, or wait conditions"].join(`
101
101
  `)}var o0=class{constructor(e,t){this.registry=e,this.getContext=t}getToolDefinitions(){return this.registry.getTools().filter(e=>e.availability.mcp).map(e=>({name:e.name,description:e.description,inputSchema:Pe(e.schema)}))}getToolDefinitionsFiltered(e){let t=new Set(e);return this.registry.getTools().filter(u=>t.has(u.name)&&u.availability.mcp).map(u=>({name:u.name,description:u.description,inputSchema:Pe(u.schema)}))}async createServer(e="web-sdk-tools"){throw new Error("MCP server creation not yet implemented. Install and configure an MCP SDK like @modelcontextprotocol/sdk")}async executeTool(e,t){let u=await this.getContext(),r=await this.registry.execute(e,t,u);return{content:[{type:"text",text:r.success?r.message||"Tool executed successfully":r.error||"Tool execution failed"}]}}getToolCount(){return this.registry.size()}getToolNames(){return this.registry.getToolNames()}};function c0(e){return e.getTools().map(t=>({name:t.name,description:t.description,inputSchema:Pe(t.schema)}))}import Tt from"fs";import St from"path";import{chromium as pa,firefox as l0,webkit as d0}from"playwright";async function f0(e,t){let u=JSON.parse(Tt.readFileSync(t,"utf-8"));u.cookies?.length&&await e.addCookies(u.cookies)}var h0=class{constructor(e={}){e.testDir&&(this.testDir=e.testDir,this.videoBasePath=St.join(e.testDir,"videos"),this.statesBasePath=St.join(e.testDir,"states"),this.downloadsBasePath=St.join(e.testDir,"downloads"),Tt.mkdirSync(this.videoBasePath,{recursive:!0}),Tt.mkdirSync(this.statesBasePath,{recursive:!0}),Tt.mkdirSync(this.downloadsBasePath,{recursive:!0})),this.terminationTimeout=e.terminationTimeout??null,this.defaultHeadless=e.headless??!1,this.additionalArgs=e.additionalArgs??[]}async launchBrowser(e={}){let t=e.debugPort,u=e.headless??this.defaultHeadless,r=Or(e.deviceName),i=Pr(e.deviceName),a=r===pe.Chromium,n=!!e.extensionPath;o.info(`[BrowserManager] Launching ${r} browser for device: ${e.deviceName||"default"}${t?` on port ${t}`:""}`);let s={headless:u};if(a){n&&u&&(o.warn("[BrowserManager] Extension requested in headless mode; forcing headed mode to load extension."),u=!1,s.headless=!1);let k=[];(e.enableCamera||e.enableMicrophone)&&(k.push("--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"),e.enableMicrophone&&e.fakeAudioCapturePath&&(k.push(`--use-file-for-fake-audio-capture=${e.fakeAudioCapturePath}`),o.info(`[BrowserManager] Using fake audio capture file: ${e.fakeAudioCapturePath}`)));let L=n&&e.extensionPath?[`--disable-extensions-except=${e.extensionPath}`,`--load-extension=${e.extensionPath}`]:[];s.args=[..._r(t,e.disableSecurity??!0,u),...k,...L,...this.additionalArgs],i&&(s.channel=i,o.debug(`[BrowserManager] Launching browser with channel: ${i}`))}let c=$r(e.deviceName),l=Br(e.deviceName),f={acceptDownloads:!0,...c,timezoneId:"America/Los_Angeles",locale:e.locale||"en-US"},b=n&&a?e.localStorageStatePath:void 0;e.localStorageStatePath&&!b&&(f.storageState=e.localStorageStatePath),e.recordVideo&&this.videoBasePath&&(f.recordVideo={dir:this.videoBasePath,size:{width:l.width,height:l.height}}),e.proxy&&(f.proxy=e.proxy);let x,h,g;if(n&&a){if(e.userDataDir)g=e.userDataDir;else if(this.testDir)g=St.join(this.testDir,"user-data");else throw new Error("[BrowserManager] testDir is required to launch a persistent context with an extension");let k={...s,...f};h=await pa.launchPersistentContext(g,k),b&&(await f0(h,b),o.info(`[BrowserManager] Loaded storage state into persistent context from ${b}`)),x=h.browser(),o.info(`[BrowserManager] Launched persistent context for extension at ${e.extensionPath}`)}else{switch(r){case pe.Firefox:x=await l0.launch(s);break;case pe.Webkit:x=await d0.launch(s);break;case pe.Chromium:default:x=await pa.launch(s);break}h=await x.newContext(f)}if(h.addInitScript(Gt),e.enableCamera||e.enableMicrophone)if(!a)o.warn("[BrowserManager] Camera/microphone enabled but browser is not Chromium; ignoring.");else{let k=[];e.enableCamera&&k.push("camera"),e.enableMicrophone&&k.push("microphone");try{await h.grantPermissions(k),o.info(`[BrowserManager] Granted permissions: ${k.join(", ")}`)}catch(L){o.warn("[BrowserManager] Failed to grant camera/microphone permissions:",L)}}if(e.cookies&&e.cookies.length>0){let k=(Date.now()+31536e6)/1e3,L=e.cookies.map(P=>({...P,expires:k}));await h.addCookies(L),o.info(`[BrowserManager] Added ${e.cookies.length} cookies to browser context with expires=${k}`)}let v=Cr(e.deviceName);o.info(`[BrowserManager] windowSize=${JSON.stringify(v)}`),a&&h.on("page",async k=>{try{await Kt(k,v.width,v.height)}catch(L){o.warn("[BrowserManager] Failed to set window bounds via CDP:",L)}});let w="";if(a&&t!==void 0)try{w=await zt(t)}catch(k){o.warn("[BrowserManager] Failed to get CDP WebSocket URL:",k)}let y={debugPort:t,browser:x,context:h,startTime:new Date,timeout:null,browserWsUrl:w,downloadsBasePath:this.downloadsBasePath,browserType:r,userDataDir:g};if(this.terminationTimeout!==null){let k=setTimeout(()=>{o.info(`[BrowserManager] Browser auto-terminated after ${this.terminationTimeout}ms`),this.terminateBrowser(y).catch(L=>o.error("[BrowserManager] Error terminating browser:",L))},this.terminationTimeout);y.timeout=k}return y}async terminateBrowser(e){e.timeout&&clearTimeout(e.timeout),await e.context.close(),await e.browser.close()}getVideoBasePath(){return this.videoBasePath}getStatesBasePath(){return this.statesBasePath}getDownloadsBasePath(){return this.downloadsBasePath}};var p0=e=>{if(!e||e===Nr)return"desktop";let t=Dr(e);return t&&t.isMobile?"mobile":"desktop"};var m0=(e=>(e.Desktop="desktop",e.Mobile="mobile",e))(m0||{});var ma=class{constructor(e){this.currentPage=null,this.currentIndex=-1,this.context=e,this.initialize()}initialize(){this.context.on("page",async t=>{await this.handleNewPage(t)});let e=this.context.pages();e.length>0&&(this.currentPage=e[0],this.currentIndex=0);for(let t of e)this.setupPageListeners(t)}async handleNewPage(e){try{this.setupPageListeners(e);let t=this.context.pages().indexOf(e);await this.setCurrentPage(e,t)}catch{}}setupPageListeners(e){e.on("close",async()=>{await this.handlePageClose(e)})}async handlePageClose(e){try{if(this.currentPage===e){let t=this.context.pages(),u=t.slice().reverse().find(r=>!r.isClosed());u&&await this.setCurrentPage(u,t.indexOf(u))}}catch{}}async setCurrentPage(e,t){let u=this.currentPage!==e;this.currentPage=e,this.currentIndex=t,u&&await e.bringToFront()}async switchToPage(e){let t=this.context.pages();if(e<0||e>=t.length)throw new Error(`Invalid page index: ${e}. Available pages: 0-${t.length-1}`);let u=t[e];if(u.isClosed())throw new Error(`Page at index ${e} is closed`);return await this.setCurrentPage(u,e),u}async closePage(e){let t=this.context.pages();if(e<0||e>=t.length)throw new Error(`Invalid page index: ${e}. Available pages: 0-${t.length-1}`);let u=t[e];if(u.isClosed())throw new Error(`Page at index ${e} is already closed`);await u.close()}getCurrentPage(){return this.currentPage}getCurrentIndex(){return this.currentIndex}getAllPages(){return this.context.pages()}getPageCount(){return this.context.pages().length}};async function ga(e,t=3e3,u=1e3){try{await qe(e,t,u)}catch{}}async function ba(e,t,u){let r=u*1e3,i=100,a=Date.now();for(;!t.downloadStatus||t.downloadStatus.status==="inProgress";){if(Date.now()-a>r){let n;throw t.downloadStatus?n=`Timed out after ${r}ms waiting for download to complete`:n="No download in progress or completed",o.error(n),new Error(n)}await e.waitForTimeout(i)}if(t.downloadStatus.status==="failed"){let n=`Download failed: ${t.downloadStatus.error||"Unknown error"}`;throw o.error(n),new Error(n)}t.agentNote=`Download completed: ${t.downloadStatus.filename}`}async function xa(e,t,u,r=60,i){let a=Math.min(r,280),n=Math.max(10,a/10)*1e3,s=Date.now()+a*1e3;for(o.info(`Waiting for condition: "${t}" (timeout: ${a}s)`);;){let c=Date.now();try{if(await u(e,t,i))return o.info(`Condition met: "${t}"`),!0}catch(f){o.warn(`Error evaluating condition: ${f.message}`)}if(Date.now()>s)return o.warn(`Timeout waiting for condition: "${t}"`),!1;let l=n-(Date.now()-c);l>0&&await e.waitForTimeout(l)}}var en=Xu(Za(),1);import*as Qa from"fs";import*as Ce from"path";function tn(e){return e.url()===":"}var Ju=class{constructor(e){this.context=e,this.testDataFileNames=[],this.extensionEnabled=!1}setTestDataDownloader(e,t){this.testDataDownloader=e,this.testDataFileNames=t??[]}setupPageTracking(e){this.tabManager=new ma(e)}async switchTab(e){if(!this.tabManager)throw new Error("Tab manager not initialized");return await this.tabManager.switchToPage(e)}async closeTab(e){if(!this.tabManager)throw new Error("Tab manager not initialized");await this.tabManager.closePage(e)}getCurrentPage(){return this.tabManager?this.tabManager.getCurrentPage():null}validatePage(e){let t=this.getCurrentPage();if(t&&t!==e&&!t.isClosed())return o.info(`[validatePage] Page changed, switching to ${t.url()}`),t;if(e.isClosed()){let u=e.context().pages().filter(r=>!r.isClosed());if(u.length>0){let r=u[u.length-1];return o.info(`[validatePage] Page closed, switching to ${r.url()}`),r}o.error("[validatePage] No valid pages found")}return e}replaceVariables(e){return Yt(e,this.context.variableStore.getAll())}getTestDataFileNames(){return this.testDataFileNames}getTestDataFilePath(e){let t=this.context.testDataDir||process.cwd();return Ce.join(t,e)}async downloadTestDataFiles(e){if(e.length===0){o.debug("[AgentServices] No file paths provided for download");return}let t=this.context.testDataDir||process.cwd(),u=e.filter(r=>{let i=Ce.basename(r),a=Ce.join(t,i),n=Qa.existsSync(a);return n&&o.debug(`[AgentServices] File already exists locally: ${i}`),!n});if(u.length===0){o.debug("[AgentServices] All files exist locally, no download needed");return}if(!this.testDataDownloader){o.debug("[AgentServices] No test data downloader configured, assuming files are pre-populated");return}o.info(`[AgentServices] Downloading ${u.length} test data files: ${u.join(", ")}`),await this.testDataDownloader(u,t)}async waitForDownloadComplete(e,t){return ba(e,this.context,t)}getRecentDownloadedFilePath(){return this.context.downloadStatus?this.context.downloadStatus.status!=="completed"?(o.debug(`Download is ${this.context.downloadStatus.status}, not completed`),null):this.context.downloadStatus.filePath?(o.info(`Retrieved recent download path: ${this.context.downloadStatus.filePath}`),this.context.downloadStatus.filePath):(o.warn("Download completed but file path is missing"),null):(o.debug("No download found"),null)}addSensitive(e,t){this.context.variableStore.set(e,t,!0)}saveVariable(e,t){let u=e.startsWith("$")?e.slice(1):e;this.context.variableStore.set(u,t),o.debug(`Saved variable: ${u} = ${JSON.stringify(t)}`),this.context.agentNote=`A new value is saved to the variable "${u}".`}addNote(e){!e||e.trim()===""||(this.context.agentNote?this.context.agentNote+=`
102
- ${e.trim()}`:this.context.agentNote=e.trim())}readVariable(e){let t=e.startsWith("$")?e.slice(1):e,u=this.context.variableStore.get(t);return o.debug(`Read variable: ${t} = ${JSON.stringify(u)}`),u}async generate2faCode(e){try{let t=en.authenticator.generate(e);return o.info(`Generated 2FA code: ${t}`),t}catch(t){throw o.error(`Failed to generate 2FA code: ${t.message}`),new Error(`Failed to generate 2FA code: ${t.message}`)}}async getDOMText(e){return await e.evaluate(()=>document.body.innerText)}async waitUntilStable(e,t){return qe(e,t)}setPage(e){this.context.setPage?(o.info("[AgentServices] Calling setPage callback"),this.context.setPage(e)):o.debug("[AgentServices] setPage callback not configured")}getModel(){if(!this.context.model)throw new Error("No LLM model configured. An LLM model is required for AI-powered actions (login, verify, ai_extract, ai_wait_until, etc.). Set GOOGLE_API_KEY or ANTHROPIC_API_KEY in your MCP server configuration.");return this.context.model}get variableStore(){return this.context.variableStore}getDownloadDir(){return this.context.downloadDir}getActionSettings(){return this.context.organizationSettings?.action_code_conversion_settings||{}}getInteractiveClassNames(){return this.context.organizationSettings?.agent_settings?.interactive_class_names||[]}getIframeFallbackDomains(){return this.context.organizationSettings?.agent_settings?.iframe_fallback_domains||[]}isUseCleanScreenshotForAssertion(){return this.context.organizationSettings?.use_clean_screenshot_for_assertion||!1}isKnowledgeImagesEnabled(){return this.context.organizationSettings?.agent_settings?.enable_knowledge_images||!1}isSlicedScreenshotsEnabled(){return this.context.organizationSettings?.agent_settings?.use_sliced_screenshots||!1}isResizeSlicedScreenshotsEnabled(){return this.context.organizationSettings?.agent_settings?.resize_sliced_screenshots||!1}isAccessibilityTreeEnabled(){return this.context.organizationSettings?.agent_settings?.use_accessibility_tree||!1}isActionIntentFilteringEnabled(){return this.context.organizationSettings?.agent_settings?.use_action_intent_filtering||!1}isDomTreeTsEnabled(){let e=process.env.USE_DOM_TREE_TS;return e!==void 0?e==="true"||e==="1":this.context.organizationSettings?.agent_settings?.use_dom_tree_ts||!1}setExtensionEnabled(e){this.extensionEnabled=e}getDomServiceOptions(){return{useDomTreeTs:this.isDomTreeTsEnabled(),domTreeRoot:this.extensionEnabled?"document":"body"}}setKnowledgeRetriever(e){this.knowledgeRetriever=e}hasKnowledgeRetriever(){return this.knowledgeRetriever!==void 0}async retrieveKnowledges(e,t,u,r){if(!this.knowledgeRetriever)return o.debug("[AgentServices] No knowledge retriever configured"),[];try{let i=await this.knowledgeRetriever(e,t,u,r);return o.debug(`[AgentServices] Retrieved ${i.length} knowledges for statement`),i}catch(i){return o.warn(`[AgentServices] Failed to retrieve knowledges: ${i.message}`),[]}}};var un=(e=>(e.Started="started",e.Action="action",e.Completion="completion",e.Error="error",e.Aborted="aborted",e.Keepalive="keepalive",e))(un||{}),Yu=class extends Error{constructor(e){super(e),this.name="AgentTaskFailedError",this.details=e}};import*as N from"fs";import*as C from"path";var _0=1,I0=3,N0=40;function Be(e,t){let u={};for(let[r,i]of Object.entries(e))u[r]=t.has(r)?"*****":i;return u}var rn=class{constructor(e){this.context=e,this._newActionEntities=new Map,this.agentServices=new Ju(e),this.agentServices.agent=this,this.context.tokenUsages||(this.context.tokenUsages=[])}getNewActionEntities(){return this._newActionEntities}async getActionHandler(){if(!this._actionHandler){let{default:e}=await import("./handler-ESLITK6N.js");this._actionHandler=new e}return this._actionHandler}async execAction(e,t,u){let r=(await this.getActionHandler()).getAction(e);if(!r)throw new Error(`Unknown action: ${e}`);await r.execute(t,u,this.agentServices)}async dismissModalIfPresent(e,t){try{let u=await this.execute(e,`TASK: Check if there is an INTRUSIVE POPUP blocking the page, and dismiss it if present.
102
+ ${e.trim()}`:this.context.agentNote=e.trim())}readVariable(e){let t=e.startsWith("$")?e.slice(1):e,u=this.context.variableStore.get(t);return o.debug(`Read variable: ${t} = ${JSON.stringify(u)}`),u}async generate2faCode(e){try{let t=en.authenticator.generate(e);return o.info(`Generated 2FA code: ${t}`),t}catch(t){throw o.error(`Failed to generate 2FA code: ${t.message}`),new Error(`Failed to generate 2FA code: ${t.message}`)}}async getDOMText(e){return await e.evaluate(()=>document.body.innerText)}async waitUntilStable(e,t){return qe(e,t)}setPage(e){this.context.setPage?(o.info("[AgentServices] Calling setPage callback"),this.context.setPage(e)):o.debug("[AgentServices] setPage callback not configured")}getModel(){if(!this.context.model)throw new Error("No LLM model configured. An LLM model is required for AI-powered actions (login, verify, ai_extract, ai_wait_until, etc.). Set GOOGLE_API_KEY or ANTHROPIC_API_KEY in your MCP server configuration.");return this.context.model}get variableStore(){return this.context.variableStore}getDownloadDir(){return this.context.downloadDir}getActionSettings(){return this.context.organizationSettings?.action_code_conversion_settings||{}}getInteractiveClassNames(){return this.context.organizationSettings?.agent_settings?.interactive_class_names||[]}getIframeFallbackDomains(){return this.context.organizationSettings?.agent_settings?.iframe_fallback_domains||[]}isUseCleanScreenshotForAssertion(){return this.context.organizationSettings?.use_clean_screenshot_for_assertion||!1}isKnowledgeImagesEnabled(){return this.context.organizationSettings?.agent_settings?.enable_knowledge_images||!1}isSlicedScreenshotsEnabled(){return this.context.organizationSettings?.agent_settings?.use_sliced_screenshots||!1}isResizeSlicedScreenshotsEnabled(){return this.context.organizationSettings?.agent_settings?.resize_sliced_screenshots||!1}isAccessibilityTreeEnabled(){return this.context.organizationSettings?.agent_settings?.use_accessibility_tree||!1}isActionIntentFilteringEnabled(){return this.context.organizationSettings?.agent_settings?.use_action_intent_filtering||!1}isDomTreeTsEnabled(){let e=process.env.USE_DOM_TREE_TS;return e!==void 0?e==="true"||e==="1":this.context.organizationSettings?.agent_settings?.use_dom_tree_ts||!1}setExtensionEnabled(e){this.extensionEnabled=e}getDomServiceOptions(){return{useDomTreeTs:this.isDomTreeTsEnabled(),domTreeRoot:this.extensionEnabled?"document":"body"}}setKnowledgeRetriever(e){this.knowledgeRetriever=e}hasKnowledgeRetriever(){return this.knowledgeRetriever!==void 0}async retrieveKnowledges(e,t,u,r){if(!this.knowledgeRetriever)return o.debug("[AgentServices] No knowledge retriever configured"),[];try{let i=await this.knowledgeRetriever(e,t,u,r);return o.debug(`[AgentServices] Retrieved ${i.length} knowledges for statement`),i}catch(i){return o.warn(`[AgentServices] Failed to retrieve knowledges: ${i.message}`),[]}}};var un=(e=>(e.Started="started",e.Action="action",e.Completion="completion",e.Error="error",e.Aborted="aborted",e.Keepalive="keepalive",e))(un||{}),Yu=class extends Error{constructor(e){super(e),this.name="AgentTaskFailedError",this.details=e}};import*as N from"fs";import*as C from"path";var _0=1,I0=3,N0=40;function Be(e,t){let u={};for(let[r,i]of Object.entries(e))u[r]=t.has(r)?"*****":i;return u}var rn=class{constructor(e){this.context=e,this._newActionEntities=new Map,this.agentServices=new Ju(e),this.agentServices.agent=this,this.context.tokenUsages||(this.context.tokenUsages=[])}getNewActionEntities(){return this._newActionEntities}async getActionHandler(){if(!this._actionHandler){let{default:e}=await import("./handler-N7MN6JWY.js");this._actionHandler=new e}return this._actionHandler}async execAction(e,t,u){let r=(await this.getActionHandler()).getAction(e);if(!r)throw new Error(`Unknown action: ${e}`);await r.execute(t,u,this.agentServices)}async dismissModalIfPresent(e,t){try{let u=await this.execute(e,`TASK: Check if there is an INTRUSIVE POPUP blocking the page, and dismiss it if present.
103
103
 
104
104
  ONLY dismiss intrusive popups such as:
105
105
  - Cookie/GDPR consent banners
@@ -121,7 +121,7 @@ If you find an intrusive popup, dismiss it by clicking its close/X button or "No
121
121
  IMPORTANT: Only act with HIGH CONFIDENCE. If unsure whether something is an intrusive popup, do nothing.
122
122
  It's better to miss a popup than to accidentally interact with normal page elements.
123
123
 
124
- If NO intrusive popup is present, do nothing and report that no intrusive popup was found.`,void 0,!1,I0),r=!!(u.actions&&u.actions.length>0);return{success:u.success,modalDismissed:r,details:u.details||(r?"Modal dismissed":"No modal found")}}catch(u){return{success:!1,modalDismissed:!1,details:u.message||"Modal dismissal failed"}}}_getContext(){return this.context}setupDownloadTracking(e){if(o.info(`[Download Tracking] Setting up download tracking for page: ${e.url()}`),tn(e)){o.info(`[Download Tracking] Skipping download tracking for blank tab: ${e.url()}`),e.close();return}e.on("download",async t=>{let u=t.suggestedFilename();o.info(`[Download Tracking] Download event detected! File: ${u}`),this.context.downloadStatus={filename:u,status:"inProgress",startTime:Date.now()},o.info(`[Download Tracking] Download status set to inProgress: ${JSON.stringify(this.context.downloadStatus)}`);try{let r=this.context.downloadDir||C.join(process.cwd(),"downloads");N.existsSync(r)||N.mkdirSync(r,{recursive:!0});let i=C.join(r,u);o.info(`[Download Tracking] Downloading file to: ${i}`),await t.saveAs(i),this.context.downloadStatus={filename:u,status:"completed",startTime:this.context.downloadStatus.startTime,filePath:i,timestamp:Date.now()},o.info(`[Download Tracking] Download completed: ${i}`),o.info(`[Download Tracking] Download status set to completed: ${JSON.stringify(this.context.downloadStatus)}`)}catch(r){this.context.downloadStatus={filename:u,status:"failed",startTime:this.context.downloadStatus.startTime,error:r.message,timestamp:Date.now()},o.error(`[Download Tracking] Download failed for ${u}: ${r.message}`)}})}setupDialogHandling(e){if(o.debug(`[Dialog Handling] setupDialogHandling called, isClosed=${e.isClosed()}, url=${e.url()}`),e.isClosed()){o.debug("[Dialog Handling] Skipping - page is closed");return}o.info(`[Dialog Handling] Setting up dialog handling for page: ${e.url()}`),e.on("dialog",async t=>{let u=t.type(),r=t.message();o.info(`[Dialog Handling] Dialog detected - type: ${u}, message: "${r}"`);let i=u==="beforeunload";try{i?await t.dismiss():await t.accept(),this.context.dialogStatus={type:u,message:r,response:i?"dismiss":"accept",timestamp:Date.now()},o.info(`[Dialog Handling] Dialog ${i?"dismissed":"accepted"} - type: ${u}, message: "${r}"`)}catch(a){o.warn(`[Dialog Handling] Failed to handle dialog (already dismissed?): ${a}`)}})}getRecentDownloadedFilePath(){return this.agentServices.getRecentDownloadedFilePath()}addNote(e){this.agentServices.addNote(e)}collectTokenUsages(e){let t;Array.isArray(e)?t=e:e?.tokenUsages&&(t=e.tokenUsages),t&&t.length>0?(this.context.tokenUsages||(this.context.tokenUsages=[]),this.context.tokenUsages.push(...t),o.debug(`[collectTokenUsages] Added ${t.length} token usage(s), total: ${this.context.tokenUsages.length}`)):o.debug("[collectTokenUsages] No token usages to collect (undefined or empty)")}trackAIAction(e,t,u,r=1,i,a){if(!e)return;let n=u?.tokenUsages||[];this.context.aiActionDetails||(this.context.aiActionDetails=[]);let s=this.context.aiActionDetails.find(c=>c.stepId===e&&c.actionType===t);s?(s.count+=r,n.length>0&&s.tokenUsages.push(...n),u?.userPrompt&&(s.userPrompt=u.userPrompt),u?.rawLlmResponse&&(s.rawLlmResponse=u.rawLlmResponse),u?.reasoningContent&&(s.reasoningContent=u.reasoningContent),u?.elementTree&&(s.elementTree=u.elementTree),u?.screenshotWithSom&&(s.screenshotWithSom=u.screenshotWithSom),a&&(s.explanation=a)):this.context.aiActionDetails.push({stepId:e,actionType:t,count:r,tokenUsages:[...n],statement:i,userPrompt:u?.userPrompt,rawLlmResponse:u?.rawLlmResponse,reasoningContent:u?.reasoningContent,explanation:a,elementTree:u?.elementTree,screenshotWithSom:u?.screenshotWithSom}),o.debug(`[trackAIAction] Tracked ${t} for step ${e}, count: ${r}`)}async assert(e,t,u){o.info(`Asserting statement: ${t}`),u&&this.context.stepTracking&&await this.createStepResult(e,u,t),await this.agentServices.waitUntilStable(e);try{let r=this.getCompletedExecutionHistory(),i=await He(t,e,this.agentServices,{executionHistory:r,useCleanScreenshotForAssertion:!0,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys()});this.collectTokenUsages(i.debugInfo),this.context.lastActionDebugInfo=i.debugInfo;let a=i.explanation||i.error||"No explanation";if(u&&this.trackAIAction(u,"assert",i.debugInfo,1,t,a),this.context.agentNote=a,u&&this.context.stepTracking&&await this.updateStepResult(u,i.success?"success":"failure",a,void 0,i.debugInfo),!i.success)throw this.addToExecutionHistory(`Assert: "${t}"`,`Failed: ${a}`),new Error(`Assertion failed: ${a}`);return this.addToExecutionHistory(`Assert: "${t}"`,`Passed: ${a}`),!0}catch(r){throw u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",r.message),r}}async evaluate(e,t,u){o.info(`Evaluating condition: ${t}`),u&&this.context.stepTracking&&await this.createStepResult(e,u,t),await this.agentServices.waitUntilStable(e);try{let r=this.getCompletedExecutionHistory(),i=await He(t,e,this.agentServices,{executionHistory:r,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys()});this.collectTokenUsages(i.debugInfo),this.context.lastActionDebugInfo=i.debugInfo;let a=i.explanation||i.error||"No explanation";return u&&this.trackAIAction(u,"evaluate",i.debugInfo,1,t,a),this.context.agentNote=a,u&&this.context.stepTracking&&await this.updateStepResult(u,"success",a,void 0,i.debugInfo),i.success?(this.addToExecutionHistory(`Evaluate: "${t}"`,`Result: true - ${a}`),!0):(o.warn(`AI evaluation returned false/unknown: ${a}`),this.addToExecutionHistory(`Evaluate: "${t}"`,`Unknown/False: ${a}`),!1)}catch(r){throw u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",r.message),r}}async performAction(e,t){o.info(`Act: ${t}`);let u=this.getCompletedExecutionHistory(),r=await Me(t,e,this.agentServices,{executionHistory:u,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys()});if(this.collectTokenUsages(r.debugInfo),r.status!=="success"||r.actionEntities.length===0)return{success:!1,details:r.explanation||r.error||"Action failed"};let i=r.actionEntities[0]?.action_description||t;return this.addToExecutionHistory(t,i),{success:!0,details:r.explanation}}async execute(e,t,u,r,i){if(i!==void 0&&i<=0)throw new Error(`maxSteps must be >= 1, got ${i}`);let a=i!==void 0&&i>1;o.info(`Executing statement: ${t} (${a?`multi, maxSteps: ${i}`:"single"})`),u&&this.context.stepTracking&&await this.createStepResult(e,u,t),e=this.agentServices.validatePage(e),await this.agentServices.waitUntilStable(e);try{let n=this.getCompletedExecutionHistory();this.context.agentNote="";let s,c;if(a){let f=u&&this.context.stepTracking?.artifactsDir?b=>{if(b.type==="action"&&b.debugInfo){let x=`${u}-step${b.step}`;this.saveDebugInfoToFiles(x,b.debugInfo,this.context.model)}}:void 0;if(s=await Ue(t,e,this.agentServices,f,{executionHistory:n,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys(),maxSteps:i??N0}),c=s.completed,this.collectTokenUsages(s.tokenUsages),u&&s.tokenUsages){let b={tokenUsages:s.tokenUsages};this.trackAIAction(u,"execute",b,s.actionEntities?.length||1,t,s.explanation||"Multi-step execution completed")}}else if(e=this.agentServices.validatePage(e),s=await Me(t,e,this.agentServices,{executionHistory:n,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys(),usePureVision:r}),c=s.completed,this.collectTokenUsages(s.debugInfo),this.context.lastActionDebugInfo=s.debugInfo,u){let f=s.explanation||s.error||"No explanation";this.trackAIAction(u,"execute",s.debugInfo,1,t,f)}if(s.status!=="success"||s.actionEntities.length===0||!c){let f=s.explanation||s.error||"Goal not completed";throw u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",f,void 0,s.debugInfo),new Error(`Action failed: ${f}`)}let l=this.context.agentNote||s.explanation||"Action executed successfully";return u&&this.context.stepTracking&&await this.updateStepResult(u,"success",l,void 0,s.debugInfo),this.addToExecutionHistory(`Execute: "${t}"`,l),{success:!0,details:l,actions:s.actionEntities,debugInfo:s.debugInfo}}catch(n){throw u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",n.message),this.addToExecutionHistory(`Execute: "${t}"`,`Failed: ${n.message}`),n}}async generate(e,t,u,r){u&&this.context.stepTracking&&await this.createStepResult(e,u,t);try{let i=this.getCompletedExecutionHistory(),a=await Jt(t,e,this.agentServices,{executionHistory:i,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys(),usePureVision:r});if(this.collectTokenUsages(a.debugInfo),a.status!=="success"||a.actionEntities.length===0){let c=a.explanation||a.error||"No explanation";throw u&&this.trackAIAction(u,"generate",a.debugInfo,1,t,c),u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",c,void 0,a.debugInfo),new Error(c)}let n=a.completed,s=a.explanation||"Action generated successfully";return u&&this.trackAIAction(u,"generate",a.debugInfo,1,t,s),u&&this.context.stepTracking&&await this.updateStepResult(u,"success",s,void 0,a.debugInfo),o.info(`[generate] Generated action for "${t}": ${s}, goalAccomplished: ${a.completed}`),{success:n,details:s,actions:a.actionEntities,debugInfo:a.debugInfo}}catch(i){throw u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",i.message),i}}async run(e,t,u,r){u&&this.context.stepTracking&&await this.createStepResult(e,u,t);try{let i=this.getCompletedExecutionHistory();this.context.agentNote="";let a=u&&this.context.stepTracking?.artifactsDir,n=r?.onAction||a?f=>{if(f.type==="action"&&f.action_entity&&(r?.onAction?.(f.action_entity),a&&f.debugInfo)){let b=`${u}-step${f.step}`;this.saveDebugInfoToFiles(b,f.debugInfo,this.context.model)}}:void 0,s=await Ue(t,e,this.agentServices,n,{executionHistory:i,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys(),abortSignal:r?.abortSignal,maxSteps:r?.maxSteps});S.log(`Run task result: status=${s.status}, completed=${s.completed}, actions=${s.actionEntities?.length||0}`),this.collectTokenUsages(s.tokenUsages);let c=s.status==="success"&&s.completed,l=this.context.agentNote?.trim()||s.explanation||s.error||(c?"Step completed":"Step failed");if(u&&s.tokenUsages){let f={tokenUsages:s.tokenUsages};this.trackAIAction(u,"run",f,s.actionEntities?.length||1,t,l)}if(!c)throw new Yu(l);return u&&this.context.stepTracking&&await this.updateStepResult(u,"success",l,void 0,void 0),this.addToExecutionHistory(`Run: "${t}"`,l),S.log(`Run result: success=${c}, details=${l}`),{success:c,details:l,actions:s.actionEntities}}catch(i){throw u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",i.message),this.addToExecutionHistory(`Run: "${t}"`,`Failed: ${i.message}`),i}}async step(e,t,u,r,i,a=!0,n){let s=Date.now();this.context.stepTracking&&await this.createStepResult(e,r,u),e=this.agentServices.validatePage(e),await this.agentServices.waitUntilStable(e),this.context.stepTracking&&(this.context.stepTracking.currentStepId=r),e=this.agentServices.validatePage(e);let c=e.url(),l=await this.captureDOMSnapshot(e),f=this.context.stepTracking?.captureVariables?Be(this.context.variableStore.getAll(),this.context.variableStore.getAllSensitiveKeys()):{},b=this.context.stepTracking?.results[r]?.screenshot;try{o.info(`Executing step ${r}: ${u}`),this.addToExecutionHistory(u,""),this.context.agentNote="",e=this.agentServices.validatePage(e);let x=await t();e=this.agentServices.validatePage(e);let h=e.url(),g=await this.captureDOMSnapshot(e),v=this.context.stepTracking?.captureVariables?Be(this.context.variableStore.getAll(),this.context.variableStore.getAllSensitiveKeys()):{};if(this.context.stepTracking&&await this.updateStepResult(r,"success",""),this.context.stepTracking?.captureStateTransitions&&this.context.stepTracking.stateTransitions){let y=Date.now()-s,k=this.context.stepTracking.results[r]?.screenshot,L=Date.now();this.context.stepTracking.stateTransitions.length===0&&this.context.stepTracking.stateTransitions.push({type:"state",url:c,domSnapshot:l||void 0,variables:f,screenshotPath:b,timestamp:s}),this.context.stepTracking.stateTransitions.push({type:"action",stepId:r,description:u,action:{playwrightCode:[t.toString()]},consoleLogs:this.getConsoleLogsForStep(r),durationMs:y,status:"success"}),this.context.stepTracking.stateTransitions.push({type:"state",url:h,domSnapshot:g||void 0,variables:v,screenshotPath:k,timestamp:L})}let w=this.context.agentNote;return(!w||w.trim()==="")&&(w="Execution successful"),this.context.executionHistory&&this.context.executionHistory.length>0&&(this.context.executionHistory[this.context.executionHistory.length-1][1]=w),this.context.stepTracking&&(this.context.stepTracking.currentStepId=void 0),x}catch(x){e=this.agentServices.validatePage(e);let h=a&&!this.context.isSelfHealing;if(h&&(this.context.stepTracking&&await this.updateStepResult(r,"failure",x.message),this.context.executionHistory&&this.context.executionHistory.length>0&&(this.context.executionHistory[this.context.executionHistory.length-1][1]=x.message)),!u||u.trim()==="")throw o.error("No description provided for self-healing"),this.context.stepTracking&&(this.context.stepTracking.currentStepId=void 0),x;if(!h){if(o.info(`Failed to heal at step ${r}. ${u}`),this.context.isSelfHealing=!1,this.context.stepTracking?.captureStateTransitions&&this.context.stepTracking.stateTransitions){let w=e.url(),y=await this.captureDOMSnapshot(e),k=this.context.stepTracking.captureVariables?Be(this.context.variableStore.getAll(),this.context.variableStore.getAllSensitiveKeys()):{},L=Date.now()-s,P=Date.now();this.context.stepTracking.stateTransitions.length===0&&this.context.stepTracking.stateTransitions.push({type:"state",url:c,domSnapshot:l||void 0,variables:f,screenshotPath:b,timestamp:s}),this.context.stepTracking.stateTransitions.push({type:"action",stepId:r,description:u,action:{playwrightCode:[t.toString()]},consoleLogs:this.getConsoleLogsForStep(r),durationMs:L,status:"failure",errorMessage:x.message}),this.context.stepTracking.stateTransitions.push({type:"state",url:w,domSnapshot:y||void 0,variables:k,timestamp:P})}throw this.context.stepTracking&&(await this.updateStepResult(r,void 0,void 0),this.context.stepTracking.currentStepId=void 0),x}this.context.isSelfHealing=!0,o.info(`Action failed at step ${r}. ${u}`),o.info(`with error: ${x.message}`);let g;if(this.context.autoDisableModal){o.info("Attempting modal dismissal before self-healing...");let w=await this.dismissModalIfPresent(e,u);if(o.info(`Modal dismissal result: ${w.details}`),w.modalDismissed){g=`[Auto-dismissed modal: ${w.details}]`,o.info(`Modal dismissed, retrying original action for step ${r}`);try{let y=await t();return this.context.isSelfHealing=!1,this.context.executionHistory&&this.context.executionHistory.length>0&&(this.context.executionHistory[this.context.executionHistory.length-1][1]=g+" Retry successful"),this.context.stepTracking&&(await this.updateStepResult(r,"success",g),this.context.stepTracking.currentStepId=void 0),y}catch(y){o.info(`Retry after modal dismissal failed: ${y.message}, falling back to self-healing`)}}}let v=n??_0;o.info(`Calling execute() to self-heal (maxSteps: ${v})`);try{let w=await this.execute(e,u,r,!1,v);if(this.context.isSelfHealing=!1,!w.success)throw new Error(`Self-healing failed: ${w.details}`);let y=w.actions?.at(-1);i&&y&&(this._newActionEntities.set(i,y),o.info(`Stored new action entity for stmtUid: ${i} (last of ${w.actions?.length} actions)`));let k=e.url(),L=await this.captureDOMSnapshot(e),P=this.context.stepTracking?.captureVariables?Be(this.context.variableStore.getAll(),this.context.variableStore.getAllSensitiveKeys()):{};if(this.context.stepTracking){let F=g||"";await this.updateStepResult(r,"success",F)}if(this.context.stepTracking?.captureStateTransitions&&this.context.stepTracking.stateTransitions){let F=Date.now()-s,M=this.context.stepTracking.results[r]?.screenshot,qt=Date.now();this.context.stepTracking.stateTransitions.length===0&&this.context.stepTracking.stateTransitions.push({type:"state",url:c,domSnapshot:l||void 0,variables:f,screenshotPath:b,timestamp:s}),this.context.stepTracking.stateTransitions.push({type:"action",stepId:r,description:u,action:{actionEntity:y,playwrightCode:w.actions?.map(Mt=>Mt.locator||""),llmPrompt:w.debugInfo?.userPrompt,llmResponse:w.debugInfo?.rawLlmResponse,llmReasoning:w.debugInfo?.reasoningContent},consoleLogs:this.getConsoleLogsForStep(r),durationMs:F,status:"success"}),this.context.stepTracking.stateTransitions.push({type:"state",url:k,domSnapshot:L||void 0,variables:P,screenshotPath:M,timestamp:qt})}return this.context.stepTracking&&(this.context.stepTracking.currentStepId=void 0),w}catch(w){if(this.context.isSelfHealing=!1,this.context.stepTracking?.captureStateTransitions&&this.context.stepTracking.stateTransitions){let y=e.url(),k=await this.captureDOMSnapshot(e),L=this.context.stepTracking.captureVariables?Be(this.context.variableStore.getAll(),this.context.variableStore.getAllSensitiveKeys()):{},P=Date.now()-s,F=Date.now();this.context.stepTracking.stateTransitions.length===0&&this.context.stepTracking.stateTransitions.push({type:"state",url:c,domSnapshot:l||void 0,variables:f,screenshotPath:b,timestamp:s}),this.context.stepTracking.stateTransitions.push({type:"action",stepId:r,description:u,action:{playwrightCode:[t.toString()]},consoleLogs:this.getConsoleLogsForStep(r),durationMs:P,status:"failure",errorMessage:w.message}),this.context.stepTracking.stateTransitions.push({type:"state",url:y,domSnapshot:k||void 0,variables:L,timestamp:F})}throw this.context.stepTracking&&(this.context.stepTracking.currentStepId=void 0),w}}}async extract(e,t,u,r){r&&this.context.stepTracking&&await this.createStepResult(e,r,`Extract ${t} into ${u}`);try{let i=`Extract ${t} and save to ${u}`,a=await this.execute(e,i,r);if(!a.success)throw new Error(`AI extraction failed: ${a.details}`);r&&this.context.stepTracking&&await this.updateStepResult(r,"success",`Extracted ${t} to ${u}`)}catch(i){throw r&&this.context.stepTracking&&await this.updateStepResult(r,"failure",i.message),i}}async getDOMText(e){let t=new Re(this.agentServices.getDomServiceOptions()),u=this.agentServices.getInteractiveClassNames(),r=this.agentServices.getIframeFallbackDomains();return(await t.getClickableElements(e,{interactiveClassNames:u,playwrightFrameFallbackDomains:r})).elementTree.clickableElementsToString()}async captureDOMSnapshot(e){if(!this.context.stepTracking?.captureStateTransitions||!this.context.stepTracking?.captureDom)return null;try{let t=new Re(this.agentServices.getDomServiceOptions()),u=this.agentServices.getInteractiveClassNames(),r=this.agentServices.getIframeFallbackDomains(),i=await t.getClickableElements(e,{interactiveClassNames:u,playwrightFrameFallbackDomains:r,highlightElements:!1,viewportExpansion:0});return{elementTreeText:i.elementTree.clickableElementsToString(),elementCount:i.selectorMap.size,timestamp:Date.now()}}catch(t){return o.warn("Failed to capture DOM snapshot:",t),null}}getConsoleLogsForStep(e){return this.context.stepTracking?.consoleLogs?this.context.stepTracking.consoleLogs.filter(t=>t.stepId===e).map(t=>({type:t.type,message:t.message,timestamp:t.timestamp})):[]}async waitUntilStable(e,t=3e3,u=1e3){return ga(e,t,u)}async waitUntilCondition(e,t,u=60,r){return xa(e,t,(i,a,n)=>this.evaluate(i,a,n),u,r)}async uploadFile(e,t,u={},r){return ir(e,t,u,this.context,(i,a,n)=>this.execute(i,a,n),r)}async loginPage(e,t,u){let{LoginType:r}=await import("./agentLogin-J2342DF2.js");if(o.info("Start login"),S.section("Login Flow"),S.log(`Site URL: ${t.site_url}`),S.log(`Account type: ${t.account.type}`),S.log(`Has cached actions: ${!!u?.cached_actions?.length}`),S.log(`Has validation exprs: ${!!u?.validation_exprs?.length}`),t.skip_verification)return o.info("Skipping login verification (skip_verification=true)"),{success:!0,page:e};if((t.account.type===r.PASSWORD||t.account.type===r.OAUTH2)&&(this.context.variableStore.set("username",t.account.username,!0),this.context.variableStore.set("password",t.account.password,!0)),t.account.two_factor_auth_config?.type==="totp"&&this.context.variableStore.set("otp_secret_key",t.account.two_factor_auth_config.data,!0),o.info(`Navigating to: ${t.site_url}`),await e.goto(t.site_url),await this.waitUntilStable(e,1e4,3e3),u?.validation_exprs&&u.validation_exprs.length>0){if(S.log("Level 1: Checking if already logged in via storage state..."),S.log(`Validation expressions: ${JSON.stringify(u.validation_exprs)}`),await Xt(e,u.validation_exprs))return S.log("Level 1 SUCCESS: Already logged in via storage state"),o.info("Login: Already logged in via storage state"),{success:!0,page:e,storage_state:null,cached_actions:u.cached_actions,validation_exprs:u.validation_exprs,alreadyLoggedIn:!0};S.log("Level 1 FAILED: Storage state validation failed, trying Level 2")}if(u?.cached_actions&&u.cached_actions.length>0&&u?.validation_exprs&&u.validation_exprs.length>0){S.log(`Level 2: Attempting cached login with ${u.cached_actions.length} actions`);try{if((await this.executeCachedLogin(e,u.cached_actions,u.validation_exprs)).success){S.log("Level 2 SUCCESS: Cached login succeeded"),o.info("Login: Cached login succeeded");let a=await e.context().storageState();return{success:!0,page:e,storage_state:a,cached_actions:u.cached_actions,validation_exprs:u.validation_exprs}}S.log("Level 2 FAILED: Cached login failed, trying Level 3")}catch(a){S.log(`Level 2 ERROR: ${a.message}, trying Level 3`)}}else u?.cached_actions&&u.cached_actions.length>0&&S.log("Level 2 SKIPPED: Cached actions exist but no validation expressions, going to Level 3");let i=`First check if the page is already signed in. If it is, do nothing.
124
+ If NO intrusive popup is present, do nothing and report that no intrusive popup was found.`,void 0,!1,I0),r=!!(u.actions&&u.actions.length>0);return{success:u.success,modalDismissed:r,details:u.details||(r?"Modal dismissed":"No modal found")}}catch(u){return{success:!1,modalDismissed:!1,details:u.message||"Modal dismissal failed"}}}_getContext(){return this.context}setupDownloadTracking(e){if(o.info(`[Download Tracking] Setting up download tracking for page: ${e.url()}`),tn(e)){o.info(`[Download Tracking] Skipping download tracking for blank tab: ${e.url()}`),e.close();return}e.on("download",async t=>{let u=t.suggestedFilename();o.info(`[Download Tracking] Download event detected! File: ${u}`),this.context.downloadStatus={filename:u,status:"inProgress",startTime:Date.now()},o.info(`[Download Tracking] Download status set to inProgress: ${JSON.stringify(this.context.downloadStatus)}`);try{let r=this.context.downloadDir||C.join(process.cwd(),"downloads");N.existsSync(r)||N.mkdirSync(r,{recursive:!0});let i=C.join(r,u);o.info(`[Download Tracking] Downloading file to: ${i}`),await t.saveAs(i),this.context.downloadStatus={filename:u,status:"completed",startTime:this.context.downloadStatus.startTime,filePath:i,timestamp:Date.now()},o.info(`[Download Tracking] Download completed: ${i}`),o.info(`[Download Tracking] Download status set to completed: ${JSON.stringify(this.context.downloadStatus)}`)}catch(r){this.context.downloadStatus={filename:u,status:"failed",startTime:this.context.downloadStatus.startTime,error:r.message,timestamp:Date.now()},o.error(`[Download Tracking] Download failed for ${u}: ${r.message}`)}})}setupDialogHandling(e){if(o.debug(`[Dialog Handling] setupDialogHandling called, isClosed=${e.isClosed()}, url=${e.url()}`),e.isClosed()){o.debug("[Dialog Handling] Skipping - page is closed");return}o.info(`[Dialog Handling] Setting up dialog handling for page: ${e.url()}`),e.on("dialog",async t=>{let u=t.type(),r=t.message();o.info(`[Dialog Handling] Dialog detected - type: ${u}, message: "${r}"`);let i=u==="beforeunload";try{i?await t.dismiss():await t.accept(),this.context.dialogStatus={type:u,message:r,response:i?"dismiss":"accept",timestamp:Date.now()},o.info(`[Dialog Handling] Dialog ${i?"dismissed":"accepted"} - type: ${u}, message: "${r}"`)}catch(a){o.warn(`[Dialog Handling] Failed to handle dialog (already dismissed?): ${a}`)}})}getRecentDownloadedFilePath(){return this.agentServices.getRecentDownloadedFilePath()}addNote(e){this.agentServices.addNote(e)}collectTokenUsages(e){let t;Array.isArray(e)?t=e:e?.tokenUsages&&(t=e.tokenUsages),t&&t.length>0?(this.context.tokenUsages||(this.context.tokenUsages=[]),this.context.tokenUsages.push(...t),o.debug(`[collectTokenUsages] Added ${t.length} token usage(s), total: ${this.context.tokenUsages.length}`)):o.debug("[collectTokenUsages] No token usages to collect (undefined or empty)")}trackAIAction(e,t,u,r=1,i,a){if(!e)return;let n=u?.tokenUsages||[];this.context.aiActionDetails||(this.context.aiActionDetails=[]);let s=this.context.aiActionDetails.find(c=>c.stepId===e&&c.actionType===t);s?(s.count+=r,n.length>0&&s.tokenUsages.push(...n),u?.userPrompt&&(s.userPrompt=u.userPrompt),u?.rawLlmResponse&&(s.rawLlmResponse=u.rawLlmResponse),u?.reasoningContent&&(s.reasoningContent=u.reasoningContent),u?.elementTree&&(s.elementTree=u.elementTree),u?.screenshotWithSom&&(s.screenshotWithSom=u.screenshotWithSom),a&&(s.explanation=a)):this.context.aiActionDetails.push({stepId:e,actionType:t,count:r,tokenUsages:[...n],statement:i,userPrompt:u?.userPrompt,rawLlmResponse:u?.rawLlmResponse,reasoningContent:u?.reasoningContent,explanation:a,elementTree:u?.elementTree,screenshotWithSom:u?.screenshotWithSom}),o.debug(`[trackAIAction] Tracked ${t} for step ${e}, count: ${r}`)}async assert(e,t,u){o.info(`Asserting statement: ${t}`),u&&this.context.stepTracking&&await this.createStepResult(e,u,t),await this.agentServices.waitUntilStable(e);try{let r=this.getCompletedExecutionHistory(),i=await He(t,e,this.agentServices,{executionHistory:r,useCleanScreenshotForAssertion:!0,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys()});this.collectTokenUsages(i.debugInfo),this.context.lastActionDebugInfo=i.debugInfo;let a=i.explanation||i.error||"No explanation";if(u&&this.trackAIAction(u,"assert",i.debugInfo,1,t,a),this.context.agentNote=a,u&&this.context.stepTracking&&await this.updateStepResult(u,i.success?"success":"failure",a,void 0,i.debugInfo),!i.success)throw this.addToExecutionHistory(`Assert: "${t}"`,`Failed: ${a}`),new Error(`Assertion failed: ${a}`);return this.addToExecutionHistory(`Assert: "${t}"`,`Passed: ${a}`),!0}catch(r){throw u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",r.message),r}}async evaluate(e,t,u){o.info(`Evaluating condition: ${t}`),u&&this.context.stepTracking&&await this.createStepResult(e,u,t),await this.agentServices.waitUntilStable(e);try{let r=this.getCompletedExecutionHistory(),i=await He(t,e,this.agentServices,{executionHistory:r,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys()});this.collectTokenUsages(i.debugInfo),this.context.lastActionDebugInfo=i.debugInfo;let a=i.explanation||i.error||"No explanation";return u&&this.trackAIAction(u,"evaluate",i.debugInfo,1,t,a),this.context.agentNote=a,u&&this.context.stepTracking&&await this.updateStepResult(u,"success",a,void 0,i.debugInfo),i.success?(this.addToExecutionHistory(`Evaluate: "${t}"`,`Result: true - ${a}`),!0):(o.warn(`AI evaluation returned false/unknown: ${a}`),this.addToExecutionHistory(`Evaluate: "${t}"`,`Unknown/False: ${a}`),!1)}catch(r){throw u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",r.message),r}}async performAction(e,t){o.info(`Act: ${t}`);let u=this.getCompletedExecutionHistory(),r=await Me(t,e,this.agentServices,{executionHistory:u,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys()});if(this.collectTokenUsages(r.debugInfo),r.status!=="success"||r.actionEntities.length===0)return{success:!1,details:r.explanation||r.error||"Action failed"};let i=r.actionEntities[0]?.action_description||t;return this.addToExecutionHistory(t,i),{success:!0,details:r.explanation}}async execute(e,t,u,r,i){if(i!==void 0&&i<=0)throw new Error(`maxSteps must be >= 1, got ${i}`);let a=i!==void 0&&i>1;o.info(`Executing statement: ${t} (${a?`multi, maxSteps: ${i}`:"single"})`),u&&this.context.stepTracking&&await this.createStepResult(e,u,t),e=this.agentServices.validatePage(e),await this.agentServices.waitUntilStable(e);try{let n=this.getCompletedExecutionHistory();this.context.agentNote="";let s,c;if(a){let f=u&&this.context.stepTracking?.artifactsDir?b=>{if(b.type==="action"&&b.debugInfo){let x=`${u}-step${b.step}`;this.saveDebugInfoToFiles(x,b.debugInfo,this.context.model)}}:void 0;if(s=await Ue(t,e,this.agentServices,f,{executionHistory:n,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys(),maxSteps:i??N0}),c=s.completed,this.collectTokenUsages(s.tokenUsages),u&&s.tokenUsages){let b={tokenUsages:s.tokenUsages};this.trackAIAction(u,"execute",b,s.actionEntities?.length||1,t,s.explanation||"Multi-step execution completed")}}else if(e=this.agentServices.validatePage(e),s=await Me(t,e,this.agentServices,{executionHistory:n,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys(),usePureVision:r}),c=s.completed,this.collectTokenUsages(s.debugInfo),this.context.lastActionDebugInfo=s.debugInfo,u){let f=s.explanation||s.error||"No explanation";this.trackAIAction(u,"execute",s.debugInfo,1,t,f)}if(s.status!=="success"||s.actionEntities.length===0||!c){let f=s.explanation||s.error||"Goal not completed";throw u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",f,void 0,s.debugInfo),new Error(`Action failed: ${f}`)}let l=this.context.agentNote||s.explanation||"Action executed successfully";return u&&this.context.stepTracking&&await this.updateStepResult(u,"success",l,void 0,s.debugInfo),this.addToExecutionHistory(`Execute: "${t}"`,l),{success:!0,details:l,actions:s.actionEntities,debugInfo:s.debugInfo}}catch(n){throw u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",n.message),this.addToExecutionHistory(`Execute: "${t}"`,`Failed: ${n.message}`),n}}async generate(e,t,u,r){u&&this.context.stepTracking&&await this.createStepResult(e,u,t);try{let i=this.getCompletedExecutionHistory(),a=await Jt(t,e,this.agentServices,{executionHistory:i,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys(),usePureVision:r});if(this.collectTokenUsages(a.debugInfo),a.status!=="success"||a.actionEntities.length===0){let c=a.explanation||a.error||"No explanation";throw u&&this.trackAIAction(u,"generate",a.debugInfo,1,t,c),u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",c,void 0,a.debugInfo),new Error(c)}let n=a.completed,s=a.explanation||"Action generated successfully";return u&&this.trackAIAction(u,"generate",a.debugInfo,1,t,s),u&&this.context.stepTracking&&await this.updateStepResult(u,"success",s,void 0,a.debugInfo),o.info(`[generate] Generated action for "${t}": ${s}, goalAccomplished: ${a.completed}`),{success:n,details:s,actions:a.actionEntities,debugInfo:a.debugInfo}}catch(i){throw u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",i.message),i}}async run(e,t,u,r){u&&this.context.stepTracking&&await this.createStepResult(e,u,t);try{let i=this.getCompletedExecutionHistory();this.context.agentNote="";let a=u&&this.context.stepTracking?.artifactsDir,n=r?.onAction||a?f=>{if(f.type==="action"&&f.action_entity&&(r?.onAction?.(f.action_entity),a&&f.debugInfo)){let b=`${u}-step${f.step}`;this.saveDebugInfoToFiles(b,f.debugInfo,this.context.model)}}:void 0,s=await Ue(t,e,this.agentServices,n,{executionHistory:i,variables:this.context.variableStore.getAll(),sensitiveKeys:this.context.variableStore.getAllSensitiveKeys(),abortSignal:r?.abortSignal,maxSteps:r?.maxSteps});S.log(`Run task result: status=${s.status}, completed=${s.completed}, actions=${s.actionEntities?.length||0}`),this.collectTokenUsages(s.tokenUsages);let c=s.status==="success"&&s.completed,l=this.context.agentNote?.trim()||s.explanation||s.error||(c?"Step completed":"Step failed");if(u&&s.tokenUsages){let f={tokenUsages:s.tokenUsages};this.trackAIAction(u,"run",f,s.actionEntities?.length||1,t,l)}if(!c)throw new Yu(l);return u&&this.context.stepTracking&&await this.updateStepResult(u,"success",l,void 0,void 0),this.addToExecutionHistory(`Run: "${t}"`,l),S.log(`Run result: success=${c}, details=${l}`),{success:c,details:l,actions:s.actionEntities}}catch(i){throw u&&this.context.stepTracking&&await this.updateStepResult(u,"failure",i.message),this.addToExecutionHistory(`Run: "${t}"`,`Failed: ${i.message}`),i}}async step(e,t,u,r,i,a=!0,n){let s=Date.now();this.context.stepTracking&&await this.createStepResult(e,r,u),e=this.agentServices.validatePage(e),await this.agentServices.waitUntilStable(e),this.context.stepTracking&&(this.context.stepTracking.currentStepId=r),e=this.agentServices.validatePage(e);let c=e.url(),l=await this.captureDOMSnapshot(e),f=this.context.stepTracking?.captureVariables?Be(this.context.variableStore.getAll(),this.context.variableStore.getAllSensitiveKeys()):{},b=this.context.stepTracking?.results[r]?.screenshot;try{o.info(`Executing step ${r}: ${u}`),this.addToExecutionHistory(u,""),this.context.agentNote="",e=this.agentServices.validatePage(e);let x=await t();e=this.agentServices.validatePage(e);let h=e.url(),g=await this.captureDOMSnapshot(e),v=this.context.stepTracking?.captureVariables?Be(this.context.variableStore.getAll(),this.context.variableStore.getAllSensitiveKeys()):{};if(this.context.stepTracking&&await this.updateStepResult(r,"success",""),this.context.stepTracking?.captureStateTransitions&&this.context.stepTracking.stateTransitions){let y=Date.now()-s,k=this.context.stepTracking.results[r]?.screenshot,L=Date.now();this.context.stepTracking.stateTransitions.length===0&&this.context.stepTracking.stateTransitions.push({type:"state",url:c,domSnapshot:l||void 0,variables:f,screenshotPath:b,timestamp:s}),this.context.stepTracking.stateTransitions.push({type:"action",stepId:r,description:u,action:{playwrightCode:[t.toString()]},consoleLogs:this.getConsoleLogsForStep(r),durationMs:y,status:"success"}),this.context.stepTracking.stateTransitions.push({type:"state",url:h,domSnapshot:g||void 0,variables:v,screenshotPath:k,timestamp:L})}let w=this.context.agentNote;return(!w||w.trim()==="")&&(w="Execution successful"),this.context.executionHistory&&this.context.executionHistory.length>0&&(this.context.executionHistory[this.context.executionHistory.length-1][1]=w),this.context.stepTracking&&(this.context.stepTracking.currentStepId=void 0),x}catch(x){e=this.agentServices.validatePage(e);let h=a&&!this.context.isSelfHealing;if(h&&(this.context.stepTracking&&await this.updateStepResult(r,"failure",x.message),this.context.executionHistory&&this.context.executionHistory.length>0&&(this.context.executionHistory[this.context.executionHistory.length-1][1]=x.message)),!u||u.trim()==="")throw o.error("No description provided for self-healing"),this.context.stepTracking&&(this.context.stepTracking.currentStepId=void 0),x;if(!h){if(o.info(`Failed to heal at step ${r}. ${u}`),this.context.isSelfHealing=!1,this.context.stepTracking?.captureStateTransitions&&this.context.stepTracking.stateTransitions){let w=e.url(),y=await this.captureDOMSnapshot(e),k=this.context.stepTracking.captureVariables?Be(this.context.variableStore.getAll(),this.context.variableStore.getAllSensitiveKeys()):{},L=Date.now()-s,P=Date.now();this.context.stepTracking.stateTransitions.length===0&&this.context.stepTracking.stateTransitions.push({type:"state",url:c,domSnapshot:l||void 0,variables:f,screenshotPath:b,timestamp:s}),this.context.stepTracking.stateTransitions.push({type:"action",stepId:r,description:u,action:{playwrightCode:[t.toString()]},consoleLogs:this.getConsoleLogsForStep(r),durationMs:L,status:"failure",errorMessage:x.message}),this.context.stepTracking.stateTransitions.push({type:"state",url:w,domSnapshot:y||void 0,variables:k,timestamp:P})}throw this.context.stepTracking&&(await this.updateStepResult(r,void 0,void 0),this.context.stepTracking.currentStepId=void 0),x}this.context.isSelfHealing=!0,o.info(`Action failed at step ${r}. ${u}`),o.info(`with error: ${x.message}`);let g;if(this.context.autoDisableModal){o.info("Attempting modal dismissal before self-healing...");let w=await this.dismissModalIfPresent(e,u);if(o.info(`Modal dismissal result: ${w.details}`),w.modalDismissed){g=`[Auto-dismissed modal: ${w.details}]`,o.info(`Modal dismissed, retrying original action for step ${r}`);try{let y=await t();return this.context.isSelfHealing=!1,this.context.executionHistory&&this.context.executionHistory.length>0&&(this.context.executionHistory[this.context.executionHistory.length-1][1]=g+" Retry successful"),this.context.stepTracking&&(await this.updateStepResult(r,"success",g),this.context.stepTracking.currentStepId=void 0),y}catch(y){o.info(`Retry after modal dismissal failed: ${y.message}, falling back to self-healing`)}}}let v=n??_0;o.info(`Calling execute() to self-heal (maxSteps: ${v})`);try{let w=await this.execute(e,u,r,!1,v);if(this.context.isSelfHealing=!1,!w.success)throw new Error(`Self-healing failed: ${w.details}`);let y=w.actions?.at(-1);i&&y&&(this._newActionEntities.set(i,y),o.info(`Stored new action entity for stmtUid: ${i} (last of ${w.actions?.length} actions)`));let k=e.url(),L=await this.captureDOMSnapshot(e),P=this.context.stepTracking?.captureVariables?Be(this.context.variableStore.getAll(),this.context.variableStore.getAllSensitiveKeys()):{};if(this.context.stepTracking){let F=g||"";await this.updateStepResult(r,"success",F)}if(this.context.stepTracking?.captureStateTransitions&&this.context.stepTracking.stateTransitions){let F=Date.now()-s,M=this.context.stepTracking.results[r]?.screenshot,qt=Date.now();this.context.stepTracking.stateTransitions.length===0&&this.context.stepTracking.stateTransitions.push({type:"state",url:c,domSnapshot:l||void 0,variables:f,screenshotPath:b,timestamp:s}),this.context.stepTracking.stateTransitions.push({type:"action",stepId:r,description:u,action:{actionEntity:y,playwrightCode:w.actions?.map(Mt=>Mt.locator||""),llmPrompt:w.debugInfo?.userPrompt,llmResponse:w.debugInfo?.rawLlmResponse,llmReasoning:w.debugInfo?.reasoningContent},consoleLogs:this.getConsoleLogsForStep(r),durationMs:F,status:"success"}),this.context.stepTracking.stateTransitions.push({type:"state",url:k,domSnapshot:L||void 0,variables:P,screenshotPath:M,timestamp:qt})}return this.context.stepTracking&&(this.context.stepTracking.currentStepId=void 0),w}catch(w){if(this.context.isSelfHealing=!1,this.context.stepTracking?.captureStateTransitions&&this.context.stepTracking.stateTransitions){let y=e.url(),k=await this.captureDOMSnapshot(e),L=this.context.stepTracking.captureVariables?Be(this.context.variableStore.getAll(),this.context.variableStore.getAllSensitiveKeys()):{},P=Date.now()-s,F=Date.now();this.context.stepTracking.stateTransitions.length===0&&this.context.stepTracking.stateTransitions.push({type:"state",url:c,domSnapshot:l||void 0,variables:f,screenshotPath:b,timestamp:s}),this.context.stepTracking.stateTransitions.push({type:"action",stepId:r,description:u,action:{playwrightCode:[t.toString()]},consoleLogs:this.getConsoleLogsForStep(r),durationMs:P,status:"failure",errorMessage:w.message}),this.context.stepTracking.stateTransitions.push({type:"state",url:y,domSnapshot:k||void 0,variables:L,timestamp:F})}throw this.context.stepTracking&&(this.context.stepTracking.currentStepId=void 0),w}}}async extract(e,t,u,r){r&&this.context.stepTracking&&await this.createStepResult(e,r,`Extract ${t} into ${u}`);try{let i=`Extract ${t} and save to ${u}`,a=await this.execute(e,i,r);if(!a.success)throw new Error(`AI extraction failed: ${a.details}`);r&&this.context.stepTracking&&await this.updateStepResult(r,"success",`Extracted ${t} to ${u}`)}catch(i){throw r&&this.context.stepTracking&&await this.updateStepResult(r,"failure",i.message),i}}async getDOMText(e){let t=new Re(this.agentServices.getDomServiceOptions()),u=this.agentServices.getInteractiveClassNames(),r=this.agentServices.getIframeFallbackDomains();return(await t.getClickableElements(e,{interactiveClassNames:u,playwrightFrameFallbackDomains:r})).elementTree.clickableElementsToString()}async captureDOMSnapshot(e){if(!this.context.stepTracking?.captureStateTransitions||!this.context.stepTracking?.captureDom)return null;try{let t=new Re(this.agentServices.getDomServiceOptions()),u=this.agentServices.getInteractiveClassNames(),r=this.agentServices.getIframeFallbackDomains(),i=await t.getClickableElements(e,{interactiveClassNames:u,playwrightFrameFallbackDomains:r,highlightElements:!1,viewportExpansion:0});return{elementTreeText:i.elementTree.clickableElementsToString(),elementCount:i.selectorMap.size,timestamp:Date.now()}}catch(t){return o.warn("Failed to capture DOM snapshot:",t),null}}getConsoleLogsForStep(e){return this.context.stepTracking?.consoleLogs?this.context.stepTracking.consoleLogs.filter(t=>t.stepId===e).map(t=>({type:t.type,message:t.message,timestamp:t.timestamp})):[]}async waitUntilStable(e,t=3e3,u=1e3){return ga(e,t,u)}async waitUntilCondition(e,t,u=60,r){return xa(e,t,(i,a,n)=>this.evaluate(i,a,n),u,r)}async uploadFile(e,t,u={},r){return ir(e,t,u,this.context,(i,a,n)=>this.execute(i,a,n),r)}async loginPage(e,t,u){let{LoginType:r}=await import("./agentLogin-IIER6KDC.js");if(o.info("Start login"),S.section("Login Flow"),S.log(`Site URL: ${t.site_url}`),S.log(`Account type: ${t.account.type}`),S.log(`Has cached actions: ${!!u?.cached_actions?.length}`),S.log(`Has validation exprs: ${!!u?.validation_exprs?.length}`),t.skip_verification)return o.info("Skipping login verification (skip_verification=true)"),{success:!0,page:e};if((t.account.type===r.PASSWORD||t.account.type===r.OAUTH2)&&(this.context.variableStore.set("username",t.account.username,!0),this.context.variableStore.set("password",t.account.password,!0)),t.account.two_factor_auth_config?.type==="totp"&&this.context.variableStore.set("otp_secret_key",t.account.two_factor_auth_config.data,!0),o.info(`Navigating to: ${t.site_url}`),await e.goto(t.site_url),await this.waitUntilStable(e,1e4,3e3),u?.validation_exprs&&u.validation_exprs.length>0){if(S.log("Level 1: Checking if already logged in via storage state..."),S.log(`Validation expressions: ${JSON.stringify(u.validation_exprs)}`),await Xt(e,u.validation_exprs))return S.log("Level 1 SUCCESS: Already logged in via storage state"),o.info("Login: Already logged in via storage state"),{success:!0,page:e,storage_state:null,cached_actions:u.cached_actions,validation_exprs:u.validation_exprs,alreadyLoggedIn:!0};S.log("Level 1 FAILED: Storage state validation failed, trying Level 2")}if(u?.cached_actions&&u.cached_actions.length>0&&u?.validation_exprs&&u.validation_exprs.length>0){S.log(`Level 2: Attempting cached login with ${u.cached_actions.length} actions`);try{if((await this.executeCachedLogin(e,u.cached_actions,u.validation_exprs)).success){S.log("Level 2 SUCCESS: Cached login succeeded"),o.info("Login: Cached login succeeded");let a=await e.context().storageState();return{success:!0,page:e,storage_state:a,cached_actions:u.cached_actions,validation_exprs:u.validation_exprs}}S.log("Level 2 FAILED: Cached login failed, trying Level 3")}catch(a){S.log(`Level 2 ERROR: ${a.message}, trying Level 3`)}}else u?.cached_actions&&u.cached_actions.length>0&&S.log("Level 2 SKIPPED: Cached actions exist but no validation expressions, going to Level 3");let i=`First check if the page is already signed in. If it is, do nothing.
125
125
  Use your best judgement to determine if the page is signed in.
126
126
  `;if(t.verification_hint&&(i+=`
127
127
  Signed in verification hint: ${t.verification_hint}
@@ -133,7 +133,7 @@ If the page is not signed in, sign in with the OAuth provider "${a.provider_name
133
133
  `}t.additional_prompt&&(i+=`
134
134
  Additional instructions: ${t.additional_prompt}
135
135
  `);try{S.log("Level 3: Attempting agent-based login"),S.log(`Login prompt:
136
- ${i}`);let a=this.agentServices.knowledgeRetriever,n=!1;this.agentServices.hasKnowledgeRetriever()&&a&&(S.log("Setting up login knowledge retriever..."),this.agentServices.setKnowledgeRetriever(async(x,h,g,v)=>await a(x,h,g,"login")),n=!0,S.log("Login knowledge retriever configured"));let s;try{if(s=await this.run(e,i,"login"),!s.success)return S.log("Level 3 FAILED: Agent login failed"),o.info("Login: Failed"),{success:!1,page:e}}finally{n&&a&&(this.agentServices.setKnowledgeRetriever(a),S.log("Restored original knowledge retriever"))}let c=await e.context().storageState(),l;if(t.num_verification_exprs!==0)try{S.log("Generating validation locators for future login verification...");let x=await qr(e,t.site_url,{verification_hint:t.verification_hint,num_verification_exprs:t.num_verification_exprs},async(h,g)=>this.run(h,g),async h=>this.getDOMText(h));x?(l=x,S.log(`Generated ${l.length} validation locator(s): ${JSON.stringify(l)}`)):S.log("Failed to generate validation locators, login will still succeed")}catch(x){S.log(`Error generating validation locators: ${x.message}`)}else S.log("Skipping validation locator generation (num_verification_exprs=0)");S.log("Level 3 SUCCESS: Agent login succeeded"),o.info("Login: Agent login succeeded");let f=s.actions||[],b=f.length>0?f:u?.cached_actions;return{success:!0,page:e,storage_state:c,cached_actions:b,validation_exprs:l}}catch(a){return S.error(`Agent login failed: ${a.message}`),o.info("Login: Failed"),{success:!1,page:e}}}async executeCachedLogin(e,t,u){let r=(await import("./handler-ESLITK6N.js")).default,i=new r;for(let a=0;a<t.length;a++){let n=t[a];S.log(`Executing cached action ${a+1}/${t.length}: ${n.action_description||n.action_data?.action_name}`);try{if(!n.action_data){S.log(`Action ${a+1} missing action_data, skipping`);continue}await i.execute(e,n,this.agentServices),await this.waitUntilStable(e,5e3)}catch(s){return S.error(`Cached action ${a+1} failed: ${s.message}`),{success:!1}}}return u&&u.length>0&&!await Xt(e,u)?{success:!1}:{success:!0}}getCompletedExecutionHistory(){if(!this.context.executionHistory||this.context.executionHistory.length===0)return[];let e=this.context.executionHistory[this.context.executionHistory.length-1];return!e[1]||e[1].trim()===""?this.context.executionHistory.slice(0,-1):this.context.executionHistory}addToExecutionHistory(e,t){this.context.executionHistory||(this.context.executionHistory=[]),this.context.executionHistory.push([e,t])}async createStepResult(e,t,u){if(!this.context.stepTracking||this.context.stepTracking.results[t])return;this.context.stepTracking.currentStepId=t,this.context.stepTracking.onStepChange&&this.context.stepTracking.onStepChange(t),e=this.agentServices.validatePage(e),await this.waitUntilStable(e);let r={description:u,startTime:Date.now(),artifacts:[]};if(this.context.stepTracking.artifactsDir){let i=C.join(this.context.stepTracking.artifactsDir,t.replace(/\./g,"-"));N.mkdirSync(i,{recursive:!0});let a=C.join(i,"screenshot.png");e=this.agentServices.validatePage(e),await e.screenshot({type:"png",path:a}),r.screenshot=a}this.context.stepTracking.results[t]=r}saveDebugInfoToFiles(e,t,u){let r={};if(!this.context.stepTracking?.artifactsDir)return o.debug("[saveDebugInfoToFiles] No artifacts directory configured, skipping debug info save"),r;let i=C.join(this.context.stepTracking.artifactsDir,e.replace(/\./g,"-"));try{if(N.mkdirSync(i,{recursive:!0}),t.systemPrompt){let a=C.join(i,"system_prompt.txt");N.writeFileSync(a,t.systemPrompt),r.system_prompt_path=a,o.debug(`[saveDebugInfoToFiles] Saved system prompt to: ${a}`)}if(t.userPrompt)if(typeof t.userPrompt=="string"){let a=C.join(i,"user_prompt.txt");N.writeFileSync(a,t.userPrompt),r.user_prompt_path=a,o.debug(`[saveDebugInfoToFiles] Saved user prompt to: ${a}`)}else{let a=t.userPrompt.map(c=>Array.isArray(c.content)?{...c,content:c.content.map(l=>l.type==="image"&&l.file?.startsWith("data:")?{...l,file:"[base64 image data stripped]"}:l)}:c),n=C.join(i,"messages.json"),s={system:t.systemPrompt,messages:a};N.writeFileSync(n,JSON.stringify(s,null,2)),r.messages_path=n,o.debug(`[saveDebugInfoToFiles] Saved messages to: ${n}`)}if(t.rawLlmResponse){let a=u?u.replace(/[\/\\:]/g,"-"):"llm",n=C.join(i,`${a}_response.txt`);N.writeFileSync(n,t.rawLlmResponse),r.response_path=n,o.debug(`[saveDebugInfoToFiles] Saved LLM response to: ${n}`)}if(t.screenshotWithSom){let a=C.join(i,"screenshot.png");N.writeFileSync(a,Buffer.from(t.screenshotWithSom,"base64")),r.screenshot_path=a,o.debug(`[saveDebugInfoToFiles] Saved SOM screenshot to: ${a}`)}if(t.reasoningContent){let a=C.join(i,"reasoning.txt");N.writeFileSync(a,t.reasoningContent),r.reasoning_path=a,o.debug(`[saveDebugInfoToFiles] Saved reasoning to: ${a}`)}o.debug(`[saveDebugInfoToFiles] Saved ${Object.keys(r).length} artifacts for step ${e}`)}catch(a){o.error(`[saveDebugInfoToFiles] Failed to save debug info for step ${e}:`,a)}return r}async updateStepResult(e,t,u,r,i){if(!this.context.stepTracking)return;let a=this.context.stepTracking.results[e];if(a){if(t&&(a.status=t,this.context.stepTracking.currentStepId=void 0,this.context.stepTracking.onStepChange&&this.context.stepTracking.onStepChange(void 0)),u!==void 0&&(a.message=u),r&&a.artifacts.push(r),i){let n=i.tokenUsages?.[0]?.model,s=this.saveDebugInfoToFiles(e,i,n);Object.keys(s).length>0&&a.artifacts.push(s)}a.duration=Date.now()-a.startTime,this.context.stepTracking.onStepComplete&&this.context.stepTracking.onStepComplete(e,a)}}async writeExecutionResults(e,t){try{if(await N.promises.mkdir(e,{recursive:!0}),this.context.stepTracking?.results&&Object.keys(this.context.stepTracking.results).length>0){let u=C.join(e,"test-results.json");await N.promises.writeFile(u,JSON.stringify(this.context.stepTracking.results,null,2)),o.debug(`Test results written to: ${u}`)}if(t?.tokenUsages&&this.context.tokenUsages&&this.context.tokenUsages.length>0){let u=C.join(e,"token-usages.json");await N.promises.writeFile(u,JSON.stringify(this.context.tokenUsages,null,2)),o.debug(`Token usages written to: ${u}`)}if(this.context.aiActionDetails&&this.context.aiActionDetails.length>0){let u=C.join(e,"ai-actions.json");await N.promises.writeFile(u,JSON.stringify(this.context.aiActionDetails,null,2)),o.debug(`AI action details written to: ${u}`)}}catch(u){throw o.error("Failed to write execution results:",u),u}}};function D0(){let e=new Date,t=new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(e),u=t.find(y=>y.type==="year").value,r=t.find(y=>y.type==="month").value,i=t.find(y=>y.type==="day").value,a=t.find(y=>y.type==="hour").value,n=t.find(y=>y.type==="minute").value,s=t.find(y=>y.type==="second").value,c=String(e.getMilliseconds()).padStart(3,"0"),l=`${u}-${r}-${i}T${a}:${n}:${s}.${c}`,f=e.toISOString().slice(0,-1),b=Date.parse(l+"Z"),x=Date.parse(f+"Z"),h=Math.round((x-b)/(1e3*60)),g=String(Math.floor(Math.abs(h)/60)).padStart(2,"0"),v=String(Math.abs(h)%60).padStart(2,"0"),w=h<=0?"+":"-";return`${u}-${r}-${i}T${a}:${n}:${s}.${c}${w}${g}:${v}`}function an(e){let t=e.variableStore;return t.has("currentTime")||t.set("currentTime",D0()),{model:e.model,variableStore:t,organizationId:e.organizationId,organizationSettings:e.organizationSettings,executionHistory:e.executionHistory||[],testDataDir:e.testDataDir,downloadDir:e.downloadDir,useNativeGenerator:e.useNativeGenerator,autoDisableModal:e.autoDisableModal,tokenUsages:[],aiActionDetails:[]}}function y1(e){let t=new Rr,u=new Set(e.sensitiveKeys||[]);if(e.variables)for(let[i,a]of Object.entries(e.variables))t.set(i,a,u.has(i));let r=an({model:e.model,variableStore:t,testDataDir:e.testDataDir,downloadDir:e.downloadDir});return new rn(r)}var v1="1.0.0";export{Hr as a,sn as b,on as c,cn as d,ln as e,r0 as f,i0 as g,a0 as h,n0 as i,s0 as j,o0 as k,c0 as l,h0 as m,p0 as n,Ju as o,un as p,Yu as q,rn as r,an as s,y1 as t,v1 as u};
136
+ ${i}`);let a=this.agentServices.knowledgeRetriever,n=!1;this.agentServices.hasKnowledgeRetriever()&&a&&(S.log("Setting up login knowledge retriever..."),this.agentServices.setKnowledgeRetriever(async(x,h,g,v)=>await a(x,h,g,"login")),n=!0,S.log("Login knowledge retriever configured"));let s;try{if(s=await this.run(e,i,"login"),!s.success)return S.log("Level 3 FAILED: Agent login failed"),o.info("Login: Failed"),{success:!1,page:e}}finally{n&&a&&(this.agentServices.setKnowledgeRetriever(a),S.log("Restored original knowledge retriever"))}let c=await e.context().storageState(),l;if(t.num_verification_exprs!==0)try{S.log("Generating validation locators for future login verification...");let x=await qr(e,t.site_url,{verification_hint:t.verification_hint,num_verification_exprs:t.num_verification_exprs},async(h,g)=>this.run(h,g),async h=>this.getDOMText(h));x?(l=x,S.log(`Generated ${l.length} validation locator(s): ${JSON.stringify(l)}`)):S.log("Failed to generate validation locators, login will still succeed")}catch(x){S.log(`Error generating validation locators: ${x.message}`)}else S.log("Skipping validation locator generation (num_verification_exprs=0)");S.log("Level 3 SUCCESS: Agent login succeeded"),o.info("Login: Agent login succeeded");let f=s.actions||[],b=f.length>0?f:u?.cached_actions;return{success:!0,page:e,storage_state:c,cached_actions:b,validation_exprs:l}}catch(a){return S.error(`Agent login failed: ${a.message}`),o.info("Login: Failed"),{success:!1,page:e}}}async executeCachedLogin(e,t,u){let r=(await import("./handler-N7MN6JWY.js")).default,i=new r;for(let a=0;a<t.length;a++){let n=t[a];S.log(`Executing cached action ${a+1}/${t.length}: ${n.action_description||n.action_data?.action_name}`);try{if(!n.action_data){S.log(`Action ${a+1} missing action_data, skipping`);continue}await i.execute(e,n,this.agentServices),await this.waitUntilStable(e,5e3)}catch(s){return S.error(`Cached action ${a+1} failed: ${s.message}`),{success:!1}}}return u&&u.length>0&&!await Xt(e,u)?{success:!1}:{success:!0}}getCompletedExecutionHistory(){if(!this.context.executionHistory||this.context.executionHistory.length===0)return[];let e=this.context.executionHistory[this.context.executionHistory.length-1];return!e[1]||e[1].trim()===""?this.context.executionHistory.slice(0,-1):this.context.executionHistory}addToExecutionHistory(e,t){this.context.executionHistory||(this.context.executionHistory=[]),this.context.executionHistory.push([e,t])}async createStepResult(e,t,u){if(!this.context.stepTracking||this.context.stepTracking.results[t])return;this.context.stepTracking.currentStepId=t,this.context.stepTracking.onStepChange&&this.context.stepTracking.onStepChange(t),e=this.agentServices.validatePage(e),await this.waitUntilStable(e);let r={description:u,startTime:Date.now(),artifacts:[]};if(this.context.stepTracking.artifactsDir){let i=C.join(this.context.stepTracking.artifactsDir,t.replace(/\./g,"-"));N.mkdirSync(i,{recursive:!0});let a=C.join(i,"screenshot.png");e=this.agentServices.validatePage(e),await e.screenshot({type:"png",path:a}),r.screenshot=a}this.context.stepTracking.results[t]=r}saveDebugInfoToFiles(e,t,u){let r={};if(!this.context.stepTracking?.artifactsDir)return o.debug("[saveDebugInfoToFiles] No artifacts directory configured, skipping debug info save"),r;let i=C.join(this.context.stepTracking.artifactsDir,e.replace(/\./g,"-"));try{if(N.mkdirSync(i,{recursive:!0}),t.systemPrompt){let a=C.join(i,"system_prompt.txt");N.writeFileSync(a,t.systemPrompt),r.system_prompt_path=a,o.debug(`[saveDebugInfoToFiles] Saved system prompt to: ${a}`)}if(t.userPrompt)if(typeof t.userPrompt=="string"){let a=C.join(i,"user_prompt.txt");N.writeFileSync(a,t.userPrompt),r.user_prompt_path=a,o.debug(`[saveDebugInfoToFiles] Saved user prompt to: ${a}`)}else{let a=t.userPrompt.map(c=>Array.isArray(c.content)?{...c,content:c.content.map(l=>l.type==="image"&&l.file?.startsWith("data:")?{...l,file:"[base64 image data stripped]"}:l)}:c),n=C.join(i,"messages.json"),s={system:t.systemPrompt,messages:a};N.writeFileSync(n,JSON.stringify(s,null,2)),r.messages_path=n,o.debug(`[saveDebugInfoToFiles] Saved messages to: ${n}`)}if(t.rawLlmResponse){let a=u?u.replace(/[\/\\:]/g,"-"):"llm",n=C.join(i,`${a}_response.txt`);N.writeFileSync(n,t.rawLlmResponse),r.response_path=n,o.debug(`[saveDebugInfoToFiles] Saved LLM response to: ${n}`)}if(t.screenshotWithSom){let a=C.join(i,"screenshot.png");N.writeFileSync(a,Buffer.from(t.screenshotWithSom,"base64")),r.screenshot_path=a,o.debug(`[saveDebugInfoToFiles] Saved SOM screenshot to: ${a}`)}if(t.reasoningContent){let a=C.join(i,"reasoning.txt");N.writeFileSync(a,t.reasoningContent),r.reasoning_path=a,o.debug(`[saveDebugInfoToFiles] Saved reasoning to: ${a}`)}o.debug(`[saveDebugInfoToFiles] Saved ${Object.keys(r).length} artifacts for step ${e}`)}catch(a){o.error(`[saveDebugInfoToFiles] Failed to save debug info for step ${e}:`,a)}return r}async updateStepResult(e,t,u,r,i){if(!this.context.stepTracking)return;let a=this.context.stepTracking.results[e];if(a){if(t&&(a.status=t,this.context.stepTracking.currentStepId=void 0,this.context.stepTracking.onStepChange&&this.context.stepTracking.onStepChange(void 0)),u!==void 0&&(a.message=u),r&&a.artifacts.push(r),i){let n=i.tokenUsages?.[0]?.model,s=this.saveDebugInfoToFiles(e,i,n);Object.keys(s).length>0&&a.artifacts.push(s)}a.duration=Date.now()-a.startTime,this.context.stepTracking.onStepComplete&&this.context.stepTracking.onStepComplete(e,a)}}async writeExecutionResults(e,t){try{if(await N.promises.mkdir(e,{recursive:!0}),this.context.stepTracking?.results&&Object.keys(this.context.stepTracking.results).length>0){let u=C.join(e,"test-results.json");await N.promises.writeFile(u,JSON.stringify(this.context.stepTracking.results,null,2)),o.debug(`Test results written to: ${u}`)}if(t?.tokenUsages&&this.context.tokenUsages&&this.context.tokenUsages.length>0){let u=C.join(e,"token-usages.json");await N.promises.writeFile(u,JSON.stringify(this.context.tokenUsages,null,2)),o.debug(`Token usages written to: ${u}`)}if(this.context.aiActionDetails&&this.context.aiActionDetails.length>0){let u=C.join(e,"ai-actions.json");await N.promises.writeFile(u,JSON.stringify(this.context.aiActionDetails,null,2)),o.debug(`AI action details written to: ${u}`)}}catch(u){throw o.error("Failed to write execution results:",u),u}}};function D0(){let e=new Date,t=new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(e),u=t.find(y=>y.type==="year").value,r=t.find(y=>y.type==="month").value,i=t.find(y=>y.type==="day").value,a=t.find(y=>y.type==="hour").value,n=t.find(y=>y.type==="minute").value,s=t.find(y=>y.type==="second").value,c=String(e.getMilliseconds()).padStart(3,"0"),l=`${u}-${r}-${i}T${a}:${n}:${s}.${c}`,f=e.toISOString().slice(0,-1),b=Date.parse(l+"Z"),x=Date.parse(f+"Z"),h=Math.round((x-b)/(1e3*60)),g=String(Math.floor(Math.abs(h)/60)).padStart(2,"0"),v=String(Math.abs(h)%60).padStart(2,"0"),w=h<=0?"+":"-";return`${u}-${r}-${i}T${a}:${n}:${s}.${c}${w}${g}:${v}`}function an(e){let t=e.variableStore;return t.has("currentTime")||t.set("currentTime",D0()),{model:e.model,variableStore:t,organizationId:e.organizationId,organizationSettings:e.organizationSettings,executionHistory:e.executionHistory||[],testDataDir:e.testDataDir,downloadDir:e.downloadDir,useNativeGenerator:e.useNativeGenerator,autoDisableModal:e.autoDisableModal,tokenUsages:[],aiActionDetails:[]}}function v1(e){let t=new Rr,u=new Set(e.sensitiveKeys||[]);if(e.variables)for(let[i,a]of Object.entries(e.variables))t.set(i,a,u.has(i));let r=an({model:e.model,variableStore:t,testDataDir:e.testDataDir,downloadDir:e.downloadDir});return new rn(r)}var k1="1.0.0";export{Hr as a,sn as b,on as c,cn as d,ln as e,r0 as f,i0 as g,a0 as h,n0 as i,s0 as j,o0 as k,c0 as l,h0 as m,p0 as n,Ju as o,un as p,Yu as q,rn as r,an as s,v1 as t,k1 as u};
137
137
  /*! Bundled license information:
138
138
 
139
139
  @otplib/plugin-crypto/index.js:
@@ -0,0 +1,5 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ const require = __createRequire(import.meta.url);
3
+ import{d as o,e as g,f as d}from"./chunk-T2JTBHI7.js";var b={};d(b,{ACTION_TIMEOUT:()=>p,GOTO_TIMEOUT:()=>w,LOCATOR_TIMEOUT:()=>u,getActionTimeoutMs:()=>_,getFrameContext:()=>f,getLocator:()=>E,getMinimalActionEntity:()=>O,getPageLocatorExpression:()=>$,sanitizeForComment:()=>L});function _(e,t){return t??e?.getActionSettings()?.action_timeout_ms??p}function L(e){return e.replace(/\r\n/g," ").replace(/\n/g," ").replace(/\r/g," ").trim()}function E(e,t){let a=$(t);return a?new Function("page",`return ${a}`)(e):null}async function f(e,t=[]){let a=e;for(let i of t){let n=await a.locator(i).elementHandle();if(!n)return null;let r=await n.contentFrame();if(await n.dispose(),!r)return null;a=r}return a}function O(e){let t={action_data:e.action_data};return e.locator&&(t.locator=e.locator),e.xpath&&(t.xpath=e.xpath),e.frame_path&&(t.frame_path=e.frame_path),t}function v(e){let t=e.frame_path;return!t||t.length===0?"page":`page.frameLocator('${t[0]}')`}function T(e){let t=e.xpath;return typeof t=="string"&&t.trim()?!t.startsWith("xpath=")&&!t.startsWith("/")&&!t.startsWith("//")?`xpath=//${t}`:t.startsWith("xpath=")?t:`xpath=${t}`:null}function $(e){let t=v(e),a=e.locator;if(typeof a=="string"&&a.trim())return a=a.trim(),a.endsWith("first()")?`${t}.${a}`:`${t}.${a}.first()`;let i=T(e);if(i){let n=JSON.stringify(i);return`${t}.locator(${n}).first()`}return null}var u,p,w,y=g(()=>{u=5e3,p=5e3,w=2e4});y();async function h(e,t,a=[],i=[]){try{let n=await f(e,a);if(!n)return o.warn(`Could not find frame context for xpath: ${t}`),null;let r=null;if(i.length>0){let s=i[0];if(!s)return o.warn(`Missing shadow host xpath for element: ${t}`),null;let c=n.locator(`xpath=${x(s)}`),m=W(t);if(r=await(m?c.locator(`css=${m}`):c.locator(`xpath=${x(t)}`)).elementHandle({timeout:u}),!r)return o.warn(`Could not find shadow DOM element with xpath: ${t}`),null}else if(r=await n.locator(`xpath=${t}`).elementHandle({timeout:u}),!r)return o.warn(`Could not find element with xpath: ${t}`),null;let l=await n.evaluate(s=>typeof playwright<"u"&&playwright.generateLocator?playwright.generateLocator(s):null,r);return await r.dispose(),l?(o.debug(`Generated locator for ${t}: ${l}`),l):(o.debug("playwright.generateLocator is not available (PWDEBUG=console not set), using xpath fallback"),null)}catch(n){return o.error(`Error in pickBestLocator: ${n}`),null}}async function B(e,t){try{let a=await(await t.ownerFrame()??e).evaluate(i=>typeof playwright<"u"&&playwright.generateLocator?playwright.generateLocator(i):null,t);return await t.dispose(),a?(o.debug(`Generated locator: ${a}`),a):(o.debug("playwright.generateLocator is not available (PWDEBUG=console not set), using xpath fallback"),null)}catch(a){return o.error(`Error in pickBestLocator: ${a}`),null}}async function G(e,t){let a=new Map;return await Promise.all(t.map(async i=>{let n=await h(e,i);a.set(i,n)})),a}function x(e){let t=e.trim();return t.startsWith("/")||t.startsWith("(")||t.startsWith(".")?t:`//${t}`}function W(e){let t=e.trim().replace(/^\/+/,"");if(!t)return null;let a=t.split("/").filter(Boolean),i=[];for(let n of a){let r=n.match(/^([a-zA-Z][\w-]*)(?:\[(\d+)\])?$/);if(!r)return null;let l=r[1].toLowerCase(),s=r[2]?`:nth-of-type(${r[2]})`:"";i.push(`${l}${s}`)}return i.join(" > ")}async function H(e,t){if(t<0)return;let{page:a,domService:i}=e;return(e.domState||await i.getClickableElements(a)).selectorMap.get(t)}function A(e){let t=e.split("/").filter(n=>n);if(t.length===0)return"*";let a=t[t.length-1],i=a.match(/^(\w+)(?:\[(\d+)\])?$/);if(i){let[,n,r]=i;return r?`${n}:nth-of-type(${r})`:n}return a}function C(e,t=!0){try{let a=A(e.xpath);if(e.attributes.class&&t){let n=/^[a-zA-Z_][a-zA-Z0-9_-]*$/,r=e.attributes.class.split(/\s+/);for(let l of r)l.trim()&&n.test(l)&&(a+=`.${l}`)}let i=new Set(["id","name","type","placeholder","aria-label","aria-labelledby","aria-describedby","role","for","autocomplete","required","readonly","alt","title","target"]);t&&["data-id","data-qa","data-cy","data-testid","data-handlepos"].forEach(n=>i.add(n));for(let[n,r]of Object.entries(e.attributes)){if(n==="class"||!n.trim()||!i.has(n))continue;let l=n.replace(/:/g,"\\:");if(r==="")a+=`[${l}]`;else if(/["'<>`\n\r\t]/.test(r)){let s=r;r.includes(`
4
+ `)&&(s=r.split(`
5
+ `)[0]),s=s.replace(/\s+/g," ").trim();let c=s.replace(/"/g,'\\"');a+=`[${l}*="${c}"]`}else a+=`[${l}="${r}"]`}return a}catch{return`${e.tagName||"*"}[highlight_index='${e.highlightIndex}']`}}function M(e){let t=e.attributes;if(t.title)return`iframe[title="${t.title.replace(/"/g,'\\"')}"]`;if(t.id)return`iframe#${t.id}`;if(t.name)return`iframe[name="${t.name.replace(/"/g,'\\"')}"]`;if(t.src){try{let a=new URL(t.src);if(a.protocol==="chrome-extension:")return`iframe[src^="${a.origin}"]`}catch{}return`iframe[src="${t.src.replace(/"/g,'\\"')}"]`}return C(e,!1)}function k(e){let t=[],a=e;for(;a&&a.parent!==null;){let r=a.parent;t.push(r),a=r}t.reverse();let i=[],n=t.filter(r=>r.tagName==="iframe");for(let r of n){let l=M(r);o.debug("[frame-path] iframe attrs:",JSON.stringify(r.attributes),"\u2192",l),i.push(l)}return i}async function j(e,t){let a=null,i=k(t);return t.xpath&&(a=await h(e,t.xpath,i,t.shadowHostXPaths??[])),{locator:a||void 0,xpath:t.xpath,frame_path:i}}export{b as a,_ as b,E as c,$ as d,w as e,y as f,h as g,B as h,G as i,H as j,k,j as l};
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  const require = __createRequire(import.meta.url);
3
- import{c as w}from"./chunk-DJDHFWEV.js";var h=`
3
+ import{d as w}from"./chunk-T2JTBHI7.js";var g=`
4
4
  // check to make sure we're not inside the PDF viewer
5
5
  window.isPdfViewer = !!document?.body?.querySelector('body > embed[type="application/pdf"][width="100%"]')
6
6
  if (!window.isPdfViewer) {
@@ -55,4 +55,4 @@ if (!window.isPdfViewer) {
55
55
  };
56
56
  })();
57
57
  }
58
- `;function F(e,r=!0,t=!1){return[...e!==void 0?[`--remote-debugging-port=${e}`,"--remote-allow-origins=*"]:[],"--no-sandbox","--disable-blink-features=AutomationControlled","--timezone=America/Los_Angeles",...t?["--headless"]:[],...r?["--disable-web-security","--disable-site-isolation-trials","--disable-features=IsolateOrigins,site-per-process","--allow-running-insecure-content","--ignore-certificate-errors","--ignore-ssl-errors","--ignore-certificate-errors-spki-list"]:[]]}async function E(e,r){let t=await e.newContext(r);return t.addInitScript(h),t}async function T(e){return(await(await fetch(`http://127.0.0.1:${e}/json/version`)).json()).webSocketDebuggerUrl.replace("localhost","127.0.0.1")}async function x(e,r){let t=await(await fetch(`http://localhost:${e}/json/list`)).json();for(let s of t)if(s.type==="page"&&s.id===r)return s.webSocketDebuggerUrl;throw new Error(`No page found for id: ${r}`)}async function z(e){let r=await e.context().newCDPSession(e),t=await r.send("Target.getTargetInfo");return await r.detach(),t.targetInfo}var I=async(e,r,t)=>{let s=await e.context().newCDPSession(e),c=await s.send("Browser.getWindowForTarget");await s.send("Browser.setWindowBounds",{windowId:c.windowId,bounds:{width:r,height:t,windowState:"normal"}});try{await Promise.race([s.detach(),new Promise((d,l)=>setTimeout(()=>l(new Error("CDP detach timeout")),1e3))])}catch{}},y=.5*1e3,b=30*1e3,v=1*1e3,k=3*1e3;async function P(e,r){let t=new Set,s=Date.now(),c=new Set(["document","stylesheet","image","font","script","iframe"]),d=new Set(["text/html","text/css","application/javascript","image/","font/","application/json"]),l=["analytics","tracking","telemetry","beacon","metrics","doubleclick","adsystem","adserver","advertising","facebook.com/plugins","platform.twitter","linkedin.com/embed","livechat","zendesk","intercom","crisp.chat","hotjar","push-notifications","onesignal","pushwoosh","heartbeat","ping","alive","webrtc","rtmp://","wss://","cloudfront.net","fastly.net"],u=i=>{let n=i.toLowerCase();return n.startsWith("data:")||n.startsWith("blob:")?!0:l.some(o=>n.includes(o))},f=i=>{let n=i.resourceType(),o=i.url();if(!c.has(n)||u(o))return;let a=i.headers();a.purpose==="prefetch"||["video","audio"].includes(a["sec-fetch-dest"])||(t.add(i),s=Date.now())},m=async i=>{let n=i.request();if(!t.has(n))return;let o=(i.headers()["content-type"]||"").toLowerCase();if(["streaming","video","audio","webm","mp4","event-stream","websocket","protobuf"].some(p=>o.includes(p))){t.delete(n);return}if(![...d].some(p=>o.startsWith(p))){t.delete(n);return}let a=i.headers()["content-length"];if(a)try{if(parseInt(a,10)>5*1024*1024){t.delete(n);return}}catch{}t.delete(n),s=Date.now()},g=Date.now()-k;for(let i of await e.requests()){let n=i.resourceType(),o=i.url(),a=i.timing();c.has(n)&&!u(o)&&a.responseEnd===-1&&a.startTime>=g&&(t.add(i),s=Date.now())}w.info(`[waitForStableNetwork] Pre-populated ${t.size} in-flight requests`),e.on("request",f),e.on("response",m);try{let i=Date.now(),n=v;for(;;){await new Promise(a=>setTimeout(a,100));let o=Date.now();if(t.size===0&&o-s>=n){w.info(`[waitForStableNetwork] Network idle after ${o-i}ms`);break}if(o-i>r){w.info(`[waitForStableNetwork] Max wait time exceeded (${r}ms), pending: ${t.size}`);break}}}finally{e.removeListener("request",f),e.removeListener("response",m)}}async function _(e,r=b,t=y){let s=Date.now();try{await Promise.all([e.waitForLoadState("load",{timeout:r}).catch(()=>{}),P(e,r)])}catch(l){throw l instanceof Error?new Error(`Failed during network stabilization: ${l.message}`):new Error("An unknown error occurred during network stabilization.")}let c=Date.now()-s,d=Math.max(t-c,0);d>0&&await new Promise(l=>setTimeout(l,d))}export{h as a,F as b,E as c,T as d,x as e,z as f,I as g,_ as h};
58
+ `;function F(e,r=!0,t=!1){return[...e!==void 0?[`--remote-debugging-port=${e}`,"--remote-allow-origins=*"]:[],"--no-sandbox","--disable-blink-features=AutomationControlled","--timezone=America/Los_Angeles",...t?["--headless"]:[],...r?["--disable-web-security","--disable-site-isolation-trials","--disable-features=IsolateOrigins,site-per-process","--allow-running-insecure-content","--ignore-certificate-errors","--ignore-ssl-errors","--ignore-certificate-errors-spki-list"]:[]]}async function E(e,r){let t=await e.newContext(r);return t.addInitScript(g),t}async function T(e){return(await(await fetch(`http://127.0.0.1:${e}/json/version`)).json()).webSocketDebuggerUrl.replace("localhost","127.0.0.1")}async function x(e,r){let t=await(await fetch(`http://localhost:${e}/json/list`)).json();for(let s of t)if(s.type==="page"&&s.id===r)return s.webSocketDebuggerUrl;throw new Error(`No page found for id: ${r}`)}async function z(e){let r=await e.context().newCDPSession(e),t=await r.send("Target.getTargetInfo");return await r.detach(),t.targetInfo}var I=async(e,r,t)=>{let s=await e.context().newCDPSession(e),d=await s.send("Browser.getWindowForTarget");await s.send("Browser.setWindowBounds",{windowId:d.windowId,bounds:{width:r,height:t,windowState:"normal"}});try{await Promise.race([s.detach(),new Promise((c,l)=>setTimeout(()=>l(new Error("CDP detach timeout")),1e3))])}catch{}},y=.5*1e3,b=30*1e3,v=1*1e3,k=3*1e3;async function P(e,r){let t=new Set,s=Date.now(),d=new Set(["document","stylesheet","image","font","script","iframe"]),c=new Set(["text/html","text/css","application/javascript","image/","font/","application/json"]),l=["analytics","tracking","telemetry","beacon","metrics","doubleclick","adsystem","adserver","advertising","facebook.com/plugins","platform.twitter","linkedin.com/embed","livechat","zendesk","intercom","crisp.chat","hotjar","push-notifications","onesignal","pushwoosh","heartbeat","ping","alive","webrtc","rtmp://","wss://","cloudfront.net","fastly.net"],p=i=>{let n=i.toLowerCase();return n.startsWith("data:")||n.startsWith("blob:")?!0:l.some(o=>n.includes(o))},f=i=>{let n=i.resourceType(),o=i.url();if(!d.has(n)||p(o))return;let a=i.headers();a.purpose==="prefetch"||["video","audio"].includes(a["sec-fetch-dest"])||(t.add(i),s=Date.now())},m=async i=>{let n=i.request();if(!t.has(n))return;let o=(i.headers()["content-type"]||"").toLowerCase();if(["streaming","video","audio","webm","mp4","event-stream","websocket","protobuf"].some(u=>o.includes(u))){t.delete(n);return}if(![...c].some(u=>o.startsWith(u))){t.delete(n);return}let a=i.headers()["content-length"];if(a)try{if(parseInt(a,10)>5*1024*1024){t.delete(n);return}}catch{}t.delete(n),s=Date.now()},h=Date.now()-k;for(let i of await e.requests()){let n=i.resourceType(),o=i.url(),a=i.timing();d.has(n)&&!p(o)&&a.responseEnd===-1&&a.startTime>=h&&(t.add(i),s=Date.now())}w.debug(`[waitForStableNetwork] Pre-populated ${t.size} in-flight requests`),e.on("request",f),e.on("response",m);try{let i=Date.now(),n=v;for(;;){await new Promise(a=>setTimeout(a,100));let o=Date.now();if(t.size===0&&o-s>=n){w.debug(`[waitForStableNetwork] Network idle after ${o-i}ms`);break}if(o-i>r){w.debug(`[waitForStableNetwork] Max wait time exceeded (${r}ms), pending: ${t.size}`);break}}}finally{e.removeListener("request",f),e.removeListener("response",m)}}async function _(e,r=b,t=y){let s=Date.now();try{await Promise.all([e.waitForLoadState("load",{timeout:r}).catch(()=>{}),P(e,r)])}catch(l){throw l instanceof Error?new Error(`Failed during network stabilization: ${l.message}`):new Error("An unknown error occurred during network stabilization.")}let d=Date.now()-s,c=Math.max(t-d,0);c>0&&await new Promise(l=>setTimeout(l,c))}export{g as a,F as b,E as c,T as d,x as e,z as f,I as g,_ as h};