page-agent 0.0.22 → 0.0.23
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/umd/page-agent.js +2 -2
- package/package.json +4 -4
package/dist/umd/page-agent.js
CHANGED
|
@@ -155,7 +155,7 @@ out vec2 vUV;
|
|
|
155
155
|
void main() {
|
|
156
156
|
vUV = aUV;
|
|
157
157
|
gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
158
|
-
}`;const DEFAULT_COLORS=["rgb(57, 182, 255)","rgb(189, 69, 251)","rgb(255, 87, 51)","rgb(255, 214, 0)"];function parseColor(e){const n=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!n)throw new Error(`Invalid color format: ${e}`);const[,r,o,t]=n;return[parseInt(r)/255,parseInt(o)/255,parseInt(t)/255]}s(parseColor,"parseColor");const ht=class ht{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(n={}){this.options={width:n.width??600,height:n.height??600,ratio:n.ratio??window.devicePixelRatio??1,borderWidth:n.borderWidth??8,glowWidth:n.glowWidth??200,borderRadius:n.borderRadius??8,mode:n.mode??"light",...n},this.canvas=document.createElement("canvas"),this.options.classNames&&(this.canvas.className=this.options.classNames),this.options.styles&&Object.assign(this.canvas.style,this.options.styles),this.canvas.style.display="block",this.canvas.style.transformOrigin="center",this.canvas.style.pointerEvents="none",this.element=this.canvas,this.setupGL(),this.options.skipGreeting||this.greet()}start(){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.running)return;if(!this.glr){console.error("WebGL resources are not initialized.");return}this.running=!0,this.startTime=performance.now(),this.resize(this.options.width??600,this.options.height??600,this.options.ratio),this.glr.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.glr.gl.useProgram(this.glr.program),this.glr.gl.uniform2f(this.glr.uResolution,this.canvas.width,this.canvas.height),this.checkGLError(this.glr.gl,"start: after initial setup");const n=s(()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(n);const r=performance.now();if(r-this.lastTime<1e3/32)return;this.lastTime=r;const t=(r-this.startTime)*.001;this.render(t)},"loop");this.rafId=requestAnimationFrame(n)}pause(){if(this.disposed)throw new Error("Motion instance has been disposed.");this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId)}dispose(){if(this.disposed)return;this.disposed=!0,this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId);const{gl:n,vao:r,positionBuffer:o,uvBuffer:t,program:i}=this.glr;r&&n.deleteVertexArray(r),o&&n.deleteBuffer(o),t&&n.deleteBuffer(t),n.deleteProgram(i),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(n,r,o){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.options.width=n,this.options.height=r,o&&(this.options.ratio=o),!this.running)return;const{gl:t,program:i,vao:a,positionBuffer:c,uvBuffer:l,uResolution:u}=this.glr,m=o??this.options.ratio??window.devicePixelRatio??1,p=Math.max(1,Math.floor(n*m)),g=Math.max(1,Math.floor(r*m));this.canvas.style.width=`${n}px`,this.canvas.style.height=`${r}px`,(this.canvas.width!==p||this.canvas.height!==g)&&(this.canvas.width=p,this.canvas.height=g),t.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(t,"resize: after viewport setup");const{positions:h,uvs:y}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*m,this.options.glowWidth*m);t.bindVertexArray(a),t.bindBuffer(t.ARRAY_BUFFER,c),t.bufferData(t.ARRAY_BUFFER,h,t.STATIC_DRAW);const w=t.getAttribLocation(i,"aPosition");t.enableVertexAttribArray(w),t.vertexAttribPointer(w,2,t.FLOAT,!1,0,0),this.checkGLError(t,"resize: after position buffer update"),t.bindBuffer(t.ARRAY_BUFFER,l),t.bufferData(t.ARRAY_BUFFER,y,t.STATIC_DRAW);const Z=t.getAttribLocation(i,"aUV");t.enableVertexAttribArray(Z),t.vertexAttribPointer(Z,2,t.FLOAT,!1,0,0),this.checkGLError(t,"resize: after UV buffer update"),t.useProgram(i),t.uniform2f(u,this.canvas.width,this.canvas.height),t.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*m),t.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*m),t.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*m),this.checkGLError(t,"resize: after uniform updates");const N=performance.now();this.lastTime=N;const B=(N-this.startTime)*.001;this.render(B)}autoResize(n){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{const r=n.getBoundingClientRect();this.resize(r.width,r.height)}),this.observer.observe(n)}fadeIn(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((n,r)=>{const o=this.canvas.animate([{opacity:0,transform:"scale(1.2)"},{opacity:1,transform:"scale(1)"}],{duration:300,easing:"ease-out",fill:"forwards"});o.onfinish=()=>n(),o.oncancel=()=>r("canceled")})}fadeOut(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((n,r)=>{const o=this.canvas.animate([{opacity:1,transform:"scale(1)"},{opacity:0,transform:"scale(1.2)"}],{duration:300,easing:"ease-in",fill:"forwards"});o.onfinish=()=>n(),o.oncancel=()=>r("canceled")})}checkGLError(n,r){let o=n.getError();if(o!==n.NO_ERROR){for(console.group(`🔴 WebGL Error in ${r}`);o!==n.NO_ERROR;){const t=this.getGLErrorName(n,o);console.error(`${t} (0x${o.toString(16)})`),o=n.getError()}console.groupEnd()}}getGLErrorName(n,r){switch(r){case n.INVALID_ENUM:return"INVALID_ENUM";case n.INVALID_VALUE:return"INVALID_VALUE";case n.INVALID_OPERATION:return"INVALID_OPERATION";case n.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case n.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case n.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"UNKNOWN_ERROR"}}setupGL(){const n=this.canvas.getContext("webgl2",{antialias:!1,alpha:!0});if(!n)throw new Error("WebGL2 is required but not available.");const r=createProgram(n,vertexShaderSource,fragmentShaderSource);this.checkGLError(n,"setupGL: after createProgram");const o=n.createVertexArray();n.bindVertexArray(o),this.checkGLError(n,"setupGL: after VAO creation");const t=this.canvas.width||2,i=this.canvas.height||2,{positions:a,uvs:c}=computeBorderGeometry(t,i,this.options.borderWidth,this.options.glowWidth),l=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,l),n.bufferData(n.ARRAY_BUFFER,a,n.STATIC_DRAW);const u=n.getAttribLocation(r,"aPosition");n.enableVertexAttribArray(u),n.vertexAttribPointer(u,2,n.FLOAT,!1,0,0),this.checkGLError(n,"setupGL: after position buffer setup");const m=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,m),n.bufferData(n.ARRAY_BUFFER,c,n.STATIC_DRAW);const p=n.getAttribLocation(r,"aUV");n.enableVertexAttribArray(p),n.vertexAttribPointer(p,2,n.FLOAT,!1,0,0),this.checkGLError(n,"setupGL: after UV buffer setup");const g=n.getUniformLocation(r,"uResolution"),h=n.getUniformLocation(r,"uTime"),y=n.getUniformLocation(r,"uBorderWidth"),w=n.getUniformLocation(r,"uGlowWidth"),Z=n.getUniformLocation(r,"uBorderRadius"),N=n.getUniformLocation(r,"uColors"),B=n.getUniformLocation(r,"uGlowExponent"),S=n.getUniformLocation(r,"uGlowFactor");n.useProgram(r),n.uniform1f(y,this.options.borderWidth),n.uniform1f(w,this.options.glowWidth),n.uniform1f(Z,this.options.borderRadius),this.options.mode==="dark"?(n.uniform1f(B,2),n.uniform1f(S,1.8)):(n.uniform1f(B,1),n.uniform1f(S,1));const b=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let P=0;P<b.length;P++)n.uniform3f(n.getUniformLocation(r,`uColors[${P}]`),...b[P]);this.checkGLError(n,"setupGL: after uniform setup"),n.bindVertexArray(null),n.bindBuffer(n.ARRAY_BUFFER,null),this.glr={gl:n,program:r,vao:o,positionBuffer:l,uvBuffer:m,uResolution:g,uTime:h,uBorderWidth:y,uGlowWidth:w,uBorderRadius:Z,uColors:N}}render(n){if(!this.glr)return;const{gl:r,program:o,vao:t,uTime:i}=this.glr;r.useProgram(o),r.bindVertexArray(t),r.uniform1f(i,n),r.disable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.disable(r.BLEND),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLES,0,24),this.checkGLError(r,"render: after draw call"),r.bindVertexArray(null)}greet(){console.log("%c🌈 ai-motion 0.4.8 🌈","background: linear-gradient(90deg, #39b6ff, #bd45fb, #ff5733, #ffd600); color: white; text-shadow: 0 0 2px rgba(0, 0, 0, 0.2); font-weight: bold; font-size: 1em; padding: 2px 12px; border-radius: 6px;")}};s(ht,"Motion");let Motion=ht;function hasDarkModeClass(){const e=["dark","dark-mode","theme-dark","night","night-mode"],n=document.documentElement,r=document.body||document.documentElement;for(const t of e)if(n.classList.contains(t)||r?.classList.contains(t))return!0;return!!n.getAttribute("data-theme")?.toLowerCase().includes("dark")}s(hasDarkModeClass,"hasDarkModeClass");function parseRgbColor(e){const n=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(e);return n?{r:parseInt(n[1]),g:parseInt(n[2]),b:parseInt(n[3])}:null}s(parseRgbColor,"parseRgbColor");function isColorDark(e,n=128){if(!e||e==="transparent"||e.startsWith("rgba(0, 0, 0, 0)"))return!1;const r=parseRgbColor(e);return r?.299*r.r+.587*r.g+.114*r.b<n:!1}s(isColorDark,"isColorDark");function isBackgroundDark(){const e=window.getComputedStyle(document.documentElement),n=window.getComputedStyle(document.body||document.documentElement),r=e.backgroundColor,o=n.backgroundColor;return isColorDark(o)?!0:o==="transparent"||o.startsWith("rgba(0, 0, 0, 0)")?isColorDark(r):!1}s(isBackgroundDark,"isBackgroundDark");function isPageDark(){try{return!!(hasDarkModeClass()||isBackgroundDark())}catch(e){return console.warn("Error determining if page is dark:",e),!1}}s(isPageDark,"isPageDark");const wrapper$1="_wrapper_1oy2s_1",styles$1={wrapper:wrapper$1},cursor="_cursor_1vrf3_2",cursorBorder="_cursorBorder_1vrf3_13",cursorFilling="_cursorFilling_1vrf3_23",cursorRipple="_cursorRipple_1vrf3_31",clicking="_clicking_1vrf3_37",cursorStyles={cursor,cursorBorder,cursorFilling,cursorRipple,clicking},vt=class vt{constructor(){D(this,De);re(this,"wrapper",document.createElement("div"));re(this,"motion",new Motion({mode:isPageDark()?"dark":"light",styles:{position:"absolute",inset:"0"}}));D(this,q,document.createElement("div"));D(this,oe,0);D(this,ae,0);D(this,Ie,0);D(this,ze,0);this.wrapper.id="page-agent-runtime_simulator-mask",this.wrapper.className=styles$1.wrapper,this.wrapper.setAttribute("data-browser-use-ignore","true"),this.wrapper.appendChild(this.motion.element),this.motion.autoResize(this.wrapper),this.wrapper.addEventListener("click",n=>{n.stopPropagation(),n.preventDefault()}),this.wrapper.addEventListener("mousedown",n=>{n.stopPropagation(),n.preventDefault()}),this.wrapper.addEventListener("mouseup",n=>{n.stopPropagation(),n.preventDefault()}),this.wrapper.addEventListener("mousemove",n=>{n.stopPropagation(),n.preventDefault()}),this.wrapper.addEventListener("wheel",n=>{n.stopPropagation(),n.preventDefault()}),this.wrapper.addEventListener("keydown",n=>{n.stopPropagation(),n.preventDefault()}),this.wrapper.addEventListener("keyup",n=>{n.stopPropagation(),n.preventDefault()}),T(this,De,jt).call(this),document.body.appendChild(this.wrapper),T(this,De,kt).call(this),window.addEventListener("PageAgent::MovePointerTo",n=>{const{x:r,y:o}=n.detail;this.setCursorPosition(r,o)}),window.addEventListener("PageAgent::ClickPointer",n=>{this.triggerClickAnimation()})}setCursorPosition(n,r){E(this,Ie,n),E(this,ze,r)}triggerClickAnimation(){f(this,q).classList.remove(cursorStyles.clicking),f(this,q).offsetHeight,f(this,q).classList.add(cursorStyles.clicking)}show(){this.motion.start(),this.motion.fadeIn(),this.wrapper.style.display="block",E(this,oe,window.innerWidth/2),E(this,ae,window.innerHeight/2),E(this,Ie,f(this,oe)),E(this,ze,f(this,ae)),f(this,q).style.left=`${f(this,oe)}px`,f(this,q).style.top=`${f(this,ae)}px`}hide(){this.motion.fadeOut(),this.motion.pause(),f(this,q).classList.remove(cursorStyles.clicking),setTimeout(()=>{this.wrapper.style.display="none"},800)}dispose(){this.motion.dispose(),this.wrapper.remove()}};q=new WeakMap,oe=new WeakMap,ae=new WeakMap,Ie=new WeakMap,ze=new WeakMap,De=new WeakSet,jt=s(function(){f(this,q).className=cursorStyles.cursor;const n=document.createElement("div");n.className=cursorStyles.cursorRipple,f(this,q).appendChild(n);const r=document.createElement("div");r.className=cursorStyles.cursorFilling,f(this,q).appendChild(r);const o=document.createElement("div");o.className=cursorStyles.cursorBorder,f(this,q).appendChild(o),this.wrapper.appendChild(f(this,q))},"#createCursor"),kt=s(function(){const n=f(this,oe)+(f(this,Ie)-f(this,oe))*.2,r=f(this,ae)+(f(this,ze)-f(this,ae))*.2,o=Math.abs(n-f(this,Ie));o>0&&(o<2?E(this,oe,f(this,Ie)):E(this,oe,n),f(this,q).style.left=`${f(this,oe)}px`);const t=Math.abs(r-f(this,ze));t>0&&(t<2?E(this,ae,f(this,ze)):E(this,ae,r),f(this,q).style.top=`${f(this,ae)}px`),requestAnimationFrame(()=>T(this,De,kt).call(this))},"#moveCursorToTarget"),s(vt,"SimulatorMask");let SimulatorMask=vt;function patchReact(e){const n=document.querySelectorAll('[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root');for(const r of n)r.setAttribute("data-page-agent-not-interactive","true")}s(patchReact,"patchReact");const _PageController=class _PageController extends EventTarget{config;flatTree=null;selectorMap=new Map;elementTextMap=new Map;simplifiedHTML="<EMPTY>";lastTimeUpdate=0;mask=null;constructor(e={}){super(),this.config=e,patchReact(),e.enableMask&&(this.mask=new SimulatorMask)}async getCurrentUrl(){return window.location.href}async getPageTitle(){return document.title}async getPageInfo(){return getPageInfo()}async getSimplifiedHTML(){return this.simplifiedHTML}async getElementText(e){return this.elementTextMap.get(e)}async getElementCount(){return this.selectorMap.size}async getLastUpdateTime(){return this.lastTimeUpdate}async getViewportExpansion(){return this.config.viewportExpansion??VIEWPORT_EXPANSION}async updateTree(){this.dispatchEvent(new Event("beforeUpdate")),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents="none"),cleanUpHighlights();const e=[...this.config.interactiveBlacklist||[],...document.querySelectorAll("[data-page-agent-not-interactive]").values()];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:e}),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.mask&&(this.mask.wrapper.style.pointerEvents="auto"),this.dispatchEvent(new Event("afterUpdate")),this.simplifiedHTML}async cleanUpHighlights(){cleanUpHighlights()}async clickElement(e){try{const n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return await clickElement(n),n instanceof HTMLAnchorElement&&n.target==="_blank"?{success:!0,message:`✅ Clicked element (${r??e}). ⚠️ Link opens in a new tab. You are not capable of reading new tabs.`}:{success:!0,message:`✅ Clicked element (${r??e}).`}}catch(n){return{success:!1,message:`❌ Failed to click element: ${n}`}}}async inputText(e,n){try{const r=getElementByIndex(this.selectorMap,e),o=this.elementTextMap.get(e);return await inputTextElement(r,n),{success:!0,message:`✅ Input text (${n}) into element (${o??e}).`}}catch(r){return{success:!1,message:`❌ Failed to input text: ${r}`}}}async selectOption(e,n){try{const r=getElementByIndex(this.selectorMap,e),o=this.elementTextMap.get(e);return await selectOptionElement(r,n),{success:!0,message:`✅ Selected option (${n}) in element (${o??e}).`}}catch(r){return{success:!1,message:`❌ Failed to select option: ${r}`}}}async scroll(e){try{const{down:n,numPages:r,pixels:o,index:t}=e,i=o??r*(n?1:-1)*window.innerHeight,a=t!==void 0?getElementByIndex(this.selectorMap,t):null;return{success:!0,message:await scrollVertically(n,i,a)}}catch(n){return{success:!1,message:`❌ Failed to scroll: ${n}`}}}async scrollHorizontally(e){try{const{right:n,pixels:r,index:o}=e,t=r*(n?1:-1),i=o!==void 0?getElementByIndex(this.selectorMap,o):null;return{success:!0,message:await scrollHorizontally(n,t,i)}}catch(n){return{success:!1,message:`❌ Failed to scroll horizontally: ${n}`}}}async executeJavascript(script){try{const asyncFunction=eval(`(async () => { ${script} })`),result=await asyncFunction();return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(e){return{success:!1,message:`❌ Error executing JavaScript: ${e}`}}}showMask(){this.mask?.show()}hideMask(){this.mask?.hide()}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="<EMPTY>",this.mask?.dispose(),this.mask=null}};s(_PageController,"PageController");let PageController=_PageController;const _t=class _t{steps=[];currentStep=null;status="idle";stepCounter=0;addStep(n){const r={id:this.generateId(),stepNumber:++this.stepCounter,timestamp:new Date,...n};return this.steps.push(r),this.currentStep=r,this.updateStatus(r.type),r}updateCurrentStep(n){return this.currentStep?(Object.assign(this.currentStep,n),this.currentStep):null}getCurrentStep(){return this.currentStep}getAllSteps(){return[...this.steps]}getStatus(){return this.status}reset(){this.steps=[],this.currentStep=null,this.status="idle",this.stepCounter=0}updateStatus(n){switch(n){case"thinking":case"tool_executing":case"output":case"input":case"retry":this.status="running";break;case"completed":this.status="completed";break;case"error":this.status="error";break}}generateId(){return`step_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}};s(_t,"UIState");let UIState=_t;const enUS={ui:{panel:{ready:"Ready",thinking:"Thinking...",paused:"Paused",taskInput:"Enter new task, describe steps in detail, press Enter to submit",userAnswerPrompt:"Please answer the question above, press Enter to submit",taskTerminated:"Task terminated",taskCompleted:"Task completed",continueExecution:"Continue execution",userAnswer:"User answer: {{input}}",question:"Question: {{question}}",waitingPlaceholder:"Waiting for task to start...",pause:"Pause",continue:"Continue",stop:"Stop",expand:"Expand history",collapse:"Collapse history",step:"Step {{number}} · {{time}}{{duration}}"},tools:{clicking:"Clicking element [{{index}}]...",inputting:"Inputting text to element [{{index}}]...",selecting:'Selecting option "{{text}}"...',scrolling:"Scrolling page...",waiting:"Waiting {{seconds}} seconds...",done:"Task done",clicked:"🖱️ Clicked element [{{index}}]",inputted:'⌨️ Inputted text "{{text}}"',selected:'☑️ Selected option "{{text}}"',scrolled:"🛞 Page scrolled",waited:"⌛️ Wait completed",executing:"Executing {{toolName}}...",resultSuccess:"success",resultFailure:"failed",resultError:"error"},errors:{elementNotFound:"No interactive element found at index {{index}}",taskRequired:"Task description is required",executionFailed:"Task execution failed",notInputElement:"Element is not an input or textarea",notSelectElement:"Element is not a select element",optionNotFound:'Option "{{text}}" not found'}}},zhCN={ui:{panel:{ready:"准备就绪",thinking:"正在思考...",paused:"暂停中,稍后",taskInput:"输入新任务,详细描述步骤,回车提交",userAnswerPrompt:"请回答上面问题,回车提交",taskTerminated:"任务已终止",taskCompleted:"任务结束",continueExecution:"继续执行",userAnswer:"用户回答: {{input}}",question:"询问: {{question}}",waitingPlaceholder:"等待任务开始...",pause:"暂停",continue:"继续",stop:"终止",expand:"展开历史",collapse:"收起历史",step:"步骤 {{number}} · {{time}}{{duration}}"},tools:{clicking:"正在点击元素 [{{index}}]...",inputting:"正在输入文本到元素 [{{index}}]...",selecting:'正在选择选项 "{{text}}"...',scrolling:"正在滚动页面...",waiting:"等待 {{seconds}} 秒...",done:"结束任务",clicked:"🖱️ 已点击元素 [{{index}}]",inputted:'⌨️ 已输入文本 "{{text}}"',selected:'☑️ 已选择选项 "{{text}}"',scrolled:"🛞 页面滚动完成",waited:"⌛️ 等待完成",executing:"正在执行 {{toolName}}...",resultSuccess:"成功",resultFailure:"失败",resultError:"错误"},errors:{elementNotFound:"未找到索引为 {{index}} 的交互元素",taskRequired:"任务描述不能为空",executionFailed:"任务执行失败",notInputElement:"元素不是输入框或文本域",notSelectElement:"元素不是选择框",optionNotFound:'未找到选项 "{{text}}"'}}},locales={"en-US":enUS,"zh-CN":zhCN},yt=class yt{language;translations;constructor(n="en-US"){this.language=n in locales?n:"en-US",this.translations=locales[this.language]}t(n,r){const o=this.getNestedValue(this.translations,n);return o?r?this.interpolate(o,r):o:(console.warn(`Translation key "${n}" not found for language "${this.language}"`),n)}getNestedValue(n,r){return r.split(".").reduce((o,t)=>o?.[t],n)}interpolate(n,r){return n.replace(/\{\{(\w+)\}\}/g,(o,t)=>r[t]!=null?r[t].toString():o)}getLanguage(){return this.language}};s(yt,"I18n");let I18n=yt;function truncate(e,n){return e.length>n?e.substring(0,n)+"...":e}s(truncate,"truncate");const wrapper="_wrapper_1j0ct_1",background="_background_1j0ct_39",header="_header_1j0ct_99",pulse="_pulse_1j0ct_1",retryPulse="_retryPulse_1j0ct_1",statusTextFadeOut="_statusTextFadeOut_1j0ct_1",statusTextFadeIn="_statusTextFadeIn_1j0ct_1",statusSection="_statusSection_1j0ct_121",indicator="_indicator_1j0ct_128",thinking="_thinking_1j0ct_137",tool_executing="_tool_executing_1j0ct_142",retry="_retry_1j0ct_147",completed="_completed_1j0ct_153",input="_input_1j0ct_154",output="_output_1j0ct_155",error="_error_1j0ct_160",statusText="_statusText_1j0ct_166",fadeOut="_fadeOut_1j0ct_178",fadeIn="_fadeIn_1j0ct_182",controls="_controls_1j0ct_188",controlButton="_controlButton_1j0ct_193",pauseButton="_pauseButton_1j0ct_212",paused="_paused_1j0ct_214",stopButton="_stopButton_1j0ct_224",historySectionWrapper="_historySectionWrapper_1j0ct_258",shimmer="_shimmer_1j0ct_1",celebrate="_celebrate_1j0ct_1",expanded="_expanded_1j0ct_290",historySection="_historySection_1j0ct_258",historyItem="_historyItem_1j0ct_309",doneSuccess="_doneSuccess_1j0ct_368",historyContent="_historyContent_1j0ct_404",statusIcon="_statusIcon_1j0ct_405",doneError="_doneError_1j0ct_414",historyMeta="_historyMeta_1j0ct_465",inputSectionWrapper="_inputSectionWrapper_1j0ct_535",hidden="_hidden_1j0ct_558",inputSection="_inputSection_1j0ct_535",taskInput="_taskInput_1j0ct_569",styles={wrapper,"mask-running":"_mask-running_1j0ct_1",background,header,pulse,retryPulse,statusTextFadeOut,statusTextFadeIn,statusSection,indicator,thinking,tool_executing,retry,completed,input,output,error,statusText,fadeOut,fadeIn,controls,controlButton,pauseButton,paused,stopButton,historySectionWrapper,shimmer,celebrate,expanded,historySection,historyItem,doneSuccess,historyContent,statusIcon,doneError,historyMeta,inputSectionWrapper,hidden,inputSection,taskInput},$t=class $t{constructor(n){D(this,_);D(this,Q);D(this,We);D(this,ee);D(this,Ae);D(this,Ce);D(this,se);D(this,Ke);D(this,Re);D(this,$e);D(this,Le,new UIState);D(this,Te,!1);D(this,_e);D(this,U);D(this,Ee,null);D(this,we,!1);D(this,Fe,null);D(this,ke,null);D(this,Je,!1);E(this,_e,n),E(this,U,new I18n(n.language??"en-US")),E(this,Q,T(this,_,Lt).call(this)),E(this,We,f(this,Q).querySelector(`.${styles.indicator}`)),E(this,ee,f(this,Q).querySelector(`.${styles.statusText}`)),E(this,Ae,f(this,Q).querySelector(`.${styles.historySection}`)),E(this,Ce,f(this,Q).querySelector(`.${styles.expandButton}`)),E(this,se,f(this,Q).querySelector(`.${styles.pauseButton}`)),E(this,Ke,f(this,Q).querySelector(`.${styles.stopButton}`)),E(this,Re,f(this,Q).querySelector(`.${styles.inputSectionWrapper}`)),E(this,$e,f(this,Q).querySelector(`.${styles.taskInput}`)),T(this,_,Ft).call(this),T(this,_,Mt).call(this),T(this,_,tt).call(this)}get wrapper(){return f(this,Q)}async askUser(n){return new Promise(r=>{E(this,we,!0),E(this,Ee,r),T(this,_,et).call(this,{type:"output",displayText:f(this,U).t("ui.panel.question",{question:n})}),f(this,Te)||T(this,_,nt).call(this),T(this,_,tt).call(this,f(this,U).t("ui.panel.userAnswerPrompt"))})}show(){this.wrapper.style.display="block",this.wrapper.offsetHeight,this.wrapper.style.opacity="1",this.wrapper.style.transform="translateX(-50%) translateY(0)"}hide(){this.wrapper.style.opacity="0",this.wrapper.style.transform="translateX(-50%) translateY(20px)",this.wrapper.style.display="none"}reset(){f(this,Le).reset(),f(this,ee).textContent=f(this,U).t("ui.panel.ready"),T(this,_,rt).call(this,"thinking"),T(this,_,zt).call(this),T(this,_,st).call(this),f(this,_e).getPaused()&&f(this,_e).onPauseToggle(),T(this,_,St).call(this),E(this,we,!1),E(this,Ee,null),T(this,_,tt).call(this)}expand(){T(this,_,nt).call(this)}collapse(){T(this,_,st).call(this)}update(n){const r=T(this,_,Pt).call(this,n);T(this,_,et).call(this,r)}dispose(){E(this,we,!1),T(this,_,Bt).call(this),this.wrapper.remove()}};Q=new WeakMap,We=new WeakMap,ee=new WeakMap,Ae=new WeakMap,Ce=new WeakMap,se=new WeakMap,Ke=new WeakMap,Re=new WeakMap,$e=new WeakMap,Le=new WeakMap,Te=new WeakMap,_e=new WeakMap,U=new WeakMap,Ee=new WeakMap,we=new WeakMap,Fe=new WeakMap,ke=new WeakMap,Je=new WeakMap,_=new WeakSet,Pt=s(function(n){switch(n.type){case"thinking":return{type:"thinking",displayText:n.text??f(this,U).t("ui.panel.thinking")};case"input":return{type:"input",displayText:n.task};case"question":return{type:"output",displayText:f(this,U).t("ui.panel.question",{question:n.question})};case"userAnswer":return{type:"input",displayText:f(this,U).t("ui.panel.userAnswer",{input:n.input})};case"retry":return{type:"retry",displayText:`retry-ing (${n.current} / ${n.max})`};case"error":return{type:"error",displayText:n.message};case"output":return{type:"output",displayText:n.text};case"completed":return{type:"completed",displayText:f(this,U).t("ui.panel.taskCompleted")};case"toolExecuting":return{type:"tool_executing",toolName:n.toolName,toolArgs:n.args,displayText:T(this,_,Ot).call(this,n.toolName,n.args)};case"toolCompleted":{const r=T(this,_,Ut).call(this,n.toolName,n.args);return r?{type:"tool_executing",toolName:n.toolName,toolArgs:n.args,toolResult:n.result,displayText:r,duration:n.duration}:{type:"tool_executing",displayText:""}}}},"#toStepData"),Ot=s(function(n,r){switch(n){case"click_element_by_index":return f(this,U).t("ui.tools.clicking",{index:r.index});case"input_text":return f(this,U).t("ui.tools.inputting",{index:r.index});case"select_dropdown_option":return f(this,U).t("ui.tools.selecting",{text:r.text});case"scroll":return f(this,U).t("ui.tools.scrolling");case"wait":return f(this,U).t("ui.tools.waiting",{seconds:r.seconds});case"done":return f(this,U).t("ui.tools.done");default:return f(this,U).t("ui.tools.executing",{toolName:n})}},"#getToolExecutingText"),Ut=s(function(n,r){switch(n){case"click_element_by_index":return f(this,U).t("ui.tools.clicked",{index:r.index});case"input_text":return f(this,U).t("ui.tools.inputted",{text:r.text});case"select_dropdown_option":return f(this,U).t("ui.tools.selected",{text:r.text});case"scroll":return f(this,U).t("ui.tools.scrolled");case"wait":return f(this,U).t("ui.tools.waited");case"done":return null;default:return null}},"#getToolCompletedText"),et=s(function(n){if(!n.displayText)return;const r=f(this,Le).addStep(n),o=truncate(r.displayText,20);E(this,ke,o),T(this,_,rt).call(this,r.type),T(this,_,zt).call(this),(r.type==="completed"||r.type==="error")&&(f(this,Te)||T(this,_,nt).call(this)),T(this,_,Rt).call(this)?T(this,_,tt).call(this):T(this,_,xt).call(this)},"#updateInternal"),Nt=s(function(){const n=f(this,_e).onPauseToggle();T(this,_,St).call(this),n?(f(this,ee).textContent=f(this,U).t("ui.panel.paused"),T(this,_,rt).call(this,"thinking")):(f(this,ee).textContent=f(this,U).t("ui.panel.continueExecution"),T(this,_,rt).call(this,"tool_executing"))},"#togglePause"),St=s(function(){f(this,_e).getPaused()?(f(this,se).textContent="▶",f(this,se).title=f(this,U).t("ui.panel.continue"),f(this,se).classList.add(styles.paused)):(f(this,se).textContent="⏸︎",f(this,se).title=f(this,U).t("ui.panel.pause"),f(this,se).classList.remove(styles.paused))},"#updatePauseButton"),Dt=s(function(){T(this,_,et).call(this,{type:"error",displayText:f(this,U).t("ui.panel.taskTerminated")}),f(this,_e).onStop()},"#stopAgent"),At=s(function(){const n=f(this,$e).value.trim();n&&(T(this,_,xt).call(this),f(this,we)?T(this,_,Ct).call(this,n):f(this,_e).onExecuteTask(n))},"#submitTask"),Ct=s(function(n){T(this,_,et).call(this,{type:"input",displayText:f(this,U).t("ui.panel.userAnswer",{input:n})}),E(this,we,!1),f(this,Ee)&&(f(this,Ee).call(this,n),E(this,Ee,null))},"#handleUserAnswer"),tt=s(function(n){f(this,$e).value="",f(this,$e).placeholder=n||f(this,U).t("ui.panel.taskInput"),f(this,Re).classList.remove(styles.hidden),setTimeout(()=>{f(this,$e).focus()},100)},"#showInputArea"),xt=s(function(){f(this,Re).classList.add(styles.hidden)},"#hideInputArea"),Rt=s(function(){if(f(this,we))return!0;const n=f(this,Le).getAllSteps();if(n.length===0)return!0;const r=n[n.length-1];return r.type==="completed"||r.type==="error"},"#shouldShowInputArea"),Lt=s(function(){const n=document.createElement("div");return n.id="page-agent-runtime_agent-panel",n.className=`${styles.wrapper} ${styles.collapsed}`,n.setAttribute("data-browser-use-ignore","true"),n.innerHTML=`
|
|
158
|
+
}`;const DEFAULT_COLORS=["rgb(57, 182, 255)","rgb(189, 69, 251)","rgb(255, 87, 51)","rgb(255, 214, 0)"];function parseColor(e){const n=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!n)throw new Error(`Invalid color format: ${e}`);const[,r,o,t]=n;return[parseInt(r)/255,parseInt(o)/255,parseInt(t)/255]}s(parseColor,"parseColor");const ht=class ht{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(n={}){this.options={width:n.width??600,height:n.height??600,ratio:n.ratio??window.devicePixelRatio??1,borderWidth:n.borderWidth??8,glowWidth:n.glowWidth??200,borderRadius:n.borderRadius??8,mode:n.mode??"light",...n},this.canvas=document.createElement("canvas"),this.options.classNames&&(this.canvas.className=this.options.classNames),this.options.styles&&Object.assign(this.canvas.style,this.options.styles),this.canvas.style.display="block",this.canvas.style.transformOrigin="center",this.canvas.style.pointerEvents="none",this.element=this.canvas,this.setupGL(),this.options.skipGreeting||this.greet()}start(){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.running)return;if(!this.glr){console.error("WebGL resources are not initialized.");return}this.running=!0,this.startTime=performance.now(),this.resize(this.options.width??600,this.options.height??600,this.options.ratio),this.glr.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.glr.gl.useProgram(this.glr.program),this.glr.gl.uniform2f(this.glr.uResolution,this.canvas.width,this.canvas.height),this.checkGLError(this.glr.gl,"start: after initial setup");const n=s(()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(n);const r=performance.now();if(r-this.lastTime<1e3/32)return;this.lastTime=r;const t=(r-this.startTime)*.001;this.render(t)},"loop");this.rafId=requestAnimationFrame(n)}pause(){if(this.disposed)throw new Error("Motion instance has been disposed.");this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId)}dispose(){if(this.disposed)return;this.disposed=!0,this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId);const{gl:n,vao:r,positionBuffer:o,uvBuffer:t,program:i}=this.glr;r&&n.deleteVertexArray(r),o&&n.deleteBuffer(o),t&&n.deleteBuffer(t),n.deleteProgram(i),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(n,r,o){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.options.width=n,this.options.height=r,o&&(this.options.ratio=o),!this.running)return;const{gl:t,program:i,vao:a,positionBuffer:c,uvBuffer:l,uResolution:u}=this.glr,m=o??this.options.ratio??window.devicePixelRatio??1,p=Math.max(1,Math.floor(n*m)),g=Math.max(1,Math.floor(r*m));this.canvas.style.width=`${n}px`,this.canvas.style.height=`${r}px`,(this.canvas.width!==p||this.canvas.height!==g)&&(this.canvas.width=p,this.canvas.height=g),t.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(t,"resize: after viewport setup");const{positions:h,uvs:y}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*m,this.options.glowWidth*m);t.bindVertexArray(a),t.bindBuffer(t.ARRAY_BUFFER,c),t.bufferData(t.ARRAY_BUFFER,h,t.STATIC_DRAW);const w=t.getAttribLocation(i,"aPosition");t.enableVertexAttribArray(w),t.vertexAttribPointer(w,2,t.FLOAT,!1,0,0),this.checkGLError(t,"resize: after position buffer update"),t.bindBuffer(t.ARRAY_BUFFER,l),t.bufferData(t.ARRAY_BUFFER,y,t.STATIC_DRAW);const Z=t.getAttribLocation(i,"aUV");t.enableVertexAttribArray(Z),t.vertexAttribPointer(Z,2,t.FLOAT,!1,0,0),this.checkGLError(t,"resize: after UV buffer update"),t.useProgram(i),t.uniform2f(u,this.canvas.width,this.canvas.height),t.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*m),t.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*m),t.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*m),this.checkGLError(t,"resize: after uniform updates");const N=performance.now();this.lastTime=N;const B=(N-this.startTime)*.001;this.render(B)}autoResize(n){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{const r=n.getBoundingClientRect();this.resize(r.width,r.height)}),this.observer.observe(n)}fadeIn(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((n,r)=>{const o=this.canvas.animate([{opacity:0,transform:"scale(1.2)"},{opacity:1,transform:"scale(1)"}],{duration:300,easing:"ease-out",fill:"forwards"});o.onfinish=()=>n(),o.oncancel=()=>r("canceled")})}fadeOut(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((n,r)=>{const o=this.canvas.animate([{opacity:1,transform:"scale(1)"},{opacity:0,transform:"scale(1.2)"}],{duration:300,easing:"ease-in",fill:"forwards"});o.onfinish=()=>n(),o.oncancel=()=>r("canceled")})}checkGLError(n,r){let o=n.getError();if(o!==n.NO_ERROR){for(console.group(`🔴 WebGL Error in ${r}`);o!==n.NO_ERROR;){const t=this.getGLErrorName(n,o);console.error(`${t} (0x${o.toString(16)})`),o=n.getError()}console.groupEnd()}}getGLErrorName(n,r){switch(r){case n.INVALID_ENUM:return"INVALID_ENUM";case n.INVALID_VALUE:return"INVALID_VALUE";case n.INVALID_OPERATION:return"INVALID_OPERATION";case n.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case n.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case n.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"UNKNOWN_ERROR"}}setupGL(){const n=this.canvas.getContext("webgl2",{antialias:!1,alpha:!0});if(!n)throw new Error("WebGL2 is required but not available.");const r=createProgram(n,vertexShaderSource,fragmentShaderSource);this.checkGLError(n,"setupGL: after createProgram");const o=n.createVertexArray();n.bindVertexArray(o),this.checkGLError(n,"setupGL: after VAO creation");const t=this.canvas.width||2,i=this.canvas.height||2,{positions:a,uvs:c}=computeBorderGeometry(t,i,this.options.borderWidth,this.options.glowWidth),l=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,l),n.bufferData(n.ARRAY_BUFFER,a,n.STATIC_DRAW);const u=n.getAttribLocation(r,"aPosition");n.enableVertexAttribArray(u),n.vertexAttribPointer(u,2,n.FLOAT,!1,0,0),this.checkGLError(n,"setupGL: after position buffer setup");const m=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,m),n.bufferData(n.ARRAY_BUFFER,c,n.STATIC_DRAW);const p=n.getAttribLocation(r,"aUV");n.enableVertexAttribArray(p),n.vertexAttribPointer(p,2,n.FLOAT,!1,0,0),this.checkGLError(n,"setupGL: after UV buffer setup");const g=n.getUniformLocation(r,"uResolution"),h=n.getUniformLocation(r,"uTime"),y=n.getUniformLocation(r,"uBorderWidth"),w=n.getUniformLocation(r,"uGlowWidth"),Z=n.getUniformLocation(r,"uBorderRadius"),N=n.getUniformLocation(r,"uColors"),B=n.getUniformLocation(r,"uGlowExponent"),S=n.getUniformLocation(r,"uGlowFactor");n.useProgram(r),n.uniform1f(y,this.options.borderWidth),n.uniform1f(w,this.options.glowWidth),n.uniform1f(Z,this.options.borderRadius),this.options.mode==="dark"?(n.uniform1f(B,2),n.uniform1f(S,1.8)):(n.uniform1f(B,1),n.uniform1f(S,1));const b=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let P=0;P<b.length;P++)n.uniform3f(n.getUniformLocation(r,`uColors[${P}]`),...b[P]);this.checkGLError(n,"setupGL: after uniform setup"),n.bindVertexArray(null),n.bindBuffer(n.ARRAY_BUFFER,null),this.glr={gl:n,program:r,vao:o,positionBuffer:l,uvBuffer:m,uResolution:g,uTime:h,uBorderWidth:y,uGlowWidth:w,uBorderRadius:Z,uColors:N}}render(n){if(!this.glr)return;const{gl:r,program:o,vao:t,uTime:i}=this.glr;r.useProgram(o),r.bindVertexArray(t),r.uniform1f(i,n),r.disable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.disable(r.BLEND),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLES,0,24),this.checkGLError(r,"render: after draw call"),r.bindVertexArray(null)}greet(){console.log("%c🌈 ai-motion 0.4.8 🌈","background: linear-gradient(90deg, #39b6ff, #bd45fb, #ff5733, #ffd600); color: white; text-shadow: 0 0 2px rgba(0, 0, 0, 0.2); font-weight: bold; font-size: 1em; padding: 2px 12px; border-radius: 6px;")}};s(ht,"Motion");let Motion=ht;function hasDarkModeClass(){const e=["dark","dark-mode","theme-dark","night","night-mode"],n=document.documentElement,r=document.body||document.documentElement;for(const t of e)if(n.classList.contains(t)||r?.classList.contains(t))return!0;return!!n.getAttribute("data-theme")?.toLowerCase().includes("dark")}s(hasDarkModeClass,"hasDarkModeClass");function parseRgbColor(e){const n=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(e);return n?{r:parseInt(n[1]),g:parseInt(n[2]),b:parseInt(n[3])}:null}s(parseRgbColor,"parseRgbColor");function isColorDark(e,n=128){if(!e||e==="transparent"||e.startsWith("rgba(0, 0, 0, 0)"))return!1;const r=parseRgbColor(e);return r?.299*r.r+.587*r.g+.114*r.b<n:!1}s(isColorDark,"isColorDark");function isBackgroundDark(){const e=window.getComputedStyle(document.documentElement),n=window.getComputedStyle(document.body||document.documentElement),r=e.backgroundColor,o=n.backgroundColor;return isColorDark(o)?!0:o==="transparent"||o.startsWith("rgba(0, 0, 0, 0)")?isColorDark(r):!1}s(isBackgroundDark,"isBackgroundDark");function isPageDark(){try{return!!(hasDarkModeClass()||isBackgroundDark())}catch(e){return console.warn("Error determining if page is dark:",e),!1}}s(isPageDark,"isPageDark");const wrapper$1="_wrapper_1oy2s_1",styles$1={wrapper:wrapper$1},cursor="_cursor_1vrf3_2",cursorBorder="_cursorBorder_1vrf3_13",cursorFilling="_cursorFilling_1vrf3_23",cursorRipple="_cursorRipple_1vrf3_31",clicking="_clicking_1vrf3_37",cursorStyles={cursor,cursorBorder,cursorFilling,cursorRipple,clicking},vt=class vt{constructor(){D(this,De);re(this,"wrapper",document.createElement("div"));re(this,"motion",new Motion({mode:isPageDark()?"dark":"light",styles:{position:"absolute",inset:"0"}}));D(this,q,document.createElement("div"));D(this,oe,0);D(this,ae,0);D(this,Ie,0);D(this,ze,0);this.wrapper.id="page-agent-runtime_simulator-mask",this.wrapper.className=styles$1.wrapper,this.wrapper.setAttribute("data-browser-use-ignore","true"),this.wrapper.appendChild(this.motion.element),this.motion.autoResize(this.wrapper),this.wrapper.addEventListener("click",n=>{n.stopPropagation(),n.preventDefault()}),this.wrapper.addEventListener("mousedown",n=>{n.stopPropagation(),n.preventDefault()}),this.wrapper.addEventListener("mouseup",n=>{n.stopPropagation(),n.preventDefault()}),this.wrapper.addEventListener("mousemove",n=>{n.stopPropagation(),n.preventDefault()}),this.wrapper.addEventListener("wheel",n=>{n.stopPropagation(),n.preventDefault()}),this.wrapper.addEventListener("keydown",n=>{n.stopPropagation(),n.preventDefault()}),this.wrapper.addEventListener("keyup",n=>{n.stopPropagation(),n.preventDefault()}),T(this,De,jt).call(this),document.body.appendChild(this.wrapper),T(this,De,kt).call(this),window.addEventListener("PageAgent::MovePointerTo",n=>{const{x:r,y:o}=n.detail;this.setCursorPosition(r,o)}),window.addEventListener("PageAgent::ClickPointer",n=>{this.triggerClickAnimation()})}setCursorPosition(n,r){E(this,Ie,n),E(this,ze,r)}triggerClickAnimation(){f(this,q).classList.remove(cursorStyles.clicking),f(this,q).offsetHeight,f(this,q).classList.add(cursorStyles.clicking)}show(){this.motion.start(),this.motion.fadeIn(),this.wrapper.style.display="block",E(this,oe,window.innerWidth/2),E(this,ae,window.innerHeight/2),E(this,Ie,f(this,oe)),E(this,ze,f(this,ae)),f(this,q).style.left=`${f(this,oe)}px`,f(this,q).style.top=`${f(this,ae)}px`}hide(){this.motion.fadeOut(),this.motion.pause(),f(this,q).classList.remove(cursorStyles.clicking),setTimeout(()=>{this.wrapper.style.display="none"},800)}dispose(){this.motion.dispose(),this.wrapper.remove()}};q=new WeakMap,oe=new WeakMap,ae=new WeakMap,Ie=new WeakMap,ze=new WeakMap,De=new WeakSet,jt=s(function(){f(this,q).className=cursorStyles.cursor;const n=document.createElement("div");n.className=cursorStyles.cursorRipple,f(this,q).appendChild(n);const r=document.createElement("div");r.className=cursorStyles.cursorFilling,f(this,q).appendChild(r);const o=document.createElement("div");o.className=cursorStyles.cursorBorder,f(this,q).appendChild(o),this.wrapper.appendChild(f(this,q))},"#createCursor"),kt=s(function(){const n=f(this,oe)+(f(this,Ie)-f(this,oe))*.2,r=f(this,ae)+(f(this,ze)-f(this,ae))*.2,o=Math.abs(n-f(this,Ie));o>0&&(o<2?E(this,oe,f(this,Ie)):E(this,oe,n),f(this,q).style.left=`${f(this,oe)}px`);const t=Math.abs(r-f(this,ze));t>0&&(t<2?E(this,ae,f(this,ze)):E(this,ae,r),f(this,q).style.top=`${f(this,ae)}px`),requestAnimationFrame(()=>T(this,De,kt).call(this))},"#moveCursorToTarget"),s(vt,"SimulatorMask");let SimulatorMask=vt;function patchReact(e){const n=document.querySelectorAll('[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root');for(const r of n)r.setAttribute("data-page-agent-not-interactive","true")}s(patchReact,"patchReact");const _PageController=class _PageController extends EventTarget{config;flatTree=null;selectorMap=new Map;elementTextMap=new Map;simplifiedHTML="<EMPTY>";lastTimeUpdate=0;mask=null;constructor(e={}){super(),this.config=e,patchReact(),e.enableMask&&(this.mask=new SimulatorMask)}async getCurrentUrl(){return window.location.href}async getPageTitle(){return document.title}async getPageInfo(){return getPageInfo()}async getSimplifiedHTML(){return this.simplifiedHTML}async getElementText(e){return this.elementTextMap.get(e)}async getElementCount(){return this.selectorMap.size}async getLastUpdateTime(){return this.lastTimeUpdate}async getViewportExpansion(){return this.config.viewportExpansion??VIEWPORT_EXPANSION}async updateTree(){this.dispatchEvent(new Event("beforeUpdate")),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents="none"),cleanUpHighlights();const e=[...this.config.interactiveBlacklist||[],...document.querySelectorAll("[data-page-agent-not-interactive]").values()];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:e}),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.mask&&(this.mask.wrapper.style.pointerEvents="auto"),this.dispatchEvent(new Event("afterUpdate")),this.simplifiedHTML}async cleanUpHighlights(){cleanUpHighlights()}async clickElement(e){try{const n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return await clickElement(n),n instanceof HTMLAnchorElement&&n.target==="_blank"?{success:!0,message:`✅ Clicked element (${r??e}). ⚠️ Link opens in a new tab. You are not capable of reading new tabs.`}:{success:!0,message:`✅ Clicked element (${r??e}).`}}catch(n){return{success:!1,message:`❌ Failed to click element: ${n}`}}}async inputText(e,n){try{const r=getElementByIndex(this.selectorMap,e),o=this.elementTextMap.get(e);return await inputTextElement(r,n),{success:!0,message:`✅ Input text (${n}) into element (${o??e}).`}}catch(r){return{success:!1,message:`❌ Failed to input text: ${r}`}}}async selectOption(e,n){try{const r=getElementByIndex(this.selectorMap,e),o=this.elementTextMap.get(e);return await selectOptionElement(r,n),{success:!0,message:`✅ Selected option (${n}) in element (${o??e}).`}}catch(r){return{success:!1,message:`❌ Failed to select option: ${r}`}}}async scroll(e){try{const{down:n,numPages:r,pixels:o,index:t}=e,i=o??r*(n?1:-1)*window.innerHeight,a=t!==void 0?getElementByIndex(this.selectorMap,t):null;return{success:!0,message:await scrollVertically(n,i,a)}}catch(n){return{success:!1,message:`❌ Failed to scroll: ${n}`}}}async scrollHorizontally(e){try{const{right:n,pixels:r,index:o}=e,t=r*(n?1:-1),i=o!==void 0?getElementByIndex(this.selectorMap,o):null;return{success:!0,message:await scrollHorizontally(n,t,i)}}catch(n){return{success:!1,message:`❌ Failed to scroll horizontally: ${n}`}}}async executeJavascript(script){try{const asyncFunction=eval(`(async () => { ${script} })`),result=await asyncFunction();return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(e){return{success:!1,message:`❌ Error executing JavaScript: ${e}`}}}showMask(){this.mask?.show()}hideMask(){this.mask?.hide()}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="<EMPTY>",this.mask?.dispose(),this.mask=null}};s(_PageController,"PageController");let PageController=_PageController;const _t=class _t{steps=[];currentStep=null;status="idle";stepCounter=0;addStep(n){const r={id:this.generateId(),stepNumber:++this.stepCounter,timestamp:new Date,...n};return this.steps.push(r),this.currentStep=r,this.updateStatus(r.type),r}updateCurrentStep(n){return this.currentStep?(Object.assign(this.currentStep,n),this.currentStep):null}getCurrentStep(){return this.currentStep}getAllSteps(){return[...this.steps]}getStatus(){return this.status}reset(){this.steps=[],this.currentStep=null,this.status="idle",this.stepCounter=0}updateStatus(n){switch(n){case"thinking":case"tool_executing":case"output":case"input":case"retry":this.status="running";break;case"completed":this.status="completed";break;case"error":this.status="error";break}}generateId(){return`step_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}};s(_t,"UIState");let UIState=_t;const enUS={ui:{panel:{ready:"Ready",thinking:"Thinking...",paused:"Paused",taskInput:"Enter new task, describe steps in detail, press Enter to submit",userAnswerPrompt:"Please answer the question above, press Enter to submit",taskTerminated:"Task terminated",taskCompleted:"Task completed",continueExecution:"Continue execution",userAnswer:"User answer: {{input}}",question:"Question: {{question}}",waitingPlaceholder:"Waiting for task to start...",pause:"Pause",continue:"Continue",stop:"Stop",expand:"Expand history",collapse:"Collapse history",step:"Step {{number}} · {{time}}{{duration}}"},tools:{clicking:"Clicking element [{{index}}]...",inputting:"Inputting text to element [{{index}}]...",selecting:'Selecting option "{{text}}"...',scrolling:"Scrolling page...",waiting:"Waiting {{seconds}} seconds...",done:"Task done",clicked:"🖱️ Clicked element [{{index}}]",inputted:'⌨️ Inputted text "{{text}}"',selected:'☑️ Selected option "{{text}}"',scrolled:"🛞 Page scrolled",waited:"⌛️ Wait completed",executing:"Executing {{toolName}}...",resultSuccess:"success",resultFailure:"failed",resultError:"error"},errors:{elementNotFound:"No interactive element found at index {{index}}",taskRequired:"Task description is required",executionFailed:"Task execution failed",notInputElement:"Element is not an input or textarea",notSelectElement:"Element is not a select element",optionNotFound:'Option "{{text}}" not found'}}},zhCN={ui:{panel:{ready:"准备就绪",thinking:"正在思考...",paused:"暂停中,稍后",taskInput:"输入新任务,详细描述步骤,回车提交",userAnswerPrompt:"请回答上面问题,回车提交",taskTerminated:"任务已终止",taskCompleted:"任务结束",continueExecution:"继续执行",userAnswer:"用户回答: {{input}}",question:"询问: {{question}}",waitingPlaceholder:"等待任务开始...",pause:"暂停",continue:"继续",stop:"终止",expand:"展开历史",collapse:"收起历史",step:"步骤 {{number}} · {{time}}{{duration}}"},tools:{clicking:"正在点击元素 [{{index}}]...",inputting:"正在输入文本到元素 [{{index}}]...",selecting:'正在选择选项 "{{text}}"...',scrolling:"正在滚动页面...",waiting:"等待 {{seconds}} 秒...",done:"结束任务",clicked:"🖱️ 已点击元素 [{{index}}]",inputted:'⌨️ 已输入文本 "{{text}}"',selected:'☑️ 已选择选项 "{{text}}"',scrolled:"🛞 页面滚动完成",waited:"⌛️ 等待完成",executing:"正在执行 {{toolName}}...",resultSuccess:"成功",resultFailure:"失败",resultError:"错误"},errors:{elementNotFound:"未找到索引为 {{index}} 的交互元素",taskRequired:"任务描述不能为空",executionFailed:"任务执行失败",notInputElement:"元素不是输入框或文本域",notSelectElement:"元素不是选择框",optionNotFound:'未找到选项 "{{text}}"'}}},locales={"en-US":enUS,"zh-CN":zhCN},yt=class yt{language;translations;constructor(n="en-US"){this.language=n in locales?n:"en-US",this.translations=locales[this.language]}t(n,r){const o=this.getNestedValue(this.translations,n);return o?r?this.interpolate(o,r):o:(console.warn(`Translation key "${n}" not found for language "${this.language}"`),n)}getNestedValue(n,r){return r.split(".").reduce((o,t)=>o?.[t],n)}interpolate(n,r){return n.replace(/\{\{(\w+)\}\}/g,(o,t)=>r[t]!=null?r[t].toString():o)}getLanguage(){return this.language}};s(yt,"I18n");let I18n=yt;function truncate(e,n){return e.length>n?e.substring(0,n)+"...":e}s(truncate,"truncate");function escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}s(escapeHtml,"escapeHtml");const wrapper="_wrapper_1j0ct_1",background="_background_1j0ct_39",header="_header_1j0ct_99",pulse="_pulse_1j0ct_1",retryPulse="_retryPulse_1j0ct_1",statusTextFadeOut="_statusTextFadeOut_1j0ct_1",statusTextFadeIn="_statusTextFadeIn_1j0ct_1",statusSection="_statusSection_1j0ct_121",indicator="_indicator_1j0ct_128",thinking="_thinking_1j0ct_137",tool_executing="_tool_executing_1j0ct_142",retry="_retry_1j0ct_147",completed="_completed_1j0ct_153",input="_input_1j0ct_154",output="_output_1j0ct_155",error="_error_1j0ct_160",statusText="_statusText_1j0ct_166",fadeOut="_fadeOut_1j0ct_178",fadeIn="_fadeIn_1j0ct_182",controls="_controls_1j0ct_188",controlButton="_controlButton_1j0ct_193",pauseButton="_pauseButton_1j0ct_212",paused="_paused_1j0ct_214",stopButton="_stopButton_1j0ct_224",historySectionWrapper="_historySectionWrapper_1j0ct_258",shimmer="_shimmer_1j0ct_1",celebrate="_celebrate_1j0ct_1",expanded="_expanded_1j0ct_290",historySection="_historySection_1j0ct_258",historyItem="_historyItem_1j0ct_309",doneSuccess="_doneSuccess_1j0ct_368",historyContent="_historyContent_1j0ct_404",statusIcon="_statusIcon_1j0ct_405",doneError="_doneError_1j0ct_414",historyMeta="_historyMeta_1j0ct_465",inputSectionWrapper="_inputSectionWrapper_1j0ct_535",hidden="_hidden_1j0ct_558",inputSection="_inputSection_1j0ct_535",taskInput="_taskInput_1j0ct_569",styles={wrapper,"mask-running":"_mask-running_1j0ct_1",background,header,pulse,retryPulse,statusTextFadeOut,statusTextFadeIn,statusSection,indicator,thinking,tool_executing,retry,completed,input,output,error,statusText,fadeOut,fadeIn,controls,controlButton,pauseButton,paused,stopButton,historySectionWrapper,shimmer,celebrate,expanded,historySection,historyItem,doneSuccess,historyContent,statusIcon,doneError,historyMeta,inputSectionWrapper,hidden,inputSection,taskInput},$t=class $t{constructor(n){D(this,_);D(this,Q);D(this,We);D(this,ee);D(this,Ae);D(this,Ce);D(this,se);D(this,Ke);D(this,Re);D(this,$e);D(this,Le,new UIState);D(this,Te,!1);D(this,_e);D(this,U);D(this,Ee,null);D(this,we,!1);D(this,Fe,null);D(this,ke,null);D(this,Je,!1);E(this,_e,n),E(this,U,new I18n(n.language??"en-US")),E(this,Q,T(this,_,Lt).call(this)),E(this,We,f(this,Q).querySelector(`.${styles.indicator}`)),E(this,ee,f(this,Q).querySelector(`.${styles.statusText}`)),E(this,Ae,f(this,Q).querySelector(`.${styles.historySection}`)),E(this,Ce,f(this,Q).querySelector(`.${styles.expandButton}`)),E(this,se,f(this,Q).querySelector(`.${styles.pauseButton}`)),E(this,Ke,f(this,Q).querySelector(`.${styles.stopButton}`)),E(this,Re,f(this,Q).querySelector(`.${styles.inputSectionWrapper}`)),E(this,$e,f(this,Q).querySelector(`.${styles.taskInput}`)),T(this,_,Ft).call(this),T(this,_,Mt).call(this),T(this,_,tt).call(this)}get wrapper(){return f(this,Q)}async askUser(n){return new Promise(r=>{E(this,we,!0),E(this,Ee,r),T(this,_,et).call(this,{type:"output",displayText:f(this,U).t("ui.panel.question",{question:n})}),f(this,Te)||T(this,_,nt).call(this),T(this,_,tt).call(this,f(this,U).t("ui.panel.userAnswerPrompt"))})}show(){this.wrapper.style.display="block",this.wrapper.offsetHeight,this.wrapper.style.opacity="1",this.wrapper.style.transform="translateX(-50%) translateY(0)"}hide(){this.wrapper.style.opacity="0",this.wrapper.style.transform="translateX(-50%) translateY(20px)",this.wrapper.style.display="none"}reset(){f(this,Le).reset(),f(this,ee).textContent=f(this,U).t("ui.panel.ready"),T(this,_,rt).call(this,"thinking"),T(this,_,zt).call(this),T(this,_,st).call(this),f(this,_e).getPaused()&&f(this,_e).onPauseToggle(),T(this,_,St).call(this),E(this,we,!1),E(this,Ee,null),T(this,_,tt).call(this)}expand(){T(this,_,nt).call(this)}collapse(){T(this,_,st).call(this)}update(n){const r=T(this,_,Pt).call(this,n);T(this,_,et).call(this,r)}dispose(){E(this,we,!1),T(this,_,Bt).call(this),this.wrapper.remove()}};Q=new WeakMap,We=new WeakMap,ee=new WeakMap,Ae=new WeakMap,Ce=new WeakMap,se=new WeakMap,Ke=new WeakMap,Re=new WeakMap,$e=new WeakMap,Le=new WeakMap,Te=new WeakMap,_e=new WeakMap,U=new WeakMap,Ee=new WeakMap,we=new WeakMap,Fe=new WeakMap,ke=new WeakMap,Je=new WeakMap,_=new WeakSet,Pt=s(function(n){switch(n.type){case"thinking":return{type:"thinking",displayText:n.text??f(this,U).t("ui.panel.thinking")};case"input":return{type:"input",displayText:n.task};case"question":return{type:"output",displayText:f(this,U).t("ui.panel.question",{question:n.question})};case"userAnswer":return{type:"input",displayText:f(this,U).t("ui.panel.userAnswer",{input:n.input})};case"retry":return{type:"retry",displayText:`retry-ing (${n.current} / ${n.max})`};case"error":return{type:"error",displayText:n.message};case"output":return{type:"output",displayText:n.text};case"completed":return{type:"completed",displayText:f(this,U).t("ui.panel.taskCompleted")};case"toolExecuting":return{type:"tool_executing",toolName:n.toolName,toolArgs:n.args,displayText:T(this,_,Ot).call(this,n.toolName,n.args)};case"toolCompleted":{const r=T(this,_,Ut).call(this,n.toolName,n.args);return r?{type:"tool_executing",toolName:n.toolName,toolArgs:n.args,toolResult:n.result,displayText:r,duration:n.duration}:{type:"tool_executing",displayText:""}}}},"#toStepData"),Ot=s(function(n,r){switch(n){case"click_element_by_index":return f(this,U).t("ui.tools.clicking",{index:r.index});case"input_text":return f(this,U).t("ui.tools.inputting",{index:r.index});case"select_dropdown_option":return f(this,U).t("ui.tools.selecting",{text:r.text});case"scroll":return f(this,U).t("ui.tools.scrolling");case"wait":return f(this,U).t("ui.tools.waiting",{seconds:r.seconds});case"done":return f(this,U).t("ui.tools.done");default:return f(this,U).t("ui.tools.executing",{toolName:n})}},"#getToolExecutingText"),Ut=s(function(n,r){switch(n){case"click_element_by_index":return f(this,U).t("ui.tools.clicked",{index:r.index});case"input_text":return f(this,U).t("ui.tools.inputted",{text:r.text});case"select_dropdown_option":return f(this,U).t("ui.tools.selected",{text:r.text});case"scroll":return f(this,U).t("ui.tools.scrolled");case"wait":return f(this,U).t("ui.tools.waited");case"done":return null;default:return null}},"#getToolCompletedText"),et=s(function(n){if(!n.displayText)return;const r=f(this,Le).addStep(n),o=truncate(r.displayText,20);E(this,ke,o),T(this,_,rt).call(this,r.type),T(this,_,zt).call(this),(r.type==="completed"||r.type==="error")&&(f(this,Te)||T(this,_,nt).call(this)),T(this,_,Rt).call(this)?T(this,_,tt).call(this):T(this,_,xt).call(this)},"#updateInternal"),Nt=s(function(){const n=f(this,_e).onPauseToggle();T(this,_,St).call(this),n?(f(this,ee).textContent=f(this,U).t("ui.panel.paused"),T(this,_,rt).call(this,"thinking")):(f(this,ee).textContent=f(this,U).t("ui.panel.continueExecution"),T(this,_,rt).call(this,"tool_executing"))},"#togglePause"),St=s(function(){f(this,_e).getPaused()?(f(this,se).textContent="▶",f(this,se).title=f(this,U).t("ui.panel.continue"),f(this,se).classList.add(styles.paused)):(f(this,se).textContent="⏸︎",f(this,se).title=f(this,U).t("ui.panel.pause"),f(this,se).classList.remove(styles.paused))},"#updatePauseButton"),Dt=s(function(){T(this,_,et).call(this,{type:"error",displayText:f(this,U).t("ui.panel.taskTerminated")}),f(this,_e).onStop()},"#stopAgent"),At=s(function(){const n=f(this,$e).value.trim();n&&(T(this,_,xt).call(this),f(this,we)?T(this,_,Ct).call(this,n):f(this,_e).onExecuteTask(n))},"#submitTask"),Ct=s(function(n){T(this,_,et).call(this,{type:"input",displayText:f(this,U).t("ui.panel.userAnswer",{input:n})}),E(this,we,!1),f(this,Ee)&&(f(this,Ee).call(this,n),E(this,Ee,null))},"#handleUserAnswer"),tt=s(function(n){f(this,$e).value="",f(this,$e).placeholder=n||f(this,U).t("ui.panel.taskInput"),f(this,Re).classList.remove(styles.hidden),setTimeout(()=>{f(this,$e).focus()},100)},"#showInputArea"),xt=s(function(){f(this,Re).classList.add(styles.hidden)},"#hideInputArea"),Rt=s(function(){if(f(this,we))return!0;const n=f(this,Le).getAllSteps();if(n.length===0)return!0;const r=n[n.length-1];return r.type==="completed"||r.type==="error"},"#shouldShowInputArea"),Lt=s(function(){const n=document.createElement("div");return n.id="page-agent-runtime_agent-panel",n.className=`${styles.wrapper} ${styles.collapsed}`,n.setAttribute("data-browser-use-ignore","true"),n.innerHTML=`
|
|
159
159
|
<div class="${styles.background}"></div>
|
|
160
160
|
<div class="${styles.historySectionWrapper}">
|
|
161
161
|
<div class="${styles.historySection}">
|
|
@@ -192,7 +192,7 @@ gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
|
192
192
|
<div class="${styles.historyItem} ${o}">
|
|
193
193
|
<div class="${styles.historyContent}">
|
|
194
194
|
<span class="${styles.statusIcon}">${t}</span>
|
|
195
|
-
<span>${n.displayText}</span>
|
|
195
|
+
<span>${escapeHtml(n.displayText)}</span>
|
|
196
196
|
</div>
|
|
197
197
|
<div class="${styles.historyMeta}">
|
|
198
198
|
${a}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "page-agent",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.23",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/esm/page-agent.js",
|
|
7
7
|
"module": "./dist/esm/page-agent.js",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"dependencies": {
|
|
47
47
|
"chalk": "^5.6.2",
|
|
48
48
|
"zod": "^4.3.5",
|
|
49
|
-
"@page-agent/llms": "0.0.
|
|
50
|
-
"@page-agent/page-controller": "0.0.
|
|
51
|
-
"@page-agent/ui": "0.0.
|
|
49
|
+
"@page-agent/llms": "0.0.23",
|
|
50
|
+
"@page-agent/page-controller": "0.0.23",
|
|
51
|
+
"@page-agent/ui": "0.0.23"
|
|
52
52
|
}
|
|
53
53
|
}
|