page-agent 1.9.0 → 1.9.1
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/README.md +5 -3
- package/dist/iife/page-agent.demo.js +7 -8
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -13,7 +13,9 @@ The GUI Agent Living in Your Webpage. Control web interfaces with natural langua
|
|
|
13
13
|
|
|
14
14
|
<a href="https://alibaba.github.io/page-agent/" target="_blank"><b>🚀 Demo</b></a> | <a href="https://alibaba.github.io/page-agent/docs/introduction/overview" target="_blank"><b>📖 Docs</b></a> | <a href="https://news.ycombinator.com/item?id=47264138" target="_blank"><b>📢 HN Discussion</b></a> | <a href="https://x.com/simonluvramen" target="_blank"><b>𝕏 Follow on X</b></a>
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
<!-- demo video -->
|
|
17
|
+
|
|
18
|
+
https://github.com/user-attachments/assets/a1f2eae2-13fb-4aae-98cf-a3fc1620a6c2
|
|
17
19
|
|
|
18
20
|
---
|
|
19
21
|
|
|
@@ -50,8 +52,8 @@ Fastest way to try PageAgent with our free Demo LLM:
|
|
|
50
52
|
|
|
51
53
|
| Mirrors | URL |
|
|
52
54
|
| ------- | ---------------------------------------------------------------------------------- |
|
|
53
|
-
| Global | https://cdn.jsdelivr.net/npm/page-agent@1.9.
|
|
54
|
-
| China | https://registry.npmmirror.com/page-agent/1.9.
|
|
55
|
+
| Global | https://cdn.jsdelivr.net/npm/page-agent@1.9.1/dist/iife/page-agent.demo.js |
|
|
56
|
+
| China | https://registry.npmmirror.com/page-agent/1.9.1/files/dist/iife/page-agent.demo.js |
|
|
55
57
|
|
|
56
58
|
Add `?autoInit=false` to load the script without creating the demo agent automatically. You can then instantiate it with `new window.PageAgent(...)`.
|
|
57
59
|
|
|
@@ -139,7 +139,6 @@ Strictly follow these rules while using the browser and navigating the web:
|
|
|
139
139
|
- You can scroll by a specific number of pages using the num_pages parameter (e.g., 0.5 for half page, 2.0 for two pages).
|
|
140
140
|
- All the elements that are scrollable are marked with \`data-scrollable\` attribute. Including the scrollable distance in every directions. You can scroll *the element* in case some area are overflowed.
|
|
141
141
|
- If a captcha appears, tell user you can not solve captcha. Finish the task and ask user to solve it.
|
|
142
|
-
- If expected elements are missing, try scrolling, or navigating back.
|
|
143
142
|
- If the page is not fully loaded, use the \`wait\` action.
|
|
144
143
|
- Do not repeat one action for more than 3 times unless some conditions changed.
|
|
145
144
|
- If you fill an input field and your action sequence is interrupted, most often something changed e.g. suggestions popped up under the field.
|
|
@@ -220,11 +219,11 @@ Here are examples of good output patterns. Use them as reference but never copy
|
|
|
220
219
|
}
|
|
221
220
|
}
|
|
222
221
|
</output>
|
|
223
|
-
`,log=console.log.bind(console,chalk.yellow(`[autoFixer]`));function normalizeResponse(e,t){let n,r=e.choices?.[0];if(!r)throw Error(`No choices in response`);let i=r.message;if(!i)throw Error(`No message in choice`);let a=i.tool_calls?.[0];if(a?.function?.arguments)n=safeJsonParse(a.function.arguments),a.function.name&&a.function.name!==`AgentOutput`&&(log(`#1: fixing tool_call`),n={action:safeJsonParse(n)});else if(i.content){let e=retrieveJsonFromString(i.content.trim());if(e)n=safeJsonParse(e),n?.name===`AgentOutput`&&(log(`#2: fixing tool_call`),n=safeJsonParse(n.arguments)),n?.type===`function`&&(log(`#3: fixing tool_call`),n=safeJsonParse(n.function.arguments)),!n?.action&&!n?.evaluation_previous_goal&&!n?.memory&&!n?.next_goal&&!n?.thinking&&(log(`#4: fixing tool_call`),n={action:safeJsonParse(n)});else throw Error(`No tool_call and the message content does not contain valid JSON`)}else throw Error(`No tool_call nor message content is present`);return n=safeJsonParse(n),n.action&&=safeJsonParse(n.action),n.action&&t&&(n.action=validateAction(n.action,t)),n.action||(log(`#5: fixing tool_call`),n.action={wait:{seconds:1}}),{...e,choices:[{...r,message:{...i,tool_calls:[{...a||{},function:{...a?.function||{},name:`AgentOutput`,arguments:JSON.stringify(n)}}]}}]}}function validateAction(e,t){if(typeof e!=`object`||!e)return e;let n=Object.keys(e)[0];if(!n)return e;let r=t.get(n);if(!r){let e=Array.from(t.keys()).join(`, `);throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Unknown action "${n}". Available: ${e}`)}let i=e[n],a=r.inputSchema;if(a instanceof ZodObject&&i!==null&&typeof i!=`object`){let e=Object.keys(a.shape).find(e=>!a.shape[e].safeParse(void 0).success);e&&(log(`coercing primitive action input for "${n}"`),i={[e]:i})}let o=a.safeParse(i);if(!o.success)throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Invalid input for action "${n}": ${prettifyError(o.error)}`);return{[n]:o.data}}function safeJsonParse(e){if(typeof e==`string`)try{return JSON.parse(e.trim())}catch{return e}return e}function retrieveJsonFromString(e){try{let t=/({[\s\S]*})/.exec(e)??[];return t.length===0?null:JSON.parse(t[0])}catch{return null}}async function waitFor$1(e,t){if(!t){await new Promise(t=>setTimeout(t,e*1e3));return}t.throwIfAborted(),await new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e*1e3),a=()=>{clearTimeout(i),r(t.reason)};t.addEventListener(`abort`,a,{once:!0})})}function truncate$1(e,t){return e.length>t?e.substring(0,t)+`...`:e}function randomID(e){let t=Math.random().toString(36).substring(2,11);if(!e)return t;let n=1e3,r=0;for(;e.includes(t);)if(t=Math.random().toString(36).substring(2,11),r++,r>1e3)throw Error(`randomID: too many tries`);return t}var _global=globalThis;_global.__PAGE_AGENT_IDS__||=[];var ids=_global.__PAGE_AGENT_IDS__;function uid(){let e=randomID(ids);return ids.push(e),e}var llmsTxtCache=new Map;async function fetchLlmsTxt(e){let t;try{t=new URL(e).origin}catch{return null}if(t===`null`)return null;if(llmsTxtCache.has(t))return llmsTxtCache.get(t);let n=`${t}/llms.txt`,r=null;try{console.log(chalk.gray(`[llms.txt] Fetching ${n}`));let e=await fetch(n,{signal:AbortSignal.timeout(3e3)});e.ok?(r=await e.text(),console.log(chalk.green(`[llms.txt] Found (${r.length} chars)`)),r.length>1e3&&(console.log(chalk.yellow(`[llms.txt] Truncating to 1000 chars`)),r=truncate$1(r,1e3))):console.debug(chalk.gray(`[llms.txt] ${e.status} for ${n}`))}catch(e){console.debug(chalk.gray(`[llms.txt] not found for ${n}`),e)}return llmsTxtCache.set(t,r),r}function assert(e,t,n){if(!e){let e=t??`Assertion failed`;throw n||console.error(chalk.red(`❌ assert: ${e}`)),Error(e)}}function tool(e){return e}var tools=new Map;tools.set(`done`,tool({description:`Complete task. Text is your final response to the user — keep it concise unless the user explicitly asks for detail.`,inputSchema:object({text:string(),success:boolean().default(!0)}),execute:async function(e){return Promise.resolve(`Task completed`)}})),tools.set(`wait`,tool({description:`Wait for x seconds. Can be used to wait until the page or data is fully loaded.`,inputSchema:object({seconds:number().min(1).max(10).default(1)}),execute:async function(e,{signal:t}){let n=await this.pageController.getLastUpdateTime(),r=Math.max(0,e.seconds-(Date.now()-n)/1e3);return console.log(`actualWaitTime: ${r} seconds`),await waitFor$1(r,t),`✅ Waited for ${e.seconds} seconds.`}})),tools.set(`ask_user`,tool({description:`Ask the user a question and wait for their answer. Use this if you need more information or clarification.`,inputSchema:object({question:string()}),execute:async function(e,{signal:t}){if(!this.onAskUser)throw Error(`ask_user tool requires onAskUser callback to be set`);return`User answered: ${await this.onAskUser(e.question,{signal:t})}`}})),tools.set(`click_element_by_index`,tool({description:`Click element by index`,inputSchema:object({index:int().min(0)}),execute:async function(e){return(await this.pageController.clickElement(e.index)).message}})),tools.set(`input_text`,tool({description:`Click and type text into an interactive input element`,inputSchema:object({index:int().min(0),text:string()}),execute:async function(e){return(await this.pageController.inputText(e.index,e.text)).message}})),tools.set(`select_dropdown_option`,tool({description:`Select dropdown option for interactive element index by the text of the option you want to select`,inputSchema:object({index:int().min(0),text:string()}),execute:async function(e){return(await this.pageController.selectOption(e.index,e.text)).message}})),tools.set(`scroll`,tool({description:`Scroll vertically. Without index: scrolls the document. With index: scrolls the container at that index (or its nearest scrollable ancestor). Use index of a data-scrollable element to scroll a specific area.`,inputSchema:object({down:boolean().default(!0),num_pages:number().min(0).max(10).optional().default(.1),pixels:number().int().min(0).optional(),index:number().int().min(0).optional()}),execute:async function(e){return(await this.pageController.scroll({...e,numPages:e.num_pages})).message}})),tools.set(`scroll_horizontally`,tool({description:`Scroll horizontally. Without index: scrolls the document. With index: scrolls the container at that index (or its nearest scrollable ancestor). Use index of a data-scrollable element to scroll a specific area.`,inputSchema:object({right:boolean().default(!0),pixels:number().int().min(0),index:number().int().min(0).optional()}),execute:async function(e){return(await this.pageController.scrollHorizontally(e)).message}})),tools.set(`execute_javascript`,tool({description:`Execute JavaScript code on the current page. Supports async/await syntax. Use with caution!`,inputSchema:object({script:string()}),execute:async function(e){return(await this.pageController.executeJavascript(e.script)).message}}));var PageAgentCore=class extends EventTarget{id=uid();config;tools;pageController;task=``;taskId=``;history=[];disposed=!1;onAskUser;#e=`idle`;#t;#n=new AbortController;#r=[];#i={totalWaitTime:0,lastURL:``,browserState:null};constructor(e){if(super(),this.config={...e,maxSteps:e.maxSteps??40},this.#t=new LLM(this.config),this.tools=new Map(tools),this.pageController=e.pageController,this.#t.addEventListener(`retry`,e=>{let{attempt:t,maxAttempts:n,lastError:r}=e.detail;this.#s({type:`retrying`,attempt:t,maxAttempts:n}),this.history.push({type:`error`,message:String(r),rawResponse:r.rawResponse}),this.history.push({type:`retry`,message:`LLM retry attempt ${t} of ${n}`,attempt:t,maxAttempts:n}),this.#o()}),this.config.customTools)for(let[e,t]of Object.entries(this.config.customTools)){if(t===null){this.tools.delete(e);continue}this.tools.set(e,t)}this.config.experimentalScriptExecutionTool||this.tools.delete(`execute_javascript`)}get status(){return this.#e}#a(){this.dispatchEvent(new Event(`statuschange`))}#o(){this.dispatchEvent(new Event(`historychange`))}#s(e){this.dispatchEvent(new CustomEvent(`activity`,{detail:e}))}#c(e){this.#e!==e&&(this.#e=e,this.#a())}pushObservation(e){this.#r.push(e)}stop(){this.pageController.cleanUpHighlights(),this.pageController.hideMask(),this.#n.abort()}async execute(e){if(this.disposed)throw Error(`PageAgent has been disposed. Create a new instance.`);if(this.#e===`running`)throw Error(`A task is already running.`);if(!e)throw Error(`Task is required`);this.task=e,this.taskId=uid(),this.history=[],this.#r=[],this.#i={totalWaitTime:0,lastURL:``,browserState:null},this.#n=new AbortController,this.#c(`running`),this.#o(),this.onAskUser||this.tools.delete(`ask_user`);let t=this.config.onBeforeStep,n=this.config.onAfterStep,r=this.config.onBeforeTask,i=this.config.onAfterTask;try{await r?.(this),await this.pageController.showMask()}catch(e){throw this.#c(`error`),e}let a=0,o,s;for(;;){try{console.group(`step: ${a}`),await t?.(this,a),console.log(chalk.blue.bold(`👀 Observing...`)),this.#i.browserState=await this.pageController.getBrowserState(),await this.#f(a);let e=[{role:`system`,content:this.#u()},{role:`user`,content:await this.#p()}],r={AgentOutput:this.#l()};console.log(chalk.blue.bold(`🧠 Thinking...`)),this.#s({type:`thinking`});let i=await this.#t.invoke(e,r,this.#n.signal,{toolChoiceName:`AgentOutput`,normalizeResponse:e=>normalizeResponse(e,this.tools)}),c=i.toolResult,l=c.input,u=c.output,d={evaluation_previous_goal:l.evaluation_previous_goal,memory:l.memory,next_goal:l.next_goal},f=Object.keys(l.action)[0],p={name:f,input:l.action[f],output:u};if(this.history.push({type:`step`,stepIndex:a,reflection:d,action:p,usage:i.usage,rawResponse:i.rawResponse,rawRequest:i.rawRequest}),this.#o(),await n?.(this,this.history),console.groupEnd(),f===`done`){o=p.input?.success??!1,s=p.input?.text||`no text provided`,console.log(chalk.green.bold(`Task completed`),o,s);break}}catch(e){console.groupEnd();let t=e?.name===`AbortError`;t||console.error(`Task failed`,e),s=t?`Task aborted`:String(e),o=!1,this.#s({type:`error`,message:s}),this.history.push({type:`error`,message:s,rawResponse:e}),this.#o();break}if(a++,a>this.config.maxSteps){s=`Step count exceeded maximum limit`,o=!1,this.#s({type:`error`,message:s}),this.history.push({type:`error`,message:s}),this.#o();break}await waitFor$1(this.config.stepDelay??.4)}this.#m(o);let c={success:o,data:s,history:this.history};return await i?.(this,c),c}#l(){let e=this.tools,t=union(Array.from(e.entries()).map(([e,t])=>object({[e]:t.inputSchema}).describe(t.description)));return{description:`You MUST call this tool every step!`,inputSchema:object({evaluation_previous_goal:string().optional(),memory:string().optional(),next_goal:string().optional(),action:t}),execute:async t=>{let n=this.#n.signal;n.throwIfAborted(),console.log(chalk.blue.bold(`MacroTool input`),t);let r=t.action,i=Object.keys(r)[0],a=r[i],o=[];t.evaluation_previous_goal&&o.push(`✅: ${t.evaluation_previous_goal}`),t.memory&&o.push(`💾: ${t.memory}`),t.next_goal&&o.push(`🎯: ${t.next_goal}`);let s=o.length>0?o.join(`
|
|
224
|
-
`):``;s&&console.log(s);let c=e.get(i);assert(c,`Tool ${i} not found`),console.log(chalk.blue.bold(`Executing tool: ${i}`),a),this.#
|
|
222
|
+
`,log=console.log.bind(console,chalk.yellow(`[autoFixer]`));function normalizeResponse(e,t){let n,r=e.choices?.[0];if(!r)throw Error(`No choices in response`);let i=r.message;if(!i)throw Error(`No message in choice`);let a=i.tool_calls?.[0];if(a?.function?.arguments)n=safeJsonParse(a.function.arguments),a.function.name&&a.function.name!==`AgentOutput`&&(log(`#1: fixing tool_call`),n={action:safeJsonParse(n)});else if(i.content){let e=retrieveJsonFromString(i.content.trim());if(e)n=safeJsonParse(e),n?.name===`AgentOutput`&&(log(`#2: fixing tool_call`),n=safeJsonParse(n.arguments)),n?.type===`function`&&(log(`#3: fixing tool_call`),n=safeJsonParse(n.function.arguments)),!n?.action&&!n?.evaluation_previous_goal&&!n?.memory&&!n?.next_goal&&!n?.thinking&&(log(`#4: fixing tool_call`),n={action:safeJsonParse(n)});else throw Error(`No tool_call and the message content does not contain valid JSON`)}else throw Error(`No tool_call nor message content is present`);return n=safeJsonParse(n),n.action&&=safeJsonParse(n.action),n.action&&t&&(n.action=validateAction(n.action,t)),n.action||(log(`#5: fixing tool_call`),n.action={wait:{seconds:1}}),{...e,choices:[{...r,message:{...i,tool_calls:[{...a||{},function:{...a?.function||{},name:`AgentOutput`,arguments:JSON.stringify(n)}}]}}]}}function validateAction(e,t){if(typeof e!=`object`||!e)return e;let n=Object.keys(e)[0];if(!n)return e;let r=t.get(n);if(!r){let e=Array.from(t.keys()).join(`, `);throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Unknown action "${n}". Available: ${e}`)}let i=e[n],a=r.inputSchema;if(a instanceof ZodObject&&i!==null&&typeof i!=`object`){let e=Object.keys(a.shape).find(e=>!a.shape[e].safeParse(void 0).success);e&&(log(`coercing primitive action input for "${n}"`),i={[e]:i})}let o=a.safeParse(i);if(!o.success)throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Invalid input for action "${n}": ${prettifyError(o.error)}`);return{[n]:o.data}}function safeJsonParse(e){if(typeof e==`string`)try{return JSON.parse(e.trim())}catch{return e}return e}function retrieveJsonFromString(e){try{let t=/({[\s\S]*})/.exec(e)??[];return t.length===0?null:JSON.parse(t[0])}catch{return null}}async function waitFor$1(e,t){if(!t){await new Promise(t=>setTimeout(t,e*1e3));return}t.throwIfAborted(),await new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e*1e3),a=()=>{clearTimeout(i),r(t.reason)};t.addEventListener(`abort`,a,{once:!0})})}function truncate$1(e,t){return e.length>t?e.substring(0,t)+`...`:e}function randomID(e){let t=Math.random().toString(36).substring(2,11);if(!e)return t;let n=1e3,r=0;for(;e.includes(t);)if(t=Math.random().toString(36).substring(2,11),r++,r>1e3)throw Error(`randomID: too many tries`);return t}var _global=globalThis;_global.__PAGE_AGENT_IDS__||=[];var ids=_global.__PAGE_AGENT_IDS__;function uid(){let e=randomID(ids);return ids.push(e),e}var llmsTxtCache=new Map;async function fetchLlmsTxt(e){let t;try{t=new URL(e).origin}catch{return null}if(t===`null`)return null;if(llmsTxtCache.has(t))return llmsTxtCache.get(t);let n=`${t}/llms.txt`,r=null;try{console.log(chalk.gray(`[llms.txt] Fetching ${n}`));let e=await fetch(n,{signal:AbortSignal.timeout(3e3)});e.ok?(r=await e.text(),console.log(chalk.green(`[llms.txt] Found (${r.length} chars)`)),r.length>1e3&&(console.log(chalk.yellow(`[llms.txt] Truncating to 1000 chars`)),r=truncate$1(r,1e3))):console.debug(chalk.gray(`[llms.txt] ${e.status} for ${n}`))}catch(e){console.debug(chalk.gray(`[llms.txt] not found for ${n}`),e)}return llmsTxtCache.set(t,r),r}function assert(e,t,n){if(!e){let e=t??`Assertion failed`;throw n||console.error(chalk.red(`❌ assert: ${e}`)),Error(e)}}async function suppress(e){try{return await e()}catch(e){console.error(e);return}}function tool(e){return e}var tools=new Map;tools.set(`done`,tool({description:`Complete task. Text is your final response to the user — keep it concise unless the user explicitly asks for detail.`,inputSchema:object({text:string(),success:boolean().default(!0)}),execute:async function(e){return Promise.resolve(`Task completed`)}})),tools.set(`wait`,tool({description:`Wait for x seconds. Can be used to wait until the page or data is fully loaded.`,inputSchema:object({seconds:number().min(1).max(10).default(1)}),execute:async function(e,{signal:t}){let n=await this.pageController.getLastUpdateTime(),r=(Date.now()-n)/1e3,i=Math.max(0,e.seconds-r);return console.log(`actualWaitTime: ${i} seconds`),await waitFor$1(i,t),`✅ Waited for ${(r+i).toFixed(2)} seconds.`}})),tools.set(`ask_user`,tool({description:`Ask the user a question and wait for their answer. Use this if you need more information or clarification.`,inputSchema:object({question:string()}),execute:async function(e,{signal:t}){if(!this.onAskUser)throw Error(`ask_user tool requires onAskUser callback to be set`);return`User answered: ${await this.onAskUser(e.question,{signal:t})}`}})),tools.set(`click_element_by_index`,tool({description:`Click element by index`,inputSchema:object({index:int().min(0)}),execute:async function(e){return(await this.pageController.clickElement(e.index)).message}})),tools.set(`input_text`,tool({description:`Click and type text into an interactive input element`,inputSchema:object({index:int().min(0),text:string()}),execute:async function(e){return(await this.pageController.inputText(e.index,e.text)).message}})),tools.set(`select_dropdown_option`,tool({description:`Select dropdown option for interactive element index by the text of the option you want to select`,inputSchema:object({index:int().min(0),text:string()}),execute:async function(e){return(await this.pageController.selectOption(e.index,e.text)).message}})),tools.set(`scroll`,tool({description:`Scroll vertically. Without index: scrolls the document. With index: scrolls the container at that index (or its nearest scrollable ancestor). Use index of a data-scrollable element to scroll a specific area.`,inputSchema:object({down:boolean().default(!0),num_pages:number().min(0).max(10).optional().default(.1),pixels:number().int().min(0).optional(),index:number().int().min(0).optional()}),execute:async function(e){return(await this.pageController.scroll({...e,numPages:e.num_pages})).message}})),tools.set(`scroll_horizontally`,tool({description:`Scroll horizontally. Without index: scrolls the document. With index: scrolls the container at that index (or its nearest scrollable ancestor). Use index of a data-scrollable element to scroll a specific area.`,inputSchema:object({right:boolean().default(!0),pixels:number().int().min(0),index:number().int().min(0).optional()}),execute:async function(e){return(await this.pageController.scrollHorizontally(e)).message}})),tools.set(`execute_javascript`,tool({description:"Execute JavaScript code on the current page. Supports async/await syntax. Use with caution! An `AbortSignal` named `signal` is available in scope: long-running async code MUST honor it (e.g. `await fetch(url, { signal })`, or `signal.throwIfAborted()` in loops)",inputSchema:object({script:string()}),execute:async function(e,{signal:t}){let n=await this.pageController.executeJavascript(e.script,t);return t.throwIfAborted(),n.message}}));var PageAgentCore=class extends EventTarget{id=uid();config;tools;pageController;task=``;taskId=``;history=[];disposed=!1;onAskUser;#e=`idle`;#t;#n=new AbortController;#r=[];#i=Promise.resolve();#a=null;#o={totalWaitTime:0,lastURL:``,browserState:null};constructor(e){if(super(),this.config={...e,maxSteps:e.maxSteps??40},this.#t=new LLM(this.config),this.tools=new Map(tools),this.pageController=e.pageController,this.#t.addEventListener(`retry`,e=>{let{attempt:t,maxAttempts:n,lastError:r}=e.detail;this.#l({type:`retrying`,attempt:t,maxAttempts:n}),this.history.push({type:`error`,message:String(r),rawResponse:r.rawResponse}),this.history.push({type:`retry`,message:`LLM retry attempt ${t} of ${n}`,attempt:t,maxAttempts:n}),this.#c()}),this.config.customTools)for(let[e,t]of Object.entries(this.config.customTools)){if(t===null){this.tools.delete(e);continue}this.tools.set(e,t)}this.config.experimentalScriptExecutionTool||this.tools.delete(`execute_javascript`)}get status(){return this.#e}get lastResult(){return this.#a}#s(){this.dispatchEvent(new Event(`statuschange`))}#c(e){e&&this.history.push(e),this.dispatchEvent(new Event(`historychange`))}#l(e){this.dispatchEvent(new CustomEvent(`activity`,{detail:e}))}#u(e){this.#e!==e&&(this.#e=e,this.#s())}pushObservation(e){this.#r.push(e)}async stop(){this.#e===`running`&&(this.#n.abort(),await this.#i)}async execute(e){if(this.disposed)throw Error(`PageAgent has been disposed. Create a new instance.`);if(this.#e===`running`)throw Error(`A task is already running.`);if(!e)throw Error(`Task is required`);this.task=e,this.taskId=uid(),this.history=[],this.#r=[],this.#o={totalWaitTime:0,lastURL:``,browserState:null},this.#n=new AbortController;let t=this.#n.signal,n;this.#i=new Promise(e=>n=e),this.#u(`running`),this.#c(),this.onAskUser||this.tools.delete(`ask_user`);let r=this.config.onBeforeStep,i=this.config.onAfterStep,a=this.config.onBeforeTask,o=this.config.onAfterTask,s=this.config.stepDelay??.4,c=this.config.maxSteps,l=0,u,d=`error`;await suppress(()=>this.pageController.showMask());try{for(await a?.(this);;){await r?.(this,l);try{console.group(`step: ${l}`),l>0&&await waitFor$1(s,t),t.throwIfAborted(),console.log(chalk.blue.bold(`👀 Observing...`)),this.#o.browserState=await this.pageController.getBrowserState(),await this.#m(l);let e=[{role:`system`,content:this.#f()},{role:`user`,content:await this.#h()}],n={AgentOutput:this.#d()};console.log(chalk.blue.bold(`🧠 Thinking...`)),this.#l({type:`thinking`});let r=await this.#t.invoke(e,n,t,{toolChoiceName:`AgentOutput`,normalizeResponse:e=>normalizeResponse(e,this.tools)}),i=r.toolResult,a=i.input,o=i.output,c={evaluation_previous_goal:a.evaluation_previous_goal,memory:a.memory,next_goal:a.next_goal},f=Object.keys(a.action)[0],p={name:f,input:a.action[f],output:o};if(this.#c({type:`step`,stepIndex:l,reflection:c,action:p,usage:r.usage,rawResponse:r.rawResponse,rawRequest:r.rawRequest}),f===`done`){let e=p.input?.success??!1,t=p.input?.text||`no text provided`;console.log(chalk.green.bold(`Task completed`),e,t),u={success:e,data:t,history:this.history},this.#a=u,d=`completed`;break}}catch(e){let t=e?.name===`AbortError`;t||console.error(`Task failed`,e);let n=t?`Task aborted`:String(e);this.#l({type:`error`,message:n}),this.#c({type:`error`,message:n,rawResponse:e}),u={success:!1,data:n,history:this.history},this.#a=u,d=t?`stopped`:`error`;break}finally{console.groupEnd(),await i?.(this,this.history)}if(l++,l>c){let e=`Step count exceeded maximum limit`;console.error(e),this.#l({type:`error`,message:e}),this.#c({type:`error`,message:e}),u={success:!1,data:e,history:this.history},this.#a=u,d=`error`;break}}return await o?.(this,u),u}catch(e){throw this.#l({type:`error`,message:String(e)}),d=`error`,e}finally{await suppress(()=>this.pageController.cleanUpHighlights()),await suppress(()=>this.pageController.hideMask()),this.#n.abort(),n(),this.#u(d)}}#d(){let e=this.tools,t=union(Array.from(e.entries()).map(([e,t])=>object({[e]:t.inputSchema}).describe(t.description)));return{description:`You MUST call this tool every step!`,inputSchema:object({evaluation_previous_goal:string().optional(),memory:string().optional(),next_goal:string().optional(),action:t}),execute:async t=>{let n=this.#n.signal;n.throwIfAborted(),console.log(chalk.blue.bold(`MacroTool input`),t);let r=t.action,i=Object.keys(r)[0],a=r[i],o=[];t.evaluation_previous_goal&&o.push(`✅: ${t.evaluation_previous_goal}`),t.memory&&o.push(`💾: ${t.memory}`),t.next_goal&&o.push(`🎯: ${t.next_goal}`);let s=o.length>0?o.join(`
|
|
223
|
+
`):``;s&&console.log(s);let c=e.get(i);assert(c,`Tool ${i} not found`),console.log(chalk.blue.bold(`Executing tool: ${i}`),a),this.#l({type:`executing`,tool:i,input:a});let l=Date.now(),u=await c.execute.bind(this)(a,{signal:n});n.throwIfAborted();let d=Date.now()-l;return console.log(chalk.green.bold(`Tool (${i}) executed for ${d}ms`),u),this.#l({type:`executed`,tool:i,input:a,output:u,duration:d}),i===`wait`?this.#o.totalWaitTime+=a?.seconds||0:this.#o.totalWaitTime=0,{input:t,output:u}}}}#f(){if(this.config.customSystemPrompt)return this.config.customSystemPrompt;let e=this.config.language===`zh-CN`?`中文`:`English`;return system_prompt_default.replace(/Default working language: \*\*.*?\*\*/,`Default working language: **${e}**`)}async#p(){let{instructions:e,experimentalLlmsTxt:t}=this.config,n=e?.system?.trim(),r,i=this.#o.browserState?.url||``;if(e?.getPageInstructions&&i)try{r=e.getPageInstructions(i)?.trim()}catch(e){console.error(chalk.red(`[PageAgent] Failed to execute getPageInstructions callback:`),e)}let a=t&&i?await fetchLlmsTxt(i):void 0;if(!n&&!r&&!a)return``;let o=`<instructions>
|
|
225
224
|
`;return n&&(o+=`<system_instructions>\n${n}\n</system_instructions>\n`),r&&(o+=`<page_instructions>\n${r}\n</page_instructions>\n`),a&&(o+=`<llms_txt>\n${a}\n</llms_txt>\n`),o+=`</instructions>
|
|
226
225
|
|
|
227
|
-
`,o}async#
|
|
226
|
+
`,o}async#m(e){this.#o.totalWaitTime>=3&&this.pushObservation(`You have waited ${this.#o.totalWaitTime} seconds accumulatively. DO NOT wait any longer unless you have a good reason.`);let t=this.#o.browserState?.url||``;t!==this.#o.lastURL&&(this.pushObservation(`Page navigated to → ${t}`),this.#o.lastURL=t,await waitFor$1(.5));let n=this.config.maxSteps-e;if(n===5?this.pushObservation(`⚠️ Only ${n} steps remaining. Consider wrapping up or calling done with partial results.`):n===2&&this.pushObservation(`⚠️ Critical: Only ${n} steps left! You must finish the task or call done immediately.`),this.#r.length>0){for(let e of this.#r)this.history.push({type:`observation`,content:e}),console.log(chalk.cyan(`Observation:`),e);this.#r=[],this.#c()}}async#h(){let e=this.#o.browserState,t=``;t+=await this.#p();let n=this.history.filter(e=>e.type===`step`).length;t+=`<agent_state>
|
|
228
227
|
`,t+=`<user_request>
|
|
229
228
|
`,t+=`${this.task}\n`,t+=`</user_request>
|
|
230
229
|
`,t+=`<step_info>
|
|
@@ -242,7 +241,7 @@ Here are examples of good output patterns. Use them as reference but never copy
|
|
|
242
241
|
|
|
243
242
|
`,t+=`</browser_state>
|
|
244
243
|
|
|
245
|
-
`,t}#m(e=!0){this.pageController.cleanUpHighlights(),this.pageController.hideMask(),this.#c(e?`completed`:`error`),this.#n.abort()}dispose(){console.log(`Disposing PageAgent...`),this.disposed=!0,this.pageController.dispose(),this.#n.abort(),this.dispatchEvent(new Event(`dispose`)),this.config.onDispose?.(this)}};function isHTMLElement(e){return!!e&&e.nodeType===1}function isInputElement(e){return e?.nodeType===1&&e.tagName===`INPUT`}function isTextAreaElement(e){return e?.nodeType===1&&e.tagName===`TEXTAREA`}function isSelectElement(e){return e?.nodeType===1&&e.tagName===`SELECT`}function isAnchorElement(e){return e?.nodeType===1&&e.tagName===`A`}function getIframeOffset(e){let t=e.ownerDocument.defaultView?.frameElement;if(!t)return{x:0,y:0};let n=t.getBoundingClientRect();return{x:n.left,y:n.top}}function getNativeValueSetter(e){return Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),`value`).set}async function waitFor(e){await new Promise(t=>setTimeout(t,e*1e3))}async function movePointerToElement(e,t,n){let r=getIframeOffset(e);window.dispatchEvent(new CustomEvent(`PageAgent::MovePointerTo`,{detail:{x:t+r.x,y:n+r.y}})),await waitFor(.3)}async function clickPointer(){window.dispatchEvent(new CustomEvent(`PageAgent::ClickPointer`))}async function enablePassThrough(){window.dispatchEvent(new CustomEvent(`PageAgent::EnablePassThrough`))}async function disablePassThrough(){window.dispatchEvent(new CustomEvent(`PageAgent::DisablePassThrough`))}function getElementByIndex(e,t){let n=e.get(t);if(!n)throw Error(`No interactive element found at index ${t}`);let r=n.ref;if(!r)throw Error(`Element at index ${t} does not have a reference`);if(!isHTMLElement(r))throw Error(`Element at index ${t} is not an HTMLElement`);return r}var lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&=(lastClickedElement.dispatchEvent(new PointerEvent(`pointerout`,{bubbles:!0})),lastClickedElement.dispatchEvent(new PointerEvent(`pointerleave`,{bubbles:!1})),lastClickedElement.dispatchEvent(new MouseEvent(`mouseout`,{bubbles:!0})),lastClickedElement.dispatchEvent(new MouseEvent(`mouseleave`,{bubbles:!1})),lastClickedElement.blur(),null)}async function clickElement(e){blurLastClickedElement(),lastClickedElement=e,await scrollIntoViewIfNeeded(e);let t=e.ownerDocument.defaultView?.frameElement;t&&await scrollIntoViewIfNeeded(t);let n=e.getBoundingClientRect(),r=n.left+n.width/2,i=n.top+n.height/2;await movePointerToElement(e,r,i),await clickPointer(),await waitFor(.1);let a=e.ownerDocument;await enablePassThrough();let o=a.elementFromPoint(r,i);await disablePassThrough();let s=o instanceof HTMLElement&&e.contains(o)?o:e,c={bubbles:!0,cancelable:!0,clientX:r,clientY:i,pointerType:`mouse`},l={bubbles:!0,cancelable:!0,clientX:r,clientY:i,button:0};s.dispatchEvent(new PointerEvent(`pointerover`,c)),s.dispatchEvent(new PointerEvent(`pointerenter`,{...c,bubbles:!1})),s.dispatchEvent(new MouseEvent(`mouseover`,l)),s.dispatchEvent(new MouseEvent(`mouseenter`,{...l,bubbles:!1})),s.dispatchEvent(new PointerEvent(`pointerdown`,c)),s.dispatchEvent(new MouseEvent(`mousedown`,l)),e.focus({preventScroll:!0}),s.dispatchEvent(new PointerEvent(`pointerup`,c)),s.dispatchEvent(new MouseEvent(`mouseup`,l)),s.click(),await waitFor(.2)}async function inputTextElement(e,t){let n=e.isContentEditable;if(!isInputElement(e)&&!isTextAreaElement(e)&&!n)throw Error(`Element is not an input, textarea, or contenteditable`);if(await clickElement(e),n){if(e.dispatchEvent(new InputEvent(`beforeinput`,{bubbles:!0,cancelable:!0,inputType:`deleteContent`}))&&(e.innerText=``,e.dispatchEvent(new InputEvent(`input`,{bubbles:!0,inputType:`deleteContent`}))),e.dispatchEvent(new InputEvent(`beforeinput`,{bubbles:!0,cancelable:!0,inputType:`insertText`,data:t}))&&(e.innerText=t,e.dispatchEvent(new InputEvent(`input`,{bubbles:!0,inputType:`insertText`,data:t}))),e.innerText.trim()!==t.trim()){e.focus();let n=e.ownerDocument,r=(n.defaultView||window).getSelection(),i=n.createRange();i.selectNodeContents(e),r?.removeAllRanges(),r?.addRange(i),n.execCommand(`delete`,!1),n.execCommand(`insertText`,!1,t)}e.dispatchEvent(new Event(`change`,{bubbles:!0})),e.blur()}else getNativeValueSetter(e).call(e,t);n||e.dispatchEvent(new Event(`input`,{bubbles:!0})),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(e,t){if(!isSelectElement(e))throw Error(`Element is not a select element`);let n=Array.from(e.options).find(e=>e.textContent?.trim()===t.trim());if(!n)throw Error(`Option with text "${t}" not found in select element`);e.value=n.value,e.dispatchEvent(new Event(`change`,{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(e){let t=e;typeof t.scrollIntoViewIfNeeded==`function`?t.scrollIntoViewIfNeeded():e.scrollIntoView({behavior:`auto`,block:`center`,inline:`nearest`})}async function scrollVertically(e,t){if(t){let n=t,r=n,i=!1,a=null,o=0,s=0,c=e;for(;r&&s<10;){let e=window.getComputedStyle(r),t=/(auto|scroll|overlay)/.test(e.overflowY)||e.scrollbarWidth&&e.scrollbarWidth!==`auto`||e.scrollbarGutter&&e.scrollbarGutter!==`auto`,n=r.scrollHeight>r.clientHeight;if(t&&n){let e=r.scrollTop,t=r.scrollHeight-r.clientHeight,n=c/3;n=n>0?Math.min(n,t-e):Math.max(n,-e),r.scrollTop=e+n;let s=r.scrollTop-e;if(Math.abs(s)>.5){i=!0,a=r,o=s;break}}if(r===document.body||r===document.documentElement)break;r=r.parentElement,s++}return i?`Scrolled container (${a?.tagName}) by ${o}px`:`No scrollable container found for element (${n.tagName})`}let n=e,r=e=>e.clientHeight>=window.innerHeight*.5,i=e=>e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowY)&&e.scrollHeight>e.clientHeight&&r(e),a=document.activeElement;for(;a&&!i(a)&&a!==document.body;)a=a.parentElement;if(a=i(a)?a:Array.from(document.querySelectorAll(`*`)).find(i)||document.scrollingElement||document.documentElement,a===document.scrollingElement||a===document.documentElement||a===document.body){let e=window.scrollY,t=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,n);let r=window.scrollY,i=r-e;return Math.abs(i)<1?n>0?`⚠️ Already at the bottom of the page, cannot scroll down further.`:`⚠️ Already at the top of the page, cannot scroll up further.`:n>0&&r>=t-1?`✅ Scrolled page by ${i}px. Reached the bottom of the page.`:n<0&&r<=1?`✅ Scrolled page by ${i}px. Reached the top of the page.`:`✅ Scrolled page by ${i}px.`}else{let e=`The document is not scrollable. Falling back to container scroll.`;console.log(`[PageController] ${e}`);let t=a.scrollTop,r=a.scrollHeight-a.clientHeight;a.scrollBy({top:n,behavior:`smooth`}),await waitFor(.1);let i=a.scrollTop,o=i-t;return Math.abs(o)<1?n>0?`⚠️ ${e} Already at the bottom of container (${a.tagName}), cannot scroll down further.`:`⚠️ ${e} Already at the top of container (${a.tagName}), cannot scroll up further.`:n>0&&i>=r-1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the bottom.`:n<0&&i<=1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the top.`:`✅ ${e} Scrolled container (${a.tagName}) by ${o}px.`}}async function scrollHorizontally(e,t){if(t){let n=t,r=n,i=!1,a=null,o=0,s=0,c=e;for(;r&&s<10;){let e=window.getComputedStyle(r),t=/(auto|scroll|overlay)/.test(e.overflowX)||e.scrollbarWidth&&e.scrollbarWidth!==`auto`||e.scrollbarGutter&&e.scrollbarGutter!==`auto`,n=r.scrollWidth>r.clientWidth;if(t&&n){let e=r.scrollLeft,t=r.scrollWidth-r.clientWidth,n=c/3;n=n>0?Math.min(n,t-e):Math.max(n,-e),r.scrollLeft=e+n;let s=r.scrollLeft-e;if(Math.abs(s)>.5){i=!0,a=r,o=s;break}}if(r===document.body||r===document.documentElement)break;r=r.parentElement,s++}return i?`Scrolled container (${a?.tagName}) horizontally by ${o}px`:`No horizontally scrollable container found for element (${n.tagName})`}let n=e,r=e=>e.clientWidth>=window.innerWidth*.5,i=e=>e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowX)&&e.scrollWidth>e.clientWidth&&r(e),a=document.activeElement;for(;a&&!i(a)&&a!==document.body;)a=a.parentElement;if(a=i(a)?a:Array.from(document.querySelectorAll(`*`)).find(i)||document.scrollingElement||document.documentElement,a===document.scrollingElement||a===document.documentElement||a===document.body){let e=window.scrollX,t=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(n,0);let r=window.scrollX,i=r-e;return Math.abs(i)<1?n>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.`:n>0&&r>=t-1?`✅ Scrolled page by ${i}px. Reached the right edge of the page.`:n<0&&r<=1?`✅ Scrolled page by ${i}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${i}px.`}else{let e=`The document is not scrollable. Falling back to container scroll.`;console.log(`[PageController] ${e}`);let t=a.scrollLeft,r=a.scrollWidth-a.clientWidth;a.scrollBy({left:n,behavior:`smooth`}),await waitFor(.1);let i=a.scrollLeft,o=i-t;return Math.abs(o)<1?n>0?`⚠️ ${e} Already at the right edge of container (${a.tagName}), cannot scroll right further.`:`⚠️ ${e} Already at the left edge of container (${a.tagName}), cannot scroll left further.`:n>0&&i>=r-1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the right edge.`:n<0&&i<=1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the left edge.`:`✅ ${e} Scrolled container (${a.tagName}) horizontally by ${o}px.`}}var dom_tree_default=(e={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{let{interactiveBlacklist:t,interactiveWhitelist:n,highlightOpacity:r,highlightLabelOpacity:i}=e,{doHighlightElements:a,focusHighlightIndex:o,viewportExpansion:s,debugMode:c}=e,l=0,u=new WeakMap;function d(e,t){!e||e.nodeType!==Node.ELEMENT_NODE||u.set(e,{...u.get(e),...t})}let f={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{f.boundingRects=new WeakMap,f.clientRects=new WeakMap,f.computedStyles=new WeakMap}};function p(e){if(!e)return null;if(f.boundingRects.has(e))return f.boundingRects.get(e);let t=e.getBoundingClientRect();return t&&f.boundingRects.set(e,t),t}function m(e){if(!e)return null;if(f.computedStyles.has(e))return f.computedStyles.get(e);let t=window.getComputedStyle(e);return t&&f.computedStyles.set(e,t),t}function h(e){if(!e)return null;if(f.clientRects.has(e))return f.clientRects.get(e);let t=e.getClientRects();return t&&f.clientRects.set(e,t),t}let g={},_={current:0},v=`playwright-highlight-container`;function y(e,t,n=null){if(!e)return t;let a=[],o=null,s=20,c=16,l=null;try{let u=document.getElementById(v);u||(u=document.createElement(`div`),u.id=v,u.style.position=`fixed`,u.style.pointerEvents=`none`,u.style.top=`0`,u.style.left=`0`,u.style.width=`100%`,u.style.height=`100%`,u.style.zIndex=`2147483640`,u.style.backgroundColor=`transparent`,document.body.appendChild(u));let d=e.getClientRects();if(!d||d.length===0)return t;let f=[`#FF0000`,`#00FF00`,`#0000FF`,`#FFA500`,`#800080`,`#008080`,`#FF69B4`,`#4B0082`,`#FF4500`,`#2E8B57`,`#DC143C`,`#4682B4`],p=f[t%f.length],m=p+Math.floor(r*255).toString(16).padStart(2,`0`);p+=Math.floor(i*255).toString(16).padStart(2,`0`);let h={x:0,y:0};if(n){let e=n.getBoundingClientRect();h.x=e.left,h.y=e.top}let g=document.createDocumentFragment();for(let e of d){if(e.width===0||e.height===0)continue;let t=document.createElement(`div`);t.style.position=`fixed`,t.style.border=`2px solid ${p}`,t.style.backgroundColor=m,t.style.pointerEvents=`none`,t.style.boxSizing=`border-box`;let n=e.top+h.y,r=e.left+h.x;t.style.top=`${n}px`,t.style.left=`${r}px`,t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,g.appendChild(t),a.push({element:t,initialRect:e})}let _=d[0];o=document.createElement(`div`),o.className=`playwright-highlight-label`,o.style.position=`fixed`,o.style.background=p,o.style.color=`white`,o.style.padding=`1px 4px`,o.style.borderRadius=`4px`,o.style.fontSize=`${Math.min(12,Math.max(8,_.height/2))}px`,o.textContent=t.toString(),s=o.offsetWidth>0?o.offsetWidth:s,c=o.offsetHeight>0?o.offsetHeight:c;let y=_.top+h.y,b=_.left+h.x,x=y+2,S=b+_.width-s-2;(_.width<s+4||_.height<c+4)&&(x=y-c-2,S=b+_.width-s,S<h.x&&(S=b)),x=Math.max(0,Math.min(x,window.innerHeight-c)),S=Math.max(0,Math.min(S,window.innerWidth-s)),o.style.top=`${x}px`,o.style.left=`${S}px`,g.appendChild(o);let C=((e,t)=>{let n=0;return(...r)=>{let i=performance.now();if(!(i-n<t))return n=i,e(...r)}})(()=>{let t=e.getClientRects(),r={x:0,y:0};if(n){let e=n.getBoundingClientRect();r.x=e.left,r.y=e.top}if(a.forEach((e,n)=>{if(n<t.length){let i=t[n],a=i.top+r.y,o=i.left+r.x;e.element.style.top=`${a}px`,e.element.style.left=`${o}px`,e.element.style.width=`${i.width}px`,e.element.style.height=`${i.height}px`,e.element.style.display=i.width===0||i.height===0?`none`:`block`}else e.element.style.display=`none`}),t.length<a.length)for(let e=t.length;e<a.length;e++)a[e].element.style.display=`none`;if(o&&t.length>0){let e=t[0],n=e.top+r.y,i=e.left+r.x,a=n+2,l=i+e.width-s-2;(e.width<s+4||e.height<c+4)&&(a=n-c-2,l=i+e.width-s,l<r.x&&(l=i)),a=Math.max(0,Math.min(a,window.innerHeight-c)),l=Math.max(0,Math.min(l,window.innerWidth-s)),o.style.top=`${a}px`,o.style.left=`${l}px`,o.style.display=`block`}else o&&(o.style.display=`none`)},16);return window.addEventListener(`scroll`,C,!0),window.addEventListener(`resize`,C),l=()=>{window.removeEventListener(`scroll`,C,!0),window.removeEventListener(`resize`,C),a.forEach(e=>e.element.remove()),o&&o.remove()},u.appendChild(g),t+1}finally{l&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(l)}}function b(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return null;let t=m(e);if(!t)return null;let n=t.display;if(n===`inline`||n===`inline-block`)return null;let r=t.overflowX,i=t.overflowY,a=t.scrollbarWidth&&t.scrollbarWidth!==`auto`||t.scrollbarGutter&&t.scrollbarGutter!==`auto`,o=r===`auto`||r===`scroll`,s=i===`auto`||i===`scroll`;if(!o&&!s&&!a)return null;let c=e.scrollWidth-e.clientWidth,l=e.scrollHeight-e.clientHeight,u=4;if(c<4&&l<4||!s&&!a&&c<4||!o&&!a&&l<4)return null;let f=e.scrollTop,p=e.scrollLeft,h={top:f,right:e.scrollWidth-e.clientWidth-e.scrollLeft,bottom:e.scrollHeight-e.clientHeight-e.scrollTop,left:p};return d(e,{scrollable:!0,scrollData:h}),console.log(`scrollData!!!`,h),h}function x(e){try{if(s===-1){let t=e.parentElement;if(!t)return!1;try{return t.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{let e=window.getComputedStyle(t);return e.display!==`none`&&e.visibility!==`hidden`&&e.opacity!==`0`}}let t=document.createRange();t.selectNodeContents(e);let n=t.getClientRects();if(!n||n.length===0)return!1;let r=!1,i=!1;for(let e of n)if(e.width>0&&e.height>0&&(r=!0,!(e.bottom<-s||e.top>window.innerHeight+s||e.right<-s||e.left>window.innerWidth+s))){i=!0;break}if(!r||!i)return!1;let a=e.parentElement;if(!a)return!1;try{return a.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{let e=window.getComputedStyle(a);return e.display!==`none`&&e.visibility!==`hidden`&&e.opacity!==`0`}}catch(e){return console.warn(`Error checking text node visibility:`,e),!1}}function S(e){if(!e||!e.tagName)return!1;let t=new Set([`body`,`div`,`main`,`article`,`section`,`nav`,`header`,`footer`]),n=e.tagName.toLowerCase();return t.has(n)?!0:!new Set([`svg`,`script`,`style`,`link`,`meta`,`noscript`,`template`]).has(n)}function C(e){let t=m(e);return e.offsetWidth>0&&e.offsetHeight>0&&t?.visibility!==`hidden`&&t?.display!==`none`}function w(e){if(!e||e.nodeType!==Node.ELEMENT_NODE||t.includes(e))return!1;if(n.includes(e))return!0;let r=e.tagName.toLowerCase(),i=m(e),a=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`.split(`.`)),o=new Set([`not-allowed`,`no-drop`,`wait`,`progress`,`initial`,`inherit`]);function s(e){return e.tagName.toLowerCase()===`html`?!1:!!(i?.cursor&&a.has(i.cursor))}if(s(e))return!0;let c=new Set([`a`,`button`,`input`,`select`,`textarea`,`details`,`summary`,`label`,`option`,`optgroup`,`fieldset`,`legend`]),l=new Set([`disabled`,`readonly`]);if(c.has(r)){if(i?.cursor&&o.has(i.cursor))return!1;for(let t of l)if(e.hasAttribute(t)||e.getAttribute(t)===`true`||e.getAttribute(t)===``)return!1;return!(e.disabled||e.readOnly||e.inert)}let u=e.getAttribute(`role`),d=e.getAttribute(`aria-role`);if(e.getAttribute(`contenteditable`)===`true`||e.isContentEditable||e.classList&&(e.classList.contains(`button`)||e.classList.contains(`dropdown-toggle`)||e.getAttribute(`data-index`)||e.getAttribute(`data-toggle`)===`dropdown`||e.getAttribute(`aria-haspopup`)===`true`))return!0;let f=new Set([`button`,`menu`,`menubar`,`menuitem`,`menuitemradio`,`menuitemcheckbox`,`radio`,`checkbox`,`tab`,`switch`,`slider`,`spinbutton`,`combobox`,`searchbox`,`textbox`,`listbox`,`option`,`scrollbar`]);if(c.has(r)||u&&f.has(u)||d&&f.has(d))return!0;try{if(typeof getEventListeners==`function`){let t=getEventListeners(e);for(let e of[`click`,`mousedown`,`mouseup`,`dblclick`])if(t[e]&&t[e].length>0)return!0}let t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof t==`function`){let n=t(e);for(let e of[`click`,`mousedown`,`mouseup`,`keydown`,`keyup`,`submit`,`change`,`input`,`focus`,`blur`])for(let t of n)if(t.type===e)return!0}for(let t of[`onclick`,`onmousedown`,`onmouseup`,`ondblclick`])if(e.hasAttribute(t)||typeof e[t]==`function`)return!0}catch{}return!!b(e)}function T(e){if(s===-1)return!0;let t=h(e);if(!t||t.length===0)return!1;let n=!1;for(let e of t)if(e.width>0&&e.height>0&&!(e.bottom<-s||e.top>window.innerHeight+s||e.right<-s||e.left>window.innerWidth+s)){n=!0;break}if(!n)return!1;if(e.ownerDocument!==window.document)return!0;let r=Array.from(t).find(e=>e.width>0&&e.height>0);if(!r)return!1;let i=e.getRootNode();if(i instanceof ShadowRoot){let t=r.left+r.width/2,n=r.top+r.height/2;try{let r=i.elementFromPoint(t,n);if(!r)return!1;let a=r;for(;a&&a!==i;){if(a===e)return!0;a=a.parentElement}return!1}catch{return!0}}let a=5;return[{x:r.left+r.width/2,y:r.top+r.height/2},{x:r.left+5,y:r.top+5},{x:r.right-5,y:r.bottom-5}].some(({x:t,y:n})=>{try{let r=document.elementFromPoint(t,n);if(!r)return!1;let i=r;for(;i&&i!==document.documentElement;){if(i===e)return!0;i=i.parentElement}return!1}catch{return!0}})}function E(e,t){if(t===-1)return!0;let n=e.getClientRects();if(!n||n.length===0){let n=p(e);return!n||n.width===0||n.height===0?!1:!(n.bottom<-t||n.top>window.innerHeight+t||n.right<-t||n.left>window.innerWidth+t)}for(let e of n)if(!(e.width===0||e.height===0)&&!(e.bottom<-t||e.top>window.innerHeight+t||e.right<-t||e.left>window.innerWidth+t))return!0;return!1}let D=[`aria-expanded`,`aria-checked`,`aria-selected`,`aria-pressed`,`aria-haspopup`,`aria-controls`,`aria-owns`,`aria-activedescendant`,`aria-valuenow`,`aria-valuetext`,`aria-valuemax`,`aria-valuemin`,`aria-autocomplete`];function O(e){for(let t=0;t<D.length;t++)if(e.hasAttribute(D[t]))return!0;return!1}function k(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;let t=e.tagName.toLowerCase();return new Set([`a`,`button`,`input`,`select`,`textarea`,`details`,`summary`,`label`]).has(t)?!0:e.hasAttribute(`onclick`)||e.hasAttribute(`role`)||e.hasAttribute(`tabindex`)||O(e)||e.hasAttribute(`data-action`)||e.getAttribute(`contenteditable`)===`true`}let A=new Set([`a`,`button`,`input`,`select`,`textarea`,`summary`,`details`,`label`,`option`,`li`]),j=new Set([`button`,`link`,`menuitem`,`menuitemradio`,`menuitemcheckbox`,`radio`,`checkbox`,`tab`,`switch`,`slider`,`spinbutton`,`combobox`,`searchbox`,`textbox`,`listbox`,`listitem`,`treeitem`,`row`,`option`,`scrollbar`]);function M(e){if(!e||e.nodeType!==Node.ELEMENT_NODE||!C(e))return!1;let t=e.hasAttribute(`role`)||e.hasAttribute(`tabindex`)||e.hasAttribute(`onclick`)||typeof e.onclick==`function`,n=/\b(btn|clickable|menu|item|entry|link)\b/i.test(e.className||``),r=!!e.closest(`button,a,[role="button"],.menu,.dropdown,.list,.toolbar`),i=[...e.children].some(C),a=e.parentElement&&e.parentElement.isSameNode(document.body);return(w(e)||t||n)&&i&&r&&!a}function N(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;let t=e.tagName.toLowerCase(),n=e.getAttribute(`role`);if(t===`iframe`||A.has(t)||n&&j.has(n)||e.isContentEditable||e.getAttribute(`contenteditable`)===`true`||e.hasAttribute(`data-testid`)||e.hasAttribute(`data-cy`)||e.hasAttribute(`data-test`)||e.hasAttribute(`onclick`)||typeof e.onclick==`function`||O(e))return!0;try{let t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof t==`function`){let n=t(e);for(let e of[`click`,`mousedown`,`mouseup`,`keydown`,`keyup`,`submit`,`change`,`input`,`focus`,`blur`])for(let t of n)if(t.type===e)return!0}if([`onmousedown`,`onmouseup`,`onkeydown`,`onkeyup`,`onsubmit`,`onchange`,`oninput`,`onfocus`,`onblur`].some(t=>e.hasAttribute(t)))return!0}catch{}return!!(M(e)||u.get(e)?.scrollable)}function P(e,t,n,r){if(!e.isInteractive)return!1;let i=!1;return i=r?!!N(t):!0,i&&(e.isInViewport=E(t,s),(e.isInViewport||s===-1)&&(e.highlightIndex=l++,a))?(o>=0?o===e.highlightIndex&&y(t,e.highlightIndex,n):y(t,e.highlightIndex,n),!0):!1}function F(e,t=null,n=!1){if(!e||e.id===v||e.nodeType!==Node.ELEMENT_NODE&&e.nodeType!==Node.TEXT_NODE||!e||e.id===v||e.dataset?.browserUseIgnore===`true`||e.dataset?.pageAgentIgnore===`true`||e.getAttribute&&e.getAttribute(`aria-hidden`)===`true`)return null;if(e===document.body){let n={tagName:`body`,attributes:{},xpath:`/body`,children:[]};for(let r of e.childNodes){let e=F(r,t,!1);e&&n.children.push(e)}let r=`${_.current++}`;return g[r]=n,r}if(e.nodeType!==Node.ELEMENT_NODE&&e.nodeType!==Node.TEXT_NODE)return null;if(e.nodeType===Node.TEXT_NODE){let t=e.textContent?.trim();if(!t)return null;let n=e.parentElement;if(!n||n.tagName.toLowerCase()===`script`)return null;let r=`${_.current++}`;return g[r]={type:`TEXT_NODE`,text:t,isVisible:x(e)},r}if(e.nodeType===Node.ELEMENT_NODE&&!S(e))return null;if(s!==-1&&!e.shadowRoot){let t=p(e),n=m(e),r=n&&(n.position===`fixed`||n.position===`sticky`),i=e.offsetWidth>0||e.offsetHeight>0;if(!t||!r&&!i&&(t.bottom<-s||t.top>window.innerHeight+s||t.right<-s||t.left>window.innerWidth+s))return null}let r={tagName:e.tagName.toLowerCase(),attributes:{},children:[]};if(k(e)||e.tagName.toLowerCase()===`iframe`||e.tagName.toLowerCase()===`body`){let t=e.getAttributeNames?.()||[];for(let n of t){let t=e.getAttribute(n);r.attributes[n]=t}e.tagName.toLowerCase()===`input`&&(e.type===`checkbox`||e.type===`radio`)&&(r.attributes.checked=e.checked?`true`:`false`)}let i=!1;if(e.nodeType===Node.ELEMENT_NODE&&(r.isVisible=C(e),r.isVisible)){r.isTopElement=T(e);let a=e.getAttribute(`role`),o=a===`menu`||a===`menubar`||a===`listbox`;if((r.isTopElement||o)&&(r.isInteractive=w(e),i=P(r,e,t,n),r.ref=e,r.isInteractive&&Object.keys(r.attributes).length===0)){let t=e.getAttributeNames?.()||[];for(let n of t){let t=e.getAttribute(n);r.attributes[n]=t}}}if(e.tagName){let a=e.tagName.toLowerCase();if(a===`iframe`)try{let t=e.contentDocument||e.contentWindow?.document;if(t)for(let n of t.childNodes){let t=F(n,e,!1);t&&r.children.push(t)}}catch(e){console.warn(`Unable to access iframe:`,e)}else if(e.isContentEditable||e.getAttribute(`contenteditable`)===`true`||e.id===`tinymce`||e.classList.contains(`mce-content-body`)||a===`body`&&e.getAttribute(`data-id`)?.startsWith(`mce_`))for(let n of e.childNodes){let e=F(n,t,i);e&&r.children.push(e)}else{if(e.shadowRoot){r.shadowRoot=!0;for(let n of e.shadowRoot.childNodes){let e=F(n,t,i);e&&r.children.push(e)}}for(let a of e.childNodes){let e=F(a,t,i||n);e&&r.children.push(e)}}}if(r.tagName===`a`&&r.children.length===0&&!r.attributes.href){let t=p(e);if(!(t&&t.width>0&&t.height>0||e.offsetWidth>0||e.offsetHeight>0))return null}r.extra=u.get(e)||null;let a=`${_.current++}`;return g[a]=r,a}let I=F(document.body);return f.clearCache(),{rootId:I,map:g}},dom_exports=__exportAll({cleanUpHighlights:()=>cleanUpHighlights,flatTreeToString:()=>flatTreeToString,getAllTextTillNextClickableElement:()=>getAllTextTillNextClickableElement,getElementTextMap:()=>getElementTextMap,getFlatTree:()=>getFlatTree,getSelectorMap:()=>getSelectorMap,resolveViewportExpansion:()=>resolveViewportExpansion}),DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(e){return e??DEFAULT_VIEWPORT_EXPANSION}var SEMANTIC_TAGS=new Set([`nav`,`menu`,`header`,`footer`,`aside`,`dialog`]),newElementsCache=new WeakMap;function getFlatTree(e){let t=resolveViewportExpansion(e.viewportExpansion),n=[];for(let t of e.interactiveBlacklist||[])typeof t==`function`?n.push(t()):n.push(t);let r=[];for(let t of e.interactiveWhitelist||[])typeof t==`function`?r.push(t()):r.push(t);let i=dom_tree_default({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:t,interactiveBlacklist:n,interactiveWhitelist:r,highlightOpacity:e.highlightOpacity??0,highlightLabelOpacity:e.highlightLabelOpacity??.1}),a=window.location.href;for(let e in i.map){let t=i.map[e];if(t.isInteractive&&t.ref){let e=t.ref;newElementsCache.has(e)||(newElementsCache.set(e,a),t.isNew=!0)}}return i}var globRegexCache=new Map;function globToRegex(e){let t=globRegexCache.get(e);if(!t){let n=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`);t=RegExp(`^${n.replace(/\*/g,`.*`)}$`),globRegexCache.set(e,t)}return t}function matchAttributes(e,t){let n={};for(let r of t)if(r.includes(`*`)){let t=globToRegex(r);for(let r of Object.keys(e))t.test(r)&&e[r].trim()&&(n[r]=e[r].trim())}else{let t=e[r];t&&t.trim()&&(n[r]=t.trim())}return n}function flatTreeToString(e,t=[],n=!1){let r=[`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`,`contenteditable`],i=[...t,...r],a=(e,t)=>e.length>t?e.substring(0,t)+`...`:e,o=t=>{let n=e.map[t];if(!n)return null;if(n.type===`TEXT_NODE`){let e=n;return{type:`text`,text:e.text,isVisible:e.isVisible,parent:null,children:[]}}else{let e=n,t=[];if(e.children)for(let n of e.children){let e=o(n);e&&(e.parent=null,t.push(e))}return{type:`element`,tagName:e.tagName,attributes:e.attributes??{},isVisible:e.isVisible??!1,isInteractive:e.isInteractive??!1,isTopElement:e.isTopElement??!1,isNew:e.isNew??!1,highlightIndex:e.highlightIndex,parent:null,children:t,extra:e.extra??{}}}},s=(e,t=null)=>{e.parent=t;for(let t of e.children)s(t,e)},c=o(e.rootId);if(!c)return``;s(c);let l=e=>{let t=e.parent;for(;t;){if(t.type===`element`&&t.highlightIndex!==void 0)return!0;t=t.parent}return!1},u=(e,t,r)=>{let o=t,s=` `.repeat(t);if(e.type===`element`){let t=n&&e.tagName&&SEMANTIC_TAGS.has(e.tagName);if(e.highlightIndex!==void 0){o+=1;let t=getAllTextTillNextClickableElement(e),n=``;if(i.length>0&&e.attributes){let r=matchAttributes(e.attributes,i),o=Object.keys(r);if(o.length>1){let e=new Set,t={};for(let n of o){let i=r[n];i.length>5&&(i in t?e.add(n):t[i]=n)}for(let t of e)delete r[t]}r.role===e.tagName&&delete r.role;for(let e of[`aria-label`,`placeholder`,`title`])r[e]&&r[e].toLowerCase().trim()===t.toLowerCase().trim()&&delete r[e];Object.keys(r).length>0&&(n=Object.entries(r).map(([e,t])=>`${e}=${a(t,20)}`).join(` `))}let c=`${s}${e.isNew?`*[${e.highlightIndex}]`:`[${e.highlightIndex}]`}<${e.tagName??``}`;if(n&&(c+=` ${n}`),e.extra&&e.extra.scrollable){let t=``;e.extra.scrollData?.left&&(t+=`left=${e.extra.scrollData.left}, `),e.extra.scrollData?.top&&(t+=`top=${e.extra.scrollData.top}, `),e.extra.scrollData?.right&&(t+=`right=${e.extra.scrollData.right}, `),e.extra.scrollData?.bottom&&(t+=`bottom=${e.extra.scrollData.bottom}`),c+=` data-scrollable="${t}"`}if(t){let e=t.trim();n||(c+=` `),c+=`>${e}`}else n||(c+=` `);c+=` />`,r.push(c)}let c=t&&e.highlightIndex===void 0,l=c?r.length:-1;c&&(r.push(`${s}<${e.tagName}>`),o+=1);for(let t of e.children)u(t,o,r);c&&(r.length===l+1?r.pop():r.push(`${s}</${e.tagName}>`))}else if(e.type===`text`){if(l(e))return;e.parent&&e.parent.type===`element`&&e.parent.isVisible&&e.parent.isTopElement&&r.push(`${s}${e.text??``}`)}},d=[];return u(c,0,d),d.join(`
|
|
244
|
+
`,t}dispose(){console.log(`Disposing PageAgent...`),this.disposed=!0,this.pageController.dispose(),this.#n.abort(),this.dispatchEvent(new Event(`dispose`)),this.config.onDispose?.(this)}};function isHTMLElement(e){return!!e&&e.nodeType===1}function isInputElement(e){return e?.nodeType===1&&e.tagName===`INPUT`}function isTextAreaElement(e){return e?.nodeType===1&&e.tagName===`TEXTAREA`}function isSelectElement(e){return e?.nodeType===1&&e.tagName===`SELECT`}function isAnchorElement(e){return e?.nodeType===1&&e.tagName===`A`}function getIframeOffset(e){let t=e.ownerDocument.defaultView?.frameElement;if(!t)return{x:0,y:0};let n=t.getBoundingClientRect();return{x:n.left,y:n.top}}function getNativeValueSetter(e){return Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),`value`).set}async function waitFor(e){await new Promise(t=>setTimeout(t,e*1e3))}async function movePointerToElement(e,t,n){let r=getIframeOffset(e);window.dispatchEvent(new CustomEvent(`PageAgent::MovePointerTo`,{detail:{x:t+r.x,y:n+r.y}})),await waitFor(.3)}async function clickPointer(){window.dispatchEvent(new CustomEvent(`PageAgent::ClickPointer`))}async function enablePassThrough(){window.dispatchEvent(new CustomEvent(`PageAgent::EnablePassThrough`))}async function disablePassThrough(){window.dispatchEvent(new CustomEvent(`PageAgent::DisablePassThrough`))}function getElementByIndex(e,t){let n=e.get(t);if(!n)throw Error(`No interactive element found at index ${t}`);let r=n.ref;if(!r)throw Error(`Element at index ${t} does not have a reference`);if(!isHTMLElement(r))throw Error(`Element at index ${t} is not an HTMLElement`);return r}var lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&=(lastClickedElement.dispatchEvent(new PointerEvent(`pointerout`,{bubbles:!0})),lastClickedElement.dispatchEvent(new PointerEvent(`pointerleave`,{bubbles:!1})),lastClickedElement.dispatchEvent(new MouseEvent(`mouseout`,{bubbles:!0})),lastClickedElement.dispatchEvent(new MouseEvent(`mouseleave`,{bubbles:!1})),lastClickedElement.blur(),null)}async function clickElement(e){blurLastClickedElement(),lastClickedElement=e,await scrollIntoViewIfNeeded(e);let t=e.ownerDocument.defaultView?.frameElement;t&&await scrollIntoViewIfNeeded(t);let n=e.getBoundingClientRect(),r=n.left+n.width/2,i=n.top+n.height/2;await movePointerToElement(e,r,i),await clickPointer(),await waitFor(.1);let a=e.ownerDocument;await enablePassThrough();let o=a.elementFromPoint(r,i);await disablePassThrough();let s=o instanceof HTMLElement&&e.contains(o)?o:e,c={bubbles:!0,cancelable:!0,clientX:r,clientY:i,pointerType:`mouse`},l={bubbles:!0,cancelable:!0,clientX:r,clientY:i,button:0};s.dispatchEvent(new PointerEvent(`pointerover`,c)),s.dispatchEvent(new PointerEvent(`pointerenter`,{...c,bubbles:!1})),s.dispatchEvent(new MouseEvent(`mouseover`,l)),s.dispatchEvent(new MouseEvent(`mouseenter`,{...l,bubbles:!1})),s.dispatchEvent(new PointerEvent(`pointerdown`,c)),s.dispatchEvent(new MouseEvent(`mousedown`,l)),e.focus({preventScroll:!0}),s.dispatchEvent(new PointerEvent(`pointerup`,c)),s.dispatchEvent(new MouseEvent(`mouseup`,l)),s.click(),await waitFor(.2)}async function inputTextElement(e,t){let n=e.isContentEditable;if(!isInputElement(e)&&!isTextAreaElement(e)&&!n)throw Error(`Element is not an input, textarea, or contenteditable`);if(await clickElement(e),n){if(e.dispatchEvent(new InputEvent(`beforeinput`,{bubbles:!0,cancelable:!0,inputType:`deleteContent`}))&&(e.innerText=``,e.dispatchEvent(new InputEvent(`input`,{bubbles:!0,inputType:`deleteContent`}))),e.dispatchEvent(new InputEvent(`beforeinput`,{bubbles:!0,cancelable:!0,inputType:`insertText`,data:t}))&&(e.innerText=t,e.dispatchEvent(new InputEvent(`input`,{bubbles:!0,inputType:`insertText`,data:t}))),e.innerText.trim()!==t.trim()){e.focus();let n=e.ownerDocument,r=(n.defaultView||window).getSelection(),i=n.createRange();i.selectNodeContents(e),r?.removeAllRanges(),r?.addRange(i),n.execCommand(`delete`,!1),n.execCommand(`insertText`,!1,t)}e.dispatchEvent(new Event(`change`,{bubbles:!0})),e.blur()}else getNativeValueSetter(e).call(e,t);n||e.dispatchEvent(new Event(`input`,{bubbles:!0})),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(e,t){if(!isSelectElement(e))throw Error(`Element is not a select element`);let n=Array.from(e.options).find(e=>e.textContent?.trim()===t.trim());if(!n)throw Error(`Option with text "${t}" not found in select element`);e.value=n.value,e.dispatchEvent(new Event(`change`,{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(e){let t=e;typeof t.scrollIntoViewIfNeeded==`function`?t.scrollIntoViewIfNeeded():e.scrollIntoView({behavior:`auto`,block:`center`,inline:`nearest`})}async function scrollVertically(e,t){if(t){let n=t,r=n,i=!1,a=null,o=0,s=0,c=e;for(;r&&s<10;){let e=window.getComputedStyle(r),t=/(auto|scroll|overlay)/.test(e.overflowY)||e.scrollbarWidth&&e.scrollbarWidth!==`auto`||e.scrollbarGutter&&e.scrollbarGutter!==`auto`,n=r.scrollHeight>r.clientHeight;if(t&&n){let e=r.scrollTop,t=r.scrollHeight-r.clientHeight,n=c/3;n=n>0?Math.min(n,t-e):Math.max(n,-e),r.scrollTop=e+n;let s=r.scrollTop-e;if(Math.abs(s)>.5){i=!0,a=r,o=s;break}}if(r===document.body||r===document.documentElement)break;r=r.parentElement,s++}return i?`Scrolled container (${a?.tagName}) by ${o}px`:`No scrollable container found for element (${n.tagName})`}let n=e,r=e=>e.clientHeight>=window.innerHeight*.5,i=e=>!!(e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowY)&&e.scrollHeight>e.clientHeight&&r(e)),a=document.activeElement;for(;a&&!i(a)&&a!==document.body;)a=a.parentElement;if(a=i(a)?a:Array.from(document.querySelectorAll(`*`)).find(i)||document.scrollingElement||document.documentElement,a===document.scrollingElement||a===document.documentElement||a===document.body){let e=window.scrollY,t=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,n);let r=window.scrollY,i=r-e;return Math.abs(i)<1?n>0?`⚠️ Already at the bottom of the page, cannot scroll down further.`:`⚠️ Already at the top of the page, cannot scroll up further.`:n>0&&r>=t-1?`✅ Scrolled page by ${i}px. Reached the bottom of the page.`:n<0&&r<=1?`✅ Scrolled page by ${i}px. Reached the top of the page.`:`✅ Scrolled page by ${i}px.`}else{let e=`The document is not scrollable. Falling back to container scroll.`;console.log(`[PageController] ${e}`);let t=a.scrollTop,r=a.scrollHeight-a.clientHeight;a.scrollBy({top:n,behavior:`smooth`}),await waitFor(.1);let i=a.scrollTop,o=i-t;return Math.abs(o)<1?n>0?`⚠️ ${e} Already at the bottom of container (${a.tagName}), cannot scroll down further.`:`⚠️ ${e} Already at the top of container (${a.tagName}), cannot scroll up further.`:n>0&&i>=r-1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the bottom.`:n<0&&i<=1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the top.`:`✅ ${e} Scrolled container (${a.tagName}) by ${o}px.`}}async function scrollHorizontally(e,t){if(t){let n=t,r=n,i=!1,a=null,o=0,s=0,c=e;for(;r&&s<10;){let e=window.getComputedStyle(r),t=/(auto|scroll|overlay)/.test(e.overflowX)||e.scrollbarWidth&&e.scrollbarWidth!==`auto`||e.scrollbarGutter&&e.scrollbarGutter!==`auto`,n=r.scrollWidth>r.clientWidth;if(t&&n){let e=r.scrollLeft,t=r.scrollWidth-r.clientWidth,n=c/3;n=n>0?Math.min(n,t-e):Math.max(n,-e),r.scrollLeft=e+n;let s=r.scrollLeft-e;if(Math.abs(s)>.5){i=!0,a=r,o=s;break}}if(r===document.body||r===document.documentElement)break;r=r.parentElement,s++}return i?`Scrolled container (${a?.tagName}) horizontally by ${o}px`:`No horizontally scrollable container found for element (${n.tagName})`}let n=e,r=e=>e.clientWidth>=window.innerWidth*.5,i=e=>!!(e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowX)&&e.scrollWidth>e.clientWidth&&r(e)),a=document.activeElement;for(;a&&!i(a)&&a!==document.body;)a=a.parentElement;if(a=i(a)?a:Array.from(document.querySelectorAll(`*`)).find(i)||document.scrollingElement||document.documentElement,a===document.scrollingElement||a===document.documentElement||a===document.body){let e=window.scrollX,t=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(n,0);let r=window.scrollX,i=r-e;return Math.abs(i)<1?n>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.`:n>0&&r>=t-1?`✅ Scrolled page by ${i}px. Reached the right edge of the page.`:n<0&&r<=1?`✅ Scrolled page by ${i}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${i}px.`}else{let e=`The document is not scrollable. Falling back to container scroll.`;console.log(`[PageController] ${e}`);let t=a.scrollLeft,r=a.scrollWidth-a.clientWidth;a.scrollBy({left:n,behavior:`smooth`}),await waitFor(.1);let i=a.scrollLeft,o=i-t;return Math.abs(o)<1?n>0?`⚠️ ${e} Already at the right edge of container (${a.tagName}), cannot scroll right further.`:`⚠️ ${e} Already at the left edge of container (${a.tagName}), cannot scroll left further.`:n>0&&i>=r-1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the right edge.`:n<0&&i<=1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the left edge.`:`✅ ${e} Scrolled container (${a.tagName}) horizontally by ${o}px.`}}var dom_tree_default=(e={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{let{interactiveBlacklist:t,interactiveWhitelist:n,highlightOpacity:r,highlightLabelOpacity:i}=e,{doHighlightElements:a,focusHighlightIndex:o,viewportExpansion:s,debugMode:c}=e,l=0,u=new WeakMap;function d(e,t){!e||e.nodeType!==Node.ELEMENT_NODE||u.set(e,{...u.get(e),...t})}let f={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{f.boundingRects=new WeakMap,f.clientRects=new WeakMap,f.computedStyles=new WeakMap}};function p(e){if(!e)return null;if(f.boundingRects.has(e))return f.boundingRects.get(e);let t=e.getBoundingClientRect();return t&&f.boundingRects.set(e,t),t}function m(e){if(!e)return null;if(f.computedStyles.has(e))return f.computedStyles.get(e);let t=window.getComputedStyle(e);return t&&f.computedStyles.set(e,t),t}function h(e){if(!e)return null;if(f.clientRects.has(e))return f.clientRects.get(e);let t=e.getClientRects();return t&&f.clientRects.set(e,t),t}let g={},_={current:0},v=`playwright-highlight-container`;function y(e,t,n=null){if(!e)return t;let a=[],o=null,s=20,c=16,l=null;try{let u=document.getElementById(v);u||(u=document.createElement(`div`),u.id=v,u.style.position=`fixed`,u.style.pointerEvents=`none`,u.style.top=`0`,u.style.left=`0`,u.style.width=`100%`,u.style.height=`100%`,u.style.zIndex=`2147483640`,u.style.backgroundColor=`transparent`,document.body.appendChild(u));let d=e.getClientRects();if(!d||d.length===0)return t;let f=[`#FF0000`,`#00FF00`,`#0000FF`,`#FFA500`,`#800080`,`#008080`,`#FF69B4`,`#4B0082`,`#FF4500`,`#2E8B57`,`#DC143C`,`#4682B4`],p=f[t%f.length],m=p+Math.floor(r*255).toString(16).padStart(2,`0`);p+=Math.floor(i*255).toString(16).padStart(2,`0`);let h={x:0,y:0};if(n){let e=n.getBoundingClientRect();h.x=e.left,h.y=e.top}let g=document.createDocumentFragment();for(let e of d){if(e.width===0||e.height===0)continue;let t=document.createElement(`div`);t.style.position=`fixed`,t.style.border=`2px solid ${p}`,t.style.backgroundColor=m,t.style.pointerEvents=`none`,t.style.boxSizing=`border-box`;let n=e.top+h.y,r=e.left+h.x;t.style.top=`${n}px`,t.style.left=`${r}px`,t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,g.appendChild(t),a.push({element:t,initialRect:e})}let _=d[0];o=document.createElement(`div`),o.className=`playwright-highlight-label`,o.style.position=`fixed`,o.style.background=p,o.style.color=`white`,o.style.padding=`1px 4px`,o.style.borderRadius=`4px`,o.style.fontSize=`${Math.min(12,Math.max(8,_.height/2))}px`,o.textContent=t.toString(),s=o.offsetWidth>0?o.offsetWidth:s,c=o.offsetHeight>0?o.offsetHeight:c;let y=_.top+h.y,b=_.left+h.x,x=y+2,S=b+_.width-s-2;(_.width<s+4||_.height<c+4)&&(x=y-c-2,S=b+_.width-s,S<h.x&&(S=b)),x=Math.max(0,Math.min(x,window.innerHeight-c)),S=Math.max(0,Math.min(S,window.innerWidth-s)),o.style.top=`${x}px`,o.style.left=`${S}px`,g.appendChild(o);let C=((e,t)=>{let n=0;return(...r)=>{let i=performance.now();if(!(i-n<t))return n=i,e(...r)}})(()=>{let t=e.getClientRects(),r={x:0,y:0};if(n){let e=n.getBoundingClientRect();r.x=e.left,r.y=e.top}if(a.forEach((e,n)=>{if(n<t.length){let i=t[n],a=i.top+r.y,o=i.left+r.x;e.element.style.top=`${a}px`,e.element.style.left=`${o}px`,e.element.style.width=`${i.width}px`,e.element.style.height=`${i.height}px`,e.element.style.display=i.width===0||i.height===0?`none`:`block`}else e.element.style.display=`none`}),t.length<a.length)for(let e=t.length;e<a.length;e++)a[e].element.style.display=`none`;if(o&&t.length>0){let e=t[0],n=e.top+r.y,i=e.left+r.x,a=n+2,l=i+e.width-s-2;(e.width<s+4||e.height<c+4)&&(a=n-c-2,l=i+e.width-s,l<r.x&&(l=i)),a=Math.max(0,Math.min(a,window.innerHeight-c)),l=Math.max(0,Math.min(l,window.innerWidth-s)),o.style.top=`${a}px`,o.style.left=`${l}px`,o.style.display=`block`}else o&&(o.style.display=`none`)},16);return window.addEventListener(`scroll`,C,!0),window.addEventListener(`resize`,C),l=()=>{window.removeEventListener(`scroll`,C,!0),window.removeEventListener(`resize`,C),a.forEach(e=>e.element.remove()),o&&o.remove()},u.appendChild(g),t+1}finally{l&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(l)}}function b(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return null;let t=m(e);if(!t)return null;let n=t.display;if(n===`inline`||n===`inline-block`)return null;let r=t.overflowX,i=t.overflowY,a=t.scrollbarWidth&&t.scrollbarWidth!==`auto`||t.scrollbarGutter&&t.scrollbarGutter!==`auto`,o=r===`auto`||r===`scroll`,s=i===`auto`||i===`scroll`;if(!o&&!s&&!a)return null;let c=e.scrollWidth-e.clientWidth,l=e.scrollHeight-e.clientHeight,u=4;if(c<4&&l<4||!s&&!a&&c<4||!o&&!a&&l<4)return null;let f=e.scrollTop,p=e.scrollLeft,h={top:f,right:e.scrollWidth-e.clientWidth-e.scrollLeft,bottom:e.scrollHeight-e.clientHeight-e.scrollTop,left:p};return d(e,{scrollable:!0,scrollData:h}),h}function x(e){try{if(s===-1){let t=e.parentElement;if(!t)return!1;try{return t.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{let e=window.getComputedStyle(t);return e.display!==`none`&&e.visibility!==`hidden`&&e.opacity!==`0`}}let t=document.createRange();t.selectNodeContents(e);let n=t.getClientRects();if(!n||n.length===0)return!1;let r=!1,i=!1;for(let e of n)if(e.width>0&&e.height>0&&(r=!0,!(e.bottom<-s||e.top>window.innerHeight+s||e.right<-s||e.left>window.innerWidth+s))){i=!0;break}if(!r||!i)return!1;let a=e.parentElement;if(!a)return!1;try{return a.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{let e=window.getComputedStyle(a);return e.display!==`none`&&e.visibility!==`hidden`&&e.opacity!==`0`}}catch(e){return console.warn(`Error checking text node visibility:`,e),!1}}function S(e){if(!e||!e.tagName)return!1;let t=new Set([`body`,`div`,`main`,`article`,`section`,`nav`,`header`,`footer`]),n=e.tagName.toLowerCase();return t.has(n)?!0:!new Set([`svg`,`script`,`style`,`link`,`meta`,`noscript`,`template`]).has(n)}function C(e){let t=m(e);return e.offsetWidth>0&&e.offsetHeight>0&&t?.visibility!==`hidden`&&t?.display!==`none`}function w(e){if(!e||e.nodeType!==Node.ELEMENT_NODE||t.includes(e))return!1;if(n.includes(e))return!0;let r=e.tagName.toLowerCase(),i=m(e),a=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`.split(`.`)),o=new Set([`not-allowed`,`no-drop`,`wait`,`progress`,`initial`,`inherit`]);function s(e){return e.tagName.toLowerCase()===`html`?!1:!!(i?.cursor&&a.has(i.cursor))}if(s(e))return!0;let c=new Set([`a`,`button`,`input`,`select`,`textarea`,`details`,`summary`,`label`,`option`,`optgroup`,`fieldset`,`legend`]),l=new Set([`disabled`,`readonly`]);if(c.has(r)){if(i?.cursor&&o.has(i.cursor))return!1;for(let t of l)if(e.hasAttribute(t)||e.getAttribute(t)===`true`||e.getAttribute(t)===``)return!1;return!(e.disabled||e.readOnly||e.inert)}let u=e.getAttribute(`role`),d=e.getAttribute(`aria-role`);if(e.getAttribute(`contenteditable`)===`true`||e.isContentEditable||e.classList&&(e.classList.contains(`button`)||e.classList.contains(`dropdown-toggle`)||e.getAttribute(`data-index`)||e.getAttribute(`data-toggle`)===`dropdown`||e.getAttribute(`aria-haspopup`)===`true`))return!0;let f=new Set([`button`,`menu`,`menubar`,`menuitem`,`menuitemradio`,`menuitemcheckbox`,`radio`,`checkbox`,`tab`,`switch`,`slider`,`spinbutton`,`combobox`,`searchbox`,`textbox`,`listbox`,`option`,`scrollbar`]);if(c.has(r)||u&&f.has(u)||d&&f.has(d))return!0;try{if(typeof getEventListeners==`function`){let t=getEventListeners(e);for(let e of[`click`,`mousedown`,`mouseup`,`dblclick`])if(t[e]&&t[e].length>0)return!0}let t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof t==`function`){let n=t(e);for(let e of[`click`,`mousedown`,`mouseup`,`keydown`,`keyup`,`submit`,`change`,`input`,`focus`,`blur`])for(let t of n)if(t.type===e)return!0}for(let t of[`onclick`,`onmousedown`,`onmouseup`,`ondblclick`])if(e.hasAttribute(t)||typeof e[t]==`function`)return!0}catch{}return!!b(e)}function T(e){if(s===-1)return!0;let t=h(e);if(!t||t.length===0)return!1;let n=!1;for(let e of t)if(e.width>0&&e.height>0&&!(e.bottom<-s||e.top>window.innerHeight+s||e.right<-s||e.left>window.innerWidth+s)){n=!0;break}if(!n)return!1;if(e.ownerDocument!==window.document)return!0;let r=Array.from(t).find(e=>e.width>0&&e.height>0);if(!r)return!1;let i=e.getRootNode();if(i instanceof ShadowRoot){let t=r.left+r.width/2,n=r.top+r.height/2;try{let r=i.elementFromPoint(t,n);if(!r)return!1;let a=r;for(;a&&a!==i;){if(a===e)return!0;a=a.parentElement}return!1}catch{return!0}}let a=5;return[{x:r.left+r.width/2,y:r.top+r.height/2},{x:r.left+5,y:r.top+5},{x:r.right-5,y:r.bottom-5}].some(({x:t,y:n})=>{try{let r=document.elementFromPoint(t,n);if(!r)return!1;let i=r;for(;i&&i!==document.documentElement;){if(i===e)return!0;i=i.parentElement}return!1}catch{return!0}})}function E(e,t){if(t===-1)return!0;let n=e.getClientRects();if(!n||n.length===0){let n=p(e);return!n||n.width===0||n.height===0?!1:!(n.bottom<-t||n.top>window.innerHeight+t||n.right<-t||n.left>window.innerWidth+t)}for(let e of n)if(!(e.width===0||e.height===0)&&!(e.bottom<-t||e.top>window.innerHeight+t||e.right<-t||e.left>window.innerWidth+t))return!0;return!1}let D=[`aria-expanded`,`aria-checked`,`aria-selected`,`aria-pressed`,`aria-haspopup`,`aria-controls`,`aria-owns`,`aria-activedescendant`,`aria-valuenow`,`aria-valuetext`,`aria-valuemax`,`aria-valuemin`,`aria-autocomplete`];function O(e){for(let t=0;t<D.length;t++)if(e.hasAttribute(D[t]))return!0;return!1}function k(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;let t=e.tagName.toLowerCase();return new Set([`a`,`button`,`input`,`select`,`textarea`,`details`,`summary`,`label`]).has(t)?!0:e.hasAttribute(`onclick`)||e.hasAttribute(`role`)||e.hasAttribute(`tabindex`)||O(e)||e.hasAttribute(`data-action`)||e.getAttribute(`contenteditable`)===`true`}let A=new Set([`a`,`button`,`input`,`select`,`textarea`,`summary`,`details`,`label`,`option`,`li`]),j=new Set([`button`,`link`,`menuitem`,`menuitemradio`,`menuitemcheckbox`,`radio`,`checkbox`,`tab`,`switch`,`slider`,`spinbutton`,`combobox`,`searchbox`,`textbox`,`listbox`,`listitem`,`treeitem`,`row`,`option`,`scrollbar`]);function M(e){if(!e||e.nodeType!==Node.ELEMENT_NODE||!C(e))return!1;let t=e.hasAttribute(`role`)||e.hasAttribute(`tabindex`)||e.hasAttribute(`onclick`)||typeof e.onclick==`function`,n=/\b(btn|clickable|menu|item|entry|link)\b/i.test(e.className||``),r=!!e.closest(`button,a,[role="button"],.menu,.dropdown,.list,.toolbar`),i=[...e.children].some(C),a=e.parentElement&&e.parentElement.isSameNode(document.body);return(w(e)||t||n)&&i&&r&&!a}function N(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;let t=e.tagName.toLowerCase(),n=e.getAttribute(`role`);if(t===`iframe`||A.has(t)||n&&j.has(n)||e.isContentEditable||e.getAttribute(`contenteditable`)===`true`||e.hasAttribute(`data-testid`)||e.hasAttribute(`data-cy`)||e.hasAttribute(`data-test`)||e.hasAttribute(`onclick`)||typeof e.onclick==`function`||O(e))return!0;try{let t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof t==`function`){let n=t(e);for(let e of[`click`,`mousedown`,`mouseup`,`keydown`,`keyup`,`submit`,`change`,`input`,`focus`,`blur`])for(let t of n)if(t.type===e)return!0}if([`onmousedown`,`onmouseup`,`onkeydown`,`onkeyup`,`onsubmit`,`onchange`,`oninput`,`onfocus`,`onblur`].some(t=>e.hasAttribute(t)))return!0}catch{}return!!(M(e)||u.get(e)?.scrollable)}function P(e,t,n,r){if(!e.isInteractive)return!1;let i=!1;return i=r?!!N(t):!0,i&&(e.isInViewport=E(t,s),(e.isInViewport||s===-1)&&(e.highlightIndex=l++,a))?(o>=0?o===e.highlightIndex&&y(t,e.highlightIndex,n):y(t,e.highlightIndex,n),!0):!1}function F(e,t=null,n=!1){if(!e||e.id===v||e.nodeType!==Node.ELEMENT_NODE&&e.nodeType!==Node.TEXT_NODE||!e||e.id===v||e.dataset?.browserUseIgnore===`true`||e.dataset?.pageAgentIgnore===`true`||e.getAttribute&&e.getAttribute(`aria-hidden`)===`true`)return null;if(e===document.body){let n={tagName:`body`,attributes:{},xpath:`/body`,children:[]};for(let r of e.childNodes){let e=F(r,t,!1);e&&n.children.push(e)}let r=`${_.current++}`;return g[r]=n,r}if(e.nodeType!==Node.ELEMENT_NODE&&e.nodeType!==Node.TEXT_NODE)return null;if(e.nodeType===Node.TEXT_NODE){let t=e.textContent?.trim();if(!t)return null;let n=e.parentElement;if(!n||n.tagName.toLowerCase()===`script`)return null;let r=`${_.current++}`;return g[r]={type:`TEXT_NODE`,text:t,isVisible:x(e)},r}if(e.nodeType===Node.ELEMENT_NODE&&!S(e))return null;if(s!==-1&&!e.shadowRoot){let t=p(e),n=m(e),r=n&&(n.position===`fixed`||n.position===`sticky`),i=e.offsetWidth>0||e.offsetHeight>0;if(!t||!r&&!i&&(t.bottom<-s||t.top>window.innerHeight+s||t.right<-s||t.left>window.innerWidth+s))return null}let r={tagName:e.tagName.toLowerCase(),attributes:{},children:[]};if(k(e)||e.tagName.toLowerCase()===`iframe`||e.tagName.toLowerCase()===`body`){let t=e.getAttributeNames?.()||[];for(let n of t){let t=e.getAttribute(n);r.attributes[n]=t}e.tagName.toLowerCase()===`input`&&(e.type===`checkbox`||e.type===`radio`)&&(r.attributes.checked=e.checked?`true`:`false`)}let i=!1;if(e.nodeType===Node.ELEMENT_NODE&&(r.isVisible=C(e),r.isVisible)){r.isTopElement=T(e);let a=e.getAttribute(`role`),o=a===`menu`||a===`menubar`||a===`listbox`;if((r.isTopElement||o)&&(r.isInteractive=w(e),i=P(r,e,t,n),r.ref=e,r.isInteractive&&Object.keys(r.attributes).length===0)){let t=e.getAttributeNames?.()||[];for(let n of t){let t=e.getAttribute(n);r.attributes[n]=t}}}if(e.tagName){let a=e.tagName.toLowerCase();if(a===`iframe`)try{let t=e.contentDocument||e.contentWindow?.document;if(t)for(let n of t.childNodes){let t=F(n,e,!1);t&&r.children.push(t)}}catch(e){console.warn(`Unable to access iframe:`,e)}else if(e.isContentEditable||e.getAttribute(`contenteditable`)===`true`||e.id===`tinymce`||e.classList.contains(`mce-content-body`)||a===`body`&&e.getAttribute(`data-id`)?.startsWith(`mce_`))for(let n of e.childNodes){let e=F(n,t,i);e&&r.children.push(e)}else{if(e.shadowRoot){r.shadowRoot=!0;for(let n of e.shadowRoot.childNodes){let e=F(n,t,i);e&&r.children.push(e)}}for(let a of e.childNodes){let e=F(a,t,i||n);e&&r.children.push(e)}}}if(r.tagName===`a`&&r.children.length===0&&!r.attributes.href){let t=p(e);if(!(t&&t.width>0&&t.height>0||e.offsetWidth>0||e.offsetHeight>0))return null}r.extra=u.get(e)||null;let a=`${_.current++}`;return g[a]=r,a}let I=F(document.body);return f.clearCache(),{rootId:I,map:g}},dom_exports=__exportAll({cleanUpHighlights:()=>cleanUpHighlights,flatTreeToString:()=>flatTreeToString,getAllTextTillNextClickableElement:()=>getAllTextTillNextClickableElement,getElementTextMap:()=>getElementTextMap,getFlatTree:()=>getFlatTree,getSelectorMap:()=>getSelectorMap,resolveViewportExpansion:()=>resolveViewportExpansion}),DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(e){return e??DEFAULT_VIEWPORT_EXPANSION}var SEMANTIC_TAGS=new Set([`nav`,`menu`,`header`,`footer`,`aside`,`dialog`]),newElementsCache=new WeakMap;function getFlatTree(e){let t=resolveViewportExpansion(e.viewportExpansion),n=[];for(let t of e.interactiveBlacklist||[])typeof t==`function`?n.push(t()):n.push(t);let r=[];for(let t of e.interactiveWhitelist||[])typeof t==`function`?r.push(t()):r.push(t);let i=dom_tree_default({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:t,interactiveBlacklist:n,interactiveWhitelist:r,highlightOpacity:e.highlightOpacity??0,highlightLabelOpacity:e.highlightLabelOpacity??.1}),a=window.location.href;for(let e in i.map){let t=i.map[e];if(t.isInteractive&&t.ref){let e=t.ref;newElementsCache.has(e)||(newElementsCache.set(e,a),t.isNew=!0)}}return i}var globRegexCache=new Map;function globToRegex(e){let t=globRegexCache.get(e);if(!t){let n=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`);t=RegExp(`^${n.replace(/\*/g,`.*`)}$`),globRegexCache.set(e,t)}return t}function matchAttributes(e,t){let n={};for(let r of t)if(r.includes(`*`)){let t=globToRegex(r);for(let r of Object.keys(e))t.test(r)&&e[r].trim()&&(n[r]=e[r].trim())}else{let t=e[r];t&&t.trim()&&(n[r]=t.trim())}return n}function flatTreeToString(e,t=[],n=!1){let r=[`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`,`contenteditable`],i=[...t,...r],a=(e,t)=>e.length>t?e.substring(0,t)+`...`:e,o=t=>{let n=e.map[t];if(!n)return null;if(n.type===`TEXT_NODE`){let e=n;return{type:`text`,text:e.text,isVisible:e.isVisible,parent:null,children:[]}}else{let e=n,t=[];if(e.children)for(let n of e.children){let e=o(n);e&&(e.parent=null,t.push(e))}return{type:`element`,tagName:e.tagName,attributes:e.attributes??{},isVisible:e.isVisible??!1,isInteractive:e.isInteractive??!1,isTopElement:e.isTopElement??!1,isNew:e.isNew??!1,highlightIndex:e.highlightIndex,parent:null,children:t,extra:e.extra??{}}}},s=(e,t=null)=>{e.parent=t;for(let t of e.children)s(t,e)},c=o(e.rootId);if(!c)return``;s(c);let l=e=>{let t=e.parent;for(;t;){if(t.type===`element`&&t.highlightIndex!==void 0)return!0;t=t.parent}return!1},u=(e,t,r)=>{let o=t,s=` `.repeat(t);if(e.type===`element`){let t=n&&e.tagName&&SEMANTIC_TAGS.has(e.tagName);if(e.highlightIndex!==void 0){o+=1;let t=getAllTextTillNextClickableElement(e),n=``;if(i.length>0&&e.attributes){let r=matchAttributes(e.attributes,i),o=Object.keys(r);if(o.length>1){let e=new Set,t={};for(let n of o){let i=r[n];i.length>5&&(i in t?e.add(n):t[i]=n)}for(let t of e)delete r[t]}r.role===e.tagName&&delete r.role;for(let e of[`aria-label`,`placeholder`,`title`])r[e]&&r[e].toLowerCase().trim()===t.toLowerCase().trim()&&delete r[e];Object.keys(r).length>0&&(n=Object.entries(r).map(([e,t])=>`${e}=${a(t,20)}`).join(` `))}let c=`${s}${e.isNew?`*[${e.highlightIndex}]`:`[${e.highlightIndex}]`}<${e.tagName??``}`;if(n&&(c+=` ${n}`),e.extra&&e.extra.scrollable){let t=``;e.extra.scrollData?.left&&(t+=`left=${e.extra.scrollData.left}, `),e.extra.scrollData?.top&&(t+=`top=${e.extra.scrollData.top}, `),e.extra.scrollData?.right&&(t+=`right=${e.extra.scrollData.right}, `),e.extra.scrollData?.bottom&&(t+=`bottom=${e.extra.scrollData.bottom}`),c+=` data-scrollable="${t}"`}if(t){let e=t.trim();n||(c+=` `),c+=`>${e}`}else n||(c+=` `);c+=` />`,r.push(c)}let c=t&&e.highlightIndex===void 0,l=c?r.length:-1;c&&(r.push(`${s}<${e.tagName}>`),o+=1);for(let t of e.children)u(t,o,r);c&&(r.length===l+1?r.pop():r.push(`${s}</${e.tagName}>`))}else if(e.type===`text`){if(l(e))return;e.parent&&e.parent.type===`element`&&e.parent.isVisible&&e.parent.isTopElement&&r.push(`${s}${e.text??``}`)}},d=[];return u(c,0,d),d.join(`
|
|
246
245
|
`)}var getAllTextTillNextClickableElement=(e,t=-1)=>{let n=[],r=(i,a)=>{if(!(t!==-1&&a>t)&&!(i.type===`element`&&i!==e&&i.highlightIndex!==void 0)){if(i.type===`text`&&i.text)n.push(i.text);else if(i.type===`element`)for(let e of i.children)r(e,a+1)}};return r(e,0),n.join(`
|
|
247
246
|
`).trim()};function getSelectorMap(e){let t=new Map,n=Object.keys(e.map);for(let r of n){let n=e.map[r];n.isInteractive&&typeof n.highlightIndex==`number`&&t.set(n.highlightIndex,n)}return t}function getElementTextMap(e){let t=e.split(`
|
|
248
247
|
`).map(e=>e.trim()).filter(e=>e.length>0),n=new Map;for(let e of t){let t=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(e);if(t){let r=parseInt(t[1],10);n.set(r,e)}}return n}function cleanUpHighlights(){let e=window._highlightCleanupFunctions||[];for(let t of e)typeof t==`function`&&t();window._highlightCleanupFunctions=[]}window.addEventListener(`popstate`,()=>{cleanUpHighlights()}),window.addEventListener(`hashchange`,()=>{cleanUpHighlights()}),window.addEventListener(`beforeunload`,()=>{cleanUpHighlights()});var navigation=window.navigation;if(navigation&&typeof navigation.addEventListener==`function`)navigation.addEventListener(`navigate`,()=>{cleanUpHighlights()});else{let e=window.location.href;setInterval(()=>{window.location.href!==e&&(e=window.location.href,cleanUpHighlights())},500)}function getPageInfo(){let e=window.innerWidth,t=window.innerHeight,n=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),r=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),i=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,a=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,o=Math.max(0,r-(window.innerHeight+a)),s=Math.max(0,n-(window.innerWidth+i));return{viewport_width:e,viewport_height:t,page_width:n,page_height:r,scroll_x:i,scroll_y:a,pixels_above:a,pixels_below:o,pages_above:t>0?a/t:0,pages_below:t>0?o/t:0,total_pages:t>0?r/t:0,current_page_position:a/Math.max(1,r-t),pixels_left:i,pixels_right:s}}function patchReact(e){let t=document.querySelectorAll(`[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root`);for(let e of t)e.setAttribute(`data-page-agent-not-interactive`,`true`)}function computeBorderGeometry(e,t,n,r){let i=Math.max(1,Math.min(e,t)),a=Math.min(Math.min(n,20)+r,i),o=Math.min(a,Math.floor(e/2)),s=Math.min(a,Math.floor(t/2)),c=t=>t/e*2-1,l=e=>e/t*2-1,u=0,d=e,f=0,p=t,m=o,h=e-o,g=s,_=t-s,v=c(0),y=c(d),b=l(0),x=l(p),S=c(m),C=c(h),w=l(g),T=l(_),E=0,D=0,O=1,k=1,A=o/e,j=1-o/e,M=s/t,N=1-s/t;return{positions:new Float32Array([v,b,y,b,v,w,v,w,y,b,y,w,v,T,y,T,v,x,v,x,y,T,y,x,v,w,S,w,v,T,v,T,S,w,S,T,C,w,y,w,C,T,C,T,y,w,y,T]),uvs:new Float32Array([0,0,1,0,0,M,0,M,1,0,1,M,0,N,1,N,0,1,0,1,1,N,1,1,0,M,A,M,0,N,0,N,A,M,A,N,j,M,1,M,j,N,j,N,1,M,1,N])}}function compileShader(e,t,n){let r=e.createShader(t);if(!r)throw Error(`Failed to create shader`);if(e.shaderSource(r,n),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){let t=e.getShaderInfoLog(r)||`Unknown shader error`;throw e.deleteShader(r),Error(t)}return r}function createProgram(e,t,n){let r=compileShader(e,e.VERTEX_SHADER,t),i=compileShader(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error(`Failed to create program`);if(e.attachShader(a,r),e.attachShader(a,i),e.linkProgram(a),!e.getProgramParameter(a,e.LINK_STATUS)){let t=e.getProgramInfoLog(a)||`Unknown link error`;throw e.deleteProgram(a),e.deleteShader(r),e.deleteShader(i),Error(t)}return e.deleteShader(r),e.deleteShader(i),a}function parseColor(e){let t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!t)throw Error(`Invalid color format: ${e}`);let[,n,r,i]=t;return[parseInt(n)/255,parseInt(r)/255,parseInt(i)/255]}var fragmentShaderSource,vertexShaderSource,DEFAULT_COLORS,Motion,init_Motion=__esmMin((()=>{fragmentShaderSource=`#version 300 es
|
|
@@ -355,7 +354,7 @@ out vec2 vUV;
|
|
|
355
354
|
void main() {
|
|
356
355
|
vUV = aUV;
|
|
357
356
|
gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
358
|
-
}`,DEFAULT_COLORS=[`rgb(57, 182, 255)`,`rgb(189, 69, 251)`,`rgb(255, 87, 51)`,`rgb(255, 214, 0)`],Motion=class{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(e={}){this.options={width:e.width??600,height:e.height??600,ratio:e.ratio??window.devicePixelRatio??1,borderWidth:e.borderWidth??8,glowWidth:e.glowWidth??200,borderRadius:e.borderRadius??8,mode:e.mode??`light`,...e},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 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`);let e=()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(e);let t=performance.now();if(t-this.lastTime<1e3/32)return;this.lastTime=t;let n=(t-this.startTime)*.001;this.render(n)};this.rafId=requestAnimationFrame(e)}pause(){if(this.disposed)throw 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);let{gl:e,vao:t,positionBuffer:n,uvBuffer:r,program:i}=this.glr;t&&e.deleteVertexArray(t),n&&e.deleteBuffer(n),r&&e.deleteBuffer(r),e.deleteProgram(i),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(e,t,n){if(this.disposed)throw Error(`Motion instance has been disposed.`);if(this.options.width=e,this.options.height=t,n&&(this.options.ratio=n),!this.running)return;let{gl:r,program:i,vao:a,positionBuffer:o,uvBuffer:s,uResolution:c}=this.glr,l=n??this.options.ratio??window.devicePixelRatio??1,u=Math.max(1,Math.floor(e*l)),d=Math.max(1,Math.floor(t*l));this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,(this.canvas.width!==u||this.canvas.height!==d)&&(this.canvas.width=u,this.canvas.height=d),r.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(r,`resize: after viewport setup`);let{positions:f,uvs:p}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*l,this.options.glowWidth*l);r.bindVertexArray(a),r.bindBuffer(r.ARRAY_BUFFER,o),r.bufferData(r.ARRAY_BUFFER,f,r.STATIC_DRAW);let m=r.getAttribLocation(i,`aPosition`);r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,0),this.checkGLError(r,`resize: after position buffer update`),r.bindBuffer(r.ARRAY_BUFFER,s),r.bufferData(r.ARRAY_BUFFER,p,r.STATIC_DRAW);let h=r.getAttribLocation(i,`aUV`);r.enableVertexAttribArray(h),r.vertexAttribPointer(h,2,r.FLOAT,!1,0,0),this.checkGLError(r,`resize: after UV buffer update`),r.useProgram(i),r.uniform2f(c,this.canvas.width,this.canvas.height),r.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*l),r.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*l),r.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*l),this.checkGLError(r,`resize: after uniform updates`);let g=performance.now();this.lastTime=g;let _=(g-this.startTime)*.001;this.render(_)}autoResize(e){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{let t=e.getBoundingClientRect();this.resize(t.width,t.height)}),this.observer.observe(e)}fadeIn(){if(this.disposed)throw Error(`Motion instance has been disposed.`);return new Promise((e,t)=>{let n=this.canvas.animate([{opacity:0,transform:`scale(1.2)`},{opacity:1,transform:`scale(1)`}],{duration:300,easing:`ease-out`,fill:`forwards`});n.onfinish=()=>e(),n.oncancel=()=>t(`canceled`)})}fadeOut(){if(this.disposed)throw Error(`Motion instance has been disposed.`);return new Promise((e,t)=>{let n=this.canvas.animate([{opacity:1,transform:`scale(1)`},{opacity:0,transform:`scale(1.2)`}],{duration:300,easing:`ease-in`,fill:`forwards`});n.onfinish=()=>e(),n.oncancel=()=>t(`canceled`)})}checkGLError(e,t){let n=e.getError();if(n!==e.NO_ERROR){for(console.group(`🔴 WebGL Error in ${t}`);n!==e.NO_ERROR;){let t=this.getGLErrorName(e,n);console.error(`${t} (0x${n.toString(16)})`),n=e.getError()}console.groupEnd()}}getGLErrorName(e,t){switch(t){case e.INVALID_ENUM:return`INVALID_ENUM`;case e.INVALID_VALUE:return`INVALID_VALUE`;case e.INVALID_OPERATION:return`INVALID_OPERATION`;case e.INVALID_FRAMEBUFFER_OPERATION:return`INVALID_FRAMEBUFFER_OPERATION`;case e.OUT_OF_MEMORY:return`OUT_OF_MEMORY`;case e.CONTEXT_LOST_WEBGL:return`CONTEXT_LOST_WEBGL`;default:return`UNKNOWN_ERROR`}}setupGL(){let e=this.canvas.getContext(`webgl2`,{antialias:!1,alpha:!0});if(!e)throw Error(`WebGL2 is required but not available.`);let t=createProgram(e,vertexShaderSource,fragmentShaderSource);this.checkGLError(e,`setupGL: after createProgram`);let n=e.createVertexArray();e.bindVertexArray(n),this.checkGLError(e,`setupGL: after VAO creation`);let{positions:r,uvs:i}=computeBorderGeometry(this.canvas.width||2,this.canvas.height||2,this.options.borderWidth,this.options.glowWidth),a=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,a),e.bufferData(e.ARRAY_BUFFER,r,e.STATIC_DRAW);let o=e.getAttribLocation(t,`aPosition`);e.enableVertexAttribArray(o),e.vertexAttribPointer(o,2,e.FLOAT,!1,0,0),this.checkGLError(e,`setupGL: after position buffer setup`);let s=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,s),e.bufferData(e.ARRAY_BUFFER,i,e.STATIC_DRAW);let c=e.getAttribLocation(t,`aUV`);e.enableVertexAttribArray(c),e.vertexAttribPointer(c,2,e.FLOAT,!1,0,0),this.checkGLError(e,`setupGL: after UV buffer setup`);let l=e.getUniformLocation(t,`uResolution`),u=e.getUniformLocation(t,`uTime`),d=e.getUniformLocation(t,`uBorderWidth`),f=e.getUniformLocation(t,`uGlowWidth`),p=e.getUniformLocation(t,`uBorderRadius`),m=e.getUniformLocation(t,`uColors`),h=e.getUniformLocation(t,`uGlowExponent`),g=e.getUniformLocation(t,`uGlowFactor`);e.useProgram(t),e.uniform1f(d,this.options.borderWidth),e.uniform1f(f,this.options.glowWidth),e.uniform1f(p,this.options.borderRadius),this.options.mode===`dark`?(e.uniform1f(h,2),e.uniform1f(g,1.8)):(e.uniform1f(h,1),e.uniform1f(g,1));let _=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let n=0;n<_.length;n++)e.uniform3f(e.getUniformLocation(t,`uColors[${n}]`),..._[n]);this.checkGLError(e,`setupGL: after uniform setup`),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),this.glr={gl:e,program:t,vao:n,positionBuffer:a,uvBuffer:s,uResolution:l,uTime:u,uBorderWidth:d,uGlowWidth:f,uBorderRadius:p,uColors:m}}render(e){if(!this.glr)return;let{gl:t,program:n,vao:r,uTime:i}=this.glr;t.useProgram(n),t.bindVertexArray(r),t.uniform1f(i,e),t.disable(t.DEPTH_TEST),t.disable(t.CULL_FACE),t.disable(t.BLEND),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLES,0,24),this.checkGLError(t,`render: after draw call`),t.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;`)}}}));function hasDarkModeClass(){let e=[`dark`,`dark-mode`,`theme-dark`,`night`,`night-mode`],t=document.documentElement,n=document.body||document.documentElement;for(let r of e)if(t.classList.contains(r)||n?.classList.contains(r))return!0;return!!t.getAttribute(`data-theme`)?.toLowerCase().includes(`dark`)}function parseRgbColor(e){let t=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(e);return t?{r:parseInt(t[1]),g:parseInt(t[2]),b:parseInt(t[3])}:null}function isColorDark(e,t=128){if(!e||e===`transparent`||e.startsWith(`rgba(0, 0, 0, 0)`))return!1;let n=parseRgbColor(e);return n?.299*n.r+.587*n.g+.114*n.b<t:!1}function isBackgroundDark(){let e=window.getComputedStyle(document.documentElement),t=window.getComputedStyle(document.body||document.documentElement),n=e.backgroundColor,r=t.backgroundColor;return isColorDark(r)?!0:r===`transparent`||r.startsWith(`rgba(0, 0, 0, 0)`)?isColorDark(n):!1}function isPageDark(){try{return!!(hasDarkModeClass()||isBackgroundDark())}catch(e){return console.warn(`Error determining if page is dark:`,e),!1}}var init_checkDarkMode=__esmMin((()=>{})),wrapper$1,visible,SimulatorMask_module_default,init_SimulatorMask_module=__esmMin((()=>{wrapper$1=`_wrapper_1ooyb_1`,visible=`_visible_1ooyb_11`,SimulatorMask_module_default={wrapper:wrapper$1,visible}})),cursor,cursorBorder,cursorFilling,cursorRipple,clicking,cursor_module_default,init_cursor_module=__esmMin((()=>{cursor=`_cursor_1dgwb_2`,cursorBorder=`_cursorBorder_1dgwb_10`,cursorFilling=`_cursorFilling_1dgwb_25`,cursorRipple=`_cursorRipple_1dgwb_39`,clicking=`_clicking_1dgwb_57`,cursor_module_default={cursor,cursorBorder,cursorFilling,cursorRipple,clicking,"cursor-ripple":`_cursor-ripple_1dgwb_1`}})),SimulatorMask_exports=__exportAll({SimulatorMask:()=>SimulatorMask}),SimulatorMask,init_SimulatorMask=__esmMin((()=>{init_Motion(),init_checkDarkMode(),init_SimulatorMask_module(),init_cursor_module(),SimulatorMask=class extends EventTarget{shown=!1;wrapper=document.createElement(`div`);motion=null;#e=!1;#t=document.createElement(`div`);#n=0;#r=0;#i=0;#a=0;constructor(){super(),this.wrapper.id=`page-agent-runtime_simulator-mask`,this.wrapper.className=SimulatorMask_module_default.wrapper,this.wrapper.setAttribute(`data-browser-use-ignore`,`true`),this.wrapper.setAttribute(`data-page-agent-ignore`,`true`);try{let e=new Motion({mode:isPageDark()?`dark`:`light`,styles:{position:`absolute`,inset:`0`}});this.motion=e,this.wrapper.appendChild(e.element),e.autoResize(this.wrapper)}catch(e){console.warn(`[SimulatorMask] Motion overlay unavailable:`,e)}this.wrapper.addEventListener(`click`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mousedown`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mouseup`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mousemove`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`wheel`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`keydown`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`keyup`,e=>{e.stopPropagation(),e.preventDefault()}),this.#o(),document.body.appendChild(this.wrapper),this.#s();let e=e=>{let{x:t,y:n}=e.detail;this.setCursorPosition(t,n)},t=()=>{this.triggerClickAnimation()},n=()=>{this.wrapper.style.pointerEvents=`none`},r=()=>{this.wrapper.style.pointerEvents=`auto`};window.addEventListener(`PageAgent::MovePointerTo`,e),window.addEventListener(`PageAgent::ClickPointer`,t),window.addEventListener(`PageAgent::EnablePassThrough`,n),window.addEventListener(`PageAgent::DisablePassThrough`,r),this.addEventListener(`dispose`,()=>{window.removeEventListener(`PageAgent::MovePointerTo`,e),window.removeEventListener(`PageAgent::ClickPointer`,t),window.removeEventListener(`PageAgent::EnablePassThrough`,n),window.removeEventListener(`PageAgent::DisablePassThrough`,r)})}#o(){this.#t.className=cursor_module_default.cursor;let e=document.createElement(`div`);e.className=cursor_module_default.cursorRipple,this.#t.appendChild(e);let t=document.createElement(`div`);t.className=cursor_module_default.cursorFilling,this.#t.appendChild(t);let n=document.createElement(`div`);n.className=cursor_module_default.cursorBorder,this.#t.appendChild(n),this.wrapper.appendChild(this.#t)}#s(){if(this.#e)return;let e=this.#n+(this.#i-this.#n)*.2,t=this.#r+(this.#a-this.#r)*.2,n=Math.abs(e-this.#i);n>0&&(n<2?this.#n=this.#i:this.#n=e,this.#t.style.left=`${this.#n}px`);let r=Math.abs(t-this.#a);r>0&&(r<2?this.#r=this.#a:this.#r=t,this.#t.style.top=`${this.#r}px`),requestAnimationFrame(()=>this.#s())}setCursorPosition(e,t){this.#e||(this.#i=e,this.#a=t)}triggerClickAnimation(){this.#e||(this.#t.classList.remove(cursor_module_default.clicking),this.#t.offsetHeight,this.#t.classList.add(cursor_module_default.clicking))}show(){this.shown||this.#e||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.classList.add(SimulatorMask_module_default.visible),this.#n=window.innerWidth/2,this.#r=window.innerHeight/2,this.#i=this.#n,this.#a=this.#r,this.#t.style.left=`${this.#n}px`,this.#t.style.top=`${this.#r}px`)}hide(){!this.shown||this.#e||(this.shown=!1,this.motion?.fadeOut(),this.motion?.pause(),this.#t.classList.remove(cursor_module_default.clicking),setTimeout(()=>{this.wrapper.classList.remove(SimulatorMask_module_default.visible)},800))}dispose(){this.#e=!0,console.log(`dispose SimulatorMask`),this.motion?.dispose(),this.wrapper.remove(),this.dispatchEvent(new Event(`dispose`))}}})),PageController=class extends EventTarget{config;flatTree=null;selectorMap=new Map;elementTextMap=new Map;simplifiedHTML=`<EMPTY>`;lastTimeUpdate=0;isIndexed=!1;mask=null;maskReady=null;constructor(e={}){super(),this.config=e,patchReact(this),e.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{let{SimulatorMask:e}=await Promise.resolve().then(()=>(init_SimulatorMask(),SimulatorMask_exports));this.mask=new e})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){let e=window.location.href,t=document.title,n=getPageInfo(),r=resolveViewportExpansion(this.config.viewportExpansion);await this.updateTree();let i=this.simplifiedHTML;return{url:e,title:t,header:`${`Current Page: [${t}](${e})`}\n${`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`}\n\n${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:`}\n\n${n.pixels_above>4&&r!==-1?`... ${n.pixels_above} pixels above (${n.pages_above.toFixed(1)} pages) - scroll to see more ...`:`[Start of page]`}`,content:i,footer:n.pixels_below>4&&r!==-1?`... ${n.pixels_below} pixels below (${n.pages_below.toFixed(1)} pages) - scroll to see more ...`:`[End of page]`}}async updateTree(){this.dispatchEvent(new Event(`beforeUpdate`)),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents=`none`),cleanUpHighlights();let e=[...this.config.interactiveBlacklist||[],...Array.from(document.querySelectorAll(`[data-page-agent-not-interactive]`))];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:e}),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.includeAttributes,this.config.keepSemanticTags),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(){console.log(`[PageController] cleanUpHighlights`),cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw Error(`DOM tree not indexed yet. Can not perform actions on elements.`)}async clickElement(e){try{this.assertIndexed();let t=getElementByIndex(this.selectorMap,e),n=this.elementTextMap.get(e);return await clickElement(t),isAnchorElement(t)&&t.target===`_blank`?{success:!0,message:`✅ Clicked element (${n??e}). ⚠️ Link opened in a new tab.`}:{success:!0,message:`✅ Clicked element (${n??e}).`}}catch(e){return{success:!1,message:`❌ Failed to click element: ${e}`}}}async inputText(e,t){try{this.assertIndexed();let n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return await inputTextElement(n,t),{success:!0,message:`✅ Input text (${t}) into element (${r??e}).`}}catch(e){return{success:!1,message:`❌ Failed to input text: ${e}`}}}async selectOption(e,t){try{this.assertIndexed();let n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return await selectOptionElement(n,t),{success:!0,message:`✅ Selected option (${t}) in element (${r??e}).`}}catch(e){return{success:!1,message:`❌ Failed to select option: ${e}`}}}async scroll(e){try{let{down:t,numPages:n,pixels:r,index:i}=e;return this.assertIndexed(),{success:!0,message:await scrollVertically((r??n*window.innerHeight)*(t?1:-1),i===void 0?null:getElementByIndex(this.selectorMap,i))}}catch(e){return{success:!1,message:`❌ Failed to scroll: ${e}`}}}async scrollHorizontally(e){try{let{right:t,pixels:n,index:r}=e;return this.assertIndexed(),{success:!0,message:await scrollHorizontally(n*(t?1:-1),r===void 0?null:getElementByIndex(this.selectorMap,r))}}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(e){return{success:!1,message:`❌ Error executing JavaScript: ${e}`}}}async showMask(){await this.maskReady,this.mask?.show()}async hideMask(){await this.maskReady,this.mask?.hide()}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML=`<EMPTY>`,this.isIndexed=!1,this.mask?.dispose(),this.mask=null}},enUS={ui:{panel:{ready:`Ready`,thinking:`Thinking...`,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`,userAnswer:`User answer: {{input}}`,question:`Question: {{question}}`,waitingPlaceholder:`Waiting for task to start...`,stop:`Stop`,close:`Close`,expand:`Expand history`,collapse:`Collapse history`,step:`Step {{number}}`},tools:{clicking:`Clicking element [{{index}}]...`,inputting:`Inputting text to element [{{index}}]...`,selecting:`Selecting option "{{text}}"...`,scrolling:`Scrolling page...`,waiting:`Waiting {{seconds}} seconds...`,askingUser:`Asking user...`,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:`正在思考...`,taskInput:`输入新任务,详细描述步骤,回车提交`,userAnswerPrompt:`请回答上面问题,回车提交`,taskTerminated:`任务已终止`,taskCompleted:`任务结束`,userAnswer:`用户回答: {{input}}`,question:`询问: {{question}}`,waitingPlaceholder:`等待任务开始...`,stop:`终止`,close:`关闭`,expand:`展开历史`,collapse:`收起历史`,step:`步骤 {{number}}`},tools:{clicking:`正在点击元素 [{{index}}]...`,inputting:`正在输入文本到元素 [{{index}}]...`,selecting:`正在选择选项 "{{text}}"...`,scrolling:`正在滚动页面...`,waiting:`等待 {{seconds}} 秒...`,askingUser:`正在询问用户...`,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},I18n=class{language;translations;constructor(e=`en-US`){this.language=e in locales?e:`en-US`,this.translations=locales[this.language]}t(e,t){let n=this.getNestedValue(this.translations,e);return n?t?this.interpolate(n,t):n:(console.warn(`Translation key "${e}" not found for language "${this.language}"`),e)}getNestedValue(e,t){return t.split(`.`).reduce((e,t)=>e?.[t],e)}interpolate(e,t){return e.replace(/\{\{(\w+)\}\}/g,(e,n)=>t[n]==null?e:t[n].toString())}getLanguage(){return this.language}};function truncate(e,t){return e.length>t?e.substring(0,t)+`...`:e}function escapeHtml(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}var wrapper=`_wrapper_1tu05_1`,background=`_background_1tu05_39`,header=`_header_1tu05_99`,pulse=`_pulse_1tu05_1`,retryPulse=`_retryPulse_1tu05_1`,statusTextFadeOut=`_statusTextFadeOut_1tu05_1`,statusTextFadeIn=`_statusTextFadeIn_1tu05_1`,statusSection=`_statusSection_1tu05_121`,indicator=`_indicator_1tu05_128`,thinking=`_thinking_1tu05_137`,tool_executing=`_tool_executing_1tu05_142`,retry=`_retry_1tu05_147`,completed=`_completed_1tu05_153`,input=`_input_1tu05_154`,output=`_output_1tu05_155`,error=`_error_1tu05_160`,statusText=`_statusText_1tu05_166`,fadeOut=`_fadeOut_1tu05_178`,fadeIn=`_fadeIn_1tu05_182`,controls=`_controls_1tu05_188`,controlButton=`_controlButton_1tu05_193`,stopButton=`_stopButton_1tu05_212`,historySectionWrapper=`_historySectionWrapper_1tu05_246`,shimmer=`_shimmer_1tu05_1`,celebrate=`_celebrate_1tu05_1`,expanded=`_expanded_1tu05_278`,historySection=`_historySection_1tu05_246`,historyItem=`_historyItem_1tu05_297`,observation=`_observation_1tu05_355`,question=`_question_1tu05_360`,doneSuccess=`_doneSuccess_1tu05_366`,historyContent=`_historyContent_1tu05_402`,statusIcon=`_statusIcon_1tu05_403`,doneError=`_doneError_1tu05_412`,reflectionLines=`_reflectionLines_1tu05_462`,historyMeta=`_historyMeta_1tu05_469`,inputSectionWrapper=`_inputSectionWrapper_1tu05_539`,hidden=`_hidden_1tu05_562`,inputSection=`_inputSection_1tu05_539`,taskInput=`_taskInput_1tu05_573`,Panel_module_default={wrapper,"mask-running":`_mask-running_1tu05_1`,background,header,pulse,retryPulse,statusTextFadeOut,statusTextFadeIn,statusSection,indicator,thinking,tool_executing,retry,completed,input,output,error,statusText,fadeOut,fadeIn,controls,controlButton,stopButton,historySectionWrapper,shimmer,celebrate,expanded,historySection,historyItem,observation,question,doneSuccess,historyContent,statusIcon,doneError,reflectionLines,historyMeta,inputSectionWrapper,hidden,inputSection,taskInput};function createCard({icon:e,content:t,meta:n,type:r}){let i=r?Panel_module_default[r]:``,a=Array.isArray(t)?`<div class="${Panel_module_default.reflectionLines}">${t.map(e=>`<span>${escapeHtml(e)}</span>`).join(``)}</div>`:`<span>${escapeHtml(t)}</span>`;return`
|
|
357
|
+
}`,DEFAULT_COLORS=[`rgb(57, 182, 255)`,`rgb(189, 69, 251)`,`rgb(255, 87, 51)`,`rgb(255, 214, 0)`],Motion=class{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(e={}){this.options={width:e.width??600,height:e.height??600,ratio:e.ratio??window.devicePixelRatio??1,borderWidth:e.borderWidth??8,glowWidth:e.glowWidth??200,borderRadius:e.borderRadius??8,mode:e.mode??`light`,...e},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 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`);let e=()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(e);let t=performance.now();if(t-this.lastTime<1e3/32)return;this.lastTime=t;let n=(t-this.startTime)*.001;this.render(n)};this.rafId=requestAnimationFrame(e)}pause(){if(this.disposed)throw 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);let{gl:e,vao:t,positionBuffer:n,uvBuffer:r,program:i}=this.glr;t&&e.deleteVertexArray(t),n&&e.deleteBuffer(n),r&&e.deleteBuffer(r),e.deleteProgram(i),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(e,t,n){if(this.disposed)throw Error(`Motion instance has been disposed.`);if(this.options.width=e,this.options.height=t,n&&(this.options.ratio=n),!this.running)return;let{gl:r,program:i,vao:a,positionBuffer:o,uvBuffer:s,uResolution:c}=this.glr,l=n??this.options.ratio??window.devicePixelRatio??1,u=Math.max(1,Math.floor(e*l)),d=Math.max(1,Math.floor(t*l));this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,(this.canvas.width!==u||this.canvas.height!==d)&&(this.canvas.width=u,this.canvas.height=d),r.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(r,`resize: after viewport setup`);let{positions:f,uvs:p}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*l,this.options.glowWidth*l);r.bindVertexArray(a),r.bindBuffer(r.ARRAY_BUFFER,o),r.bufferData(r.ARRAY_BUFFER,f,r.STATIC_DRAW);let m=r.getAttribLocation(i,`aPosition`);r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,0),this.checkGLError(r,`resize: after position buffer update`),r.bindBuffer(r.ARRAY_BUFFER,s),r.bufferData(r.ARRAY_BUFFER,p,r.STATIC_DRAW);let h=r.getAttribLocation(i,`aUV`);r.enableVertexAttribArray(h),r.vertexAttribPointer(h,2,r.FLOAT,!1,0,0),this.checkGLError(r,`resize: after UV buffer update`),r.useProgram(i),r.uniform2f(c,this.canvas.width,this.canvas.height),r.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*l),r.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*l),r.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*l),this.checkGLError(r,`resize: after uniform updates`);let g=performance.now();this.lastTime=g;let _=(g-this.startTime)*.001;this.render(_)}autoResize(e){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{let t=e.getBoundingClientRect();this.resize(t.width,t.height)}),this.observer.observe(e)}fadeIn(){if(this.disposed)throw Error(`Motion instance has been disposed.`);return new Promise((e,t)=>{let n=this.canvas.animate([{opacity:0,transform:`scale(1.2)`},{opacity:1,transform:`scale(1)`}],{duration:300,easing:`ease-out`,fill:`forwards`});n.onfinish=()=>e(),n.oncancel=()=>t(`canceled`)})}fadeOut(){if(this.disposed)throw Error(`Motion instance has been disposed.`);return new Promise((e,t)=>{let n=this.canvas.animate([{opacity:1,transform:`scale(1)`},{opacity:0,transform:`scale(1.2)`}],{duration:300,easing:`ease-in`,fill:`forwards`});n.onfinish=()=>e(),n.oncancel=()=>t(`canceled`)})}checkGLError(e,t){let n=e.getError();if(n!==e.NO_ERROR){for(console.group(`🔴 WebGL Error in ${t}`);n!==e.NO_ERROR;){let t=this.getGLErrorName(e,n);console.error(`${t} (0x${n.toString(16)})`),n=e.getError()}console.groupEnd()}}getGLErrorName(e,t){switch(t){case e.INVALID_ENUM:return`INVALID_ENUM`;case e.INVALID_VALUE:return`INVALID_VALUE`;case e.INVALID_OPERATION:return`INVALID_OPERATION`;case e.INVALID_FRAMEBUFFER_OPERATION:return`INVALID_FRAMEBUFFER_OPERATION`;case e.OUT_OF_MEMORY:return`OUT_OF_MEMORY`;case e.CONTEXT_LOST_WEBGL:return`CONTEXT_LOST_WEBGL`;default:return`UNKNOWN_ERROR`}}setupGL(){let e=this.canvas.getContext(`webgl2`,{antialias:!1,alpha:!0});if(!e)throw Error(`WebGL2 is required but not available.`);let t=createProgram(e,vertexShaderSource,fragmentShaderSource);this.checkGLError(e,`setupGL: after createProgram`);let n=e.createVertexArray();e.bindVertexArray(n),this.checkGLError(e,`setupGL: after VAO creation`);let{positions:r,uvs:i}=computeBorderGeometry(this.canvas.width||2,this.canvas.height||2,this.options.borderWidth,this.options.glowWidth),a=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,a),e.bufferData(e.ARRAY_BUFFER,r,e.STATIC_DRAW);let o=e.getAttribLocation(t,`aPosition`);e.enableVertexAttribArray(o),e.vertexAttribPointer(o,2,e.FLOAT,!1,0,0),this.checkGLError(e,`setupGL: after position buffer setup`);let s=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,s),e.bufferData(e.ARRAY_BUFFER,i,e.STATIC_DRAW);let c=e.getAttribLocation(t,`aUV`);e.enableVertexAttribArray(c),e.vertexAttribPointer(c,2,e.FLOAT,!1,0,0),this.checkGLError(e,`setupGL: after UV buffer setup`);let l=e.getUniformLocation(t,`uResolution`),u=e.getUniformLocation(t,`uTime`),d=e.getUniformLocation(t,`uBorderWidth`),f=e.getUniformLocation(t,`uGlowWidth`),p=e.getUniformLocation(t,`uBorderRadius`),m=e.getUniformLocation(t,`uColors`),h=e.getUniformLocation(t,`uGlowExponent`),g=e.getUniformLocation(t,`uGlowFactor`);e.useProgram(t),e.uniform1f(d,this.options.borderWidth),e.uniform1f(f,this.options.glowWidth),e.uniform1f(p,this.options.borderRadius),this.options.mode===`dark`?(e.uniform1f(h,2),e.uniform1f(g,1.8)):(e.uniform1f(h,1),e.uniform1f(g,1));let _=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let n=0;n<_.length;n++)e.uniform3f(e.getUniformLocation(t,`uColors[${n}]`),..._[n]);this.checkGLError(e,`setupGL: after uniform setup`),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),this.glr={gl:e,program:t,vao:n,positionBuffer:a,uvBuffer:s,uResolution:l,uTime:u,uBorderWidth:d,uGlowWidth:f,uBorderRadius:p,uColors:m}}render(e){if(!this.glr)return;let{gl:t,program:n,vao:r,uTime:i}=this.glr;t.useProgram(n),t.bindVertexArray(r),t.uniform1f(i,e),t.disable(t.DEPTH_TEST),t.disable(t.CULL_FACE),t.disable(t.BLEND),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLES,0,24),this.checkGLError(t,`render: after draw call`),t.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;`)}}}));function isPageDark(){try{return!!(hasDarkModeClass()||hasDarkModeDataAttribute()||isColorSchemeDark()||isBackgroundDark()||isMainContentBackgroundDark()||isTextColorLight())}catch(e){return console.warn(`Error determining if page is dark:`,e),!1}}function hasDarkModeClass(){let e=[`dark`,`dark-mode`,`theme-dark`,`night`,`night-mode`],t=document.documentElement,n=document.body||document.documentElement;for(let r of e)if(t.classList.contains(r)||n?.classList.contains(r))return!0;return!1}function hasDarkModeDataAttribute(){let e=document.documentElement,t=document.body||document.documentElement;for(let n of[`data-theme`,`data-color-mode`,`data-bs-theme`,`data-mui-color-scheme`]){let r=t?.getAttribute(n),i=e.getAttribute(n);if(r?.toLowerCase()===`dark`||i?.toLowerCase()===`dark`)return!0}return!1}function isColorSchemeDark(){let e=document.querySelector(`meta[name="color-scheme"]`)?.content.toLowerCase();if(e===`dark`||e===`only dark`)return!0;let t=window.getComputedStyle(document.documentElement).getPropertyValue(`color-scheme`).trim().toLowerCase();return t===`dark`||t===`only dark`}function isBackgroundDark(){let e=window.getComputedStyle(document.documentElement),t=window.getComputedStyle(document.body||document.documentElement),n=e.backgroundColor,r=t.backgroundColor;return isColorDark(r)?!0:r===`transparent`||r.startsWith(`rgba(0, 0, 0, 0)`)?isColorDark(n):!1}function isTextColorLight(){let e=200,t=getLuminance(window.getComputedStyle(document.body||document.documentElement).color);return t!==null&&t>200}function isMainContentBackgroundDark(){let{innerWidth:e,innerHeight:t}=window,n=e*t*.5;for(let e of[`#app`,`#root`,`#__next`]){let t=document.querySelector(e);if(!t)continue;let r=t.getBoundingClientRect();if(!(r.width*r.height<n)&&isColorDark(window.getComputedStyle(t).backgroundColor))return!0}return!1}function parseRgbColor(e){let t=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(e);return t?{r:parseInt(t[1]),g:parseInt(t[2]),b:parseInt(t[3])}:null}function getLuminance(e){if(!e||e===`transparent`||e.startsWith(`rgba(0, 0, 0, 0)`))return null;let t=parseRgbColor(e);return t?.299*t.r+.587*t.g+.114*t.b:null}function isColorDark(e,t=128){let n=getLuminance(e);return n!==null&&n<t}var init_checkDarkMode=__esmMin((()=>{})),wrapper$1,visible,SimulatorMask_module_default,init_SimulatorMask_module=__esmMin((()=>{wrapper$1=`_wrapper_1ooyb_1`,visible=`_visible_1ooyb_11`,SimulatorMask_module_default={wrapper:wrapper$1,visible}})),cursor,cursorBorder,cursorFilling,cursorRipple,clicking,cursor_module_default,init_cursor_module=__esmMin((()=>{cursor=`_cursor_1dgwb_2`,cursorBorder=`_cursorBorder_1dgwb_10`,cursorFilling=`_cursorFilling_1dgwb_25`,cursorRipple=`_cursorRipple_1dgwb_39`,clicking=`_clicking_1dgwb_57`,cursor_module_default={cursor,cursorBorder,cursorFilling,cursorRipple,clicking,"cursor-ripple":`_cursor-ripple_1dgwb_1`}})),SimulatorMask_exports=__exportAll({SimulatorMask:()=>SimulatorMask}),SimulatorMask,init_SimulatorMask=__esmMin((()=>{init_Motion(),init_checkDarkMode(),init_SimulatorMask_module(),init_cursor_module(),SimulatorMask=class extends EventTarget{shown=!1;wrapper=document.createElement(`div`);motion=null;#e=!1;#t=document.createElement(`div`);#n=0;#r=0;#i=0;#a=0;constructor(){super(),this.wrapper.id=`page-agent-runtime_simulator-mask`,this.wrapper.className=SimulatorMask_module_default.wrapper,this.wrapper.setAttribute(`data-browser-use-ignore`,`true`),this.wrapper.setAttribute(`data-page-agent-ignore`,`true`);try{let e=new Motion({mode:isPageDark()?`dark`:`light`,styles:{position:`absolute`,inset:`0`}});this.motion=e,this.wrapper.appendChild(e.element),e.autoResize(this.wrapper)}catch(e){console.warn(`[SimulatorMask] Motion overlay unavailable:`,e)}this.wrapper.addEventListener(`click`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mousedown`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mouseup`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mousemove`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`wheel`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`keydown`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`keyup`,e=>{e.stopPropagation(),e.preventDefault()}),this.#o(),document.body.appendChild(this.wrapper),this.#s();let e=e=>{let{x:t,y:n}=e.detail;this.setCursorPosition(t,n)},t=()=>{this.triggerClickAnimation()},n=()=>{this.wrapper.style.pointerEvents=`none`},r=()=>{this.wrapper.style.pointerEvents=`auto`};window.addEventListener(`PageAgent::MovePointerTo`,e),window.addEventListener(`PageAgent::ClickPointer`,t),window.addEventListener(`PageAgent::EnablePassThrough`,n),window.addEventListener(`PageAgent::DisablePassThrough`,r),this.addEventListener(`dispose`,()=>{window.removeEventListener(`PageAgent::MovePointerTo`,e),window.removeEventListener(`PageAgent::ClickPointer`,t),window.removeEventListener(`PageAgent::EnablePassThrough`,n),window.removeEventListener(`PageAgent::DisablePassThrough`,r)})}#o(){this.#t.className=cursor_module_default.cursor;let e=document.createElement(`div`);e.className=cursor_module_default.cursorRipple,this.#t.appendChild(e);let t=document.createElement(`div`);t.className=cursor_module_default.cursorFilling,this.#t.appendChild(t);let n=document.createElement(`div`);n.className=cursor_module_default.cursorBorder,this.#t.appendChild(n),this.wrapper.appendChild(this.#t)}#s(){if(this.#e)return;let e=this.#n+(this.#i-this.#n)*.2,t=this.#r+(this.#a-this.#r)*.2,n=Math.abs(e-this.#i);n>0&&(n<2?this.#n=this.#i:this.#n=e,this.#t.style.left=`${this.#n}px`);let r=Math.abs(t-this.#a);r>0&&(r<2?this.#r=this.#a:this.#r=t,this.#t.style.top=`${this.#r}px`),requestAnimationFrame(()=>this.#s())}setCursorPosition(e,t){this.#e||(this.#i=e,this.#a=t)}triggerClickAnimation(){this.#e||(this.#t.classList.remove(cursor_module_default.clicking),this.#t.offsetHeight,this.#t.classList.add(cursor_module_default.clicking))}show(){this.shown||this.#e||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.classList.add(SimulatorMask_module_default.visible),this.#n=window.innerWidth/2,this.#r=window.innerHeight/2,this.#i=this.#n,this.#a=this.#r,this.#t.style.left=`${this.#n}px`,this.#t.style.top=`${this.#r}px`)}hide(){!this.shown||this.#e||(this.shown=!1,this.motion?.fadeOut(),this.motion?.pause(),this.#t.classList.remove(cursor_module_default.clicking),setTimeout(()=>{this.wrapper.classList.remove(SimulatorMask_module_default.visible)},800))}dispose(){this.#e=!0,this.motion?.dispose(),this.wrapper.remove(),this.dispatchEvent(new Event(`dispose`))}}})),PageController=class extends EventTarget{config;flatTree=null;selectorMap=new Map;elementTextMap=new Map;simplifiedHTML=`<EMPTY>`;lastTimeUpdate=0;isIndexed=!1;mask=null;maskReady=null;constructor(e={}){super(),this.config=e,patchReact(this),e.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{let{SimulatorMask:e}=await Promise.resolve().then(()=>(init_SimulatorMask(),SimulatorMask_exports));this.mask=new e})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){let e=window.location.href,t=document.title,n=getPageInfo(),r=resolveViewportExpansion(this.config.viewportExpansion);await this.updateTree();let i=this.simplifiedHTML;return{url:e,title:t,header:`${`Current Page: [${t}](${e})`}\n${`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`}\n\n${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:`}\n\n${n.pixels_above>4&&r!==-1?`... ${n.pixels_above} pixels above (${n.pages_above.toFixed(1)} pages) - scroll to see more ...`:`[Start of page]`}`,content:i,footer:n.pixels_below>4&&r!==-1?`... ${n.pixels_below} pixels below (${n.pages_below.toFixed(1)} pages) - scroll to see more ...`:`[End of page]`}}async updateTree(){this.dispatchEvent(new Event(`beforeUpdate`)),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents=`none`),cleanUpHighlights();let e=[...this.config.interactiveBlacklist||[],...Array.from(document.querySelectorAll(`[data-page-agent-not-interactive]`))];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:e}),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.includeAttributes,this.config.keepSemanticTags),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(){console.log(`[PageController] cleanUpHighlights`),cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw Error(`DOM tree not indexed yet. Can not perform actions on elements.`)}async clickElement(e){try{this.assertIndexed();let t=getElementByIndex(this.selectorMap,e),n=this.elementTextMap.get(e);return await clickElement(t),isAnchorElement(t)&&t.target===`_blank`?{success:!0,message:`✅ Clicked element (${n??e}). ⚠️ Link opened in a new tab.`}:{success:!0,message:`✅ Clicked element (${n??e}).`}}catch(e){return{success:!1,message:`❌ Failed to click element: ${e}`}}}async inputText(e,t){try{this.assertIndexed();let n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return await inputTextElement(n,t),{success:!0,message:`✅ Input text (${t}) into element (${r??e}).`}}catch(e){return{success:!1,message:`❌ Failed to input text: ${e}`}}}async selectOption(e,t){try{this.assertIndexed();let n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return await selectOptionElement(n,t),{success:!0,message:`✅ Selected option (${t}) in element (${r??e}).`}}catch(e){return{success:!1,message:`❌ Failed to select option: ${e}`}}}async scroll(e){try{let{down:t,numPages:n,pixels:r,index:i}=e;return this.assertIndexed(),{success:!0,message:await scrollVertically((r??n*window.innerHeight)*(t?1:-1),i===void 0?null:getElementByIndex(this.selectorMap,i))}}catch(e){return{success:!1,message:`❌ Failed to scroll: ${e}`}}}async scrollHorizontally(e){try{let{right:t,pixels:n,index:r}=e;return this.assertIndexed(),{success:!0,message:await scrollHorizontally(n*(t?1:-1),r===void 0?null:getElementByIndex(this.selectorMap,r))}}catch(e){return{success:!1,message:`❌ Failed to scroll horizontally: ${e}`}}}async executeJavascript(script,signal){try{const asyncFunction=eval(`(async (signal) => { ${script} })`),result=await asyncFunction(signal);return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(e){return{success:!1,message:`❌ Error executing JavaScript: ${e}`}}}async showMask(){await this.maskReady,this.mask?.show()}async hideMask(){await this.maskReady,this.mask?.hide()}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML=`<EMPTY>`,this.isIndexed=!1,this.mask?.dispose(),this.mask=null}},enUS={ui:{panel:{ready:`Ready`,thinking:`Thinking...`,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`,userAnswer:`User answer: {{input}}`,question:`Question: {{question}}`,waitingPlaceholder:`Waiting for task to start...`,stop:`Stop`,close:`Close`,expand:`Expand history`,collapse:`Collapse history`,step:`Step {{number}}`},tools:{clicking:`Clicking element [{{index}}]...`,inputting:`Inputting text to element [{{index}}]...`,selecting:`Selecting option "{{text}}"...`,scrolling:`Scrolling page...`,waiting:`Waiting {{seconds}} seconds...`,askingUser:`Asking user...`,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:`正在思考...`,taskInput:`输入新任务,详细描述步骤,回车提交`,userAnswerPrompt:`请回答上面问题,回车提交`,taskTerminated:`任务已终止`,taskCompleted:`任务结束`,userAnswer:`用户回答: {{input}}`,question:`询问: {{question}}`,waitingPlaceholder:`等待任务开始...`,stop:`终止`,close:`关闭`,expand:`展开历史`,collapse:`收起历史`,step:`步骤 {{number}}`},tools:{clicking:`正在点击元素 [{{index}}]...`,inputting:`正在输入文本到元素 [{{index}}]...`,selecting:`正在选择选项 "{{text}}"...`,scrolling:`正在滚动页面...`,waiting:`等待 {{seconds}} 秒...`,askingUser:`正在询问用户...`,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},I18n=class{language;translations;constructor(e=`en-US`){this.language=e in locales?e:`en-US`,this.translations=locales[this.language]}t(e,t){let n=this.getNestedValue(this.translations,e);return n?t?this.interpolate(n,t):n:(console.warn(`Translation key "${e}" not found for language "${this.language}"`),e)}getNestedValue(e,t){return t.split(`.`).reduce((e,t)=>e?.[t],e)}interpolate(e,t){return e.replace(/\{\{(\w+)\}\}/g,(e,n)=>t[n]==null?e:t[n].toString())}getLanguage(){return this.language}};function truncate(e,t){return e.length>t?e.substring(0,t)+`...`:e}function escapeHtml(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}var wrapper=`_wrapper_1tu05_1`,background=`_background_1tu05_39`,header=`_header_1tu05_99`,pulse=`_pulse_1tu05_1`,retryPulse=`_retryPulse_1tu05_1`,statusTextFadeOut=`_statusTextFadeOut_1tu05_1`,statusTextFadeIn=`_statusTextFadeIn_1tu05_1`,statusSection=`_statusSection_1tu05_121`,indicator=`_indicator_1tu05_128`,thinking=`_thinking_1tu05_137`,tool_executing=`_tool_executing_1tu05_142`,retry=`_retry_1tu05_147`,completed=`_completed_1tu05_153`,input=`_input_1tu05_154`,output=`_output_1tu05_155`,error=`_error_1tu05_160`,statusText=`_statusText_1tu05_166`,fadeOut=`_fadeOut_1tu05_178`,fadeIn=`_fadeIn_1tu05_182`,controls=`_controls_1tu05_188`,controlButton=`_controlButton_1tu05_193`,stopButton=`_stopButton_1tu05_212`,historySectionWrapper=`_historySectionWrapper_1tu05_246`,shimmer=`_shimmer_1tu05_1`,celebrate=`_celebrate_1tu05_1`,expanded=`_expanded_1tu05_278`,historySection=`_historySection_1tu05_246`,historyItem=`_historyItem_1tu05_297`,observation=`_observation_1tu05_355`,question=`_question_1tu05_360`,doneSuccess=`_doneSuccess_1tu05_366`,historyContent=`_historyContent_1tu05_402`,statusIcon=`_statusIcon_1tu05_403`,doneError=`_doneError_1tu05_412`,reflectionLines=`_reflectionLines_1tu05_462`,historyMeta=`_historyMeta_1tu05_469`,inputSectionWrapper=`_inputSectionWrapper_1tu05_539`,hidden=`_hidden_1tu05_562`,inputSection=`_inputSection_1tu05_539`,taskInput=`_taskInput_1tu05_573`,Panel_module_default={wrapper,"mask-running":`_mask-running_1tu05_1`,background,header,pulse,retryPulse,statusTextFadeOut,statusTextFadeIn,statusSection,indicator,thinking,tool_executing,retry,completed,input,output,error,statusText,fadeOut,fadeIn,controls,controlButton,stopButton,historySectionWrapper,shimmer,celebrate,expanded,historySection,historyItem,observation,question,doneSuccess,historyContent,statusIcon,doneError,reflectionLines,historyMeta,inputSectionWrapper,hidden,inputSection,taskInput};function createCard({icon:e,content:t,meta:n,type:r}){let i=r?Panel_module_default[r]:``,a=Array.isArray(t)?`<div class="${Panel_module_default.reflectionLines}">${t.map(e=>`<span>${escapeHtml(e)}</span>`).join(``)}</div>`:`<span>${escapeHtml(t)}</span>`;return`
|
|
359
358
|
<div class="${Panel_module_default.historyItem} ${i}">
|
|
360
359
|
<div class="${Panel_module_default.historyContent}">
|
|
361
360
|
<span class="${Panel_module_default.statusIcon}">${e}</span>
|
|
@@ -363,7 +362,7 @@ gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
|
363
362
|
</div>
|
|
364
363
|
${n?`<div class="${Panel_module_default.historyMeta}">${n}</div>`:``}
|
|
365
364
|
</div>
|
|
366
|
-
`}function createReflectionLines(e){let t=[];return e.evaluation_previous_goal&&t.push(`🔍 ${e.evaluation_previous_goal}`),e.memory&&t.push(`💾 ${e.memory}`),e.next_goal&&t.push(`🎯 ${e.next_goal}`),t}var Panel=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u=!1;#d;#f=null;#p=!1;#m=null;#h=null;#g=!1;#_=()=>this.#x();#v=()=>this.#S();#y=e=>this.#C(e.detail);#b=()=>this.dispose();get wrapper(){return this.#e}constructor(e,t={}){this.#c=e,this.#l=t,this.#d=new I18n(t.language??`en-US`),this.#c.onAskUser=(e,t)=>this.#w(e,t?.signal),this.#e=this.#N(),this.#t=this.#e.querySelector(`.${Panel_module_default.indicator}`),this.#n=this.#e.querySelector(`.${Panel_module_default.statusText}`),this.#r=this.#e.querySelector(`.${Panel_module_default.historySection}`),this.#i=this.#e.querySelector(`.${Panel_module_default.expandButton}`),this.#a=this.#e.querySelector(`.${Panel_module_default.stopButton}`),this.#o=this.#e.querySelector(`.${Panel_module_default.inputSectionWrapper}`),this.#s=this.#e.querySelector(`.${Panel_module_default.taskInput}`),this.#c.addEventListener(`statuschange`,this.#_),this.#c.addEventListener(`historychange`,this.#v),this.#c.addEventListener(`activity`,this.#y),this.#c.addEventListener(`dispose`,this.#b),this.#P(),this.#R(),this.#A(),this.hide()}#x(){let e=this.#c.status,t=e===`
|
|
365
|
+
`}function createReflectionLines(e){let t=[];return e.evaluation_previous_goal&&t.push(`🔍 ${e.evaluation_previous_goal}`),e.memory&&t.push(`💾 ${e.memory}`),e.next_goal&&t.push(`🎯 ${e.next_goal}`),t}var Panel=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u=!1;#d;#f=null;#p=!1;#m=null;#h=null;#g=!1;#_=()=>this.#x();#v=()=>this.#S();#y=e=>this.#C(e.detail);#b=()=>this.dispose();get wrapper(){return this.#e}constructor(e,t={}){this.#c=e,this.#l=t,this.#d=new I18n(t.language??`en-US`),this.#c.onAskUser=(e,t)=>this.#w(e,t?.signal),this.#e=this.#N(),this.#t=this.#e.querySelector(`.${Panel_module_default.indicator}`),this.#n=this.#e.querySelector(`.${Panel_module_default.statusText}`),this.#r=this.#e.querySelector(`.${Panel_module_default.historySection}`),this.#i=this.#e.querySelector(`.${Panel_module_default.expandButton}`),this.#a=this.#e.querySelector(`.${Panel_module_default.stopButton}`),this.#o=this.#e.querySelector(`.${Panel_module_default.inputSectionWrapper}`),this.#s=this.#e.querySelector(`.${Panel_module_default.taskInput}`),this.#c.addEventListener(`statuschange`,this.#_),this.#c.addEventListener(`historychange`,this.#v),this.#c.addEventListener(`activity`,this.#y),this.#c.addEventListener(`dispose`,this.#b),this.#P(),this.#R(),this.#A(),this.hide()}#x(){let e=this.#c.status,t=e===`completed`&&this.#c.lastResult?.success===!1;this.#H(t?`error`:e),e===`running`?(this.#a.textContent=`■`,this.#a.title=this.#d.t(`ui.panel.stop`)):(this.#a.textContent=`X`,this.#a.title=this.#d.t(`ui.panel.close`)),e===`running`&&(this.show(),this.#j()),(e===`completed`||e===`error`||e===`stopped`)&&(this.#u||this.#I(),this.#M()&&this.#A())}#S(){this.#W()}#C(e){switch(e.type){case`thinking`:this.#h=this.#d.t(`ui.panel.thinking`),this.#H(`thinking`);break;case`executing`:this.#h=this.#E(e.tool,e.input),this.#H(`executing`);break;case`executed`:this.#h=truncate(e.output,50);break;case`retrying`:this.#h=`Retrying (${e.attempt}/${e.maxAttempts})`,this.#H(`retrying`);break;case`error`:this.#h=truncate(e.message,50),this.#H(`error`);break}}#w(e,t){return new Promise((n,r)=>{this.#p=!0,this.#f=n,this.#u||this.#I();let i=document.createElement(`div`);i.innerHTML=createCard({icon:`❓`,content:`Question: ${e}`,type:`question`});let a=i.firstElementChild;a.setAttribute(`data-temp-card`,`true`),this.#r.appendChild(a),this.#U(),this.#A(this.#d.t(`ui.panel.userAnswerPrompt`)),t?.addEventListener(`abort`,()=>{this.#T(),this.#p=!1,this.#f=null,r(t.reason)},{once:!0})})}#T(){Array.from(this.#r.children).forEach(e=>{e.getAttribute(`data-temp-card`)===`true`&&e.remove()})}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(){this.#n.textContent=this.#d.t(`ui.panel.ready`),this.#H(`thinking`),this.#W(),this.#L(),this.#p=!1,this.#f=null,this.#A()}expand(){this.#I()}collapse(){this.#L()}dispose(){this.#c.removeEventListener(`statuschange`,this.#_),this.#c.removeEventListener(`historychange`,this.#v),this.#c.removeEventListener(`activity`,this.#y),this.#c.removeEventListener(`dispose`,this.#b),this.#p=!1,this.#z(),this.wrapper.remove()}#E(e,t){let n=t;switch(e){case`click_element_by_index`:return this.#d.t(`ui.tools.clicking`,{index:n.index});case`input_text`:return this.#d.t(`ui.tools.inputting`,{index:n.index});case`select_dropdown_option`:return this.#d.t(`ui.tools.selecting`,{text:n.text});case`scroll`:return this.#d.t(`ui.tools.scrolling`);case`wait`:return this.#d.t(`ui.tools.waiting`,{seconds:n.seconds});case`ask_user`:return this.#d.t(`ui.tools.askingUser`);case`done`:return this.#d.t(`ui.tools.done`);default:return this.#d.t(`ui.tools.executing`,{toolName:e})}}#D(){this.#c.status===`running`?this.#c.stop():this.#c.dispose()}#O(){let e=this.#s.value.trim();e&&(this.#j(),this.#p?this.#k(e):this.#c.execute(e))}#k(e){this.#T(),this.#p=!1,this.#f&&=(this.#f(e),null)}#A(e){this.#s.value=``,this.#s.placeholder=e||this.#d.t(`ui.panel.taskInput`),this.#o.classList.remove(Panel_module_default.hidden),setTimeout(()=>{this.#s.focus()},100)}#j(){this.#o.classList.add(Panel_module_default.hidden)}#M(){if(this.#p||this.#c.history.length===0)return!0;let e=this.#c.status;return e===`completed`||e===`error`||e===`stopped`?this.#l.promptForNextTask??!0:!1}#N(){let e=1e3,t=document.createElement(`div`);return t.id=`page-agent-runtime_agent-panel`,t.className=Panel_module_default.wrapper,t.setAttribute(`data-browser-use-ignore`,`true`),t.setAttribute(`data-page-agent-ignore`,`true`),t.innerHTML=`
|
|
367
366
|
<div class="${Panel_module_default.background}"></div>
|
|
368
367
|
<div class="${Panel_module_default.historySectionWrapper}">
|
|
369
368
|
<div class="${Panel_module_default.historySection}">
|
|
@@ -398,4 +397,4 @@ gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
|
398
397
|
/>
|
|
399
398
|
</div>
|
|
400
399
|
</div>
|
|
401
|
-
`,document.body.appendChild(t),t}#P(){this.wrapper.querySelector(`.${Panel_module_default.header}`).addEventListener(`click`,e=>{e.target.closest(`.${Panel_module_default.controlButton}`)||this.#F()}),this.#i.addEventListener(`click`,e=>{e.stopPropagation(),this.#F()}),this.#a.addEventListener(`click`,e=>{e.stopPropagation(),this.#D()}),this.#s.addEventListener(`keydown`,e=>{e.isComposing||e.key===`Enter`&&(e.preventDefault(),this.#O())}),this.#o.addEventListener(`click`,e=>{e.stopPropagation()})}#F(){this.#u?this.#L():this.#I()}#I(){this.#u=!0,this.wrapper.classList.add(Panel_module_default.expanded),this.#i.textContent=`▲`}#L(){this.#u=!1,this.wrapper.classList.remove(Panel_module_default.expanded),this.#i.textContent=`▼`}#R(){this.#m=setInterval(()=>{this.#B()},450)}#z(){this.#m&&=(clearInterval(this.#m),null)}#B(){if(!this.#h||this.#g)return;if(this.#n.textContent===this.#h){this.#h=null;return}let e=this.#h;this.#h=null,this.#V(e)}#V(e){this.#g=!0,this.#n.classList.add(Panel_module_default.fadeOut),setTimeout(()=>{this.#n.textContent=e,this.#n.classList.remove(Panel_module_default.fadeOut),this.#n.classList.add(Panel_module_default.fadeIn),setTimeout(()=>{this.#n.classList.remove(Panel_module_default.fadeIn),this.#g=!1},300)},150)}#H(e){this.#t.className=Panel_module_default.indicator,this.#t.classList.add(Panel_module_default[
|
|
400
|
+
`,document.body.appendChild(t),t}#P(){this.wrapper.querySelector(`.${Panel_module_default.header}`).addEventListener(`click`,e=>{e.target.closest(`.${Panel_module_default.controlButton}`)||this.#F()}),this.#i.addEventListener(`click`,e=>{e.stopPropagation(),this.#F()}),this.#a.addEventListener(`click`,e=>{e.stopPropagation(),this.#D()}),this.#s.addEventListener(`keydown`,e=>{e.isComposing||e.key===`Enter`&&(e.preventDefault(),this.#O())}),this.#o.addEventListener(`click`,e=>{e.stopPropagation()})}#F(){this.#u?this.#L():this.#I()}#I(){this.#u=!0,this.wrapper.classList.add(Panel_module_default.expanded),this.#i.textContent=`▲`}#L(){this.#u=!1,this.wrapper.classList.remove(Panel_module_default.expanded),this.#i.textContent=`▼`}#R(){this.#m=setInterval(()=>{this.#B()},450)}#z(){this.#m&&=(clearInterval(this.#m),null)}#B(){if(!this.#h||this.#g)return;if(this.#n.textContent===this.#h){this.#h=null;return}let e=this.#h;this.#h=null,this.#V(e)}#V(e){this.#g=!0,this.#n.classList.add(Panel_module_default.fadeOut),setTimeout(()=>{this.#n.textContent=e,this.#n.classList.remove(Panel_module_default.fadeOut),this.#n.classList.add(Panel_module_default.fadeIn),setTimeout(()=>{this.#n.classList.remove(Panel_module_default.fadeIn),this.#g=!1},300)},150)}#H(e){let t=e===`running`?`thinking`:e;this.#t.className=Panel_module_default.indicator,t!==`idle`&&t!==`stopped`&&this.#t.classList.add(Panel_module_default[t])}#U(){setTimeout(()=>{this.#r.scrollTop=this.#r.scrollHeight},0)}#W(){let e=[],t=this.#c.task;t&&e.push(this.#G(t));let n=this.#c.history;for(let t of n)e.push(...this.#K(t));this.#r.innerHTML=e.join(``),this.#U()}#G(e){return createCard({icon:`🎯`,content:e,type:`input`})}#K(e){let t=[],n=e.type===`step`&&e.stepIndex!==void 0?this.#d.t(`ui.panel.step`,{number:(e.stepIndex+1).toString()}):void 0;if(e.type===`step`){if(e.reflection){let r=createReflectionLines(e.reflection);r.length>0&&t.push(createCard({icon:`🧠`,content:r,meta:n}))}let r=e.action;r&&t.push(...this.#q(r,n))}else if(e.type===`observation`)t.push(createCard({icon:`👁️`,content:e.content||``,meta:n,type:`observation`}));else if(e.type===`user_takeover`)t.push(createCard({icon:`👤`,content:`User takeover`,meta:n,type:`input`}));else if(e.type===`retry`){let r=`${e.message||`Retrying`} (${e.attempt}/${e.maxAttempts})`;t.push(createCard({icon:`🔄`,content:r,meta:n,type:`observation`}))}else e.type===`error`&&t.push(createCard({icon:`❌`,content:e.message||`Error`,meta:n,type:`observation`}));return t}#q(e,t){let n=[];if(e.name===`done`){let r=e.input.text||e.output||``;r&&n.push(createCard({icon:`🤖`,content:r,meta:t,type:`output`}))}else if(e.name===`ask_user`){let r=e.input,i=e.output.replace(/^User answered:\s*/i,``);n.push(createCard({icon:`❓`,content:`Question: ${r.question||``}`,meta:t,type:`question`})),n.push(createCard({icon:`💬`,content:`Answer: ${i}`,meta:t,type:`input`}))}else{let r=this.#E(e.name,e.input);n.push(createCard({icon:`🔨`,content:r,meta:t})),e.output?.length>0&&n.push(createCard({icon:`🔨`,content:e.output,meta:t,type:`output`}))}return n}},PageAgent=class extends PageAgentCore{panel;constructor(e){let t=new PageController({...e,enableMask:e.enableMask??!0});super({...e,pageController:t}),this.panel=new Panel(this,{language:e.language,promptForNextTask:e.promptForNextTask})}},currentScript=document.currentScript,currentScriptURL=currentScript?.src?new URL(currentScript.src):null,autoInit=currentScriptURL?.searchParams.get(`autoInit`)!==`false`;autoInit&&window.pageAgent&&window.pageAgent.dispose(),window.PageAgent=PageAgent,console.log(`🚀 page-agent.js loaded!`);var DEMO_MODEL=`qwen3.5-plus`,DEMO_BASE_URL=`https://page-ag-testing-ohftxirgbn.cn-shanghai.fcapp.run`,DEMO_API_KEY=`NA`;autoInit&&setTimeout(()=>{let e,t=!0;if(currentScriptURL){let n=currentScriptURL,r=n.searchParams.get(`model`)||DEMO_MODEL,i=n.searchParams.get(`baseURL`)||DEMO_BASE_URL,a=n.searchParams.get(`apiKey`)||DEMO_API_KEY,o=n.searchParams.get(`lang`)||`zh-CN`;t=(n.searchParams.get(`showPanel`)||`true`)===`true`,e={model:r,baseURL:i,apiKey:a,language:o}}else console.log(`🚀 page-agent.js no current script detected, using default demo config`),e={model:DEMO_MODEL,baseURL:DEMO_BASE_URL,apiKey:DEMO_API_KEY};window.pageAgent=new PageAgent(e),t&&window.pageAgent.panel.show(),console.log(`🚀 page-agent.js initialized with config:`,window.pageAgent.config)})})();
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "page-agent",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "1.9.
|
|
4
|
+
"version": "1.9.1",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/esm/page-agent.js",
|
|
7
7
|
"types": "./dist/esm/PageAgent.d.ts",
|
|
@@ -43,10 +43,10 @@
|
|
|
43
43
|
"postpublish": "node ../../scripts/post-publish.js"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@page-agent/core": "1.9.
|
|
47
|
-
"@page-agent/llms": "1.9.
|
|
48
|
-
"@page-agent/page-controller": "1.9.
|
|
49
|
-
"@page-agent/ui": "1.9.
|
|
46
|
+
"@page-agent/core": "1.9.1",
|
|
47
|
+
"@page-agent/llms": "1.9.1",
|
|
48
|
+
"@page-agent/page-controller": "1.9.1",
|
|
49
|
+
"@page-agent/ui": "1.9.1",
|
|
50
50
|
"chalk": "^5.6.2"
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|