@browserbasehq/orca 3.0.2-patch → 3.0.2-zod34

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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/dist/index.d.ts +85 -43
  3. package/dist/index.js +1022 -493
  4. package/package.json +21 -21
package/dist/index.js CHANGED
@@ -61,7 +61,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
61
61
  ));
62
62
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
63
63
  var __async = (__this, __arguments, generator) => {
64
- return new Promise((resolve3, reject) => {
64
+ return new Promise((resolve2, reject) => {
65
65
  var fulfilled = (value) => {
66
66
  try {
67
67
  step(generator.next(value));
@@ -76,7 +76,7 @@ var __async = (__this, __arguments, generator) => {
76
76
  reject(e);
77
77
  }
78
78
  };
79
- var step = (x) => x.done ? resolve3(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
79
+ var step = (x) => x.done ? resolve2(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
80
80
  step((generator = generator.apply(__this, __arguments)).next());
81
81
  });
82
82
  };
@@ -85,7 +85,7 @@ var __async = (__this, __arguments, generator) => {
85
85
  var STAGEHAND_VERSION;
86
86
  var init_version = __esm({
87
87
  "lib/version.ts"() {
88
- STAGEHAND_VERSION = "3.0.2-patch";
88
+ STAGEHAND_VERSION = "3.0.2-zod34";
89
89
  }
90
90
  });
91
91
 
@@ -461,7 +461,7 @@ var init_executionContextRegistry = __esm({
461
461
  });
462
462
  const after = this.getMainWorld(session, frameId);
463
463
  if (after) return after;
464
- return yield new Promise((resolve3, reject) => {
464
+ return yield new Promise((resolve2, reject) => {
465
465
  let done = false;
466
466
  const onCreated = (evt) => {
467
467
  var _a;
@@ -472,7 +472,7 @@ var init_executionContextRegistry = __esm({
472
472
  done = true;
473
473
  clearTimeout(timer);
474
474
  session.off("Runtime.executionContextCreated", onCreated);
475
- resolve3(evt.context.id);
475
+ resolve2(evt.context.id);
476
476
  }
477
477
  }
478
478
  };
@@ -1178,8 +1178,8 @@ function normalizeXPath(x) {
1178
1178
  if (s.length > 1 && s.endsWith("/")) s = s.slice(0, -1);
1179
1179
  return s;
1180
1180
  }
1181
- function parseXPathToSteps(path6) {
1182
- const s = path6.trim();
1181
+ function parseXPathToSteps(path7) {
1182
+ const s = path7.trim();
1183
1183
  let i = 0;
1184
1184
  const steps = [];
1185
1185
  while (i < s.length) {
@@ -1848,31 +1848,33 @@ var init_snapshot = __esm({
1848
1848
  var locatorScriptBootstrap, locatorScriptSources, locatorScriptGlobalRefs;
1849
1849
  var init_locatorScripts_generated = __esm({
1850
1850
  "lib/v3/dom/build/locatorScripts.generated.ts"() {
1851
- locatorScriptBootstrap = 'if (!globalThis.__stagehandLocatorScripts) { var __stagehandLocatorScriptsFactory=(()=>{var L=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var D=(t,e)=>{for(var c in e)L(t,c,{get:e[c],enumerable:!0})},A=(t,e,c,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of k(e))!H.call(t,r)&&r!==c&&L(t,r,{get:()=>e[r],enumerable:!(n=C(e,r))||n.enumerable});return t};var _=t=>A(L({},"__esModule",{value:!0}),t);var ne={};D(ne,{countCssMatchesPierce:()=>Z,countCssMatchesPrimary:()=>Q,countTextMatches:()=>ee,countXPathMatchesMainWorld:()=>te,dispatchDomClick:()=>W,ensureFileInputElement:()=>I,fillElementValue:()=>O,focusElement:()=>P,isElementChecked:()=>Y,isElementVisible:()=>X,prepareElementForTyping:()=>b,readElementInnerHTML:()=>j,readElementInnerText:()=>K,readElementInputValue:()=>$,readElementTextContent:()=>B,resolveCssSelector:()=>U,resolveCssSelectorPierce:()=>z,resolveTextSelector:()=>G,resolveXPathMainWorld:()=>J,scrollElementToPercent:()=>q,selectElementOptions:()=>V});function I(){try{return(this.tagName?.toLowerCase()??"")!=="input"?!1:String(this.type??"").toLowerCase()==="file"}catch{return!1}}function W(t){let e=t??{};try{let c=new MouseEvent("click",{bubbles:!!e.bubbles,cancelable:!!e.cancelable,composed:!!e.composed,detail:typeof e.detail=="number"?e.detail:1,view:this?.ownerDocument?.defaultView??window});this.dispatchEvent(c)}catch{try{this.click()}catch{}}}function q(t){let e=c=>{if(typeof c=="number"&&Number.isFinite(c))return c;let n=String(c??"").trim();if(!n)return 0;let r=parseFloat(n.replace("%",""));return Number.isNaN(r)||!Number.isFinite(r)?0:r};try{let c=Math.max(0,Math.min(e(t),100)),n=this,r=n.tagName?.toLowerCase()??"";if(r==="html"||r==="body"){let d=(n.ownerDocument?.scrollingElement||n.ownerDocument?.documentElement||n.ownerDocument?.body||document.scrollingElement||document.documentElement||document.body)?.scrollHeight??document.body.scrollHeight??0,s=n.ownerDocument?.defaultView?.innerHeight??window.innerHeight,g=Math.max(0,d-s)*(c/100);return n.ownerDocument?.defaultView?.scrollTo({top:g,left:n.ownerDocument?.defaultView?.scrollX??window.scrollX??0,behavior:"smooth"}),!0}let f=n.scrollHeight??0,u=n.clientHeight??0,i=Math.max(0,f-u)*(c/100);return n.scrollTo({top:i,left:n.scrollLeft??0,behavior:"smooth"}),!0}catch{return!1}}var R=new Set(["color","date","datetime-local","month","range","time","week"]),F=new Set(["","email","number","password","search","tel","text","url"]);function b(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument||document,c=e.defaultView||window;try{typeof t.focus=="function"&&t.focus()}catch{}if(t instanceof c.HTMLInputElement||t instanceof c.HTMLTextAreaElement){try{if(typeof t.select=="function")return t.select(),!0}catch{}try{let n=(t.value??"").length;if(typeof t.setSelectionRange=="function")return t.setSelectionRange(0,n),!0}catch{}return!0}if(t.isContentEditable){let n=e.getSelection?.(),r=e.createRange?.();if(n&&r)try{r.selectNodeContents(t),n.removeAllRanges(),n.addRange(r)}catch{}return!0}return!1}catch{return!1}}function O(t){let e=this;if(!e.isConnected)return{status:"error",reason:"notconnected"};let n=(e.ownerDocument||document).defaultView||window,r=t??"";try{let y=f=>{let u;if(typeof n.InputEvent=="function")try{u=new n.InputEvent("input",{bubbles:!0,composed:!0,data:f,inputType:"insertText"})}catch{u=new n.Event("input",{bubbles:!0,composed:!0})}else u=new n.Event("input",{bubbles:!0,composed:!0});e.dispatchEvent(u);let l=new n.Event("change",{bubbles:!0});e.dispatchEvent(l)};if(e instanceof n.HTMLInputElement){let f=(e.type||"").toLowerCase();if(!F.has(f)&&!R.has(f))return{status:"error",reason:`unsupported-input-type:${f}`};let u=t;if(f==="number"){let l=t.trim();if(l!==""&&Number.isNaN(Number(l)))return{status:"error",reason:"invalid-number-value"};u=l}if(r=u,R.has(f)){let l=t.trim();r=l,b.call(e);let i=n.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(i,"value")?.set;return typeof d=="function"?d.call(e,l):e.value=l,e._valueTracker?.setValue?.(l),e.value!==l?{status:"error",reason:"malformed-value"}:(y(l),{status:"done"})}return b.call(e),{status:"needsinput",value:u}}return e instanceof n.HTMLTextAreaElement?(b.call(e),r=t,{status:"needsinput",value:t}):e instanceof n.HTMLSelectElement?{status:"error",reason:"unsupported-element"}:e.isContentEditable?(b.call(e),r=t,{status:"needsinput",value:t}):{status:"error",reason:"unsupported-element"}}catch(y){let f="exception";if(y&&typeof y=="object"){let u=y.message;typeof u=="string"&&u.trim().length>0&&(f=`exception:${u}`)}return{status:"needsinput",value:r,reason:f}}}function P(){try{typeof this.focus=="function"&&this.focus()}catch{}}function V(t){try{if(!(this instanceof HTMLSelectElement))return[];let e=Array.isArray(t)?t:[t],c=new Set(e.map(f=>String(f??"").trim())),n=f=>{let u=(f.label||f.textContent||"").trim(),l=String(f.value??"").trim();return c.has(u)||c.has(l)};if(this.multiple)for(let f of Array.from(this.options))f.selected=n(f);else{let f=!1;for(let u of Array.from(this.options))!f&&n(u)?(u.selected=!0,this.value=u.value,f=!0):u.selected=!1}let r=new Event("input",{bubbles:!0}),y=new Event("change",{bubbles:!0});return this.dispatchEvent(r),this.dispatchEvent(y),Array.from(this.selectedOptions).map(f=>f.value)}catch{return[]}}function X(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument?.defaultView?.getComputedStyle(t)??window.getComputedStyle(t);if(!e||e.display==="none"||e.visibility==="hidden")return!1;let c=parseFloat(e.opacity??"1");if(!Number.isFinite(c)||c===0)return!1;let n=t.getBoundingClientRect();return!(!n||Math.max(n.width,n.height)===0||t.getClientRects().length===0)}catch{return!1}}function Y(){try{let t=this;if((t.tagName||"").toLowerCase()==="input"){let n=t.type?.toLowerCase()??"";if(n==="checkbox"||n==="radio")return!!t.checked}let c=t.getAttribute?.("aria-checked");return c!=null?c==="true":!1}catch{return!1}}function $(){try{let t=this,e=(t.tagName||"").toLowerCase();return e==="input"||e==="textarea"||e==="select"?String(t.value??""):t.isContentEditable?String(t.textContent??""):""}catch{return""}}function B(){try{return String(this.textContent??"")}catch{return""}}function j(){try{return String(this.innerHTML??"")}catch{return""}}function K(){try{let t=this,e=t.innerText;if(typeof e=="string"&&e.length>0)return e;let c=t.textContent;return typeof c=="string"?c:""}catch{return""}}var N=t=>{let e=Number(t??0);return!Number.isFinite(e)||e<0?0:Math.floor(e)},v=(t,e)=>{if(!t)return[];let c=new WeakSet,n=new Set,r=[],y=[document],f=u=>{if(!(!u||c.has(u)||r.length>=e)){c.add(u);try{let l=u.querySelectorAll(t);for(let i of l)if(!n.has(i)&&(n.add(i),r.push(i),r.length>=e))return}catch{}try{let i=(u instanceof Document?u:u.host?.ownerDocument??document).createTreeWalker(u,NodeFilter.SHOW_ELEMENT),h;for(;h=i.nextNode();){if(!(h instanceof Element))continue;let d=h.shadowRoot;d&&y.push(d)}}catch{}}};for(;y.length&&r.length<e;){let u=y.shift();u&&f(u)}return r};function U(t,e){let c=String(t??"").trim();if(!c)return null;let n=N(e);return v(c,n+1)[n]??null}function z(t,e){let c=String(t??"").trim();if(!c)return null;let n=N(e),r=window.__stagehandV3__;if(!r||typeof r.getClosedRoot!="function")return v(c,n+1)[n]??null;let y=d=>{try{return r.getClosedRoot(d)??null}catch{return null}},f=new WeakSet,u=new Set,l=[],i=[document],h=d=>{if(!(!d||f.has(d)||l.length>=n+1)){f.add(d);try{let s=d.querySelectorAll(c);for(let m of s)if(!u.has(m)&&(u.add(m),l.push(m),l.length>=n+1))return}catch{}try{let m=(d instanceof Document?d:d.host?.ownerDocument??document).createTreeWalker(d,NodeFilter.SHOW_ELEMENT),g;for(;g=m.nextNode();){if(!(g instanceof Element))continue;let w=g.shadowRoot;w&&i.push(w);let E=y(g);E&&i.push(E)}}catch{}}};for(;i.length&&l.length<n+1;){let d=i.shift();d&&h(d)}return l[n]??null}function G(t,e){let c=String(t??"");if(!c)return null;let n=c.toLowerCase(),r=N(e),y=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),f=o=>{if(!o)return!1;let p=o.tagName?.toUpperCase()??"";return y.has(p)},u=o=>{try{if(f(o))return"";let p=o.innerText;if(typeof p=="string"&&p.trim())return p.trim()}catch{}try{let p=o.textContent;if(typeof p=="string")return p.trim()}catch{}return""},l=o=>{let p=u(o);return!!p&&p.toLowerCase().includes(n)},i=window.__stagehandV3__,h=i&&typeof i.getClosedRoot=="function"?o=>{try{return i.getClosedRoot(o)??null}catch{return null}}:o=>null,d=new WeakSet,s=[],m=[],g=o=>{!o||d.has(o)||(d.add(o),s.push(o))},w=o=>{try{return(o instanceof Document?o:o?.ownerDocument??document).createTreeWalker(o,NodeFilter.SHOW_ELEMENT)}catch{return null}};for(g(document);s.length;){let o=s.shift();if(!o)continue;o instanceof Element&&l(o)&&m.push({element:o,tag:o.tagName??"",id:o.id??"",className:o.className??"",text:u(o)});let p=w(o);if(!p)continue;let x;for(;x=p.nextNode();){if(!(x instanceof Element))continue;l(x)&&m.push({element:x,tag:x.tagName??"",id:x.id??"",className:x.className??"",text:u(x)});let S=x.shadowRoot;S&&g(S);let T=h(x);T&&g(T)}}let E=[];for(let o of m){let p=o.element,x=!1;for(let S of m)if(o!==S)try{if(p.contains(S.element)){x=!0;break}}catch{}x||E.push(o)}return E[r]?.element??null}function J(t,e){let c=String(t??"").trim();if(!c)return null;let n=N(e),r=window.__stagehandV3__;if(n===0){try{if(r&&typeof r.resolveSimpleXPath=="function"){let s=r.resolveSimpleXPath(c);if(s)return s}}catch{}try{return document.evaluate(c,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{}}let f=(s=>{let m=String(s||"").trim();if(!m)return[];let g=m.replace(/^xpath=/i,""),w=[],E=0;for(;E<g.length;){let a="child";g.startsWith("//",E)?(a="desc",E+=2):g[E]==="/"&&(a="child",E+=1);let o=E;for(;E<g.length&&g[E]!=="/";)E+=1;let p=g.slice(o,E).trim();if(!p)continue;let x=p.match(/^(.*?)(\\[(\\d+)\\])?$/u),S=(x?.[1]??p).trim(),T=x?.[3]?Math.max(1,Number(x[3])):null,M=S===""?"*":S.toLowerCase();w.push({axis:a,tag:M,index:T})}return w})(c);if(!f.length)return null;let u=r&&typeof r.getClosedRoot=="function"?s=>{try{return r.getClosedRoot(s)??null}catch{return null}}:s=>null,l=s=>{let m=[];if(!s)return m;if(s instanceof Document)return s.documentElement&&m.push(s.documentElement),m;if(s instanceof ShadowRoot||s instanceof DocumentFragment)return m.push(...Array.from(s.children??[])),m;if(s instanceof Element){m.push(...Array.from(s.children??[]));let g=s.shadowRoot;g&&m.push(...Array.from(g.children??[]));let w=u(s);return w&&m.push(...Array.from(w.children??[])),m}return m},i=s=>{let m=[],g=new Set,w=[...l(s)];for(;w.length;){let E=w.shift();!E||g.has(E)||(g.add(E),m.push(E),w.push(...l(E)))}return m},h=[document];for(let s of f){let m=[],g=new Set;for(let w of h){if(!w)continue;let E=s.axis==="child"?l(w):i(w);if(!E.length)continue;let a=E.filter(o=>o instanceof Element?s.tag==="*"?!0:o.localName===s.tag:!1);if(s.index!=null){let o=s.index-1,p=o>=0&&o<a.length?a[o]:null;p&&!g.has(p)&&(g.add(p),m.push(p))}else for(let o of a)g.has(o)||(g.add(o),m.push(o))}if(!m.length)return null;h=m}return h[n]??null}function Q(t){let e=String(t??"").trim();if(!e)return 0;let c=new WeakSet,n=r=>{if(!r||c.has(r))return 0;c.add(r);let y=0;try{let f=r;typeof f.querySelectorAll=="function"&&(y+=f.querySelectorAll(e).length)}catch{}try{let u=(r instanceof Document?r:r?.ownerDocument??document).createTreeWalker(r,NodeFilter.SHOW_ELEMENT),l;for(;l=u.nextNode();)l instanceof Element&&l.shadowRoot&&(y+=n(l.shadowRoot))}catch{}return y};try{return n(document)}catch{try{return document.querySelectorAll(e).length}catch{return 0}}}function Z(t){let e=String(t??"").trim();if(!e)return 0;let c=window.__stagehandV3__;if(!c||typeof c.getClosedRoot!="function")try{return document.querySelectorAll(e).length}catch{return 0}let n=new WeakSet,r=[],y=l=>{!l||n.has(l)||(n.add(l),r.push(l))};y(document);let f=0,u=l=>{let i=l.shadowRoot;i&&y(i);try{let h=c.getClosedRoot(l);h&&y(h)}catch{}};for(;r.length;){let l=r.shift();if(l){try{let i=l;typeof i.querySelectorAll=="function"&&(f+=i.querySelectorAll(e).length)}catch{}try{let h=(l instanceof Document?l:l instanceof ShadowRoot?l.host?.ownerDocument??document:l.ownerDocument??document).createTreeWalker(l,NodeFilter.SHOW_ELEMENT),d;for(;d=h.nextNode();)d instanceof Element&&u(d)}catch{}}}return f}function ee(t){let e=String(t??"");if(!e)return{count:0,sample:[],error:null};let c=e.toLowerCase(),n=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),r=a=>{if(!a)return!1;let o=a.tagName?.toUpperCase()??"";return n.has(o)},y=a=>{try{if(r(a))return"";let o=a.innerText;if(typeof o=="string"&&o.trim())return o.trim()}catch{}try{let o=a.textContent;if(typeof o=="string")return o.trim()}catch{}return""},f=a=>{let o=y(a);return!!o&&o.toLowerCase().includes(c)},u=window.__stagehandV3__,l=u&&typeof u.getClosedRoot=="function"?a=>{try{return u.getClosedRoot(a)??null}catch{return null}}:a=>null,i=new WeakSet,h=[],d=a=>{!a||i.has(a)||(i.add(a),h.push(a))},s=a=>{try{return(a instanceof Document?a:a?.ownerDocument??document).createTreeWalker(a,NodeFilter.SHOW_ELEMENT)}catch{return null}},m=[];for(d(document);h.length;){let a=h.shift();if(!a)continue;a instanceof Element&&f(a)&&m.push({element:a,tag:a.tagName??"",id:a.id??"",className:a.className??"",text:y(a)});let o=s(a);if(!o)continue;let p;for(;p=o.nextNode();){if(!(p instanceof Element))continue;f(p)&&m.push({element:p,tag:p.tagName??"",id:p.id??"",className:p.className??"",text:y(p)});let x=p.shadowRoot;x&&d(x);let S=l(p);S&&d(S)}}let g=[];for(let a of m){let o=a.element,p=!1;for(let x of m)if(a!==x)try{if(o.contains(x.element)){p=!0;break}}catch{}p||g.push(a)}let w=g.length,E=g.slice(0,5).map(a=>({tag:a.tag,id:a.id,class:a.className,text:a.text}));return{count:w,sample:E,error:null}}function te(t){let e=String(t??"").trim();if(!e)return 0;let n=(i=>{let h=String(i||"").trim().replace(/^xpath=/i,"");if(!h)return[];let d=[],s=0;for(;s<h.length;){let m="child";h.startsWith("//",s)?(m="desc",s+=2):h[s]==="/"&&(m="child",s+=1);let g=s;for(;s<h.length&&h[s]!=="/";)s+=1;let w=h.slice(g,s).trim();if(!w)continue;let E=w.match(/^(.*?)(\\[(\\d+)\\])?$/u),a=(E?.[1]??w).trim(),o=E?.[3]?Math.max(1,Number(E[3])):null,p=a===""?"*":a.toLowerCase();d.push({axis:m,tag:p,index:o})}return d})(e);if(!n.length)return 0;let r=window.__stagehandV3__,y=r&&typeof r.getClosedRoot=="function"?i=>{try{return r.getClosedRoot(i)??null}catch{return null}}:i=>null,f=i=>{let h=[];if(!i)return h;if(i instanceof Document)return i.documentElement&&h.push(i.documentElement),h;if(i instanceof ShadowRoot||i instanceof DocumentFragment)return h.push(...Array.from(i.children??[])),h;if(i instanceof Element){h.push(...Array.from(i.children??[]));let d=i.shadowRoot;d&&h.push(...Array.from(d.children??[]));let s=y(i);return s&&h.push(...Array.from(s.children??[])),h}return h},u=i=>{let h=[],d=new Set,s=[...f(i)];for(;s.length;){let m=s.shift();!m||d.has(m)||(d.add(m),h.push(m),s.push(...f(m)))}return h},l=[document];for(let i of n){let h=[],d=new Set;for(let s of l){if(!s)continue;let m=i.axis==="child"?f(s):u(s);if(!m.length)continue;let g=m.filter(w=>w instanceof Element?i.tag==="*"?!0:w.localName===i.tag:!1);if(i.index!=null){let w=i.index-1,E=w>=0&&w<g.length?g[w]:null;E&&!d.has(E)&&(d.add(E),h.push(E))}else for(let w of g)d.has(w)||(d.add(w),h.push(w))}if(!h.length)return 0;l=h}return l.length}return _(ne);})();\n globalThis.__stagehandLocatorScripts = __stagehandLocatorScriptsFactory;\n}';
1851
+ locatorScriptBootstrap = 'if (!globalThis.__stagehandLocatorScripts) { var __stagehandLocatorScriptsFactory=(()=>{var L=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var D=(t,e)=>{for(var c in e)L(t,c,{get:e[c],enumerable:!0})},A=(t,e,c,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of k(e))!H.call(t,o)&&o!==c&&L(t,o,{get:()=>e[o],enumerable:!(n=R(e,o))||n.enumerable});return t};var _=t=>A(L({},"__esModule",{value:!0}),t);var oe={};D(oe,{assignFilePayloadsToInputElement:()=>F,countCssMatchesPierce:()=>ee,countCssMatchesPrimary:()=>Z,countTextMatches:()=>te,countXPathMatchesMainWorld:()=>ne,dispatchDomClick:()=>W,ensureFileInputElement:()=>I,fillElementValue:()=>O,focusElement:()=>V,isElementChecked:()=>B,isElementVisible:()=>Y,prepareElementForTyping:()=>T,readElementInnerHTML:()=>U,readElementInnerText:()=>j,readElementInputValue:()=>$,readElementTextContent:()=>z,resolveCssSelector:()=>K,resolveCssSelectorPierce:()=>G,resolveTextSelector:()=>J,resolveXPathMainWorld:()=>Q,scrollElementToPercent:()=>q,selectElementOptions:()=>X});function I(){try{return(this.tagName?.toLowerCase()??"")!=="input"?!1:String(this.type??"").toLowerCase()==="file"}catch{return!1}}function F(t){try{let e=this;if(!e||e.tagName?.toLowerCase()!=="input"||(e.type??"").toLowerCase()!=="file")return!1;let c=(()=>{try{return new DataTransfer}catch{return null}})();if(!c)return!1;let n=Array.isArray(t)?t:[];for(let o of n){if(!o)continue;let y=o.name||"upload.bin",u=o.mimeType||"application/octet-stream",a=typeof o.lastModified=="number"?o.lastModified:Date.now(),l=window.atob(o.base64??""),i=new Uint8Array(l.length);for(let s=0;s<l.length;s+=1)i[s]=l.charCodeAt(s);let f=new Blob([i],{type:u}),h=new File([f],y,{type:u,lastModified:a});c.items.add(h)}return e.files=c.files,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),!0}catch{return!1}}function W(t){let e=t??{};try{let c=new MouseEvent("click",{bubbles:!!e.bubbles,cancelable:!!e.cancelable,composed:!!e.composed,detail:typeof e.detail=="number"?e.detail:1,view:this?.ownerDocument?.defaultView??window});this.dispatchEvent(c)}catch{try{this.click()}catch{}}}function q(t){let e=c=>{if(typeof c=="number"&&Number.isFinite(c))return c;let n=String(c??"").trim();if(!n)return 0;let o=parseFloat(n.replace("%",""));return Number.isNaN(o)||!Number.isFinite(o)?0:o};try{let c=Math.max(0,Math.min(e(t),100)),n=this,o=n.tagName?.toLowerCase()??"";if(o==="html"||o==="body"){let h=(n.ownerDocument?.scrollingElement||n.ownerDocument?.documentElement||n.ownerDocument?.body||document.scrollingElement||document.documentElement||document.body)?.scrollHeight??document.body.scrollHeight??0,s=n.ownerDocument?.defaultView?.innerHeight??window.innerHeight,g=Math.max(0,h-s)*(c/100);return n.ownerDocument?.defaultView?.scrollTo({top:g,left:n.ownerDocument?.defaultView?.scrollX??window.scrollX??0,behavior:"smooth"}),!0}let u=n.scrollHeight??0,a=n.clientHeight??0,i=Math.max(0,u-a)*(c/100);return n.scrollTo({top:i,left:n.scrollLeft??0,behavior:"smooth"}),!0}catch{return!1}}var v=new Set(["color","date","datetime-local","month","range","time","week"]),P=new Set(["","email","number","password","search","tel","text","url"]);function T(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument||document,c=e.defaultView||window;try{typeof t.focus=="function"&&t.focus()}catch{}if(t instanceof c.HTMLInputElement||t instanceof c.HTMLTextAreaElement){try{if(typeof t.select=="function")return t.select(),!0}catch{}try{let n=(t.value??"").length;if(typeof t.setSelectionRange=="function")return t.setSelectionRange(0,n),!0}catch{}return!0}if(t.isContentEditable){let n=e.getSelection?.(),o=e.createRange?.();if(n&&o)try{o.selectNodeContents(t),n.removeAllRanges(),n.addRange(o)}catch{}return!0}return!1}catch{return!1}}function O(t){let e=this;if(!e.isConnected)return{status:"error",reason:"notconnected"};let n=(e.ownerDocument||document).defaultView||window,o=t??"";try{let y=u=>{let a;if(typeof n.InputEvent=="function")try{a=new n.InputEvent("input",{bubbles:!0,composed:!0,data:u,inputType:"insertText"})}catch{a=new n.Event("input",{bubbles:!0,composed:!0})}else a=new n.Event("input",{bubbles:!0,composed:!0});e.dispatchEvent(a);let l=new n.Event("change",{bubbles:!0});e.dispatchEvent(l)};if(e instanceof n.HTMLInputElement){let u=(e.type||"").toLowerCase();if(!P.has(u)&&!v.has(u))return{status:"error",reason:`unsupported-input-type:${u}`};let a=t;if(u==="number"){let l=t.trim();if(l!==""&&Number.isNaN(Number(l)))return{status:"error",reason:"invalid-number-value"};a=l}if(o=a,v.has(u)){let l=t.trim();o=l,T.call(e);let i=n.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(i,"value")?.set;return typeof h=="function"?h.call(e,l):e.value=l,e._valueTracker?.setValue?.(l),e.value!==l?{status:"error",reason:"malformed-value"}:(y(l),{status:"done"})}return T.call(e),{status:"needsinput",value:a}}return e instanceof n.HTMLTextAreaElement?(T.call(e),o=t,{status:"needsinput",value:t}):e instanceof n.HTMLSelectElement?{status:"error",reason:"unsupported-element"}:e.isContentEditable?(T.call(e),o=t,{status:"needsinput",value:t}):{status:"error",reason:"unsupported-element"}}catch(y){let u="exception";if(y&&typeof y=="object"){let a=y.message;typeof a=="string"&&a.trim().length>0&&(u=`exception:${a}`)}return{status:"needsinput",value:o,reason:u}}}function V(){try{typeof this.focus=="function"&&this.focus()}catch{}}function X(t){try{if(!(this instanceof HTMLSelectElement))return[];let e=Array.isArray(t)?t:[t],c=new Set(e.map(u=>String(u??"").trim())),n=u=>{let a=(u.label||u.textContent||"").trim(),l=String(u.value??"").trim();return c.has(a)||c.has(l)};if(this.multiple)for(let u of Array.from(this.options))u.selected=n(u);else{let u=!1;for(let a of Array.from(this.options))!u&&n(a)?(a.selected=!0,this.value=a.value,u=!0):a.selected=!1}let o=new Event("input",{bubbles:!0}),y=new Event("change",{bubbles:!0});return this.dispatchEvent(o),this.dispatchEvent(y),Array.from(this.selectedOptions).map(u=>u.value)}catch{return[]}}function Y(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument?.defaultView?.getComputedStyle(t)??window.getComputedStyle(t);if(!e||e.display==="none"||e.visibility==="hidden")return!1;let c=parseFloat(e.opacity??"1");if(!Number.isFinite(c)||c===0)return!1;let n=t.getBoundingClientRect();return!(!n||Math.max(n.width,n.height)===0||t.getClientRects().length===0)}catch{return!1}}function B(){try{let t=this;if((t.tagName||"").toLowerCase()==="input"){let n=t.type?.toLowerCase()??"";if(n==="checkbox"||n==="radio")return!!t.checked}let c=t.getAttribute?.("aria-checked");return c!=null?c==="true":!1}catch{return!1}}function $(){try{let t=this,e=(t.tagName||"").toLowerCase();return e==="input"||e==="textarea"||e==="select"?String(t.value??""):t.isContentEditable?String(t.textContent??""):""}catch{return""}}function z(){try{return String(this.textContent??"")}catch{return""}}function U(){try{return String(this.innerHTML??"")}catch{return""}}function j(){try{let t=this,e=t.innerText;if(typeof e=="string"&&e.length>0)return e;let c=t.textContent;return typeof c=="string"?c:""}catch{return""}}var N=t=>{let e=Number(t??0);return!Number.isFinite(e)||e<0?0:Math.floor(e)},M=(t,e)=>{if(!t)return[];let c=new WeakSet,n=new Set,o=[],y=[document],u=a=>{if(!(!a||c.has(a)||o.length>=e)){c.add(a);try{let l=a.querySelectorAll(t);for(let i of l)if(!n.has(i)&&(n.add(i),o.push(i),o.length>=e))return}catch{}try{let i=(a instanceof Document?a:a.host?.ownerDocument??document).createTreeWalker(a,NodeFilter.SHOW_ELEMENT),f;for(;f=i.nextNode();){if(!(f instanceof Element))continue;let h=f.shadowRoot;h&&y.push(h)}}catch{}}};for(;y.length&&o.length<e;){let a=y.shift();a&&u(a)}return o};function K(t,e){let c=String(t??"").trim();if(!c)return null;let n=N(e);return M(c,n+1)[n]??null}function G(t,e){let c=String(t??"").trim();if(!c)return null;let n=N(e),o=window.__stagehandV3__;if(!o||typeof o.getClosedRoot!="function")return M(c,n+1)[n]??null;let y=h=>{try{return o.getClosedRoot(h)??null}catch{return null}},u=new WeakSet,a=new Set,l=[],i=[document],f=h=>{if(!(!h||u.has(h)||l.length>=n+1)){u.add(h);try{let s=h.querySelectorAll(c);for(let d of s)if(!a.has(d)&&(a.add(d),l.push(d),l.length>=n+1))return}catch{}try{let d=(h instanceof Document?h:h.host?.ownerDocument??document).createTreeWalker(h,NodeFilter.SHOW_ELEMENT),g;for(;g=d.nextNode();){if(!(g instanceof Element))continue;let w=g.shadowRoot;w&&i.push(w);let E=y(g);E&&i.push(E)}}catch{}}};for(;i.length&&l.length<n+1;){let h=i.shift();h&&f(h)}return l[n]??null}function J(t,e){let c=String(t??"");if(!c)return null;let n=c.toLowerCase(),o=N(e),y=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),u=r=>{if(!r)return!1;let p=r.tagName?.toUpperCase()??"";return y.has(p)},a=r=>{try{if(u(r))return"";let p=r.innerText;if(typeof p=="string"&&p.trim())return p.trim()}catch{}try{let p=r.textContent;if(typeof p=="string")return p.trim()}catch{}return""},l=r=>{let p=a(r);return!!p&&p.toLowerCase().includes(n)},i=window.__stagehandV3__,f=i&&typeof i.getClosedRoot=="function"?r=>{try{return i.getClosedRoot(r)??null}catch{return null}}:r=>null,h=new WeakSet,s=[],d=[],g=r=>{!r||h.has(r)||(h.add(r),s.push(r))},w=r=>{try{return(r instanceof Document?r:r?.ownerDocument??document).createTreeWalker(r,NodeFilter.SHOW_ELEMENT)}catch{return null}};for(g(document);s.length;){let r=s.shift();if(!r)continue;r instanceof Element&&l(r)&&d.push({element:r,tag:r.tagName??"",id:r.id??"",className:r.className??"",text:a(r)});let p=w(r);if(!p)continue;let x;for(;x=p.nextNode();){if(!(x instanceof Element))continue;l(x)&&d.push({element:x,tag:x.tagName??"",id:x.id??"",className:x.className??"",text:a(x)});let b=x.shadowRoot;b&&g(b);let S=f(x);S&&g(S)}}let E=[];for(let r of d){let p=r.element,x=!1;for(let b of d)if(r!==b)try{if(p.contains(b.element)){x=!0;break}}catch{}x||E.push(r)}return E[o]?.element??null}function Q(t,e){let c=String(t??"").trim();if(!c)return null;let n=N(e),o=window.__stagehandV3__;if(n===0){try{if(o&&typeof o.resolveSimpleXPath=="function"){let s=o.resolveSimpleXPath(c);if(s)return s}}catch{}try{return document.evaluate(c,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{}}let u=(s=>{let d=String(s||"").trim();if(!d)return[];let g=d.replace(/^xpath=/i,""),w=[],E=0;for(;E<g.length;){let m="child";g.startsWith("//",E)?(m="desc",E+=2):g[E]==="/"&&(m="child",E+=1);let r=E;for(;E<g.length&&g[E]!=="/";)E+=1;let p=g.slice(r,E).trim();if(!p)continue;let x=p.match(/^(.*?)(\\[(\\d+)\\])?$/u),b=(x?.[1]??p).trim(),S=x?.[3]?Math.max(1,Number(x[3])):null,C=b===""?"*":b.toLowerCase();w.push({axis:m,tag:C,index:S})}return w})(c);if(!u.length)return null;let a=o&&typeof o.getClosedRoot=="function"?s=>{try{return o.getClosedRoot(s)??null}catch{return null}}:s=>null,l=s=>{let d=[];if(!s)return d;if(s instanceof Document)return s.documentElement&&d.push(s.documentElement),d;if(s instanceof ShadowRoot||s instanceof DocumentFragment)return d.push(...Array.from(s.children??[])),d;if(s instanceof Element){d.push(...Array.from(s.children??[]));let g=s.shadowRoot;g&&d.push(...Array.from(g.children??[]));let w=a(s);return w&&d.push(...Array.from(w.children??[])),d}return d},i=s=>{let d=[],g=new Set,w=[...l(s)];for(;w.length;){let E=w.shift();!E||g.has(E)||(g.add(E),d.push(E),w.push(...l(E)))}return d},f=[document];for(let s of u){let d=[],g=new Set;for(let w of f){if(!w)continue;let E=s.axis==="child"?l(w):i(w);if(!E.length)continue;let m=E.filter(r=>r instanceof Element?s.tag==="*"?!0:r.localName===s.tag:!1);if(s.index!=null){let r=s.index-1,p=r>=0&&r<m.length?m[r]:null;p&&!g.has(p)&&(g.add(p),d.push(p))}else for(let r of m)g.has(r)||(g.add(r),d.push(r))}if(!d.length)return null;f=d}return f[n]??null}function Z(t){let e=String(t??"").trim();if(!e)return 0;let c=new WeakSet,n=o=>{if(!o||c.has(o))return 0;c.add(o);let y=0;try{let u=o;typeof u.querySelectorAll=="function"&&(y+=u.querySelectorAll(e).length)}catch{}try{let a=(o instanceof Document?o:o?.ownerDocument??document).createTreeWalker(o,NodeFilter.SHOW_ELEMENT),l;for(;l=a.nextNode();)l instanceof Element&&l.shadowRoot&&(y+=n(l.shadowRoot))}catch{}return y};try{return n(document)}catch{try{return document.querySelectorAll(e).length}catch{return 0}}}function ee(t){let e=String(t??"").trim();if(!e)return 0;let c=window.__stagehandV3__;if(!c||typeof c.getClosedRoot!="function")try{return document.querySelectorAll(e).length}catch{return 0}let n=new WeakSet,o=[],y=l=>{!l||n.has(l)||(n.add(l),o.push(l))};y(document);let u=0,a=l=>{let i=l.shadowRoot;i&&y(i);try{let f=c.getClosedRoot(l);f&&y(f)}catch{}};for(;o.length;){let l=o.shift();if(l){try{let i=l;typeof i.querySelectorAll=="function"&&(u+=i.querySelectorAll(e).length)}catch{}try{let f=(l instanceof Document?l:l instanceof ShadowRoot?l.host?.ownerDocument??document:l.ownerDocument??document).createTreeWalker(l,NodeFilter.SHOW_ELEMENT),h;for(;h=f.nextNode();)h instanceof Element&&a(h)}catch{}}}return u}function te(t){let e=String(t??"");if(!e)return{count:0,sample:[],error:null};let c=e.toLowerCase(),n=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),o=m=>{if(!m)return!1;let r=m.tagName?.toUpperCase()??"";return n.has(r)},y=m=>{try{if(o(m))return"";let r=m.innerText;if(typeof r=="string"&&r.trim())return r.trim()}catch{}try{let r=m.textContent;if(typeof r=="string")return r.trim()}catch{}return""},u=m=>{let r=y(m);return!!r&&r.toLowerCase().includes(c)},a=window.__stagehandV3__,l=a&&typeof a.getClosedRoot=="function"?m=>{try{return a.getClosedRoot(m)??null}catch{return null}}:m=>null,i=new WeakSet,f=[],h=m=>{!m||i.has(m)||(i.add(m),f.push(m))},s=m=>{try{return(m instanceof Document?m:m?.ownerDocument??document).createTreeWalker(m,NodeFilter.SHOW_ELEMENT)}catch{return null}},d=[];for(h(document);f.length;){let m=f.shift();if(!m)continue;m instanceof Element&&u(m)&&d.push({element:m,tag:m.tagName??"",id:m.id??"",className:m.className??"",text:y(m)});let r=s(m);if(!r)continue;let p;for(;p=r.nextNode();){if(!(p instanceof Element))continue;u(p)&&d.push({element:p,tag:p.tagName??"",id:p.id??"",className:p.className??"",text:y(p)});let x=p.shadowRoot;x&&h(x);let b=l(p);b&&h(b)}}let g=[];for(let m of d){let r=m.element,p=!1;for(let x of d)if(m!==x)try{if(r.contains(x.element)){p=!0;break}}catch{}p||g.push(m)}let w=g.length,E=g.slice(0,5).map(m=>({tag:m.tag,id:m.id,class:m.className,text:m.text}));return{count:w,sample:E,error:null}}function ne(t){let e=String(t??"").trim();if(!e)return 0;let n=(i=>{let f=String(i||"").trim().replace(/^xpath=/i,"");if(!f)return[];let h=[],s=0;for(;s<f.length;){let d="child";f.startsWith("//",s)?(d="desc",s+=2):f[s]==="/"&&(d="child",s+=1);let g=s;for(;s<f.length&&f[s]!=="/";)s+=1;let w=f.slice(g,s).trim();if(!w)continue;let E=w.match(/^(.*?)(\\[(\\d+)\\])?$/u),m=(E?.[1]??w).trim(),r=E?.[3]?Math.max(1,Number(E[3])):null,p=m===""?"*":m.toLowerCase();h.push({axis:d,tag:p,index:r})}return h})(e);if(!n.length)return 0;let o=window.__stagehandV3__,y=o&&typeof o.getClosedRoot=="function"?i=>{try{return o.getClosedRoot(i)??null}catch{return null}}:i=>null,u=i=>{let f=[];if(!i)return f;if(i instanceof Document)return i.documentElement&&f.push(i.documentElement),f;if(i instanceof ShadowRoot||i instanceof DocumentFragment)return f.push(...Array.from(i.children??[])),f;if(i instanceof Element){f.push(...Array.from(i.children??[]));let h=i.shadowRoot;h&&f.push(...Array.from(h.children??[]));let s=y(i);return s&&f.push(...Array.from(s.children??[])),f}return f},a=i=>{let f=[],h=new Set,s=[...u(i)];for(;s.length;){let d=s.shift();!d||h.has(d)||(h.add(d),f.push(d),s.push(...u(d)))}return f},l=[document];for(let i of n){let f=[],h=new Set;for(let s of l){if(!s)continue;let d=i.axis==="child"?u(s):a(s);if(!d.length)continue;let g=d.filter(w=>w instanceof Element?i.tag==="*"?!0:w.localName===i.tag:!1);if(i.index!=null){let w=i.index-1,E=w>=0&&w<g.length?g[w]:null;E&&!h.has(E)&&(h.add(E),f.push(E))}else for(let w of g)h.has(w)||(h.add(w),f.push(w))}if(!f.length)return 0;l=f}return l.length}return _(oe);})();\n globalThis.__stagehandLocatorScripts = __stagehandLocatorScriptsFactory;\n}';
1852
1852
  locatorScriptSources = {
1853
- "countCssMatchesPierce": 'function U(t){let e=String(t??"").trim();if(!e)return 0;let i=window.__stagehandV3__;if(!i||typeof i.getClosedRoot!="function")try{return document.querySelectorAll(e).length}catch{return 0}let n=new WeakSet,l=[],y=s=>{!s||n.has(s)||(n.add(s),l.push(s))};y(document);let f=0,u=s=>{let c=s.shadowRoot;c&&y(c);try{let h=i.getClosedRoot(s);h&&y(h)}catch{}};for(;l.length;){let s=l.shift();if(s){try{let c=s;typeof c.querySelectorAll=="function"&&(f+=c.querySelectorAll(e).length)}catch{}try{let h=(s instanceof Document?s:s instanceof ShadowRoot?s.host?.ownerDocument??document:s.ownerDocument??document).createTreeWalker(s,NodeFilter.SHOW_ELEMENT),d;for(;d=h.nextNode();)d instanceof Element&&u(d)}catch{}}}return f}',
1854
- "countCssMatchesPrimary": 'function K(t){let e=String(t??"").trim();if(!e)return 0;let i=new WeakSet,n=l=>{if(!l||i.has(l))return 0;i.add(l);let y=0;try{let f=l;typeof f.querySelectorAll=="function"&&(y+=f.querySelectorAll(e).length)}catch{}try{let u=(l instanceof Document?l:l?.ownerDocument??document).createTreeWalker(l,NodeFilter.SHOW_ELEMENT),s;for(;s=u.nextNode();)s instanceof Element&&s.shadowRoot&&(y+=n(s.shadowRoot))}catch{}return y};try{return n(document)}catch{try{return document.querySelectorAll(e).length}catch{return 0}}}',
1855
- "countTextMatches": 'function z(t){let e=String(t??"");if(!e)return{count:0,sample:[],error:null};let i=e.toLowerCase(),n=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),l=a=>{if(!a)return!1;let o=a.tagName?.toUpperCase()??"";return n.has(o)},y=a=>{try{if(l(a))return"";let o=a.innerText;if(typeof o=="string"&&o.trim())return o.trim()}catch{}try{let o=a.textContent;if(typeof o=="string")return o.trim()}catch{}return""},f=a=>{let o=y(a);return!!o&&o.toLowerCase().includes(i)},u=window.__stagehandV3__,s=u&&typeof u.getClosedRoot=="function"?a=>{try{return u.getClosedRoot(a)??null}catch{return null}}:a=>null,c=new WeakSet,h=[],d=a=>{!a||c.has(a)||(c.add(a),h.push(a))},r=a=>{try{return(a instanceof Document?a:a?.ownerDocument??document).createTreeWalker(a,NodeFilter.SHOW_ELEMENT)}catch{return null}},m=[];for(d(document);h.length;){let a=h.shift();if(!a)continue;a instanceof Element&&f(a)&&m.push({element:a,tag:a.tagName??"",id:a.id??"",className:a.className??"",text:y(a)});let o=r(a);if(!o)continue;let p;for(;p=o.nextNode();){if(!(p instanceof Element))continue;f(p)&&m.push({element:p,tag:p.tagName??"",id:p.id??"",className:p.className??"",text:y(p)});let x=p.shadowRoot;x&&d(x);let S=s(p);S&&d(S)}}let g=[];for(let a of m){let o=a.element,p=!1;for(let x of m)if(a!==x)try{if(o.contains(x.element)){p=!0;break}}catch{}p||g.push(a)}let w=g.length,E=g.slice(0,5).map(a=>({tag:a.tag,id:a.id,class:a.className,text:a.text}));return{count:w,sample:E,error:null}}',
1856
- "countXPathMatchesMainWorld": 'function G(t){let e=String(t??"").trim();if(!e)return 0;let n=(c=>{let h=String(c||"").trim().replace(/^xpath=/i,"");if(!h)return[];let d=[],r=0;for(;r<h.length;){let m="child";h.startsWith("//",r)?(m="desc",r+=2):h[r]==="/"&&(m="child",r+=1);let g=r;for(;r<h.length&&h[r]!=="/";)r+=1;let w=h.slice(g,r).trim();if(!w)continue;let E=w.match(/^(.*?)(\\[(\\d+)\\])?$/u),a=(E?.[1]??w).trim(),o=E?.[3]?Math.max(1,Number(E[3])):null,p=a===""?"*":a.toLowerCase();d.push({axis:m,tag:p,index:o})}return d})(e);if(!n.length)return 0;let l=window.__stagehandV3__,y=l&&typeof l.getClosedRoot=="function"?c=>{try{return l.getClosedRoot(c)??null}catch{return null}}:c=>null,f=c=>{let h=[];if(!c)return h;if(c instanceof Document)return c.documentElement&&h.push(c.documentElement),h;if(c instanceof ShadowRoot||c instanceof DocumentFragment)return h.push(...Array.from(c.children??[])),h;if(c instanceof Element){h.push(...Array.from(c.children??[]));let d=c.shadowRoot;d&&h.push(...Array.from(d.children??[]));let r=y(c);return r&&h.push(...Array.from(r.children??[])),h}return h},u=c=>{let h=[],d=new Set,r=[...f(c)];for(;r.length;){let m=r.shift();!m||d.has(m)||(d.add(m),h.push(m),r.push(...f(m)))}return h},s=[document];for(let c of n){let h=[],d=new Set;for(let r of s){if(!r)continue;let m=c.axis==="child"?f(r):u(r);if(!m.length)continue;let g=m.filter(w=>w instanceof Element?c.tag==="*"?!0:w.localName===c.tag:!1);if(c.index!=null){let w=c.index-1,E=w>=0&&w<g.length?g[w]:null;E&&!d.has(E)&&(d.add(E),h.push(E))}else for(let w of g)d.has(w)||(d.add(w),h.push(w))}if(!h.length)return 0;s=h}return s.length}',
1857
- "dispatchDomClick": 'function k(t){let e=t??{};try{let i=new MouseEvent("click",{bubbles:!!e.bubbles,cancelable:!!e.cancelable,composed:!!e.composed,detail:typeof e.detail=="number"?e.detail:1,view:this?.ownerDocument?.defaultView??window});this.dispatchEvent(i)}catch{try{this.click()}catch{}}}',
1858
- "ensureFileInputElement": 'function C(){try{return(this.tagName?.toLowerCase()??"")!=="input"?!1:String(this.type??"").toLowerCase()==="file"}catch{return!1}}',
1859
- "fillElementValue": 'function D(t){let e=this;if(!e.isConnected)return{status:"error",reason:"notconnected"};let n=(e.ownerDocument||document).defaultView||window,l=t??"";try{let y=f=>{let u;if(typeof n.InputEvent=="function")try{u=new n.InputEvent("input",{bubbles:!0,composed:!0,data:f,inputType:"insertText"})}catch{u=new n.Event("input",{bubbles:!0,composed:!0})}else u=new n.Event("input",{bubbles:!0,composed:!0});e.dispatchEvent(u);let s=new n.Event("change",{bubbles:!0});e.dispatchEvent(s)};if(e instanceof n.HTMLInputElement){let f=(e.type||"").toLowerCase();if(!M.has(f)&&!L.has(f))return{status:"error",reason:`unsupported-input-type:${f}`};let u=t;if(f==="number"){let s=t.trim();if(s!==""&&Number.isNaN(Number(s)))return{status:"error",reason:"invalid-number-value"};u=s}if(l=u,L.has(f)){let s=t.trim();l=s,T.call(e);let c=n.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value")?.set;return typeof d=="function"?d.call(e,s):e.value=s,e._valueTracker?.setValue?.(s),e.value!==s?{status:"error",reason:"malformed-value"}:(y(s),{status:"done"})}return T.call(e),{status:"needsinput",value:u}}return e instanceof n.HTMLTextAreaElement?(T.call(e),l=t,{status:"needsinput",value:t}):e instanceof n.HTMLSelectElement?{status:"error",reason:"unsupported-element"}:e.isContentEditable?(T.call(e),l=t,{status:"needsinput",value:t}):{status:"error",reason:"unsupported-element"}}catch(y){let f="exception";if(y&&typeof y=="object"){let u=y.message;typeof u=="string"&&u.trim().length>0&&(f=`exception:${u}`)}return{status:"needsinput",value:l,reason:f}}}',
1860
- "focusElement": 'function A(){try{typeof this.focus=="function"&&this.focus()}catch{}}',
1853
+ "assignFilePayloadsToInputElement": 'function k(t){try{let e=this;if(!e||e.tagName?.toLowerCase()!=="input"||(e.type??"").toLowerCase()!=="file")return!1;let i=(()=>{try{return new DataTransfer}catch{return null}})();if(!i)return!1;let n=Array.isArray(t)?t:[];for(let s of n){if(!s)continue;let y=s.name||"upload.bin",u=s.mimeType||"application/octet-stream",a=typeof s.lastModified=="number"?s.lastModified:Date.now(),l=window.atob(s.base64??""),c=new Uint8Array(l.length);for(let r=0;r<l.length;r+=1)c[r]=l.charCodeAt(r);let f=new Blob([c],{type:u}),h=new File([f],y,{type:u,lastModified:a});i.items.add(h)}return e.files=i.files,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),!0}catch{return!1}}',
1854
+ "countCssMatchesPierce": 'function K(t){let e=String(t??"").trim();if(!e)return 0;let i=window.__stagehandV3__;if(!i||typeof i.getClosedRoot!="function")try{return document.querySelectorAll(e).length}catch{return 0}let n=new WeakSet,s=[],y=l=>{!l||n.has(l)||(n.add(l),s.push(l))};y(document);let u=0,a=l=>{let c=l.shadowRoot;c&&y(c);try{let f=i.getClosedRoot(l);f&&y(f)}catch{}};for(;s.length;){let l=s.shift();if(l){try{let c=l;typeof c.querySelectorAll=="function"&&(u+=c.querySelectorAll(e).length)}catch{}try{let f=(l instanceof Document?l:l instanceof ShadowRoot?l.host?.ownerDocument??document:l.ownerDocument??document).createTreeWalker(l,NodeFilter.SHOW_ELEMENT),h;for(;h=f.nextNode();)h instanceof Element&&a(h)}catch{}}}return u}',
1855
+ "countCssMatchesPrimary": 'function j(t){let e=String(t??"").trim();if(!e)return 0;let i=new WeakSet,n=s=>{if(!s||i.has(s))return 0;i.add(s);let y=0;try{let u=s;typeof u.querySelectorAll=="function"&&(y+=u.querySelectorAll(e).length)}catch{}try{let a=(s instanceof Document?s:s?.ownerDocument??document).createTreeWalker(s,NodeFilter.SHOW_ELEMENT),l;for(;l=a.nextNode();)l instanceof Element&&l.shadowRoot&&(y+=n(l.shadowRoot))}catch{}return y};try{return n(document)}catch{try{return document.querySelectorAll(e).length}catch{return 0}}}',
1856
+ "countTextMatches": 'function G(t){let e=String(t??"");if(!e)return{count:0,sample:[],error:null};let i=e.toLowerCase(),n=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),s=m=>{if(!m)return!1;let o=m.tagName?.toUpperCase()??"";return n.has(o)},y=m=>{try{if(s(m))return"";let o=m.innerText;if(typeof o=="string"&&o.trim())return o.trim()}catch{}try{let o=m.textContent;if(typeof o=="string")return o.trim()}catch{}return""},u=m=>{let o=y(m);return!!o&&o.toLowerCase().includes(i)},a=window.__stagehandV3__,l=a&&typeof a.getClosedRoot=="function"?m=>{try{return a.getClosedRoot(m)??null}catch{return null}}:m=>null,c=new WeakSet,f=[],h=m=>{!m||c.has(m)||(c.add(m),f.push(m))},r=m=>{try{return(m instanceof Document?m:m?.ownerDocument??document).createTreeWalker(m,NodeFilter.SHOW_ELEMENT)}catch{return null}},d=[];for(h(document);f.length;){let m=f.shift();if(!m)continue;m instanceof Element&&u(m)&&d.push({element:m,tag:m.tagName??"",id:m.id??"",className:m.className??"",text:y(m)});let o=r(m);if(!o)continue;let p;for(;p=o.nextNode();){if(!(p instanceof Element))continue;u(p)&&d.push({element:p,tag:p.tagName??"",id:p.id??"",className:p.className??"",text:y(p)});let x=p.shadowRoot;x&&h(x);let b=l(p);b&&h(b)}}let g=[];for(let m of d){let o=m.element,p=!1;for(let x of d)if(m!==x)try{if(o.contains(x.element)){p=!0;break}}catch{}p||g.push(m)}let w=g.length,E=g.slice(0,5).map(m=>({tag:m.tag,id:m.id,class:m.className,text:m.text}));return{count:w,sample:E,error:null}}',
1857
+ "countXPathMatchesMainWorld": 'function J(t){let e=String(t??"").trim();if(!e)return 0;let n=(c=>{let f=String(c||"").trim().replace(/^xpath=/i,"");if(!f)return[];let h=[],r=0;for(;r<f.length;){let d="child";f.startsWith("//",r)?(d="desc",r+=2):f[r]==="/"&&(d="child",r+=1);let g=r;for(;r<f.length&&f[r]!=="/";)r+=1;let w=f.slice(g,r).trim();if(!w)continue;let E=w.match(/^(.*?)(\\[(\\d+)\\])?$/u),m=(E?.[1]??w).trim(),o=E?.[3]?Math.max(1,Number(E[3])):null,p=m===""?"*":m.toLowerCase();h.push({axis:d,tag:p,index:o})}return h})(e);if(!n.length)return 0;let s=window.__stagehandV3__,y=s&&typeof s.getClosedRoot=="function"?c=>{try{return s.getClosedRoot(c)??null}catch{return null}}:c=>null,u=c=>{let f=[];if(!c)return f;if(c instanceof Document)return c.documentElement&&f.push(c.documentElement),f;if(c instanceof ShadowRoot||c instanceof DocumentFragment)return f.push(...Array.from(c.children??[])),f;if(c instanceof Element){f.push(...Array.from(c.children??[]));let h=c.shadowRoot;h&&f.push(...Array.from(h.children??[]));let r=y(c);return r&&f.push(...Array.from(r.children??[])),f}return f},a=c=>{let f=[],h=new Set,r=[...u(c)];for(;r.length;){let d=r.shift();!d||h.has(d)||(h.add(d),f.push(d),r.push(...u(d)))}return f},l=[document];for(let c of n){let f=[],h=new Set;for(let r of l){if(!r)continue;let d=c.axis==="child"?u(r):a(r);if(!d.length)continue;let g=d.filter(w=>w instanceof Element?c.tag==="*"?!0:w.localName===c.tag:!1);if(c.index!=null){let w=c.index-1,E=w>=0&&w<g.length?g[w]:null;E&&!h.has(E)&&(h.add(E),f.push(E))}else for(let w of g)h.has(w)||(h.add(w),f.push(w))}if(!f.length)return 0;l=f}return l.length}',
1858
+ "dispatchDomClick": 'function H(t){let e=t??{};try{let i=new MouseEvent("click",{bubbles:!!e.bubbles,cancelable:!!e.cancelable,composed:!!e.composed,detail:typeof e.detail=="number"?e.detail:1,view:this?.ownerDocument?.defaultView??window});this.dispatchEvent(i)}catch{try{this.click()}catch{}}}',
1859
+ "ensureFileInputElement": 'function R(){try{return(this.tagName?.toLowerCase()??"")!=="input"?!1:String(this.type??"").toLowerCase()==="file"}catch{return!1}}',
1860
+ "fillElementValue": 'function A(t){let e=this;if(!e.isConnected)return{status:"error",reason:"notconnected"};let n=(e.ownerDocument||document).defaultView||window,s=t??"";try{let y=u=>{let a;if(typeof n.InputEvent=="function")try{a=new n.InputEvent("input",{bubbles:!0,composed:!0,data:u,inputType:"insertText"})}catch{a=new n.Event("input",{bubbles:!0,composed:!0})}else a=new n.Event("input",{bubbles:!0,composed:!0});e.dispatchEvent(a);let l=new n.Event("change",{bubbles:!0});e.dispatchEvent(l)};if(e instanceof n.HTMLInputElement){let u=(e.type||"").toLowerCase();if(!C.has(u)&&!L.has(u))return{status:"error",reason:`unsupported-input-type:${u}`};let a=t;if(u==="number"){let l=t.trim();if(l!==""&&Number.isNaN(Number(l)))return{status:"error",reason:"invalid-number-value"};a=l}if(s=a,L.has(u)){let l=t.trim();s=l,S.call(e);let c=n.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(c,"value")?.set;return typeof h=="function"?h.call(e,l):e.value=l,e._valueTracker?.setValue?.(l),e.value!==l?{status:"error",reason:"malformed-value"}:(y(l),{status:"done"})}return S.call(e),{status:"needsinput",value:a}}return e instanceof n.HTMLTextAreaElement?(S.call(e),s=t,{status:"needsinput",value:t}):e instanceof n.HTMLSelectElement?{status:"error",reason:"unsupported-element"}:e.isContentEditable?(S.call(e),s=t,{status:"needsinput",value:t}):{status:"error",reason:"unsupported-element"}}catch(y){let u="exception";if(y&&typeof y=="object"){let a=y.message;typeof a=="string"&&a.trim().length>0&&(u=`exception:${a}`)}return{status:"needsinput",value:s,reason:u}}}',
1861
+ "focusElement": 'function _(){try{typeof this.focus=="function"&&this.focus()}catch{}}',
1861
1862
  "isElementChecked": 'function W(){try{let t=this;if((t.tagName||"").toLowerCase()==="input"){let n=t.type?.toLowerCase()??"";if(n==="checkbox"||n==="radio")return!!t.checked}let i=t.getAttribute?.("aria-checked");return i!=null?i==="true":!1}catch{return!1}}',
1862
- "isElementVisible": 'function I(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument?.defaultView?.getComputedStyle(t)??window.getComputedStyle(t);if(!e||e.display==="none"||e.visibility==="hidden")return!1;let i=parseFloat(e.opacity??"1");if(!Number.isFinite(i)||i===0)return!1;let n=t.getBoundingClientRect();return!(!n||Math.max(n.width,n.height)===0||t.getClientRects().length===0)}catch{return!1}}',
1863
- "prepareElementForTyping": 'function T(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument||document,i=e.defaultView||window;try{typeof t.focus=="function"&&t.focus()}catch{}if(t instanceof i.HTMLInputElement||t instanceof i.HTMLTextAreaElement){try{if(typeof t.select=="function")return t.select(),!0}catch{}try{let n=(t.value??"").length;if(typeof t.setSelectionRange=="function")return t.setSelectionRange(0,n),!0}catch{}return!0}if(t.isContentEditable){let n=e.getSelection?.(),l=e.createRange?.();if(n&&l)try{l.selectNodeContents(t),n.removeAllRanges(),n.addRange(l)}catch{}return!0}return!1}catch{return!1}}',
1863
+ "isElementVisible": 'function F(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument?.defaultView?.getComputedStyle(t)??window.getComputedStyle(t);if(!e||e.display==="none"||e.visibility==="hidden")return!1;let i=parseFloat(e.opacity??"1");if(!Number.isFinite(i)||i===0)return!1;let n=t.getBoundingClientRect();return!(!n||Math.max(n.width,n.height)===0||t.getClientRects().length===0)}catch{return!1}}',
1864
+ "prepareElementForTyping": 'function S(){try{let t=this;if(!t.isConnected)return!1;let e=t.ownerDocument||document,i=e.defaultView||window;try{typeof t.focus=="function"&&t.focus()}catch{}if(t instanceof i.HTMLInputElement||t instanceof i.HTMLTextAreaElement){try{if(typeof t.select=="function")return t.select(),!0}catch{}try{let n=(t.value??"").length;if(typeof t.setSelectionRange=="function")return t.setSelectionRange(0,n),!0}catch{}return!0}if(t.isContentEditable){let n=e.getSelection?.(),s=e.createRange?.();if(n&&s)try{s.selectNodeContents(t),n.removeAllRanges(),n.addRange(s)}catch{}return!0}return!1}catch{return!1}}',
1864
1865
  "readElementInnerHTML": 'function O(){try{return String(this.innerHTML??"")}catch{return""}}',
1865
- "readElementInnerText": 'function P(){try{let t=this,e=t.innerText;if(typeof e=="string"&&e.length>0)return e;let i=t.textContent;return typeof i=="string"?i:""}catch{return""}}',
1866
+ "readElementInnerText": 'function V(){try{let t=this,e=t.innerText;if(typeof e=="string"&&e.length>0)return e;let i=t.textContent;return typeof i=="string"?i:""}catch{return""}}',
1866
1867
  "readElementInputValue": 'function q(){try{let t=this,e=(t.tagName||"").toLowerCase();return e==="input"||e==="textarea"||e==="select"?String(t.value??""):t.isContentEditable?String(t.textContent??""):""}catch{return""}}',
1867
- "readElementTextContent": 'function F(){try{return String(this.textContent??"")}catch{return""}}',
1868
- "resolveCssSelector": 'function X(t,e){let i=String(t??"").trim();if(!i)return null;let n=N(e);return R(i,n+1)[n]??null}',
1869
- "resolveCssSelectorPierce": 'function Y(t,e){let i=String(t??"").trim();if(!i)return null;let n=N(e),l=window.__stagehandV3__;if(!l||typeof l.getClosedRoot!="function")return R(i,n+1)[n]??null;let y=d=>{try{return l.getClosedRoot(d)??null}catch{return null}},f=new WeakSet,u=new Set,s=[],c=[document],h=d=>{if(!(!d||f.has(d)||s.length>=n+1)){f.add(d);try{let r=d.querySelectorAll(i);for(let m of r)if(!u.has(m)&&(u.add(m),s.push(m),s.length>=n+1))return}catch{}try{let m=(d instanceof Document?d:d.host?.ownerDocument??document).createTreeWalker(d,NodeFilter.SHOW_ELEMENT),g;for(;g=m.nextNode();){if(!(g instanceof Element))continue;let w=g.shadowRoot;w&&c.push(w);let E=y(g);E&&c.push(E)}}catch{}}};for(;c.length&&s.length<n+1;){let d=c.shift();d&&h(d)}return s[n]??null}',
1870
- "resolveTextSelector": 'function $(t,e){let i=String(t??"");if(!i)return null;let n=i.toLowerCase(),l=N(e),y=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),f=o=>{if(!o)return!1;let p=o.tagName?.toUpperCase()??"";return y.has(p)},u=o=>{try{if(f(o))return"";let p=o.innerText;if(typeof p=="string"&&p.trim())return p.trim()}catch{}try{let p=o.textContent;if(typeof p=="string")return p.trim()}catch{}return""},s=o=>{let p=u(o);return!!p&&p.toLowerCase().includes(n)},c=window.__stagehandV3__,h=c&&typeof c.getClosedRoot=="function"?o=>{try{return c.getClosedRoot(o)??null}catch{return null}}:o=>null,d=new WeakSet,r=[],m=[],g=o=>{!o||d.has(o)||(d.add(o),r.push(o))},w=o=>{try{return(o instanceof Document?o:o?.ownerDocument??document).createTreeWalker(o,NodeFilter.SHOW_ELEMENT)}catch{return null}};for(g(document);r.length;){let o=r.shift();if(!o)continue;o instanceof Element&&s(o)&&m.push({element:o,tag:o.tagName??"",id:o.id??"",className:o.className??"",text:u(o)});let p=w(o);if(!p)continue;let x;for(;x=p.nextNode();){if(!(x instanceof Element))continue;s(x)&&m.push({element:x,tag:x.tagName??"",id:x.id??"",className:x.className??"",text:u(x)});let S=x.shadowRoot;S&&g(S);let b=h(x);b&&g(b)}}let E=[];for(let o of m){let p=o.element,x=!1;for(let S of m)if(o!==S)try{if(p.contains(S.element)){x=!0;break}}catch{}x||E.push(o)}return E[l]?.element??null}',
1871
- "resolveXPathMainWorld": 'function B(t,e){let i=String(t??"").trim();if(!i)return null;let n=N(e),l=window.__stagehandV3__;if(n===0){try{if(l&&typeof l.resolveSimpleXPath=="function"){let r=l.resolveSimpleXPath(i);if(r)return r}}catch{}try{return document.evaluate(i,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{}}let f=(r=>{let m=String(r||"").trim();if(!m)return[];let g=m.replace(/^xpath=/i,""),w=[],E=0;for(;E<g.length;){let a="child";g.startsWith("//",E)?(a="desc",E+=2):g[E]==="/"&&(a="child",E+=1);let o=E;for(;E<g.length&&g[E]!=="/";)E+=1;let p=g.slice(o,E).trim();if(!p)continue;let x=p.match(/^(.*?)(\\[(\\d+)\\])?$/u),S=(x?.[1]??p).trim(),b=x?.[3]?Math.max(1,Number(x[3])):null,v=S===""?"*":S.toLowerCase();w.push({axis:a,tag:v,index:b})}return w})(i);if(!f.length)return null;let u=l&&typeof l.getClosedRoot=="function"?r=>{try{return l.getClosedRoot(r)??null}catch{return null}}:r=>null,s=r=>{let m=[];if(!r)return m;if(r instanceof Document)return r.documentElement&&m.push(r.documentElement),m;if(r instanceof ShadowRoot||r instanceof DocumentFragment)return m.push(...Array.from(r.children??[])),m;if(r instanceof Element){m.push(...Array.from(r.children??[]));let g=r.shadowRoot;g&&m.push(...Array.from(g.children??[]));let w=u(r);return w&&m.push(...Array.from(w.children??[])),m}return m},c=r=>{let m=[],g=new Set,w=[...s(r)];for(;w.length;){let E=w.shift();!E||g.has(E)||(g.add(E),m.push(E),w.push(...s(E)))}return m},h=[document];for(let r of f){let m=[],g=new Set;for(let w of h){if(!w)continue;let E=r.axis==="child"?s(w):c(w);if(!E.length)continue;let a=E.filter(o=>o instanceof Element?r.tag==="*"?!0:o.localName===r.tag:!1);if(r.index!=null){let o=r.index-1,p=o>=0&&o<a.length?a[o]:null;p&&!g.has(p)&&(g.add(p),m.push(p))}else for(let o of a)g.has(o)||(g.add(o),m.push(o))}if(!m.length)return null;h=m}return h[n]??null}',
1872
- "scrollElementToPercent": 'function H(t){let e=i=>{if(typeof i=="number"&&Number.isFinite(i))return i;let n=String(i??"").trim();if(!n)return 0;let l=parseFloat(n.replace("%",""));return Number.isNaN(l)||!Number.isFinite(l)?0:l};try{let i=Math.max(0,Math.min(e(t),100)),n=this,l=n.tagName?.toLowerCase()??"";if(l==="html"||l==="body"){let d=(n.ownerDocument?.scrollingElement||n.ownerDocument?.documentElement||n.ownerDocument?.body||document.scrollingElement||document.documentElement||document.body)?.scrollHeight??document.body.scrollHeight??0,r=n.ownerDocument?.defaultView?.innerHeight??window.innerHeight,g=Math.max(0,d-r)*(i/100);return n.ownerDocument?.defaultView?.scrollTo({top:g,left:n.ownerDocument?.defaultView?.scrollX??window.scrollX??0,behavior:"smooth"}),!0}let f=n.scrollHeight??0,u=n.clientHeight??0,c=Math.max(0,f-u)*(i/100);return n.scrollTo({top:c,left:n.scrollLeft??0,behavior:"smooth"}),!0}catch{return!1}}',
1873
- "selectElementOptions": 'function _(t){try{if(!(this instanceof HTMLSelectElement))return[];let e=Array.isArray(t)?t:[t],i=new Set(e.map(f=>String(f??"").trim())),n=f=>{let u=(f.label||f.textContent||"").trim(),s=String(f.value??"").trim();return i.has(u)||i.has(s)};if(this.multiple)for(let f of Array.from(this.options))f.selected=n(f);else{let f=!1;for(let u of Array.from(this.options))!f&&n(u)?(u.selected=!0,this.value=u.value,f=!0):u.selected=!1}let l=new Event("input",{bubbles:!0}),y=new Event("change",{bubbles:!0});return this.dispatchEvent(l),this.dispatchEvent(y),Array.from(this.selectedOptions).map(f=>f.value)}catch{return[]}}'
1868
+ "readElementTextContent": 'function P(){try{return String(this.textContent??"")}catch{return""}}',
1869
+ "resolveCssSelector": 'function Y(t,e){let i=String(t??"").trim();if(!i)return null;let n=N(e);return v(i,n+1)[n]??null}',
1870
+ "resolveCssSelectorPierce": 'function B(t,e){let i=String(t??"").trim();if(!i)return null;let n=N(e),s=window.__stagehandV3__;if(!s||typeof s.getClosedRoot!="function")return v(i,n+1)[n]??null;let y=h=>{try{return s.getClosedRoot(h)??null}catch{return null}},u=new WeakSet,a=new Set,l=[],c=[document],f=h=>{if(!(!h||u.has(h)||l.length>=n+1)){u.add(h);try{let r=h.querySelectorAll(i);for(let d of r)if(!a.has(d)&&(a.add(d),l.push(d),l.length>=n+1))return}catch{}try{let d=(h instanceof Document?h:h.host?.ownerDocument??document).createTreeWalker(h,NodeFilter.SHOW_ELEMENT),g;for(;g=d.nextNode();){if(!(g instanceof Element))continue;let w=g.shadowRoot;w&&c.push(w);let E=y(g);E&&c.push(E)}}catch{}}};for(;c.length&&l.length<n+1;){let h=c.shift();h&&f(h)}return l[n]??null}',
1871
+ "resolveTextSelector": 'function $(t,e){let i=String(t??"");if(!i)return null;let n=i.toLowerCase(),s=N(e),y=new Set(["SCRIPT","STYLE","TEMPLATE","NOSCRIPT","HEAD","TITLE","LINK","META","HTML","BODY"]),u=o=>{if(!o)return!1;let p=o.tagName?.toUpperCase()??"";return y.has(p)},a=o=>{try{if(u(o))return"";let p=o.innerText;if(typeof p=="string"&&p.trim())return p.trim()}catch{}try{let p=o.textContent;if(typeof p=="string")return p.trim()}catch{}return""},l=o=>{let p=a(o);return!!p&&p.toLowerCase().includes(n)},c=window.__stagehandV3__,f=c&&typeof c.getClosedRoot=="function"?o=>{try{return c.getClosedRoot(o)??null}catch{return null}}:o=>null,h=new WeakSet,r=[],d=[],g=o=>{!o||h.has(o)||(h.add(o),r.push(o))},w=o=>{try{return(o instanceof Document?o:o?.ownerDocument??document).createTreeWalker(o,NodeFilter.SHOW_ELEMENT)}catch{return null}};for(g(document);r.length;){let o=r.shift();if(!o)continue;o instanceof Element&&l(o)&&d.push({element:o,tag:o.tagName??"",id:o.id??"",className:o.className??"",text:a(o)});let p=w(o);if(!p)continue;let x;for(;x=p.nextNode();){if(!(x instanceof Element))continue;l(x)&&d.push({element:x,tag:x.tagName??"",id:x.id??"",className:x.className??"",text:a(x)});let b=x.shadowRoot;b&&g(b);let T=f(x);T&&g(T)}}let E=[];for(let o of d){let p=o.element,x=!1;for(let b of d)if(o!==b)try{if(p.contains(b.element)){x=!0;break}}catch{}x||E.push(o)}return E[s]?.element??null}',
1872
+ "resolveXPathMainWorld": 'function z(t,e){let i=String(t??"").trim();if(!i)return null;let n=N(e),s=window.__stagehandV3__;if(n===0){try{if(s&&typeof s.resolveSimpleXPath=="function"){let r=s.resolveSimpleXPath(i);if(r)return r}}catch{}try{return document.evaluate(i,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}catch{}}let u=(r=>{let d=String(r||"").trim();if(!d)return[];let g=d.replace(/^xpath=/i,""),w=[],E=0;for(;E<g.length;){let m="child";g.startsWith("//",E)?(m="desc",E+=2):g[E]==="/"&&(m="child",E+=1);let o=E;for(;E<g.length&&g[E]!=="/";)E+=1;let p=g.slice(o,E).trim();if(!p)continue;let x=p.match(/^(.*?)(\\[(\\d+)\\])?$/u),b=(x?.[1]??p).trim(),T=x?.[3]?Math.max(1,Number(x[3])):null,M=b===""?"*":b.toLowerCase();w.push({axis:m,tag:M,index:T})}return w})(i);if(!u.length)return null;let a=s&&typeof s.getClosedRoot=="function"?r=>{try{return s.getClosedRoot(r)??null}catch{return null}}:r=>null,l=r=>{let d=[];if(!r)return d;if(r instanceof Document)return r.documentElement&&d.push(r.documentElement),d;if(r instanceof ShadowRoot||r instanceof DocumentFragment)return d.push(...Array.from(r.children??[])),d;if(r instanceof Element){d.push(...Array.from(r.children??[]));let g=r.shadowRoot;g&&d.push(...Array.from(g.children??[]));let w=a(r);return w&&d.push(...Array.from(w.children??[])),d}return d},c=r=>{let d=[],g=new Set,w=[...l(r)];for(;w.length;){let E=w.shift();!E||g.has(E)||(g.add(E),d.push(E),w.push(...l(E)))}return d},f=[document];for(let r of u){let d=[],g=new Set;for(let w of f){if(!w)continue;let E=r.axis==="child"?l(w):c(w);if(!E.length)continue;let m=E.filter(o=>o instanceof Element?r.tag==="*"?!0:o.localName===r.tag:!1);if(r.index!=null){let o=r.index-1,p=o>=0&&o<m.length?m[o]:null;p&&!g.has(p)&&(g.add(p),d.push(p))}else for(let o of m)g.has(o)||(g.add(o),d.push(o))}if(!d.length)return null;f=d}return f[n]??null}',
1873
+ "scrollElementToPercent": 'function D(t){let e=i=>{if(typeof i=="number"&&Number.isFinite(i))return i;let n=String(i??"").trim();if(!n)return 0;let s=parseFloat(n.replace("%",""));return Number.isNaN(s)||!Number.isFinite(s)?0:s};try{let i=Math.max(0,Math.min(e(t),100)),n=this,s=n.tagName?.toLowerCase()??"";if(s==="html"||s==="body"){let h=(n.ownerDocument?.scrollingElement||n.ownerDocument?.documentElement||n.ownerDocument?.body||document.scrollingElement||document.documentElement||document.body)?.scrollHeight??document.body.scrollHeight??0,r=n.ownerDocument?.defaultView?.innerHeight??window.innerHeight,g=Math.max(0,h-r)*(i/100);return n.ownerDocument?.defaultView?.scrollTo({top:g,left:n.ownerDocument?.defaultView?.scrollX??window.scrollX??0,behavior:"smooth"}),!0}let u=n.scrollHeight??0,a=n.clientHeight??0,c=Math.max(0,u-a)*(i/100);return n.scrollTo({top:c,left:n.scrollLeft??0,behavior:"smooth"}),!0}catch{return!1}}',
1874
+ "selectElementOptions": 'function I(t){try{if(!(this instanceof HTMLSelectElement))return[];let e=Array.isArray(t)?t:[t],i=new Set(e.map(u=>String(u??"").trim())),n=u=>{let a=(u.label||u.textContent||"").trim(),l=String(u.value??"").trim();return i.has(a)||i.has(l)};if(this.multiple)for(let u of Array.from(this.options))u.selected=n(u);else{let u=!1;for(let a of Array.from(this.options))!u&&n(a)?(a.selected=!0,this.value=a.value,u=!0):a.selected=!1}let s=new Event("input",{bubbles:!0}),y=new Event("change",{bubbles:!0});return this.dispatchEvent(s),this.dispatchEvent(y),Array.from(this.selectedOptions).map(u=>u.value)}catch{return[]}}'
1874
1875
  };
1875
1876
  locatorScriptGlobalRefs = {
1877
+ "assignFilePayloadsToInputElement": "globalThis.__stagehandLocatorScripts.assignFilePayloadsToInputElement",
1876
1878
  "countCssMatchesPierce": "globalThis.__stagehandLocatorScripts.countCssMatchesPierce",
1877
1879
  "countCssMatchesPrimary": "globalThis.__stagehandLocatorScripts.countCssMatchesPrimary",
1878
1880
  "countTextMatches": "globalThis.__stagehandLocatorScripts.countTextMatches",
@@ -2258,17 +2260,99 @@ var init_selectorResolver = __esm({
2258
2260
  }
2259
2261
  });
2260
2262
 
2263
+ // lib/v3/understudy/fileUploadUtils.ts
2264
+ function normalizeInputFiles(_0) {
2265
+ return __async(this, arguments, function* (files, opts = {}) {
2266
+ var _a;
2267
+ if (files === null || files === void 0) return [];
2268
+ const flattened = Array.isArray(files) ? files : [files];
2269
+ if (!flattened.length) return [];
2270
+ const baseDir = (_a = opts.baseDir) != null ? _a : process.cwd();
2271
+ const normalized = [];
2272
+ for (const entry of flattened) {
2273
+ if (typeof entry === "string") {
2274
+ const absolutePath = import_path3.default.isAbsolute(entry) ? entry : import_path3.default.resolve(baseDir, entry);
2275
+ const stat = yield statFile(absolutePath);
2276
+ if (!stat.isFile()) {
2277
+ throw new StagehandInvalidArgumentError(
2278
+ `setInputFiles(): expected a file but received directory or special entry at ${absolutePath}`
2279
+ );
2280
+ }
2281
+ const buffer = yield import_fs3.promises.readFile(absolutePath);
2282
+ normalized.push({
2283
+ name: import_path3.default.basename(absolutePath) || "upload.bin",
2284
+ mimeType: DEFAULT_MIME_TYPE,
2285
+ buffer,
2286
+ lastModified: stat.mtimeMs || Date.now(),
2287
+ absolutePath
2288
+ });
2289
+ continue;
2290
+ }
2291
+ if (entry && typeof entry === "object" && "buffer" in entry) {
2292
+ const payload = entry;
2293
+ const buffer = toBuffer(payload.buffer);
2294
+ normalized.push({
2295
+ name: payload.name || "upload.bin",
2296
+ mimeType: payload.mimeType || DEFAULT_MIME_TYPE,
2297
+ buffer,
2298
+ lastModified: typeof payload.lastModified === "number" ? payload.lastModified : Date.now()
2299
+ });
2300
+ continue;
2301
+ }
2302
+ throw new StagehandInvalidArgumentError(
2303
+ "setInputFiles(): expected file path(s) or payload object(s)"
2304
+ );
2305
+ }
2306
+ return normalized;
2307
+ });
2308
+ }
2309
+ function statFile(absolutePath) {
2310
+ return __async(this, null, function* () {
2311
+ try {
2312
+ return yield import_fs3.promises.stat(absolutePath);
2313
+ } catch (error) {
2314
+ const code = error == null ? void 0 : error.code;
2315
+ if (code === "ENOENT") {
2316
+ throw new StagehandInvalidArgumentError(
2317
+ `setInputFiles(): file not found at ${absolutePath}`
2318
+ );
2319
+ }
2320
+ throw error;
2321
+ }
2322
+ });
2323
+ }
2324
+ function toBuffer(data) {
2325
+ if (import_buffer.Buffer.isBuffer(data)) return data;
2326
+ if (data instanceof Uint8Array) return import_buffer.Buffer.from(data);
2327
+ if (typeof data === "string") return import_buffer.Buffer.from(data);
2328
+ if (data instanceof ArrayBuffer) return import_buffer.Buffer.from(new Uint8Array(data));
2329
+ throw new StagehandInvalidArgumentError(
2330
+ "Unsupported file payload buffer type"
2331
+ );
2332
+ }
2333
+ var import_fs3, import_path3, import_buffer, DEFAULT_MIME_TYPE;
2334
+ var init_fileUploadUtils = __esm({
2335
+ "lib/v3/understudy/fileUploadUtils.ts"() {
2336
+ import_fs3 = require("fs");
2337
+ import_path3 = __toESM(require("path"));
2338
+ import_buffer = require("buffer");
2339
+ init_sdkErrors();
2340
+ DEFAULT_MIME_TYPE = "application/octet-stream";
2341
+ }
2342
+ });
2343
+
2261
2344
  // lib/v3/understudy/locator.ts
2262
- var fs3, os, path3, import_buffer, Locator;
2345
+ var fs4, os, path4, MAX_REMOTE_UPLOAD_BYTES, Locator;
2263
2346
  var init_locator = __esm({
2264
2347
  "lib/v3/understudy/locator.ts"() {
2265
- fs3 = __toESM(require("fs"));
2348
+ fs4 = __toESM(require("fs"));
2266
2349
  os = __toESM(require("os"));
2267
- path3 = __toESM(require("path"));
2268
- import_buffer = require("buffer");
2350
+ path4 = __toESM(require("path"));
2269
2351
  init_locatorScripts_generated();
2270
2352
  init_selectorResolver();
2271
2353
  init_sdkErrors();
2354
+ init_fileUploadUtils();
2355
+ MAX_REMOTE_UPLOAD_BYTES = 50 * 1024 * 1024;
2272
2356
  Locator = class _Locator {
2273
2357
  constructor(frame, selector, options, nthIndex = 0) {
2274
2358
  this.frame = frame;
@@ -2298,18 +2382,7 @@ var init_locator = __esm({
2298
2382
  return __async(this, null, function* () {
2299
2383
  const session = this.frame.session;
2300
2384
  const { objectId } = yield this.resolveNode();
2301
- const items = Array.isArray(files) ? files : [files];
2302
2385
  const tempFiles = [];
2303
- const filePaths = [];
2304
- const toBuffer = (data) => {
2305
- if (import_buffer.Buffer.isBuffer(data)) return data;
2306
- if (data instanceof Uint8Array) return import_buffer.Buffer.from(data);
2307
- if (typeof data === "string") return import_buffer.Buffer.from(data);
2308
- if (data instanceof ArrayBuffer) return import_buffer.Buffer.from(new Uint8Array(data));
2309
- throw new StagehandInvalidArgumentError(
2310
- "Unsupported file payload buffer type"
2311
- );
2312
- };
2313
2386
  try {
2314
2387
  try {
2315
2388
  const res = yield session.send(
@@ -2330,28 +2403,32 @@ var init_locator = __esm({
2330
2403
  e instanceof Error ? e.message : "Unable to verify file input element"
2331
2404
  );
2332
2405
  }
2333
- for (const it of items) {
2334
- if (typeof it === "string") {
2335
- filePaths.push(path3.resolve(it));
2336
- continue;
2337
- }
2338
- if (it && typeof it === "object" && "name" in it && "mimeType" in it && "buffer" in it) {
2339
- const payload = it;
2340
- const base = payload.name || "upload.bin";
2341
- const ext = path3.extname(base);
2342
- const tmp = path3.join(
2343
- os.tmpdir(),
2344
- `stagehand-upload-${Date.now()}-${Math.random().toString(36).slice(2)}${ext}`
2345
- );
2346
- const buf = toBuffer(payload.buffer);
2347
- yield fs3.promises.writeFile(tmp, buf);
2348
- tempFiles.push(tmp);
2349
- filePaths.push(tmp);
2406
+ const normalized = yield normalizeInputFiles(files);
2407
+ if (!normalized.length) {
2408
+ yield session.send("DOM.setFileInputFiles", {
2409
+ objectId,
2410
+ files: []
2411
+ });
2412
+ return;
2413
+ }
2414
+ if (this.frame.isBrowserRemote()) {
2415
+ yield this.assignFilesViaPayloadInjection(objectId, normalized);
2416
+ return;
2417
+ }
2418
+ const filePaths = [];
2419
+ for (const payload of normalized) {
2420
+ if (payload.absolutePath) {
2421
+ filePaths.push(payload.absolutePath);
2350
2422
  continue;
2351
2423
  }
2352
- throw new StagehandInvalidArgumentError(
2353
- "Unsupported setInputFiles item \u2013 expected path or payload"
2424
+ const ext = path4.extname(payload.name);
2425
+ const tmp = path4.join(
2426
+ os.tmpdir(),
2427
+ `stagehand-upload-${Date.now()}-${Math.random().toString(36).slice(2)}${ext}`
2354
2428
  );
2429
+ yield fs4.promises.writeFile(tmp, payload.buffer);
2430
+ tempFiles.push(tmp);
2431
+ filePaths.push(tmp);
2355
2432
  }
2356
2433
  yield session.send("DOM.setFileInputFiles", {
2357
2434
  objectId,
@@ -2362,13 +2439,59 @@ var init_locator = __esm({
2362
2439
  });
2363
2440
  for (const p of tempFiles) {
2364
2441
  try {
2365
- yield fs3.promises.unlink(p);
2442
+ yield fs4.promises.unlink(p);
2366
2443
  } catch (e) {
2367
2444
  }
2368
2445
  }
2369
2446
  }
2370
2447
  });
2371
2448
  }
2449
+ /**
2450
+ * Remote browser fallback: build File objects inside the page and attach them via JS.
2451
+ *
2452
+ * When Stagehand is driving a browser that cannot see the local filesystem (Browserbase,
2453
+ * remote CDP, etc.), CDP's DOM.setFileInputFiles would fail because Chrome can't reach
2454
+ * our temp files. Instead we base64-encode the payloads, send them into the page, and
2455
+ * let a DOM helper create File objects + dispatch change/input events.
2456
+ */
2457
+ assignFilesViaPayloadInjection(objectId, files) {
2458
+ return __async(this, null, function* () {
2459
+ var _a;
2460
+ const session = this.frame.session;
2461
+ for (const payload of files) {
2462
+ if (payload.buffer.length > MAX_REMOTE_UPLOAD_BYTES) {
2463
+ throw new StagehandInvalidArgumentError(
2464
+ `setInputFiles(): file "${payload.name}" is larger than the 50MB limit for remote uploads`
2465
+ );
2466
+ }
2467
+ }
2468
+ const serialized = files.map((payload) => ({
2469
+ name: payload.name,
2470
+ mimeType: payload.mimeType,
2471
+ lastModified: payload.lastModified,
2472
+ base64: payload.buffer.toString("base64")
2473
+ }));
2474
+ const res = yield session.send(
2475
+ "Runtime.callFunctionOn",
2476
+ {
2477
+ objectId,
2478
+ functionDeclaration: locatorScriptSources.assignFilePayloadsToInputElement,
2479
+ arguments: [
2480
+ {
2481
+ value: serialized
2482
+ }
2483
+ ],
2484
+ returnByValue: true
2485
+ }
2486
+ );
2487
+ const ok = Boolean((_a = res.result) == null ? void 0 : _a.value);
2488
+ if (!ok) {
2489
+ throw new StagehandInvalidArgumentError(
2490
+ "Unable to assign file payloads to remote input element"
2491
+ );
2492
+ }
2493
+ });
2494
+ }
2372
2495
  /**
2373
2496
  * Return the DOM backendNodeId for this locator's target element.
2374
2497
  * Useful for identity comparisons without needing element handles.
@@ -3031,13 +3154,13 @@ function ensureChildFrameReady(page, parentFrame, childFrameId, budgetMs) {
3031
3154
  });
3032
3155
  yield parentSession2.send("Runtime.enable").catch(() => {
3033
3156
  });
3034
- yield new Promise((resolve3) => {
3157
+ yield new Promise((resolve2) => {
3035
3158
  let done = false;
3036
3159
  const finish = () => {
3037
3160
  if (done) return;
3038
3161
  done = true;
3039
3162
  parentSession2.off("Page.lifecycleEvent", onLifecycle);
3040
- resolve3();
3163
+ resolve2();
3041
3164
  };
3042
3165
  const onLifecycle = (evt) => {
3043
3166
  if (evt.frameId !== childFrameId || evt.name !== "DOMContentLoaded" && evt.name !== "load" && evt.name !== "networkIdle" && evt.name !== "networkidle") {
@@ -3217,8 +3340,8 @@ var init_frameLocator = __esm({
3217
3340
  });
3218
3341
 
3219
3342
  // lib/v3/understudy/deepLocator.ts
3220
- function parseXPath(path6) {
3221
- const s = path6.trim();
3343
+ function parseXPath(path7) {
3344
+ const s = path7.trim();
3222
3345
  let i = 0;
3223
3346
  const steps = [];
3224
3347
  while (i < s.length) {
@@ -3249,10 +3372,10 @@ function buildXPathFromSteps2(steps) {
3249
3372
  }
3250
3373
  function deepLocatorThroughIframes(page, root, xpathOrSelector) {
3251
3374
  return __async(this, null, function* () {
3252
- let path6 = xpathOrSelector.trim();
3253
- if (path6.startsWith("xpath=")) path6 = path6.slice("xpath=".length).trim();
3254
- if (!path6.startsWith("/")) path6 = "/" + path6;
3255
- const steps = parseXPath(path6);
3375
+ let path7 = xpathOrSelector.trim();
3376
+ if (path7.startsWith("xpath=")) path7 = path7.slice("xpath=".length).trim();
3377
+ if (!path7.startsWith("/")) path7 = "/" + path7;
3378
+ const steps = parseXPath(path7);
3256
3379
  let fl;
3257
3380
  let buf = [];
3258
3381
  const flushIntoFrameLocator = () => {
@@ -4227,11 +4350,11 @@ var require_src = __commonJS({
4227
4350
  var require_is_docker = __commonJS({
4228
4351
  "../../node_modules/.pnpm/is-docker@2.2.1/node_modules/is-docker/index.js"(exports2, module2) {
4229
4352
  "use strict";
4230
- var fs8 = require("fs");
4353
+ var fs9 = require("fs");
4231
4354
  var isDocker;
4232
4355
  function hasDockerEnv() {
4233
4356
  try {
4234
- fs8.statSync("/.dockerenv");
4357
+ fs9.statSync("/.dockerenv");
4235
4358
  return true;
4236
4359
  } catch (_) {
4237
4360
  return false;
@@ -4239,7 +4362,7 @@ var require_is_docker = __commonJS({
4239
4362
  }
4240
4363
  function hasDockerCGroup() {
4241
4364
  try {
4242
- return fs8.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
4365
+ return fs9.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
4243
4366
  } catch (_) {
4244
4367
  return false;
4245
4368
  }
@@ -4258,7 +4381,7 @@ var require_is_wsl = __commonJS({
4258
4381
  "../../node_modules/.pnpm/is-wsl@2.2.0/node_modules/is-wsl/index.js"(exports2, module2) {
4259
4382
  "use strict";
4260
4383
  var os3 = require("os");
4261
- var fs8 = require("fs");
4384
+ var fs9 = require("fs");
4262
4385
  var isDocker = require_is_docker();
4263
4386
  var isWsl3 = () => {
4264
4387
  if (process.platform !== "linux") {
@@ -4271,7 +4394,7 @@ var require_is_wsl = __commonJS({
4271
4394
  return true;
4272
4395
  }
4273
4396
  try {
4274
- return fs8.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isDocker() : false;
4397
+ return fs9.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isDocker() : false;
4275
4398
  } catch (_) {
4276
4399
  return false;
4277
4400
  }
@@ -4357,13 +4480,13 @@ function isSerializableResponse(value) {
4357
4480
  return true;
4358
4481
  }
4359
4482
  function createDeferred() {
4360
- let resolve3;
4483
+ let resolve2;
4361
4484
  let reject;
4362
4485
  const promise = new Promise((res, rej) => {
4363
- resolve3 = res;
4486
+ resolve2 = res;
4364
4487
  reject = rej;
4365
4488
  });
4366
- return { promise, resolve: resolve3, reject };
4489
+ return { promise, resolve: resolve2, reject };
4367
4490
  }
4368
4491
  function normaliseHeaderName(name) {
4369
4492
  return name.toLowerCase();
@@ -4664,13 +4787,18 @@ var init_frame = __esm({
4664
4787
  init_locator();
4665
4788
  init_sdkErrors();
4666
4789
  Frame = class _Frame {
4667
- constructor(session, frameId, pageId) {
4790
+ constructor(session, frameId, pageId, remoteBrowser) {
4668
4791
  this.session = session;
4669
4792
  this.frameId = frameId;
4670
4793
  this.pageId = pageId;
4794
+ this.remoteBrowser = remoteBrowser;
4671
4795
  var _a;
4672
4796
  this.sessionId = (_a = this.session.id) != null ? _a : null;
4673
4797
  }
4798
+ /** True when the controlled browser runs on a different machine. */
4799
+ isBrowserRemote() {
4800
+ return this.remoteBrowser;
4801
+ }
4674
4802
  /** DOM.getNodeForLocation → DOM.describeNode */
4675
4803
  getNodeAtLocation(x, y) {
4676
4804
  return __async(this, null, function* () {
@@ -4820,7 +4948,14 @@ var init_frame = __esm({
4820
4948
  const collect = (tree) => {
4821
4949
  var _a;
4822
4950
  if (tree.frame.parentId === this.frameId) {
4823
- frames.push(new _Frame(this.session, tree.frame.id, this.pageId));
4951
+ frames.push(
4952
+ new _Frame(
4953
+ this.session,
4954
+ tree.frame.id,
4955
+ this.pageId,
4956
+ this.remoteBrowser
4957
+ )
4958
+ );
4824
4959
  }
4825
4960
  (_a = tree.childFrames) == null ? void 0 : _a.forEach(collect);
4826
4961
  };
@@ -4832,11 +4967,11 @@ var init_frame = __esm({
4832
4967
  waitForLoadState(state = "load") {
4833
4968
  return __async(this, null, function* () {
4834
4969
  yield this.session.send("Page.enable");
4835
- yield new Promise((resolve3) => {
4970
+ yield new Promise((resolve2) => {
4836
4971
  const handler = (evt) => {
4837
4972
  if (evt.frameId === this.frameId && evt.name === state) {
4838
4973
  this.session.off("Page.lifecycleEvent", handler);
4839
- resolve3();
4974
+ resolve2();
4840
4975
  }
4841
4976
  };
4842
4977
  this.session.on("Page.lifecycleEvent", handler);
@@ -5357,8 +5492,8 @@ var init_networkManager = __esm({
5357
5492
  }
5358
5493
  };
5359
5494
  const removeObserver = this.addObserver(observer);
5360
- const promise = new Promise((resolve3, reject) => {
5361
- resolveFn = resolve3;
5495
+ const promise = new Promise((resolve2, reject) => {
5496
+ resolveFn = resolve2;
5362
5497
  rejectFn = reject;
5363
5498
  });
5364
5499
  maybeIdle();
@@ -5663,11 +5798,11 @@ var init_navigationResponseTracker = __esm({
5663
5798
  this.page = params.page;
5664
5799
  this.session = params.session;
5665
5800
  this.navigationCommandId = params.navigationCommandId;
5666
- this.responsePromise = new Promise((resolve3) => {
5801
+ this.responsePromise = new Promise((resolve2) => {
5667
5802
  this.resolveResponse = (value) => {
5668
5803
  if (this.responseResolved) return;
5669
5804
  this.responseResolved = true;
5670
- resolve3(value);
5805
+ resolve2(value);
5671
5806
  };
5672
5807
  });
5673
5808
  this.installListeners();
@@ -6165,10 +6300,10 @@ var page_exports = {};
6165
6300
  __export(page_exports, {
6166
6301
  Page: () => Page
6167
6302
  });
6168
- var import_fs5, LIFECYCLE_NAME, Page;
6303
+ var import_fs6, LIFECYCLE_NAME, Page;
6169
6304
  var init_page = __esm({
6170
6305
  "lib/v3/understudy/page.ts"() {
6171
- import_fs5 = require("fs");
6306
+ import_fs6 = require("fs");
6172
6307
  init_logger();
6173
6308
  init_frame();
6174
6309
  init_frameLocator();
@@ -6188,7 +6323,7 @@ var init_page = __esm({
6188
6323
  networkidle: "networkIdle"
6189
6324
  };
6190
6325
  Page = class _Page {
6191
- constructor(conn, mainSession, _targetId, mainFrameId, apiClient) {
6326
+ constructor(conn, mainSession, _targetId, mainFrameId, apiClient, browserIsRemote = false) {
6192
6327
  this.conn = conn;
6193
6328
  this.mainSession = mainSession;
6194
6329
  this._targetId = _targetId;
@@ -6213,12 +6348,14 @@ var init_page = __esm({
6213
6348
  this._pressedModifiers = /* @__PURE__ */ new Set();
6214
6349
  this.pageId = _targetId;
6215
6350
  this.apiClient = apiClient != null ? apiClient : null;
6351
+ this.browserIsRemote = browserIsRemote;
6216
6352
  if (mainSession.id) this.sessions.set(mainSession.id, mainSession);
6217
6353
  this.registry = new FrameRegistry(_targetId, mainFrameId);
6218
6354
  this.mainFrameWrapper = new Frame(
6219
6355
  this.mainSession,
6220
6356
  mainFrameId,
6221
- this.pageId
6357
+ this.pageId,
6358
+ this.browserIsRemote
6222
6359
  );
6223
6360
  this.networkManager = new NetworkManager();
6224
6361
  this.networkManager.trackSession(this.mainSession);
@@ -6318,7 +6455,7 @@ var init_page = __esm({
6318
6455
  * Factory: create Page and seed registry with the shallow tree from Page.getFrameTree.
6319
6456
  * Assumes Page domain is already enabled on the session passed in.
6320
6457
  */
6321
- static create(conn, session, targetId, apiClient, localBrowserLaunchOptions) {
6458
+ static create(conn, session, targetId, apiClient, localBrowserLaunchOptions, browserIsRemote = false) {
6322
6459
  return __async(this, null, function* () {
6323
6460
  var _a, _b, _c, _d;
6324
6461
  yield session.send("Page.enable").catch(() => {
@@ -6327,7 +6464,14 @@ var init_page = __esm({
6327
6464
  });
6328
6465
  const { frameTree } = yield session.send("Page.getFrameTree");
6329
6466
  const mainFrameId = frameTree.frame.id;
6330
- const page = new _Page(conn, session, targetId, mainFrameId, apiClient);
6467
+ const page = new _Page(
6468
+ conn,
6469
+ session,
6470
+ targetId,
6471
+ mainFrameId,
6472
+ apiClient,
6473
+ browserIsRemote
6474
+ );
6331
6475
  try {
6332
6476
  page._currentUrl = String((_b = (_a = frameTree == null ? void 0 : frameTree.frame) == null ? void 0 : _a.url) != null ? _b : page._currentUrl);
6333
6477
  if (localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.viewport) {
@@ -6375,7 +6519,12 @@ var init_page = __esm({
6375
6519
  if (newRoot !== prevRoot) {
6376
6520
  const oldOrd = (_b = this.frameOrdinals.get(prevRoot)) != null ? _b : 0;
6377
6521
  this.frameOrdinals.set(newRoot, oldOrd);
6378
- this.mainFrameWrapper = new Frame(this.mainSession, newRoot, this.pageId);
6522
+ this.mainFrameWrapper = new Frame(
6523
+ this.mainSession,
6524
+ newRoot,
6525
+ this.pageId,
6526
+ this.browserIsRemote
6527
+ );
6379
6528
  }
6380
6529
  if (frame.id === this.mainFrameId()) {
6381
6530
  try {
@@ -6481,7 +6630,7 @@ var init_page = __esm({
6481
6630
  const hit = this.frameCache.get(frameId);
6482
6631
  if (hit) return hit;
6483
6632
  const sess = this.getSessionForFrame(frameId);
6484
- const f = new Frame(sess, frameId, this.pageId);
6633
+ const f = new Frame(sess, frameId, this.pageId, this.browserIsRemote);
6485
6634
  this.frameCache.set(frameId, f);
6486
6635
  return f;
6487
6636
  }
@@ -6998,7 +7147,7 @@ var init_page = __esm({
6998
7147
  scale: captureScale
6999
7148
  });
7000
7149
  if (opts.path) {
7001
- yield import_fs5.promises.writeFile(opts.path, buffer);
7150
+ yield import_fs6.promises.writeFile(opts.path, buffer);
7002
7151
  }
7003
7152
  return buffer;
7004
7153
  } finally {
@@ -7672,7 +7821,7 @@ var init_page = __esm({
7672
7821
  } catch (e) {
7673
7822
  }
7674
7823
  const wanted = LIFECYCLE_NAME[state];
7675
- return new Promise((resolve3, reject) => {
7824
+ return new Promise((resolve2, reject) => {
7676
7825
  let done = false;
7677
7826
  let timer = null;
7678
7827
  const off = () => {
@@ -7688,7 +7837,7 @@ var init_page = __esm({
7688
7837
  timer = null;
7689
7838
  }
7690
7839
  off();
7691
- resolve3();
7840
+ resolve2();
7692
7841
  };
7693
7842
  const onLifecycle = (evt) => {
7694
7843
  if (evt.name !== wanted) return;
@@ -7800,16 +7949,180 @@ module.exports = __toCommonJS(v3_exports);
7800
7949
 
7801
7950
  // lib/v3/v3.ts
7802
7951
  var import_dotenv = __toESM(require("dotenv"));
7803
- var import_fs6 = __toESM(require("fs"));
7952
+ var import_fs7 = __toESM(require("fs"));
7804
7953
  var import_os2 = __toESM(require("os"));
7805
- var import_path5 = __toESM(require("path"));
7954
+ var import_path6 = __toESM(require("path"));
7806
7955
  var import_process2 = __toESM(require("process"));
7807
7956
 
7808
7957
  // lib/utils.ts
7809
7958
  init_sdkErrors();
7810
7959
  var import_genai = require("@google/genai");
7811
- var import_v3 = require("zod/v3");
7960
+ var import_zod2 = require("zod");
7961
+ var import_v3 = __toESM(require("zod/v3"));
7962
+
7963
+ // lib/v3/zodCompat.ts
7964
+ var import_zod = require("zod");
7965
+ var import_zod_to_json_schema = require("zod-to-json-schema");
7966
+ var isZod4Schema = (schema) => typeof schema._zod !== "undefined";
7967
+ function toJsonSchema(schema, options) {
7968
+ if (isZod4Schema(schema) && typeof import_zod.z.toJSONSchema === "function" && !options) {
7969
+ return import_zod.z.toJSONSchema(schema);
7970
+ }
7971
+ return (0, import_zod_to_json_schema.zodToJsonSchema)(
7972
+ schema,
7973
+ options != null ? options : { $refStrategy: "none" }
7974
+ );
7975
+ }
7976
+
7977
+ // lib/utils.ts
7812
7978
  var ID_PATTERN = /^\d+-\d+$/;
7979
+ var zFactories = {
7980
+ v4: import_zod2.z,
7981
+ v3: import_v3.default
7982
+ };
7983
+ function getZFactory(schema) {
7984
+ return isZod4Schema(schema) ? zFactories.v4 : zFactories.v3;
7985
+ }
7986
+ var TYPE_NAME_MAP = {
7987
+ ZodString: "string",
7988
+ string: "string",
7989
+ ZodNumber: "number",
7990
+ number: "number",
7991
+ ZodBoolean: "boolean",
7992
+ boolean: "boolean",
7993
+ ZodObject: "object",
7994
+ object: "object",
7995
+ ZodArray: "array",
7996
+ array: "array",
7997
+ ZodUnion: "union",
7998
+ union: "union",
7999
+ ZodIntersection: "intersection",
8000
+ intersection: "intersection",
8001
+ ZodOptional: "optional",
8002
+ optional: "optional",
8003
+ ZodNullable: "nullable",
8004
+ nullable: "nullable",
8005
+ ZodLiteral: "literal",
8006
+ literal: "literal",
8007
+ ZodEnum: "enum",
8008
+ enum: "enum",
8009
+ ZodDefault: "default",
8010
+ default: "default",
8011
+ ZodEffects: "effects",
8012
+ effects: "effects",
8013
+ pipe: "pipe"
8014
+ };
8015
+ function getZ4Def(schema) {
8016
+ var _a;
8017
+ return (_a = schema._zod) == null ? void 0 : _a.def;
8018
+ }
8019
+ function getZ4Bag(schema) {
8020
+ var _a;
8021
+ return (_a = schema._zod) == null ? void 0 : _a.bag;
8022
+ }
8023
+ function getZ3Def(schema) {
8024
+ return schema._def;
8025
+ }
8026
+ function getObjectShape(schema) {
8027
+ var _a, _b;
8028
+ const z4Shape = (_a = getZ4Def(schema)) == null ? void 0 : _a.shape;
8029
+ if (z4Shape) {
8030
+ return z4Shape;
8031
+ }
8032
+ const z3Shape = (_b = getZ3Def(schema)) == null ? void 0 : _b.shape;
8033
+ if (!z3Shape) {
8034
+ return void 0;
8035
+ }
8036
+ if (typeof z3Shape === "function") {
8037
+ return z3Shape();
8038
+ }
8039
+ return z3Shape;
8040
+ }
8041
+ function getArrayElement(schema) {
8042
+ var _a, _b, _c;
8043
+ return (_c = (_a = getZ4Def(schema)) == null ? void 0 : _a.element) != null ? _c : (_b = getZ3Def(schema)) == null ? void 0 : _b.type;
8044
+ }
8045
+ function getInnerType(schema) {
8046
+ var _a, _b, _c;
8047
+ return (_c = (_a = getZ4Def(schema)) == null ? void 0 : _a.innerType) != null ? _c : (_b = getZ3Def(schema)) == null ? void 0 : _b.innerType;
8048
+ }
8049
+ function getUnionOptions(schema) {
8050
+ var _a, _b;
8051
+ const z4Options = (_a = getZ4Def(schema)) == null ? void 0 : _a.options;
8052
+ if (Array.isArray(z4Options)) {
8053
+ return z4Options;
8054
+ }
8055
+ const z3Options = (_b = getZ3Def(schema)) == null ? void 0 : _b.options;
8056
+ return Array.isArray(z3Options) ? z3Options : void 0;
8057
+ }
8058
+ function getIntersectionSides(schema) {
8059
+ const z4Def = getZ4Def(schema);
8060
+ if ((z4Def == null ? void 0 : z4Def.left) || (z4Def == null ? void 0 : z4Def.right)) {
8061
+ return {
8062
+ left: z4Def == null ? void 0 : z4Def.left,
8063
+ right: z4Def == null ? void 0 : z4Def.right
8064
+ };
8065
+ }
8066
+ const z3Def = getZ3Def(schema);
8067
+ return {
8068
+ left: z3Def == null ? void 0 : z3Def.left,
8069
+ right: z3Def == null ? void 0 : z3Def.right
8070
+ };
8071
+ }
8072
+ function getEnumValues(schema) {
8073
+ var _a, _b;
8074
+ const z4Entries = (_a = getZ4Def(schema)) == null ? void 0 : _a.entries;
8075
+ if (z4Entries && typeof z4Entries === "object") {
8076
+ return Object.values(z4Entries);
8077
+ }
8078
+ const z3Values = (_b = getZ3Def(schema)) == null ? void 0 : _b.values;
8079
+ return Array.isArray(z3Values) ? z3Values : void 0;
8080
+ }
8081
+ function getLiteralValues(schema) {
8082
+ var _a, _b;
8083
+ const z4Values = (_a = getZ4Def(schema)) == null ? void 0 : _a.values;
8084
+ if (Array.isArray(z4Values)) {
8085
+ return z4Values;
8086
+ }
8087
+ const value = (_b = getZ3Def(schema)) == null ? void 0 : _b.value;
8088
+ return typeof value !== "undefined" ? [value] : [];
8089
+ }
8090
+ function getStringChecks(schema) {
8091
+ var _a, _b;
8092
+ const z4Checks = (_a = getZ4Def(schema)) == null ? void 0 : _a.checks;
8093
+ if (Array.isArray(z4Checks)) {
8094
+ return z4Checks;
8095
+ }
8096
+ const z3Checks = (_b = getZ3Def(schema)) == null ? void 0 : _b.checks;
8097
+ return Array.isArray(z3Checks) ? z3Checks : [];
8098
+ }
8099
+ function getStringFormat(schema) {
8100
+ var _a, _b, _c;
8101
+ const bagFormat = (_a = getZ4Bag(schema)) == null ? void 0 : _a.format;
8102
+ if (typeof bagFormat === "string") {
8103
+ return bagFormat;
8104
+ }
8105
+ const z4Format = (_b = getZ4Def(schema)) == null ? void 0 : _b.format;
8106
+ if (typeof z4Format === "string") {
8107
+ return z4Format;
8108
+ }
8109
+ const z3Format = (_c = getZ3Def(schema)) == null ? void 0 : _c.format;
8110
+ return typeof z3Format === "string" ? z3Format : void 0;
8111
+ }
8112
+ function getPipeEndpoints(schema) {
8113
+ const z4Def = getZ4Def(schema);
8114
+ if ((z4Def == null ? void 0 : z4Def.in) || (z4Def == null ? void 0 : z4Def.out)) {
8115
+ return {
8116
+ in: z4Def == null ? void 0 : z4Def.in,
8117
+ out: z4Def == null ? void 0 : z4Def.out
8118
+ };
8119
+ }
8120
+ return {};
8121
+ }
8122
+ function getEffectsBaseSchema(schema) {
8123
+ var _a;
8124
+ return (_a = getZ3Def(schema)) == null ? void 0 : _a.schema;
8125
+ }
7813
8126
  function validateZodSchema(schema, data) {
7814
8127
  const result = schema.safeParse(data);
7815
8128
  if (result.success) {
@@ -7830,118 +8143,150 @@ function decorateGeminiSchema(geminiSchema, zodSchema2) {
7830
8143
  return geminiSchema;
7831
8144
  }
7832
8145
  function toGeminiSchema(zodSchema2) {
8146
+ var _a, _b;
8147
+ const normalizedSchema = zodSchema2;
7833
8148
  const zodType = getZodType(zodSchema2);
7834
8149
  switch (zodType) {
7835
- case "ZodArray": {
8150
+ case "array": {
8151
+ const element = (_a = getArrayElement(zodSchema2)) != null ? _a : import_zod2.z.any();
7836
8152
  return decorateGeminiSchema(
7837
8153
  {
7838
8154
  type: import_genai.Type.ARRAY,
7839
- items: toGeminiSchema(
7840
- zodSchema2.element
7841
- )
8155
+ items: toGeminiSchema(element)
7842
8156
  },
7843
- zodSchema2
8157
+ normalizedSchema
7844
8158
  );
7845
8159
  }
7846
- case "ZodObject": {
8160
+ case "object": {
7847
8161
  const properties = {};
7848
8162
  const required = [];
7849
- Object.entries(zodSchema2.shape).forEach(
7850
- ([key, value]) => {
7851
- properties[key] = toGeminiSchema(value);
7852
- if (getZodType(value) !== "ZodOptional") {
7853
- required.push(key);
8163
+ const shape = getObjectShape(zodSchema2);
8164
+ if (shape) {
8165
+ Object.entries(shape).forEach(
8166
+ ([key, value]) => {
8167
+ properties[key] = toGeminiSchema(value);
8168
+ if (getZodType(value) !== "optional") {
8169
+ required.push(key);
8170
+ }
7854
8171
  }
7855
- }
7856
- );
8172
+ );
8173
+ }
7857
8174
  return decorateGeminiSchema(
7858
8175
  {
7859
8176
  type: import_genai.Type.OBJECT,
7860
8177
  properties,
7861
8178
  required: required.length > 0 ? required : void 0
7862
8179
  },
7863
- zodSchema2
8180
+ normalizedSchema
7864
8181
  );
7865
8182
  }
7866
- case "ZodString":
8183
+ case "string":
7867
8184
  return decorateGeminiSchema(
7868
8185
  {
7869
8186
  type: import_genai.Type.STRING
7870
8187
  },
7871
- zodSchema2
8188
+ normalizedSchema
7872
8189
  );
7873
- case "ZodNumber":
8190
+ case "number":
7874
8191
  return decorateGeminiSchema(
7875
8192
  {
7876
8193
  type: import_genai.Type.NUMBER
7877
8194
  },
7878
- zodSchema2
8195
+ normalizedSchema
7879
8196
  );
7880
- case "ZodBoolean":
8197
+ case "boolean":
7881
8198
  return decorateGeminiSchema(
7882
8199
  {
7883
8200
  type: import_genai.Type.BOOLEAN
7884
8201
  },
7885
- zodSchema2
8202
+ normalizedSchema
7886
8203
  );
7887
- case "ZodEnum":
8204
+ case "enum": {
8205
+ const values = getEnumValues(zodSchema2);
7888
8206
  return decorateGeminiSchema(
7889
8207
  {
7890
8208
  type: import_genai.Type.STRING,
7891
- enum: zodSchema2._def.values
8209
+ enum: values
7892
8210
  },
7893
- zodSchema2
8211
+ normalizedSchema
7894
8212
  );
7895
- case "ZodDefault":
7896
- case "ZodNullable":
7897
- case "ZodOptional": {
7898
- const innerSchema = toGeminiSchema(zodSchema2._def.innerType);
8213
+ }
8214
+ case "default":
8215
+ case "nullable":
8216
+ case "optional": {
8217
+ const innerType = (_b = getInnerType(zodSchema2)) != null ? _b : import_zod2.z.any();
8218
+ const innerSchema = toGeminiSchema(innerType);
7899
8219
  return decorateGeminiSchema(
7900
8220
  __spreadProps(__spreadValues({}, innerSchema), {
7901
8221
  nullable: true
7902
8222
  }),
7903
- zodSchema2
8223
+ normalizedSchema
7904
8224
  );
7905
8225
  }
7906
- case "ZodLiteral":
8226
+ case "literal": {
8227
+ const values = getLiteralValues(zodSchema2);
7907
8228
  return decorateGeminiSchema(
7908
8229
  {
7909
8230
  type: import_genai.Type.STRING,
7910
- enum: [zodSchema2._def.value]
8231
+ enum: values
8232
+ },
8233
+ normalizedSchema
8234
+ );
8235
+ }
8236
+ case "pipe": {
8237
+ const endpoints = getPipeEndpoints(zodSchema2);
8238
+ if (endpoints.in) {
8239
+ return toGeminiSchema(endpoints.in);
8240
+ }
8241
+ return decorateGeminiSchema(
8242
+ {
8243
+ type: import_genai.Type.STRING
7911
8244
  },
7912
- zodSchema2
8245
+ normalizedSchema
7913
8246
  );
8247
+ }
8248
+ // Standalone transforms and any unknown types fall through to default
7914
8249
  default:
7915
8250
  return decorateGeminiSchema(
7916
8251
  {
7917
- type: import_genai.Type.OBJECT,
7918
- nullable: true
8252
+ type: import_genai.Type.STRING
7919
8253
  },
7920
- zodSchema2
8254
+ normalizedSchema
7921
8255
  );
7922
8256
  }
7923
8257
  }
7924
8258
  function getZodType(schema) {
7925
- return schema._def.typeName;
8259
+ var _a, _b, _c, _d, _e, _f, _g;
8260
+ const schemaWithDef = schema;
8261
+ const rawType = (_f = (_d = (_b = (_a = schemaWithDef._zod) == null ? void 0 : _a.def) == null ? void 0 : _b.type) != null ? _d : (_c = schemaWithDef._def) == null ? void 0 : _c.typeName) != null ? _f : (_e = schemaWithDef._def) == null ? void 0 : _e.type;
8262
+ if (!rawType) {
8263
+ return "unknown";
8264
+ }
8265
+ return (_g = TYPE_NAME_MAP[rawType]) != null ? _g : rawType;
7926
8266
  }
7927
8267
  function transformSchema(schema, currentPath) {
7928
- var _a, _b;
7929
- if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodString)) {
7930
- const hasUrlCheck = (_b = (_a = schema._def.checks) == null ? void 0 : _a.some(
7931
- (check) => check.kind === "url"
7932
- )) != null ? _b : false;
8268
+ if (isKind(schema, "string")) {
8269
+ const checks = getStringChecks(schema);
8270
+ const format = getStringFormat(schema);
8271
+ const hasUrlCheck = checks.some((check) => {
8272
+ var _a, _b, _c, _d;
8273
+ const candidate = check;
8274
+ return candidate.kind === "url" || candidate.format === "url" || ((_b = (_a = candidate._zod) == null ? void 0 : _a.def) == null ? void 0 : _b.check) === "url" || ((_d = (_c = candidate._zod) == null ? void 0 : _c.def) == null ? void 0 : _d.format) === "url";
8275
+ }) || format === "url";
7933
8276
  if (hasUrlCheck) {
7934
8277
  return [makeIdStringSchema(schema), [{ segments: [] }]];
7935
8278
  }
7936
8279
  return [schema, []];
7937
8280
  }
7938
- if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodObject)) {
7939
- const shape = schema._def.shape();
8281
+ if (isKind(schema, "object")) {
8282
+ const shape = getObjectShape(schema);
8283
+ if (!shape) {
8284
+ return [schema, []];
8285
+ }
7940
8286
  const newShape = {};
7941
8287
  const urlPaths = [];
7942
8288
  let changed = false;
7943
- const shapeKeys = Object.keys(shape);
7944
- for (const key of shapeKeys) {
8289
+ for (const key of Object.keys(shape)) {
7945
8290
  const child = shape[key];
7946
8291
  const [transformedChild, childPaths] = transformSchema(child, [
7947
8292
  ...currentPath,
@@ -7951,34 +8296,45 @@ function transformSchema(schema, currentPath) {
7951
8296
  changed = true;
7952
8297
  }
7953
8298
  newShape[key] = transformedChild;
7954
- if (childPaths.length > 0) {
7955
- for (const cp of childPaths) {
7956
- urlPaths.push({ segments: [key, ...cp.segments] });
7957
- }
7958
- }
8299
+ childPaths.forEach((cp) => {
8300
+ urlPaths.push({ segments: [key, ...cp.segments] });
8301
+ });
7959
8302
  }
7960
8303
  if (changed) {
7961
- return [import_v3.z.object(newShape), urlPaths];
8304
+ const factory6 = getZFactory(schema);
8305
+ return [
8306
+ factory6.object(newShape),
8307
+ urlPaths
8308
+ ];
7962
8309
  }
7963
8310
  return [schema, urlPaths];
7964
8311
  }
7965
- if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodArray)) {
7966
- const itemType = schema._def.type;
8312
+ if (isKind(schema, "array")) {
8313
+ const itemType = getArrayElement(schema);
8314
+ if (!itemType) {
8315
+ return [schema, []];
8316
+ }
7967
8317
  const [transformedItem, childPaths] = transformSchema(itemType, [
7968
8318
  ...currentPath,
7969
8319
  "*"
7970
8320
  ]);
7971
- const changed = transformedItem !== itemType;
7972
8321
  const arrayPaths = childPaths.map((cp) => ({
7973
8322
  segments: ["*", ...cp.segments]
7974
8323
  }));
7975
- if (changed) {
7976
- return [import_v3.z.array(transformedItem), arrayPaths];
8324
+ if (transformedItem !== itemType) {
8325
+ const factory6 = getZFactory(schema);
8326
+ return [
8327
+ factory6.array(transformedItem),
8328
+ arrayPaths
8329
+ ];
7977
8330
  }
7978
8331
  return [schema, arrayPaths];
7979
8332
  }
7980
- if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodUnion)) {
7981
- const unionOptions = schema._def.options;
8333
+ if (isKind(schema, "union")) {
8334
+ const unionOptions = getUnionOptions(schema);
8335
+ if (!unionOptions || unionOptions.length === 0) {
8336
+ return [schema, []];
8337
+ }
7982
8338
  const newOptions = [];
7983
8339
  let changed = false;
7984
8340
  let allPaths = [];
@@ -7994,60 +8350,100 @@ function transformSchema(schema, currentPath) {
7994
8350
  allPaths = [...allPaths, ...childPaths];
7995
8351
  });
7996
8352
  if (changed) {
8353
+ const factory6 = getZFactory(schema);
7997
8354
  return [
7998
- import_v3.z.union(newOptions),
8355
+ factory6.union(
8356
+ newOptions
8357
+ ),
7999
8358
  allPaths
8000
8359
  ];
8001
8360
  }
8002
8361
  return [schema, allPaths];
8003
8362
  }
8004
- if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodIntersection)) {
8005
- const leftType = schema._def.left;
8006
- const rightType = schema._def.right;
8007
- const [left, leftPaths] = transformSchema(leftType, [
8363
+ if (isKind(schema, "intersection")) {
8364
+ const { left, right } = getIntersectionSides(schema);
8365
+ if (!left || !right) {
8366
+ return [schema, []];
8367
+ }
8368
+ const [newLeft, leftPaths] = transformSchema(left, [
8008
8369
  ...currentPath,
8009
8370
  "intersection_left"
8010
8371
  ]);
8011
- const [right, rightPaths] = transformSchema(rightType, [
8372
+ const [newRight, rightPaths] = transformSchema(right, [
8012
8373
  ...currentPath,
8013
8374
  "intersection_right"
8014
8375
  ]);
8015
- const changed = left !== leftType || right !== rightType;
8376
+ const changed = newLeft !== left || newRight !== right;
8016
8377
  const allPaths = [...leftPaths, ...rightPaths];
8017
8378
  if (changed) {
8018
- return [import_v3.z.intersection(left, right), allPaths];
8379
+ const factory6 = getZFactory(schema);
8380
+ return [
8381
+ factory6.intersection(
8382
+ newLeft,
8383
+ newRight
8384
+ ),
8385
+ allPaths
8386
+ ];
8019
8387
  }
8020
8388
  return [schema, allPaths];
8021
8389
  }
8022
- if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodOptional)) {
8023
- const innerType = schema._def.innerType;
8390
+ if (isKind(schema, "optional")) {
8391
+ const innerType = getInnerType(schema);
8392
+ if (!innerType) {
8393
+ return [schema, []];
8394
+ }
8024
8395
  const [inner, innerPaths] = transformSchema(innerType, currentPath);
8025
8396
  if (inner !== innerType) {
8026
- return [import_v3.z.optional(inner), innerPaths];
8397
+ return [
8398
+ inner.optional(),
8399
+ innerPaths
8400
+ ];
8027
8401
  }
8028
8402
  return [schema, innerPaths];
8029
8403
  }
8030
- if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodNullable)) {
8031
- const innerType = schema._def.innerType;
8404
+ if (isKind(schema, "nullable")) {
8405
+ const innerType = getInnerType(schema);
8406
+ if (!innerType) {
8407
+ return [schema, []];
8408
+ }
8032
8409
  const [inner, innerPaths] = transformSchema(innerType, currentPath);
8033
8410
  if (inner !== innerType) {
8034
- return [import_v3.z.nullable(inner), innerPaths];
8411
+ return [
8412
+ inner.nullable(),
8413
+ innerPaths
8414
+ ];
8035
8415
  }
8036
8416
  return [schema, innerPaths];
8037
8417
  }
8038
- if (isKind(schema, import_v3.ZodFirstPartyTypeKind.ZodEffects)) {
8039
- const baseSchema = schema._def.schema;
8040
- const [newBaseSchema, basePaths] = transformSchema(baseSchema, currentPath);
8041
- if (newBaseSchema !== baseSchema) {
8042
- return [import_v3.z.effect(newBaseSchema, schema._def.effect), basePaths];
8418
+ if (isKind(schema, "pipe") && isZod4Schema(schema)) {
8419
+ const { in: inSchema, out: outSchema } = getPipeEndpoints(schema);
8420
+ if (!inSchema || !outSchema) {
8421
+ return [schema, []];
8422
+ }
8423
+ const [newIn, inPaths] = transformSchema(inSchema, currentPath);
8424
+ const [newOut, outPaths] = transformSchema(outSchema, currentPath);
8425
+ const allPaths = [...inPaths, ...outPaths];
8426
+ if (newIn !== inSchema || newOut !== outSchema) {
8427
+ const result = import_zod2.z.pipe(
8428
+ newIn,
8429
+ newOut
8430
+ );
8431
+ return [result, allPaths];
8043
8432
  }
8044
- return [schema, basePaths];
8433
+ return [schema, allPaths];
8434
+ }
8435
+ if (isKind(schema, "effects")) {
8436
+ const baseSchema = getEffectsBaseSchema(schema);
8437
+ if (!baseSchema) {
8438
+ return [schema, []];
8439
+ }
8440
+ return transformSchema(baseSchema, currentPath);
8045
8441
  }
8046
8442
  return [schema, []];
8047
8443
  }
8048
- function injectUrls(obj, path6, idToUrlMapping) {
8444
+ function injectUrls(obj, path7, idToUrlMapping) {
8049
8445
  var _a, _b;
8050
- if (path6.length === 0) return;
8446
+ if (path7.length === 0) return;
8051
8447
  const toId = (value) => {
8052
8448
  if (typeof value === "number") {
8053
8449
  return String(value);
@@ -8057,7 +8453,7 @@ function injectUrls(obj, path6, idToUrlMapping) {
8057
8453
  }
8058
8454
  return void 0;
8059
8455
  };
8060
- const [key, ...rest] = path6;
8456
+ const [key, ...rest] = path7;
8061
8457
  if (key === "*") {
8062
8458
  if (Array.isArray(obj)) {
8063
8459
  if (rest.length === 0) {
@@ -8075,7 +8471,7 @@ function injectUrls(obj, path6, idToUrlMapping) {
8075
8471
  }
8076
8472
  if (obj && typeof obj === "object") {
8077
8473
  const record = obj;
8078
- if (path6.length === 1) {
8474
+ if (path7.length === 1) {
8079
8475
  const fieldValue = record[key];
8080
8476
  const id = toId(fieldValue);
8081
8477
  if (id !== void 0) {
@@ -8087,17 +8483,19 @@ function injectUrls(obj, path6, idToUrlMapping) {
8087
8483
  }
8088
8484
  }
8089
8485
  function isKind(s, kind) {
8090
- return s._def.typeName === kind;
8486
+ try {
8487
+ return getZodType(s) === kind;
8488
+ } catch (e) {
8489
+ return false;
8490
+ }
8091
8491
  }
8092
8492
  function makeIdStringSchema(orig) {
8093
- var _a, _b, _c;
8094
- const userDesc = (
8095
- // Zod ≥3.23 exposes .description directly; fall back to _def for older minor versions
8096
- (_c = (_b = orig.description) != null ? _b : (_a = orig._def) == null ? void 0 : _a.description) != null ? _c : ""
8097
- );
8493
+ var _a;
8494
+ const userDesc = (_a = orig.description) != null ? _a : "";
8098
8495
  const base = `This field must be the element-ID in the form 'frameId-backendId' (e.g. "0-432").`;
8099
8496
  const composed = userDesc.trim().length > 0 ? `${base} that follows this user-defined description: ${userDesc}` : base;
8100
- return import_v3.z.string().regex(ID_PATTERN).describe(composed);
8497
+ const factory6 = getZFactory(orig);
8498
+ return factory6.string().regex(ID_PATTERN).describe(composed);
8101
8499
  }
8102
8500
  var providerEnvVarMap = {
8103
8501
  openai: "OPENAI_API_KEY",
@@ -8132,8 +8530,8 @@ function loadApiKeyFromEnv(provider, logger) {
8132
8530
  }
8133
8531
  return void 0;
8134
8532
  }
8135
- function trimTrailingTextNode(path6) {
8136
- return path6 == null ? void 0 : path6.replace(/\/text\(\)(\[\d+\])?$/iu, "");
8533
+ function trimTrailingTextNode(path7) {
8534
+ return path7 == null ? void 0 : path7.replace(/\/text\(\)(\[\d+\])?$/iu, "");
8137
8535
  }
8138
8536
  function jsonSchemaToZod(schema) {
8139
8537
  switch (schema.type) {
@@ -8143,7 +8541,7 @@ function jsonSchemaToZod(schema) {
8143
8541
  for (const key in schema.properties) {
8144
8542
  shape[key] = jsonSchemaToZod(schema.properties[key]);
8145
8543
  }
8146
- let zodObject = import_v3.z.object(shape);
8544
+ let zodObject = import_zod2.z.object(shape);
8147
8545
  if (schema.required && Array.isArray(schema.required)) {
8148
8546
  const requiredFields = schema.required.reduce(
8149
8547
  (acc, field) => __spreadProps(__spreadValues({}, acc), { [field]: true }),
@@ -8156,30 +8554,30 @@ function jsonSchemaToZod(schema) {
8156
8554
  }
8157
8555
  return zodObject;
8158
8556
  } else {
8159
- return import_v3.z.object({});
8557
+ return import_zod2.z.object({});
8160
8558
  }
8161
8559
  case "array":
8162
8560
  if (schema.items) {
8163
- let zodArray = import_v3.z.array(jsonSchemaToZod(schema.items));
8561
+ let zodArray = import_zod2.z.array(jsonSchemaToZod(schema.items));
8164
8562
  if (schema.description) {
8165
8563
  zodArray = zodArray.describe(schema.description);
8166
8564
  }
8167
8565
  return zodArray;
8168
8566
  } else {
8169
- return import_v3.z.array(import_v3.z.any());
8567
+ return import_zod2.z.array(import_zod2.z.any());
8170
8568
  }
8171
8569
  case "string": {
8172
8570
  if (schema.enum) {
8173
- return import_v3.z.string().refine((val) => schema.enum.includes(val));
8571
+ return import_zod2.z.string().refine((val) => schema.enum.includes(val));
8174
8572
  }
8175
- let zodString = import_v3.z.string();
8573
+ let zodString = import_zod2.z.string();
8176
8574
  if (schema.description) {
8177
8575
  zodString = zodString.describe(schema.description);
8178
8576
  }
8179
8577
  return zodString;
8180
8578
  }
8181
8579
  case "number": {
8182
- let zodNumber = import_v3.z.number();
8580
+ let zodNumber = import_zod2.z.number();
8183
8581
  if (schema.minimum !== void 0) {
8184
8582
  zodNumber = zodNumber.min(schema.minimum);
8185
8583
  }
@@ -8192,14 +8590,14 @@ function jsonSchemaToZod(schema) {
8192
8590
  return zodNumber;
8193
8591
  }
8194
8592
  case "boolean": {
8195
- let zodBoolean = import_v3.z.boolean();
8593
+ let zodBoolean = import_zod2.z.boolean();
8196
8594
  if (schema.description) {
8197
8595
  zodBoolean = zodBoolean.describe(schema.description);
8198
8596
  }
8199
8597
  return zodBoolean;
8200
8598
  }
8201
8599
  default:
8202
- return import_v3.z.any();
8600
+ return import_zod2.z.any();
8203
8601
  }
8204
8602
  }
8205
8603
 
@@ -8510,12 +8908,12 @@ var ActCache = class {
8510
8908
  const {
8511
8909
  value: entry,
8512
8910
  error,
8513
- path: path6
8911
+ path: path7
8514
8912
  } = yield this.storage.readJson(`${context.cacheKey}.json`);
8515
- if (error && path6) {
8913
+ if (error && path7) {
8516
8914
  this.logger({
8517
8915
  category: "cache",
8518
- message: `failed to read act cache entry: ${path6}`,
8916
+ message: `failed to read act cache entry: ${path7}`,
8519
8917
  level: 2,
8520
8918
  auxiliary: {
8521
8919
  error: { value: String(error), type: "string" }
@@ -8556,11 +8954,11 @@ var ActCache = class {
8556
8954
  actionDescription: result.actionDescription,
8557
8955
  message: result.message
8558
8956
  };
8559
- const { error, path: path6 } = yield this.storage.writeJson(
8957
+ const { error, path: path7 } = yield this.storage.writeJson(
8560
8958
  `${context.cacheKey}.json`,
8561
8959
  entry
8562
8960
  );
8563
- if (error && path6) {
8961
+ if (error && path7) {
8564
8962
  this.logger({
8565
8963
  category: "cache",
8566
8964
  message: "failed to write act cache entry",
@@ -8678,11 +9076,11 @@ var ActCache = class {
8678
9076
  }
8679
9077
  refreshCacheEntry(context, entry) {
8680
9078
  return __async(this, null, function* () {
8681
- const { error, path: path6 } = yield this.storage.writeJson(
9079
+ const { error, path: path7 } = yield this.storage.writeJson(
8682
9080
  `${context.cacheKey}.json`,
8683
9081
  entry
8684
9082
  );
8685
- if (error && path6) {
9083
+ if (error && path7) {
8686
9084
  this.logger({
8687
9085
  category: "cache",
8688
9086
  message: "failed to update act cache entry after self-heal",
@@ -8709,14 +9107,14 @@ var ActCache = class {
8709
9107
  if (!timeout) {
8710
9108
  return yield run();
8711
9109
  }
8712
- return yield new Promise((resolve3, reject) => {
9110
+ return yield new Promise((resolve2, reject) => {
8713
9111
  const timer = setTimeout(() => {
8714
9112
  reject(new Error(`act() timed out after ${timeout}ms`));
8715
9113
  }, timeout);
8716
9114
  void run().then(
8717
9115
  (value) => {
8718
9116
  clearTimeout(timer);
8719
- resolve3(value);
9117
+ resolve2(value);
8720
9118
  },
8721
9119
  (err) => {
8722
9120
  clearTimeout(timer);
@@ -8824,14 +9222,14 @@ var AgentCache = class {
8824
9222
  const {
8825
9223
  value: entry,
8826
9224
  error,
8827
- path: path6
9225
+ path: path7
8828
9226
  } = yield this.storage.readJson(
8829
9227
  `agent-${context.cacheKey}.json`
8830
9228
  );
8831
- if (error && path6) {
9229
+ if (error && path7) {
8832
9230
  this.logger({
8833
9231
  category: "cache",
8834
- message: `failed to read agent cache entry: ${path6}`,
9232
+ message: `failed to read agent cache entry: ${path7}`,
8835
9233
  level: 1,
8836
9234
  auxiliary: {
8837
9235
  error: { value: String(error), type: "string" }
@@ -8867,11 +9265,11 @@ var AgentCache = class {
8867
9265
  result: cloneForCache(result),
8868
9266
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
8869
9267
  };
8870
- const { error, path: path6 } = yield this.storage.writeJson(
9268
+ const { error, path: path7 } = yield this.storage.writeJson(
8871
9269
  `agent-${context.cacheKey}.json`,
8872
9270
  entry
8873
9271
  );
8874
- if (error && path6) {
9272
+ if (error && path7) {
8875
9273
  this.logger({
8876
9274
  category: "cache",
8877
9275
  message: "failed to write agent cache entry",
@@ -8983,6 +9381,8 @@ var AgentCache = class {
8983
9381
  result.usage = {
8984
9382
  input_tokens: 0,
8985
9383
  output_tokens: 0,
9384
+ reasoning_tokens: 0,
9385
+ cached_input_tokens: 0,
8986
9386
  inference_time_ms: 0
8987
9387
  };
8988
9388
  result.metadata = __spreadProps(__spreadValues({}, (_b = result.metadata) != null ? _b : {}), {
@@ -9107,7 +9507,7 @@ var AgentCache = class {
9107
9507
  replayAgentWaitStep(step) {
9108
9508
  return __async(this, null, function* () {
9109
9509
  if (!step.timeMs || step.timeMs <= 0) return;
9110
- yield new Promise((resolve3) => setTimeout(resolve3, step.timeMs));
9510
+ yield new Promise((resolve2) => setTimeout(resolve2, step.timeMs));
9111
9511
  });
9112
9512
  }
9113
9513
  replayAgentNavBackStep(step, ctx) {
@@ -9199,7 +9599,7 @@ var CacheStorage = class _CacheStorage {
9199
9599
  };
9200
9600
 
9201
9601
  // lib/inference.ts
9202
- var import_v32 = require("zod/v3");
9602
+ var import_zod3 = require("zod");
9203
9603
 
9204
9604
  // lib/prompt.ts
9205
9605
  function buildUserInstructionsString(userProvidedInstructions) {
@@ -9457,12 +9857,12 @@ function extract(_0) {
9457
9857
  userProvidedInstructions,
9458
9858
  logInferenceToFile = false
9459
9859
  }) {
9460
- var _a, _b, _c, _d, _e, _f, _g, _h;
9461
- const metadataSchema = import_v32.z.object({
9462
- progress: import_v32.z.string().describe(
9860
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
9861
+ const metadataSchema = import_zod3.z.object({
9862
+ progress: import_zod3.z.string().describe(
9463
9863
  "progress of what has been extracted so far, as concise as possible"
9464
9864
  ),
9465
- completed: import_v32.z.boolean().describe(
9865
+ completed: import_zod3.z.boolean().describe(
9466
9866
  "true if the goal is now accomplished. Use this conservatively, only when sure that the goal has been completed."
9467
9867
  )
9468
9868
  });
@@ -9521,6 +9921,8 @@ function extract(_0) {
9521
9921
  LLM_output_file: extractResponseFile,
9522
9922
  prompt_tokens: (_a = extractUsage == null ? void 0 : extractUsage.prompt_tokens) != null ? _a : 0,
9523
9923
  completion_tokens: (_b = extractUsage == null ? void 0 : extractUsage.completion_tokens) != null ? _b : 0,
9924
+ reasoning_tokens: (_c = extractUsage == null ? void 0 : extractUsage.reasoning_tokens) != null ? _c : 0,
9925
+ cached_input_tokens: (_d = extractUsage == null ? void 0 : extractUsage.cached_input_tokens) != null ? _d : 0,
9524
9926
  inference_time_ms: extractEndTime - extractStartTime
9525
9927
  });
9526
9928
  }
@@ -9582,14 +9984,18 @@ function extract(_0) {
9582
9984
  timestamp: metadataCallTimestamp,
9583
9985
  LLM_input_file: metadataCallFile,
9584
9986
  LLM_output_file: metadataResponseFile,
9585
- prompt_tokens: (_c = metadataResponseUsage == null ? void 0 : metadataResponseUsage.prompt_tokens) != null ? _c : 0,
9586
- completion_tokens: (_d = metadataResponseUsage == null ? void 0 : metadataResponseUsage.completion_tokens) != null ? _d : 0,
9987
+ prompt_tokens: (_e = metadataResponseUsage == null ? void 0 : metadataResponseUsage.prompt_tokens) != null ? _e : 0,
9988
+ completion_tokens: (_f = metadataResponseUsage == null ? void 0 : metadataResponseUsage.completion_tokens) != null ? _f : 0,
9989
+ reasoning_tokens: (_g = metadataResponseUsage == null ? void 0 : metadataResponseUsage.reasoning_tokens) != null ? _g : 0,
9990
+ cached_input_tokens: (_h = metadataResponseUsage == null ? void 0 : metadataResponseUsage.cached_input_tokens) != null ? _h : 0,
9587
9991
  inference_time_ms: metadataEndTime - metadataStartTime
9588
9992
  });
9589
9993
  }
9590
- const totalPromptTokens = ((_e = extractUsage == null ? void 0 : extractUsage.prompt_tokens) != null ? _e : 0) + ((_f = metadataResponseUsage == null ? void 0 : metadataResponseUsage.prompt_tokens) != null ? _f : 0);
9591
- const totalCompletionTokens = ((_g = extractUsage == null ? void 0 : extractUsage.completion_tokens) != null ? _g : 0) + ((_h = metadataResponseUsage == null ? void 0 : metadataResponseUsage.completion_tokens) != null ? _h : 0);
9994
+ const totalPromptTokens = ((_i = extractUsage == null ? void 0 : extractUsage.prompt_tokens) != null ? _i : 0) + ((_j = metadataResponseUsage == null ? void 0 : metadataResponseUsage.prompt_tokens) != null ? _j : 0);
9995
+ const totalCompletionTokens = ((_k = extractUsage == null ? void 0 : extractUsage.completion_tokens) != null ? _k : 0) + ((_l = metadataResponseUsage == null ? void 0 : metadataResponseUsage.completion_tokens) != null ? _l : 0);
9592
9996
  const totalInferenceTimeMs = extractEndTime - extractStartTime + (metadataEndTime - metadataStartTime);
9997
+ const totalReasoningTokens = ((_m = extractUsage == null ? void 0 : extractUsage.reasoning_tokens) != null ? _m : 0) + ((_n = metadataResponseUsage == null ? void 0 : metadataResponseUsage.reasoning_tokens) != null ? _n : 0);
9998
+ const totalCachedInputTokens = ((_o = extractUsage == null ? void 0 : extractUsage.cached_input_tokens) != null ? _o : 0) + ((_p = metadataResponseUsage == null ? void 0 : metadataResponseUsage.cached_input_tokens) != null ? _p : 0);
9593
9999
  return __spreadProps(__spreadValues({}, extractedData), {
9594
10000
  metadata: {
9595
10001
  completed: metadataResponseCompleted,
@@ -9597,6 +10003,8 @@ function extract(_0) {
9597
10003
  },
9598
10004
  prompt_tokens: totalPromptTokens,
9599
10005
  completion_tokens: totalCompletionTokens,
10006
+ reasoning_tokens: totalReasoningTokens,
10007
+ cached_input_tokens: totalCachedInputTokens,
9600
10008
  inference_time_ms: totalInferenceTimeMs
9601
10009
  });
9602
10010
  });
@@ -9610,22 +10018,22 @@ function observe(_0) {
9610
10018
  logger,
9611
10019
  logInferenceToFile = false
9612
10020
  }) {
9613
- var _a, _b, _c, _d;
10021
+ var _a, _b, _c, _d, _e, _f;
9614
10022
  const isGPT5 = llmClient.modelName.includes("gpt-5");
9615
- const observeSchema = import_v32.z.object({
9616
- elements: import_v32.z.array(
9617
- import_v32.z.object({
9618
- elementId: import_v32.z.string().describe(
10023
+ const observeSchema = import_zod3.z.object({
10024
+ elements: import_zod3.z.array(
10025
+ import_zod3.z.object({
10026
+ elementId: import_zod3.z.string().describe(
9619
10027
  "the ID string associated with the element. Never include surrounding square brackets. This field must follow the format of 'number-number'."
9620
10028
  ),
9621
- description: import_v32.z.string().describe(
10029
+ description: import_zod3.z.string().describe(
9622
10030
  "a description of the accessible element and its purpose"
9623
10031
  ),
9624
- method: import_v32.z.string().describe(
10032
+ method: import_zod3.z.string().describe(
9625
10033
  "the candidate method/action to interact with the element. Select one of the available Playwright interaction methods."
9626
10034
  ),
9627
- arguments: import_v32.z.array(
9628
- import_v32.z.string().describe(
10035
+ arguments: import_zod3.z.array(
10036
+ import_zod3.z.string().describe(
9629
10037
  "the arguments to pass to the method. For example, for a click, the arguments are empty, but for a fill, the arguments are the value to fill in."
9630
10038
  )
9631
10039
  )
@@ -9670,6 +10078,8 @@ function observe(_0) {
9670
10078
  const { data: observeData, usage: observeUsage } = rawResponse;
9671
10079
  const promptTokens = (_a = observeUsage == null ? void 0 : observeUsage.prompt_tokens) != null ? _a : 0;
9672
10080
  const completionTokens = (_b = observeUsage == null ? void 0 : observeUsage.completion_tokens) != null ? _b : 0;
10081
+ const reasoningTokens = (_c = observeUsage == null ? void 0 : observeUsage.reasoning_tokens) != null ? _c : 0;
10082
+ const cachedInputTokens = (_d = observeUsage == null ? void 0 : observeUsage.cached_input_tokens) != null ? _d : 0;
9673
10083
  let responseFile = "";
9674
10084
  if (logInferenceToFile) {
9675
10085
  const { fileName: responseFileName } = writeTimestampedTxtFile(
@@ -9688,10 +10098,12 @@ function observe(_0) {
9688
10098
  LLM_output_file: responseFile,
9689
10099
  prompt_tokens: promptTokens,
9690
10100
  completion_tokens: completionTokens,
10101
+ reasoning_tokens: reasoningTokens,
10102
+ cached_input_tokens: cachedInputTokens,
9691
10103
  inference_time_ms: usageTimeMs
9692
10104
  });
9693
10105
  }
9694
- const parsedElements = (_d = (_c = observeData.elements) == null ? void 0 : _c.map((el) => {
10106
+ const parsedElements = (_f = (_e = observeData.elements) == null ? void 0 : _e.map((el) => {
9695
10107
  const base = {
9696
10108
  elementId: el.elementId,
9697
10109
  description: String(el.description),
@@ -9699,11 +10111,13 @@ function observe(_0) {
9699
10111
  arguments: el.arguments
9700
10112
  };
9701
10113
  return base;
9702
- })) != null ? _d : [];
10114
+ })) != null ? _f : [];
9703
10115
  return {
9704
10116
  elements: parsedElements,
9705
10117
  prompt_tokens: promptTokens,
9706
10118
  completion_tokens: completionTokens,
10119
+ reasoning_tokens: reasoningTokens,
10120
+ cached_input_tokens: cachedInputTokens,
9707
10121
  inference_time_ms: usageTimeMs
9708
10122
  };
9709
10123
  });
@@ -9717,22 +10131,22 @@ function act(_0) {
9717
10131
  logger,
9718
10132
  logInferenceToFile = false
9719
10133
  }) {
9720
- var _a, _b;
10134
+ var _a, _b, _c, _d;
9721
10135
  const isGPT5 = llmClient.modelName.includes("gpt-5");
9722
- const actSchema = import_v32.z.object({
9723
- elementId: import_v32.z.string().describe(
10136
+ const actSchema = import_zod3.z.object({
10137
+ elementId: import_zod3.z.string().describe(
9724
10138
  "the ID string associated with the element. Never include surrounding square brackets. This field must follow the format of 'number-number'."
9725
10139
  ),
9726
- description: import_v32.z.string().describe("a description of the accessible element and its purpose"),
9727
- method: import_v32.z.string().describe(
10140
+ description: import_zod3.z.string().describe("a description of the accessible element and its purpose"),
10141
+ method: import_zod3.z.string().describe(
9728
10142
  "the candidate method/action to interact with the element. Select one of the available Playwright interaction methods."
9729
10143
  ),
9730
- arguments: import_v32.z.array(
9731
- import_v32.z.string().describe(
10144
+ arguments: import_zod3.z.array(
10145
+ import_zod3.z.string().describe(
9732
10146
  "the arguments to pass to the method. For example, for a click, the arguments are empty, but for a fill, the arguments are the value to fill in."
9733
10147
  )
9734
10148
  ),
9735
- twoStep: import_v32.z.boolean()
10149
+ twoStep: import_zod3.z.boolean()
9736
10150
  });
9737
10151
  const messages = [
9738
10152
  buildActSystemPrompt(userProvidedInstructions),
@@ -9772,6 +10186,8 @@ function act(_0) {
9772
10186
  const { data: actData, usage: actUsage } = rawResponse;
9773
10187
  const promptTokens = (_a = actUsage == null ? void 0 : actUsage.prompt_tokens) != null ? _a : 0;
9774
10188
  const completionTokens = (_b = actUsage == null ? void 0 : actUsage.completion_tokens) != null ? _b : 0;
10189
+ const reasoningTokens = (_c = actUsage == null ? void 0 : actUsage.reasoning_tokens) != null ? _c : 0;
10190
+ const cachedInputTokens = (_d = actUsage == null ? void 0 : actUsage.cached_input_tokens) != null ? _d : 0;
9775
10191
  let responseFile = "";
9776
10192
  if (logInferenceToFile) {
9777
10193
  const { fileName: responseFileName } = writeTimestampedTxtFile(
@@ -9790,6 +10206,8 @@ function act(_0) {
9790
10206
  LLM_output_file: responseFile,
9791
10207
  prompt_tokens: promptTokens,
9792
10208
  completion_tokens: completionTokens,
10209
+ reasoning_tokens: reasoningTokens,
10210
+ cached_input_tokens: cachedInputTokens,
9793
10211
  inference_time_ms: usageTimeMs
9794
10212
  });
9795
10213
  }
@@ -9803,6 +10221,8 @@ function act(_0) {
9803
10221
  element: parsedElement,
9804
10222
  prompt_tokens: promptTokens,
9805
10223
  completion_tokens: completionTokens,
10224
+ reasoning_tokens: reasoningTokens,
10225
+ cached_input_tokens: cachedInputTokens,
9806
10226
  inference_time_ms: usageTimeMs,
9807
10227
  twoStep: actData.twoStep
9808
10228
  };
@@ -9813,12 +10233,12 @@ function act(_0) {
9813
10233
  init_logger();
9814
10234
 
9815
10235
  // lib/v3/types/public/methods.ts
9816
- var import_v33 = require("zod/v3");
9817
- var defaultExtractSchema = import_v33.z.object({
9818
- extraction: import_v33.z.string()
10236
+ var import_zod4 = require("zod");
10237
+ var defaultExtractSchema = import_zod4.z.object({
10238
+ extraction: import_zod4.z.string()
9819
10239
  });
9820
- var pageTextSchema = import_v33.z.object({
9821
- pageText: import_v33.z.string()
10240
+ var pageTextSchema = import_zod4.z.object({
10241
+ pageText: import_zod4.z.string()
9822
10242
  });
9823
10243
  var V3FunctionName = /* @__PURE__ */ ((V3FunctionName2) => {
9824
10244
  V3FunctionName2["ACT"] = "ACT";
@@ -10352,7 +10772,7 @@ function waitForDomNetworkQuiet(frame, timeoutMs) {
10352
10772
  ]
10353
10773
  }).catch(() => {
10354
10774
  });
10355
- return new Promise((resolve3) => {
10775
+ return new Promise((resolve2) => {
10356
10776
  const inflight = /* @__PURE__ */ new Set();
10357
10777
  const meta = /* @__PURE__ */ new Map();
10358
10778
  const docByFrame = /* @__PURE__ */ new Map();
@@ -10443,7 +10863,7 @@ function waitForDomNetworkQuiet(frame, timeoutMs) {
10443
10863
  if (quietTimer) clearTimeout(quietTimer);
10444
10864
  if (stalledRequestSweepTimer) clearInterval(stalledRequestSweepTimer);
10445
10865
  clearTimeout(guard);
10446
- resolve3();
10866
+ resolve2();
10447
10867
  };
10448
10868
  });
10449
10869
  });
@@ -10493,7 +10913,7 @@ var ActHandler = class {
10493
10913
  const { instruction, page, variables, timeout, model } = params;
10494
10914
  const llmClient = this.resolveLlmClient(model);
10495
10915
  const doObserveAndAct = () => __async(this, null, function* () {
10496
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
10916
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
10497
10917
  yield waitForDomNetworkQuiet(
10498
10918
  page.mainFrame(),
10499
10919
  this.defaultDomSettleTimeoutMs
@@ -10518,12 +10938,16 @@ var ActHandler = class {
10518
10938
  });
10519
10939
  const actPromptTokens = (_b = actInferenceResponse.prompt_tokens) != null ? _b : 0;
10520
10940
  const actCompletionTokens = (_c = actInferenceResponse.completion_tokens) != null ? _c : 0;
10521
- const actInferenceTimeMs = (_d = actInferenceResponse.inference_time_ms) != null ? _d : 0;
10522
- (_e = this.onMetrics) == null ? void 0 : _e.call(
10941
+ const actReasoningTokens = (_d = actInferenceResponse.reasoning_tokens) != null ? _d : 0;
10942
+ const actCachedInputTokens = (_e = actInferenceResponse.cached_input_tokens) != null ? _e : 0;
10943
+ const actInferenceTimeMs = (_f = actInferenceResponse.inference_time_ms) != null ? _f : 0;
10944
+ (_g = this.onMetrics) == null ? void 0 : _g.call(
10523
10945
  this,
10524
10946
  "ACT" /* ACT */,
10525
10947
  actPromptTokens,
10526
10948
  actCompletionTokens,
10949
+ actReasoningTokens,
10950
+ actCachedInputTokens,
10527
10951
  actInferenceTimeMs
10528
10952
  );
10529
10953
  const raw = actInferenceResponse.element;
@@ -10588,7 +11012,7 @@ var ActHandler = class {
10588
11012
  if (!diffedTree.trim()) {
10589
11013
  diffedTree = combinedTree2;
10590
11014
  }
10591
- const combinedXpathMap2 = (_f = secondSnapshot.combinedXpathMap) != null ? _f : {};
11015
+ const combinedXpathMap2 = (_h = secondSnapshot.combinedXpathMap) != null ? _h : {};
10592
11016
  const previousAction = `method: ${chosen.method}, description: ${chosen.description}, arguments: ${chosen.arguments}`;
10593
11017
  const stepTwoInstructions = buildStepTwoPrompt(
10594
11018
  instruction,
@@ -10606,12 +11030,14 @@ var ActHandler = class {
10606
11030
  logger: v3Logger,
10607
11031
  logInferenceToFile: this.logInferenceToFile
10608
11032
  });
10609
- (_j = this.onMetrics) == null ? void 0 : _j.call(
11033
+ (_n = this.onMetrics) == null ? void 0 : _n.call(
10610
11034
  this,
10611
11035
  "ACT" /* ACT */,
10612
- (_g = action2.prompt_tokens) != null ? _g : 0,
10613
- (_h = action2.completion_tokens) != null ? _h : 0,
10614
- (_i = action2.inference_time_ms) != null ? _i : 0
11036
+ (_i = action2.prompt_tokens) != null ? _i : 0,
11037
+ (_j = action2.completion_tokens) != null ? _j : 0,
11038
+ (_k = action2.reasoning_tokens) != null ? _k : 0,
11039
+ (_l = action2.cached_input_tokens) != null ? _l : 0,
11040
+ (_m = action2.inference_time_ms) != null ? _m : 0
10615
11041
  );
10616
11042
  const raw2 = action2.element;
10617
11043
  const result2 = (() => {
@@ -10679,7 +11105,7 @@ var ActHandler = class {
10679
11105
  }
10680
11106
  actFromObserveResult(action, page, domSettleTimeoutMs, llmClientOverride) {
10681
11107
  return __async(this, null, function* () {
10682
- var _a, _b, _c, _d, _e, _f;
11108
+ var _a, _b, _c, _d, _e, _f, _g, _h;
10683
11109
  const settleTimeout = domSettleTimeoutMs != null ? domSettleTimeoutMs : this.defaultDomSettleTimeoutMs;
10684
11110
  const effectiveClient = llmClientOverride != null ? llmClientOverride : this.llmClient;
10685
11111
  const method = (_a = action.method) == null ? void 0 : _a.trim();
@@ -10756,12 +11182,14 @@ var ActHandler = class {
10756
11182
  logger: v3Logger,
10757
11183
  logInferenceToFile: this.logInferenceToFile
10758
11184
  });
10759
- (_e = this.onMetrics) == null ? void 0 : _e.call(
11185
+ (_g = this.onMetrics) == null ? void 0 : _g.call(
10760
11186
  this,
10761
11187
  "ACT" /* ACT */,
10762
11188
  (_b = actInferenceResponse.prompt_tokens) != null ? _b : 0,
10763
11189
  (_c = actInferenceResponse.completion_tokens) != null ? _c : 0,
10764
- (_d = actInferenceResponse.inference_time_ms) != null ? _d : 0
11190
+ (_d = actInferenceResponse.reasoning_tokens) != null ? _d : 0,
11191
+ (_e = actInferenceResponse.cached_input_tokens) != null ? _e : 0,
11192
+ (_f = actInferenceResponse.inference_time_ms) != null ? _f : 0
10765
11193
  );
10766
11194
  const fallback = actInferenceResponse.element;
10767
11195
  if (!fallback) {
@@ -10775,7 +11203,7 @@ var ActHandler = class {
10775
11203
  let newSelector = action.selector;
10776
11204
  if (typeof fallback.elementId === "string") {
10777
11205
  const enc = fallback.elementId;
10778
- const rawXp = ((_f = snapshot.combinedXpathMap) != null ? _f : {})[enc];
11206
+ const rawXp = ((_h = snapshot.combinedXpathMap) != null ? _h : {})[enc];
10779
11207
  const trimmed = trimTrailingTextNode(rawXp);
10780
11208
  if (trimmed) newSelector = `xpath=${trimmed}`;
10781
11209
  }
@@ -10824,7 +11252,7 @@ var ActHandler = class {
10824
11252
  // lib/v3/handlers/extractHandler.ts
10825
11253
  init_logger();
10826
11254
  init_snapshot();
10827
- var import_v34 = require("zod/v3");
11255
+ var import_zod5 = require("zod");
10828
11256
  init_sdkErrors();
10829
11257
  function transformUrlStringsToNumericIds(schema) {
10830
11258
  const [finalSchema, urlPaths] = transformSchema(schema, []);
@@ -10846,7 +11274,7 @@ var ExtractHandler = class {
10846
11274
  const { instruction, schema, page, selector, timeout, model } = params;
10847
11275
  const llmClient = this.resolveLlmClient(model);
10848
11276
  const doExtract = () => __async(this, null, function* () {
10849
- var _a, _b, _c, _e;
11277
+ var _a, _b, _d;
10850
11278
  const noArgs = !instruction && !schema;
10851
11279
  if (noArgs) {
10852
11280
  const focusSelector2 = (_a = selector == null ? void 0 : selector.replace(/^xpath=/i, "")) != null ? _a : "";
@@ -10877,9 +11305,11 @@ var ExtractHandler = class {
10877
11305
  auxiliary: instruction ? { instruction: { value: instruction, type: "string" } } : void 0
10878
11306
  });
10879
11307
  const baseSchema = schema != null ? schema : defaultExtractSchema;
10880
- const isObjectSchema = !!((_c = baseSchema._def) == null ? void 0 : _c.shape);
11308
+ const isObjectSchema = getZodType(baseSchema) === "object";
10881
11309
  const WRAP_KEY = "value";
10882
- const objectSchema = isObjectSchema ? baseSchema : import_v34.z.object({ [WRAP_KEY]: baseSchema });
11310
+ const objectSchema = isObjectSchema ? baseSchema : import_zod5.z.object({
11311
+ [WRAP_KEY]: baseSchema
11312
+ });
10883
11313
  const [transformedSchema, urlFieldPaths] = transformUrlStringsToNumericIds(objectSchema);
10884
11314
  const extractionResponse = yield extract({
10885
11315
  instruction,
@@ -10890,15 +11320,19 @@ var ExtractHandler = class {
10890
11320
  logger: v3Logger,
10891
11321
  logInferenceToFile: this.logInferenceToFile
10892
11322
  });
10893
- const _d = extractionResponse, {
11323
+ const _c = extractionResponse, {
10894
11324
  metadata: { completed },
10895
11325
  prompt_tokens,
10896
11326
  completion_tokens,
11327
+ reasoning_tokens = 0,
11328
+ cached_input_tokens = 0,
10897
11329
  inference_time_ms
10898
- } = _d, rest = __objRest(_d, [
11330
+ } = _c, rest = __objRest(_c, [
10899
11331
  "metadata",
10900
11332
  "prompt_tokens",
10901
11333
  "completion_tokens",
11334
+ "reasoning_tokens",
11335
+ "cached_input_tokens",
10902
11336
  "inference_time_ms"
10903
11337
  ]);
10904
11338
  let output = rest;
@@ -10918,11 +11352,13 @@ var ExtractHandler = class {
10918
11352
  }
10919
11353
  }
10920
11354
  });
10921
- (_e = this.onMetrics) == null ? void 0 : _e.call(
11355
+ (_d = this.onMetrics) == null ? void 0 : _d.call(
10922
11356
  this,
10923
11357
  "EXTRACT" /* EXTRACT */,
10924
11358
  prompt_tokens,
10925
11359
  completion_tokens,
11360
+ reasoning_tokens,
11361
+ cached_input_tokens,
10926
11362
  inference_time_ms
10927
11363
  );
10928
11364
  const idToUrl = combinedUrlMap != null ? combinedUrlMap : {};
@@ -10941,12 +11377,14 @@ var ExtractHandler = class {
10941
11377
  if (!timeout) return doExtract();
10942
11378
  return yield Promise.race([
10943
11379
  doExtract(),
10944
- new Promise((_, reject) => {
10945
- setTimeout(
10946
- () => reject(new Error(`extract() timed out after ${timeout}ms`)),
10947
- timeout
10948
- );
10949
- })
11380
+ new Promise(
11381
+ (_, reject) => {
11382
+ setTimeout(
11383
+ () => reject(new Error(`extract() timed out after ${timeout}ms`)),
11384
+ timeout
11385
+ );
11386
+ }
11387
+ )
10950
11388
  ]);
10951
11389
  });
10952
11390
  }
@@ -11007,6 +11445,8 @@ var ObserveHandler = class {
11007
11445
  const {
11008
11446
  prompt_tokens = 0,
11009
11447
  completion_tokens = 0,
11448
+ reasoning_tokens = 0,
11449
+ cached_input_tokens = 0,
11010
11450
  inference_time_ms = 0
11011
11451
  } = observationResponse;
11012
11452
  (_c = this.onMetrics) == null ? void 0 : _c.call(
@@ -11014,6 +11454,8 @@ var ObserveHandler = class {
11014
11454
  "OBSERVE" /* OBSERVE */,
11015
11455
  prompt_tokens,
11016
11456
  completion_tokens,
11457
+ reasoning_tokens,
11458
+ cached_input_tokens,
11017
11459
  inference_time_ms
11018
11460
  );
11019
11461
  const elementsWithSelectors = (yield Promise.all(
@@ -11066,11 +11508,11 @@ var ObserveHandler = class {
11066
11508
 
11067
11509
  // lib/v3/agent/tools/v3-goto.ts
11068
11510
  var import_ai = require("ai");
11069
- var import_v35 = require("zod/v3");
11511
+ var import_zod6 = require("zod");
11070
11512
  var createGotoTool = (v3) => (0, import_ai.tool)({
11071
11513
  description: "Navigate to a specific URL",
11072
- inputSchema: import_v35.z.object({
11073
- url: import_v35.z.string().describe("The URL to navigate to")
11514
+ inputSchema: import_zod6.z.object({
11515
+ url: import_zod6.z.string().describe("The URL to navigate to")
11074
11516
  }),
11075
11517
  execute: (_0) => __async(null, [_0], function* ({ url }) {
11076
11518
  var _a;
@@ -11098,11 +11540,11 @@ var createGotoTool = (v3) => (0, import_ai.tool)({
11098
11540
 
11099
11541
  // lib/v3/agent/tools/v3-act.ts
11100
11542
  var import_ai2 = require("ai");
11101
- var import_v36 = require("zod/v3");
11543
+ var import_zod7 = require("zod");
11102
11544
  var createActTool = (v3, executionModel) => (0, import_ai2.tool)({
11103
11545
  description: "Perform an action on the page (click, type). Provide a short, specific phrase that mentions the element type.",
11104
- inputSchema: import_v36.z.object({
11105
- action: import_v36.z.string().describe(
11546
+ inputSchema: import_zod7.z.object({
11547
+ action: import_zod7.z.string().describe(
11106
11548
  'Describe what to click or type, e.g. "click the Login button" or "type "John" into the first name input"'
11107
11549
  )
11108
11550
  }),
@@ -11143,10 +11585,10 @@ var createActTool = (v3, executionModel) => (0, import_ai2.tool)({
11143
11585
 
11144
11586
  // lib/v3/agent/tools/v3-screenshot.ts
11145
11587
  var import_ai3 = require("ai");
11146
- var import_v37 = require("zod/v3");
11588
+ var import_zod8 = require("zod");
11147
11589
  var createScreenshotTool = (v3) => (0, import_ai3.tool)({
11148
11590
  description: "Takes a screenshot (PNG) of the current page. Use this to quickly verify page state.",
11149
- inputSchema: import_v37.z.object({}),
11591
+ inputSchema: import_zod8.z.object({}),
11150
11592
  execute: () => __async(null, null, function* () {
11151
11593
  v3.logger({
11152
11594
  category: "agent",
@@ -11170,11 +11612,11 @@ var createScreenshotTool = (v3) => (0, import_ai3.tool)({
11170
11612
 
11171
11613
  // lib/v3/agent/tools/v3-wait.ts
11172
11614
  var import_ai4 = require("ai");
11173
- var import_v38 = require("zod/v3");
11615
+ var import_zod9 = require("zod");
11174
11616
  var createWaitTool = (v3) => (0, import_ai4.tool)({
11175
11617
  description: "Wait for a specified time",
11176
- inputSchema: import_v38.z.object({
11177
- timeMs: import_v38.z.number().describe("Time in milliseconds")
11618
+ inputSchema: import_zod9.z.object({
11619
+ timeMs: import_zod9.z.number().describe("Time in milliseconds")
11178
11620
  }),
11179
11621
  execute: (_0) => __async(null, [_0], function* ({ timeMs }) {
11180
11622
  v3.logger({
@@ -11188,7 +11630,7 @@ var createWaitTool = (v3) => (0, import_ai4.tool)({
11188
11630
  }
11189
11631
  }
11190
11632
  });
11191
- yield new Promise((resolve3) => setTimeout(resolve3, timeMs));
11633
+ yield new Promise((resolve2) => setTimeout(resolve2, timeMs));
11192
11634
  if (timeMs > 0) {
11193
11635
  v3.recordAgentReplayStep({ type: "wait", timeMs });
11194
11636
  }
@@ -11198,11 +11640,11 @@ var createWaitTool = (v3) => (0, import_ai4.tool)({
11198
11640
 
11199
11641
  // lib/v3/agent/tools/v3-navback.ts
11200
11642
  var import_ai5 = require("ai");
11201
- var import_v39 = require("zod/v3");
11643
+ var import_zod10 = require("zod");
11202
11644
  var createNavBackTool = (v3) => (0, import_ai5.tool)({
11203
11645
  description: "Navigate back to the previous page",
11204
- inputSchema: import_v39.z.object({
11205
- reasoningText: import_v39.z.string().describe("Why you're going back")
11646
+ inputSchema: import_zod10.z.object({
11647
+ reasoningText: import_zod10.z.string().describe("Why you're going back")
11206
11648
  }),
11207
11649
  execute: () => __async(null, null, function* () {
11208
11650
  v3.logger({
@@ -11222,12 +11664,12 @@ var createNavBackTool = (v3) => (0, import_ai5.tool)({
11222
11664
 
11223
11665
  // lib/v3/agent/tools/v3-close.ts
11224
11666
  var import_ai6 = require("ai");
11225
- var import_v310 = require("zod/v3");
11667
+ var import_zod11 = require("zod");
11226
11668
  var createCloseTool = () => (0, import_ai6.tool)({
11227
11669
  description: "Complete the task and close",
11228
- inputSchema: import_v310.z.object({
11229
- reasoning: import_v310.z.string().describe("Summary of what was accomplished"),
11230
- taskComplete: import_v310.z.boolean().describe("Whether the task was completed successfully")
11670
+ inputSchema: import_zod11.z.object({
11671
+ reasoning: import_zod11.z.string().describe("Summary of what was accomplished"),
11672
+ taskComplete: import_zod11.z.boolean().describe("Whether the task was completed successfully")
11231
11673
  }),
11232
11674
  execute: (_0) => __async(null, [_0], function* ({ reasoning, taskComplete }) {
11233
11675
  return { success: true, reasoning, taskComplete };
@@ -11236,10 +11678,10 @@ var createCloseTool = () => (0, import_ai6.tool)({
11236
11678
 
11237
11679
  // lib/v3/agent/tools/v3-ariaTree.ts
11238
11680
  var import_ai7 = require("ai");
11239
- var import_v311 = require("zod/v3");
11681
+ var import_zod12 = require("zod");
11240
11682
  var createAriaTreeTool = (v3) => (0, import_ai7.tool)({
11241
11683
  description: "gets the accessibility (ARIA) hybrid tree text for the current page. use this to understand structure and content.",
11242
- inputSchema: import_v311.z.object({}),
11684
+ inputSchema: import_zod12.z.object({}),
11243
11685
  execute: () => __async(null, null, function* () {
11244
11686
  v3.logger({
11245
11687
  category: "agent",
@@ -11267,17 +11709,17 @@ ${result.content}` }]
11267
11709
 
11268
11710
  // lib/v3/agent/tools/v3-fillform.ts
11269
11711
  var import_ai8 = require("ai");
11270
- var import_v312 = require("zod/v3");
11712
+ var import_zod13 = require("zod");
11271
11713
  var createFillFormTool = (v3, executionModel) => (0, import_ai8.tool)({
11272
11714
  description: `\u{1F4DD} FORM FILL - MULTI-FIELD INPUT TOOL
11273
11715
  For any form with 2+ inputs/textareas. Faster than individual typing.`,
11274
- inputSchema: import_v312.z.object({
11275
- fields: import_v312.z.array(
11276
- import_v312.z.object({
11277
- action: import_v312.z.string().describe(
11716
+ inputSchema: import_zod13.z.object({
11717
+ fields: import_zod13.z.array(
11718
+ import_zod13.z.object({
11719
+ action: import_zod13.z.string().describe(
11278
11720
  'Description of typing action, e.g. "type foo into the email field"'
11279
11721
  ),
11280
- value: import_v312.z.string().describe("Text to type into the target")
11722
+ value: import_zod13.z.string().describe("Text to type into the target")
11281
11723
  })
11282
11724
  ).min(1, "Provide at least one field to fill")
11283
11725
  }),
@@ -11321,12 +11763,12 @@ For any form with 2+ inputs/textareas. Faster than individual typing.`,
11321
11763
 
11322
11764
  // lib/v3/agent/tools/v3-scroll.ts
11323
11765
  var import_ai9 = require("ai");
11324
- var import_v313 = require("zod/v3");
11766
+ var import_zod14 = require("zod");
11325
11767
  var createScrollTool = (v3) => (0, import_ai9.tool)({
11326
11768
  description: "Scroll the page",
11327
- inputSchema: import_v313.z.object({
11328
- pixels: import_v313.z.number().describe("Number of pixels to scroll up or down"),
11329
- direction: import_v313.z.enum(["up", "down"]).describe("Direction to scroll")
11769
+ inputSchema: import_zod14.z.object({
11770
+ pixels: import_zod14.z.number().describe("Number of pixels to scroll up or down"),
11771
+ direction: import_zod14.z.enum(["up", "down"]).describe("Direction to scroll")
11330
11772
  }),
11331
11773
  execute: (_0) => __async(null, [_0], function* ({ pixels, direction }) {
11332
11774
  v3.logger({
@@ -11358,19 +11800,19 @@ var createScrollTool = (v3) => (0, import_ai9.tool)({
11358
11800
 
11359
11801
  // lib/v3/agent/tools/v3-extract.ts
11360
11802
  var import_ai10 = require("ai");
11361
- var import_v314 = require("zod/v3");
11803
+ var import_zod15 = require("zod");
11362
11804
  function evaluateZodSchema(schemaStr, logger) {
11363
11805
  var _a;
11364
11806
  try {
11365
11807
  const fn = new Function("z", `return ${schemaStr}`);
11366
- return fn(import_v314.z);
11808
+ return fn(import_zod15.z);
11367
11809
  } catch (e) {
11368
11810
  logger == null ? void 0 : logger({
11369
11811
  category: "agent",
11370
11812
  message: `Failed to evaluate schema: ${(_a = e == null ? void 0 : e.message) != null ? _a : String(e)}`,
11371
11813
  level: 0
11372
11814
  });
11373
- return import_v314.z.any();
11815
+ return import_zod15.z.any();
11374
11816
  }
11375
11817
  }
11376
11818
  var createExtractTool = (v3, executionModel, logger) => (0, import_ai10.tool)({
@@ -11392,9 +11834,9 @@ var createExtractTool = (v3, executionModel, logger) => (0, import_ai10.tool)({
11392
11834
  3. Extract arrays:
11393
11835
  instruction: "extract all product names and prices"
11394
11836
  schema: "z.object({ products: z.array(z.object({ name: z.string(), price: z.number() })) })"`,
11395
- inputSchema: import_v314.z.object({
11396
- instruction: import_v314.z.string(),
11397
- schema: import_v314.z.string().optional().describe("Zod schema as code, e.g. z.object({ title: z.string() })")
11837
+ inputSchema: import_zod15.z.object({
11838
+ instruction: import_zod15.z.string(),
11839
+ schema: import_zod15.z.string().optional().describe("Zod schema as code, e.g. z.object({ title: z.string() })")
11398
11840
  }),
11399
11841
  execute: (_0) => __async(null, [_0], function* ({ instruction, schema }) {
11400
11842
  var _a;
@@ -11724,6 +12166,8 @@ var V3AgentHandler = class {
11724
12166
  "AGENT" /* AGENT */,
11725
12167
  result.usage.inputTokens || 0,
11726
12168
  result.usage.outputTokens || 0,
12169
+ result.usage.reasoningTokens || 0,
12170
+ result.usage.cachedInputTokens || 0,
11727
12171
  inferenceTimeMs
11728
12172
  );
11729
12173
  }
@@ -11735,6 +12179,8 @@ var V3AgentHandler = class {
11735
12179
  usage: result.usage ? {
11736
12180
  input_tokens: result.usage.inputTokens || 0,
11737
12181
  output_tokens: result.usage.outputTokens || 0,
12182
+ reasoning_tokens: result.usage.reasoningTokens || 0,
12183
+ cached_input_tokens: result.usage.cachedInputTokens || 0,
11738
12184
  inference_time_ms: inferenceTimeMs
11739
12185
  } : void 0
11740
12186
  };
@@ -11802,7 +12248,6 @@ init_sdkErrors();
11802
12248
  // lib/v3/agent/AnthropicCUAClient.ts
11803
12249
  init_sdkErrors();
11804
12250
  var import_sdk = __toESM(require("@anthropic-ai/sdk"));
11805
- var import_zod_to_json_schema = require("zod-to-json-schema");
11806
12251
 
11807
12252
  // lib/v3/agent/AgentClient.ts
11808
12253
  var AgentClient = class {
@@ -12305,7 +12750,19 @@ var AnthropicCUAClient = class extends AgentClient {
12305
12750
  };
12306
12751
  if (this.tools && Object.keys(this.tools).length > 0) {
12307
12752
  const customTools = Object.entries(this.tools).map(([name, tool12]) => {
12308
- const jsonSchema2 = (0, import_zod_to_json_schema.zodToJsonSchema)(tool12.inputSchema);
12753
+ const schema = tool12.inputSchema;
12754
+ if (!schema) {
12755
+ return {
12756
+ name,
12757
+ description: tool12.description,
12758
+ input_schema: {
12759
+ type: "object",
12760
+ properties: {},
12761
+ required: []
12762
+ }
12763
+ };
12764
+ }
12765
+ const jsonSchema2 = toJsonSchema(schema);
12309
12766
  const inputSchema = {
12310
12767
  type: "object",
12311
12768
  properties: jsonSchema2.properties || {},
@@ -12615,7 +13072,7 @@ var AnthropicCUAClient = class extends AgentClient {
12615
13072
  y
12616
13073
  }, input);
12617
13074
  } else if (action === "drag" || action === "left_click_drag") {
12618
- const path6 = input.path || (input.coordinate ? [
13075
+ const path7 = input.path || (input.coordinate ? [
12619
13076
  {
12620
13077
  x: input.start_coordinate[0],
12621
13078
  y: input.start_coordinate[1]
@@ -12627,7 +13084,7 @@ var AnthropicCUAClient = class extends AgentClient {
12627
13084
  ] : []);
12628
13085
  return __spreadValues({
12629
13086
  type: "drag",
12630
- path: path6
13087
+ path: path7
12631
13088
  }, input);
12632
13089
  } else if (action === "wait") {
12633
13090
  return __spreadValues({
@@ -13171,7 +13628,6 @@ init_sdkErrors();
13171
13628
 
13172
13629
  // lib/v3/agent/utils/googleCustomToolHandler.ts
13173
13630
  var import_genai2 = require("@google/genai");
13174
- var import_zod_to_json_schema2 = require("zod-to-json-schema");
13175
13631
  function executeGoogleCustomTool(toolName, toolArgs, tools, functionCall, logger) {
13176
13632
  return __async(this, null, function* () {
13177
13633
  try {
@@ -13239,7 +13695,11 @@ function convertToolSetToFunctionDeclarations(tools) {
13239
13695
  }
13240
13696
  function convertToolToFunctionDeclaration(name, tool12) {
13241
13697
  try {
13242
- const jsonSchema2 = (0, import_zod_to_json_schema2.zodToJsonSchema)(tool12.inputSchema);
13698
+ const schema = tool12.inputSchema;
13699
+ if (!schema) {
13700
+ return null;
13701
+ }
13702
+ const jsonSchema2 = toJsonSchema(schema);
13243
13703
  const parameters = convertJsonSchemaToGoogleParameters(jsonSchema2);
13244
13704
  return {
13245
13705
  name,
@@ -13478,7 +13938,7 @@ var GoogleCUAClient = class extends AgentClient {
13478
13938
  message: `Generating content failed on attempt ${attempt + 1}. Retrying in ${delay2 / 1e3} seconds...`,
13479
13939
  level: 2
13480
13940
  });
13481
- yield new Promise((resolve3) => setTimeout(resolve3, delay2));
13941
+ yield new Promise((resolve2) => setTimeout(resolve2, delay2));
13482
13942
  }
13483
13943
  response = yield this.client.models.generateContent({
13484
13944
  model: this.modelName,
@@ -13576,7 +14036,7 @@ var GoogleCUAClient = class extends AgentClient {
13576
14036
  const nextAction = result.actions[i + 1];
13577
14037
  const isTypingAction = action.type === "type" || nextAction.type === "type";
13578
14038
  const delay2 = isTypingAction ? 500 : 200;
13579
- yield new Promise((resolve3) => setTimeout(resolve3, delay2));
14039
+ yield new Promise((resolve2) => setTimeout(resolve2, delay2));
13580
14040
  }
13581
14041
  } catch (actionError) {
13582
14042
  logger({
@@ -14091,6 +14551,7 @@ var V3CuaAgentHandler = class {
14091
14551
  }
14092
14552
  execute(optionsOrInstruction) {
14093
14553
  return __async(this, null, function* () {
14554
+ var _a, _b;
14094
14555
  const options = typeof optionsOrInstruction === "string" ? { instruction: optionsOrInstruction } : optionsOrInstruction;
14095
14556
  this.highlightCursor = options.highlightCursor !== false;
14096
14557
  const page = yield this.v3.context.awaitActivePage();
@@ -14123,6 +14584,8 @@ var V3CuaAgentHandler = class {
14123
14584
  "AGENT" /* AGENT */,
14124
14585
  result.usage.input_tokens,
14125
14586
  result.usage.output_tokens,
14587
+ (_a = result.usage.reasoning_tokens) != null ? _a : 0,
14588
+ (_b = result.usage.cached_input_tokens) != null ? _b : 0,
14126
14589
  inferenceTimeMs
14127
14590
  );
14128
14591
  }
@@ -14289,13 +14752,13 @@ var V3CuaAgentHandler = class {
14289
14752
  return { success: true };
14290
14753
  }
14291
14754
  case "drag": {
14292
- const { path: path6 } = action;
14293
- if (Array.isArray(path6) && path6.length >= 2) {
14294
- const start = path6[0];
14295
- const end = path6[path6.length - 1];
14755
+ const { path: path7 } = action;
14756
+ if (Array.isArray(path7) && path7.length >= 2) {
14757
+ const start = path7[0];
14758
+ const end = path7[path7.length - 1];
14296
14759
  if (recording) {
14297
14760
  const xps = yield page.dragAndDrop(start.x, start.y, end.x, end.y, {
14298
- steps: Math.min(20, Math.max(5, path6.length)),
14761
+ steps: Math.min(20, Math.max(5, path7.length)),
14299
14762
  delay: 10,
14300
14763
  returnXpath: true
14301
14764
  });
@@ -14317,7 +14780,7 @@ var V3CuaAgentHandler = class {
14317
14780
  }
14318
14781
  } else {
14319
14782
  yield page.dragAndDrop(start.x, start.y, end.x, end.y, {
14320
- steps: Math.min(20, Math.max(5, path6.length)),
14783
+ steps: Math.min(20, Math.max(5, path7.length)),
14321
14784
  delay: 10
14322
14785
  });
14323
14786
  }
@@ -14536,7 +14999,7 @@ function createBrowserbaseSession(apiKey, projectId, params, resumeSessionId) {
14536
14999
  }
14537
15000
 
14538
15001
  // ../../node_modules/.pnpm/chrome-launcher@1.2.0/node_modules/chrome-launcher/dist/chrome-launcher.js
14539
- var fs5 = __toESM(require("fs"), 1);
15002
+ var fs6 = __toESM(require("fs"), 1);
14540
15003
  var net = __toESM(require("net"), 1);
14541
15004
 
14542
15005
  // ../../node_modules/.pnpm/chrome-launcher@1.2.0/node_modules/chrome-launcher/dist/chrome-finder.js
@@ -14548,8 +15011,8 @@ __export(chrome_finder_exports, {
14548
15011
  win32: () => win32,
14549
15012
  wsl: () => wsl
14550
15013
  });
14551
- var import_fs4 = __toESM(require("fs"), 1);
14552
- var import_path4 = __toESM(require("path"), 1);
15014
+ var import_fs5 = __toESM(require("fs"), 1);
15015
+ var import_path5 = __toESM(require("path"), 1);
14553
15016
  var import_os = require("os");
14554
15017
  var import_child_process2 = require("child_process");
14555
15018
  var import_escape_string_regexp = __toESM(require_escape_string_regexp(), 1);
@@ -14893,16 +15356,16 @@ Log.getTimeEntries = () => getEntries();
14893
15356
  var lighthouse_logger_default = Log;
14894
15357
 
14895
15358
  // ../../node_modules/.pnpm/chrome-launcher@1.2.0/node_modules/chrome-launcher/dist/utils.js
14896
- var import_path3 = require("path");
15359
+ var import_path4 = require("path");
14897
15360
  var import_child_process = __toESM(require("child_process"), 1);
14898
- var import_fs3 = require("fs");
15361
+ var import_fs4 = require("fs");
14899
15362
  var import_is_wsl = __toESM(require_is_wsl(), 1);
14900
15363
  function defaults(val, def) {
14901
15364
  return typeof val === "undefined" ? def : val;
14902
15365
  }
14903
15366
  function delay(time) {
14904
15367
  return __async(this, null, function* () {
14905
- return new Promise((resolve3) => setTimeout(resolve3, time));
15368
+ return new Promise((resolve2) => setTimeout(resolve2, time));
14906
15369
  });
14907
15370
  }
14908
15371
  var LauncherError = class extends Error {
@@ -14983,15 +15446,15 @@ function toWSLPath(dir, fallback) {
14983
15446
  return fallback;
14984
15447
  }
14985
15448
  }
14986
- function getLocalAppDataPath(path6) {
15449
+ function getLocalAppDataPath(path7) {
14987
15450
  const userRegExp = /\/mnt\/([a-z])\/Users\/([^\/:]+)\/AppData\//;
14988
- const results = userRegExp.exec(path6) || [];
15451
+ const results = userRegExp.exec(path7) || [];
14989
15452
  return `/mnt/${results[1]}/Users/${results[2]}/AppData/Local`;
14990
15453
  }
14991
- function getWSLLocalAppDataPath(path6) {
15454
+ function getWSLLocalAppDataPath(path7) {
14992
15455
  const userRegExp = /\/([a-z])\/Users\/([^\/:]+)\/AppData\//;
14993
- const results = userRegExp.exec(path6) || [];
14994
- return toWSLPath(`${results[1]}:\\Users\\${results[2]}\\AppData\\Local`, getLocalAppDataPath(path6));
15456
+ const results = userRegExp.exec(path7) || [];
15457
+ return toWSLPath(`${results[1]}:\\Users\\${results[2]}\\AppData\\Local`, getLocalAppDataPath(path7));
14995
15458
  }
14996
15459
  function makeUnixTmpDir() {
14997
15460
  return import_child_process.default.execSync("mktemp -d -t lighthouse.XXXXXXX").toString().trim();
@@ -14999,8 +15462,8 @@ function makeUnixTmpDir() {
14999
15462
  function makeWin32TmpDir() {
15000
15463
  const winTmpPath = process.env.TEMP || process.env.TMP || (process.env.SystemRoot || process.env.windir) + "\\temp";
15001
15464
  const randomNumber = Math.floor(Math.random() * 9e7 + 1e7);
15002
- const tmpdir2 = (0, import_path3.join)(winTmpPath, "lighthouse." + randomNumber);
15003
- (0, import_fs3.mkdirSync)(tmpdir2, { recursive: true });
15465
+ const tmpdir2 = (0, import_path4.join)(winTmpPath, "lighthouse." + randomNumber);
15466
+ (0, import_fs4.mkdirSync)(tmpdir2, { recursive: true });
15004
15467
  return tmpdir2;
15005
15468
  }
15006
15469
 
@@ -15029,7 +15492,7 @@ function darwin() {
15029
15492
  }
15030
15493
  (0, import_child_process2.execSync)(`${LSREGISTER} -dump | grep -i 'google chrome\\( canary\\)\\?\\.app' | awk '{$1=""; print $0}'`).toString().split(newLineRegex).forEach((inst) => {
15031
15494
  suffixes.forEach((suffix) => {
15032
- const execPath = import_path4.default.join(inst.substring(0, inst.indexOf(".app") + 4).trim(), suffix);
15495
+ const execPath = import_path5.default.join(inst.substring(0, inst.indexOf(".app") + 4).trim(), suffix);
15033
15496
  if (canAccess(execPath) && installations.indexOf(execPath) === -1) {
15034
15497
  installations.push(execPath);
15035
15498
  }
@@ -15069,7 +15532,7 @@ function linux() {
15069
15532
  installations.push(customChromePath);
15070
15533
  }
15071
15534
  const desktopInstallationFolders = [
15072
- import_path4.default.join((0, import_os.homedir)(), ".local/share/applications/"),
15535
+ import_path5.default.join((0, import_os.homedir)(), ".local/share/applications/"),
15073
15536
  "/usr/share/applications/"
15074
15537
  ];
15075
15538
  desktopInstallationFolders.forEach((folder) => {
@@ -15117,8 +15580,8 @@ function wsl() {
15117
15580
  function win32() {
15118
15581
  const installations = [];
15119
15582
  const suffixes = [
15120
- `${import_path4.default.sep}Google${import_path4.default.sep}Chrome SxS${import_path4.default.sep}Application${import_path4.default.sep}chrome.exe`,
15121
- `${import_path4.default.sep}Google${import_path4.default.sep}Chrome${import_path4.default.sep}Application${import_path4.default.sep}chrome.exe`
15583
+ `${import_path5.default.sep}Google${import_path5.default.sep}Chrome SxS${import_path5.default.sep}Application${import_path5.default.sep}chrome.exe`,
15584
+ `${import_path5.default.sep}Google${import_path5.default.sep}Chrome${import_path5.default.sep}Application${import_path5.default.sep}chrome.exe`
15122
15585
  ];
15123
15586
  const prefixes = [
15124
15587
  process.env.LOCALAPPDATA,
@@ -15130,7 +15593,7 @@ function win32() {
15130
15593
  installations.push(customChromePath);
15131
15594
  }
15132
15595
  prefixes.forEach((prefix) => suffixes.forEach((suffix) => {
15133
- const chromePath = import_path4.default.join(prefix, suffix);
15596
+ const chromePath = import_path5.default.join(prefix, suffix);
15134
15597
  if (canAccess(chromePath)) {
15135
15598
  installations.push(chromePath);
15136
15599
  }
@@ -15153,7 +15616,7 @@ function canAccess(file) {
15153
15616
  return false;
15154
15617
  }
15155
15618
  try {
15156
- import_fs4.default.accessSync(file);
15619
+ import_fs5.default.accessSync(file);
15157
15620
  return true;
15158
15621
  } catch (e) {
15159
15622
  return false;
@@ -15182,12 +15645,12 @@ function findChromeExecutables(folder) {
15182
15645
  // ../../node_modules/.pnpm/chrome-launcher@1.2.0/node_modules/chrome-launcher/dist/random-port.js
15183
15646
  var import_http = require("http");
15184
15647
  function getRandomPort() {
15185
- return new Promise((resolve3, reject) => {
15648
+ return new Promise((resolve2, reject) => {
15186
15649
  const server = (0, import_http.createServer)();
15187
15650
  server.listen(0);
15188
15651
  server.once("listening", () => {
15189
15652
  const { port } = server.address();
15190
- server.close(() => resolve3(port));
15653
+ server.close(() => resolve2(port));
15191
15654
  });
15192
15655
  server.once("error", reject);
15193
15656
  });
@@ -15316,7 +15779,7 @@ var Launcher = class _Launcher {
15316
15779
  this.opts = opts;
15317
15780
  this.tmpDirandPidFileReady = false;
15318
15781
  this.remoteDebuggingPipes = null;
15319
- this.fs = moduleOverrides.fs || fs5;
15782
+ this.fs = moduleOverrides.fs || fs6;
15320
15783
  this.spawn = moduleOverrides.spawn || import_child_process3.spawn;
15321
15784
  lighthouse_logger_default.setLevel(defaults(this.opts.logLevel, "silent"));
15322
15785
  this.startingUrl = defaults(this.opts.startingUrl, "about:blank");
@@ -15492,7 +15955,7 @@ var Launcher = class _Launcher {
15492
15955
  }
15493
15956
  // resolves if ready, rejects otherwise
15494
15957
  isDebuggerReady() {
15495
- return new Promise((resolve3, reject) => {
15958
+ return new Promise((resolve2, reject) => {
15496
15959
  const client = net.createConnection(this.port, "127.0.0.1");
15497
15960
  client.once("error", (err) => {
15498
15961
  this.cleanup(client);
@@ -15500,14 +15963,14 @@ var Launcher = class _Launcher {
15500
15963
  });
15501
15964
  client.once("connect", () => {
15502
15965
  this.cleanup(client);
15503
- resolve3();
15966
+ resolve2();
15504
15967
  });
15505
15968
  });
15506
15969
  }
15507
15970
  // resolves when debugger is ready, rejects after 10 polls
15508
15971
  waitUntilReady() {
15509
15972
  const launcher = this;
15510
- return new Promise((resolve3, reject) => {
15973
+ return new Promise((resolve2, reject) => {
15511
15974
  let retries = 0;
15512
15975
  let waitStatus = "Waiting for browser.";
15513
15976
  const poll = () => {
@@ -15519,7 +15982,7 @@ var Launcher = class _Launcher {
15519
15982
  lighthouse_logger_default.log("ChromeLauncher", waitStatus);
15520
15983
  launcher.isDebuggerReady().then(() => {
15521
15984
  lighthouse_logger_default.log("ChromeLauncher", waitStatus + `${lighthouse_logger_default.greenify(lighthouse_logger_default.tick)}`);
15522
- resolve3();
15985
+ resolve2();
15523
15986
  }).catch((err) => {
15524
15987
  if (retries > launcher.maxConnectionRetries) {
15525
15988
  lighthouse_logger_default.error("ChromeLauncher", err.message);
@@ -15672,7 +16135,7 @@ var AISdkClient = class extends LLMClient {
15672
16135
  return __async(this, arguments, function* ({
15673
16136
  options
15674
16137
  }) {
15675
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
16138
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
15676
16139
  (_a = this.logger) == null ? void 0 : _a.call(this, {
15677
16140
  category: "aisdk",
15678
16141
  message: "creating chat completion",
@@ -15803,10 +16266,12 @@ var AISdkClient = class extends LLMClient {
15803
16266
  usage: {
15804
16267
  prompt_tokens: (_h = objectResponse.usage.inputTokens) != null ? _h : 0,
15805
16268
  completion_tokens: (_i = objectResponse.usage.outputTokens) != null ? _i : 0,
15806
- total_tokens: (_j = objectResponse.usage.totalTokens) != null ? _j : 0
16269
+ reasoning_tokens: (_j = objectResponse.usage.reasoningTokens) != null ? _j : 0,
16270
+ cached_input_tokens: (_k = objectResponse.usage.cachedInputTokens) != null ? _k : 0,
16271
+ total_tokens: (_l = objectResponse.usage.totalTokens) != null ? _l : 0
15807
16272
  }
15808
16273
  };
15809
- (_k = this.logger) == null ? void 0 : _k.call(this, {
16274
+ (_m = this.logger) == null ? void 0 : _m.call(this, {
15810
16275
  category: "aisdk",
15811
16276
  message: "response",
15812
16277
  level: 1,
@@ -15871,12 +16336,14 @@ var AISdkClient = class extends LLMClient {
15871
16336
  }
15872
16337
  ],
15873
16338
  usage: {
15874
- prompt_tokens: (_l = textResponse.usage.inputTokens) != null ? _l : 0,
15875
- completion_tokens: (_m = textResponse.usage.outputTokens) != null ? _m : 0,
15876
- total_tokens: (_n = textResponse.usage.totalTokens) != null ? _n : 0
16339
+ prompt_tokens: (_n = textResponse.usage.inputTokens) != null ? _n : 0,
16340
+ completion_tokens: (_o = textResponse.usage.outputTokens) != null ? _o : 0,
16341
+ reasoning_tokens: (_p = textResponse.usage.reasoningTokens) != null ? _p : 0,
16342
+ cached_input_tokens: (_q = textResponse.usage.cachedInputTokens) != null ? _q : 0,
16343
+ total_tokens: (_r = textResponse.usage.totalTokens) != null ? _r : 0
15877
16344
  }
15878
16345
  };
15879
- (_o = this.logger) == null ? void 0 : _o.call(this, {
16346
+ (_s = this.logger) == null ? void 0 : _s.call(this, {
15880
16347
  category: "aisdk",
15881
16348
  message: "response",
15882
16349
  level: 2,
@@ -15903,7 +16370,6 @@ var AISdkClient = class extends LLMClient {
15903
16370
 
15904
16371
  // lib/v3/llm/AnthropicClient.ts
15905
16372
  var import_sdk3 = __toESM(require("@anthropic-ai/sdk"));
15906
- var import_zod_to_json_schema3 = require("zod-to-json-schema");
15907
16373
  init_sdkErrors();
15908
16374
  var AnthropicClient = class extends LLMClient {
15909
16375
  constructor({
@@ -16014,7 +16480,7 @@ var AnthropicClient = class extends LLMClient {
16014
16480
  });
16015
16481
  let toolDefinition;
16016
16482
  if (options.response_model) {
16017
- const jsonSchema2 = (0, import_zod_to_json_schema3.zodToJsonSchema)(options.response_model.schema);
16483
+ const jsonSchema2 = toJsonSchema(options.response_model.schema);
16018
16484
  const { properties: schemaProperties, required: schemaRequired } = extractSchemaProperties(jsonSchema2);
16019
16485
  toolDefinition = {
16020
16486
  name: "print_extracted_data",
@@ -16146,7 +16612,6 @@ var extractSchemaProperties = (jsonSchema2) => {
16146
16612
 
16147
16613
  // lib/v3/llm/CerebrasClient.ts
16148
16614
  var import_openai2 = __toESM(require("openai"));
16149
- var import_zod_to_json_schema4 = require("zod-to-json-schema");
16150
16615
  init_sdkErrors();
16151
16616
  var CerebrasClient = class extends LLMClient {
16152
16617
  constructor({
@@ -16209,7 +16674,7 @@ var CerebrasClient = class extends LLMClient {
16209
16674
  }
16210
16675
  }));
16211
16676
  if (options.response_model) {
16212
- const jsonSchema2 = (0, import_zod_to_json_schema4.zodToJsonSchema)(options.response_model.schema);
16677
+ const jsonSchema2 = toJsonSchema(options.response_model.schema);
16213
16678
  const schemaProperties = jsonSchema2.properties || {};
16214
16679
  const schemaRequired = jsonSchema2.required || [];
16215
16680
  const responseTool = {
@@ -16714,7 +17179,7 @@ ${firstPartText.text}`;
16714
17179
  level: 1
16715
17180
  });
16716
17181
  yield new Promise(
16717
- (resolve3) => setTimeout(resolve3, 1e3 * (4 - retries))
17182
+ (resolve2) => setTimeout(resolve2, 1e3 * (4 - retries))
16718
17183
  );
16719
17184
  return this.createChatCompletion({
16720
17185
  options,
@@ -16735,7 +17200,6 @@ ${firstPartText.text}`;
16735
17200
 
16736
17201
  // lib/v3/llm/GroqClient.ts
16737
17202
  var import_openai3 = __toESM(require("openai"));
16738
- var import_zod_to_json_schema5 = require("zod-to-json-schema");
16739
17203
  init_sdkErrors();
16740
17204
  var GroqClient = class extends LLMClient {
16741
17205
  constructor({
@@ -16798,7 +17262,7 @@ var GroqClient = class extends LLMClient {
16798
17262
  }
16799
17263
  }));
16800
17264
  if (options.response_model) {
16801
- const jsonSchema2 = (0, import_zod_to_json_schema5.zodToJsonSchema)(options.response_model.schema);
17265
+ const jsonSchema2 = toJsonSchema(options.response_model.schema);
16802
17266
  const schemaProperties = jsonSchema2.properties || {};
16803
17267
  const schemaRequired = jsonSchema2.required || [];
16804
17268
  const responseTool = {
@@ -16956,8 +17420,7 @@ var GroqClient = class extends LLMClient {
16956
17420
 
16957
17421
  // lib/v3/llm/OpenAIClient.ts
16958
17422
  var import_openai4 = __toESM(require("openai"));
16959
- var import_zod = require("openai/helpers/zod");
16960
- var import_zod_to_json_schema6 = __toESM(require("zod-to-json-schema"));
17423
+ var import_zod16 = require("openai/helpers/zod");
16961
17424
  init_sdkErrors();
16962
17425
  var OpenAIClient = class extends LLMClient {
16963
17426
  constructor({
@@ -17064,12 +17527,12 @@ ${JSON.stringify(
17064
17527
  };
17065
17528
  options.messages.push(screenshotMessage);
17066
17529
  }
17067
- let responseFormat = void 0;
17530
+ let responseFormat;
17068
17531
  if (options.response_model) {
17069
17532
  if (this.modelName.startsWith("o1") || this.modelName.startsWith("o3")) {
17070
17533
  try {
17071
17534
  const parsedSchema = JSON.stringify(
17072
- (0, import_zod_to_json_schema6.default)(options.response_model.schema)
17535
+ toJsonSchema(options.response_model.schema)
17073
17536
  );
17074
17537
  options.messages.push({
17075
17538
  role: "user",
@@ -17094,11 +17557,19 @@ ${parsedSchema}
17094
17557
  }
17095
17558
  throw error;
17096
17559
  }
17097
- } else {
17098
- responseFormat = (0, import_zod.zodResponseFormat)(
17560
+ } else if (isZod4Schema(options.response_model.schema)) {
17561
+ responseFormat = (0, import_zod16.zodResponseFormat)(
17099
17562
  options.response_model.schema,
17100
17563
  options.response_model.name
17101
17564
  );
17565
+ } else {
17566
+ responseFormat = {
17567
+ type: "json_schema",
17568
+ json_schema: {
17569
+ name: options.response_model.name,
17570
+ schema: toJsonSchema(options.response_model.schema)
17571
+ }
17572
+ };
17102
17573
  }
17103
17574
  }
17104
17575
  const _d = __spreadProps(__spreadValues({}, optionsWithoutImageAndRequestId), {
@@ -17279,7 +17750,7 @@ ${parsedSchema}
17279
17750
  }
17280
17751
  };
17281
17752
 
17282
- // ../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.12_zod@3.25.67/node_modules/@ai-sdk/provider-utils/dist/index.mjs
17753
+ // ../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.12_zod@4.1.12/node_modules/@ai-sdk/provider-utils/dist/index.mjs
17283
17754
  var import_provider = require("@ai-sdk/provider");
17284
17755
  var import_provider2 = require("@ai-sdk/provider");
17285
17756
  var import_provider3 = require("@ai-sdk/provider");
@@ -17416,14 +17887,14 @@ var EventSourceParserStream = class extends TransformStream {
17416
17887
  }
17417
17888
  };
17418
17889
 
17419
- // ../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.12_zod@3.25.67/node_modules/@ai-sdk/provider-utils/dist/index.mjs
17890
+ // ../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.12_zod@4.1.12/node_modules/@ai-sdk/provider-utils/dist/index.mjs
17420
17891
  var import_provider9 = require("@ai-sdk/provider");
17421
17892
  var import_provider10 = require("@ai-sdk/provider");
17422
17893
  var import_provider11 = require("@ai-sdk/provider");
17423
17894
  var z42 = __toESM(require("zod/v4"), 1);
17424
- var import_v315 = require("zod/v3");
17425
- var import_v316 = require("zod/v3");
17426
- var import_v317 = require("zod/v3");
17895
+ var import_v32 = require("zod/v3");
17896
+ var import_v33 = require("zod/v3");
17897
+ var import_v34 = require("zod/v3");
17427
17898
  function combineHeaders(...headers) {
17428
17899
  return headers.reduce(
17429
17900
  (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
@@ -18040,7 +18511,7 @@ function createProviderDefinedToolFactoryWithOutputSchema({
18040
18511
  });
18041
18512
  };
18042
18513
  }
18043
- function resolve2(value) {
18514
+ function resolve(value) {
18044
18515
  return __async(this, null, function* () {
18045
18516
  if (typeof value === "function") {
18046
18517
  value = value();
@@ -18240,7 +18711,7 @@ function parseArrayDef(def, refs) {
18240
18711
  const res = {
18241
18712
  type: "array"
18242
18713
  };
18243
- if (((_a = def.type) == null ? void 0 : _a._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== import_v316.ZodFirstPartyTypeKind.ZodAny) {
18714
+ if (((_a = def.type) == null ? void 0 : _a._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== import_v33.ZodFirstPartyTypeKind.ZodAny) {
18244
18715
  res.items = parseDef(def.type._def, __spreadProps(__spreadValues({}, refs), {
18245
18716
  currentPath: [...refs.currentPath, "items"]
18246
18717
  }));
@@ -18729,18 +19200,18 @@ function parseRecordDef(def, refs) {
18729
19200
  currentPath: [...refs.currentPath, "additionalProperties"]
18730
19201
  }))) != null ? _a : refs.allowedAdditionalProperties
18731
19202
  };
18732
- if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === import_v317.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
19203
+ if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === import_v34.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
18733
19204
  const _a2 = parseStringDef(def.keyType._def, refs), { type } = _a2, keyType = __objRest(_a2, ["type"]);
18734
19205
  return __spreadProps(__spreadValues({}, schema), {
18735
19206
  propertyNames: keyType
18736
19207
  });
18737
- } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === import_v317.ZodFirstPartyTypeKind.ZodEnum) {
19208
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === import_v34.ZodFirstPartyTypeKind.ZodEnum) {
18738
19209
  return __spreadProps(__spreadValues({}, schema), {
18739
19210
  propertyNames: {
18740
19211
  enum: def.keyType._def.values
18741
19212
  }
18742
19213
  });
18743
- } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === import_v317.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === import_v317.ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
19214
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === import_v34.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === import_v34.ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
18744
19215
  const _b2 = parseBrandedDef(
18745
19216
  def.keyType._def,
18746
19217
  refs
@@ -19066,73 +19537,73 @@ var parseReadonlyDef = (def, refs) => {
19066
19537
  };
19067
19538
  var selectParser = (def, typeName, refs) => {
19068
19539
  switch (typeName) {
19069
- case import_v315.ZodFirstPartyTypeKind.ZodString:
19540
+ case import_v32.ZodFirstPartyTypeKind.ZodString:
19070
19541
  return parseStringDef(def, refs);
19071
- case import_v315.ZodFirstPartyTypeKind.ZodNumber:
19542
+ case import_v32.ZodFirstPartyTypeKind.ZodNumber:
19072
19543
  return parseNumberDef(def);
19073
- case import_v315.ZodFirstPartyTypeKind.ZodObject:
19544
+ case import_v32.ZodFirstPartyTypeKind.ZodObject:
19074
19545
  return parseObjectDef(def, refs);
19075
- case import_v315.ZodFirstPartyTypeKind.ZodBigInt:
19546
+ case import_v32.ZodFirstPartyTypeKind.ZodBigInt:
19076
19547
  return parseBigintDef(def);
19077
- case import_v315.ZodFirstPartyTypeKind.ZodBoolean:
19548
+ case import_v32.ZodFirstPartyTypeKind.ZodBoolean:
19078
19549
  return parseBooleanDef();
19079
- case import_v315.ZodFirstPartyTypeKind.ZodDate:
19550
+ case import_v32.ZodFirstPartyTypeKind.ZodDate:
19080
19551
  return parseDateDef(def, refs);
19081
- case import_v315.ZodFirstPartyTypeKind.ZodUndefined:
19552
+ case import_v32.ZodFirstPartyTypeKind.ZodUndefined:
19082
19553
  return parseUndefinedDef();
19083
- case import_v315.ZodFirstPartyTypeKind.ZodNull:
19554
+ case import_v32.ZodFirstPartyTypeKind.ZodNull:
19084
19555
  return parseNullDef();
19085
- case import_v315.ZodFirstPartyTypeKind.ZodArray:
19556
+ case import_v32.ZodFirstPartyTypeKind.ZodArray:
19086
19557
  return parseArrayDef(def, refs);
19087
- case import_v315.ZodFirstPartyTypeKind.ZodUnion:
19088
- case import_v315.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
19558
+ case import_v32.ZodFirstPartyTypeKind.ZodUnion:
19559
+ case import_v32.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
19089
19560
  return parseUnionDef(def, refs);
19090
- case import_v315.ZodFirstPartyTypeKind.ZodIntersection:
19561
+ case import_v32.ZodFirstPartyTypeKind.ZodIntersection:
19091
19562
  return parseIntersectionDef(def, refs);
19092
- case import_v315.ZodFirstPartyTypeKind.ZodTuple:
19563
+ case import_v32.ZodFirstPartyTypeKind.ZodTuple:
19093
19564
  return parseTupleDef(def, refs);
19094
- case import_v315.ZodFirstPartyTypeKind.ZodRecord:
19565
+ case import_v32.ZodFirstPartyTypeKind.ZodRecord:
19095
19566
  return parseRecordDef(def, refs);
19096
- case import_v315.ZodFirstPartyTypeKind.ZodLiteral:
19567
+ case import_v32.ZodFirstPartyTypeKind.ZodLiteral:
19097
19568
  return parseLiteralDef(def);
19098
- case import_v315.ZodFirstPartyTypeKind.ZodEnum:
19569
+ case import_v32.ZodFirstPartyTypeKind.ZodEnum:
19099
19570
  return parseEnumDef(def);
19100
- case import_v315.ZodFirstPartyTypeKind.ZodNativeEnum:
19571
+ case import_v32.ZodFirstPartyTypeKind.ZodNativeEnum:
19101
19572
  return parseNativeEnumDef(def);
19102
- case import_v315.ZodFirstPartyTypeKind.ZodNullable:
19573
+ case import_v32.ZodFirstPartyTypeKind.ZodNullable:
19103
19574
  return parseNullableDef(def, refs);
19104
- case import_v315.ZodFirstPartyTypeKind.ZodOptional:
19575
+ case import_v32.ZodFirstPartyTypeKind.ZodOptional:
19105
19576
  return parseOptionalDef(def, refs);
19106
- case import_v315.ZodFirstPartyTypeKind.ZodMap:
19577
+ case import_v32.ZodFirstPartyTypeKind.ZodMap:
19107
19578
  return parseMapDef(def, refs);
19108
- case import_v315.ZodFirstPartyTypeKind.ZodSet:
19579
+ case import_v32.ZodFirstPartyTypeKind.ZodSet:
19109
19580
  return parseSetDef(def, refs);
19110
- case import_v315.ZodFirstPartyTypeKind.ZodLazy:
19581
+ case import_v32.ZodFirstPartyTypeKind.ZodLazy:
19111
19582
  return () => def.getter()._def;
19112
- case import_v315.ZodFirstPartyTypeKind.ZodPromise:
19583
+ case import_v32.ZodFirstPartyTypeKind.ZodPromise:
19113
19584
  return parsePromiseDef(def, refs);
19114
- case import_v315.ZodFirstPartyTypeKind.ZodNaN:
19115
- case import_v315.ZodFirstPartyTypeKind.ZodNever:
19585
+ case import_v32.ZodFirstPartyTypeKind.ZodNaN:
19586
+ case import_v32.ZodFirstPartyTypeKind.ZodNever:
19116
19587
  return parseNeverDef();
19117
- case import_v315.ZodFirstPartyTypeKind.ZodEffects:
19588
+ case import_v32.ZodFirstPartyTypeKind.ZodEffects:
19118
19589
  return parseEffectsDef(def, refs);
19119
- case import_v315.ZodFirstPartyTypeKind.ZodAny:
19590
+ case import_v32.ZodFirstPartyTypeKind.ZodAny:
19120
19591
  return parseAnyDef();
19121
- case import_v315.ZodFirstPartyTypeKind.ZodUnknown:
19592
+ case import_v32.ZodFirstPartyTypeKind.ZodUnknown:
19122
19593
  return parseUnknownDef();
19123
- case import_v315.ZodFirstPartyTypeKind.ZodDefault:
19594
+ case import_v32.ZodFirstPartyTypeKind.ZodDefault:
19124
19595
  return parseDefaultDef(def, refs);
19125
- case import_v315.ZodFirstPartyTypeKind.ZodBranded:
19596
+ case import_v32.ZodFirstPartyTypeKind.ZodBranded:
19126
19597
  return parseBrandedDef(def, refs);
19127
- case import_v315.ZodFirstPartyTypeKind.ZodReadonly:
19598
+ case import_v32.ZodFirstPartyTypeKind.ZodReadonly:
19128
19599
  return parseReadonlyDef(def, refs);
19129
- case import_v315.ZodFirstPartyTypeKind.ZodCatch:
19600
+ case import_v32.ZodFirstPartyTypeKind.ZodCatch:
19130
19601
  return parseCatchDef(def, refs);
19131
- case import_v315.ZodFirstPartyTypeKind.ZodPipeline:
19602
+ case import_v32.ZodFirstPartyTypeKind.ZodPipeline:
19132
19603
  return parsePipelineDef(def, refs);
19133
- case import_v315.ZodFirstPartyTypeKind.ZodFunction:
19134
- case import_v315.ZodFirstPartyTypeKind.ZodVoid:
19135
- case import_v315.ZodFirstPartyTypeKind.ZodSymbol:
19604
+ case import_v32.ZodFirstPartyTypeKind.ZodFunction:
19605
+ case import_v32.ZodFirstPartyTypeKind.ZodVoid:
19606
+ case import_v32.ZodFirstPartyTypeKind.ZodSymbol:
19136
19607
  return void 0;
19137
19608
  default:
19138
19609
  return /* @__PURE__ */ ((_) => void 0)(typeName);
@@ -19219,7 +19690,7 @@ var getRefs = (options) => {
19219
19690
  )
19220
19691
  });
19221
19692
  };
19222
- var zodToJsonSchema7 = (schema, options) => {
19693
+ var zodToJsonSchema2 = (schema, options) => {
19223
19694
  var _a;
19224
19695
  const refs = getRefs(options);
19225
19696
  let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
@@ -19264,7 +19735,7 @@ var zodToJsonSchema7 = (schema, options) => {
19264
19735
  combined.$schema = "http://json-schema.org/draft-07/schema#";
19265
19736
  return combined;
19266
19737
  };
19267
- var zod_to_json_schema_default = zodToJsonSchema7;
19738
+ var zod_to_json_schema_default = zodToJsonSchema2;
19268
19739
  function zod3Schema(zodSchema2, options) {
19269
19740
  var _a;
19270
19741
  const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
@@ -19299,11 +19770,11 @@ function zod4Schema(zodSchema2, options) {
19299
19770
  }
19300
19771
  );
19301
19772
  }
19302
- function isZod4Schema(zodSchema2) {
19773
+ function isZod4Schema2(zodSchema2) {
19303
19774
  return "_zod" in zodSchema2;
19304
19775
  }
19305
19776
  function zodSchema(zodSchema2, options) {
19306
- if (isZod4Schema(zodSchema2)) {
19777
+ if (isZod4Schema2(zodSchema2)) {
19307
19778
  return zod4Schema(zodSchema2, options);
19308
19779
  } else {
19309
19780
  return zod3Schema(zodSchema2, options);
@@ -19356,7 +19827,7 @@ function withoutTrailingSlash(url) {
19356
19827
  return url == null ? void 0 : url.replace(/\/$/, "");
19357
19828
  }
19358
19829
 
19359
- // ../../node_modules/.pnpm/@ai-sdk+openai@2.0.53_zod@3.25.67/node_modules/@ai-sdk/openai/dist/index.mjs
19830
+ // ../../node_modules/.pnpm/@ai-sdk+openai@2.0.53_zod@4.1.12/node_modules/@ai-sdk/openai/dist/index.mjs
19360
19831
  var import_provider12 = require("@ai-sdk/provider");
19361
19832
  var import_v4 = require("zod/v4");
19362
19833
  var import_provider13 = require("@ai-sdk/provider");
@@ -23674,37 +24145,37 @@ function createOpenAI(options = {}) {
23674
24145
  );
23675
24146
  const createChatModel = (modelId) => new OpenAIChatLanguageModel(modelId, {
23676
24147
  provider: `${providerName}.chat`,
23677
- url: ({ path: path6 }) => `${baseURL}${path6}`,
24148
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23678
24149
  headers: getHeaders,
23679
24150
  fetch: options.fetch
23680
24151
  });
23681
24152
  const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, {
23682
24153
  provider: `${providerName}.completion`,
23683
- url: ({ path: path6 }) => `${baseURL}${path6}`,
24154
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23684
24155
  headers: getHeaders,
23685
24156
  fetch: options.fetch
23686
24157
  });
23687
24158
  const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, {
23688
24159
  provider: `${providerName}.embedding`,
23689
- url: ({ path: path6 }) => `${baseURL}${path6}`,
24160
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23690
24161
  headers: getHeaders,
23691
24162
  fetch: options.fetch
23692
24163
  });
23693
24164
  const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
23694
24165
  provider: `${providerName}.image`,
23695
- url: ({ path: path6 }) => `${baseURL}${path6}`,
24166
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23696
24167
  headers: getHeaders,
23697
24168
  fetch: options.fetch
23698
24169
  });
23699
24170
  const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, {
23700
24171
  provider: `${providerName}.transcription`,
23701
- url: ({ path: path6 }) => `${baseURL}${path6}`,
24172
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23702
24173
  headers: getHeaders,
23703
24174
  fetch: options.fetch
23704
24175
  });
23705
24176
  const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
23706
24177
  provider: `${providerName}.speech`,
23707
- url: ({ path: path6 }) => `${baseURL}${path6}`,
24178
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23708
24179
  headers: getHeaders,
23709
24180
  fetch: options.fetch
23710
24181
  });
@@ -23719,7 +24190,7 @@ function createOpenAI(options = {}) {
23719
24190
  const createResponsesModel = (modelId) => {
23720
24191
  return new OpenAIResponsesLanguageModel(modelId, {
23721
24192
  provider: `${providerName}.responses`,
23722
- url: ({ path: path6 }) => `${baseURL}${path6}`,
24193
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
23723
24194
  headers: getHeaders,
23724
24195
  fetch: options.fetch,
23725
24196
  fileIdPrefixes: ["file-"]
@@ -23746,7 +24217,7 @@ function createOpenAI(options = {}) {
23746
24217
  }
23747
24218
  var openai = createOpenAI();
23748
24219
 
23749
- // ../../node_modules/.pnpm/@ai-sdk+anthropic@2.0.34_zod@3.25.67/node_modules/@ai-sdk/anthropic/dist/index.mjs
24220
+ // ../../node_modules/.pnpm/@ai-sdk+anthropic@2.0.34_zod@4.1.12/node_modules/@ai-sdk/anthropic/dist/index.mjs
23750
24221
  var import_provider20 = require("@ai-sdk/provider");
23751
24222
  var import_provider21 = require("@ai-sdk/provider");
23752
24223
  var import_v421 = require("zod/v4");
@@ -25627,7 +26098,7 @@ var AnthropicMessagesLanguageModel = class {
25627
26098
  headers
25628
26099
  }) {
25629
26100
  return combineHeaders(
25630
- yield resolve2(this.config.headers),
26101
+ yield resolve(this.config.headers),
25631
26102
  betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {},
25632
26103
  headers
25633
26104
  );
@@ -26785,7 +27256,7 @@ function createAnthropic(options = {}) {
26785
27256
  }
26786
27257
  var anthropic = createAnthropic();
26787
27258
 
26788
- // ../../node_modules/.pnpm/@ai-sdk+google@2.0.23_zod@3.25.67/node_modules/@ai-sdk/google/dist/index.mjs
27259
+ // ../../node_modules/.pnpm/@ai-sdk+google@2.0.23_zod@4.1.12/node_modules/@ai-sdk/google/dist/index.mjs
26789
27260
  var import_provider24 = require("@ai-sdk/provider");
26790
27261
  var import_v437 = require("zod/v4");
26791
27262
  var import_v438 = require("zod/v4");
@@ -26879,7 +27350,7 @@ var GoogleGenerativeAIEmbeddingModel = class {
26879
27350
  });
26880
27351
  }
26881
27352
  const mergedHeaders = combineHeaders(
26882
- yield resolve2(this.config.headers),
27353
+ yield resolve(this.config.headers),
26883
27354
  headers
26884
27355
  );
26885
27356
  if (values.length === 1) {
@@ -27586,7 +28057,7 @@ var GoogleGenerativeAILanguageModel = class {
27586
28057
  const { args, warnings } = yield this.getArgs(options);
27587
28058
  const body = JSON.stringify(args);
27588
28059
  const mergedHeaders = combineHeaders(
27589
- yield resolve2(this.config.headers),
28060
+ yield resolve(this.config.headers),
27590
28061
  options.headers
27591
28062
  );
27592
28063
  const {
@@ -27699,7 +28170,7 @@ var GoogleGenerativeAILanguageModel = class {
27699
28170
  const { args, warnings } = yield this.getArgs(options);
27700
28171
  const body = JSON.stringify(args);
27701
28172
  const headers = combineHeaders(
27702
- yield resolve2(this.config.headers),
28173
+ yield resolve(this.config.headers),
27703
28174
  options.headers
27704
28175
  );
27705
28176
  const { responseHeaders, value: response } = yield postJsonToApi({
@@ -28224,7 +28695,7 @@ var GoogleGenerativeAIImageModel = class {
28224
28695
  };
28225
28696
  const { responseHeaders, value: response } = yield postJsonToApi({
28226
28697
  url: `${this.config.baseURL}/models/${this.modelId}:predict`,
28227
- headers: combineHeaders(yield resolve2(this.config.headers), headers),
28698
+ headers: combineHeaders(yield resolve(this.config.headers), headers),
28228
28699
  body,
28229
28700
  failedResponseHandler: googleFailedResponseHandler,
28230
28701
  successfulResponseHandler: createJsonResponseHandler(
@@ -28337,7 +28808,7 @@ function createGoogleGenerativeAI(options = {}) {
28337
28808
  }
28338
28809
  var google = createGoogleGenerativeAI();
28339
28810
 
28340
- // ../../node_modules/.pnpm/@ai-sdk+openai-compatible@1.0.22_zod@3.25.67/node_modules/@ai-sdk/openai-compatible/dist/index.mjs
28811
+ // ../../node_modules/.pnpm/@ai-sdk+openai-compatible@1.0.22_zod@4.1.12/node_modules/@ai-sdk/openai-compatible/dist/index.mjs
28341
28812
  var import_provider27 = require("@ai-sdk/provider");
28342
28813
  var import_v446 = require("zod/v4");
28343
28814
  var import_provider28 = require("@ai-sdk/provider");
@@ -29657,7 +30128,7 @@ var openaiCompatibleImageResponseSchema = import_v453.z.object({
29657
30128
  data: import_v453.z.array(import_v453.z.object({ b64_json: import_v453.z.string() }))
29658
30129
  });
29659
30130
 
29660
- // ../../node_modules/.pnpm/@ai-sdk+xai@2.0.26_zod@3.25.67/node_modules/@ai-sdk/xai/dist/index.mjs
30131
+ // ../../node_modules/.pnpm/@ai-sdk+xai@2.0.26_zod@4.1.12/node_modules/@ai-sdk/xai/dist/index.mjs
29661
30132
  var import_provider32 = require("@ai-sdk/provider");
29662
30133
  var import_v454 = require("zod/v4");
29663
30134
  var import_provider33 = require("@ai-sdk/provider");
@@ -30391,7 +30862,7 @@ function createXai(options = {}) {
30391
30862
  const createImageModel = (modelId) => {
30392
30863
  return new OpenAICompatibleImageModel(modelId, {
30393
30864
  provider: "xai.image",
30394
- url: ({ path: path6 }) => `${baseURL}${path6}`,
30865
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
30395
30866
  headers: getHeaders,
30396
30867
  fetch: options.fetch,
30397
30868
  errorStructure: xaiErrorStructure
@@ -30409,7 +30880,7 @@ function createXai(options = {}) {
30409
30880
  }
30410
30881
  var xai = createXai();
30411
30882
 
30412
- // ../../node_modules/.pnpm/@ai-sdk+openai@2.0.53_zod@3.25.67/node_modules/@ai-sdk/openai/dist/internal/index.mjs
30883
+ // ../../node_modules/.pnpm/@ai-sdk+openai@2.0.53_zod@4.1.12/node_modules/@ai-sdk/openai/dist/internal/index.mjs
30413
30884
  var import_provider35 = require("@ai-sdk/provider");
30414
30885
  var import_v457 = require("zod/v4");
30415
30886
  var import_provider36 = require("@ai-sdk/provider");
@@ -34632,7 +35103,7 @@ function mapWebSearchOutput2(action) {
34632
35103
  }
34633
35104
  }
34634
35105
 
34635
- // ../../node_modules/.pnpm/@ai-sdk+azure@2.0.54_zod@3.25.67/node_modules/@ai-sdk/azure/dist/index.mjs
35106
+ // ../../node_modules/.pnpm/@ai-sdk+azure@2.0.54_zod@4.1.12/node_modules/@ai-sdk/azure/dist/index.mjs
34636
35107
  var azureOpenaiTools = {
34637
35108
  codeInterpreter: codeInterpreter2,
34638
35109
  fileSearch: fileSearch2,
@@ -34658,14 +35129,14 @@ function createAzure(options = {}) {
34658
35129
  description: "Azure OpenAI resource name"
34659
35130
  });
34660
35131
  const apiVersion = (_a = options.apiVersion) != null ? _a : "v1";
34661
- const url = ({ path: path6, modelId }) => {
35132
+ const url = ({ path: path7, modelId }) => {
34662
35133
  var _a2;
34663
35134
  const baseUrlPrefix = (_a2 = options.baseURL) != null ? _a2 : `https://${getResourceName()}.openai.azure.com/openai`;
34664
35135
  let fullUrl;
34665
35136
  if (options.useDeploymentBasedUrls) {
34666
- fullUrl = new URL(`${baseUrlPrefix}/deployments/${modelId}${path6}`);
35137
+ fullUrl = new URL(`${baseUrlPrefix}/deployments/${modelId}${path7}`);
34667
35138
  } else {
34668
- fullUrl = new URL(`${baseUrlPrefix}/v1${path6}`);
35139
+ fullUrl = new URL(`${baseUrlPrefix}/v1${path7}`);
34669
35140
  }
34670
35141
  fullUrl.searchParams.set("api-version", apiVersion);
34671
35142
  return fullUrl.toString();
@@ -34737,7 +35208,7 @@ function createAzure(options = {}) {
34737
35208
  }
34738
35209
  var azure = createAzure();
34739
35210
 
34740
- // ../../node_modules/.pnpm/@ai-sdk+groq@2.0.24_zod@3.25.67/node_modules/@ai-sdk/groq/dist/index.mjs
35211
+ // ../../node_modules/.pnpm/@ai-sdk+groq@2.0.24_zod@4.1.12/node_modules/@ai-sdk/groq/dist/index.mjs
34741
35212
  var import_provider43 = require("@ai-sdk/provider");
34742
35213
  var import_provider44 = require("@ai-sdk/provider");
34743
35214
  var import_v477 = require("zod/v4");
@@ -35581,7 +36052,7 @@ function createGroq(options = {}) {
35581
36052
  );
35582
36053
  const createChatModel = (modelId) => new GroqChatLanguageModel(modelId, {
35583
36054
  provider: "groq.chat",
35584
- url: ({ path: path6 }) => `${baseURL}${path6}`,
36055
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
35585
36056
  headers: getHeaders,
35586
36057
  fetch: options.fetch
35587
36058
  });
@@ -35596,7 +36067,7 @@ function createGroq(options = {}) {
35596
36067
  const createTranscriptionModel = (modelId) => {
35597
36068
  return new GroqTranscriptionModel(modelId, {
35598
36069
  provider: "groq.transcription",
35599
- url: ({ path: path6 }) => `${baseURL}${path6}`,
36070
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
35600
36071
  headers: getHeaders,
35601
36072
  fetch: options.fetch
35602
36073
  });
@@ -35619,7 +36090,7 @@ function createGroq(options = {}) {
35619
36090
  }
35620
36091
  var groq = createGroq();
35621
36092
 
35622
- // ../../node_modules/.pnpm/@ai-sdk+cerebras@1.0.25_zod@3.25.67/node_modules/@ai-sdk/cerebras/dist/index.mjs
36093
+ // ../../node_modules/.pnpm/@ai-sdk+cerebras@1.0.25_zod@4.1.12/node_modules/@ai-sdk/cerebras/dist/index.mjs
35623
36094
  var import_provider47 = require("@ai-sdk/provider");
35624
36095
  var import_v482 = require("zod/v4");
35625
36096
  var VERSION8 = true ? "1.0.25" : "0.0.0-test";
@@ -35651,7 +36122,7 @@ function createCerebras(options = {}) {
35651
36122
  const createLanguageModel = (modelId) => {
35652
36123
  return new OpenAICompatibleChatLanguageModel(modelId, {
35653
36124
  provider: `cerebras.chat`,
35654
- url: ({ path: path6 }) => `${baseURL}${path6}`,
36125
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
35655
36126
  headers: getHeaders,
35656
36127
  fetch: options.fetch,
35657
36128
  errorStructure: cerebrasErrorStructure,
@@ -35671,7 +36142,7 @@ function createCerebras(options = {}) {
35671
36142
  }
35672
36143
  var cerebras = createCerebras();
35673
36144
 
35674
- // ../../node_modules/.pnpm/@ai-sdk+togetherai@1.0.23_zod@3.25.67/node_modules/@ai-sdk/togetherai/dist/index.mjs
36145
+ // ../../node_modules/.pnpm/@ai-sdk+togetherai@1.0.23_zod@4.1.12/node_modules/@ai-sdk/togetherai/dist/index.mjs
35675
36146
  var import_v483 = require("zod/v4");
35676
36147
  var TogetherAIImageModel = class {
35677
36148
  constructor(modelId, config) {
@@ -35770,7 +36241,7 @@ function createTogetherAI(options = {}) {
35770
36241
  );
35771
36242
  const getCommonModelConfig = (modelType) => ({
35772
36243
  provider: `togetherai.${modelType}`,
35773
- url: ({ path: path6 }) => `${baseURL}${path6}`,
36244
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
35774
36245
  headers: getHeaders,
35775
36246
  fetch: options.fetch
35776
36247
  });
@@ -35802,7 +36273,7 @@ function createTogetherAI(options = {}) {
35802
36273
  }
35803
36274
  var togetherai = createTogetherAI();
35804
36275
 
35805
- // ../../node_modules/.pnpm/@ai-sdk+mistral@2.0.19_zod@3.25.67/node_modules/@ai-sdk/mistral/dist/index.mjs
36276
+ // ../../node_modules/.pnpm/@ai-sdk+mistral@2.0.19_zod@4.1.12/node_modules/@ai-sdk/mistral/dist/index.mjs
35806
36277
  var import_provider48 = require("@ai-sdk/provider");
35807
36278
  var import_v484 = require("zod/v4");
35808
36279
  var import_provider49 = require("@ai-sdk/provider");
@@ -36585,7 +37056,7 @@ function createMistral(options = {}) {
36585
37056
  }
36586
37057
  var mistral = createMistral();
36587
37058
 
36588
- // ../../node_modules/.pnpm/@ai-sdk+deepseek@1.0.23_zod@3.25.67/node_modules/@ai-sdk/deepseek/dist/index.mjs
37059
+ // ../../node_modules/.pnpm/@ai-sdk+deepseek@1.0.23_zod@4.1.12/node_modules/@ai-sdk/deepseek/dist/index.mjs
36589
37060
  var import_provider52 = require("@ai-sdk/provider");
36590
37061
  var import_v488 = require("zod/v4");
36591
37062
  var buildDeepseekMetadata = (usage) => {
@@ -36656,7 +37127,7 @@ function createDeepSeek(options = {}) {
36656
37127
  const createLanguageModel = (modelId) => {
36657
37128
  return new OpenAICompatibleChatLanguageModel(modelId, {
36658
37129
  provider: `deepseek.chat`,
36659
- url: ({ path: path6 }) => `${baseURL}${path6}`,
37130
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
36660
37131
  headers: getHeaders,
36661
37132
  fetch: options.fetch,
36662
37133
  metadataExtractor: deepSeekMetadataExtractor
@@ -36675,7 +37146,7 @@ function createDeepSeek(options = {}) {
36675
37146
  }
36676
37147
  var deepseek = createDeepSeek();
36677
37148
 
36678
- // ../../node_modules/.pnpm/@ai-sdk+perplexity@2.0.13_zod@3.25.67/node_modules/@ai-sdk/perplexity/dist/index.mjs
37149
+ // ../../node_modules/.pnpm/@ai-sdk+perplexity@2.0.13_zod@4.1.12/node_modules/@ai-sdk/perplexity/dist/index.mjs
36679
37150
  var import_provider53 = require("@ai-sdk/provider");
36680
37151
  var import_v489 = require("zod/v4");
36681
37152
  var import_provider54 = require("@ai-sdk/provider");
@@ -37105,7 +37576,7 @@ function createPerplexity(options = {}) {
37105
37576
  }
37106
37577
  var perplexity = createPerplexity();
37107
37578
 
37108
- // ../../node_modules/.pnpm/ollama-ai-provider-v2@1.5.0_zod@3.25.67/node_modules/ollama-ai-provider-v2/dist/index.mjs
37579
+ // ../../node_modules/.pnpm/ollama-ai-provider-v2@1.5.0_zod@4.1.12/node_modules/ollama-ai-provider-v2/dist/index.mjs
37109
37580
  var import_provider55 = require("@ai-sdk/provider");
37110
37581
  var import_v490 = require("zod/v4");
37111
37582
  var import_v491 = require("zod/v4");
@@ -38366,13 +38837,13 @@ function createOllama(options = {}) {
38366
38837
  }, options.headers);
38367
38838
  const createCompletionModel = (modelId, settings = {}) => new OllamaCompletionLanguageModel(modelId, settings, {
38368
38839
  provider: `${providerName}.completion`,
38369
- url: ({ path: path6 }) => `${baseURL}${path6}`,
38840
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
38370
38841
  headers: getHeaders,
38371
38842
  fetch: options.fetch
38372
38843
  });
38373
38844
  const createEmbeddingModel = (modelId, settings = {}) => new OllamaEmbeddingModel(modelId, settings, {
38374
38845
  provider: `${providerName}.embedding`,
38375
- url: ({ path: path6 }) => `${baseURL}${path6}`,
38846
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
38376
38847
  headers: getHeaders,
38377
38848
  fetch: options.fetch
38378
38849
  });
@@ -38387,7 +38858,7 @@ function createOllama(options = {}) {
38387
38858
  const createResponsesModel = (modelId) => {
38388
38859
  return new OllamaResponsesLanguageModel(modelId, {
38389
38860
  provider: `${providerName}.responses`,
38390
- url: ({ path: path6 }) => `${baseURL}${path6}`,
38861
+ url: ({ path: path7 }) => `${baseURL}${path7}`,
38391
38862
  headers: getHeaders,
38392
38863
  fetch: options.fetch
38393
38864
  });
@@ -38723,7 +39194,7 @@ var AISdkClient2 = class extends LLMClient {
38723
39194
  return __async(this, arguments, function* ({
38724
39195
  options
38725
39196
  }) {
38726
- var _a, _b, _c, _d, _e, _f;
39197
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
38727
39198
  const formattedMessages = options.messages.map(
38728
39199
  (message) => {
38729
39200
  if (Array.isArray(message.content)) {
@@ -38784,7 +39255,9 @@ var AISdkClient2 = class extends LLMClient {
38784
39255
  usage: {
38785
39256
  prompt_tokens: (_a = response2.usage.inputTokens) != null ? _a : 0,
38786
39257
  completion_tokens: (_b = response2.usage.outputTokens) != null ? _b : 0,
38787
- total_tokens: (_c = response2.usage.totalTokens) != null ? _c : 0
39258
+ reasoning_tokens: (_c = response2.usage.reasoningTokens) != null ? _c : 0,
39259
+ cached_input_tokens: (_d = response2.usage.cachedInputTokens) != null ? _d : 0,
39260
+ total_tokens: (_e = response2.usage.totalTokens) != null ? _e : 0
38788
39261
  }
38789
39262
  };
38790
39263
  }
@@ -38803,9 +39276,11 @@ var AISdkClient2 = class extends LLMClient {
38803
39276
  return {
38804
39277
  data: response.text,
38805
39278
  usage: {
38806
- prompt_tokens: (_d = response.usage.inputTokens) != null ? _d : 0,
38807
- completion_tokens: (_e = response.usage.outputTokens) != null ? _e : 0,
38808
- total_tokens: (_f = response.usage.totalTokens) != null ? _f : 0
39279
+ prompt_tokens: (_f = response.usage.inputTokens) != null ? _f : 0,
39280
+ completion_tokens: (_g = response.usage.outputTokens) != null ? _g : 0,
39281
+ reasoning_tokens: (_h = response.usage.reasoningTokens) != null ? _h : 0,
39282
+ cached_input_tokens: (_i = response.usage.cachedInputTokens) != null ? _i : 0,
39283
+ total_tokens: (_j = response.usage.totalTokens) != null ? _j : 0
38809
39284
  }
38810
39285
  };
38811
39286
  });
@@ -38855,8 +39330,8 @@ var CdpConnection = class _CdpConnection {
38855
39330
  static connect(wsUrl) {
38856
39331
  return __async(this, null, function* () {
38857
39332
  const ws = new import_ws.default(wsUrl);
38858
- yield new Promise((resolve3, reject) => {
38859
- ws.once("open", () => resolve3());
39333
+ yield new Promise((resolve2, reject) => {
39334
+ ws.once("open", () => resolve2());
38860
39335
  ws.once("error", (e) => reject(e));
38861
39336
  });
38862
39337
  return new _CdpConnection(ws);
@@ -38883,9 +39358,9 @@ var CdpConnection = class _CdpConnection {
38883
39358
  const id = this.nextId++;
38884
39359
  const payload = { id, method, params };
38885
39360
  const stack = (_a = new Error().stack) == null ? void 0 : _a.split("\n").slice(1, 4).join("\n");
38886
- const p = new Promise((resolve3, reject) => {
39361
+ const p = new Promise((resolve2, reject) => {
38887
39362
  this.inflight.set(id, {
38888
- resolve: resolve3,
39363
+ resolve: resolve2,
38889
39364
  reject,
38890
39365
  sessionId: null,
38891
39366
  method,
@@ -38910,8 +39385,8 @@ var CdpConnection = class _CdpConnection {
38910
39385
  }
38911
39386
  close() {
38912
39387
  return __async(this, null, function* () {
38913
- yield new Promise((resolve3) => {
38914
- this.ws.once("close", () => resolve3());
39388
+ yield new Promise((resolve2) => {
39389
+ this.ws.once("close", () => resolve2());
38915
39390
  this.ws.close();
38916
39391
  });
38917
39392
  });
@@ -38983,9 +39458,9 @@ var CdpConnection = class _CdpConnection {
38983
39458
  const id = this.nextId++;
38984
39459
  const payload = { id, method, params, sessionId };
38985
39460
  const stack = (_a = new Error().stack) == null ? void 0 : _a.split("\n").slice(1, 4).join("\n");
38986
- const p = new Promise((resolve3, reject) => {
39461
+ const p = new Promise((resolve2, reject) => {
38987
39462
  this.inflight.set(id, {
38988
- resolve: resolve3,
39463
+ resolve: resolve2,
38989
39464
  reject,
38990
39465
  sessionId,
38991
39466
  method,
@@ -39405,7 +39880,8 @@ var V3Context = class _V3Context {
39405
39880
  session,
39406
39881
  info.targetId,
39407
39882
  this.apiClient,
39408
- this.localBrowserLaunchOptions
39883
+ this.localBrowserLaunchOptions,
39884
+ this.env === "BROWSERBASE"
39409
39885
  );
39410
39886
  this.wireSessionToOwnerPage(sessionId, page);
39411
39887
  this.pagesByTarget.set(info.targetId, page);
@@ -39461,11 +39937,11 @@ var V3Context = class _V3Context {
39461
39937
  try {
39462
39938
  yield session.send("Page.setLifecycleEventsEnabled", { enabled: true }).catch(() => {
39463
39939
  });
39464
- const loadWait = new Promise((resolve3) => {
39940
+ const loadWait = new Promise((resolve2) => {
39465
39941
  const handler = (evt) => {
39466
39942
  if (evt.name === "load") {
39467
39943
  session.off("Page.lifecycleEvent", handler);
39468
- resolve3();
39944
+ resolve2();
39469
39945
  }
39470
39946
  };
39471
39947
  session.on("Page.lifecycleEvent", handler);
@@ -39681,7 +40157,6 @@ function resolveModel(model) {
39681
40157
 
39682
40158
  // lib/v3/api.ts
39683
40159
  var import_fetch_cookie = __toESM(require("fetch-cookie"));
39684
- var import_zod_to_json_schema7 = __toESM(require("zod-to-json-schema"));
39685
40160
  init_version();
39686
40161
  var StagehandAPIClient = class {
39687
40162
  constructor({ apiKey, projectId, logger }) {
@@ -39776,7 +40251,7 @@ var StagehandAPIClient = class {
39776
40251
  options,
39777
40252
  frameId
39778
40253
  }) {
39779
- const jsonSchema2 = zodSchema2 ? (0, import_zod_to_json_schema7.default)(zodSchema2) : void 0;
40254
+ const jsonSchema2 = zodSchema2 ? toJsonSchema(zodSchema2) : void 0;
39780
40255
  const args = {
39781
40256
  schema: jsonSchema2,
39782
40257
  instruction,
@@ -39879,18 +40354,28 @@ var StagehandAPIClient = class {
39879
40354
  const metrics = {
39880
40355
  actPromptTokens: 0,
39881
40356
  actCompletionTokens: 0,
40357
+ actReasoningTokens: 0,
40358
+ actCachedInputTokens: 0,
39882
40359
  actInferenceTimeMs: 0,
39883
40360
  extractPromptTokens: 0,
39884
40361
  extractCompletionTokens: 0,
40362
+ extractReasoningTokens: 0,
40363
+ extractCachedInputTokens: 0,
39885
40364
  extractInferenceTimeMs: 0,
39886
40365
  observePromptTokens: 0,
39887
40366
  observeCompletionTokens: 0,
40367
+ observeReasoningTokens: 0,
40368
+ observeCachedInputTokens: 0,
39888
40369
  observeInferenceTimeMs: 0,
39889
40370
  agentPromptTokens: 0,
39890
40371
  agentCompletionTokens: 0,
40372
+ agentReasoningTokens: 0,
40373
+ agentCachedInputTokens: 0,
39891
40374
  agentInferenceTimeMs: 0,
39892
40375
  totalPromptTokens: 0,
39893
40376
  totalCompletionTokens: 0,
40377
+ totalReasoningTokens: 0,
40378
+ totalCachedInputTokens: 0,
39894
40379
  totalInferenceTimeMs: 0
39895
40380
  };
39896
40381
  const pages = apiData.pages || [];
@@ -39902,26 +40387,38 @@ var StagehandAPIClient = class {
39902
40387
  if (tokenUsage) {
39903
40388
  const inputTokens = tokenUsage.inputTokens || 0;
39904
40389
  const outputTokens = tokenUsage.outputTokens || 0;
40390
+ const reasoningTokens = tokenUsage.reasoningTokens || 0;
40391
+ const cachedInputTokens = tokenUsage.cachedInputTokens || 0;
39905
40392
  const timeMs = tokenUsage.timeMs || 0;
39906
40393
  if (method === "act") {
39907
40394
  metrics.actPromptTokens += inputTokens;
39908
40395
  metrics.actCompletionTokens += outputTokens;
40396
+ metrics.actReasoningTokens += reasoningTokens;
40397
+ metrics.actCachedInputTokens += cachedInputTokens;
39909
40398
  metrics.actInferenceTimeMs += timeMs;
39910
40399
  } else if (method === "extract") {
39911
40400
  metrics.extractPromptTokens += inputTokens;
39912
40401
  metrics.extractCompletionTokens += outputTokens;
40402
+ metrics.extractReasoningTokens += reasoningTokens;
40403
+ metrics.extractCachedInputTokens += cachedInputTokens;
39913
40404
  metrics.extractInferenceTimeMs += timeMs;
39914
40405
  } else if (method === "observe") {
39915
40406
  metrics.observePromptTokens += inputTokens;
39916
40407
  metrics.observeCompletionTokens += outputTokens;
40408
+ metrics.observeReasoningTokens += reasoningTokens;
40409
+ metrics.observeCachedInputTokens += cachedInputTokens;
39917
40410
  metrics.observeInferenceTimeMs += timeMs;
39918
40411
  } else if (method === "agent") {
39919
40412
  metrics.agentPromptTokens += inputTokens;
39920
40413
  metrics.agentCompletionTokens += outputTokens;
40414
+ metrics.agentReasoningTokens += reasoningTokens;
40415
+ metrics.agentCachedInputTokens += cachedInputTokens;
39921
40416
  metrics.agentInferenceTimeMs += timeMs;
39922
40417
  }
39923
40418
  metrics.totalPromptTokens += inputTokens;
39924
40419
  metrics.totalCompletionTokens += outputTokens;
40420
+ metrics.totalReasoningTokens += reasoningTokens;
40421
+ metrics.totalCachedInputTokens += cachedInputTokens;
39925
40422
  metrics.totalInferenceTimeMs += timeMs;
39926
40423
  }
39927
40424
  }
@@ -40015,7 +40512,7 @@ var StagehandAPIClient = class {
40015
40512
  }
40016
40513
  });
40017
40514
  }
40018
- request(path6, options) {
40515
+ request(path7, options) {
40019
40516
  return __async(this, null, function* () {
40020
40517
  var _a;
40021
40518
  const defaultHeaders = {
@@ -40033,7 +40530,7 @@ var StagehandAPIClient = class {
40033
40530
  defaultHeaders["Content-Type"] = "application/json";
40034
40531
  }
40035
40532
  const response = yield this.fetchWithCookies(
40036
- `${(_a = process.env.STAGEHAND_API_URL) != null ? _a : "https://api.stagehand.browserbase.com/v1"}${path6}`,
40533
+ `${(_a = process.env.STAGEHAND_API_URL) != null ? _a : "https://api.stagehand.browserbase.com/v1"}${path7}`,
40037
40534
  __spreadProps(__spreadValues({}, options), {
40038
40535
  headers: __spreadValues(__spreadValues({}, defaultHeaders), options.headers)
40039
40536
  })
@@ -40090,18 +40587,28 @@ var _V3 = class _V3 {
40090
40587
  this.stagehandMetrics = {
40091
40588
  actPromptTokens: 0,
40092
40589
  actCompletionTokens: 0,
40590
+ actReasoningTokens: 0,
40591
+ actCachedInputTokens: 0,
40093
40592
  actInferenceTimeMs: 0,
40094
40593
  extractPromptTokens: 0,
40095
40594
  extractCompletionTokens: 0,
40595
+ extractReasoningTokens: 0,
40596
+ extractCachedInputTokens: 0,
40096
40597
  extractInferenceTimeMs: 0,
40097
40598
  observePromptTokens: 0,
40098
40599
  observeCompletionTokens: 0,
40600
+ observeReasoningTokens: 0,
40601
+ observeCachedInputTokens: 0,
40099
40602
  observeInferenceTimeMs: 0,
40100
40603
  agentPromptTokens: 0,
40101
40604
  agentCompletionTokens: 0,
40605
+ agentReasoningTokens: 0,
40606
+ agentCachedInputTokens: 0,
40102
40607
  agentInferenceTimeMs: 0,
40103
40608
  totalPromptTokens: 0,
40104
40609
  totalCompletionTokens: 0,
40610
+ totalReasoningTokens: 0,
40611
+ totalCachedInputTokens: 0,
40105
40612
  totalInferenceTimeMs: 0
40106
40613
  };
40107
40614
  var _a, _b, _c, _d, _e, _f, _g;
@@ -40285,34 +40792,50 @@ var _V3 = class _V3 {
40285
40792
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
40286
40793
  });
40287
40794
  }
40288
- updateMetrics(functionName, promptTokens, completionTokens, inferenceTimeMs) {
40795
+ updateMetrics(functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs) {
40289
40796
  switch (functionName) {
40290
40797
  case "ACT" /* ACT */:
40291
40798
  this.stagehandMetrics.actPromptTokens += promptTokens;
40292
40799
  this.stagehandMetrics.actCompletionTokens += completionTokens;
40800
+ this.stagehandMetrics.actReasoningTokens += reasoningTokens;
40801
+ this.stagehandMetrics.actCachedInputTokens += cachedInputTokens;
40293
40802
  this.stagehandMetrics.actInferenceTimeMs += inferenceTimeMs;
40294
40803
  break;
40295
40804
  case "EXTRACT" /* EXTRACT */:
40296
40805
  this.stagehandMetrics.extractPromptTokens += promptTokens;
40297
40806
  this.stagehandMetrics.extractCompletionTokens += completionTokens;
40807
+ this.stagehandMetrics.extractReasoningTokens += reasoningTokens;
40808
+ this.stagehandMetrics.extractCachedInputTokens += cachedInputTokens;
40298
40809
  this.stagehandMetrics.extractInferenceTimeMs += inferenceTimeMs;
40299
40810
  break;
40300
40811
  case "OBSERVE" /* OBSERVE */:
40301
40812
  this.stagehandMetrics.observePromptTokens += promptTokens;
40302
40813
  this.stagehandMetrics.observeCompletionTokens += completionTokens;
40814
+ this.stagehandMetrics.observeReasoningTokens += reasoningTokens;
40815
+ this.stagehandMetrics.observeCachedInputTokens += cachedInputTokens;
40303
40816
  this.stagehandMetrics.observeInferenceTimeMs += inferenceTimeMs;
40304
40817
  break;
40305
40818
  case "AGENT" /* AGENT */:
40306
40819
  this.stagehandMetrics.agentPromptTokens += promptTokens;
40307
40820
  this.stagehandMetrics.agentCompletionTokens += completionTokens;
40821
+ this.stagehandMetrics.agentReasoningTokens += reasoningTokens;
40822
+ this.stagehandMetrics.agentCachedInputTokens += cachedInputTokens;
40308
40823
  this.stagehandMetrics.agentInferenceTimeMs += inferenceTimeMs;
40309
40824
  break;
40310
40825
  }
40311
- this.updateTotalMetrics(promptTokens, completionTokens, inferenceTimeMs);
40826
+ this.updateTotalMetrics(
40827
+ promptTokens,
40828
+ completionTokens,
40829
+ reasoningTokens,
40830
+ cachedInputTokens,
40831
+ inferenceTimeMs
40832
+ );
40312
40833
  }
40313
- updateTotalMetrics(promptTokens, completionTokens, inferenceTimeMs) {
40834
+ updateTotalMetrics(promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs) {
40314
40835
  this.stagehandMetrics.totalPromptTokens += promptTokens;
40315
40836
  this.stagehandMetrics.totalCompletionTokens += completionTokens;
40837
+ this.stagehandMetrics.totalReasoningTokens += reasoningTokens;
40838
+ this.stagehandMetrics.totalCachedInputTokens += cachedInputTokens;
40316
40839
  this.stagehandMetrics.totalInferenceTimeMs += inferenceTimeMs;
40317
40840
  }
40318
40841
  _immediateShutdown(reason) {
@@ -40405,10 +40928,12 @@ var _V3 = class _V3 {
40405
40928
  (_a = this.opts.systemPrompt) != null ? _a : "",
40406
40929
  this.logInferenceToFile,
40407
40930
  (_b = this.opts.selfHeal) != null ? _b : true,
40408
- (functionName, promptTokens, completionTokens, inferenceTimeMs) => this.updateMetrics(
40931
+ (functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs) => this.updateMetrics(
40409
40932
  functionName,
40410
40933
  promptTokens,
40411
40934
  completionTokens,
40935
+ reasoningTokens,
40936
+ cachedInputTokens,
40412
40937
  inferenceTimeMs
40413
40938
  ),
40414
40939
  this.domSettleTimeoutMs
@@ -40421,10 +40946,12 @@ var _V3 = class _V3 {
40421
40946
  (_c = this.opts.systemPrompt) != null ? _c : "",
40422
40947
  this.logInferenceToFile,
40423
40948
  this.experimental,
40424
- (functionName, promptTokens, completionTokens, inferenceTimeMs) => this.updateMetrics(
40949
+ (functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs) => this.updateMetrics(
40425
40950
  functionName,
40426
40951
  promptTokens,
40427
40952
  completionTokens,
40953
+ reasoningTokens,
40954
+ cachedInputTokens,
40428
40955
  inferenceTimeMs
40429
40956
  )
40430
40957
  );
@@ -40436,10 +40963,12 @@ var _V3 = class _V3 {
40436
40963
  (_d = this.opts.systemPrompt) != null ? _d : "",
40437
40964
  this.logInferenceToFile,
40438
40965
  this.experimental,
40439
- (functionName, promptTokens, completionTokens, inferenceTimeMs) => this.updateMetrics(
40966
+ (functionName, promptTokens, completionTokens, reasoningTokens, cachedInputTokens, inferenceTimeMs) => this.updateMetrics(
40440
40967
  functionName,
40441
40968
  promptTokens,
40442
40969
  completionTokens,
40970
+ reasoningTokens,
40971
+ cachedInputTokens,
40443
40972
  inferenceTimeMs
40444
40973
  )
40445
40974
  );
@@ -40482,9 +41011,9 @@ var _V3 = class _V3 {
40482
41011
  let userDataDir = lbo.userDataDir;
40483
41012
  let createdTemp = false;
40484
41013
  if (!userDataDir) {
40485
- const base = import_path5.default.join(import_os2.default.tmpdir(), "stagehand-v3");
40486
- import_fs6.default.mkdirSync(base, { recursive: true });
40487
- userDataDir = import_fs6.default.mkdtempSync(import_path5.default.join(base, "profile-"));
41014
+ const base = import_path6.default.join(import_os2.default.tmpdir(), "stagehand-v3");
41015
+ import_fs7.default.mkdirSync(base, { recursive: true });
41016
+ userDataDir = import_fs7.default.mkdtempSync(import_path6.default.join(base, "profile-"));
40488
41017
  createdTemp = true;
40489
41018
  }
40490
41019
  const defaults2 = [
@@ -40915,7 +41444,7 @@ var _V3 = class _V3 {
40915
41444
  }
40916
41445
  try {
40917
41446
  if (this.state.createdTempProfile && !this.state.preserveUserDataDir && this.state.userDataDir) {
40918
- import_fs6.default.rmSync(this.state.userDataDir, { recursive: true, force: true });
41447
+ import_fs7.default.rmSync(this.state.userDataDir, { recursive: true, force: true });
40919
41448
  }
40920
41449
  } catch (e) {
40921
41450
  }
@@ -41262,14 +41791,14 @@ function isObserveResult(v) {
41262
41791
 
41263
41792
  // lib/v3Evaluator.ts
41264
41793
  var import_dotenv2 = __toESM(require("dotenv"));
41265
- var import_v318 = require("zod/v3");
41794
+ var import_zod17 = require("zod");
41266
41795
  init_sdkErrors();
41267
41796
  import_dotenv2.default.config();
41268
- var EvaluationSchema = import_v318.z.object({
41269
- evaluation: import_v318.z.enum(["YES", "NO"]),
41270
- reasoning: import_v318.z.string()
41797
+ var EvaluationSchema = import_zod17.z.object({
41798
+ evaluation: import_zod17.z.enum(["YES", "NO"]),
41799
+ reasoning: import_zod17.z.string()
41271
41800
  });
41272
- var BatchEvaluationSchema = import_v318.z.array(EvaluationSchema);
41801
+ var BatchEvaluationSchema = import_zod17.z.array(EvaluationSchema);
41273
41802
  var V3Evaluator = class {
41274
41803
  constructor(v3, modelName, modelClientOptions) {
41275
41804
  this.silentLogger = () => {