@usecrow/client 0.1.28 → 0.1.30

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.
package/dist/browser.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./PageController-72owMK9b.cjs"),o=require("./browserUse-CMYea2D_.cjs");o.setPageController(t.PageController);function w(e,i){return async n=>{const s=n.instruction||n.instruction;if(!s)return{status:"error",error:"Missing instruction parameter for browser_use tool"};const u=window.__crow_browser_callbacks,r=i||u;return new o.CrowBrowserUse({productId:e.productId,apiUrl:e.apiUrl,onConfirmation:r==null?void 0:r.onConfirmation,onQuestion:r==null?void 0:r.onQuestion,onProgress:r==null?void 0:r.onProgress}).execute(s)}}exports.PageController=t.PageController;exports.CrowBrowserUse=o.CrowBrowserUse;exports.createBrowserUseTool=w;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./browserUse-B-b3zqW1.cjs");e.setPageController(e.PageController);let r=null;function w(){r&&(console.log("[Crow] Stopping active browser-use automation"),r.stop(),r=null)}function a(t,u){return async n=>{const s=n.instruction||n.instruction;if(!s)return{status:"error",error:"Missing instruction parameter for browser_use tool"};const l=window.__crow_browser_callbacks,o=u||l,i=new e.CrowBrowserUse({productId:t.productId,apiUrl:t.apiUrl,onConfirmation:o==null?void 0:o.onConfirmation,onQuestion:o==null?void 0:o.onQuestion,onProgress:o==null?void 0:o.onProgress});r=i;try{return await i.execute(s)}finally{r=null}}}exports.CrowBrowserUse=e.CrowBrowserUse;exports.PageController=e.PageController;exports.createBrowserUseTool=a;exports.stopActiveBrowserUse=w;
package/dist/browser.d.ts CHANGED
@@ -74,6 +74,7 @@ export declare class CrowBrowserUse {
74
74
  private pageController;
75
75
  private sessionId;
76
76
  private maxSteps;
77
+ private aborted;
77
78
  constructor(config: BrowserUseConfig);
78
79
  /**
79
80
  * Initialize PageController with non-blocking pointer
@@ -91,10 +92,6 @@ export declare class CrowBrowserUse {
91
92
  * Process a step on the server
92
93
  */
93
94
  private processStep;
94
- /**
95
- * Submit user's response to an ask_user question
96
- */
97
- private submitUserResponse;
98
95
  /**
99
96
  * Execute an action using PageController
100
97
  */
@@ -329,6 +326,12 @@ declare interface PageControllerConfig extends dom.DomConfig {
329
326
  enableMask?: boolean;
330
327
  }
331
328
 
329
+ /**
330
+ * Stop any currently running browser-use automation.
331
+ * Safe to call even if no automation is running.
332
+ */
333
+ export declare function stopActiveBrowserUse(): void;
334
+
332
335
  declare interface TextDomNode {
333
336
  type: 'TEXT_NODE';
334
337
  text: string;
package/dist/browser.js CHANGED
@@ -1,26 +1,35 @@
1
- import { PageController as i } from "./PageController-BT9YJiz0.js";
2
- import { C as u, s as w } from "./browserUse-CMq8wG4u.js";
3
- w(i);
4
- function m(o, t) {
5
- return async (n) => {
6
- const s = n.instruction || n.instruction;
1
+ import { C as a, s as l, P as w } from "./browserUse-D5NUCzN4.js";
2
+ l(w);
3
+ let r = null;
4
+ function p() {
5
+ r && (console.log("[Crow] Stopping active browser-use automation"), r.stop(), r = null);
6
+ }
7
+ function U(n, i) {
8
+ return async (t) => {
9
+ const s = t.instruction || t.instruction;
7
10
  if (!s)
8
11
  return {
9
12
  status: "error",
10
13
  error: "Missing instruction parameter for browser_use tool"
11
14
  };
12
- const e = window.__crow_browser_callbacks, r = t || e;
13
- return new u({
14
- productId: o.productId,
15
- apiUrl: o.apiUrl,
16
- onConfirmation: r == null ? void 0 : r.onConfirmation,
17
- onQuestion: r == null ? void 0 : r.onQuestion,
18
- onProgress: r == null ? void 0 : r.onProgress
19
- }).execute(s);
15
+ const u = window.__crow_browser_callbacks, o = i || u, e = new a({
16
+ productId: n.productId,
17
+ apiUrl: n.apiUrl,
18
+ onConfirmation: o == null ? void 0 : o.onConfirmation,
19
+ onQuestion: o == null ? void 0 : o.onQuestion,
20
+ onProgress: o == null ? void 0 : o.onProgress
21
+ });
22
+ r = e;
23
+ try {
24
+ return await e.execute(s);
25
+ } finally {
26
+ r = null;
27
+ }
20
28
  };
21
29
  }
22
30
  export {
23
- u as CrowBrowserUse,
24
- i as PageController,
25
- m as createBrowserUseTool
31
+ a as CrowBrowserUse,
32
+ w as PageController,
33
+ U as createBrowserUseTool,
34
+ p as stopActiveBrowserUse
26
35
  };
@@ -0,0 +1,9 @@
1
+ "use strict";async function waitFor(o){await new Promise(e=>setTimeout(e,o*1e3))}async function movePointerToElement(o){const e=o.getBoundingClientRect(),n=e.left+e.width/2,r=e.top+e.height/2;window.dispatchEvent(new CustomEvent("PageAgent::MovePointerTo",{detail:{x:n,y:r}})),await waitFor(.3)}function getElementByIndex(o,e){const n=o.get(e);if(!n)throw new Error(`No interactive element found at index ${e}`);const r=n.ref;if(!r)throw new Error(`Element at index ${e} does not have a reference`);if(!(r instanceof HTMLElement))throw new Error(`Element at index ${e} is not an HTMLElement`);return r}let lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&(lastClickedElement.blur(),lastClickedElement.dispatchEvent(new MouseEvent("mouseout",{bubbles:!0,cancelable:!0})),lastClickedElement=null)}async function clickElement(o){blurLastClickedElement(),lastClickedElement=o,await scrollIntoViewIfNeeded(o),await movePointerToElement(o),window.dispatchEvent(new CustomEvent("PageAgent::ClickPointer")),await waitFor(.1),o.dispatchEvent(new MouseEvent("mouseenter",{bubbles:!0,cancelable:!0})),o.dispatchEvent(new MouseEvent("mouseover",{bubbles:!0,cancelable:!0})),o.dispatchEvent(new MouseEvent("mousedown",{bubbles:!0,cancelable:!0})),o.focus(),o.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0})),o.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),await waitFor(.1)}const nativeInputValueSetter=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value").set,nativeTextAreaValueSetter=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value").set;async function inputTextElement(o,e){if(!(o instanceof HTMLInputElement||o instanceof HTMLTextAreaElement))throw new Error("Element is not an input or textarea");await clickElement(o),o instanceof HTMLTextAreaElement?nativeTextAreaValueSetter.call(o,e):nativeInputValueSetter.call(o,e);const n=new Event("input",{bubbles:!0});o.dispatchEvent(n),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(o,e){if(!(o instanceof HTMLSelectElement))throw new Error("Element is not a select element");const r=Array.from(o.options).find(d=>{var h;return((h=d.textContent)==null?void 0:h.trim())===e.trim()});if(!r)throw new Error(`Option with text "${e}" not found in select element`);o.value=r.value,o.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(o){const e=o;e.scrollIntoViewIfNeeded?e.scrollIntoViewIfNeeded():e.scrollIntoView({behavior:"auto",block:"center",inline:"nearest"})}async function scrollVertically(o,e,n){if(n){const l=n;console.log("[SCROLL DEBUG] Starting direct container scroll for element:",l.tagName);let f=l,v=!1,m=null,c=0,g=0;const C=e;for(;f&&g<10;){const B=window.getComputedStyle(f),D=/(auto|scroll|overlay)/.test(B.overflowY),S=f.scrollHeight>f.clientHeight;if(console.log("[SCROLL DEBUG] Checking element:",f.tagName,"hasScrollableY:",D,"canScrollVertically:",S,"scrollHeight:",f.scrollHeight,"clientHeight:",f.clientHeight),D&&S){const R=f.scrollTop,U=f.scrollHeight-f.clientHeight;let k=C/3;k>0?k=Math.min(k,U-R):k=Math.max(k,-R),f.scrollTop=R+k;const V=f.scrollTop,$=V-R;if(console.log("[SCROLL DEBUG] Scroll attempt:",f.tagName,"before:",R,"after:",V,"delta:",$),Math.abs($)>.5){v=!0,m=f,c=$,console.log("[SCROLL DEBUG] Successfully scrolled container:",f.tagName,"delta:",$);break}}if(f===document.body||f===document.documentElement)break;f=f.parentElement,g++}return v?`Scrolled container (${m==null?void 0:m.tagName}) by ${c}px`:`No scrollable container found for element (${l.tagName})`}const r=e,d=l=>l.clientHeight>=window.innerHeight*.5,h=l=>l&&/(auto|scroll|overlay)/.test(getComputedStyle(l).overflowY)&&l.scrollHeight>l.clientHeight&&d(l);let s=document.activeElement;for(;s&&!h(s)&&s!==document.body;)s=s.parentElement;if(s=h(s)?s:Array.from(document.querySelectorAll("*")).find(h)||document.scrollingElement||document.documentElement,s===document.scrollingElement||s===document.documentElement||s===document.body){const l=window.scrollY,f=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,r);const v=window.scrollY,m=v-l;if(Math.abs(m)<1)return r>0?"⚠️ Already at the bottom of the page, cannot scroll down further.":"⚠️ Already at the top of the page, cannot scroll up further.";const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled page by ${m}px. Reached the bottom of the page.`:g?`✅ Scrolled page by ${m}px. Reached the top of the page.`:`✅ Scrolled page by ${m}px.`}else{const l=s.scrollTop,f=s.scrollHeight-s.clientHeight;s.scrollBy({top:r,behavior:"smooth"}),await waitFor(.1);const v=s.scrollTop,m=v-l;if(Math.abs(m)<1)return r>0?`⚠️ Already at the bottom of container (${s.tagName}), cannot scroll down further.`:`⚠️ Already at the top of container (${s.tagName}), cannot scroll up further.`;const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the bottom.`:g?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the top.`:`✅ Scrolled container (${s.tagName}) by ${m}px.`}}async function scrollHorizontally(o,e,n){if(n){const l=n;console.log("[SCROLL DEBUG] Starting direct container scroll for element:",l.tagName);let f=l,v=!1,m=null,c=0,g=0;const C=o?e:-e;for(;f&&g<10;){const B=window.getComputedStyle(f),D=/(auto|scroll|overlay)/.test(B.overflowX),S=f.scrollWidth>f.clientWidth;if(console.log("[SCROLL DEBUG] Checking element:",f.tagName,"hasScrollableX:",D,"canScrollHorizontally:",S,"scrollWidth:",f.scrollWidth,"clientWidth:",f.clientWidth),D&&S){const R=f.scrollLeft,U=f.scrollWidth-f.clientWidth;let k=C/3;k>0?k=Math.min(k,U-R):k=Math.max(k,-R),f.scrollLeft=R+k;const V=f.scrollLeft,$=V-R;if(console.log("[SCROLL DEBUG] Scroll attempt:",f.tagName,"before:",R,"after:",V,"delta:",$),Math.abs($)>.5){v=!0,m=f,c=$,console.log("[SCROLL DEBUG] Successfully scrolled container:",f.tagName,"delta:",$);break}}if(f===document.body||f===document.documentElement)break;f=f.parentElement,g++}return v?`Scrolled container (${m==null?void 0:m.tagName}) horizontally by ${c}px`:`No horizontally scrollable container found for element (${l.tagName})`}const r=o?e:-e,d=l=>l.clientWidth>=window.innerWidth*.5,h=l=>l&&/(auto|scroll|overlay)/.test(getComputedStyle(l).overflowX)&&l.scrollWidth>l.clientWidth&&d(l);let s=document.activeElement;for(;s&&!h(s)&&s!==document.body;)s=s.parentElement;if(s=h(s)?s:Array.from(document.querySelectorAll("*")).find(h)||document.scrollingElement||document.documentElement,s===document.scrollingElement||s===document.documentElement||s===document.body){const l=window.scrollX,f=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(r,0);const v=window.scrollX,m=v-l;if(Math.abs(m)<1)return r>0?"⚠️ Already at the right edge of the page, cannot scroll right further.":"⚠️ Already at the left edge of the page, cannot scroll left further.";const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled page by ${m}px. Reached the right edge of the page.`:g?`✅ Scrolled page by ${m}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${m}px.`}else{const l=s.scrollLeft,f=s.scrollWidth-s.clientWidth;s.scrollBy({left:r,behavior:"smooth"}),await waitFor(.1);const v=s.scrollLeft,m=v-l;if(Math.abs(m)<1)return r>0?`⚠️ Already at the right edge of container (${s.tagName}), cannot scroll right further.`:`⚠️ Already at the left edge of container (${s.tagName}), cannot scroll left further.`;const c=r>0&&v>=f-1,g=r<0&&v<=1;return c?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the right edge.`:g?`✅ Scrolled container (${s.tagName}) by ${m}px. Reached the left edge.`:`✅ Scrolled container (${s.tagName}) horizontally by ${m}px.`}}const VIEWPORT_EXPANSION=-1,domTree=(o={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:e,interactiveWhitelist:n,highlightOpacity:r,highlightLabelOpacity:d}=o,{doHighlightElements:h,focusHighlightIndex:s,viewportExpansion:l,debugMode:f}=o;let v=0;const m=new WeakMap;function c(t,i){!t||t.nodeType!==Node.ELEMENT_NODE||m.set(t,{...m.get(t),...i})}const g={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{g.boundingRects=new WeakMap,g.clientRects=new WeakMap,g.computedStyles=new WeakMap}};function C(t){if(!t)return null;if(g.boundingRects.has(t))return g.boundingRects.get(t);const i=t.getBoundingClientRect();return i&&g.boundingRects.set(t,i),i}function B(t){if(!t)return null;if(g.computedStyles.has(t))return g.computedStyles.get(t);const i=window.getComputedStyle(t);return i&&g.computedStyles.set(t,i),i}function D(t){if(!t)return null;if(g.clientRects.has(t))return g.clientRects.get(t);const i=t.getClientRects();return i&&g.clientRects.set(t,i),i}const S={},R={current:0},U="playwright-highlight-container";function k(t,i,w=null){if(!t)return i;const u=[];let a=null,x=20,E=16,H=null;try{let b=document.getElementById(U);b||(b=document.createElement("div"),b.id=U,b.style.position="fixed",b.style.pointerEvents="none",b.style.top="0",b.style.left="0",b.style.width="100%",b.style.height="100%",b.style.zIndex="2147483640",b.style.backgroundColor="transparent",document.body.appendChild(b));const P=t.getClientRects();if(!P||P.length===0)return i;const O=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"],p=i%O.length;let y=O[p];const I=y+Math.floor(r*255).toString(16).padStart(2,"0");y=y+Math.floor(d*255).toString(16).padStart(2,"0");let L={x:0,y:0};if(w){const N=w.getBoundingClientRect();L.x=N.left,L.y=N.top}const j=document.createDocumentFragment();for(const N of P){if(N.width===0||N.height===0)continue;const M=document.createElement("div");M.style.position="fixed",M.style.border=`2px solid ${y}`,M.style.backgroundColor=I,M.style.pointerEvents="none",M.style.boxSizing="border-box";const T=N.top+L.y,W=N.left+L.x;M.style.top=`${T}px`,M.style.left=`${W}px`,M.style.width=`${N.width}px`,M.style.height=`${N.height}px`,j.appendChild(M),u.push({element:M,initialRect:N})}const G=P[0];if(d>0){a=document.createElement("div"),a.className="playwright-highlight-label",a.style.position="fixed",a.style.background=y,a.style.color="white",a.style.padding="1px 4px",a.style.borderRadius="4px",a.style.fontSize=`${Math.min(12,Math.max(8,G.height/2))}px`,a.textContent=i.toString(),x=a.offsetWidth>0?a.offsetWidth:x,E=a.offsetHeight>0?a.offsetHeight:E;const N=G.top+L.y,M=G.left+L.x;let T=N+2,W=M+G.width-x-2;(G.width<x+4||G.height<E+4)&&(T=N-E-2,W=M+G.width-x,W<L.x&&(W=M)),T=Math.max(0,Math.min(T,window.innerHeight-E)),W=Math.max(0,Math.min(W,window.innerWidth-x)),a.style.top=`${T}px`,a.style.left=`${W}px`,j.appendChild(a)}const q=((N,M)=>{let T=0;return(...W)=>{const X=performance.now();if(!(X-T<M))return T=X,N(...W)}})(()=>{const N=t.getClientRects();let M={x:0,y:0};if(w){const T=w.getBoundingClientRect();M.x=T.left,M.y=T.top}if(u.forEach((T,W)=>{if(W<N.length){const X=N[W],tt=X.top+M.y,Q=X.left+M.x;T.element.style.top=`${tt}px`,T.element.style.left=`${Q}px`,T.element.style.width=`${X.width}px`,T.element.style.height=`${X.height}px`,T.element.style.display=X.width===0||X.height===0?"none":"block"}else T.element.style.display="none"}),N.length<u.length)for(let T=N.length;T<u.length;T++)u[T].element.style.display="none";if(a&&N.length>0){const T=N[0],W=T.top+M.y,X=T.left+M.x;let tt=W+2,Q=X+T.width-x-2;(T.width<x+4||T.height<E+4)&&(tt=W-E-2,Q=X+T.width-x,Q<M.x&&(Q=X)),tt=Math.max(0,Math.min(tt,window.innerHeight-E)),Q=Math.max(0,Math.min(Q,window.innerWidth-x)),a.style.top=`${tt}px`,a.style.left=`${Q}px`,a.style.display="block"}else a&&(a.style.display="none")},16);return window.addEventListener("scroll",q,!0),window.addEventListener("resize",q),H=()=>{window.removeEventListener("scroll",q,!0),window.removeEventListener("resize",q),u.forEach(N=>N.element.remove()),a&&a.remove()},b.appendChild(j),i+1}finally{H&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(H)}}function V(t){if(!t||t.nodeType!==Node.ELEMENT_NODE)return null;const i=B(t);if(!i)return null;const w=i.display;if(w==="inline"||w==="inline-block")return null;const u=i.overflowX,a=i.overflowY,x=u==="auto"||u==="scroll",E=a==="auto"||a==="scroll";if(!x&&!E)return null;const H=t.scrollWidth-t.clientWidth,b=t.scrollHeight-t.clientHeight,P=4;if(H<P&&b<P||!E&&H<P||!x&&b<P)return null;const O=t.scrollTop,p=t.scrollLeft,y=t.scrollWidth-t.clientWidth-t.scrollLeft,I=t.scrollHeight-t.clientHeight-t.scrollTop,L={top:O,right:y,bottom:I,left:p};return c(t,{scrollable:!0,scrollData:L}),L}function $(t){try{if(l===-1){const E=t.parentElement;if(!E)return!1;try{return E.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const b=window.getComputedStyle(E);return b.display!=="none"&&b.visibility!=="hidden"&&b.opacity!=="0"}}const i=document.createRange();i.selectNodeContents(t);const w=i.getClientRects();if(!w||w.length===0)return!1;let u=!1,a=!1;for(const E of w)if(E.width>0&&E.height>0&&(u=!0,!(E.bottom<-l||E.top>window.innerHeight+l||E.right<-l||E.left>window.innerWidth+l))){a=!0;break}if(!u||!a)return!1;const x=t.parentElement;if(!x)return!1;try{return x.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const H=window.getComputedStyle(x);return H.display!=="none"&&H.visibility!=="hidden"&&H.opacity!=="0"}}catch(i){return console.warn("Error checking text node visibility:",i),!1}}function _(t){if(!t||!t.tagName)return!1;const i=new Set(["body","div","main","article","section","nav","header","footer"]),w=t.tagName.toLowerCase();return i.has(w)?!0:!new Set(["svg","script","style","link","meta","noscript","template"]).has(w)}function F(t){const i=B(t);return t.offsetWidth>0&&t.offsetHeight>0&&(i==null?void 0:i.visibility)!=="hidden"&&(i==null?void 0:i.display)!=="none"}function A(t){var I,L;if(!t||t.nodeType!==Node.ELEMENT_NODE||e.includes(t))return!1;if(n.includes(t))return!0;const i=t.tagName.toLowerCase(),w=B(t),u=new Set(["pointer","move","text","grab","grabbing","cell","copy","alias","all-scroll","col-resize","context-menu","crosshair","e-resize","ew-resize","help","n-resize","ne-resize","nesw-resize","ns-resize","nw-resize","nwse-resize","row-resize","s-resize","se-resize","sw-resize","vertical-text","w-resize","zoom-in","zoom-out"]),a=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);function x(j){return j.tagName.toLowerCase()==="html"?!1:!!(w!=null&&w.cursor&&u.has(w.cursor))}if(x(t))return!0;const H=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),b=new Set(["disabled","readonly"]);if(H.has(i)){if(w!=null&&w.cursor&&a.has(w.cursor))return!1;for(const j of b)if(t.hasAttribute(j)||t.getAttribute(j)==="true"||t.getAttribute(j)==="")return!1;return!(t.disabled||t.readOnly||t.inert)}const P=t.getAttribute("role"),O=t.getAttribute("aria-role");if(t.getAttribute("contenteditable")==="true"||t.isContentEditable||t.classList&&(t.classList.contains("button")||t.classList.contains("dropdown-toggle")||t.getAttribute("data-index")||t.getAttribute("data-toggle")==="dropdown"||t.getAttribute("aria-haspopup")==="true"))return!0;const p=new Set(["button","menu","menubar","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);if(H.has(i)||P&&p.has(P)||O&&p.has(O))return!0;try{if(typeof getEventListeners=="function"){const J=getEventListeners(t),nt=["click","mousedown","mouseup","dblclick"];for(const q of nt)if(J[q]&&J[q].length>0)return!0}const j=((L=(I=t==null?void 0:t.ownerDocument)==null?void 0:I.defaultView)==null?void 0:L.getEventListenersForNode)||window.getEventListenersForNode;if(typeof j=="function"){const J=j(t),nt=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const q of nt)for(const N of J)if(N.type===q)return!0}const G=["onclick","onmousedown","onmouseup","ondblclick"];for(const J of G)if(t.hasAttribute(J)||typeof t[J]=="function")return!0}catch{}return!!V(t)}function ot(t){if(l===-1)return!0;const i=D(t);if(!i||i.length===0)return!1;let w=!1;for(const b of i)if(b.width>0&&b.height>0&&!(b.bottom<-l||b.top>window.innerHeight+l||b.right<-l||b.left>window.innerWidth+l)){w=!0;break}if(!w)return!1;if(t.ownerDocument!==window.document)return!0;let a=Array.from(i).find(b=>b.width>0&&b.height>0);if(!a)return!1;const x=t.getRootNode();if(x instanceof ShadowRoot){const b=a.left+a.width/2,P=a.top+a.height/2;try{const O=x.elementFromPoint(b,P);if(!O)return!1;let p=O;for(;p&&p!==x;){if(p===t)return!0;p=p.parentElement}return!1}catch{return!0}}const E=5;return[{x:a.left+a.width/2,y:a.top+a.height/2},{x:a.left+E,y:a.top+E},{x:a.right-E,y:a.bottom-E}].some(({x:b,y:P})=>{try{const O=document.elementFromPoint(b,P);if(!O)return!1;let p=O;for(;p&&p!==document.documentElement;){if(p===t)return!0;p=p.parentElement}return!1}catch{return!0}})}function rt(t,i){if(i===-1)return!0;const w=t.getClientRects();if(!w||w.length===0){const u=C(t);return!u||u.width===0||u.height===0?!1:!(u.bottom<-i||u.top>window.innerHeight+i||u.right<-i||u.left>window.innerWidth+i)}for(const u of w)if(!(u.width===0||u.height===0)&&!(u.bottom<-i||u.top>window.innerHeight+i||u.right<-i||u.left>window.innerWidth+i))return!0;return!1}function z(t){if(!t||t.nodeType!==Node.ELEMENT_NODE)return!1;const i=t.tagName.toLowerCase();return new Set(["a","button","input","select","textarea","details","summary","label"]).has(i)?!0:t.hasAttribute("onclick")||t.hasAttribute("role")||t.hasAttribute("tabindex")||t.hasAttribute("aria-")||t.hasAttribute("data-action")||t.getAttribute("contenteditable")==="true"}const Y=new Set(["a","button","input","select","textarea","summary","details","label","option"]),K=new Set(["button","link","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);function et(t){if(!t||t.nodeType!==Node.ELEMENT_NODE||!F(t))return!1;const i=t.hasAttribute("role")||t.hasAttribute("tabindex")||t.hasAttribute("onclick")||typeof t.onclick=="function",w=/\b(btn|clickable|menu|item|entry|link)\b/i.test(t.className||""),u=!!t.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar'),a=[...t.children].some(F),x=t.parentElement&&t.parentElement.isSameNode(document.body);return(A(t)||i||w)&&a&&u&&!x}function it(t){var u,a;if(!t||t.nodeType!==Node.ELEMENT_NODE)return!1;const i=t.tagName.toLowerCase(),w=t.getAttribute("role");if(i==="iframe"||Y.has(i)||w&&K.has(w)||t.isContentEditable||t.getAttribute("contenteditable")==="true"||t.hasAttribute("data-testid")||t.hasAttribute("data-cy")||t.hasAttribute("data-test")||t.hasAttribute("onclick")||typeof t.onclick=="function")return!0;try{const x=((a=(u=t==null?void 0:t.ownerDocument)==null?void 0:u.defaultView)==null?void 0:a.getEventListenersForNode)||window.getEventListenersForNode;if(typeof x=="function"){const H=x(t),b=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const P of b)for(const O of H)if(O.type===P)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(H=>t.hasAttribute(H)))return!0}catch{}return!!et(t)}function st(t,i,w,u){if(!t.isInteractive)return!1;let a=!1;return u?it(i)?a=!0:a=!1:a=!0,a&&(t.isInViewport=rt(i,l),(t.isInViewport||l===-1)&&(t.highlightIndex=v++,h))?(s>=0?s===t.highlightIndex&&k(i,t.highlightIndex,w):k(i,t.highlightIndex,w),!0):!1}function Z(t,i=null,w=!1){var E,H,b,P,O;if(!t||t.id===U||t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE||!t||t.id===U||((E=t.dataset)==null?void 0:E.browserUseIgnore)==="true"||t.getAttribute&&t.getAttribute("aria-hidden")==="true")return null;if(t===document.body){const p={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const I of t.childNodes){const L=Z(I,i,!1);L&&p.children.push(L)}const y=`${R.current++}`;return S[y]=p,y}if(t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE)return null;if(t.nodeType===Node.TEXT_NODE){const p=(H=t.textContent)==null?void 0:H.trim();if(!p)return null;const y=t.parentElement;if(!y||y.tagName.toLowerCase()==="script")return null;const I=`${R.current++}`;return S[I]={type:"TEXT_NODE",text:p,isVisible:$(t)},I}if(t.nodeType===Node.ELEMENT_NODE&&!_(t))return null;if(l!==-1&&!t.shadowRoot){const p=C(t),y=B(t),I=y&&(y.position==="fixed"||y.position==="sticky"),L=t.offsetWidth>0||t.offsetHeight>0;if(!p||!I&&!L&&(p.bottom<-l||p.top>window.innerHeight+l||p.right<-l||p.left>window.innerWidth+l))return null}const u={tagName:t.tagName.toLowerCase(),attributes:{},children:[]};if(z(t)||t.tagName.toLowerCase()==="iframe"||t.tagName.toLowerCase()==="body"){const p=((b=t.getAttributeNames)==null?void 0:b.call(t))||[];for(const y of p){const I=t.getAttribute(y);u.attributes[y]=I}t.tagName.toLowerCase()==="input"&&(t.type==="checkbox"||t.type==="radio")&&(u.attributes.checked=t.checked?"true":"false")}let a=!1;if(t.nodeType===Node.ELEMENT_NODE&&(u.isVisible=F(t),u.isVisible)){u.isTopElement=ot(t);const p=t.getAttribute("role"),y=p==="menu"||p==="menubar"||p==="listbox";(u.isTopElement||y)&&(u.isInteractive=A(t),a=st(u,t,i,w),u.ref=t)}if(t.tagName){const p=t.tagName.toLowerCase();if(p==="iframe")try{const y=t.contentDocument||((P=t.contentWindow)==null?void 0:P.document);if(y)for(const I of y.childNodes){const L=Z(I,t,!1);L&&u.children.push(L)}}catch(y){console.warn("Unable to access iframe:",y)}else if(t.isContentEditable||t.getAttribute("contenteditable")==="true"||t.id==="tinymce"||t.classList.contains("mce-content-body")||p==="body"&&((O=t.getAttribute("data-id"))!=null&&O.startsWith("mce_")))for(const y of t.childNodes){const I=Z(y,i,a);I&&u.children.push(I)}else{if(t.shadowRoot){u.shadowRoot=!0;for(const y of t.shadowRoot.childNodes){const I=Z(y,i,a);I&&u.children.push(I)}}for(const y of t.childNodes){const L=Z(y,i,a||w);L&&u.children.push(L)}}}if(u.tagName==="a"&&u.children.length===0&&!u.attributes.href){const p=C(t);if(!(p&&p.width>0&&p.height>0||t.offsetWidth>0||t.offsetHeight>0))return null}u.extra=m.get(t)||null;const x=`${R.current++}`;return S[x]=u,x}const lt=Z(document.body);return g.clearCache(),{rootId:lt,map:S}},newElementsCache=new WeakMap;function getFlatTree(o){const e=[];for(const h of o.interactiveBlacklist||[])typeof h=="function"?e.push(h()):e.push(h);const n=[];for(const h of o.interactiveWhitelist||[])typeof h=="function"?n.push(h()):n.push(h);const r=domTree({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:VIEWPORT_EXPANSION,interactiveBlacklist:e,interactiveWhitelist:n,highlightOpacity:o.highlightOpacity??0,highlightLabelOpacity:o.highlightLabelOpacity??.1}),d=window.location.href;for(const h in r.map){const s=r.map[h];if(s.isInteractive&&s.ref){const l=s.ref;newElementsCache.has(l)||(newElementsCache.set(l,d),s.isNew=!0)}}return r}function flatTreeToString(o,e){const n=["title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","id","for","target","aria-haspopup","aria-controls","aria-owns"],r=[...e||[],...n],d=(c,g)=>c.length>g?c.substring(0,g)+"...":c,h=c=>{const g=o.map[c];if(!g)return null;if(g.type==="TEXT_NODE"){const C=g;return{type:"text",text:C.text,isVisible:C.isVisible,parent:null,children:[]}}else{const C=g,B=[];if(C.children)for(const D of C.children){const S=h(D);S&&(S.parent=null,B.push(S))}return{type:"element",tagName:C.tagName,attributes:C.attributes??{},isVisible:C.isVisible??!1,isInteractive:C.isInteractive??!1,isTopElement:C.isTopElement??!1,isNew:C.isNew??!1,highlightIndex:C.highlightIndex,parent:null,children:B,extra:C.extra??{}}}},s=(c,g=null)=>{c.parent=g;for(const C of c.children)s(C,c)},l=h(o.rootId);if(!l)return"";s(l);const f=c=>{let g=c.parent;for(;g;){if(g.type==="element"&&g.highlightIndex!==void 0)return!0;g=g.parent}return!1},v=(c,g,C)=>{var S,R,U,k;let B=g;const D=" ".repeat(g);if(c.type==="element"){if(c.highlightIndex!==void 0){B+=1;const V=getAllTextTillNextClickableElement(c);let $="";if(r.length>0&&c.attributes){const A={};for(const z of r){const Y=c.attributes[z];Y&&Y.trim()!==""&&(A[z]=Y.trim())}const ot=r.filter(z=>z in A);if(ot.length>1){const z=new Set,Y={};for(const K of ot){const et=A[K];et.length>5&&(et in Y?z.add(K):Y[et]=K)}for(const K of z)delete A[K]}A.role===c.tagName&&delete A.role;const rt=["aria-label","placeholder","title"];for(const z of rt)A[z]&&A[z].toLowerCase().trim()===V.toLowerCase().trim()&&delete A[z];Object.keys(A).length>0&&($=Object.entries(A).map(([z,Y])=>`${z}=${d(Y,20)}`).join(" "))}const _=c.isNew?`*[${c.highlightIndex}]`:`[${c.highlightIndex}]`;let F=`${D}${_}<${c.tagName??""}`;if($&&(F+=` ${$}`),c.extra&&c.extra.scrollable){let A="";(S=c.extra.scrollData)!=null&&S.left&&(A+=`left=${c.extra.scrollData.left}, `),(R=c.extra.scrollData)!=null&&R.top&&(A+=`top=${c.extra.scrollData.top}, `),(U=c.extra.scrollData)!=null&&U.right&&(A+=`right=${c.extra.scrollData.right}, `),(k=c.extra.scrollData)!=null&&k.bottom&&(A+=`bottom=${c.extra.scrollData.bottom}`),F+=` data-scrollable="${A}"`}if(V){const A=V.trim();$||(F+=" "),F+=`>${A}`}else $||(F+=" ");F+=" />",C.push(F)}for(const V of c.children)v(V,B,C)}else if(c.type==="text"){if(f(c))return;c.parent&&c.parent.type==="element"&&c.parent.isVisible&&c.parent.isTopElement&&C.push(`${D}${c.text??""}`)}},m=[];return v(l,0,m),m.join(`
2
+ `)}const getAllTextTillNextClickableElement=(o,e=-1)=>{const n=[],r=(d,h)=>{if(!(e!==-1&&h>e)&&!(d.type==="element"&&d!==o&&d.highlightIndex!==void 0)){if(d.type==="text"&&d.text)n.push(d.text);else if(d.type==="element")for(const s of d.children)r(s,h+1)}};return r(o,0),n.join(`
3
+ `).trim()};function getSelectorMap(o){const e=new Map,n=Object.keys(o.map);for(const r of n){const d=o.map[r];d.isInteractive&&typeof d.highlightIndex=="number"&&e.set(d.highlightIndex,d)}return e}function getElementTextMap(o){const e=o.split(`
4
+ `).map(r=>r.trim()).filter(r=>r.length>0),n=new Map;for(const r of e){const h=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(r);if(h){const s=parseInt(h[1],10);n.set(s,r)}}return n}function cleanUpHighlights(){const o=window._highlightCleanupFunctions||[];for(const e of o)typeof e=="function"&&e();window._highlightCleanupFunctions=[]}window.addEventListener("popstate",()=>{cleanUpHighlights()});window.addEventListener("hashchange",()=>{cleanUpHighlights()});window.addEventListener("beforeunload",()=>{cleanUpHighlights()});const navigation=window.navigation;if(navigation&&typeof navigation.addEventListener=="function")navigation.addEventListener("navigate",()=>{cleanUpHighlights()});else{let o=window.location.href;setInterval(()=>{window.location.href!==o&&(o=window.location.href,cleanUpHighlights())},500)}function getPageInfo(){const o=window.innerWidth,e=window.innerHeight,n=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),r=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),d=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,h=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,s=Math.max(0,r-(window.innerHeight+h)),l=Math.max(0,n-(window.innerWidth+d));return{viewport_width:o,viewport_height:e,page_width:n,page_height:r,scroll_x:d,scroll_y:h,pixels_above:h,pixels_below:s,pages_above:e>0?h/e:0,pages_below:e>0?s/e:0,total_pages:e>0?r/e:0,current_page_position:h/Math.max(1,r-e),pixels_left:d,pixels_right:l}}function patchReact(o){const e=document.querySelectorAll('[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root');for(const n of e)n.setAttribute("data-page-agent-not-interactive","true")}class PageController extends EventTarget{constructor(o={}){super(),this.flatTree=null,this.selectorMap=new Map,this.elementTextMap=new Map,this.simplifiedHTML="<EMPTY>",this.lastTimeUpdate=0,this.isIndexed=!1,this.mask=null,this.maskReady=null,this.config=o,patchReact(),o.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{const{SimulatorMask:o}=await Promise.resolve().then(()=>require("./SimulatorMask-jCkPs2Tt.cjs"));this.mask=new o})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){const o=window.location.href,e=document.title,n=getPageInfo(),r=this.config.viewportExpansion??VIEWPORT_EXPANSION;await this.updateTree();const d=this.simplifiedHTML,h=`Current Page: [${e}](${o})`,s=`Page info: ${n.viewport_width}x${n.viewport_height}px viewport, ${n.page_width}x${n.page_height}px total page size, ${n.pages_above.toFixed(1)} pages above, ${n.pages_below.toFixed(1)} pages below, ${n.total_pages.toFixed(1)} total pages, at ${(n.current_page_position*100).toFixed(0)}% of page`,l=r===-1?"Interactive elements from top layer of the current page (full page):":"Interactive elements from top layer of the current page inside the viewport:",v=n.pixels_above>4&&r!==-1?`... ${n.pixels_above} pixels above (${n.pages_above.toFixed(1)} pages) - scroll to see more ...`:"[Start of page]",m=`${h}
5
+ ${s}
6
+
7
+ ${l}
8
+
9
+ ${v}`,g=n.pixels_below>4&&r!==-1?`... ${n.pixels_below} pixels below (${n.pages_below.toFixed(1)} pages) - scroll to see more ...`:"[End of page]";return{url:o,title:e,header:m,content:d,footer:g}}async updateTree(){this.dispatchEvent(new Event("beforeUpdate")),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents="none"),cleanUpHighlights();const o=[...this.config.interactiveBlacklist||[],...document.querySelectorAll("[data-page-agent-not-interactive]").values()];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:o}),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.include_attributes),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.mask&&(this.mask.wrapper.style.pointerEvents="auto"),this.dispatchEvent(new Event("afterUpdate")),this.simplifiedHTML}async cleanUpHighlights(){cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw new Error("DOM tree not indexed yet. Can not perform actions on elements.")}async clickElement(o){try{this.assertIndexed();const e=getElementByIndex(this.selectorMap,o),n=this.elementTextMap.get(o);return await clickElement(e),e instanceof HTMLAnchorElement&&e.target==="_blank"?{success:!0,message:`✅ Clicked element (${n??o}). ⚠️ Link opens in a new tab. You are not capable of reading new tabs.`}:{success:!0,message:`✅ Clicked element (${n??o}).`}}catch(e){return{success:!1,message:`❌ Failed to click element: ${e}`}}}async inputText(o,e){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,o),r=this.elementTextMap.get(o);return await inputTextElement(n,e),{success:!0,message:`✅ Input text (${e}) into element (${r??o}).`}}catch(n){return{success:!1,message:`❌ Failed to input text: ${n}`}}}async selectOption(o,e){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,o),r=this.elementTextMap.get(o);return await selectOptionElement(n,e),{success:!0,message:`✅ Selected option (${e}) in element (${r??o}).`}}catch(n){return{success:!1,message:`❌ Failed to select option: ${n}`}}}async scroll(o){try{const{down:e,numPages:n,pixels:r,index:d}=o;this.assertIndexed();const h=r??n*(e?1:-1)*window.innerHeight,s=d!==void 0?getElementByIndex(this.selectorMap,d):null;return{success:!0,message:await scrollVertically(e,h,s)}}catch(e){return{success:!1,message:`❌ Failed to scroll: ${e}`}}}async scrollHorizontally(o){try{const{right:e,pixels:n,index:r}=o;this.assertIndexed();const d=n*(e?1:-1),h=r!==void 0?getElementByIndex(this.selectorMap,r):null;return{success:!0,message:await scrollHorizontally(e,d,h)}}catch(e){return{success:!1,message:`❌ Failed to scroll horizontally: ${e}`}}}async executeJavascript(script){try{const asyncFunction=eval(`(async () => { ${script} })`),result=await asyncFunction();return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(o){return{success:!1,message:`❌ Error executing JavaScript: ${o}`}}}async showMask(){var o;await this.maskReady,(o=this.mask)==null||o.show()}async hideMask(){var o;await this.maskReady,(o=this.mask)==null||o.hide()}dispose(){var o;cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="<EMPTY>",this.isIndexed=!1,(o=this.mask)==null||o.dispose(),this.mask=null}}const PageController$1=Object.freeze(Object.defineProperty({__proto__:null,PageController},Symbol.toStringTag,{value:"Module"}));let injectedPageController=null,PageControllerModule=null;function setPageController(o){injectedPageController=o}async function getPageController(){if(injectedPageController)return injectedPageController;if(!PageControllerModule)try{PageControllerModule=await Promise.resolve().then(()=>PageController$1)}catch{throw new Error('PageController not available. Either import from "@usecrow/client/browser" or use the bundled version.')}return PageControllerModule.PageController}class CrowBrowserUse{constructor(e){this.pageController=null,this.sessionId=null,this.maxSteps=20,this.aborted=!1,this.config=e}async initPageController(){if(this.pageController)return this.pageController;try{const e=await getPageController();this.pageController=new e({enableMask:!0,viewportExpansion:500,highlightLabelOpacity:0,highlightOpacity:0}),await this.pageController.showMask();const n=this.pageController.mask;return n!=null&&n.wrapper&&(n.wrapper.style.pointerEvents="none"),console.log("[CrowBrowserUse] PageController initialized with non-blocking pointer"),this.pageController}catch(e){throw console.error("[CrowBrowserUse] Failed to initialize PageController:",e),new Error("Failed to initialize browser automation. Please import from @usecrow/client/browser.")}}async execute(e){var n,r,d,h,s,l,f,v,m,c,g,C,B,D;if(console.log("[CrowBrowserUse] Starting task:",e),this.config.onConfirmation&&!await this.config.onConfirmation(e))return console.log("[CrowBrowserUse] User declined browser automation"),(r=(n=this.config).onProgress)==null||r.call(n,-1,this.maxSteps),{status:"error",error:"User declined browser automation",data:{declined:!0}};try{const S=await this.initPageController(),R=await this.startSession(e);this.sessionId=R.session_id,this.maxSteps=R.max_steps,console.log("[CrowBrowserUse] Session started:",this.sessionId);let U=0,k;for(;U<this.maxSteps;){if(this.aborted)return console.log("[CrowBrowserUse] Task cancelled by user"),await this.cleanup(),(h=(d=this.config).onProgress)==null||h.call(d,-1,this.maxSteps),{status:"error",error:"Task cancelled by user"};U++;const V=await S.getBrowserState(),$=S.mask;$!=null&&$.wrapper&&($.wrapper.style.pointerEvents="none");const _=await this.processStep(V,k);if(_.needs_user_input&&_.question){if(console.log("[CrowBrowserUse] Asking user:",_.question),!this.config.onQuestion){k="User input not available - no callback provided",console.warn("[CrowBrowserUse] No onQuestion callback provided");continue}try{const F=await this.config.onQuestion(_.question);k=`User answered: ${F}`,console.log("[CrowBrowserUse] User answered:",F)}catch(F){if(k="User cancelled or failed to respond",console.log("[CrowBrowserUse] User cancelled or error:",F),this.aborted)return console.log("[CrowBrowserUse] Aborted after user cancelled"),await this.cleanup(),(l=(s=this.config).onProgress)==null||l.call(s,-1,this.maxSteps),{status:"error",error:"Task cancelled by user"}}continue}if(_.done)return console.log("[CrowBrowserUse] Task completed:",_.message),await this.cleanup(),(v=(f=this.config).onProgress)==null||v.call(f,U,this.maxSteps),{status:_.success?"success":"error",data:{message:_.message,steps:U},error:_.success?void 0:_.message};if(_.error)return console.error("[CrowBrowserUse] Error:",_.error),await this.cleanup(),(c=(m=this.config).onProgress)==null||c.call(m,-1,this.maxSteps),{status:"error",error:_.error};_.action&&(k=await this.executeAction(S,_.action),console.log(`[CrowBrowserUse] Step ${U}:`,k)),_.reflection&&console.log("[CrowBrowserUse] Reflection:",_.reflection.next_goal)}return await this.cleanup(),(C=(g=this.config).onProgress)==null||C.call(g,-1,this.maxSteps),{status:"error",error:`Task incomplete after ${this.maxSteps} steps`}}catch(S){return console.error("[CrowBrowserUse] Error:",S),await this.cleanup(),(D=(B=this.config).onProgress)==null||D.call(B,-1,this.maxSteps),{status:"error",error:S instanceof Error?S.message:String(S)}}}async startSession(e){const n=await fetch(`${this.config.apiUrl}/api/browser-use/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({product_id:this.config.productId,task:e})});if(!n.ok){const r=await n.json().catch(()=>({detail:"Unknown error"}));throw new Error(r.detail||`Failed to start session: ${n.status}`)}return n.json()}async processStep(e,n){const r=await fetch(`${this.config.apiUrl}/api/browser-use/step`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.sessionId,product_id:this.config.productId,browser_state:e,action_result:n})});if(!r.ok){const d=await r.json().catch(()=>({detail:"Unknown error"}));throw new Error(d.detail||`Failed to process step: ${r.status}`)}return r.json()}async executeAction(e,n){const r=Object.keys(n)[0],d=n[r];try{switch(r){case"click_element_by_index":return(await e.clickElement(d.index)).message;case"input_text":return(await e.inputText(d.index,d.text)).message;case"select_dropdown_option":return(await e.selectOption(d.index,d.text)).message;case"scroll":return(await e.scroll({down:d.down,numPages:d.num_pages,pixels:d.pixels,index:d.index})).message;case"scroll_horizontally":return(await e.scrollHorizontally({right:d.right,pixels:d.pixels,index:d.index})).message;case"wait":{const h=d.seconds||1;return await new Promise(s=>setTimeout(s,h*1e3)),`Waited ${h} seconds`}case"done":return"Task completed";default:return`Unknown action: ${r}`}}catch(h){return`Action failed: ${h instanceof Error?h.message:String(h)}`}}async cleanup(){if(this.pageController){try{await this.pageController.hideMask(),await this.pageController.cleanUpHighlights(),this.pageController.dispose()}catch(e){console.warn("[CrowBrowserUse] Cleanup error:",e)}this.pageController=null}if(this.sessionId){try{await fetch(`${this.config.apiUrl}/api/browser-use/end`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.sessionId,product_id:this.config.productId})})}catch{}this.sessionId=null}}async stop(){this.aborted=!0,await this.cleanup()}}exports.CrowBrowserUse=CrowBrowserUse;exports.PageController=PageController;exports.setPageController=setPageController;