@nostop/page 0.1.0-rc.5 → 0.1.0-rc.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/page-agent.js +631 -170
- package/dist/esm/page-agent.js.map +1 -1
- package/dist/iife/page-agent.demo.js +23 -19
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"page-agent.js","names":[],"sources":["../../../llms/src/errors.ts","../../../llms/src/utils.ts","../../../llms/src/OpenAIClient.ts","../../../llms/src/index.ts","../../../core/src/skills/files.ts","../../../core/src/utils/autoFixer.ts","../../../core/src/utils/index.ts","../../../core/src/tools/index.ts","../../../core/src/skills/types.ts","../../../core/src/skills/parse.ts","../../../core/src/skills/runtime.ts","../../../core/src/skills/storage.ts","../../../core/src/skills/host.ts","../../../core/src/skills/recorder.ts","../../../core/src/skills/synthesize.ts","../../../core/src/skills/watcher.ts","../../../core/src/PageAgentCore.ts","../../../page-controller/src/utils/index.ts","../../../page-controller/src/actions.ts","../../../page-controller/src/ax/domPath.ts","../../../page-controller/src/ax/evidence.ts","../../../page-controller/src/ax/errors.ts","../../../page-controller/src/ax/format.ts","../../../page-controller/src/ax/ids.ts","../../../page-controller/src/ax/observation.ts","../../../page-controller/src/ax/AccessibilityController.ts","../../../page-controller/src/dom/dom_tree/index.js","../../../page-controller/src/dom/index.ts","../../../page-controller/src/dom/getPageInfo.ts","../../../page-controller/src/patches/react.ts","../../../page-controller/src/scriptAccess.ts","../../../page-controller/src/scriptResult.ts","../../../page-controller/src/stateFreshness.ts","../../../page-controller/src/surfaceIndexes.ts","../../../page-controller/src/PageController.ts","../../../ui/src/i18n/locales.ts","../../../ui/src/i18n/index.ts","../../../ui/src/voice/realtime-protocol.ts","../../../ui/src/voice/gemini-protocol.ts","../../../ui/src/voice/gemini-client.ts","../../../ui/src/voice/realtime-client.ts","../../../ui/src/voice/voice-prompt.ts","../../../ui/src/voice/voice-session.ts","../../../ui/src/utils.ts","../../../ui/src/panel/Panel.module.css","../../../ui/src/panel/fold.ts","../../../ui/src/panel/icons.ts","../../../ui/src/panel/highlight.ts","../../../ui/src/panel/scriptCard.ts","../../../ui/src/panel/toolVisual.ts","../../../ui/src/panel/feed.ts","../../../ui/src/panel/microphone.ts","../../../ui/src/panel/recovery.ts","../../../ui/src/panel/trace.ts","../../../ui/src/panel/voiceRuns.ts","../../../ui/src/panel/Panel.ts","../../src/PageAgent.ts"],"sourcesContent":["/**\n * Error types and error handling for LLM invocations.\n */\n\nexport const InvokeErrorTypes = {\n\t// Retryable\n\tNETWORK_ERROR: 'network_error', // Network error, retry\n\tRATE_LIMIT: 'rate_limit', // Rate limit, retry\n\tSERVER_ERROR: 'server_error', // 5xx, retry\n\tNO_TOOL_CALL: 'no_tool_call', // Model did not call tool\n\tINVALID_TOOL_ARGS: 'invalid_tool_args', // Tool args don't match schema\n\tTOOL_EXECUTION_ERROR: 'tool_execution_error', // Tool execution error\n\tINVALID_RESPONSE: 'invalid_response', // Response body is not valid JSON\n\tINVALID_SCHEMA: 'invalid_schema', // Response is valid JSON but doesn't match expected shape\n\n\tUNKNOWN: 'unknown',\n\n\t// Non-retryable\n\tCONFIG_ERROR: 'config_error', // Invalid local configuration or hook\n\tAUTH_ERROR: 'auth_error', // Authentication failed\n\tCONTEXT_LENGTH: 'context_length', // Prompt too long\n\tCONTENT_FILTER: 'content_filter', // Content filtered\n} as const\n\ntype InvokeErrorType = (typeof InvokeErrorTypes)[keyof typeof InvokeErrorTypes]\n\nconst RETRYABLE_TYPES: readonly InvokeErrorType[] = [\n\tInvokeErrorTypes.NETWORK_ERROR,\n\tInvokeErrorTypes.RATE_LIMIT,\n\tInvokeErrorTypes.SERVER_ERROR,\n\tInvokeErrorTypes.NO_TOOL_CALL,\n\tInvokeErrorTypes.INVALID_TOOL_ARGS,\n\tInvokeErrorTypes.TOOL_EXECUTION_ERROR,\n\tInvokeErrorTypes.INVALID_RESPONSE,\n\tInvokeErrorTypes.INVALID_SCHEMA,\n\tInvokeErrorTypes.UNKNOWN,\n]\n\nexport class InvokeError extends Error {\n\ttype: InvokeErrorType\n\tretryable: boolean\n\tstatusCode?: number\n\t/* raw error (provided if this error is caused by another error) */\n\trawError?: unknown\n\t/* raw response from the API (provided if this error is caused by an API calling) */\n\trawResponse?: unknown\n\n\tconstructor(type: InvokeErrorType, message: string, rawError?: unknown, rawResponse?: unknown) {\n\t\tsuper(message)\n\t\tthis.name = 'InvokeError'\n\t\tthis.type = type\n\t\tthis.retryable = RETRYABLE_TYPES.includes(type)\n\t\tthis.rawError = rawError\n\t\tthis.rawResponse = rawResponse\n\t}\n}\n","/**\n * Utility functions for LLM integration\n */\nimport chalk from 'chalk'\nimport * as z from 'zod/v4'\n\nimport type { Tool } from './types'\n\nfunction debug(...args: unknown[]) {\n\tconsole.debug(chalk.gray('[LLM]'), ...args)\n}\n\n/**\n * Convert Zod schema to OpenAI tool format\n * Uses Zod 4 native z.toJSONSchema()\n */\nexport function zodToOpenAITool(name: string, tool: Tool) {\n\treturn {\n\t\ttype: 'function' as const,\n\t\tfunction: {\n\t\t\tname,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: z.toJSONSchema(tool.inputSchema, { target: 'openapi-3.0' }),\n\t\t},\n\t}\n}\n\n/**\n * Patch model specific parameters. Only patches known models.\n *\n * @purpose\n * - Reconcile the differences in the parameter schema each model accepts.\n * - Disable thinking/reasoning, or lower it to the minimum where a full disable is impossible.\n * - Minimize returned tokens.\n * - Raise temperature for known smaller models to improve auto-recovery odds.\n * @note Honor temperature if explicitly set by the user\n *\n * @todo Need vendor-specific patches.\n * Local and 3rd-party hosted models may have different schema.\n */\nexport function modelPatch(body: Record<string, any>, baseURL?: string) {\n\tconst model: string = body.model || ''\n\tif (!model) return body\n\n\tconst provider = getProvider(baseURL)\n\n\tconst modelName = normalizeModelName(model)\n\n\tif (modelName.startsWith('qwen')) {\n\t\tif (provider === 'openrouter' && modelName.startsWith('qwen38-max')) {\n\t\t\t// OpenRouter forces thinking on for this endpoint, and Qwen rejects tool_choice in thinking mode\n\t\t\tdebug('Patch Qwen3.8-max on OpenRouter: reasoning_effort=low, remove tool_choice')\n\t\t\tbody.reasoning_effort = 'low'\n\t\t\tdelete body.tool_choice\n\t\t} else {\n\t\t\tdebug('Patch Qwen: disable thinking')\n\t\t\tbody.enable_thinking = false\n\t\t}\n\t\tif (body.temperature === undefined && !/max|plus/.test(modelName)) {\n\t\t\tdebug('Patch Qwen: raise temperature to 1.0')\n\t\t\tbody.temperature = 1.0\n\t\t}\n\t}\n\n\tif (modelName.startsWith('deepseek')) {\n\t\tdebug('Patch DeepSeek: disable thinking, remove tool_choice')\n\t\tbody.thinking = { type: 'disabled' }\n\t\tdelete body.tool_choice\n\t}\n\n\tif (modelName.startsWith('gpt')) {\n\t\tif (modelName.startsWith('gpt-5')) {\n\t\t\tbody.verbosity = 'low'\n\t\t}\n\n\t\t// Since gpt-5.4, /chat/completions rejects any explicit reasoning_effort\n\t\t// when function tools are present. Newer models are expected to follow.\n\t\t// - gpt-5.1 / gpt-5.2 can fully disable reasoning\n\t\t// - gpt-5 / -mini / -nano bottom out at \"minimal\"\n\t\t// - everything else (gpt-4.x, chat-latest, gpt-5.4+) must not receive it\n\t\tif (modelName.includes('chat-latest')) {\n\t\t\tdebug('Patch chat-latest: omit reasoning_effort and temperature')\n\t\t\tdelete body.reasoning_effort\n\t\t\tdelete body.temperature\n\t\t} else if (/^gpt-5[12](-|$)/.test(modelName)) {\n\t\t\tdebug('Patch GPT-5.1/5.2: reasoning_effort=none')\n\t\t\tbody.reasoning_effort = 'none'\n\t\t} else if (/^gpt-5(-|$)/.test(modelName)) {\n\t\t\tdebug('Patch GPT-5: reasoning_effort=minimal')\n\t\t\tbody.reasoning_effort = 'minimal'\n\t\t} else {\n\t\t\tdebug('Patch GPT: omit reasoning_effort')\n\t\t\tdelete body.reasoning_effort\n\t\t}\n\t}\n\n\tif (modelName.startsWith('claude')) {\n\t\tif (/opus|sonnet|haiku/.test(modelName)) {\n\t\t\tdebug('Patch Claude: disable thinking')\n\t\t\tbody.thinking = { type: 'disabled' }\n\n\t\t\tif (provider !== 'openrouter') {\n\t\t\t\t// Convert tool_choice to Claude format\n\t\t\t\tif (body.tool_choice === 'required') {\n\t\t\t\t\t// 'required' -> { type: 'any' } (must call some tool)\n\t\t\t\t\tdebug('Applying Claude patch: convert tool_choice \"required\" to { type: \"any\" }')\n\t\t\t\t\tbody.tool_choice = { type: 'any' }\n\t\t\t\t} else if (body.tool_choice?.function?.name) {\n\t\t\t\t\t// { type: 'function', function: { name: '...' } } -> { type: 'tool', name: '...' }\n\t\t\t\t\tdebug('Applying Claude patch: convert tool_choice format')\n\t\t\t\t\tbody.tool_choice = { type: 'tool', name: body.tool_choice.function.name }\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tdebug('Patch Claude: reasoning_effort=low')\n\t\t\tbody.reasoning_effort = 'low'\n\n\t\t\t// Fable and mythos can not disable adaptive thinking.\n\t\t\t// Claude does not support tool_choice with extended thinking.\n\t\t\t// These 2 concepts are blurred. Basically no tool_choice with thinking.\n\t\t\tdelete body.tool_choice\n\t\t}\n\t}\n\n\tif (modelName.startsWith('gemini')) {\n\t\tdebug('Patch Gemini: reasoning_effort=low')\n\t\tbody.reasoning_effort = 'low'\n\t\tif (/^gemini-25(?!.*pro)/.test(modelName)) {\n\t\t\tdebug('Patch Gemini 2.5 non-Pro: reasoning_effort=none')\n\t\t\tbody.reasoning_effort = 'none'\n\t\t} else if (\n\t\t\tmodelName.startsWith('gemini-35-flash') ||\n\t\t\tmodelName.startsWith('gemini-31-flash-lite') ||\n\t\t\tmodelName.startsWith('gemini-3-flash')\n\t\t) {\n\t\t\tdebug('Patch Gemini 3.x Flash/Lite: reasoning_effort=minimal')\n\t\t\tbody.reasoning_effort = 'minimal'\n\t\t}\n\t}\n\n\tif (modelName.startsWith('glm')) {\n\t\tif (/^glm-5[3-9]/.test(modelName)) {\n\t\t\t// GLM 5.3+ cannot disable thinking\n\t\t\tdebug('Patch GLM 5.3+: reasoning_effort=low')\n\t\t\tbody.reasoning_effort = 'low'\n\t\t} else {\n\t\t\tdebug('Patch GLM: disable thinking')\n\t\t\tbody.thinking = { type: 'disabled' }\n\t\t}\n\t}\n\n\tif (modelName.startsWith('hy')) {\n\t\tdebug('Patch Hunyuan: disable thinking, reasoning_effort=low')\n\t\tbody.thinking = { type: 'disabled' }\n\t\tbody.reasoning_effort = 'low'\n\t}\n\n\tif (modelName.startsWith('grok')) {\n\t\tif (/^grok-4-?3/.test(modelName)) {\n\t\t\tdebug('Patch Grok 4.3: reasoning_effort=none')\n\t\t\tbody.reasoning_effort = 'none'\n\t\t} else if (modelName.startsWith('grok-3-mini') || modelName.startsWith('grok-code-fast')) {\n\t\t\tdebug('Patch Grok mini/code: reasoning_effort=low')\n\t\t\tbody.reasoning_effort = 'low'\n\t\t}\n\t}\n\n\tif (modelName.startsWith('kimi')) {\n\t\tif (modelName.startsWith('kimi-k3')) {\n\t\t\t// Kimi K3 always thinks and rejects named tool choice while thinking.\n\t\t\tdebug('Patch Kimi K3: use required tool choice, remove parallel tool calls')\n\t\t\tdelete body.parallel_tool_calls\n\t\t\tif (body.tool_choice?.function?.name) body.tool_choice = 'required'\n\t\t} else if (!modelName.includes('code')) {\n\t\t\t// kimi-k2.7-code cannot disable thinking\n\t\t\tdebug('Patch Kimi: disable thinking')\n\t\t\tbody.thinking = { type: 'disabled' }\n\t\t}\n\t}\n\n\tif (modelName.startsWith('minimax')) {\n\t\tdebug('Patch MiniMax: remove parallel_tool_calls')\n\t\tdelete body.parallel_tool_calls\n\n\t\tif (modelName.includes('m3')) {\n\t\t\t// Only M3 can disable thinking\n\t\t\tdebug('Patch MiniMax: disable thinking')\n\t\t\tbody.thinking = { type: 'disabled' }\n\t\t}\n\t}\n\n\t// provider patches\n\n\tif (provider === 'openrouter') {\n\t\t// openrouter use reasoning object instead of reasoning_effort\n\n\t\tconst reasoningEffort = body.reasoning_effort\n\t\tconst reasoningDisabled =\n\t\t\tbody.thinking?.type === 'disabled' ||\n\t\t\tbody.enable_thinking === false ||\n\t\t\treasoningEffort === 'none'\n\n\t\tif (reasoningDisabled) {\n\t\t\tbody.reasoning = { enabled: false }\n\t\t} else if (reasoningEffort) {\n\t\t\tbody.reasoning = { enabled: true, effort: reasoningEffort }\n\t\t}\n\t}\n\n\treturn body\n}\n\n/**\n * check if a given model ID fits a specific model name\n *\n * @note\n * Different model providers may use different model IDs for the same model.\n * For example, openai's `gpt-5.2` may called:\n *\n * - `gpt-5.2-version`\n * - `gpt-5_2-date`\n * - `GPT-52-version-date`\n * - `openai/gpt-5.2-chat`\n *\n * They should be treated as the same model.\n * Normalize them to `gpt-52`\n */\nexport function normalizeModelName(modelName: string): string {\n\tlet normalizedName = modelName.toLowerCase()\n\n\t// remove prefix before '/'\n\tif (normalizedName.includes('/')) {\n\t\tnormalizedName = normalizedName.split('/')[1]\n\t}\n\n\t// remove '_'\n\tnormalizedName = normalizedName.replace(/_/g, '')\n\n\t// remove '.'\n\tnormalizedName = normalizedName.replace(/\\./g, '')\n\n\treturn normalizedName\n}\n\nexport function getProvider(baseURL?: string): 'openrouter' | undefined {\n\tif (!baseURL) return undefined\n\ttry {\n\t\tconst url = new URL(baseURL)\n\t\tconst hostname = url.hostname\n\t\tif (hostname === 'openrouter.ai') return 'openrouter'\n\t\treturn undefined\n\t} catch (e) {\n\t\treturn undefined\n\t}\n}\n","/**\n * OpenAI Client implementation\n */\nimport * as z from 'zod/v4'\n\nimport { InvokeError, InvokeErrorTypes } from './errors'\nimport type {\n\tInvokeOptions,\n\tInvokeResult,\n\tLLMClient,\n\tMessage,\n\tResolvedLLMConfig,\n\tTool,\n} from './types'\nimport { modelPatch, zodToOpenAITool } from './utils'\n\n/**\n * Client for OpenAI compatible APIs\n */\nexport class OpenAIClient implements LLMClient {\n\tconfig: ResolvedLLMConfig\n\tprivate fetch: typeof globalThis.fetch\n\n\tconstructor(config: ResolvedLLMConfig) {\n\t\tthis.config = config\n\t\tthis.fetch = config.customFetch\n\t}\n\n\tasync invoke(\n\t\tmessages: Message[],\n\t\ttools: Record<string, Tool>,\n\t\tabortSignal?: AbortSignal,\n\t\toptions?: InvokeOptions\n\t): Promise<InvokeResult> {\n\t\tabortSignal?.throwIfAborted()\n\n\t\t// 1. Convert tools to OpenAI format\n\t\tconst openaiTools = Object.entries(tools).map(([name, t]) => zodToOpenAITool(name, t))\n\n\t\t// Build request body\n\n\t\tlet toolChoice: unknown = 'required'\n\t\tif (options?.toolChoiceName && !this.config.disableNamedToolChoice) {\n\t\t\ttoolChoice = { type: 'function', function: { name: options.toolChoiceName } }\n\t\t}\n\n\t\tconst requestBody: Record<string, unknown> = {\n\t\t\tmodel: this.config.model,\n\t\t\tmessages,\n\t\t\ttools: openaiTools,\n\t\t\tparallel_tool_calls: false,\n\t\t\ttool_choice: toolChoice,\n\t\t}\n\t\t// Only sent if the caller explicitly set it. Most new models throw if this is set.\n\t\tif (this.config.temperature !== undefined) {\n\t\t\trequestBody.temperature = this.config.temperature\n\t\t}\n\n\t\tmodelPatch(requestBody, this.config.baseURL)\n\n\t\tlet transformedBody: Record<string, unknown> | undefined\n\t\ttry {\n\t\t\ttransformedBody = this.config.transformRequestBody(requestBody)\n\t\t} catch (error) {\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.CONFIG_ERROR,\n\t\t\t\t`transformRequestBody failed: ${(error as Error).message}`,\n\t\t\t\terror\n\t\t\t)\n\t\t}\n\t\tconst finalRequestBody = transformedBody ?? requestBody\n\n\t\t// 2. Call API\n\t\tlet response: Response\n\t\ttry {\n\t\t\tresponse = await this.fetch(`${this.config.baseURL}/chat/completions`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t...(this.config.apiKey && { Authorization: `Bearer ${this.config.apiKey}` }),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(finalRequestBody),\n\t\t\t\tsignal: abortSignal,\n\t\t\t})\n\t\t} catch (error: unknown) {\n\t\t\tif ((error as any)?.name === 'AbortError') throw error\n\t\t\tconsole.error(error)\n\t\t\tthrow new InvokeError(InvokeErrorTypes.NETWORK_ERROR, 'Network request failed', error)\n\t\t}\n\n\t\t// 3. Handle HTTP errors\n\t\tif (!response.ok) {\n\t\t\tlet errorData: any\n\t\t\ttry {\n\t\t\t\terrorData = await response.json()\n\t\t\t} catch (error) {\n\t\t\t\tif ((error as any)?.name === 'AbortError') throw error\n\t\t\t}\n\t\t\tconst errorMessage = errorData?.error?.message || response.statusText\n\n\t\t\tif (response.status === 401 || response.status === 403) {\n\t\t\t\tthrow new InvokeError(\n\t\t\t\t\tInvokeErrorTypes.AUTH_ERROR,\n\t\t\t\t\t`Authentication failed: ${errorMessage}`,\n\t\t\t\t\terrorData\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (response.status === 429) {\n\t\t\t\tthrow new InvokeError(\n\t\t\t\t\tInvokeErrorTypes.RATE_LIMIT,\n\t\t\t\t\t`Rate limit exceeded: ${errorMessage}`,\n\t\t\t\t\terrorData\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (response.status >= 500) {\n\t\t\t\tthrow new InvokeError(\n\t\t\t\t\tInvokeErrorTypes.SERVER_ERROR,\n\t\t\t\t\t`Server error: ${errorMessage}`,\n\t\t\t\t\terrorData\n\t\t\t\t)\n\t\t\t}\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.UNKNOWN,\n\t\t\t\t`HTTP ${response.status}: ${errorMessage}`,\n\t\t\t\terrorData\n\t\t\t)\n\t\t}\n\n\t\t// 4. Parse and validate response\n\t\tlet data: any\n\t\ttry {\n\t\t\tdata = await response.json()\n\t\t} catch (error) {\n\t\t\tif ((error as any)?.name === 'AbortError') throw error\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.INVALID_RESPONSE,\n\t\t\t\t'Response body is not valid JSON',\n\t\t\t\terror\n\t\t\t)\n\t\t}\n\n\t\tconst choice = data.choices?.[0]\n\t\tif (!choice) {\n\t\t\tthrow new InvokeError(InvokeErrorTypes.INVALID_SCHEMA, 'No choices in response', data)\n\t\t}\n\n\t\t// Check finish_reason\n\t\tswitch (choice.finish_reason) {\n\t\t\tcase 'tool_calls':\n\t\t\tcase 'function_call': // gemini\n\t\t\tcase 'stop': // some models use this even with tool calls\n\t\t\t\tbreak\n\t\t\tcase 'length':\n\t\t\t\tthrow new InvokeError(\n\t\t\t\t\tInvokeErrorTypes.CONTEXT_LENGTH,\n\t\t\t\t\t'Response truncated: max tokens reached',\n\t\t\t\t\tundefined,\n\t\t\t\t\tdata\n\t\t\t\t)\n\t\t\tcase 'content_filter':\n\t\t\t\tthrow new InvokeError(\n\t\t\t\t\tInvokeErrorTypes.CONTENT_FILTER,\n\t\t\t\t\t'Content filtered by safety system',\n\t\t\t\t\tundefined,\n\t\t\t\t\tdata\n\t\t\t\t)\n\t\t\tdefault:\n\t\t\t\tthrow new InvokeError(\n\t\t\t\t\tInvokeErrorTypes.INVALID_SCHEMA,\n\t\t\t\t\t`Unexpected finish_reason: ${choice.finish_reason}`,\n\t\t\t\t\tundefined,\n\t\t\t\t\tdata\n\t\t\t\t)\n\t\t}\n\n\t\t// Apply normalizeResponse if provided (for fixing format issues automatically)\n\t\tconst normalizedData = options?.normalizeResponse ? options.normalizeResponse(data) : data\n\t\tconst normalizedChoice = (normalizedData as any).choices?.[0]\n\n\t\t// Get tool name from response\n\t\tconst toolCallName = normalizedChoice?.message?.tool_calls?.[0]?.function?.name\n\t\tif (!toolCallName) {\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.NO_TOOL_CALL,\n\t\t\t\t'No tool call found in response',\n\t\t\t\tundefined,\n\t\t\t\tdata\n\t\t\t)\n\t\t}\n\n\t\tconst tool = tools[toolCallName]\n\t\tif (!tool) {\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.UNKNOWN,\n\t\t\t\t`Tool \"${toolCallName}\" not found in tools`,\n\t\t\t\tundefined,\n\t\t\t\tdata\n\t\t\t)\n\t\t}\n\n\t\t// Extract and parse tool arguments\n\t\tconst argString = normalizedChoice.message?.tool_calls?.[0]?.function?.arguments\n\t\tif (!argString) {\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.INVALID_TOOL_ARGS,\n\t\t\t\t'No tool call arguments found',\n\t\t\t\tundefined,\n\t\t\t\tdata\n\t\t\t)\n\t\t}\n\n\t\tlet parsedArgs: unknown\n\t\ttry {\n\t\t\tparsedArgs = JSON.parse(argString)\n\t\t} catch (error) {\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.INVALID_TOOL_ARGS,\n\t\t\t\t'Failed to parse tool arguments as JSON',\n\t\t\t\terror,\n\t\t\t\tdata\n\t\t\t)\n\t\t}\n\n\t\t// Validate with schema\n\t\tconst validation = tool.inputSchema.safeParse(parsedArgs)\n\t\tif (!validation.success) {\n\t\t\tconsole.error(z.prettifyError(validation.error))\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.INVALID_TOOL_ARGS,\n\t\t\t\t'Tool arguments validation failed',\n\t\t\t\tvalidation.error,\n\t\t\t\tdata\n\t\t\t)\n\t\t}\n\t\tconst toolInput = validation.data\n\n\t\t// 5. Execute tool\n\t\tlet toolResult: unknown\n\t\ttry {\n\t\t\ttoolResult = await tool.execute(toolInput)\n\t\t} catch (error: unknown) {\n\t\t\tif ((error as any)?.name === 'AbortError') throw error\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.TOOL_EXECUTION_ERROR,\n\t\t\t\t`Tool execution failed: ${(error as Error)?.message}`,\n\t\t\t\terror,\n\t\t\t\tdata\n\t\t\t)\n\t\t}\n\n\t\t// Return result\n\t\treturn {\n\t\t\ttoolCall: {\n\t\t\t\tname: toolCallName,\n\t\t\t\targs: toolInput,\n\t\t\t},\n\t\t\ttoolResult,\n\t\t\tusage: {\n\t\t\t\tpromptTokens: data.usage?.prompt_tokens ?? 0,\n\t\t\t\tcompletionTokens: data.usage?.completion_tokens ?? 0,\n\t\t\t\ttotalTokens: data.usage?.total_tokens ?? 0,\n\t\t\t\tcachedTokens: data.usage?.prompt_tokens_details?.cached_tokens,\n\t\t\t\treasoningTokens: data.usage?.completion_tokens_details?.reasoning_tokens,\n\t\t\t},\n\t\t\trawResponse: data,\n\t\t\trawRequest: finalRequestBody,\n\t\t}\n\t}\n}\n","import { OpenAIClient } from './OpenAIClient'\nimport { InvokeError, InvokeErrorTypes } from './errors'\nimport type {\n\tInvokeOptions,\n\tInvokeResult,\n\tLLMClient,\n\tLLMConfig,\n\tMessage,\n\tResolvedLLMConfig,\n\tTool,\n} from './types'\n\nexport { InvokeError, InvokeErrorTypes }\nexport type { InvokeOptions, InvokeResult, LLMClient, LLMConfig, Message, Tool }\n\n/**\n * LLM module\n */\nexport class LLM extends EventTarget {\n\tconfig: ResolvedLLMConfig\n\tclient: LLMClient\n\n\tconstructor(config: LLMConfig) {\n\t\tsuper()\n\t\tthis.config = parseLLMConfig(config)\n\n\t\t// Default to OpenAI client\n\t\tthis.client = new OpenAIClient(this.config)\n\t}\n\n\t/**\n\t * - call llm api *once*\n\t * - invoke tool call *once*\n\t * - return the result of the tool\n\t */\n\tasync invoke(\n\t\tmessages: Message[],\n\t\ttools: Record<string, Tool>,\n\t\tabortSignal: AbortSignal,\n\t\toptions?: InvokeOptions\n\t): Promise<InvokeResult> {\n\t\treturn await withRetry(async () => this.client.invoke(messages, tools, abortSignal, options), {\n\t\t\tmaxRetries: this.config.maxRetries,\n\t\t\tonRetry: (attempt, lastError) => {\n\t\t\t\tthis.dispatchEvent(\n\t\t\t\t\tnew CustomEvent('retry', {\n\t\t\t\t\t\tdetail: { attempt, maxAttempts: this.config.maxRetries, lastError },\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t},\n\t\t})\n\t}\n}\n\n/**\n * Retry a function until it succeeds or reaches the maximum number of retries.\n */\nasync function withRetry<T>(\n\tfn: () => Promise<T>,\n\tsettings: {\n\t\tmaxRetries: number\n\t\tonRetry: (attempt: number, lastError: Error) => void\n\t}\n): Promise<T> {\n\tlet attempt = 0\n\twhile (true) {\n\t\ttry {\n\t\t\treturn await fn()\n\t\t} catch (error: unknown) {\n\t\t\tif ((error as any)?.name === 'AbortError') throw error\n\t\t\tif (error instanceof InvokeError && !error.retryable) throw error\n\t\t\tattempt++\n\t\t\tif (attempt > settings.maxRetries) throw error\n\n\t\t\tconsole.debug('[LLM] retryable failure, will retry:', error)\n\t\t\tsettings.onRetry(attempt, error as Error)\n\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 100))\n\t\t}\n\t}\n}\n\nexport function parseLLMConfig(config: LLMConfig): ResolvedLLMConfig {\n\t// Runtime validation as defensive programming (types already guarantee these)\n\tif (!config.baseURL || !config.model) {\n\t\tthrow new Error(\n\t\t\t'[PageAgent] LLM configuration required. Please provide: baseURL, model. ' +\n\t\t\t\t'See: https://alibaba.github.io/page-agent/docs/features/models'\n\t\t)\n\t}\n\n\tif (config.temperature !== undefined) {\n\t\tconsole.warn(\n\t\t\t'[PageAgent] LLMConfig.temperature is deprecated and will be removed in a future version. ' +\n\t\t\t\t'Use transformRequestBody to set it only for models you have verified accept it.'\n\t\t)\n\t}\n\n\treturn {\n\t\tbaseURL: config.baseURL,\n\t\tmodel: config.model,\n\t\tapiKey: config.apiKey || '',\n\t\ttemperature: config.temperature,\n\t\tmaxRetries: config.maxRetries ?? 2,\n\t\ttransformRequestBody: config.transformRequestBody ?? ((requestBody) => requestBody),\n\t\tdisableNamedToolChoice: config.disableNamedToolChoice ?? false,\n\t\tcustomFetch: (config.customFetch ?? fetch).bind(globalThis), // fetch will be illegal unless bound\n\t}\n}\n","/**\n * Task attachment store for skill ctx.files.\n * Callers: SkillHost / createSkillContext; Panel may push files later.\n * Empty-safe until UI attaches files for a task.\n */\n\nexport interface SkillAttachment {\n\tid: string\n\tname: string\n\tmimeType: string\n\t/** UTF-8 text when available; binary left as base64 in `dataBase64`. */\n\ttext?: string\n\tdataBase64?: string\n\tsize: number\n}\n\nexport interface SkillFileStore {\n\tlist(): SkillAttachment[]\n\tread(id: string): SkillAttachment | undefined\n\tclear(): void\n\tremove(id: string): boolean\n\tadd(file: Omit<SkillAttachment, 'id'> & { id?: string }): SkillAttachment\n}\n\n/** Soft cap so panel attaches stay in memory without blowing the tab. */\nexport const MAX_TASK_FILE_BYTES = 1_048_576\n\n/** In-memory attachment store for one agent / task lifecycle. */\nexport function createSkillFileStore(): SkillFileStore {\n\tconst files = new Map<string, SkillAttachment>()\n\tlet seq = 0\n\n\treturn {\n\t\tlist() {\n\t\t\treturn [...files.values()]\n\t\t},\n\t\tread(id: string) {\n\t\t\treturn files.get(id)\n\t\t},\n\t\tclear() {\n\t\t\tfiles.clear()\n\t\t},\n\t\tremove(id: string) {\n\t\t\treturn files.delete(id)\n\t\t},\n\t\tadd(file) {\n\t\t\tconst id = file.id ?? `file-${++seq}`\n\t\t\tconst entry: SkillAttachment = {\n\t\t\t\tid,\n\t\t\t\tname: file.name,\n\t\t\t\tmimeType: file.mimeType,\n\t\t\t\ttext: file.text,\n\t\t\t\tdataBase64: file.dataBase64,\n\t\t\t\tsize: file.size,\n\t\t\t}\n\t\t\tfiles.set(id, entry)\n\t\t\treturn entry\n\t\t},\n\t}\n}\n\nfunction isTextAttachment(name: string, mimeType: string): boolean {\n\tif (mimeType.startsWith('text/')) return true\n\tif (\n\t\tmimeType === 'application/json' ||\n\t\tmimeType === 'application/xml' ||\n\t\tmimeType === 'application/javascript' ||\n\t\tmimeType === 'application/typescript'\n\t) {\n\t\treturn true\n\t}\n\treturn /\\.(md|txt|json|csv|tsv|xml|html?|js|mjs|cjs|ts|tsx|jsx|css|yml|yaml|toml|log)$/i.test(\n\t\tname\n\t)\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\tif (typeof Buffer !== 'undefined') {\n\t\treturn Buffer.from(bytes).toString('base64')\n\t}\n\tlet binary = ''\n\tconst chunk = 0x8000\n\tfor (let i = 0; i < bytes.length; i += chunk) {\n\t\tbinary += String.fromCharCode(...bytes.subarray(i, i + chunk))\n\t}\n\treturn btoa(binary)\n}\n\n/** Build a SkillAttachment payload from a browser File / Blob. */\nexport async function readTaskFileBlob(\n\tfile: Blob & { name?: string },\n\toptions?: { maxBytes?: number }\n): Promise<Omit<SkillAttachment, 'id'>> {\n\tconst maxBytes = options?.maxBytes ?? MAX_TASK_FILE_BYTES\n\tconst name = file.name?.trim() || 'attachment'\n\tconst mimeType = file.type || 'application/octet-stream'\n\tif (file.size > maxBytes) {\n\t\tthrow new Error(`File \"${name}\" is too large (max ${maxBytes} bytes)`)\n\t}\n\n\tif (isTextAttachment(name, mimeType)) {\n\t\tconst text = await file.text()\n\t\treturn { name, mimeType, text, size: file.size }\n\t}\n\n\tconst bytes = new Uint8Array(await file.arrayBuffer())\n\treturn { name, mimeType, dataBase64: bytesToBase64(bytes), size: file.size }\n}\n","import { InvokeError, InvokeErrorTypes } from '@page-agent/llms'\nimport chalk from 'chalk'\nimport * as z from 'zod/v4'\n\nimport type { PageAgentTool } from '../tools'\n\nconst log = console.log.bind(console, chalk.yellow('[autoFixer]'))\n\n/**\n * Normalize LLM response and fix common format issues.\n *\n * Handles:\n * - No tool_calls but JSON in message.content (fallback)\n * - Model returns action name as tool call instead of AgentOutput\n * - Arguments wrapped as double JSON string\n * - Nested function call format\n * - Missing action field (fallback to wait)\n * - Primitive action input for single-field tools (e.g. `{\"click_element_by_index\": 2}`)\n * - etc.\n */\nexport function normalizeResponse(response: any, tools?: Map<string, PageAgentTool>): any {\n\tlet resolvedArguments: any\n\n\tconst choice = (response as { choices?: Choice[] }).choices?.[0]\n\tif (!choice) throw new Error('No choices in response')\n\n\tconst message = choice.message\n\tif (!message) throw new Error('No message in choice')\n\n\tconst toolCall = message.tool_calls?.[0]\n\n\t// fix level and location of arguments\n\n\tif (toolCall?.function?.arguments) {\n\t\tresolvedArguments = safeJsonParse(toolCall.function.arguments)\n\n\t\t// case: sometimes the model only returns the action level\n\t\tif (toolCall.function.name && toolCall.function.name !== 'AgentOutput') {\n\t\t\tlog(`#1: fixing tool_call`)\n\t\t\tresolvedArguments = { action: safeJsonParse(resolvedArguments) }\n\t\t}\n\t} else {\n\t\t// case: sometimes the model returns json in content instead of tool_calls\n\t\tif (message.content) {\n\t\t\tconst content = message.content.trim()\n\t\t\tconst jsonInContent = retrieveJsonFromString(content)\n\t\t\tif (jsonInContent) {\n\t\t\t\tresolvedArguments = safeJsonParse(jsonInContent)\n\n\t\t\t\t// case: sometimes the content json includes upper level wrapper\n\t\t\t\tif (resolvedArguments?.name === 'AgentOutput') {\n\t\t\t\t\tlog(`#2: fixing tool_call`)\n\t\t\t\t\tresolvedArguments = safeJsonParse(resolvedArguments.arguments)\n\t\t\t\t}\n\n\t\t\t\t// case: sometimes even 2-levels of wrapping\n\t\t\t\tif (resolvedArguments?.type === 'function') {\n\t\t\t\t\tlog(`#3: fixing tool_call`)\n\t\t\t\t\tresolvedArguments = safeJsonParse(resolvedArguments.function.arguments)\n\t\t\t\t}\n\n\t\t\t\t// case: and sometimes action level only\n\t\t\t\t// todo: needs better detection logic\n\t\t\t\tif (\n\t\t\t\t\t!resolvedArguments?.action &&\n\t\t\t\t\t!resolvedArguments?.evaluation_previous_goal &&\n\t\t\t\t\t!resolvedArguments?.memory &&\n\t\t\t\t\t!resolvedArguments?.next_goal &&\n\t\t\t\t\t!resolvedArguments?.thinking\n\t\t\t\t) {\n\t\t\t\t\tlog(`#4: fixing tool_call`)\n\t\t\t\t\tresolvedArguments = { action: safeJsonParse(resolvedArguments) }\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new Error('No tool_call and the message content does not contain valid JSON')\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new Error('No tool_call nor message content is present')\n\t\t}\n\t}\n\n\t// fix double stringified arguments\n\tresolvedArguments = safeJsonParse(resolvedArguments)\n\tif (resolvedArguments.action) {\n\t\tresolvedArguments.action = safeJsonParse(resolvedArguments.action)\n\t}\n\n\t// validate and fix action input using tool schemas\n\tif (resolvedArguments.action && tools) {\n\t\tresolvedArguments.action = validateAction(resolvedArguments.action, tools)\n\t}\n\n\t// fix incomplete formats\n\tif (!resolvedArguments.action) {\n\t\tlog(`#5: fixing tool_call`)\n\t\tresolvedArguments.action = { wait: { seconds: 1 } }\n\t}\n\n\t// pack back to standard format\n\treturn {\n\t\t...response,\n\t\tchoices: [\n\t\t\t{\n\t\t\t\t...choice,\n\t\t\t\tmessage: {\n\t\t\t\t\t...message,\n\t\t\t\t\ttool_calls: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...(toolCall || {}),\n\t\t\t\t\t\t\tfunction: {\n\t\t\t\t\t\t\t\t...(toolCall?.function || {}),\n\t\t\t\t\t\t\t\tname: 'AgentOutput',\n\t\t\t\t\t\t\t\targuments: JSON.stringify(resolvedArguments),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t}\n}\n\n/**\n * Validate action against tool schemas. Provides clear error messages\n * instead of letting the union schema produce unreadable errors.\n *\n * Also coerces primitive inputs for single-field tools:\n * e.g. `{\"click_element_by_index\": 2}` → `{\"click_element_by_index\": {\"index\": 2}}`\n */\nfunction validateAction(action: any, tools: Map<string, PageAgentTool>): any {\n\tif (typeof action !== 'object' || action === null) return action\n\n\tconst toolName = Object.keys(action)[0]\n\tif (!toolName) return action\n\n\tconst tool = tools.get(toolName)\n\tif (!tool) {\n\t\tconst available = Array.from(tools.keys()).join(', ')\n\t\tthrow new InvokeError(\n\t\t\tInvokeErrorTypes.INVALID_TOOL_ARGS,\n\t\t\t`Unknown action \"${toolName}\". Available: ${available}`\n\t\t)\n\t}\n\n\tlet value = action[toolName]\n\tconst schema = tool.inputSchema\n\n\t// coerce primitive input for single-field tools\n\tif (schema instanceof z.ZodObject && value !== null && typeof value !== 'object') {\n\t\tconst requiredKey = Object.keys(schema.shape).find(\n\t\t\t(k) => !(schema.shape as Record<string, z.ZodType>)[k].safeParse(undefined).success\n\t\t)\n\t\tif (requiredKey) {\n\t\t\tlog(`coercing primitive action input for \"${toolName}\"`)\n\t\t\tvalue = { [requiredKey]: value }\n\t\t}\n\t}\n\n\tconst result = schema.safeParse(value)\n\tif (!result.success) {\n\t\tthrow new InvokeError(\n\t\t\tInvokeErrorTypes.INVALID_TOOL_ARGS,\n\t\t\t`Invalid input for action \"${toolName}\": ${z.prettifyError(result.error)}`\n\t\t)\n\t}\n\n\treturn { [toolName]: result.data }\n}\n\n/**\n * Safely parse JSON, return original input if not json.\n */\nfunction safeJsonParse(input: any): any {\n\tif (typeof input === 'string') {\n\t\ttry {\n\t\t\treturn JSON.parse(input.trim())\n\t\t} catch {\n\t\t\treturn input\n\t\t}\n\t}\n\treturn input\n}\n\n/**\n * Extract and parse JSON from a string.\n * - Treat content between the first `{` and the last `}` as JSON.\n * - Try to parse that content as JSON and return the parsed value (object/array/primitive) if successful, otherwise return null.\n */\nfunction retrieveJsonFromString(str: string): any {\n\ttry {\n\t\tconst json = /({[\\s\\S]*})/.exec(str) ?? []\n\t\tif (json.length === 0) {\n\t\t\treturn null\n\t\t}\n\t\treturn JSON.parse(json[0]!)\n\t} catch {\n\t\treturn null\n\t}\n}\n\ninterface Choice {\n\tmessage?: {\n\t\trole?: 'assistant'\n\t\tcontent?: string\n\t\ttool_calls?: {\n\t\t\tid?: string\n\t\t\ttype?: 'function'\n\t\t\tfunction?: {\n\t\t\t\tname?: string\n\t\t\t\targuments?: string\n\t\t\t}\n\t\t}[]\n\t}\n\tindex?: 0\n\tfinish_reason?: 'tool_calls'\n}\n","import chalk from 'chalk'\n\nexport * from './autoFixer'\n\n/**\n * Wait for `seconds`. If a `signal` is provided, the wait is cancellable:\n * aborting rejects with the signal's reason (an `AbortError`).\n */\nexport async function waitFor(seconds: number, signal?: AbortSignal): Promise<void> {\n\tif (!signal) {\n\t\tawait new Promise((resolve) => setTimeout(resolve, seconds * 1000))\n\t\treturn\n\t}\n\tsignal.throwIfAborted()\n\tawait new Promise<void>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\tresolve()\n\t\t}, seconds * 1000)\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timer)\n\t\t\t// reason is a DOMException AbortError.\n\t\t\treject(signal.reason as DOMException)\n\t\t}\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t})\n}\n\n//\n\nexport function truncate(text: string, maxLength: number): string {\n\tif (text.length > maxLength) {\n\t\treturn text.substring(0, maxLength) + '...'\n\t}\n\treturn text\n}\n\n//\n\nexport function randomID(existingIDs?: string[]): string {\n\tlet id = Math.random().toString(36).substring(2, 11)\n\n\tif (!existingIDs) {\n\t\treturn id\n\t}\n\n\tconst MAX_TRY = 1000\n\tlet tryCount = 0\n\n\twhile (existingIDs.includes(id)) {\n\t\tid = Math.random().toString(36).substring(2, 11)\n\t\ttryCount++\n\t\tif (tryCount > MAX_TRY) {\n\t\t\tthrow new Error('randomID: too many tries')\n\t\t}\n\t}\n\n\treturn id\n}\n\n//\nconst _global = globalThis as any\n\nif (!_global.__PAGE_AGENT_IDS__) {\n\t_global.__PAGE_AGENT_IDS__ = []\n}\n\nconst ids = _global.__PAGE_AGENT_IDS__\n\n/**\n * Generate a random ID.\n * @note Unique within this window.\n */\nexport function uid() {\n\tconst id = randomID(ids)\n\tids.push(id)\n\treturn id\n}\n\nconst llmsTxtCache = new Map<string, string | null>()\n\n/** Fetch /llms.txt for a URL's origin. Cached per origin, `null` = tried and not found. */\nexport async function fetchLlmsTxt(url: string): Promise<string | null> {\n\tlet origin: string\n\ttry {\n\t\torigin = new URL(url).origin\n\t} catch {\n\t\treturn null // Invalid URL\n\t}\n\t// about:blank, data:, file:\n\tif (origin === 'null') return null\n\n\tif (llmsTxtCache.has(origin)) return llmsTxtCache.get(origin)!\n\n\tconst endpoint = `${origin}/llms.txt`\n\tlet result: string | null = null\n\ttry {\n\t\tconsole.log(chalk.gray(`[llms.txt] Fetching ${endpoint}`))\n\t\tconst res = await fetch(endpoint, { signal: AbortSignal.timeout(3000) })\n\t\tif (res.ok) {\n\t\t\tresult = await res.text()\n\t\t\tconsole.log(chalk.green(`[llms.txt] Found (${result.length} chars)`))\n\t\t\tif (result.length > 1000) {\n\t\t\t\tconsole.log(chalk.yellow(`[llms.txt] Truncating to 1000 chars`))\n\t\t\t\tresult = truncate(result, 1000)\n\t\t\t}\n\t\t} else {\n\t\t\tconsole.debug(chalk.gray(`[llms.txt] ${res.status} for ${endpoint}`))\n\t\t}\n\t} catch (e) {\n\t\tconsole.debug(chalk.gray(`[llms.txt] not found for ${endpoint}`), e)\n\t}\n\tllmsTxtCache.set(origin, result)\n\treturn result\n}\n\n/**\n * Simple assertion function that throws an error if the condition is falsy\n * @param condition - The condition to assert\n * @param message - Optional error message\n * @throws Error if condition is falsy\n */\nexport function assert(condition: unknown, message?: string, silent?: boolean): asserts condition {\n\tif (!condition) {\n\t\tconst errorMessage = message ?? 'Assertion failed'\n\n\t\tif (!silent) console.error(chalk.red(`❌ assert: ${errorMessage}`))\n\n\t\tthrow new Error(errorMessage)\n\t}\n}\n\n/**\n * Suppress errors from a function.\n */\nexport async function suppress<T>(fn: () => T | Promise<T>): Promise<Awaited<T> | undefined> {\n\ttry {\n\t\treturn await fn()\n\t} catch (error) {\n\t\tconsole.error(error)\n\t\treturn undefined\n\t}\n}\n","/**\n * Internal tools for PageAgent.\n * @note Adapted from browser-use\n */\nimport * as z from 'zod/v4'\n\nimport type { PageAgentCore } from '../PageAgentCore'\nimport { waitFor } from '../utils'\n\n/**\n * Per-invocation context passed to every tool execution.\n * Tools MUST honor `signal` to support cooperative cancellation.\n */\nexport interface ToolContext {\n\tsignal: AbortSignal\n}\n\n/**\n * Internal tool definition that has access to PageAgent `this` context\n */\nexport interface PageAgentTool<TParams = any> {\n\t// name: string\n\tdescription: string\n\tinputSchema: z.ZodType<TParams>\n\texecute: (this: PageAgentCore, args: TParams, ctx: ToolContext) => Promise<string>\n}\n\nexport function tool<TParams>(options: PageAgentTool<TParams>): PageAgentTool<TParams> {\n\treturn options\n}\n\n/**\n * Internal tools for PageAgent.\n * Note: Using any to allow different parameter types for each tool\n */\nexport const tools = new Map<string, PageAgentTool>()\n\ntools.set(\n\t'done',\n\ttool({\n\t\tdescription:\n\t\t\t'Complete task. Text is your final response to the user — keep it concise unless the user explicitly asks for detail.',\n\t\tinputSchema: z.object({\n\t\t\ttext: z.string(),\n\t\t\tsuccess: z.boolean().default(true),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\t// @note main loop will handle this one\n\t\t\treturn Promise.resolve('Task completed')\n\t\t},\n\t})\n)\n\ntools.set(\n\t'wait',\n\ttool({\n\t\tdescription: 'Wait for x seconds. Can be used to wait until the page or data is fully loaded.',\n\t\tinputSchema: z.object({\n\t\t\tseconds: z.number().min(1).max(10).default(1),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input, { signal }) {\n\t\t\t// try to subtract LLM calling time from the actual wait time\n\t\t\tconst lastTimeUpdate = await this.pageController.getLastUpdateTime()\n\t\t\tconst secondsSinceLastUpdate = (Date.now() - lastTimeUpdate) / 1000\n\t\t\tconst actualWaitTime = Math.max(0, input.seconds - secondsSinceLastUpdate)\n\t\t\tconsole.log(`actualWaitTime: ${actualWaitTime} seconds`)\n\t\t\tawait waitFor(actualWaitTime, signal)\n\n\t\t\tconst waitedSeconds = (secondsSinceLastUpdate + actualWaitTime).toFixed(2)\n\t\t\treturn `✅ Waited for ${waitedSeconds} seconds.`\n\t\t},\n\t})\n)\n\ntools.set(\n\t'ask_user',\n\ttool({\n\t\tdescription:\n\t\t\t'Ask the user a question and wait for their answer. Use this if you need more information or clarification.',\n\t\tinputSchema: z.object({\n\t\t\tquestion: z.string(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input, { signal }) {\n\t\t\tif (!this.onAskUser) {\n\t\t\t\tthrow new Error('ask_user tool requires onAskUser callback to be set')\n\t\t\t}\n\t\t\tconst answer = await this.onAskUser(input.question, { signal })\n\t\t\treturn `User answered: ${answer}`\n\t\t},\n\t})\n)\n\ntools.set(\n\t'click_element_by_index',\n\ttool({\n\t\tdescription: 'Click element by index',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.clickElement(input.index)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'input_text',\n\ttool({\n\t\tdescription: 'Click and type text into an interactive input element',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t\ttext: z.string(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.inputText(input.index, input.text)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'select_dropdown_option',\n\ttool({\n\t\tdescription:\n\t\t\t'Select dropdown option for interactive element index by the text of the option you want to select',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t\ttext: z.string(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.selectOption(input.index, input.text)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\n/**\n * @note Reference from browser-use\n */\ntools.set(\n\t'scroll',\n\ttool({\n\t\tdescription:\n\t\t\t'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. num_pages must be between 0 and 10.',\n\t\tinputSchema: z.object({\n\t\t\tdown: z.boolean().default(true),\n\t\t\tnum_pages: z.number().min(0).max(10).optional().default(0.1),\n\t\t\tpixels: z.number().int().min(0).optional(),\n\t\t\tindex: z.number().int().min(0).optional(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.scroll({\n\t\t\t\t...input,\n\t\t\t\tnumPages: input.num_pages,\n\t\t\t})\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\n/**\n * @todo Tables need a dedicated parser to extract structured data. This tool is useless.\n */\ntools.set(\n\t'scroll_horizontally',\n\ttool({\n\t\tdescription:\n\t\t\t'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.',\n\t\tinputSchema: z.object({\n\t\t\tright: z.boolean().default(true),\n\t\t\tpixels: z.number().int().min(0),\n\t\t\tindex: z.number().int().min(0).optional(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.scrollHorizontally(input)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'drag_element',\n\ttool({\n\t\tdescription:\n\t\t\t'Drag the element at source_index onto the element at target_index. Both indexes belong to this step. ' +\n\t\t\t'Synthetic events only: isTrusted is false. mode html5 sends DragEvents and drops only if the destination cancels dragover. ' +\n\t\t\t'pointer and pointer-paced send pointer and mouse events. A dispatched drag is not proof the page accepted it: check the next read. ' +\n\t\t\t'If html5 comes back not applied, the next step may call drag_element once with mode pointer-paced. Do not call both in the same step. Neither result proves the effect. ' +\n\t\t\t'Event sent, effect not verified, change not persisted. Do not simulate this drag with execute_javascript.',\n\t\tinputSchema: z.object({\n\t\t\tsource_index: z.int().min(0),\n\t\t\ttarget_index: z.int().min(0),\n\t\t\tmode: z.enum(['html5', 'pointer', 'pointer-paced']).default('html5'),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.dragElement(\n\t\t\t\tinput.source_index,\n\t\t\t\tinput.target_index,\n\t\t\t\tinput.mode\n\t\t\t)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'hover_element',\n\ttool({\n\t\tdescription:\n\t\t\t'Hover the element at index. The index belongs to this step. ' +\n\t\t\t'Synthetic pointer and mouse events only: isTrusted is false, CSS :hover is not activated, and the real pointer does not move. ' +\n\t\t\t'A script that listens may still react. Event sent, effect not verified, change not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.hoverElement(input.index)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'press_key',\n\ttool({\n\t\tdescription:\n\t\t\t'Press one key on the element at index. The index belongs to this step. ' +\n\t\t\t'Synthetic keydown and keyup only: the native default does not run, so no character is typed, Tab does not move focus and Enter does not activate the control. ' +\n\t\t\t'Event sent, effect not verified, change not persisted. One key per step.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t\tkey: z.string().min(1),\n\t\t\tcode: z.string().min(1).optional(),\n\t\t\tctrl_key: z.boolean().optional(),\n\t\t\talt_key: z.boolean().optional(),\n\t\t\tshift_key: z.boolean().optional(),\n\t\t\tmeta_key: z.boolean().optional(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.pressKey(input.index, input.key, {\n\t\t\t\tcode: input.code,\n\t\t\t\tctrlKey: input.ctrl_key,\n\t\t\t\taltKey: input.alt_key,\n\t\t\t\tshiftKey: input.shift_key,\n\t\t\t\tmetaKey: input.meta_key,\n\t\t\t})\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'double_click_element',\n\ttool({\n\t\tdescription:\n\t\t\t'Double-click the element at index. The index belongs to this step. ' +\n\t\t\t'Synthetic pointer, mouse, click and dblclick events only: isTrusted is false, and text is not selected the way a physical double click selects it. ' +\n\t\t\t'Event sent, effect not verified, change not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.doubleClickElement(input.index)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'focus_element',\n\ttool({\n\t\tdescription:\n\t\t\t'Focus the element at index. The index belongs to this step. ' +\n\t\t\t'Calls focus(). The message says whether that element was focused right after. ' +\n\t\t\t'Focus is not a saved change. Not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.focusElement(input.index)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'set_checked',\n\ttool({\n\t\tdescription:\n\t\t\t'Set a native checkbox or radio at index. checked true selects it. A radio cannot be cleared. ' +\n\t\t\t'The index belongs to this step. Right after the action the message says whether the control held that state. ' +\n\t\t\t'It does not show that a form was submitted or saved. Not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t\tchecked: z.boolean().default(true),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.setChecked(input.index, input.checked)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'set_range',\n\ttool({\n\t\tdescription:\n\t\t\t'Set a native range input at index to value. A value the browser would clamp or round is refused. ' +\n\t\t\t'The index belongs to this step. Right after the action the message says whether the control held that value. ' +\n\t\t\t'It does not show that the page saved it. Not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t\tvalue: z.number(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.setRange(input.index, input.value)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'scroll_into_view',\n\ttool({\n\t\tdescription:\n\t\t\t'Call scrollIntoView on the element at index. The index belongs to this step. ' +\n\t\t\t'The message gives the window scroll before and after. Nested scrollers are not measured. Not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.scrollIntoView(input.index)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'wheel',\n\ttool({\n\t\tdescription:\n\t\t\t'Send one synthetic wheel event. It does not scroll: use scroll to move the page. ' +\n\t\t\t'delta_x and delta_y are the WheelEvent deltas in CSS pixels. ' +\n\t\t\t'With index, that element receives the event. Without index, the page receives it. ' +\n\t\t\t'The index belongs to this step. Event sent, effect not verified, change not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0).optional(),\n\t\t\tdelta_x: z.number().default(0),\n\t\t\tdelta_y: z.number().default(0),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.wheel({\n\t\t\t\tindex: input.index,\n\t\t\t\tx: input.delta_x,\n\t\t\t\ty: input.delta_y,\n\t\t\t})\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'execute_javascript',\n\ttool({\n\t\tdescription:\n\t\t\t'Execute JavaScript code on the current page. Supports async/await syntax. Use with caution! ' +\n\t\t\t'An `AbortSignal` named `signal` is available in scope: long-running async code MUST honor it ' +\n\t\t\t'(e.g. `await fetch(url, { signal })`, or `signal.throwIfAborted()` in loops). ' +\n\t\t\t'The variable `agent` is the page-agent instance (`agent.pageController`, `agent.tools`). ' +\n\t\t\t// REVERSIBLE (2026-11-17, executor reliability): the next sentence. A bare expression returns undefined.\n\t\t\t'Use `return` to send a value back: a bare expression gives undefined. ' +\n\t\t\t'Do not use this to drag one element onto another: use drag_element. ' +\n\t\t\t'If the result starts with blocked_by_csp, user_denied or unavailable, do not call this tool again on this page.',\n\t\tinputSchema: z.object({\n\t\t\tscript: z.string(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input, { signal }) {\n\t\t\tconst result = await this.pageController.executeJavascript(input.script, signal, {\n\t\t\t\tagent: this,\n\t\t\t})\n\t\t\tsignal.throwIfAborted()\n\t\t\t// Same prefixes as scriptAccessClosed. A CSP block or a refused grant cannot be\n\t\t\t// fixed by another script, so the tool leaves this agent's schema.\n\t\t\tif (/^(blocked_by_csp|user_denied|unavailable):/.test(result.message)) {\n\t\t\t\tthis.tools.delete('execute_javascript')\n\t\t\t}\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\n// @todo send_keys\n// @todo upload_file\n// @todo extract_structured_data\n","/**\n * Page Agent skills — shared types for the skill document protocol.\n * @see docs/skills.md\n */\n\n/** Where a skill came from. */\nexport type SkillScope = 'remote' | 'agent'\n\n/** Scalar types allowed in command `input` maps. */\nexport type SkillInputType = 'string' | 'number' | 'boolean'\n\nexport interface SkillInputField {\n\ttype: SkillInputType\n\tdescription?: string\n\tdefault?: string | number | boolean\n}\n\n/**\n * One command exported from a `skill-js` block.\n * `run` receives the sandboxed ctx (typed loosely here; runtime narrows it).\n */\nexport interface SkillCommandDefinition {\n\tdescription: string\n\tinput?: Record<string, SkillInputField>\n\trun: (ctx: unknown, input: Record<string, unknown>) => Promise<unknown>\n}\n\n/** Parsed, validated skill ready for the host to register. */\nexport interface SkillManifest {\n\tid: string\n\tname: string\n\tdescription: string\n\tversion: number\n\tscope: SkillScope\n\ttriggers: string[]\n\t/** Markdown body without frontmatter / skill-js fence. */\n\tbody: string\n\t/** Raw `skill-js` source (for re-save / edit). */\n\tmoduleSource: string\n\tcommands: Record<string, SkillCommandDefinition>\n}\n\n/** Catalog entry before the full document is loaded. */\nexport type SkillCatalogRef =\n\t| { id: string; inline: string }\n\t| { id: string; url: string; etag?: string }\n\t| { id: string; name: string; description: string; url: string; etag?: string }\n\n/**\n * Optional remote catalog / publish backend (installer, Studio sync).\n * Local agent storage remains the source of truth until `put` succeeds.\n */\nexport interface SkillsRemoteAdapter {\n\tlist(): Promise<\n\t\t{ id: string; name: string; description: string; version: number; etag?: string }[]\n\t>\n\tget(id: string): Promise<{ document: string; version: number; etag?: string }>\n\tput(input: {\n\t\tdocument: string\n\t\texpectedVersion?: number\n\t}): Promise<{ id: string; version: number; etag?: string }>\n\tremove?(id: string): Promise<void>\n}\n\n/** Default TTL for `SkillsRemoteAdapter.list` cache (5 minutes). */\nexport const DEFAULT_REMOTE_CACHE_TTL_MS = 5 * 60_000\n\n/** Public agent config for skills. */\nexport interface SkillsConfig {\n\tenabled?: boolean\n\tcatalog?: SkillCatalogRef[]\n\tallowedOrigins?: string[]\n\t/** @default 3 */\n\tmaxLoaded?: number\n\t/** @default true */\n\tpersistAgentSkills?: boolean\n\t/** Optional remote list/get/put adapter (Skills Studio / installer). */\n\tremote?: SkillsRemoteAdapter\n\t/** Cache TTL for `remote.list` in ms. @default 300000 */\n\tremoteCacheTtlMs?: number\n}\n\n/** Result of SkillHost.publishDocument (local save, then optional remote.put). */\nexport interface PublishDocumentResult {\n\tid: string\n\tversion: number\n\tdocument: string\n\t/** True when remote.put completed successfully. */\n\tremote?: boolean\n\tetag?: string\n\t/** Set when local save succeeded but remote.put failed; local copy is kept. */\n\tremoteError?: string\n}\n\n/** Thrown when SkillsRemoteAdapter.get/list/put fails for reasons other than local persist. */\nexport class SkillRemoteError extends Error {\n\treadonly code: string\n\treadonly id?: string\n\n\tconstructor(code: string, message: string, id?: string) {\n\t\tsuper(message)\n\t\tthis.name = 'SkillRemoteError'\n\t\tthis.code = code\n\t\tthis.id = id\n\t}\n}\n\n/** Compact row returned by `list_skills`. */\nexport interface SkillListEntry {\n\tid: string\n\tname: string\n\tdescription: string\n\tscope: SkillScope\n\tloaded: boolean\n\tcommands: { name: string; description: string }[]\n}\n\nexport class SkillParseError extends Error {\n\treadonly code: string\n\n\tconstructor(code: string, message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'SkillParseError'\n\t\tthis.code = code\n\t}\n}\n\n/** Stable MacroTool name for a loaded command. */\nexport function skillToolName(skillId: string, commandName: string): string {\n\treturn `skill__${skillId}__${commandName}`\n}\n\nexport const SKILL_ID_PATTERN = /^[a-z][a-z0-9-]*$/\nexport const SKILL_COMMAND_PATTERN = /^[a-z][a-z0-9_]*$/\nexport const SKILL_STORAGE_KEY = 'page-agent-skills-v1'\nexport const SKILL_JS_FENCE = 'skill-js'\n\n/** Per-command wall clock for skill__* runs (composed with the task AbortSignal). */\nexport const SKILL_COMMAND_TIMEOUT_MS = 30_000\n/** Soft cap for one skill markdown document (remote fetch or agent save/edit). */\nexport const MAX_SKILL_DOCUMENT_BYTES = 256_000\n/** Max agent-authored skills persisted in browser storage. */\nexport const MAX_AGENT_SKILLS = 32\n/** Max concurrent SkillWatcher arms. */\nexport const MAX_SKILL_WATCHES = 3\n/** Default poll interval for interval watches. */\nexport const DEFAULT_SKILL_WATCH_INTERVAL_MS = 15_000\n/** Floor for watch intervals (avoid hot loops). */\nexport const MIN_SKILL_WATCH_INTERVAL_MS = 5_000\n\n/** How a SkillWatcher is scheduled. */\nexport type SkillWatchTrigger = 'interval' | 'on-enter' | 'on-url'\n\n/**\n * Spec to arm a background watch (same tab; no second ReAct execute).\n * Prefer observe/assert-only skill commands for ticks.\n */\nexport interface SkillWatchSpec {\n\tid: string\n\tskillId: string\n\tcommand: string\n\tinput?: Record<string, unknown>\n\t/** @default DEFAULT_SKILL_WATCH_INTERVAL_MS for trigger interval */\n\teveryMs?: number\n\t/** @default 'interval' */\n\ttrigger?: SkillWatchTrigger\n\t/** When trigger is on-url, fire check when location href includes this. */\n\turlIncludes?: string\n\t/** @default true — skip ticks while PageAgentCore status is running */\n\tpauseWhileTaskRunning?: boolean\n\t/** @default true — disarm after the first successful fire */\n\tonce?: boolean\n}\n\n/** Public row returned by listWatches. */\nexport interface SkillWatchEntry {\n\tid: string\n\tskillId: string\n\tcommand: string\n\ttrigger: SkillWatchTrigger\n\teveryMs: number\n\tarmed: boolean\n\tlastFiredAt?: number\n\tlastError?: string\n}\n","/**\n * Parse Page Agent skill documents (frontmatter + markdown + skill-js).\n * @see docs/skills.md\n *\n * Callers: parse.test.ts; later SkillHost / list_skills / load_skill.\n * API: parseSkillDocument(source) → SkillManifest\n */\nimport {\n\tSKILL_COMMAND_PATTERN,\n\tSKILL_ID_PATTERN,\n\tSKILL_JS_FENCE,\n\ttype SkillCommandDefinition,\n\ttype SkillInputField,\n\ttype SkillInputType,\n\ttype SkillManifest,\n\tSkillParseError,\n\ttype SkillScope,\n} from './types'\n\nconst INPUT_TYPES = new Set<SkillInputType>(['string', 'number', 'boolean'])\n\ninterface Frontmatter {\n\tname?: string\n\tdescription?: string\n\tversion?: number\n\tid?: string\n\tscope?: string\n\ttriggers?: string[]\n}\n\n/** Split `---` frontmatter from the markdown body. */\nexport function splitFrontmatter(source: string): { raw: string; body: string } {\n\tconst text = source.replace(/^\\uFEFF/, '')\n\tif (!text.startsWith('---')) {\n\t\tthrow new SkillParseError(\n\t\t\t'missing_frontmatter',\n\t\t\t'Skill document must start with YAML frontmatter (---)'\n\t\t)\n\t}\n\tconst end = text.indexOf('\\n---', 3)\n\tif (end === -1) {\n\t\tthrow new SkillParseError('unclosed_frontmatter', 'Frontmatter has no closing --- line')\n\t}\n\tconst raw = text.slice(3, end).replace(/^\\r?\\n/, '')\n\tconst body = text.slice(end + 4).replace(/^\\r?\\n/, '')\n\treturn { raw, body }\n}\n\n/**\n * Minimal YAML subset for skill frontmatter: scalars, folded `>`, `[a, b]` lists.\n * Not a general YAML parser.\n */\nexport function parseFrontmatterYaml(raw: string): Frontmatter {\n\tconst result: Frontmatter = {}\n\tconst lines = raw.split(/\\r?\\n/)\n\tlet i = 0\n\twhile (i < lines.length) {\n\t\tconst line = lines[i]\n\t\ti++\n\t\tif (!line.trim() || line.trimStart().startsWith('#')) continue\n\t\tconst match = /^([A-Za-z][A-Za-z0-9_]*)\\s*:\\s*(.*)$/.exec(line)\n\t\tif (!match) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'invalid_frontmatter_line',\n\t\t\t\t`Cannot parse frontmatter line: ${line}`\n\t\t\t)\n\t\t}\n\t\tconst key = match[1]\n\t\tlet value = match[2].trim()\n\t\tif (value === '>' || value === '|') {\n\t\t\tconst folded: string[] = []\n\t\t\twhile (i < lines.length) {\n\t\t\t\tconst next = lines[i]\n\t\t\t\tif (/^[A-Za-z][A-Za-z0-9_]*\\s*:/.test(next)) break\n\t\t\t\ti++\n\t\t\t\tfolded.push(next.replace(/^\\s{2}/, ''))\n\t\t\t}\n\t\t\tvalue = folded.join(value === '>' ? ' ' : '\\n').trim()\n\t\t}\n\t\t;(result as Record<string, unknown>)[key] = coerceYamlValue(value)\n\t}\n\treturn result\n}\n\nfunction coerceYamlValue(value: string): unknown {\n\tif (value === '') return ''\n\tif (\n\t\t(value.startsWith('\"') && value.endsWith('\"')) ||\n\t\t(value.startsWith(\"'\") && value.endsWith(\"'\"))\n\t) {\n\t\treturn value.slice(1, -1)\n\t}\n\tif (value.startsWith('[') && value.endsWith(']')) {\n\t\tconst inner = value.slice(1, -1).trim()\n\t\tif (!inner) return []\n\t\treturn inner.split(',').map((part) => {\n\t\t\tconst item = part.trim()\n\t\t\tif (\n\t\t\t\t(item.startsWith('\"') && item.endsWith('\"')) ||\n\t\t\t\t(item.startsWith(\"'\") && item.endsWith(\"'\"))\n\t\t\t) {\n\t\t\t\treturn item.slice(1, -1)\n\t\t\t}\n\t\t\treturn item\n\t\t})\n\t}\n\tif (/^-?\\d+$/.test(value)) return Number(value)\n\tif (value === 'true') return true\n\tif (value === 'false') return false\n\treturn value\n}\n\n/** Extract the single ```skill-js fence; returns source and body without that fence. */\nexport function extractSkillJs(body: string): { moduleSource: string; docs: string } {\n\tconst fence = new RegExp('```' + SKILL_JS_FENCE + '\\\\s*\\\\r?\\\\n([\\\\s\\\\S]*?)\\\\r?\\\\n```', 'gm')\n\tconst matches = [...body.matchAll(fence)]\n\tif (matches.length === 0) {\n\t\tthrow new SkillParseError(\n\t\t\t'missing_skill_js',\n\t\t\t`Skill must contain one \\`\\`\\`${SKILL_JS_FENCE} code block with commands`\n\t\t)\n\t}\n\tif (matches.length > 1) {\n\t\tthrow new SkillParseError(\n\t\t\t'multiple_skill_js',\n\t\t\t`Skill must contain exactly one \\`\\`\\`${SKILL_JS_FENCE} block`\n\t\t)\n\t}\n\tconst moduleSource = matches[0][1].trim()\n\tconst docs = body.replace(matches[0][0], '').trim()\n\treturn { moduleSource, docs }\n}\n\n/** Names shadowed inside skill-js so free lookups do not reach the real page/globals. */\nconst SKILL_JS_DENIED_PARAMS = [\n\t'document',\n\t'window',\n\t'self',\n\t'frames',\n\t'parent',\n\t'top',\n\t'fetch',\n\t'XMLHttpRequest',\n\t'WebSocket',\n\t'eval',\n\t'Function',\n\t'globalThis',\n\t'global',\n] as const\n\n/**\n * Evaluate the skill-js module and return its `commands` object.\n * Uses `new Function` with denied globals shadowed as parameters (undefined / empty realm).\n * May throw SkillParseError `skill_blocked_by_csp`.\n */\nexport function evaluateSkillCommands(\n\tmoduleSource: string\n): Record<string, SkillCommandDefinition> {\n\tlet factory: (...denied: unknown[]) => unknown\n\ttry {\n\t\t// Strip a leading `export` so the body works inside a function.\n\t\tconst body = moduleSource.replace(/^\\s*export\\s+/m, '')\n\t\tconst sandboxGlobal = Object.freeze(Object.create(null))\n\n\t\t// No \"use strict\": binding the name `eval` as a parameter is a SyntaxError in strict mode,\n\t\t// and we need that parameter to shadow the real eval for skill-js.\n\t\t// eslint-disable-next-line @typescript-eslint/no-implied-eval -- intentional skill-js sandbox factory\n\t\tfactory = new Function(\n\t\t\t...SKILL_JS_DENIED_PARAMS,\n\t\t\t`${body}\\n; return typeof commands !== \"undefined\" ? commands : undefined;`\n\t\t) as (...denied: unknown[]) => unknown\n\t\t// Bind sandbox args once. `this` must be sandboxGlobal: in non-strict mode,\n\t\t// `bind(undefined)` would coerce `this` to the real global, so `this.fetch` escapes.\n\t\tconst deniedArgs: unknown[] = SKILL_JS_DENIED_PARAMS.map((name) =>\n\t\t\tname === 'globalThis' ? sandboxGlobal : undefined\n\t\t)\n\t\tfactory = factory.bind(sandboxGlobal, ...deniedArgs)\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\tif (/unsafe-eval|Content Security Policy|Refused to evaluate/i.test(message)) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'skill_blocked_by_csp',\n\t\t\t\t'blocked_by_csp: This page blocks evaluating skill modules (unsafe-eval).'\n\t\t\t)\n\t\t}\n\t\tthrow new SkillParseError('skill_js_syntax', `skill-js syntax error: ${message}`)\n\t}\n\n\tlet commands: unknown\n\ttry {\n\t\tcommands = factory()\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\tthrow new SkillParseError(\n\t\t\t'skill_js_runtime',\n\t\t\t`skill-js failed while loading commands: ${message}`\n\t\t)\n\t}\n\n\tif (!commands || typeof commands !== 'object' || Array.isArray(commands)) {\n\t\tthrow new SkillParseError(\n\t\t\t'missing_commands',\n\t\t\t'skill-js must define a `commands` object (e.g. `export const commands = { ... }`)'\n\t\t)\n\t}\n\treturn validateCommands(commands as Record<string, unknown>)\n}\n\nfunction validateCommands(raw: Record<string, unknown>): Record<string, SkillCommandDefinition> {\n\tconst names = Object.keys(raw)\n\tif (names.length === 0) {\n\t\tthrow new SkillParseError('empty_commands', 'commands object must include at least one command')\n\t}\n\tconst out: Record<string, SkillCommandDefinition> = {}\n\tfor (const name of names) {\n\t\tif (!SKILL_COMMAND_PATTERN.test(name)) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'invalid_command_name',\n\t\t\t\t`Command name \"${name}\" must match ${SKILL_COMMAND_PATTERN}`\n\t\t\t)\n\t\t}\n\t\tconst entry = raw[name]\n\t\tif (!entry || typeof entry !== 'object' || Array.isArray(entry)) {\n\t\t\tthrow new SkillParseError('invalid_command', `Command \"${name}\" must be an object`)\n\t\t}\n\t\tconst command = entry as Record<string, unknown>\n\t\tif (typeof command.description !== 'string' || !command.description.trim()) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'invalid_command',\n\t\t\t\t`Command \"${name}\" needs a non-empty description`\n\t\t\t)\n\t\t}\n\t\tif (typeof command.run !== 'function') {\n\t\t\tthrow new SkillParseError('invalid_command', `Command \"${name}\" needs a run() function`)\n\t\t}\n\t\tout[name] = {\n\t\t\tdescription: command.description.trim(),\n\t\t\tinput: command.input ? validateInputMap(name, command.input) : undefined,\n\t\t\trun: command.run as SkillCommandDefinition['run'],\n\t\t}\n\t}\n\treturn out\n}\n\nfunction validateInputMap(commandName: string, raw: unknown): Record<string, SkillInputField> {\n\tif (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n\t\tthrow new SkillParseError('invalid_input', `Command \"${commandName}\" input must be an object`)\n\t}\n\tconst out: Record<string, SkillInputField> = {}\n\tfor (const [field, spec] of Object.entries(raw as Record<string, unknown>)) {\n\t\tif (!spec || typeof spec !== 'object' || Array.isArray(spec)) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'invalid_input',\n\t\t\t\t`Command \"${commandName}\" field \"${field}\" must be an object`\n\t\t\t)\n\t\t}\n\t\tconst fieldSpec = spec as Record<string, unknown>\n\t\tconst type = fieldSpec.type\n\t\tif (typeof type !== 'string' || !INPUT_TYPES.has(type as SkillInputType)) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'invalid_input',\n\t\t\t\t`Command \"${commandName}\" field \"${field}\" type must be string|number|boolean`\n\t\t\t)\n\t\t}\n\t\tout[field] = {\n\t\t\ttype: type as SkillInputType,\n\t\t\tdescription: typeof fieldSpec.description === 'string' ? fieldSpec.description : undefined,\n\t\t\tdefault: fieldSpec.default as SkillInputField['default'],\n\t\t}\n\t}\n\treturn out\n}\n\nfunction validateMeta(fm: Frontmatter): {\n\tid: string\n\tname: string\n\tdescription: string\n\tversion: number\n\tscope: SkillScope\n\ttriggers: string[]\n} {\n\tif (typeof fm.name !== 'string' || !SKILL_ID_PATTERN.test(fm.name)) {\n\t\tthrow new SkillParseError('invalid_name', `name is required and must match ${SKILL_ID_PATTERN}`)\n\t}\n\tif (typeof fm.description !== 'string' || !fm.description.trim()) {\n\t\tthrow new SkillParseError('invalid_description', 'description is required')\n\t}\n\tif (typeof fm.version !== 'number' || !Number.isInteger(fm.version) || fm.version < 1) {\n\t\tthrow new SkillParseError('invalid_version', 'version must be a positive integer')\n\t}\n\tconst id = fm.id ?? fm.name\n\tif (typeof id !== 'string' || !SKILL_ID_PATTERN.test(id)) {\n\t\tthrow new SkillParseError('invalid_id', `id must match ${SKILL_ID_PATTERN}`)\n\t}\n\tconst scope: SkillScope = fm.scope === 'agent' ? 'agent' : 'remote'\n\tif (fm.scope !== undefined && fm.scope !== 'remote' && fm.scope !== 'agent') {\n\t\tthrow new SkillParseError('invalid_scope', 'scope must be \"remote\" or \"agent\"')\n\t}\n\tconst triggers = Array.isArray(fm.triggers)\n\t\t? fm.triggers.filter((t): t is string => typeof t === 'string')\n\t\t: []\n\treturn {\n\t\tid,\n\t\tname: fm.name,\n\t\tdescription: fm.description.trim(),\n\t\tversion: fm.version,\n\t\tscope,\n\t\ttriggers,\n\t}\n}\n\n/** Parse a full skill markdown document into a SkillManifest. */\nexport function parseSkillDocument(source: string): SkillManifest {\n\tif (typeof source !== 'string' || !source.trim()) {\n\t\tthrow new SkillParseError('empty_document', 'Skill document is empty')\n\t}\n\tconst { raw, body } = splitFrontmatter(source)\n\tconst meta = validateMeta(parseFrontmatterYaml(raw))\n\tconst { moduleSource, docs } = extractSkillJs(body)\n\tconst commands = evaluateSkillCommands(moduleSource)\n\treturn {\n\t\t...meta,\n\t\tbody: docs,\n\t\tmoduleSource,\n\t\tcommands,\n\t}\n}\n","/**\n * Sandboxed skill ctx — page/assert/ask/files/memo/ok/fail.\n * Callers: SkillHost when executing skill__* tools.\n * Does not put document, window, fetch, or eval on ctx.\n */\nimport type { PageController } from '@page-agent/page-controller'\n\nimport type { SkillFileStore } from './files'\n\nexport class SkillAssertError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'SkillAssertError'\n\t}\n}\n\nexport class SkillFailError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'SkillFailError'\n\t}\n}\n\nexport interface SkillPageQuery {\n\trole?: string\n\tname?: string | RegExp\n\t/** Escape hatch: index from the current observe only. */\n\tindex?: number\n}\n\nexport interface SkillElementHandle {\n\treadonly __skillHandle: true\n}\n\ninterface InternalHandle extends SkillElementHandle {\n\tgen: number\n\tindex: number\n\tlabel: string\n}\n\nexport interface ObservationLabel {\n\tindex: number\n\trole: string\n\tname: string\n\tlabel: string\n}\n\nexport interface SkillResult {\n\tok: boolean\n\tmessage: string\n}\n\nexport interface SkillContext {\n\tpage: {\n\t\tfind(query: SkillPageQuery): Promise<SkillElementHandle>\n\t\tclick(target: SkillPageQuery | SkillElementHandle): Promise<string>\n\t\tfill(target: SkillPageQuery | SkillElementHandle, text: string): Promise<string>\n\t\tselect(target: SkillPageQuery | SkillElementHandle, optionText: string): Promise<string>\n\t\thover(target: SkillPageQuery | SkillElementHandle): Promise<string>\n\t\tdrag(\n\t\t\tsource: SkillPageQuery | SkillElementHandle,\n\t\t\ttarget: SkillPageQuery | SkillElementHandle,\n\t\t\tmode?: 'html5' | 'pointer' | 'pointer-paced'\n\t\t): Promise<string>\n\t\tscroll(options?: {\n\t\t\tdown?: boolean\n\t\t\tnumPages?: number\n\t\t\tpixels?: number\n\t\t\ttarget?: SkillPageQuery | SkillElementHandle\n\t\t}): Promise<string>\n\t\tpressKey(\n\t\t\ttarget: SkillPageQuery | SkillElementHandle,\n\t\t\tkey: string,\n\t\t\toptions?: {\n\t\t\t\tcode?: string\n\t\t\t\tctrlKey?: boolean\n\t\t\t\taltKey?: boolean\n\t\t\t\tshiftKey?: boolean\n\t\t\t\tmetaKey?: boolean\n\t\t\t}\n\t\t): Promise<string>\n\t\twaitFor(\n\t\t\tquery: SkillPageQuery,\n\t\t\topts?: { timeoutMs?: number; intervalMs?: number }\n\t\t): Promise<SkillElementHandle>\n\t\tobserve(): Promise<{ url: string; title: string; content: string }>\n\t}\n\tassert: {\n\t\turlMatches(pattern: RegExp | string): Promise<void>\n\t\ttextIncludes(text: string): Promise<void>\n\t\texists(query: SkillPageQuery): Promise<void>\n\t}\n\task(question: string): Promise<string>\n\tfiles: {\n\t\tlist(): { id: string; name: string; mimeType: string; size: number }[]\n\t\tread(\n\t\t\tid: string\n\t\t): { id: string; name: string; mimeType: string; size: number; text?: string } | undefined\n\t}\n\tsignal: AbortSignal\n\tok(message: string): SkillResult\n\tfail(message: string): never\n\tmemo: {\n\t\tget(key: string): unknown\n\t\tset(key: string, value: unknown): void\n\t}\n}\n\nexport interface SkillRuntimeDeps {\n\tpageController: PageController\n\tfiles: SkillFileStore\n\tsignal: AbortSignal\n\tmemo: Map<string, unknown>\n\tonAskUser?: (question: string, options?: { signal: AbortSignal }) => Promise<string>\n}\n\n/** Parse `[index] role \"name\"` lines from an observation dump. */\nexport function parseObservationLabels(content: string): ObservationLabel[] {\n\tconst out: ObservationLabel[] = []\n\tfor (const line of content.split(/\\r?\\n/)) {\n\t\tconst match = /^\\s*\\[(\\d+)\\]\\s+(\\S+)(?:\\s+\"([^\"]*)\")?/.exec(line)\n\t\tif (!match) continue\n\t\tconst index = Number(match[1])\n\t\tconst role = match[2]\n\t\tconst name = match[3] ?? ''\n\t\tout.push({ index, role, name, label: `${role}${name ? ` \"${name}\"` : ''}` })\n\t}\n\treturn out\n}\n\nfunction nameMatches(actual: string, expected: string | RegExp | undefined): boolean {\n\tif (expected === undefined) return true\n\tif (typeof expected === 'string') {\n\t\treturn actual === expected || actual.toLowerCase() === expected.toLowerCase()\n\t}\n\treturn expected.test(actual)\n}\n\nfunction isHandle(value: unknown): value is InternalHandle {\n\treturn Boolean(value && typeof value === 'object' && (value as SkillElementHandle).__skillHandle)\n}\n\n/**\n * Build a sealed skill ctx bound to the current PageController + task signal.\n * Handles die after the next observe().\n */\nexport function createSkillContext(deps: SkillRuntimeDeps): SkillContext {\n\tconst { pageController, files, signal, memo, onAskUser } = deps\n\tlet generation = 0\n\tlet labels: ObservationLabel[] = []\n\tlet lastContent = ''\n\tlet lastUrl = ''\n\tlet lastTitle = ''\n\n\tasync function refresh(): Promise<void> {\n\t\tsignal.throwIfAborted()\n\t\tconst state = await pageController.getBrowserState()\n\t\tgeneration += 1\n\t\tlastContent = state.content\n\t\tlastUrl = state.url\n\t\tlastTitle = state.title\n\t\tlabels = parseObservationLabels(state.content)\n\t}\n\n\tfunction resolveHandle(handle: InternalHandle): InternalHandle {\n\t\tif (handle.gen !== generation) {\n\t\t\tthrow new SkillAssertError(\n\t\t\t\t'Element handle is stale after observe(). Re-find the control on this read.'\n\t\t\t)\n\t\t}\n\t\treturn handle\n\t}\n\n\tfunction matchLabel(query: SkillPageQuery): ObservationLabel {\n\t\tif (typeof query.index === 'number') {\n\t\t\tconst found = labels.find((row) => row.index === query.index)\n\t\t\tif (!found) throw new SkillAssertError(`No element at index ${query.index} on this read`)\n\t\t\treturn found\n\t\t}\n\t\tif (!query.role) {\n\t\t\tthrow new SkillAssertError('find() requires role or index')\n\t\t}\n\t\tconst role = query.role.toLowerCase()\n\t\tconst found = labels.find(\n\t\t\t(row) => row.role.toLowerCase() === role && nameMatches(row.name, query.name)\n\t\t)\n\t\tif (!found) {\n\t\t\tconst nameHint =\n\t\t\t\tquery.name === undefined\n\t\t\t\t\t? ''\n\t\t\t\t\t: typeof query.name === 'string'\n\t\t\t\t\t\t? ` name=${JSON.stringify(query.name)}`\n\t\t\t\t\t\t: ` name=${query.name}`\n\t\t\tthrow new SkillAssertError(`No element matching role=${query.role}${nameHint} on this read`)\n\t\t}\n\t\treturn found\n\t}\n\n\tfunction toHandle(row: ObservationLabel): InternalHandle {\n\t\treturn {\n\t\t\t__skillHandle: true,\n\t\t\tgen: generation,\n\t\t\tindex: row.index,\n\t\t\tlabel: row.label,\n\t\t}\n\t}\n\n\tasync function ensureObserved(): Promise<void> {\n\t\tif (generation === 0) await refresh()\n\t}\n\n\tasync function resolve(target: SkillPageQuery | SkillElementHandle): Promise<InternalHandle> {\n\t\tawait ensureObserved()\n\t\tif (isHandle(target)) return resolveHandle(target)\n\t\treturn toHandle(matchLabel(target as SkillPageQuery))\n\t}\n\n\tconst page = {\n\t\tasync find(query: SkillPageQuery) {\n\t\t\tawait ensureObserved()\n\t\t\treturn toHandle(matchLabel(query))\n\t\t},\n\t\tasync click(target: SkillPageQuery | SkillElementHandle) {\n\t\t\tconst handle = await resolve(target)\n\t\t\tconst result = await pageController.clickElement(handle.index)\n\t\t\treturn result.message\n\t\t},\n\t\tasync fill(target: SkillPageQuery | SkillElementHandle, text: string) {\n\t\t\tconst handle = await resolve(target)\n\t\t\tconst result = await pageController.inputText(handle.index, text)\n\t\t\treturn result.message\n\t\t},\n\t\tasync select(target: SkillPageQuery | SkillElementHandle, optionText: string) {\n\t\t\tconst handle = await resolve(target)\n\t\t\tconst result = await pageController.selectOption(handle.index, optionText)\n\t\t\treturn result.message\n\t\t},\n\t\tasync hover(target: SkillPageQuery | SkillElementHandle) {\n\t\t\tconst handle = await resolve(target)\n\t\t\tconst result = await pageController.hoverElement(handle.index)\n\t\t\treturn result.message\n\t\t},\n\t\tasync drag(\n\t\t\tsource: SkillPageQuery | SkillElementHandle,\n\t\t\ttarget: SkillPageQuery | SkillElementHandle,\n\t\t\tmode: 'html5' | 'pointer' | 'pointer-paced' = 'html5'\n\t\t) {\n\t\t\tconst from = await resolve(source)\n\t\t\tconst to = await resolve(target)\n\t\t\tconst result = await pageController.dragElement(from.index, to.index, mode)\n\t\t\treturn result.message\n\t\t},\n\t\tasync scroll(\n\t\t\toptions: {\n\t\t\t\tdown?: boolean\n\t\t\t\tnumPages?: number\n\t\t\t\tpixels?: number\n\t\t\t\ttarget?: SkillPageQuery | SkillElementHandle\n\t\t\t} = {}\n\t\t) {\n\t\t\tlet index: number | undefined\n\t\t\tif (options.target) {\n\t\t\t\tindex = (await resolve(options.target)).index\n\t\t\t}\n\t\t\tconst result = await pageController.scroll({\n\t\t\t\tdown: options.down ?? true,\n\t\t\t\tnumPages: options.numPages ?? 0.1,\n\t\t\t\tpixels: options.pixels,\n\t\t\t\t...(index !== undefined ? { index } : {}),\n\t\t\t})\n\t\t\treturn result.message\n\t\t},\n\t\tasync pressKey(\n\t\t\ttarget: SkillPageQuery | SkillElementHandle,\n\t\t\tkey: string,\n\t\t\toptions: {\n\t\t\t\tcode?: string\n\t\t\t\tctrlKey?: boolean\n\t\t\t\taltKey?: boolean\n\t\t\t\tshiftKey?: boolean\n\t\t\t\tmetaKey?: boolean\n\t\t\t} = {}\n\t\t) {\n\t\t\tconst handle = await resolve(target)\n\t\t\tconst result = await pageController.pressKey(handle.index, key, options)\n\t\t\treturn result.message\n\t\t},\n\t\tasync waitFor(query: SkillPageQuery, opts: { timeoutMs?: number; intervalMs?: number } = {}) {\n\t\t\tconst timeoutMs = opts.timeoutMs ?? 5000\n\t\t\tconst intervalMs = opts.intervalMs ?? 100\n\t\t\tconst started = Date.now()\n\t\t\twhile (true) {\n\t\t\t\tsignal.throwIfAborted()\n\t\t\t\tawait refresh()\n\t\t\t\ttry {\n\t\t\t\t\treturn toHandle(matchLabel(query))\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!(error instanceof SkillAssertError)) throw error\n\t\t\t\t\tif (Date.now() - started >= timeoutMs) throw error\n\t\t\t\t\tawait new Promise((r) => setTimeout(r, intervalMs))\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tasync observe() {\n\t\t\tawait refresh()\n\t\t\treturn { url: lastUrl, title: lastTitle, content: lastContent }\n\t\t},\n\t}\n\n\tconst ctx: SkillContext = {\n\t\tpage,\n\t\tassert: {\n\t\t\tasync urlMatches(pattern: RegExp | string) {\n\t\t\t\tawait ensureObserved()\n\t\t\t\tconst re = typeof pattern === 'string' ? new RegExp(pattern) : pattern\n\t\t\t\tif (!re.test(lastUrl)) {\n\t\t\t\t\tthrow new SkillAssertError(`urlMatches failed: ${lastUrl} !~ ${re}`)\n\t\t\t\t}\n\t\t\t},\n\t\t\tasync textIncludes(text: string) {\n\t\t\t\tawait ensureObserved()\n\t\t\t\tif (!lastContent.includes(text)) {\n\t\t\t\t\tthrow new SkillAssertError(`textIncludes failed: missing ${JSON.stringify(text)}`)\n\t\t\t\t}\n\t\t\t},\n\t\t\tasync exists(query: SkillPageQuery) {\n\t\t\t\tawait ensureObserved()\n\t\t\t\tmatchLabel(query)\n\t\t\t},\n\t\t},\n\t\tasync ask(question: string) {\n\t\t\tif (!onAskUser) {\n\t\t\t\tthrow new SkillFailError('ask() requires onAskUser on the agent')\n\t\t\t}\n\t\t\treturn onAskUser(question, { signal })\n\t\t},\n\t\tfiles: {\n\t\t\tlist() {\n\t\t\t\treturn files.list().map(({ id, name, mimeType, size }) => ({\n\t\t\t\t\tid,\n\t\t\t\t\tname,\n\t\t\t\t\tmimeType,\n\t\t\t\t\tsize,\n\t\t\t\t}))\n\t\t\t},\n\t\t\tread(id: string) {\n\t\t\t\tconst file = files.read(id)\n\t\t\t\tif (!file) return undefined\n\t\t\t\treturn {\n\t\t\t\t\tid: file.id,\n\t\t\t\t\tname: file.name,\n\t\t\t\t\tmimeType: file.mimeType,\n\t\t\t\t\tsize: file.size,\n\t\t\t\t\ttext: file.text,\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tsignal,\n\t\tok(message: string) {\n\t\t\treturn { ok: true, message }\n\t\t},\n\t\tfail(message: string): never {\n\t\t\tthrow new SkillFailError(message)\n\t\t},\n\t\tmemo: {\n\t\t\tget(key: string) {\n\t\t\t\treturn memo.get(key)\n\t\t\t},\n\t\t\tset(key: string, value: unknown) {\n\t\t\t\tmemo.set(key, value)\n\t\t\t},\n\t\t},\n\t}\n\n\treturn Object.freeze(ctx)\n}\n\n/** Normalize a command return value or thrown fail/assert into a tool string. */\nexport function formatSkillCommandResult(result: unknown, error?: unknown): string {\n\tif (error !== undefined) {\n\t\tif (error instanceof SkillFailError) return `❌ ${error.message}`\n\t\tif (error instanceof SkillAssertError) return `❌ assert failed: ${error.message}`\n\t\tthrow error instanceof Error\n\t\t\t? error\n\t\t\t: new Error(typeof error === 'string' ? error : 'skill command failed')\n\t}\n\tif (typeof result === 'string') return result\n\tif (result && typeof result === 'object' && 'message' in result) {\n\t\tconst raw = (result as SkillResult).message\n\t\tconst message = typeof raw === 'string' ? raw : String(raw)\n\t\tif ('ok' in result && !(result as SkillResult).ok) return `❌ ${message}`\n\t\treturn message.startsWith('✅') || message.startsWith('❌') ? message : `✅ ${message}`\n\t}\n\tif (result === undefined || result === null) return '✅ done'\n\tif (typeof result === 'string' || typeof result === 'number' || typeof result === 'boolean') {\n\t\treturn `✅ ${String(result)}`\n\t}\n\treturn '✅ done'\n}\n","/**\n * Persist agent-authored skill documents.\n * Key: page-agent-skills-v1 (IndexedDB preferred, sessionStorage fallback).\n * Callers: SkillHost save/edit/hydrate.\n */\nimport { SKILL_STORAGE_KEY } from './types'\n\nexport interface StoredSkillRecord {\n\tid: string\n\tdocument: string\n\tupdatedAt: number\n}\n\nexport interface SkillStorage {\n\tlist(): Promise<StoredSkillRecord[]>\n\tget(id: string): Promise<StoredSkillRecord | undefined>\n\tput(record: StoredSkillRecord): Promise<void>\n\tremove(id: string): Promise<void>\n}\n\nconst SESSION_PREFIX = `${SKILL_STORAGE_KEY}:`\n\nfunction sessionAvailable(): Storage | null {\n\ttry {\n\t\tif (typeof sessionStorage === 'undefined') return null\n\t\treturn sessionStorage\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction readSessionAll(): StoredSkillRecord[] {\n\tconst store = sessionAvailable()\n\tif (!store) return []\n\tconst out: StoredSkillRecord[] = []\n\tfor (let i = 0; i < store.length; i++) {\n\t\tconst key = store.key(i)\n\t\tif (!key || !key.startsWith(SESSION_PREFIX)) continue\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(store.getItem(key) || '') as StoredSkillRecord\n\t\t\tif (parsed?.id && typeof parsed.document === 'string') out.push(parsed)\n\t\t} catch {\n\t\t\t// skip corrupt\n\t\t}\n\t}\n\treturn out\n}\n\nfunction writeSession(record: StoredSkillRecord): void {\n\tconst store = sessionAvailable()\n\tif (!store) return\n\tstore.setItem(SESSION_PREFIX + record.id, JSON.stringify(record))\n}\n\nfunction removeSession(id: string): void {\n\tconst store = sessionAvailable()\n\tif (!store) return\n\tstore.removeItem(SESSION_PREFIX + id)\n}\n\n/** Pure in-memory storage for tests. */\nexport function createMemorySkillStorage(seed: StoredSkillRecord[] = []): SkillStorage {\n\tconst map = new Map(seed.map((r) => [r.id, { ...r }]))\n\treturn {\n\t\tasync list() {\n\t\t\treturn [...map.values()]\n\t\t},\n\t\tasync get(id) {\n\t\t\tconst row = map.get(id)\n\t\t\treturn row ? { ...row } : undefined\n\t\t},\n\t\tasync put(record) {\n\t\t\tmap.set(record.id, { ...record })\n\t\t},\n\t\tasync remove(id) {\n\t\t\tmap.delete(id)\n\t\t},\n\t}\n}\n\n/**\n * Browser storage: IndexedDB when available, else sessionStorage.\n * Writes always mirror to sessionStorage when present so sync hydrate works.\n */\nexport function createBrowserSkillStorage(): SkillStorage {\n\tlet dbPromise: Promise<IDBDatabase | null> | null = null\n\n\tasync function openDb(): Promise<IDBDatabase | null> {\n\t\tif (typeof indexedDB === 'undefined') return null\n\t\tif (!dbPromise) {\n\t\t\tdbPromise = new Promise((resolve) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst request = indexedDB.open(SKILL_STORAGE_KEY, 1)\n\t\t\t\t\trequest.onupgradeneeded = () => {\n\t\t\t\t\t\tconst db = request.result\n\t\t\t\t\t\tif (!db.objectStoreNames.contains('skills')) {\n\t\t\t\t\t\t\tdb.createObjectStore('skills', { keyPath: 'id' })\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trequest.onsuccess = () => resolve(request.result)\n\t\t\t\t\trequest.onerror = () => resolve(null)\n\t\t\t\t} catch {\n\t\t\t\t\tresolve(null)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\treturn dbPromise\n\t}\n\n\tasync function idbList(db: IDBDatabase): Promise<StoredSkillRecord[]> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction('skills', 'readonly')\n\t\t\tconst req = tx.objectStore('skills').getAll()\n\t\t\treq.onsuccess = () => resolve((req.result as StoredSkillRecord[]) || [])\n\t\t\treq.onerror = () => reject(req.error ?? new Error('idbList failed'))\n\t\t})\n\t}\n\n\tasync function idbGet(db: IDBDatabase, id: string): Promise<StoredSkillRecord | undefined> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction('skills', 'readonly')\n\t\t\tconst req = tx.objectStore('skills').get(id)\n\t\t\treq.onsuccess = () => resolve(req.result as StoredSkillRecord | undefined)\n\t\t\treq.onerror = () => reject(req.error ?? new Error('idbGet failed'))\n\t\t})\n\t}\n\n\tasync function idbPut(db: IDBDatabase, record: StoredSkillRecord): Promise<void> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction('skills', 'readwrite')\n\t\t\ttx.objectStore('skills').put(record)\n\t\t\ttx.oncomplete = () => resolve()\n\t\t\ttx.onerror = () => reject(tx.error ?? new Error('idbPut failed'))\n\t\t})\n\t}\n\n\tasync function idbRemove(db: IDBDatabase, id: string): Promise<void> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction('skills', 'readwrite')\n\t\t\ttx.objectStore('skills').delete(id)\n\t\t\ttx.oncomplete = () => resolve()\n\t\t\ttx.onerror = () => reject(tx.error ?? new Error('idbRemove failed'))\n\t\t})\n\t}\n\n\treturn {\n\t\tasync list() {\n\t\t\tconst db = await openDb()\n\t\t\tif (db) {\n\t\t\t\ttry {\n\t\t\t\t\tconst rows = await idbList(db)\n\t\t\t\t\tif (rows.length > 0) return rows\n\t\t\t\t} catch {\n\t\t\t\t\t// fall through\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn readSessionAll()\n\t\t},\n\t\tasync get(id) {\n\t\t\tconst db = await openDb()\n\t\t\tif (db) {\n\t\t\t\ttry {\n\t\t\t\t\tconst row = await idbGet(db, id)\n\t\t\t\t\tif (row) return row\n\t\t\t\t} catch {\n\t\t\t\t\t// fall through\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn readSessionAll().find((r) => r.id === id)\n\t\t},\n\t\tasync put(record) {\n\t\t\twriteSession(record)\n\t\t\tconst db = await openDb()\n\t\t\tif (db) {\n\t\t\t\ttry {\n\t\t\t\t\tawait idbPut(db, record)\n\t\t\t\t} catch {\n\t\t\t\t\t// session already written\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tasync remove(id) {\n\t\t\tremoveSession(id)\n\t\t\tconst db = await openDb()\n\t\t\tif (db) {\n\t\t\t\ttry {\n\t\t\t\t\tawait idbRemove(db, id)\n\t\t\t\t} catch {\n\t\t\t\t\t// session already cleared\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}\n}\n","/**\n * SkillHost — catalog, load/unload, register skill__* + list/load/save/edit/unload tools.\n * Callers: PageAgentCore constructor / execute finally / dispose.\n */\nimport type { PageController } from '@page-agent/page-controller'\nimport * as z from 'zod/v4'\n\nimport { type PageAgentTool, tool } from '../tools'\nimport { type SkillFileStore, createSkillFileStore } from './files'\nimport { parseSkillDocument } from './parse'\nimport {\n\tSkillAssertError,\n\tSkillFailError,\n\tcreateSkillContext,\n\tformatSkillCommandResult,\n} from './runtime'\nimport {\n\ttype SkillStorage,\n\ttype StoredSkillRecord,\n\tcreateBrowserSkillStorage,\n\tcreateMemorySkillStorage,\n} from './storage'\nimport {\n\tDEFAULT_REMOTE_CACHE_TTL_MS,\n\tMAX_AGENT_SKILLS,\n\tMAX_SKILL_DOCUMENT_BYTES,\n\ttype PublishDocumentResult,\n\tSKILL_COMMAND_TIMEOUT_MS,\n\ttype SkillCatalogRef,\n\ttype SkillListEntry,\n\ttype SkillManifest,\n\tSkillParseError,\n\tSkillRemoteError,\n\ttype SkillsConfig,\n\ttype SkillsRemoteAdapter,\n\tskillToolName,\n} from './types'\n\nconst DEFAULT_MAX_LOADED = 3\n\nexport interface SkillDocumentFetchResult {\n\t/** Body when the server returned content (not 304). */\n\ttext?: string\n\tetag?: string\n\t/** True when the server responded 304 Not Modified. */\n\tnotModified?: boolean\n}\n\nexport type SkillDocumentFetch = (\n\turl: string,\n\topts?: { etag?: string }\n) => Promise<SkillDocumentFetchResult>\n\nexport interface SkillHostDeps {\n\ttools: Map<string, PageAgentTool>\n\tpageController: PageController\n\tconfig: SkillsConfig\n\tgetSignal: () => AbortSignal\n\tgetOnAskUser: () =>\n\t\t((question: string, options?: { signal: AbortSignal }) => Promise<string>) | undefined\n\tstorage?: SkillStorage\n\tfiles?: SkillFileStore\n\t/** Fetch a remote skill document; may honor If-None-Match via opts.etag. */\n\tfetchDocument?: SkillDocumentFetch\n\t/**\n\t * @deprecated Prefer `fetchDocument`. Still accepted for tests that return a plain string body.\n\t */\n\tfetchText?: (url: string) => Promise<string>\n}\n\ninterface CatalogEntry {\n\tid: string\n\tname: string\n\tdescription: string\n\tscope: 'remote' | 'agent'\n\tinline?: string\n\turl?: string\n\tetag?: string\n\t/** Listed via SkillsRemoteAdapter; body fetched with remote.get on load. */\n\tremoteAdapter?: boolean\n\tversion?: number\n}\n\nfunction buildInputSchema(\n\tinput: SkillManifest['commands'][string]['input']\n): z.ZodType<Record<string, unknown>> {\n\tif (!input || Object.keys(input).length === 0) {\n\t\treturn z.object({}).passthrough()\n\t}\n\tconst shape: Record<string, z.ZodType> = {}\n\tfor (const [key, field] of Object.entries(input)) {\n\t\tlet schema: z.ZodType\n\t\tif (field.type === 'number') schema = z.number()\n\t\telse if (field.type === 'boolean') schema = z.boolean()\n\t\telse schema = z.string()\n\t\tif (field.description) schema = schema.describe(field.description)\n\t\tif (field.default !== undefined) {\n\t\t\tschema = schema.default(field.default as never)\n\t\t}\n\t\tshape[key] = schema\n\t}\n\treturn z.object(shape)\n}\n\n/** Compose task/tool abort with a wall-clock timeout for one skill command. */\nexport function createSkillCommandAbort(\n\tparent: AbortSignal,\n\ttimeoutMs: number = SKILL_COMMAND_TIMEOUT_MS\n): { signal: AbortSignal; cleanup: () => void; timeoutPromise: Promise<never> } {\n\tconst controller = new AbortController()\n\tlet settled = false\n\n\tconst onParentAbort = () => {\n\t\tif (settled) return\n\t\tcontroller.abort(parent.reason)\n\t}\n\n\tif (parent.aborted) {\n\t\tcontroller.abort(parent.reason)\n\t} else {\n\t\tparent.addEventListener('abort', onParentAbort)\n\t}\n\n\tlet timeoutReject!: (error: SkillFailError) => void\n\tconst timeoutPromise = new Promise<never>((_resolve, reject) => {\n\t\ttimeoutReject = reject\n\t})\n\n\tconst timer = setTimeout(() => {\n\t\tif (settled) return\n\t\tconst error = new SkillFailError(`skill_timeout: command exceeded ${timeoutMs}ms`)\n\t\tcontroller.abort(error)\n\t\ttimeoutReject(error)\n\t}, timeoutMs)\n\n\tconst cleanup = () => {\n\t\tif (settled) return\n\t\tsettled = true\n\t\tclearTimeout(timer)\n\t\tparent.removeEventListener('abort', onParentAbort)\n\t}\n\n\treturn { signal: controller.signal, cleanup, timeoutPromise }\n}\n\nexport class SkillHost {\n\treadonly files: SkillFileStore\n\treadonly storage: SkillStorage\n\treadonly config: SkillsConfig\n\n\t#tools: Map<string, PageAgentTool>\n\t#pageController: PageController\n\t#getSignal: () => AbortSignal\n\t#getOnAskUser: SkillHostDeps['getOnAskUser']\n\t#fetchDocument: SkillDocumentFetch\n\t#catalog = new Map<string, CatalogEntry>()\n\t#loaded = new Map<string, SkillManifest>()\n\t#memos = new Map<string, Map<string, unknown>>()\n\t#agentToolsAttached = false\n\t#maxLoaded: number\n\t#persistAgentSkills: boolean\n\t#allowedOrigins: string[] | undefined\n\t#remote: SkillsRemoteAdapter | undefined\n\t#remoteCacheTtlMs: number\n\t#remoteListCache: { at: number; ids: string[] } | null = null\n\n\tconstructor(deps: SkillHostDeps) {\n\t\tthis.#tools = deps.tools\n\t\tthis.#pageController = deps.pageController\n\t\tthis.#getSignal = deps.getSignal\n\t\tthis.#getOnAskUser = deps.getOnAskUser\n\t\tthis.config = deps.config\n\t\tthis.files = deps.files ?? createSkillFileStore()\n\t\tthis.storage = deps.storage ?? createBrowserSkillStorage()\n\t\tthis.#fetchDocument = resolveFetchDocument(deps)\n\t\tthis.#maxLoaded = deps.config.maxLoaded ?? DEFAULT_MAX_LOADED\n\t\tthis.#persistAgentSkills = deps.config.persistAgentSkills !== false\n\t\tthis.#allowedOrigins = deps.config.allowedOrigins\n\t\tthis.#remote = deps.config.remote\n\t\tthis.#remoteCacheTtlMs = deps.config.remoteCacheTtlMs ?? DEFAULT_REMOTE_CACHE_TTL_MS\n\n\t\tfor (const ref of deps.config.catalog ?? []) {\n\t\t\tthis.#ingestCatalogRef(ref)\n\t\t}\n\t}\n\n\t/** Whether list/load tools should be present. */\n\tget enabled(): boolean {\n\t\tif (this.config.enabled === false) return false\n\t\tif (this.config.enabled === true) return true\n\t\tif (this.#remote) return true\n\t\tif ((this.config.catalog?.length ?? 0) > 0) return true\n\t\tif (this.#catalog.size > 0) return true\n\t\treturn false\n\t}\n\n\tget loadedIds(): string[] {\n\t\treturn [...this.#loaded.keys()]\n\t}\n\n\t/** Compact prompt block so the LLM sees loaded skill ids + command names. */\n\tformatLoadedSkillsPromptBlock(): string {\n\t\tif (this.#loaded.size === 0) return ''\n\t\tconst lines: string[] = ['<loaded_skills>']\n\t\tfor (const [id, manifest] of this.#loaded) {\n\t\t\tconst commands = Object.keys(manifest.commands).join(', ')\n\t\t\tlines.push(`- ${id}: ${commands}`)\n\t\t}\n\t\tlines.push('</loaded_skills>', '')\n\t\treturn `${lines.join('\\n')}\\n`\n\t}\n\n\t/** Register catalog refs and optional agent-tool set. */\n\tattachAgentTools(): void {\n\t\tif (this.#agentToolsAttached) return\n\t\tthis.#agentToolsAttached = true\n\t\tthis.#tools.set('list_skills', this.#listSkillsTool())\n\t\tthis.#tools.set('load_skill', this.#loadSkillTool())\n\t\tthis.#tools.set('unload_skill', this.#unloadSkillTool())\n\t\tthis.#tools.set('save_skill', this.#saveSkillTool())\n\t\tthis.#tools.set('edit_skill', this.#editSkillTool())\n\t}\n\n\tdetachAgentTools(): void {\n\t\tif (!this.#agentToolsAttached) return\n\t\tthis.#agentToolsAttached = false\n\t\tthis.#tools.delete('list_skills')\n\t\tthis.#tools.delete('load_skill')\n\t\tthis.#tools.delete('unload_skill')\n\t\tthis.#tools.delete('save_skill')\n\t\tthis.#tools.delete('edit_skill')\n\t}\n\n\t/** Load stored agent skills into the catalog; attach tools if anything is present. */\n\tasync hydrate(): Promise<boolean> {\n\t\tconst rows = await this.storage.list()\n\t\tfor (const row of rows) {\n\t\t\ttry {\n\t\t\t\tconst manifest = parseSkillDocument(row.document)\n\t\t\t\tthis.#catalog.set(manifest.id, {\n\t\t\t\t\tid: manifest.id,\n\t\t\t\t\tname: manifest.name,\n\t\t\t\t\tdescription: manifest.description,\n\t\t\t\t\tscope: 'agent',\n\t\t\t\t\tinline: row.document,\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\t// skip corrupt documents\n\t\t\t}\n\t\t}\n\t\tif (this.enabled || rows.length > 0) {\n\t\t\tif (this.config.enabled !== false) this.attachAgentTools()\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tlist(query?: string): SkillListEntry[] {\n\t\tconst q = query?.trim().toLowerCase()\n\t\tconst entries: SkillListEntry[] = []\n\t\tfor (const entry of this.#catalog.values()) {\n\t\t\tconst loaded = this.#loaded.get(entry.id)\n\t\t\tconst hay = `${entry.id} ${entry.name} ${entry.description}`.toLowerCase()\n\t\t\tif (q && !hay.includes(q)) continue\n\t\t\tconst commands = loaded\n\t\t\t\t? Object.entries(loaded.commands).map(([name, cmd]) => ({\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tdescription: cmd.description,\n\t\t\t\t\t}))\n\t\t\t\t: this.#commandsFromInline(entry.inline)\n\t\t\tentries.push({\n\t\t\t\tid: entry.id,\n\t\t\t\tname: entry.name || entry.id,\n\t\t\t\tdescription: entry.description,\n\t\t\t\tscope: entry.scope,\n\t\t\t\tloaded: Boolean(loaded),\n\t\t\t\tcommands,\n\t\t\t})\n\t\t}\n\t\treturn entries\n\t}\n\n\tasync load(id: string): Promise<string> {\n\t\tif (this.#loaded.has(id)) {\n\t\t\treturn `Skill \"${id}\" is already loaded`\n\t\t}\n\t\tif (this.#loaded.size >= this.#maxLoaded) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'max_loaded',\n\t\t\t\t`Cannot load more than ${this.#maxLoaded} skills at once. Unload one first.`\n\t\t\t)\n\t\t}\n\n\t\tconst entry = this.#catalog.get(id)\n\t\tif (!entry) {\n\t\t\tthrow new SkillParseError('unknown_skill', `Unknown skill id \"${id}\"`)\n\t\t}\n\n\t\tconst document = await this.#resolveDocument(entry)\n\t\tconst manifest = parseSkillDocument(document)\n\t\tconst skillId = entry.id\n\t\tconst normalized: SkillManifest = { ...manifest, id: skillId, scope: entry.scope }\n\n\t\tthis.#catalog.set(skillId, {\n\t\t\t...entry,\n\t\t\tname: normalized.name,\n\t\t\tdescription: normalized.description,\n\t\t\tinline: document,\n\t\t})\n\n\t\tthis.#registerCommandTools(normalized)\n\t\tthis.#loaded.set(skillId, normalized)\n\t\tthis.#memos.set(skillId, new Map())\n\n\t\tconst commandNames = Object.keys(normalized.commands).join(', ')\n\t\treturn `✅ Loaded skill \"${skillId}\" with commands: ${commandNames}`\n\t}\n\n\tunload(id?: string): void {\n\t\tif (id) {\n\t\t\tthis.#unloadOne(id)\n\t\t\treturn\n\t\t}\n\t\tfor (const skillId of [...this.#loaded.keys()]) {\n\t\t\tthis.#unloadOne(skillId)\n\t\t}\n\t}\n\n\t/** End of task: drop loaded tools and memos; keep catalog + storage. */\n\tresetTask(): void {\n\t\tthis.unload()\n\t\tthis.files.clear()\n\t}\n\n\tasync save(document: string): Promise<string> {\n\t\tthis.#assertDocumentQuota(document)\n\t\tconst manifest = parseSkillDocument(document)\n\t\tawait this.#assertAgentSkillCountQuota(manifest.id)\n\t\tconst record: StoredSkillRecord = {\n\t\t\tid: manifest.id,\n\t\t\tdocument,\n\t\t\tupdatedAt: Date.now(),\n\t\t}\n\t\tif (this.#persistAgentSkills) {\n\t\t\tawait this.storage.put(record)\n\t\t}\n\t\tthis.#catalog.set(manifest.id, {\n\t\t\tid: manifest.id,\n\t\t\tname: manifest.name,\n\t\t\tdescription: manifest.description,\n\t\t\tscope: 'agent',\n\t\t\tinline: document,\n\t\t})\n\t\tif (this.#loaded.has(manifest.id)) {\n\t\t\tthis.#unloadOne(manifest.id)\n\t\t\tawait this.load(manifest.id)\n\t\t}\n\t\treturn `✅ Saved agent skill \"${manifest.id}\"`\n\t}\n\n\tasync edit(id: string, document: string): Promise<string> {\n\t\tconst existing = this.#catalog.get(id)\n\t\tif (!existing && !(await this.storage.get(id))) {\n\t\t\tthrow new SkillParseError('unknown_skill', `Unknown skill id \"${id}\" to edit`)\n\t\t}\n\t\tthis.#assertDocumentQuota(document)\n\t\tconst record: StoredSkillRecord = {\n\t\t\tid,\n\t\t\tdocument: ensureIdInDocument(document, id),\n\t\t\tupdatedAt: Date.now(),\n\t\t}\n\t\tconst pinned = parseSkillDocument(record.document)\n\t\tconst storedManifest = { ...pinned, id, scope: 'agent' as const }\n\n\t\tif (this.#persistAgentSkills) {\n\t\t\tawait this.storage.put(record)\n\t\t}\n\t\tthis.#catalog.set(id, {\n\t\t\tid,\n\t\t\tname: storedManifest.name,\n\t\t\tdescription: storedManifest.description,\n\t\t\tscope: 'agent',\n\t\t\tinline: record.document,\n\t\t})\n\t\tif (this.#loaded.has(id)) {\n\t\t\tthis.#unloadOne(id)\n\t\t\tawait this.load(id)\n\t\t}\n\t\treturn `✅ Edited agent skill \"${id}\"`\n\t}\n\n\t/**\n\t * Remove an agent-authored skill from storage and catalog.\n\t * Unloads it if currently loaded. Remote catalog entries are not deleted.\n\t */\n\tasync removeAgentSkill(id: string): Promise<string> {\n\t\tconst entry = this.#catalog.get(id)\n\t\tconst stored = await this.storage.get(id)\n\t\tif (!stored && (!entry || entry.scope !== 'agent')) {\n\t\t\tthrow new SkillParseError('unknown_skill', `Unknown agent skill id \"${id}\"`)\n\t\t}\n\t\tif (entry && entry.scope !== 'agent' && !stored) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'not_agent_skill',\n\t\t\t\t`Skill \"${id}\" is remote and cannot be removed from agent storage`\n\t\t\t)\n\t\t}\n\t\tif (this.#loaded.has(id)) this.#unloadOne(id)\n\t\tawait this.storage.remove(id)\n\t\tif (!entry || entry.scope === 'agent') {\n\t\t\tthis.#catalog.delete(id)\n\t\t}\n\t\treturn `✅ Removed agent skill \"${id}\"`\n\t}\n\n\t/**\n\t * Refresh the remote adapter catalog into the local catalog (scope `remote`).\n\t * Results are cached for `remoteCacheTtlMs` unless `force` is set.\n\t */\n\tasync refreshRemote(options?: {\n\t\tforce?: boolean\n\t}): Promise<{ ids: string[]; fromCache: boolean }> {\n\t\tif (!this.#remote) {\n\t\t\treturn { ids: [], fromCache: false }\n\t\t}\n\t\tconst now = Date.now()\n\t\tif (\n\t\t\t!options?.force &&\n\t\t\tthis.#remoteListCache &&\n\t\t\tnow - this.#remoteListCache.at < this.#remoteCacheTtlMs\n\t\t) {\n\t\t\treturn { ids: [...this.#remoteListCache.ids], fromCache: true }\n\t\t}\n\n\t\tlet items: Awaited<ReturnType<SkillsRemoteAdapter['list']>>\n\t\ttry {\n\t\t\titems = await this.#remote.list()\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthrow new SkillRemoteError('remote_list_failed', message)\n\t\t}\n\n\t\tconst ids: string[] = []\n\t\tconst listed = new Set<string>()\n\t\tfor (const item of items) {\n\t\t\tids.push(item.id)\n\t\t\tlisted.add(item.id)\n\t\t\tconst existing = this.#catalog.get(item.id)\n\t\t\tif (existing?.scope === 'agent') continue\n\t\t\tthis.#catalog.set(item.id, {\n\t\t\t\tid: item.id,\n\t\t\t\tname: item.name,\n\t\t\t\tdescription: item.description,\n\t\t\t\tscope: 'remote',\n\t\t\t\tetag: item.etag,\n\t\t\t\tversion: item.version,\n\t\t\t\tremoteAdapter: true,\n\t\t\t\tinline: existing?.remoteAdapter ? existing.inline : undefined,\n\t\t\t})\n\t\t}\n\n\t\tfor (const [id, entry] of [...this.#catalog.entries()]) {\n\t\t\tif (entry.remoteAdapter && !listed.has(id) && !this.#loaded.has(id)) {\n\t\t\t\tthis.#catalog.delete(id)\n\t\t\t}\n\t\t}\n\n\t\tthis.#remoteListCache = { at: now, ids }\n\t\tif (this.enabled && this.config.enabled !== false) this.attachAgentTools()\n\t\treturn { ids: [...ids], fromCache: false }\n\t}\n\n\t/**\n\t * Parse → persist locally (same as `save`) → optional `remote.put`.\n\t * Local copy is kept even when remote.put fails (`remoteError` set).\n\t */\n\tasync publishDocument(document: string): Promise<PublishDocumentResult> {\n\t\tconst manifest = parseSkillDocument(document)\n\t\tconst expectedVersion = this.#catalog.get(manifest.id)?.version\n\t\tawait this.save(document)\n\n\t\tconst result: PublishDocumentResult = {\n\t\t\tid: manifest.id,\n\t\t\tversion: manifest.version,\n\t\t\tdocument,\n\t\t}\n\n\t\tif (!this.#remote) return result\n\n\t\ttry {\n\t\t\tconst remoteResult = await this.#remote.put({\n\t\t\t\tdocument,\n\t\t\t\texpectedVersion,\n\t\t\t})\n\t\t\tresult.remote = true\n\t\t\tresult.id = remoteResult.id || manifest.id\n\t\t\tresult.version = remoteResult.version\n\t\t\tresult.etag = remoteResult.etag\n\t\t\tconst entry = this.#catalog.get(result.id)\n\t\t\tif (entry) {\n\t\t\t\tentry.etag = remoteResult.etag\n\t\t\t\tentry.version = remoteResult.version\n\t\t\t\tentry.inline = document\n\t\t\t}\n\t\t\treturn result\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tresult.remoteError = message\n\t\t\treturn result\n\t\t}\n\t}\n\n\t#unloadOne(id: string): void {\n\t\tconst manifest = this.#loaded.get(id)\n\t\tif (!manifest) return\n\t\tfor (const commandName of Object.keys(manifest.commands)) {\n\t\t\tthis.#tools.delete(skillToolName(id, commandName))\n\t\t}\n\t\tthis.#loaded.delete(id)\n\t\tthis.#memos.delete(id)\n\t}\n\n\t#registerCommandTools(manifest: SkillManifest): void {\n\t\tfor (const [commandName, command] of Object.entries(manifest.commands)) {\n\t\t\tconst toolName = skillToolName(manifest.id, commandName)\n\t\t\tconst inputSchema = buildInputSchema(command.input)\n\t\t\tthis.#tools.set(\n\t\t\t\ttoolName,\n\t\t\t\ttool({\n\t\t\t\t\tdescription: `[skill:${manifest.id}] ${command.description}`,\n\t\t\t\t\tinputSchema,\n\t\t\t\t\texecute: async (_args, { signal }) => {\n\t\t\t\t\t\tconst memo = this.#memos.get(manifest.id) ?? new Map()\n\t\t\t\t\t\tthis.#memos.set(manifest.id, memo)\n\t\t\t\t\t\tconst parent = signal ?? this.#getSignal()\n\t\t\t\t\t\tconst timed = createSkillCommandAbort(parent, SKILL_COMMAND_TIMEOUT_MS)\n\t\t\t\t\t\tconst ctx = createSkillContext({\n\t\t\t\t\t\t\tpageController: this.#pageController,\n\t\t\t\t\t\t\tfiles: this.files,\n\t\t\t\t\t\t\tsignal: timed.signal,\n\t\t\t\t\t\t\tmemo,\n\t\t\t\t\t\t\tonAskUser: this.#getOnAskUser(),\n\t\t\t\t\t\t})\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await Promise.race([\n\t\t\t\t\t\t\t\tPromise.resolve(command.run(ctx, _args as Record<string, unknown>)),\n\t\t\t\t\t\t\t\ttimed.timeoutPromise,\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t\treturn formatSkillCommandResult(result)\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\treturn formatSkillCommandResult(undefined, error)\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\ttimed.cleanup()\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t}\n\n\tasync #resolveDocument(entry: CatalogEntry): Promise<string> {\n\t\tif (entry.url) {\n\t\t\tthis.#assertUrlAllowed(entry.url)\n\t\t\tconst result = await this.#fetchDocument(entry.url, { etag: entry.etag })\n\t\t\tif (result.notModified) {\n\t\t\t\tif (!entry.inline) {\n\t\t\t\t\tthrow new SkillParseError(\n\t\t\t\t\t\t'not_modified_without_cache',\n\t\t\t\t\t\t`Skill \"${entry.id}\" returned 304 but no cached document is available`\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (result.etag) entry.etag = result.etag\n\t\t\t\treturn entry.inline\n\t\t\t}\n\t\t\tconst text = result.text ?? ''\n\t\t\tif (text.length > MAX_SKILL_DOCUMENT_BYTES) {\n\t\t\t\tthrow new SkillParseError(\n\t\t\t\t\t'skill_too_large',\n\t\t\t\t\t`Skill \"${entry.id}\" exceeds ${MAX_SKILL_DOCUMENT_BYTES} bytes`\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (result.etag) entry.etag = result.etag\n\t\t\treturn text\n\t\t}\n\t\tif (entry.remoteAdapter && this.#remote && !entry.inline) {\n\t\t\ttry {\n\t\t\t\tconst remoteDoc = await this.#remote.get(entry.id)\n\t\t\t\tif (remoteDoc.document.length > MAX_SKILL_DOCUMENT_BYTES) {\n\t\t\t\t\tthrow new SkillParseError(\n\t\t\t\t\t\t'skill_too_large',\n\t\t\t\t\t\t`Skill \"${entry.id}\" exceeds ${MAX_SKILL_DOCUMENT_BYTES} bytes`\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tentry.inline = remoteDoc.document\n\t\t\t\tentry.etag = remoteDoc.etag\n\t\t\t\tentry.version = remoteDoc.version\n\t\t\t\treturn remoteDoc.document\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof SkillParseError) throw error\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\t\tthrow new SkillRemoteError('remote_get_failed', message, entry.id)\n\t\t\t}\n\t\t}\n\t\tif (entry.inline) return entry.inline\n\t\tthrow new SkillParseError('missing_document', `Skill \"${entry.id}\" has no document source`)\n\t}\n\n\t#assertUrlAllowed(url: string): void {\n\t\tlet parsed: URL\n\t\ttry {\n\t\t\tparsed = new URL(url)\n\t\t} catch {\n\t\t\tthrow new SkillParseError('invalid_url', `Invalid skill URL: ${url}`)\n\t\t}\n\t\tconst sameOrigin = typeof location !== 'undefined' && parsed.origin === location.origin\n\t\tif (parsed.protocol !== 'https:' && !sameOrigin) {\n\t\t\tthrow new SkillParseError('insecure_url', `Skill URL must be https or same-origin: ${url}`)\n\t\t}\n\t\tif (this.#allowedOrigins && this.#allowedOrigins.length > 0) {\n\t\t\tif (!this.#allowedOrigins.includes(parsed.origin) && !sameOrigin) {\n\t\t\t\tthrow new SkillParseError(\n\t\t\t\t\t'origin_not_allowed',\n\t\t\t\t\t`Skill origin not allowed: ${parsed.origin}`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\t#assertDocumentQuota(document: string): void {\n\t\tconst bytes = new TextEncoder().encode(document).length\n\t\tif (bytes > MAX_SKILL_DOCUMENT_BYTES) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'quota_bytes',\n\t\t\t\t`Agent skill document exceeds ${MAX_SKILL_DOCUMENT_BYTES} bytes (got ${bytes})`\n\t\t\t)\n\t\t}\n\t}\n\n\tasync #assertAgentSkillCountQuota(id: string): Promise<void> {\n\t\tconst stored = await this.storage.get(id)\n\t\tif (stored) return\n\t\tif (this.#catalog.get(id)?.scope === 'agent') return\n\t\tconst count = await this.#countAgentSkills()\n\t\tif (count >= MAX_AGENT_SKILLS) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'quota_count',\n\t\t\t\t`Cannot store more than ${MAX_AGENT_SKILLS} agent skills. Remove one first.`\n\t\t\t)\n\t\t}\n\t}\n\n\tasync #countAgentSkills(): Promise<number> {\n\t\tconst ids = new Set<string>()\n\t\tfor (const entry of this.#catalog.values()) {\n\t\t\tif (entry.scope === 'agent') ids.add(entry.id)\n\t\t}\n\t\tfor (const row of await this.storage.list()) {\n\t\t\tids.add(row.id)\n\t\t}\n\t\treturn ids.size\n\t}\n\n\t/**\n\t * Expose command names for catalog UI (Arm watch, etc.) without loading tools.\n\t * Returns [] when there is no inline body or parse fails.\n\t */\n\t#commandsFromInline(inline: string | undefined): { name: string; description: string }[] {\n\t\tif (!inline?.trim()) return []\n\t\ttry {\n\t\t\tconst manifest = parseSkillDocument(inline)\n\t\t\treturn Object.entries(manifest.commands).map(([name, cmd]) => ({\n\t\t\t\tname,\n\t\t\t\tdescription: cmd.description,\n\t\t\t}))\n\t\t} catch {\n\t\t\treturn []\n\t\t}\n\t}\n\n\t#ingestCatalogRef(ref: SkillCatalogRef): void {\n\t\tif ('inline' in ref) {\n\t\t\ttry {\n\t\t\t\tconst manifest = parseSkillDocument(ref.inline)\n\t\t\t\tthis.#catalog.set(ref.id, {\n\t\t\t\t\tid: ref.id,\n\t\t\t\t\tname: manifest.name,\n\t\t\t\t\tdescription: manifest.description,\n\t\t\t\t\tscope: 'remote',\n\t\t\t\t\tinline: ref.inline,\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\tthis.#catalog.set(ref.id, {\n\t\t\t\t\tid: ref.id,\n\t\t\t\t\tname: ref.id,\n\t\t\t\t\tdescription: '',\n\t\t\t\t\tscope: 'remote',\n\t\t\t\t\tinline: ref.inline,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif ('name' in ref && 'description' in ref) {\n\t\t\tthis.#catalog.set(ref.id, {\n\t\t\t\tid: ref.id,\n\t\t\t\tname: ref.name,\n\t\t\t\tdescription: ref.description,\n\t\t\t\tscope: 'remote',\n\t\t\t\turl: ref.url,\n\t\t\t\tetag: ref.etag,\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tthis.#catalog.set(ref.id, {\n\t\t\tid: ref.id,\n\t\t\tname: ref.id,\n\t\t\tdescription: '',\n\t\t\tscope: 'remote',\n\t\t\turl: ref.url,\n\t\t\tetag: ref.etag,\n\t\t})\n\t}\n\n\t#listSkillsTool(): PageAgentTool {\n\t\treturn tool({\n\t\t\tdescription:\n\t\t\t\t'List available Page Agent skills (remote catalog + agent-authored). Optional query filters by id/name/description. Does not fetch remote bodies.',\n\t\t\tinputSchema: z.object({\n\t\t\t\tquery: z.string().optional(),\n\t\t\t}),\n\t\t\texecute: async (input) => {\n\t\t\t\tconst entries = this.list(input.query)\n\t\t\t\treturn JSON.stringify(entries, null, 2)\n\t\t\t},\n\t\t})\n\t}\n\n\t#loadSkillTool(): PageAgentTool {\n\t\treturn tool({\n\t\t\tdescription:\n\t\t\t\t'Load a skill by id. Registers its commands as skill__{id}__{command} tools for this task. Unloads automatically when the task ends. Respects maxLoaded.',\n\t\t\tinputSchema: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t}),\n\t\t\texecute: async (input) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.load(input.id)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof SkillParseError) return `❌ ${error.message}`\n\t\t\t\t\tif (error instanceof SkillFailError || error instanceof SkillAssertError) {\n\t\t\t\t\t\treturn `❌ ${error.message}`\n\t\t\t\t\t}\n\t\t\t\t\tthrow error\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t}\n\n\t#unloadSkillTool(): PageAgentTool {\n\t\treturn tool({\n\t\t\tdescription:\n\t\t\t\t'Unload a previously loaded skill by id for this task. Removes its skill__* tools. Catalog and storage are unchanged.',\n\t\t\tinputSchema: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t}),\n\t\t\texecute: async (input) => {\n\t\t\t\tif (!this.#loaded.has(input.id)) {\n\t\t\t\t\treturn `❌ Skill \"${input.id}\" is not loaded`\n\t\t\t\t}\n\t\t\t\tthis.unload(input.id)\n\t\t\t\treturn `✅ Unloaded skill \"${input.id}\"`\n\t\t\t},\n\t\t})\n\t}\n\n\t#saveSkillTool(): PageAgentTool {\n\t\treturn tool({\n\t\t\tdescription:\n\t\t\t\t'Save an agent-authored skill document (frontmatter + skill-js). Persists in browser storage and adds it to the catalog.',\n\t\t\tinputSchema: z.object({\n\t\t\t\tdocument: z.string(),\n\t\t\t}),\n\t\t\texecute: async (input) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.save(input.document)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof SkillParseError) return `❌ ${error.message}`\n\t\t\t\t\tthrow error\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t}\n\n\t#editSkillTool(): PageAgentTool {\n\t\treturn tool({\n\t\t\tdescription:\n\t\t\t\t'Replace an existing agent skill document by id. Updates storage and reloads the skill if it is currently loaded.',\n\t\t\tinputSchema: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tdocument: z.string(),\n\t\t\t}),\n\t\t\texecute: async (input) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.edit(input.id, input.document)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof SkillParseError) return `❌ ${error.message}`\n\t\t\t\t\tthrow error\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t}\n}\n\nfunction ensureIdInDocument(document: string, id: string): string {\n\tif (/^id:\\s*/m.test(document)) {\n\t\treturn document.replace(/^id:\\s*.+$/m, `id: ${id}`)\n\t}\n\treturn document.replace(/^(---\\r?\\n)/, `$1id: ${id}\\n`)\n}\n\nfunction resolveFetchDocument(deps: SkillHostDeps): SkillDocumentFetch {\n\tif (deps.fetchDocument) return deps.fetchDocument\n\tif (deps.fetchText) {\n\t\treturn async (url: string) => {\n\t\t\tconst text = await deps.fetchText!(url)\n\t\t\treturn { text, notModified: false }\n\t\t}\n\t}\n\treturn defaultFetchDocument\n}\n\nasync function defaultFetchDocument(\n\turl: string,\n\topts?: { etag?: string }\n): Promise<SkillDocumentFetchResult> {\n\tconst headers: Record<string, string> = {}\n\tif (opts?.etag) headers['If-None-Match'] = opts.etag\n\tconst response = await fetch(url, { headers })\n\tif (response.status === 304) {\n\t\treturn { notModified: true, etag: opts?.etag }\n\t}\n\tif (!response.ok) {\n\t\tthrow new SkillParseError(\n\t\t\t'fetch_failed',\n\t\t\t`Failed to fetch skill from ${url}: HTTP ${response.status}`\n\t\t)\n\t}\n\tconst text = await response.text()\n\tconst etag = response.headers.get('etag') ?? undefined\n\treturn { text, etag, notModified: false }\n}\n\n/** Test helper: host with memory storage and no browser APIs. */\nexport function createTestSkillHost(\n\tdeps: Omit<SkillHostDeps, 'storage'> & { storage?: SkillStorage }\n): SkillHost {\n\treturn new SkillHost({\n\t\t...deps,\n\t\tstorage: deps.storage ?? createMemorySkillStorage(),\n\t})\n}\n","/**\n * Skills Studio recorder — capture trusted page interactions as AX-oriented steps.\n * Does not store durable indexes; role/name come from resolveTarget, heuristics, or observation.\n */\nimport { parseObservationLabels } from './runtime'\n\nexport interface RecordedStep {\n\tid: string\n\tkind: 'click' | 'fill' | 'select' | 'note'\n\trole?: string\n\tname?: string\n\tvalue?: string\n\turl: string\n\tts: number\n\trawLabel?: string\n\tparam?: boolean\n}\n\nexport interface SkillRecorderDeps {\n\t/** Refresh page observation; return content like BrowserState.content + url */\n\tobserve: () => Promise<{ url: string; content: string }>\n\t/** Optional: resolve a DOM Element to { role, name } using current observation / page controller */\n\tresolveTarget?: (\n\t\tel: Element\n\t) => Promise<{ role?: string; name?: string; rawLabel?: string } | null>\n\troot?: Document | ParentNode\n\tignoreSelector?: string // default '[data-page-agent-ignore], [data-browser-use-ignore]'\n}\n\nconst DEFAULT_IGNORE = '[data-page-agent-ignore], [data-browser-use-ignore]'\nconst FILL_DEBOUNCE_MS = 300\n\nconst IMPLICIT_ROLES: Record<string, string> = {\n\tA: 'link',\n\tBUTTON: 'button',\n\tSELECT: 'combobox',\n\tTEXTAREA: 'textbox',\n\tIMG: 'img',\n\tSUMMARY: 'button',\n\tH1: 'heading',\n\tH2: 'heading',\n\tH3: 'heading',\n\tH4: 'heading',\n\tH5: 'heading',\n\tH6: 'heading',\n}\n\nfunction newStepId(): string {\n\tif (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n\t\treturn crypto.randomUUID()\n\t}\n\treturn `rec-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n}\n\nfunction eventElement(target: EventTarget | null): Element | null {\n\tif (!target) return null\n\tif (target instanceof Element) return target\n\tif (target instanceof Node && target.parentElement) return target.parentElement\n\treturn null\n}\n\nfunction isIgnored(el: Element, ignoreSelector: string): boolean {\n\ttry {\n\t\treturn Boolean(el.closest(ignoreSelector))\n\t} catch {\n\t\treturn false\n\t}\n}\n\nfunction inputType(el: Element): string {\n\tif (!(el instanceof HTMLInputElement)) return ''\n\treturn (el.type || 'text').toLowerCase()\n}\n\nfunction isTextLike(el: Element): boolean {\n\tif (el instanceof HTMLTextAreaElement) return true\n\tif (el instanceof HTMLElement && el.isContentEditable) return true\n\tif (!(el instanceof HTMLInputElement)) return false\n\tconst type = inputType(el)\n\treturn (\n\t\ttype === '' ||\n\t\ttype === 'text' ||\n\t\ttype === 'search' ||\n\t\ttype === 'email' ||\n\t\ttype === 'password' ||\n\t\ttype === 'tel' ||\n\t\ttype === 'url' ||\n\t\ttype === 'number' ||\n\t\ttype === 'date' ||\n\t\ttype === 'datetime-local' ||\n\t\ttype === 'month' ||\n\t\ttype === 'week' ||\n\t\ttype === 'time'\n\t)\n}\n\nfunction isSelectControl(el: Element): boolean {\n\treturn el instanceof HTMLSelectElement || el.closest('select') instanceof HTMLSelectElement\n}\n\nfunction selectElement(el: Element): HTMLSelectElement | null {\n\tif (el instanceof HTMLSelectElement) return el\n\tconst nested = el.closest('select')\n\treturn nested instanceof HTMLSelectElement ? nested : null\n}\n\nfunction heuristicRole(el: Element): string | undefined {\n\tconst explicit = el.getAttribute('role')?.trim()\n\tif (explicit) return explicit\n\n\tif (el instanceof HTMLInputElement) {\n\t\tconst type = inputType(el)\n\t\tif (type === 'checkbox') return 'checkbox'\n\t\tif (type === 'radio') return 'radio'\n\t\tif (type === 'search') return 'searchbox'\n\t\tif (type === 'range') return 'slider'\n\t\tif (type === 'button' || type === 'submit' || type === 'reset' || type === 'image') {\n\t\t\treturn 'button'\n\t\t}\n\t\tif (isTextLike(el)) return 'textbox'\n\t\treturn 'textbox'\n\t}\n\n\tif (el instanceof HTMLSelectElement) {\n\t\treturn el.multiple ? 'listbox' : 'combobox'\n\t}\n\n\tif (el instanceof HTMLElement && el.isContentEditable) return 'textbox'\n\n\treturn IMPLICIT_ROLES[el.tagName]\n}\n\nfunction associatedLabelText(el: Element): string | undefined {\n\tif (!(el instanceof HTMLElement)) return undefined\n\tconst id = el.id\n\tif (id && el.ownerDocument) {\n\t\tconst label = el.ownerDocument.querySelector(`label[for=\"${CSS.escape(id)}\"]`)\n\t\tconst text = label?.textContent?.trim()\n\t\tif (text) return text\n\t}\n\tconst wrapping = el.closest('label')\n\tif (wrapping) {\n\t\tconst clone = wrapping.cloneNode(true) as HTMLElement\n\t\tfor (const control of clone.querySelectorAll('input, select, textarea, button')) {\n\t\t\tcontrol.remove()\n\t\t}\n\t\tconst text = clone.textContent?.trim()\n\t\tif (text) return text\n\t}\n\treturn undefined\n}\n\nfunction heuristicName(el: Element): string | undefined {\n\tconst aria = el.getAttribute('aria-label')?.trim()\n\tif (aria) return aria\n\n\tconst labelledBy = el.getAttribute('aria-labelledby')?.trim()\n\tif (labelledBy && el.ownerDocument) {\n\t\tconst parts = labelledBy\n\t\t\t.split(/\\s+/)\n\t\t\t.map((id) => el.ownerDocument!.getElementById(id)?.textContent?.trim())\n\t\t\t.filter(Boolean)\n\t\tif (parts.length) return parts.join(' ')\n\t}\n\n\tconst fromLabel = associatedLabelText(el)\n\tif (fromLabel) return fromLabel\n\n\tif (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n\t\tconst title = el.getAttribute('title')?.trim()\n\t\tif (title) return title\n\t\tconst placeholder = el.getAttribute('placeholder')?.trim()\n\t\tif (placeholder) return placeholder\n\t\tconst nameAttr = el.getAttribute('name')?.trim()\n\t\tif (nameAttr) return nameAttr\n\t}\n\n\tif (el instanceof HTMLSelectElement) {\n\t\tconst title = el.getAttribute('title')?.trim()\n\t\tif (title) return title\n\t\tconst nameAttr = el.getAttribute('name')?.trim()\n\t\tif (nameAttr) return nameAttr\n\t}\n\n\tif (el instanceof HTMLImageElement) {\n\t\tconst alt = el.alt?.trim()\n\t\tif (alt) return alt\n\t}\n\n\tif (\n\t\tel instanceof HTMLButtonElement ||\n\t\tel.tagName === 'A' ||\n\t\tel.getAttribute('role') === 'button'\n\t) {\n\t\tconst text = el.textContent?.replace(/\\s+/g, ' ').trim()\n\t\tif (text) return text\n\t}\n\n\tconst text = el.textContent?.replace(/\\s+/g, ' ').trim()\n\tif (text && text.length <= 80) return text\n\n\treturn undefined\n}\n\nfunction heuristicRawLabel(el: Element, role?: string, name?: string): string {\n\tif (role && name) return `${role} \"${name}\"`\n\tif (role) return role\n\tif (name) return name\n\tconst tag = el.tagName.toLowerCase()\n\tconst id = el.id ? `#${el.id}` : ''\n\treturn `${tag}${id}`\n}\n\nfunction controlValue(el: Element): string {\n\tif (el instanceof HTMLSelectElement) {\n\t\tconst selected = el.selectedOptions[0]\n\t\treturn (selected?.textContent ?? selected?.value ?? el.value ?? '').trim()\n\t}\n\tif (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n\t\treturn el.value\n\t}\n\tif (el instanceof HTMLElement && el.isContentEditable) {\n\t\treturn el.textContent ?? ''\n\t}\n\treturn ''\n}\n\nfunction namesEqual(a: string, b: string): boolean {\n\treturn a === b || a.toLowerCase() === b.toLowerCase()\n}\n\nfunction enrichFromObservation(\n\tstep: RecordedStep,\n\tcontent: string\n): Pick<RecordedStep, 'role' | 'name' | 'rawLabel'> {\n\tconst labels = parseObservationLabels(content)\n\tif (!labels.length) return {}\n\n\tconst role = step.role?.toLowerCase()\n\tconst name = step.name\n\tconst raw = step.rawLabel\n\n\t// Prefer an exact role+name hit so resolved identity is not replaced by a sibling control.\n\tif (role && name) {\n\t\tconst exact = labels.find(\n\t\t\t(row) => row.role.toLowerCase() === role && namesEqual(row.name, name)\n\t\t)\n\t\tif (exact) {\n\t\t\treturn {\n\t\t\t\trole: exact.role,\n\t\t\t\tname: exact.name,\n\t\t\t\trawLabel: exact.label || step.rawLabel,\n\t\t\t}\n\t\t}\n\t\treturn {}\n\t}\n\n\tlet match: (typeof labels)[number] | undefined\n\n\tif (role) {\n\t\tconst roleMatches = labels.filter((row) => row.role.toLowerCase() === role)\n\t\tif (roleMatches.length === 1) match = roleMatches[0]\n\t\telse if (raw) {\n\t\t\tmatch = roleMatches.find(\n\t\t\t\t(row) =>\n\t\t\t\t\tnamesEqual(row.name, raw) ||\n\t\t\t\t\trow.label.toLowerCase() === raw.toLowerCase() ||\n\t\t\t\t\t(row.name && raw.toLowerCase().includes(row.name.toLowerCase()))\n\t\t\t)\n\t\t}\n\t}\n\n\tif (!match && name) {\n\t\tconst byName = labels.filter((row) => namesEqual(row.name, name))\n\t\tif (byName.length === 1) match = byName[0]\n\t}\n\n\tif (!match && raw) {\n\t\tmatch = labels.find(\n\t\t\t(row) =>\n\t\t\t\trow.label.toLowerCase() === raw.toLowerCase() ||\n\t\t\t\t(row.name && raw.toLowerCase().includes(`\"${row.name.toLowerCase()}\"`))\n\t\t)\n\t}\n\n\tif (!match) return {}\n\n\treturn {\n\t\trole: step.role ?? match.role,\n\t\tname: step.name ?? (match.name || undefined),\n\t\trawLabel: match.label || step.rawLabel,\n\t}\n}\n\nasync function resolveIdentity(\n\tel: Element,\n\tdeps: SkillRecorderDeps\n): Promise<{ role?: string; name?: string; rawLabel?: string }> {\n\tif (deps.resolveTarget) {\n\t\ttry {\n\t\t\tconst resolved = await deps.resolveTarget(el)\n\t\t\tif (resolved) {\n\t\t\t\tconst role = resolved.role ?? heuristicRole(el)\n\t\t\t\tconst name = resolved.name ?? heuristicName(el)\n\t\t\t\treturn {\n\t\t\t\t\trole,\n\t\t\t\t\tname,\n\t\t\t\t\trawLabel: resolved.rawLabel ?? heuristicRawLabel(el, role, name),\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to heuristics.\n\t\t}\n\t}\n\n\tconst role = heuristicRole(el)\n\tconst name = heuristicName(el)\n\treturn {\n\t\trole,\n\t\tname,\n\t\trawLabel: heuristicRawLabel(el, role, name),\n\t}\n}\n\nexport function createSkillRecorder(deps: SkillRecorderDeps): {\n\tstart(): void\n\tstop(): void\n\tclear(): void\n\tgetSteps(): RecordedStep[]\n\tsetSteps(steps: RecordedStep[]): void\n\tremoveStep(id: string): void\n\ttoggleParam(id: string, param?: boolean): void\n\treadonly recording: boolean\n} {\n\tconst ignoreSelector = deps.ignoreSelector ?? DEFAULT_IGNORE\n\tlet recording = false\n\tlet steps: RecordedStep[] = []\n\tlet fillTimer: ReturnType<typeof setTimeout> | null = null\n\tlet pendingFill: { el: Element; urlHint: string } | null = null\n\tlet lastUrl = ''\n\n\tfunction rootNode(): Document | ParentNode {\n\t\treturn deps.root ?? document\n\t}\n\n\tfunction currentUrl(): string {\n\t\ttry {\n\t\t\tconst root = rootNode()\n\t\t\tconst doc = root instanceof Document ? root : root.ownerDocument\n\t\t\treturn doc?.defaultView?.location?.href ?? lastUrl ?? ''\n\t\t} catch {\n\t\t\treturn lastUrl\n\t\t}\n\t}\n\n\tfunction pushStep(partial: Omit<RecordedStep, 'id' | 'ts'> & { ts?: number }): RecordedStep {\n\t\tconst step: RecordedStep = {\n\t\t\tid: newStepId(),\n\t\t\tts: partial.ts ?? Date.now(),\n\t\t\tkind: partial.kind,\n\t\t\turl: partial.url,\n\t\t\trole: partial.role,\n\t\t\tname: partial.name,\n\t\t\tvalue: partial.value,\n\t\t\trawLabel: partial.rawLabel,\n\t\t\tparam: partial.param,\n\t\t}\n\t\tsteps = [...steps, step]\n\t\treturn step\n\t}\n\n\tfunction updateStep(id: string, patch: Partial<RecordedStep>): void {\n\t\tsteps = steps.map((step) => (step.id === id ? { ...step, ...patch, id: step.id } : step))\n\t}\n\n\tasync function enrichStep(id: string, base: RecordedStep): Promise<void> {\n\t\ttry {\n\t\t\tconst observed = await deps.observe()\n\t\t\tlastUrl = observed.url || lastUrl\n\t\t\tconst patch = enrichFromObservation(\n\t\t\t\t{ ...base, url: observed.url || base.url },\n\t\t\t\tobserved.content\n\t\t\t)\n\t\t\tupdateStep(id, {\n\t\t\t\turl: observed.url || base.url,\n\t\t\t\t...patch,\n\t\t\t})\n\t\t} catch {\n\t\t\t// Observation is best-effort enrichment.\n\t\t}\n\t}\n\n\tasync function recordClick(el: Element): Promise<void> {\n\t\tconst identity = await resolveIdentity(el, deps)\n\t\tconst step = pushStep({\n\t\t\tkind: 'click',\n\t\t\turl: currentUrl(),\n\t\t\trole: identity.role,\n\t\t\tname: identity.name,\n\t\t\trawLabel: identity.rawLabel,\n\t\t})\n\t\tvoid enrichStep(step.id, step)\n\t}\n\n\tasync function flushFill(options: { force?: boolean } = {}): Promise<void> {\n\t\tif (fillTimer) {\n\t\t\tclearTimeout(fillTimer)\n\t\t\tfillTimer = null\n\t\t}\n\t\tconst pending = pendingFill\n\t\tpendingFill = null\n\t\tif (!pending) return\n\t\tif (!options.force && !recording) return\n\t\tif (!pending.el.isConnected) return\n\n\t\tconst identity = await resolveIdentity(pending.el, deps)\n\t\tconst value = controlValue(pending.el)\n\t\tconst step = pushStep({\n\t\t\tkind: 'fill',\n\t\t\turl: pending.urlHint || currentUrl(),\n\t\t\trole: identity.role,\n\t\t\tname: identity.name,\n\t\t\trawLabel: identity.rawLabel,\n\t\t\tvalue,\n\t\t})\n\t\tvoid enrichStep(step.id, step)\n\t}\n\n\tfunction scheduleFill(el: Element): void {\n\t\tpendingFill = { el, urlHint: currentUrl() }\n\t\tif (fillTimer) clearTimeout(fillTimer)\n\t\tfillTimer = setTimeout(() => {\n\t\t\tfillTimer = null\n\t\t\tvoid flushFill()\n\t\t}, FILL_DEBOUNCE_MS)\n\t}\n\n\tasync function recordSelect(el: HTMLSelectElement): Promise<void> {\n\t\tif (pendingFill?.el === el || (pendingFill && el.contains(pendingFill.el))) {\n\t\t\tawait flushFill()\n\t\t}\n\t\tconst identity = await resolveIdentity(el, deps)\n\t\tconst value = controlValue(el)\n\t\tconst step = pushStep({\n\t\t\tkind: 'select',\n\t\t\turl: currentUrl(),\n\t\t\trole: identity.role,\n\t\t\tname: identity.name,\n\t\t\trawLabel: identity.rawLabel,\n\t\t\tvalue,\n\t\t})\n\t\tvoid enrichStep(step.id, step)\n\t}\n\n\tfunction onClick(event: Event): void {\n\t\tif (!recording || !event.isTrusted) return\n\t\tconst el = eventElement(event.target)\n\t\tif (!el || isIgnored(el, ignoreSelector)) return\n\t\tif (isTextLike(el) || isSelectControl(el)) return\n\t\tvoid recordClick(el)\n\t}\n\n\tfunction onInput(event: Event): void {\n\t\tif (!recording || !event.isTrusted) return\n\t\tconst el = eventElement(event.target)\n\t\tif (!el || isIgnored(el, ignoreSelector)) return\n\t\tif (!isTextLike(el)) return\n\t\tscheduleFill(el)\n\t}\n\n\tfunction onChange(event: Event): void {\n\t\tif (!recording || !event.isTrusted) return\n\t\tconst el = eventElement(event.target)\n\t\tif (!el || isIgnored(el, ignoreSelector)) return\n\n\t\tconst select = selectElement(el)\n\t\tif (select) {\n\t\t\tvoid recordSelect(select)\n\t\t\treturn\n\t\t}\n\n\t\tif (isTextLike(el)) {\n\t\t\tscheduleFill(el)\n\t\t}\n\t}\n\n\treturn {\n\t\tstart(): void {\n\t\t\tif (recording) return\n\t\t\trecording = true\n\t\t\tconst root = rootNode()\n\t\t\troot.addEventListener('click', onClick, true)\n\t\t\troot.addEventListener('input', onInput, true)\n\t\t\troot.addEventListener('change', onChange, true)\n\t\t},\n\t\tstop(): void {\n\t\t\tif (!recording) return\n\t\t\trecording = false\n\t\t\tconst root = rootNode()\n\t\t\troot.removeEventListener('click', onClick, true)\n\t\t\troot.removeEventListener('input', onInput, true)\n\t\t\troot.removeEventListener('change', onChange, true)\n\t\t\tvoid flushFill({ force: true })\n\t\t},\n\t\tclear(): void {\n\t\t\tif (fillTimer) {\n\t\t\t\tclearTimeout(fillTimer)\n\t\t\t\tfillTimer = null\n\t\t\t}\n\t\t\tpendingFill = null\n\t\t\tsteps = []\n\t\t},\n\t\tgetSteps(): RecordedStep[] {\n\t\t\treturn steps.map((step) => ({ ...step }))\n\t\t},\n\t\tsetSteps(next: RecordedStep[]): void {\n\t\t\tsteps = next.map((step) => ({ ...step }))\n\t\t},\n\t\tremoveStep(id: string): void {\n\t\t\tsteps = steps.filter((step) => step.id !== id)\n\t\t},\n\t\ttoggleParam(id: string, param?: boolean): void {\n\t\t\tsteps = steps.map((step) => {\n\t\t\t\tif (step.id !== id) return step\n\t\t\t\tconst next = param === undefined ? !step.param : param\n\t\t\t\treturn { ...step, param: next || undefined }\n\t\t\t})\n\t\t},\n\t\tget recording(): boolean {\n\t\t\treturn recording\n\t\t},\n\t}\n}\n","/**\n * Deterministic Skills Studio synthesizer: RecordedStep timeline → skill Markdown + skill-js.\n * Validates with parseSkillDocument before returning.\n */\nimport { parseSkillDocument } from './parse'\nimport type { RecordedStep } from './recorder'\nimport { SKILL_ID_PATTERN, type SkillManifest, SkillParseError } from './types'\n\nexport interface SynthesizeFromStepsOptions {\n\tsteps: RecordedStep[]\n\t/** Natural-language goal (Ask mode or Record annotation). */\n\tgoal?: string\n\tid?: string\n\tname?: string\n\tdescription?: string\n\t/** Primary command name. @default 'run' */\n\tcommandName?: string\n\tversion?: number\n}\n\nexport interface SynthesizeFromStepsResult {\n\tdocument: string\n\tmanifest: SkillManifest\n}\n\nfunction slugify(raw: string): string {\n\tconst slug = raw\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, '-')\n\t\t.replace(/^-+|-+$/g, '')\n\t\t.replace(/-+/g, '-')\n\tif (SKILL_ID_PATTERN.test(slug)) return slug\n\tconst prefixed = `skill-${slug}`.replace(/-+/g, '-').replace(/-$/, '')\n\tif (SKILL_ID_PATTERN.test(prefixed)) return prefixed\n\treturn 'recorded-skill'\n}\n\nfunction jsString(value: string): string {\n\treturn JSON.stringify(value)\n}\n\nfunction fieldNameFromStep(step: RecordedStep, used: Set<string>): string {\n\tconst baseRaw = (step.name || step.role || step.kind || 'value')\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, '_')\n\t\t.replace(/^_+|_+$/g, '')\n\t\t.replace(/_+/g, '_')\n\tlet base = baseRaw && /^[a-z]/.test(baseRaw) ? baseRaw : `value_${baseRaw || 'x'}`\n\tif (!base) base = 'value'\n\tlet name = base\n\tlet n = 2\n\twhile (used.has(name)) {\n\t\tname = `${base}_${n}`\n\t\tn++\n\t}\n\tused.add(name)\n\treturn name\n}\n\nfunction actionableSteps(steps: RecordedStep[]): RecordedStep[] {\n\treturn steps.filter(\n\t\t(step) => step.kind === 'click' || step.kind === 'fill' || step.kind === 'select'\n\t)\n}\n\nfunction shouldParameterize(step: RecordedStep): boolean {\n\tif (step.kind !== 'fill' && step.kind !== 'select') return false\n\tif (step.param) return true\n\tconst value = (step.value ?? '').trim()\n\tif (!value) return false\n\t// Short literals that look like entity names / emails / ids become inputs.\n\tif (value.length >= 2 && value.length <= 64) return true\n\treturn false\n}\n\nfunction queryExpr(step: RecordedStep): string {\n\tconst parts: string[] = []\n\tif (step.role) parts.push(`role: ${jsString(step.role)}`)\n\tif (step.name) parts.push(`name: ${jsString(step.name)}`)\n\tif (parts.length === 0) {\n\t\tthrow new SkillParseError(\n\t\t\t'synthesize_unresolved',\n\t\t\t`Step ${step.id} (${step.kind}) has no role/name; fix it in the Studio timeline before synthesizing`\n\t\t)\n\t}\n\treturn `{ ${parts.join(', ')} }`\n}\n\nfunction deriveAssert(steps: RecordedStep[]): string | null {\n\tconst urls = steps.map((s) => s.url).filter(Boolean)\n\tif (urls.length < 2) return null\n\tconst first = urls[0]\n\tconst last = urls[urls.length - 1]\n\tif (!last || last === first) return null\n\ttry {\n\t\tconst path = new URL(last).pathname\n\t\tif (!path || path === '/') return null\n\t\t// Prefer RegExp constructor so `/` in paths cannot open a `//` line comment.\n\t\tconst escaped = path.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\t\treturn `await ctx.assert.urlMatches(new RegExp(${jsString(escaped)}))`\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction yamlFold(text: string): string {\n\tconst clean = text.replace(/\\s+/g, ' ').trim()\n\tif (clean.length <= 70) return clean\n\treturn `>\\n ${clean}`\n}\n\n/**\n * Build a skill document from a recorded timeline.\n * Variable fill/select values become command inputs; unresolved AX steps throw.\n */\nexport function synthesizeFromSteps(\n\toptions: SynthesizeFromStepsOptions\n): SynthesizeFromStepsResult {\n\tconst steps = options.steps\n\tif (!steps.length) {\n\t\tthrow new SkillParseError(\n\t\t\t'synthesize_empty',\n\t\t\t'Cannot synthesize a skill from an empty timeline'\n\t\t)\n\t}\n\n\tconst actions = actionableSteps(steps)\n\tif (!actions.length) {\n\t\tthrow new SkillParseError(\n\t\t\t'synthesize_no_actions',\n\t\t\t'Timeline has no click/fill/select steps to turn into skill-js'\n\t\t)\n\t}\n\n\tconst goal = options.goal?.trim()\n\tconst name = options.name?.trim() || (goal ? slugify(goal) : 'recorded-flow')\n\tconst id = options.id?.trim() || slugify(name)\n\tif (!SKILL_ID_PATTERN.test(id)) {\n\t\tthrow new SkillParseError('invalid_id', `Synthesized id \"${id}\" is invalid`)\n\t}\n\n\tconst description =\n\t\toptions.description?.trim() || goal || `Replay the recorded flow (${actions.length} steps).`\n\n\tconst commandName = options.commandName?.trim() || 'run'\n\tconst version = options.version ?? 1\n\n\tconst usedFields = new Set<string>()\n\tconst inputs: { field: string; description: string; sample: string }[] = []\n\tconst lines: string[] = []\n\n\tfor (const step of actions) {\n\t\tif (step.kind === 'click') {\n\t\t\tlines.push(` await ctx.page.click(${queryExpr(step)})`)\n\t\t\tcontinue\n\t\t}\n\n\t\tif (step.kind === 'fill') {\n\t\t\tif (shouldParameterize(step)) {\n\t\t\t\tconst field = fieldNameFromStep(step, usedFields)\n\t\t\t\tinputs.push({\n\t\t\t\t\tfield,\n\t\t\t\t\tdescription: step.name ? `Value for ${step.name}` : 'Fill value',\n\t\t\t\t\tsample: step.value ?? '',\n\t\t\t\t})\n\t\t\t\tlines.push(` await ctx.page.fill(${queryExpr(step)}, ${field})`)\n\t\t\t} else {\n\t\t\t\tlines.push(` await ctx.page.fill(${queryExpr(step)}, ${jsString(step.value ?? '')})`)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif (step.kind === 'select') {\n\t\t\tif (shouldParameterize(step)) {\n\t\t\t\tconst field = fieldNameFromStep(step, usedFields)\n\t\t\t\tinputs.push({\n\t\t\t\t\tfield,\n\t\t\t\t\tdescription: step.name ? `Option for ${step.name}` : 'Select option',\n\t\t\t\t\tsample: step.value ?? '',\n\t\t\t\t})\n\t\t\t\tlines.push(` await ctx.page.select(${queryExpr(step)}, ${field})`)\n\t\t\t} else {\n\t\t\t\tlines.push(` await ctx.page.select(${queryExpr(step)}, ${jsString(step.value ?? '')})`)\n\t\t\t}\n\t\t}\n\t}\n\n\tconst assertLine = deriveAssert(steps)\n\tif (assertLine) lines.push(` ${assertLine}`)\n\n\tconst inputBlock =\n\t\tinputs.length === 0\n\t\t\t? ''\n\t\t\t: ` input: {\\n${inputs\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(row) =>\n\t\t\t\t\t\t\t` ${row.field}: { type: 'string', description: ${jsString(row.description)} },`\n\t\t\t\t\t)\n\t\t\t\t\t.join('\\n')}\\n },\\n`\n\n\tconst destructure =\n\t\tinputs.length === 0 ? '_input' : `{ ${inputs.map((row) => row.field).join(', ')} }`\n\n\tconst okMessage = `Completed recorded flow \"${id}\"`\n\n\tconst whenToUse = goal\n\t\t? `- ${goal}`\n\t\t: '- Replay this recorded interaction sequence on a matching page.'\n\n\tconst document = `---\nname: ${id}\ndescription: ${yamlFold(description)}\nversion: ${version}\nid: ${id}\nscope: agent\n---\n\n# ${name}\n\n## When to use\n\n${whenToUse}\n\n## Notes\n\n- Re-find controls each run. Do not cache accessibility indexes across observes.\n- Generated from Skills Studio recording (${actions.length} actions).\n\n## Commands\n\n\\`\\`\\`skill-js\nexport const commands = {\n ${commandName}: {\n description: ${jsString(description)},\n${inputBlock} async run(ctx, ${destructure}) {\n${lines.join('\\n')}\n return ctx.ok(${jsString(okMessage)})\n },\n },\n}\n\\`\\`\\`\n`\n\n\tconst manifest = parseSkillDocument(document)\n\treturn { document, manifest }\n}\n","/**\n * SkillWatcher — same-tab scheduled skill ticks (observe/assert preferred).\n * Does not call PageAgentCore.execute; ticks go through runCommand.\n */\nimport {\n\tDEFAULT_SKILL_WATCH_INTERVAL_MS,\n\tMAX_SKILL_WATCHES,\n\tMIN_SKILL_WATCH_INTERVAL_MS,\n\tSkillParseError,\n\ttype SkillWatchEntry,\n\ttype SkillWatchSpec,\n\ttype SkillWatchTrigger,\n} from './types'\n\nexport interface SkillWatcherDeps {\n\t/** Run one skill command without taking the main execute lock. */\n\trunCommand: (skillId: string, command: string, input: Record<string, unknown>) => Promise<string>\n\tisTaskRunning: () => boolean\n\tgetUrl?: () => string\n\tonArmed?: (entry: SkillWatchEntry) => void\n\tonFired?: (detail: { id: string; skillId: string; command: string; message: string }) => void\n\tonStopped?: (detail: { id: string; skillId: string; reason: string }) => void\n\tnow?: () => number\n}\n\ninterface ArmedWatch {\n\tspec: Required<\n\t\tPick<\n\t\t\tSkillWatchSpec,\n\t\t\t'id' | 'skillId' | 'command' | 'everyMs' | 'trigger' | 'pauseWhileTaskRunning' | 'once'\n\t\t>\n\t> &\n\t\tPick<SkillWatchSpec, 'input' | 'urlIncludes'>\n\ttimer: ReturnType<typeof setInterval> | null\n\tlastFiredAt?: number\n\tlastError?: string\n\t/** For on-enter: already ran once since arm. */\n\tenterDone: boolean\n\t/** Last href seen for on-url edge detection. */\n\tlastUrl?: string\n\tticking: boolean\n}\n\nfunction normalizeSpec(spec: SkillWatchSpec): ArmedWatch['spec'] {\n\tconst everyMs = Math.max(\n\t\tMIN_SKILL_WATCH_INTERVAL_MS,\n\t\tspec.everyMs ?? DEFAULT_SKILL_WATCH_INTERVAL_MS\n\t)\n\tconst trigger: SkillWatchTrigger = spec.trigger ?? 'interval'\n\treturn {\n\t\tid: spec.id,\n\t\tskillId: spec.skillId,\n\t\tcommand: spec.command,\n\t\tinput: spec.input,\n\t\teveryMs,\n\t\ttrigger,\n\t\turlIncludes: spec.urlIncludes,\n\t\tpauseWhileTaskRunning: spec.pauseWhileTaskRunning !== false,\n\t\tonce: spec.once !== false,\n\t}\n}\n\nfunction isFireResult(message: string): boolean {\n\tconst trimmed = message.trim()\n\tif (!trimmed) return false\n\tif (trimmed.startsWith('❌')) return false\n\tif (/assert failed/i.test(trimmed)) return false\n\tif (/^⏳|waiting|not yet/i.test(trimmed)) return false\n\treturn trimmed.startsWith('✅') || /watch[_ ]?fire|detected|matched|changed/i.test(trimmed)\n}\n\nexport function createSkillWatcher(deps: SkillWatcherDeps): {\n\tarm(spec: SkillWatchSpec): SkillWatchEntry\n\tdisarm(id: string, reason?: string): boolean\n\tdisarmAll(reason?: string): void\n\tlist(): SkillWatchEntry[]\n\t/** Manual tick (tests / on-enter from Panel show). */\n\ttick(id: string): Promise<'fired' | 'skipped' | 'waiting' | 'error' | 'missing'>\n\tnotifyEnter(): void\n\tdispose(): void\n} {\n\tconst watches = new Map<string, ArmedWatch>()\n\tconst now = () => (deps.now ? deps.now() : Date.now())\n\n\tfunction toEntry(watch: ArmedWatch): SkillWatchEntry {\n\t\treturn {\n\t\t\tid: watch.spec.id,\n\t\t\tskillId: watch.spec.skillId,\n\t\t\tcommand: watch.spec.command,\n\t\t\ttrigger: watch.spec.trigger,\n\t\t\teveryMs: watch.spec.everyMs,\n\t\t\tarmed: true,\n\t\t\tlastFiredAt: watch.lastFiredAt,\n\t\t\tlastError: watch.lastError,\n\t\t}\n\t}\n\n\tfunction clearTimer(watch: ArmedWatch): void {\n\t\tif (watch.timer) {\n\t\t\tclearInterval(watch.timer)\n\t\t\twatch.timer = null\n\t\t}\n\t}\n\n\tfunction disarm(id: string, reason = 'disarmed'): boolean {\n\t\tconst watch = watches.get(id)\n\t\tif (!watch) return false\n\t\tclearTimer(watch)\n\t\twatches.delete(id)\n\t\tdeps.onStopped?.({ id, skillId: watch.spec.skillId, reason })\n\t\treturn true\n\t}\n\n\tasync function runTick(\n\t\tid: string\n\t): Promise<'fired' | 'skipped' | 'waiting' | 'error' | 'missing'> {\n\t\tconst watch = watches.get(id)\n\t\tif (!watch) return 'missing'\n\t\tif (watch.ticking) return 'skipped'\n\t\tif (watch.spec.pauseWhileTaskRunning && deps.isTaskRunning()) return 'skipped'\n\n\t\tif (watch.spec.trigger === 'on-url') {\n\t\t\tconst href = deps.getUrl?.() ?? ''\n\t\t\tconst needle = watch.spec.urlIncludes ?? ''\n\t\t\tif (needle && !href.includes(needle)) {\n\t\t\t\twatch.lastUrl = href\n\t\t\t\treturn 'skipped'\n\t\t\t}\n\t\t\tif (watch.lastUrl === href && watch.enterDone) return 'skipped'\n\t\t}\n\n\t\tif (watch.spec.trigger === 'on-enter' && watch.enterDone) return 'skipped'\n\n\t\twatch.ticking = true\n\t\ttry {\n\t\t\tconst message = await deps.runCommand(\n\t\t\t\twatch.spec.skillId,\n\t\t\t\twatch.spec.command,\n\t\t\t\twatch.spec.input ?? {}\n\t\t\t)\n\t\t\twatch.lastError = undefined\n\t\t\tif (!isFireResult(message)) {\n\t\t\t\treturn 'waiting'\n\t\t\t}\n\t\t\twatch.lastFiredAt = now()\n\t\t\twatch.enterDone = true\n\t\t\twatch.lastUrl = deps.getUrl?.() ?? watch.lastUrl\n\t\t\tdeps.onFired?.({\n\t\t\t\tid: watch.spec.id,\n\t\t\t\tskillId: watch.spec.skillId,\n\t\t\t\tcommand: watch.spec.command,\n\t\t\t\tmessage,\n\t\t\t})\n\t\t\tif (watch.spec.once) {\n\t\t\t\tdisarm(id, 'fired-once')\n\t\t\t}\n\t\t\treturn 'fired'\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\twatch.lastError = message\n\t\t\treturn 'error'\n\t\t} finally {\n\t\t\twatch.ticking = false\n\t\t}\n\t}\n\n\tfunction arm(spec: SkillWatchSpec): SkillWatchEntry {\n\t\tif (!spec.id?.trim() || !spec.skillId?.trim() || !spec.command?.trim()) {\n\t\t\tthrow new SkillParseError('invalid_watch', 'Watch requires id, skillId, and command')\n\t\t}\n\t\tif (watches.has(spec.id)) {\n\t\t\tdisarm(spec.id, 're-armed')\n\t\t}\n\t\tif (watches.size >= MAX_SKILL_WATCHES) {\n\t\t\tthrow new SkillParseError('watch_quota', `At most ${MAX_SKILL_WATCHES} watches can be armed`)\n\t\t}\n\n\t\tconst normalized = normalizeSpec(spec)\n\t\tconst watch: ArmedWatch = {\n\t\t\tspec: normalized,\n\t\t\ttimer: null,\n\t\t\tenterDone: false,\n\t\t\tticking: false,\n\t\t\tlastUrl: deps.getUrl?.(),\n\t\t}\n\t\twatches.set(normalized.id, watch)\n\n\t\tif (normalized.trigger === 'interval') {\n\t\t\twatch.timer = setInterval(() => {\n\t\t\t\tvoid runTick(normalized.id)\n\t\t\t}, normalized.everyMs)\n\t\t}\n\n\t\tconst entry = toEntry(watch)\n\t\tdeps.onArmed?.(entry)\n\n\t\tif (normalized.trigger === 'on-enter') {\n\t\t\tvoid runTick(normalized.id)\n\t\t}\n\n\t\treturn entry\n\t}\n\n\treturn {\n\t\tarm,\n\t\tdisarm,\n\t\tdisarmAll(reason = 'dispose') {\n\t\t\tfor (const id of [...watches.keys()]) disarm(id, reason)\n\t\t},\n\t\tlist() {\n\t\t\treturn [...watches.values()].map(toEntry)\n\t\t},\n\t\ttick: runTick,\n\t\tnotifyEnter() {\n\t\t\tfor (const watch of watches.values()) {\n\t\t\t\tif (watch.spec.trigger !== 'on-enter') continue\n\t\t\t\twatch.enterDone = false\n\t\t\t\tvoid runTick(watch.spec.id)\n\t\t\t}\n\t\t},\n\t\tdispose() {\n\t\t\tfor (const watch of watches.values()) clearTimer(watch)\n\t\t\twatches.clear()\n\t\t},\n\t}\n}\n\nexport type SkillWatcher = ReturnType<typeof createSkillWatcher>\n","/**\n * Copyright (C) 2025 Alibaba Group Holding Limited\n * Copyright (C) 2026 SimonLuvRamen\n * All rights reserved.\n */\nimport { InvokeError, LLM, type Tool } from '@page-agent/llms'\nimport type { BrowserState, PageController } from '@page-agent/page-controller'\nimport chalk from 'chalk'\nimport * as z from 'zod/v4'\n\nimport SYSTEM_PROMPT from './prompts/system_prompt.md?raw'\nimport {\n\tMAX_TASK_FILE_BYTES,\n\ttype PublishDocumentResult,\n\ttype RecordedStep,\n\ttype SkillAttachment,\n\ttype SkillListEntry,\n\ttype SkillWatchEntry,\n\ttype SkillWatchSpec,\n\ttype SynthesizeFromStepsOptions,\n\ttype SynthesizeFromStepsResult,\n\tcreateSkillRecorder,\n\tcreateSkillWatcher,\n\tparseSkillDocument,\n\treadTaskFileBlob,\n\tskillToolName,\n\tsynthesizeFromSteps,\n} from './skills'\nimport { SkillHost } from './skills/host'\nimport { tools } from './tools'\nimport type {\n\tAgentActivity,\n\tAgentConfig,\n\tAgentReflection,\n\tAgentStatus,\n\tAgentStepEvent,\n\tExecutionResult,\n\tHistoricalEvent,\n\tMacroToolInput,\n\tMacroToolResult,\n} from './types'\nimport { assert, fetchLlmsTxt, normalizeResponse, suppress, uid, waitFor } from './utils'\n\nexport { tool, type PageAgentTool, type ToolContext } from './tools'\nexport type * from './types'\n/** Skills protocol, runtime host, and storage helpers. */\nexport {\n\tDEFAULT_REMOTE_CACHE_TTL_MS,\n\tSKILL_COMMAND_PATTERN,\n\tSKILL_COMMAND_TIMEOUT_MS,\n\tSKILL_ID_PATTERN,\n\tSKILL_JS_FENCE,\n\tSKILL_STORAGE_KEY,\n\tSkillHost,\n\tSkillParseError,\n\tSkillRemoteError,\n\tMAX_AGENT_SKILLS,\n\tMAX_SKILL_DOCUMENT_BYTES,\n\tMAX_TASK_FILE_BYTES,\n\tcreateBrowserSkillStorage,\n\tcreateMemorySkillStorage,\n\tcreateSkillCommandAbort,\n\tcreateSkillFileStore,\n\tcreateSkillRecorder,\n\tcreateTestSkillHost,\n\tevaluateSkillCommands,\n\textractSkillJs,\n\tparseFrontmatterYaml,\n\tparseSkillDocument,\n\treadTaskFileBlob,\n\tskillToolName,\n\tsplitFrontmatter,\n\tsynthesizeFromSteps,\n\ttype PublishDocumentResult,\n\ttype SkillAttachment,\n\ttype SkillCatalogRef,\n\ttype SkillCommandDefinition,\n\ttype SkillContext,\n\ttype SkillDocumentFetch,\n\ttype SkillDocumentFetchResult,\n\ttype SkillFileStore,\n\ttype SkillInputField,\n\ttype SkillInputType,\n\ttype SkillListEntry,\n\ttype SkillManifest,\n\ttype SkillScope,\n\ttype SkillStorage,\n\ttype SkillsConfig,\n\ttype SkillsRemoteAdapter,\n\ttype RecordedStep,\n\ttype SkillRecorderDeps,\n\ttype SynthesizeFromStepsOptions,\n\ttype SynthesizeFromStepsResult,\n} from './skills'\n\nexport type PageAgentCoreConfig = AgentConfig & { pageController: PageController }\n\n/**\n * AI agent for browser automation.\n *\n * @remarks\n * ## Re-act Agent Loop\n * - step\n * - observe (gather information about current environment and context)\n * - think (LLM calling)\n * - reflection (evaluate history, generate memory, short-term planning)\n * - action (give the action to approach the next goal)\n * - act (execute the action)\n * - loop\n *\n * ## Event System\n * - `statuschange` - Agent status transitions (idle → running → completed/error/stopped)\n * - `historychange` - History events updated (persistent, part of agent memory)\n * - `activity` - Real-time activity feedback (transient, for UI only)\n * - `dispose` - Agent cleanup triggered\n * - `skills:publish` / `skills:published` / `skills:publish-failed` - Studio publish path\n * - `skills:remote-refresh` - Remote adapter catalog refresh\n * - `skills:removed` - Agent skill removed from storage\n *\n * ## Information Streams\n * 1. **History Events** (`history` array)\n * - Persistent event stream that forms agent's memory\n * - Included in LLM context across steps\n * - Types: steps, observations, user takeovers, llm errors\n *\n * 2. **Activity Events** (via `activity` event)\n * - Transient UI feedback during task execution\n * - NOT included in LLM context\n * - Types: thinking, executing, executed, retrying, error\n */\nexport class PageAgentCore extends EventTarget {\n\treadonly id = uid()\n\treadonly config: PageAgentCoreConfig & { maxSteps: number }\n\treadonly tools: typeof tools\n\t/** PageController for DOM operations */\n\treadonly pageController: PageController\n\n\ttask = ''\n\ttaskId = ''\n\t/** History events */\n\thistory: HistoricalEvent[] = []\n\t/** Whether this agent has been disposed */\n\tdisposed = false\n\n\t/**\n\t * Called when the agent needs to ask the user questions.\n\t * If unset, the `ask_user` tool will be disabled.\n\t * Implementations should reject the promise when `signal` aborts.\n\t * @example onAskUser: (q) => window.prompt(q) || ''\n\t */\n\tonAskUser?: (question: string, options?: { signal: AbortSignal }) => Promise<string>\n\n\t#status: AgentStatus = 'idle'\n\t#llm: LLM\n\t/**\n\t * Task cancellation primitive: its signal reaches the LLM fetch, tools\n\t * (via `ctx.signal`) and async callbacks. Aborted only by `stop`/`dispose`\n\t * (during a task) or task setup, always WITHOUT a reason so `signal.reason`\n\t * stays a standard `AbortError`.\n\t */\n\t#abortController = new AbortController()\n\t#observations: string[] = []\n\n\t/** Resolves when the current run has fully settled. Awaited by `stop()`. */\n\t#running: Promise<void> = Promise.resolve()\n\t#lastResult: ExecutionResult | null = null\n\t#skillHost: SkillHost | null = null\n\t#skillRecorder: ReturnType<typeof createSkillRecorder> | null = null\n\t#skillWatcher: ReturnType<typeof createSkillWatcher> | null = null\n\n\t/** internal states during a single task execution */\n\t#states = {\n\t\t/** Accumulated wait time in seconds */\n\t\ttotalWaitTime: 0,\n\t\t/** For detecting navigation */\n\t\tlastURL: '',\n\t\t/** Browser state */\n\t\tbrowserState: null as BrowserState | null,\n\t}\n\n\tconstructor(config: PageAgentCoreConfig) {\n\t\tsuper()\n\n\t\tthis.config = { ...config, maxSteps: config.maxSteps ?? 40 }\n\n\t\tthis.#llm = new LLM(this.config)\n\t\tthis.tools = new Map(tools)\n\t\tthis.pageController = config.pageController\n\n\t\tthis.#llm.addEventListener('retry', (e) => {\n\t\t\tconst { attempt, maxAttempts, lastError } = (e as CustomEvent).detail\n\t\t\tthis.#emitActivity({ type: 'retrying', attempt, maxAttempts })\n\t\t\tthis.history.push({\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: String(lastError),\n\t\t\t\trawResponse: (lastError as InvokeError).rawResponse,\n\t\t\t})\n\t\t\tthis.history.push({\n\t\t\t\ttype: 'retry',\n\t\t\t\tmessage: `LLM retry attempt ${attempt} of ${maxAttempts}`,\n\t\t\t\tattempt,\n\t\t\t\tmaxAttempts,\n\t\t\t})\n\t\t\tthis.#emitHistoryChange()\n\t\t})\n\n\t\tif (this.config.customTools) {\n\t\t\tfor (const [name, tool] of Object.entries(this.config.customTools)) {\n\t\t\t\tif (tool === null) {\n\t\t\t\t\tthis.tools.delete(name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tthis.tools.set(name, tool)\n\t\t\t}\n\t\t}\n\n\t\t// On by default. Set `experimentalScriptExecutionTool: false` to remove the tool.\n\t\tif (this.config.experimentalScriptExecutionTool === false) {\n\t\t\tthis.tools.delete('execute_javascript')\n\t\t}\n\n\t\tthis.#initSkills()\n\t}\n\n\t/** Optional skills host (null when skills are not configured / hydrated). */\n\tget skillHost(): SkillHost | null {\n\t\treturn this.#skillHost\n\t}\n\n\t/**\n\t * Attach a file for the current task so skill-js can read it via `ctx.files`.\n\t * Accepts a browser `File`/`Blob` or a pre-read payload. Cleared when the task ends.\n\t */\n\tasync attachTaskFile(\n\t\tfile:\n\t\t\t| (Blob & { name?: string })\n\t\t\t| {\n\t\t\t\t\tname: string\n\t\t\t\t\tmimeType?: string\n\t\t\t\t\ttext?: string\n\t\t\t\t\tdataBase64?: string\n\t\t\t\t\tsize?: number\n\t\t\t }\n\t): Promise<SkillAttachment> {\n\t\tif (!this.#skillHost) {\n\t\t\tthrow new Error('Task file attachments are unavailable because skills are disabled.')\n\t\t}\n\t\tif (typeof Blob !== 'undefined' && file instanceof Blob) {\n\t\t\tconst payload = await readTaskFileBlob(file)\n\t\t\treturn this.#skillHost.files.add(payload)\n\t\t}\n\t\tconst plain = file as {\n\t\t\tname: string\n\t\t\tmimeType?: string\n\t\t\ttext?: string\n\t\t\tdataBase64?: string\n\t\t\tsize?: number\n\t\t}\n\t\tif (!plain.name?.trim()) throw new Error('Attachment name is required')\n\t\tif (plain.text === undefined && plain.dataBase64 === undefined) {\n\t\t\tthrow new Error('Attachment needs text or dataBase64 content')\n\t\t}\n\t\tconst size =\n\t\t\tplain.size ??\n\t\t\t(plain.text !== undefined\n\t\t\t\t? new TextEncoder().encode(plain.text).length\n\t\t\t\t: Math.ceil(((plain.dataBase64?.length ?? 0) * 3) / 4))\n\t\tif (size > MAX_TASK_FILE_BYTES) {\n\t\t\tthrow new Error(`File \"${plain.name}\" is too large (max ${MAX_TASK_FILE_BYTES} bytes)`)\n\t\t}\n\t\treturn this.#skillHost.files.add({\n\t\t\tname: plain.name.trim(),\n\t\t\tmimeType: plain.mimeType || 'application/octet-stream',\n\t\t\ttext: plain.text,\n\t\t\tdataBase64: plain.dataBase64,\n\t\t\tsize,\n\t\t})\n\t}\n\n\t/** List files attached for the current task (for panel chips / debugging). */\n\tlistTaskFiles(): SkillAttachment[] {\n\t\treturn this.#skillHost?.files.list() ?? []\n\t}\n\n\t/** Remove one attached file before the task ends. */\n\tremoveTaskFile(id: string): boolean {\n\t\treturn this.#skillHost?.files.remove(id) ?? false\n\t}\n\n\t/**\n\t * Publish a skill document: local save first, then optional remote.put.\n\t * Dispatches `skills:publish`, then `skills:published` or `skills:publish-failed`.\n\t * On remote failure the local copy is kept and `skills:publish-failed` fires with `remote: true`.\n\t */\n\tasync publishSkill(document: string, source?: string): Promise<PublishDocumentResult> {\n\t\tif (!this.#skillHost) {\n\t\t\tthrow new Error('Skills are disabled.')\n\t\t}\n\n\t\tlet manifestSummary: {\n\t\t\tid: string\n\t\t\tname: string\n\t\t\tdescription: string\n\t\t\tversion: number\n\t\t}\n\t\ttry {\n\t\t\tconst manifest = parseSkillDocument(document)\n\t\t\tmanifestSummary = {\n\t\t\t\tid: manifest.id,\n\t\t\t\tname: manifest.name,\n\t\t\t\tdescription: manifest.description,\n\t\t\t\tversion: manifest.version,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.dispatchEvent(\n\t\t\t\tnew CustomEvent('skills:publish-failed', {\n\t\t\t\t\tdetail: { error: message, remote: false },\n\t\t\t\t})\n\t\t\t)\n\t\t\tthrow error\n\t\t}\n\n\t\tthis.dispatchEvent(\n\t\t\tnew CustomEvent('skills:publish', {\n\t\t\t\tdetail: { document, manifest: manifestSummary, source },\n\t\t\t})\n\t\t)\n\n\t\ttry {\n\t\t\tconst result = await this.#skillHost.publishDocument(document)\n\t\t\tif (result.remoteError) {\n\t\t\t\tthis.dispatchEvent(\n\t\t\t\t\tnew CustomEvent('skills:publish-failed', {\n\t\t\t\t\t\tdetail: {\n\t\t\t\t\t\t\tid: result.id,\n\t\t\t\t\t\t\terror: result.remoteError,\n\t\t\t\t\t\t\tremote: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\treturn result\n\t\t\t}\n\t\t\tthis.dispatchEvent(\n\t\t\t\tnew CustomEvent('skills:published', {\n\t\t\t\t\tdetail: {\n\t\t\t\t\t\tid: result.id,\n\t\t\t\t\t\tversion: result.version,\n\t\t\t\t\t\tdocument: result.document,\n\t\t\t\t\t\tremote: Boolean(result.remote),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t)\n\t\t\treturn result\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.dispatchEvent(\n\t\t\t\tnew CustomEvent('skills:publish-failed', {\n\t\t\t\t\tdetail: {\n\t\t\t\t\t\tid: manifestSummary.id,\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tremote: false,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t)\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/**\n\t * Refresh remote adapter catalog into the host. Dispatches `skills:remote-refresh`.\n\t */\n\tasync refreshRemoteSkills(options?: {\n\t\tforce?: boolean\n\t}): Promise<{ ids: string[]; fromCache: boolean }> {\n\t\tif (!this.#skillHost) {\n\t\t\treturn { ids: [], fromCache: false }\n\t\t}\n\t\tconst result = await this.#skillHost.refreshRemote(options)\n\t\tthis.dispatchEvent(\n\t\t\tnew CustomEvent('skills:remote-refresh', {\n\t\t\t\tdetail: { ids: result.ids, fromCache: result.fromCache },\n\t\t\t})\n\t\t)\n\t\treturn result\n\t}\n\n\t/**\n\t * Remove an agent-authored skill from storage + catalog.\n\t * Dispatches `skills:removed` on success.\n\t */\n\tasync removeAgentSkill(id: string): Promise<string> {\n\t\tif (!this.#skillHost) {\n\t\t\tthrow new Error('Skills are disabled.')\n\t\t}\n\t\tconst result = await this.#skillHost.removeAgentSkill(id)\n\t\tthis.dispatchEvent(new CustomEvent('skills:removed', { detail: { id } }))\n\t\treturn result\n\t}\n\n\t/** Ensure a SkillHost exists for Studio (unless skills were explicitly disabled). */\n\t#ensureSkillHost(): SkillHost {\n\t\tif (this.#skillHost) return this.#skillHost\n\t\tif (this.config.skills?.enabled === false) {\n\t\t\tthrow new Error('Skills are disabled.')\n\t\t}\n\t\tconst host = new SkillHost({\n\t\t\ttools: this.tools,\n\t\t\tpageController: this.pageController,\n\t\t\tconfig: { ...(this.config.skills ?? {}), enabled: true },\n\t\t\tgetSignal: () => this.#abortController.signal,\n\t\t\tgetOnAskUser: () => this.onAskUser,\n\t\t})\n\t\thost.attachAgentTools()\n\t\tthis.#skillHost = host\n\t\tvoid host.hydrate().catch((error) => {\n\t\t\tconsole.warn('[PageAgent] skills hydrate failed', error)\n\t\t})\n\t\treturn host\n\t}\n\n\t/** Start capturing trusted page interactions for Skills Studio Record. */\n\tasync startSkillRecording(): Promise<void> {\n\t\tthis.#ensureSkillHost()\n\t\tif (this.#skillRecorder?.recording) return\n\t\tawait suppress(() => this.pageController.hideMask())\n\t\tif (!this.#skillRecorder) {\n\t\t\tthis.#skillRecorder = createSkillRecorder({\n\t\t\t\tobserve: async () => {\n\t\t\t\t\tconst state = await this.pageController.getBrowserState()\n\t\t\t\t\treturn { url: state.url, content: state.content }\n\t\t\t\t},\n\t\t\t\troot: typeof document !== 'undefined' ? document : undefined,\n\t\t\t})\n\t\t}\n\t\tthis.#skillRecorder.start()\n\t\tthis.dispatchEvent(new CustomEvent('skills:recording', { detail: { recording: true } }))\n\t}\n\n\t/** Stop capturing interactions (keeps the current timeline). */\n\tstopSkillRecording(): void {\n\t\tif (!this.#skillRecorder) return\n\t\tthis.#skillRecorder.stop()\n\t\tthis.dispatchEvent(new CustomEvent('skills:recording', { detail: { recording: false } }))\n\t}\n\n\tisSkillRecording(): boolean {\n\t\treturn Boolean(this.#skillRecorder?.recording)\n\t}\n\n\tgetRecordedSteps(): RecordedStep[] {\n\t\treturn this.#skillRecorder?.getSteps() ?? []\n\t}\n\n\tsetRecordedSteps(steps: RecordedStep[]): void {\n\t\tif (!this.#skillRecorder) {\n\t\t\tthis.#skillRecorder = createSkillRecorder({\n\t\t\t\tobserve: async () => {\n\t\t\t\t\tconst state = await this.pageController.getBrowserState()\n\t\t\t\t\treturn { url: state.url, content: state.content }\n\t\t\t\t},\n\t\t\t\troot: typeof document !== 'undefined' ? document : undefined,\n\t\t\t})\n\t\t}\n\t\tthis.#skillRecorder.setSteps(steps)\n\t}\n\n\tremoveRecordedStep(id: string): void {\n\t\tthis.#skillRecorder?.removeStep(id)\n\t}\n\n\ttoggleRecordedStepParam(id: string, param?: boolean): void {\n\t\tthis.#skillRecorder?.toggleParam(id, param)\n\t}\n\n\tclearRecordedSteps(): void {\n\t\tthis.#skillRecorder?.clear()\n\t}\n\n\t/** Deterministic timeline → skill document (validated via parseSkillDocument). */\n\tsynthesizeSkill(\n\t\toptions: Omit<SynthesizeFromStepsOptions, 'steps'> = {}\n\t): SynthesizeFromStepsResult {\n\t\tconst steps = this.getRecordedSteps()\n\t\treturn synthesizeFromSteps({ ...options, steps })\n\t}\n\n\tlistSkillsCatalog(query?: string): SkillListEntry[] {\n\t\treturn this.#ensureSkillHost().list(query)\n\t}\n\n\tasync loadSkill(id: string): Promise<string> {\n\t\treturn this.#ensureSkillHost().load(id)\n\t}\n\n\tunloadSkill(id?: string): void {\n\t\tthis.#ensureSkillHost().unload(id)\n\t}\n\n\t/**\n\t * Load a skill and execute its primary command (`run` or the first command).\n\t * Returns the tool output string.\n\t */\n\tasync testSkill(id: string, input: Record<string, unknown> = {}): Promise<string> {\n\t\tconst host = this.#ensureSkillHost()\n\t\tawait host.load(id)\n\t\tconst entry = host.list().find((row) => row.id === id)\n\t\tconst commands = entry?.commands ?? []\n\t\tconst commandName = commands.find((c) => c.name === 'run')?.name ?? commands[0]?.name\n\t\tif (!commandName) {\n\t\t\tthrow new Error(`Skill \"${id}\" has no commands to test`)\n\t\t}\n\t\tconst toolName = `skill__${id}__${commandName}`\n\t\tconst tool = this.tools.get(toolName)\n\t\tif (!tool) {\n\t\t\tthrow new Error(`Tool \"${toolName}\" is not registered after load`)\n\t\t}\n\t\tconst result = await tool.execute.call(this, input, {\n\t\t\tsignal: this.#abortController.signal,\n\t\t})\n\t\treturn typeof result === 'string' ? result : String(result ?? '')\n\t}\n\n\t#ensureSkillWatcher(): ReturnType<typeof createSkillWatcher> {\n\t\tif (this.#skillWatcher) return this.#skillWatcher\n\t\tthis.#ensureSkillHost()\n\t\tthis.#skillWatcher = createSkillWatcher({\n\t\t\trunCommand: async (skillId, command, input) => {\n\t\t\t\tawait this.loadSkill(skillId)\n\t\t\t\tconst toolName = skillToolName(skillId, command)\n\t\t\t\tconst tool = this.tools.get(toolName)\n\t\t\t\tif (!tool) {\n\t\t\t\t\tthrow new Error(`Watch tool \"${toolName}\" is not registered`)\n\t\t\t\t}\n\t\t\t\tconst result = await tool.execute.call(this, input, {\n\t\t\t\t\tsignal: this.#abortController.signal,\n\t\t\t\t})\n\t\t\t\treturn typeof result === 'string' ? result : String(result ?? '')\n\t\t\t},\n\t\t\tisTaskRunning: () => this.#status === 'running',\n\t\t\tgetUrl: () => {\n\t\t\t\ttry {\n\t\t\t\t\treturn typeof location !== 'undefined' ? location.href : ''\n\t\t\t\t} catch {\n\t\t\t\t\treturn ''\n\t\t\t\t}\n\t\t\t},\n\t\t\tonArmed: (entry) => {\n\t\t\t\tthis.dispatchEvent(new CustomEvent('skills:watch-armed', { detail: entry }))\n\t\t\t},\n\t\t\tonFired: (detail) => {\n\t\t\t\tthis.dispatchEvent(new CustomEvent('skills:watch-fired', { detail }))\n\t\t\t\tthis.#emitHistoryChange({\n\t\t\t\t\ttype: 'observation',\n\t\t\t\t\tcontent: `Watch fired (${detail.skillId}/${detail.command}): ${detail.message}`,\n\t\t\t\t})\n\t\t\t},\n\t\t\tonStopped: (detail) => {\n\t\t\t\tthis.dispatchEvent(new CustomEvent('skills:watch-stopped', { detail }))\n\t\t\t},\n\t\t})\n\t\treturn this.#skillWatcher\n\t}\n\n\tarmSkillWatch(spec: SkillWatchSpec): SkillWatchEntry {\n\t\treturn this.#ensureSkillWatcher().arm(spec)\n\t}\n\n\tdisarmSkillWatch(id: string): boolean {\n\t\treturn this.#skillWatcher?.disarm(id) ?? false\n\t}\n\n\tlistSkillWatches(): SkillWatchEntry[] {\n\t\treturn this.#skillWatcher?.list() ?? []\n\t}\n\n\t/** Re-run on-enter watches (call when the panel is shown). */\n\tnotifySkillWatchEnter(): void {\n\t\tthis.#skillWatcher?.notifyEnter()\n\t}\n\n\t#initSkills(): void {\n\t\tconst skillsConfig = this.config.skills\n\t\tif (skillsConfig?.enabled === false) return\n\n\t\tconst host = new SkillHost({\n\t\t\ttools: this.tools,\n\t\t\tpageController: this.pageController,\n\t\t\tconfig: skillsConfig ?? {},\n\t\t\tgetSignal: () => this.#abortController.signal,\n\t\t\tgetOnAskUser: () => this.onAskUser,\n\t\t})\n\t\tthis.#skillHost = host\n\n\t\tif (skillsConfig) {\n\t\t\thost.attachAgentTools()\n\t\t}\n\n\t\t// Agent-authored skills in storage also enable list/load without config.catalog.\n\t\tvoid host.hydrate().catch((error) => {\n\t\t\tconsole.warn('[PageAgent] skills hydrate failed', error)\n\t\t})\n\t}\n\n\t#resetSkillsForTaskEnd(): void {\n\t\tthis.#skillHost?.resetTask()\n\t}\n\n\t/** Get current agent status */\n\tget status(): AgentStatus {\n\t\treturn this.#status\n\t}\n\n\t/** Result of the most recent run, or `null` before the first run completes. */\n\tget lastResult(): ExecutionResult | null {\n\t\treturn this.#lastResult\n\t}\n\n\t/** Emit statuschange event */\n\t#emitStatusChange(): void {\n\t\tthis.dispatchEvent(new Event('statuschange'))\n\t}\n\n\t/** Emit historychange event */\n\t#emitHistoryChange(pushHistoricalEvent?: HistoricalEvent): void {\n\t\tif (pushHistoricalEvent) this.history.push(pushHistoricalEvent)\n\t\tthis.dispatchEvent(new Event('historychange'))\n\t}\n\n\t/**\n\t * Emit activity event - for transient UI feedback\n\t * @param activity - Current agent activity\n\t */\n\t#emitActivity(activity: AgentActivity): void {\n\t\tthis.dispatchEvent(new CustomEvent('activity', { detail: activity }))\n\t}\n\n\t/** Update status and emit event */\n\t#setStatus(status: AgentStatus): void {\n\t\tif (this.#status !== status) {\n\t\t\tthis.#status = status\n\t\t\tthis.#emitStatusChange()\n\t\t}\n\t}\n\n\t/**\n\t * Push an observation message to the history event stream.\n\t * This will be visible in <agent_history> and remain persistent in memory across steps.\n\t * @experimental @internal\n\t * @note history change will be emitted before next step starts\n\t */\n\tpushObservation(content: string): void {\n\t\tthis.#observations.push(content)\n\t}\n\n\t/**\n\t * Stop the current task and wait until the run has fully settled (including lifecycle hooks).\n\t * @note never await .stop() in a lifecycle hook.\n\t */\n\tasync stop(): Promise<void> {\n\t\tif (this.#status !== 'running') return\n\t\tthis.#abortController.abort()\n\t\tawait this.#running\n\t}\n\n\t/**\n\t * external errors (pre-checks/config/hooks) will threw;\n\t * agent errors will be caught and added to history, and return a failed result\n\t */\n\tasync execute(task: string): Promise<ExecutionResult> {\n\t\t// pre-checks\n\t\tif (this.disposed) throw new Error('PageAgent has been disposed. Create a new instance.')\n\t\tif (this.#status === 'running') throw new Error('A task is already running.')\n\t\tif (!task) throw new Error('Task is required')\n\n\t\tthis.task = task\n\t\tthis.taskId = uid()\n\n\t\tthis.history = []\n\t\tthis.#observations = []\n\t\tthis.#states = { totalWaitTime: 0, lastURL: '', browserState: null }\n\t\tthis.#abortController = new AbortController()\n\t\tconst signal = this.#abortController.signal\n\n\t\tlet resolveRunning!: () => void\n\t\tthis.#running = new Promise<void>((r) => (resolveRunning = r))\n\n\t\tthis.#setStatus('running')\n\t\tthis.#emitHistoryChange()\n\n\t\t// Disable ask_user tool if onAskUser is not set\n\t\tif (!this.onAskUser) this.tools.delete('ask_user')\n\n\t\tconst onBeforeStep = this.config.onBeforeStep\n\t\tconst onAfterStep = this.config.onAfterStep\n\t\tconst onBeforeTask = this.config.onBeforeTask\n\t\tconst onAfterTask = this.config.onAfterTask\n\t\tconst stepDelay = this.config.stepDelay ?? 0.4\n\t\tconst maxSteps = this.config.maxSteps\n\n\t\tlet step = 0\n\t\tlet taskResult: ExecutionResult\n\t\tlet finalStatus: AgentStatus = 'error'\n\n\t\tawait suppress(() => this.pageController.showMask())\n\n\t\t// graceful exit\n\t\ttry {\n\t\t\tawait onBeforeTask?.(this)\n\n\t\t\twhile (true) {\n\t\t\t\tawait onBeforeStep?.(this, step)\n\n\t\t\t\t// handle internal agent errors\n\t\t\t\ttry {\n\t\t\t\t\tconsole.group(`step: ${step}`)\n\n\t\t\t\t\t// @note It's convenient to treat stepDelay as part of the next step.\n\t\t\t\t\t// Maybe move it to a dedicated try block for better semantics?\n\t\t\t\t\tif (step > 0) await waitFor(stepDelay, signal)\n\n\t\t\t\t\tsignal.throwIfAborted()\n\n\t\t\t\t\t// observe\n\n\t\t\t\t\tconsole.log(chalk.blue.bold('👀 Observing...'))\n\n\t\t\t\t\tthis.#states.browserState = await this.pageController.getBrowserState()\n\t\t\t\t\tawait this.#handleObservations(step)\n\n\t\t\t\t\t// assemble prompts\n\n\t\t\t\t\tconst messages = [\n\t\t\t\t\t\t{ role: 'system' as const, content: this.#getSystemPrompt() },\n\t\t\t\t\t\t{ role: 'user' as const, content: await this.#assembleUserPrompt() },\n\t\t\t\t\t]\n\n\t\t\t\t\tconst macroTool = { AgentOutput: this.#packMacroTool() }\n\n\t\t\t\t\t// invoke LLM\n\n\t\t\t\t\tconsole.log(chalk.blue.bold('🧠 Thinking...'))\n\t\t\t\t\tthis.#emitActivity({ type: 'thinking' })\n\n\t\t\t\t\tconst result = await this.#llm.invoke(messages, macroTool, signal, {\n\t\t\t\t\t\ttoolChoiceName: 'AgentOutput',\n\t\t\t\t\t\tnormalizeResponse: (res) => normalizeResponse(res, this.tools),\n\t\t\t\t\t})\n\n\t\t\t\t\t// assemble history\n\n\t\t\t\t\tconst macroResult = result.toolResult as MacroToolResult\n\t\t\t\t\tconst input = macroResult.input\n\t\t\t\t\tconst output = macroResult.output\n\t\t\t\t\tconst reflection: Partial<AgentReflection> = {\n\t\t\t\t\t\tevaluation_previous_goal: input.evaluation_previous_goal,\n\t\t\t\t\t\tmemory: input.memory,\n\t\t\t\t\t\tnext_goal: input.next_goal,\n\t\t\t\t\t}\n\t\t\t\t\tconst actionName = Object.keys(input.action)[0]\n\t\t\t\t\tconst action: AgentStepEvent['action'] = {\n\t\t\t\t\t\tname: actionName,\n\t\t\t\t\t\tinput: input.action[actionName],\n\t\t\t\t\t\toutput: output,\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.#emitHistoryChange({\n\t\t\t\t\t\ttype: 'step',\n\t\t\t\t\t\tstepIndex: step,\n\t\t\t\t\t\treflection,\n\t\t\t\t\t\taction,\n\t\t\t\t\t\tusage: result.usage,\n\t\t\t\t\t\trawResponse: result.rawResponse,\n\t\t\t\t\t\trawRequest: result.rawRequest,\n\t\t\t\t\t})\n\n\t\t\t\t\tif (actionName === 'done') {\n\t\t\t\t\t\tconst success = action.input?.success ?? false\n\t\t\t\t\t\tconst data = action.input?.text || 'no text provided'\n\t\t\t\t\t\tconsole.log(chalk.green.bold('Task completed'), success, data)\n\t\t\t\t\t\ttaskResult = { success, data, history: this.history }\n\t\t\t\t\t\tthis.#lastResult = taskResult\n\t\t\t\t\t\tfinalStatus = 'completed'\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t// catch block must not throw error. otherwise the error may be overridden if finally block also throws error.\n\n\t\t\t\t\tconst isAbortError = (error as any)?.name === 'AbortError'\n\t\t\t\t\tif (!isAbortError) console.error('Task failed', error)\n\t\t\t\t\tconst message = isAbortError ? 'Task aborted' : String(error)\n\t\t\t\t\tthis.#emitActivity({ type: 'error', message: message })\n\t\t\t\t\tthis.#emitHistoryChange({ type: 'error', message: message, rawResponse: error })\n\t\t\t\t\ttaskResult = { success: false, data: message, history: this.history }\n\t\t\t\t\tthis.#lastResult = taskResult\n\t\t\t\t\tfinalStatus = isAbortError ? 'stopped' : 'error'\n\t\t\t\t\tbreak\n\t\t\t\t} finally {\n\t\t\t\t\t// finally block runs before the break above.\n\n\t\t\t\t\tconsole.groupEnd()\n\t\t\t\t\t// @note hook may throw error.\n\t\t\t\t\t// which will override the `break` above and be handled as an external error.\n\t\t\t\t\t// as expected.\n\t\t\t\t\tawait onAfterStep?.(this, this.history)\n\t\t\t\t}\n\n\t\t\t\tstep++\n\t\t\t\tif (step > maxSteps) {\n\t\t\t\t\tconst message = 'Step count exceeded maximum limit'\n\t\t\t\t\tconsole.error(message)\n\t\t\t\t\tthis.#emitActivity({ type: 'error', message: message })\n\t\t\t\t\tthis.#emitHistoryChange({ type: 'error', message: message })\n\t\t\t\t\ttaskResult = { success: false, data: message, history: this.history }\n\t\t\t\t\tthis.#lastResult = taskResult\n\t\t\t\t\tfinalStatus = 'error'\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} // while\n\n\t\t\tawait onAfterTask?.(this, taskResult)\n\n\t\t\treturn taskResult\n\t\t} catch (error) {\n\t\t\tthis.#emitActivity({ type: 'error', message: String(error) })\n\t\t\tfinalStatus = 'error'\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tthis.#resetSkillsForTaskEnd()\n\t\t\tawait suppress(() => this.pageController.cleanUpHighlights())\n\t\t\tawait suppress(() => this.pageController.hideMask())\n\t\t\tthis.#abortController.abort()\n\t\t\tresolveRunning()\n\t\t\tthis.#setStatus(finalStatus)\n\t\t}\n\t}\n\n\t/**\n\t * Merge all tools into a single MacroTool with the following input:\n\t * - thinking: string\n\t * - evaluation_previous_goal: string\n\t * - memory: string\n\t * - next_goal: string\n\t * - action: { toolName: toolInput }\n\t * where action must be selected from tools defined in this.tools\n\t */\n\t#packMacroTool(): Tool<MacroToolInput, MacroToolResult> {\n\t\tconst tools = this.tools\n\n\t\tconst actionSchemas = Array.from(tools.entries()).map(([toolName, tool]) => {\n\t\t\treturn z.object({ [toolName]: tool.inputSchema }).describe(tool.description)\n\t\t})\n\n\t\tconst actionSchema = z.union(actionSchemas as unknown as [z.ZodType, z.ZodType, ...z.ZodType[]])\n\n\t\tconst macroToolSchema = z.object({\n\t\t\t// thinking: z.string().optional(),\n\t\t\tevaluation_previous_goal: z.string().optional(),\n\t\t\tmemory: z.string().optional(),\n\t\t\tnext_goal: z.string().optional(),\n\t\t\taction: actionSchema,\n\t\t})\n\n\t\treturn {\n\t\t\tdescription: 'You MUST call this tool every step!',\n\t\t\tinputSchema: macroToolSchema as z.ZodType<MacroToolInput>,\n\t\t\texecute: async (input: MacroToolInput): Promise<MacroToolResult> => {\n\t\t\t\tconst signal = this.#abortController.signal\n\t\t\t\tsignal.throwIfAborted()\n\n\t\t\t\tconsole.log(chalk.blue.bold('MacroTool input'), input)\n\t\t\t\tconst action = input.action\n\n\t\t\t\tconst toolName = Object.keys(action)[0]\n\t\t\t\tconst toolInput = action[toolName]\n\n\t\t\t\t// Build reflection text, only include non-empty fields\n\t\t\t\tconst reflectionLines: string[] = []\n\t\t\t\tif (input.evaluation_previous_goal)\n\t\t\t\t\treflectionLines.push(`✅: ${input.evaluation_previous_goal}`)\n\t\t\t\tif (input.memory) reflectionLines.push(`💾: ${input.memory}`)\n\t\t\t\tif (input.next_goal) reflectionLines.push(`🎯: ${input.next_goal}`)\n\n\t\t\t\tconst reflectionText = reflectionLines.length > 0 ? reflectionLines.join('\\n') : ''\n\n\t\t\t\tif (reflectionText) {\n\t\t\t\t\tconsole.log(reflectionText)\n\t\t\t\t}\n\n\t\t\t\t// Find the corresponding tool\n\t\t\t\tconst tool = tools.get(toolName)\n\t\t\t\tassert(tool, `Tool ${toolName} not found`)\n\n\t\t\t\tconsole.log(chalk.blue.bold(`Executing tool: ${toolName}`), toolInput)\n\n\t\t\t\t// Emit executing activity\n\t\t\t\tthis.#emitActivity({ type: 'executing', tool: toolName, input: toolInput })\n\n\t\t\t\tconst startTime = Date.now()\n\n\t\t\t\tconst result = await tool.execute.bind(this)(toolInput, { signal })\n\t\t\t\t// Enforce abort even if the tool ignored the signal and resolved normally.\n\t\t\t\tsignal.throwIfAborted()\n\n\t\t\t\tconst duration = Date.now() - startTime\n\t\t\t\tconsole.log(chalk.green.bold(`Tool (${toolName}) executed for ${duration}ms`), result)\n\n\t\t\t\t// Emit executed activity\n\t\t\t\tthis.#emitActivity({\n\t\t\t\t\ttype: 'executed',\n\t\t\t\t\ttool: toolName,\n\t\t\t\t\tinput: toolInput,\n\t\t\t\t\toutput: result,\n\t\t\t\t\tduration,\n\t\t\t\t})\n\n\t\t\t\t// counting wait time\n\t\t\t\tif (toolName === 'wait') {\n\t\t\t\t\tthis.#states.totalWaitTime += toolInput?.seconds || 0\n\t\t\t\t} else {\n\t\t\t\t\tthis.#states.totalWaitTime = 0\n\t\t\t\t}\n\n\t\t\t\t// Return structured result\n\t\t\t\treturn {\n\t\t\t\t\tinput,\n\t\t\t\t\toutput: result,\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t}\n\n\t/**\n\t * Get system prompt, dynamically replace language settings based on configured language.\n\t *\n\t * REVERSIBLE (2026-11-23, system prompt override): a custom prompt is added to the built-in one. It\n\t * replaces it only with `overrideSystemPrompt: true`, so the built-in rules are never lost by accident.\n\t */\n\t#getSystemPrompt(): string {\n\t\tconst custom = this.config.customSystemPrompt\n\t\tif (custom?.trim() && this.config.overrideSystemPrompt === true) {\n\t\t\treturn custom\n\t\t}\n\n\t\tconst targetLanguage = this.config.language === 'zh-CN' ? '中文' : 'English'\n\t\tconst systemPrompt = SYSTEM_PROMPT.replace(\n\t\t\t/Default working language: \\*\\*.*?\\*\\*/,\n\t\t\t`Default working language: **${targetLanguage}**`\n\t\t)\n\n\t\tif (!custom?.trim()) return systemPrompt\n\t\treturn `${systemPrompt}\\n\\n<additional_instructions>\\n${custom.trim()}\\n</additional_instructions>`\n\t}\n\n\t/**\n\t * Get instructions from config\n\t */\n\tasync #getInstructions(): Promise<string> {\n\t\tconst { instructions, experimentalLlmsTxt } = this.config\n\n\t\tconst systemInstructions = instructions?.system?.trim()\n\t\tlet pageInstructions: string | undefined\n\n\t\tconst url = this.#states.browserState?.url || ''\n\t\tif (instructions?.getPageInstructions && url) {\n\t\t\ttry {\n\t\t\t\tpageInstructions = instructions.getPageInstructions(url)?.trim()\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red('[PageAgent] Failed to execute getPageInstructions callback:'),\n\t\t\t\t\terror\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst llmsTxt = experimentalLlmsTxt && url ? await fetchLlmsTxt(url) : undefined\n\n\t\tif (!systemInstructions && !pageInstructions && !llmsTxt) return ''\n\n\t\tlet result = '<instructions>\\n'\n\n\t\tif (systemInstructions) {\n\t\t\tresult += `<system_instructions>\\n${systemInstructions}\\n</system_instructions>\\n`\n\t\t}\n\n\t\tif (pageInstructions) {\n\t\t\tresult += `<page_instructions>\\n${pageInstructions}\\n</page_instructions>\\n`\n\t\t}\n\n\t\tif (llmsTxt) {\n\t\t\tresult += `<llms_txt>\\n${llmsTxt}\\n</llms_txt>\\n`\n\t\t}\n\n\t\tresult += '</instructions>\\n\\n'\n\n\t\treturn result\n\t}\n\n\t/**\n\t * Generate system observations before each step\n\t * @todo loop detection\n\t * @todo console error\n\t */\n\tasync #handleObservations(step: number): Promise<void> {\n\t\t// Accumulated wait time warning\n\t\tif (this.#states.totalWaitTime >= 3) {\n\t\t\tthis.pushObservation(\n\t\t\t\t`You have waited ${this.#states.totalWaitTime} seconds accumulatively. ` +\n\t\t\t\t\t`DO NOT wait any longer unless you have a good reason.`\n\t\t\t)\n\t\t}\n\n\t\t// Detect URL change\n\t\tconst currentURL = this.#states.browserState?.url || ''\n\t\tif (currentURL !== this.#states.lastURL) {\n\t\t\tthis.pushObservation(`Page navigated to → ${currentURL}`)\n\t\t\tthis.#states.lastURL = currentURL\n\t\t\tawait waitFor(0.5) // wait for page to stabilize\n\t\t}\n\n\t\t// Remaining steps warning\n\t\tconst remaining = this.config.maxSteps - step\n\t\tif (remaining === 5) {\n\t\t\tthis.pushObservation(\n\t\t\t\t`⚠️ Only ${remaining} steps remaining. ` +\n\t\t\t\t\t`Consider wrapping up or calling done with partial results.`\n\t\t\t)\n\t\t} else if (remaining === 2) {\n\t\t\tthis.pushObservation(\n\t\t\t\t`⚠️ Critical: Only ${remaining} steps left! You must finish the task or call done immediately.`\n\t\t\t)\n\t\t}\n\n\t\t// Push observations to history and emit\n\t\tif (this.#observations.length > 0) {\n\t\t\tfor (const content of this.#observations) {\n\t\t\t\tthis.history.push({ type: 'observation', content })\n\t\t\t\tconsole.log(chalk.cyan('Observation:'), content)\n\t\t\t}\n\t\t\tthis.#observations = []\n\t\t\tthis.#emitHistoryChange()\n\t\t}\n\t}\n\n\tasync #assembleUserPrompt(): Promise<string> {\n\t\tconst browserState = this.#states.browserState!\n\n\t\tlet prompt = ''\n\n\t\t// <instructions> (optional)\n\n\t\tprompt += await this.#getInstructions()\n\n\t\t// <agent_state>\n\t\t// - <user_request>\n\t\t// - <step_info>\n\t\t// <agent_state>\n\n\t\tconst stepCount = this.history.filter((e) => e.type === 'step').length\n\n\t\tprompt += '<agent_state>\\n'\n\t\tprompt += '<user_request>\\n'\n\t\tprompt += `${this.task}\\n`\n\t\tprompt += '</user_request>\\n'\n\t\tprompt += '<step_info>\\n'\n\t\tprompt += `Step ${stepCount + 1} of ${this.config.maxSteps} max possible steps\\n`\n\t\tprompt += `Current time: ${new Date().toLocaleString()} (${Intl.DateTimeFormat().resolvedOptions().timeZone})\\n`\n\t\tprompt += '</step_info>\\n'\n\t\tprompt += '</agent_state>\\n\\n'\n\n\t\tconst loadedSkillsBlock = this.#skillHost?.formatLoadedSkillsPromptBlock() ?? ''\n\t\tif (loadedSkillsBlock) prompt += loadedSkillsBlock\n\n\t\t// <agent_history>\n\t\t// - <step_N> for steps\n\t\t// - <sys> for observations and system messages\n\n\t\tprompt += '<agent_history>\\n'\n\n\t\tlet stepIndex = 0\n\t\tfor (const event of this.history) {\n\t\t\tif (event.type === 'step') {\n\t\t\t\tstepIndex++\n\t\t\t\tprompt += `<step_${stepIndex}>\\n`\n\t\t\t\tprompt += `Evaluation of Previous Step: ${event.reflection.evaluation_previous_goal}\\n`\n\t\t\t\tprompt += `Memory: ${event.reflection.memory}\\n`\n\t\t\t\tprompt += `Next Goal: ${event.reflection.next_goal}\\n`\n\t\t\t\tprompt += `Action Results: ${event.action.output}\\n`\n\t\t\t\tprompt += `</step_${stepIndex}>\\n`\n\t\t\t} else if (event.type === 'observation') {\n\t\t\t\tprompt += `<sys>${event.content}</sys>\\n`\n\t\t\t} else if (event.type === 'user_takeover') {\n\t\t\t\tprompt += `<sys>User took over control and made changes to the page</sys>\\n`\n\t\t\t} else if (event.type === 'error') {\n\t\t\t\t// Error events are mainly for panel rendering, not included in LLM context\n\t\t\t\t// to avoid polluting the agent's reasoning with transient errors\n\t\t\t}\n\t\t}\n\n\t\tprompt += '</agent_history>\\n\\n'\n\n\t\t// <browser_state>\n\n\t\tlet pageContent = browserState.content\n\t\tif (this.config.transformPageContent) {\n\t\t\tpageContent = await this.config.transformPageContent(pageContent)\n\t\t}\n\n\t\tprompt += '<browser_state>\\n'\n\t\tprompt += browserState.header + '\\n'\n\t\tprompt += pageContent + '\\n'\n\t\tprompt += browserState.footer + '\\n\\n'\n\t\tprompt += '</browser_state>\\n\\n'\n\n\t\treturn prompt\n\t}\n\n\tdispose() {\n\t\tconsole.log('Disposing PageAgent...')\n\t\tthis.disposed = true\n\t\tthis.#skillWatcher?.dispose()\n\t\tthis.#skillWatcher = null\n\t\tthis.stopSkillRecording()\n\t\tthis.#resetSkillsForTaskEnd()\n\t\tthis.pageController.dispose()\n\t\t// this.history = []\n\t\tthis.#abortController.abort()\n\n\t\t// Emit dispose event for UI cleanup\n\t\tthis.dispatchEvent(new Event('dispose'))\n\n\t\tthis.config.onDispose?.(this)\n\t}\n}\n","// ======= type guards =======\n// @note instanceof fails for elements inside iframes\n\nexport function isHTMLElement(el: unknown): el is HTMLElement {\n\t// @todo either specify to HTMLElement or allow Element here.\n\treturn !!el && (el as Node).nodeType === 1\n}\n\nexport function isInputElement(el: Element): el is HTMLInputElement {\n\treturn el?.nodeType === 1 && el.tagName === 'INPUT'\n}\n\nexport function isTextAreaElement(el: Element): el is HTMLTextAreaElement {\n\treturn el?.nodeType === 1 && el.tagName === 'TEXTAREA'\n}\n\nexport function isSelectElement(el: Element): el is HTMLSelectElement {\n\treturn el?.nodeType === 1 && el.tagName === 'SELECT'\n}\n\nexport function isAnchorElement(el: Element): el is HTMLAnchorElement {\n\treturn el?.nodeType === 1 && el.tagName === 'A'\n}\n\n// ======= iframe helpers =======\n\n/** Iframe offset for translating element coordinates to top-frame viewport. */\nexport function getIframeOffset(element: HTMLElement): { x: number; y: number } {\n\tconst frame = element.ownerDocument.defaultView?.frameElement as HTMLElement | null\n\tif (!frame) return { x: 0, y: 0 }\n\tconst rect = frame.getBoundingClientRect()\n\treturn { x: rect.left, y: rect.top }\n}\n\n/**\n * Get native value setter from the element's own prototype (iframe-safe).\n * @note for React\n */\nexport function getNativeValueSetter(element: HTMLInputElement | HTMLTextAreaElement) {\n\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\treturn Object.getOwnPropertyDescriptor(Object.getPrototypeOf(element) as object, 'value')!\n\t\t.set as (v: string) => void\n}\n\n// ======= general utils =======\n\nexport async function waitFor(seconds: number): Promise<void> {\n\tawait new Promise((resolve) => setTimeout(resolve, seconds * 1000))\n}\n\n// ======= mask events =======\n\n/**\n * Move the visual pointer to a position within an element.\n * @param x - x coordinate in the element's document viewport\n * @param y - y coordinate in the element's document viewport\n */\nexport async function movePointerToElement(element: HTMLElement, x: number, y: number) {\n\tconst offset = getIframeOffset(element)\n\n\twindow.dispatchEvent(\n\t\tnew CustomEvent('PageAgent::MovePointerTo', {\n\t\t\tdetail: { x: x + offset.x, y: y + offset.y },\n\t\t})\n\t)\n\n\tawait waitFor(0.3)\n}\n\nexport async function clickPointer() {\n\twindow.dispatchEvent(new CustomEvent('PageAgent::ClickPointer'))\n}\n\nexport async function enablePassThrough() {\n\twindow.dispatchEvent(new CustomEvent('PageAgent::EnablePassThrough'))\n}\n\nexport async function disablePassThrough() {\n\twindow.dispatchEvent(new CustomEvent('PageAgent::DisablePassThrough'))\n}\n","/**\n * Copyright (C) 2025 Alibaba Group Holding Limited\n * All rights reserved.\n */\nimport type { InteractiveElementDomNode } from './dom/dom_tree/type'\nimport {\n\tclickPointer,\n\tdisablePassThrough,\n\tenablePassThrough,\n\tgetNativeValueSetter,\n\tisHTMLElement,\n\tisInputElement,\n\tisSelectElement,\n\tisTextAreaElement,\n\tmovePointerToElement,\n\twaitFor,\n} from './utils'\n\n/**\n * Get the HTMLElement by index from a selectorMap.\n * @private Internal method, subject to change at any time.\n */\nexport function getElementByIndex(\n\tselectorMap: Map<number, InteractiveElementDomNode>,\n\tindex: number\n): HTMLElement {\n\tconst interactiveNode = selectorMap.get(index)\n\tif (!interactiveNode) {\n\t\tthrow new Error(`No interactive element found at index ${index}`)\n\t}\n\n\tconst element = interactiveNode.ref\n\tif (!element) {\n\t\tthrow new Error(`Element at index ${index} does not have a reference`)\n\t}\n\n\tif (!isHTMLElement(element)) {\n\t\tthrow new Error(`Element at index ${index} is not an HTMLElement`)\n\t}\n\n\treturn element\n}\n\nlet lastClickedElement: HTMLElement | null = null\n\nfunction blurLastClickedElement() {\n\tif (lastClickedElement) {\n\t\tlastClickedElement.dispatchEvent(new PointerEvent('pointerout', { bubbles: true }))\n\t\tlastClickedElement.dispatchEvent(new PointerEvent('pointerleave', { bubbles: false }))\n\t\tlastClickedElement.dispatchEvent(new MouseEvent('mouseout', { bubbles: true }))\n\t\tlastClickedElement.dispatchEvent(new MouseEvent('mouseleave', { bubbles: false }))\n\t\tlastClickedElement.blur()\n\t\tlastClickedElement = null\n\t}\n}\n\n/**\n * Simulate a full click following W3C Pointer Events + UI Events spec order:\n * pointerover/enter → mouseover/enter → pointerdown → mousedown → [focus] →\n * pointerup → mouseup → click\n *\n * @private Internal method, subject to change at any time.\n */\nexport async function clickElement(element: HTMLElement) {\n\tblurLastClickedElement()\n\n\tlastClickedElement = element\n\n\tawait scrollIntoViewIfNeeded(element)\n\tconst frame = element.ownerDocument.defaultView?.frameElement\n\tif (frame) await scrollIntoViewIfNeeded(frame)\n\n\tconst rect = element.getBoundingClientRect()\n\tconst x = rect.left + rect.width / 2\n\tconst y = rect.top + rect.height / 2\n\n\tawait movePointerToElement(element, x, y)\n\tawait clickPointer()\n\n\tawait waitFor(0.1)\n\n\t// Hit-test to find the deepest element at click coordinates, matching\n\t// real browser behavior where events target the innermost element.\n\t// @note This may hit a element in the blacklist\n\t// TODO: This is a temporary workaround. Should have been handled during dom extraction.\n\tconst doc = element.ownerDocument\n\tawait enablePassThrough()\n\tconst hitTarget = doc.elementFromPoint(x, y)\n\tawait disablePassThrough()\n\tconst target =\n\t\thitTarget instanceof HTMLElement && element.contains(hitTarget) ? hitTarget : element\n\n\tconst pointerOpts = {\n\t\tbubbles: true,\n\t\tcancelable: true,\n\t\tclientX: x,\n\t\tclientY: y,\n\t\tpointerType: 'mouse',\n\t}\n\tconst mouseOpts = { bubbles: true, cancelable: true, clientX: x, clientY: y, button: 0 }\n\n\t// Hover — pointer events first, then mouse events (spec order)\n\ttarget.dispatchEvent(new PointerEvent('pointerover', pointerOpts))\n\ttarget.dispatchEvent(new PointerEvent('pointerenter', { ...pointerOpts, bubbles: false }))\n\ttarget.dispatchEvent(new MouseEvent('mouseover', mouseOpts))\n\ttarget.dispatchEvent(new MouseEvent('mouseenter', { ...mouseOpts, bubbles: false }))\n\n\t// Press\n\ttarget.dispatchEvent(new PointerEvent('pointerdown', pointerOpts))\n\ttarget.dispatchEvent(new MouseEvent('mousedown', mouseOpts))\n\n\t// Focus is not part of the standard pointer/mouse event sequence\n\t// \"undefined and varies between user agents\".\n\t// We focus the original element (nearest focusable ancestor), not the hit-test target, matching browser behavior.\n\telement.focus({ preventScroll: true })\n\n\t// Release\n\ttarget.dispatchEvent(new PointerEvent('pointerup', pointerOpts))\n\ttarget.dispatchEvent(new MouseEvent('mouseup', mouseOpts))\n\n\t// Click — activation behavior (navigation, form submit, etc.) triggers\n\t// via bubbling from target up to the interactive ancestor.\n\ttarget.click()\n\n\tawait waitFor(0.2)\n}\n\n/**\n * @private Internal method, subject to change at any time.\n */\nexport async function inputTextElement(element: HTMLElement, text: string) {\n\tconst isContentEditable = element.isContentEditable\n\tif (!isInputElement(element) && !isTextAreaElement(element) && !isContentEditable) {\n\t\tthrow new Error('Element is not an input, textarea, or contenteditable')\n\t}\n\n\tawait clickElement(element)\n\n\tif (isContentEditable) {\n\t\t// Contenteditable support (partial)\n\t\t// Not supported:\n\t\t// - Monaco/CodeMirror: Require direct JS instance access. No universal way to obtain.\n\t\t// - Draft.js: Not responsive to synthetic/execCommand/Range/DataTransfer. Unmaintained.\n\t\t//\n\t\t// Strategy: Try Plan A (synthetic events) first, then verify and fall back\n\t\t// to Plan B (execCommand) if the text wasn't actually inserted.\n\t\t//\n\t\t// Plan A: Dispatch synthetic events\n\t\t// Works: React contenteditable, Quill.\n\t\t// Fails: Slate.js, some contenteditable editors that ignore synthetic events.\n\t\t// Sequence: beforeinput -> mutation -> input -> change -> blur\n\n\t\t// Dispatch beforeinput + mutation + input for clearing\n\t\tif (\n\t\t\telement.dispatchEvent(\n\t\t\t\tnew InputEvent('beforeinput', {\n\t\t\t\t\tbubbles: true,\n\t\t\t\t\tcancelable: true,\n\t\t\t\t\tinputType: 'deleteContent',\n\t\t\t\t})\n\t\t\t)\n\t\t) {\n\t\t\telement.innerText = ''\n\t\t\telement.dispatchEvent(\n\t\t\t\tnew InputEvent('input', {\n\t\t\t\t\tbubbles: true,\n\t\t\t\t\tinputType: 'deleteContent',\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\n\t\t// Dispatch beforeinput + mutation + input for insertion (important for React apps)\n\t\tif (\n\t\t\telement.dispatchEvent(\n\t\t\t\tnew InputEvent('beforeinput', {\n\t\t\t\t\tbubbles: true,\n\t\t\t\t\tcancelable: true,\n\t\t\t\t\tinputType: 'insertText',\n\t\t\t\t\tdata: text,\n\t\t\t\t})\n\t\t\t)\n\t\t) {\n\t\t\telement.innerText = text\n\t\t\telement.dispatchEvent(\n\t\t\t\tnew InputEvent('input', {\n\t\t\t\t\tbubbles: true,\n\t\t\t\t\tinputType: 'insertText',\n\t\t\t\t\tdata: text,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\n\t\t// Verify Plan A worked by checking if the text was actually inserted\n\t\tconst planASucceeded = element.innerText.trim() === text.trim()\n\n\t\tif (!planASucceeded) {\n\t\t\t// Plan B: execCommand fallback (deprecated but widely supported)\n\t\t\t// Works: Quill, Slate.js, react contenteditable components.\n\t\t\t// This approach integrates with the browser's undo stack and is handled\n\t\t\t// natively by most rich-text editors.\n\t\t\telement.focus()\n\n\t\t\t// Select all existing content and delete it\n\t\t\tconst doc = element.ownerDocument\n\t\t\tconst selection = (doc.defaultView || window).getSelection()\n\t\t\tconst range = doc.createRange()\n\t\t\trange.selectNodeContents(element)\n\t\t\tselection?.removeAllRanges()\n\t\t\tselection?.addRange(range)\n\n\t\t\tdoc.execCommand('delete', false)\n\t\t\tdoc.execCommand('insertText', false, text)\n\t\t}\n\n\t\t// Dispatch change event (for good measure)\n\t\telement.dispatchEvent(new Event('change', { bubbles: true }))\n\n\t\t// Trigger blur for validation\n\t\telement.blur()\n\t} else {\n\t\tgetNativeValueSetter(element as HTMLInputElement | HTMLTextAreaElement).call(element, text)\n\t}\n\n\t// Only dispatch shared input event for non-contenteditable (contenteditable has its own)\n\tif (!isContentEditable) {\n\t\telement.dispatchEvent(new Event('input', { bubbles: true }))\n\t}\n\n\tawait waitFor(0.1)\n}\n\n/**\n * @todo browser-use version is very complex and supports menu tags, need to follow up\n * @private Internal method, subject to change at any time.\n */\nexport async function selectOptionElement(selectElement: HTMLSelectElement, optionText: string) {\n\tif (!isSelectElement(selectElement)) {\n\t\tthrow new Error('Element is not a select element')\n\t}\n\n\tconst options = Array.from(selectElement.options)\n\tconst option = options.find((opt) => opt.textContent?.trim() === optionText.trim())\n\n\tif (!option) {\n\t\tthrow new Error(`Option with text \"${optionText}\" not found in select element`)\n\t}\n\n\tselectElement.value = option.value\n\tselectElement.dispatchEvent(new Event('change', { bubbles: true }))\n\n\tawait waitFor(0.1) // Wait to ensure change event processing completes\n}\n\ninterface ScrollableElement extends Element {\n\tscrollIntoViewIfNeeded?: (centerIfNeeded?: boolean) => void\n}\n\n/**\n * @private Internal method, subject to change at any time.\n */\nexport async function scrollIntoViewIfNeeded(element: Element) {\n\tconst el = element as ScrollableElement\n\tif (typeof el.scrollIntoViewIfNeeded === 'function') {\n\t\tel.scrollIntoViewIfNeeded()\n\t\t// await waitFor(0.5) // Animation playback\n\t} else {\n\t\t// @todo visibility check\n\t\telement.scrollIntoView({ behavior: 'auto', block: 'center', inline: 'nearest' })\n\t\t// await waitFor(0.5) // Animation playback\n\t}\n}\n\nexport async function scrollVertically(scroll_amount: number, element?: HTMLElement | null) {\n\t// Element-specific scrolling if element is provided\n\tif (element) {\n\t\tconst targetElement = element\n\t\tlet currentElement = targetElement as HTMLElement | null\n\t\tlet scrollSuccess = false\n\t\tlet scrolledElement: HTMLElement | null = null\n\t\tlet scrollDelta = 0\n\t\tlet attempts = 0\n\t\tconst dy = scroll_amount\n\n\t\twhile (currentElement && attempts < 10) {\n\t\t\tconst computedStyle = window.getComputedStyle(currentElement)\n\t\t\tconst hasScrollableY =\n\t\t\t\t/(auto|scroll|overlay)/.test(computedStyle.overflowY) ||\n\t\t\t\t(computedStyle.scrollbarWidth && computedStyle.scrollbarWidth !== 'auto') ||\n\t\t\t\t(computedStyle.scrollbarGutter && computedStyle.scrollbarGutter !== 'auto')\n\t\t\tconst canScrollVertically = currentElement.scrollHeight > currentElement.clientHeight\n\n\t\t\tif (hasScrollableY && canScrollVertically) {\n\t\t\t\tconst beforeScroll = currentElement.scrollTop\n\t\t\t\tconst maxScroll = currentElement.scrollHeight - currentElement.clientHeight\n\n\t\t\t\tlet scrollAmount = dy / 3\n\n\t\t\t\tif (scrollAmount > 0) {\n\t\t\t\t\tscrollAmount = Math.min(scrollAmount, maxScroll - beforeScroll)\n\t\t\t\t} else {\n\t\t\t\t\tscrollAmount = Math.max(scrollAmount, -beforeScroll)\n\t\t\t\t}\n\n\t\t\t\tcurrentElement.scrollTop = beforeScroll + scrollAmount\n\n\t\t\t\tconst afterScroll = currentElement.scrollTop\n\t\t\t\tconst actualScrollDelta = afterScroll - beforeScroll\n\n\t\t\t\tif (Math.abs(actualScrollDelta) > 0.5) {\n\t\t\t\t\tscrollSuccess = true\n\t\t\t\t\tscrolledElement = currentElement\n\t\t\t\t\tscrollDelta = actualScrollDelta\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (currentElement === document.body || currentElement === document.documentElement) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcurrentElement = currentElement.parentElement\n\t\t\tattempts++\n\t\t}\n\n\t\tif (scrollSuccess) {\n\t\t\treturn `Scrolled container (${scrolledElement?.tagName}) by ${scrollDelta}px`\n\t\t} else {\n\t\t\treturn `No scrollable container found for element (${targetElement.tagName})`\n\t\t}\n\t}\n\n\t// Page-level scrolling (default or fallback)\n\n\tconst dy = scroll_amount\n\tconst bigEnough = (el: HTMLElement) => el.clientHeight >= window.innerHeight * 0.5\n\tconst canScroll = (el: HTMLElement | null): boolean =>\n\t\tBoolean(\n\t\t\tel &&\n\t\t\t/(auto|scroll|overlay)/.test(getComputedStyle(el).overflowY) &&\n\t\t\tel.scrollHeight > el.clientHeight &&\n\t\t\tbigEnough(el)\n\t\t)\n\n\t// @deprecated Heuristic container search.\n\t// Unreliable in multi-panel layouts. Should guide LLMs to use indexed scroll for consistency.\n\t// TODO: remove this fallback\n\n\t// try to find the nearest scrollable container\n\t// document.activeElement is usually body.\n\t// After a successful element.focus(), activeElement become the nearest focusable parent\n\n\tlet el: HTMLElement | null = document.activeElement as HTMLElement | null\n\twhile (el && !canScroll(el) && el !== document.body) el = el.parentElement\n\n\t// Something is wrong if it falls back to global '*' search\n\t// TODO: Return error message instead of global '*' search\n\n\tel = canScroll(el)\n\t\t? el\n\t\t: Array.from(document.querySelectorAll<HTMLElement>('*')).find(canScroll) ||\n\t\t\t(document.scrollingElement as HTMLElement) ||\n\t\t\t(document.documentElement as HTMLElement)\n\n\tif (el === document.scrollingElement || el === document.documentElement || el === document.body) {\n\t\t// Page-level scroll\n\t\tconst scrollBefore = window.scrollY\n\t\tconst scrollMax = document.documentElement.scrollHeight - window.innerHeight\n\n\t\twindow.scrollBy(0, dy)\n\n\t\tconst scrollAfter = window.scrollY\n\t\tconst scrolled = scrollAfter - scrollBefore\n\n\t\tif (Math.abs(scrolled) < 1) {\n\t\t\treturn dy > 0\n\t\t\t\t? `⚠️ Already at the bottom of the page, cannot scroll down further.`\n\t\t\t\t: `⚠️ Already at the top of the page, cannot scroll up further.`\n\t\t}\n\n\t\tconst reachedBottom = dy > 0 && scrollAfter >= scrollMax - 1\n\t\tconst reachedTop = dy < 0 && scrollAfter <= 1\n\n\t\tif (reachedBottom) return `✅ Scrolled page by ${scrolled}px. Reached the bottom of the page.`\n\t\tif (reachedTop) return `✅ Scrolled page by ${scrolled}px. Reached the top of the page.`\n\t\treturn `✅ Scrolled page by ${scrolled}px.`\n\t} else {\n\t\t// Container scroll\n\n\t\tconst warningMsg = `The document is not scrollable. Falling back to container scroll.`\n\t\tconsole.log(`[PageController] ${warningMsg}`)\n\n\t\tconst scrollBefore = el!.scrollTop\n\t\tconst scrollMax = el!.scrollHeight - el!.clientHeight\n\n\t\tel!.scrollBy({ top: dy, behavior: 'smooth' })\n\t\tawait waitFor(0.1)\n\n\t\tconst scrollAfter = el!.scrollTop\n\t\tconst scrolled = scrollAfter - scrollBefore\n\n\t\tif (Math.abs(scrolled) < 1) {\n\t\t\treturn dy > 0\n\t\t\t\t? `⚠️ ${warningMsg} Already at the bottom of container (${el!.tagName}), cannot scroll down further.`\n\t\t\t\t: `⚠️ ${warningMsg} Already at the top of container (${el!.tagName}), cannot scroll up further.`\n\t\t}\n\n\t\tconst reachedBottom = dy > 0 && scrollAfter >= scrollMax - 1\n\t\tconst reachedTop = dy < 0 && scrollAfter <= 1\n\n\t\tif (reachedBottom)\n\t\t\treturn `✅ ${warningMsg} Scrolled container (${el!.tagName}) by ${scrolled}px. Reached the bottom.`\n\t\tif (reachedTop)\n\t\t\treturn `✅ ${warningMsg} Scrolled container (${el!.tagName}) by ${scrolled}px. Reached the top.`\n\t\treturn `✅ ${warningMsg} Scrolled container (${el!.tagName}) by ${scrolled}px.`\n\t}\n}\n\nexport async function scrollHorizontally(scroll_amount: number, element?: HTMLElement | null) {\n\t// Element-specific scrolling if element is provided\n\tif (element) {\n\t\tconst targetElement = element\n\t\tlet currentElement = targetElement as HTMLElement | null\n\t\tlet scrollSuccess = false\n\t\tlet scrolledElement: HTMLElement | null = null\n\t\tlet scrollDelta = 0\n\t\tlet attempts = 0\n\t\tconst dx = scroll_amount\n\n\t\twhile (currentElement && attempts < 10) {\n\t\t\tconst computedStyle = window.getComputedStyle(currentElement)\n\t\t\tconst hasScrollableX =\n\t\t\t\t/(auto|scroll|overlay)/.test(computedStyle.overflowX) ||\n\t\t\t\t(computedStyle.scrollbarWidth && computedStyle.scrollbarWidth !== 'auto') ||\n\t\t\t\t(computedStyle.scrollbarGutter && computedStyle.scrollbarGutter !== 'auto')\n\t\t\tconst canScrollHorizontally = currentElement.scrollWidth > currentElement.clientWidth\n\n\t\t\tif (hasScrollableX && canScrollHorizontally) {\n\t\t\t\tconst beforeScroll = currentElement.scrollLeft\n\t\t\t\tconst maxScroll = currentElement.scrollWidth - currentElement.clientWidth\n\n\t\t\t\tlet scrollAmount = dx / 3\n\n\t\t\t\tif (scrollAmount > 0) {\n\t\t\t\t\tscrollAmount = Math.min(scrollAmount, maxScroll - beforeScroll)\n\t\t\t\t} else {\n\t\t\t\t\tscrollAmount = Math.max(scrollAmount, -beforeScroll)\n\t\t\t\t}\n\n\t\t\t\tcurrentElement.scrollLeft = beforeScroll + scrollAmount\n\n\t\t\t\tconst afterScroll = currentElement.scrollLeft\n\t\t\t\tconst actualScrollDelta = afterScroll - beforeScroll\n\n\t\t\t\tif (Math.abs(actualScrollDelta) > 0.5) {\n\t\t\t\t\tscrollSuccess = true\n\t\t\t\t\tscrolledElement = currentElement\n\t\t\t\t\tscrollDelta = actualScrollDelta\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (currentElement === document.body || currentElement === document.documentElement) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcurrentElement = currentElement.parentElement\n\t\t\tattempts++\n\t\t}\n\n\t\tif (scrollSuccess) {\n\t\t\treturn `Scrolled container (${scrolledElement?.tagName}) horizontally by ${scrollDelta}px`\n\t\t} else {\n\t\t\treturn `No horizontally scrollable container found for element (${targetElement.tagName})`\n\t\t}\n\t}\n\n\t// Page-level scrolling (default or fallback)\n\n\tconst dx = scroll_amount\n\n\tconst bigEnough = (el: HTMLElement) => el.clientWidth >= window.innerWidth * 0.5\n\tconst canScroll = (el: HTMLElement | null): boolean =>\n\t\tBoolean(\n\t\t\tel &&\n\t\t\t/(auto|scroll|overlay)/.test(getComputedStyle(el).overflowX) &&\n\t\t\tel.scrollWidth > el.clientWidth &&\n\t\t\tbigEnough(el)\n\t\t)\n\n\t// @deprecated Same heuristic container search as scrollVertically.\n\t// TODO: Remove once LLMs reliably use indexed scrolling via data-scrollable.\n\n\tlet el: HTMLElement | null = document.activeElement as HTMLElement | null\n\twhile (el && !canScroll(el) && el !== document.body) el = el.parentElement\n\n\tel = canScroll(el)\n\t\t? el\n\t\t: Array.from(document.querySelectorAll<HTMLElement>('*')).find(canScroll) ||\n\t\t\t(document.scrollingElement as HTMLElement) ||\n\t\t\t(document.documentElement as HTMLElement)\n\n\tif (el === document.scrollingElement || el === document.documentElement || el === document.body) {\n\t\t// Page-level scroll\n\t\tconst scrollBefore = window.scrollX\n\t\tconst scrollMax = document.documentElement.scrollWidth - window.innerWidth\n\n\t\twindow.scrollBy(dx, 0)\n\n\t\tconst scrollAfter = window.scrollX\n\t\tconst scrolled = scrollAfter - scrollBefore\n\n\t\tif (Math.abs(scrolled) < 1) {\n\t\t\treturn dx > 0\n\t\t\t\t? `⚠️ Already at the right edge of the page, cannot scroll right further.`\n\t\t\t\t: `⚠️ Already at the left edge of the page, cannot scroll left further.`\n\t\t}\n\n\t\tconst reachedRight = dx > 0 && scrollAfter >= scrollMax - 1\n\t\tconst reachedLeft = dx < 0 && scrollAfter <= 1\n\n\t\tif (reachedRight)\n\t\t\treturn `✅ Scrolled page by ${scrolled}px. Reached the right edge of the page.`\n\t\tif (reachedLeft) return `✅ Scrolled page by ${scrolled}px. Reached the left edge of the page.`\n\t\treturn `✅ Scrolled page horizontally by ${scrolled}px.`\n\t} else {\n\t\t// Container scroll\n\t\tconst warningMsg = `The document is not scrollable. Falling back to container scroll.`\n\t\tconsole.log(`[PageController] ${warningMsg}`)\n\n\t\tconst scrollBefore = el!.scrollLeft\n\t\tconst scrollMax = el!.scrollWidth - el!.clientWidth\n\n\t\tel!.scrollBy({ left: dx, behavior: 'smooth' })\n\t\tawait waitFor(0.1)\n\n\t\tconst scrollAfter = el!.scrollLeft\n\t\tconst scrolled = scrollAfter - scrollBefore\n\n\t\tif (Math.abs(scrolled) < 1) {\n\t\t\treturn dx > 0\n\t\t\t\t? `⚠️ ${warningMsg} Already at the right edge of container (${el!.tagName}), cannot scroll right further.`\n\t\t\t\t: `⚠️ ${warningMsg} Already at the left edge of container (${el!.tagName}), cannot scroll left further.`\n\t\t}\n\n\t\tconst reachedRight = dx > 0 && scrollAfter >= scrollMax - 1\n\t\tconst reachedLeft = dx < 0 && scrollAfter <= 1\n\n\t\tif (reachedRight)\n\t\t\treturn `✅ ${warningMsg} Scrolled container (${el!.tagName}) by ${scrolled}px. Reached the right edge.`\n\t\tif (reachedLeft)\n\t\t\treturn `✅ ${warningMsg} Scrolled container (${el!.tagName}) by ${scrolled}px. Reached the left edge.`\n\t\treturn `✅ ${warningMsg} Scrolled container (${el!.tagName}) horizontally by ${scrolled}px.`\n\t}\n}\n","/**\n * The core identifies each node by a capture-local DOM path (`html[1]/body[2]/div[0]`), which it\n * publishes on every node as `domPath`. These helpers read and write that same format so the adapter\n * can relate nodes to elements it owns (the agent's own interface, frame documents) without reaching\n * into the core. Real-browser tests check them against the core's output.\n */\n\n/** The core's path for `node` inside `root`: child index among all siblings, tag in lower case. */\nexport function domPathOf(node: Node, root: Document): string {\n\tconst parts: string[] = []\n\tlet current: Node | null = node\n\twhile (current && current !== root) {\n\t\tif (current.nodeType === 1 || current.nodeType === 3) {\n\t\t\tlet index = 0\n\t\t\tfor (let previous = current.previousSibling; previous; previous = previous.previousSibling)\n\t\t\t\tindex++\n\t\t\tparts.push(`${current.nodeType === 1 ? (current as Element).localName : '#text'}[${index}]`)\n\t\t} else if (current.nodeType === 11 && (current as ShadowRoot).host) {\n\t\t\tparts.push('#shadow-root[0]')\n\t\t}\n\t\tcurrent = current.parentNode ?? (current as ShadowRoot).host ?? null\n\t}\n\treturn parts.reverse().join('/')\n}\n\n/** The node a core path points to now, or null when the document no longer matches the path. */\nexport function resolveDomPath(root: Document, path: string): Node | null {\n\tif (!path) return null\n\tlet current: Node = root\n\tfor (const part of path.split('/')) {\n\t\tconst match = /^(.+)\\[(\\d+)\\]$/.exec(part)\n\t\tif (!match) return null\n\t\tconst [, name, index] = match\n\t\tif (name === '#shadow-root') {\n\t\t\tconst shadow = (current as Element).shadowRoot\n\t\t\tif (!shadow) return null\n\t\t\tcurrent = shadow\n\t\t\tcontinue\n\t\t}\n\t\tconst child = current.childNodes[Number(index)] as Node | undefined\n\t\tif (!child) return null\n\t\tif (name === '#text' ? child.nodeType !== 3 : (child as Element).localName !== name) return null\n\t\tcurrent = child\n\t}\n\treturn current\n}\n\n/** Whether `path` is `ancestor` or lies below it. */\nexport function isWithinPath(path: string, ancestor: string): boolean {\n\treturn path === ancestor || path.startsWith(`${ancestor}/`)\n}\n","/**\n * What an action demonstrably sent to the page, observed independently of the core.\n *\n * This is evidence of delivery only. It never shows that the page accepted, applied or saved\n * anything: that needs a new capture or a query of the page.\n */\nexport interface AxEvidence {\n\t/**\n\t * Untrusted (`isTrusted === false`) events seen at the session window while the action ran, by type.\n\t * Null when the session window is unknown.\n\t *\n\t * It is an observation of the window, not a log of the action: it also counts untrusted events the\n\t * page itself dispatched meanwhile, and it misses events the page stops before the window and\n\t * events that do not leave a shadow root (a `change` fired inside one, for example).\n\t */\n\tsyntheticEvents: Record<string, number> | null\n\t/** Whether the focused element changed while the action ran. Null when the document is unknown. */\n\tfocusMoved: boolean | null\n\t/** Whether `scrollIntoView` was requested on the target before the action itself. */\n\tscrollIntoViewRequested: boolean\n}\n\nconst OBSERVED_EVENTS = [\n\t'pointerover',\n\t'pointerenter',\n\t'pointerdown',\n\t'pointermove',\n\t'pointerup',\n\t'pointercancel',\n\t'pointerout',\n\t'pointerleave',\n\t'mouseover',\n\t'mouseenter',\n\t'mousedown',\n\t'mousemove',\n\t'mouseup',\n\t'mouseout',\n\t'mouseleave',\n\t'click',\n\t'dblclick',\n\t'dragstart',\n\t'dragenter',\n\t'dragover',\n\t'drop',\n\t'dragend',\n\t'keydown',\n\t'keyup',\n\t'input',\n\t'change',\n\t'wheel',\n] as const\n\nfunction deepActiveElement(doc: Document): Element | null {\n\tlet active = doc.activeElement\n\twhile (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement\n\treturn active\n}\n\n/**\n * Starts counting untrusted events at the document's window (capture phase, so non-bubbling events\n * are included). Call `stop()` exactly once to remove the listeners and read the evidence.\n */\nexport function observeAction(doc: Document | null): { stop: () => AxEvidence } {\n\t// A frame document that navigated away has no window any more.\n\tconst target = doc?.defaultView ?? null\n\tif (!doc || !target)\n\t\treturn {\n\t\t\tstop: () => ({ syntheticEvents: null, focusMoved: null, scrollIntoViewRequested: false }),\n\t\t}\n\n\tconst counts: Record<string, number> = {}\n\tconst listener = (event: Event) => {\n\t\tif (!event.isTrusted) counts[event.type] = (counts[event.type] ?? 0) + 1\n\t}\n\tfor (const type of OBSERVED_EVENTS) target.addEventListener(type, listener, true)\n\tconst focusedBefore = deepActiveElement(doc)\n\n\treturn {\n\t\tstop: () => {\n\t\t\tfor (const type of OBSERVED_EVENTS) target.removeEventListener(type, listener, true)\n\t\t\tlet focusMoved: boolean | null\n\t\t\ttry {\n\t\t\t\tfocusMoved = deepActiveElement(doc) !== focusedBefore\n\t\t\t} catch {\n\t\t\t\tfocusMoved = null\n\t\t\t}\n\t\t\treturn { syntheticEvents: counts, focusMoved, scrollIntoViewRequested: false }\n\t\t},\n\t}\n}\n\n/** `click ×2, dblclick ×1`, or an empty string when nothing was seen. */\nexport function describeEvents(evidence: AxEvidence | null): string {\n\tconst events = evidence?.syntheticEvents\n\tif (!events) return ''\n\treturn Object.entries(events)\n\t\t.map(([type, count]) => `${type} ×${count}`)\n\t\t.join(', ')\n}\n","import { type AxEvidence, describeEvents } from './evidence'\n\n/**\n * Failure classes. All but the last four come straight from the core's `code: message` errors.\n *\n * - `stale_id`, `no_capture`, `engine_unavailable` and `unknown` are raised by this adapter.\n */\nexport type AxErrorCode =\n\t| 'stale_snapshot'\n\t| 'stale_node'\n\t| 'stale_document'\n\t| 'session_closed'\n\t| 'blocked'\n\t| 'invalid'\n\t| 'unsupported'\n\t| 'budget_exceeded'\n\t| 'gesture_active'\n\t| 'frame_unavailable'\n\t| 'timeout'\n\t| 'aborted'\n\t| 'stale_id'\n\t| 'no_capture'\n\t| 'engine_unavailable'\n\t| 'unknown'\n\nconst CORE_CODES = new Set<string>([\n\t'stale_snapshot',\n\t'stale_node',\n\t'stale_document',\n\t'session_closed',\n\t'blocked',\n\t'invalid',\n\t'unsupported',\n\t'budget_exceeded',\n\t'gesture_active',\n\t'frame_unavailable',\n\t'timeout',\n\t'aborted',\n])\n\n/**\n * An accessibility operation that did not complete.\n *\n * `partial` is set when synthetic events were already delivered, or focus already moved, before the\n * failure. Those effects are not undone: treat the page as possibly changed and capture again.\n */\nexport class AxError extends Error {\n\treadonly code: AxErrorCode\n\treadonly action: string | null\n\treadonly partial: AxEvidence | null\n\n\tconstructor(\n\t\tcode: AxErrorCode,\n\t\tmessage: string,\n\t\toptions: { action?: string; partial?: AxEvidence | null; cause?: unknown } = {}\n\t) {\n\t\tsuper(message, options.cause === undefined ? undefined : { cause: options.cause })\n\t\tthis.name = 'AxError'\n\t\tthis.code = code\n\t\tthis.action = options.action ?? null\n\t\tthis.partial = options.partial ?? null\n\t}\n\n\t/**\n\t * What had already reached the page when the action failed, in words, or an empty string. For\n\t * example `untrusted events already observed: pointerover ×1; focus already moved`.\n\t */\n\tget effects(): string {\n\t\tif (!this.partial) return ''\n\t\tconst events = describeEvents(this.partial)\n\t\tconst parts: string[] = []\n\t\tif (this.partial.scrollIntoViewRequested) parts.push('scrollIntoView already requested')\n\t\tif (events) parts.push(`untrusted events already observed: ${events}`)\n\t\tif (this.partial.focusMoved) parts.push('focus already moved')\n\t\treturn parts.join('; ')\n\t}\n}\n\n/** True when the evidence shows the page already received something from the action. */\nexport function hasEffects(evidence: AxEvidence | null | undefined): evidence is AxEvidence {\n\tif (!evidence) return false\n\tconst events = evidence.syntheticEvents\n\treturn (\n\t\tevidence.scrollIntoViewRequested ||\n\t\tevidence.focusMoved === true ||\n\t\t(!!events && Object.keys(events).length > 0)\n\t)\n}\n\n/**\n * Wraps any thrown value as an `AxError`, keeping the core's message unchanged.\n * The code is the `code:` prefix the core puts on its errors.\n */\nexport function toAxError(error: unknown, action?: string, evidence?: AxEvidence | null): AxError {\n\tconst partial = hasEffects(evidence) ? evidence : null\n\tif (error instanceof AxError) {\n\t\tif (!partial && !action) return error\n\t\treturn new AxError(error.code, error.message, {\n\t\t\taction: error.action ?? action,\n\t\t\tpartial: error.partial ?? partial,\n\t\t\tcause: error.cause,\n\t\t})\n\t}\n\tconst message = error instanceof Error ? error.message : String(error)\n\tconst prefix = /^([a-z_]+): /.exec(message)?.[1]\n\tconst code: AxErrorCode = prefix && CORE_CODES.has(prefix) ? (prefix as AxErrorCode) : 'unknown'\n\treturn new AxError(code, message, { action, partial, cause: error })\n}\n","import type { AxNode, AxTreeFormatOptions, AxTreeText } from './types'\n\ninterface Entry {\n\tnode: AxNode\n\tdepth: number\n\t/** Index of the nearest printed-candidate ancestor in the entry list, or -1. */\n\tparent: number\n}\n\nconst collapseSpaces = (text: string) => text.replace(/\\s+/g, ' ').trim()\n\n/** JSON text of a value. Long strings are cut at `maxTextLength`, and the cut is stated. */\nfunction quote(value: unknown, options: AxTreeFormatOptions): string {\n\tconst limit = options.maxTextLength\n\tif (typeof value !== 'string' || limit === undefined || value.length <= limit)\n\t\treturn JSON.stringify(value)\n\treturn `${JSON.stringify(`${value.slice(0, limit)}…`)} (+${value.length - limit} chars)`\n}\n\n/**\n * One line per node, in the same shape as the core's console interface:\n * `[id] role \"name\" value: ... description: ... key: value`.\n */\nfunction formatLine(node: AxNode, depth: number, options: AxTreeFormatOptions): string {\n\tconst properties = Object.entries(node.properties ?? {})\n\t\t.filter(([, value]) => value !== null && value !== undefined && typeof value !== 'object')\n\t\t.map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`)\n\t\t.join('')\n\tconst description = node.description ? ` description: ${quote(node.description, options)}` : ''\n\tconst value =\n\t\tnode.value !== undefined && node.value !== null ? ` value: ${quote(node.value, options)}` : ''\n\tconst name = options.compact && !node.name ? '' : ` ${quote(node.name || '', options)}`\n\n\tlet relations = ''\n\tif (options.relations) {\n\t\tconst omitted = new Set(options.omitRelationTypes ?? [])\n\t\trelations = (node.relations ?? [])\n\t\t\t.filter((relation) => !omitted.has(relation.type))\n\t\t\t.map((relation) => ` ${relation.type}=>[${relation.targetId ?? 'unresolved'}]`)\n\t\t\t.join('')\n\t}\n\n\tconst label = options.idLabel ? options.idLabel(node) : node.id\n\tconst bracket = label === null ? '' : `[${label}] `\n\tconst annotation = options.annotation?.(node)\n\treturn `${' '.repeat(depth)}${bracket}${node.role}${name}${value}${description}${properties}${relations}${annotation ? ` ${annotation}` : ''}`\n}\n\n/**\n * Hierarchical text for a capture's nodes. Ignored nodes are not printed and their children take\n * their place, as in the core's console interface.\n *\n * With `maxLines`, whole levels are printed from the top down and the remaining budget is spent on\n * the next level in document order. Nothing is dropped silently: every printed node that has\n * unprinted descendants ends with `… +N hidden`.\n */\nexport function formatTree(nodes: AxNode[], options: AxTreeFormatOptions = {}): AxTreeText {\n\t// A node whose parent is not in the list (it was left out of the capture) is printed as a root,\n\t// so it is never lost without a trace.\n\tconst ids = new Set(nodes.map((node) => node.id))\n\tconst children = new Map<string | null, AxNode[]>()\n\tfor (const node of nodes) {\n\t\tconst parentId = node.parentId !== null && ids.has(node.parentId) ? node.parentId : null\n\t\tconst siblings = children.get(parentId)\n\t\tif (siblings) siblings.push(node)\n\t\telse children.set(parentId, [node])\n\t}\n\n\tconst entries: Entry[] = []\n\tlet foldedTextNodes = 0\n\n\tconst visit = (parentId: string | null, depth: number, parent: number) => {\n\t\tfor (const node of children.get(parentId) ?? []) {\n\t\t\tif (node.ignored) {\n\t\t\t\tvisit(node.id, depth, parent)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (options.compact && node.role === 'StaticText' && !children.has(node.id)) {\n\t\t\t\tconst text = collapseSpaces(node.name)\n\t\t\t\tconst repeatsParent = parent >= 0 && text === collapseSpaces(entries[parent].node.name)\n\t\t\t\tif (!text || repeatsParent) {\n\t\t\t\t\tfoldedTextNodes++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst index = entries.push({ node, depth, parent }) - 1\n\t\t\tvisit(node.id, depth + 1, index)\n\t\t}\n\t}\n\n\tif (options.rootId === undefined) {\n\t\tvisit(null, 0, -1)\n\t} else {\n\t\tconst root = nodes.find((node) => node.id === options.rootId)\n\t\tif (root) {\n\t\t\tif (root.ignored) visit(root.id, 0, -1)\n\t\t\telse {\n\t\t\t\tentries.push({ node: root, depth: 0, parent: -1 })\n\t\t\t\tvisit(root.id, 1, 0)\n\t\t\t}\n\t\t}\n\t}\n\n\t// With a filter, a node stays when it passes or when something below it does, so what is printed\n\t// is still a tree with its context. Everything else is counted as filtered.\n\tconst totalNodes = entries.length\n\tif (options.filter) {\n\t\tconst keep = entries.map((entry) => options.filter!(entry.node))\n\t\tfor (let index = entries.length - 1; index >= 0; index--)\n\t\t\tif (keep[index] && entries[index].parent >= 0) keep[entries[index].parent] = true\n\t\tconst moved = new Array<number>(entries.length).fill(-1)\n\t\tconst kept: Entry[] = []\n\t\tentries.forEach((entry, index) => {\n\t\t\tif (!keep[index]) return\n\t\t\tmoved[index] =\n\t\t\t\tkept.push({ ...entry, parent: entry.parent < 0 ? -1 : moved[entry.parent] }) - 1\n\t\t})\n\t\tentries.length = 0\n\t\tentries.push(...kept)\n\t}\n\tconst filteredNodes = totalNodes - entries.length\n\n\tconst printed = new Array<boolean>(entries.length).fill(true)\n\tconst maxLines = options.maxLines\n\tif (maxLines !== undefined && entries.length > maxLines) {\n\t\tconst perDepth: number[] = []\n\t\tfor (const entry of entries) perDepth[entry.depth] = (perDepth[entry.depth] ?? 0) + 1\n\n\t\t// Deepest level that still fits whole.\n\t\tlet fullDepth = -1\n\t\tlet used = 0\n\t\tfor (let depth = 0; depth < perDepth.length; depth++) {\n\t\t\tif (used + (perDepth[depth] ?? 0) > maxLines) break\n\t\t\tused += perDepth[depth] ?? 0\n\t\t\tfullDepth = depth\n\t\t}\n\n\t\tlet remaining = maxLines - used\n\t\tentries.forEach((entry, index) => {\n\t\t\tif (entry.depth <= fullDepth) return\n\t\t\t// A node is printed only under a printed parent, so the output stays a tree.\n\t\t\tconst parentPrinted = entry.parent < 0 || printed[entry.parent]\n\t\t\tif (entry.depth === fullDepth + 1 && parentPrinted && remaining > 0) remaining--\n\t\t\telse printed[index] = false\n\t\t})\n\t}\n\n\tconst hidden = new Array<number>(entries.length).fill(0)\n\tlet orphans = 0\n\tentries.forEach((entry, index) => {\n\t\tif (printed[index]) return\n\t\tlet ancestor = entry.parent\n\t\twhile (ancestor >= 0 && !printed[ancestor]) ancestor = entries[ancestor].parent\n\t\tif (ancestor >= 0) hidden[ancestor]++\n\t\telse orphans++\n\t})\n\n\tconst lines: string[] = []\n\tlet shownNodes = 0\n\tentries.forEach((entry, index) => {\n\t\tif (!printed[index]) return\n\t\tshownNodes++\n\t\tconst suffix = hidden[index] > 0 ? ` … +${hidden[index]} hidden` : ''\n\t\tlines.push(formatLine(entry.node, entry.depth, options) + suffix)\n\t})\n\tif (orphans > 0) lines.push(`… +${orphans} hidden`)\n\n\treturn {\n\t\ttext: lines.join('\\n'),\n\t\tshownNodes,\n\t\ttotalNodes,\n\t\thiddenNodes: entries.length - shownNodes,\n\t\tfilteredNodes,\n\t\tfoldedTextNodes,\n\t}\n}\n","/**\n * Public node IDs: `<session token>.<capture generation>:<core node id>`, e.g. `k3m9x2pa.4:h12`.\n *\n * The token binds an ID to one session and the generation binds it to one capture of that session,\n * so an ID from an earlier capture, another frame or a destroyed session can never address a node\n * of the current capture by accident.\n */\n\nexport interface ParsedAxId {\n\ttoken: string\n\tgeneration: number\n\tnodeId: string\n}\n\nconst ID_PATTERN = /^([0-9a-z]{8})\\.([1-9]\\d*):(\\S+)$/\n\n/** 40 random bits as 8 base-36 characters. */\nexport function createSessionToken(): string {\n\tconst bytes = crypto.getRandomValues(new Uint8Array(5))\n\tlet value = 0\n\tfor (const byte of bytes) value = value * 256 + byte\n\treturn value.toString(36).padStart(8, '0').slice(-8)\n}\n\nexport function captureIdOf(token: string, generation: number): string {\n\treturn `${token}.${generation}`\n}\n\nexport function publicId(captureId: string, nodeId: string): string {\n\treturn `${captureId}:${nodeId}`\n}\n\nexport function parseAxId(id: unknown): ParsedAxId | null {\n\tif (typeof id !== 'string') return null\n\tconst match = ID_PATTERN.exec(id)\n\tif (!match) return null\n\treturn { token: match[1], generation: Number(match[2]), nodeId: match[3] }\n}\n","import type { AxTreeFormatOptions, AxTreeView } from './types'\n\n/** How the tree is printed when it is added to the browser state at every step. */\nexport const OBSERVATION_FORMAT: AxTreeFormatOptions = {\n\tcompact: true,\n\trelations: true,\n\t// The accessible name already carries what a labelledby relation contributes.\n\tomitRelationTypes: ['labelledby'],\n\t// A container can be reconstructed with its whole text as its name; its children carry that text.\n\tmaxTextLength: 160,\n}\n\nexport const DEFAULT_OBSERVATION_MAX_LINES = 400\n\n/** Header and tree text for one capture, as it is shown to a model. */\nexport function formatAccessibilityObservation(view: AxTreeView, subtreeOf?: string): string {\n\tconst counts = [`${view.shownNodes} of ${view.totalNodes} nodes shown`]\n\tif (view.hiddenNodes > 0)\n\t\tcounts.push('\"… +N hidden\" marks collapsed descendants that can be expanded by ID')\n\tif (view.foldedTextNodes > 0)\n\t\tcounts.push(`${view.foldedTextNodes} blank or repeated text leaves folded`)\n\treturn [\n\t\tsubtreeOf === undefined\n\t\t\t? `Accessibility tree, capture ${view.captureId} (${counts.join('; ')}).`\n\t\t\t: `Subtree of [${subtreeOf}] in capture ${view.captureId}, not captured again (${counts.join('; ')}).`,\n\t\t\"It is a reconstruction from the page's observable state, not the browser's native accessibility tree, and it can differ from it.\",\n\t\t'Each line is [id] role \"name\" followed by value, description, states and relations. IDs are valid only until the next capture.',\n\t\t'',\n\t\tview.text,\n\t].join('\\n')\n}\n","/**\n * AccessibilityController - reads the page as a reconstructed accessibility tree and acts on its\n * nodes by ID.\n *\n * It is an adapter around the preserved core in `vendor/ax-core.js`. The core does the\n * reconstruction, the semantic computation, the identity checks and the gestures; this class only\n * adds what the project needs around it: public IDs bound to a session and a capture, sessions for\n * same-origin frames, exclusion of the agent's own interface, lazy loading, and results that keep\n * \"event sent\", \"effect observed\" and \"change persisted\" apart.\n *\n * Contract, in short:\n * - The tree is an approximation built from the page's observable state. It is not the browser's\n * native accessibility tree.\n * - Actions are synthetic DOM events and API calls (`isTrusted === false`). They are not physical\n * input: synthetic hover does not set CSS `:hover`, a synthetic `wheel` does not scroll, and a page\n * may ignore any of them.\n * - An ID is valid only for the capture that produced it. A new capture of the same session, or a\n * new session, invalidates it (`stale_id`).\n * - Closed shadow roots, cross-origin frames and browser-internal structures are out of reach.\n */\nimport { domPathOf, isWithinPath, resolveDomPath } from './domPath'\nimport type {\n\tAxCoreAgent,\n\tAxCoreFactory,\n\tAxCoreNode,\n\tAxCoreRequest,\n\tAxCoreSnapshot,\n\tAxCoreTextFragments,\n\tAxDragMode,\n\tAxStandardsCatalog,\n} from './engine'\nimport { AxError, toAxError } from './errors'\nimport { type AxEvidence, observeAction } from './evidence'\nimport { formatTree } from './format'\nimport { captureIdOf, createSessionToken, parseAxId, publicId } from './ids'\nimport {\n\tDEFAULT_OBSERVATION_MAX_LINES,\n\tOBSERVATION_FORMAT,\n\tformatAccessibilityObservation,\n} from './observation'\nimport type {\n\tAccessibilityConfig,\n\tAxActionName,\n\tAxActionOptions,\n\tAxActionOutcome,\n\tAxActionStatus,\n\tAxAttributeStandards,\n\tAxCapture,\n\tAxClickOutcome,\n\tAxDragOutcome,\n\tAxDraggable,\n\tAxElementStandards,\n\tAxFillOutcome,\n\tAxFindQuery,\n\tAxFocusOutcome,\n\tAxHoverOutcome,\n\tAxIndexedObservation,\n\tAxKeyOptions,\n\tAxKeyOutcome,\n\tAxNode,\n\tAxScrollIntoViewOutcome,\n\tAxScrollOffsets,\n\tAxScrollOutcome,\n\tAxSessionInfo,\n\tAxStateOutcome,\n\tAxSurface,\n\tAxTreeFormatOptions,\n\tAxTreeText,\n\tAxTreeView,\n\tAxVisualTarget,\n\tAxWaitQuery,\n\tAxWheelOutcome,\n} from './types'\n\nexport const DEFAULT_IGNORE_SELECTOR = '[data-page-agent-ignore], #playwright-highlight-container'\nconst DEFAULT_MAX_FRAME_SESSIONS = 8\nconst NOT_VERIFIED = 'The effect on the page was not verified; capture again to check it.'\n\n/** Collaborators the controller cannot own itself. All have working defaults except for tests. */\nexport interface AccessibilityControllerOptions extends AccessibilityConfig {\n\t/** Document of the root session. @default the global document */\n\tdocument?: Document\n\t/**\n\t * Runs an interaction with the agent's own overlays out of the way. The core hit-tests its\n\t * targets, so a visible mask would make every target look obscured.\n\t */\n\trunInteraction?: <T>(interaction: () => Promise<T>) => Promise<T>\n\t/** Loads the core. @default dynamic import of the vendored module */\n\tloadCore?: () => Promise<{ createPageAgent: AxCoreFactory }>\n\t/** Loads the standards catalog. @default dynamic import of the vendored module */\n\tloadStandards?: () => Promise<{ standardsCatalog: AxStandardsCatalog }>\n}\n\ninterface Session {\n\ttoken: string\n\tkind: 'root' | 'frame'\n\tparent: Session | null\n\tchildren: Set<Session>\n\tcore: AxCoreAgent\n\t/** Null when the frame document could not be identified; evidence is then unavailable. */\n\tdocument: Document | null\n\tgeneration: number\n\tcurrent: {\n\t\tcaptureId: string\n\t\tsnapshot: AxCoreSnapshot\n\t\tcapture: AxCapture\n\t\tcoreNodes: Map<string, AxCoreNode>\n\t\t/** Core node IDs of the agent's own interface. */\n\t\texcluded: Set<string>\n\t\t/** Temporary IDs issued by `targetAt` for this capture. */\n\t\tvisualIds: Set<string>\n\t} | null\n\tlastUsed: number\n\t/** The capture that observers asking right now will share, until it runs. */\n\tpending: Promise<AxCapture> | null\n}\n\ninterface Target {\n\tsession: Session\n\trequest: AxCoreRequest\n\tnodeId: string\n\t/** True for IDs that came from `targetAt`. */\n\tvisual: boolean\n}\n\nexport class AccessibilityController {\n\treadonly #options: AccessibilityControllerOptions\n\treadonly #sessions = new Map<string, Session>()\n\t#root: Session | null = null\n\t#factory: Promise<AxCoreFactory> | null = null\n\t#destroyed = false\n\t#clock = 0\n\n\tconstructor(options: AccessibilityControllerOptions = {}) {\n\t\tthis.#options = options\n\t}\n\n\t// ======= Capture =======\n\n\t/**\n\t * Captures the tree of a session as structured data. Every ID from an earlier capture of the same\n\t * session stops working.\n\t */\n\tasync capture(options: { sessionId?: string } = {}): Promise<AxCapture> {\n\t\tconst session = await this.#session(options.sessionId)\n\t\treturn structuredClone(await this.#observation(session))\n\t}\n\n\t/** Captures the tree of a session and returns it as readable hierarchical text. */\n\tasync tree(options: AxTreeFormatOptions & { sessionId?: string } = {}): Promise<AxTreeView> {\n\t\tconst session = await this.#session(options.sessionId)\n\t\tconst capture = await this.#observation(session)\n\t\treturn this.#view(capture, options)\n\t}\n\n\t/**\n\t * The last capture of a session as structured data, without reading the page again. It can be out\n\t * of date; its IDs are still the valid ones.\n\t */\n\tasync current(options: { sessionId?: string } = {}): Promise<AxCapture> {\n\t\tconst session = await this.#session(options.sessionId)\n\t\treturn structuredClone(this.#requireCurrent(session).capture)\n\t}\n\n\t/** Readable text of the last capture, or of one subtree of it, without reading the page again. */\n\tasync describe(options: AxTreeFormatOptions & { sessionId?: string } = {}): Promise<AxTreeView> {\n\t\tlet session: Session\n\t\tif (options.rootId !== undefined) session = this.#locate(options.rootId).session\n\t\telse session = await this.#session(options.sessionId)\n\t\treturn this.#view(this.#requireCurrent(session).capture, options)\n\t}\n\n\t/**\n\t * Captures a session and returns the text a model reads: a short header that states what the tree\n\t * is, then the compact tree, collapsed to `maxLines`.\n\t */\n\tasync observe(options: { sessionId?: string; maxLines?: number } = {}): Promise<string> {\n\t\tconst view = await this.tree({\n\t\t\t...OBSERVATION_FORMAT,\n\t\t\tsessionId: options.sessionId,\n\t\t\tmaxLines:\n\t\t\t\toptions.maxLines ?? this.#options.observationMaxLines ?? DEFAULT_OBSERVATION_MAX_LINES,\n\t\t})\n\t\treturn formatAccessibilityObservation(view)\n\t}\n\n\t/** The same text for one subtree of the current capture, without capturing again. */\n\tasync expand(id: string, options: { maxLines?: number } = {}): Promise<string> {\n\t\tconst view = await this.describe({\n\t\t\t...OBSERVATION_FORMAT,\n\t\t\trootId: id,\n\t\t\tmaxLines:\n\t\t\t\toptions.maxLines ?? this.#options.observationMaxLines ?? DEFAULT_OBSERVATION_MAX_LINES,\n\t\t})\n\t\treturn formatAccessibilityObservation(view, id)\n\t}\n\n\t/**\n\t * Captures the page and returns the tree the agent reads, with a short numeric index on every node\n\t * that has an element. The indexes are the handles of the existing index-based tools; `ids` maps\n\t * each one to the node ID to act on.\n\t *\n\t * `viewportExpansion` is the margin around the viewport, in CSS pixels, within which nodes are\n\t * listed; `-1` lists the whole page. A whole page that does not fit in `maxLines` is narrowed to the\n\t * viewport instead of being cut arbitrarily.\n\t */\n\tasync observeIndexed(\n\t\toptions: { maxLines?: number; viewportExpansion?: number } = {}\n\t): Promise<AxIndexedObservation> {\n\t\tconst session = await this.#session()\n\t\tconst capture = await this.#observation(session)\n\t\tconst doc = session.document\n\t\tconst maxLines =\n\t\t\toptions.maxLines ?? this.#options.observationMaxLines ?? DEFAULT_OBSERVATION_MAX_LINES\n\n\t\t// The capture was made in this same task, so each path still points at the node it came from.\n\t\tconst domNodes = new Map<string, Node | null>()\n\t\tfor (const node of capture.nodes)\n\t\t\tdomNodes.set(\n\t\t\t\tnode.id,\n\t\t\t\t!doc ? null : node.domPath === '' ? doc : resolveDomPath(doc, node.domPath)\n\t\t\t)\n\t\tconst view = doc?.defaultView\n\t\t// This is geometry, not a claim that the element is visible or unobscured.\n\t\t// Missing and zero-size geometry is left unannotated; no nodes are filtered.\n\t\tconst viewportAnnotation = (node: AxNode): string | null => {\n\t\t\tconst domNode = domNodes.get(node.id)\n\t\t\tif (!view || !domNode || domNode.nodeType !== 1) return null\n\t\t\ttry {\n\t\t\t\tconst rect = (domNode as Element).getBoundingClientRect()\n\t\t\t\tif (\n\t\t\t\t\t![rect.left, rect.top, rect.right, rect.bottom, rect.width, rect.height].every(\n\t\t\t\t\t\tNumber.isFinite\n\t\t\t\t\t) ||\n\t\t\t\t\trect.width <= 0 ||\n\t\t\t\t\trect.height <= 0\n\t\t\t\t)\n\t\t\t\t\treturn null\n\t\t\t\tif (rect.bottom <= 0) return 'viewport: outside-above'\n\t\t\t\tif (rect.top >= view.innerHeight) return 'viewport: outside-below'\n\t\t\t\tif (rect.right <= 0) return 'viewport: outside-left'\n\t\t\t\tif (rect.left >= view.innerWidth) return 'viewport: outside-right'\n\t\t\t\treturn 'viewport: intersects'\n\t\t\t} catch {\n\t\t\t\treturn null\n\t\t\t}\n\t\t}\n\t\tconst inViewport = (margin: number) => (node: AxNode) => {\n\t\t\tconst domNode = domNodes.get(node.id)\n\t\t\tif (!view || !domNode || domNode === doc) return true\n\t\t\tconst element = domNode.nodeType === 1 ? (domNode as Element) : domNode.parentElement\n\t\t\tif (!element) return true\n\t\t\tconst rect = element.getBoundingClientRect()\n\t\t\treturn (\n\t\t\t\trect.bottom >= -margin &&\n\t\t\t\trect.top <= view.innerHeight + margin &&\n\t\t\t\trect.right >= -margin &&\n\t\t\t\trect.left <= view.innerWidth + margin\n\t\t\t)\n\t\t}\n\n\t\tconst format = (filter?: (node: AxNode) => boolean) => {\n\t\t\tconst ids: string[] = []\n\t\t\tconst labels: string[] = []\n\t\t\tconst text = formatTree(capture.nodes, {\n\t\t\t\t...OBSERVATION_FORMAT,\n\t\t\t\tmaxLines,\n\t\t\t\tfilter,\n\t\t\t\tannotation: viewportAnnotation,\n\t\t\t\tidLabel: (node) => {\n\t\t\t\t\tif (domNodes.get(node.id)?.nodeType !== 1) return null\n\t\t\t\t\tlabels.push(`${node.role} ${JSON.stringify(clip(node.name))}`)\n\t\t\t\t\treturn String(ids.push(node.id) - 1)\n\t\t\t\t},\n\t\t\t})\n\t\t\treturn { ...text, ids, labels }\n\t\t}\n\n\t\tconst expansion = options.viewportExpansion ?? -1\n\t\tlet viewportOnly = expansion !== -1\n\t\tlet result = format(viewportOnly ? inViewport(expansion) : undefined)\n\t\tif (!viewportOnly && result.hiddenNodes > 0) {\n\t\t\tviewportOnly = true\n\t\t\tresult = format(inViewport(0))\n\t\t}\n\n\t\treturn {\n\t\t\t...result,\n\t\t\tcaptureId: capture.captureId,\n\t\t\tviewportOnly,\n\t\t\texcludedNodeCount: capture.excludedNodeCount,\n\t\t\tdurationMs: capture.durationMs,\n\t\t}\n\t}\n\n\t/**\n\t * The element now at the captured path of a node, or null. It is for visual feedback and for\n\t * reading, and it is not validated: always act through the action methods, which are.\n\t */\n\tasync elementAt(id: string): Promise<Element | null> {\n\t\tconst { session, nodeId } = this.#locate(id)\n\t\tconst domPath = session.current?.coreNodes.get(nodeId)?.domPath\n\t\tif (!session.document || !domPath) return null\n\t\tconst node = resolveDomPath(session.document, domPath)\n\t\treturn node?.nodeType === 1 ? (node as Element) : null\n\t}\n\n\t/** Captures and returns the non-ignored nodes with this role and, if given, this exact name. */\n\tasync find(query: AxFindQuery): Promise<{ captureId: string; nodes: AxNode[] }> {\n\t\tif (\n\t\t\ttypeof query?.role !== 'string' ||\n\t\t\t!query.role ||\n\t\t\t!(query.name === undefined || typeof query.name === 'string')\n\t\t)\n\t\t\tthrow new AxError('invalid', 'invalid: role is required and name must be a string')\n\t\tconst capture = await this.capture({ sessionId: query.sessionId })\n\t\treturn {\n\t\t\tcaptureId: capture.captureId,\n\t\t\tnodes: capture.nodes.filter(\n\t\t\t\t(node) =>\n\t\t\t\t\t!node.ignored &&\n\t\t\t\t\tnode.role === query.role &&\n\t\t\t\t\t(query.name === undefined || node.name === query.name)\n\t\t\t),\n\t\t}\n\t}\n\n\t/**\n\t * Polls `find` until a node matches, the timeout passes or the signal aborts. Each poll is a full\n\t * synchronous reconstruction, and very brief states can be missed.\n\t */\n\tasync waitFor(query: AxWaitQuery): Promise<{ captureId: string; nodes: AxNode[] }> {\n\t\tconst { timeoutMs = 5000, intervalMs = 100, signal } = query\n\t\tif (\n\t\t\t!Number.isInteger(timeoutMs) ||\n\t\t\ttimeoutMs < 0 ||\n\t\t\ttimeoutMs > 60000 ||\n\t\t\t!Number.isInteger(intervalMs) ||\n\t\t\tintervalMs < 20 ||\n\t\t\tintervalMs > 1000\n\t\t)\n\t\t\tthrow new AxError('invalid', 'invalid: wait timeout or interval')\n\n\t\tconst started = performance.now()\n\t\tfor (;;) {\n\t\t\tif (signal?.aborted) throw new AxError('aborted', 'aborted: wait cancelled')\n\t\t\tconst result = await this.find(query)\n\t\t\tif (result.nodes.length > 0) return result\n\t\t\tconst remaining = timeoutMs - (performance.now() - started)\n\t\t\tif (remaining <= 0) throw new AxError('timeout', 'timeout: element not found')\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tconst done = () => {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\tsignal?.removeEventListener('abort', done)\n\t\t\t\t\tresolve()\n\t\t\t\t}\n\t\t\t\tconst timer = setTimeout(done, Math.min(intervalMs, remaining))\n\t\t\t\tsignal?.addEventListener('abort', done, { once: true })\n\t\t\t})\n\t\t}\n\t}\n\n\t// ======= Actions =======\n\n\t/** Synthetic click through the element's own `click()`. It can navigate or submit a form. */\n\tasync click(id: string, options: AxActionOptions = {}): Promise<AxClickOutcome> {\n\t\treturn this.#act('click', id, options, (core, request) => core.click(request), {\n\t\t\tstatus: () => 'dispatched',\n\t\t\tsummary: () => `Synthetic click dispatched (isTrusted is false). ${NOT_VERIFIED}`,\n\t\t})\n\t}\n\n\t/** Two synthetic pointer, mouse and click sequences followed by `dblclick`. */\n\tasync doubleClick(id: string, options: AxActionOptions = {}): Promise<AxClickOutcome> {\n\t\treturn this.#act('doubleClick', id, options, (core, request) => core.doubleClick(request), {\n\t\t\tstatus: () => 'dispatched',\n\t\t\tsummary: () =>\n\t\t\t\t`Two synthetic click sequences and a dblclick were dispatched (isTrusted is false). It is not a physical double click and does not select text natively. ${NOT_VERIFIED}`,\n\t\t})\n\t}\n\n\t/** Calls `focus()` and reports whether the element is focused afterwards. */\n\tasync focus(id: string): Promise<AxFocusOutcome> {\n\t\treturn this.#act('focus', id, {}, (core, request) => core.focus(request), {\n\t\t\tstatus: (result) => (result.focused ? 'applied' : 'not_applied'),\n\t\t\tsummary: (result) =>\n\t\t\t\tresult.focused\n\t\t\t\t\t? 'The element is focused.'\n\t\t\t\t\t: 'focus() was called but the element is not the focused element.',\n\t\t})\n\t}\n\n\t/**\n\t * Replaces the value of a text-like input, textarea or contenteditable element and dispatches\n\t * `input` and `change`. It does not type key by key.\n\t */\n\tasync fill(id: string, value: string, options: AxActionOptions = {}): Promise<AxFillOutcome> {\n\t\treturn this.#act('fill', id, options, (core, request) => core.fill({ ...request, value }), {\n\t\t\tstatus: (result) => (result.applied ? 'applied' : 'not_applied'),\n\t\t\tsummary: (result) =>\n\t\t\t\t(result.applied\n\t\t\t\t\t? 'Right after the events the control held the requested value.'\n\t\t\t\t\t: 'Right after the events the control did not hold the requested value.') +\n\t\t\t\tchangeNote(result.changeDispatched) +\n\t\t\t\t' This does not show that the page validated or saved it.',\n\t\t})\n\t}\n\n\t/** Selects by option value in a native `<select>`. Pass an array for `<select multiple>`. */\n\tasync select(\n\t\tid: string,\n\t\tvalue: string | string[],\n\t\toptions: AxActionOptions = {}\n\t): Promise<AxStateOutcome> {\n\t\t// The core reads `value` for a single select and `values` for a multiple one. A single value is\n\t\t// sent in both shapes, so one option can be chosen in either kind of control.\n\t\tconst values = Array.isArray(value) ? value : [value]\n\t\tconst selection = values.length === 1 ? { value: values[0], values } : { values }\n\t\treturn this.#act(\n\t\t\t'select',\n\t\t\tid,\n\t\t\toptions,\n\t\t\t(core, request) => core.select({ ...request, ...selection }),\n\t\t\t{\n\t\t\t\tstatus: stateStatus,\n\t\t\t\tsummary: (result) => stateSummary(result, 'selection'),\n\t\t\t}\n\t\t)\n\t}\n\n\t/** Checks or unchecks a native checkbox, or selects a native radio. */\n\tasync setChecked(\n\t\tid: string,\n\t\tchecked = true,\n\t\toptions: AxActionOptions = {}\n\t): Promise<AxStateOutcome> {\n\t\treturn this.#act(\n\t\t\t'setChecked',\n\t\t\tid,\n\t\t\toptions,\n\t\t\t(core, request) => core.setChecked({ ...request, checked }),\n\t\t\t{\n\t\t\t\tstatus: stateStatus,\n\t\t\t\tsummary: (result) => stateSummary(result, 'checked state'),\n\t\t\t}\n\t\t)\n\t}\n\n\t/** Sets a native `<input type=\"range\">`. Values the browser would clamp or round are refused. */\n\tasync setRange(\n\t\tid: string,\n\t\tvalue: number,\n\t\toptions: AxActionOptions = {}\n\t): Promise<AxStateOutcome> {\n\t\treturn this.#act(\n\t\t\t'setRange',\n\t\t\tid,\n\t\t\toptions,\n\t\t\t(core, request) => core.setRange({ ...request, value }),\n\t\t\t{\n\t\t\t\tstatus: stateStatus,\n\t\t\t\tsummary: (result) => stateSummary(result, 'value'),\n\t\t\t}\n\t\t)\n\t}\n\n\t/**\n\t * Dispatches synthetic `keydown` and `keyup` to the focused target. The key's native behaviour is\n\t * not performed: no character is typed and `Tab` does not move focus.\n\t */\n\tasync pressKey(\n\t\tid: string,\n\t\tkey: string,\n\t\toptions: AxKeyOptions & AxActionOptions = {}\n\t): Promise<AxKeyOutcome> {\n\t\tconst { scrollIntoView, ...keyOptions } = options\n\t\treturn this.#act(\n\t\t\t'pressKey',\n\t\t\tid,\n\t\t\t{ scrollIntoView },\n\t\t\t(core, request) => core.key({ ...request, key, ...keyOptions }),\n\t\t\t{\n\t\t\t\tstatus: () => 'dispatched',\n\t\t\t\tsummary: (result) =>\n\t\t\t\t\t`Synthetic keydown${result.keyupDispatched ? ' and keyup' : ''} dispatched` +\n\t\t\t\t\t(result.keyupDispatched ? '' : ' (keyup withheld: the target lost focus)') +\n\t\t\t\t\t`; the page ${result.defaultPrevented ? 'cancelled' : 'did not cancel'} keydown. ` +\n\t\t\t\t\t`The key's native behaviour was not performed. ${NOT_VERIFIED}`,\n\t\t\t}\n\t\t)\n\t}\n\n\t/**\n\t * Dispatches synthetic pointer and mouse enter, over and move events. The real pointer does not\n\t * move and CSS `:hover` is not activated, so CSS-only menus may stay closed.\n\t */\n\tasync hover(id: string, options: AxActionOptions = {}): Promise<AxHoverOutcome> {\n\t\treturn this.#act('hover', id, options, (core, request) => core.hover(request), {\n\t\t\tstatus: () => 'dispatched',\n\t\t\tsummary: () =>\n\t\t\t\t`Synthetic hover events dispatched (isTrusted is false). CSS :hover was not activated and the real pointer did not move. ${NOT_VERIFIED}`,\n\t\t})\n\t}\n\n\t/**\n\t * Drags a source node to a destination node of the same capture.\n\t *\n\t * - `html5`: DragEvents with a synthetic DataTransfer. `drop` is sent only if the destination\n\t * cancels `dragover`.\n\t * - `pointer`: a short pointer and mouse sequence with one intermediate point.\n\t * - `pointer-paced`: the same sequence spaced in time for libraries that wait between events.\n\t * The session refuses captures and actions until it settles.\n\t */\n\tasync drag(\n\t\tsourceId: string,\n\t\ttargetId: string,\n\t\tmode: AxDragMode = 'html5'\n\t): Promise<AxDragOutcome> {\n\t\tconst source = this.#locate(sourceId)\n\t\tconst target = this.#locate(targetId)\n\t\tif (source.session !== target.session)\n\t\t\tthrow new AxError(\n\t\t\t\t'invalid',\n\t\t\t\t'invalid: source and destination must belong to the same session and capture',\n\t\t\t\t{ action: 'drag' }\n\t\t\t)\n\t\tconst { result, evidence } = await this.#run('drag', source.session, false, () =>\n\t\t\tsource.session.core.dragTo({ ...source.request, targetNodeId: target.nodeId, mode })\n\t\t)\n\t\treturn {\n\t\t\taction: 'drag',\n\t\t\tstatus: result.mode === 'html5' && !result.dropDispatched ? 'not_applied' : 'dispatched',\n\t\t\tresult,\n\t\t\tevidence,\n\t\t\tscrolledIntoView: false,\n\t\t\t...PAGE_SCRIPT,\n\t\t\tsummary: dragSummary(result),\n\t\t}\n\t}\n\n\t/**\n\t * Programmatic scroll of a container, or of the session viewport when no ID is given, in CSS\n\t * pixels. Reports the positions right before and after.\n\t */\n\tasync scroll(offsets: AxScrollOffsets & { sessionId?: string }): Promise<AxScrollOutcome>\n\tasync scroll(id: string, offsets: AxScrollOffsets): Promise<AxScrollOutcome>\n\tasync scroll(\n\t\tidOrOffsets: string | (AxScrollOffsets & { sessionId?: string }),\n\t\toffsets?: AxScrollOffsets\n\t): Promise<AxScrollOutcome> {\n\t\tconst { session, request } = await this.#motion(idOrOffsets, offsets)\n\t\tconst { result, evidence } = await this.#run('scroll', session, false, () =>\n\t\t\tsession.core.scroll(request)\n\t\t)\n\t\treturn {\n\t\t\taction: 'scroll',\n\t\t\tstatus: result.moved ? 'applied' : 'not_applied',\n\t\t\tresult,\n\t\t\tevidence,\n\t\t\tscrolledIntoView: false,\n\t\t\t...PAGE_SCRIPT,\n\t\t\tsummary: result.moved\n\t\t\t\t? `Scrolled from (${result.before.x}, ${result.before.y}) to (${result.after.x}, ${result.after.y}). Effects the page runs after scrolling may not have finished.`\n\t\t\t\t: 'The scroll was requested but the position did not change (edge reached, not scrollable, or limited by the page).',\n\t\t}\n\t}\n\n\t/**\n\t * Dispatches one synthetic `WheelEvent` to a container or to the session document. It does not\n\t * scroll: use `scroll` to move content, and this only when a component needs the event.\n\t */\n\tasync wheel(offsets: AxScrollOffsets & { sessionId?: string }): Promise<AxWheelOutcome>\n\tasync wheel(id: string, offsets: AxScrollOffsets): Promise<AxWheelOutcome>\n\tasync wheel(\n\t\tidOrOffsets: string | (AxScrollOffsets & { sessionId?: string }),\n\t\toffsets?: AxScrollOffsets\n\t): Promise<AxWheelOutcome> {\n\t\tconst { session, request } = await this.#motion(idOrOffsets, offsets)\n\t\tconst { result, evidence } = await this.#run('wheel', session, false, () =>\n\t\t\tsession.core.wheel(request)\n\t\t)\n\t\treturn {\n\t\t\taction: 'wheel',\n\t\t\tstatus: 'dispatched',\n\t\t\tresult,\n\t\t\tevidence,\n\t\t\tscrolledIntoView: false,\n\t\t\t...PAGE_SCRIPT,\n\t\t\tsummary: `Synthetic wheel event dispatched; the page ${result.defaultPrevented ? 'cancelled' : 'did not cancel'} it. It does not perform native scrolling. ${NOT_VERIFIED}`,\n\t\t}\n\t}\n\n\t/** Calls `scrollIntoView` on the element. Movement is not measured. */\n\tasync scrollIntoView(id: string): Promise<AxScrollIntoViewOutcome> {\n\t\treturn this.#act('scrollIntoView', id, {}, (core, request) => core.scrollIntoView(request), {\n\t\t\tstatus: () => 'requested',\n\t\t\tsummary: () => 'scrollIntoView was called. Whether anything moved was not measured.',\n\t\t})\n\t}\n\n\t// ======= Inspection =======\n\n\t/**\n\t * Nodes of the current capture that look draggable (`draggable`, `aria-grabbed`, grab cursor).\n\t * A heuristic: it can list false positives and miss components that drag through handlers.\n\t */\n\tasync draggables(options: { sessionId?: string } = {}): Promise<AxDraggable[]> {\n\t\tconst session = await this.#session(options.sessionId)\n\t\tconst current = this.#requireCurrent(session)\n\t\treturn this.#guard('draggables', () =>\n\t\t\tsession.core\n\t\t\t\t.draggableCandidates({ snapshotId: current.snapshot.snapshotId })\n\t\t\t\t.filter((candidate) => !current.excluded.has(candidate.nodeId))\n\t\t\t\t.map(({ nodeId, ...rest }) => ({ id: publicId(current.captureId, nodeId), ...rest }))\n\t\t)\n\t}\n\n\t/**\n\t * Hit-tests viewport coordinates (CSS pixels) and returns a temporary ID for the element found.\n\t * It reads no pixels and invents no role. The ID can be a drag source or destination and uses\n\t * exactly this point.\n\t */\n\tasync targetAt(\n\t\tx: number,\n\t\ty: number,\n\t\toptions: { sessionId?: string } = {}\n\t): Promise<AxVisualTarget> {\n\t\tconst session = await this.#session(options.sessionId)\n\t\tconst current = this.#requireCurrent(session)\n\t\tconst { result } = await this.#run('targetAt', session, true, () => {\n\t\t\tif (this.#hitsOwnInterface(session, x, y))\n\t\t\t\tthrow new AxError('blocked', \"blocked: the point is on the agent's own interface\")\n\t\t\treturn session.core.targetAt({ snapshotId: current.snapshot.snapshotId, x, y })\n\t\t})\n\t\tconst { nodeId, snapshotId: _snapshotId, ...target } = result\n\t\tcurrent.visualIds.add(nodeId)\n\t\treturn { id: publicId(current.captureId, nodeId), ...target }\n\t}\n\n\t/**\n\t * `canvas`, `svg` and `role=application` elements, including those in open shadow roots. This is a\n\t * list of DOM surfaces, not of what is drawn on them, and a null ID cannot be a target.\n\t */\n\tasync surfaces(options: { sessionId?: string } = {}): Promise<AxSurface[]> {\n\t\tconst session = await this.#session(options.sessionId)\n\t\tconst current = this.#requireCurrent(session)\n\t\treturn this.#guard('surfaces', () => {\n\t\t\tconst own = this.#ownSurfaceKeys(session)\n\t\t\treturn session.core\n\t\t\t\t.visualSurfaces({ snapshotId: current.snapshot.snapshotId })\n\t\t\t\t.filter((surface) => {\n\t\t\t\t\tif (surface.nodeId !== null) return !current.excluded.has(surface.nodeId)\n\t\t\t\t\tconst key = surfaceKey(surface.tag, surface.bounds)\n\t\t\t\t\tconst count = own.get(key) ?? 0\n\t\t\t\t\tif (count === 0) return true\n\t\t\t\t\town.set(key, count - 1)\n\t\t\t\t\treturn false\n\t\t\t\t})\n\t\t\t\t.map(({ nodeId, ...rest }) => ({\n\t\t\t\t\tid: nodeId === null ? null : publicId(current.captureId, nodeId),\n\t\t\t\t\t...rest,\n\t\t\t\t}))\n\t\t})\n\t}\n\n\t/** Geometric estimate of the visual runs of one `StaticText` node. Not part of the tree. */\n\tasync textFragments(id: string): Promise<AxCoreTextFragments> {\n\t\tconst target = this.#locate(id)\n\t\treturn this.#guard('textFragments', () => target.session.core.textFragments(target.request))\n\t}\n\n\t// ======= Frames =======\n\n\t/**\n\t * Opens a separate session for a same-origin iframe node. Capture it with the returned\n\t * `sessionId` to get its own IDs. Cross-origin and sandboxed frames are not available.\n\t */\n\tasync openFrame(id: string): Promise<{ sessionId: string; closedSessionIds: string[] }> {\n\t\tconst target = this.#locate(id)\n\t\tconst { session: parent } = target\n\t\tconst core = this.#guard('openFrame', () => parent.core.frame(target.request))\n\n\t\t// The core has just confirmed that the captured element is still at its captured path.\n\t\tlet frameDocument: Document | null = null\n\t\tconst domPath = parent.current?.coreNodes.get(target.nodeId)?.domPath\n\t\tif (parent.document && domPath) {\n\t\t\tconst element = resolveDomPath(parent.document, domPath) as HTMLIFrameElement | null\n\t\t\ttry {\n\t\t\t\tframeDocument = element?.contentDocument ?? null\n\t\t\t} catch {\n\t\t\t\tframeDocument = null\n\t\t\t}\n\t\t}\n\n\t\tconst session = this.#register({ kind: 'frame', parent, core, document: frameDocument })\n\t\treturn { sessionId: session.token, closedSessionIds: this.#evictFrameSessions(session) }\n\t}\n\n\t/** Closes a frame session and the sessions opened from it. Its IDs stop working. */\n\tasync closeSession(sessionId: string): Promise<void> {\n\t\tconst session = this.#sessions.get(sessionId)\n\t\tif (!session) return\n\t\tif (session.kind === 'root')\n\t\t\tthrow new AxError('invalid', 'invalid: the root session is closed with destroy()')\n\t\tthis.#close(session)\n\t}\n\n\t/** Open sessions, root first. */\n\tasync sessions(): Promise<AxSessionInfo[]> {\n\t\treturn [...this.#sessions.values()].map((session) => ({\n\t\t\tsessionId: session.token,\n\t\t\tkind: session.kind,\n\t\t\tparentSessionId: session.parent?.token ?? null,\n\t\t\tcaptureId: session.current?.captureId ?? null,\n\t\t\tframeUrl: session.current?.capture.frameUrl ?? null,\n\t\t}))\n\t}\n\n\t// ======= Standards index =======\n\n\t/**\n\t * HTML-AAM cases indexed for an element, with the AccName step order. A lookup of candidate roles\n\t * from two Working Drafts: it does not evaluate conditions and does not show what the\n\t * reconstruction implements.\n\t */\n\tasync standards(element: string): Promise<AxElementStandards> {\n\t\tif (typeof element !== 'string' || !element.trim())\n\t\t\tthrow new AxError('invalid', 'invalid: provide an HTML element name, for example \"button\"')\n\t\tconst catalog = await this.#standards()\n\t\tconst name = element.trim().toLowerCase()\n\t\treturn {\n\t\t\telement: name,\n\t\t\tcases: catalog.htmlAam.cases.filter((item) => item.element === name),\n\t\t\thtmlAam: catalog.htmlAam.document,\n\t\t\taccname: {\n\t\t\t\tdocument: catalog.accname.document,\n\t\t\t\tnameSteps: catalog.accname.nameSteps,\n\t\t\t\tdescriptionSteps: catalog.accname.descriptionSteps,\n\t\t\t},\n\t\t\tnote: catalog.disclaimer,\n\t\t}\n\t}\n\n\t/** HTML-AAM cases indexed for an attribute. Same caveats as `standards`. */\n\tasync attributeStandards(attribute: string): Promise<AxAttributeStandards> {\n\t\tif (typeof attribute !== 'string' || !attribute.trim())\n\t\t\tthrow new AxError('invalid', 'invalid: provide an HTML attribute name, for example \"checked\"')\n\t\tconst catalog = await this.#standards()\n\t\tconst name = attribute.trim().toLowerCase()\n\t\treturn {\n\t\t\tattribute: name,\n\t\t\tcases: catalog.htmlAam.attributeCases.filter((item) => item.attribute === name),\n\t\t\thtmlAam: catalog.htmlAam.document,\n\t\t\tnote: catalog.disclaimer,\n\t\t}\n\t}\n\n\t// ======= Lifecycle =======\n\n\t/** Ends every session. All IDs stop working and the controller cannot be used again. */\n\tdestroy(): void {\n\t\tthis.#destroyed = true\n\t\tif (this.#root) this.#close(this.#root)\n\t\tthis.#root = null\n\t}\n\n\t// ======= Internals =======\n\n\tasync #core(): Promise<AxCoreFactory> {\n\t\tthis.#factory ??= (this.#options.loadCore ?? (() => import('./vendor/ax-core.js')))().then(\n\t\t\t(module) => module.createPageAgent,\n\t\t\t(error: unknown) => {\n\t\t\t\tthis.#factory = null\n\t\t\t\tthrow new AxError(\n\t\t\t\t\t'engine_unavailable',\n\t\t\t\t\t`engine_unavailable: the accessibility core could not be loaded (${String(error)})`,\n\t\t\t\t\t{ cause: error }\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\t\treturn this.#factory\n\t}\n\n\tasync #standards(): Promise<AxStandardsCatalog> {\n\t\tconst load = this.#options.loadStandards ?? (() => import('./vendor/ax-standards.js'))\n\t\treturn (await load()).standardsCatalog\n\t}\n\n\t/** The root session, created on first use, or an open session by ID. */\n\tasync #session(sessionId?: string): Promise<Session> {\n\t\tif (this.#destroyed)\n\t\t\tthrow new AxError(\n\t\t\t\t'session_closed',\n\t\t\t\t'session_closed: the accessibility controller was destroyed'\n\t\t\t)\n\t\tif (sessionId !== undefined) {\n\t\t\tconst session = this.#sessions.get(sessionId)\n\t\t\tif (!session)\n\t\t\t\tthrow new AxError('session_closed', `session_closed: no open session \"${sessionId}\"`)\n\t\t\tthis.#touch(session)\n\t\t\treturn session\n\t\t}\n\t\tif (!this.#root) {\n\t\t\tconst createPageAgent = await this.#core()\n\t\t\tif (this.#destroyed)\n\t\t\t\tthrow new AxError(\n\t\t\t\t\t'session_closed',\n\t\t\t\t\t'session_closed: the accessibility controller was destroyed'\n\t\t\t\t)\n\t\t\t// A concurrent call may have created it while the core was loading.\n\t\t\tif (!this.#root) {\n\t\t\t\tconst doc = this.#options.document ?? document\n\t\t\t\tconst core = this.#guard('session', () =>\n\t\t\t\t\tcreatePageAgent({\n\t\t\t\t\t\tdocument: doc,\n\t\t\t\t\t\t...(this.#options.maxNodes !== undefined && { maxNodes: this.#options.maxNodes }),\n\t\t\t\t\t\t...(this.#options.maxDurationMs !== undefined && {\n\t\t\t\t\t\t\tmaxDurationMs: this.#options.maxDurationMs,\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\tthis.#root = this.#register({ kind: 'root', parent: null, core, document: doc })\n\t\t\t}\n\t\t}\n\t\tthis.#touch(this.#root)\n\t\treturn this.#root\n\t}\n\n\t#register(init: Pick<Session, 'kind' | 'parent' | 'core' | 'document'>): Session {\n\t\tlet token = createSessionToken()\n\t\twhile (this.#sessions.has(token)) token = createSessionToken()\n\t\tconst session: Session = {\n\t\t\t...init,\n\t\t\ttoken,\n\t\t\tchildren: new Set(),\n\t\t\tgeneration: 0,\n\t\t\tcurrent: null,\n\t\t\tlastUsed: ++this.#clock,\n\t\t\tpending: null,\n\t\t}\n\t\tinit.parent?.children.add(session)\n\t\tthis.#sessions.set(token, session)\n\t\treturn session\n\t}\n\n\t/** Closes a session and the sessions opened from it. Returns the IDs of all that were closed. */\n\t#close(session: Session): string[] {\n\t\tconst closed = [...session.children].flatMap((child) => this.#close(child))\n\t\tsession.parent?.children.delete(session)\n\t\tthis.#sessions.delete(session.token)\n\t\tsession.current = null\n\t\ttry {\n\t\t\tsession.core.destroy()\n\t\t} catch (error) {\n\t\t\tconsole.warn('[AccessibilityController] core session did not close cleanly', error)\n\t\t}\n\t\treturn [...closed, session.token]\n\t}\n\n\t/** Marks a session as just used. A frame in use keeps the frames it was opened from in use too. */\n\t#touch(session: Session): void {\n\t\tconst now = ++this.#clock\n\t\tfor (let current: Session | null = session; current; current = current.parent)\n\t\t\tcurrent.lastUsed = now\n\t}\n\n\t/** Keeps at most `maxFrameSessions` frame sessions, closing the least recently used first. */\n\t#evictFrameSessions(keep: Session): string[] {\n\t\tconst limit = this.#options.maxFrameSessions ?? DEFAULT_MAX_FRAME_SESSIONS\n\t\tconst closed: string[] = []\n\t\tconst isAncestorOfKept = (session: Session) => {\n\t\t\tfor (let current = keep.parent; current; current = current.parent)\n\t\t\t\tif (current === session) return true\n\t\t\treturn false\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst frames = [...this.#sessions.values()].filter((session) => session.kind === 'frame')\n\t\t\tif (frames.length <= limit) break\n\t\t\tconst victim = frames\n\t\t\t\t.filter((session) => session !== keep && !isAncestorOfKept(session))\n\t\t\t\t.sort((a, b) => a.lastUsed - b.lastUsed)[0]\n\t\t\tif (!victim) break\n\t\t\tclosed.push(...this.#close(victim))\n\t\t}\n\t\treturn closed\n\t}\n\n\t/**\n\t * One capture for every observer that asks before it runs. A capture voids the IDs of the one\n\t * before it, so two observers reading at the same moment (the agent's step and a script, say) would\n\t * otherwise invalidate each other, and pay for two reconstructions.\n\t *\n\t * Nothing is reused across time: the shared capture runs after every request that joins it, and a\n\t * request made once it has run starts a new one. Actions never use it; they are validated by the\n\t * core against the live page every time.\n\t *\n\t * It runs in a microtask, not a timer: timers are throttled in background tabs, and a microtask\n\t * leaves the page no chance to change between the request and the capture.\n\t */\n\t#observation(session: Session): Promise<AxCapture> {\n\t\tsession.pending ??= new Promise<AxCapture>((resolve, reject) => {\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tsession.pending = null\n\t\t\t\ttry {\n\t\t\t\t\tif (!this.#sessions.has(session.token))\n\t\t\t\t\t\tthrow new AxError('session_closed', 'session_closed: the session was closed')\n\t\t\t\t\tresolve(this.#capture(session))\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(toAxError(error, 'capture'))\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t\treturn session.pending\n\t}\n\n\t#capture(session: Session): AxCapture {\n\t\tconst started = performance.now()\n\t\tconst snapshot = this.#guard('capture', () => session.core.snapshot())\n\t\tconst durationMs = Math.round((performance.now() - started) * 10) / 10\n\n\t\t// The core now holds a new snapshot, so everything issued before is void from here on, whether\n\t\t// or not the rest of this method succeeds.\n\t\tsession.generation++\n\t\tsession.current = null\n\t\treturn this.#guard('capture', () => this.#commit(session, snapshot, durationMs))\n\t}\n\n\t/** Builds the public capture of a snapshot and makes it the session's current one. */\n\t#commit(session: Session, snapshot: AxCoreSnapshot, durationMs: number): AxCapture {\n\t\tconst captureId = captureIdOf(session.token, session.generation)\n\t\tconst toPublic = (nodeId: string | null | undefined) =>\n\t\t\tnodeId === null || nodeId === undefined ? null : publicId(captureId, nodeId)\n\n\t\tconst ownPaths = this.#ownInterfacePaths(session)\n\t\tconst excluded = new Set<string>()\n\t\tconst coreNodes = new Map<string, AxCoreNode>()\n\t\tfor (const node of snapshot.tree.nodes) {\n\t\t\tcoreNodes.set(node.id, node)\n\t\t\tif (ownPaths.some((path) => isWithinPath(node.domPath, path))) excluded.add(node.id)\n\t\t}\n\n\t\t// A private copy: callers and the core never share objects through a capture.\n\t\tconst tree = structuredClone(snapshot.tree)\n\t\tconst nodes: AxNode[] = tree.nodes\n\t\t\t.filter((node) => !excluded.has(node.id))\n\t\t\t.map((node) => ({\n\t\t\t\tid: publicId(captureId, node.id),\n\t\t\t\tparentId: toPublic(node.parentId),\n\t\t\t\trole: node.role,\n\t\t\t\tname: node.name,\n\t\t\t\tdescription: node.description,\n\t\t\t\t...(node.value !== undefined && { value: node.value }),\n\t\t\t\tignored: node.ignored,\n\t\t\t\tignoredReason: node.ignoredReason,\n\t\t\t\tproperties: node.properties ?? {},\n\t\t\t\trelations: (node.relations ?? []).map((relation) => ({\n\t\t\t\t\ttype: relation.type,\n\t\t\t\t\ttargetId:\n\t\t\t\t\t\trelation.targetId !== null && !excluded.has(relation.targetId)\n\t\t\t\t\t\t\t? toPublic(relation.targetId)\n\t\t\t\t\t\t\t: null,\n\t\t\t\t})),\n\t\t\t\tdomPath: node.domPath,\n\t\t\t}))\n\n\t\tconst capture: AxCapture = {\n\t\t\tcaptureId,\n\t\t\tsessionId: session.token,\n\t\t\tframeUrl: tree.frameUrl,\n\t\t\trootId: publicId(captureId, tree.rootId),\n\t\t\tnodes,\n\t\t\tunresolvedRelations: (tree.unresolvedRelations ?? [])\n\t\t\t\t.filter((relation) => !relation.sourceId || !excluded.has(relation.sourceId))\n\t\t\t\t.map((relation) => ({\n\t\t\t\t\t...relation,\n\t\t\t\t\tsourceId: toPublic(relation.sourceId),\n\t\t\t\t\t...(relation.targetId !== undefined && {\n\t\t\t\t\t\ttargetId:\n\t\t\t\t\t\t\trelation.targetId && excluded.has(relation.targetId)\n\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t: toPublic(relation.targetId),\n\t\t\t\t\t}),\n\t\t\t\t})),\n\t\t\tlimitations: [...new Set([...snapshot.limitations, ...tree.limitations])],\n\t\t\texcludedNodeCount: excluded.size,\n\t\t\tdurationMs,\n\t\t}\n\t\tsession.current = { captureId, snapshot, capture, coreNodes, excluded, visualIds: new Set() }\n\t\treturn capture\n\t}\n\n\t#view(capture: AxCapture, options: AxTreeFormatOptions): AxTreeView {\n\t\tconst text: AxTreeText = formatTree(capture.nodes, options)\n\t\treturn {\n\t\t\t...text,\n\t\t\tcaptureId: capture.captureId,\n\t\t\tsessionId: capture.sessionId,\n\t\t\tframeUrl: capture.frameUrl,\n\t\t\tlimitations: [...capture.limitations],\n\t\t\texcludedNodeCount: capture.excludedNodeCount,\n\t\t\tdurationMs: capture.durationMs,\n\t\t}\n\t}\n\n\t#requireCurrent(session: Session): NonNullable<Session['current']> {\n\t\tif (!session.current)\n\t\t\tthrow new AxError('no_capture', 'no_capture: capture the tree of this session first')\n\t\treturn session.current\n\t}\n\n\t/** Resolves a public ID to its session and the core request, or fails with `stale_id`. */\n\t#locate(id: string): Target {\n\t\tif (this.#destroyed)\n\t\t\tthrow new AxError(\n\t\t\t\t'session_closed',\n\t\t\t\t'session_closed: the accessibility controller was destroyed'\n\t\t\t)\n\t\tconst parsed = parseAxId(id)\n\t\tif (!parsed)\n\t\t\tthrow new AxError(\n\t\t\t\t'stale_id',\n\t\t\t\t'stale_id: not an ID of the accessibility tree; capture the tree and use an ID from it'\n\t\t\t)\n\t\tconst session = this.#sessions.get(parsed.token)\n\t\tif (!session)\n\t\t\tthrow new AxError(\n\t\t\t\t'stale_id',\n\t\t\t\t'stale_id: this ID belongs to a session that is closed; capture the tree again and use a current ID'\n\t\t\t)\n\t\tif (!session.current || parsed.generation !== session.generation)\n\t\t\tthrow new AxError(\n\t\t\t\t'stale_id',\n\t\t\t\t'stale_id: this ID is from an earlier capture; capture the tree again and use a current ID'\n\t\t\t)\n\t\tif (session.current.excluded.has(parsed.nodeId))\n\t\t\tthrow new AxError('blocked', \"blocked: the node belongs to the agent's own interface\")\n\t\tconst visual = session.current.visualIds.has(parsed.nodeId)\n\t\tif (!visual && !session.current.coreNodes.has(parsed.nodeId))\n\t\t\tthrow new AxError('invalid', 'invalid: the current capture has no node with this ID')\n\t\tthis.#touch(session)\n\t\treturn {\n\t\t\tsession,\n\t\t\trequest: { snapshotId: session.current.snapshot.snapshotId, nodeId: parsed.nodeId },\n\t\t\tnodeId: parsed.nodeId,\n\t\t\tvisual,\n\t\t}\n\t}\n\n\tasync #motion(\n\t\tidOrOffsets: string | (AxScrollOffsets & { sessionId?: string }),\n\t\toffsets?: AxScrollOffsets\n\t): Promise<{\n\t\tsession: Session\n\t\trequest: { snapshotId: string; nodeId?: string; x?: number; y?: number }\n\t}> {\n\t\tif (typeof idOrOffsets === 'string') {\n\t\t\tif (!offsets || typeof offsets !== 'object')\n\t\t\t\tthrow new AxError('invalid', 'invalid: provide scroll offsets as {x, y}')\n\t\t\tconst target = this.#locate(idOrOffsets)\n\t\t\treturn { session: target.session, request: { ...target.request, x: offsets.x, y: offsets.y } }\n\t\t}\n\t\tif (!idOrOffsets || typeof idOrOffsets !== 'object' || offsets !== undefined)\n\t\t\tthrow new AxError('invalid', 'invalid: provide scroll offsets as {x, y}')\n\t\tconst session = await this.#session(idOrOffsets.sessionId)\n\t\tconst current = this.#requireCurrent(session)\n\t\treturn {\n\t\t\tsession,\n\t\t\trequest: { snapshotId: current.snapshot.snapshotId, x: idOrOffsets.x, y: idOrOffsets.y },\n\t\t}\n\t}\n\n\t/** Runs a synchronous core call and turns its failure into an `AxError`. */\n\t#guard<T>(action: string, call: () => T): T {\n\t\ttry {\n\t\t\treturn call()\n\t\t} catch (error) {\n\t\t\tthrow toAxError(error, action)\n\t\t}\n\t}\n\n\t/**\n\t * Runs one core call as an interaction: overlays out of the way, synthetic events observed, and\n\t * failures reported with whatever had already reached the page.\n\t */\n\tasync #run<T>(\n\t\taction: string,\n\t\tsession: Session,\n\t\tquiet: boolean,\n\t\tcall: () => T | Promise<T>,\n\t\tscrollRequested: () => boolean = () => false\n\t): Promise<{ result: T; evidence: AxEvidence }> {\n\t\tconst runInteraction =\n\t\t\tthis.#options.runInteraction ?? (<R>(interaction: () => Promise<R>) => interaction())\n\t\treturn runInteraction(async () => {\n\t\t\tconst observer = quiet ? null : observeAction(session.document)\n\t\t\tconst stop = (): AxEvidence => ({\n\t\t\t\t...(observer?.stop() ?? { syntheticEvents: null, focusMoved: null }),\n\t\t\t\tscrollIntoViewRequested: scrollRequested(),\n\t\t\t})\n\t\t\ttry {\n\t\t\t\tconst result = await call()\n\t\t\t\treturn { result, evidence: stop() }\n\t\t\t} catch (error) {\n\t\t\t\tthrow toAxError(error, action, stop())\n\t\t\t}\n\t\t})\n\t}\n\n\tasync #act<TResult>(\n\t\taction: AxActionName,\n\t\tid: string,\n\t\toptions: AxActionOptions,\n\t\tcall: (core: AxCoreAgent, request: AxCoreRequest) => TResult,\n\t\tdescribe: {\n\t\t\tstatus: (result: TResult) => AxActionStatus\n\t\t\tsummary: (result: TResult) => string\n\t\t}\n\t): Promise<AxActionOutcome<TResult>> {\n\t\tconst target = this.#locate(id)\n\t\tconst scrolledIntoView = options.scrollIntoView === true && !target.visual\n\t\tlet scrollRequested = false\n\t\tconst { result, evidence } = await this.#run(\n\t\t\taction,\n\t\t\ttarget.session,\n\t\t\tfalse,\n\t\t\t() => {\n\t\t\t\tif (scrolledIntoView) {\n\t\t\t\t\ttarget.session.core.scrollIntoView(target.request)\n\t\t\t\t\tscrollRequested = true\n\t\t\t\t}\n\t\t\t\treturn call(target.session.core, target.request)\n\t\t\t},\n\t\t\t() => scrollRequested\n\t\t)\n\t\treturn {\n\t\t\taction,\n\t\t\tstatus: describe.status(result),\n\t\t\tresult,\n\t\t\tevidence,\n\t\t\tscrolledIntoView,\n\t\t\t...PAGE_SCRIPT,\n\t\t\tsummary: describe.summary(result),\n\t\t}\n\t}\n\n\t#ownInterfaceRoots(session: Session): Element[] {\n\t\t// The agent mounts its interface in the top document only.\n\t\tif (session.kind !== 'root' || !session.document) return []\n\t\tconst selector = this.#options.ignoreSelector ?? DEFAULT_IGNORE_SELECTOR\n\t\tif (!selector) return []\n\t\ttry {\n\t\t\treturn [...session.document.querySelectorAll(selector)]\n\t\t} catch (error) {\n\t\t\tthrow new AxError(\n\t\t\t\t'invalid',\n\t\t\t\t`invalid: ignoreSelector is not a valid selector (${selector})`,\n\t\t\t\t{\n\t\t\t\t\tcause: error,\n\t\t\t\t}\n\t\t\t)\n\t\t}\n\t}\n\n\t#ownInterfacePaths(session: Session): string[] {\n\t\tconst doc = session.document\n\t\tif (!doc) return []\n\t\treturn this.#ownInterfaceRoots(session).map((element) => domPathOf(element, doc))\n\t}\n\n\t#hitsOwnInterface(session: Session, x: number, y: number): boolean {\n\t\tconst roots = this.#ownInterfaceRoots(session)\n\t\tif (roots.length === 0 || !session.document) return false\n\t\tconst hit = session.document.elementFromPoint(x, y)\n\t\treturn !!hit && roots.some((root) => root.contains(hit))\n\t}\n\n\t/** Surfaces inside the agent's own interface, keyed by tag and geometry, with their counts. */\n\t#ownSurfaceKeys(session: Session): Map<string, number> {\n\t\tconst keys = new Map<string, number>()\n\t\tfor (const root of this.#ownInterfaceRoots(session)) {\n\t\t\tconst candidates = [\n\t\t\t\t...(root.matches('canvas, svg, [role=\"application\"]') ? [root] : []),\n\t\t\t\t...root.querySelectorAll('canvas, svg, [role=\"application\"]'),\n\t\t\t]\n\t\t\tfor (const element of candidates) {\n\t\t\t\tconst key = surfaceKey(element.localName, element.getBoundingClientRect())\n\t\t\t\tkeys.set(key, (keys.get(key) ?? 0) + 1)\n\t\t\t}\n\t\t}\n\t\treturn keys\n\t}\n}\n\n/** A name short enough for a message. */\nfunction clip(text: string, limit = 60): string {\n\treturn text.length > limit ? `${text.slice(0, limit)}…` : text\n}\n\n/**\n * How every action here is performed, in the same terms a native-input executor would use: page\n * JavaScript, never physical input, and never a confirmation of the effect on the application.\n */\nconst PAGE_SCRIPT = { backend: 'page-script', nativeInput: false, verifiedOutcome: false } as const\n\nfunction surfaceKey(\n\ttag: string,\n\tbounds: { x: number; y: number; width: number; height: number }\n): string {\n\treturn `${tag}|${bounds.x}|${bounds.y}|${bounds.width}|${bounds.height}`\n}\n\nfunction changeNote(changeDispatched: boolean | undefined): string {\n\treturn changeDispatched === false\n\t\t? ' The change event was withheld because the control, its value or its form target changed during input; the value and the input event may already have had effects.'\n\t\t: ''\n}\n\nfunction stateStatus(result: { dispatched: boolean; applied: boolean }): AxActionStatus {\n\tif (!result.dispatched) return 'noop'\n\treturn result.applied ? 'applied' : 'not_applied'\n}\n\nfunction stateSummary(\n\tresult: { dispatched: boolean; applied: boolean; changeDispatched?: boolean },\n\twhat: string\n): string {\n\tif (!result.dispatched)\n\t\treturn `The control already had the requested ${what}; nothing was dispatched.`\n\treturn (\n\t\t(result.applied\n\t\t\t? `Right after the events the control had the requested ${what}.`\n\t\t\t: `Right after the events the control did not have the requested ${what}.`) +\n\t\tchangeNote(result.changeDispatched) +\n\t\t' This does not show that the page validated or saved it.'\n\t)\n}\n\nfunction dragSummary(result: {\n\tmode: AxDragMode\n\tdropDispatched?: boolean\n\taccepted?: boolean\n\treason?: string\n}): string {\n\tif (result.mode === 'html5') {\n\t\tif (result.reason === 'dragstart_cancelled')\n\t\t\treturn 'The page cancelled dragstart, so nothing else was dispatched and there was no drop.'\n\t\tif (!result.dropDispatched)\n\t\t\treturn 'The destination did not cancel dragover, so no drop was dispatched. dragstart, dragenter, dragover and dragend were.'\n\t\treturn `Synthetic dragstart, dragenter, dragover, drop and dragend were dispatched with a synthetic DataTransfer. ${NOT_VERIFIED}`\n\t}\n\treturn `Synthetic pointer and mouse press, move and release events were dispatched${result.mode === 'pointer-paced' ? ', spaced in time' : ''}. There is no native pointer capture and a library may ignore them. ${NOT_VERIFIED}`\n}\n","/**\n * @file port from browser-use\n * @see https://github.com/browser-use/browser-use/commits/main/browser_use/dom/dom_tree/index.js\n * @match 0.5.9 d51b6e73daff7165fdd3e44debd667e7f5f7fdc5\n *\n * search @edit for all the changed lines.\n *\n * @edit export\n * @edit add interactiveBlacklist interactiveWhitelist\n * @edit adjustable opacity\n * @edit direct dom ref\n * @edit @workaround input.checked\n * @edit smaller zIndex for highlight\n * @edit no need for xpath\n * @edit add `extra` field for extra data\n * @edit scrollable element detection\n * @edit add `data-browser-use-ignore` attribute\n * @edit improve `sampleRect`, filter out rects with 0 area\n * @edit exclude aria-hidden elements\n * @edit make sure attributes exist for interactive candidates.\n * @edit fix \"aria-*\" attributes check\n */\n\nexport default (\n\targs = {\n\t\tdoHighlightElements: true,\n\t\tfocusHighlightIndex: -1,\n\t\tviewportExpansion: 0,\n\t\tdebugMode: false,\n\n\t\t/**\n\t\t * @edit\n\t\t */\n\t\t/** @type {Element[]} */\n\t\tinteractiveBlacklist: [],\n\t\t/** @type {Element[]} */\n\t\tinteractiveWhitelist: [],\n\t\thighlightOpacity: 0.1,\n\t\thighlightLabelOpacity: 0.5,\n\t}\n) => {\n\t/**\n\t * @edit\n\t */\n\tconst { interactiveBlacklist, interactiveWhitelist, highlightOpacity, highlightLabelOpacity } =\n\t\targs\n\n\tconst { doHighlightElements, focusHighlightIndex, viewportExpansion, debugMode } = args\n\tlet highlightIndex = 0 // Reset highlight index\n\n\t/**\n\t * @edit add `extra` field for extra data\n\t */\n\tconst extraData = new WeakMap()\n\tfunction addExtraData(element, data) {\n\t\tif (!element || element.nodeType !== Node.ELEMENT_NODE) return\n\t\textraData.set(element, { ...extraData.get(element), ...data })\n\t}\n\n\t// Add caching mechanisms at the top level\n\tconst DOM_CACHE = {\n\t\tboundingRects: new WeakMap(),\n\t\tclientRects: new WeakMap(),\n\t\tcomputedStyles: new WeakMap(),\n\t\tclearCache: () => {\n\t\t\tDOM_CACHE.boundingRects = new WeakMap()\n\t\t\tDOM_CACHE.clientRects = new WeakMap()\n\t\t\tDOM_CACHE.computedStyles = new WeakMap()\n\t\t},\n\t}\n\n\t/**\n\t * Gets the cached bounding rect for an element.\n\t *\n\t * @param {HTMLElement} element - The element to get the bounding rect for.\n\t * @returns {DOMRect | null} The cached bounding rect, or null if the element is not found.\n\t */\n\tfunction getCachedBoundingRect(element) {\n\t\tif (!element) return null\n\n\t\tif (DOM_CACHE.boundingRects.has(element)) {\n\t\t\treturn DOM_CACHE.boundingRects.get(element)\n\t\t}\n\n\t\tconst rect = element.getBoundingClientRect()\n\n\t\tif (rect) {\n\t\t\tDOM_CACHE.boundingRects.set(element, rect)\n\t\t}\n\t\treturn rect\n\t}\n\n\t/**\n\t * Gets the cached computed style for an element.\n\t *\n\t * @param {HTMLElement} element - The element to get the computed style for.\n\t * @returns {CSSStyleDeclaration | null} The cached computed style, or null if the element is not found.\n\t */\n\tfunction getCachedComputedStyle(element) {\n\t\tif (!element) return null\n\n\t\tif (DOM_CACHE.computedStyles.has(element)) {\n\t\t\treturn DOM_CACHE.computedStyles.get(element)\n\t\t}\n\n\t\tconst style = window.getComputedStyle(element)\n\n\t\tif (style) {\n\t\t\tDOM_CACHE.computedStyles.set(element, style)\n\t\t}\n\t\treturn style\n\t}\n\n\t/**\n\t * Gets the cached client rects for an element.\n\t *\n\t * @param {HTMLElement} element - The element to get the client rects for.\n\t * @returns {DOMRectList | null} The cached client rects, or null if the element is not found.\n\t */\n\tfunction getCachedClientRects(element) {\n\t\tif (!element) return null\n\n\t\tif (DOM_CACHE.clientRects.has(element)) {\n\t\t\treturn DOM_CACHE.clientRects.get(element)\n\t\t}\n\n\t\tconst rects = element.getClientRects()\n\n\t\tif (rects) {\n\t\t\tDOM_CACHE.clientRects.set(element, rects)\n\t\t}\n\t\treturn rects\n\t}\n\n\t/**\n\t * Hash map of DOM nodes indexed by their highlight index.\n\t *\n\t * @type {Object<string, any>}\n\t */\n\tconst DOM_HASH_MAP = {}\n\n\tconst ID = { current: 0 }\n\n\tconst HIGHLIGHT_CONTAINER_ID = 'playwright-highlight-container'\n\n\t// Add a WeakMap cache for XPath strings\n\tconst xpathCache = new WeakMap()\n\n\t// // Initialize once and reuse\n\t// const viewportObserver = new IntersectionObserver(\n\t// (entries) => {\n\t// entries.forEach(entry => {\n\t// elementVisibilityMap.set(entry.target, entry.isIntersecting);\n\t// });\n\t// },\n\t// { rootMargin: `${viewportExpansion}px` }\n\t// );\n\n\t/**\n\t * Highlights an element in the DOM and returns the index of the next element.\n\t *\n\t * @param {HTMLElement} element - The element to highlight.\n\t * @param {number} index - The index of the element.\n\t * @param {HTMLElement | null} parentIframe - The parent iframe node.\n\t * @returns {number} The index of the next element.\n\t */\n\tfunction highlightElement(element, index, parentIframe = null) {\n\t\tif (!element) return index\n\n\t\tconst overlays = []\n\t\t/**\n\t\t * @type {HTMLElement | null}\n\t\t */\n\t\tlet label = null\n\t\tlet labelWidth = 20\n\t\tlet labelHeight = 16\n\t\tlet cleanupFn = null\n\n\t\ttry {\n\t\t\t// Create or get highlight container\n\t\t\tlet container = document.getElementById(HIGHLIGHT_CONTAINER_ID)\n\t\t\tif (!container) {\n\t\t\t\tcontainer = document.createElement('div')\n\t\t\t\tcontainer.id = HIGHLIGHT_CONTAINER_ID\n\t\t\t\tcontainer.style.position = 'fixed'\n\t\t\t\tcontainer.style.pointerEvents = 'none'\n\t\t\t\tcontainer.style.top = '0'\n\t\t\t\tcontainer.style.left = '0'\n\t\t\t\tcontainer.style.width = '100%'\n\t\t\t\tcontainer.style.height = '100%'\n\n\t\t\t\t/**\n\t\t\t\t * @edit smaller zIndex for highlight\n\t\t\t\t */\n\t\t\t\t// Use the maximum valid value in zIndex to ensure the element is not blocked by overlapping elements.\n\t\t\t\t// container.style.zIndex = \"2147483647\";\n\t\t\t\tcontainer.style.zIndex = '2147483640'\n\n\t\t\t\tcontainer.style.backgroundColor = 'transparent'\n\t\t\t\tdocument.body.appendChild(container)\n\t\t\t}\n\n\t\t\t// Get element client rects\n\t\t\tconst rects = element.getClientRects() // Use getClientRects()\n\n\t\t\tif (!rects || rects.length === 0) return index // Exit if no rects\n\n\t\t\t// Generate a color based on the index\n\t\t\tconst colors = [\n\t\t\t\t'#FF0000',\n\t\t\t\t'#00FF00',\n\t\t\t\t'#0000FF',\n\t\t\t\t'#FFA500',\n\t\t\t\t'#800080',\n\t\t\t\t'#008080',\n\t\t\t\t'#FF69B4',\n\t\t\t\t'#4B0082',\n\t\t\t\t'#FF4500',\n\t\t\t\t'#2E8B57',\n\t\t\t\t'#DC143C',\n\t\t\t\t'#4682B4',\n\t\t\t]\n\t\t\tconst colorIndex = index % colors.length\n\t\t\tlet baseColor = colors[colorIndex]\n\n\t\t\t/**\n\t\t\t * @edit adjustable opacity\n\t\t\t */\n\t\t\t// const backgroundColor = baseColor + \"1A\"; // 10% opacity version of the color\n\t\t\tconst backgroundColor =\n\t\t\t\tbaseColor +\n\t\t\t\tMath.floor(highlightOpacity * 255)\n\t\t\t\t\t.toString(16)\n\t\t\t\t\t.padStart(2, '0')\n\t\t\tbaseColor =\n\t\t\t\tbaseColor +\n\t\t\t\tMath.floor(highlightLabelOpacity * 255)\n\t\t\t\t\t.toString(16)\n\t\t\t\t\t.padStart(2, '0')\n\n\t\t\t// Get iframe offset if necessary\n\t\t\tlet iframeOffset = { x: 0, y: 0 }\n\t\t\tif (parentIframe) {\n\t\t\t\tconst iframeRect = parentIframe.getBoundingClientRect() // Keep getBoundingClientRect for iframe offset\n\t\t\t\tiframeOffset.x = iframeRect.left\n\t\t\t\tiframeOffset.y = iframeRect.top\n\t\t\t}\n\n\t\t\t// Create fragment to hold overlay elements\n\t\t\tconst fragment = document.createDocumentFragment()\n\n\t\t\t// Create highlight overlays for each client rect\n\t\t\tfor (const rect of rects) {\n\t\t\t\tif (rect.width === 0 || rect.height === 0) continue // Skip empty rects\n\n\t\t\t\tconst overlay = document.createElement('div')\n\t\t\t\toverlay.style.position = 'fixed'\n\t\t\t\toverlay.style.border = `2px solid ${baseColor}`\n\t\t\t\toverlay.style.backgroundColor = backgroundColor\n\t\t\t\toverlay.style.pointerEvents = 'none'\n\t\t\t\toverlay.style.boxSizing = 'border-box'\n\n\t\t\t\tconst top = rect.top + iframeOffset.y\n\t\t\t\tconst left = rect.left + iframeOffset.x\n\n\t\t\t\toverlay.style.top = `${top}px`\n\t\t\t\toverlay.style.left = `${left}px`\n\t\t\t\toverlay.style.width = `${rect.width}px`\n\t\t\t\toverlay.style.height = `${rect.height}px`\n\n\t\t\t\tfragment.appendChild(overlay)\n\t\t\t\toverlays.push({ element: overlay, initialRect: rect }) // Store overlay and its rect\n\t\t\t}\n\n\t\t\t// Create and position a single label relative to the first rect\n\t\t\tconst firstRect = rects[0]\n\t\t\tlabel = document.createElement('div')\n\t\t\tlabel.className = 'playwright-highlight-label'\n\t\t\tlabel.style.position = 'fixed'\n\t\t\tlabel.style.background = baseColor\n\t\t\tlabel.style.color = 'white'\n\t\t\tlabel.style.padding = '1px 4px'\n\t\t\tlabel.style.borderRadius = '4px'\n\t\t\tlabel.style.fontSize = `${Math.min(12, Math.max(8, firstRect.height / 2))}px`\n\t\t\tlabel.textContent = index.toString()\n\n\t\t\tlabelWidth = label.offsetWidth > 0 ? label.offsetWidth : labelWidth // Update actual width if possible\n\t\t\tlabelHeight = label.offsetHeight > 0 ? label.offsetHeight : labelHeight // Update actual height if possible\n\n\t\t\tconst firstRectTop = firstRect.top + iframeOffset.y\n\t\t\tconst firstRectLeft = firstRect.left + iframeOffset.x\n\n\t\t\tlet labelTop = firstRectTop + 2\n\t\t\tlet labelLeft = firstRectLeft + firstRect.width - labelWidth - 2\n\n\t\t\t// Adjust label position if first rect is too small\n\t\t\tif (firstRect.width < labelWidth + 4 || firstRect.height < labelHeight + 4) {\n\t\t\t\tlabelTop = firstRectTop - labelHeight - 2\n\t\t\t\tlabelLeft = firstRectLeft + firstRect.width - labelWidth // Align with right edge\n\t\t\t\tif (labelLeft < iframeOffset.x) labelLeft = firstRectLeft // Prevent going off-left\n\t\t\t}\n\n\t\t\t// Ensure label stays within viewport bounds slightly better\n\t\t\tlabelTop = Math.max(0, Math.min(labelTop, window.innerHeight - labelHeight))\n\t\t\tlabelLeft = Math.max(0, Math.min(labelLeft, window.innerWidth - labelWidth))\n\n\t\t\tlabel.style.top = `${labelTop}px`\n\t\t\tlabel.style.left = `${labelLeft}px`\n\n\t\t\tfragment.appendChild(label)\n\n\t\t\t// Update positions on scroll/resize\n\t\t\tconst updatePositions = () => {\n\t\t\t\tconst newRects = element.getClientRects() // Get fresh rects\n\t\t\t\tlet newIframeOffset = { x: 0, y: 0 }\n\n\t\t\t\tif (parentIframe) {\n\t\t\t\t\tconst iframeRect = parentIframe.getBoundingClientRect() // Keep getBoundingClientRect for iframe\n\t\t\t\t\tnewIframeOffset.x = iframeRect.left\n\t\t\t\t\tnewIframeOffset.y = iframeRect.top\n\t\t\t\t}\n\n\t\t\t\t// Update each overlay\n\t\t\t\toverlays.forEach((overlayData, i) => {\n\t\t\t\t\tif (i < newRects.length) {\n\t\t\t\t\t\t// Check if rect still exists\n\t\t\t\t\t\tconst newRect = newRects[i]\n\t\t\t\t\t\tconst newTop = newRect.top + newIframeOffset.y\n\t\t\t\t\t\tconst newLeft = newRect.left + newIframeOffset.x\n\n\t\t\t\t\t\toverlayData.element.style.top = `${newTop}px`\n\t\t\t\t\t\toverlayData.element.style.left = `${newLeft}px`\n\t\t\t\t\t\toverlayData.element.style.width = `${newRect.width}px`\n\t\t\t\t\t\toverlayData.element.style.height = `${newRect.height}px`\n\t\t\t\t\t\toverlayData.element.style.display =\n\t\t\t\t\t\t\tnewRect.width === 0 || newRect.height === 0 ? 'none' : 'block'\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// If fewer rects now, hide extra overlays\n\t\t\t\t\t\toverlayData.element.style.display = 'none'\n\t\t\t\t\t}\n\t\t\t\t})\n\n\t\t\t\t// If there are fewer new rects than overlays, hide the extras\n\t\t\t\tif (newRects.length < overlays.length) {\n\t\t\t\t\tfor (let i = newRects.length; i < overlays.length; i++) {\n\t\t\t\t\t\toverlays[i].element.style.display = 'none'\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Update label position based on the first new rect\n\t\t\t\tif (label && newRects.length > 0) {\n\t\t\t\t\tconst firstNewRect = newRects[0]\n\t\t\t\t\tconst firstNewRectTop = firstNewRect.top + newIframeOffset.y\n\t\t\t\t\tconst firstNewRectLeft = firstNewRect.left + newIframeOffset.x\n\n\t\t\t\t\tlet newLabelTop = firstNewRectTop + 2\n\t\t\t\t\tlet newLabelLeft = firstNewRectLeft + firstNewRect.width - labelWidth - 2\n\n\t\t\t\t\tif (firstNewRect.width < labelWidth + 4 || firstNewRect.height < labelHeight + 4) {\n\t\t\t\t\t\tnewLabelTop = firstNewRectTop - labelHeight - 2\n\t\t\t\t\t\tnewLabelLeft = firstNewRectLeft + firstNewRect.width - labelWidth\n\t\t\t\t\t\tif (newLabelLeft < newIframeOffset.x) newLabelLeft = firstNewRectLeft\n\t\t\t\t\t}\n\n\t\t\t\t\t// Ensure label stays within viewport bounds\n\t\t\t\t\tnewLabelTop = Math.max(0, Math.min(newLabelTop, window.innerHeight - labelHeight))\n\t\t\t\t\tnewLabelLeft = Math.max(0, Math.min(newLabelLeft, window.innerWidth - labelWidth))\n\n\t\t\t\t\tlabel.style.top = `${newLabelTop}px`\n\t\t\t\t\tlabel.style.left = `${newLabelLeft}px`\n\t\t\t\t\tlabel.style.display = 'block'\n\t\t\t\t} else if (label) {\n\t\t\t\t\t// Hide label if element has no rects anymore\n\t\t\t\t\tlabel.style.display = 'none'\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst throttleFunction = (func, delay) => {\n\t\t\t\tlet lastCall = 0\n\t\t\t\treturn (...args) => {\n\t\t\t\t\tconst now = performance.now()\n\t\t\t\t\tif (now - lastCall < delay) return\n\t\t\t\t\tlastCall = now\n\t\t\t\t\treturn func(...args)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst throttledUpdatePositions = throttleFunction(updatePositions, 16) // ~60fps\n\t\t\twindow.addEventListener('scroll', throttledUpdatePositions, true)\n\t\t\twindow.addEventListener('resize', throttledUpdatePositions)\n\n\t\t\t// Add cleanup function\n\t\t\tcleanupFn = () => {\n\t\t\t\twindow.removeEventListener('scroll', throttledUpdatePositions, true)\n\t\t\t\twindow.removeEventListener('resize', throttledUpdatePositions)\n\t\t\t\t// Remove overlay elements if needed\n\t\t\t\toverlays.forEach((overlay) => overlay.element.remove())\n\t\t\t\tif (label) label.remove()\n\t\t\t}\n\n\t\t\t// Then add fragment to container in one operation\n\t\t\tcontainer.appendChild(fragment)\n\n\t\t\treturn index + 1\n\t\t} finally {\n\t\t\t// Store cleanup function for later use\n\t\t\tif (cleanupFn) {\n\t\t\t\t// Keep a reference to cleanup functions in a global array\n\t\t\t\t;(window._highlightCleanupFunctions = window._highlightCleanupFunctions || []).push(\n\t\t\t\t\tcleanupFn\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\t// // Add this function to perform cleanup when needed\n\t// function cleanupHighlights() {\n\t// if (window._highlightCleanupFunctions && window._highlightCleanupFunctions.length) {\n\t// window._highlightCleanupFunctions.forEach(fn => fn());\n\t// window._highlightCleanupFunctions = [];\n\t// }\n\n\t// // Also remove the container\n\t// const container = document.getElementById(HIGHLIGHT_CONTAINER_ID);\n\t// if (container) container.remove();\n\t// }\n\n\t/**\n\t * Gets the position of an element in its parent.\n\t *\n\t * @param {HTMLElement} currentElement - The element to get the position for.\n\t * @returns {number} The position of the element in its parent.\n\t */\n\tfunction getElementPosition(currentElement) {\n\t\tif (!currentElement.parentElement) {\n\t\t\treturn 0 // No parent means no siblings\n\t\t}\n\n\t\tconst tagName = currentElement.nodeName.toLowerCase()\n\n\t\tconst siblings = Array.from(currentElement.parentElement.children).filter(\n\t\t\t(sib) => sib.nodeName.toLowerCase() === tagName\n\t\t)\n\n\t\tif (siblings.length === 1) {\n\t\t\treturn 0 // Only element of its type\n\t\t}\n\n\t\tconst index = siblings.indexOf(currentElement) + 1 // 1-based index\n\t\treturn index\n\t}\n\n\tfunction getXPathTree(element, stopAtBoundary = true) {\n\t\tif (xpathCache.has(element)) return xpathCache.get(element)\n\n\t\tconst segments = []\n\t\tlet currentElement = element\n\n\t\twhile (currentElement && currentElement.nodeType === Node.ELEMENT_NODE) {\n\t\t\t// Stop if we hit a shadow root or iframe\n\t\t\tif (\n\t\t\t\tstopAtBoundary &&\n\t\t\t\t(currentElement.parentNode instanceof ShadowRoot ||\n\t\t\t\t\tcurrentElement.parentNode instanceof HTMLIFrameElement)\n\t\t\t) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tconst position = getElementPosition(currentElement)\n\t\t\tconst tagName = currentElement.nodeName.toLowerCase()\n\t\t\tconst xpathIndex = position > 0 ? `[${position}]` : ''\n\t\t\tsegments.unshift(`${tagName}${xpathIndex}`)\n\n\t\t\tcurrentElement = currentElement.parentNode\n\t\t}\n\n\t\tconst result = segments.join('/')\n\t\txpathCache.set(element, result)\n\t\treturn result\n\t}\n\n\t/**\n\t * @edit scrollable element detection\n\t * Checks if an element is scrollable. if so, return the scrollable distance on each direction (left right top bottom). if not return null.\n\t * @note distance smaller than 4 will be considered as not scrollable.\n\t * @note only check block elements, not inline elements.\n\t */\n\tfunction isScrollableElement(element) {\n\t\tif (!element || element.nodeType !== Node.ELEMENT_NODE) {\n\t\t\treturn null // Not a valid element\n\t\t}\n\n\t\tconst style = getCachedComputedStyle(element)\n\t\tif (!style) return null\n\n\t\t// Check if the element is a block-level element\n\t\tconst display = style.display\n\t\tif (display === 'inline' || display === 'inline-block') {\n\t\t\treturn null // Not a block-level element\n\t\t}\n\n\t\t// Check overflow properties\n\t\tconst overflowX = style.overflowX\n\t\tconst overflowY = style.overflowY\n\n\t\t// scrollbar-width/scrollbar-gutter are only set on elements designed to scroll;\n\t\t// their presence signals scroll intent even when overflow is hidden (e.g. overflow: auto on :hover)\n\t\tconst hasScrollbarSignal =\n\t\t\t(style.scrollbarWidth && style.scrollbarWidth !== 'auto') ||\n\t\t\t(style.scrollbarGutter && style.scrollbarGutter !== 'auto')\n\n\t\tconst scrollableX = overflowX === 'auto' || overflowX === 'scroll'\n\t\tconst scrollableY = overflowY === 'auto' || overflowY === 'scroll'\n\n\t\tif (!scrollableX && !scrollableY && !hasScrollbarSignal) {\n\t\t\treturn null // Not scrollable in any direction\n\t\t}\n\n\t\tconst scrollWidth = element.scrollWidth - element.clientWidth\n\t\tconst scrollHeight = element.scrollHeight - element.clientHeight\n\n\t\t// Consider small distances as not scrollable\n\t\tconst threshold = 4\n\n\t\tif (scrollWidth < threshold && scrollHeight < threshold) {\n\t\t\treturn null // Not scrollable\n\t\t}\n\n\t\tif (!scrollableY && !hasScrollbarSignal && scrollWidth < threshold) {\n\t\t\treturn null // Not scrollable horizontally\n\t\t}\n\n\t\tif (!scrollableX && !hasScrollbarSignal && scrollHeight < threshold) {\n\t\t\treturn null // Not scrollable vertically\n\t\t}\n\n\t\tconst distanceToTop = element.scrollTop\n\t\tconst distanceToLeft = element.scrollLeft\n\t\tconst distanceToRight = element.scrollWidth - element.clientWidth - element.scrollLeft\n\t\tconst distanceToBottom = element.scrollHeight - element.clientHeight - element.scrollTop\n\n\t\tconst scrollData = {\n\t\t\ttop: distanceToTop,\n\t\t\tright: distanceToRight,\n\t\t\tbottom: distanceToBottom,\n\t\t\tleft: distanceToLeft,\n\t\t}\n\n\t\t// Store extra data for the element\n\t\taddExtraData(element, {\n\t\t\tscrollable: true,\n\t\t\tscrollData: scrollData,\n\t\t})\n\n\t\treturn scrollData\n\t}\n\n\t/**\n\t * Checks if a text node is visible.\n\t *\n\t * @param {Text} textNode - The text node to check.\n\t * @returns {boolean} Whether the text node is visible.\n\t */\n\tfunction isTextNodeVisible(textNode) {\n\t\ttry {\n\t\t\t// Special case: when viewportExpansion is -1, consider all text nodes as visible\n\t\t\tif (viewportExpansion === -1) {\n\t\t\t\t// Still check parent visibility for basic filtering\n\t\t\t\tconst parentElement = textNode.parentElement\n\t\t\t\tif (!parentElement) return false\n\n\t\t\t\ttry {\n\t\t\t\t\treturn parentElement.checkVisibility({\n\t\t\t\t\t\tcheckOpacity: true,\n\t\t\t\t\t\tcheckVisibilityCSS: true,\n\t\t\t\t\t})\n\t\t\t\t} catch (e) {\n\t\t\t\t\t// Fallback if checkVisibility is not supported\n\t\t\t\t\tconst style = window.getComputedStyle(parentElement)\n\t\t\t\t\treturn style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0'\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst range = document.createRange()\n\t\t\trange.selectNodeContents(textNode)\n\t\t\tconst rects = range.getClientRects() // Use getClientRects for Range\n\n\t\t\tif (!rects || rects.length === 0) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tlet isAnyRectVisible = false\n\t\t\tlet isAnyRectInViewport = false\n\n\t\t\tfor (const rect of rects) {\n\t\t\t\t// Check size\n\t\t\t\tif (rect.width > 0 && rect.height > 0) {\n\t\t\t\t\tisAnyRectVisible = true\n\n\t\t\t\t\t// Viewport check for this rect\n\t\t\t\t\tif (!(\n\t\t\t\t\t\trect.bottom < -viewportExpansion ||\n\t\t\t\t\t\trect.top > window.innerHeight + viewportExpansion ||\n\t\t\t\t\t\trect.right < -viewportExpansion ||\n\t\t\t\t\t\trect.left > window.innerWidth + viewportExpansion\n\t\t\t\t\t)) {\n\t\t\t\t\t\tisAnyRectInViewport = true\n\t\t\t\t\t\tbreak // Found a visible rect in viewport, no need to check others\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!isAnyRectVisible || !isAnyRectInViewport) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// Check parent visibility\n\t\t\tconst parentElement = textNode.parentElement\n\t\t\tif (!parentElement) return false\n\n\t\t\ttry {\n\t\t\t\treturn parentElement.checkVisibility({\n\t\t\t\t\tcheckOpacity: true,\n\t\t\t\t\tcheckVisibilityCSS: true,\n\t\t\t\t})\n\t\t\t} catch (e) {\n\t\t\t\t// Fallback if checkVisibility is not supported\n\t\t\t\tconst style = window.getComputedStyle(parentElement)\n\t\t\t\treturn style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0'\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tconsole.warn('Error checking text node visibility:', e)\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/**\n\t * Checks if an element is accepted.\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @returns {boolean} Whether the element is accepted.\n\t */\n\tfunction isElementAccepted(element) {\n\t\tif (!element || !element.tagName) return false\n\n\t\t// Always accept body and common container elements\n\t\tconst alwaysAccept = new Set([\n\t\t\t'body',\n\t\t\t'div',\n\t\t\t'main',\n\t\t\t'article',\n\t\t\t'section',\n\t\t\t'nav',\n\t\t\t'header',\n\t\t\t'footer',\n\t\t])\n\t\tconst tagName = element.tagName.toLowerCase()\n\n\t\tif (alwaysAccept.has(tagName)) return true\n\n\t\tconst leafElementDenyList = new Set([\n\t\t\t'svg',\n\t\t\t'script',\n\t\t\t'style',\n\t\t\t'link',\n\t\t\t'meta',\n\t\t\t'noscript',\n\t\t\t'template',\n\t\t])\n\n\t\treturn !leafElementDenyList.has(tagName)\n\t}\n\n\t/**\n\t * Checks if an element is visible.\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @returns {boolean} Whether the element is visible.\n\t */\n\tfunction isElementVisible(element) {\n\t\tconst style = getCachedComputedStyle(element)\n\t\treturn (\n\t\t\telement.offsetWidth > 0 &&\n\t\t\telement.offsetHeight > 0 &&\n\t\t\tstyle?.visibility !== 'hidden' &&\n\t\t\tstyle?.display !== 'none'\n\t\t)\n\t}\n\n\t/**\n\t * Checks if an element is interactive.\n\t *\n\t * lots of comments, and uncommented code - to show the logic of what we already tried\n\t *\n\t * One of the things we tried at the beginning was also to use event listeners, and other fancy class, style stuff -> what actually worked best was just combining most things with computed cursor style :)\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t */\n\tfunction isInteractiveElement(element) {\n\t\tif (!element || element.nodeType !== Node.ELEMENT_NODE) {\n\t\t\treturn false\n\t\t}\n\n\t\t/**\n\t\t * @edit add interactiveBlacklist interactiveWhitelist\n\t\t */\n\t\tif (interactiveBlacklist.includes(element)) {\n\t\t\treturn false // Skip blacklisted elements\n\t\t}\n\t\tif (interactiveWhitelist.includes(element)) {\n\t\t\treturn true // Skip whitelisted elements\n\t\t}\n\n\t\t// Cache the tagName and style lookups\n\t\tconst tagName = element.tagName.toLowerCase()\n\t\tconst style = getCachedComputedStyle(element)\n\n\t\t// Define interactive cursors\n\t\tconst interactiveCursors = new Set([\n\t\t\t'pointer', // Link/clickable elements\n\t\t\t'move', // Movable elements\n\t\t\t'text', // Text selection\n\t\t\t'grab', // Grabbable elements\n\t\t\t'grabbing', // Currently grabbing\n\t\t\t'cell', // Table cell selection\n\t\t\t'copy', // Copy operation\n\t\t\t'alias', // Alias creation\n\t\t\t'all-scroll', // Scrollable content\n\t\t\t'col-resize', // Column resize\n\t\t\t'context-menu', // Context menu available\n\t\t\t'crosshair', // Precise selection\n\t\t\t'e-resize', // East resize\n\t\t\t'ew-resize', // East-west resize\n\t\t\t'help', // Help available\n\t\t\t'n-resize', // North resize\n\t\t\t'ne-resize', // Northeast resize\n\t\t\t'nesw-resize', // Northeast-southwest resize\n\t\t\t'ns-resize', // North-south resize\n\t\t\t'nw-resize', // Northwest resize\n\t\t\t'nwse-resize', // Northwest-southeast resize\n\t\t\t'row-resize', // Row resize\n\t\t\t's-resize', // South resize\n\t\t\t'se-resize', // Southeast resize\n\t\t\t'sw-resize', // Southwest resize\n\t\t\t'vertical-text', // Vertical text selection\n\t\t\t'w-resize', // West resize\n\t\t\t'zoom-in', // Zoom in\n\t\t\t'zoom-out', // Zoom out\n\t\t])\n\n\t\t// Define non-interactive cursors\n\t\tconst nonInteractiveCursors = new Set([\n\t\t\t'not-allowed', // Action not allowed\n\t\t\t'no-drop', // Drop not allowed\n\t\t\t'wait', // Processing\n\t\t\t'progress', // In progress\n\t\t\t'initial', // Initial value\n\t\t\t'inherit', // Inherited value\n\t\t\t//? Let's just include all potentially clickable elements that are not specifically blocked\n\t\t\t// 'none', // No cursor\n\t\t\t// 'default', // Default cursor\n\t\t\t// 'auto', // Browser default\n\t\t])\n\n\t\t/**\n\t\t * Checks if an element has an interactive pointer.\n\t\t *\n\t\t * @param {HTMLElement} element - The element to check.\n\t\t * @returns {boolean} Whether the element has an interactive pointer.\n\t\t */\n\t\tfunction doesElementHaveInteractivePointer(element) {\n\t\t\tif (element.tagName.toLowerCase() === 'html') return false\n\n\t\t\tif (style?.cursor && interactiveCursors.has(style.cursor)) return true\n\n\t\t\treturn false\n\t\t}\n\n\t\tlet isInteractiveCursor = doesElementHaveInteractivePointer(element)\n\n\t\t// Genius fix for almost all interactive elements\n\t\tif (isInteractiveCursor) {\n\t\t\treturn true\n\t\t}\n\n\t\tconst interactiveElements = new Set([\n\t\t\t'a', // Links\n\t\t\t'button', // Buttons\n\t\t\t'input', // All input types (text, checkbox, radio, etc.)\n\t\t\t'select', // Dropdown menus\n\t\t\t'textarea', // Text areas\n\t\t\t'details', // Expandable details\n\t\t\t'summary', // Summary element (clickable part of details)\n\t\t\t'label', // Form labels (often clickable)\n\t\t\t'option', // Select options\n\t\t\t'optgroup', // Option groups\n\t\t\t'fieldset', // Form fieldsets (can be interactive with legend)\n\t\t\t'legend', // Fieldset legends\n\t\t])\n\n\t\t// Define explicit disable attributes and properties\n\t\tconst explicitDisableTags = new Set([\n\t\t\t'disabled', // Standard disabled attribute\n\t\t\t// 'aria-disabled', // ARIA disabled state\n\t\t\t'readonly', // Read-only state\n\t\t\t// 'aria-readonly', // ARIA read-only state\n\t\t\t// 'aria-hidden', // Hidden from accessibility\n\t\t\t// 'hidden', // Hidden attribute\n\t\t\t// 'inert', // Inert attribute\n\t\t\t// 'aria-inert', // ARIA inert state\n\t\t\t// 'tabindex=\"-1\"', // Removed from tab order\n\t\t\t// 'aria-hidden=\"true\"' // Hidden from screen readers\n\t\t])\n\n\t\t// handle inputs, select, checkbox, radio, textarea, button and make sure they are not cursor style disabled/not-allowed\n\t\tif (interactiveElements.has(tagName)) {\n\t\t\t// Check for non-interactive cursor\n\t\t\tif (style?.cursor && nonInteractiveCursors.has(style.cursor)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// Check for explicit disable attributes\n\t\t\tfor (const disableTag of explicitDisableTags) {\n\t\t\t\tif (\n\t\t\t\t\telement.hasAttribute(disableTag) ||\n\t\t\t\t\telement.getAttribute(disableTag) === 'true' ||\n\t\t\t\t\telement.getAttribute(disableTag) === ''\n\t\t\t\t) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check for disabled property on form elements\n\t\t\tif (element.disabled) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// Check for readonly property on form elements\n\t\t\tif (element.readOnly) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// Check for inert property\n\t\t\tif (element.inert) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\treturn true\n\t\t}\n\n\t\tconst role = element.getAttribute('role')\n\t\tconst ariaRole = element.getAttribute('aria-role')\n\n\t\t// Check for contenteditable attribute\n\t\tif (element.getAttribute('contenteditable') === 'true' || element.isContentEditable) {\n\t\t\treturn true\n\t\t}\n\n\t\t// Added enhancement to capture dropdown interactive elements\n\t\tif (\n\t\t\telement.classList &&\n\t\t\t(element.classList.contains('button') ||\n\t\t\t\telement.classList.contains('dropdown-toggle') ||\n\t\t\t\telement.getAttribute('data-index') ||\n\t\t\t\telement.getAttribute('data-toggle') === 'dropdown' ||\n\t\t\t\telement.getAttribute('aria-haspopup') === 'true')\n\t\t) {\n\t\t\treturn true\n\t\t}\n\n\t\tconst interactiveRoles = new Set([\n\t\t\t'button', // Directly clickable element\n\t\t\t// 'link', // Clickable link\n\t\t\t'menu', // Menu container (ARIA menus)\n\t\t\t'menubar', // Menu bar container\n\t\t\t'menuitem', // Clickable menu item\n\t\t\t'menuitemradio', // Radio-style menu item (selectable)\n\t\t\t'menuitemcheckbox', // Checkbox-style menu item (toggleable)\n\t\t\t'radio', // Radio button (selectable)\n\t\t\t'checkbox', // Checkbox (toggleable)\n\t\t\t'tab', // Tab (clickable to switch content)\n\t\t\t'switch', // Toggle switch (clickable to change state)\n\t\t\t'slider', // Slider control (draggable)\n\t\t\t'spinbutton', // Number input with up/down controls\n\t\t\t'combobox', // Dropdown with text input\n\t\t\t'searchbox', // Search input field\n\t\t\t'textbox', // Text input field\n\t\t\t'listbox', // Selectable list\n\t\t\t'option', // Selectable option in a list\n\t\t\t'scrollbar', // Scrollable control\n\t\t])\n\n\t\t// Basic role/attribute checks\n\t\tconst hasInteractiveRole =\n\t\t\tinteractiveElements.has(tagName) ||\n\t\t\t(role && interactiveRoles.has(role)) ||\n\t\t\t(ariaRole && interactiveRoles.has(ariaRole))\n\n\t\tif (hasInteractiveRole) return true\n\n\t\t// check whether element has event listeners by window.getEventListeners\n\t\ttry {\n\t\t\tif (typeof getEventListeners === 'function') {\n\t\t\t\tconst listeners = getEventListeners(element)\n\t\t\t\tconst mouseEvents = ['click', 'mousedown', 'mouseup', 'dblclick']\n\t\t\t\tfor (const eventType of mouseEvents) {\n\t\t\t\t\tif (listeners[eventType] && listeners[eventType].length > 0) {\n\t\t\t\t\t\treturn true // Found a mouse interaction listener\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst getEventListenersForNode =\n\t\t\t\telement?.ownerDocument?.defaultView?.getEventListenersForNode ||\n\t\t\t\twindow.getEventListenersForNode\n\t\t\tif (typeof getEventListenersForNode === 'function') {\n\t\t\t\tconst listeners = getEventListenersForNode(element)\n\t\t\t\tconst interactionEvents = [\n\t\t\t\t\t'click',\n\t\t\t\t\t'mousedown',\n\t\t\t\t\t'mouseup',\n\t\t\t\t\t'keydown',\n\t\t\t\t\t'keyup',\n\t\t\t\t\t'submit',\n\t\t\t\t\t'change',\n\t\t\t\t\t'input',\n\t\t\t\t\t'focus',\n\t\t\t\t\t'blur',\n\t\t\t\t]\n\t\t\t\tfor (const eventType of interactionEvents) {\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tif (listener.type === eventType) {\n\t\t\t\t\t\t\treturn true // Found a common interaction listener\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Fallback: Check common event attributes if getEventListeners is not available (getEventListeners doesn't work in page.evaluate context)\n\t\t\tconst commonMouseAttrs = ['onclick', 'onmousedown', 'onmouseup', 'ondblclick']\n\t\t\tfor (const attr of commonMouseAttrs) {\n\t\t\t\tif (element.hasAttribute(attr) || typeof element[attr] === 'function') {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// console.warn(`Could not check event listeners for ${element.tagName}:`, e);\n\t\t\t// If checking listeners fails, rely on other checks\n\t\t}\n\n\t\t/**\n\t\t * @edit scrollable element detection\n\t\t */\n\t\tif (isScrollableElement(element)) {\n\t\t\treturn true\n\t\t}\n\n\t\treturn false\n\t}\n\n\t/**\n\t * Checks if an element is the topmost element at its position.\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @returns {boolean} Whether the element is the topmost element at its position.\n\t */\n\tfunction isTopElement(element) {\n\t\t// Special case: when viewportExpansion is -1, consider all elements as \"top\" elements\n\t\tif (viewportExpansion === -1) {\n\t\t\treturn true\n\t\t}\n\n\t\tconst rects = getCachedClientRects(element) // Replace element.getClientRects()\n\n\t\tif (!rects || rects.length === 0) {\n\t\t\treturn false // No geometry, cannot be top\n\t\t}\n\n\t\tlet isAnyRectInViewport = false\n\t\tfor (const rect of rects) {\n\t\t\t// Use the same logic as isInExpandedViewport check\n\t\t\tif (\n\t\t\t\trect.width > 0 &&\n\t\t\t\trect.height > 0 &&\n\t\t\t\t!(\n\t\t\t\t\t// Only check non-empty rects\n\t\t\t\t\trect.bottom < -viewportExpansion ||\n\t\t\t\t\trect.top > window.innerHeight + viewportExpansion ||\n\t\t\t\t\trect.right < -viewportExpansion ||\n\t\t\t\t\trect.left > window.innerWidth + viewportExpansion\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tisAnyRectInViewport = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif (!isAnyRectInViewport) {\n\t\t\treturn false // All rects are outside the viewport area\n\t\t}\n\n\t\t// Find the correct document context and root element\n\t\tlet doc = element.ownerDocument\n\n\t\t// If we're in an iframe, elements are considered top by default\n\t\tif (doc !== window.document) {\n\t\t\treturn true\n\t\t}\n\n\t\t/**\n\t\t * @edit improve `sampleRect`, filter out rects with 0 area\n\t\t */\n\t\t// find a rect that has width and height as sample\n\t\tlet rect = Array.from(rects).find((r) => r.width > 0 && r.height > 0)\n\t\tif (!rect) {\n\t\t\treturn false // No valid rect found\n\t\t}\n\n\t\t// For shadow DOM, we need to check within its own root context\n\t\tconst shadowRoot = element.getRootNode()\n\t\tif (shadowRoot instanceof ShadowRoot) {\n\t\t\tconst centerX = rect.left + rect.width / 2\n\t\t\tconst centerY = rect.top + rect.height / 2\n\n\t\t\ttry {\n\t\t\t\tconst topEl = shadowRoot.elementFromPoint(centerX, centerY)\n\t\t\t\tif (!topEl) return false\n\n\t\t\t\tlet current = topEl\n\t\t\t\twhile (current && current !== shadowRoot) {\n\t\t\t\t\tif (current === element) return true\n\t\t\t\t\tcurrent = current.parentElement\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t} catch (e) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\tconst margin = 5\n\n\t\t// For elements in viewport, check if they're topmost. Do the check in the\n\t\t// center of the element and at the corners to ensure we catch more cases.\n\t\tconst checkPoints = [\n\t\t\t// Initially only this was used, but it was not enough\n\t\t\t{ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 },\n\t\t\t{ x: rect.left + margin, y: rect.top + margin }, // top left\n\t\t\t// { x: rect.right - margin, y: rect.top + margin }, // top right\n\t\t\t// { x: rect.left + margin, y: rect.bottom - margin }, // bottom left\n\t\t\t{ x: rect.right - margin, y: rect.bottom - margin }, // bottom right\n\t\t]\n\n\t\treturn checkPoints.some(({ x, y }) => {\n\t\t\ttry {\n\t\t\t\tconst topEl = document.elementFromPoint(x, y)\n\t\t\t\tif (!topEl) return false\n\n\t\t\t\tlet current = topEl\n\t\t\t\twhile (current && current !== document.documentElement) {\n\t\t\t\t\tif (current === element) return true\n\t\t\t\t\tcurrent = current.parentElement\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t} catch (e) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Checks if an element is within the expanded viewport.\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @param {number} viewportExpansion - The viewport expansion.\n\t * @returns {boolean} Whether the element is within the expanded viewport.\n\t */\n\tfunction isInExpandedViewport(element, viewportExpansion) {\n\t\tif (viewportExpansion === -1) {\n\t\t\treturn true\n\t\t}\n\n\t\tconst rects = element.getClientRects() // Use getClientRects\n\n\t\tif (!rects || rects.length === 0) {\n\t\t\t// Fallback to getBoundingClientRect if getClientRects is empty,\n\t\t\t// useful for elements like <svg> that might not have client rects but have a bounding box.\n\t\t\tconst boundingRect = getCachedBoundingRect(element)\n\t\t\tif (!boundingRect || boundingRect.width === 0 || boundingRect.height === 0) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn !(\n\t\t\t\tboundingRect.bottom < -viewportExpansion ||\n\t\t\t\tboundingRect.top > window.innerHeight + viewportExpansion ||\n\t\t\t\tboundingRect.right < -viewportExpansion ||\n\t\t\t\tboundingRect.left > window.innerWidth + viewportExpansion\n\t\t\t)\n\t\t}\n\n\t\t// Check if *any* client rect is within the viewport\n\t\tfor (const rect of rects) {\n\t\t\tif (rect.width === 0 || rect.height === 0) continue // Skip empty rects\n\n\t\t\tif (!(\n\t\t\t\trect.bottom < -viewportExpansion ||\n\t\t\t\trect.top > window.innerHeight + viewportExpansion ||\n\t\t\t\trect.right < -viewportExpansion ||\n\t\t\t\trect.left > window.innerWidth + viewportExpansion\n\t\t\t)) {\n\t\t\t\treturn true // Found at least one rect in the viewport\n\t\t\t}\n\t\t}\n\n\t\treturn false // No rects were found in the viewport\n\t}\n\n\t// /**\n\t// * Gets the effective scroll of an element.\n\t// *\n\t// * @param {HTMLElement} element - The element to get the effective scroll for.\n\t// * @returns {Object} The effective scroll of the element.\n\t// */\n\t// function getEffectiveScroll(element) {\n\t// let currentEl = element;\n\t// let scrollX = 0;\n\t// let scrollY = 0;\n\n\t// while (currentEl && currentEl !== document.documentElement) {\n\t// if (currentEl.scrollLeft || currentEl.scrollTop) {\n\t// scrollX += currentEl.scrollLeft;\n\t// scrollY += currentEl.scrollTop;\n\t// }\n\t// currentEl = currentEl.parentElement;\n\t// }\n\n\t// scrollX += window.scrollX;\n\t// scrollY += window.scrollY;\n\n\t// return { scrollX, scrollY };\n\t// }\n\n\t/**\n\t * Checks if an element is an interactive candidate.\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @returns {boolean} Whether the element is an interactive candidate.\n\t */\n\n\t// @edit fix \"aria-*\" attributes check\n\tconst INTERACTIVE_ARIA_ATTRS = [\n\t\t'aria-expanded',\n\t\t'aria-checked',\n\t\t'aria-selected',\n\t\t'aria-pressed',\n\t\t'aria-haspopup',\n\t\t'aria-controls',\n\t\t'aria-owns',\n\t\t'aria-activedescendant',\n\t\t'aria-valuenow',\n\t\t'aria-valuetext',\n\t\t'aria-valuemax',\n\t\t'aria-valuemin',\n\t\t'aria-autocomplete',\n\t]\n\n\tfunction hasInteractiveAria(el) {\n\t\tfor (let i = 0; i < INTERACTIVE_ARIA_ATTRS.length; i++) {\n\t\t\tif (el.hasAttribute(INTERACTIVE_ARIA_ATTRS[i])) return true\n\t\t}\n\t\treturn false\n\t}\n\n\tfunction isInteractiveCandidate(element) {\n\t\tif (!element || element.nodeType !== Node.ELEMENT_NODE) return false\n\n\t\tconst tagName = element.tagName.toLowerCase()\n\n\t\t// Fast-path for common interactive elements\n\t\tconst interactiveElements = new Set([\n\t\t\t'a',\n\t\t\t'button',\n\t\t\t'input',\n\t\t\t'select',\n\t\t\t'textarea',\n\t\t\t'details',\n\t\t\t'summary',\n\t\t\t'label',\n\t\t])\n\n\t\tif (interactiveElements.has(tagName)) return true\n\n\t\t// Quick attribute checks without getting full lists\n\t\tconst hasQuickInteractiveAttr =\n\t\t\telement.hasAttribute('onclick') ||\n\t\t\telement.hasAttribute('role') ||\n\t\t\telement.hasAttribute('tabindex') ||\n\t\t\thasInteractiveAria(element) ||\n\t\t\telement.hasAttribute('data-action') ||\n\t\t\telement.getAttribute('contenteditable') === 'true'\n\n\t\treturn hasQuickInteractiveAttr\n\t}\n\n\t// --- Define constants for distinct interaction check ---\n\tconst DISTINCT_INTERACTIVE_TAGS = new Set([\n\t\t'a',\n\t\t'button',\n\t\t'input',\n\t\t'select',\n\t\t'textarea',\n\t\t'summary',\n\t\t'details',\n\t\t'label',\n\t\t'option',\n\t\t'li',\n\t])\n\tconst DISTINCT_INTERACTIVE_ROLES = new Set([\n\t\t'button',\n\t\t'link',\n\t\t'menuitem',\n\t\t'menuitemradio',\n\t\t'menuitemcheckbox',\n\t\t'radio',\n\t\t'checkbox',\n\t\t'tab',\n\t\t'switch',\n\t\t'slider',\n\t\t'spinbutton',\n\t\t'combobox',\n\t\t'searchbox',\n\t\t'textbox',\n\t\t'listbox',\n\t\t'listitem',\n\t\t'treeitem',\n\t\t'row',\n\t\t'option',\n\t\t'scrollbar',\n\t])\n\n\t/**\n\t * Heuristically determines if an element should be considered as independently interactive,\n\t * even if it's nested inside another interactive container.\n\t *\n\t * This function helps detect deeply nested actionable elements (e.g., menu items within a button)\n\t * that may not be picked up by strict interactivity checks.\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @returns {boolean} Whether the element is heuristically interactive.\n\t */\n\tfunction isHeuristicallyInteractive(element) {\n\t\tif (!element || element.nodeType !== Node.ELEMENT_NODE) return false\n\n\t\t// Skip non-visible elements early for performance\n\t\tif (!isElementVisible(element)) return false\n\n\t\t// Check for common attributes that often indicate interactivity\n\t\tconst hasInteractiveAttributes =\n\t\t\telement.hasAttribute('role') ||\n\t\t\telement.hasAttribute('tabindex') ||\n\t\t\telement.hasAttribute('onclick') ||\n\t\t\ttypeof element.onclick === 'function'\n\n\t\t// Check for semantic class names suggesting interactivity\n\t\tconst hasInteractiveClass = /\\b(btn|clickable|menu|item|entry|link)\\b/i.test(\n\t\t\telement.className || ''\n\t\t)\n\n\t\t// Determine whether the element is inside a known interactive container\n\t\tconst isInKnownContainer = Boolean(\n\t\t\telement.closest('button,a,[role=\"button\"],.menu,.dropdown,.list,.toolbar')\n\t\t)\n\n\t\t// Ensure the element has at least one visible child (to avoid marking empty wrappers)\n\t\tconst hasVisibleChildren = [...element.children].some(isElementVisible)\n\n\t\t// Avoid highlighting elements whose parent is <body> (top-level wrappers)\n\t\tconst isParentBody = element.parentElement && element.parentElement.isSameNode(document.body)\n\n\t\treturn (\n\t\t\t(isInteractiveElement(element) || hasInteractiveAttributes || hasInteractiveClass) &&\n\t\t\thasVisibleChildren &&\n\t\t\tisInKnownContainer &&\n\t\t\t!isParentBody\n\t\t)\n\t}\n\n\t/**\n\t * Checks if an element likely represents a distinct interaction\n\t * separate from its parent (if the parent is also interactive).\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @returns {boolean} Whether the element is a distinct interaction.\n\t */\n\tfunction isElementDistinctInteraction(element) {\n\t\tif (!element || element.nodeType !== Node.ELEMENT_NODE) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst tagName = element.tagName.toLowerCase()\n\t\tconst role = element.getAttribute('role')\n\n\t\t// Check if it's an iframe - always distinct boundary\n\t\tif (tagName === 'iframe') {\n\t\t\treturn true\n\t\t}\n\n\t\t// Check tag name\n\t\tif (DISTINCT_INTERACTIVE_TAGS.has(tagName)) {\n\t\t\treturn true\n\t\t}\n\t\t// Check interactive roles\n\t\tif (role && DISTINCT_INTERACTIVE_ROLES.has(role)) {\n\t\t\treturn true\n\t\t}\n\t\t// Check contenteditable\n\t\tif (element.isContentEditable || element.getAttribute('contenteditable') === 'true') {\n\t\t\treturn true\n\t\t}\n\t\t// Check for common testing/automation attributes\n\t\tif (\n\t\t\telement.hasAttribute('data-testid') ||\n\t\t\telement.hasAttribute('data-cy') ||\n\t\t\telement.hasAttribute('data-test')\n\t\t) {\n\t\t\treturn true\n\t\t}\n\t\t// Check for explicit onclick handler (attribute or property)\n\t\tif (element.hasAttribute('onclick') || typeof element.onclick === 'function') {\n\t\t\treturn true\n\t\t}\n\t\t// ARIA state attributes imply the element manages its own interaction state\n\t\tif (hasInteractiveAria(element)) {\n\t\t\treturn true\n\t\t}\n\n\t\t// return false\n\n\t\t// Check for other common interaction event listeners\n\t\ttry {\n\t\t\tconst getEventListenersForNode =\n\t\t\t\telement?.ownerDocument?.defaultView?.getEventListenersForNode ||\n\t\t\t\twindow.getEventListenersForNode\n\t\t\tif (typeof getEventListenersForNode === 'function') {\n\t\t\t\tconst listeners = getEventListenersForNode(element)\n\t\t\t\tconst interactionEvents = [\n\t\t\t\t\t'click',\n\t\t\t\t\t'mousedown',\n\t\t\t\t\t'mouseup',\n\t\t\t\t\t'keydown',\n\t\t\t\t\t'keyup',\n\t\t\t\t\t'submit',\n\t\t\t\t\t'change',\n\t\t\t\t\t'input',\n\t\t\t\t\t'focus',\n\t\t\t\t\t'blur',\n\t\t\t\t]\n\t\t\t\tfor (const eventType of interactionEvents) {\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tif (listener.type === eventType) {\n\t\t\t\t\t\t\treturn true // Found a common interaction listener\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Fallback: Check common event attributes if getEventListeners is not available (getEventListenersForNode doesn't work in page.evaluate context)\n\t\t\tconst commonEventAttrs = [\n\t\t\t\t'onmousedown',\n\t\t\t\t'onmouseup',\n\t\t\t\t'onkeydown',\n\t\t\t\t'onkeyup',\n\t\t\t\t'onsubmit',\n\t\t\t\t'onchange',\n\t\t\t\t'oninput',\n\t\t\t\t'onfocus',\n\t\t\t\t'onblur',\n\t\t\t]\n\t\t\tif (commonEventAttrs.some((attr) => element.hasAttribute(attr))) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// console.warn(`Could not check event listeners for ${element.tagName}:`, e);\n\t\t\t// If checking listeners fails, rely on other checks\n\t\t}\n\n\t\t// if the element is not strictly interactive but appears clickable based on heuristic signals\n\t\tif (isHeuristicallyInteractive(element)) {\n\t\t\treturn true\n\t\t}\n\n\t\t// Scrollable containers are always distinct — the LLM needs their index for targeted scrolling.\n\t\t// Check extraData (already set by isScrollableElement in isInteractiveElement) to avoid redundant layout reads.\n\t\tif (extraData.get(element)?.scrollable) {\n\t\t\treturn true\n\t\t}\n\n\t\t// Default to false: if it's interactive but doesn't match above,\n\t\t// assume it triggers the same action as the parent.\n\t\treturn false\n\t}\n\t// --- End distinct interaction check ---\n\n\t/**\n * Handles the logic for deciding whether to highlight an element and performing the highlight.\n * @param {\n {\n tagName: string;\n attributes: Record<string, string>;\n xpath: any;\n children: never[];\n isVisible?: boolean;\n isTopElement?: boolean;\n isInteractive?: boolean;\n isInViewport?: boolean;\n highlightIndex?: number;\n shadowRoot?: boolean;\n }} nodeData - The node data object.\n * @param {HTMLElement} node - The node to highlight.\n * @param {HTMLElement | null} parentIframe - The parent iframe node.\n * @param {boolean} isParentHighlighted - Whether the parent node is highlighted.\n * @returns {boolean} Whether the element was highlighted.\n */\n\tfunction handleHighlighting(nodeData, node, parentIframe, isParentHighlighted) {\n\t\tif (!nodeData.isInteractive) return false // Not interactive, definitely don't highlight\n\n\t\tlet shouldHighlight = false\n\t\tif (!isParentHighlighted) {\n\t\t\t// Parent wasn't highlighted, this interactive node can be highlighted.\n\t\t\tshouldHighlight = true\n\t\t} else {\n\t\t\t// Parent *was* highlighted. Only highlight this node if it represents a distinct interaction.\n\t\t\tif (isElementDistinctInteraction(node)) {\n\t\t\t\tshouldHighlight = true\n\t\t\t} else {\n\t\t\t\t// console.log(`Skipping highlight for ${nodeData.tagName} (parent highlighted)`);\n\t\t\t\tshouldHighlight = false\n\t\t\t}\n\t\t}\n\n\t\tif (shouldHighlight) {\n\t\t\t// Check viewport status before assigning index and highlighting\n\t\t\tnodeData.isInViewport = isInExpandedViewport(node, viewportExpansion)\n\n\t\t\t// When viewportExpansion is -1, all interactive elements should get a highlight index\n\t\t\t// regardless of viewport status\n\t\t\tif (nodeData.isInViewport || viewportExpansion === -1) {\n\t\t\t\tnodeData.highlightIndex = highlightIndex++\n\n\t\t\t\tif (doHighlightElements) {\n\t\t\t\t\tif (focusHighlightIndex >= 0) {\n\t\t\t\t\t\tif (focusHighlightIndex === nodeData.highlightIndex) {\n\t\t\t\t\t\t\thighlightElement(node, nodeData.highlightIndex, parentIframe)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\thighlightElement(node, nodeData.highlightIndex, parentIframe)\n\t\t\t\t\t}\n\t\t\t\t\treturn true // Successfully highlighted\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// console.log(`Skipping highlight for ${nodeData.tagName} (outside viewport)`);\n\t\t\t}\n\t\t}\n\n\t\treturn false // Did not highlight\n\t}\n\n\t/**\n\t * Creates a node data object for a given node and its descendants.\n\t *\n\t * @param {HTMLElement} node - The node to process.\n\t * @param {HTMLElement | null} parentIframe - The parent iframe node.\n\t * @param {boolean} isParentHighlighted - Whether the parent node is highlighted.\n\t * @returns {string | null} The ID of the node data object, or null if the node is not processed.\n\t */\n\tfunction buildDomTree(node, parentIframe = null, isParentHighlighted = false) {\n\t\t// Fast rejection checks first\n\t\tif (\n\t\t\t!node ||\n\t\t\tnode.id === HIGHLIGHT_CONTAINER_ID ||\n\t\t\t(node.nodeType !== Node.ELEMENT_NODE && node.nodeType !== Node.TEXT_NODE)\n\t\t) {\n\t\t\treturn null\n\t\t}\n\n\t\tif (!node || node.id === HIGHLIGHT_CONTAINER_ID) {\n\t\t\treturn null\n\t\t}\n\n\t\t/**\n\t\t * @edit add `data-browser-use-ignore` attribute\n\t\t */\n\t\tif (node.dataset?.browserUseIgnore === 'true' || node.dataset?.pageAgentIgnore === 'true') {\n\t\t\treturn null // Skip this node and its children\n\t\t}\n\n\t\t/**\n\t\t * @edit exclude aria-hidden elements\n\t\t */\n\t\tif (node.getAttribute && node.getAttribute('aria-hidden') === 'true') {\n\t\t\treturn null // Skip this node and its children\n\t\t}\n\n\t\t// Special handling for root node (body)\n\t\tif (node === document.body) {\n\t\t\tconst nodeData = {\n\t\t\t\ttagName: 'body',\n\t\t\t\tattributes: {},\n\t\t\t\txpath: '/body',\n\t\t\t\tchildren: [],\n\t\t\t}\n\n\t\t\t// Process children of body\n\t\t\tfor (const child of node.childNodes) {\n\t\t\t\tconst domElement = buildDomTree(child, parentIframe, false) // Body's children have no highlighted parent initially\n\t\t\t\tif (domElement) nodeData.children.push(domElement)\n\t\t\t}\n\n\t\t\tconst id = `${ID.current++}`\n\t\t\tDOM_HASH_MAP[id] = nodeData\n\t\t\treturn id\n\t\t}\n\n\t\t// Early bailout for non-element nodes except text\n\t\tif (node.nodeType !== Node.ELEMENT_NODE && node.nodeType !== Node.TEXT_NODE) {\n\t\t\treturn null\n\t\t}\n\n\t\t// Process text nodes\n\t\tif (node.nodeType === Node.TEXT_NODE) {\n\t\t\tconst textContent = node.textContent?.trim()\n\t\t\tif (!textContent) {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\t// Only check visibility for text nodes that might be visible\n\t\t\tconst parentElement = node.parentElement\n\t\t\tif (!parentElement || parentElement.tagName.toLowerCase() === 'script') {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\tconst id = `${ID.current++}`\n\t\t\tDOM_HASH_MAP[id] = {\n\t\t\t\ttype: 'TEXT_NODE',\n\t\t\t\ttext: textContent,\n\t\t\t\tisVisible: isTextNodeVisible(node),\n\t\t\t}\n\t\t\treturn id\n\t\t}\n\n\t\t// Quick checks for element nodes\n\t\tif (node.nodeType === Node.ELEMENT_NODE && !isElementAccepted(node)) {\n\t\t\treturn null\n\t\t}\n\n\t\t// Early viewport check - only filter out elements clearly outside viewport\n\t\t// The getBoundingClientRect() of the Shadow DOM host element may return width/height = 0\n\t\tif (viewportExpansion !== -1 && !node.shadowRoot) {\n\t\t\tconst rect = getCachedBoundingRect(node) // Keep for initial quick check\n\t\t\tconst style = getCachedComputedStyle(node)\n\n\t\t\t// Skip viewport check for fixed/sticky elements as they may appear anywhere\n\t\t\tconst isFixedOrSticky = style && (style.position === 'fixed' || style.position === 'sticky')\n\n\t\t\t// Check if element has actual dimensions using offsetWidth/Height (quick check)\n\t\t\tconst hasSize = node.offsetWidth > 0 || node.offsetHeight > 0\n\n\t\t\t// Use getBoundingClientRect for the quick OUTSIDE check.\n\t\t\t// isInExpandedViewport will do the more accurate check later if needed.\n\t\t\tif (\n\t\t\t\t!rect ||\n\t\t\t\t(!isFixedOrSticky &&\n\t\t\t\t\t!hasSize &&\n\t\t\t\t\t(rect.bottom < -viewportExpansion ||\n\t\t\t\t\t\trect.top > window.innerHeight + viewportExpansion ||\n\t\t\t\t\t\trect.right < -viewportExpansion ||\n\t\t\t\t\t\trect.left > window.innerWidth + viewportExpansion))\n\t\t\t) {\n\t\t\t\t// console.log(\"Skipping node outside viewport (quick check):\", node.tagName, rect);\n\t\t\t\treturn null\n\t\t\t}\n\t\t}\n\n\t\t/**\n * @type {\n {\n tagName: string;\n attributes: Record<string, string | null>;\n xpath: any;\n children: never[];\n isVisible?: boolean;\n isTopElement?: boolean;\n isInteractive?: boolean;\n isInViewport?: boolean;\n highlightIndex?: number;\n shadowRoot?: boolean;\n }\n } nodeData - The node data object.\n */\n\t\tconst nodeData = {\n\t\t\ttagName: node.tagName.toLowerCase(),\n\t\t\tattributes: {},\n\n\t\t\t/**\n\t\t\t * @edit no need for xpath\n\t\t\t */\n\t\t\t// xpath: getXPathTree(node, true),\n\n\t\t\tchildren: [],\n\t\t}\n\n\t\t// Get attributes for interactive elements or potential text containers\n\t\tif (\n\t\t\tisInteractiveCandidate(node) ||\n\t\t\tnode.tagName.toLowerCase() === 'iframe' ||\n\t\t\tnode.tagName.toLowerCase() === 'body'\n\t\t) {\n\t\t\tconst attributeNames = node.getAttributeNames?.() || []\n\t\t\tfor (const name of attributeNames) {\n\t\t\t\tconst value = node.getAttribute(name)\n\t\t\t\tnodeData.attributes[name] = value\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * @edit @workaround input.checked\n\t\t\t */\n\t\t\tif (\n\t\t\t\tnode.tagName.toLowerCase() === 'input' &&\n\t\t\t\t(node.type === 'checkbox' || node.type === 'radio')\n\t\t\t) {\n\t\t\t\tnodeData.attributes.checked = node.checked ? 'true' : 'false' // Store as string for consistency\n\t\t\t}\n\t\t}\n\n\t\tlet nodeWasHighlighted = false\n\t\t// Perform visibility, interactivity, and highlighting checks\n\t\tif (node.nodeType === Node.ELEMENT_NODE) {\n\t\t\tnodeData.isVisible = isElementVisible(node) // isElementVisible uses offsetWidth/Height, which is fine\n\t\t\tif (nodeData.isVisible) {\n\t\t\t\tnodeData.isTopElement = isTopElement(node)\n\n\t\t\t\t// Special handling for ARIA menu containers - check interactivity even if not top element\n\t\t\t\tconst role = node.getAttribute('role')\n\t\t\t\tconst isMenuContainer = role === 'menu' || role === 'menubar' || role === 'listbox'\n\n\t\t\t\tif (nodeData.isTopElement || isMenuContainer) {\n\t\t\t\t\tnodeData.isInteractive = isInteractiveElement(node)\n\t\t\t\t\t// Call the dedicated highlighting function\n\t\t\t\t\tnodeWasHighlighted = handleHighlighting(nodeData, node, parentIframe, isParentHighlighted)\n\n\t\t\t\t\t/**\n\t\t\t\t\t * @edit direct dom ref\n\t\t\t\t\t */\n\t\t\t\t\tnodeData.ref = node\n\n\t\t\t\t\t/**\n\t\t\t\t\t * @edit make sure attributes exist for interactive candidates.\n\t\t\t\t\t * @note if the element failed the isInteractiveCandidate, attributes would be empty.\n\t\t\t\t\t */\n\t\t\t\t\tif (nodeData.isInteractive && Object.keys(nodeData.attributes).length === 0) {\n\t\t\t\t\t\tconst attributeNames = node.getAttributeNames?.() || []\n\t\t\t\t\t\tfor (const name of attributeNames) {\n\t\t\t\t\t\t\tconst value = node.getAttribute(name)\n\t\t\t\t\t\t\tnodeData.attributes[name] = value\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Process children, with special handling for iframes and rich text editors\n\t\tif (node.tagName) {\n\t\t\tconst tagName = node.tagName.toLowerCase()\n\n\t\t\t// Handle iframes\n\t\t\tif (tagName === 'iframe') {\n\t\t\t\ttry {\n\t\t\t\t\tconst iframeDoc = node.contentDocument || node.contentWindow?.document\n\t\t\t\t\tif (iframeDoc) {\n\t\t\t\t\t\tfor (const child of iframeDoc.childNodes) {\n\t\t\t\t\t\t\tconst domElement = buildDomTree(child, node, false)\n\t\t\t\t\t\t\tif (domElement) nodeData.children.push(domElement)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconsole.warn('Unable to access iframe:', e)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Handle rich text editors and contenteditable elements\n\t\t\telse if (\n\t\t\t\tnode.isContentEditable ||\n\t\t\t\tnode.getAttribute('contenteditable') === 'true' ||\n\t\t\t\tnode.id === 'tinymce' ||\n\t\t\t\tnode.classList.contains('mce-content-body') ||\n\t\t\t\t(tagName === 'body' && node.getAttribute('data-id')?.startsWith('mce_'))\n\t\t\t) {\n\t\t\t\t// Process all child nodes to capture formatted text\n\t\t\t\tfor (const child of node.childNodes) {\n\t\t\t\t\tconst domElement = buildDomTree(child, parentIframe, nodeWasHighlighted)\n\t\t\t\t\tif (domElement) nodeData.children.push(domElement)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Handle shadow DOM\n\t\t\t\tif (node.shadowRoot) {\n\t\t\t\t\tnodeData.shadowRoot = true\n\t\t\t\t\tfor (const child of node.shadowRoot.childNodes) {\n\t\t\t\t\t\tconst domElement = buildDomTree(child, parentIframe, nodeWasHighlighted)\n\t\t\t\t\t\tif (domElement) nodeData.children.push(domElement)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Handle regular elements\n\t\t\t\tfor (const child of node.childNodes) {\n\t\t\t\t\t// Pass the highlighted status of the *current* node to its children\n\t\t\t\t\tconst passHighlightStatusToChild = nodeWasHighlighted || isParentHighlighted\n\t\t\t\t\tconst domElement = buildDomTree(child, parentIframe, passHighlightStatusToChild)\n\t\t\t\t\tif (domElement) nodeData.children.push(domElement)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Skip empty anchor tags only if they have no dimensions and no children\n\t\tif (nodeData.tagName === 'a' && nodeData.children.length === 0 && !nodeData.attributes.href) {\n\t\t\t// Check if the anchor has actual dimensions\n\t\t\tconst rect = getCachedBoundingRect(node)\n\t\t\tconst hasSize =\n\t\t\t\t(rect && rect.width > 0 && rect.height > 0) || node.offsetWidth > 0 || node.offsetHeight > 0\n\n\t\t\tif (!hasSize) {\n\t\t\t\treturn null\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * @edit add `extra` field for extra data\n\t\t */\n\t\tnodeData.extra = extraData.get(node) || null\n\n\t\tconst id = `${ID.current++}`\n\t\tDOM_HASH_MAP[id] = nodeData\n\t\treturn id\n\t}\n\n\tconst rootId = buildDomTree(document.body)\n\n\t// Clear the cache before starting\n\tDOM_CACHE.clearCache()\n\n\treturn { rootId, map: DOM_HASH_MAP }\n}\n","import domTree from './dom_tree/index.js'\nimport {\n\tElementDomNode,\n\tFlatDomTree,\n\tInteractiveElementDomNode,\n\tTextDomNode,\n} from './dom_tree/type'\n\n/**\n * Viewport expansion for DOM tree extraction.\n * -1 means full page (no viewport restriction)\n * 0 means viewport only\n * positive values expand the viewport by that many pixels\n *\n * @note Since isTopElement depends on elementFromPoint,\n * it returns null when out of viewport, this feature has no practical use, only differ between -1 and 0\n */\nconst DEFAULT_VIEWPORT_EXPANSION = -1\n\nexport function resolveViewportExpansion(viewportExpansion?: number): number {\n\treturn viewportExpansion ?? DEFAULT_VIEWPORT_EXPANSION\n}\n\nexport interface DomConfig {\n\tviewportExpansion?: number\n\tinteractiveBlacklist?: (Element | (() => Element))[]\n\tinteractiveWhitelist?: (Element | (() => Element))[]\n\tincludeAttributes?: string[]\n\thighlightOpacity?: number\n\thighlightLabelOpacity?: number\n\n\t/**\n\t * Preserve semantic landmark tags in dehydrated output even if not interactive\n\t * @note maybe confusing for LLM combining with page scrolling, use with caution\n\t **/\n\tkeepSemanticTags?: boolean\n}\n\n// TODO: corresponding roles\nconst SEMANTIC_TAGS = new Set([\n\t'nav',\n\t'menu',\n\t// 'main',\n\t'header',\n\t'footer',\n\t'aside',\n\t// 'article',\n\t// 'form',\n\t'dialog',\n])\n\n/**\n * 用于检测可交互元素是否是新出现的。\n */\nconst newElementsCache = new WeakMap<HTMLElement, string>()\n\nexport function getFlatTree(config: DomConfig): FlatDomTree {\n\tconst viewportExpansion = resolveViewportExpansion(config.viewportExpansion)\n\n\tconst interactiveBlacklist = [] as Element[]\n\tfor (const item of config.interactiveBlacklist || []) {\n\t\tif (typeof item === 'function') {\n\t\t\tinteractiveBlacklist.push(item())\n\t\t} else {\n\t\t\tinteractiveBlacklist.push(item)\n\t\t}\n\t}\n\n\tconst interactiveWhitelist = [] as Element[]\n\tfor (const item of config.interactiveWhitelist || []) {\n\t\tif (typeof item === 'function') {\n\t\t\tinteractiveWhitelist.push(item())\n\t\t} else {\n\t\t\tinteractiveWhitelist.push(item)\n\t\t}\n\t}\n\n\tconst elements = domTree({\n\t\tdoHighlightElements: true,\n\t\tdebugMode: true,\n\t\tfocusHighlightIndex: -1,\n\t\tviewportExpansion,\n\t\tinteractiveBlacklist,\n\t\tinteractiveWhitelist,\n\t\thighlightOpacity: config.highlightOpacity ?? 0.0,\n\t\thighlightLabelOpacity: config.highlightLabelOpacity ?? 0.1,\n\t}) as FlatDomTree\n\n\tconst currentUrl = window.location.href\n\n\t/**\n\t * 标记新出现的元素\n\t * @todo browser-use 使用 hash(位置,属性等信息) 来判断是否同一个元素,\n\t * 能够解决 1. 元素被删除后重新添加 2. 页面卸载 等问题。\n\t * 这里先简单做.\n\t */\n\tfor (const nodeId in elements.map) {\n\t\tconst node = elements.map[nodeId]\n\t\tif (node.isInteractive && node.ref) {\n\t\t\tconst ref = node.ref as HTMLElement\n\t\t\t// @note 这样太严格,元素是可以跨页面存在的\n\t\t\t// if (newElementsCache.get(ref) !== currentUrl) {\n\t\t\tif (!newElementsCache.has(ref)) {\n\t\t\t\tnewElementsCache.set(ref, currentUrl)\n\t\t\t\tnode.isNew = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn elements\n}\n\nconst globRegexCache = new Map<string, RegExp>()\n\nfunction globToRegex(pattern: string): RegExp {\n\tlet regex = globRegexCache.get(pattern)\n\tif (!regex) {\n\t\tconst escaped = pattern.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n\t\tregex = new RegExp(`^${escaped.replace(/\\*/g, '.*')}$`)\n\t\tglobRegexCache.set(pattern, regex)\n\t}\n\treturn regex\n}\n\nfunction matchAttributes(\n\tattrs: Record<string, string>,\n\tpatterns: string[]\n): Record<string, string> {\n\tconst result: Record<string, string> = {}\n\n\tfor (const pattern of patterns) {\n\t\tif (pattern.includes('*')) {\n\t\t\tconst regex = globToRegex(pattern)\n\t\t\tfor (const key of Object.keys(attrs)) {\n\t\t\t\tif (regex.test(key) && attrs[key].trim()) {\n\t\t\t\t\tresult[key] = attrs[key].trim()\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tconst value = attrs[pattern]\n\t\t\tif (value && value.trim()) {\n\t\t\t\tresult[pattern] = value.trim()\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}\n\n/**\n * elementsToString 内部使用的类型\n */\ninterface TreeNode {\n\ttype: 'text' | 'element'\n\tparent: TreeNode | null\n\tchildren: TreeNode[]\n\tisVisible: boolean\n\t// Text node properties\n\ttext?: string\n\t// Element node properties\n\ttagName?: string\n\tattributes?: Record<string, string>\n\tisInteractive?: boolean\n\tisTopElement?: boolean\n\tisNew?: boolean\n\thighlightIndex?: number\n\textra?: Record<string, any>\n}\n\n/**\n * 对应 python 中的 views::clickable_elements_to_string,\n * 将 dom 信息处理成适合 llm 阅读的文本格式\n * @形如\n * ``` text\n * [0]<a aria-label=page-agent.js 首页 />\n * [1]<div >P />\n * [2]<div >page-agent.js\n * UI Agent in your webpage />\n * [3]<a >文档 />\n * [4]<a aria-label=查看源码(在新窗口打开)>源码 />\n * UI Agent in your webpage\n * 用户输入需求,AI 理解页面并自动操作。\n * [5]<a role=button>快速开始 />\n * [6]<a role=button>查看文档 />\n * 无需后端\n * ```\n * 其中可交互元素用序号标出,提示llm可以用序号操作。\n * 缩进代表父子关系。\n * 普通文本则直接列出来。\n *\n * @todo 数据脱敏过滤器\n */\nexport function flatTreeToString(\n\tflatTree: FlatDomTree,\n\tincludeAttributes: string[] = [],\n\tkeepSemanticTags = false\n): string {\n\tconst DEFAULT_INCLUDE_ATTRIBUTES = [\n\t\t'title',\n\t\t'type',\n\t\t'checked',\n\t\t'name',\n\t\t'role',\n\t\t'value',\n\t\t'placeholder',\n\t\t'data-date-format',\n\t\t'alt',\n\t\t'aria-label',\n\t\t'aria-expanded',\n\t\t'data-state',\n\t\t'aria-checked',\n\n\t\t// @edit added for better form handling\n\t\t'id',\n\t\t'for',\n\n\t\t// for jump check\n\t\t'target',\n\n\t\t// absolute position dropdown menu\n\t\t'aria-haspopup',\n\t\t'aria-controls',\n\t\t'aria-owns',\n\n\t\t// content editable\n\t\t'contenteditable',\n\t]\n\n\tconst includeAttrs = [...includeAttributes, ...DEFAULT_INCLUDE_ATTRIBUTES]\n\n\t// Helper function to cap text length\n\tconst capTextLength = (text: string, maxLength: number): string => {\n\t\tif (text.length > maxLength) {\n\t\t\treturn text.substring(0, maxLength) + '...'\n\t\t}\n\t\treturn text\n\t}\n\n\t// Build tree structure from flat map\n\tconst buildTreeNode = (nodeId: string): TreeNode | null => {\n\t\tconst node = flatTree.map[nodeId]\n\t\tif (!node) return null\n\n\t\tif (node.type === 'TEXT_NODE') {\n\t\t\tconst textNode = node as TextDomNode\n\t\t\treturn {\n\t\t\t\ttype: 'text',\n\t\t\t\ttext: textNode.text,\n\t\t\t\tisVisible: textNode.isVisible,\n\t\t\t\tparent: null,\n\t\t\t\tchildren: [],\n\t\t\t}\n\t\t} else {\n\t\t\tconst elementNode = node as ElementDomNode\n\t\t\tconst children: TreeNode[] = []\n\n\t\t\tif (elementNode.children) {\n\t\t\t\tfor (const childId of elementNode.children) {\n\t\t\t\t\tconst child = buildTreeNode(childId)\n\t\t\t\t\tif (child) {\n\t\t\t\t\t\tchild.parent = null // Will be set later\n\t\t\t\t\t\tchildren.push(child)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\ttype: 'element',\n\t\t\t\ttagName: elementNode.tagName,\n\t\t\t\tattributes: elementNode.attributes ?? {},\n\t\t\t\tisVisible: elementNode.isVisible ?? false,\n\t\t\t\tisInteractive: elementNode.isInteractive ?? false,\n\t\t\t\tisTopElement: elementNode.isTopElement ?? false,\n\t\t\t\tisNew: elementNode.isNew ?? false,\n\t\t\t\thighlightIndex: elementNode.highlightIndex,\n\t\t\t\tparent: null,\n\t\t\t\tchildren,\n\t\t\t\textra: elementNode.extra ?? {},\n\t\t\t}\n\t\t}\n\t}\n\n\t// Set parent references\n\tconst setParentReferences = (node: TreeNode, parent: TreeNode | null = null) => {\n\t\tnode.parent = parent\n\t\tfor (const child of node.children) {\n\t\t\tsetParentReferences(child, node)\n\t\t}\n\t}\n\n\t// Build root node\n\tconst rootNode = buildTreeNode(flatTree.rootId)\n\tif (!rootNode) return ''\n\n\tsetParentReferences(rootNode)\n\n\t// Helper to check if text node has parent with highlight index\n\tconst hasParentWithHighlightIndex = (node: TreeNode): boolean => {\n\t\tlet current = node.parent\n\t\twhile (current) {\n\t\t\tif (current.type === 'element' && current.highlightIndex !== undefined) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tcurrent = current.parent\n\t\t}\n\t\treturn false\n\t}\n\n\t// Helper to check if parent is top element\n\t// const isParentTopElement = (node: TreeNode): boolean => {\n\t// \treturn node.parent?.type === 'element' && node.parent.isTopElement === true\n\t// }\n\n\t// Main processing function\n\tconst processNode = (node: TreeNode, depth: number, result: string[]): void => {\n\t\tlet nextDepth = depth\n\t\tconst depthStr = '\\t'.repeat(depth)\n\n\t\tif (node.type === 'element') {\n\t\t\tconst isSemantic = keepSemanticTags && node.tagName && SEMANTIC_TAGS.has(node.tagName)\n\n\t\t\t// Add element with highlight_index\n\t\t\tif (node.highlightIndex !== undefined) {\n\t\t\t\tnextDepth += 1\n\n\t\t\t\tconst text = getAllTextTillNextClickableElement(node)\n\t\t\t\tlet attributesHtmlStr = ''\n\n\t\t\t\tif (includeAttrs.length > 0 && node.attributes) {\n\t\t\t\t\tconst attributesToInclude = matchAttributes(node.attributes, includeAttrs)\n\n\t\t\t\t\t// Remove duplicate values (for attributes longer than 5 chars)\n\t\t\t\t\tconst keys = Object.keys(attributesToInclude)\n\t\t\t\t\tif (keys.length > 1) {\n\t\t\t\t\t\tconst keysToRemove = new Set<string>()\n\t\t\t\t\t\tconst seenValues: Record<string, string> = {}\n\n\t\t\t\t\t\tfor (const key of keys) {\n\t\t\t\t\t\t\tconst value = attributesToInclude[key]\n\t\t\t\t\t\t\tif (value.length > 5) {\n\t\t\t\t\t\t\t\tif (value in seenValues) {\n\t\t\t\t\t\t\t\t\tkeysToRemove.add(key)\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tseenValues[value] = key\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (const key of keysToRemove) {\n\t\t\t\t\t\t\tdelete attributesToInclude[key]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Remove role if it matches tagName\n\t\t\t\t\tif (attributesToInclude.role === node.tagName) {\n\t\t\t\t\t\tdelete attributesToInclude.role\n\t\t\t\t\t}\n\n\t\t\t\t\t// Remove attributes that duplicate text content\n\t\t\t\t\tconst attrsToRemoveIfTextMatches = ['aria-label', 'placeholder', 'title']\n\t\t\t\t\tfor (const attr of attrsToRemoveIfTextMatches) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tattributesToInclude[attr] &&\n\t\t\t\t\t\t\tattributesToInclude[attr].toLowerCase().trim() === text.toLowerCase().trim()\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tdelete attributesToInclude[attr]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (Object.keys(attributesToInclude).length > 0) {\n\t\t\t\t\t\tattributesHtmlStr = Object.entries(attributesToInclude)\n\t\t\t\t\t\t\t.map(([key, value]) => `${key}=${capTextLength(value, 20)}`)\n\t\t\t\t\t\t\t.join(' ')\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Build the line\n\t\t\t\tconst highlightIndicator = node.isNew\n\t\t\t\t\t? `*[${node.highlightIndex}]`\n\t\t\t\t\t: `[${node.highlightIndex}]`\n\t\t\t\tlet line = `${depthStr}${highlightIndicator}<${node.tagName ?? ''}`\n\n\t\t\t\tif (attributesHtmlStr) {\n\t\t\t\t\tline += ` ${attributesHtmlStr}`\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * @edit scrollable 数据\n\t\t\t\t */\n\t\t\t\tif (node.extra) {\n\t\t\t\t\tif (node.extra.scrollable) {\n\t\t\t\t\t\tlet scrollDataText = ''\n\t\t\t\t\t\tif (node.extra.scrollData?.left)\n\t\t\t\t\t\t\tscrollDataText += `left=${node.extra.scrollData.left}, `\n\t\t\t\t\t\tif (node.extra.scrollData?.top) scrollDataText += `top=${node.extra.scrollData.top}, `\n\t\t\t\t\t\tif (node.extra.scrollData?.right)\n\t\t\t\t\t\t\tscrollDataText += `right=${node.extra.scrollData.right}, `\n\t\t\t\t\t\tif (node.extra.scrollData?.bottom)\n\t\t\t\t\t\t\tscrollDataText += `bottom=${node.extra.scrollData.bottom}`\n\n\t\t\t\t\t\tline += ` data-scrollable=\"${scrollDataText}\"`\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (text) {\n\t\t\t\t\tconst trimmedText = text.trim()\n\t\t\t\t\tif (!attributesHtmlStr) {\n\t\t\t\t\t\tline += ' '\n\t\t\t\t\t}\n\t\t\t\t\tline += `>${trimmedText}`\n\t\t\t\t} else if (!attributesHtmlStr) {\n\t\t\t\t\tline += ' '\n\t\t\t\t}\n\n\t\t\t\tline += ' />'\n\t\t\t\tresult.push(line)\n\t\t\t}\n\n\t\t\t// special treatment for semantic tags\n\t\t\t// even if they are not interactive, we can keep them for clear context\n\n\t\t\tconst emitSemantic = isSemantic && node.highlightIndex === undefined\n\t\t\t// to check if this tag is empty\n\t\t\tconst mark = emitSemantic ? result.length : -1\n\n\t\t\tif (emitSemantic) {\n\t\t\t\tresult.push(`${depthStr}<${node.tagName}>`)\n\t\t\t\tnextDepth += 1\n\t\t\t}\n\n\t\t\tfor (const child of node.children) {\n\t\t\t\tprocessNode(child, nextDepth, result)\n\t\t\t}\n\n\t\t\tif (emitSemantic) {\n\t\t\t\t// empty tag should be removed\n\t\t\t\tif (result.length === mark + 1) {\n\t\t\t\t\tresult.pop()\n\t\t\t\t} else {\n\t\t\t\t\tresult.push(`${depthStr}</${node.tagName}>`)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (node.type === 'text') {\n\t\t\t// Add text only if it doesn't have a highlighted parent\n\t\t\tif (hasParentWithHighlightIndex(node)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tnode.parent &&\n\t\t\t\tnode.parent.type === 'element' &&\n\t\t\t\tnode.parent.isVisible &&\n\t\t\t\tnode.parent.isTopElement\n\t\t\t) {\n\t\t\t\tresult.push(`${depthStr}${node.text ?? ''}`)\n\t\t\t}\n\t\t}\n\t}\n\n\tconst result: string[] = []\n\tprocessNode(rootNode, 0, result)\n\treturn result.join('\\n')\n}\n\n// Get all text until next clickable element\nexport const getAllTextTillNextClickableElement = (node: TreeNode, maxDepth = -1): string => {\n\tconst textParts: string[] = []\n\n\tconst collectText = (currentNode: TreeNode, currentDepth: number) => {\n\t\tif (maxDepth !== -1 && currentDepth > maxDepth) {\n\t\t\treturn\n\t\t}\n\n\t\t// Skip this branch if we hit a highlighted element (except for the current node)\n\t\tif (\n\t\t\tcurrentNode.type === 'element' &&\n\t\t\tcurrentNode !== node &&\n\t\t\tcurrentNode.highlightIndex !== undefined\n\t\t) {\n\t\t\treturn\n\t\t}\n\n\t\tif (currentNode.type === 'text' && currentNode.text) {\n\t\t\ttextParts.push(currentNode.text)\n\t\t} else if (currentNode.type === 'element') {\n\t\t\tfor (const child of currentNode.children) {\n\t\t\t\tcollectText(child, currentDepth + 1)\n\t\t\t}\n\t\t}\n\t}\n\n\tcollectText(node, 0)\n\treturn textParts.join('\\n').trim()\n}\n\nexport function getSelectorMap(flatTree: FlatDomTree): Map<number, InteractiveElementDomNode> {\n\tconst selectorMap = new Map<number, InteractiveElementDomNode>()\n\n\tconst keys = Object.keys(flatTree.map)\n\tfor (const key of keys) {\n\t\tconst node = flatTree.map[key]\n\t\tif (node.isInteractive && typeof node.highlightIndex === 'number') {\n\t\t\tselectorMap.set(node.highlightIndex, node as InteractiveElementDomNode)\n\t\t}\n\t}\n\n\treturn selectorMap\n}\n\nexport function getElementTextMap(simplifiedHTML: string) {\n\tconst lines = simplifiedHTML\n\t\t.split('\\n')\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0)\n\tconst elementTextMap = new Map<number, string>()\n\tfor (const line of lines) {\n\t\tconst regex = /^\\[(\\d+)\\]<[^>]+>([^<]*)/\n\t\tconst match = regex.exec(line)\n\t\tif (match) {\n\t\t\tconst index = parseInt(match[1], 10)\n\t\t\telementTextMap.set(index, line)\n\t\t}\n\t}\n\n\treturn elementTextMap\n}\n\nexport function cleanUpHighlights() {\n\tconst cleanupFunctions = (window as any)._highlightCleanupFunctions || []\n\tfor (const cleanup of cleanupFunctions) {\n\t\tif (typeof cleanup === 'function') {\n\t\t\tcleanup()\n\t\t}\n\t}\n\n\t;(window as any)._highlightCleanupFunctions = []\n}\n\n// 监听 URL 的任何变化,立刻清空 highLights\nwindow.addEventListener('popstate', () => {\n\t// console.log('URL changed (popstate), highlights cleaned up.')\n\tcleanUpHighlights()\n})\nwindow.addEventListener('hashchange', () => {\n\t// console.log('URL changed (hashchange), highlights cleaned up.')\n\tcleanUpHighlights()\n})\nwindow.addEventListener('beforeunload', () => {\n\t// console.log('Page is unloading, highlights cleaned up.')\n\tcleanUpHighlights()\n})\n\nconst navigation = (window as any).navigation\nif (navigation && typeof navigation.addEventListener === 'function') {\n\tnavigation.addEventListener('navigate', () => {\n\t\t// console.log('Navigation event detected, highlights cleaned up.')\n\t\tcleanUpHighlights()\n\t})\n} else {\n\t// 定时器\n\tlet currentUrl = window.location.href\n\tsetInterval(() => {\n\t\tif (window.location.href !== currentUrl) {\n\t\t\tcurrentUrl = window.location.href\n\t\t\t// console.log('URL changed (interval), highlights cleaned up.')\n\t\t\tcleanUpHighlights()\n\t\t}\n\t}, 500)\n}\n","export function getPageInfo() {\n\tconst viewport_width = window.innerWidth\n\tconst viewport_height = window.innerHeight\n\n\tconst page_width = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth || 0)\n\tconst page_height = Math.max(\n\t\tdocument.documentElement.scrollHeight,\n\t\tdocument.body.scrollHeight || 0\n\t)\n\n\tconst scroll_x = window.scrollX || window.pageXOffset || document.documentElement.scrollLeft || 0\n\tconst scroll_y = window.scrollY || window.pageYOffset || document.documentElement.scrollTop || 0\n\n\tconst pixels_below = Math.max(0, page_height - (window.innerHeight + scroll_y))\n\tconst pixels_right = Math.max(0, page_width - (window.innerWidth + scroll_x))\n\n\treturn {\n\t\t// Current viewport dimensions\n\t\tviewport_width,\n\t\tviewport_height,\n\n\t\t// Total page dimensions\n\t\tpage_width,\n\t\tpage_height,\n\n\t\t// Current scroll position\n\t\tscroll_x,\n\t\tscroll_y,\n\n\t\tpixels_above: scroll_y,\n\t\tpixels_below,\n\n\t\tpages_above: viewport_height > 0 ? scroll_y / viewport_height : 0,\n\t\tpages_below: viewport_height > 0 ? pixels_below / viewport_height : 0,\n\t\ttotal_pages: viewport_height > 0 ? page_height / viewport_height : 0,\n\n\t\tcurrent_page_position: scroll_y / Math.max(1, page_height - viewport_height),\n\n\t\tpixels_left: scroll_x,\n\t\tpixels_right,\n\t}\n}\n","import type { PageController } from '../PageController'\n\n// Find common React root elements and add data-page-agent-not-interactive attribute\nexport function patchReact(pageController: PageController) {\n\tconst reactRootElements = document.querySelectorAll(\n\t\t'[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^=\"root-\"], [id^=\"app-\"], #adex-wrapper, #adex-root'\n\t)\n\n\tfor (const element of reactRootElements) {\n\t\telement.setAttribute('data-page-agent-not-interactive', 'true')\n\t}\n}\n\n/**\n * @todo (Heavy, might have false negatives) Interaction detection, if element width/height equals body offsetWidth/Height, consider it root element and non-interactive (React often attaches many events to root elements, causing false positives)\n */\n","/**\n * Whether generated JavaScript can run in this page.\n *\n * A site Content Security Policy that omits `unsafe-eval` rejects `eval` and `new Function`.\n * No browser permission dialog adds `unsafe-eval` to that policy. The probe runs once per origin.\n */\n\nexport type ScriptAccess = 'allowed' | 'blocked_by_csp'\n\nconst accessByOrigin = new Map<string, ScriptAccess>()\n\nexport const SCRIPT_BLOCKED_BY_CSP =\n\t\"blocked_by_csp: This site's Content Security Policy disallows generated JavaScript (unsafe-eval). The user cannot grant this on the page. Do not call execute_javascript again here. Use the indexed tools, including drag_element to move one index onto another.\"\n\nexport const SCRIPT_USER_DENIED =\n\t'user_denied: The user did not allow generated JavaScript in this browser. Do not call execute_javascript again here. Use the indexed tools.'\n\nexport const SCRIPT_UNAVAILABLE =\n\t'unavailable: Generated JavaScript cannot run in this browser. Do not call execute_javascript again here. Use the indexed tools.'\n\n/** True when the tool result closes generated scripts for the rest of the task. */\nexport function scriptAccessClosed(message: string): boolean {\n\treturn /^(blocked_by_csp|user_denied|unavailable):/.test(message)\n}\n\nexport function scriptOrigin(): string {\n\ttry {\n\t\treturn globalThis.location?.origin || 'unknown'\n\t} catch {\n\t\treturn 'unknown'\n\t}\n}\n\n/** A CSP refusal is an EvalError, sometimes wrapped as a plain Error with the policy text. */\nexport function isEvalBlocked(error: unknown): boolean {\n\tif (typeof EvalError !== 'undefined' && error instanceof EvalError) return true\n\tconst message = error instanceof Error ? error.message : String(error)\n\treturn /unsafe-eval|Content Security Policy|Refused to evaluate a string as JavaScript/i.test(\n\t\tmessage\n\t)\n}\n\n/**\n * Probe `new Function` once per origin and remember the answer.\n * Pass an origin in tests. The page path uses `scriptOrigin()`.\n */\nexport function generatedScriptAccess(origin = scriptOrigin()): ScriptAccess {\n\tconst cached = accessByOrigin.get(origin)\n\tif (cached) return cached\n\tlet access: ScriptAccess = 'allowed'\n\ttry {\n\t\t// The empty function is never called. Compiling it is the only way to ask\n\t\t// whether this page's Content Security Policy allows generated scripts.\n\t\t// eslint-disable-next-line @typescript-eslint/no-implied-eval\n\t\tnew Function('')\n\t} catch (error) {\n\t\tif (!isEvalBlocked(error)) throw error\n\t\taccess = 'blocked_by_csp'\n\t}\n\taccessByOrigin.set(origin, access)\n\treturn access\n}\n\nexport function rememberScriptAccess(origin: string, access: ScriptAccess): void {\n\taccessByOrigin.set(origin, access)\n}\n\n/** Test-only. Production never forgets a probe during the page session. */\nexport function clearScriptAccessForTests(): void {\n\taccessByOrigin.clear()\n}\n","/** Longest script result sent back to the model. Longer results are cut and say so. */\nexport const SCRIPT_RESULT_MAX_CHARS = 4000\n\n/**\n * Turns the value returned by a page script into text the model can read.\n * Objects and arrays become JSON (a template literal would print \"[object Object]\").\n * Functions show their source; values JSON cannot represent (cycles) are named as such.\n */\nexport function formatScriptResult(result: unknown): string {\n\tif (typeof result === 'string') return truncate(result)\n\tif (result === undefined) return 'undefined'\n\tif (typeof result === 'function') return truncate(result.toString())\n\tlet text: string\n\ttry {\n\t\ttext = JSON.stringify(result) ?? '[unserializable value]'\n\t} catch {\n\t\ttext = '[unserializable value]'\n\t}\n\treturn truncate(text)\n}\n\nfunction truncate(text: string): string {\n\tif (text.length <= SCRIPT_RESULT_MAX_CHARS) return text\n\treturn `${text.slice(0, SCRIPT_RESULT_MAX_CHARS)}... [truncated, ${text.length - SCRIPT_RESULT_MAX_CHARS} more characters]`\n}\n","/** How old, in seconds, a read of the element list may be and still confirm a fact about the page. */\nexport const STATE_FRESH_SECONDS = 10\n\n/** Seconds since the element list was read. Never negative. */\nexport function stateAgeSeconds(lastUpdate: number, now: number): number {\n\treturn Math.max(0, (now - lastUpdate) / 1000)\n}\n\n/** Whether a read of the given age may still be used to confirm a fact. */\nexport function isStateFresh(ageSeconds: number): boolean {\n\treturn ageSeconds <= STATE_FRESH_SECONDS\n}\n\n/**\n * Whether a script should read the page before answering. It reads when the page was never read, or the last read\n * is older than the limit. It never reads while the agent is busy: the agent owns the element list then.\n */\nexport function shouldRefresh(input: {\n\tneverRead: boolean\n\tageSeconds: number\n\tmaxAgeSeconds: number\n\tbusy: boolean\n}): boolean {\n\tif (input.busy) return false\n\treturn input.neverRead || input.ageSeconds > input.maxAgeSeconds\n}\n","/**\n * Indexes for canvas, svg and role=application surfaces that are not nodes of the accessibility\n * tree. The index is a public id from `targetAt`, so the existing drag tool can aim at it.\n * A surface that already has an id is a tree node and is left as it is. No role is invented.\n *\n * Called from PageController.updateAccessibilityTree after observeIndexed.\n */\nimport type { AxBounds, AxIndexedObservation, AxSurface } from './ax'\n\nexport interface ViewportSize {\n\twidth: number\n\theight: number\n}\n\nexport interface SurfaceHit {\n\tid: string\n\ttag: string\n}\n\n/**\n * A point inside both the surface rectangle and the viewport.\n * `targetAt` rejects coordinates outside the viewport, so a center that falls outside is moved\n * into the visible overlap. Returns null when that overlap is empty or thinner than one pixel.\n */\nexport function visibleSurfacePoint(\n\tbounds: AxBounds,\n\tviewport: ViewportSize\n): { x: number; y: number } | null {\n\tif (!(viewport.width >= 1) || !(viewport.height >= 1)) return null\n\tif (![bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isFinite)) return null\n\tif (!(bounds.width > 0) || !(bounds.height > 0)) return null\n\n\tconst left = Math.max(bounds.x, 0)\n\tconst top = Math.max(bounds.y, 0)\n\tconst right = Math.min(bounds.x + bounds.width, viewport.width)\n\tconst bottom = Math.min(bounds.y + bounds.height, viewport.height)\n\tif (right - left < 1 || bottom - top < 1) return null\n\n\tconst x = clamp(Math.round((left + right) / 2), 0, viewport.width - 1)\n\tconst y = clamp(Math.round((top + bottom) / 2), 0, viewport.height - 1)\n\tif (x >= left && x < right && y >= top && y < bottom) return { x, y }\n\n\tconst fallbackX = clamp(Math.floor(left), 0, viewport.width - 1)\n\tconst fallbackY = clamp(Math.floor(top), 0, viewport.height - 1)\n\tif (fallbackX >= left && fallbackX < right && fallbackY >= top && fallbackY < bottom)\n\t\treturn { x: fallbackX, y: fallbackY }\n\treturn null\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n\treturn Math.min(max, Math.max(min, value))\n}\n\nexport interface IndexedSurfaces {\n\tobservation: AxIndexedObservation\n\t/** Viewport point passed to `targetAt` for each new index. */\n\tpoints: Map<number, { x: number; y: number }>\n}\n\n/**\n * Appends one numbered line per surface that has bounds and no tree id.\n * A failed hit-test is skipped. The original observation is not mutated.\n */\nexport async function appendSurfaceIndexes(\n\tobservation: AxIndexedObservation,\n\tsurfaces: readonly AxSurface[],\n\ttargetAt: (x: number, y: number) => Promise<SurfaceHit>,\n\tviewport: ViewportSize\n): Promise<IndexedSurfaces> {\n\tconst ids = observation.ids.slice()\n\tconst labels = observation.labels.slice()\n\tconst lines: string[] = []\n\tconst points = new Map<number, { x: number; y: number }>()\n\n\tfor (const surface of surfaces) {\n\t\tif (surface.id !== null) continue\n\t\tconst point = visibleSurfacePoint(surface.bounds, viewport)\n\t\tif (!point) continue\n\t\ttry {\n\t\t\tconst hit = await targetAt(point.x, point.y)\n\t\t\tif (hit.tag.toLowerCase() !== surface.tag.toLowerCase()) continue\n\t\t\tif (ids.includes(hit.id)) continue\n\t\t\tconst index = ids.length\n\t\t\tconst quoted = JSON.stringify(surface.label ?? '')\n\t\t\tids.push(hit.id)\n\t\t\tlabels.push(`${surface.tag} ${quoted}`)\n\t\t\tpoints.set(index, point)\n\t\t\tlines.push(`[${index}] ${surface.tag} ${quoted} (not in the tree; drag target for this read)`)\n\t\t} catch {\n\t\t\t// One surface that cannot be addressed must not drop the rest of the read.\n\t\t}\n\t}\n\n\tif (lines.length === 0) return { observation, points }\n\treturn {\n\t\tobservation: {\n\t\t\t...observation,\n\t\t\ttext: `${observation.text.replace(/\\s*$/, '')}\\n${lines.join('\\n')}`,\n\t\t\tids,\n\t\t\tlabels,\n\t\t},\n\t\tpoints,\n\t}\n}\n","/**\n * Copyright (C) 2025 Alibaba Group Holding Limited\n * All rights reserved.\n *\n * PageController - Manages DOM operations and element interactions.\n * Designed to be independent of LLM and can be tested in unit tests.\n * All public methods are async for potential remote calling support.\n */\nimport {\n\tclickElement,\n\tgetElementByIndex,\n\tinputTextElement,\n\tscrollHorizontally,\n\tscrollIntoViewIfNeeded,\n\tscrollVertically,\n\tselectOptionElement,\n} from './actions'\nimport {\n\ttype AccessibilityConfig,\n\tAccessibilityController,\n\ttype AxActionOutcome,\n\ttype AxDragMode,\n\tAxError,\n\ttype AxIndexedObservation,\n\ttype AxKeyOptions,\n} from './ax'\nimport * as dom from './dom'\nimport type { FlatDomTree, InteractiveElementDomNode } from './dom/dom_tree/type'\nimport { getPageInfo } from './dom/getPageInfo'\nimport { patchReact } from './patches/react'\nimport {\n\tSCRIPT_BLOCKED_BY_CSP,\n\tgeneratedScriptAccess,\n\tisEvalBlocked,\n\trememberScriptAccess,\n\tscriptOrigin,\n} from './scriptAccess'\nimport { formatScriptResult } from './scriptResult'\nimport { STATE_FRESH_SECONDS, isStateFresh, shouldRefresh, stateAgeSeconds } from './stateFreshness'\nimport { appendSurfaceIndexes } from './surfaceIndexes'\nimport {\n\tclickPointer,\n\tdisablePassThrough,\n\tenablePassThrough,\n\tisAnchorElement,\n\tisHTMLElement,\n\tisSelectElement,\n\tmovePointerToElement,\n} from './utils'\n\n/**\n * Configuration for PageController\n */\nexport interface PageControllerConfig extends dom.DomConfig {\n\t/** Enable visual mask overlay during operations (default: false) */\n\tenableMask?: boolean\n\n\t/**\n\t * How the page is read for the agent, and therefore what the element indexes point at.\n\t *\n\t * - `'accessibility'` (default): a reconstructed accessibility tree. Each index is a node of the\n\t * tree, and the index-based actions (click, input, select, scroll) go through the tree's\n\t * identity checks: a target that changed since it was read is refused instead of guessed.\n\t * - `'dom'`: the list of interactive elements with numbered highlights on the page.\n\t *\n\t * The methods, the tools and the indexes are the same in both. If the tree cannot be built for a\n\t * step, that step falls back to `'dom'` and says so in the state.\n\t * @note The tree is an approximation of the browser's accessibility tree, and its actions are\n\t * synthetic events that a page may ignore.\n\t */\n\tobservation?: 'accessibility' | 'dom'\n\n\t/** Budgets and limits of the accessibility tree. */\n\taccessibility?: AccessibilityConfig\n\n\t/**\n\t * Print to the console what the agent reads at every step, exactly as it receives it, and what\n\t * each action targeted. The text is the page's own content, before `transformPageContent`.\n\t * @default true\n\t */\n\tlogObservations?: boolean\n}\n\n/**\n * Structured browser state for LLM consumption\n */\nexport interface BrowserState {\n\turl: string\n\ttitle: string\n\t/** Page info + scroll position hint (e.g. \"Page info: 1920x1080px...\\n[Start of page]\") */\n\theader: string\n\t/** Simplified HTML of interactive elements */\n\tcontent: string\n\t/** Page footer hint (e.g. \"... 300 pixels below ...\" or \"[End of page]\") */\n\tfooter: string\n}\n\ninterface ActionResult {\n\tsuccess: boolean\n\tmessage: string\n}\n\nconst LOG_STYLE = 'color:#7c5cff;font-weight:600'\n\n/** What a failed accessibility action tells the agent: the reason, and what had already happened. */\nfunction describeFailure(error: unknown): string {\n\tconst message = error instanceof Error ? error.message : String(error)\n\tif (!(error instanceof AxError)) return `${message}.`\n\tlet text = `${message}.`\n\tif (error.effects)\n\t\ttext += ` ⚠️ Partially executed (${error.effects}); this was not undone and may have changed the page.`\n\tif (error.code === 'stale_id' || error.code === 'stale_snapshot' || error.code === 'stale_node')\n\t\ttext +=\n\t\t\t' The page changed since it was read: use the indexes of the next page state, and do not assume the same element is behind this index.'\n\treturn text\n}\n\n/** Window scroll position. A missing or non-finite value is reported as zero. */\nfunction readWindowScroll(): { x: number; y: number } {\n\tconst x = window.scrollX\n\tconst y = window.scrollY\n\treturn {\n\t\tx: Number.isFinite(x) ? Math.round(x) : 0,\n\t\ty: Number.isFinite(y) ? Math.round(y) : 0,\n\t}\n}\n\n/** Index actions that exist only on the accessibility tree. */\nfunction treeRequired(action: string): ActionResult {\n\treturn {\n\t\tsuccess: false,\n\t\tmessage: `❌ ${action} needs the accessibility tree. This step is the element list, so these indexes cannot be used.`,\n\t}\n}\n\n/**\n * PageController manages DOM state and element interactions.\n * It provides async methods for all DOM operations, keeping state isolated.\n *\n * @lifecycle\n * - beforeUpdate: Emitted before the DOM tree is updated.\n * - afterUpdate: Emitted after the DOM tree is updated.\n */\nexport class PageController extends EventTarget {\n\tprivate config: PageControllerConfig\n\n\t/** Corresponds to eval_page in browser-use */\n\tprivate flatTree: FlatDomTree | null = null\n\n\t/**\n\t * All highlighted index-mapped interactive elements\n\t * Corresponds to DOMState.selector_map in browser-use\n\t */\n\tprivate selectorMap = new Map<number, InteractiveElementDomNode>()\n\n\t/** Index -> element text description mapping */\n\tprivate elementTextMap = new Map<number, string>()\n\n\t/**\n\t * Simplified HTML for LLM consumption.\n\t * Corresponds to clickable_elements_to_string in browser-use\n\t */\n\tprivate simplifiedHTML = '<EMPTY>'\n\n\t/** last time the tree was updated */\n\tprivate lastTimeUpdate = 0\n\n\t/** Whether the tree has been indexed at least once */\n\tprivate isIndexed = false\n\n\t/** Visual mask overlay for blocking user interaction during automation */\n\tprivate mask: InstanceType<typeof import('./mask/SimulatorMask').SimulatorMask> | null = null\n\tprivate maskReady: Promise<void> | null = null\n\n\t/** What the indexes of the last read point at. A failed tree read makes a step `'dom'`. */\n\tprivate indexSource: 'accessibility' | 'dom' = 'dom'\n\n\t/** The last accessibility read: index -> node ID and label. */\n\tprivate axObservation: AxIndexedObservation | null = null\n\n\t/**\n\t * Viewport point of a surface index added after the tree. The id behind that index is a visual\n\t * target, so later gestures use this point instead of looking the element up again.\n\t */\n\tprivate surfacePoints = new Map<number, { x: number; y: number }>()\n\n\t/** Why the last read fell back from the accessibility tree to the element list, if it did. */\n\tprivate fallbackNote = ''\n\n\t/**\n\t * Milliseconds of the last successful accessibility read, including surface indexes.\n\t * Null until that read succeeds. A fallback to the element list does not invent a duration.\n\t * This is not a precision score and it is not a speed budget.\n\t */\n\tprivate lastTreeReadMs: number | null = null\n\n\t/** Created on first use; the core behind it is loaded on the first capture. */\n\tprivate accessibilityController: AccessibilityController | null = null\n\t/** Accessibility interactions in progress that need the mask out of the way. */\n\tprivate accessibilityInteractions = 0\n\n\tconstructor(config: PageControllerConfig = {}) {\n\t\tsuper()\n\n\t\tthis.config = config\n\n\t\tpatchReact(this)\n\n\t\tif (config.enableMask) this.initMask()\n\t}\n\n\t/**\n\t * Initialize mask asynchronously (dynamic import to avoid CSS loading in Node)\n\t */\n\tinitMask() {\n\t\tif (this.maskReady !== null) return\n\t\tthis.maskReady = (async () => {\n\t\t\tconst { SimulatorMask } = await import('./mask/SimulatorMask')\n\t\t\tthis.mask = new SimulatorMask()\n\t\t})()\n\t}\n\t// ======= State Queries =======\n\n\t/**\n\t * Get current page URL\n\t */\n\tasync getCurrentUrl(): Promise<string> {\n\t\treturn window.location.href\n\t}\n\n\t/**\n\t * Get last tree update timestamp\n\t */\n\tasync getLastUpdateTime(): Promise<number> {\n\t\treturn this.lastTimeUpdate\n\t}\n\n\t/**\n\t * Duration of the last successful accessibility read, in milliseconds.\n\t * Null when that read has not succeeded. The number is not a precision score.\n\t */\n\tasync getLastTreeReadMs(): Promise<number | null> {\n\t\treturn this.lastTreeReadMs\n\t}\n\n\t/** Set by the agent: true while a task runs. Scripts never refresh the element list then. */\n\tisBusy: () => boolean = () => false\n\n\t/**\n\t * The page state a script should use. Reads the page only when it was never read or the last read is older than\n\t * `maxAgeSeconds`, and only while the agent is idle. Otherwise it returns the last read as it is.\n\t */\n\tasync getState(options: { maxAgeSeconds?: number } = {}): Promise<{\n\t\tpageInfo: ReturnType<typeof getPageInfo>\n\t\tsimplifiedHTML: string\n\t\tageSeconds: number\n\t\tfresh: boolean\n\t\trefreshed: boolean\n\t}> {\n\t\tconst maxAgeSeconds = options.maxAgeSeconds ?? STATE_FRESH_SECONDS\n\t\tconst refreshed = shouldRefresh({\n\t\t\tneverRead: this.lastTimeUpdate === 0,\n\t\t\tageSeconds: stateAgeSeconds(this.lastTimeUpdate, Date.now()),\n\t\t\tmaxAgeSeconds,\n\t\t\tbusy: this.isBusy(),\n\t\t})\n\t\tif (refreshed) await this.updateTree()\n\t\tconst ageSeconds = stateAgeSeconds(this.lastTimeUpdate, Date.now())\n\t\treturn {\n\t\t\tpageInfo: getPageInfo(),\n\t\t\tsimplifiedHTML: this.simplifiedHTML,\n\t\t\tageSeconds,\n\t\t\tfresh: ageSeconds <= maxAgeSeconds,\n\t\t\trefreshed,\n\t\t}\n\t}\n\n\t/**\n\t * The element list from the agent's last read, with its age, and the page position measured now.\n\t * Read-only: it does not refresh the tree, move the highlights or change any element index.\n\t */\n\tasync getLastState(): Promise<{\n\t\tpageInfo: ReturnType<typeof getPageInfo>\n\t\tsimplifiedHTML: string\n\t\tageSeconds: number\n\t\tfresh: boolean\n\t}> {\n\t\tconst ageSeconds = stateAgeSeconds(this.lastTimeUpdate, Date.now())\n\t\treturn {\n\t\t\tpageInfo: getPageInfo(),\n\t\t\tsimplifiedHTML: this.simplifiedHTML,\n\t\t\tageSeconds,\n\t\t\tfresh: isStateFresh(ageSeconds),\n\t\t}\n\t}\n\n\t/**\n\t * Get structured browser state for LLM consumption.\n\t * Automatically calls updateTree() to refresh the DOM state.\n\t */\n\tasync getBrowserState(): Promise<BrowserState> {\n\t\tconst url = window.location.href\n\t\tconst title = document.title\n\t\tconst pi = getPageInfo()\n\t\tconst viewportExpansion = dom.resolveViewportExpansion(this.config.viewportExpansion)\n\n\t\tawait this.updateTree()\n\n\t\tconst content = this.fallbackNote\n\t\t\t? `${this.fallbackNote}\\n\\n${this.simplifiedHTML}`\n\t\t\t: this.simplifiedHTML\n\t\tconst tree = this.indexSource === 'accessibility' ? this.axObservation : null\n\t\t// The tree is narrowed to the viewport when it is asked to be, or when the whole page is too long.\n\t\tconst fullPage = tree ? !tree.viewportOnly : viewportExpansion === -1\n\n\t\t// Build header: page info + scroll position hint\n\t\tconst titleLine = `Current Page: [${title}](${url})`\n\n\t\tconst pageInfoLine = `Page info: ${pi.viewport_width}x${pi.viewport_height}px viewport, ${pi.page_width}x${pi.page_height}px total page size, ${pi.pages_above.toFixed(1)} pages above, ${pi.pages_below.toFixed(1)} pages below, ${pi.total_pages.toFixed(1)} total pages, at ${(pi.current_page_position * 100).toFixed(0)}% of page`\n\n\t\tlet elementsLabel = fullPage\n\t\t\t? 'Interactive elements from top layer of the current page (full page):'\n\t\t\t: 'Interactive elements from top layer of the current page inside the viewport:'\n\t\tif (tree) {\n\t\t\tconst notes = [\n\t\t\t\t`Accessibility tree of the current page ${fullPage ? '(full page)' : 'inside the viewport'}, reconstructed from what the page exposes. It is not the browser's native accessibility tree and can differ from it.`,\n\t\t\t\t'Each line is [index] role \"name\", then value, description and states; indentation is nesting. Only lines with a numeric [index] can be acted on, and an index is valid for this step only.',\n\t\t\t\t'Viewport annotations describe element geometry at capture time. An intersection does not prove the element is visible or unobscured. Unannotated elements remain in the tree; their viewport position is not stated.',\n\t\t\t]\n\t\t\tif (tree.filteredNodes > 0)\n\t\t\t\tnotes.push(\n\t\t\t\t\t`${tree.filteredNodes} nodes outside the viewport are not listed: scroll to list them.`\n\t\t\t\t)\n\t\t\tif (tree.hiddenNodes > 0)\n\t\t\t\tnotes.push(\n\t\t\t\t\t`\"… +N hidden\" marks ${tree.hiddenNodes} nodes that did not fit: scroll so that fewer are in view.`\n\t\t\t\t)\n\t\t\tif (this.surfacePoints.size > 0)\n\t\t\t\tnotes.push(\n\t\t\t\t\t`${this.surfacePoints.size} surface${this.surfacePoints.size === 1 ? '' : 's'} with no tree node (canvas, svg or role=application) are listed after the tree. The line gives the tag and label, not a role. The index is a drag target for this step only.`\n\t\t\t\t)\n\t\t\telementsLabel = notes.join('\\n')\n\t\t}\n\n\t\tconst hasContentAbove = pi.pixels_above > 4\n\t\tconst scrollHintAbove =\n\t\t\thasContentAbove && !fullPage\n\t\t\t\t? `... ${pi.pixels_above} pixels above (${pi.pages_above.toFixed(1)} pages) - scroll to see more ...`\n\t\t\t\t: fullPage\n\t\t\t\t\t? '[Start of full-page tree]'\n\t\t\t\t\t: '[Start of page]'\n\n\t\tconst header = `${titleLine}\\n${pageInfoLine}\\n\\n${elementsLabel}\\n\\n${scrollHintAbove}`\n\n\t\t// Build footer: scroll position hint\n\t\tconst hasContentBelow = pi.pixels_below > 4\n\t\tconst footer =\n\t\t\thasContentBelow && !fullPage\n\t\t\t\t? `... ${pi.pixels_below} pixels below (${pi.pages_below.toFixed(1)} pages) - scroll to see more ...`\n\t\t\t\t: fullPage\n\t\t\t\t\t? `[End of full-page tree; ${pi.pixels_below} pixels below the viewport]`\n\t\t\t\t\t: '[End of page]'\n\n\t\tif (this.config.logObservations !== false) {\n\t\t\tconst summary = tree\n\t\t\t\t? `accessibility tree · ${tree.ids.length} indexed · ${tree.shownNodes}/${tree.totalNodes} nodes · ${tree.durationMs} ms`\n\t\t\t\t: 'element list'\n\t\t\t// An open group: what the agent received is on screen without a click, and can still be folded.\n\t\t\tconsole.group(`%c[page-agent] observed · ${summary}`, LOG_STYLE)\n\t\t\tconsole.log(`${header}\\n${content}\\n${footer}`)\n\t\t\tconsole.groupEnd()\n\t\t}\n\n\t\treturn { url, title, header, content, footer }\n\t}\n\n\t// ======= Accessibility Tree =======\n\n\t/**\n\t * The page as a reconstructed accessibility tree, with interactions addressed by node ID: capture,\n\t * click, fill, select, keyboard, hover, drag, scroll, frames. Every method is async.\n\t *\n\t * The tree approximates the browser's accessibility tree from what page JavaScript can observe, and\n\t * the interactions are synthetic events, not physical input. See `AccessibilityController`.\n\t */\n\tget accessibility(): AccessibilityController {\n\t\tthis.accessibilityController ??= new AccessibilityController({\n\t\t\t...this.config.accessibility,\n\t\t\t// The core hit-tests its targets, so the mask must not be on top while it acts. Interactions\n\t\t\t// can overlap (a paced drag takes time), so the mask returns only when the last one ends.\n\t\t\trunInteraction: async (interaction) => {\n\t\t\t\tif (this.accessibilityInteractions++ === 0) await enablePassThrough()\n\t\t\t\ttry {\n\t\t\t\t\treturn await interaction()\n\t\t\t\t} finally {\n\t\t\t\t\tif (--this.accessibilityInteractions === 0) await disablePassThrough()\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t\treturn this.accessibilityController\n\t}\n\n\t/** Whether the page is read as the accessibility tree. The default. */\n\tprivate usesAccessibility(): boolean {\n\t\treturn (this.config.observation ?? 'accessibility') === 'accessibility'\n\t}\n\n\t/**\n\t * The ID of the accessibility node behind an index of the last read, for use with\n\t * `accessibility` (the same node the index tools act on).\n\t */\n\tasync accessibilityId(index: number): Promise<string> {\n\t\treturn this.axTarget(index).id\n\t}\n\n\tprivate axTarget(index: number): { id: string; label: string } {\n\t\tconst id = this.axObservation?.ids[index]\n\t\tif (this.indexSource !== 'accessibility' || id === undefined)\n\t\t\tthrow new Error(`No element with index ${index} in the current page state`)\n\t\treturn { id, label: `[${index}] ${this.axObservation!.labels[index]}` }\n\t}\n\n\t/**\n\t * Scrolls the target into view and moves the visual pointer to it, so a person watching sees where\n\t * the agent is about to act. Feedback only: the action that follows checks the target itself.\n\t */\n\tprivate async pointAt(id: string): Promise<{ x: number; y: number } | null> {\n\t\tconst element = await this.accessibility.elementAt(id)\n\t\tif (!element || !isHTMLElement(element)) return null\n\t\tawait scrollIntoViewIfNeeded(element)\n\t\tconst rect = element.getBoundingClientRect()\n\t\tconst point = {\n\t\t\tx: Math.round(rect.left + rect.width / 2),\n\t\t\ty: Math.round(rect.top + rect.height / 2),\n\t\t}\n\t\tif (this.mask) {\n\t\t\tawait movePointerToElement(element, point.x, point.y)\n\t\t\tawait clickPointer()\n\t\t}\n\t\treturn point\n\t}\n\n\t/** Runs one index-based action on the accessibility tree and words its result for the agent. */\n\tprivate async axAction(\n\t\tverb: string,\n\t\tindex: number,\n\t\tact: (id: string) => Promise<AxActionOutcome>,\n\t\tdescribe: (outcome: AxActionOutcome, label: string) => string\n\t): Promise<ActionResult> {\n\t\tlet label = `[${index}]`\n\t\tlet point: { x: number; y: number } | null = null\n\t\tlet result: ActionResult\n\t\ttry {\n\t\t\tconst target = this.axTarget(index)\n\t\t\tlabel = target.label\n\t\t\tpoint = await this.pointAt(target.id)\n\t\t\tconst outcome = await act(target.id)\n\t\t\tresult = { success: outcome.status !== 'not_applied', message: describe(outcome, label) }\n\t\t} catch (error) {\n\t\t\tresult = { success: false, message: `❌ Failed to ${verb}: ${describeFailure(error)}` }\n\t\t}\n\t\tif (this.config.logObservations !== false)\n\t\t\tconsole.log(\n\t\t\t\t`%c[page-agent] ${verb}`,\n\t\t\t\tLOG_STYLE,\n\t\t\t\tlabel,\n\t\t\t\tpoint ? `at (${point.x}, ${point.y})` : '',\n\t\t\t\t'→',\n\t\t\t\tresult.message\n\t\t\t)\n\t\treturn result\n\t}\n\n\t// ======= DOM Tree Operations =======\n\n\t/**\n\t * Update DOM tree, returns simplified HTML for LLM.\n\t * This is the main method to refresh the page state.\n\t * Automatically bypasses mask during DOM extraction if enabled.\n\t */\n\tasync updateTree(): Promise<string> {\n\t\tthis.dispatchEvent(new Event('beforeUpdate'))\n\n\t\tthis.lastTimeUpdate = Date.now()\n\t\tthis.fallbackNote = ''\n\n\t\tif (this.usesAccessibility()) {\n\t\t\ttry {\n\t\t\t\tawait this.updateAccessibilityTree()\n\t\t\t\tthis.isIndexed = true\n\t\t\t\tthis.dispatchEvent(new Event('afterUpdate'))\n\t\t\t\treturn this.simplifiedHTML\n\t\t\t} catch (error) {\n\t\t\t\t// The step still gets a readable page: the element list, with the reason stated.\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'[PageController] accessibility tree unavailable, using the element list',\n\t\t\t\t\terror\n\t\t\t\t)\n\t\t\t\tthis.fallbackNote = `Accessibility tree unavailable for this step (${error instanceof Error ? error.message : String(error)}). Showing the list of interactive elements instead; its indexes work the same way.`\n\t\t\t}\n\t\t}\n\t\tthis.indexSource = 'dom'\n\t\tthis.axObservation = null\n\t\tthis.surfacePoints.clear()\n\n\t\t// Temporarily bypass mask to allow DOM extraction\n\t\tif (this.mask) {\n\t\t\tthis.mask.wrapper.style.pointerEvents = 'none'\n\t\t}\n\n\t\tdom.cleanUpHighlights()\n\n\t\tconst blacklist = [\n\t\t\t...(this.config.interactiveBlacklist || []),\n\t\t\t...Array.from(document.querySelectorAll('[data-page-agent-not-interactive]')),\n\t\t]\n\n\t\tthis.flatTree = dom.getFlatTree({\n\t\t\t...this.config,\n\t\t\tinteractiveBlacklist: blacklist,\n\t\t})\n\n\t\tthis.simplifiedHTML = dom.flatTreeToString(\n\t\t\tthis.flatTree,\n\t\t\tthis.config.includeAttributes,\n\t\t\tthis.config.keepSemanticTags\n\t\t)\n\n\t\tthis.selectorMap.clear()\n\t\tthis.selectorMap = dom.getSelectorMap(this.flatTree)\n\n\t\tthis.elementTextMap.clear()\n\t\tthis.elementTextMap = dom.getElementTextMap(this.simplifiedHTML)\n\n\t\t// Mark as indexed - now element actions are allowed\n\t\tthis.isIndexed = true\n\n\t\t// Restore mask blocking\n\t\tif (this.mask) {\n\t\t\tthis.mask.wrapper.style.pointerEvents = 'auto'\n\t\t}\n\n\t\tthis.dispatchEvent(new Event('afterUpdate'))\n\n\t\treturn this.simplifiedHTML\n\t}\n\n\t/**\n\t * Reads the page as the accessibility tree and makes its indexes the current ones. The read is\n\t * synchronous and can take long on a large page, so the mask shows a progress bar meanwhile.\n\t */\n\tprivate async updateAccessibilityTree(): Promise<void> {\n\t\t// The numbered highlights belong to the element list and would not match these indexes.\n\t\tdom.cleanUpHighlights()\n\t\tawait this.mask?.startProgress()\n\t\tconst started = performance.now()\n\t\ttry {\n\t\t\tconst observation = await this.accessibility.observeIndexed({\n\t\t\t\tviewportExpansion: dom.resolveViewportExpansion(this.config.viewportExpansion),\n\t\t\t})\n\t\t\tconst indexed = await this.withSurfaceIndexes(observation)\n\t\t\tthis.axObservation = indexed\n\t\t\tthis.simplifiedHTML = indexed.text\n\t\t\tthis.indexSource = 'accessibility'\n\t\t\tthis.selectorMap.clear()\n\t\t\tthis.elementTextMap = new Map(indexed.labels.map((label, index) => [index, label]))\n\t\t\tthis.lastTreeReadMs = Math.round(performance.now() - started)\n\t\t\tif (this.config.logObservations !== false) {\n\t\t\t\tconsole.log('%c[page-agent] accessibility read', LOG_STYLE, `${this.lastTreeReadMs}ms`)\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.mask?.stopProgress()\n\t\t}\n\t}\n\n\t/**\n\t * Gives a numeric index to canvas, svg and role=application surfaces that are not tree nodes.\n\t * A failure here keeps the tree that was already read.\n\t */\n\tprivate async withSurfaceIndexes(\n\t\tobservation: AxIndexedObservation\n\t): Promise<AxIndexedObservation> {\n\t\tthis.surfacePoints = new Map()\n\t\ttry {\n\t\t\tconst surfaces = await this.accessibility.surfaces()\n\t\t\tconst indexed = await appendSurfaceIndexes(\n\t\t\t\tobservation,\n\t\t\t\tsurfaces,\n\t\t\t\tasync (x, y) => {\n\t\t\t\t\tconst hit = await this.accessibility.targetAt(x, y)\n\t\t\t\t\treturn { id: hit.id, tag: hit.tag }\n\t\t\t\t},\n\t\t\t\t{ width: window.innerWidth, height: window.innerHeight }\n\t\t\t)\n\t\t\tthis.surfacePoints = indexed.points\n\t\t\treturn indexed.observation\n\t\t} catch (error) {\n\t\t\tconsole.warn('[PageController] surface indexes unavailable for this read', error)\n\t\t\treturn observation\n\t\t}\n\t}\n\n\t/**\n\t * Clean up all element highlights\n\t */\n\tasync cleanUpHighlights(): Promise<void> {\n\t\tconsole.log('[PageController] cleanUpHighlights')\n\t\tdom.cleanUpHighlights()\n\t}\n\n\t// ======= Element Actions =======\n\n\t/**\n\t * Ensure the tree has been indexed before any index-based operation.\n\t * Throws if updateTree() hasn't been called yet.\n\t */\n\tprivate assertIndexed(): void {\n\t\tif (!this.isIndexed) {\n\t\t\tthrow new Error('DOM tree not indexed yet. Can not perform actions on elements.')\n\t\t}\n\t}\n\n\t/**\n\t * Click element by index\n\t */\n\tasync clickElement(index: number): Promise<ActionResult> {\n\t\tif (this.indexSource === 'accessibility')\n\t\t\treturn this.axAction(\n\t\t\t\t'click element',\n\t\t\t\tindex,\n\t\t\t\t(id) => this.accessibility.click(id),\n\t\t\t\t(_outcome, label) =>\n\t\t\t\t\t`📤 Clicked element (${label}) with a synthetic click. What it did is not verified: check the next page state.`\n\t\t\t)\n\t\ttry {\n\t\t\tthis.assertIndexed()\n\t\t\tconst element = getElementByIndex(this.selectorMap, index)\n\t\t\tconst elemText = this.elementTextMap.get(index)\n\t\t\tawait clickElement(element)\n\n\t\t\t// Handle links that open in new tabs\n\t\t\tif (isAnchorElement(element) && element.target === '_blank') {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tmessage: `✅ Clicked element (${elemText ?? index}). ⚠️ Link opened in a new tab.`,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tmessage: `✅ Clicked element (${elemText ?? index}).`,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Failed to click element: ${error}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Input text into element by index\n\t */\n\tasync inputText(index: number, text: string): Promise<ActionResult> {\n\t\tif (this.indexSource === 'accessibility')\n\t\t\treturn this.axAction(\n\t\t\t\t'input text',\n\t\t\t\tindex,\n\t\t\t\t(id) => this.accessibility.fill(id, text),\n\t\t\t\t(outcome, label) =>\n\t\t\t\t\toutcome.status === 'applied'\n\t\t\t\t\t\t? `✅ Input text (${text}) into element (${label}). The field held it right after; that does not show the page accepted it.`\n\t\t\t\t\t\t: `⚠️ Input text (${text}) was sent to element (${label}). ${outcome.summary}`\n\t\t\t)\n\t\ttry {\n\t\t\tthis.assertIndexed()\n\t\t\tconst element = getElementByIndex(this.selectorMap, index)\n\t\t\tconst elemText = this.elementTextMap.get(index)\n\t\t\tawait inputTextElement(element, text)\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tmessage: `✅ Input text (${text}) into element (${elemText ?? index}).`,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Failed to input text: ${error}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Select dropdown option by index and option text\n\t */\n\tasync selectOption(index: number, optionText: string): Promise<ActionResult> {\n\t\tif (this.indexSource === 'accessibility')\n\t\t\treturn this.axAction(\n\t\t\t\t'select option',\n\t\t\t\tindex,\n\t\t\t\tasync (id) => {\n\t\t\t\t\t// The tool names an option by its text; the tree selects by option value.\n\t\t\t\t\tconst element = await this.accessibility.elementAt(id)\n\t\t\t\t\tif (!element || !isSelectElement(element))\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'the element is not a native select. Click it to open it, then click the option'\n\t\t\t\t\t\t)\n\t\t\t\t\tconst option = Array.from(element.options).find(\n\t\t\t\t\t\t(candidate) => candidate.textContent?.trim() === optionText.trim()\n\t\t\t\t\t)\n\t\t\t\t\tif (!option)\n\t\t\t\t\t\tthrow new Error(`Option with text \"${optionText}\" not found in select element`)\n\t\t\t\t\treturn this.accessibility.select(id, option.value)\n\t\t\t\t},\n\t\t\t\t(outcome, label) =>\n\t\t\t\t\toutcome.status === 'not_applied'\n\t\t\t\t\t\t? `⚠️ Option (${optionText}) was sent to element (${label}). ${outcome.summary}`\n\t\t\t\t\t\t: `✅ Selected option (${optionText}) in element (${label}).`\n\t\t\t)\n\t\ttry {\n\t\t\tthis.assertIndexed()\n\t\t\tconst element = getElementByIndex(this.selectorMap, index)\n\t\t\tconst elemText = this.elementTextMap.get(index)\n\t\t\tawait selectOptionElement(element as HTMLSelectElement, optionText)\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tmessage: `✅ Selected option (${optionText}) in element (${elemText ?? index}).`,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Failed to select option: ${error}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Scroll vertically\n\t */\n\tasync scroll(options: {\n\t\tdown: boolean\n\t\tnumPages: number\n\t\tpixels?: number\n\t\tindex?: number\n\t}): Promise<ActionResult> {\n\t\ttry {\n\t\t\tconst { down, numPages, pixels, index } = options\n\n\t\t\tthis.assertIndexed()\n\n\t\t\tconst scrollAmount = (pixels ?? numPages * window.innerHeight) * (down ? 1 : -1)\n\n\t\t\tif (this.indexSource === 'accessibility')\n\t\t\t\treturn await this.axScroll({ y: scrollAmount }, index)\n\n\t\t\tconst element = index !== undefined ? getElementByIndex(this.selectorMap, index) : null\n\n\t\t\tconst message = await scrollVertically(scrollAmount, element)\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tmessage,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Failed to scroll: ${error}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Scroll horizontally\n\t */\n\tasync scrollHorizontally(options: {\n\t\tright: boolean\n\t\tpixels: number\n\t\tindex?: number\n\t}): Promise<ActionResult> {\n\t\ttry {\n\t\t\tconst { right, pixels, index } = options\n\n\t\t\tthis.assertIndexed()\n\n\t\t\tconst scrollAmount = pixels * (right ? 1 : -1)\n\n\t\t\tif (this.indexSource === 'accessibility')\n\t\t\t\treturn await this.axScroll({ x: scrollAmount }, index)\n\n\t\t\tconst element = index !== undefined ? getElementByIndex(this.selectorMap, index) : null\n\n\t\t\tconst message = await scrollHorizontally(scrollAmount, element)\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tmessage,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Failed to scroll horizontally: ${error}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Scrolls the page, or the container behind an index, and reports the measured movement. */\n\tprivate async axScroll(\n\t\toffsets: { x?: number; y?: number },\n\t\tindex?: number\n\t): Promise<ActionResult> {\n\t\tconst target = index === undefined ? null : this.axTarget(index)\n\t\tconst outcome = target\n\t\t\t? await this.accessibility.scroll(target.id, offsets)\n\t\t\t: await this.accessibility.scroll(offsets)\n\t\tconst { before, after, moved } = outcome.result\n\t\tconst where = target ? `container (${target.label})` : 'page'\n\t\tconst dx = after.x - before.x\n\t\tconst dy = after.y - before.y\n\t\tconst message = moved\n\t\t\t? `✅ Scrolled ${where} by ${offsets.y === undefined ? dx : dy}px (now at x=${after.x}, y=${after.y}).`\n\t\t\t: `⚠️ Scroll of ${where} requested, but the position did not change: the edge was reached or it does not scroll.`\n\t\tif (this.config.logObservations !== false)\n\t\t\tconsole.log('%c[page-agent] scroll', LOG_STYLE, where, offsets, '→', message)\n\t\treturn { success: moved, message }\n\t}\n\n\t/**\n\t * Drag one index of the current read onto another.\n\t * Accessibility indexes only. The events are synthetic (`isTrusted` is false).\n\t * `html5` drops only when the destination cancels `dragover`.\n\t */\n\tasync dragElement(\n\t\tsourceIndex: number,\n\t\ttargetIndex: number,\n\t\tmode: AxDragMode = 'html5'\n\t): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage:\n\t\t\t\t\t'❌ Drag needs the accessibility tree. This step is the element list, so these indexes cannot be dragged.',\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst source = this.axTarget(sourceIndex)\n\t\t\tconst target = this.axTarget(targetIndex)\n\t\t\tconst outcome = await this.accessibility.drag(source.id, target.id, mode)\n\t\t\tconst followUp =\n\t\t\t\tmode === 'html5' && outcome.status === 'not_applied'\n\t\t\t\t\t? ' On the next step, call drag_element once with mode \"pointer-paced\". Neither result proves the effect.'\n\t\t\t\t\t: ''\n\t\t\treturn {\n\t\t\t\tsuccess: outcome.status !== 'not_applied',\n\t\t\t\tmessage:\n\t\t\t\t\t`📤 Dragged ${source.label} onto ${target.label} (${mode}). ${outcome.summary} ` +\n\t\t\t\t\t'Event sent. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.' +\n\t\t\t\t\tfollowUp,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Failed to drag: ${describeFailure(error)}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Synthetic hover. CSS `:hover` stays off. One index of this read. */\n\tasync hoverElement(index: number): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Hover')\n\t\treturn this.axAction(\n\t\t\t'hover element',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.hover(id),\n\t\t\t(outcome, label) =>\n\t\t\t\t`📤 Hover events sent to ${label}. ${outcome.summary} Event sent. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/**\n\t * Synthetic keydown and keyup. The key's native default does not run: no character is typed,\n\t * Tab does not move focus and Enter does not activate the control.\n\t */\n\tasync pressKey(index: number, key: string, options: AxKeyOptions = {}): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Key')\n\t\treturn this.axAction(\n\t\t\t'press key',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.pressKey(id, key, options),\n\t\t\t(outcome, label) =>\n\t\t\t\t`📤 Key ${JSON.stringify(key)} sent to ${label}. ${outcome.summary} Event sent. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/** Synthetic double click. It does not select text the way a physical double click does. */\n\tasync doubleClickElement(index: number): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Double-click')\n\t\treturn this.axAction(\n\t\t\t'double-click element',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.doubleClick(id),\n\t\t\t(outcome, label) =>\n\t\t\t\t`📤 Double-click events sent to ${label}. ${outcome.summary} Event sent. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/**\n\t * Calls `focus()` on an index. The result says whether that element was focused right after.\n\t * Focus is not a saved change.\n\t */\n\tasync focusElement(index: number): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Focus')\n\t\treturn this.axAction(\n\t\t\t'focus element',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.focus(id),\n\t\t\t(outcome, label) =>\n\t\t\t\toutcome.status === 'applied'\n\t\t\t\t\t? `✅ Focus observed on ${label}. ${outcome.summary} Observed right after focus(). Not persisted. These indexes die on the next read.`\n\t\t\t\t\t: `⚠️ Focus was requested on ${label}. ${outcome.summary} Effect not observed. Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/** Checks or unchecks a native checkbox, or selects a native radio. One index of this read. */\n\tasync setChecked(index: number, checked: boolean): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Set-checked')\n\t\treturn this.axAction(\n\t\t\t'set checked',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.setChecked(id, checked),\n\t\t\t(outcome, label) =>\n\t\t\t\t`📤 Set checked=${checked} on ${label}. ${outcome.summary} Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/** Sets a native range input. A value the browser would clamp or round is refused by the core. */\n\tasync setRange(index: number, value: number): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Set-range')\n\t\treturn this.axAction(\n\t\t\t'set range',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.setRange(id, value),\n\t\t\t(outcome, label) =>\n\t\t\t\t`📤 Set range=${value} on ${label}. ${outcome.summary} Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/**\n\t * Calls `scrollIntoView`. The message reports window scroll before and after.\n\t * A scroller inside the page is not measured. The status stays `requested`.\n\t */\n\tasync scrollIntoView(index: number): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Scroll-into-view')\n\t\tconst before = readWindowScroll()\n\t\tconst result = await this.axAction(\n\t\t\t'scroll into view',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.scrollIntoView(id),\n\t\t\t(_outcome, label) =>\n\t\t\t\t`📤 scrollIntoView called on ${label}. Not persisted. These indexes die on the next read.`\n\t\t)\n\t\tconst after = readWindowScroll()\n\t\tresult.message += ` Window scroll went from (${before.x}, ${before.y}) to (${after.x}, ${after.y}). Nested scrollers were not measured.`\n\t\treturn result\n\t}\n\n\t/**\n\t * One synthetic wheel event. It does not scroll. Without an index the event goes to the page.\n\t */\n\tasync wheel(input: { x?: number; y?: number; index?: number }): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Wheel')\n\t\tconst offsets = { x: input.x, y: input.y }\n\t\tif (input.index === undefined) {\n\t\t\ttry {\n\t\t\t\tconst outcome = await this.accessibility.wheel(offsets)\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t`📤 Wheel event sent to the page. ${outcome.summary} ` +\n\t\t\t\t\t\t'Event sent. This tool did not scroll. Effect not verified: check the next page state. Not persisted.',\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\treturn { success: false, message: `❌ Failed to wheel: ${describeFailure(error)}` }\n\t\t\t}\n\t\t}\n\t\treturn this.axAction(\n\t\t\t'wheel',\n\t\t\tinput.index,\n\t\t\t(id) => this.accessibility.wheel(id, offsets),\n\t\t\t(outcome, label) =>\n\t\t\t\t`📤 Wheel event sent to ${label}. ${outcome.summary} Event sent. This tool did not scroll. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/**\n\t * Execute arbitrary JavaScript on the page.\n\t * The optional `signal` is exposed to the script scope so cooperative code\n\t * can abort promptly when the task is stopped.\n\t *\n\t * When the page CSP disallows `unsafe-eval`, this does not call `eval`. The same origin\n\t * keeps that answer, and the message tells the agent not to try again.\n\t */\n\tasync executeJavascript(\n\t\tscript: string,\n\t\tsignal?: AbortSignal,\n\t\tscope: Record<string, unknown> = {}\n\t): Promise<ActionResult> {\n\t\tconst origin = scriptOrigin()\n\t\tif (generatedScriptAccess(origin) === 'blocked_by_csp') {\n\t\t\treturn { success: false, message: SCRIPT_BLOCKED_BY_CSP }\n\t\t}\n\t\ttry {\n\t\t\t// Wrap the script in an async function so it can await. `signal` and the scope names are parameters.\n\t\t\tconst names = Object.keys(scope)\n\t\t\tconst asyncFunction = eval(`(async (${[...names, 'signal'].join(', ')}) => { ${script} })`)\n\t\t\tconst result = await asyncFunction(...names.map((name) => scope[name]), signal)\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tmessage: `✅ Executed JavaScript. Result: ${formatScriptResult(result)}`,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (isEvalBlocked(error)) {\n\t\t\t\trememberScriptAccess(origin, 'blocked_by_csp')\n\t\t\t\treturn { success: false, message: SCRIPT_BLOCKED_BY_CSP }\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Error executing JavaScript: ${error}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t// ======= Mask Operations =======\n\n\t/**\n\t * Show the visual mask overlay.\n\t * Only works after mask is setup.\n\t */\n\tasync showMask(): Promise<void> {\n\t\tawait this.maskReady\n\t\tthis.mask?.show()\n\t}\n\n\t/**\n\t * Hide the visual mask overlay.\n\t * Only works after mask is setup.\n\t */\n\tasync hideMask(): Promise<void> {\n\t\tawait this.maskReady\n\t\tthis.mask?.hide()\n\t}\n\n\t/**\n\t * Dispose and clean up resources\n\t */\n\tdispose(): void {\n\t\tdom.cleanUpHighlights()\n\t\tthis.flatTree = null\n\t\tthis.selectorMap.clear()\n\t\tthis.elementTextMap.clear()\n\t\tthis.simplifiedHTML = '<EMPTY>'\n\t\tthis.isIndexed = false\n\t\tthis.indexSource = 'dom'\n\t\tthis.axObservation = null\n\t\tthis.surfacePoints.clear()\n\t\tthis.fallbackNote = ''\n\t\tthis.accessibilityController?.destroy()\n\t\tthis.accessibilityController = null\n\t\tthis.mask?.dispose()\n\t\tthis.mask = null\n\t}\n}\n\nexport * from './actions'\nexport * from './ax'\nexport {\n\tscriptAccessClosed,\n\tSCRIPT_BLOCKED_BY_CSP,\n\tSCRIPT_UNAVAILABLE,\n\tSCRIPT_USER_DENIED,\n} from './scriptAccess'\n","// English translations (base/reference language)\nconst enUS = {\n\tui: {\n\t\tpanel: {\n\t\t\tready: 'Ready',\n\t\t\tthinking: 'Thinking...',\n\t\t\ttaskInput: 'Enter new task, describe steps in detail, press Enter to submit',\n\t\t\tuserAnswerPrompt: 'Please answer the question above, press Enter to submit',\n\t\t\ttaskTerminated: 'Task terminated',\n\t\t\ttaskCompleted: 'Task completed',\n\t\t\tuserAnswer: 'User answer: {{input}}',\n\t\t\tquestion: 'Question: {{question}}',\n\t\t\twaitingPlaceholder: 'Waiting for task to start...',\n\t\t\tstop: 'Stop task',\n\t\t\tclose: 'Minimize',\n\t\t\tsend: 'Send',\n\t\t\topen: 'Open assistant',\n\t\t\tnewCount: '{{count}} new',\n\t\t\tnewTask: 'New task',\n\t\t\texportLog: 'Export log',\n\t\t\tcodeTitle: 'JavaScript',\n\t\t\tcodeScript: 'Script',\n\t\t\tcodeResult: 'Result',\n\t\t\tcodeError: 'Error',\n\t\t\tcodeRunning: 'running',\n\t\t\tcodeDone: 'done',\n\t\t\tcodeFailed: 'failed',\n\t\t\tcodeVoice: 'Voice',\n\t\t\tcodeRefused: 'refused',\n\t\t\tcodeShowMore: 'show more',\n\t\t\tcodeShowLess: 'show less',\n\t\t\tlogTask: 'Task',\n\t\t\tlogAction: 'Action',\n\t\t\tlogResult: 'Result',\n\t\t\tresultTitle: 'Result',\n\t\t\tmsgAborted: 'Task stopped',\n\t\t\tmsgStepLimit: 'Step limit reached',\n\t\t\tmsgRetry: 'Model retry {{attempt}} of {{max}}',\n\t\t\tmsgNavigated: 'Page changed to → {{url}}',\n\t\t\tmsgWaited: 'Waited {{seconds}} seconds in total. Do not wait longer without a reason.',\n\t\t\tmsgStepsLeft: '{{count}} steps left. Consider wrapping up.',\n\t\t\tmsgStepsCritical: 'Critical: only {{count}} steps left.',\n\t\t\tmsgCompleted: 'Task completed',\n\t\t\tpin: 'Pin task',\n\t\t\tunpin: 'Unpin task',\n\t\t\tjumpLatest: 'Latest',\n\t\t\texpand: 'Show conversation',\n\t\t\tcollapse: 'Hide conversation',\n\t\t\texpandFromFab: 'Open assistant',\n\t\t\tfollowModeBar: 'Status bar',\n\t\t\tfollowModeMinimize: 'Minimize',\n\t\t\tstep: 'Step {{number}}',\n\t\t\thideCursor: 'Hide agent cursor',\n\t\t\tshowCursor: 'Show agent cursor',\n\t\t\tstatusRunning: 'Working...',\n\t\t\tstatusRetrying: 'Retrying ({{attempt}}/{{max}})',\n\t\t\tstatusDone: 'Done',\n\t\t\tstatusNotDone: 'Not completed',\n\t\t\tstatusStopped: 'Stopped',\n\t\t\tstatusError: 'Error',\n\t\t\tstatusWaiting: 'Waiting for you',\n\t\t\tcomposerPlaceholder: 'Describe a task…',\n\t\t\tcomposerRunning: 'Task in progress…',\n\t\t\tcomposerAnswer: 'Answer the agent…',\n\t\t\tattachFile: 'Attach file',\n\t\t\tattachRemove: 'Remove {{name}}',\n\t\t\tattachFailed: 'Could not attach file',\n\t\t\tskillsStudio: 'Skills Studio',\n\t\t\tskillsStudioBack: 'Back to chat',\n\t\t\tskillsStudioRecord: 'Record',\n\t\t\tskillsStudioAsk: 'Ask',\n\t\t\tskillsStudioCatalog: 'Catalog',\n\t\t\tskillsStudioRecordHint:\n\t\t\t\t'Click the page to capture steps. Finish later to turn them into a skill.',\n\t\t\tskillsStudioAskHint:\n\t\t\t\t'Describe the skill you want. The agent will walk the flow and draft it.',\n\t\t\tskillsStudioAskPlaceholder: 'e.g. Switch workspace by name…',\n\t\t\tskillsStudioEmptyCatalog: 'No skills in this browser yet.',\n\t\t\tskillsStudioUnavailable: 'Skills Studio needs a skills-enabled agent.',\n\t\t\tskillsStudioStart: 'Start recording',\n\t\t\tskillsStudioStop: 'Stop',\n\t\t\tskillsStudioFinish: 'Finish & synthesize',\n\t\t\tskillsStudioClear: 'Clear',\n\t\t\tskillsStudioSave: 'Save',\n\t\t\tskillsStudioTest: 'Test',\n\t\t\tskillsStudioParam: 'Parameterize',\n\t\t\tskillsStudioUnparam: 'Keep literal',\n\t\t\tskillsStudioRemoveStep: 'Remove step',\n\t\t\tskillsStudioEmptySteps: 'No steps recorded yet.',\n\t\t\tskillsStudioPreview: 'Skill preview',\n\t\t\tskillsStudioAskStart: 'Start',\n\t\t\tskillsStudioRefreshRemote: 'Refresh remote',\n\t\t\tskillsStudioRemoveSkill: 'Remove',\n\t\t\tskillsStudioRemoveAgentSkills: 'Remove agent skills',\n\t\t\tskillsStudioRecording: 'Recording…',\n\t\t\tskillsStudioIdle: 'Not recording',\n\t\t\tskillsStudioSaved: 'Saved {{id}} v{{version}}',\n\t\t\tskillsStudioRemoteWarn: 'Saved locally; remote sync failed: {{error}}',\n\t\t\tskillsStudioSynthesized: 'Synthesized {{id}}',\n\t\t\tskillsStudioTested: 'Test: {{result}}',\n\t\t\tskillsStudioAskQueued: 'Authoring skill for your goal…',\n\t\t\tskillsStudioError: '{{message}}',\n\t\t\tskillsStudioScopeAgent: 'agent',\n\t\t\tskillsStudioScopeRemote: 'remote',\n\t\t\tskillsStudioLoaded: 'loaded',\n\t\t\tskillsStudioCatalogCount: '{{count}} skills',\n\t\t\tskillsStudioArmWatch: 'Arm watch',\n\t\t\tskillsStudioDisarmWatch: 'Disarm',\n\t\t\tskillsStudioWatchers: 'Watchers',\n\t\t\tskillsStudioWatchArmed: 'Armed {{id}}',\n\t\t\tskillsStudioWatchFired: 'Watch fired: {{message}}',\n\t\t\tskillsStudioWatchEmpty: 'No active watches',\n\t\t\tskillsStudioWatchNeedlePrompt: 'Text to watch for (default: reply)',\n\t\t\tswitchToVoice: 'Use voice',\n\t\t\tswitchToText: 'Use text',\n\t\t\tvoiceUnavailable: 'Unavailable',\n\t\t\tvoiceConnecting: 'Connecting…',\n\t\t\tvoiceListening: 'Listening',\n\t\t\tvoiceSpeaking: 'Speaking',\n\t\t\tvoiceBusy: 'Still on the previous task.',\n\t\t\tvoiceNoKey: 'Voice needs an API key',\n\t\t\tvoiceConnectFailed: 'Could not connect voice',\n\t\t\tvoiceOn: 'Mic on',\n\t\t\tvoiceOff: 'Mic off',\n\t\t\tvoiceMuted: 'Muted',\n\t\t\tvoiceDenied: 'Mic blocked',\n\t\t\tvoiceMicBusy: 'Mic in use by another app',\n\t\t\tvoiceMicSilent: 'This mic is silent — try another',\n\t\t\tswitchMic: 'Switch microphone',\n\t\t\tmute: 'Mute mic',\n\t\t\tunmute: 'Unmute mic',\n\t\t\tresultDone: 'Task completed',\n\t\t\tresultNotDone: 'Task not completed',\n\t\t\tresultStopped: 'Task stopped',\n\t\t\tresultError: 'Task failed',\n\t\t\tquestionTitle: 'Question',\n\t\t\tanswerTitle: 'Your answer',\n\t\t\tmemory: 'Memory',\n\t\t\tnextGoal: 'Next goal',\n\t\t\tevaluation: 'Last step',\n\t\t\tuserTakeover: 'You took control',\n\t\t\temptyHint: 'Describe a task to get started.',\n\t\t},\n\t\ttools: {\n\t\t\tclicking: 'Clicking element [{{index}}]...',\n\t\t\tinputting: 'Inputting text to element [{{index}}]...',\n\t\t\tselecting: 'Selecting option \"{{text}}\"...',\n\t\t\tscrolling: 'Scrolling page...',\n\t\t\twaiting: 'Waiting {{seconds}} seconds...',\n\t\t\taskingUser: 'Asking user...',\n\t\t\tdone: 'Task done',\n\t\t\tclicked: '🖱️ Clicked element [{{index}}]',\n\t\t\tinputted: '⌨️ Inputted text \"{{text}}\"',\n\t\t\tselected: '☑️ Selected option \"{{text}}\"',\n\t\t\tscrolled: '🛞 Page scrolled',\n\t\t\twaited: '⌛️ Wait completed',\n\t\t\texecuting: 'Executing {{toolName}}...',\n\t\t\tresultSuccess: 'success',\n\t\t\tresultFailure: 'failed',\n\t\t\tresultError: 'error',\n\t\t},\n\t\terrors: {\n\t\t\telementNotFound: 'No interactive element found at index {{index}}',\n\t\t\ttaskRequired: 'Task description is required',\n\t\t\texecutionFailed: 'Task execution failed',\n\t\t\tnotInputElement: 'Element is not an input or textarea',\n\t\t\tnotSelectElement: 'Element is not a select element',\n\t\t\toptionNotFound: 'Option \"{{text}}\" not found',\n\t\t},\n\t},\n} as const\n\n// Portuguese (Brazil) translations (must match the structure of enUS)\nconst ptBR = {\n\tui: {\n\t\tpanel: {\n\t\t\tready: 'Pronto',\n\t\t\tthinking: 'Pensando...',\n\t\t\ttaskInput: 'Digite uma nova tarefa, descreva os passos com detalhes e pressione Enter',\n\t\t\tuserAnswerPrompt: 'Responda à pergunta acima e pressione Enter',\n\t\t\ttaskTerminated: 'Tarefa encerrada',\n\t\t\ttaskCompleted: 'Tarefa concluída',\n\t\t\tuserAnswer: 'Resposta do usuário: {{input}}',\n\t\t\tquestion: 'Pergunta: {{question}}',\n\t\t\twaitingPlaceholder: 'Aguardando o início da tarefa...',\n\t\t\tstop: 'Parar tarefa',\n\t\t\tclose: 'Minimizar',\n\t\t\tsend: 'Enviar',\n\t\t\topen: 'Abrir assistente',\n\t\t\tnewCount: '{{count}} novas',\n\t\t\tnewTask: 'Nova tarefa',\n\t\t\texportLog: 'Exportar log',\n\t\t\tcodeTitle: 'JavaScript',\n\t\t\tcodeScript: 'Código',\n\t\t\tcodeResult: 'Resultado',\n\t\t\tcodeError: 'Erro',\n\t\t\tcodeRunning: 'executando',\n\t\t\tcodeDone: 'executado',\n\t\t\tcodeFailed: 'falhou',\n\t\t\tcodeVoice: 'Voz',\n\t\t\tcodeRefused: 'recusado',\n\t\t\tcodeShowMore: 'mostrar mais',\n\t\t\tcodeShowLess: 'recolher',\n\t\t\tlogTask: 'Tarefa',\n\t\t\tlogAction: 'Ação',\n\t\t\tlogResult: 'Resultado',\n\t\t\tresultTitle: 'Resultado',\n\t\t\tmsgAborted: 'Tarefa interrompida',\n\t\t\tmsgStepLimit: 'Limite de passos atingido',\n\t\t\tmsgRetry: 'Nova tentativa do modelo {{attempt}} de {{max}}',\n\t\t\tmsgNavigated: 'Página mudou para → {{url}}',\n\t\t\tmsgWaited: 'Esperou {{seconds}} segundos no total. Não espere mais sem motivo.',\n\t\t\tmsgStepsLeft: '{{count}} passos restantes. Considere concluir.',\n\t\t\tmsgStepsCritical: 'Crítico: restam só {{count}} passos.',\n\t\t\tmsgCompleted: 'Tarefa concluída',\n\t\t\tpin: 'Fixar tarefa',\n\t\t\tunpin: 'Desafixar tarefa',\n\t\t\tjumpLatest: 'Mais recentes',\n\t\t\texpand: 'Mostrar conversa',\n\t\t\tcollapse: 'Ocultar conversa',\n\t\t\texpandFromFab: 'Abrir assistente',\n\t\t\tfollowModeBar: 'Barra de status',\n\t\t\tfollowModeMinimize: 'Minimizar',\n\t\t\tstep: 'Passo {{number}}',\n\t\t\thideCursor: 'Ocultar cursor do agente',\n\t\t\tshowCursor: 'Mostrar cursor do agente',\n\t\t\tstatusRunning: 'Trabalhando...',\n\t\t\tstatusRetrying: 'Tentando de novo ({{attempt}}/{{max}})',\n\t\t\tstatusDone: 'Concluído',\n\t\t\tstatusNotDone: 'Não concluído',\n\t\t\tstatusStopped: 'Parado',\n\t\t\tstatusError: 'Erro',\n\t\t\tstatusWaiting: 'Aguardando você',\n\t\t\tcomposerPlaceholder: 'Descreva uma tarefa…',\n\t\t\tcomposerRunning: 'Tarefa em andamento…',\n\t\t\tcomposerAnswer: 'Responda ao agente…',\n\t\t\tattachFile: 'Anexar arquivo',\n\t\t\tattachRemove: 'Remover {{name}}',\n\t\t\tattachFailed: 'Não foi possível anexar o arquivo',\n\t\t\tskillsStudio: 'Skills Studio',\n\t\t\tskillsStudioBack: 'Voltar ao chat',\n\t\t\tskillsStudioRecord: 'Gravar',\n\t\t\tskillsStudioAsk: 'Pedir',\n\t\t\tskillsStudioCatalog: 'Catálogo',\n\t\t\tskillsStudioRecordHint:\n\t\t\t\t'Clique na página para capturar passos. Depois finalize para virar uma skill.',\n\t\t\tskillsStudioAskHint: 'Descreva a skill. O agente percorre o fluxo e monta o rascunho.',\n\t\t\tskillsStudioAskPlaceholder: 'ex.: Trocar workspace pelo nome…',\n\t\t\tskillsStudioEmptyCatalog: 'Nenhuma skill neste browser ainda.',\n\t\t\tskillsStudioUnavailable: 'O Skills Studio precisa de um agente com skills habilitadas.',\n\t\t\tskillsStudioStart: 'Começar gravação',\n\t\t\tskillsStudioStop: 'Parar',\n\t\t\tskillsStudioFinish: 'Finalizar e sintetizar',\n\t\t\tskillsStudioClear: 'Limpar',\n\t\t\tskillsStudioSave: 'Salvar',\n\t\t\tskillsStudioTest: 'Testar',\n\t\t\tskillsStudioParam: 'Parametrizar',\n\t\t\tskillsStudioUnparam: 'Manter literal',\n\t\t\tskillsStudioRemoveStep: 'Remover passo',\n\t\t\tskillsStudioEmptySteps: 'Nenhum passo gravado ainda.',\n\t\t\tskillsStudioPreview: 'Prévia da skill',\n\t\t\tskillsStudioAskStart: 'Começar',\n\t\t\tskillsStudioRefreshRemote: 'Atualizar remoto',\n\t\t\tskillsStudioRemoveSkill: 'Remover',\n\t\t\tskillsStudioRemoveAgentSkills: 'Remover skills do agente',\n\t\t\tskillsStudioRecording: 'Gravando…',\n\t\t\tskillsStudioIdle: 'Sem gravação',\n\t\t\tskillsStudioSaved: 'Salva {{id}} v{{version}}',\n\t\t\tskillsStudioRemoteWarn: 'Salva localmente; sync remoto falhou: {{error}}',\n\t\t\tskillsStudioSynthesized: 'Sintetizada {{id}}',\n\t\t\tskillsStudioTested: 'Teste: {{result}}',\n\t\t\tskillsStudioAskQueued: 'Criando skill para o seu objetivo…',\n\t\t\tskillsStudioError: '{{message}}',\n\t\t\tskillsStudioScopeAgent: 'agente',\n\t\t\tskillsStudioScopeRemote: 'remoto',\n\t\t\tskillsStudioLoaded: 'carregada',\n\t\t\tskillsStudioCatalogCount: '{{count}} skills',\n\t\t\tskillsStudioArmWatch: 'Armar watch',\n\t\t\tskillsStudioDisarmWatch: 'Desarmar',\n\t\t\tskillsStudioWatchers: 'Watches',\n\t\t\tskillsStudioWatchArmed: 'Armado {{id}}',\n\t\t\tskillsStudioWatchFired: 'Watch disparou: {{message}}',\n\t\t\tskillsStudioWatchEmpty: 'Nenhum watch ativo',\n\t\t\tskillsStudioWatchNeedlePrompt: 'Texto a observar (padrão: reply)',\n\t\t\tswitchToVoice: 'Usar voz',\n\t\t\tswitchToText: 'Usar texto',\n\t\t\tvoiceUnavailable: 'Indisponível',\n\t\t\tvoiceConnecting: 'Conectando…',\n\t\t\tvoiceListening: 'Ouvindo',\n\t\t\tvoiceSpeaking: 'Falando',\n\t\t\tvoiceBusy: 'Ainda estou na tarefa anterior.',\n\t\t\tvoiceNoKey: 'A voz precisa de uma chave de API',\n\t\t\tvoiceConnectFailed: 'Não consegui conectar a voz',\n\t\t\tvoiceOn: 'Mic ativo',\n\t\t\tvoiceOff: 'Mic desligado',\n\t\t\tvoiceMuted: 'Mudo',\n\t\t\tvoiceDenied: 'Mic bloqueado',\n\t\t\tvoiceMicBusy: 'Mic em uso por outro app',\n\t\t\tvoiceMicSilent: 'Este mic está mudo — tente outro',\n\t\t\tswitchMic: 'Trocar microfone',\n\t\t\tmute: 'Silenciar',\n\t\t\tunmute: 'Ativar microfone',\n\t\t\tresultDone: 'Tarefa concluída',\n\t\t\tresultNotDone: 'Tarefa não concluída',\n\t\t\tresultStopped: 'Tarefa parada',\n\t\t\tresultError: 'Tarefa falhou',\n\t\t\tquestionTitle: 'Pergunta',\n\t\t\tanswerTitle: 'Sua resposta',\n\t\t\tmemory: 'Memória',\n\t\t\tnextGoal: 'Próximo objetivo',\n\t\t\tevaluation: 'Último passo',\n\t\t\tuserTakeover: 'Você assumiu o controle',\n\t\t\temptyHint: 'Descreva uma tarefa para começar.',\n\t\t},\n\t\ttools: {\n\t\t\tclicking: 'Clicando no elemento [{{index}}]...',\n\t\t\tinputting: 'Digitando texto no elemento [{{index}}]...',\n\t\t\tselecting: 'Selecionando a opção \"{{text}}\"...',\n\t\t\tscrolling: 'Rolando a página...',\n\t\t\twaiting: 'Aguardando {{seconds}} segundos...',\n\t\t\taskingUser: 'Perguntando ao usuário...',\n\t\t\tdone: 'Tarefa concluída',\n\t\t\tclicked: '🖱️ Clicou no elemento [{{index}}]',\n\t\t\tinputted: '⌨️ Digitou o texto \"{{text}}\"',\n\t\t\tselected: '☑️ Selecionou a opção \"{{text}}\"',\n\t\t\tscrolled: '🛞 Página rolada',\n\t\t\twaited: '⌛️ Espera concluída',\n\t\t\texecuting: 'Executando {{toolName}}...',\n\t\t\tresultSuccess: 'sucesso',\n\t\t\tresultFailure: 'falhou',\n\t\t\tresultError: 'erro',\n\t\t},\n\t\terrors: {\n\t\t\telementNotFound: 'Nenhum elemento interativo encontrado no índice {{index}}',\n\t\t\ttaskRequired: 'A descrição da tarefa é obrigatória',\n\t\t\texecutionFailed: 'Falha na execução da tarefa',\n\t\t\tnotInputElement: 'O elemento não é um campo de texto',\n\t\t\tnotSelectElement: 'O elemento não é uma lista de seleção',\n\t\t\toptionNotFound: 'Opção \"{{text}}\" não encontrada',\n\t\t},\n\t},\n} as const\n\n// Type definitions generated from English base structure (but with string values)\ntype DeepStringify<T> = {\n\t[K in keyof T]: T[K] extends string ? string : T[K] extends object ? DeepStringify<T[K]> : T[K]\n}\n\nexport type TranslationSchema = DeepStringify<typeof enUS>\n\n// Utility type: Extract all nested paths from translation object\ntype NestedKeyOf<ObjectType extends object> = {\n\t[Key in keyof ObjectType & (string | number)]: ObjectType[Key] extends object\n\t\t? `${Key}` | `${Key}.${NestedKeyOf<ObjectType[Key]>}`\n\t\t: `${Key}`\n}[keyof ObjectType & (string | number)]\n\n// Extract all possible key paths from translation structure\nexport type TranslationKey = NestedKeyOf<TranslationSchema>\n\n// Parameterized translation types\nexport type TranslationParams = Record<string, string | number>\n\nexport const locales = {\n\t'en-US': enUS,\n\t'pt-BR': ptBR,\n} as const\n\nexport type SupportedLanguage = keyof typeof locales\n","import {\n\ttype SupportedLanguage,\n\ttype TranslationKey,\n\ttype TranslationParams,\n\ttype TranslationSchema,\n\tlocales,\n} from './locales'\n\nexport class I18n {\n\tprivate language: SupportedLanguage\n\tprivate translations: TranslationSchema\n\n\tconstructor(language: string = 'en-US') {\n\t\t// Languages without a translation (for example, codes the core still accepts) fall back to English.\n\t\tthis.language = (language in locales ? language : 'en-US') as SupportedLanguage\n\t\tthis.translations = locales[this.language]\n\t}\n\n\t// 类型安全的翻译方法\n\tt(key: TranslationKey, params?: TranslationParams): string {\n\t\tconst value = this.getNestedValue(this.translations, key)\n\t\tif (!value) {\n\t\t\tconsole.warn(`Translation key \"${key}\" not found for language \"${this.language}\"`)\n\t\t\treturn key\n\t\t}\n\n\t\tif (params) {\n\t\t\treturn this.interpolate(value, params)\n\t\t}\n\t\treturn value\n\t}\n\n\tprivate getNestedValue(obj: any, path: string): string | undefined {\n\t\treturn path.split('.').reduce((current, key) => current?.[key], obj)\n\t}\n\n\tprivate interpolate(template: string, params: TranslationParams): string {\n\t\treturn template.replace(/\\{\\{(\\w+)\\}\\}/g, (match, key) => {\n\t\t\t// Use != null to check for both null and undefined, allow empty strings\n\t\t\treturn params[key] != null ? params[key].toString() : match\n\t\t})\n\t}\n\n\tgetLanguage(): SupportedLanguage {\n\t\treturn this.language\n\t}\n}\n\n// 导出类型和实例创建函数\nexport type { TranslationKey, SupportedLanguage, TranslationParams }\nexport { locales }\n","/**\n * Messages of the OpenAI Realtime API used by the panel's voice mode.\n * Pure functions only: building and reading messages, no network.\n */\n\nexport const REALTIME_MODEL = 'gpt-realtime-2.1-mini'\nexport const TRANSCRIPTION_MODEL = 'gpt-4o-mini-transcribe'\nexport const REALTIME_VOICE = 'marin'\nexport const RUN_TASK = 'run_task'\nexport const EXECUTE_JS = 'execute_javascript'\n\nexport interface RealtimeSettings {\n\tinstructions: string\n\tlanguage: string\n\tvoice?: string\n}\n\n/** Hands a multi-step task or a judgment about the page to the agent. */\nexport const RUN_TASK_TOOL = {\n\ttype: 'function',\n\tname: RUN_TASK,\n\tdescription:\n\t\t'Gives a task to the page agent, which carries it out in several steps. Use it for a task that needs several steps or a judgment about the page. For one simple action or a read, use execute_javascript.',\n\tparameters: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\ttask: {\n\t\t\t\ttype: 'string',\n\t\t\t\t// REVERSIBLE (2026-11-17, task intake): the request goes as the user said it.\n\t\t\t\tdescription:\n\t\t\t\t\t\"The user's request, exactly as the user said it. Do not rewrite it or add context.\",\n\t\t\t},\n\t\t},\n\t\trequired: ['task'],\n\t},\n} as const\n\n/** Runs JavaScript in the page, with the page-agent instance in scope as `agent`. */\nexport const EXECUTE_JS_TOOL = {\n\ttype: 'function',\n\tname: EXECUTE_JS,\n\tdescription:\n\t\t'Runs JavaScript in this page and returns its result. The variable `agent` is the page-agent instance (`agent.pageController`, `agent.tools`). Use it to read the page, measure positions, or act on an element, without starting an agent task. `await agent.pageController.getState()` reads the page only when needed. Write one script for the whole job, and return a small object with the values you need.',\n\tparameters: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\tscript: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'The JavaScript body. Use `return` to send a value back.',\n\t\t\t},\n\t\t},\n\t\trequired: ['script'],\n\t},\n} as const\n\n/**\n * Session configuration sent when the call is created. The model answers conversation by itself and uses its\n * two tools for the page. Speech interrupts the model (barge-in) through server-side turn detection.\n */\nexport function callSessionConfig(settings: RealtimeSettings): string {\n\treturn JSON.stringify({\n\t\ttype: 'realtime',\n\t\tmodel: REALTIME_MODEL,\n\t\tinstructions: settings.instructions,\n\t\toutput_modalities: ['audio'],\n\t\ttools: [RUN_TASK_TOOL, EXECUTE_JS_TOOL],\n\t\ttool_choice: 'auto',\n\t\taudio: {\n\t\t\tinput: {\n\t\t\t\ttranscription: { model: TRANSCRIPTION_MODEL, language: settings.language },\n\t\t\t\tturn_detection: { type: 'server_vad', create_response: true, interrupt_response: true },\n\t\t\t},\n\t\t\toutput: { voice: settings.voice ?? REALTIME_VOICE },\n\t\t},\n\t})\n}\n\n/**\n * The current date, time and time zone. Sent with each response, so a long voice session does not keep a\n * stale time from when it started.\n */\nexport function currentTimeLine(now: Date = new Date()): string {\n\tconst zone = Intl.DateTimeFormat().resolvedOptions().timeZone\n\tconst formatted = new Intl.DateTimeFormat('en-US', {\n\t\tdateStyle: 'full',\n\t\ttimeStyle: 'medium',\n\t\ttimeZone: zone,\n\t}).format(now)\n\treturn `Current time: ${formatted} (${zone}).`\n}\n\n/** What the agent reports to the voice. Facts only; the voice model turns them into one spoken sentence. */\nexport interface VoiceReport {\n\tkind: 'question' | 'done' | 'not-done' | 'stopped' | 'error' | 'notice'\n\ttext: string\n}\n\nconst KIND_LABEL: Record<VoiceReport['kind'], string> = {\n\tquestion: 'The agent needs an answer from the user',\n\tdone: 'The task was completed',\n\t'not-done': 'The task was not completed',\n\tstopped: 'The task was stopped',\n\terror: 'The task failed',\n\tnotice: 'System notice',\n}\n\nconst REPORT_MAX_CHARS = 600\n\n/** Sends a report as context and asks for one short spoken sentence. The model does not repeat the text. */\nexport function reportCommand(report: VoiceReport): string {\n\tconst body = report.text.trim().slice(0, REPORT_MAX_CHARS)\n\treturn JSON.stringify({\n\t\ttype: 'response.create',\n\t\tresponse: {\n\t\t\toutput_modalities: ['audio'],\n\t\t\tinstructions: `${KIND_LABEL[report.kind]}. ${currentTimeLine()}\\nData for you to use with judgment; do not read technical details:\\n${body}\\nAnswer in one short sentence.`,\n\t\t},\n\t})\n}\n\n/** Stops the model's speech in progress. Only send it while a response is running. */\nexport function cancelResponseCommand(): string {\n\treturn JSON.stringify({ type: 'response.cancel' })\n}\n\n/** Returns the result of a tool call to the model, then asks it to continue speaking. */\nexport function toolResultCommands(callId: string, output: string): string[] {\n\treturn [\n\t\tJSON.stringify({\n\t\t\ttype: 'conversation.item.create',\n\t\t\titem: { type: 'function_call_output', call_id: callId, output },\n\t\t}),\n\t\tJSON.stringify({\n\t\t\ttype: 'response.create',\n\t\t\t// REVERSIBLE (2026-11-17, task intake): after a tool result, speak only the result in one sentence.\n\t\t\tresponse: {\n\t\t\t\toutput_modalities: ['audio'],\n\t\t\t\tinstructions: `${currentTimeLine()} Give only the result of the tool in one short sentence. Do not describe what you are about to do.`,\n\t\t\t},\n\t\t}),\n\t]\n}\n\nexport type ServerEvent =\n\t| { type: 'ready' }\n\t| { type: 'transcript'; text: string }\n\t| { type: 'speech_started' }\n\t| { type: 'response_started' }\n\t| { type: 'response_done' }\n\t| { type: 'tool_call'; name: string; callId: string; args: Record<string, unknown> }\n\t| { type: 'error'; message: string }\n\t| { type: 'other' }\n\n/** Reads the arguments of a tool call. Missing or malformed arguments give an empty object. */\nfunction argsFrom(raw: unknown): Record<string, unknown> {\n\tif (typeof raw !== 'string') return {}\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(raw)\n\t\treturn typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {}\n\t} catch {\n\t\treturn {}\n\t}\n}\n\n/** Reads one message from the data channel. Unknown or malformed messages become `other`. */\nexport function parseServerEvent(raw: string): ServerEvent {\n\tlet data: unknown\n\ttry {\n\t\tdata = JSON.parse(raw)\n\t} catch {\n\t\treturn { type: 'other' }\n\t}\n\tif (typeof data !== 'object' || data === null) return { type: 'other' }\n\tconst event = data as Record<string, unknown>\n\tswitch (event.type) {\n\t\tcase 'session.created':\n\t\tcase 'session.started':\n\t\tcase 'session.updated':\n\t\t\treturn { type: 'ready' }\n\t\tcase 'conversation.item.input_audio_transcription.completed':\n\t\t\treturn typeof event.transcript === 'string'\n\t\t\t\t? { type: 'transcript', text: event.transcript.trim() }\n\t\t\t\t: { type: 'other' }\n\t\tcase 'input_audio_buffer.speech_started':\n\t\t\treturn { type: 'speech_started' }\n\t\tcase 'response.created':\n\t\t\treturn { type: 'response_started' }\n\t\tcase 'response.done':\n\t\t\treturn { type: 'response_done' }\n\t\tcase 'response.function_call_arguments.done':\n\t\t\treturn typeof event.name === 'string' && typeof event.call_id === 'string'\n\t\t\t\t? {\n\t\t\t\t\t\ttype: 'tool_call',\n\t\t\t\t\t\tname: event.name,\n\t\t\t\t\t\tcallId: event.call_id,\n\t\t\t\t\t\targs: argsFrom(event.arguments),\n\t\t\t\t\t}\n\t\t\t\t: { type: 'other' }\n\t\tcase 'error': {\n\t\t\tconst error = event.error as { message?: unknown } | undefined\n\t\t\treturn {\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: typeof error?.message === 'string' ? error.message : 'error',\n\t\t\t}\n\t\t}\n\t\tdefault:\n\t\t\treturn { type: 'other' }\n\t}\n}\n","/**\n * Gemini Live protocol for the voice panel. Pure functions only: no network, no audio devices.\n * REVERSIBLE (2026-11-17, gemini provider): delete this file and gemini-client.ts to remove Gemini support.\n *\n * The session sends commands in the shape the OpenAI client already uses. `translateCommand` turns each one into a\n * Gemini client message, so the session does not change for either provider.\n */\nimport {\n\tEXECUTE_JS_TOOL,\n\tRUN_TASK_TOOL,\n\ttype RealtimeSettings,\n\ttype ServerEvent,\n} from './realtime-protocol'\n\nexport const GEMINI_LIVE_MODEL = 'gemini-3.8-live'\nexport const GEMINI_VOICE = 'Leda'\nconst LIVE_ENDPOINT =\n\t'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent'\n\nexport function liveUrl(apiKey: string): string {\n\treturn `${LIVE_ENDPOINT}?key=${encodeURIComponent(apiKey)}`\n}\n\n/** Gemini wants schema types in upper case (OBJECT, STRING); the tool definitions use lower case. */\nfunction toGeminiSchema(schema: unknown): unknown {\n\tif (Array.isArray(schema)) return schema.map(toGeminiSchema)\n\tif (typeof schema !== 'object' || schema === null) return schema\n\tconst out: Record<string, unknown> = {}\n\tfor (const [key, value] of Object.entries(schema)) {\n\t\tout[key] =\n\t\t\tkey === 'type' && typeof value === 'string' ? value.toUpperCase() : toGeminiSchema(value)\n\t}\n\treturn out\n}\n\n/** The two tools, declared with the same names, descriptions and parameters as for OpenAI. */\nexport function geminiTools(): unknown[] {\n\treturn [\n\t\t{\n\t\t\tfunctionDeclarations: [RUN_TASK_TOOL, EXECUTE_JS_TOOL].map((tool) => ({\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tparameters: toGeminiSchema(tool.parameters),\n\t\t\t})),\n\t\t},\n\t]\n}\n\n/** The first message on a new connection: model, voice, instructions and tools. */\nexport function geminiSetup(settings: RealtimeSettings): string {\n\treturn JSON.stringify({\n\t\tsetup: {\n\t\t\tmodel: `models/${GEMINI_LIVE_MODEL}`,\n\t\t\tgenerationConfig: {\n\t\t\t\tresponseModalities: ['AUDIO'],\n\t\t\t\tspeechConfig: {\n\t\t\t\t\tvoiceConfig: { prebuiltVoiceConfig: { voiceName: GEMINI_VOICE } },\n\t\t\t\t},\n\t\t\t},\n\t\t\tsystemInstruction: { parts: [{ text: settings.instructions }] },\n\t\t\ttools: geminiTools(),\n\t\t\tinputAudioTranscription: {},\n\t\t\toutputAudioTranscription: {},\n\t\t},\n\t})\n}\n\n/** State the translation needs between commands: the name of each tool call, and whether a tool reply is pending. */\nexport interface GeminiSendState {\n\tcallNames: Map<string, string>\n\tawaitingToolReply: boolean\n}\n\nexport function newSendState(): GeminiSendState {\n\treturn { callNames: new Map(), awaitingToolReply: false }\n}\n\n/** A command as the session builds it (OpenAI Realtime shape). Only the fields used here are typed. */\ninterface Command {\n\ttype?: string\n\tresponse?: { instructions?: string }\n\titem?: {\n\t\ttype?: string\n\t\trole?: string\n\t\tcall_id?: string\n\t\toutput?: string\n\t\tcontent?: { text?: string }[]\n\t}\n}\n\nfunction userText(text: string, turnComplete: boolean): unknown {\n\treturn { clientContent: { turns: [{ role: 'user', parts: [{ text }] }], turnComplete } }\n}\n\n/**\n * Turns one session command into Gemini client messages.\n * - A report (response.create) asks the model to speak: it ends the user turn.\n * - A silent note (system item) is added without asking for a reply.\n * - A tool result is a tool response; Gemini then continues by itself, so the response.create that follows is dropped.\n * - Cancel and delete have no Gemini equivalent here: the client stops local playback for cancel.\n */\nexport function translateCommand(raw: string, state: GeminiSendState): unknown[] {\n\tlet cmd: Command\n\ttry {\n\t\tcmd = JSON.parse(raw) as Command\n\t} catch {\n\t\treturn []\n\t}\n\tswitch (cmd.type) {\n\t\tcase 'response.create': {\n\t\t\tif (state.awaitingToolReply) {\n\t\t\t\tstate.awaitingToolReply = false\n\t\t\t\treturn []\n\t\t\t}\n\t\t\tconst text = cmd.response?.instructions\n\t\t\treturn text ? [userText(text, true)] : []\n\t\t}\n\t\tcase 'conversation.item.create': {\n\t\t\tconst item = cmd.item\n\t\t\tif (item?.type === 'function_call_output') {\n\t\t\t\tconst callId = item.call_id ?? ''\n\t\t\t\tstate.awaitingToolReply = true\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\ttoolResponse: {\n\t\t\t\t\t\t\tfunctionResponses: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tid: callId,\n\t\t\t\t\t\t\t\t\tname: state.callNames.get(callId) ?? '',\n\t\t\t\t\t\t\t\t\tresponse: { output: item.output ?? '' },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t}\n\t\t\tconst text = item?.content?.[0]?.text\n\t\t\treturn item?.role === 'system' && text ? [userText(text, false)] : []\n\t\t}\n\t\tdefault:\n\t\t\treturn []\n\t}\n}\n\ninterface GeminiServerMessage {\n\tsetupComplete?: unknown\n\tserverContent?: {\n\t\tinterrupted?: boolean\n\t\tturnComplete?: boolean\n\t\tinputTranscription?: { text?: string }\n\t\tmodelTurn?: { parts?: { inlineData?: { data?: string } }[] }\n\t}\n\ttoolCall?: { functionCalls?: { id?: string; name?: string; args?: Record<string, unknown> }[] }\n\terror?: { message?: string }\n}\n\n/** What the client needs from a server message: the shared events, plus audio and the end of a turn. */\nexport type GeminiEvent = ServerEvent | { type: 'audio'; data: string } | { type: 'turn_complete' }\n\n/** Reads one server message. Unknown or malformed messages give no events. */\nexport function parseGeminiMessage(data: unknown): GeminiEvent[] {\n\tif (typeof data !== 'object' || data === null) return []\n\tconst msg = data as GeminiServerMessage\n\tconst events: GeminiEvent[] = []\n\tif (msg.setupComplete !== undefined) events.push({ type: 'ready' })\n\tconst content = msg.serverContent\n\tif (content) {\n\t\tif (content.interrupted) events.push({ type: 'speech_started' })\n\t\tconst transcript = content.inputTranscription?.text?.trim()\n\t\tif (transcript) events.push({ type: 'transcript', text: transcript })\n\t\tfor (const part of content.modelTurn?.parts ?? []) {\n\t\t\tif (part.inlineData?.data) events.push({ type: 'audio', data: part.inlineData.data })\n\t\t}\n\t\tif (content.turnComplete) events.push({ type: 'turn_complete' })\n\t}\n\tfor (const call of msg.toolCall?.functionCalls ?? []) {\n\t\tif (call.id && call.name) {\n\t\t\tevents.push({ type: 'tool_call', name: call.name, callId: call.id, args: call.args ?? {} })\n\t\t}\n\t}\n\tif (msg.error?.message) events.push({ type: 'error', message: msg.error.message })\n\treturn events\n}\n\n/** Microphone samples (float, -1..1) to 16-bit little-endian PCM, as base64. */\nexport function floatToPcm16Base64(samples: Float32Array): string {\n\tconst bytes = new Uint8Array(samples.length * 2)\n\tconst view = new DataView(bytes.buffer)\n\tfor (let i = 0; i < samples.length; i++) {\n\t\tconst s = Math.max(-1, Math.min(1, samples[i]))\n\t\tview.setInt16(i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true)\n\t}\n\treturn bytesToBase64(bytes)\n}\n\n/** 16-bit little-endian PCM, as base64, to float samples (-1..1). */\nexport function pcm16Base64ToFloat(base64: string): Float32Array {\n\tconst bytes = base64ToBytes(base64)\n\tconst view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n\tconst out = new Float32Array(bytes.byteLength / 2)\n\tfor (let i = 0; i < out.length; i++) out[i] = view.getInt16(i * 2, true) / 0x8000\n\treturn out\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\tlet binary = ''\n\tfor (const byte of bytes) binary += String.fromCharCode(byte)\n\treturn btoa(binary)\n}\n\nfunction base64ToBytes(base64: string): Uint8Array {\n\tconst binary = atob(base64)\n\tconst bytes = new Uint8Array(binary.length)\n\tfor (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n\treturn bytes\n}\n\n/**\n * Fades the first `ms` milliseconds in, from silence. Used at the start of a model response only.\n * REVERSIBLE (2026-11-17, playback blocks).\n */\nexport function fadeIn(samples: Float32Array, sampleRate: number, ms: number): void {\n\tconst n = Math.min(Math.floor((sampleRate * ms) / 1000), samples.length)\n\tfor (let i = 0; i < n; i++) samples[i] *= i / n\n}\n\n/**\n * Fades the last `ms` milliseconds out, to silence. Used at the end of a model response only.\n * REVERSIBLE (2026-11-17, playback blocks).\n */\nexport function fadeOut(samples: Float32Array, sampleRate: number, ms: number): void {\n\tconst n = Math.min(Math.floor((sampleRate * ms) / 1000), samples.length)\n\tfor (let i = 0; i < n; i++) samples[samples.length - 1 - i] *= i / n\n}\n","/**\n * WebSocket connection to the Gemini Live API. Same interface as the OpenAI client (connect, send, replaceTrack,\n * close) and the same normalized events, so the voice session does not know which provider it talks to.\n * The browser calls the API directly with the key it was given (development setup, no backend yet).\n * REVERSIBLE (2026-11-17, gemini provider): delete this file and gemini-protocol.ts to remove Gemini support.\n */\nimport {\n\ttype GeminiSendState,\n\tfadeIn,\n\tfadeOut,\n\tfloatToPcm16Base64,\n\tgeminiSetup,\n\tliveUrl,\n\tnewSendState,\n\tparseGeminiMessage,\n\tpcm16Base64ToFloat,\n\ttranslateCommand,\n} from './gemini-protocol'\nimport type { RealtimeCallbacks, RealtimeConnectOptions } from './realtime-client'\nimport type { RealtimeSettings, ServerEvent } from './realtime-protocol'\n\nconst READY_TIMEOUT_MS = 10000\nconst CAPTURE_RATE = 16000\nconst PLAYBACK_RATE = 24000\n// REVERSIBLE (2026-11-17, playback blocks): model audio is played in blocks of about 150 ms, with a fade only at the\n// start and end of each response. Fades on every chunk made audible dips inside the speech.\nconst BLOCK_SECONDS = 0.15\nconst BLOCK_SAMPLES = Math.round(PLAYBACK_RATE * BLOCK_SECONDS)\nconst EDGE_FADE_MS = 5\n/** Collects microphone samples in blocks of about 128 ms before sending them. */\nconst CAPTURE_BLOCK = 2048\n\nconst CAPTURE_WORKLET = `\nclass PaCapture extends AudioWorkletProcessor {\n constructor() { super(); this.block = []; this.size = 0 }\n process(inputs) {\n const channel = inputs[0] && inputs[0][0];\n if (channel) {\n this.block.push(channel.slice(0));\n this.size += channel.length;\n if (this.size >= ${CAPTURE_BLOCK}) {\n const out = new Float32Array(this.size);\n let at = 0;\n for (const part of this.block) { out.set(part, at); at += part.length; }\n this.port.postMessage(out, [out.buffer]);\n this.block = []; this.size = 0;\n }\n }\n return true;\n }\n}\nregisterProcessor('pa-capture', PaCapture);\n`\n\nexport class GeminiLiveClient {\n\t#callbacks: RealtimeCallbacks\n\t#ws: WebSocket | null = null\n\t#ctx: AudioContext | null = null\n\t// REVERSIBLE (2026-11-17, playback fix): plays the model's audio at the device's own rate, apart from the 16 kHz capture context.\n\t#playCtx: AudioContext | null = null\n\t#capture: AudioWorkletNode | null = null\n\t#source: MediaStreamAudioSourceNode | null = null\n\t#sending = false\n\t#closing = false\n\t#onReady: (() => void) | null = null\n\t#send: GeminiSendState = newSendState()\n\t#playing: AudioBufferSourceNode[] = []\n\t#nextPlayTime = 0\n\t#inTurn = false\n\t// REVERSIBLE (2026-11-17, playback blocks)\n\t#pending: Float32Array[] = []\n\t#pendingLength = 0\n\t#turnStart = true\n\n\tconstructor(callbacks: RealtimeCallbacks) {\n\t\tthis.#callbacks = callbacks\n\t}\n\n\t/** Opens the connection. Resolves once the server confirms the setup; rejects on any failure. */\n\tasync connect(options: RealtimeConnectOptions): Promise<void> {\n\t\ttry {\n\t\t\tawait this.#open(options.apiKey, options.settings)\n\t\t\tthis.#ctx = new AudioContext({ sampleRate: CAPTURE_RATE })\n\t\t\tawait this.#ctx.resume()\n\t\t\tthis.#playCtx = new AudioContext()\n\t\t\tawait this.#playCtx.resume()\n\t\t\t// Mobile browsers often start AudioContext suspended until a fresh resume after setup.\n\t\t\tif (this.#ctx.state !== 'running') await this.#ctx.resume()\n\t\t\tif (this.#playCtx.state !== 'running') await this.#playCtx.resume()\n\t\t\tawait this.#startCapture(options.track)\n\t\t} catch (error) {\n\t\t\tthis.close()\n\t\t\tthrow error\n\t\t}\n\t\tawait this.#ready\n\t}\n\n\t#ready: Promise<void> = Promise.resolve()\n\n\t#open(apiKey: string, settings: RealtimeSettings): Promise<void> {\n\t\tconst ws = new WebSocket(liveUrl(apiKey))\n\t\tws.binaryType = 'blob'\n\t\tthis.#ws = ws\n\t\tthis.#ready = new Promise<void>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => reject(new Error('session timeout')), READY_TIMEOUT_MS)\n\t\t\tthis.#onReady = () => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tresolve()\n\t\t\t}\n\t\t})\n\t\tws.onmessage = (event: MessageEvent<unknown>) => void this.#receive(event.data)\n\t\tws.onclose = () => {\n\t\t\tif (!this.#closing) this.#callbacks.onClosed()\n\t\t}\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tws.onopen = () => {\n\t\t\t\tws.send(geminiSetup(settings))\n\t\t\t\tresolve()\n\t\t\t}\n\t\t\tws.onerror = () => reject(new Error('connection failed'))\n\t\t})\n\t}\n\n\tasync #receive(data: unknown): Promise<void> {\n\t\tconst text = data instanceof Blob ? await data.text() : String(data)\n\t\tlet parsed: unknown\n\t\ttry {\n\t\t\tparsed = JSON.parse(text)\n\t\t} catch {\n\t\t\treturn\n\t\t}\n\t\tfor (const event of parseGeminiMessage(parsed)) this.#handle(event)\n\t}\n\n\t#handle(event: ReturnType<typeof parseGeminiMessage>[number]): void {\n\t\tswitch (event.type) {\n\t\t\tcase 'audio':\n\t\t\t\tthis.#play(event.data)\n\t\t\t\tif (!this.#inTurn) {\n\t\t\t\t\tthis.#inTurn = true\n\t\t\t\t\tthis.#callbacks.onEvent({ type: 'response_started' })\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase 'turn_complete':\n\t\t\t\tthis.#inTurn = false\n\t\t\t\tthis.#flush(true)\n\t\t\t\tthis.#turnStart = true\n\t\t\t\tthis.#callbacks.onEvent({ type: 'response_done' })\n\t\t\t\treturn\n\t\t\tcase 'speech_started':\n\t\t\t\tthis.#stopPlayback()\n\t\t\t\tthis.#inTurn = false\n\t\t\t\tthis.#callbacks.onEvent({ type: 'speech_started' })\n\t\t\t\treturn\n\t\t\tcase 'ready':\n\t\t\t\tthis.#onReady?.()\n\t\t\t\tthis.#callbacks.onEvent({ type: 'ready' })\n\t\t\t\treturn\n\t\t\tcase 'tool_call':\n\t\t\t\tthis.#send.callNames.set(event.callId, event.name)\n\t\t\t\tthis.#callbacks.onEvent(event as ServerEvent)\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tthis.#callbacks.onEvent(event as ServerEvent)\n\t\t}\n\t}\n\n\t/** Sends a command in the session's shape, translated for Gemini. Cancel stops the local playback. */\n\tsend(message: string): void {\n\t\tif (this.#ws?.readyState !== WebSocket.OPEN) return\n\t\tif ((JSON.parse(message) as { type?: string }).type === 'response.cancel') this.#stopPlayback()\n\t\tfor (const out of translateCommand(message, this.#send)) this.#ws.send(JSON.stringify(out))\n\t}\n\n\t/** Swaps the microphone track. A null track stops sending audio (mute). */\n\tasync replaceTrack(track: MediaStreamTrack | null): Promise<void> {\n\t\tif (!track) {\n\t\t\tthis.#sending = false\n\t\t\tthis.#source?.disconnect()\n\t\t\tthis.#source = null\n\t\t\treturn\n\t\t}\n\t\tawait this.#startCapture(track)\n\t}\n\n\tclose(): void {\n\t\tthis.#closing = true\n\t\tthis.#ws?.close()\n\t\tthis.#stopPlayback()\n\t\tthis.#source?.disconnect()\n\t\tthis.#capture?.disconnect()\n\t\tvoid this.#ctx?.close()\n\t\tvoid this.#playCtx?.close()\n\t\tthis.#playCtx = null\n\t\tthis.#ws = null\n\t\tthis.#ctx = null\n\t\tthis.#capture = null\n\t\tthis.#source = null\n\t\tthis.#sending = false\n\t}\n\n\tasync #startCapture(track: MediaStreamTrack): Promise<void> {\n\t\tconst ctx = this.#ctx\n\t\tif (!ctx) return\n\t\tif (!this.#capture) {\n\t\t\tconst url = URL.createObjectURL(\n\t\t\t\tnew Blob([CAPTURE_WORKLET], { type: 'application/javascript' })\n\t\t\t)\n\t\t\tawait ctx.audioWorklet.addModule(url)\n\t\t\tURL.revokeObjectURL(url)\n\t\t\tconst capture = new AudioWorkletNode(ctx, 'pa-capture')\n\t\t\tconst silent = new GainNode(ctx, { gain: 0 })\n\t\t\tcapture.connect(silent)\n\t\t\tsilent.connect(ctx.destination)\n\t\t\tcapture.port.onmessage = (event: MessageEvent<Float32Array>) => this.#sendAudio(event.data)\n\t\t\tthis.#capture = capture\n\t\t}\n\t\tthis.#source?.disconnect()\n\t\tthis.#source = ctx.createMediaStreamSource(new MediaStream([track]))\n\t\tthis.#source.connect(this.#capture)\n\t\tthis.#sending = true\n\t}\n\n\t#sendAudio(samples: Float32Array): void {\n\t\tif (!this.#sending || this.#ws?.readyState !== WebSocket.OPEN) return\n\t\tthis.#ws.send(\n\t\t\tJSON.stringify({\n\t\t\t\trealtimeInput: {\n\t\t\t\t\taudio: { data: floatToPcm16Base64(samples), mimeType: `audio/pcm;rate=${CAPTURE_RATE}` },\n\t\t\t\t},\n\t\t\t})\n\t\t)\n\t}\n\n\t#play(base64: string): void {\n\t\tif (!this.#playCtx) return\n\t\tthis.#pending.push(pcm16Base64ToFloat(base64))\n\t\tthis.#pendingLength += this.#pending[this.#pending.length - 1].length\n\t\tif (this.#pendingLength >= BLOCK_SAMPLES) this.#flush(false)\n\t}\n\n\t/** Schedules everything queued as one buffer. The start of a response fades in, and the end fades out when final. */\n\t#flush(final: boolean): void {\n\t\tconst ctx = this.#playCtx\n\t\tif (!ctx || this.#pendingLength === 0) return\n\t\tconst samples = new Float32Array(this.#pendingLength)\n\t\tlet at = 0\n\t\tfor (const part of this.#pending) {\n\t\t\tsamples.set(part, at)\n\t\t\tat += part.length\n\t\t}\n\t\tthis.#pending = []\n\t\tthis.#pendingLength = 0\n\t\tif (this.#turnStart) fadeIn(samples, PLAYBACK_RATE, EDGE_FADE_MS)\n\t\tif (final) fadeOut(samples, PLAYBACK_RATE, EDGE_FADE_MS)\n\t\tthis.#turnStart = false\n\n\t\tconst buffer = ctx.createBuffer(1, samples.length, PLAYBACK_RATE)\n\t\tbuffer.getChannelData(0).set(samples)\n\t\tconst node = ctx.createBufferSource()\n\t\tnode.buffer = buffer\n\t\tnode.connect(ctx.destination)\n\t\tconst now = ctx.currentTime\n\t\t// Nothing is queued any more (a gap in the stream): start a little later so the next block can arrive.\n\t\tif (this.#nextPlayTime <= now) this.#nextPlayTime = now + 0.05\n\t\tconst start = this.#nextPlayTime\n\t\tnode.start(start)\n\t\tthis.#nextPlayTime = start + buffer.duration\n\t\tthis.#playing.push(node)\n\t\tnode.onended = () => {\n\t\t\tthis.#playing = this.#playing.filter((n) => n !== node)\n\t\t}\n\t}\n\n\t#stopPlayback(): void {\n\t\tfor (const node of this.#playing) {\n\t\t\ttry {\n\t\t\t\tnode.stop()\n\t\t\t} catch {\n\t\t\t\t// already stopped\n\t\t\t}\n\t\t}\n\t\tthis.#playing = []\n\t\tthis.#pending = []\n\t\tthis.#pendingLength = 0\n\t\tthis.#turnStart = true\n\t\tthis.#nextPlayTime = this.#playCtx?.currentTime ?? 0\n\t}\n}\n","/**\n * WebRTC connection to the OpenAI Realtime API. The browser calls the API directly with the key it was given\n * (development setup, no backend yet). Microphone and speech travel on media tracks; JSON events on a data channel.\n */\nimport {\n\ttype RealtimeSettings,\n\ttype ServerEvent,\n\tcallSessionConfig,\n\tparseServerEvent,\n} from './realtime-protocol'\n\nconst CALLS_URL = 'https://api.openai.com/v1/realtime/calls'\nconst READY_TIMEOUT_MS = 10000\n\nexport interface RealtimeCallbacks {\n\tonEvent: (event: ServerEvent) => void\n\tonClosed: () => void\n}\n\nexport interface RealtimeConnectOptions {\n\tapiKey: string\n\tsettings: RealtimeSettings\n\ttrack: MediaStreamTrack\n}\n\nexport class RealtimeClient {\n\t#callbacks: RealtimeCallbacks\n\t#pc: RTCPeerConnection | null = null\n\t#channel: RTCDataChannel | null = null\n\t#audio: HTMLAudioElement | null = null\n\n\tconstructor(callbacks: RealtimeCallbacks) {\n\t\tthis.#callbacks = callbacks\n\t}\n\n\t/** Opens the call. Resolves once the server confirms the session; rejects on any failure. */\n\tasync connect(options: RealtimeConnectOptions): Promise<void> {\n\t\tconst pc = new RTCPeerConnection()\n\t\tthis.#pc = pc\n\t\tconst audio = document.createElement('audio')\n\t\taudio.autoplay = true\n\t\t// Mobile Safari needs playsInline and a connected element before remote audio can start.\n\t\taudio.setAttribute('playsinline', 'true')\n\t\t;(audio as HTMLAudioElement & { playsInline?: boolean }).playsInline = true\n\t\taudio.setAttribute('aria-hidden', 'true')\n\t\taudio.style.display = 'none'\n\t\tdocument.body.appendChild(audio)\n\t\tthis.#audio = audio\n\t\tpc.ontrack = (event) => {\n\t\t\taudio.srcObject = event.streams[0] ?? null\n\t\t\tvoid audio.play().catch((error) => {\n\t\t\t\tconsole.warn('[page-agent voice] remote audio playback blocked', error)\n\t\t\t})\n\t\t}\n\t\tpc.addTrack(options.track)\n\n\t\tconst channel = pc.createDataChannel('oai-events')\n\t\tthis.#channel = channel\n\t\tconst ready = new Promise<void>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => reject(new Error('session timeout')), READY_TIMEOUT_MS)\n\t\t\tchannel.onmessage = (message) => {\n\t\t\t\tconst event = parseServerEvent(String(message.data))\n\t\t\t\tif (event.type === 'ready') {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\tresolve()\n\t\t\t\t}\n\t\t\t\tthis.#callbacks.onEvent(event)\n\t\t\t}\n\t\t})\n\t\tchannel.onclose = () => this.#callbacks.onClosed()\n\n\t\tconst offer = await pc.createOffer()\n\t\tawait pc.setLocalDescription(offer)\n\t\tconst form = new FormData()\n\t\tform.set('sdp', offer.sdp ?? '')\n\t\tform.set('session', callSessionConfig(options.settings))\n\t\tconst response = await fetch(CALLS_URL, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { Authorization: `Bearer ${options.apiKey}` },\n\t\t\tbody: form,\n\t\t})\n\t\tif (!response.ok) throw new Error(`realtime call failed: ${response.status}`)\n\t\tawait pc.setRemoteDescription({ type: 'answer', sdp: await response.text() })\n\t\tawait ready\n\t}\n\n\t/** Sends a JSON command on the data channel, if the channel is open. */\n\tsend(message: string): void {\n\t\tif (this.#channel?.readyState === 'open') this.#channel.send(message)\n\t}\n\n\t/** Swaps the microphone track (used after mute and unmute). A null track stops sending audio. */\n\tasync replaceTrack(track: MediaStreamTrack | null): Promise<void> {\n\t\tconst sender = this.#pc?.getSenders().find((s) => s.track === null || s.track.kind === 'audio')\n\t\tawait sender?.replaceTrack(track)\n\t}\n\n\tclose(): void {\n\t\tthis.#channel?.close()\n\t\tthis.#pc?.close()\n\t\tthis.#audio?.remove()\n\t\tthis.#channel = null\n\t\tthis.#pc = null\n\t\tthis.#audio = null\n\t}\n}\n","import defaultPrompt from './prompts/voice.md?raw'\n\n/**\n * The language rule the panel's configured language imposes on the voice. Always in English, like the prompt.\n * It is added after the prompt, so the model replies in the panel's language even if the user speaks another one.\n */\nexport function languageRule(language: string): string {\n\tconst name = language === 'pt-BR' ? 'Brazilian Portuguese' : 'English'\n\treturn `Always reply in ${name}, whatever language the user speaks. The panel's language is fixed.`\n}\n\n/**\n * The voice model's system prompt. A custom text is added after the default one, which is kept whole. It replaces the\n * default only when `override` is true, like `overrideSystemPrompt` does for the agent. `null` or empty means the default.\n * REVERSIBLE (2026-11-23, system prompt override): the `override` parameter and the merge.\n */\nexport function resolveVoicePrompt(custom: string | null | undefined, override = false): string {\n\tconst text = custom?.trim()\n\tif (!text) return defaultPrompt\n\treturn override ? text : `${defaultPrompt}\\n\\n${text}`\n}\n","/**\n * Voice mode of the panel. The only owner of the voice state.\n * The voice model talks with the user and hands page actions to the agent through `run_task`.\n * The panel gives it reports from the agent; the session queues them so they never overlap a spoken answer.\n */\nimport type { MicState } from '../panel/microphone'\nimport {\n\tEXECUTE_JS,\n\tRUN_TASK,\n\ttype RealtimeSettings,\n\ttype ServerEvent,\n\ttype VoiceReport,\n\tcancelResponseCommand,\n\treportCommand,\n\ttoolResultCommands,\n} from './realtime-protocol'\n\nexport type VoiceState = 'off' | 'connecting' | 'listening' | 'speaking' | 'muted' | 'error'\nexport type VoiceError = 'no-key' | 'mic-denied' | 'mic-unsupported' | 'mic-busy' | 'connect-failed'\n\n/** Result given to the model when the agent is already busy. */\nexport const BUSY_OUTPUT =\n\t'O agente está ocupado com outra tarefa. Avise o usuário e não repita o pedido agora.'\n/** Result given to the model when the task was started. */\nexport const STARTED_OUTPUT = 'Tarefa iniciada no agente. Confirme ao usuário em uma frase.'\n\n/** The part of the microphone control the voice session uses. */\nexport interface VoiceMic {\n\treadonly state: MicState\n\treadonly stream: MediaStream | null\n\treadonly label: string\n\treadonly hardwareMuted: boolean\n\tenable(deviceId?: string): Promise<void>\n\tcycleInput(): Promise<boolean>\n\tsetMuted(muted: boolean): void\n\tdisable(): void\n}\n\n/** The part of the realtime client the voice session uses. */\nexport interface VoiceClient {\n\tconnect(options: {\n\t\tapiKey: string\n\t\tsettings: RealtimeSettings\n\t\ttrack: MediaStreamTrack\n\t}): Promise<void>\n\tsend(message: string): void\n\treplaceTrack(track: MediaStreamTrack | null): Promise<void>\n\tclose(): void\n}\n\nexport interface VoiceSessionOptions {\n\tapiKey?: string\n\tsettings: RealtimeSettings\n\tmic: VoiceMic\n\tcreateClient: (callbacks: {\n\t\tonEvent: (event: ServerEvent) => void\n\t\tonClosed: () => void\n\t}) => VoiceClient\n\t/** Starts a task in the agent. Returns false when the agent is busy. */\n\tonTask: (task: string) => boolean\n\t/**\n\t * Runs a script for the voice and returns the text the model receives. The panel refuses it with a\n\t * message while the agent is running.\n\t */\n\tonScript?: (script: string) => Promise<string>\n\tonChange: () => void\n}\n\n/** Errors about cancelling a response that is not running are harmless and must not end the call. */\nfunction isHarmlessCancelError(message: string): boolean {\n\treturn /cancel/i.test(message)\n}\n\nexport class VoiceSession {\n\t#options: VoiceSessionOptions\n\t#state: VoiceState = 'off'\n\t#error: VoiceError | null = null\n\t#client: VoiceClient | null = null\n\t#wanted = false\n\t/** Reports that arrived while the model was speaking. */\n\t#queue: VoiceReport[] = []\n\n\tconstructor(options: VoiceSessionOptions) {\n\t\tthis.#options = options\n\t}\n\n\tget state(): VoiceState {\n\t\treturn this.#state\n\t}\n\n\tget error(): VoiceError | null {\n\t\treturn this.#error\n\t}\n\n\tget muted(): boolean {\n\t\treturn this.#state === 'muted'\n\t}\n\n\t/** The user turned voice on: ask for the microphone, then open the realtime call. */\n\tasync enable(): Promise<void> {\n\t\tconst { apiKey, mic } = this.#options\n\t\tif (!apiKey) return this.#fail('no-key')\n\t\tthis.#wanted = true\n\t\tthis.#error = null\n\t\tthis.#set('connecting')\n\t\tawait mic.enable()\n\t\tif (!this.#wanted) return\n\t\tif (mic.state === 'denied') return this.#fail('mic-denied')\n\t\tif (mic.state === 'busy') return this.#fail('mic-busy')\n\t\tif (mic.state === 'unsupported') return this.#fail('mic-unsupported')\n\t\tconst track = mic.stream?.getAudioTracks()[0]\n\t\tif (!track) return this.#fail('mic-denied')\n\t\tconst client = this.#options.createClient({\n\t\t\tonEvent: (event) => this.#onEvent(event),\n\t\t\tonClosed: () => this.#fail('connect-failed'),\n\t\t})\n\t\tthis.#client = client\n\t\ttry {\n\t\t\tawait client.connect({ apiKey, settings: this.#options.settings, track })\n\t\t} catch {\n\t\t\tthis.#client = null\n\t\t\tthis.#fail('connect-failed')\n\t\t\treturn\n\t\t}\n\t\tif (this.#wanted && this.#state === 'connecting') this.#set('listening')\n\t}\n\n\t/**\n\t * Cycle to the next microphone while the call is open and send that track.\n\t * Returns false when there is no other device or the session is not live.\n\t */\n\tasync changeInput(): Promise<boolean> {\n\t\tif (this.#state !== 'listening' && this.#state !== 'speaking' && this.#state !== 'connecting') {\n\t\t\treturn false\n\t\t}\n\t\tconst changed = await this.#options.mic.cycleInput()\n\t\tif (!changed) return false\n\t\tconst track = this.#options.mic.stream?.getAudioTracks()[0]\n\t\tif (!track) {\n\t\t\tthis.#fail('mic-denied')\n\t\t\treturn false\n\t\t}\n\t\tawait this.#client?.replaceTrack(track)\n\t\tthis.#options.onChange()\n\t\treturn true\n\t}\n\n\t/** The user turned voice off: close the call and release the microphone. */\n\tdisable(): void {\n\t\tthis.#wanted = false\n\t\tthis.#queue = []\n\t\tthis.#client?.close()\n\t\tthis.#client = null\n\t\tthis.#options.mic.disable()\n\t\tthis.#error = null\n\t\tthis.#set('off')\n\t}\n\n\t/**\n\t * Mute stops the microphone and the audio sent, and stops the model if it is speaking.\n\t * The call stays open until the user goes back to text.\n\t */\n\tasync setMuted(muted: boolean): Promise<void> {\n\t\tif (muted) {\n\t\t\tif (this.#state === 'speaking') this.#client?.send(cancelResponseCommand())\n\t\t\tthis.#queue = []\n\t\t\tthis.#options.mic.setMuted(true)\n\t\t\tawait this.#client?.replaceTrack(null)\n\t\t\tthis.#set('muted')\n\t\t\treturn\n\t\t}\n\t\tthis.#options.mic.setMuted(false)\n\t\tawait this.#options.mic.enable()\n\t\tconst track = this.#options.mic.stream?.getAudioTracks()[0]\n\t\tif (track) await this.#client?.replaceTrack(track)\n\t\tthis.#set('listening')\n\t}\n\n\t/**\n\t * Gives the voice a report from the agent. It is spoken when the model is not speaking already.\n\t * Ignored while voice is off, muted or in error.\n\t */\n\treport(report: VoiceReport): void {\n\t\tif (!this.#client || (this.#state !== 'listening' && this.#state !== 'speaking')) return\n\t\tif (!report.text.trim()) return\n\t\tif (this.#state === 'speaking') {\n\t\t\tthis.#queue.push(report)\n\t\t\treturn\n\t\t}\n\t\tthis.#client.send(reportCommand(report))\n\t\tthis.#set('speaking')\n\t}\n\n\t#onEvent(event: ServerEvent): void {\n\t\tif (this.#state === 'off' || this.#state === 'muted') return\n\t\tswitch (event.type) {\n\t\t\tcase 'ready':\n\t\t\t\tif (this.#state === 'connecting') this.#set('listening')\n\t\t\t\treturn\n\t\t\tcase 'transcript':\n\t\t\t\t// What the user says is conversation: the voice model answers it. Only run_task reaches the agent.\n\t\t\t\treturn\n\t\t\tcase 'speech_started':\n\t\t\t\t// The server cuts the model's voice when the user talks. The state changes when the response ends.\n\t\t\t\treturn\n\t\t\tcase 'response_started':\n\t\t\t\tthis.#set('speaking')\n\t\t\t\treturn\n\t\t\tcase 'response_done':\n\t\t\t\tthis.#flushQueue()\n\t\t\t\treturn\n\t\t\tcase 'tool_call':\n\t\t\t\tthis.#handleToolCall(event.name, event.callId, event.args)\n\t\t\t\treturn\n\t\t\tcase 'error':\n\t\t\t\tif (isHarmlessCancelError(event.message)) return\n\t\t\t\tthis.#fail('connect-failed')\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\treturn\n\t\t}\n\t}\n\n\t#handleToolCall(name: string, callId: string, args: Record<string, unknown>): void {\n\t\tif (name === RUN_TASK) {\n\t\t\tconst task = typeof args.task === 'string' ? args.task.trim() : ''\n\t\t\tif (!task) return\n\t\t\tthis.#answer(callId, this.#options.onTask(task) ? STARTED_OUTPUT : BUSY_OUTPUT)\n\t\t\treturn\n\t\t}\n\t\tif (name === EXECUTE_JS) {\n\t\t\tconst script = typeof args.script === 'string' ? args.script : ''\n\t\t\tif (!this.#options.onScript) {\n\t\t\t\tthis.#answer(callId, 'Running scripts is not available in this session.')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (!script) {\n\t\t\t\tthis.#answer(callId, 'No script was given.')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvoid this.#runScript(callId, script)\n\t\t}\n\t}\n\n\t/** Sends the result of a tool call back to the model, then the model speaks again. */\n\t#answer(callId: string, output: string): void {\n\t\tfor (const message of toolResultCommands(callId, output)) this.#client?.send(message)\n\t\tthis.#set('speaking')\n\t}\n\n\tasync #runScript(callId: string, script: string): Promise<void> {\n\t\tconst client = this.#client\n\t\tconst run = this.#options.onScript\n\t\tif (!client || !run) return\n\t\tlet output: string\n\t\ttry {\n\t\t\toutput = await run(script)\n\t\t} catch (error) {\n\t\t\toutput = `The script failed: ${error instanceof Error ? error.message : 'unknown error'}`\n\t\t}\n\t\t// The call may have been turned off while the script ran: then there is no one to answer.\n\t\tif (this.#client !== client) return\n\t\tthis.#answer(callId, output)\n\t}\n\n\t#flushQueue(): void {\n\t\tif (this.#state !== 'speaking') return\n\t\tconst next = this.#queue.shift()\n\t\tif (next) {\n\t\t\tthis.#client?.send(reportCommand(next))\n\t\t\treturn\n\t\t}\n\t\tthis.#set('listening')\n\t}\n\n\t#fail(error: VoiceError): void {\n\t\tthis.#error = error\n\t\tthis.#wanted = false\n\t\tthis.#queue = []\n\t\tthis.#client?.close()\n\t\tthis.#client = null\n\t\tthis.#options.mic.disable()\n\t\tthis.#set('error')\n\t}\n\n\t#set(state: VoiceState): void {\n\t\tif (this.#state === state) return\n\t\tthis.#state = state\n\t\tthis.#options.onChange()\n\t}\n}\n","export function truncate(text: string, maxLength: number): string {\n\tif (text.length > maxLength) {\n\t\treturn text.substring(0, maxLength) + '...'\n\t}\n\treturn text\n}\n\n/**\n * Escape HTML special characters to prevent XSS and rendering issues\n */\nexport function escapeHtml(text: string): string {\n\treturn text\n\t\t.replace(/&/g, '&')\n\t\t.replace(/</g, '<')\n\t\t.replace(/>/g, '>')\n\t\t.replace(/\"/g, '"')\n\t\t.replace(/'/g, ''')\n}\n","/* Page Agent panel. Design from the modern renderer; dark by default, light when the system asks for it. */\n\n.wrapper {\n\toverscroll-behavior: contain;\n\t--pa-fg: #f4f3ee;\n\t--pa-muted: #aaa9a1;\n\t--pa-accent: #fa8d45;\n\t--pa-surface: #191918;\n\t--pa-raised: #20201e;\n\t--pa-line: rgba(244, 243, 238, 0.12);\n\t--pa-ok: #b1d8b8;\n\t--pa-warn: #ead39a;\n\t--pa-err: #ffb9a9;\n\t--pa-radius: 18px;\n\t--pa-c-keyword: #fa8d45;\n\t--pa-c-string: #b1d8b8;\n\t--pa-c-number: #ead39a;\n\t--pa-c-key: #9ec5f0;\n\t--pa-c-bool: #ffb9a9;\n\t--pa-c-comment: #7d7c75;\n\t--pa-c-name: #f4f3ee;\n\t--pa-c-punct: #aaa9a1;\n\n\tposition: fixed;\n\tbottom: 100px;\n\tleft: 0;\n\tright: 0;\n\tmargin: 0 auto;\n\ttransform: translateY(20px);\n\topacity: 0;\n\tz-index: 2147483642;\n\tbox-sizing: border-box;\n\t/* 100% of the fixed containing block — avoids the classic 100vw horizontal overflow on mobile. */\n\twidth: min(414px, calc(100% - 24px));\n\tmax-height: min(640px, calc(100svh - 120px));\n\tdisplay: none;\n\tflex-direction: column;\n\toverflow: hidden;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: var(--pa-radius);\n\tbackground: var(--pa-surface);\n\tcolor: var(--pa-fg);\n\tbox-shadow: 0 16px 40px rgba(0, 0, 0, 0.35);\n\tfont:\n\t\t13px/1.4 system-ui,\n\t\t-apple-system,\n\t\t'Segoe UI',\n\t\tsans-serif;\n\ttransition:\n\t\topacity 0.2s ease,\n\t\ttransform 0.2s ease,\n\t\tbox-shadow 0.3s ease,\n\t\twidth 0.2s ease;\n}\n\n@media (min-width: 481px) {\n\t.wrapper[data-mode='skills-studio'] {\n\t\twidth: min(560px, calc(100vw - 24px));\n\t}\n}\n\n.wrapper *,\n.wrapper *::before,\n.wrapper *::after {\n\tbox-sizing: border-box;\n}\n\n.wrapper[data-state='running'] {\n\tbox-shadow:\n\t\t0 0 0 1px color-mix(in srgb, var(--pa-accent) 55%, transparent),\n\t\t0 16px 40px rgba(0, 0, 0, 0.35);\n}\n\n.wrapper[data-state='waiting'] {\n\tbox-shadow:\n\t\t0 0 0 1px color-mix(in srgb, var(--pa-accent) 80%, transparent),\n\t\t0 16px 40px rgba(0, 0, 0, 0.35);\n}\n\n.wrapper.collapsed .feedWrap {\n\tdisplay: none;\n}\n\n/* Follow bar (mobile peek strip). Hidden unless data-follow=\"bar\" on narrow viewports. */\n.followBar {\n\tdisplay: none;\n\tflex: none;\n\talign-items: center;\n\tgap: 8px;\n\tmin-height: 56px;\n\tpadding: 8px 10px;\n\tpadding-bottom: max(8px, env(safe-area-inset-bottom, 0px));\n}\n\n.followBarBody {\n\tflex: 1;\n\tmin-width: 0;\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 10px;\n\tpadding: 0;\n\tborder: 0;\n\tbackground: transparent;\n\tcolor: inherit;\n\tfont: inherit;\n\ttext-align: left;\n\tcursor: pointer;\n}\n\n.followBarStatus {\n\tflex: 1;\n\tmin-width: 0;\n\tfont-size: 13px;\n\tfont-weight: 600;\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n\n.followBarLens {\n\twidth: 28px;\n\theight: 28px;\n}\n\n.followBarLens svg {\n\twidth: 14px;\n\theight: 14px;\n}\n\n.voiceActions {\n\tflex: none;\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 8px;\n}\n\n/* Voice stop is for the mobile expanded voice layout; desktop keeps Stop in the header. */\n.voiceActions [data-role='voice-stop'] {\n\tdisplay: none;\n}\n\n[hidden] {\n\tdisplay: none !important;\n}\n\n/* Header */\n\n.header {\n\tflex: none;\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 10px;\n\theight: 52px;\n\tpadding: 0 12px 0 14px;\n\tborder-bottom: 1px solid var(--pa-line);\n\tcursor: grab;\n\ttouch-action: none;\n\tuser-select: none;\n}\n\n.brand:has(img) {\n\tbackground: transparent;\n}\n\n.brand img {\n\twidth: 100%;\n\theight: 100%;\n\tobject-fit: contain;\n\tborder-radius: inherit;\n}\n\n.brand {\n\tflex: none;\n\twidth: 30px;\n\theight: 30px;\n\tdisplay: grid;\n\tplace-items: center;\n\tborder-radius: 10px;\n\tbackground: var(--pa-accent);\n\tcolor: #20150e;\n\tfont-weight: 800;\n\tfont-size: 16px;\n}\n\n.titleBlock {\n\tflex: 1;\n\tmin-width: 0;\n\tdisplay: flex;\n\tflex-direction: column;\n}\n\n.title {\n\tfont-size: 12px;\n\tfont-weight: 650;\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n\n.status {\n\tfont-size: 10.5px;\n\tcolor: var(--pa-muted);\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n\n.controls {\n\tflex: none;\n\tdisplay: flex;\n\tgap: 2px;\n}\n\n.iconButton {\n\tdisplay: grid;\n\tplace-items: center;\n\tmin-width: 28px;\n\tmin-height: 28px;\n\tpadding: 0;\n\tborder: 0;\n\tborder-radius: 8px;\n\tbackground: transparent;\n\tcolor: inherit;\n\tfont-size: 14px;\n\tcursor: pointer;\n}\n\n.iconButton:hover {\n\tbackground: rgba(255, 255, 255, 0.08);\n}\n\n.stopButton {\n\tcolor: #ff8a80;\n}\n\n/* Feed */\n\n.feedWrap {\n\tposition: relative;\n\tflex: 1;\n\tdisplay: flex;\n\tflex-direction: column;\n\tmin-height: 120px;\n\tmax-height: 380px;\n}\n\n.feed {\n\tposition: relative;\n\tflex: 1;\n\tmin-height: 0;\n\toverflow-y: auto;\n\toverscroll-behavior: contain;\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 10px;\n\tpadding: 14px 18px 14px 14px;\n\tscroll-behavior: auto;\n\tscrollbar-width: thin;\n\tscrollbar-color: color-mix(in srgb, var(--pa-muted) 40%, transparent) transparent;\n}\n\n/* Right-edge rail: viewport thumb plus one marker per turn, question and result. Click a marker to jump. */\n.rail {\n\tposition: absolute;\n\ttop: 8px;\n\tbottom: 8px;\n\tright: 0;\n\twidth: 16px;\n\topacity: 0.55;\n\ttransition: opacity 0.2s ease;\n}\n\n.rail::before {\n\tcontent: '';\n\tposition: absolute;\n\ttop: 0;\n\tbottom: 0;\n\tright: 6px;\n\twidth: 2px;\n\tborder-radius: 2px;\n\tbackground: var(--pa-line);\n}\n\n.feedWrap:hover .rail,\n.feedWrap:focus-within .rail {\n\topacity: 1;\n}\n\n.feedWrap:hover .rail,\n.feedWrap:focus-within .rail {\n\topacity: 1;\n}\n\n.railThumb {\n\tposition: absolute;\n\tright: 6px;\n\twidth: 2px;\n\tborder-radius: 2px;\n\tbackground: var(--pa-muted);\n\ttransition: top 0.12s ease;\n}\n\n.railMark {\n\tposition: absolute;\n\tright: 2px;\n\theight: 3px;\n\twidth: 10px;\n\tmargin-top: -1px;\n\tpadding: 0;\n\tborder: 0;\n\tborder-radius: 3px;\n\tbackground: var(--pa-muted);\n\topacity: 0.7;\n\tcursor: pointer;\n\ttransition:\n\t\twidth 0.15s ease,\n\t\topacity 0.15s ease,\n\t\tbackground-color 0.15s ease;\n}\n\n.railMark[data-kind='turn'] {\n\twidth: 14px;\n}\n\n.railMark[data-kind='question'],\n.railMark[data-kind='result'] {\n\twidth: 6px;\n\theight: 6px;\n\tright: 4px;\n\tmargin-top: -2px;\n\tborder-radius: 50%;\n}\n\n.railMark[data-kind='question'] {\n\tbackground: var(--pa-accent);\n\topacity: 1;\n}\n\n.railMark[data-kind='result'] {\n\tbackground: var(--pa-ok);\n\topacity: 1;\n}\n\n.railMark[data-active='true'] {\n\twidth: 18px;\n\topacity: 1;\n\tbackground: var(--pa-fg);\n}\n\n.railMark[data-pinned='true'] {\n\tbackground: var(--pa-accent);\n\topacity: 1;\n}\n\n.railMark:hover {\n\twidth: 18px;\n\topacity: 1;\n}\n\n.railMark[data-kind='question'] {\n\tbackground: var(--pa-accent);\n}\n\n.railMark[data-kind='turn'] {\n\tbackground: var(--pa-muted);\n}\n\n.railMark[data-kind='result'] {\n\tbackground: var(--pa-ok);\n}\n\n/* Divider between finished tasks and the current one. */\n.divider {\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 10px;\n\tmargin: 6px 0;\n\tcolor: var(--pa-muted);\n\tfont-size: 10.5px;\n\ttext-transform: uppercase;\n\tletter-spacing: 0.06em;\n}\n\n.divider::before,\n.divider::after {\n\tcontent: '';\n\tflex: 1;\n\theight: 1px;\n\tbackground: var(--pa-line);\n}\n\n/* Hover card for a rail tick. */\n.peek {\n\tposition: absolute;\n\tright: 26px;\n\tz-index: 6;\n\twidth: min(260px, calc(100% - 56px));\n\tpadding: 10px 12px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 12px;\n\tbackground: var(--pa-surface);\n\tbox-shadow: 0 12px 30px rgba(0, 0, 0, 0.3);\n\tanimation: peekIn 0.16s ease-out both;\n}\n\n.peek[hidden] {\n\tdisplay: none !important;\n}\n\n@keyframes peekIn {\n\tfrom {\n\t\topacity: 0;\n\t\ttransform: translateX(6px);\n\t}\n\tto {\n\t\topacity: 1;\n\t\ttransform: none;\n\t}\n}\n\n.peekHead {\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 8px;\n}\n\n.peekHead strong {\n\tflex: 1;\n\tmin-width: 0;\n\tfont-size: 12px;\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n\n.peekText {\n\tmargin: 6px 0 0;\n\tmax-height: 4.2em;\n\toverflow: hidden;\n\tcolor: var(--pa-muted);\n\tfont-size: 11.5px;\n\tline-height: 1.4;\n\twhite-space: pre-wrap;\n\toverflow-wrap: anywhere;\n\t-webkit-mask-image: linear-gradient(to bottom, #000 60%, transparent);\n\tmask-image: linear-gradient(to bottom, #000 60%, transparent);\n}\n\n.pin {\n\tflex: none;\n\tdisplay: grid;\n\tplace-items: center;\n\twidth: 26px;\n\theight: 26px;\n\tpadding: 0;\n\tborder: 0;\n\tborder-radius: 7px;\n\tbackground: transparent;\n\tcolor: var(--pa-muted);\n\tcursor: pointer;\n}\n\n.pin:hover {\n\tbackground: rgba(255, 255, 255, 0.08);\n\tcolor: var(--pa-fg);\n}\n\n.pin[aria-pressed='true'] {\n\tcolor: var(--pa-accent);\n}\n\n.pin[aria-pressed='true'] svg {\n\tfill: currentColor;\n}\n\n.pin svg {\n\twidth: 14px;\n\theight: 14px;\n}\n\n/* Jump pill: appears while reading above, shows how many new events arrived. */\n.jump {\n\tposition: absolute;\n\tleft: 50%;\n\tbottom: 10px;\n\ttransform: translateX(-50%);\n\tdisplay: inline-flex;\n\talign-items: center;\n\tgap: 6px;\n\tpadding: 6px 12px 6px 9px;\n\tborder: 0;\n\tborder-radius: 999px;\n\tbackground: var(--pa-fg);\n\tcolor: var(--pa-surface);\n\tfont-size: 11px;\n\tfont-weight: 600;\n\twhite-space: nowrap;\n\tbox-shadow: 0 6px 18px rgba(0, 0, 0, 0.25);\n\tcursor: pointer;\n\tanimation: jumpIn 0.22s ease-out both;\n}\n\n.jump svg {\n\twidth: 14px;\n\theight: 14px;\n}\n\n.jump[hidden] {\n\tdisplay: none !important;\n}\n\n@keyframes jumpIn {\n\tfrom {\n\t\topacity: 0;\n\t\ttransform: translate(-50%, 6px);\n\t}\n\tto {\n\t\topacity: 1;\n\t\ttransform: translate(-50%, 0);\n\t}\n}\n\n.empty {\n\tmargin: auto;\n\tpadding: 24px 8px;\n\ttext-align: center;\n\tcolor: var(--pa-muted);\n\tfont-size: 13px;\n}\n\n.enter {\n\tanimation: enter 0.2s ease-out both;\n}\n\n@keyframes enter {\n\tfrom {\n\t\topacity: 0;\n\t\ttransform: translateY(4px);\n\t}\n\tto {\n\t\topacity: 1;\n\t\ttransform: none;\n\t}\n}\n\n.bubble {\n\talign-self: flex-end;\n\tmax-width: 85%;\n\tpadding: 8px 12px;\n\tborder-radius: 14px 14px 4px 14px;\n\tbackground: var(--pa-raised);\n\twhite-space: pre-wrap;\n\toverflow-wrap: anywhere;\n}\n\n.line {\n\tfont-size: 12px;\n\tcolor: var(--pa-muted);\n\twhite-space: pre-wrap;\n\toverflow-wrap: anywhere;\n}\n\n.reflection {\n\tpadding-left: 8px;\n\tborder-left: 2px solid var(--pa-line);\n}\n\n.observation {\n\tfont-size: 12px;\n}\n\n.warning {\n\tcolor: var(--pa-warn);\n}\n\n.live {\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 8px;\n\tcolor: var(--pa-accent);\n}\n\n.live::before {\n\tcontent: '';\n\tflex: none;\n\twidth: 8px;\n\theight: 8px;\n\tborder-radius: 50%;\n\tbackground: var(--pa-accent);\n\tanimation: pulse 1.6s ease-in-out infinite;\n}\n\n@keyframes pulse {\n\t0%,\n\t100% {\n\t\topacity: 0.35;\n\t}\n\t50% {\n\t\topacity: 1;\n\t}\n}\n\n/* Tool cards */\n\n.tool {\n\tpadding: 9px 11px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 11px;\n\tbackground: var(--pa-raised);\n\tfont-size: 12px;\n}\n\n.tool[data-status='running'] {\n\tborder-color: color-mix(in srgb, var(--pa-accent) 50%, transparent);\n}\n\n.tool[data-status='error'] {\n\tborder-color: color-mix(in srgb, var(--pa-err) 55%, transparent);\n\tcolor: var(--pa-err);\n}\n\n.toolHead {\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 8px;\n}\n\n.toolDot {\n\tflex: none;\n\twidth: 7px;\n\theight: 7px;\n\tborder-radius: 50%;\n\tbackground: var(--pa-ok);\n}\n\n.toolLabel {\n\tfont-weight: 600;\n\toverflow-wrap: anywhere;\n}\n\n.toolDetail {\n\tmargin-top: 5px;\n\tpadding-left: 15px;\n\tcolor: var(--pa-muted);\n\twhite-space: pre-wrap;\n\toverflow-wrap: anywhere;\n}\n\n.spinner {\n\tflex: none;\n\twidth: 11px;\n\theight: 11px;\n\tborder: 1.5px solid var(--pa-accent);\n\tborder-right-color: transparent;\n\tborder-radius: 50%;\n\tanimation: spin 0.9s linear infinite;\n}\n\n@keyframes spin {\n\tto {\n\t\ttransform: rotate(360deg);\n\t}\n}\n\n/* Question and result cards */\n\n.question {\n\tpadding: 2px 0 2px 12px;\n\tborder-left: 2px solid var(--pa-accent);\n}\n\n.questionTag {\n\tdisplay: block;\n\tmargin-bottom: 4px;\n\tcolor: var(--pa-accent);\n\tfont-size: 11px;\n\tfont-weight: 650;\n}\n\n.questionText {\n\tmargin: 0;\n\tfont-size: 14px;\n}\n\n.result {\n\tpadding: 11px 12px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 12px;\n\tbackground: var(--pa-raised);\n\tfont-size: 12px;\n}\n\n.result strong {\n\tdisplay: block;\n\tmargin-bottom: 4px;\n\tfont-size: 13px;\n}\n\n.result[data-kind='done'] strong {\n\tcolor: var(--pa-ok);\n}\n\n.result[data-kind='notDone'] strong,\n.result[data-kind='stopped'] strong {\n\tcolor: var(--pa-warn);\n}\n\n.result[data-kind='error'] strong {\n\tcolor: var(--pa-err);\n}\n\n.resultText {\n\tcolor: var(--pa-muted);\n\twhite-space: pre-wrap;\n\toverflow-wrap: anywhere;\n}\n\n/* Composer (text input and voice toggle share this area) */\n\n.composer {\n\tflex: none;\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 6px;\n\tpadding: 10px 12px 12px;\n\tborder-top: 1px solid var(--pa-line);\n}\n\n.answerContext {\n\tfont-size: 11px;\n\tcolor: var(--pa-accent);\n\tfont-weight: 650;\n}\n\n.box {\n\tdisplay: flex;\n\talign-items: flex-end;\n\tgap: 6px;\n\tpadding: 6px 6px 6px 12px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 16px;\n\tbackground: var(--pa-raised);\n}\n\n.box:focus-within {\n\toutline: 2px solid var(--pa-accent);\n\toutline-offset: 2px;\n}\n\n.box textarea {\n\tflex: 1;\n\tmin-width: 0;\n\tmin-height: 28px;\n\tmax-height: 120px;\n\tresize: none;\n\tborder: 0;\n\toutline: none;\n\tbackground: transparent;\n\tcolor: inherit;\n\tfont: inherit;\n\tfont-size: 13px;\n\tline-height: 1.4;\n\tpadding: 5px 0;\n}\n\n.box textarea:disabled {\n\topacity: 0.6;\n}\n\n.box textarea::placeholder {\n\tcolor: var(--pa-muted);\n}\n\n.actions {\n\tflex: none;\n\tdisplay: flex;\n\tgap: 4px;\n}\n\n.attachList {\n\tdisplay: flex;\n\tflex-wrap: wrap;\n\tgap: 6px;\n\talign-items: center;\n}\n\n.attachChip {\n\tdisplay: inline-flex;\n\talign-items: center;\n\tgap: 4px;\n\tmax-width: 100%;\n\tpadding: 2px 4px 2px 8px;\n\tborder-radius: 999px;\n\tbackground: rgba(255, 255, 255, 0.08);\n\tfont-size: 12px;\n\tline-height: 1.3;\n}\n\n.attachName {\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\twhite-space: nowrap;\n\tmax-width: 180px;\n}\n\n.attachRemove {\n\tdisplay: grid;\n\tplace-items: center;\n\tpadding: 0;\n\twidth: 20px;\n\theight: 20px;\n\tborder: 0;\n\tborder-radius: 50%;\n\tbackground: transparent;\n\tcolor: inherit;\n\tcursor: pointer;\n\topacity: 0.7;\n}\n\n.attachRemove:hover {\n\topacity: 1;\n\tbackground: rgba(255, 255, 255, 0.1);\n}\n\n.attachRemove svg {\n\twidth: 12px;\n\theight: 12px;\n}\n\n.attachError {\n\tcolor: #f5a3a3;\n\tfont-size: 12px;\n\tline-height: 1.3;\n}\n\n.roundButton {\n\tdisplay: grid;\n\tplace-items: center;\n\tpadding: 0;\n\twidth: 30px;\n\theight: 30px;\n\tborder: 0;\n\tborder-radius: 50%;\n\tbackground: rgba(255, 255, 255, 0.08);\n\tcolor: inherit;\n\tfont-size: 14px;\n\tcursor: pointer;\n}\n\n.roundButton[aria-pressed='true'] {\n\tbackground: color-mix(in srgb, var(--pa-accent) 35%, transparent);\n}\n\n.send {\n\tbackground: var(--pa-accent);\n\tcolor: #20150e;\n\tfont-weight: 800;\n}\n\n.roundButton:disabled {\n\topacity: 0.4;\n\tcursor: not-allowed;\n}\n\n/* Skills Studio (replaces feed + composer while authoring skills) */\n\n.studio {\n\tflex: 1;\n\tmin-height: 0;\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 10px;\n\tpadding: 10px 12px 12px;\n\tborder-top: 1px solid var(--pa-line);\n}\n\n.studioHeader {\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: space-between;\n\tgap: 8px;\n}\n\n.studioTitle {\n\tfont-size: 14px;\n\tfont-weight: 700;\n}\n\n.studioTabs {\n\tdisplay: flex;\n\tgap: 4px;\n}\n\n.studioTab {\n\tflex: 1;\n\tpadding: 6px 8px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 10px;\n\tbackground: transparent;\n\tcolor: inherit;\n\tfont-size: 12px;\n\tfont-weight: 600;\n\tcursor: pointer;\n}\n\n.studioTab[aria-selected='true'] {\n\tbackground: color-mix(in srgb, var(--pa-accent) 28%, transparent);\n\tborder-color: color-mix(in srgb, var(--pa-accent) 55%, var(--pa-line));\n}\n\n.studioBody {\n\tflex: 1;\n\tmin-height: 0;\n\toverflow: auto;\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 8px;\n}\n\n.studioHint {\n\tmargin: 0;\n\tcolor: var(--pa-muted);\n\tfont-size: 12px;\n\tline-height: 1.4;\n}\n\n.studioToolbar {\n\tdisplay: flex;\n\tflex-wrap: wrap;\n\tgap: 6px;\n}\n\n.studioToolButton {\n\tflex: none;\n\tpadding: 6px 10px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 10px;\n\tbackground: var(--pa-raised);\n\tcolor: inherit;\n\tfont-size: 12px;\n\tfont-weight: 600;\n\tcursor: pointer;\n}\n\n.studioToolButton:disabled {\n\topacity: 0.45;\n\tcursor: default;\n}\n\n.studioToolButton[data-variant='accent'] {\n\tbackground: color-mix(in srgb, var(--pa-accent) 28%, transparent);\n\tborder-color: color-mix(in srgb, var(--pa-accent) 55%, var(--pa-line));\n}\n\n.studioToolButton[data-variant='danger'] {\n\tcolor: var(--pa-err);\n}\n\n.studioStatus {\n\tmargin: 0;\n\tcolor: var(--pa-muted);\n\tfont-size: 11px;\n\tline-height: 1.4;\n\twhite-space: pre-wrap;\n}\n\n.studioStatus[data-tone='ok'] {\n\tcolor: var(--pa-ok);\n}\n\n.studioStatus[data-tone='warn'] {\n\tcolor: var(--pa-warn);\n}\n\n.studioStatus[data-tone='err'] {\n\tcolor: var(--pa-err);\n}\n\n.studioAsk {\n\twidth: 100%;\n\tmin-height: 72px;\n\tresize: vertical;\n\tpadding: 8px 10px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 12px;\n\tbackground: var(--pa-raised);\n\tcolor: inherit;\n\tfont: inherit;\n\tline-height: 1.4;\n}\n\n.studioAsk:focus {\n\toutline: 2px solid var(--pa-accent);\n\toutline-offset: 2px;\n}\n\n.studioSteps,\n.studioCatalog {\n\tlist-style: none;\n\tmargin: 0;\n\tpadding: 0;\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 6px;\n\tfont-size: 12px;\n\tline-height: 1.45;\n}\n\n.studioStep,\n.studioCatalogRow {\n\tdisplay: flex;\n\talign-items: flex-start;\n\tgap: 8px;\n\tpadding: 8px 10px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 10px;\n\tbackground: rgba(255, 255, 255, 0.04);\n}\n\n.studioCatalogRow {\n\tpadding: 6px 8px;\n\tgap: 6px;\n}\n\n.studioWatchers {\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 6px;\n\tpadding: 8px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 12px;\n\tbackground: color-mix(in srgb, var(--pa-raised) 85%, transparent);\n}\n\n.studioWatchersHead {\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: space-between;\n\tgap: 8px;\n}\n\n.studioWatchersTitle {\n\tfont-size: 11px;\n\tfont-weight: 700;\n\ttext-transform: uppercase;\n\tletter-spacing: 0.04em;\n\tcolor: var(--pa-muted);\n}\n\n.studioWatchersEmpty {\n\tmargin: 0;\n\tcolor: var(--pa-muted);\n\tfont-size: 11px;\n}\n\n.studioWatchersList {\n\tlist-style: none;\n\tmargin: 0;\n\tpadding: 0;\n\tdisplay: flex;\n\tflex-wrap: wrap;\n\tgap: 6px;\n}\n\n.studioWatcherChip {\n\tdisplay: inline-flex;\n\talign-items: center;\n\tgap: 6px;\n\tmax-width: 100%;\n\tpadding: 4px 6px 4px 8px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 999px;\n\tbackground: rgba(255, 255, 255, 0.06);\n\tfont-size: 11px;\n\tline-height: 1.3;\n}\n\n.studioWatcherLabel {\n\tmin-width: 0;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\twhite-space: nowrap;\n\tfont-weight: 600;\n}\n\n.studioWatcherMeta {\n\tcolor: var(--pa-muted);\n\tfont-size: 10px;\n\ttext-transform: uppercase;\n\tletter-spacing: 0.03em;\n}\n\n.studioWatcherChip button {\n\tpadding: 2px 8px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 999px;\n\tbackground: transparent;\n\tcolor: inherit;\n\tfont-size: 10px;\n\tfont-weight: 600;\n\tcursor: pointer;\n}\n\n.studioWatcherChip button:disabled {\n\topacity: 0.45;\n\tcursor: default;\n}\n\n.studioStepBody,\n.studioCatalogBody {\n\tflex: 1;\n\tmin-width: 0;\n}\n\n.studioStepKind {\n\tdisplay: inline-block;\n\tmargin-right: 6px;\n\tpadding: 1px 6px;\n\tborder-radius: 999px;\n\tbackground: color-mix(in srgb, var(--pa-accent) 22%, transparent);\n\tfont-size: 10px;\n\tfont-weight: 700;\n\ttext-transform: uppercase;\n\tletter-spacing: 0.04em;\n}\n\n.studioStepMeta,\n.studioCatalogMeta {\n\tcolor: var(--pa-muted);\n\tfont-size: 11px;\n}\n\n.studioStepActions,\n.studioCatalogActions {\n\tdisplay: flex;\n\tflex-wrap: wrap;\n\tgap: 4px;\n}\n\n.studioStepActions button,\n.studioCatalogActions button {\n\tpadding: 4px 8px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 8px;\n\tbackground: transparent;\n\tcolor: inherit;\n\tfont-size: 11px;\n\tcursor: pointer;\n}\n\n.studioCatalogActions button[data-variant='accent'] {\n\tbackground: color-mix(in srgb, var(--pa-accent) 28%, transparent);\n\tborder-color: color-mix(in srgb, var(--pa-accent) 55%, var(--pa-line));\n\tfont-weight: 700;\n}\n\n.studioStepActions button:disabled,\n.studioCatalogActions button:disabled {\n\topacity: 0.45;\n\tcursor: default;\n}\n\n@media (min-width: 768px) {\n\t.wrapper[data-mode='skills-studio'] .studioToolbar {\n\t\tgap: 8px;\n\t}\n\n\t.wrapper[data-mode='skills-studio'] .studioToolButton {\n\t\tpadding: 7px 12px;\n\t}\n\n\t.wrapper[data-mode='skills-studio'] .studioCatalog {\n\t\tgap: 5px;\n\t}\n}\n\n.studioPreviewLabel {\n\tmargin: 0;\n\tfont-size: 11px;\n\tfont-weight: 700;\n\tcolor: var(--pa-muted);\n\ttext-transform: uppercase;\n\tletter-spacing: 0.04em;\n}\n\n.studioPreview {\n\tmargin: 0;\n\tmax-height: 180px;\n\toverflow: auto;\n\tpadding: 8px 10px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 10px;\n\tbackground: var(--pa-raised);\n\tfont:\n\t\t11px/1.45 ui-monospace,\n\t\tSFMono-Regular,\n\t\tMenlo,\n\t\tConsolas,\n\t\tmonospace;\n\twhite-space: pre-wrap;\n\tword-break: break-word;\n}\n\n/* Voice stage (replaces the composer while voice is selected) */\n\n.voice {\n\tflex: none;\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 10px;\n\tpadding: 12px 12px;\n\tborder-top: 1px solid var(--pa-line);\n}\n\n.voiceMeta {\n\tflex: 1;\n\tmin-width: 0;\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 2px;\n}\n\n.lens {\n\tflex: none;\n\tdisplay: grid;\n\tplace-items: center;\n\twidth: 30px;\n\theight: 30px;\n\tborder-radius: 50%;\n\tcolor: var(--pa-muted);\n\tbackground: var(--pa-raised);\n\tborder: 1px solid var(--pa-line);\n\ttransition:\n\t\tborder-color 0.3s ease,\n\t\tcolor 0.3s ease,\n\t\topacity 0.3s ease;\n}\n\n.lens svg {\n\twidth: 15px;\n\theight: 15px;\n}\n\n/* Microphone state: active breathes in accent, muted is dimmed, blocked or unavailable is red. */\n.lens[data-state='active'] {\n\tcolor: var(--pa-accent);\n\tborder-color: var(--pa-accent);\n\tanimation: breathe 2.8s ease-in-out infinite;\n}\n\n.lens[data-state='muted'] {\n\topacity: 0.5;\n}\n\n.lens[data-state='denied'],\n.lens[data-state='unsupported'] {\n\tcolor: var(--pa-err);\n\tborder-color: var(--pa-err);\n}\n\n@keyframes breathe {\n\t50% {\n\t\ttransform: scale(1.06);\n\t}\n}\n\n.voiceText {\n\tmin-width: 0;\n\tfont-size: 12px;\n\tfont-weight: 600;\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n\n.micDevice {\n\tmin-width: 0;\n\tmax-width: 100%;\n\talign-self: start;\n\tpadding: 0;\n\tborder: 0;\n\tborder-radius: 4px;\n\tbackground: transparent;\n\tcolor: var(--pa-muted);\n\tfont: inherit;\n\tfont-size: 10.5px;\n\tfont-weight: 500;\n\tline-height: 1.3;\n\ttext-align: left;\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\tcursor: pointer;\n}\n\n.micDevice:disabled {\n\tcursor: default;\n\topacity: 0.7;\n}\n\n.micDevice:not(:disabled):hover {\n\tcolor: var(--pa-accent);\n}\n\n.textButton {\n\tflex: none;\n\twhite-space: nowrap;\n\tpadding: 8px 10px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 9px;\n\tbackground: var(--pa-raised);\n\tcolor: inherit;\n\tfont-size: 12px;\n\tcursor: pointer;\n}\n\n/* Pressed toggles (agent cursor visible, microphone on) read as on: tinted background and accent icon. */\n.iconButton[aria-pressed='true'] {\n\tbackground: color-mix(in srgb, var(--pa-accent) 22%, transparent);\n\tcolor: var(--pa-accent);\n}\n\n/* Floating button shown while the panel is closed. Snaps to a corner after dragging. */\n.fab {\n\tposition: fixed;\n\tz-index: 2147483642;\n\tdisplay: grid;\n\tplace-items: center;\n\twidth: 46px;\n\theight: 46px;\n\tpadding: 0;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 50%;\n\tbackground: var(--pa-surface);\n\tcolor: var(--pa-accent);\n\tbox-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);\n\tcursor: grab;\n\ttouch-action: none;\n\tuser-select: none;\n\ttransition:\n\t\ttransform 0.2s ease,\n\t\tbox-shadow 0.2s ease;\n}\n\n.fab:hover {\n\ttransform: scale(1.06);\n\tbox-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);\n}\n\n.fab[hidden] {\n\tdisplay: none !important;\n}\n\n.fab img {\n\twidth: 26px;\n\theight: 26px;\n\tobject-fit: contain;\n\tborder-radius: 6px;\n\tpointer-events: none;\n}\n\n.fab svg {\n\twidth: 20px;\n\theight: 20px;\n\tpointer-events: none;\n}\n\n.fabLeft::after {\n\tleft: 0;\n\tright: auto;\n}\n\n/* Icon hints: a short label on hover or keyboard focus. */\n.tip:not(.fab) {\n\tposition: relative;\n}\n\n.tip::after {\n\tcontent: attr(data-tip);\n\tposition: absolute;\n\ttop: calc(100% + 6px);\n\tright: 0;\n\tz-index: 10;\n\tpadding: 4px 8px;\n\tborder-radius: 6px;\n\tbackground: var(--pa-fg);\n\tcolor: var(--pa-surface);\n\tfont-size: 11px;\n\tfont-weight: 550;\n\tline-height: 1.3;\n\twhite-space: nowrap;\n\tpointer-events: none;\n\topacity: 0;\n\ttransition: opacity 0.15s ease;\n}\n\n.tipUp::after {\n\ttop: auto;\n\tbottom: calc(100% + 6px);\n}\n\n.tip:hover::after,\n.tip:focus-visible::after {\n\topacity: 1;\n}\n\n.iconButton svg,\n.roundButton svg {\n\tdisplay: block;\n}\n\n/* Light theme */\n\n@media (prefers-color-scheme: light) {\n\t.wrapper {\n\t\t--pa-fg: #171716;\n\t\t--pa-muted: #61615b;\n\t\t--pa-accent: #c25a16;\n\t\t--pa-surface: #ffffff;\n\t\t--pa-raised: #f1f0ec;\n\t\t--pa-line: rgba(23, 23, 22, 0.12);\n\t\t--pa-ok: #1f6b3a;\n\t\t--pa-warn: #7a5a00;\n\t\t--pa-err: #a33a2a;\n\t\t--pa-c-keyword: #c25a16;\n\t\t--pa-c-string: #1f6b3a;\n\t\t--pa-c-number: #7a5a00;\n\t\t--pa-c-key: #1f4f8a;\n\t\t--pa-c-bool: #a33a2a;\n\t\t--pa-c-comment: #7a796f;\n\t\t--pa-c-name: #171716;\n\t\t--pa-c-punct: #61615b;\n\t\tbox-shadow: 0 16px 40px rgba(0, 0, 0, 0.12);\n\t}\n\t.stopButton {\n\t\tcolor: #a33a2a;\n\t}\n\t.iconButton:hover {\n\t\tbackground: rgba(0, 0, 0, 0.06);\n\t}\n\t.roundButton {\n\t\tbackground: rgba(0, 0, 0, 0.06);\n\t}\n\t.attachChip {\n\t\tbackground: rgba(0, 0, 0, 0.06);\n\t}\n\t.attachRemove:hover {\n\t\tbackground: rgba(0, 0, 0, 0.08);\n\t}\n\t.attachError {\n\t\tcolor: #b42318;\n\t}\n\t.send {\n\t\tcolor: #ffffff;\n\t}\n\t.brand {\n\t\tcolor: #ffffff;\n\t}\n}\n\n/* Mobile: follow modes (expanded / bar / fab), larger hit areas, no sticky hover tips. */\n\n@media (max-width: 480px) {\n\t.wrapper {\n\t\tleft: 0;\n\t\tright: 0;\n\t\tbottom: 0;\n\t\tmargin: 0;\n\t\twidth: auto;\n\t\tmax-height: min(560px, calc(100svh - env(safe-area-inset-top, 0px) - 12px));\n\t\tborder-radius: 18px 18px 0 0;\n\t\tborder-bottom: 0;\n\t\tpadding-bottom: env(safe-area-inset-bottom, 0px);\n\t\tbackground: color-mix(in srgb, var(--pa-surface) 92%, transparent);\n\t\tbackdrop-filter: blur(18px);\n\t\t-webkit-backdrop-filter: blur(18px);\n\t}\n\n\t.wrapper[data-follow='bar'] {\n\t\tleft: 8px;\n\t\tright: 8px;\n\t\tbottom: max(10px, env(safe-area-inset-bottom, 0px));\n\t\tmax-height: none;\n\t\tborder-radius: 16px;\n\t\tborder: 1px solid var(--pa-line);\n\t\tpadding-bottom: 0;\n\t\tbox-shadow: 0 12px 32px rgba(0, 0, 0, 0.4);\n\t}\n\n\t.wrapper[data-follow='bar'] .header,\n\t.wrapper[data-follow='bar'] .feedWrap,\n\t.wrapper[data-follow='bar'] .composer,\n\t.wrapper[data-follow='bar'] .voice,\n\t.wrapper[data-follow='bar'] .studio {\n\t\tdisplay: none !important;\n\t}\n\n\t.wrapper[data-follow='bar'] .followBar {\n\t\tdisplay: flex;\n\t}\n\n\t.header {\n\t\theight: 48px;\n\t\tgap: 6px;\n\t\tpadding: 0 8px 0 12px;\n\t}\n\n\t.brand {\n\t\twidth: 26px;\n\t\theight: 26px;\n\t\tborder-radius: 8px;\n\t\tfont-size: 13px;\n\t}\n\n\t.title {\n\t\tfont-size: 13px;\n\t}\n\n\t.status {\n\t\tfont-size: 10.5px;\n\t}\n\n\t/* Compact visuals with an expanded hit area (~44px) via ::before. */\n\t.controls {\n\t\tgap: 6px;\n\t}\n\n\t.iconButton {\n\t\tposition: relative;\n\t\tmin-width: 32px;\n\t\tmin-height: 32px;\n\t\twidth: 32px;\n\t\theight: 32px;\n\t\tborder-radius: 9px;\n\t}\n\n\t.iconButton::before {\n\t\tcontent: '';\n\t\tposition: absolute;\n\t\tinset: -6px;\n\t}\n\n\t.feed {\n\t\tpadding: 8px 10px 8px 8px;\n\t\tgap: 6px;\n\t}\n\n\t.feedWrap {\n\t\tmin-height: 72px;\n\t\tmax-height: 240px;\n\t}\n\n\t.composer {\n\t\tpadding: 8px 8px 10px;\n\t}\n\n\t.box {\n\t\tpadding: 4px 4px 4px 10px;\n\t\tborder-radius: 14px;\n\t}\n\n\t.actions {\n\t\tgap: 8px;\n\t}\n\n\t.roundButton {\n\t\tposition: relative;\n\t\twidth: 40px;\n\t\theight: 40px;\n\t}\n\n\t.roundButton::before {\n\t\tcontent: '';\n\t\tposition: absolute;\n\t\tinset: -4px;\n\t}\n\n\t/* Voice expanded: large lens, status, device, Mute + Stop row. */\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .voice {\n\t\tflex-direction: column;\n\t\talign-items: center;\n\t\tgap: 12px;\n\t\tpadding: 16px 14px 18px;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .lens {\n\t\twidth: 72px;\n\t\theight: 72px;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .lens svg {\n\t\twidth: 28px;\n\t\theight: 28px;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .voiceMeta {\n\t\talign-items: center;\n\t\ttext-align: center;\n\t\twidth: 100%;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .voiceText {\n\t\tfont-size: 15px;\n\t\twhite-space: normal;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .micDevice {\n\t\talign-self: center;\n\t\ttext-align: center;\n\t\tfont-size: 12px;\n\t\tmin-height: 28px;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .voiceActions {\n\t\tgap: 12px;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .voiceActions [data-role='voice-stop'] {\n\t\tdisplay: grid;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .voiceActions [data-role='back'] {\n\t\tdisplay: none;\n\t}\n\n\t.voice {\n\t\tgap: 8px;\n\t\tpadding: 8px 10px 10px;\n\t}\n\n\t.lens {\n\t\twidth: 26px;\n\t\theight: 26px;\n\t}\n\n\t.micDevice {\n\t\tmin-height: 32px;\n\t\tpadding: 6px 0;\n\t\tfont-size: 11px;\n\t}\n\n\t.followBar {\n\t\tmin-height: 60px;\n\t\tpadding: 10px 12px;\n\t\tpadding-bottom: max(10px, env(safe-area-inset-bottom, 0px));\n\t}\n\n\t.followBar .roundButton {\n\t\twidth: 40px;\n\t\theight: 40px;\n\t}\n\n\t/* Skills Studio: wrap toolbars, full-width preview, no horizontal overflow. */\n\t.studio {\n\t\toverflow-x: hidden;\n\t\tpadding: 10px 10px 14px;\n\t\tgap: 8px;\n\t}\n\n\t.studioTabs {\n\t\tflex-wrap: wrap;\n\t\tgap: 6px;\n\t}\n\n\t.studioTab {\n\t\tflex: 1 1 auto;\n\t\tmin-width: calc(33% - 6px);\n\t\tpadding: 10px 8px;\n\t\tfont-size: 12px;\n\t}\n\n\t.studioToolbar {\n\t\tgap: 8px;\n\t}\n\n\t.studioToolButton {\n\t\tflex: 1 1 auto;\n\t\tmin-height: 40px;\n\t\tpadding: 8px 12px;\n\t\tfont-size: 13px;\n\t}\n\n\t.studioStep,\n\t.studioCatalogRow {\n\t\tflex-wrap: wrap;\n\t\tpadding: 10px 12px;\n\t\tgap: 10px;\n\t}\n\n\t.studioStepActions,\n\t.studioCatalogActions {\n\t\twidth: 100%;\n\t\tjustify-content: flex-start;\n\t\tgap: 6px;\n\t}\n\n\t.studioStepActions button,\n\t.studioCatalogActions button {\n\t\tmin-height: 36px;\n\t\tpadding: 6px 10px;\n\t\tfont-size: 12px;\n\t}\n\n\t.studioPreview {\n\t\tmax-height: none;\n\t\twidth: 100%;\n\t\toverflow-x: auto;\n\t}\n\n\t.studioAsk {\n\t\tmin-height: 88px;\n\t}\n\n\t.fab {\n\t\twidth: 56px;\n\t\theight: 56px;\n\t\tbottom: max(16px, env(safe-area-inset-bottom, 0px));\n\t\tright: max(16px, env(safe-area-inset-right, 0px));\n\t\tbackground: color-mix(in srgb, var(--pa-surface) 88%, transparent);\n\t\tbackdrop-filter: blur(14px);\n\t\t-webkit-backdrop-filter: blur(14px);\n\t\tbox-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);\n\t}\n\n\t.fab img {\n\t\twidth: 28px;\n\t\theight: 28px;\n\t}\n\n\t.fab svg {\n\t\twidth: 24px;\n\t\theight: 24px;\n\t}\n\n\t.tip::after {\n\t\tdisplay: none;\n\t}\n}\n\n@media (hover: none) {\n\t.tip::after {\n\t\tdisplay: none;\n\t}\n}\n\n/* Desktop (≥768px): keep binary collapse; never show the mobile follow strip. */\n@media (min-width: 768px) {\n\t.followBar {\n\t\tdisplay: none !important;\n\t}\n}\n\n/* Reduced motion: keep the state text; drop the animation */\n\n@media (prefers-reduced-motion: reduce) {\n\t.wrapper,\n\t.enter,\n\t.live::before,\n\t.lens,\n\t.spinner {\n\t\tanimation: none !important;\n\t\ttransition: none !important;\n\t}\n}\n\n/* Script card: compact. Each block shows a preview that fades out; a click opens it, a second click closes it. */\n.code {\n\tpadding: 6px 8px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 9px;\n\tbackground: var(--pa-raised);\n\tfont-size: 11px;\n\tline-height: 1.3;\n}\n\n.code[data-status='running'] {\n\tborder-color: color-mix(in srgb, var(--pa-accent) 50%, transparent);\n}\n\n.code[data-status='error'],\n.code[data-status='refused'] {\n\tborder-color: color-mix(in srgb, var(--pa-err) 55%, transparent);\n}\n\n.codeHead {\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 6px;\n\tmin-width: 0;\n}\n\n.codeTitle {\n\tfont-weight: 600;\n\tcolor: var(--pa-accent);\n}\n\n.codeMeta {\n\tflex: 1;\n\tmin-width: 0;\n\toverflow: hidden;\n\twhite-space: nowrap;\n\ttext-overflow: ellipsis;\n\tcolor: var(--pa-muted);\n\tfont-size: 10px;\n}\n\n.codeStatus {\n\tfont-size: 10px;\n\tcolor: var(--pa-muted);\n}\n\n.code[data-status='error'] .codeStatus,\n.code[data-status='refused'] .codeStatus {\n\tcolor: var(--pa-err);\n}\n\n.codeBadge {\n\tpadding: 0 5px;\n\tmargin-right: 4px;\n\tborder-radius: 999px;\n\tbackground: color-mix(in srgb, var(--pa-accent) 18%, transparent);\n\tcolor: var(--pa-accent);\n\tfont-size: 9px;\n\tfont-weight: 600;\n}\n\n.codeSection {\n\tmargin-top: 4px;\n\tmin-width: 0;\n}\n\n.codeLabel {\n\tdisplay: block;\n\tmargin-bottom: 2px;\n\tfont-size: 9px;\n\tletter-spacing: 0.05em;\n\ttext-transform: uppercase;\n\tcolor: var(--pa-muted);\n}\n\n.clip {\n\tposition: relative;\n\tmin-width: 0;\n}\n\n.codeBlock,\n.resultBlock {\n\tmargin: 0;\n\tpadding: 4px 6px;\n\tborder-radius: 6px;\n\tbackground: var(--pa-surface);\n\tborder: 1px solid var(--pa-line);\n\tfont:\n\t\t10px/1.35 ui-monospace,\n\t\tSFMono-Regular,\n\t\tMenlo,\n\t\tConsolas,\n\t\tmonospace;\n\twhite-space: pre-wrap;\n\toverflow-wrap: anywhere;\n\tcolor: var(--pa-c-name);\n}\n\n.clipBody {\n\tposition: relative;\n\tmax-height: 4.1em;\n\toverflow: hidden;\n\tcursor: pointer;\n}\n\n.clip[data-open='true'] .clipBody {\n\tmax-height: 14em;\n\toverflow: auto;\n}\n\n.clip[data-clipped='true'][data-open='false'] .clipBody::after {\n\tcontent: '';\n\tposition: absolute;\n\tleft: 0;\n\tright: 0;\n\tbottom: 0;\n\theight: 1.5em;\n\tbackground: linear-gradient(to bottom, transparent, var(--pa-surface));\n\tpointer-events: none;\n}\n\n.clipToggle {\n\tmargin-top: 2px;\n\tpadding: 0;\n\tborder: 0;\n\tbackground: none;\n\tcolor: var(--pa-muted);\n\tfont: inherit;\n\tfont-size: 10px;\n\tcursor: pointer;\n}\n\n.clipToggle:hover {\n\tcolor: var(--pa-fg);\n}\n\n.resultBlock[data-ok='false'] {\n\tcolor: var(--pa-err);\n}\n\n.tkComment {\n\tcolor: var(--pa-c-comment);\n\tfont-style: italic;\n}\n\n.tkString {\n\tcolor: var(--pa-c-string);\n}\n\n.tkNumber {\n\tcolor: var(--pa-c-number);\n}\n\n.tkKeyword {\n\tcolor: var(--pa-c-keyword);\n}\n\n.tkName {\n\tcolor: var(--pa-c-name);\n}\n\n.tkPunct {\n\tcolor: var(--pa-c-punct);\n}\n\n.tkKey {\n\tcolor: var(--pa-c-key);\n}\n\n.tkBool {\n\tcolor: var(--pa-c-bool);\n}\n\n/* REVERSIBLE (2026-11-17, card scale): tool cards and script cards at 75% of their size, with their contents.\n Remove this block to return to full size. */\n.tool,\n.code {\n\tzoom: 0.75;\n}\n\n/* REVERSIBLE (2026-11-17, card folding): folded cards. Each card starts folded; its head shows the state. */\n.foldHead {\n\tcursor: pointer;\n\tuser-select: none;\n}\n\n.foldHead::after {\n\tcontent: '';\n\tflex: none;\n\twidth: 6px;\n\theight: 6px;\n\tmargin-left: auto;\n\tborder-right: 1.5px solid var(--pa-muted);\n\tborder-bottom: 1.5px solid var(--pa-muted);\n\ttransform: rotate(45deg);\n\ttransition: transform 0.22s ease;\n}\n\n.foldHead:focus-visible {\n\toutline: 1px solid var(--pa-accent);\n\toutline-offset: 2px;\n\tborder-radius: 4px;\n}\n\n.foldBody {\n\tdisplay: grid;\n\tgrid-template-rows: 0fr;\n\ttransition: grid-template-rows 0.24s ease;\n}\n\n.foldInner {\n\tmin-height: 0;\n\toverflow: hidden;\n}\n\n.fold[data-open='true'] > .foldBody,\n[data-open='true'] > .foldBody {\n\tgrid-template-rows: 1fr;\n}\n\n[data-open='true'] > .foldHead::after {\n\ttransform: rotate(-135deg);\n}\n\n.toolState {\n\tmargin-left: auto;\n\tfont-size: 10px;\n\tcolor: var(--pa-muted);\n}\n\n.tool[data-status='done'] .toolState {\n\tcolor: var(--pa-ok);\n}\n\n.tool[data-status='error'] .toolState {\n\tcolor: var(--pa-err);\n}\n\n.codeRunning,\n.codeDot {\n\tflex: none;\n\twidth: 6px;\n\theight: 6px;\n\tborder-radius: 50%;\n\tbackground: var(--pa-accent);\n}\n\n.codeDot {\n\tbackground: var(--pa-ok);\n\tanimation: pop 0.32s ease-out both;\n}\n\n.codeRunning {\n\tanimation: pulse 1.2s ease-in-out infinite;\n}\n\n.toolDot {\n\tanimation: pop 0.32s ease-out both;\n}\n\n@keyframes pop {\n\tfrom {\n\t\ttransform: scale(0.3);\n\t\topacity: 0;\n\t}\n\tto {\n\t\ttransform: scale(1);\n\t\topacity: 1;\n\t}\n}\n\n@keyframes pulse {\n\t0%,\n\t100% {\n\t\topacity: 1;\n\t\ttransform: scale(1);\n\t}\n\t50% {\n\t\topacity: 0.35;\n\t\ttransform: scale(0.7);\n\t}\n}\n\n@media (prefers-reduced-motion: reduce) {\n\t.foldBody,\n\t.foldHead::after {\n\t\ttransition: none;\n\t}\n\t.codeDot,\n\t.codeRunning,\n\t.toolDot {\n\t\tanimation: none;\n\t}\n}\n\n/* REVERSIBLE (2026-11-17, tool visuals): each tool has its own tone: a left stripe, a tinted icon chip and a short summary. */\n.tool,\n.code {\n\t--tone: var(--pa-muted);\n\tborder-left: 2px solid var(--tone);\n}\n\n.tool[data-tone='js'],\n.code[data-tone='js'] {\n\t--tone: #b58cff;\n}\n\n.tool[data-tone='task'] {\n\t--tone: var(--pa-accent);\n}\n\n.tool[data-tone='move'] {\n\t--tone: #7cb8ff;\n}\n\n.tool[data-tone='act'] {\n\t--tone: #7fd9a4;\n}\n\n.tool[data-tone='time'] {\n\t--tone: var(--pa-muted);\n}\n\n.tool[data-tone='done'] {\n\t--tone: var(--pa-ok);\n}\n\n.tool[data-tone='ask'] {\n\t--tone: var(--pa-warn);\n}\n\n.tool[data-tone='generic'] {\n\t--tone: var(--pa-muted);\n}\n\n.toolChip {\n\tflex: none;\n\tdisplay: grid;\n\tplace-items: center;\n\twidth: 18px;\n\theight: 18px;\n\tborder-radius: 6px;\n\tbackground: color-mix(in srgb, var(--tone) 18%, transparent);\n\tcolor: var(--tone);\n}\n\n.toolSummary {\n\tmin-width: 0;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\twhite-space: nowrap;\n\tcolor: var(--pa-muted);\n\tfont-size: 10px;\n}\n\n.toolLabel {\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\tmin-width: 0;\n}\n\n.toolState {\n\tmargin-left: auto;\n}\n","/**\n * A card that starts folded: its head always shows, its body opens and closes with a short animation.\n * The open state is remembered by key, so a redraw of the feed keeps the cards the user opened.\n * REVERSIBLE (2026-11-17, card folding): delete this file and its uses in feed.ts and scriptCard.ts.\n */\nimport styles from './Panel.module.css'\n\nconst openCards = new Set<string>()\n\n/** Wraps a card head and body in a folding region. Clicking the head (or pressing Enter/Space) toggles it. */\nexport function foldable(\n\thead: HTMLElement,\n\tbody: HTMLElement,\n\tkey: string,\n\tcardClass: string\n): HTMLElement {\n\tconst card = document.createElement('div')\n\tcard.className = cardClass\n\tconst open = openCards.has(key)\n\tcard.dataset.open = String(open)\n\thead.classList.add(styles.foldHead)\n\thead.setAttribute('role', 'button')\n\thead.setAttribute('tabindex', '0')\n\thead.setAttribute('aria-expanded', String(open))\n\n\tconst toggle = (): void => {\n\t\tconst next = card.dataset.open !== 'true'\n\t\tcard.dataset.open = String(next)\n\t\thead.setAttribute('aria-expanded', String(next))\n\t\tif (next) openCards.add(key)\n\t\telse openCards.delete(key)\n\t}\n\thead.addEventListener('click', toggle)\n\thead.addEventListener('keydown', (event) => {\n\t\tif (event.key === 'Enter' || event.key === ' ') {\n\t\t\tevent.preventDefault()\n\t\t\ttoggle()\n\t\t}\n\t})\n\n\tconst inner = document.createElement('div')\n\tinner.className = styles.foldInner\n\tinner.append(body)\n\tconst region = document.createElement('div')\n\tregion.className = styles.foldBody\n\tregion.append(inner)\n\tcard.append(head, region)\n\treturn card\n}\n","/**\n * One icon set for the whole panel: 24px grid, 2px rounded strokes, currentColor.\n * Every button uses these so the panel reads as one visual system.\n */\n\nexport type IconName =\n\t| 'code'\n\t| 'scroll'\n\t| 'clock'\n\t| 'check'\n\t| 'question'\n\t| 'list'\n\t| 'cursor'\n\t| 'cursorOff'\n\t| 'chevronUp'\n\t| 'chevronDown'\n\t| 'close'\n\t| 'stop'\n\t| 'mic'\n\t| 'micOff'\n\t| 'keyboard'\n\t| 'send'\n\t| 'spark'\n\t| 'arrowDown'\n\t| 'bookmark'\n\t| 'download'\n\t| 'paperclip'\n\t| 'skills'\n\nconst PATHS: Record<IconName, string> = {\n\tcode: '<path d=\"M8 8l-4 4 4 4\"/><path d=\"M16 8l4 4-4 4\"/><path d=\"M14 5l-4 14\"/>',\n\tscroll: '<path d=\"M12 4v16\"/><path d=\"M8 8l4-4 4 4\"/><path d=\"M8 16l4 4 4-4\"/>',\n\tclock: '<circle cx=\"12\" cy=\"12\" r=\"8\"/><path d=\"M12 8v4l2.5 2\"/>',\n\tcheck: '<path d=\"M5 12.5l4.5 4.5L19 7.5\"/>',\n\tquestion:\n\t\t'<circle cx=\"12\" cy=\"12\" r=\"8\"/><path d=\"M9.5 9.5a2.5 2.5 0 1 1 3.5 2.3c-.7.4-1 .9-1 1.7\"/><path d=\"M12 17h.01\"/>',\n\tlist: '<path d=\"M9 6h11M9 12h11M9 18h11\"/><path d=\"M4 6h.01M4 12h.01M4 18h.01\"/>',\n\tcursor: '<path d=\"M4 4l6.5 16 2.5-6.5L19.5 11z\"/>',\n\tcursorOff: '<path d=\"M4 4l6.5 16 2.5-6.5L19.5 11z\"/><path d=\"M3 3l18 18\"/>',\n\tchevronUp: '<path d=\"M6 15l6-6 6 6\"/>',\n\tchevronDown: '<path d=\"M6 9l6 6 6-6\"/>',\n\tclose: '<path d=\"M6 6l12 12M18 6L6 18\"/>',\n\tstop: '<rect x=\"6\" y=\"6\" width=\"12\" height=\"12\" rx=\"2\"/>',\n\tmic: '<rect x=\"9\" y=\"3\" width=\"6\" height=\"11\" rx=\"3\"/><path d=\"M5 11a7 7 0 0 0 14 0\"/><path d=\"M12 18v3\"/>',\n\tmicOff:\n\t\t'<rect x=\"9\" y=\"3\" width=\"6\" height=\"11\" rx=\"3\"/><path d=\"M5 11a7 7 0 0 0 14 0\"/><path d=\"M12 18v3\"/><path d=\"M3 3l18 18\"/>',\n\tkeyboard:\n\t\t'<rect x=\"2\" y=\"6\" width=\"20\" height=\"12\" rx=\"2\"/><path d=\"M6 10h.01M10 10h.01M14 10h.01M18 10h.01M7 14h10\"/>',\n\tsend: '<path d=\"M12 19V5\"/><path d=\"M5 12l7-7 7 7\"/>',\n\tarrowDown: '<path d=\"M12 5v14\"/><path d=\"M6 13l6 6 6-6\"/>',\n\tbookmark: '<path d=\"M6 3h12v18l-6-4-6 4z\"/>',\n\tdownload: '<path d=\"M12 4v11\"/><path d=\"M7 10l5 5 5-5\"/><path d=\"M5 20h14\"/>',\n\tpaperclip:\n\t\t'<path d=\"M15.5 7.5l-6.8 6.8a2.5 2.5 0 0 0 3.5 3.5l7.2-7.2a4 4 0 0 0-5.7-5.7L6.2 12.4a5.5 5.5 0 0 0 7.8 7.8l6-6\"/>',\n\tskills:\n\t\t'<path d=\"M12 3l2.2 4.5L19 9l-3.5 3.4L16.4 18 12 15.6 7.6 18l.9-5.6L5 9l4.8-1.5L12 3z\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/>',\n\tspark: '<path d=\"M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z\"/>',\n}\n\nexport function icon(name: IconName): string {\n\treturn `<svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">${PATHS[name]}</svg>`\n}\n","/**\n * Tokenizers for the script card: JavaScript code and the JSON a script returns.\n * Pure functions. Tokens hold plain text only, so rendering them never parses HTML.\n */\n\nexport type TokenKind =\n\t'plain' | 'comment' | 'string' | 'number' | 'keyword' | 'name' | 'punct' | 'key' | 'bool' | 'null'\n\nexport interface Token {\n\tkind: TokenKind\n\ttext: string\n}\n\nconst JS_KEYWORDS = new Set([\n\t'async',\n\t'await',\n\t'break',\n\t'case',\n\t'catch',\n\t'class',\n\t'const',\n\t'continue',\n\t'default',\n\t'delete',\n\t'do',\n\t'else',\n\t'export',\n\t'extends',\n\t'finally',\n\t'for',\n\t'function',\n\t'if',\n\t'import',\n\t'in',\n\t'instanceof',\n\t'let',\n\t'new',\n\t'of',\n\t'return',\n\t'switch',\n\t'throw',\n\t'try',\n\t'typeof',\n\t'var',\n\t'void',\n\t'while',\n\t'yield',\n\t'true',\n\t'false',\n\t'null',\n\t'undefined',\n\t'this',\n])\n\n// Comments, strings (including unterminated ones at the end of a line), numbers, words, whitespace,\n// and any other single character. The alternatives cover every character, so no text is lost.\nconst JS_TOKEN =\n\t/\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$)|'(?:[^'\\\\\\n]|\\\\.)*'?|\"(?:[^\"\\\\\\n]|\\\\.)*\"?|`(?:[^`\\\\]|\\\\.)*`?|\\d+(?:\\.\\d+)?|[A-Za-z_$][\\w$]*|\\s+|[\\s\\S]/g\n\n/** Splits JavaScript source into coloured tokens. Words inside strings and comments are not keywords. */\nexport function jsTokens(code: string): Token[] {\n\tconst tokens: Token[] = []\n\tfor (const match of code.matchAll(JS_TOKEN)) {\n\t\tconst text = match[0]\n\t\ttokens.push({ kind: classifyJs(text), text })\n\t}\n\treturn tokens\n}\n\nfunction classifyJs(text: string): TokenKind {\n\tif (text.startsWith('//') || text.startsWith('/*')) return 'comment'\n\tconst first = text[0]\n\tif (first === \"'\" || first === '\"' || first === '`') return 'string'\n\tif (/^\\d/.test(text)) return 'number'\n\tif (/^[A-Za-z_$]/.test(text)) return JS_KEYWORDS.has(text) ? 'keyword' : 'name'\n\tif (/^\\s+$/.test(text)) return 'plain'\n\treturn 'punct'\n}\n\nconst JSON_TOKEN = /\"(?:[^\"\\\\]|\\\\.)*\"|-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?|true|false|null|\\s+|[\\s\\S]/g\n\n/**\n * Pretty-prints a JSON text and colours it. Returns null when the text is not JSON, so the caller can show it\n * as plain text (for example a string a script returned, or a result cut in the middle).\n */\nexport function jsonTokens(raw: string): Token[] | null {\n\tlet value: unknown\n\ttry {\n\t\tvalue = JSON.parse(raw)\n\t} catch {\n\t\treturn null\n\t}\n\tconst pretty = JSON.stringify(value, null, 2) ?? 'undefined'\n\tconst tokens: Token[] = []\n\tfor (const match of pretty.matchAll(JSON_TOKEN)) {\n\t\tconst text = match[0]\n\t\tconst end = (match.index ?? 0) + text.length\n\t\ttokens.push({ kind: classifyJson(text, pretty.slice(end)), text })\n\t}\n\treturn tokens\n}\n\nfunction classifyJson(text: string, after: string): TokenKind {\n\tif (text.startsWith('\"')) return /^\\s*:/.test(after) ? 'key' : 'string'\n\tif (text === 'true' || text === 'false') return 'bool'\n\tif (text === 'null') return 'null'\n\tif (/^-?\\d/.test(text)) return 'number'\n\tif (/^\\s+$/.test(text)) return 'plain'\n\treturn 'punct'\n}\n\n/** Text without colour, one token. Used for values that are not JSON. */\nexport function plainTokens(text: string): Token[] {\n\treturn [{ kind: 'plain', text }]\n}\n","import type { TranslationKey, TranslationParams } from '../i18n'\nimport { foldable } from './fold'\nimport { type Token, type TokenKind, jsTokens, jsonTokens, plainTokens } from './highlight'\nimport { icon } from './icons'\n\nimport styles from './Panel.module.css'\n\ntype Translate = (key: TranslationKey, params?: TranslationParams) => string\n\nconst OK_PREFIX = '✅ Executed JavaScript. Result: '\nconst ERROR_PREFIX = '❌ Error executing JavaScript: '\n\nconst TOKEN_CLASS: Record<TokenKind, string> = {\n\tplain: '',\n\tcomment: styles.tkComment,\n\tstring: styles.tkString,\n\tnumber: styles.tkNumber,\n\tkeyword: styles.tkKeyword,\n\tname: styles.tkName,\n\tpunct: styles.tkPunct,\n\tkey: styles.tkKey,\n\tbool: styles.tkBool,\n\tnull: styles.tkBool,\n}\n\n/** Splits the text the page controller returns into the value and whether the script succeeded. */\nexport function parseScriptOutput(output: string): { ok: boolean; value: string } {\n\tif (output.startsWith(OK_PREFIX)) return { ok: true, value: output.slice(OK_PREFIX.length) }\n\tif (output.startsWith(ERROR_PREFIX))\n\t\treturn { ok: false, value: output.slice(ERROR_PREFIX.length) }\n\treturn { ok: true, value: output }\n}\n\nfunction codeBlock(tokens: Token[], className: string): HTMLElement {\n\tconst pre = document.createElement('pre')\n\tpre.className = className\n\tfor (const token of tokens) {\n\t\tconst cls = TOKEN_CLASS[token.kind]\n\t\tif (!cls) {\n\t\t\tpre.append(token.text)\n\t\t\tcontinue\n\t\t}\n\t\tconst span = document.createElement('span')\n\t\tspan.className = cls\n\t\tspan.textContent = token.text\n\t\tpre.append(span)\n\t}\n\treturn pre\n}\n\n/**\n * A short preview of a code or result block. It fades out at the bottom when there is more; a click on the block\n * or on its button opens the whole text, and a second click returns to the preview.\n */\nfunction previewBlock(tokens: Token[], className: string, t: Translate): HTMLElement {\n\tconst wrap = document.createElement('div')\n\twrap.className = styles.clip\n\twrap.dataset.open = 'false'\n\tconst pre = codeBlock(tokens, `${className} ${styles.clipBody}`)\n\tconst toggle = document.createElement('button')\n\ttoggle.type = 'button'\n\ttoggle.className = styles.clipToggle\n\ttoggle.hidden = true\n\ttoggle.textContent = t('ui.panel.codeShowMore')\n\tconst flip = (): void => {\n\t\tconst open = wrap.dataset.open !== 'true'\n\t\twrap.dataset.open = String(open)\n\t\ttoggle.textContent = open ? t('ui.panel.codeShowLess') : t('ui.panel.codeShowMore')\n\t}\n\tpre.addEventListener('click', flip)\n\ttoggle.addEventListener('click', flip)\n\twrap.append(pre, toggle)\n\t// Measured after the card is in the feed: only blocks taller than the preview get the fade and the button.\n\trequestAnimationFrame(() => {\n\t\tconst clipped = pre.scrollHeight > pre.clientHeight + 1\n\t\twrap.dataset.clipped = String(clipped)\n\t\ttoggle.hidden = !clipped\n\t})\n\treturn wrap\n}\n\nfunction section(label: string, body: HTMLElement): HTMLElement {\n\tconst wrap = document.createElement('div')\n\twrap.className = styles.codeSection\n\tconst title = document.createElement('small')\n\ttitle.className = styles.codeLabel\n\ttitle.textContent = label\n\twrap.append(title, body)\n\treturn wrap\n}\n\n/**\n * Card for one execute_javascript call. It starts folded, showing its title and state; opened, it shows the script\n * coloured as JavaScript and the result coloured as JSON (plain text when it is not JSON).\n */\nexport function scriptCard(options: {\n\tscript: string\n\toutput?: string\n\tt: Translate\n\t/** Where the script came from. Voice scripts are labelled as such. */\n\tsource?: 'agent' | 'voice'\n\t/** A voice script the panel did not run. */\n\trefused?: boolean\n\t/** Time the script was requested, shown in the header. */\n\ttime?: string\n\t/** Stable key for remembering whether the card is open. */\n\tkey: string\n}): HTMLElement {\n\tconst { script, output, t, source = 'agent', refused = false, time, key } = options\n\tconst parsed = output === undefined ? null : parseScriptOutput(output)\n\tconst status = refused ? 'refused' : parsed === null ? 'running' : parsed.ok ? 'done' : 'error'\n\n\tconst head = document.createElement('div')\n\thead.className = styles.codeHead\n\tconst title = document.createElement('span')\n\ttitle.className = styles.codeTitle\n\ttitle.textContent = t('ui.panel.codeTitle')\n\tconst meta = document.createElement('span')\n\tmeta.className = styles.codeMeta\n\tif (source === 'voice') {\n\t\tconst badge = document.createElement('span')\n\t\tbadge.className = styles.codeBadge\n\t\tbadge.textContent = t('ui.panel.codeVoice')\n\t\tmeta.append(badge)\n\t}\n\tif (time) meta.append(time)\n\tconst state = document.createElement('span')\n\tstate.className = styles.codeStatus\n\tstate.textContent =\n\t\tstatus === 'running'\n\t\t\t? t('ui.panel.codeRunning')\n\t\t\t: status === 'done'\n\t\t\t\t? t('ui.panel.codeDone')\n\t\t\t\t: status === 'refused'\n\t\t\t\t\t? t('ui.panel.codeRefused')\n\t\t\t\t\t: t('ui.panel.codeFailed')\n\tconst chip = document.createElement('span')\n\tchip.className = styles.toolChip\n\tchip.innerHTML = icon('code')\n\thead.append(chip, title, meta, state)\n\n\tconst body = document.createElement('div')\n\tbody.append(\n\t\tsection(t('ui.panel.codeScript'), previewBlock(jsTokens(script), styles.codeBlock, t))\n\t)\n\tif (refused && output !== undefined) {\n\t\tbody.append(\n\t\t\tsection(t('ui.panel.codeRefused'), previewBlock(plainTokens(output), styles.resultBlock, t))\n\t\t)\n\t} else if (parsed) {\n\t\tconst value = parsed.value\n\t\tconst tokens = parsed.ok ? (jsonTokens(value) ?? plainTokens(value)) : plainTokens(value)\n\t\tconst label = t(parsed.ok ? 'ui.panel.codeResult' : 'ui.panel.codeError')\n\t\tbody.append(section(label, previewBlock(tokens, styles.resultBlock, t)))\n\t}\n\n\tconst card = foldable(head, body, key, styles.code)\n\tcard.dataset.status = status\n\tcard.dataset.tone = 'js'\n\treturn card\n}\n","/**\n * The visual identity of each tool: an icon, a colour tone and a one-line summary. Pure functions.\n * REVERSIBLE (2026-11-17, tool visuals): delete this file and its uses in feed.ts and scriptCard.ts.\n */\nimport { truncate } from '../utils'\nimport type { IconName } from './icons'\n\nexport type ToolTone = 'js' | 'task' | 'move' | 'act' | 'time' | 'done' | 'ask' | 'generic'\n\nexport interface ToolVisual {\n\ticon: IconName\n\ttone: ToolTone\n\t/** Short, factual detail for the folded card. Empty when there is nothing short to show. */\n\tsummary: string\n}\n\n/** Reads a value as text only when it already is text or a number; anything else gives an empty string. */\nconst textOf = (value: unknown): string =>\n\ttypeof value === 'string' || typeof value === 'number' ? String(value) : ''\n\nconst indexOf = (input: unknown): string => {\n\tconst index = (input as { index?: unknown } | undefined)?.index\n\treturn typeof index === 'number' ? `#${index}` : ''\n}\n\n/** The visual of a tool call, from its name, its input and its output text. */\nexport function toolVisual(name: string, input: unknown, output: string | undefined): ToolVisual {\n\tconst args = (input ?? {}) as Record<string, unknown>\n\tswitch (name) {\n\t\tcase 'execute_javascript':\n\t\t\treturn { icon: 'code', tone: 'js', summary: '' }\n\t\tcase 'run_task':\n\t\t\treturn { icon: 'spark', tone: 'task', summary: truncate(textOf(args.task), 32) }\n\t\tcase 'scroll': {\n\t\t\tconst px = /([\\d.]+)px/.exec(output ?? '')?.[1]\n\t\t\treturn { icon: 'scroll', tone: 'move', summary: px ? `${Math.round(Number(px))} px` : '' }\n\t\t}\n\t\tcase 'click_element_by_index':\n\t\t\treturn { icon: 'cursor', tone: 'act', summary: indexOf(input) }\n\t\tcase 'hover_element':\n\t\t\treturn { icon: 'cursor', tone: 'move', summary: indexOf(input) }\n\t\tcase 'double_click_element':\n\t\t\treturn { icon: 'cursor', tone: 'act', summary: indexOf(input) }\n\t\tcase 'press_key':\n\t\t\treturn { icon: 'keyboard', tone: 'act', summary: truncate(textOf(args.key), 24) }\n\t\tcase 'focus_element':\n\t\t\treturn { icon: 'cursor', tone: 'act', summary: indexOf(input) }\n\t\tcase 'set_checked':\n\t\t\treturn {\n\t\t\t\ticon: 'check',\n\t\t\t\ttone: 'act',\n\t\t\t\tsummary: `${indexOf(input)} ${args.checked === false ? 'off' : 'on'}`.trim(),\n\t\t\t}\n\t\tcase 'set_range':\n\t\t\treturn {\n\t\t\t\ticon: 'list',\n\t\t\t\ttone: 'act',\n\t\t\t\tsummary: `${indexOf(input)} ${textOf(args.value)}`.trim(),\n\t\t\t}\n\t\tcase 'scroll_into_view':\n\t\t\treturn { icon: 'scroll', tone: 'move', summary: indexOf(input) }\n\t\tcase 'wheel': {\n\t\t\tconst delta = textOf(args.delta_y)\n\t\t\treturn {\n\t\t\t\ticon: 'scroll',\n\t\t\t\ttone: 'move',\n\t\t\t\tsummary: delta || indexOf(input),\n\t\t\t}\n\t\t}\n\t\tcase 'drag_element': {\n\t\t\tconst from = (input as { source_index?: unknown } | undefined)?.source_index\n\t\t\tconst to = (input as { target_index?: unknown } | undefined)?.target_index\n\t\t\tconst summary = typeof from === 'number' && typeof to === 'number' ? `#${from} → #${to}` : ''\n\t\t\treturn { icon: 'cursor', tone: 'move', summary }\n\t\t}\n\t\tcase 'input_text':\n\t\t\treturn { icon: 'keyboard', tone: 'act', summary: indexOf(input) }\n\t\tcase 'select_dropdown_option':\n\t\t\treturn { icon: 'list', tone: 'act', summary: truncate(textOf(args.text), 24) }\n\t\tcase 'wait':\n\t\t\treturn {\n\t\t\t\ticon: 'clock',\n\t\t\t\ttone: 'time',\n\t\t\t\tsummary: textOf(args.seconds) ? `${textOf(args.seconds)}s` : '',\n\t\t\t}\n\t\tcase 'done':\n\t\t\treturn { icon: 'check', tone: 'done', summary: args.success === false ? 'não' : 'ok' }\n\t\tcase 'ask_user':\n\t\t\treturn { icon: 'question', tone: 'ask', summary: truncate(textOf(args.question), 32) }\n\t\tdefault:\n\t\t\treturn { icon: 'spark', tone: 'generic', summary: '' }\n\t}\n}\n","import type { TranslationKey, TranslationParams } from '../i18n'\nimport { truncate } from '../utils'\nimport { foldable } from './fold'\nimport { icon } from './icons'\nimport { scriptCard } from './scriptCard'\nimport { type ToolVisual, toolVisual } from './toolVisual'\nimport type { AgentActivity, PanelAgentAdapter } from './types'\n\nimport styles from './Panel.module.css'\n\ntype Translate = (key: TranslationKey, params?: TranslationParams) => string\ntype HistoryEvent = PanelAgentAdapter['history'][number]\n\nexport type ResultKind = 'done' | 'notDone' | 'stopped' | 'error'\n\n/**\n * The core reports some events as English sentences. Translate the known ones for display only;\n * anything else (the model's own words, page text, tool outputs) is shown as it is.\n */\nexport function localizeCore(text: string, t: Translate): string {\n\tlet m: RegExpMatchArray | null\n\tif (text === 'Task aborted') return t('ui.panel.msgAborted')\n\tif (text === 'Task completed') return t('ui.panel.msgCompleted')\n\tif (text === 'Step count exceeded maximum limit') return t('ui.panel.msgStepLimit')\n\tif ((m = /^LLM retry attempt (\\d+) of (\\d+)$/.exec(text)))\n\t\treturn t('ui.panel.msgRetry', { attempt: m[1], max: m[2] })\n\tif ((m = /^Page navigated to → (.*)$/.exec(text)))\n\t\treturn t('ui.panel.msgNavigated', { url: m[1] })\n\tif ((m = /^You have waited (\\d+) seconds accumulatively/.exec(text)))\n\t\treturn t('ui.panel.msgWaited', { seconds: m[1] })\n\tif ((m = /^⚠️ Only (\\d+) steps remaining/.exec(text)))\n\t\treturn t('ui.panel.msgStepsLeft', { count: m[1] })\n\tif ((m = /^⚠️ Critical: Only (\\d+) steps left/.exec(text)))\n\t\treturn t('ui.panel.msgStepsCritical', { count: m[1] })\n\treturn text\n}\n\nexport interface FeedModel {\n\t/** Keys the cards of this run, so their open state is remembered. */\n\tkey?: string\n\ttask: string\n\thistory: readonly HistoryEvent[]\n\tlive: AgentActivity | null\n\tquestion: string | null\n\tresult: { kind: ResultKind; text: string } | null\n}\n\nfunction node<K extends keyof HTMLElementTagNameMap>(\n\ttag: K,\n\tclassName: string,\n\ttext?: string\n): HTMLElementTagNameMap[K] {\n\tconst el = document.createElement(tag)\n\tel.className = className\n\tif (text !== undefined) el.textContent = text\n\treturn el\n}\n\nfunction spinner(): HTMLElement {\n\treturn node('span', styles.spinner)\n}\n\n/** Human-readable label for a tool call, shown on the tool card. */\nexport function toolLabel(name: string, input: unknown, t: Translate): string {\n\tconst a = (input ?? {}) as Record<string, string | number>\n\tswitch (name) {\n\t\tcase 'click_element_by_index':\n\t\t\treturn t('ui.tools.clicking', { index: a.index })\n\t\tcase 'input_text':\n\t\t\treturn t('ui.tools.inputting', { index: a.index })\n\t\tcase 'select_dropdown_option':\n\t\t\treturn t('ui.tools.selecting', { text: a.text })\n\t\tcase 'scroll':\n\t\t\treturn t('ui.tools.scrolling')\n\t\tcase 'wait':\n\t\t\treturn t('ui.tools.waiting', { seconds: a.seconds })\n\t\tcase 'ask_user':\n\t\t\treturn t('ui.tools.askingUser')\n\t\tcase 'done':\n\t\t\treturn t('ui.tools.done')\n\t\tdefault:\n\t\t\treturn t('ui.tools.executing', { toolName: name })\n\t}\n}\n\nfunction stepPrefix(event: HistoryEvent, t: Translate): string | undefined {\n\treturn event.type === 'step' && event.stepIndex !== undefined\n\t\t? t('ui.panel.step', { number: String(event.stepIndex + 1) })\n\t\t: undefined\n}\n\nfunction userBubble(text: string): HTMLElement {\n\treturn node('div', styles.bubble, text)\n}\n\nfunction line(text: string, extraClass = ''): HTMLElement {\n\treturn node('div', `${styles.line} ${extraClass}`.trim(), text)\n}\n\n/**\n * A tool call card. It starts folded, with its label and state; opened, it shows the detail text.\n * REVERSIBLE (2026-11-17, card folding).\n */\nfunction toolCard(\n\tlabel: string,\n\tdetail: string,\n\tstatus: 'done' | 'running' | 'error',\n\tkey: string,\n\tvisual: ToolVisual = { icon: 'spark', tone: 'generic', summary: '' }\n): HTMLElement {\n\tconst chip = node('span', styles.toolChip)\n\tchip.innerHTML = icon(visual.icon)\n\tconst head = node('div', styles.toolHead)\n\thead.append(\n\t\tchip,\n\t\tnode('span', styles.toolLabel, label),\n\t\tnode('span', styles.toolSummary, visual.summary),\n\t\tstatus === 'running'\n\t\t\t? spinner()\n\t\t\t: node('span', styles.toolState, status === 'error' ? '!' : '✓')\n\t)\n\tconst body = node('div', '')\n\tif (detail) body.append(node('div', styles.toolDetail, truncate(detail, 240)))\n\tconst card = foldable(head, body, key, styles.tool)\n\tcard.dataset.status = status\n\tcard.dataset.tone = visual.tone\n\treturn card\n}\n\nfunction questionCard(text: string, t: Translate, pending: boolean): HTMLElement {\n\tconst card = node('div', styles.question)\n\tcard.dataset.pending = String(pending)\n\tcard.append(\n\t\tnode('small', styles.questionTag, t('ui.panel.questionTitle')),\n\t\tnode('p', styles.questionText, text)\n\t)\n\treturn card\n}\n\nfunction markedQuestion(text: string, t: Translate, pending: boolean): HTMLElement {\n\tconst card = questionCard(text, t, pending)\n\tcard.dataset.mark = 'question'\n\treturn card\n}\n\nfunction resultCard(kind: ResultKind, text: string, t: Translate): HTMLElement {\n\tconst titles: Record<ResultKind, TranslationKey> = {\n\t\tdone: 'ui.panel.resultDone',\n\t\tnotDone: 'ui.panel.resultNotDone',\n\t\tstopped: 'ui.panel.resultStopped',\n\t\terror: 'ui.panel.resultError',\n\t}\n\tconst card = node('div', styles.result)\n\tcard.dataset.kind = kind\n\tcard.append(node('strong', '', t(titles[kind])))\n\tif (text) card.append(node('div', styles.resultText, localizeCore(text, t)))\n\treturn card\n}\n\n/** Turns the agent history and live activity into feed nodes. Only text is set via textContent. */\nexport function buildFeed(model: FeedModel, t: Translate): HTMLElement[] {\n\tconst nodes: HTMLElement[] = []\n\tif (model.task) {\n\t\tconst turn = userBubble(model.task)\n\t\tturn.dataset.mark = 'turn'\n\t\tnodes.push(turn)\n\t}\n\n\tconst runKey = model.key ?? 'current'\n\tfor (const [index, event] of model.history.entries()) {\n\t\tconst prefix = stepPrefix(event, t)\n\t\tif (event.type === 'step') {\n\t\t\tconst r = event.reflection\n\t\t\tif (r) {\n\t\t\t\tconst parts: string[] = []\n\t\t\t\tif (r.evaluation_previous_goal)\n\t\t\t\t\tparts.push(`${t('ui.panel.evaluation')}: ${r.evaluation_previous_goal}`)\n\t\t\t\tif (r.memory) parts.push(`${t('ui.panel.memory')}: ${r.memory}`)\n\t\t\t\tif (r.next_goal) parts.push(`${t('ui.panel.nextGoal')}: ${r.next_goal}`)\n\t\t\t\tif (parts.length) nodes.push(line(parts.join('\\n'), styles.reflection))\n\t\t\t}\n\t\t\tconst action = event.action\n\t\t\tif (!action || action.name === 'done') continue\n\t\t\tif (action.name === 'ask_user') {\n\t\t\t\tconst question = (action.input as { question?: string })?.question ?? ''\n\t\t\t\tnodes.push(markedQuestion(question, t, false))\n\t\t\t\tconst answer = action.output.replace(/^User answered:\\s*/i, '')\n\t\t\t\tif (answer) nodes.push(userBubble(answer))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (action.name === 'execute_javascript') {\n\t\t\t\tconst script = (action.input as { script?: string })?.script ?? ''\n\t\t\t\tnodes.push(scriptCard({ script, output: action.output, t, key: `${runKey}:${index}` }))\n\t\t\t\tif (prefix) nodes[nodes.length - 1].dataset.step = prefix\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnodes.push(\n\t\t\t\ttoolCard(\n\t\t\t\t\ttoolLabel(action.name, action.input, t),\n\t\t\t\t\taction.output,\n\t\t\t\t\t'done',\n\t\t\t\t\t`${runKey}:${index}`,\n\t\t\t\t\ttoolVisual(action.name, action.input, action.output)\n\t\t\t\t)\n\t\t\t)\n\t\t\tif (prefix) nodes[nodes.length - 1].dataset.step = prefix\n\t\t} else if (event.type === 'observation') {\n\t\t\tif (event.content) nodes.push(line(localizeCore(event.content, t), styles.observation))\n\t\t} else if (event.type === 'user_takeover') {\n\t\t\tnodes.push(line(t('ui.panel.userTakeover'), styles.observation))\n\t\t} else if (event.type === 'retry') {\n\t\t\tnodes.push(line(localizeCore(event.message ?? '', t), styles.warning))\n\t\t} else if (event.type === 'error') {\n\t\t\tnodes.push(\n\t\t\t\ttoolCard(localizeCore(event.message ?? 'Error', t), '', 'error', `${runKey}:${index}`)\n\t\t\t)\n\t\t}\n\t}\n\n\tconst live = model.live\n\tif (live?.type === 'thinking') nodes.push(line(t('ui.panel.thinking'), styles.live))\n\tif (live?.type === 'executing' && live.tool === 'execute_javascript')\n\t\tnodes.push(\n\t\t\tscriptCard({\n\t\t\t\tscript: (live.input as { script?: string })?.script ?? '',\n\t\t\t\tt,\n\t\t\t\tkey: `${runKey}:live`,\n\t\t\t})\n\t\t)\n\telse if (live?.type === 'executing')\n\t\tnodes.push(\n\t\t\ttoolCard(\n\t\t\t\ttoolLabel(live.tool, live.input, t),\n\t\t\t\t'',\n\t\t\t\t'running',\n\t\t\t\t`${runKey}:live`,\n\t\t\t\ttoolVisual(live.tool, live.input, undefined)\n\t\t\t)\n\t\t)\n\tif (live?.type === 'retrying')\n\t\tnodes.push(\n\t\t\tline(\n\t\t\t\tt('ui.panel.statusRetrying', {\n\t\t\t\t\tattempt: String(live.attempt),\n\t\t\t\t\tmax: String(live.maxAttempts),\n\t\t\t\t}),\n\t\t\t\tstyles.live\n\t\t\t)\n\t\t)\n\n\tif (model.question) nodes.push(markedQuestion(model.question, t, true))\n\tif (model.result) {\n\t\tconst result = resultCard(model.result.kind, model.result.text, t)\n\t\tresult.dataset.mark = 'result'\n\t\tnodes.push(result)\n\t}\n\n\tfor (const n of nodes) n.classList.add(styles.enter)\n\treturn nodes\n}\n\n/** Latest text the agent reported with `done`, or the latest error message. */\nexport function lastOutcomeText(history: readonly HistoryEvent[]): string {\n\tfor (let i = history.length - 1; i >= 0; i--) {\n\t\tconst e = history[i]\n\t\tif (e.type === 'step' && e.action?.name === 'done') {\n\t\t\tconst input = e.action.input as { text?: string }\n\t\t\treturn input?.text || e.action.output || ''\n\t\t}\n\t\tif (e.type === 'error' && e.message) return e.message\n\t}\n\treturn ''\n}\n","/**\n * Microphone lifecycle for the panel's voice mode.\n *\n * - Enabling asks the browser for permission and opens the microphone.\n * - Muting or turning voice off stops every track, so the browser stops showing the mic as in use.\n * - After permission, the control can list inputs and switch between them (phone vs Bluetooth, etc.).\n * - No audio is recorded or sent here. A voice engine that needs audio reads `stream` while it is open.\n */\n\nexport type MicState = 'off' | 'active' | 'muted' | 'denied' | 'unsupported' | 'busy'\n\nexport interface MicDevice {\n\tdeviceId: string\n\tlabel: string\n}\n\n/** Score used to prefer a built-in mic over a Bluetooth headset when several inputs exist. */\nexport function micPreferenceScore(label: string): number {\n\tconst l = label.toLowerCase()\n\tif (/bluetooth|airpods|headset|hands[- ]?free|\\bwh-|\\bbuds\\b|galaxy buds|freebuds/.test(l))\n\t\treturn 0\n\tif (/default|communications/.test(l)) return 1\n\tif (/built-?in|internal|iphone|android|pixel|samsung|macbook|realtek|microphone \\(/.test(l))\n\t\treturn 3\n\tif (/microphone|mic/.test(l)) return 2\n\treturn 1\n}\n\nexport class MicrophoneControl {\n\t#stream: MediaStream | null = null\n\t#state: MicState = 'off'\n\t#wanted = false\n\t#attempt = 0\n\t#deviceId: string | null = null\n\t#label = ''\n\t#hardwareMuted = false\n\t#onChange: () => void\n\t#trackCleanups: (() => void)[] = []\n\n\tconstructor(onChange: () => void) {\n\t\tthis.#onChange = onChange\n\t}\n\n\tget state(): MicState {\n\t\treturn this.#state\n\t}\n\n\t/** Open stream while the microphone is in use; null when released (off, muted, denied). */\n\tget stream(): MediaStream | null {\n\t\treturn this.#stream\n\t}\n\n\t/** Label of the open input, once permission has been granted. Empty before that. */\n\tget label(): string {\n\t\treturn this.#label\n\t}\n\n\t/** deviceId of the open input, when known. */\n\tget deviceId(): string | null {\n\t\treturn this.#deviceId\n\t}\n\n\t/**\n\t * True when the OS reports the track as muted (common with a Bluetooth headset that is not\n\t * sending audio). The stream can still look \"active\" while nothing reaches the model.\n\t */\n\tget hardwareMuted(): boolean {\n\t\treturn this.#hardwareMuted\n\t}\n\n\t/** Inputs available after permission. Labels are empty before the first successful enable. */\n\tasync listInputs(): Promise<MicDevice[]> {\n\t\tif (!navigator.mediaDevices?.enumerateDevices) return []\n\t\tconst devices = await navigator.mediaDevices.enumerateDevices()\n\t\treturn devices\n\t\t\t.filter((d) => d.kind === 'audioinput' && d.deviceId)\n\t\t\t.map((d) => ({\n\t\t\t\tdeviceId: d.deviceId,\n\t\t\t\tlabel: d.label || `Microphone ${d.deviceId.slice(0, 6)}`,\n\t\t\t}))\n\t}\n\n\t/** User turned voice on: request permission and open the microphone. */\n\tasync enable(deviceId?: string): Promise<void> {\n\t\tthis.#wanted = true\n\t\tconst attempt = ++this.#attempt\n\t\tif (!navigator.mediaDevices?.getUserMedia) {\n\t\t\tthis.#set('unsupported')\n\t\t\treturn\n\t\t}\n\t\tconst preferred = deviceId ?? this.#deviceId ?? undefined\n\t\ttry {\n\t\t\tconst stream = await navigator.mediaDevices.getUserMedia({\n\t\t\t\taudio: audioConstraints(preferred),\n\t\t\t})\n\t\t\t// The user may have muted or left voice while the prompt was open.\n\t\t\tif (attempt !== this.#attempt || !this.#wanted) {\n\t\t\t\tstopTracks(stream)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.#adopt(stream)\n\n\t\t\t// After permission, labels exist. Prefer a built-in mic over Bluetooth when the caller\n\t\t\t// did not ask for a specific device and a better one is available.\n\t\t\tif (!preferred) {\n\t\t\t\tconst better = await this.#preferredDeviceId(stream)\n\t\t\t\tif (better && better !== this.#deviceId && attempt === this.#attempt && this.#wanted) {\n\t\t\t\t\tconst switched = await navigator.mediaDevices.getUserMedia({\n\t\t\t\t\t\taudio: audioConstraints(better),\n\t\t\t\t\t})\n\t\t\t\t\tif (attempt !== this.#attempt || !this.#wanted) {\n\t\t\t\t\t\tstopTracks(switched)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tstopTracks(stream)\n\t\t\t\t\tthis.#adopt(switched)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.#set('active')\n\t\t} catch (error) {\n\t\t\tif (attempt !== this.#attempt) return\n\t\t\tthis.#set(classifyGetUserMediaError(error))\n\t\t}\n\t}\n\n\t/**\n\t * Switch to the next audio input and reopen the stream. No-op with fewer than two devices.\n\t * Returns true when the stream was reopened on a different device.\n\t */\n\tasync cycleInput(): Promise<boolean> {\n\t\tconst devices = await this.listInputs()\n\t\tif (devices.length < 2) return false\n\t\tconst current = this.#deviceId ?? devices[0]!.deviceId\n\t\tconst index = Math.max(\n\t\t\t0,\n\t\t\tdevices.findIndex((d) => d.deviceId === current)\n\t\t)\n\t\tconst next = devices[(index + 1) % devices.length]!\n\t\tif (next.deviceId === current) return false\n\t\tthis.#deviceId = next.deviceId\n\t\tif (!this.#wanted || this.#state === 'muted' || this.#state === 'off') return false\n\t\tawait this.enable(next.deviceId)\n\t\treturn this.#state === 'active' && this.#deviceId === next.deviceId\n\t}\n\n\t/** Mute releases the microphone; unmute asks again. */\n\tsetMuted(muted: boolean): void {\n\t\tif (muted) {\n\t\t\tthis.#attempt++\n\t\t\tthis.#release()\n\t\t\tthis.#set('muted')\n\t\t\treturn\n\t\t}\n\t\tvoid this.enable(this.#deviceId ?? undefined)\n\t}\n\n\t/** Voice turned off: release the microphone and forget the request. */\n\tdisable(): void {\n\t\tthis.#wanted = false\n\t\tthis.#attempt++\n\t\tthis.#release()\n\t\tthis.#set('off')\n\t}\n\n\t#adopt(stream: MediaStream): void {\n\t\tthis.#clearTrackListeners()\n\t\tthis.#stream = stream\n\t\tconst track = stream.getAudioTracks()[0]\n\t\tif (!track) {\n\t\t\tthis.#label = ''\n\t\t\tthis.#deviceId = null\n\t\t\tthis.#hardwareMuted = false\n\t\t\treturn\n\t\t}\n\t\tthis.#label = track.label || this.#label\n\t\tconst settings = track.getSettings?.() ?? {}\n\t\tif (typeof settings.deviceId === 'string' && settings.deviceId) {\n\t\t\tthis.#deviceId = settings.deviceId\n\t\t}\n\t\tthis.#hardwareMuted = track.muted\n\t\tconst onMute = () => {\n\t\t\tthis.#hardwareMuted = true\n\t\t\tthis.#onChange()\n\t\t}\n\t\tconst onUnmute = () => {\n\t\t\tthis.#hardwareMuted = false\n\t\t\tthis.#onChange()\n\t\t}\n\t\tconst onEnded = () => {\n\t\t\tif (this.#stream === stream) {\n\t\t\t\tthis.#release()\n\t\t\t\tif (this.#wanted) this.#set('unsupported')\n\t\t\t}\n\t\t}\n\t\ttrack.addEventListener('mute', onMute)\n\t\ttrack.addEventListener('unmute', onUnmute)\n\t\ttrack.addEventListener('ended', onEnded)\n\t\tthis.#trackCleanups.push(() => {\n\t\t\ttrack.removeEventListener('mute', onMute)\n\t\t\ttrack.removeEventListener('unmute', onUnmute)\n\t\t\ttrack.removeEventListener('ended', onEnded)\n\t\t})\n\t}\n\n\tasync #preferredDeviceId(current: MediaStream): Promise<string | null> {\n\t\tconst devices = await this.listInputs()\n\t\tif (devices.length < 2) return null\n\t\tconst currentId =\n\t\t\tcurrent.getAudioTracks()[0]?.getSettings?.().deviceId ??\n\t\t\tthis.#deviceId ??\n\t\t\tdevices[0]!.deviceId\n\t\tconst currentLabel =\n\t\t\tdevices.find((d) => d.deviceId === currentId)?.label ??\n\t\t\tcurrent.getAudioTracks()[0]?.label ??\n\t\t\t''\n\t\tconst ranked = [...devices].sort(\n\t\t\t(a, b) => micPreferenceScore(b.label) - micPreferenceScore(a.label)\n\t\t)\n\t\tconst best = ranked[0]!\n\t\tif (micPreferenceScore(best.label) <= micPreferenceScore(currentLabel)) return null\n\t\tif (best.deviceId === currentId) return null\n\t\treturn best.deviceId\n\t}\n\n\t#clearTrackListeners(): void {\n\t\tfor (const stop of this.#trackCleanups) stop()\n\t\tthis.#trackCleanups = []\n\t}\n\n\t#release(): void {\n\t\tthis.#clearTrackListeners()\n\t\tif (this.#stream) stopTracks(this.#stream)\n\t\tthis.#stream = null\n\t\tthis.#hardwareMuted = false\n\t\t// Keep deviceId and label so unmute / cycle reopen the same choice and the UI can still name it.\n\t}\n\n\t#set(state: MicState): void {\n\t\tif (this.#state === state) return\n\t\tthis.#state = state\n\t\tthis.#onChange()\n\t}\n}\n\nfunction audioConstraints(deviceId?: string): MediaTrackConstraints {\n\tconst constraints: MediaTrackConstraints = {\n\t\techoCancellation: true,\n\t\tnoiseSuppression: true,\n\t\tautoGainControl: true,\n\t}\n\tif (deviceId) constraints.deviceId = { exact: deviceId }\n\treturn constraints\n}\n\nfunction classifyGetUserMediaError(error: unknown): MicState {\n\tconst name = error instanceof DOMException ? error.name : ''\n\tif (name === 'NotAllowedError' || name === 'SecurityError') return 'denied'\n\tif (name === 'NotReadableError' || name === 'AbortError') return 'busy'\n\treturn 'unsupported'\n}\n\nfunction stopTracks(stream: MediaStream): void {\n\tfor (const track of stream.getTracks()) track.stop()\n}\n","import type { ResultKind } from './feed'\nimport type { PanelAgentAdapter } from './types'\nimport type { VoiceRun } from './voiceRuns'\n\ntype HistoryEvent = PanelAgentAdapter['history'][number]\nexport interface RecoveredRun {\n\ttask: string\n\thistory: HistoryEvent[]\n\tresult: { kind: ResultKind; text: string } | null\n\tvoiceRuns: VoiceRun[]\n}\ntype StoragePort = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>\nconst KEY = 'page-agent-panel-recovery-v1'\nconst sensitive = /password|passwd|secret|token|api.?key|authorization|cookie/i\n\nfunction redact(value: unknown, depth = 0): unknown {\n\tif (depth > 8) return '[omitted]'\n\tif (Array.isArray(value)) return value.map((item) => redact(item, depth + 1))\n\tif (value && typeof value === 'object')\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(value).map(([key, item]) => [\n\t\t\t\tkey,\n\t\t\t\tsensitive.test(key) ? '[hidden]' : redact(item, depth + 1),\n\t\t\t])\n\t\t)\n\treturn value\n}\n\nfunction cleanEvent(event: HistoryEvent): HistoryEvent {\n\treturn {\n\t\ttype: event.type,\n\t\t...(event.stepIndex !== undefined ? { stepIndex: event.stepIndex } : {}),\n\t\t...(event.reflection ? { reflection: event.reflection } : {}),\n\t\t...(event.action\n\t\t\t? {\n\t\t\t\t\taction: {\n\t\t\t\t\t\tname: event.action.name,\n\t\t\t\t\t\tinput: redact(event.action.input),\n\t\t\t\t\t\toutput: event.action.output,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(event.content !== undefined ? { content: event.content } : {}),\n\t\t...(event.attempt !== undefined ? { attempt: event.attempt } : {}),\n\t\t...(event.maxAttempts !== undefined ? { maxAttempts: event.maxAttempts } : {}),\n\t\t...(event.message !== undefined ? { message: event.message } : {}),\n\t}\n}\n\n/** Tab-scoped display recovery. It never resumes a task or replays an action. */\nexport function createPanelRecovery(storage: StoragePort, key = KEY) {\n\treturn {\n\t\tload(): RecoveredRun[] {\n\t\t\tconst raw = storage.getItem(key)\n\t\t\tif (raw === null) return []\n\t\t\tconst data: unknown = JSON.parse(raw)\n\t\t\tif (\n\t\t\t\t!data ||\n\t\t\t\ttypeof data !== 'object' ||\n\t\t\t\t!('version' in data) ||\n\t\t\t\tdata.version !== 1 ||\n\t\t\t\t!('runs' in data) ||\n\t\t\t\t!Array.isArray(data.runs)\n\t\t\t)\n\t\t\t\tthrow new Error('Invalid recovery data')\n\t\t\tfor (const run of data.runs) {\n\t\t\t\tif (\n\t\t\t\t\t!run ||\n\t\t\t\t\ttypeof run !== 'object' ||\n\t\t\t\t\ttypeof run.task !== 'string' ||\n\t\t\t\t\t!Array.isArray(run.history) ||\n\t\t\t\t\t!Array.isArray(run.voiceRuns) ||\n\t\t\t\t\trun.history.some(\n\t\t\t\t\t\t(event: unknown) =>\n\t\t\t\t\t\t\t!event ||\n\t\t\t\t\t\t\ttypeof event !== 'object' ||\n\t\t\t\t\t\t\t!('type' in event) ||\n\t\t\t\t\t\t\t!['step', 'observation', 'user_takeover', 'retry', 'error'].includes(\n\t\t\t\t\t\t\t\tString(event.type)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t) ||\n\t\t\t\t\trun.voiceRuns.some(\n\t\t\t\t\t\t(voice: unknown) =>\n\t\t\t\t\t\t\t!voice ||\n\t\t\t\t\t\t\ttypeof voice !== 'object' ||\n\t\t\t\t\t\t\t!('id' in voice) ||\n\t\t\t\t\t\t\t!('script' in voice) ||\n\t\t\t\t\t\t\t!('status' in voice) ||\n\t\t\t\t\t\t\t!('at' in voice)\n\t\t\t\t\t) ||\n\t\t\t\t\t(run.result !== null &&\n\t\t\t\t\t\t(!run.result ||\n\t\t\t\t\t\t\ttypeof run.result !== 'object' ||\n\t\t\t\t\t\t\t!['done', 'notDone', 'stopped', 'error'].includes(run.result.kind) ||\n\t\t\t\t\t\t\ttypeof run.result.text !== 'string'))\n\t\t\t\t)\n\t\t\t\t\tthrow new Error('Invalid recovery run')\n\t\t\t}\n\t\t\treturn data.runs as RecoveredRun[]\n\t\t},\n\t\tsave(runs: RecoveredRun[]): void {\n\t\t\tconst clean = runs.map((run) => ({ ...run, history: run.history.map(cleanEvent) }))\n\t\t\tstorage.setItem(key, JSON.stringify({ version: 1, runs: clean }))\n\t\t},\n\t\tclear(): void {\n\t\t\tstorage.removeItem(key)\n\t\t},\n\t}\n}\n","import type { TranslationKey, TranslationParams } from '../i18n'\nimport type { PanelAgentAdapter } from './types'\n\ntype Translate = (key: TranslationKey, params?: TranslationParams) => string\ntype HistoryEvent = PanelAgentAdapter['history'][number]\n\nexport interface TraceRun {\n\ttask: string\n\thistory: readonly HistoryEvent[]\n\toutcome: string\n}\n\n/**\n * Compact plain-text trace of one or more tasks, one block per step. Built only from the history the\n * panel already receives; it is read-only and does not change what the agent sees or does.\n */\nexport function formatTrace(runs: readonly TraceRun[], t: Translate, now: Date): string {\n\tconst lines: string[] = [`NoStop log ${now.toISOString()}`]\n\truns.forEach((run, index) => {\n\t\tlines.push('', `== ${t('ui.panel.logTask')} ${index + 1}: ${run.task}`)\n\t\tfor (const e of run.history) {\n\t\t\tif (e.type === 'step') {\n\t\t\t\tconst step = e.stepIndex !== undefined ? `step ${e.stepIndex + 1}` : 'step'\n\t\t\t\tconst r = e.reflection\n\t\t\t\tif (r?.evaluation_previous_goal)\n\t\t\t\t\tlines.push(`${step} | ${t('ui.panel.evaluation')}: ${r.evaluation_previous_goal}`)\n\t\t\t\tif (r?.memory) lines.push(`${step} | ${t('ui.panel.memory')}: ${r.memory}`)\n\t\t\t\tif (r?.next_goal) lines.push(`${step} | ${t('ui.panel.nextGoal')}: ${r.next_goal}`)\n\t\t\t\tif (e.action) {\n\t\t\t\t\tconst input = JSON.stringify(e.action.input ?? {})\n\t\t\t\t\tlines.push(\n\t\t\t\t\t\t`${step} | ${t('ui.panel.logAction')}: ${e.action.name} ${input} -> ${e.action.output ?? ''}`\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t} else if (e.type === 'observation') {\n\t\t\t\tlines.push(`obs | ${e.content ?? ''}`)\n\t\t\t} else if (e.type === 'retry') {\n\t\t\t\tlines.push(`retry | ${e.message ?? ''} (${e.attempt}/${e.maxAttempts})`)\n\t\t\t} else if (e.type === 'error') {\n\t\t\t\tlines.push(`error | ${e.message ?? ''}`)\n\t\t\t} else if (e.type === 'user_takeover') {\n\t\t\t\tlines.push(`user | ${t('ui.panel.userTakeover')}`)\n\t\t\t}\n\t\t}\n\t\tif (run.outcome) lines.push(`${t('ui.panel.logResult')}: ${run.outcome}`)\n\t})\n\treturn lines.join('\\n') + '\\n'\n}\n","/**\n * Scripts the voice ran in the page, shown in the conversation. The panel owns this list; it is separate from\n * the agent history, which only records the agent's own steps.\n */\nexport type VoiceRunStatus = 'running' | 'done' | 'refused'\n\nexport interface VoiceRun {\n\tid: number\n\tscript: string\n\t/** What the model received back. Undefined while the script runs. */\n\toutput?: string\n\tstatus: VoiceRunStatus\n\t/** When the script was requested (epoch milliseconds). */\n\tat: number\n}\n\nexport class VoiceRuns {\n\t#runs: VoiceRun[] = []\n\t#nextId = 1\n\n\tget list(): readonly VoiceRun[] {\n\t\treturn this.#runs\n\t}\n\n\t/** A script that starts running now. */\n\tstart(script: string, at: number): VoiceRun {\n\t\tconst run: VoiceRun = { id: this.#nextId++, script, status: 'running', at }\n\t\tthis.#runs.push(run)\n\t\treturn run\n\t}\n\n\t/** Records the output of a running script. Unknown ids are ignored. */\n\tfinish(id: number, output: string): void {\n\t\tconst run = this.#runs.find((r) => r.id === id)\n\t\tif (!run) return\n\t\trun.status = 'done'\n\t\trun.output = output\n\t}\n\n\t/** A script the panel did not run, with the reason it gave the model. */\n\trefuse(script: string, output: string, at: number): void {\n\t\tthis.#runs.push({ id: this.#nextId++, script, output, status: 'refused', at })\n\t}\n\n\t/** Hands every run to the caller and empties the list. Used when the conversation is archived. */\n\ttakeAll(): VoiceRun[] {\n\t\tconst runs = this.#runs\n\t\tthis.#runs = []\n\t\treturn runs\n\t}\n}\n","import { I18n, type TranslationKey, type TranslationParams } from '../i18n'\nimport { GeminiLiveClient } from '../voice/gemini-client'\nimport { RealtimeClient } from '../voice/realtime-client'\nimport { languageRule, resolveVoicePrompt } from '../voice/voice-prompt'\nimport { type VoiceError, VoiceSession, type VoiceState } from '../voice/voice-session'\nimport { type ResultKind, buildFeed, lastOutcomeText, localizeCore, toolLabel } from './feed'\nimport { type IconName, icon } from './icons'\nimport { MicrophoneControl } from './microphone'\nimport { createPanelRecovery } from './recovery'\nimport { scriptCard } from './scriptCard'\nimport { formatTrace } from './trace'\nimport type {\n\tAgentActivity,\n\tPanelAgentAdapter,\n\tStudioRecordedStep,\n\tStudioSkillCatalogEntry,\n\tStudioSkillWatchEntry,\n} from './types'\nimport { type VoiceRun, VoiceRuns } from './voiceRuns'\n\nimport styles from './Panel.module.css'\n\n/**\n * Panel configuration\n */\nexport interface PanelConfig {\n\t/** Restore this tab's displayed conversation after reload. Disabled by default. */\n\tsessionRecovery?: boolean\n\t/** Storage key used to isolate independent agents on the same origin. */\n\tsessionRecoveryKey?: string\n\t/** 'en-US' or 'pt-BR'; any other value falls back to English. */\n\tlanguage?: string\n\t/**\n\t * Whether to keep the composer available after a task ends\n\t * @default true\n\t */\n\tpromptForNextTask?: boolean\n\t/** Name shown in the header. @default 'NoStop' */\n\tname?: string\n\t/** Voice mode through the OpenAI Realtime API. Development setup: the key is used directly from the browser. */\n\t/** Runs a script in the page for the voice, with the page-agent instance in scope as `agent`. */\n\trunScript?: (script: string) => Promise<string>\n\tvoice?: {\n\t\tapiKey: string\n\t\t/** Voice provider. Default 'openai'. REVERSIBLE (2026-11-17, gemini provider). */\n\t\tprovider?: 'openai' | 'gemini'\n\t\t/** Added after the default voice prompt, which is kept. `null` or empty keeps only the default. */\n\t\tsystemPrompt?: string | null\n\t\t/**\n\t\t * Let `systemPrompt` replace the default voice prompt instead of being added to it.\n\t\t * REVERSIBLE (2026-11-23, system prompt override). @default false\n\t\t */\n\t\toverrideSystemPrompt?: boolean\n\t}\n}\n\nconst DRAG_KEY = 'page-agent-panel-position'\nconst FAB_KEY = 'page-agent-fab-corner'\nconst FAB_MARGIN = 16\nconst CORNERS = ['left-top', 'right-top', 'left-bottom', 'right-bottom'] as const\ntype Corner = (typeof CORNERS)[number]\n\ntype HistoryEvent = PanelAgentAdapter['history'][number]\n\n/** Latest meaningful text of a run: its outcome, else the last step output or observation. */\nfunction excerptOf(history: readonly HistoryEvent[], outcome: string): string {\n\tif (outcome) return outcome\n\tfor (let i = history.length - 1; i >= 0; i--) {\n\t\tconst e = history[i]\n\t\tif (e.type === 'step' && e.action?.output) return e.action.output\n\t\tif (e.type === 'observation' && e.content) return e.content\n\t}\n\treturn ''\n}\n\n/** Site favicon when available; the brand glyph otherwise. */\nfunction fillBrand(el: HTMLElement): void {\n\tel.textContent = ''\n\tconst siteIcon = document.querySelector<HTMLLinkElement>('link[rel~=\"icon\"][href]')\n\tif (!siteIcon) {\n\t\tel.innerHTML = icon('spark')\n\t\treturn\n\t}\n\tconst img = document.createElement('img')\n\timg.alt = ''\n\timg.src = siteIcon.href\n\timg.onerror = () => {\n\t\tel.innerHTML = icon('spark')\n\t}\n\tel.append(img)\n}\n\n/** Icon button: icon plus a short hover/focus hint, also used as the accessible name. */\nfunction setButton(el: HTMLElement, name: IconName, tip: string): void {\n\tel.innerHTML = icon(name)\n\tel.dataset.tip = tip\n\tel.setAttribute('aria-label', tip)\n\tel.removeAttribute('title')\n}\nconst CURSOR_ATTR = 'data-pa-cursor-hidden'\n/** Distance from the end (px) that still counts as \"following the conversation\". */\nconst PIN_PX = 72\n/** Window after a user scroll gesture (wheel, touch, keys, scrollbar) in which scrolling away unpins the feed. */\nconst INTENT_MS = 600\n/** Narrow viewports use expanded → bar → fab follow-mode cycling. */\nconst FOLLOW_CYCLE_MQ = '(max-width: 480px)'\ntype FollowMode = 'fab' | 'bar' | 'expanded'\n\n/**\n * Agent control panel.\n *\n * The conversation is rebuilt from `agent.history`, `agent.task`, the live\n * `activity` events and the pending question. History is the single source of\n * truth for what happened; activity only describes what is happening now.\n */\nexport class Panel {\n\t#wrapper: HTMLElement\n\t#agent: PanelAgentAdapter\n\t#config: PanelConfig\n\t#i18n: I18n\n\n\t#feed: HTMLElement\n\t#statusText: HTMLElement\n\t#textarea: HTMLTextAreaElement\n\t#answerContext: HTMLElement\n\t#sendButton: HTMLButtonElement\n\t#micButton: HTMLButtonElement\n\t#attachButton: HTMLButtonElement | null = null\n\t#attachInput: HTMLInputElement | null = null\n\t#attachList: HTMLElement | null = null\n\t#composer: HTMLFormElement\n\t#voiceStage: HTMLElement\n\t#studioStage: HTMLElement\n\t#skillsButton!: HTMLButtonElement\n\t#feedWrap: HTMLElement\n\t#stopButton: HTMLButtonElement\n\t#collapseButton: HTMLButtonElement\n\t#cursorButton: HTMLButtonElement\n\t#exportButton!: HTMLButtonElement\n\t#attachError = ''\n\t#studioTab: 'record' | 'ask' | 'catalog' = 'record'\n\t#studioMessage = ''\n\t#studioMessageTone: 'ok' | 'warn' | 'err' | '' = ''\n\t#studioPreview = ''\n\t#studioPreviewId = ''\n\t#studioBusy = false\n\t#studioPoll: ReturnType<typeof setInterval> | null = null\n\t#studioCatalog: StudioSkillCatalogEntry[] = []\n\t#studioWatches: StudioSkillWatchEntry[] = []\n\t#studioListenersBound = false\n\n\t#collapsed = false\n\t/** Mobile follow chrome: expanded card, slim status bar, or floating orb. */\n\t#followMode: FollowMode = 'expanded'\n\t#followBar!: HTMLElement\n\t#mode: 'text' | 'voice' | 'skills-studio' = 'text'\n\t/** Mode to restore when leaving Skills Studio. */\n\t#modeBeforeStudio: 'text' | 'voice' = 'text'\n\t#mic = new MicrophoneControl(() => this.#render())\n\t#voice!: VoiceSession\n\t/** Whether the outcome of the current run was already spoken. */\n\t#outcomeSpoken = false\n\t#live: AgentActivity | null = null\n\t#question: { text: string; resolve: (answer: string) => void } | null = null\n\n\t#fab!: HTMLButtonElement\n\t#rail!: HTMLElement\n\t#thumb!: HTMLElement\n\t#jump!: HTMLButtonElement\n\t/** true while the feed follows new content (pinned to the end). */\n\t#follow = true\n\t/** New history events that arrived while the user was reading above. */\n\t#pending = 0\n\t#seen = 0\n\t/** Pin the latest user turn to the top after a new task is sent. */\n\t#anchorTurn = false\n\t#intentUntil = 0\n\t/** Finished tasks kept on screen (in memory). The agent itself still starts each task fresh. */\n\t#archive: {\n\t\ttask: string\n\t\thistory: HistoryEvent[]\n\t\tresult: { kind: ResultKind; text: string } | null\n\t\tvoiceRuns: VoiceRun[]\n\t}[] = []\n\t#recovery: ReturnType<typeof createPanelRecovery> | null = null\n\t#recoveryWarning = false\n\t/** Scripts the voice ran during the current turn. */\n\t#voiceRuns = new VoiceRuns()\n\t// REVERSIBLE (2026-11-17, feed stability): key and count of the last feed build. Remove both fields and the block at #render to revert.\n\t#lastRenderKey = ''\n\t#renderedCount = 0\n\t/** Pinned tasks, by run index. */\n\t#pins = new Set<number>()\n\t#peek!: HTMLElement\n\t#peekTimer: ReturnType<typeof setTimeout> | undefined\n\t#dragOrigin: { dx: number; dy: number } | null = null\n\t#dragged = false\n\n\t#onStatusChange = () => {\n\t\tthis.#speakOutcome()\n\t\tthis.#render()\n\t}\n\t#onHistoryChange = () => {\n\t\tif (this.#live?.type === 'executing') this.#live = null\n\t\tthis.#render()\n\t}\n\t#onActivity = (e: Event) => {\n\t\tthis.#live = (e as CustomEvent<AgentActivity>).detail\n\t\tthis.#render()\n\t}\n\t#onAgentDispose = () => this.dispose()\n\t#onSkillWatchEvent = (e: Event) => {\n\t\tthis.#refreshStudioWatches()\n\t\tif (e.type === 'skills:watch-fired') {\n\t\t\tconst detail = (e as CustomEvent<{ message?: string; skillId?: string; command?: string }>)\n\t\t\t\t.detail\n\t\t\tconst message = detail?.message?.trim() || detail?.skillId || 'ok'\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioWatchFired', { message }), 'ok')\n\t\t}\n\t\tif (this.#mode === 'skills-studio') this.#renderSkillsStudio()\n\t}\n\n\tget wrapper(): HTMLElement {\n\t\treturn this.#wrapper\n\t}\n\n\t/**\n\t * Create a Panel bound to an agent\n\t * @param agent - Agent instance that implements PanelAgentAdapter\n\t * @param config - Optional panel configuration\n\t */\n\tconstructor(agent: PanelAgentAdapter, config: PanelConfig = {}) {\n\t\tthis.#agent = agent\n\t\tthis.#config = config\n\t\tthis.#i18n = new I18n(config.language ?? 'en-US')\n\t\tif (config.sessionRecovery === true) {\n\t\t\ttry {\n\t\t\t\tthis.#recovery = createPanelRecovery(window.sessionStorage, config.sessionRecoveryKey)\n\t\t\t\tthis.#archive = this.#recovery.load()\n\t\t\t} catch (error) {\n\t\t\t\tthis.#recovery = null\n\t\t\t\tconsole.warn('[page-agent] Conversation recovery unavailable', error)\n\t\t\t}\n\t\t}\n\n\t\tthis.#agent.onAskUser = (question, options) => this.#askUser(question, options?.signal)\n\n\t\tthis.#wrapper = this.#createWrapper()\n\t\tthis.#feed = this.#wrapper.querySelector<HTMLElement>('[data-role=\"feed\"]')!\n\t\t// REVERSIBLE (2026-11-17, autoscroll): when the feed gets shorter (the composer grows, the reply strip appears),\n\t\t// keep the newest item visible while the user is following the conversation. Remove this observer to revert.\n\t\tif (typeof ResizeObserver !== 'undefined')\n\t\t\tnew ResizeObserver(() => {\n\t\t\t\tif (this.#follow) this.#feed.scrollTop = this.#feed.scrollHeight\n\t\t\t}).observe(this.#feed)\n\t\tthis.#statusText = this.#wrapper.querySelector<HTMLElement>('[data-role=\"status\"]')!\n\t\tthis.#textarea = this.#wrapper.querySelector<HTMLTextAreaElement>('[data-role=\"input\"]')!\n\t\tthis.#answerContext = this.#wrapper.querySelector<HTMLElement>('[data-role=\"answer-context\"]')!\n\t\tthis.#sendButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"send\"]')!\n\t\tthis.#micButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"mic\"]')!\n\t\tthis.#attachButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"attach\"]')\n\t\tthis.#attachInput = this.#wrapper.querySelector<HTMLInputElement>('[data-role=\"attach-input\"]')\n\t\tthis.#attachList = this.#wrapper.querySelector<HTMLElement>('[data-role=\"attach-list\"]')\n\t\tthis.#composer = this.#wrapper.querySelector<HTMLFormElement>('[data-role=\"composer\"]')!\n\t\tthis.#voiceStage = this.#wrapper.querySelector<HTMLElement>('[data-role=\"voice\"]')!\n\t\tthis.#studioStage = this.#wrapper.querySelector<HTMLElement>('[data-role=\"skills-studio\"]')!\n\t\tthis.#feedWrap = this.#wrapper.querySelector<HTMLElement>('[data-role=\"feed-wrap\"]')!\n\t\tthis.#skillsButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"skills\"]')!\n\t\tthis.#stopButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"action\"]')!\n\t\tthis.#collapseButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"collapse\"]')!\n\t\tthis.#cursorButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"cursor\"]')!\n\t\tthis.#exportButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"export\"]')!\n\t\tthis.#followBar = this.#wrapper.querySelector<HTMLElement>('[data-role=\"follow-bar\"]')!\n\t\tthis.#exportButton.addEventListener('click', (e) => {\n\t\t\te.stopPropagation()\n\t\t\tthis.#exportLog()\n\t\t})\n\n\t\tthis.#agent.addEventListener('statuschange', this.#onStatusChange)\n\t\tthis.#agent.addEventListener('historychange', this.#onHistoryChange)\n\t\tthis.#agent.addEventListener('activity', this.#onActivity)\n\t\tthis.#agent.addEventListener('dispose', this.#onAgentDispose)\n\t\tthis.#agent.addEventListener('skills:watch-armed', this.#onSkillWatchEvent)\n\t\tthis.#agent.addEventListener('skills:watch-fired', this.#onSkillWatchEvent)\n\t\tthis.#agent.addEventListener('skills:watch-stopped', this.#onSkillWatchEvent)\n\n\t\tthis.#voice = this.#createVoice()\n\t\tthis.#setupEventListeners()\n\t\tthis.#setupFeed()\n\t\tthis.#setupPlacement()\n\t\tthis.#refreshStudioWatches()\n\t\tthis.#render()\n\n\t\tthis.#setupFab()\n\t\tthis.hide() // Start hidden, as the floating button\n\t}\n\n\t// ========== Public control methods ==========\n\n\tshow(): void {\n\t\tif (this.#followMode === 'fab') {\n\t\t\tthis.#followMode = 'expanded'\n\t\t\tthis.#collapsed = false\n\t\t}\n\t\tthis.#fab.hidden = true\n\t\tthis.wrapper.dataset.follow = this.#followMode\n\t\tthis.wrapper.style.display = 'flex'\n\t\tthis.wrapper.getBoundingClientRect() // force reflow before opacity transition\n\t\tthis.wrapper.style.opacity = '1'\n\t\tthis.wrapper.style.transform = 'translateY(0)'\n\t\tthis.#render()\n\t}\n\n\thide(): void {\n\t\tthis.#followMode = 'fab'\n\t\tthis.#collapsed = true\n\t\tthis.wrapper.dataset.follow = 'fab'\n\t\tthis.wrapper.style.opacity = '0'\n\t\tthis.wrapper.style.transform = 'translateY(20px)'\n\t\tthis.wrapper.style.display = 'none'\n\t\tthis.#fab.hidden = false\n\t\tthis.#syncFollowFabLabel()\n\t}\n\n\treset(): void {\n\t\tthis.#question = null\n\t\tthis.#live = null\n\t\tthis.#mode = 'text'\n\t\tthis.#followMode = 'bar'\n\t\tthis.#collapsed = true\n\t\tthis.#render()\n\t}\n\n\texpand(): void {\n\t\tthis.#setFollowMode('expanded')\n\t}\n\n\tcollapse(): void {\n\t\tthis.#setFollowMode('bar')\n\t}\n\n\t/**\n\t * Dispose panel and clean up event listeners\n\t */\n\tdispose(): void {\n\t\tthis.#stopStudioPolling()\n\t\tif (this.#agent.isSkillRecording?.()) this.#agent.stopSkillRecording?.()\n\t\tthis.#voice.disable()\n\t\tthis.#fab.remove()\n\t\tthis.#agent.removeEventListener('statuschange', this.#onStatusChange)\n\t\tthis.#agent.removeEventListener('historychange', this.#onHistoryChange)\n\t\tthis.#agent.removeEventListener('activity', this.#onActivity)\n\t\tthis.#agent.removeEventListener('dispose', this.#onAgentDispose)\n\t\tthis.#agent.removeEventListener('skills:watch-armed', this.#onSkillWatchEvent)\n\t\tthis.#agent.removeEventListener('skills:watch-fired', this.#onSkillWatchEvent)\n\t\tthis.#agent.removeEventListener('skills:watch-stopped', this.#onSkillWatchEvent)\n\t\tthis.#question = null\n\t\tthis.wrapper.remove()\n\t}\n\n\t// ========== Feed scrolling ==========\n\n\t/**\n\t * Smart follow: the feed sticks to the end only while the user is near it. A scroll the user\n\t * started (wheel, touch, keys, scrollbar) unpins it; content growing does not. A new task pins\n\t * its turn to the top; new events while reading above are counted on a jump pill.\n\t */\n\t#afterFeedUpdate(): void {\n\t\tconst feed = this.#feed\n\t\tconst total = this.#agent.history.length\n\t\tconst added = Math.max(0, total - this.#seen)\n\t\tthis.#seen = total\n\n\t\tif (this.#question) this.#follow = true\n\t\tif (this.#anchorTurn) {\n\t\t\tthis.#anchorTurn = false\n\t\t\tconst turns = feed.querySelectorAll<HTMLElement>('[data-mark=\"turn\"]')\n\t\t\tconst last = turns[turns.length - 1]\n\t\t\tif (last) {\n\t\t\t\tthis.#follow = false\n\t\t\t\tfeed.scrollTop = last.offsetTop - 12\n\t\t\t}\n\t\t} else if (this.#follow) {\n\t\t\tfeed.scrollTop = feed.scrollHeight\n\t\t} else if (added > 0 || this.#question) {\n\t\t\tthis.#pending += added\n\t\t}\n\t\tthis.#placeRailMarks()\n\t\tthis.#refreshFeed()\n\t}\n\n\t#setupFeed(): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\t// The page may run its own smooth scrolling (for example Lenis). Keep wheel and touch inside the panel:\n\t\t// Lenis skips elements marked with data-lenis-prevent, and the event never reaches page listeners.\n\t\tthis.#wrapper.setAttribute('data-lenis-prevent', '')\n\t\tconst keepInside = (e: Event) => e.stopPropagation()\n\t\tthis.#wrapper.addEventListener('wheel', keepInside, { passive: true })\n\t\tthis.#wrapper.addEventListener('touchmove', keepInside, { passive: true })\n\t\tthis.#rail = this.#wrapper.querySelector<HTMLElement>('[data-role=\"rail\"]')!\n\t\tthis.#thumb = this.#wrapper.querySelector<HTMLElement>('[data-role=\"thumb\"]')!\n\t\tthis.#jump = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"jump\"]')!\n\t\tconst feed = this.#feed\n\n\t\tconst intent = () => {\n\t\t\tthis.#intentUntil = performance.now() + INTENT_MS\n\t\t}\n\t\tfeed.addEventListener('wheel', intent, { passive: true })\n\t\tfeed.addEventListener('touchstart', intent, { passive: true })\n\t\tfeed.addEventListener('mousedown', intent)\n\t\tfeed.addEventListener('keydown', (e) => {\n\t\t\tif (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '].includes(e.key))\n\t\t\t\tintent()\n\t\t\tif (e.key === 'Home' || e.key === 'End') {\n\t\t\t\te.preventDefault()\n\t\t\t\tthis.#scrollFeed(e.key === 'End' ? 'end' : 'start')\n\t\t\t}\n\t\t})\n\t\tfeed.addEventListener('scroll', () => {\n\t\t\tconst atEnd = feed.scrollHeight - feed.scrollTop - feed.clientHeight < PIN_PX\n\t\t\tif (atEnd) {\n\t\t\t\tthis.#follow = true\n\t\t\t\tthis.#pending = 0\n\t\t\t} else if (performance.now() < this.#intentUntil) {\n\t\t\t\tthis.#follow = false\n\t\t\t}\n\t\t\tthis.#refreshFeed()\n\t\t})\n\t\tnew ResizeObserver(() => {\n\t\t\tthis.#placeRailMarks()\n\t\t\tthis.#refreshFeed()\n\t\t}).observe(feed)\n\n\t\tthis.#jump.addEventListener('click', () => this.#scrollFeed('end'))\n\t\tthis.#peek = this.#wrapper.querySelector<HTMLElement>('[data-role=\"peek\"]')!\n\t\tthis.#rail.addEventListener('pointerover', (e) => {\n\t\t\tconst tick = (e.target as HTMLElement).closest<HTMLElement>('[data-mark-dot]')\n\t\t\tif (tick) this.#showPeek(tick)\n\t\t})\n\t\tthis.#rail.addEventListener('pointerleave', () => this.#scheduleHidePeek())\n\t\tthis.#peek.addEventListener('pointerenter', () => clearTimeout(this.#peekTimer))\n\t\tthis.#peek.addEventListener('pointerleave', () => this.#scheduleHidePeek())\n\t\tthis.#peek.addEventListener('click', (e) => {\n\t\t\tconst pin = (e.target as HTMLElement).closest<HTMLElement>('[data-role=\"pin\"]')\n\t\t\tif (!pin) return\n\t\t\tconst run = Number(pin.dataset.run)\n\t\t\tif (this.#pins.has(run)) this.#pins.delete(run)\n\t\t\telse this.#pins.add(run)\n\t\t\tthis.#peek.hidden = true\n\t\t\tthis.#render()\n\t\t})\n\t\tthis.#jump.setAttribute('aria-label', t('ui.panel.jumpLatest'))\n\t\tthis.#rail.addEventListener('click', (e) => {\n\t\t\tconst mark = (e.target as HTMLElement).closest<HTMLElement>('[data-target]')\n\t\t\tif (!mark) return\n\t\t\tconst target = feed.querySelector<HTMLElement>(`[data-id=\"${mark.dataset.target}\"]`)\n\t\t\tif (!target) return\n\t\t\tthis.#follow = false\n\t\t\tfeed.scrollTo({ top: target.offsetTop - 12, behavior: this.#motion() })\n\t\t})\n\t}\n\n\t#motion(): ScrollBehavior {\n\t\treturn window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth'\n\t}\n\n\t#scrollFeed(where: 'start' | 'end'): void {\n\t\tconst feed = this.#feed\n\t\tthis.#follow = where === 'end'\n\t\tif (where === 'end') this.#pending = 0\n\t\tfeed.scrollTo({ top: where === 'end' ? feed.scrollHeight : 0, behavior: this.#motion() })\n\t\tthis.#refreshFeed()\n\t}\n\n\t/** Thumb, markers, edge fades and jump pill, derived from the current scroll position. */\n\t#refreshFeed(): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst feed = this.#feed\n\t\tconst max = feed.scrollHeight - feed.clientHeight\n\t\tconst overflow = max > 4\n\t\tconst top = feed.scrollTop > 8\n\t\tconst bottom = max - feed.scrollTop > 8\n\n\t\t// Edge fades only on the sides that have more content.\n\t\tconst start = top ? 'transparent 0, #000 24px' : '#000 0'\n\t\tconst end = bottom ? '#000 calc(100% - 24px), transparent 100%' : '#000 100%'\n\t\tconst mask = overflow ? `linear-gradient(to bottom, ${start}, ${end})` : 'none'\n\t\tfeed.style.maskImage = mask\n\t\tfeed.style.webkitMaskImage = mask\n\n\t\tthis.#rail.hidden = !overflow\n\t\tconst turns = feed.querySelectorAll<HTMLElement>('[data-mark=\"turn\"]')\n\t\tlet activeId = ''\n\t\tturns.forEach((el) => {\n\t\t\tif (el.offsetTop <= feed.scrollTop + 48) activeId = el.dataset.id ?? ''\n\t\t})\n\t\tthis.#rail.querySelectorAll<HTMLElement>('[data-mark-dot]').forEach((tick) => {\n\t\t\ttick.dataset.active = String(tick.dataset.target === activeId)\n\t\t})\n\t\tif (overflow) {\n\t\t\tconst ratio = feed.clientHeight / feed.scrollHeight\n\t\t\tconst railHeight = this.#rail.clientHeight\n\t\t\tthis.#thumb.style.height = `${Math.max(24, ratio * railHeight)}px`\n\t\t\tthis.#thumb.style.top = `${(feed.scrollTop / feed.scrollHeight) * railHeight}px`\n\t\t}\n\n\t\tconst showJump =\n\t\t\t!this.#follow && (this.#pending > 0 || this.#question !== null || (overflow && bottom))\n\t\tthis.#jump.hidden = !showJump\n\t\tif (showJump) {\n\t\t\tthis.#jump.innerHTML = `${icon('arrowDown')}<span>${this.#pending > 0 ? t('ui.panel.newCount', { count: String(this.#pending) }) : t('ui.panel.jumpLatest')}</span>`\n\t\t}\n\t}\n\n\t/** Ticks on the rail for turns (tasks), questions and results. Each one jumps to its place. */\n\t#placeRailMarks(): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst feed = this.#feed\n\t\tconst railHeight = this.#rail.clientHeight\n\t\tthis.#rail.querySelectorAll('[data-mark-dot]').forEach((n) => n.remove())\n\t\tfeed.querySelectorAll<HTMLElement>('[data-mark]').forEach((el, index) => {\n\t\t\tconst id = `m${index}`\n\t\t\tel.dataset.id = id\n\t\t\tconst kind = el.dataset.mark ?? ''\n\t\t\tconst tick = document.createElement('button')\n\t\t\ttick.type = 'button'\n\t\t\ttick.className = styles.railMark\n\t\t\ttick.dataset.markDot = ''\n\t\t\ttick.dataset.kind = kind\n\t\t\ttick.dataset.target = id\n\t\t\ttick.dataset.run = el.dataset.run ?? ''\n\t\t\ttick.dataset.pinned = el.dataset.pinned ?? 'false'\n\t\t\ttick.dataset.title = kind === 'turn' ? (el.textContent ?? '') : ''\n\t\t\ttick.dataset.preview = el.dataset.preview ?? ''\n\t\t\ttick.style.top = `${(el.offsetTop / feed.scrollHeight) * railHeight}px`\n\t\t\ttick.setAttribute(\n\t\t\t\t'aria-label',\n\t\t\t\tkind === 'turn' ? (el.textContent ?? '') : t('ui.panel.step', { number: String(index + 1) })\n\t\t\t)\n\t\t\tthis.#rail.append(tick)\n\t\t})\n\t}\n\n\t/** Hover card for a rail tick: title, short excerpt and a pin toggle for tasks. */\n\t#showPeek(tick: HTMLElement): void {\n\t\tclearTimeout(this.#peekTimer)\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst peek = this.#peek\n\t\tconst run = tick.dataset.run ?? ''\n\t\tpeek.replaceChildren()\n\t\tconst head = document.createElement('div')\n\t\thead.className = styles.peekHead\n\t\tconst title = document.createElement('strong')\n\t\tconst kindTitle =\n\t\t\ttick.dataset.kind === 'question'\n\t\t\t\t? t('ui.panel.questionTitle')\n\t\t\t\t: tick.dataset.kind === 'result'\n\t\t\t\t\t? t('ui.panel.resultTitle')\n\t\t\t\t\t: ''\n\t\ttitle.textContent = tick.dataset.title || kindTitle\n\t\thead.append(title)\n\t\tif (run !== '') {\n\t\t\tconst pin = document.createElement('button')\n\t\t\tconst pinned = this.#pins.has(Number(run))\n\t\t\tpin.type = 'button'\n\t\t\tpin.className = styles.pin\n\t\t\tpin.dataset.role = 'pin'\n\t\t\tpin.dataset.run = run\n\t\t\tpin.setAttribute('aria-pressed', String(pinned))\n\t\t\tpin.setAttribute('aria-label', t(pinned ? 'ui.panel.unpin' : 'ui.panel.pin'))\n\t\t\tpin.innerHTML = icon('bookmark')\n\t\t\thead.append(pin)\n\t\t}\n\t\tconst body = document.createElement('p')\n\t\tbody.className = styles.peekText\n\t\tbody.textContent = localizeCore(tick.dataset.preview ?? '', t)\n\t\tpeek.append(head, body)\n\t\tpeek.hidden = false\n\t\t// Align with the tick, kept inside the feed area.\n\t\tconst wrap = this.#feed.parentElement!.getBoundingClientRect()\n\t\tconst here = tick.getBoundingClientRect()\n\t\tconst top = Math.min(Math.max(8, here.top - wrap.top - 16), wrap.height - peek.offsetHeight - 8)\n\t\tpeek.style.top = `${top}px`\n\t}\n\n\t#scheduleHidePeek(): void {\n\t\tclearTimeout(this.#peekTimer)\n\t\tthis.#peekTimer = setTimeout(() => {\n\t\t\tthis.#peek.hidden = true\n\t\t}, 140)\n\t}\n\n\t/** Keep the run index on turn nodes so pins and the rail can refer to them. */\n\t#annotate(\n\t\tnodes: HTMLElement[],\n\t\tindex: number,\n\t\thistory: readonly HistoryEvent[],\n\t\tresult: { kind: ResultKind; text: string } | null\n\t): void {\n\t\tconst excerpt = excerptOf(history, result?.text ?? '')\n\t\tfor (const node of nodes) {\n\t\t\tif (node.dataset.mark !== 'turn') continue\n\t\t\tnode.dataset.run = String(index)\n\t\t\tnode.dataset.pinned = String(this.#pins.has(index))\n\t\t\tnode.dataset.preview = excerpt\n\t\t}\n\t}\n\n\t#saveRecovery(): void {\n\t\tif (!this.#recovery) return\n\t\tconst runs = [...this.#archive]\n\t\tif (this.#agent.task || this.#agent.history.length || this.#voiceRuns.list.length) {\n\t\t\truns.push({\n\t\t\t\ttask: this.#agent.task || '',\n\t\t\t\thistory: [...this.#agent.history],\n\t\t\t\tresult:\n\t\t\t\t\tthis.#agent.status === 'running'\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tkind: 'stopped',\n\t\t\t\t\t\t\t\ttext: 'Interrupted by reload or navigation. Actions were not replayed.',\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: this.#resultKind(),\n\t\t\t\tvoiceRuns: [...this.#voiceRuns.list],\n\t\t\t})\n\t\t}\n\t\ttry {\n\t\t\tthis.#recovery.save(runs)\n\t\t} catch (error) {\n\t\t\tif (!this.#recoveryWarning)\n\t\t\t\tconsole.warn('[page-agent] Could not save conversation recovery', error)\n\t\t\tthis.#recoveryWarning = true\n\t\t}\n\t}\n\n\t#archiveCurrent(): void {\n\t\tconst task = this.#agent.task || ''\n\t\tconst history = [...this.#agent.history]\n\t\tconst voiceRuns = this.#voiceRuns.takeAll()\n\t\tif (!task && history.length === 0 && voiceRuns.length === 0) return\n\t\tthis.#archive.push({ task, history, result: this.#resultKind(), voiceRuns })\n\t}\n\n\t/** Scripts the voice ran, as script cards, each with its time. */\n\t#voiceRunNodes(\n\t\truns: readonly VoiceRun[],\n\t\tt: (key: TranslationKey, params?: TranslationParams) => string\n\t): HTMLElement[] {\n\t\treturn runs.map((run) => {\n\t\t\tconst card = scriptCard({\n\t\t\t\tkey: `voice-${run.id}`,\n\t\t\t\tscript: run.script,\n\t\t\t\toutput: run.output,\n\t\t\t\tt,\n\t\t\t\tsource: 'voice',\n\t\t\t\trefused: run.status === 'refused',\n\t\t\t\ttime: new Date(run.at).toLocaleTimeString(),\n\t\t\t})\n\t\t\tcard.classList.add(styles.enter)\n\t\t\tcard.dataset.mark = 'voice'\n\t\t\treturn card\n\t\t})\n\t}\n\n\t/** Finished tasks, each followed by a divider, shown above the current task. */\n\t#archivedNodes(t: (key: TranslationKey, params?: TranslationParams) => string): HTMLElement[] {\n\t\tconst out: HTMLElement[] = []\n\t\tthis.#archive.forEach((run, index) => {\n\t\t\tconst nodes = buildFeed(\n\t\t\t\t{\n\t\t\t\t\tkey: `run-${index}`,\n\t\t\t\t\ttask: run.task,\n\t\t\t\t\thistory: run.history,\n\t\t\t\t\tlive: null,\n\t\t\t\t\tquestion: null,\n\t\t\t\t\tresult: run.result,\n\t\t\t\t},\n\t\t\t\tt\n\t\t\t)\n\t\t\tthis.#annotate(nodes, index, run.history, run.result)\n\t\t\tout.push(...nodes, ...this.#voiceRunNodes(run.voiceRuns, t))\n\t\t\tconst divider = document.createElement('div')\n\t\t\tdivider.className = styles.divider\n\t\t\tdivider.textContent = t('ui.panel.newTask')\n\t\t\tout.push(divider)\n\t\t})\n\t\treturn out\n\t}\n\n\t// ========== Agent interaction ==========\n\n\t/**\n\t * Ask the user a question on behalf of the agent. Rejects when `signal` aborts\n\t * (task stopped or disposed), so the agent loop can settle.\n\t */\n\t#askUser(question: string, signal?: AbortSignal): Promise<string> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.#question = { text: question, resolve }\n\t\t\tthis.#setCollapsed(false)\n\t\t\tthis.#render()\n\t\t\tthis.#voice.report({ kind: 'question', text: question })\n\t\t\tthis.#textarea.focus()\n\n\t\t\tsignal?.addEventListener(\n\t\t\t\t'abort',\n\t\t\t\t() => {\n\t\t\t\t\tthis.#question = null\n\t\t\t\t\tthis.#render()\n\t\t\t\t\treject(signal.reason as DOMException)\n\t\t\t\t},\n\t\t\t\t{ once: true }\n\t\t\t)\n\t\t})\n\t}\n\n\t#submit(): void {\n\t\tconst value = this.#textarea.value.trim()\n\t\tif (!value) return\n\t\tif (!this.#send(value)) return\n\t\tthis.#textarea.value = ''\n\t\tthis.#autoSize()\n\t}\n\n\t/** Sends a task or answers a pending question. The text field and voice both use this path. */\n\t#send(value: string): boolean {\n\t\tif (this.#question) {\n\t\t\tconst { resolve } = this.#question\n\t\t\tthis.#question = null\n\t\t\tresolve(value)\n\t\t\tthis.#render()\n\t\t\treturn true\n\t\t}\n\t\tif (this.#agent.status === 'running') return false\n\t\tthis.#archiveCurrent()\n\t\tthis.#anchorTurn = true\n\t\tthis.#outcomeSpoken = false\n\t\tthis.#agent.execute(value)\n\t\treturn true\n\t}\n\n\t/** Reads the outcome of a finished run once, while voice is on. */\n\t#speakOutcome(): void {\n\t\tconst status = this.#agent.status\n\t\tif (\n\t\t\tthis.#outcomeSpoken ||\n\t\t\t(status !== 'completed' && status !== 'error' && status !== 'stopped')\n\t\t)\n\t\t\treturn\n\t\tthis.#outcomeSpoken = true\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst outcome = this.#resultKind()\n\t\tconst titles: Record<ResultKind, TranslationKey> = {\n\t\t\tdone: 'ui.panel.resultDone',\n\t\t\tnotDone: 'ui.panel.resultNotDone',\n\t\t\tstopped: 'ui.panel.resultStopped',\n\t\t\terror: 'ui.panel.resultError',\n\t\t}\n\t\tconst kind = outcome?.kind ?? 'stopped'\n\t\tthis.#voice.report({\n\t\t\tkind: kind === 'notDone' ? 'not-done' : kind,\n\t\t\ttext: outcome?.text || t(titles[kind]),\n\t\t})\n\t}\n\n\t/** Runs a script for the voice. Refused while the agent is running, because the agent owns the page then. */\n\tasync #runVoiceScript(script: string): Promise<string> {\n\t\tconst at = Date.now()\n\t\tif (this.#agent.status === 'running') {\n\t\t\tconst reason =\n\t\t\t\t'The agent is busy with a task, so the page cannot be changed now. Tell the user to try again when the task ends.'\n\t\t\tthis.#voiceRuns.refuse(script, reason, at)\n\t\t\tconsole.debug('[page-agent voice] refused', { script, reason })\n\t\t\tthis.#render()\n\t\t\treturn reason\n\t\t}\n\t\tconst run = this.#config.runScript\n\t\tconst entry = this.#voiceRuns.start(script, at)\n\t\tthis.#render()\n\t\tlet output: string\n\t\ttry {\n\t\t\toutput = run ? await run(script) : 'Running scripts is not available in this session.'\n\t\t} catch (error) {\n\t\t\toutput = `The script failed: ${error instanceof Error ? error.message : 'unknown error'}`\n\t\t}\n\t\tthis.#voiceRuns.finish(entry.id, output)\n\t\tconsole.debug('[page-agent voice]', { script, output })\n\t\tthis.#render()\n\t\treturn output\n\t}\n\n\t/**\n\t * The voice session. The voice model hands a task to the agent through run_task; a task that the agent\n\t * cannot take now (already running) is answered back to the model by the session.\n\t */\n\t#createVoice(): VoiceSession {\n\t\treturn new VoiceSession({\n\t\t\tapiKey: this.#config.voice?.apiKey,\n\t\t\tsettings: {\n\t\t\t\tinstructions: `${resolveVoicePrompt(this.#config.voice?.systemPrompt, this.#config.voice?.overrideSystemPrompt === true)}\\n\\n${languageRule(this.#i18n.getLanguage())}`,\n\t\t\t\tlanguage: this.#i18n.getLanguage() === 'pt-BR' ? 'pt' : 'en',\n\t\t\t},\n\t\t\tmic: this.#mic,\n\t\t\t// REVERSIBLE (2026-11-17, gemini provider): the provider is chosen by configuration; default is OpenAI.\n\t\t\tcreateClient: (callbacks) =>\n\t\t\t\tthis.#config.voice?.provider === 'gemini'\n\t\t\t\t\t? new GeminiLiveClient(callbacks)\n\t\t\t\t\t: new RealtimeClient(callbacks),\n\t\t\tonTask: (task) => this.#send(task),\n\t\t\tonScript: (script) => this.#runVoiceScript(script),\n\t\t\tonChange: () => this.#render(),\n\t\t})\n\t}\n\n\t#onActionButton(): void {\n\t\tif (this.#agent.status === 'running') {\n\t\t\tthis.#agent.stop()\n\t\t} else {\n\t\t\t// Close minimizes to the floating button; the agent stays alive.\n\t\t\tthis.hide()\n\t\t}\n\t}\n\n\t// ========== Rendering ==========\n\n\t#resultKind(): { kind: ResultKind; text: string } | null {\n\t\tconst status = this.#agent.status\n\t\tif (status === 'completed') {\n\t\t\tconst notDone = this.#agent.lastResult?.success === false\n\t\t\treturn { kind: notDone ? 'notDone' : 'done', text: lastOutcomeText(this.#agent.history) }\n\t\t}\n\t\tif (status === 'error') return { kind: 'error', text: lastOutcomeText(this.#agent.history) }\n\t\tif (status === 'stopped') return { kind: 'stopped', text: '' }\n\t\treturn null\n\t}\n\n\t#stateName(): string {\n\t\tif (this.#question) return 'waiting'\n\t\tconst status = this.#agent.status\n\t\tif (status === 'running') return 'running'\n\t\tconst kind = this.#resultKind()?.kind\n\t\treturn kind ?? 'idle'\n\t}\n\n\t#statusLabel(): string {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tif (this.#question) return t('ui.panel.statusWaiting')\n\t\tconst status = this.#agent.status\n\t\tif (status === 'running') {\n\t\t\tif (this.#live?.type === 'retrying')\n\t\t\t\treturn t('ui.panel.statusRetrying', {\n\t\t\t\t\tattempt: String(this.#live.attempt),\n\t\t\t\t\tmax: String(this.#live.maxAttempts),\n\t\t\t\t})\n\t\t\tif (this.#live?.type === 'executing') return toolLabel(this.#live.tool, this.#live.input, t)\n\t\t\tif (this.#live?.type === 'thinking') return t('ui.panel.thinking')\n\t\t\treturn t('ui.panel.statusRunning')\n\t\t}\n\t\tswitch (this.#resultKind()?.kind) {\n\t\t\tcase 'done':\n\t\t\t\treturn t('ui.panel.statusDone')\n\t\t\tcase 'notDone':\n\t\t\t\treturn t('ui.panel.statusNotDone')\n\t\t\tcase 'stopped':\n\t\t\t\treturn t('ui.panel.statusStopped')\n\t\t\tcase 'error':\n\t\t\t\treturn t('ui.panel.statusError')\n\t\t\tdefault:\n\t\t\t\treturn t('ui.panel.ready')\n\t\t}\n\t}\n\n\t#render(): void {\n\t\tthis.#saveRecovery()\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst state = this.#stateName()\n\t\tthis.#wrapper.dataset.state = state\n\t\tthis.#wrapper.dataset.mode = this.#mode\n\t\tthis.#wrapper.dataset.follow = this.#followMode\n\t\tthis.#wrapper.classList.toggle(styles.collapsed, this.#collapsed)\n\t\tthis.#statusText.textContent = this.#statusLabel()\n\n\t\tconst nodes = buildFeed(\n\t\t\t{\n\t\t\t\tkey: 'current',\n\t\t\t\ttask: this.#agent.task || '',\n\t\t\t\thistory: this.#agent.history,\n\t\t\t\tlive: this.#agent.status === 'running' ? this.#live : null,\n\t\t\t\tquestion: this.#question?.text ?? null,\n\t\t\t\tresult: this.#question ? null : this.#resultKind(),\n\t\t\t},\n\t\t\tt\n\t\t)\n\t\tthis.#annotate(nodes, this.#archive.length, this.#agent.history, this.#resultKind())\n\t\tconst conversation = [\n\t\t\t...this.#archivedNodes(t),\n\t\t\t...nodes,\n\t\t\t...this.#voiceRunNodes(this.#voiceRuns.list, t),\n\t\t]\n\t\tif (conversation.length === 0) {\n\t\t\tconst hint = document.createElement('div')\n\t\t\thint.className = styles.empty\n\t\t\thint.textContent = t('ui.panel.emptyHint')\n\t\t\tconversation.push(hint)\n\t\t}\n\t\t// REVERSIBLE (2026-11-17, feed stability): rebuild the feed only when what it shows changed. Otherwise the\n\t\t// nodes, their open previews and their place stay, and old nodes do not replay the entrance animation.\n\t\tconst key = JSON.stringify([\n\t\t\tthis.#agent.task,\n\t\t\tthis.#agent.history.length,\n\t\t\tthis.#agent.history.at(-1) ?? null,\n\t\t\tthis.#agent.status === 'running' ? this.#live : null,\n\t\t\tthis.#question?.text ?? null,\n\t\t\tthis.#question ? null : this.#resultKind(),\n\t\t\tthis.#voiceRuns.list,\n\t\t\tthis.#archive.length,\n\t\t\tthis.#collapsed,\n\t\t\tthis.#followMode,\n\t\t\tthis.#mode,\n\t\t])\n\t\tif (key !== this.#lastRenderKey) {\n\t\t\tthis.#lastRenderKey = key\n\t\t\tconst appended = conversation.length > this.#renderedCount\n\t\t\tconversation.forEach((node, i) => {\n\t\t\t\tif (!appended || i < this.#renderedCount) node.classList.remove(styles.enter)\n\t\t\t})\n\t\t\tthis.#renderedCount = conversation.length\n\t\t\tthis.#feed.replaceChildren(...conversation)\n\t\t}\n\t\tthis.#afterFeedUpdate()\n\n\t\tconst running = this.#agent.status === 'running'\n\t\tconst answering = this.#question !== null\n\t\tconst finished = !running && !answering && this.#resultKind() !== null\n\t\tconst inStudio = this.#mode === 'skills-studio'\n\t\tconst mobileBar = this.#followMode === 'bar' && this.#useFollowCycle()\n\t\tconst composerHidden = finished && this.#config.promptForNextTask === false\n\t\tthis.#feedWrap.hidden = inStudio || mobileBar\n\t\tthis.#composer.hidden = composerHidden || this.#mode !== 'text' || inStudio || mobileBar\n\t\tthis.#voiceStage.hidden = this.#mode !== 'voice' || mobileBar\n\t\tthis.#studioStage.hidden = !inStudio || mobileBar\n\t\tthis.#followBar.hidden = !mobileBar\n\t\tthis.#renderVoice()\n\t\tthis.#renderFollowBar()\n\t\tthis.#renderSkillsStudio()\n\t\tthis.#answerContext.hidden = !answering\n\t\tthis.#answerContext.textContent = answering ? t('ui.panel.answerTitle') : ''\n\t\tthis.#textarea.disabled = running && !answering\n\t\tthis.#textarea.placeholder = answering\n\t\t\t? t('ui.panel.composerAnswer')\n\t\t\t: running\n\t\t\t\t? t('ui.panel.composerRunning')\n\t\t\t\t: t('ui.panel.composerPlaceholder')\n\t\tthis.#sendButton.disabled = running && !answering\n\t\tsetButton(this.#sendButton, 'send', t('ui.panel.send'))\n\t\tsetButton(this.#exportButton, 'download', t('ui.panel.exportLog'))\n\t\tthis.#exportButton.hidden = this.#archive.length === 0 && this.#agent.history.length === 0\n\t\tthis.#renderAttachments()\n\n\t\tif (running) setButton(this.#stopButton, 'stop', t('ui.panel.stop'))\n\t\telse setButton(this.#stopButton, 'close', t('ui.panel.close'))\n\t\tconst collapseTip =\n\t\t\tthis.#followMode === 'expanded'\n\t\t\t\t? this.#useFollowCycle()\n\t\t\t\t\t? t('ui.panel.followModeBar')\n\t\t\t\t\t: t('ui.panel.collapse')\n\t\t\t\t: this.#followMode === 'bar'\n\t\t\t\t\t? t('ui.panel.expand')\n\t\t\t\t\t: t('ui.panel.expandFromFab')\n\t\tsetButton(\n\t\t\tthis.#collapseButton,\n\t\t\tthis.#followMode === 'expanded' ? 'chevronUp' : 'chevronDown',\n\t\t\tcollapseTip\n\t\t)\n\t\tthis.#collapseButton.setAttribute('aria-expanded', String(this.#followMode === 'expanded'))\n\t\tsetButton(this.#skillsButton, 'skills', t('ui.panel.skillsStudio'))\n\t\tthis.#skillsButton.setAttribute('aria-pressed', String(inStudio))\n\t\tthis.#skillsButton.hidden = this.#mode === 'voice'\n\t\tif (this.#mode === 'voice') setButton(this.#micButton, 'keyboard', t('ui.panel.switchToText'))\n\t\telse setButton(this.#micButton, 'mic', t('ui.panel.switchToVoice'))\n\t\tthis.#micButton.setAttribute('aria-pressed', String(this.#mode === 'voice'))\n\t\tthis.#micButton.hidden = inStudio\n\t}\n\n\t#studioSupported(): boolean {\n\t\treturn (\n\t\t\ttypeof this.#agent.startSkillRecording === 'function' &&\n\t\t\ttypeof this.#agent.listSkillsCatalog === 'function' &&\n\t\t\ttypeof this.#agent.synthesizeSkill === 'function'\n\t\t)\n\t}\n\n\t#setStudioMessage(message: string, tone: 'ok' | 'warn' | 'err' | '' = ''): void {\n\t\tthis.#studioMessage = message\n\t\tthis.#studioMessageTone = tone\n\t}\n\n\t#stopStudioPolling(): void {\n\t\tif (!this.#studioPoll) return\n\t\tclearInterval(this.#studioPoll)\n\t\tthis.#studioPoll = null\n\t}\n\n\t#syncStudioPolling(): void {\n\t\tconst recording = Boolean(this.#agent.isSkillRecording?.())\n\t\tif (recording && this.#mode === 'skills-studio') {\n\t\t\tif (!this.#studioPoll) {\n\t\t\t\tthis.#studioPoll = setInterval(() => {\n\t\t\t\t\tif (this.#mode !== 'skills-studio' || !this.#agent.isSkillRecording?.()) {\n\t\t\t\t\t\tthis.#stopStudioPolling()\n\t\t\t\t\t\tthis.#renderSkillsStudio()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tthis.#renderSkillsStudio()\n\t\t\t\t}, 400)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tthis.#stopStudioPolling()\n\t}\n\n\t#refreshStudioCatalog(): void {\n\t\ttry {\n\t\t\tthis.#studioCatalog = this.#agent.listSkillsCatalog?.() ?? []\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t\tthis.#studioCatalog = []\n\t\t}\n\t}\n\n\t#refreshStudioWatches(): void {\n\t\ttry {\n\t\t\tthis.#studioWatches = this.#agent.listSkillWatches?.() ?? []\n\t\t} catch {\n\t\t\tthis.#studioWatches = []\n\t\t}\n\t}\n\n\t#watcherCommandFor(entry: StudioSkillCatalogEntry): string | null {\n\t\tconst names = new Set(entry.commands.map((c) => c.name))\n\t\tif (names.has('check')) return 'check'\n\t\tif (names.has('watch_reply')) return 'watch_reply'\n\t\tif (names.has('run')) return 'run'\n\t\treturn null\n\t}\n\n\t#canArmSkillWatch(): boolean {\n\t\treturn typeof this.#agent.armSkillWatch === 'function'\n\t}\n\n\t#notifySkillWatchEnter(): void {\n\t\tthis.#agent.notifySkillWatchEnter?.()\n\t}\n\n\t#renderSkillsStudio(): void {\n\t\tif (this.#mode !== 'skills-studio') return\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst supported = this.#studioSupported()\n\t\tconst recording = Boolean(this.#agent.isSkillRecording?.())\n\t\tconst steps = this.#agent.getRecordedSteps?.() ?? []\n\t\tconst busy = this.#studioBusy || this.#agent.status === 'running'\n\n\t\tconst back = this.#studioStage.querySelector<HTMLButtonElement>('[data-role=\"skills-back\"]')!\n\t\tsetButton(back, 'close', t('ui.panel.skillsStudioBack'))\n\t\tconst tabs = this.#studioStage.querySelectorAll<HTMLButtonElement>('[data-role=\"skills-tab\"]')\n\t\tfor (const button of tabs) {\n\t\t\tconst selected = button.dataset.tab === this.#studioTab\n\t\t\tbutton.setAttribute('aria-selected', String(selected))\n\t\t}\n\t\tconst panes = this.#studioStage.querySelectorAll<HTMLElement>('[data-role=\"skills-pane\"]')\n\t\tfor (const pane of panes) {\n\t\t\tpane.hidden = pane.dataset.tab !== this.#studioTab\n\t\t}\n\n\t\tconst unavailable = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-unavailable\"]'\n\t\t)!\n\t\tunavailable.hidden = supported\n\t\tunavailable.textContent = t('ui.panel.skillsStudioUnavailable')\n\n\t\tfor (const pane of panes) {\n\t\t\tif (pane.dataset.tab) pane.toggleAttribute('data-disabled', !supported)\n\t\t}\n\n\t\tconst recordStatus = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-record-status\"]'\n\t\t)!\n\t\tconst askStatus = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-ask-status\"]'\n\t\t)!\n\t\tconst catalogStatus = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-catalog-status\"]'\n\t\t)!\n\t\tconst statusText =\n\t\t\tthis.#studioMessage ||\n\t\t\t(recording ? t('ui.panel.skillsStudioRecording') : t('ui.panel.skillsStudioIdle'))\n\t\tconst statusTone = this.#studioMessage ? this.#studioMessageTone : recording ? 'warn' : ''\n\t\tfor (const el of [recordStatus, askStatus, catalogStatus]) {\n\t\t\tel.textContent = statusText\n\t\t\tif (statusTone) el.dataset.tone = statusTone\n\t\t\telse delete el.dataset.tone\n\t\t}\n\n\t\tconst startBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-record-start\"]'\n\t\t)!\n\t\tconst stopBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-record-stop\"]'\n\t\t)!\n\t\tconst finishBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-record-finish\"]'\n\t\t)!\n\t\tconst clearBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-record-clear\"]'\n\t\t)!\n\t\tconst saveBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-record-save\"]'\n\t\t)!\n\t\tconst testBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-record-test\"]'\n\t\t)!\n\t\tstartBtn.textContent = t('ui.panel.skillsStudioStart')\n\t\tstopBtn.textContent = t('ui.panel.skillsStudioStop')\n\t\tfinishBtn.textContent = t('ui.panel.skillsStudioFinish')\n\t\tclearBtn.textContent = t('ui.panel.skillsStudioClear')\n\t\tsaveBtn.textContent = t('ui.panel.skillsStudioSave')\n\t\ttestBtn.textContent = t('ui.panel.skillsStudioTest')\n\t\tstartBtn.disabled = !supported || busy || recording\n\t\tstopBtn.disabled = !supported || busy || !recording\n\t\tfinishBtn.disabled = !supported || busy || (!recording && steps.length === 0)\n\t\tclearBtn.disabled = !supported || busy || (steps.length === 0 && !this.#studioPreview)\n\t\tsaveBtn.disabled = !supported || busy || !this.#studioPreview\n\t\ttestBtn.disabled = !supported || busy || !this.#studioPreviewId\n\n\t\tconst stepsList = this.#studioStage.querySelector<HTMLOListElement>(\n\t\t\t'[data-role=\"skills-steps\"]'\n\t\t)!\n\t\tconst emptySteps = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-steps-empty\"]'\n\t\t)!\n\t\temptySteps.textContent = t('ui.panel.skillsStudioEmptySteps')\n\t\temptySteps.hidden = steps.length > 0\n\t\tstepsList.hidden = steps.length === 0\n\t\tstepsList.replaceChildren()\n\t\tfor (const step of steps) {\n\t\t\tstepsList.append(this.#createStudioStepRow(step, supported && !busy))\n\t\t}\n\n\t\tconst previewLabel = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-preview-label\"]'\n\t\t)!\n\t\tconst preview = this.#studioStage.querySelector<HTMLElement>('[data-role=\"skills-preview\"]')!\n\t\tconst previewActions = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-preview-actions\"]'\n\t\t)!\n\t\tpreviewLabel.textContent = t('ui.panel.skillsStudioPreview')\n\t\tconst hasPreview = Boolean(this.#studioPreview)\n\t\tpreviewLabel.hidden = !hasPreview\n\t\tpreview.hidden = !hasPreview\n\t\tpreviewActions.hidden = !hasPreview\n\t\tpreview.textContent = this.#studioPreview\n\n\t\tconst askStart = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-ask-start\"]'\n\t\t)!\n\t\tconst askInput = this.#studioStage.querySelector<HTMLTextAreaElement>(\n\t\t\t'[data-role=\"skills-ask-input\"]'\n\t\t)!\n\t\taskStart.textContent = t('ui.panel.skillsStudioAskStart')\n\t\taskStart.disabled = !supported || busy || !askInput.value.trim()\n\t\taskInput.disabled = !supported || busy\n\n\t\tconst refreshBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-catalog-refresh\"]'\n\t\t)!\n\t\tconst removeAgentBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-catalog-remove-agent\"]'\n\t\t)!\n\t\trefreshBtn.textContent = t('ui.panel.skillsStudioRefreshRemote')\n\t\tremoveAgentBtn.textContent = t('ui.panel.skillsStudioRemoveAgentSkills')\n\t\tconst agentRows = this.#studioCatalog.filter((row) => row.scope === 'agent')\n\t\trefreshBtn.disabled = !supported || busy\n\t\tremoveAgentBtn.disabled = !supported || busy || agentRows.length === 0\n\n\t\tconst catalogEmpty = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-catalog-empty\"]'\n\t\t)!\n\t\tconst catalogList = this.#studioStage.querySelector<HTMLUListElement>(\n\t\t\t'[data-role=\"skills-catalog-list\"]'\n\t\t)!\n\t\tconst catalogCount = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-catalog-count\"]'\n\t\t)!\n\t\tcatalogCount.textContent = t('ui.panel.skillsStudioCatalogCount', {\n\t\t\tcount: String(this.#studioCatalog.length),\n\t\t})\n\t\tcatalogEmpty.textContent = t('ui.panel.skillsStudioEmptyCatalog')\n\t\tcatalogEmpty.hidden = this.#studioCatalog.length > 0\n\t\tcatalogList.hidden = this.#studioCatalog.length === 0\n\t\tcatalogList.replaceChildren()\n\t\tfor (const entry of this.#studioCatalog) {\n\t\t\tcatalogList.append(this.#createStudioCatalogRow(entry, supported && !busy))\n\t\t}\n\n\t\tthis.#renderStudioWatchers(supported && !busy)\n\n\t\tthis.#syncStudioPolling()\n\t}\n\n\t#renderStudioWatchers(enabled: boolean): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst strip = this.#studioStage.querySelector<HTMLElement>('[data-role=\"skills-watchers\"]')\n\t\tif (!strip) return\n\n\t\tconst canWatch = this.#canArmSkillWatch()\n\t\tstrip.hidden = !canWatch\n\t\tif (!canWatch) return\n\n\t\tthis.#refreshStudioWatches()\n\t\tconst title = strip.querySelector<HTMLElement>('[data-role=\"skills-watchers-title\"]')!\n\t\tconst empty = strip.querySelector<HTMLElement>('[data-role=\"skills-watchers-empty\"]')!\n\t\tconst list = strip.querySelector<HTMLUListElement>('[data-role=\"skills-watchers-list\"]')!\n\t\ttitle.textContent = t('ui.panel.skillsStudioWatchers')\n\t\tempty.textContent = t('ui.panel.skillsStudioWatchEmpty')\n\t\tempty.hidden = this.#studioWatches.length > 0\n\t\tlist.hidden = this.#studioWatches.length === 0\n\t\tlist.replaceChildren()\n\t\tfor (const watch of this.#studioWatches) {\n\t\t\tlist.append(this.#createStudioWatcherChip(watch, enabled))\n\t\t}\n\t}\n\n\t#createStudioWatcherChip(watch: StudioSkillWatchEntry, enabled: boolean): HTMLLIElement {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst chip = document.createElement('li')\n\t\tchip.className = styles.studioWatcherChip\n\t\tchip.dataset.watchId = watch.id\n\n\t\tconst label = document.createElement('span')\n\t\tlabel.className = styles.studioWatcherLabel\n\t\tlabel.textContent = `${watch.skillId}/${watch.command}`\n\t\tconst meta = document.createElement('span')\n\t\tmeta.className = styles.studioWatcherMeta\n\t\tmeta.textContent = watch.trigger\n\n\t\tconst disarm = document.createElement('button')\n\t\tdisarm.type = 'button'\n\t\tdisarm.textContent = t('ui.panel.skillsStudioDisarmWatch')\n\t\tdisarm.disabled = !enabled || typeof this.#agent.disarmSkillWatch !== 'function'\n\t\tdisarm.addEventListener('click', () => this.#onStudioDisarmWatch(watch.id))\n\n\t\tchip.append(label, meta, disarm)\n\t\treturn chip\n\t}\n\n\t#createStudioStepRow(step: StudioRecordedStep, enabled: boolean): HTMLLIElement {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst row = document.createElement('li')\n\t\trow.className = styles.studioStep\n\t\trow.dataset.stepId = step.id\n\n\t\tconst body = document.createElement('div')\n\t\tbody.className = styles.studioStepBody\n\t\tconst kind = document.createElement('span')\n\t\tkind.className = styles.studioStepKind\n\t\tkind.textContent = step.kind\n\t\tconst title = document.createElement('div')\n\t\tconst label =\n\t\t\tstep.rawLabel ||\n\t\t\t[step.role, step.name ? `\"${step.name}\"` : ''].filter(Boolean).join(' ') ||\n\t\t\tstep.kind\n\t\ttitle.append(kind, document.createTextNode(label))\n\t\tconst meta = document.createElement('div')\n\t\tmeta.className = styles.studioStepMeta\n\t\tconst bits = [\n\t\t\tstep.value !== undefined ? `value=${JSON.stringify(step.value)}` : '',\n\t\t\tstep.param ? 'param' : '',\n\t\t].filter(Boolean)\n\t\tmeta.textContent = bits.join(' · ')\n\t\tbody.append(title)\n\t\tif (bits.length) body.append(meta)\n\n\t\tconst actions = document.createElement('div')\n\t\tactions.className = styles.studioStepActions\n\t\tif (step.kind === 'fill' || step.kind === 'select') {\n\t\t\tconst paramBtn = document.createElement('button')\n\t\t\tparamBtn.type = 'button'\n\t\t\tparamBtn.textContent = step.param\n\t\t\t\t? t('ui.panel.skillsStudioUnparam')\n\t\t\t\t: t('ui.panel.skillsStudioParam')\n\t\t\tparamBtn.disabled = !enabled\n\t\t\tparamBtn.addEventListener('click', () => {\n\t\t\t\tthis.#agent.toggleRecordedStepParam?.(step.id)\n\t\t\t\tthis.#studioPreview = ''\n\t\t\t\tthis.#studioPreviewId = ''\n\t\t\t\tthis.#renderSkillsStudio()\n\t\t\t})\n\t\t\tactions.append(paramBtn)\n\t\t}\n\t\tconst removeBtn = document.createElement('button')\n\t\tremoveBtn.type = 'button'\n\t\tremoveBtn.textContent = t('ui.panel.skillsStudioRemoveStep')\n\t\tremoveBtn.disabled = !enabled\n\t\tremoveBtn.addEventListener('click', () => {\n\t\t\tthis.#agent.removeRecordedStep?.(step.id)\n\t\t\tthis.#studioPreview = ''\n\t\t\tthis.#studioPreviewId = ''\n\t\t\tthis.#renderSkillsStudio()\n\t\t})\n\t\tactions.append(removeBtn)\n\n\t\trow.append(body, actions)\n\t\treturn row\n\t}\n\n\t#createStudioCatalogRow(entry: StudioSkillCatalogEntry, enabled: boolean): HTMLLIElement {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst row = document.createElement('li')\n\t\trow.className = styles.studioCatalogRow\n\n\t\tconst body = document.createElement('div')\n\t\tbody.className = styles.studioCatalogBody\n\t\tconst title = document.createElement('div')\n\t\ttitle.textContent = entry.name || entry.id\n\t\tconst meta = document.createElement('div')\n\t\tmeta.className = styles.studioCatalogMeta\n\t\tconst scopeLabel =\n\t\t\tentry.scope === 'remote'\n\t\t\t\t? t('ui.panel.skillsStudioScopeRemote')\n\t\t\t\t: t('ui.panel.skillsStudioScopeAgent')\n\t\tconst bits = [\n\t\t\tentry.id,\n\t\t\tscopeLabel,\n\t\t\tentry.loaded ? t('ui.panel.skillsStudioLoaded') : '',\n\t\t\tentry.description,\n\t\t].filter(Boolean)\n\t\tmeta.textContent = bits.join(' · ')\n\t\tbody.append(title, meta)\n\n\t\tconst actions = document.createElement('div')\n\t\tactions.className = styles.studioCatalogActions\n\t\tconst watchCommand = this.#watcherCommandFor(entry)\n\t\tif (watchCommand && this.#canArmSkillWatch()) {\n\t\t\tconst armBtn = document.createElement('button')\n\t\t\tarmBtn.type = 'button'\n\t\t\tarmBtn.dataset.variant = 'accent'\n\t\t\tarmBtn.textContent = t('ui.panel.skillsStudioArmWatch')\n\t\t\tarmBtn.disabled = !enabled\n\t\t\tarmBtn.addEventListener('click', () => void this.#onStudioArmWatch(entry))\n\t\t\tactions.append(armBtn)\n\t\t}\n\t\tconst testBtn = document.createElement('button')\n\t\ttestBtn.type = 'button'\n\t\ttestBtn.textContent = t('ui.panel.skillsStudioTest')\n\t\ttestBtn.disabled = !enabled\n\t\ttestBtn.addEventListener('click', () => void this.#onStudioTestSkill(entry.id))\n\t\tactions.append(testBtn)\n\t\tif (entry.scope === 'agent') {\n\t\t\tconst removeBtn = document.createElement('button')\n\t\t\tremoveBtn.type = 'button'\n\t\t\tremoveBtn.textContent = t('ui.panel.skillsStudioRemoveSkill')\n\t\t\tremoveBtn.disabled = !enabled\n\t\t\tremoveBtn.addEventListener('click', () => void this.#onStudioRemoveSkill(entry.id))\n\t\t\tactions.append(removeBtn)\n\t\t}\n\n\t\trow.append(body, actions)\n\t\treturn row\n\t}\n\n\tasync #onStudioStartRecording(): Promise<void> {\n\t\tif (!this.#studioSupported() || this.#studioBusy) return\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tawait this.#agent.startSkillRecording?.()\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\t#onStudioStopRecording(): void {\n\t\tthis.#agent.stopSkillRecording?.()\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t}\n\n\t#onStudioFinishSynthesize(): void {\n\t\tif (!this.#studioSupported() || this.#studioBusy) return\n\t\tthis.#agent.stopSkillRecording?.()\n\t\ttry {\n\t\t\tconst result = this.#agent.synthesizeSkill?.()\n\t\t\tif (!result) throw new Error('synthesizeSkill is unavailable')\n\t\t\tthis.#studioPreview = result.document\n\t\t\tthis.#studioPreviewId = result.manifest.id\n\t\t\tthis.#setStudioMessage(\n\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioSynthesized', { id: result.manifest.id }),\n\t\t\t\t'ok'\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t}\n\t\tthis.#renderSkillsStudio()\n\t}\n\n\t#onStudioClearRecording(): void {\n\t\tthis.#agent.clearRecordedSteps?.()\n\t\tthis.#studioPreview = ''\n\t\tthis.#studioPreviewId = ''\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t}\n\n\tasync #onStudioSavePreview(): Promise<void> {\n\t\tif (!this.#studioPreview || !this.#agent.publishSkill || this.#studioBusy) return\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tconst result = await this.#agent.publishSkill(this.#studioPreview, 'studio-record')\n\t\t\tthis.#studioPreviewId = result.id\n\t\t\tif (result.remoteError) {\n\t\t\t\tthis.#setStudioMessage(\n\t\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioRemoteWarn', { error: result.remoteError }),\n\t\t\t\t\t'warn'\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tthis.#setStudioMessage(\n\t\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioSaved', {\n\t\t\t\t\t\tid: result.id,\n\t\t\t\t\t\tversion: String(result.version),\n\t\t\t\t\t}),\n\t\t\t\t\t'ok'\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.#refreshStudioCatalog()\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\tasync #onStudioTestSkill(id: string): Promise<void> {\n\t\tif (!id || !this.#agent.testSkill || this.#studioBusy) return\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tconst result = await this.#agent.testSkill(id)\n\t\t\tconst trimmed = result.length > 180 ? `${result.slice(0, 177)}…` : result\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioTested', { result: trimmed }), 'ok')\n\t\t\tthis.#refreshStudioCatalog()\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\tasync #onStudioAskStart(): Promise<void> {\n\t\tif (!this.#studioSupported() || this.#studioBusy) return\n\t\tconst input = this.#studioStage.querySelector<HTMLTextAreaElement>(\n\t\t\t'[data-role=\"skills-ask-input\"]'\n\t\t)!\n\t\tconst goal = input.value.trim()\n\t\tif (!goal) return\n\n\t\tconst prompt = [\n\t\t\t'You are authoring a reusable Page Agent skill for the goal below.',\n\t\t\t'Explore the current page only as needed, then call save_skill with one complete skill Markdown document:',\n\t\t\t'YAML frontmatter (name, description, version, id, scope: agent), a short guidance body, and exactly one skill-js fence exporting commands.',\n\t\t\t'Keep the skill generic: parameterize values that change between runs as command inputs.',\n\t\t\t'Do not ask the user unless you are blocked. Finish after save_skill succeeds.',\n\t\t\t`Goal: ${goal}`,\n\t\t].join('\\n')\n\n\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioAskQueued'), 'warn')\n\t\tthis.#leaveSkillsStudio()\n\t\ttry {\n\t\t\tawait this.#agent.execute(prompt)\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tthis.#refreshStudioCatalog()\n\t\t\t} catch {\n\t\t\t\t/* catalog refresh is best-effort after Ask */\n\t\t\t}\n\t\t}\n\t}\n\n\tasync #onStudioRefreshRemote(): Promise<void> {\n\t\tif (!this.#agent.refreshRemoteSkills || this.#studioBusy) return\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tconst result = await this.#agent.refreshRemoteSkills({ force: true })\n\t\t\tthis.#refreshStudioCatalog()\n\t\t\tthis.#setStudioMessage(\n\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioCatalogCount', {\n\t\t\t\t\tcount: String(result.ids.length || this.#studioCatalog.length),\n\t\t\t\t}),\n\t\t\t\t'ok'\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\tasync #onStudioRemoveSkill(id: string): Promise<void> {\n\t\tif (!this.#agent.removeAgentSkill || this.#studioBusy) return\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tawait this.#agent.removeAgentSkill(id)\n\t\t\tif (this.#studioPreviewId === id) {\n\t\t\t\tthis.#studioPreviewId = ''\n\t\t\t}\n\t\t\tthis.#refreshStudioCatalog()\n\t\t\tthis.#setStudioMessage(\n\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioCatalogCount', {\n\t\t\t\t\tcount: String(this.#studioCatalog.length),\n\t\t\t\t}),\n\t\t\t\t'ok'\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\tasync #onStudioArmWatch(entry: StudioSkillCatalogEntry): Promise<void> {\n\t\tif (!this.#agent.armSkillWatch || this.#studioBusy) return\n\t\tconst command = this.#watcherCommandFor(entry)\n\t\tif (!command) return\n\n\t\tconst commandNames = new Set(entry.commands.map((c) => c.name))\n\t\tconst watchId = `watch-${entry.id}`\n\t\tlet input: Record<string, unknown> | undefined\n\t\tlet trigger: 'interval' | 'on-enter' | 'on-url' = 'interval'\n\n\t\tif (command === 'watch_reply') {\n\t\t\tconst promptLabel = this.#i18n.t('ui.panel.skillsStudioWatchNeedlePrompt')\n\t\t\tconst raw = typeof window.prompt === 'function' ? window.prompt(promptLabel, 'reply') : null\n\t\t\tconst needle = (raw ?? 'reply').trim() || 'reply'\n\t\t\tinput = { needle }\n\t\t} else if (entry.id === 'on-enter') {\n\t\t\ttrigger = 'on-enter'\n\t\t}\n\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tif (commandNames.has('snapshot')) {\n\t\t\t\tawait this.#agent.loadSkill?.(entry.id)\n\t\t\t\t// testSkill runs `run` or the first command; for watch-page-change that is snapshot.\n\t\t\t\tif (this.#agent.testSkill && !commandNames.has('run')) {\n\t\t\t\t\tawait this.#agent.testSkill(entry.id)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tawait this.#agent.loadSkill?.(entry.id)\n\t\t\t}\n\n\t\t\tconst armed = this.#agent.armSkillWatch({\n\t\t\t\tid: watchId,\n\t\t\t\tskillId: entry.id,\n\t\t\t\tcommand,\n\t\t\t\tinput,\n\t\t\t\ttrigger,\n\t\t\t\teveryMs: 15_000,\n\t\t\t})\n\t\t\tthis.#refreshStudioWatches()\n\t\t\tthis.#setStudioMessage(\n\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioWatchArmed', { id: armed.id }),\n\t\t\t\t'ok'\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\t#onStudioDisarmWatch(id: string): void {\n\t\tif (!this.#agent.disarmSkillWatch) return\n\t\ttry {\n\t\t\tthis.#agent.disarmSkillWatch(id)\n\t\t\tthis.#refreshStudioWatches()\n\t\t\tthis.#setStudioMessage('')\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t}\n\t\tthis.#renderSkillsStudio()\n\t}\n\n\tasync #onStudioRemoveAgentSkills(): Promise<void> {\n\t\tif (!this.#agent.removeAgentSkill || this.#studioBusy) return\n\t\tconst ids = this.#studioCatalog.filter((row) => row.scope === 'agent').map((row) => row.id)\n\t\tif (!ids.length) return\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tfor (const id of ids) {\n\t\t\t\tawait this.#agent.removeAgentSkill(id)\n\t\t\t}\n\t\t\tif (ids.includes(this.#studioPreviewId)) this.#studioPreviewId = ''\n\t\t\tthis.#refreshStudioCatalog()\n\t\t\tthis.#setStudioMessage(\n\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioCatalogCount', {\n\t\t\t\t\tcount: String(this.#studioCatalog.length),\n\t\t\t\t}),\n\t\t\t\t'ok'\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t\tthis.#refreshStudioCatalog()\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\t#enterSkillsStudio(): void {\n\t\tif (this.#mode === 'skills-studio') return\n\t\tif (this.#mode === 'voice') this.#voice.disable()\n\t\tthis.#modeBeforeStudio = this.#mode === 'voice' ? 'voice' : 'text'\n\t\tthis.#mode = 'skills-studio'\n\t\tthis.#studioTab = 'record'\n\t\tthis.#setStudioMessage('')\n\t\tif (this.#studioSupported()) {\n\t\t\tthis.#refreshStudioCatalog()\n\t\t\tthis.#refreshStudioWatches()\n\t\t}\n\t\tthis.#followMode = 'expanded'\n\t\tthis.#collapsed = false\n\t\tthis.#wrapper.dataset.follow = 'expanded'\n\t\tthis.#notifySkillWatchEnter()\n\t\tthis.#render()\n\t}\n\n\t#leaveSkillsStudio(): void {\n\t\tif (this.#mode !== 'skills-studio') return\n\t\tif (this.#agent.isSkillRecording?.()) this.#agent.stopSkillRecording?.()\n\t\tthis.#stopStudioPolling()\n\t\tconst next = this.#modeBeforeStudio\n\t\tthis.#mode = next\n\t\tif (next === 'voice') void this.#voice.enable()\n\t\tthis.#render()\n\t\tif (next === 'text') this.#textarea.focus()\n\t}\n\n\t#setStudioTab(tab: 'record' | 'ask' | 'catalog'): void {\n\t\tthis.#studioTab = tab\n\t\tif (tab === 'catalog' && this.#studioSupported()) this.#refreshStudioCatalog()\n\t\tthis.#renderSkillsStudio()\n\t}\n\n\t#canAttachFiles(): boolean {\n\t\treturn typeof this.#agent.attachTaskFile === 'function'\n\t}\n\n\t#renderAttachments(): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst button = this.#attachButton\n\t\tconst list = this.#attachList\n\t\tif (!button || !list) return\n\n\t\tconst supported = this.#canAttachFiles()\n\t\tbutton.hidden = !supported || this.#mode === 'voice'\n\t\tsetButton(button, 'paperclip', t('ui.panel.attachFile'))\n\t\tbutton.disabled = !supported\n\n\t\tconst files = supported ? (this.#agent.listTaskFiles?.() ?? []) : []\n\t\tlist.replaceChildren()\n\t\tlist.hidden = files.length === 0 && !this.#attachError\n\n\t\tfor (const file of files) {\n\t\t\tconst chip = document.createElement('span')\n\t\t\tchip.className = styles.attachChip\n\t\t\tconst label = document.createElement('span')\n\t\t\tlabel.className = styles.attachName\n\t\t\tlabel.textContent = file.name\n\t\t\tchip.append(label)\n\t\t\tif (typeof this.#agent.removeTaskFile === 'function') {\n\t\t\t\tconst remove = document.createElement('button')\n\t\t\t\tremove.type = 'button'\n\t\t\t\tremove.className = styles.attachRemove\n\t\t\t\tremove.setAttribute('aria-label', t('ui.panel.attachRemove', { name: file.name }))\n\t\t\t\tremove.innerHTML = icon('close')\n\t\t\t\tremove.addEventListener('click', () => {\n\t\t\t\t\tthis.#agent.removeTaskFile?.(file.id)\n\t\t\t\t\tthis.#attachError = ''\n\t\t\t\t\tthis.#renderAttachments()\n\t\t\t\t})\n\t\t\t\tchip.append(remove)\n\t\t\t}\n\t\t\tlist.append(chip)\n\t\t}\n\n\t\tif (this.#attachError) {\n\t\t\tconst err = document.createElement('span')\n\t\t\terr.className = styles.attachError\n\t\t\terr.textContent = this.#attachError\n\t\t\tlist.append(err)\n\t\t}\n\t}\n\n\tasync #onAttachFiles(fileList: FileList | null): Promise<void> {\n\t\tif (!fileList?.length || !this.#agent.attachTaskFile) return\n\t\tthis.#attachError = ''\n\t\tfor (const file of Array.from(fileList)) {\n\t\t\ttry {\n\t\t\t\tawait this.#agent.attachTaskFile(file)\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\t\tthis.#attachError = message || this.#i18n.t('ui.panel.attachFailed')\n\t\t\t\tconsole.warn('[page-agent] attachTaskFile failed', error)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (this.#attachInput) this.#attachInput.value = ''\n\t\tthis.#renderAttachments()\n\t}\n\n\t/** Download a compact text trace of every task in this panel session. */\n\t#exportLog(): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst runs = this.#archive.map((run) => ({\n\t\t\ttask: run.task,\n\t\t\thistory: run.history,\n\t\t\toutcome: run.result ? `${run.result.kind}: ${run.result.text}` : '',\n\t\t}))\n\t\tif (this.#agent.task || this.#agent.history.length > 0) {\n\t\t\tconst outcome = this.#resultKind()\n\t\t\truns.push({\n\t\t\t\ttask: this.#agent.task || '',\n\t\t\t\thistory: [...this.#agent.history],\n\t\t\t\toutcome: outcome ? `${outcome.kind}: ${outcome.text}` : '',\n\t\t\t})\n\t\t}\n\t\tconst now = new Date()\n\t\tconst text = formatTrace(runs, t, now)\n\t\tconst stamp = now.toISOString().replace(/[:.]/g, '-').slice(0, 19)\n\t\tconst url = URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' }))\n\t\tconst link = document.createElement('a')\n\t\tlink.href = url\n\t\tlink.download = `nostop-log-${stamp}.txt`\n\t\tdocument.body.appendChild(link)\n\t\tlink.click()\n\t\tlink.remove()\n\t\tsetTimeout(() => URL.revokeObjectURL(url), 1000)\n\t}\n\n\t#useFollowCycle(): boolean {\n\t\treturn typeof window !== 'undefined' && window.matchMedia(FOLLOW_CYCLE_MQ).matches\n\t}\n\n\t#syncFollowFabLabel(): void {\n\t\tconst tip = this.#i18n.t('ui.panel.expandFromFab')\n\t\tthis.#fab.dataset.tip = tip\n\t\tthis.#fab.setAttribute('aria-label', tip)\n\t}\n\n\t#setFollowMode(mode: FollowMode): void {\n\t\tconst wasCollapsed = this.#collapsed\n\t\tthis.#followMode = mode\n\t\tthis.#collapsed = mode !== 'expanded'\n\t\tthis.#wrapper.dataset.follow = mode\n\t\tif (mode === 'fab') {\n\t\t\tthis.wrapper.style.opacity = '0'\n\t\t\tthis.wrapper.style.transform = 'translateY(20px)'\n\t\t\tthis.wrapper.style.display = 'none'\n\t\t\tthis.#fab.hidden = false\n\t\t\tthis.#syncFollowFabLabel()\n\t\t} else {\n\t\t\tthis.#fab.hidden = true\n\t\t\tif (this.wrapper.style.display === 'none') {\n\t\t\t\tthis.wrapper.style.display = 'flex'\n\t\t\t\tthis.wrapper.getBoundingClientRect()\n\t\t\t\tthis.wrapper.style.opacity = '1'\n\t\t\t\tthis.wrapper.style.transform = 'translateY(0)'\n\t\t\t}\n\t\t}\n\t\tif (wasCollapsed && !this.#collapsed) this.#notifySkillWatchEnter()\n\t\tthis.#render()\n\t}\n\n\t#cycleFollowMode(): void {\n\t\tif (!this.#useFollowCycle()) {\n\t\t\tthis.#setFollowMode(this.#followMode === 'expanded' ? 'bar' : 'expanded')\n\t\t\treturn\n\t\t}\n\t\tconst next: Record<FollowMode, FollowMode> = {\n\t\t\texpanded: 'bar',\n\t\t\tbar: 'fab',\n\t\t\tfab: 'expanded',\n\t\t}\n\t\tthis.#setFollowMode(next[this.#followMode])\n\t}\n\n\t#setCollapsed(collapsed: boolean): void {\n\t\tif (this.#useFollowCycle()) {\n\t\t\tif (!collapsed) this.#setFollowMode('expanded')\n\t\t\telse if (this.#followMode === 'expanded') this.#setFollowMode('bar')\n\t\t\telse this.#setFollowMode('fab')\n\t\t\treturn\n\t\t}\n\t\tthis.#setFollowMode(collapsed ? 'bar' : 'expanded')\n\t}\n\n\t#setMode(mode: 'text' | 'voice'): void {\n\t\tif (this.#mode === 'skills-studio') this.#modeBeforeStudio = mode\n\t\tif (this.#mode === 'voice' && mode !== 'voice') this.#voice.disable()\n\t\tif (mode === 'voice') void this.#voice.enable()\n\t\telse this.#voice.disable()\n\t\tthis.#mode = mode\n\t\tthis.#render()\n\t\tif (mode === 'text') this.#textarea.focus()\n\t}\n\n\t/** Voice stage: one status word, mic name, a mute toggle and a way back to text. */\n\t#renderVoice(): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst state = this.#voice.state\n\t\tconst errorLabels: Record<VoiceError, string> = {\n\t\t\t'no-key': t('ui.panel.voiceNoKey'),\n\t\t\t'mic-denied': t('ui.panel.voiceDenied'),\n\t\t\t'mic-unsupported': t('ui.panel.voiceUnavailable'),\n\t\t\t'mic-busy': t('ui.panel.voiceMicBusy'),\n\t\t\t'connect-failed': t('ui.panel.voiceConnectFailed'),\n\t\t}\n\t\tconst live = state === 'listening' || state === 'speaking' || state === 'connecting'\n\t\tconst silent = live && this.#mic.hardwareMuted\n\t\tconst labels: Record<VoiceState, string> = {\n\t\t\toff: t('ui.panel.voiceOff'),\n\t\t\tconnecting: t('ui.panel.voiceConnecting'),\n\t\t\tlistening: silent ? t('ui.panel.voiceMicSilent') : t('ui.panel.voiceListening'),\n\t\t\tspeaking: t('ui.panel.voiceSpeaking'),\n\t\t\tmuted: t('ui.panel.voiceMuted'),\n\t\t\terror: this.#voice.error ? errorLabels[this.#voice.error] : t('ui.panel.voiceConnectFailed'),\n\t\t}\n\t\tconst lensState = {\n\t\t\toff: 'off',\n\t\t\tconnecting: 'active',\n\t\t\tlistening: silent ? 'denied' : 'active',\n\t\t\tspeaking: 'active',\n\t\t\tmuted: 'muted',\n\t\t\terror: 'denied',\n\t\t}[state]\n\t\tthis.#voiceStage.dataset.voiceState = state\n\t\tconst lens = this.#voiceStage.querySelector<HTMLElement>('[data-role=\"lens\"]')!\n\t\tlens.dataset.state = lensState\n\t\tlens.innerHTML = icon(lensState === 'active' ? 'mic' : 'micOff')\n\t\tthis.#voiceStage.querySelector<HTMLElement>('[data-role=\"voice-state\"]')!.textContent =\n\t\t\tlabels[state]\n\t\tconst device = this.#voiceStage.querySelector<HTMLButtonElement>('[data-role=\"mic-device\"]')!\n\t\tconst deviceLabel = this.#mic.label.trim()\n\t\tconst showDevice = Boolean(deviceLabel) && (live || state === 'muted' || state === 'error')\n\t\tdevice.hidden = !showDevice\n\t\tdevice.textContent = deviceLabel\n\t\tdevice.disabled = !live\n\t\tdevice.setAttribute('aria-label', t('ui.panel.switchMic'))\n\t\tdevice.dataset.tip = t('ui.panel.switchMic')\n\t\tconst mute = this.#voiceStage.querySelector<HTMLButtonElement>('[data-role=\"mute\"]')!\n\t\tconst muted = this.#voice.muted\n\t\tsetButton(mute, muted ? 'mic' : 'micOff', t(muted ? 'ui.panel.unmute' : 'ui.panel.mute'))\n\t\tmute.setAttribute('aria-pressed', String(muted))\n\t\tmute.disabled = state === 'error' || state === 'off'\n\t\tconst voiceStop = this.#voiceStage.querySelector<HTMLButtonElement>('[data-role=\"voice-stop\"]')\n\t\tif (voiceStop) {\n\t\t\tconst running = this.#agent.status === 'running'\n\t\t\tsetButton(\n\t\t\t\tvoiceStop,\n\t\t\t\trunning ? 'stop' : 'close',\n\t\t\t\tt(running ? 'ui.panel.stop' : 'ui.panel.close')\n\t\t\t)\n\t\t}\n\t\tsetButton(\n\t\t\tthis.#voiceStage.querySelector<HTMLButtonElement>('[data-role=\"back\"]')!,\n\t\t\t'keyboard',\n\t\t\tt('ui.panel.switchToText')\n\t\t)\n\t}\n\n\t/** Slim follow strip: status + optional voice lens/mute + stop, without the full feed. */\n\t#renderFollowBar(): void {\n\t\tif (this.#followMode !== 'bar') return\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst voiceMode = this.#mode === 'voice'\n\t\tconst status = this.#followBar.querySelector<HTMLElement>('[data-role=\"follow-bar-status\"]')!\n\t\tconst lens = this.#followBar.querySelector<HTMLElement>('[data-role=\"follow-bar-lens\"]')!\n\t\tconst mute = this.#followBar.querySelector<HTMLButtonElement>('[data-role=\"follow-bar-mute\"]')!\n\t\tconst action = this.#followBar.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"follow-bar-action\"]'\n\t\t)!\n\t\tconst minimize = this.#followBar.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"follow-bar-minimize\"]'\n\t\t)!\n\n\t\tif (voiceMode) {\n\t\t\tconst state = this.#voice.state\n\t\t\tconst live = state === 'listening' || state === 'speaking' || state === 'connecting'\n\t\t\tconst silent = live && this.#mic.hardwareMuted\n\t\t\tconst labels: Record<VoiceState, string> = {\n\t\t\t\toff: t('ui.panel.voiceOff'),\n\t\t\t\tconnecting: t('ui.panel.voiceConnecting'),\n\t\t\t\tlistening: silent ? t('ui.panel.voiceMicSilent') : t('ui.panel.voiceListening'),\n\t\t\t\tspeaking: t('ui.panel.voiceSpeaking'),\n\t\t\t\tmuted: t('ui.panel.voiceMuted'),\n\t\t\t\terror: t('ui.panel.voiceConnectFailed'),\n\t\t\t}\n\t\t\tstatus.textContent = labels[state]\n\t\t\tconst lensState = {\n\t\t\t\toff: 'off',\n\t\t\t\tconnecting: 'active',\n\t\t\t\tlistening: silent ? 'denied' : 'active',\n\t\t\t\tspeaking: 'active',\n\t\t\t\tmuted: 'muted',\n\t\t\t\terror: 'denied',\n\t\t\t}[state]\n\t\t\tlens.hidden = false\n\t\t\tlens.dataset.state = lensState\n\t\t\tlens.innerHTML = icon(lensState === 'active' ? 'mic' : 'micOff')\n\t\t\tmute.hidden = false\n\t\t\tconst muted = this.#voice.muted\n\t\t\tsetButton(mute, muted ? 'mic' : 'micOff', t(muted ? 'ui.panel.unmute' : 'ui.panel.mute'))\n\t\t\tmute.setAttribute('aria-pressed', String(muted))\n\t\t\tmute.disabled = state === 'error' || state === 'off'\n\t\t} else {\n\t\t\tstatus.textContent = this.#statusLabel()\n\t\t\tlens.hidden = true\n\t\t\tmute.hidden = true\n\t\t}\n\n\t\tconst running = this.#agent.status === 'running'\n\t\tsetButton(action, running ? 'stop' : 'close', t(running ? 'ui.panel.stop' : 'ui.panel.close'))\n\t\tsetButton(minimize, 'chevronDown', t('ui.panel.followModeMinimize'))\n\t}\n\n\t#autoSize(): void {\n\t\tthis.#textarea.style.height = 'auto'\n\t\tthis.#textarea.style.height = `${Math.min(this.#textarea.scrollHeight, 120)}px`\n\t}\n\n\t// ========== DOM ==========\n\n\t#createWrapper(): HTMLElement {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst wrapper = document.createElement('div')\n\t\twrapper.id = 'page-agent-runtime_agent-panel'\n\t\twrapper.className = styles.wrapper\n\t\twrapper.setAttribute('data-browser-use-ignore', 'true')\n\t\twrapper.setAttribute('data-page-agent-ignore', 'true')\n\t\twrapper.dataset.state = 'idle'\n\t\twrapper.dataset.follow = 'expanded'\n\n\t\t// Built from static markup plus textContent; no user text is parsed as HTML.\n\t\twrapper.innerHTML = `\n\t\t\t<header class=\"${styles.header}\">\n\t\t\t\t<span class=\"${styles.brand}\" data-role=\"brand\" aria-hidden=\"true\">${icon('spark')}</span>\n\t\t\t\t<div class=\"${styles.titleBlock}\">\n\t\t\t\t\t<strong class=\"${styles.title}\" data-role=\"title\"></strong>\n\t\t\t\t\t<span class=\"${styles.status}\" role=\"status\" data-role=\"status\"></span>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"${styles.controls}\">\n\t\t\t\t\t<button type=\"button\" class=\"${styles.iconButton} ${styles.tip}\" data-role=\"skills\" aria-pressed=\"false\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.iconButton} ${styles.tip}\" data-role=\"export\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.iconButton} ${styles.tip}\" data-role=\"cursor\" aria-pressed=\"false\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.iconButton} ${styles.tip}\" data-role=\"collapse\" aria-expanded=\"true\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.iconButton} ${styles.stopButton} ${styles.tip}\" data-role=\"action\"></button>\n\t\t\t\t</div>\n\t\t\t</header>\n\t\t\t<div class=\"${styles.feedWrap}\" data-role=\"feed-wrap\">\n\t\t\t\t<div class=\"${styles.feed}\" data-role=\"feed\" role=\"log\" aria-live=\"polite\" tabindex=\"0\"></div>\n\t\t\t\t<div class=\"${styles.rail}\" data-role=\"rail\" hidden><span class=\"${styles.railThumb}\" data-role=\"thumb\"></span></div>\n\t\t\t\t<button type=\"button\" class=\"${styles.jump}\" data-role=\"jump\" hidden></button>\n\t\t\t\t<div class=\"${styles.peek}\" data-role=\"peek\" hidden></div>\n\t\t\t</div>\n\t\t\t<form class=\"${styles.composer}\" data-role=\"composer\" autocomplete=\"off\">\n\t\t\t\t<div class=\"${styles.answerContext}\" data-role=\"answer-context\" hidden></div>\n\t\t\t\t<div class=\"${styles.attachList}\" data-role=\"attach-list\" hidden></div>\n\t\t\t\t<div class=\"${styles.box}\">\n\t\t\t\t\t<textarea rows=\"1\" data-role=\"input\" maxlength=\"1000\" aria-label=\"${t('ui.panel.composerPlaceholder')}\"></textarea>\n\t\t\t\t\t<div class=\"${styles.actions}\">\n\t\t\t\t\t\t<input type=\"file\" data-role=\"attach-input\" multiple hidden />\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.roundButton} ${styles.tip} ${styles.tipUp}\" data-role=\"attach\" hidden></button>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.roundButton} ${styles.tip} ${styles.tipUp}\" data-role=\"mic\" aria-pressed=\"false\"></button>\n\t\t\t\t\t\t<button type=\"submit\" class=\"${styles.roundButton} ${styles.send} ${styles.tip} ${styles.tipUp}\" data-role=\"send\"></button>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</form>\n\t\t\t<div class=\"${styles.voice}\" data-role=\"voice\" hidden>\n\t\t\t\t<span class=\"${styles.lens}\" data-role=\"lens\" data-state=\"off\" aria-hidden=\"true\"></span>\n\t\t\t\t<div class=\"${styles.voiceMeta}\">\n\t\t\t\t\t<span class=\"${styles.voiceText}\" data-role=\"voice-state\"></span>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.micDevice} ${styles.tip} ${styles.tipUp}\" data-role=\"mic-device\" hidden></button>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"${styles.voiceActions}\">\n\t\t\t\t\t<button type=\"button\" class=\"${styles.roundButton} ${styles.tip} ${styles.tipUp}\" data-role=\"mute\" aria-pressed=\"false\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.roundButton} ${styles.tip} ${styles.tipUp}\" data-role=\"voice-stop\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.roundButton} ${styles.tip} ${styles.tipUp}\" data-role=\"back\"></button>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div class=\"${styles.followBar}\" data-role=\"follow-bar\" hidden>\n\t\t\t\t<button type=\"button\" class=\"${styles.followBarBody}\" data-role=\"follow-bar-body\">\n\t\t\t\t\t<span class=\"${styles.followBarStatus}\" data-role=\"follow-bar-status\"></span>\n\t\t\t\t\t<span class=\"${styles.lens} ${styles.followBarLens}\" data-role=\"follow-bar-lens\" data-state=\"off\" hidden aria-hidden=\"true\"></span>\n\t\t\t\t</button>\n\t\t\t\t<button type=\"button\" class=\"${styles.roundButton}\" data-role=\"follow-bar-mute\" aria-pressed=\"false\" hidden></button>\n\t\t\t\t<button type=\"button\" class=\"${styles.roundButton}\" data-role=\"follow-bar-action\"></button>\n\t\t\t\t<button type=\"button\" class=\"${styles.roundButton}\" data-role=\"follow-bar-minimize\"></button>\n\t\t\t</div>\n\t\t\t<section class=\"${styles.studio}\" data-role=\"skills-studio\" hidden>\n\t\t\t\t<header class=\"${styles.studioHeader}\">\n\t\t\t\t\t<strong class=\"${styles.studioTitle}\" data-role=\"skills-title\"></strong>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.iconButton} ${styles.tip} ${styles.tipUp}\" data-role=\"skills-back\"></button>\n\t\t\t\t</header>\n\t\t\t\t<nav class=\"${styles.studioTabs}\" role=\"tablist\" data-role=\"skills-tablist\">\n\t\t\t\t\t<button type=\"button\" class=\"${styles.studioTab}\" role=\"tab\" data-role=\"skills-tab\" data-tab=\"record\" aria-selected=\"true\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.studioTab}\" role=\"tab\" data-role=\"skills-tab\" data-tab=\"ask\" aria-selected=\"false\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.studioTab}\" role=\"tab\" data-role=\"skills-tab\" data-tab=\"catalog\" aria-selected=\"false\"></button>\n\t\t\t\t</nav>\n\t\t\t\t<p class=\"${styles.studioStatus}\" data-role=\"skills-unavailable\" hidden></p>\n\t\t\t\t<div class=\"${styles.studioBody}\" data-role=\"skills-pane\" data-tab=\"record\">\n\t\t\t\t\t<p class=\"${styles.studioHint}\" data-role=\"skills-record-hint\"></p>\n\t\t\t\t\t<div class=\"${styles.studioToolbar}\" data-role=\"skills-record-toolbar\">\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-record-start\" data-variant=\"accent\"></button>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-record-stop\"></button>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-record-finish\" data-variant=\"accent\"></button>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-record-clear\"></button>\n\t\t\t\t\t</div>\n\t\t\t\t\t<p class=\"${styles.studioStatus}\" data-role=\"skills-record-status\"></p>\n\t\t\t\t\t<p class=\"${styles.studioHint}\" data-role=\"skills-steps-empty\"></p>\n\t\t\t\t\t<ol class=\"${styles.studioSteps}\" data-role=\"skills-steps\" hidden></ol>\n\t\t\t\t\t<p class=\"${styles.studioPreviewLabel}\" data-role=\"skills-preview-label\" hidden></p>\n\t\t\t\t\t<pre class=\"${styles.studioPreview}\" data-role=\"skills-preview\" hidden></pre>\n\t\t\t\t\t<div class=\"${styles.studioToolbar}\" data-role=\"skills-preview-actions\" hidden>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-record-save\" data-variant=\"accent\"></button>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-record-test\"></button>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"${styles.studioBody}\" data-role=\"skills-pane\" data-tab=\"ask\" hidden>\n\t\t\t\t\t<p class=\"${styles.studioHint}\" data-role=\"skills-ask-hint\"></p>\n\t\t\t\t\t<textarea class=\"${styles.studioAsk}\" data-role=\"skills-ask-input\" rows=\"3\" maxlength=\"2000\"></textarea>\n\t\t\t\t\t<div class=\"${styles.studioToolbar}\">\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-ask-start\" data-variant=\"accent\"></button>\n\t\t\t\t\t</div>\n\t\t\t\t\t<p class=\"${styles.studioStatus}\" data-role=\"skills-ask-status\"></p>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"${styles.studioBody}\" data-role=\"skills-pane\" data-tab=\"catalog\" hidden>\n\t\t\t\t\t<div class=\"${styles.studioToolbar}\" data-role=\"skills-catalog-toolbar\">\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-catalog-refresh\"></button>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-catalog-remove-agent\" data-variant=\"danger\"></button>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"${styles.studioWatchers}\" data-role=\"skills-watchers\" hidden>\n\t\t\t\t\t\t<div class=\"${styles.studioWatchersHead}\">\n\t\t\t\t\t\t\t<strong class=\"${styles.studioWatchersTitle}\" data-role=\"skills-watchers-title\"></strong>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<p class=\"${styles.studioWatchersEmpty}\" data-role=\"skills-watchers-empty\"></p>\n\t\t\t\t\t\t<ul class=\"${styles.studioWatchersList}\" data-role=\"skills-watchers-list\"></ul>\n\t\t\t\t\t</div>\n\t\t\t\t\t<p class=\"${styles.studioStatus}\" data-role=\"skills-catalog-count\"></p>\n\t\t\t\t\t<p class=\"${styles.studioHint}\" data-role=\"skills-catalog-empty\"></p>\n\t\t\t\t\t<ul class=\"${styles.studioCatalog}\" data-role=\"skills-catalog-list\"></ul>\n\t\t\t\t\t<p class=\"${styles.studioStatus}\" data-role=\"skills-catalog-status\"></p>\n\t\t\t\t</div>\n\t\t\t</section>\n\t\t`\n\n\t\twrapper.querySelector<HTMLElement>('[data-role=\"title\"]')!.textContent =\n\t\t\tthis.#config.name?.trim() || 'NoStop'\n\t\tthis.#fillSkillsStudioStatic(wrapper)\n\n\t\tfillBrand(wrapper.querySelector<HTMLElement>('[data-role=\"brand\"]')!)\n\n\t\tdocument.body.appendChild(wrapper)\n\t\treturn wrapper\n\t}\n\n\t#fillSkillsStudioStatic(root: HTMLElement = this.#wrapper): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\troot.querySelector<HTMLElement>('[data-role=\"skills-title\"]')!.textContent =\n\t\t\tt('ui.panel.skillsStudio')\n\t\tconst tabLabels: Record<'record' | 'ask' | 'catalog', string> = {\n\t\t\trecord: t('ui.panel.skillsStudioRecord'),\n\t\t\task: t('ui.panel.skillsStudioAsk'),\n\t\t\tcatalog: t('ui.panel.skillsStudioCatalog'),\n\t\t}\n\t\tfor (const button of root.querySelectorAll<HTMLButtonElement>('[data-role=\"skills-tab\"]')) {\n\t\t\tconst tab = button.dataset.tab as 'record' | 'ask' | 'catalog'\n\t\t\tbutton.textContent = tabLabels[tab]\n\t\t}\n\t\troot.querySelector<HTMLElement>('[data-role=\"skills-record-hint\"]')!.textContent = t(\n\t\t\t'ui.panel.skillsStudioRecordHint'\n\t\t)\n\t\troot.querySelector<HTMLElement>('[data-role=\"skills-ask-hint\"]')!.textContent = t(\n\t\t\t'ui.panel.skillsStudioAskHint'\n\t\t)\n\t\troot.querySelector<HTMLTextAreaElement>('[data-role=\"skills-ask-input\"]')!.placeholder = t(\n\t\t\t'ui.panel.skillsStudioAskPlaceholder'\n\t\t)\n\t\troot.querySelector<HTMLElement>('[data-role=\"skills-catalog-empty\"]')!.textContent = t(\n\t\t\t'ui.panel.skillsStudioEmptyCatalog'\n\t\t)\n\t}\n\n\t#setupEventListeners(): void {\n\t\tconst header = this.#wrapper.querySelector<HTMLElement>(`.${styles.header}`)!\n\t\theader.addEventListener('click', (e) => {\n\t\t\tif ((e.target as HTMLElement).closest('button')) return\n\t\t\tif (this.#useFollowCycle()) this.#cycleFollowMode()\n\t\t\telse this.#setCollapsed(!this.#collapsed)\n\t\t})\n\t\tthis.#collapseButton.addEventListener('click', (e) => {\n\t\t\te.stopPropagation()\n\t\t\tif (this.#useFollowCycle()) this.#cycleFollowMode()\n\t\t\telse this.#setCollapsed(!this.#collapsed)\n\t\t})\n\t\tthis.#stopButton.addEventListener('click', (e) => {\n\t\t\te.stopPropagation()\n\t\t\tthis.#onActionButton()\n\t\t})\n\t\tthis.#followBar\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"follow-bar-body\"]')!\n\t\t\t.addEventListener('click', () => this.#setFollowMode('expanded'))\n\t\tthis.#followBar\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"follow-bar-mute\"]')!\n\t\t\t.addEventListener('click', (e) => {\n\t\t\t\te.stopPropagation()\n\t\t\t\tvoid this.#voice.setMuted(!this.#voice.muted)\n\t\t\t})\n\t\tthis.#followBar\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"follow-bar-action\"]')!\n\t\t\t.addEventListener('click', (e) => {\n\t\t\t\te.stopPropagation()\n\t\t\t\tthis.#onActionButton()\n\t\t\t})\n\t\tthis.#followBar\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"follow-bar-minimize\"]')!\n\t\t\t.addEventListener('click', (e) => {\n\t\t\t\te.stopPropagation()\n\t\t\t\tthis.#setFollowMode('fab')\n\t\t\t})\n\t\tthis.#voiceStage\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"voice-stop\"]')\n\t\t\t?.addEventListener('click', () => this.#onActionButton())\n\t\tthis.#skillsButton.addEventListener('click', (e) => {\n\t\t\te.stopPropagation()\n\t\t\tif (this.#mode === 'skills-studio') this.#leaveSkillsStudio()\n\t\t\telse this.#enterSkillsStudio()\n\t\t})\n\t\tthis.#studioStage\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-back\"]')!\n\t\t\t.addEventListener('click', () => this.#leaveSkillsStudio())\n\t\tfor (const button of this.#studioStage.querySelectorAll<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-tab\"]'\n\t\t)) {\n\t\t\tbutton.addEventListener('click', () => {\n\t\t\t\tconst tab = button.dataset.tab\n\t\t\t\tif (tab === 'record' || tab === 'ask' || tab === 'catalog') this.#setStudioTab(tab)\n\t\t\t})\n\t\t}\n\t\tif (!this.#studioListenersBound) {\n\t\t\tthis.#studioListenersBound = true\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-record-start\"]')!\n\t\t\t\t.addEventListener('click', () => void this.#onStudioStartRecording())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-record-stop\"]')!\n\t\t\t\t.addEventListener('click', () => this.#onStudioStopRecording())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-record-finish\"]')!\n\t\t\t\t.addEventListener('click', () => this.#onStudioFinishSynthesize())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-record-clear\"]')!\n\t\t\t\t.addEventListener('click', () => this.#onStudioClearRecording())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-record-save\"]')!\n\t\t\t\t.addEventListener('click', () => void this.#onStudioSavePreview())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-record-test\"]')!\n\t\t\t\t.addEventListener('click', () => {\n\t\t\t\t\tif (this.#studioPreviewId) void this.#onStudioTestSkill(this.#studioPreviewId)\n\t\t\t\t})\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-ask-start\"]')!\n\t\t\t\t.addEventListener('click', () => void this.#onStudioAskStart())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLTextAreaElement>('[data-role=\"skills-ask-input\"]')!\n\t\t\t\t.addEventListener('input', () => this.#renderSkillsStudio())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-catalog-refresh\"]')!\n\t\t\t\t.addEventListener('click', () => void this.#onStudioRefreshRemote())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-catalog-remove-agent\"]')!\n\t\t\t\t.addEventListener('click', () => void this.#onStudioRemoveAgentSkills())\n\t\t}\n\t\tthis.#micButton.addEventListener('click', () =>\n\t\t\tthis.#setMode(this.#mode === 'voice' ? 'text' : 'voice')\n\t\t)\n\t\tthis.#voiceStage\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"mute\"]')!\n\t\t\t.addEventListener('click', () => void this.#voice.setMuted(!this.#voice.muted))\n\t\tthis.#voiceStage\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"mic-device\"]')!\n\t\t\t.addEventListener('click', () => void this.#voice.changeInput())\n\t\tthis.#wrapper\n\t\t\t.querySelector<HTMLElement>('[data-role=\"back\"]')!\n\t\t\t.addEventListener('click', () => this.#setMode('text'))\n\n\t\tthis.#composer.addEventListener('submit', (e) => {\n\t\t\te.preventDefault()\n\t\t\tthis.#submit()\n\t\t})\n\t\tthis.#textarea.addEventListener('keydown', (e) => {\n\t\t\tif (e.isComposing || e.keyCode === 229) return\n\t\t\tif (e.key === 'Enter' && !e.shiftKey) {\n\t\t\t\te.preventDefault()\n\t\t\t\tthis.#submit()\n\t\t\t}\n\t\t})\n\t\tthis.#textarea.addEventListener('input', () => this.#autoSize())\n\t\tthis.#attachButton?.addEventListener('click', () => this.#attachInput?.click())\n\t\tthis.#attachInput?.addEventListener('change', () => {\n\t\t\tvoid this.#onAttachFiles(this.#attachInput?.files ?? null)\n\t\t})\n\t}\n\n\t/**\n\t * Floating button shown while the panel is closed. Drag it; on release it snaps to the nearest corner.\n\t * A click (without dragging) reopens the panel.\n\t */\n\t#setupFab(): void {\n\t\tconst fab = document.createElement('button')\n\t\tfab.type = 'button'\n\t\tfab.id = 'page-agent-runtime_agent-fab'\n\t\tfab.className = `${styles.fab} ${styles.tip} ${styles.tipUp}`\n\t\tfab.setAttribute('data-browser-use-ignore', 'true')\n\t\tfab.setAttribute('data-page-agent-ignore', 'true')\n\t\tfillBrand(fab)\n\t\tconst tip = this.#i18n.t('ui.panel.open')\n\t\tfab.dataset.tip = tip\n\t\tfab.setAttribute('aria-label', tip)\n\t\tdocument.body.appendChild(fab)\n\t\tthis.#fab = fab\n\n\t\tconst applyCorner = (corner: Corner) => {\n\t\t\tconst [h, v] = corner.split('-')\n\t\t\tfab.style.left = h === 'left' ? `${FAB_MARGIN}px` : 'auto'\n\t\t\tfab.style.right = h === 'right' ? `${FAB_MARGIN}px` : 'auto'\n\t\t\tfab.style.top = v === 'top' ? `${FAB_MARGIN}px` : 'auto'\n\t\t\tfab.style.bottom = v === 'bottom' ? `${FAB_MARGIN}px` : 'auto'\n\t\t\tfab.classList.toggle(styles.fabLeft, h === 'left')\n\t\t}\n\t\tconst saved = (() => {\n\t\t\ttry {\n\t\t\t\treturn localStorage.getItem(FAB_KEY)\n\t\t\t} catch {\n\t\t\t\treturn null\n\t\t\t}\n\t\t})()\n\t\tapplyCorner(CORNERS.includes(saved as Corner) ? (saved as Corner) : 'right-bottom')\n\n\t\tlet origin: { dx: number; dy: number } | null = null\n\t\tlet dragged = false\n\t\tlet longPress = false\n\t\tlet longPressTimer: ReturnType<typeof setTimeout> | undefined\n\t\tconst clearLongPress = () => {\n\t\t\tif (longPressTimer !== undefined) clearTimeout(longPressTimer)\n\t\t\tlongPressTimer = undefined\n\t\t}\n\t\tfab.addEventListener('pointerdown', (event) => {\n\t\t\tif (event.button !== 0) return\n\t\t\tconst rect = fab.getBoundingClientRect()\n\t\t\torigin = { dx: event.clientX - rect.left, dy: event.clientY - rect.top }\n\t\t\tdragged = false\n\t\t\tlongPress = false\n\t\t\tclearLongPress()\n\t\t\tif (this.#useFollowCycle()) {\n\t\t\t\tlongPressTimer = setTimeout(() => {\n\t\t\t\t\tlongPress = true\n\t\t\t\t\tthis.#setFollowMode('bar')\n\t\t\t\t}, 480)\n\t\t\t}\n\t\t\tfab.style.transition = 'none'\n\t\t\tfab.setPointerCapture(event.pointerId)\n\t\t})\n\t\tfab.addEventListener('pointermove', (event) => {\n\t\t\tif (!origin) return\n\t\t\tdragged = true\n\t\t\tclearLongPress()\n\t\t\tconst x = Math.min(\n\t\t\t\tMath.max(0, event.clientX - origin.dx),\n\t\t\t\twindow.innerWidth - fab.offsetWidth\n\t\t\t)\n\t\t\tconst y = Math.min(\n\t\t\t\tMath.max(0, event.clientY - origin.dy),\n\t\t\t\twindow.innerHeight - fab.offsetHeight\n\t\t\t)\n\t\t\tfab.style.left = `${x}px`\n\t\t\tfab.style.top = `${y}px`\n\t\t\tfab.style.right = 'auto'\n\t\t\tfab.style.bottom = 'auto'\n\t\t})\n\t\tconst endDrag = () => {\n\t\t\tclearLongPress()\n\t\t\tif (!origin) return\n\t\t\torigin = null\n\t\t\tfab.style.transition = ''\n\t\t\tif (!dragged) return\n\t\t\tconst rect = fab.getBoundingClientRect()\n\t\t\tconst h = rect.left + rect.width / 2 < window.innerWidth / 2 ? 'left' : 'right'\n\t\t\tconst v = rect.top + rect.height / 2 < window.innerHeight / 2 ? 'top' : 'bottom'\n\t\t\tconst corner: Corner = `${h}-${v}` as Corner\n\t\t\tapplyCorner(corner)\n\t\t\ttry {\n\t\t\t\tlocalStorage.setItem(FAB_KEY, corner)\n\t\t\t} catch {\n\t\t\t\t/* without storage, the corner only lasts for this page */\n\t\t\t}\n\t\t}\n\t\tfab.addEventListener('pointerup', endDrag)\n\t\tfab.addEventListener('pointercancel', endDrag)\n\t\tfab.addEventListener('click', (event) => {\n\t\t\tif (dragged || longPress) {\n\t\t\t\tdragged = false\n\t\t\t\tlongPress = false\n\t\t\t\tevent.preventDefault()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.#setFollowMode('expanded')\n\t\t})\n\t}\n\n\t/**\n\t * Drag by the header, hide the agent cursor and remember the panel position.\n\t * The position is clamped to the viewport and stored in the browser; without storage it lasts only for this page.\n\t */\n\t#setupPlacement(): void {\n\t\tconst header = this.#wrapper.querySelector<HTMLElement>(`.${styles.header}`)!\n\n\t\tconst place = (x: number, y: number) => {\n\t\t\tconst width = this.#wrapper.offsetWidth || 414\n\t\t\tconst height = this.#wrapper.offsetHeight || 0\n\t\t\tconst left = Math.min(Math.max(0, x), Math.max(0, window.innerWidth - width))\n\t\t\tconst top = Math.min(Math.max(0, y), Math.max(0, window.innerHeight - height))\n\t\t\tthis.#wrapper.style.left = `${left}px`\n\t\t\tthis.#wrapper.style.top = `${top}px`\n\t\t\tthis.#wrapper.style.right = 'auto'\n\t\t\tthis.#wrapper.style.bottom = 'auto'\n\t\t\tthis.#wrapper.style.margin = '0'\n\t\t}\n\n\t\ttry {\n\t\t\tconst saved = JSON.parse(localStorage.getItem(DRAG_KEY) ?? 'null')\n\t\t\tif (\n\t\t\t\tsaved &&\n\t\t\t\ttypeof saved.x === 'number' &&\n\t\t\t\ttypeof saved.y === 'number' &&\n\t\t\t\tsaved.x < window.innerWidth - 60 &&\n\t\t\t\tsaved.y < window.innerHeight - 60\n\t\t\t)\n\t\t\t\tplace(saved.x, saved.y)\n\t\t} catch {\n\t\t\t/* default position when storage is unavailable */\n\t\t}\n\n\t\theader.addEventListener('pointerdown', (event) => {\n\t\t\tif (event.button !== 0 || (event.target as HTMLElement).closest('button')) return\n\t\t\tconst rect = this.#wrapper.getBoundingClientRect()\n\t\t\tthis.#dragOrigin = { dx: event.clientX - rect.left, dy: event.clientY - rect.top }\n\t\t\tthis.#dragged = false\n\t\t\t// Disable inherited position transitions so the panel follows the pointer exactly.\n\t\t\tthis.#wrapper.style.transition = 'none'\n\t\t\theader.setPointerCapture(event.pointerId)\n\t\t})\n\t\theader.addEventListener('pointermove', (event) => {\n\t\t\tif (!this.#dragOrigin) return\n\t\t\tthis.#dragged = true\n\t\t\tplace(event.clientX - this.#dragOrigin.dx, event.clientY - this.#dragOrigin.dy)\n\t\t})\n\t\tconst endDrag = () => {\n\t\t\tif (!this.#dragOrigin) return\n\t\t\tthis.#dragOrigin = null\n\t\t\tthis.#wrapper.style.transition = ''\n\t\t\tconst rect = this.#wrapper.getBoundingClientRect()\n\t\t\ttry {\n\t\t\t\tlocalStorage.setItem(DRAG_KEY, JSON.stringify({ x: rect.left, y: rect.top }))\n\t\t\t} catch {\n\t\t\t\t/* without storage, the position only lasts for this page */\n\t\t\t}\n\t\t}\n\t\theader.addEventListener('pointerup', endDrag)\n\t\theader.addEventListener('pointercancel', endDrag)\n\t\t// A drag ends with a click on the header; that click must not collapse or expand the feed.\n\t\theader.addEventListener(\n\t\t\t'click',\n\t\t\t(event) => {\n\t\t\t\tif (!this.#dragged) return\n\t\t\t\tthis.#dragged = false\n\t\t\t\tevent.stopPropagation()\n\t\t\t\tevent.preventDefault()\n\t\t\t},\n\t\t\ttrue\n\t\t)\n\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst setCursorHidden = (hidden: boolean) => {\n\t\t\tdocument.documentElement.toggleAttribute(CURSOR_ATTR, hidden)\n\t\t\t// Pressed means the agent cursor is visible.\n\t\t\tthis.#cursorButton.setAttribute('aria-pressed', String(!hidden))\n\t\t\tsetButton(\n\t\t\t\tthis.#cursorButton,\n\t\t\t\thidden ? 'cursorOff' : 'cursor',\n\t\t\t\tt(hidden ? 'ui.panel.showCursor' : 'ui.panel.hideCursor')\n\t\t\t)\n\t\t}\n\t\tsetCursorHidden(false)\n\t\tthis.#cursorButton.addEventListener('click', (event) => {\n\t\t\tevent.stopPropagation()\n\t\t\tsetCursorHidden(!document.documentElement.hasAttribute(CURSOR_ATTR))\n\t\t})\n\t}\n}\n","/**\n * Copyright (C) 2025 Alibaba Group Holding Limited\n * All rights reserved.\n */\nimport { type AgentConfig, PageAgentCore } from '@page-agent/core'\nimport { PageController, type PageControllerConfig } from '@page-agent/page-controller'\nimport { Panel, type PanelConfig } from '@page-agent/ui'\n\nexport * from '@page-agent/core'\nexport {\n\ttype AccessibilityConfig,\n\ttype AccessibilityController,\n\tAxError,\n\ttype AxErrorCode,\n} from '@page-agent/page-controller'\n\nexport type PageAgentConfig = AgentConfig & PageControllerConfig & Omit<PanelConfig, 'language'>\n\nexport class PageAgent extends PageAgentCore {\n\tpanel: Panel\n\n\tconstructor(config: PageAgentConfig) {\n\t\tconst pageController = new PageController({\n\t\t\t...config,\n\t\t\tenableMask: config.enableMask ?? true,\n\t\t})\n\n\t\tsuper({ ...config, pageController })\n\n\t\tpageController.isBusy = () => this.status === 'running'\n\n\t\tthis.panel = new Panel(this, {\n\t\t\tlanguage: config.language,\n\t\t\tsessionRecovery: config.sessionRecovery,\n\t\t\tsessionRecoveryKey: config.sessionRecoveryKey,\n\t\t\tpromptForNextTask: config.promptForNextTask,\n\t\t\tname: config.name,\n\t\t\tvoice: config.voice,\n\t\t\trunScript: (script) => this.#runScript(script),\n\t\t})\n\t}\n\n\t/** Runs a script in the page with this agent in scope, through the same tool the executor uses. */\n\t#runScript(script: string): Promise<string> {\n\t\tconst tool = this.tools.get('execute_javascript')\n\t\tif (!tool) return Promise.resolve('execute_javascript is not available in this session.')\n\t\tconst controller = new AbortController()\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined\n\t\tconst limit = new Promise<string>((resolve) => {\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\tcontroller.abort()\n\t\t\t\tresolve('The script took longer than 20 seconds, so the voice stopped waiting for it.')\n\t\t\t}, 20_000)\n\t\t})\n\t\tconst run = tool.execute.call(this, { script }, { signal: controller.signal })\n\t\treturn Promise.race([run, limit]).finally(() => clearTimeout(timer))\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAIA,IAAa,mBAAmB;CAE/B,eAAe;CACf,YAAY;CACZ,cAAc;CACd,cAAc;CACd,mBAAmB;CACnB,sBAAsB;CACtB,kBAAkB;CAClB,gBAAgB;CAEhB,SAAS;CAGT,cAAc;CACd,YAAY;CACZ,gBAAgB;CAChB,gBAAgB;AACjB;AAIA,IAAM,kBAA8C;CACnD,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;AAClB;AAEA,IAAa,cAAb,cAAiC,MAAM;CACtC;CACA;CACA;CAEA;CAEA;CAEA,YAAY,MAAuB,SAAiB,UAAoB,aAAuB;EAC9F,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,YAAY,gBAAgB,SAAS,IAAI;EAC9C,KAAK,WAAW;EAChB,KAAK,cAAc;CACpB;AACD;;;;;;AC/CA,SAAS,MAAM,GAAG,MAAiB;CAClC,QAAQ,MAAM,MAAM,KAAK,OAAO,GAAG,GAAG,IAAI;AAC3C;;;;;AAMA,SAAgB,gBAAgB,MAAc,MAAY;CACzD,OAAO;EACN,MAAM;EACN,UAAU;GACT;GACA,aAAa,KAAK;GAClB,YAAY,EAAE,aAAa,KAAK,aAAa,EAAE,QAAQ,cAAc,CAAC;EACvE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;GAC3B,mBAAmB,OAAO;GAC1B,MAAM,OAAO;GACb,OAAO,OAAO;GACd,YAAY,WAAW,KAAK,WAAW,MAAM;EAC9C,CAAC;CACF;;CAGA,WAAW,QAAiC;EAC3C,MAAM,OAAO,KAAK,MAAM,IAAI,oBAAoB;EAChD,IAAI,CAAC,MAAM,OAAO,QAAQ,QAAQ,sDAAsD;EACxF,MAAM,aAAa,IAAI,gBAAgB;EACvC,IAAI;EACJ,MAAM,QAAQ,IAAI,SAAiB,YAAY;GAC9C,QAAQ,iBAAiB;IACxB,WAAW,MAAM;IACjB,QAAQ,8EAA8E;GACvF,GAAG,GAAM;EACV,CAAC;EACD,MAAM,MAAM,KAAK,QAAQ,KAAK,MAAM,EAAE,OAAO,GAAG,EAAE,QAAQ,WAAW,OAAO,CAAC;EAC7E,OAAO,QAAQ,KAAK,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC,cAAc,aAAa,KAAK,CAAC;CACpE;AACD"}
|
|
1
|
+
{"version":3,"file":"page-agent.js","names":[],"sources":["../../../llms/src/errors.ts","../../../llms/src/utils.ts","../../../llms/src/OpenAIClient.ts","../../../llms/src/index.ts","../../../core/src/skills/files.ts","../../../core/src/utils/autoFixer.ts","../../../core/src/utils/index.ts","../../../core/src/tools/index.ts","../../../core/src/skills/types.ts","../../../core/src/skills/parse.ts","../../../core/src/skills/runtime.ts","../../../core/src/skills/storage.ts","../../../core/src/skills/host.ts","../../../core/src/skills/recorder.ts","../../../core/src/skills/synthesize.ts","../../../core/src/skills/watcher.ts","../../../core/src/PageAgentCore.ts","../../../page-controller/src/utils/index.ts","../../../page-controller/src/actions.ts","../../../page-controller/src/ax/domPath.ts","../../../page-controller/src/ax/evidence.ts","../../../page-controller/src/ax/errors.ts","../../../page-controller/src/ax/format.ts","../../../page-controller/src/ax/ids.ts","../../../page-controller/src/ax/observation.ts","../../../page-controller/src/ax/AccessibilityController.ts","../../../page-controller/src/dom/dom_tree/index.js","../../../page-controller/src/dom/index.ts","../../../page-controller/src/dom/getPageInfo.ts","../../../page-controller/src/patches/react.ts","../../../page-controller/src/scriptAccess.ts","../../../page-controller/src/scriptResult.ts","../../../page-controller/src/stateFreshness.ts","../../../page-controller/src/surfaceIndexes.ts","../../../page-controller/src/PageController.ts","../../../ui/src/i18n/locales.ts","../../../ui/src/i18n/index.ts","../../../ui/src/voice/realtime-protocol.ts","../../../ui/src/voice/gemini-protocol.ts","../../../ui/src/voice/gemini-client.ts","../../../ui/src/voice/realtime-client.ts","../../../ui/src/voice/voice-prompt.ts","../../../ui/src/voice/voice-session.ts","../../../ui/src/utils.ts","../../../ui/src/panel/Panel.module.css","../../../ui/src/panel/fold.ts","../../../ui/src/panel/icons.ts","../../../ui/src/panel/highlight.ts","../../../ui/src/panel/scriptCard.ts","../../../ui/src/panel/toolVisual.ts","../../../ui/src/panel/feed.ts","../../../ui/src/panel/microphone.ts","../../../ui/src/panel/recovery.ts","../../../ui/src/panel/trace.ts","../../../ui/src/panel/voiceRuns.ts","../../../ui/src/panel/Panel.ts","../../src/PageAgent.ts"],"sourcesContent":["/**\n * Error types and error handling for LLM invocations.\n */\n\nexport const InvokeErrorTypes = {\n\t// Retryable\n\tNETWORK_ERROR: 'network_error', // Network error, retry\n\tRATE_LIMIT: 'rate_limit', // Rate limit, retry\n\tSERVER_ERROR: 'server_error', // 5xx, retry\n\tNO_TOOL_CALL: 'no_tool_call', // Model did not call tool\n\tINVALID_TOOL_ARGS: 'invalid_tool_args', // Tool args don't match schema\n\tTOOL_EXECUTION_ERROR: 'tool_execution_error', // Tool execution error\n\tINVALID_RESPONSE: 'invalid_response', // Response body is not valid JSON\n\tINVALID_SCHEMA: 'invalid_schema', // Response is valid JSON but doesn't match expected shape\n\n\tUNKNOWN: 'unknown',\n\n\t// Non-retryable\n\tCONFIG_ERROR: 'config_error', // Invalid local configuration or hook\n\tAUTH_ERROR: 'auth_error', // Authentication failed\n\tCONTEXT_LENGTH: 'context_length', // Prompt too long\n\tCONTENT_FILTER: 'content_filter', // Content filtered\n} as const\n\ntype InvokeErrorType = (typeof InvokeErrorTypes)[keyof typeof InvokeErrorTypes]\n\nconst RETRYABLE_TYPES: readonly InvokeErrorType[] = [\n\tInvokeErrorTypes.NETWORK_ERROR,\n\tInvokeErrorTypes.RATE_LIMIT,\n\tInvokeErrorTypes.SERVER_ERROR,\n\tInvokeErrorTypes.NO_TOOL_CALL,\n\tInvokeErrorTypes.INVALID_TOOL_ARGS,\n\tInvokeErrorTypes.TOOL_EXECUTION_ERROR,\n\tInvokeErrorTypes.INVALID_RESPONSE,\n\tInvokeErrorTypes.INVALID_SCHEMA,\n\tInvokeErrorTypes.UNKNOWN,\n]\n\nexport class InvokeError extends Error {\n\ttype: InvokeErrorType\n\tretryable: boolean\n\tstatusCode?: number\n\t/* raw error (provided if this error is caused by another error) */\n\trawError?: unknown\n\t/* raw response from the API (provided if this error is caused by an API calling) */\n\trawResponse?: unknown\n\n\tconstructor(type: InvokeErrorType, message: string, rawError?: unknown, rawResponse?: unknown) {\n\t\tsuper(message)\n\t\tthis.name = 'InvokeError'\n\t\tthis.type = type\n\t\tthis.retryable = RETRYABLE_TYPES.includes(type)\n\t\tthis.rawError = rawError\n\t\tthis.rawResponse = rawResponse\n\t}\n}\n","/**\n * Utility functions for LLM integration\n */\nimport chalk from 'chalk'\nimport * as z from 'zod/v4'\n\nimport type { Tool } from './types'\n\nfunction debug(...args: unknown[]) {\n\tconsole.debug(chalk.gray('[LLM]'), ...args)\n}\n\n/**\n * Convert Zod schema to OpenAI tool format\n * Uses Zod 4 native z.toJSONSchema()\n */\nexport function zodToOpenAITool(name: string, tool: Tool) {\n\treturn {\n\t\ttype: 'function' as const,\n\t\tfunction: {\n\t\t\tname,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: z.toJSONSchema(tool.inputSchema, { target: 'openapi-3.0' }),\n\t\t},\n\t}\n}\n\n/**\n * Patch model specific parameters. Only patches known models.\n *\n * @purpose\n * - Reconcile the differences in the parameter schema each model accepts.\n * - Disable thinking/reasoning, or lower it to the minimum where a full disable is impossible.\n * - Minimize returned tokens.\n * - Raise temperature for known smaller models to improve auto-recovery odds.\n * @note Honor temperature if explicitly set by the user\n *\n * @todo Need vendor-specific patches.\n * Local and 3rd-party hosted models may have different schema.\n */\nexport function modelPatch(body: Record<string, any>, baseURL?: string) {\n\tconst model: string = body.model || ''\n\tif (!model) return body\n\n\tconst provider = getProvider(baseURL)\n\n\tconst modelName = normalizeModelName(model)\n\n\tif (modelName.startsWith('qwen')) {\n\t\tif (provider === 'openrouter' && modelName.startsWith('qwen38-max')) {\n\t\t\t// OpenRouter forces thinking on for this endpoint, and Qwen rejects tool_choice in thinking mode\n\t\t\tdebug('Patch Qwen3.8-max on OpenRouter: reasoning_effort=low, remove tool_choice')\n\t\t\tbody.reasoning_effort = 'low'\n\t\t\tdelete body.tool_choice\n\t\t} else {\n\t\t\tdebug('Patch Qwen: disable thinking')\n\t\t\tbody.enable_thinking = false\n\t\t}\n\t\tif (body.temperature === undefined && !/max|plus/.test(modelName)) {\n\t\t\tdebug('Patch Qwen: raise temperature to 1.0')\n\t\t\tbody.temperature = 1.0\n\t\t}\n\t}\n\n\tif (modelName.startsWith('deepseek')) {\n\t\tdebug('Patch DeepSeek: disable thinking, remove tool_choice')\n\t\tbody.thinking = { type: 'disabled' }\n\t\tdelete body.tool_choice\n\t}\n\n\tif (modelName.startsWith('gpt')) {\n\t\tif (modelName.startsWith('gpt-5')) {\n\t\t\tbody.verbosity = 'low'\n\t\t}\n\n\t\t// Since gpt-5.4, /chat/completions rejects any explicit reasoning_effort\n\t\t// when function tools are present. Newer models are expected to follow.\n\t\t// - gpt-5.1 / gpt-5.2 can fully disable reasoning\n\t\t// - gpt-5 / -mini / -nano bottom out at \"minimal\"\n\t\t// - everything else (gpt-4.x, chat-latest, gpt-5.4+) must not receive it\n\t\tif (modelName.includes('chat-latest')) {\n\t\t\tdebug('Patch chat-latest: omit reasoning_effort and temperature')\n\t\t\tdelete body.reasoning_effort\n\t\t\tdelete body.temperature\n\t\t} else if (/^gpt-5[12](-|$)/.test(modelName)) {\n\t\t\tdebug('Patch GPT-5.1/5.2: reasoning_effort=none')\n\t\t\tbody.reasoning_effort = 'none'\n\t\t} else if (/^gpt-5(-|$)/.test(modelName)) {\n\t\t\tdebug('Patch GPT-5: reasoning_effort=minimal')\n\t\t\tbody.reasoning_effort = 'minimal'\n\t\t} else {\n\t\t\tdebug('Patch GPT: omit reasoning_effort')\n\t\t\tdelete body.reasoning_effort\n\t\t}\n\t}\n\n\tif (modelName.startsWith('claude')) {\n\t\tif (/opus|sonnet|haiku/.test(modelName)) {\n\t\t\tdebug('Patch Claude: disable thinking')\n\t\t\tbody.thinking = { type: 'disabled' }\n\n\t\t\tif (provider !== 'openrouter') {\n\t\t\t\t// Convert tool_choice to Claude format\n\t\t\t\tif (body.tool_choice === 'required') {\n\t\t\t\t\t// 'required' -> { type: 'any' } (must call some tool)\n\t\t\t\t\tdebug('Applying Claude patch: convert tool_choice \"required\" to { type: \"any\" }')\n\t\t\t\t\tbody.tool_choice = { type: 'any' }\n\t\t\t\t} else if (body.tool_choice?.function?.name) {\n\t\t\t\t\t// { type: 'function', function: { name: '...' } } -> { type: 'tool', name: '...' }\n\t\t\t\t\tdebug('Applying Claude patch: convert tool_choice format')\n\t\t\t\t\tbody.tool_choice = { type: 'tool', name: body.tool_choice.function.name }\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tdebug('Patch Claude: reasoning_effort=low')\n\t\t\tbody.reasoning_effort = 'low'\n\n\t\t\t// Fable and mythos can not disable adaptive thinking.\n\t\t\t// Claude does not support tool_choice with extended thinking.\n\t\t\t// These 2 concepts are blurred. Basically no tool_choice with thinking.\n\t\t\tdelete body.tool_choice\n\t\t}\n\t}\n\n\tif (modelName.startsWith('gemini')) {\n\t\tdebug('Patch Gemini: reasoning_effort=low')\n\t\tbody.reasoning_effort = 'low'\n\t\tif (/^gemini-25(?!.*pro)/.test(modelName)) {\n\t\t\tdebug('Patch Gemini 2.5 non-Pro: reasoning_effort=none')\n\t\t\tbody.reasoning_effort = 'none'\n\t\t} else if (\n\t\t\tmodelName.startsWith('gemini-35-flash') ||\n\t\t\tmodelName.startsWith('gemini-31-flash-lite') ||\n\t\t\tmodelName.startsWith('gemini-3-flash')\n\t\t) {\n\t\t\tdebug('Patch Gemini 3.x Flash/Lite: reasoning_effort=minimal')\n\t\t\tbody.reasoning_effort = 'minimal'\n\t\t}\n\t}\n\n\tif (modelName.startsWith('glm')) {\n\t\tif (/^glm-5[3-9]/.test(modelName)) {\n\t\t\t// GLM 5.3+ cannot disable thinking\n\t\t\tdebug('Patch GLM 5.3+: reasoning_effort=low')\n\t\t\tbody.reasoning_effort = 'low'\n\t\t} else {\n\t\t\tdebug('Patch GLM: disable thinking')\n\t\t\tbody.thinking = { type: 'disabled' }\n\t\t}\n\t}\n\n\tif (modelName.startsWith('hy')) {\n\t\tdebug('Patch Hunyuan: disable thinking, reasoning_effort=low')\n\t\tbody.thinking = { type: 'disabled' }\n\t\tbody.reasoning_effort = 'low'\n\t}\n\n\tif (modelName.startsWith('grok')) {\n\t\tif (/^grok-4-?3/.test(modelName)) {\n\t\t\tdebug('Patch Grok 4.3: reasoning_effort=none')\n\t\t\tbody.reasoning_effort = 'none'\n\t\t} else if (modelName.startsWith('grok-3-mini') || modelName.startsWith('grok-code-fast')) {\n\t\t\tdebug('Patch Grok mini/code: reasoning_effort=low')\n\t\t\tbody.reasoning_effort = 'low'\n\t\t}\n\t}\n\n\tif (modelName.startsWith('kimi')) {\n\t\tif (modelName.startsWith('kimi-k3')) {\n\t\t\t// Kimi K3 always thinks and rejects named tool choice while thinking.\n\t\t\tdebug('Patch Kimi K3: use required tool choice, remove parallel tool calls')\n\t\t\tdelete body.parallel_tool_calls\n\t\t\tif (body.tool_choice?.function?.name) body.tool_choice = 'required'\n\t\t} else if (!modelName.includes('code')) {\n\t\t\t// kimi-k2.7-code cannot disable thinking\n\t\t\tdebug('Patch Kimi: disable thinking')\n\t\t\tbody.thinking = { type: 'disabled' }\n\t\t}\n\t}\n\n\tif (modelName.startsWith('minimax')) {\n\t\tdebug('Patch MiniMax: remove parallel_tool_calls')\n\t\tdelete body.parallel_tool_calls\n\n\t\tif (modelName.includes('m3')) {\n\t\t\t// Only M3 can disable thinking\n\t\t\tdebug('Patch MiniMax: disable thinking')\n\t\t\tbody.thinking = { type: 'disabled' }\n\t\t}\n\t}\n\n\t// provider patches\n\n\tif (provider === 'openrouter') {\n\t\t// openrouter use reasoning object instead of reasoning_effort\n\n\t\tconst reasoningEffort = body.reasoning_effort\n\t\tconst reasoningDisabled =\n\t\t\tbody.thinking?.type === 'disabled' ||\n\t\t\tbody.enable_thinking === false ||\n\t\t\treasoningEffort === 'none'\n\n\t\tif (reasoningDisabled) {\n\t\t\tbody.reasoning = { enabled: false }\n\t\t} else if (reasoningEffort) {\n\t\t\tbody.reasoning = { enabled: true, effort: reasoningEffort }\n\t\t}\n\t}\n\n\treturn body\n}\n\n/**\n * check if a given model ID fits a specific model name\n *\n * @note\n * Different model providers may use different model IDs for the same model.\n * For example, openai's `gpt-5.2` may called:\n *\n * - `gpt-5.2-version`\n * - `gpt-5_2-date`\n * - `GPT-52-version-date`\n * - `openai/gpt-5.2-chat`\n *\n * They should be treated as the same model.\n * Normalize them to `gpt-52`\n */\nexport function normalizeModelName(modelName: string): string {\n\tlet normalizedName = modelName.toLowerCase()\n\n\t// remove prefix before '/'\n\tif (normalizedName.includes('/')) {\n\t\tnormalizedName = normalizedName.split('/')[1]\n\t}\n\n\t// remove '_'\n\tnormalizedName = normalizedName.replace(/_/g, '')\n\n\t// remove '.'\n\tnormalizedName = normalizedName.replace(/\\./g, '')\n\n\treturn normalizedName\n}\n\nexport function getProvider(baseURL?: string): 'openrouter' | undefined {\n\tif (!baseURL) return undefined\n\ttry {\n\t\tconst url = new URL(baseURL)\n\t\tconst hostname = url.hostname\n\t\tif (hostname === 'openrouter.ai') return 'openrouter'\n\t\treturn undefined\n\t} catch (e) {\n\t\treturn undefined\n\t}\n}\n","/**\n * OpenAI Client implementation\n */\nimport * as z from 'zod/v4'\n\nimport { InvokeError, InvokeErrorTypes } from './errors'\nimport type {\n\tInvokeOptions,\n\tInvokeResult,\n\tLLMClient,\n\tMessage,\n\tResolvedLLMConfig,\n\tTool,\n} from './types'\nimport { modelPatch, zodToOpenAITool } from './utils'\n\n/**\n * Client for OpenAI compatible APIs\n */\nexport class OpenAIClient implements LLMClient {\n\tconfig: ResolvedLLMConfig\n\tprivate fetch: typeof globalThis.fetch\n\n\tconstructor(config: ResolvedLLMConfig) {\n\t\tthis.config = config\n\t\tthis.fetch = config.customFetch\n\t}\n\n\tasync invoke(\n\t\tmessages: Message[],\n\t\ttools: Record<string, Tool>,\n\t\tabortSignal?: AbortSignal,\n\t\toptions?: InvokeOptions\n\t): Promise<InvokeResult> {\n\t\tabortSignal?.throwIfAborted()\n\n\t\t// 1. Convert tools to OpenAI format\n\t\tconst openaiTools = Object.entries(tools).map(([name, t]) => zodToOpenAITool(name, t))\n\n\t\t// Build request body\n\n\t\tlet toolChoice: unknown = 'required'\n\t\tif (options?.toolChoiceName && !this.config.disableNamedToolChoice) {\n\t\t\ttoolChoice = { type: 'function', function: { name: options.toolChoiceName } }\n\t\t}\n\n\t\tconst requestBody: Record<string, unknown> = {\n\t\t\tmodel: this.config.model,\n\t\t\tmessages,\n\t\t\ttools: openaiTools,\n\t\t\tparallel_tool_calls: false,\n\t\t\ttool_choice: toolChoice,\n\t\t}\n\t\t// Only sent if the caller explicitly set it. Most new models throw if this is set.\n\t\tif (this.config.temperature !== undefined) {\n\t\t\trequestBody.temperature = this.config.temperature\n\t\t}\n\n\t\tmodelPatch(requestBody, this.config.baseURL)\n\n\t\tlet transformedBody: Record<string, unknown> | undefined\n\t\ttry {\n\t\t\ttransformedBody = this.config.transformRequestBody(requestBody)\n\t\t} catch (error) {\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.CONFIG_ERROR,\n\t\t\t\t`transformRequestBody failed: ${(error as Error).message}`,\n\t\t\t\terror\n\t\t\t)\n\t\t}\n\t\tconst finalRequestBody = transformedBody ?? requestBody\n\n\t\t// 2. Call API\n\t\tlet response: Response\n\t\ttry {\n\t\t\tresponse = await this.fetch(`${this.config.baseURL}/chat/completions`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t...(this.config.apiKey && { Authorization: `Bearer ${this.config.apiKey}` }),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(finalRequestBody),\n\t\t\t\tsignal: abortSignal,\n\t\t\t})\n\t\t} catch (error: unknown) {\n\t\t\tif ((error as any)?.name === 'AbortError') throw error\n\t\t\tconsole.error(error)\n\t\t\tthrow new InvokeError(InvokeErrorTypes.NETWORK_ERROR, 'Network request failed', error)\n\t\t}\n\n\t\t// 3. Handle HTTP errors\n\t\tif (!response.ok) {\n\t\t\tlet errorData: any\n\t\t\ttry {\n\t\t\t\terrorData = await response.json()\n\t\t\t} catch (error) {\n\t\t\t\tif ((error as any)?.name === 'AbortError') throw error\n\t\t\t}\n\t\t\tconst errorMessage = errorData?.error?.message || response.statusText\n\n\t\t\tif (response.status === 401 || response.status === 403) {\n\t\t\t\tthrow new InvokeError(\n\t\t\t\t\tInvokeErrorTypes.AUTH_ERROR,\n\t\t\t\t\t`Authentication failed: ${errorMessage}`,\n\t\t\t\t\terrorData\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (response.status === 429) {\n\t\t\t\tthrow new InvokeError(\n\t\t\t\t\tInvokeErrorTypes.RATE_LIMIT,\n\t\t\t\t\t`Rate limit exceeded: ${errorMessage}`,\n\t\t\t\t\terrorData\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (response.status >= 500) {\n\t\t\t\tthrow new InvokeError(\n\t\t\t\t\tInvokeErrorTypes.SERVER_ERROR,\n\t\t\t\t\t`Server error: ${errorMessage}`,\n\t\t\t\t\terrorData\n\t\t\t\t)\n\t\t\t}\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.UNKNOWN,\n\t\t\t\t`HTTP ${response.status}: ${errorMessage}`,\n\t\t\t\terrorData\n\t\t\t)\n\t\t}\n\n\t\t// 4. Parse and validate response\n\t\tlet data: any\n\t\ttry {\n\t\t\tdata = await response.json()\n\t\t} catch (error) {\n\t\t\tif ((error as any)?.name === 'AbortError') throw error\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.INVALID_RESPONSE,\n\t\t\t\t'Response body is not valid JSON',\n\t\t\t\terror\n\t\t\t)\n\t\t}\n\n\t\tconst choice = data.choices?.[0]\n\t\tif (!choice) {\n\t\t\tthrow new InvokeError(InvokeErrorTypes.INVALID_SCHEMA, 'No choices in response', data)\n\t\t}\n\n\t\t// Check finish_reason\n\t\tswitch (choice.finish_reason) {\n\t\t\tcase 'tool_calls':\n\t\t\tcase 'function_call': // gemini\n\t\t\tcase 'stop': // some models use this even with tool calls\n\t\t\t\tbreak\n\t\t\tcase 'length':\n\t\t\t\tthrow new InvokeError(\n\t\t\t\t\tInvokeErrorTypes.CONTEXT_LENGTH,\n\t\t\t\t\t'Response truncated: max tokens reached',\n\t\t\t\t\tundefined,\n\t\t\t\t\tdata\n\t\t\t\t)\n\t\t\tcase 'content_filter':\n\t\t\t\tthrow new InvokeError(\n\t\t\t\t\tInvokeErrorTypes.CONTENT_FILTER,\n\t\t\t\t\t'Content filtered by safety system',\n\t\t\t\t\tundefined,\n\t\t\t\t\tdata\n\t\t\t\t)\n\t\t\tdefault:\n\t\t\t\tthrow new InvokeError(\n\t\t\t\t\tInvokeErrorTypes.INVALID_SCHEMA,\n\t\t\t\t\t`Unexpected finish_reason: ${choice.finish_reason}`,\n\t\t\t\t\tundefined,\n\t\t\t\t\tdata\n\t\t\t\t)\n\t\t}\n\n\t\t// Apply normalizeResponse if provided (for fixing format issues automatically)\n\t\tconst normalizedData = options?.normalizeResponse ? options.normalizeResponse(data) : data\n\t\tconst normalizedChoice = (normalizedData as any).choices?.[0]\n\n\t\t// Get tool name from response\n\t\tconst toolCallName = normalizedChoice?.message?.tool_calls?.[0]?.function?.name\n\t\tif (!toolCallName) {\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.NO_TOOL_CALL,\n\t\t\t\t'No tool call found in response',\n\t\t\t\tundefined,\n\t\t\t\tdata\n\t\t\t)\n\t\t}\n\n\t\tconst tool = tools[toolCallName]\n\t\tif (!tool) {\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.UNKNOWN,\n\t\t\t\t`Tool \"${toolCallName}\" not found in tools`,\n\t\t\t\tundefined,\n\t\t\t\tdata\n\t\t\t)\n\t\t}\n\n\t\t// Extract and parse tool arguments\n\t\tconst argString = normalizedChoice.message?.tool_calls?.[0]?.function?.arguments\n\t\tif (!argString) {\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.INVALID_TOOL_ARGS,\n\t\t\t\t'No tool call arguments found',\n\t\t\t\tundefined,\n\t\t\t\tdata\n\t\t\t)\n\t\t}\n\n\t\tlet parsedArgs: unknown\n\t\ttry {\n\t\t\tparsedArgs = JSON.parse(argString)\n\t\t} catch (error) {\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.INVALID_TOOL_ARGS,\n\t\t\t\t'Failed to parse tool arguments as JSON',\n\t\t\t\terror,\n\t\t\t\tdata\n\t\t\t)\n\t\t}\n\n\t\t// Validate with schema\n\t\tconst validation = tool.inputSchema.safeParse(parsedArgs)\n\t\tif (!validation.success) {\n\t\t\tconsole.error(z.prettifyError(validation.error))\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.INVALID_TOOL_ARGS,\n\t\t\t\t'Tool arguments validation failed',\n\t\t\t\tvalidation.error,\n\t\t\t\tdata\n\t\t\t)\n\t\t}\n\t\tconst toolInput = validation.data\n\n\t\t// 5. Execute tool\n\t\tlet toolResult: unknown\n\t\ttry {\n\t\t\ttoolResult = await tool.execute(toolInput)\n\t\t} catch (error: unknown) {\n\t\t\tif ((error as any)?.name === 'AbortError') throw error\n\t\t\tthrow new InvokeError(\n\t\t\t\tInvokeErrorTypes.TOOL_EXECUTION_ERROR,\n\t\t\t\t`Tool execution failed: ${(error as Error)?.message}`,\n\t\t\t\terror,\n\t\t\t\tdata\n\t\t\t)\n\t\t}\n\n\t\t// Return result\n\t\treturn {\n\t\t\ttoolCall: {\n\t\t\t\tname: toolCallName,\n\t\t\t\targs: toolInput,\n\t\t\t},\n\t\t\ttoolResult,\n\t\t\tusage: {\n\t\t\t\tpromptTokens: data.usage?.prompt_tokens ?? 0,\n\t\t\t\tcompletionTokens: data.usage?.completion_tokens ?? 0,\n\t\t\t\ttotalTokens: data.usage?.total_tokens ?? 0,\n\t\t\t\tcachedTokens: data.usage?.prompt_tokens_details?.cached_tokens,\n\t\t\t\treasoningTokens: data.usage?.completion_tokens_details?.reasoning_tokens,\n\t\t\t},\n\t\t\trawResponse: data,\n\t\t\trawRequest: finalRequestBody,\n\t\t}\n\t}\n}\n","import { OpenAIClient } from './OpenAIClient'\nimport { InvokeError, InvokeErrorTypes } from './errors'\nimport type {\n\tInvokeOptions,\n\tInvokeResult,\n\tLLMClient,\n\tLLMConfig,\n\tMessage,\n\tResolvedLLMConfig,\n\tTool,\n} from './types'\n\nexport { InvokeError, InvokeErrorTypes }\nexport type { InvokeOptions, InvokeResult, LLMClient, LLMConfig, Message, Tool }\n\n/**\n * LLM module\n */\nexport class LLM extends EventTarget {\n\tconfig: ResolvedLLMConfig\n\tclient: LLMClient\n\n\tconstructor(config: LLMConfig) {\n\t\tsuper()\n\t\tthis.config = parseLLMConfig(config)\n\n\t\t// Default to OpenAI client\n\t\tthis.client = new OpenAIClient(this.config)\n\t}\n\n\t/**\n\t * - call llm api *once*\n\t * - invoke tool call *once*\n\t * - return the result of the tool\n\t */\n\tasync invoke(\n\t\tmessages: Message[],\n\t\ttools: Record<string, Tool>,\n\t\tabortSignal: AbortSignal,\n\t\toptions?: InvokeOptions\n\t): Promise<InvokeResult> {\n\t\treturn await withRetry(async () => this.client.invoke(messages, tools, abortSignal, options), {\n\t\t\tmaxRetries: this.config.maxRetries,\n\t\t\tonRetry: (attempt, lastError) => {\n\t\t\t\tthis.dispatchEvent(\n\t\t\t\t\tnew CustomEvent('retry', {\n\t\t\t\t\t\tdetail: { attempt, maxAttempts: this.config.maxRetries, lastError },\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t},\n\t\t})\n\t}\n}\n\n/**\n * Retry a function until it succeeds or reaches the maximum number of retries.\n */\nasync function withRetry<T>(\n\tfn: () => Promise<T>,\n\tsettings: {\n\t\tmaxRetries: number\n\t\tonRetry: (attempt: number, lastError: Error) => void\n\t}\n): Promise<T> {\n\tlet attempt = 0\n\twhile (true) {\n\t\ttry {\n\t\t\treturn await fn()\n\t\t} catch (error: unknown) {\n\t\t\tif ((error as any)?.name === 'AbortError') throw error\n\t\t\tif (error instanceof InvokeError && !error.retryable) throw error\n\t\t\tattempt++\n\t\t\tif (attempt > settings.maxRetries) throw error\n\n\t\t\tconsole.debug('[LLM] retryable failure, will retry:', error)\n\t\t\tsettings.onRetry(attempt, error as Error)\n\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 100))\n\t\t}\n\t}\n}\n\nexport function parseLLMConfig(config: LLMConfig): ResolvedLLMConfig {\n\t// Runtime validation as defensive programming (types already guarantee these)\n\tif (!config.baseURL || !config.model) {\n\t\tthrow new Error(\n\t\t\t'[PageAgent] LLM configuration required. Please provide: baseURL, model. ' +\n\t\t\t\t'See: https://alibaba.github.io/page-agent/docs/features/models'\n\t\t)\n\t}\n\n\tif (config.temperature !== undefined) {\n\t\tconsole.warn(\n\t\t\t'[PageAgent] LLMConfig.temperature is deprecated and will be removed in a future version. ' +\n\t\t\t\t'Use transformRequestBody to set it only for models you have verified accept it.'\n\t\t)\n\t}\n\n\treturn {\n\t\tbaseURL: config.baseURL,\n\t\tmodel: config.model,\n\t\tapiKey: config.apiKey || '',\n\t\ttemperature: config.temperature,\n\t\tmaxRetries: config.maxRetries ?? 2,\n\t\ttransformRequestBody: config.transformRequestBody ?? ((requestBody) => requestBody),\n\t\tdisableNamedToolChoice: config.disableNamedToolChoice ?? false,\n\t\tcustomFetch: (config.customFetch ?? fetch).bind(globalThis), // fetch will be illegal unless bound\n\t}\n}\n","/**\n * Task attachment store for skill ctx.files.\n * Callers: SkillHost / createSkillContext; Panel may push files later.\n * Empty-safe until UI attaches files for a task.\n */\n\nexport interface SkillAttachment {\n\tid: string\n\tname: string\n\tmimeType: string\n\t/** UTF-8 text when available; binary left as base64 in `dataBase64`. */\n\ttext?: string\n\tdataBase64?: string\n\tsize: number\n}\n\nexport interface SkillFileStore {\n\tlist(): SkillAttachment[]\n\tread(id: string): SkillAttachment | undefined\n\tclear(): void\n\tremove(id: string): boolean\n\tadd(file: Omit<SkillAttachment, 'id'> & { id?: string }): SkillAttachment\n}\n\n/** Soft cap so panel attaches stay in memory without blowing the tab. */\nexport const MAX_TASK_FILE_BYTES = 1_048_576\n\n/** In-memory attachment store for one agent / task lifecycle. */\nexport function createSkillFileStore(): SkillFileStore {\n\tconst files = new Map<string, SkillAttachment>()\n\tlet seq = 0\n\n\treturn {\n\t\tlist() {\n\t\t\treturn [...files.values()]\n\t\t},\n\t\tread(id: string) {\n\t\t\treturn files.get(id)\n\t\t},\n\t\tclear() {\n\t\t\tfiles.clear()\n\t\t},\n\t\tremove(id: string) {\n\t\t\treturn files.delete(id)\n\t\t},\n\t\tadd(file) {\n\t\t\tconst id = file.id ?? `file-${++seq}`\n\t\t\tconst entry: SkillAttachment = {\n\t\t\t\tid,\n\t\t\t\tname: file.name,\n\t\t\t\tmimeType: file.mimeType,\n\t\t\t\ttext: file.text,\n\t\t\t\tdataBase64: file.dataBase64,\n\t\t\t\tsize: file.size,\n\t\t\t}\n\t\t\tfiles.set(id, entry)\n\t\t\treturn entry\n\t\t},\n\t}\n}\n\nfunction isTextAttachment(name: string, mimeType: string): boolean {\n\tif (mimeType.startsWith('text/')) return true\n\tif (\n\t\tmimeType === 'application/json' ||\n\t\tmimeType === 'application/xml' ||\n\t\tmimeType === 'application/javascript' ||\n\t\tmimeType === 'application/typescript'\n\t) {\n\t\treturn true\n\t}\n\treturn /\\.(md|txt|json|csv|tsv|xml|html?|js|mjs|cjs|ts|tsx|jsx|css|yml|yaml|toml|log)$/i.test(\n\t\tname\n\t)\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\tif (typeof Buffer !== 'undefined') {\n\t\treturn Buffer.from(bytes).toString('base64')\n\t}\n\tlet binary = ''\n\tconst chunk = 0x8000\n\tfor (let i = 0; i < bytes.length; i += chunk) {\n\t\tbinary += String.fromCharCode(...bytes.subarray(i, i + chunk))\n\t}\n\treturn btoa(binary)\n}\n\n/** Build a SkillAttachment payload from a browser File / Blob. */\nexport async function readTaskFileBlob(\n\tfile: Blob & { name?: string },\n\toptions?: { maxBytes?: number }\n): Promise<Omit<SkillAttachment, 'id'>> {\n\tconst maxBytes = options?.maxBytes ?? MAX_TASK_FILE_BYTES\n\tconst name = file.name?.trim() || 'attachment'\n\tconst mimeType = file.type || 'application/octet-stream'\n\tif (file.size > maxBytes) {\n\t\tthrow new Error(`File \"${name}\" is too large (max ${maxBytes} bytes)`)\n\t}\n\n\tif (isTextAttachment(name, mimeType)) {\n\t\tconst text = await file.text()\n\t\treturn { name, mimeType, text, size: file.size }\n\t}\n\n\tconst bytes = new Uint8Array(await file.arrayBuffer())\n\treturn { name, mimeType, dataBase64: bytesToBase64(bytes), size: file.size }\n}\n","import { InvokeError, InvokeErrorTypes } from '@page-agent/llms'\nimport chalk from 'chalk'\nimport * as z from 'zod/v4'\n\nimport type { PageAgentTool } from '../tools'\n\nconst log = console.log.bind(console, chalk.yellow('[autoFixer]'))\n\n/**\n * Normalize LLM response and fix common format issues.\n *\n * Handles:\n * - No tool_calls but JSON in message.content (fallback)\n * - Model returns action name as tool call instead of AgentOutput\n * - Arguments wrapped as double JSON string\n * - Nested function call format\n * - Missing action field (fallback to wait)\n * - Primitive action input for single-field tools (e.g. `{\"click_element_by_index\": 2}`)\n * - etc.\n */\nexport function normalizeResponse(response: any, tools?: Map<string, PageAgentTool>): any {\n\tlet resolvedArguments: any\n\n\tconst choice = (response as { choices?: Choice[] }).choices?.[0]\n\tif (!choice) throw new Error('No choices in response')\n\n\tconst message = choice.message\n\tif (!message) throw new Error('No message in choice')\n\n\tconst toolCall = message.tool_calls?.[0]\n\n\t// fix level and location of arguments\n\n\tif (toolCall?.function?.arguments) {\n\t\tresolvedArguments = safeJsonParse(toolCall.function.arguments)\n\n\t\t// case: sometimes the model only returns the action level\n\t\tif (toolCall.function.name && toolCall.function.name !== 'AgentOutput') {\n\t\t\tlog(`#1: fixing tool_call`)\n\t\t\tresolvedArguments = { action: safeJsonParse(resolvedArguments) }\n\t\t}\n\t} else {\n\t\t// case: sometimes the model returns json in content instead of tool_calls\n\t\tif (message.content) {\n\t\t\tconst content = message.content.trim()\n\t\t\tconst jsonInContent = retrieveJsonFromString(content)\n\t\t\tif (jsonInContent) {\n\t\t\t\tresolvedArguments = safeJsonParse(jsonInContent)\n\n\t\t\t\t// case: sometimes the content json includes upper level wrapper\n\t\t\t\tif (resolvedArguments?.name === 'AgentOutput') {\n\t\t\t\t\tlog(`#2: fixing tool_call`)\n\t\t\t\t\tresolvedArguments = safeJsonParse(resolvedArguments.arguments)\n\t\t\t\t}\n\n\t\t\t\t// case: sometimes even 2-levels of wrapping\n\t\t\t\tif (resolvedArguments?.type === 'function') {\n\t\t\t\t\tlog(`#3: fixing tool_call`)\n\t\t\t\t\tresolvedArguments = safeJsonParse(resolvedArguments.function.arguments)\n\t\t\t\t}\n\n\t\t\t\t// case: and sometimes action level only\n\t\t\t\t// todo: needs better detection logic\n\t\t\t\tif (\n\t\t\t\t\t!resolvedArguments?.action &&\n\t\t\t\t\t!resolvedArguments?.evaluation_previous_goal &&\n\t\t\t\t\t!resolvedArguments?.memory &&\n\t\t\t\t\t!resolvedArguments?.next_goal &&\n\t\t\t\t\t!resolvedArguments?.thinking\n\t\t\t\t) {\n\t\t\t\t\tlog(`#4: fixing tool_call`)\n\t\t\t\t\tresolvedArguments = { action: safeJsonParse(resolvedArguments) }\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new Error('No tool_call and the message content does not contain valid JSON')\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new Error('No tool_call nor message content is present')\n\t\t}\n\t}\n\n\t// fix double stringified arguments\n\tresolvedArguments = safeJsonParse(resolvedArguments)\n\tif (resolvedArguments.action) {\n\t\tresolvedArguments.action = safeJsonParse(resolvedArguments.action)\n\t}\n\n\t// validate and fix action input using tool schemas\n\tif (resolvedArguments.action && tools) {\n\t\tresolvedArguments.action = validateAction(resolvedArguments.action, tools)\n\t}\n\n\t// fix incomplete formats\n\tif (!resolvedArguments.action) {\n\t\tlog(`#5: fixing tool_call`)\n\t\tresolvedArguments.action = { wait: { seconds: 1 } }\n\t}\n\n\t// pack back to standard format\n\treturn {\n\t\t...response,\n\t\tchoices: [\n\t\t\t{\n\t\t\t\t...choice,\n\t\t\t\tmessage: {\n\t\t\t\t\t...message,\n\t\t\t\t\ttool_calls: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...(toolCall || {}),\n\t\t\t\t\t\t\tfunction: {\n\t\t\t\t\t\t\t\t...(toolCall?.function || {}),\n\t\t\t\t\t\t\t\tname: 'AgentOutput',\n\t\t\t\t\t\t\t\targuments: JSON.stringify(resolvedArguments),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t}\n}\n\n/**\n * Validate action against tool schemas. Provides clear error messages\n * instead of letting the union schema produce unreadable errors.\n *\n * Also coerces primitive inputs for single-field tools:\n * e.g. `{\"click_element_by_index\": 2}` → `{\"click_element_by_index\": {\"index\": 2}}`\n */\nfunction validateAction(action: any, tools: Map<string, PageAgentTool>): any {\n\tif (typeof action !== 'object' || action === null) return action\n\n\tconst toolName = Object.keys(action)[0]\n\tif (!toolName) return action\n\n\tconst tool = tools.get(toolName)\n\tif (!tool) {\n\t\tconst available = Array.from(tools.keys()).join(', ')\n\t\tthrow new InvokeError(\n\t\t\tInvokeErrorTypes.INVALID_TOOL_ARGS,\n\t\t\t`Unknown action \"${toolName}\". Available: ${available}`\n\t\t)\n\t}\n\n\tlet value = action[toolName]\n\tconst schema = tool.inputSchema\n\n\t// coerce primitive input for single-field tools\n\tif (schema instanceof z.ZodObject && value !== null && typeof value !== 'object') {\n\t\tconst requiredKey = Object.keys(schema.shape).find(\n\t\t\t(k) => !(schema.shape as Record<string, z.ZodType>)[k].safeParse(undefined).success\n\t\t)\n\t\tif (requiredKey) {\n\t\t\tlog(`coercing primitive action input for \"${toolName}\"`)\n\t\t\tvalue = { [requiredKey]: value }\n\t\t}\n\t}\n\n\tconst result = schema.safeParse(value)\n\tif (!result.success) {\n\t\tthrow new InvokeError(\n\t\t\tInvokeErrorTypes.INVALID_TOOL_ARGS,\n\t\t\t`Invalid input for action \"${toolName}\": ${z.prettifyError(result.error)}`\n\t\t)\n\t}\n\n\treturn { [toolName]: result.data }\n}\n\n/**\n * Safely parse JSON, return original input if not json.\n */\nfunction safeJsonParse(input: any): any {\n\tif (typeof input === 'string') {\n\t\ttry {\n\t\t\treturn JSON.parse(input.trim())\n\t\t} catch {\n\t\t\treturn input\n\t\t}\n\t}\n\treturn input\n}\n\n/**\n * Extract and parse JSON from a string.\n * - Treat content between the first `{` and the last `}` as JSON.\n * - Try to parse that content as JSON and return the parsed value (object/array/primitive) if successful, otherwise return null.\n */\nfunction retrieveJsonFromString(str: string): any {\n\ttry {\n\t\tconst json = /({[\\s\\S]*})/.exec(str) ?? []\n\t\tif (json.length === 0) {\n\t\t\treturn null\n\t\t}\n\t\treturn JSON.parse(json[0]!)\n\t} catch {\n\t\treturn null\n\t}\n}\n\ninterface Choice {\n\tmessage?: {\n\t\trole?: 'assistant'\n\t\tcontent?: string\n\t\ttool_calls?: {\n\t\t\tid?: string\n\t\t\ttype?: 'function'\n\t\t\tfunction?: {\n\t\t\t\tname?: string\n\t\t\t\targuments?: string\n\t\t\t}\n\t\t}[]\n\t}\n\tindex?: 0\n\tfinish_reason?: 'tool_calls'\n}\n","import chalk from 'chalk'\n\nexport * from './autoFixer'\n\n/**\n * Wait for `seconds`. If a `signal` is provided, the wait is cancellable:\n * aborting rejects with the signal's reason (an `AbortError`).\n */\nexport async function waitFor(seconds: number, signal?: AbortSignal): Promise<void> {\n\tif (!signal) {\n\t\tawait new Promise((resolve) => setTimeout(resolve, seconds * 1000))\n\t\treturn\n\t}\n\tsignal.throwIfAborted()\n\tawait new Promise<void>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\tresolve()\n\t\t}, seconds * 1000)\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timer)\n\t\t\t// reason is a DOMException AbortError.\n\t\t\treject(signal.reason as DOMException)\n\t\t}\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t})\n}\n\n//\n\nexport function truncate(text: string, maxLength: number): string {\n\tif (text.length > maxLength) {\n\t\treturn text.substring(0, maxLength) + '...'\n\t}\n\treturn text\n}\n\n//\n\nexport function randomID(existingIDs?: string[]): string {\n\tlet id = Math.random().toString(36).substring(2, 11)\n\n\tif (!existingIDs) {\n\t\treturn id\n\t}\n\n\tconst MAX_TRY = 1000\n\tlet tryCount = 0\n\n\twhile (existingIDs.includes(id)) {\n\t\tid = Math.random().toString(36).substring(2, 11)\n\t\ttryCount++\n\t\tif (tryCount > MAX_TRY) {\n\t\t\tthrow new Error('randomID: too many tries')\n\t\t}\n\t}\n\n\treturn id\n}\n\n//\nconst _global = globalThis as any\n\nif (!_global.__PAGE_AGENT_IDS__) {\n\t_global.__PAGE_AGENT_IDS__ = []\n}\n\nconst ids = _global.__PAGE_AGENT_IDS__\n\n/**\n * Generate a random ID.\n * @note Unique within this window.\n */\nexport function uid() {\n\tconst id = randomID(ids)\n\tids.push(id)\n\treturn id\n}\n\nconst llmsTxtCache = new Map<string, string | null>()\n\n/** Fetch /llms.txt for a URL's origin. Cached per origin, `null` = tried and not found. */\nexport async function fetchLlmsTxt(url: string): Promise<string | null> {\n\tlet origin: string\n\ttry {\n\t\torigin = new URL(url).origin\n\t} catch {\n\t\treturn null // Invalid URL\n\t}\n\t// about:blank, data:, file:\n\tif (origin === 'null') return null\n\n\tif (llmsTxtCache.has(origin)) return llmsTxtCache.get(origin)!\n\n\tconst endpoint = `${origin}/llms.txt`\n\tlet result: string | null = null\n\ttry {\n\t\tconsole.log(chalk.gray(`[llms.txt] Fetching ${endpoint}`))\n\t\tconst res = await fetch(endpoint, { signal: AbortSignal.timeout(3000) })\n\t\tif (res.ok) {\n\t\t\tresult = await res.text()\n\t\t\tconsole.log(chalk.green(`[llms.txt] Found (${result.length} chars)`))\n\t\t\tif (result.length > 1000) {\n\t\t\t\tconsole.log(chalk.yellow(`[llms.txt] Truncating to 1000 chars`))\n\t\t\t\tresult = truncate(result, 1000)\n\t\t\t}\n\t\t} else {\n\t\t\tconsole.debug(chalk.gray(`[llms.txt] ${res.status} for ${endpoint}`))\n\t\t}\n\t} catch (e) {\n\t\tconsole.debug(chalk.gray(`[llms.txt] not found for ${endpoint}`), e)\n\t}\n\tllmsTxtCache.set(origin, result)\n\treturn result\n}\n\n/**\n * Simple assertion function that throws an error if the condition is falsy\n * @param condition - The condition to assert\n * @param message - Optional error message\n * @throws Error if condition is falsy\n */\nexport function assert(condition: unknown, message?: string, silent?: boolean): asserts condition {\n\tif (!condition) {\n\t\tconst errorMessage = message ?? 'Assertion failed'\n\n\t\tif (!silent) console.error(chalk.red(`❌ assert: ${errorMessage}`))\n\n\t\tthrow new Error(errorMessage)\n\t}\n}\n\n/**\n * Suppress errors from a function.\n */\nexport async function suppress<T>(fn: () => T | Promise<T>): Promise<Awaited<T> | undefined> {\n\ttry {\n\t\treturn await fn()\n\t} catch (error) {\n\t\tconsole.error(error)\n\t\treturn undefined\n\t}\n}\n","/**\n * Internal tools for PageAgent.\n * @note Adapted from browser-use\n */\nimport * as z from 'zod/v4'\n\nimport type { PageAgentCore } from '../PageAgentCore'\nimport { waitFor } from '../utils'\n\n/**\n * Per-invocation context passed to every tool execution.\n * Tools MUST honor `signal` to support cooperative cancellation.\n */\nexport interface ToolContext {\n\tsignal: AbortSignal\n}\n\n/**\n * Internal tool definition that has access to PageAgent `this` context\n */\nexport interface PageAgentTool<TParams = any> {\n\t// name: string\n\tdescription: string\n\tinputSchema: z.ZodType<TParams>\n\texecute: (this: PageAgentCore, args: TParams, ctx: ToolContext) => Promise<string>\n}\n\nexport function tool<TParams>(options: PageAgentTool<TParams>): PageAgentTool<TParams> {\n\treturn options\n}\n\n/**\n * Internal tools for PageAgent.\n * Note: Using any to allow different parameter types for each tool\n */\nexport const tools = new Map<string, PageAgentTool>()\n\ntools.set(\n\t'done',\n\ttool({\n\t\tdescription:\n\t\t\t'Complete task. Text is your final response to the user — keep it concise unless the user explicitly asks for detail.',\n\t\tinputSchema: z.object({\n\t\t\ttext: z.string(),\n\t\t\tsuccess: z.boolean().default(true),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\t// @note main loop will handle this one\n\t\t\treturn Promise.resolve('Task completed')\n\t\t},\n\t})\n)\n\ntools.set(\n\t'wait',\n\ttool({\n\t\tdescription: 'Wait for x seconds. Can be used to wait until the page or data is fully loaded.',\n\t\tinputSchema: z.object({\n\t\t\tseconds: z.number().min(1).max(10).default(1),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input, { signal }) {\n\t\t\t// try to subtract LLM calling time from the actual wait time\n\t\t\tconst lastTimeUpdate = await this.pageController.getLastUpdateTime()\n\t\t\tconst secondsSinceLastUpdate = (Date.now() - lastTimeUpdate) / 1000\n\t\t\tconst actualWaitTime = Math.max(0, input.seconds - secondsSinceLastUpdate)\n\t\t\tconsole.log(`actualWaitTime: ${actualWaitTime} seconds`)\n\t\t\tawait waitFor(actualWaitTime, signal)\n\n\t\t\tconst waitedSeconds = (secondsSinceLastUpdate + actualWaitTime).toFixed(2)\n\t\t\treturn `✅ Waited for ${waitedSeconds} seconds.`\n\t\t},\n\t})\n)\n\ntools.set(\n\t'get_context',\n\ttool({\n\t\tdescription:\n\t\t\t'Read a vertical slice of the page accessibility tree by document Y (page coordinates in CSS pixels). Use when browser_state is too large or you need only one band. y_min/y_max are inclusive overlap bounds; omit both to read the current viewport band. query filters role/name/description. bind_indexes=true (default) replaces action indexes with this slice for the next actions; set false for a read-only skim.',\n\t\tinputSchema: z.object({\n\t\t\ty_min: z.number().min(0).optional(),\n\t\t\ty_max: z.number().min(0).optional(),\n\t\t\tmax_lines: z.number().int().min(10).max(200).default(80),\n\t\t\tquery: z.string().optional(),\n\t\t\tbind_indexes: z.boolean().default(true),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.getContext({\n\t\t\t\tyMin: input.y_min,\n\t\t\t\tyMax: input.y_max,\n\t\t\t\tmaxLines: input.max_lines,\n\t\t\t\tquery: input.query,\n\t\t\t\tbindIndexes: input.bind_indexes,\n\t\t\t})\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'ask_user',\n\ttool({\n\t\tdescription:\n\t\t\t'Ask the user a question and wait for their answer. Use kind=text for free text, kind=choice for one option, kind=multi for several options. For choice/multi, pass 2+ distinct choices. Prefer choice/multi when the answer is a closed set.',\n\t\tinputSchema: z.object({\n\t\t\tquestion: z.string(),\n\t\t\tkind: z.enum(['text', 'choice', 'multi']).default('text'),\n\t\t\tchoices: z.array(z.string()).max(12).optional(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input, { signal }) {\n\t\t\tif (!this.onAskUser) {\n\t\t\t\tthrow new Error('ask_user tool requires onAskUser callback to be set')\n\t\t\t}\n\t\t\tconst answer = await this.onAskUser(input.question, {\n\t\t\t\tsignal,\n\t\t\t\tkind: input.kind,\n\t\t\t\tchoices: input.choices,\n\t\t\t})\n\t\t\treturn `User answered: ${answer}`\n\t\t},\n\t})\n)\n\ntools.set(\n\t'click_element_by_index',\n\ttool({\n\t\tdescription: 'Click element by index',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.clickElement(input.index)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'input_text',\n\ttool({\n\t\tdescription: 'Click and type text into an interactive input element',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t\ttext: z.string(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.inputText(input.index, input.text)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'select_dropdown_option',\n\ttool({\n\t\tdescription:\n\t\t\t'Select dropdown option for interactive element index by the text of the option you want to select',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t\ttext: z.string(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.selectOption(input.index, input.text)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\n/**\n * @note Reference from browser-use\n */\ntools.set(\n\t'scroll',\n\ttool({\n\t\tdescription:\n\t\t\t'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. num_pages must be between 0 and 10.',\n\t\tinputSchema: z.object({\n\t\t\tdown: z.boolean().default(true),\n\t\t\tnum_pages: z.number().min(0).max(10).optional().default(0.1),\n\t\t\tpixels: z.number().int().min(0).optional(),\n\t\t\tindex: z.number().int().min(0).optional(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.scroll({\n\t\t\t\t...input,\n\t\t\t\tnumPages: input.num_pages,\n\t\t\t})\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\n/**\n * @todo Tables need a dedicated parser to extract structured data. This tool is useless.\n */\ntools.set(\n\t'scroll_horizontally',\n\ttool({\n\t\tdescription:\n\t\t\t'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.',\n\t\tinputSchema: z.object({\n\t\t\tright: z.boolean().default(true),\n\t\t\tpixels: z.number().int().min(0),\n\t\t\tindex: z.number().int().min(0).optional(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.scrollHorizontally(input)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'drag_element',\n\ttool({\n\t\tdescription:\n\t\t\t'Drag the element at source_index onto the element at target_index. Both indexes belong to this step. ' +\n\t\t\t'Synthetic events only: isTrusted is false. mode html5 sends DragEvents and drops only if the destination cancels dragover. ' +\n\t\t\t'pointer and pointer-paced send pointer and mouse events. A dispatched drag is not proof the page accepted it: check the next read. ' +\n\t\t\t'If html5 comes back not applied, the next step may call drag_element once with mode pointer-paced. Do not call both in the same step. Neither result proves the effect. ' +\n\t\t\t'Event sent, effect not verified, change not persisted. Do not simulate this drag with execute_javascript.',\n\t\tinputSchema: z.object({\n\t\t\tsource_index: z.int().min(0),\n\t\t\ttarget_index: z.int().min(0),\n\t\t\tmode: z.enum(['html5', 'pointer', 'pointer-paced']).default('html5'),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.dragElement(\n\t\t\t\tinput.source_index,\n\t\t\t\tinput.target_index,\n\t\t\t\tinput.mode\n\t\t\t)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'hover_element',\n\ttool({\n\t\tdescription:\n\t\t\t'Hover the element at index. The index belongs to this step. ' +\n\t\t\t'Synthetic pointer and mouse events only: isTrusted is false, CSS :hover is not activated, and the real pointer does not move. ' +\n\t\t\t'A script that listens may still react. Event sent, effect not verified, change not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.hoverElement(input.index)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'press_key',\n\ttool({\n\t\tdescription:\n\t\t\t'Press one key on the element at index. The index belongs to this step. ' +\n\t\t\t'Synthetic keydown and keyup only: the native default does not run, so no character is typed, Tab does not move focus and Enter does not activate the control. ' +\n\t\t\t'Event sent, effect not verified, change not persisted. One key per step.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t\tkey: z.string().min(1),\n\t\t\tcode: z.string().min(1).optional(),\n\t\t\tctrl_key: z.boolean().optional(),\n\t\t\talt_key: z.boolean().optional(),\n\t\t\tshift_key: z.boolean().optional(),\n\t\t\tmeta_key: z.boolean().optional(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.pressKey(input.index, input.key, {\n\t\t\t\tcode: input.code,\n\t\t\t\tctrlKey: input.ctrl_key,\n\t\t\t\taltKey: input.alt_key,\n\t\t\t\tshiftKey: input.shift_key,\n\t\t\t\tmetaKey: input.meta_key,\n\t\t\t})\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'double_click_element',\n\ttool({\n\t\tdescription:\n\t\t\t'Double-click the element at index. The index belongs to this step. ' +\n\t\t\t'Synthetic pointer, mouse, click and dblclick events only: isTrusted is false, and text is not selected the way a physical double click selects it. ' +\n\t\t\t'Event sent, effect not verified, change not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.doubleClickElement(input.index)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'focus_element',\n\ttool({\n\t\tdescription:\n\t\t\t'Focus the element at index. The index belongs to this step. ' +\n\t\t\t'Calls focus(). The message says whether that element was focused right after. ' +\n\t\t\t'Focus is not a saved change. Not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.focusElement(input.index)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'set_checked',\n\ttool({\n\t\tdescription:\n\t\t\t'Set a native checkbox or radio at index. checked true selects it. A radio cannot be cleared. ' +\n\t\t\t'The index belongs to this step. Right after the action the message says whether the control held that state. ' +\n\t\t\t'It does not show that a form was submitted or saved. Not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t\tchecked: z.boolean().default(true),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.setChecked(input.index, input.checked)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'set_range',\n\ttool({\n\t\tdescription:\n\t\t\t'Set a native range input at index to value. A value the browser would clamp or round is refused. ' +\n\t\t\t'The index belongs to this step. Right after the action the message says whether the control held that value. ' +\n\t\t\t'It does not show that the page saved it. Not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t\tvalue: z.number(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.setRange(input.index, input.value)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'scroll_into_view',\n\ttool({\n\t\tdescription:\n\t\t\t'Call scrollIntoView on the element at index. The index belongs to this step. ' +\n\t\t\t'The message gives the window scroll before and after. Nested scrollers are not measured. Not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.scrollIntoView(input.index)\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'wheel',\n\ttool({\n\t\tdescription:\n\t\t\t'Send one synthetic wheel event. It does not scroll: use scroll to move the page. ' +\n\t\t\t'delta_x and delta_y are the WheelEvent deltas in CSS pixels. ' +\n\t\t\t'With index, that element receives the event. Without index, the page receives it. ' +\n\t\t\t'The index belongs to this step. Event sent, effect not verified, change not persisted.',\n\t\tinputSchema: z.object({\n\t\t\tindex: z.int().min(0).optional(),\n\t\t\tdelta_x: z.number().default(0),\n\t\t\tdelta_y: z.number().default(0),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input) {\n\t\t\tconst result = await this.pageController.wheel({\n\t\t\t\tindex: input.index,\n\t\t\t\tx: input.delta_x,\n\t\t\t\ty: input.delta_y,\n\t\t\t})\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\ntools.set(\n\t'execute_javascript',\n\ttool({\n\t\tdescription:\n\t\t\t'Execute JavaScript code on the current page. Supports async/await syntax. Use with caution! ' +\n\t\t\t'An `AbortSignal` named `signal` is available in scope: long-running async code MUST honor it ' +\n\t\t\t'(e.g. `await fetch(url, { signal })`, or `signal.throwIfAborted()` in loops). ' +\n\t\t\t'The variable `agent` is the page-agent instance (`agent.pageController`, `agent.tools`). ' +\n\t\t\t// REVERSIBLE (2026-11-17, executor reliability): the next sentence. A bare expression returns undefined.\n\t\t\t'Use `return` to send a value back: a bare expression gives undefined. ' +\n\t\t\t'Do not use this to drag one element onto another: use drag_element. ' +\n\t\t\t'If the result starts with blocked_by_csp, user_denied or unavailable, do not call this tool again on this page.',\n\t\tinputSchema: z.object({\n\t\t\tscript: z.string(),\n\t\t}),\n\t\texecute: async function (this: PageAgentCore, input, { signal }) {\n\t\t\tconst result = await this.pageController.executeJavascript(input.script, signal, {\n\t\t\t\tagent: this,\n\t\t\t})\n\t\t\tsignal.throwIfAborted()\n\t\t\t// Same prefixes as scriptAccessClosed. A CSP block or a refused grant cannot be\n\t\t\t// fixed by another script, so the tool leaves this agent's schema.\n\t\t\tif (/^(blocked_by_csp|user_denied|unavailable):/.test(result.message)) {\n\t\t\t\tthis.tools.delete('execute_javascript')\n\t\t\t}\n\t\t\treturn result.message\n\t\t},\n\t})\n)\n\n// @todo send_keys\n// @todo upload_file\n// @todo extract_structured_data\n","/**\n * Page Agent skills — shared types for the skill document protocol.\n * @see docs/skills.md\n */\n\n/** Where a skill came from. */\nexport type SkillScope = 'remote' | 'agent'\n\n/** Scalar types allowed in command `input` maps. */\nexport type SkillInputType = 'string' | 'number' | 'boolean'\n\nexport interface SkillInputField {\n\ttype: SkillInputType\n\tdescription?: string\n\tdefault?: string | number | boolean\n}\n\n/**\n * One command exported from a `skill-js` block.\n * `run` receives the sandboxed ctx (typed loosely here; runtime narrows it).\n */\nexport interface SkillCommandDefinition {\n\tdescription: string\n\tinput?: Record<string, SkillInputField>\n\trun: (ctx: unknown, input: Record<string, unknown>) => Promise<unknown>\n}\n\n/** Parsed, validated skill ready for the host to register. */\nexport interface SkillManifest {\n\tid: string\n\tname: string\n\tdescription: string\n\tversion: number\n\tscope: SkillScope\n\ttriggers: string[]\n\t/** Markdown body without frontmatter / skill-js fence. */\n\tbody: string\n\t/** Raw `skill-js` source (for re-save / edit). */\n\tmoduleSource: string\n\tcommands: Record<string, SkillCommandDefinition>\n}\n\n/** Catalog entry before the full document is loaded. */\nexport type SkillCatalogRef =\n\t| { id: string; inline: string }\n\t| { id: string; url: string; etag?: string }\n\t| { id: string; name: string; description: string; url: string; etag?: string }\n\n/**\n * Optional remote catalog / publish backend (installer, Studio sync).\n * Local agent storage remains the source of truth until `put` succeeds.\n */\nexport interface SkillsRemoteAdapter {\n\tlist(): Promise<\n\t\t{ id: string; name: string; description: string; version: number; etag?: string }[]\n\t>\n\tget(id: string): Promise<{ document: string; version: number; etag?: string }>\n\tput(input: {\n\t\tdocument: string\n\t\texpectedVersion?: number\n\t}): Promise<{ id: string; version: number; etag?: string }>\n\tremove?(id: string): Promise<void>\n}\n\n/** Default TTL for `SkillsRemoteAdapter.list` cache (5 minutes). */\nexport const DEFAULT_REMOTE_CACHE_TTL_MS = 5 * 60_000\n\n/** Public agent config for skills. */\nexport interface SkillsConfig {\n\tenabled?: boolean\n\tcatalog?: SkillCatalogRef[]\n\tallowedOrigins?: string[]\n\t/** @default 3 */\n\tmaxLoaded?: number\n\t/** @default true */\n\tpersistAgentSkills?: boolean\n\t/** Optional remote list/get/put adapter (Skills Studio / installer). */\n\tremote?: SkillsRemoteAdapter\n\t/** Cache TTL for `remote.list` in ms. @default 300000 */\n\tremoteCacheTtlMs?: number\n}\n\n/** Result of SkillHost.publishDocument (local save, then optional remote.put). */\nexport interface PublishDocumentResult {\n\tid: string\n\tversion: number\n\tdocument: string\n\t/** True when remote.put completed successfully. */\n\tremote?: boolean\n\tetag?: string\n\t/** Set when local save succeeded but remote.put failed; local copy is kept. */\n\tremoteError?: string\n}\n\n/** Thrown when SkillsRemoteAdapter.get/list/put fails for reasons other than local persist. */\nexport class SkillRemoteError extends Error {\n\treadonly code: string\n\treadonly id?: string\n\n\tconstructor(code: string, message: string, id?: string) {\n\t\tsuper(message)\n\t\tthis.name = 'SkillRemoteError'\n\t\tthis.code = code\n\t\tthis.id = id\n\t}\n}\n\n/** Compact row returned by `list_skills`. */\nexport interface SkillListEntry {\n\tid: string\n\tname: string\n\tdescription: string\n\tscope: SkillScope\n\tloaded: boolean\n\tcommands: { name: string; description: string }[]\n}\n\nexport class SkillParseError extends Error {\n\treadonly code: string\n\n\tconstructor(code: string, message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'SkillParseError'\n\t\tthis.code = code\n\t}\n}\n\n/** Stable MacroTool name for a loaded command. */\nexport function skillToolName(skillId: string, commandName: string): string {\n\treturn `skill__${skillId}__${commandName}`\n}\n\nexport const SKILL_ID_PATTERN = /^[a-z][a-z0-9-]*$/\nexport const SKILL_COMMAND_PATTERN = /^[a-z][a-z0-9_]*$/\nexport const SKILL_STORAGE_KEY = 'page-agent-skills-v1'\nexport const SKILL_JS_FENCE = 'skill-js'\n\n/** Per-command wall clock for skill__* runs (composed with the task AbortSignal). */\nexport const SKILL_COMMAND_TIMEOUT_MS = 30_000\n/** Soft cap for one skill markdown document (remote fetch or agent save/edit). */\nexport const MAX_SKILL_DOCUMENT_BYTES = 256_000\n/** Max agent-authored skills persisted in browser storage. */\nexport const MAX_AGENT_SKILLS = 32\n/** Max concurrent SkillWatcher arms. */\nexport const MAX_SKILL_WATCHES = 3\n/** Default poll interval for interval watches. */\nexport const DEFAULT_SKILL_WATCH_INTERVAL_MS = 15_000\n/** Floor for watch intervals (avoid hot loops). */\nexport const MIN_SKILL_WATCH_INTERVAL_MS = 5_000\n\n/** How a SkillWatcher is scheduled. */\nexport type SkillWatchTrigger = 'interval' | 'on-enter' | 'on-url'\n\n/**\n * Spec to arm a background watch (same tab; no second ReAct execute).\n * Prefer observe/assert-only skill commands for ticks.\n */\nexport interface SkillWatchSpec {\n\tid: string\n\tskillId: string\n\tcommand: string\n\tinput?: Record<string, unknown>\n\t/** @default DEFAULT_SKILL_WATCH_INTERVAL_MS for trigger interval */\n\teveryMs?: number\n\t/** @default 'interval' */\n\ttrigger?: SkillWatchTrigger\n\t/** When trigger is on-url, fire check when location href includes this. */\n\turlIncludes?: string\n\t/** @default true — skip ticks while PageAgentCore status is running */\n\tpauseWhileTaskRunning?: boolean\n\t/** @default true — disarm after the first successful fire */\n\tonce?: boolean\n}\n\n/** Public row returned by listWatches. */\nexport interface SkillWatchEntry {\n\tid: string\n\tskillId: string\n\tcommand: string\n\ttrigger: SkillWatchTrigger\n\teveryMs: number\n\tarmed: boolean\n\tlastFiredAt?: number\n\tlastError?: string\n}\n","/**\n * Parse Page Agent skill documents (frontmatter + markdown + skill-js).\n * @see docs/skills.md\n *\n * Callers: parse.test.ts; later SkillHost / list_skills / load_skill.\n * API: parseSkillDocument(source) → SkillManifest\n */\nimport {\n\tSKILL_COMMAND_PATTERN,\n\tSKILL_ID_PATTERN,\n\tSKILL_JS_FENCE,\n\ttype SkillCommandDefinition,\n\ttype SkillInputField,\n\ttype SkillInputType,\n\ttype SkillManifest,\n\tSkillParseError,\n\ttype SkillScope,\n} from './types'\n\nconst INPUT_TYPES = new Set<SkillInputType>(['string', 'number', 'boolean'])\n\ninterface Frontmatter {\n\tname?: string\n\tdescription?: string\n\tversion?: number\n\tid?: string\n\tscope?: string\n\ttriggers?: string[]\n}\n\n/** Split `---` frontmatter from the markdown body. */\nexport function splitFrontmatter(source: string): { raw: string; body: string } {\n\tconst text = source.replace(/^\\uFEFF/, '')\n\tif (!text.startsWith('---')) {\n\t\tthrow new SkillParseError(\n\t\t\t'missing_frontmatter',\n\t\t\t'Skill document must start with YAML frontmatter (---)'\n\t\t)\n\t}\n\tconst end = text.indexOf('\\n---', 3)\n\tif (end === -1) {\n\t\tthrow new SkillParseError('unclosed_frontmatter', 'Frontmatter has no closing --- line')\n\t}\n\tconst raw = text.slice(3, end).replace(/^\\r?\\n/, '')\n\tconst body = text.slice(end + 4).replace(/^\\r?\\n/, '')\n\treturn { raw, body }\n}\n\n/**\n * Minimal YAML subset for skill frontmatter: scalars, folded `>`, `[a, b]` lists.\n * Not a general YAML parser.\n */\nexport function parseFrontmatterYaml(raw: string): Frontmatter {\n\tconst result: Frontmatter = {}\n\tconst lines = raw.split(/\\r?\\n/)\n\tlet i = 0\n\twhile (i < lines.length) {\n\t\tconst line = lines[i]\n\t\ti++\n\t\tif (!line.trim() || line.trimStart().startsWith('#')) continue\n\t\tconst match = /^([A-Za-z][A-Za-z0-9_]*)\\s*:\\s*(.*)$/.exec(line)\n\t\tif (!match) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'invalid_frontmatter_line',\n\t\t\t\t`Cannot parse frontmatter line: ${line}`\n\t\t\t)\n\t\t}\n\t\tconst key = match[1]\n\t\tlet value = match[2].trim()\n\t\tif (value === '>' || value === '|') {\n\t\t\tconst folded: string[] = []\n\t\t\twhile (i < lines.length) {\n\t\t\t\tconst next = lines[i]\n\t\t\t\tif (/^[A-Za-z][A-Za-z0-9_]*\\s*:/.test(next)) break\n\t\t\t\ti++\n\t\t\t\tfolded.push(next.replace(/^\\s{2}/, ''))\n\t\t\t}\n\t\t\tvalue = folded.join(value === '>' ? ' ' : '\\n').trim()\n\t\t}\n\t\t;(result as Record<string, unknown>)[key] = coerceYamlValue(value)\n\t}\n\treturn result\n}\n\nfunction coerceYamlValue(value: string): unknown {\n\tif (value === '') return ''\n\tif (\n\t\t(value.startsWith('\"') && value.endsWith('\"')) ||\n\t\t(value.startsWith(\"'\") && value.endsWith(\"'\"))\n\t) {\n\t\treturn value.slice(1, -1)\n\t}\n\tif (value.startsWith('[') && value.endsWith(']')) {\n\t\tconst inner = value.slice(1, -1).trim()\n\t\tif (!inner) return []\n\t\treturn inner.split(',').map((part) => {\n\t\t\tconst item = part.trim()\n\t\t\tif (\n\t\t\t\t(item.startsWith('\"') && item.endsWith('\"')) ||\n\t\t\t\t(item.startsWith(\"'\") && item.endsWith(\"'\"))\n\t\t\t) {\n\t\t\t\treturn item.slice(1, -1)\n\t\t\t}\n\t\t\treturn item\n\t\t})\n\t}\n\tif (/^-?\\d+$/.test(value)) return Number(value)\n\tif (value === 'true') return true\n\tif (value === 'false') return false\n\treturn value\n}\n\n/** Extract the single ```skill-js fence; returns source and body without that fence. */\nexport function extractSkillJs(body: string): { moduleSource: string; docs: string } {\n\tconst fence = new RegExp('```' + SKILL_JS_FENCE + '\\\\s*\\\\r?\\\\n([\\\\s\\\\S]*?)\\\\r?\\\\n```', 'gm')\n\tconst matches = [...body.matchAll(fence)]\n\tif (matches.length === 0) {\n\t\tthrow new SkillParseError(\n\t\t\t'missing_skill_js',\n\t\t\t`Skill must contain one \\`\\`\\`${SKILL_JS_FENCE} code block with commands`\n\t\t)\n\t}\n\tif (matches.length > 1) {\n\t\tthrow new SkillParseError(\n\t\t\t'multiple_skill_js',\n\t\t\t`Skill must contain exactly one \\`\\`\\`${SKILL_JS_FENCE} block`\n\t\t)\n\t}\n\tconst moduleSource = matches[0][1].trim()\n\tconst docs = body.replace(matches[0][0], '').trim()\n\treturn { moduleSource, docs }\n}\n\n/** Names shadowed inside skill-js so free lookups do not reach the real page/globals. */\nconst SKILL_JS_DENIED_PARAMS = [\n\t'document',\n\t'window',\n\t'self',\n\t'frames',\n\t'parent',\n\t'top',\n\t'fetch',\n\t'XMLHttpRequest',\n\t'WebSocket',\n\t'eval',\n\t'Function',\n\t'globalThis',\n\t'global',\n] as const\n\n/**\n * Evaluate the skill-js module and return its `commands` object.\n * Uses `new Function` with denied globals shadowed as parameters (undefined / empty realm).\n * May throw SkillParseError `skill_blocked_by_csp`.\n */\nexport function evaluateSkillCommands(\n\tmoduleSource: string\n): Record<string, SkillCommandDefinition> {\n\tlet factory: (...denied: unknown[]) => unknown\n\ttry {\n\t\t// Strip a leading `export` so the body works inside a function.\n\t\tconst body = moduleSource.replace(/^\\s*export\\s+/m, '')\n\t\tconst sandboxGlobal = Object.freeze(Object.create(null))\n\n\t\t// No \"use strict\": binding the name `eval` as a parameter is a SyntaxError in strict mode,\n\t\t// and we need that parameter to shadow the real eval for skill-js.\n\t\t// eslint-disable-next-line @typescript-eslint/no-implied-eval -- intentional skill-js sandbox factory\n\t\tfactory = new Function(\n\t\t\t...SKILL_JS_DENIED_PARAMS,\n\t\t\t`${body}\\n; return typeof commands !== \"undefined\" ? commands : undefined;`\n\t\t) as (...denied: unknown[]) => unknown\n\t\t// Bind sandbox args once. `this` must be sandboxGlobal: in non-strict mode,\n\t\t// `bind(undefined)` would coerce `this` to the real global, so `this.fetch` escapes.\n\t\tconst deniedArgs: unknown[] = SKILL_JS_DENIED_PARAMS.map((name) =>\n\t\t\tname === 'globalThis' ? sandboxGlobal : undefined\n\t\t)\n\t\tfactory = factory.bind(sandboxGlobal, ...deniedArgs)\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\tif (/unsafe-eval|Content Security Policy|Refused to evaluate/i.test(message)) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'skill_blocked_by_csp',\n\t\t\t\t'blocked_by_csp: This page blocks evaluating skill modules (unsafe-eval).'\n\t\t\t)\n\t\t}\n\t\tthrow new SkillParseError('skill_js_syntax', `skill-js syntax error: ${message}`)\n\t}\n\n\tlet commands: unknown\n\ttry {\n\t\tcommands = factory()\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\tthrow new SkillParseError(\n\t\t\t'skill_js_runtime',\n\t\t\t`skill-js failed while loading commands: ${message}`\n\t\t)\n\t}\n\n\tif (!commands || typeof commands !== 'object' || Array.isArray(commands)) {\n\t\tthrow new SkillParseError(\n\t\t\t'missing_commands',\n\t\t\t'skill-js must define a `commands` object (e.g. `export const commands = { ... }`)'\n\t\t)\n\t}\n\treturn validateCommands(commands as Record<string, unknown>)\n}\n\nfunction validateCommands(raw: Record<string, unknown>): Record<string, SkillCommandDefinition> {\n\tconst names = Object.keys(raw)\n\tif (names.length === 0) {\n\t\tthrow new SkillParseError('empty_commands', 'commands object must include at least one command')\n\t}\n\tconst out: Record<string, SkillCommandDefinition> = {}\n\tfor (const name of names) {\n\t\tif (!SKILL_COMMAND_PATTERN.test(name)) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'invalid_command_name',\n\t\t\t\t`Command name \"${name}\" must match ${SKILL_COMMAND_PATTERN}`\n\t\t\t)\n\t\t}\n\t\tconst entry = raw[name]\n\t\tif (!entry || typeof entry !== 'object' || Array.isArray(entry)) {\n\t\t\tthrow new SkillParseError('invalid_command', `Command \"${name}\" must be an object`)\n\t\t}\n\t\tconst command = entry as Record<string, unknown>\n\t\tif (typeof command.description !== 'string' || !command.description.trim()) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'invalid_command',\n\t\t\t\t`Command \"${name}\" needs a non-empty description`\n\t\t\t)\n\t\t}\n\t\tif (typeof command.run !== 'function') {\n\t\t\tthrow new SkillParseError('invalid_command', `Command \"${name}\" needs a run() function`)\n\t\t}\n\t\tout[name] = {\n\t\t\tdescription: command.description.trim(),\n\t\t\tinput: command.input ? validateInputMap(name, command.input) : undefined,\n\t\t\trun: command.run as SkillCommandDefinition['run'],\n\t\t}\n\t}\n\treturn out\n}\n\nfunction validateInputMap(commandName: string, raw: unknown): Record<string, SkillInputField> {\n\tif (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n\t\tthrow new SkillParseError('invalid_input', `Command \"${commandName}\" input must be an object`)\n\t}\n\tconst out: Record<string, SkillInputField> = {}\n\tfor (const [field, spec] of Object.entries(raw as Record<string, unknown>)) {\n\t\tif (!spec || typeof spec !== 'object' || Array.isArray(spec)) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'invalid_input',\n\t\t\t\t`Command \"${commandName}\" field \"${field}\" must be an object`\n\t\t\t)\n\t\t}\n\t\tconst fieldSpec = spec as Record<string, unknown>\n\t\tconst type = fieldSpec.type\n\t\tif (typeof type !== 'string' || !INPUT_TYPES.has(type as SkillInputType)) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'invalid_input',\n\t\t\t\t`Command \"${commandName}\" field \"${field}\" type must be string|number|boolean`\n\t\t\t)\n\t\t}\n\t\tout[field] = {\n\t\t\ttype: type as SkillInputType,\n\t\t\tdescription: typeof fieldSpec.description === 'string' ? fieldSpec.description : undefined,\n\t\t\tdefault: fieldSpec.default as SkillInputField['default'],\n\t\t}\n\t}\n\treturn out\n}\n\nfunction validateMeta(fm: Frontmatter): {\n\tid: string\n\tname: string\n\tdescription: string\n\tversion: number\n\tscope: SkillScope\n\ttriggers: string[]\n} {\n\tif (typeof fm.name !== 'string' || !SKILL_ID_PATTERN.test(fm.name)) {\n\t\tthrow new SkillParseError('invalid_name', `name is required and must match ${SKILL_ID_PATTERN}`)\n\t}\n\tif (typeof fm.description !== 'string' || !fm.description.trim()) {\n\t\tthrow new SkillParseError('invalid_description', 'description is required')\n\t}\n\tif (typeof fm.version !== 'number' || !Number.isInteger(fm.version) || fm.version < 1) {\n\t\tthrow new SkillParseError('invalid_version', 'version must be a positive integer')\n\t}\n\tconst id = fm.id ?? fm.name\n\tif (typeof id !== 'string' || !SKILL_ID_PATTERN.test(id)) {\n\t\tthrow new SkillParseError('invalid_id', `id must match ${SKILL_ID_PATTERN}`)\n\t}\n\tconst scope: SkillScope = fm.scope === 'agent' ? 'agent' : 'remote'\n\tif (fm.scope !== undefined && fm.scope !== 'remote' && fm.scope !== 'agent') {\n\t\tthrow new SkillParseError('invalid_scope', 'scope must be \"remote\" or \"agent\"')\n\t}\n\tconst triggers = Array.isArray(fm.triggers)\n\t\t? fm.triggers.filter((t): t is string => typeof t === 'string')\n\t\t: []\n\treturn {\n\t\tid,\n\t\tname: fm.name,\n\t\tdescription: fm.description.trim(),\n\t\tversion: fm.version,\n\t\tscope,\n\t\ttriggers,\n\t}\n}\n\n/** Parse a full skill markdown document into a SkillManifest. */\nexport function parseSkillDocument(source: string): SkillManifest {\n\tif (typeof source !== 'string' || !source.trim()) {\n\t\tthrow new SkillParseError('empty_document', 'Skill document is empty')\n\t}\n\tconst { raw, body } = splitFrontmatter(source)\n\tconst meta = validateMeta(parseFrontmatterYaml(raw))\n\tconst { moduleSource, docs } = extractSkillJs(body)\n\tconst commands = evaluateSkillCommands(moduleSource)\n\treturn {\n\t\t...meta,\n\t\tbody: docs,\n\t\tmoduleSource,\n\t\tcommands,\n\t}\n}\n","/**\n * Sandboxed skill ctx — page/assert/ask/files/memo/ok/fail.\n * Callers: SkillHost when executing skill__* tools.\n * Does not put document, window, fetch, or eval on ctx.\n */\nimport type { PageController } from '@page-agent/page-controller'\n\nimport type { SkillFileStore } from './files'\n\nexport class SkillAssertError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'SkillAssertError'\n\t}\n}\n\nexport class SkillFailError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'SkillFailError'\n\t}\n}\n\nexport interface SkillPageQuery {\n\trole?: string\n\tname?: string | RegExp\n\t/** Escape hatch: index from the current observe only. */\n\tindex?: number\n}\n\nexport interface SkillElementHandle {\n\treadonly __skillHandle: true\n}\n\ninterface InternalHandle extends SkillElementHandle {\n\tgen: number\n\tindex: number\n\tlabel: string\n}\n\nexport interface ObservationLabel {\n\tindex: number\n\trole: string\n\tname: string\n\tlabel: string\n}\n\nexport interface SkillResult {\n\tok: boolean\n\tmessage: string\n}\n\nexport interface SkillContext {\n\tpage: {\n\t\tfind(query: SkillPageQuery): Promise<SkillElementHandle>\n\t\tclick(target: SkillPageQuery | SkillElementHandle): Promise<string>\n\t\tfill(target: SkillPageQuery | SkillElementHandle, text: string): Promise<string>\n\t\tselect(target: SkillPageQuery | SkillElementHandle, optionText: string): Promise<string>\n\t\thover(target: SkillPageQuery | SkillElementHandle): Promise<string>\n\t\tdrag(\n\t\t\tsource: SkillPageQuery | SkillElementHandle,\n\t\t\ttarget: SkillPageQuery | SkillElementHandle,\n\t\t\tmode?: 'html5' | 'pointer' | 'pointer-paced'\n\t\t): Promise<string>\n\t\tscroll(options?: {\n\t\t\tdown?: boolean\n\t\t\tnumPages?: number\n\t\t\tpixels?: number\n\t\t\ttarget?: SkillPageQuery | SkillElementHandle\n\t\t}): Promise<string>\n\t\tpressKey(\n\t\t\ttarget: SkillPageQuery | SkillElementHandle,\n\t\t\tkey: string,\n\t\t\toptions?: {\n\t\t\t\tcode?: string\n\t\t\t\tctrlKey?: boolean\n\t\t\t\taltKey?: boolean\n\t\t\t\tshiftKey?: boolean\n\t\t\t\tmetaKey?: boolean\n\t\t\t}\n\t\t): Promise<string>\n\t\twaitFor(\n\t\t\tquery: SkillPageQuery,\n\t\t\topts?: { timeoutMs?: number; intervalMs?: number }\n\t\t): Promise<SkillElementHandle>\n\t\tobserve(): Promise<{ url: string; title: string; content: string }>\n\t}\n\tassert: {\n\t\turlMatches(pattern: RegExp | string): Promise<void>\n\t\ttextIncludes(text: string): Promise<void>\n\t\texists(query: SkillPageQuery): Promise<void>\n\t}\n\task(question: string): Promise<string>\n\tfiles: {\n\t\tlist(): { id: string; name: string; mimeType: string; size: number }[]\n\t\tread(\n\t\t\tid: string\n\t\t): { id: string; name: string; mimeType: string; size: number; text?: string } | undefined\n\t}\n\tsignal: AbortSignal\n\tok(message: string): SkillResult\n\tfail(message: string): never\n\tmemo: {\n\t\tget(key: string): unknown\n\t\tset(key: string, value: unknown): void\n\t}\n}\n\nexport interface SkillRuntimeDeps {\n\tpageController: PageController\n\tfiles: SkillFileStore\n\tsignal: AbortSignal\n\tmemo: Map<string, unknown>\n\tonAskUser?: import('../askUser').AskUserHandler\n}\n\n/** Parse `[index] role \"name\"` lines from an observation dump. */\nexport function parseObservationLabels(content: string): ObservationLabel[] {\n\tconst out: ObservationLabel[] = []\n\tfor (const line of content.split(/\\r?\\n/)) {\n\t\tconst match = /^\\s*\\[(\\d+)\\]\\s+(\\S+)(?:\\s+\"([^\"]*)\")?/.exec(line)\n\t\tif (!match) continue\n\t\tconst index = Number(match[1])\n\t\tconst role = match[2]\n\t\tconst name = match[3] ?? ''\n\t\tout.push({ index, role, name, label: `${role}${name ? ` \"${name}\"` : ''}` })\n\t}\n\treturn out\n}\n\nfunction nameMatches(actual: string, expected: string | RegExp | undefined): boolean {\n\tif (expected === undefined) return true\n\tif (typeof expected === 'string') {\n\t\treturn actual === expected || actual.toLowerCase() === expected.toLowerCase()\n\t}\n\treturn expected.test(actual)\n}\n\nfunction isHandle(value: unknown): value is InternalHandle {\n\treturn Boolean(value && typeof value === 'object' && (value as SkillElementHandle).__skillHandle)\n}\n\n/**\n * Build a sealed skill ctx bound to the current PageController + task signal.\n * Handles die after the next observe().\n */\nexport function createSkillContext(deps: SkillRuntimeDeps): SkillContext {\n\tconst { pageController, files, signal, memo, onAskUser } = deps\n\tlet generation = 0\n\tlet labels: ObservationLabel[] = []\n\tlet lastContent = ''\n\tlet lastUrl = ''\n\tlet lastTitle = ''\n\n\tasync function refresh(): Promise<void> {\n\t\tsignal.throwIfAborted()\n\t\tconst state = await pageController.getBrowserState()\n\t\tgeneration += 1\n\t\tlastContent = state.content\n\t\tlastUrl = state.url\n\t\tlastTitle = state.title\n\t\tlabels = parseObservationLabels(state.content)\n\t}\n\n\tfunction resolveHandle(handle: InternalHandle): InternalHandle {\n\t\tif (handle.gen !== generation) {\n\t\t\tthrow new SkillAssertError(\n\t\t\t\t'Element handle is stale after observe(). Re-find the control on this read.'\n\t\t\t)\n\t\t}\n\t\treturn handle\n\t}\n\n\tfunction matchLabel(query: SkillPageQuery): ObservationLabel {\n\t\tif (typeof query.index === 'number') {\n\t\t\tconst found = labels.find((row) => row.index === query.index)\n\t\t\tif (!found) throw new SkillAssertError(`No element at index ${query.index} on this read`)\n\t\t\treturn found\n\t\t}\n\t\tif (!query.role) {\n\t\t\tthrow new SkillAssertError('find() requires role or index')\n\t\t}\n\t\tconst role = query.role.toLowerCase()\n\t\tconst found = labels.find(\n\t\t\t(row) => row.role.toLowerCase() === role && nameMatches(row.name, query.name)\n\t\t)\n\t\tif (!found) {\n\t\t\tconst nameHint =\n\t\t\t\tquery.name === undefined\n\t\t\t\t\t? ''\n\t\t\t\t\t: typeof query.name === 'string'\n\t\t\t\t\t\t? ` name=${JSON.stringify(query.name)}`\n\t\t\t\t\t\t: ` name=${query.name}`\n\t\t\tthrow new SkillAssertError(`No element matching role=${query.role}${nameHint} on this read`)\n\t\t}\n\t\treturn found\n\t}\n\n\tfunction toHandle(row: ObservationLabel): InternalHandle {\n\t\treturn {\n\t\t\t__skillHandle: true,\n\t\t\tgen: generation,\n\t\t\tindex: row.index,\n\t\t\tlabel: row.label,\n\t\t}\n\t}\n\n\tasync function ensureObserved(): Promise<void> {\n\t\tif (generation === 0) await refresh()\n\t}\n\n\tasync function resolve(target: SkillPageQuery | SkillElementHandle): Promise<InternalHandle> {\n\t\tawait ensureObserved()\n\t\tif (isHandle(target)) return resolveHandle(target)\n\t\treturn toHandle(matchLabel(target as SkillPageQuery))\n\t}\n\n\tconst page = {\n\t\tasync find(query: SkillPageQuery) {\n\t\t\tawait ensureObserved()\n\t\t\treturn toHandle(matchLabel(query))\n\t\t},\n\t\tasync click(target: SkillPageQuery | SkillElementHandle) {\n\t\t\tconst handle = await resolve(target)\n\t\t\tconst result = await pageController.clickElement(handle.index)\n\t\t\treturn result.message\n\t\t},\n\t\tasync fill(target: SkillPageQuery | SkillElementHandle, text: string) {\n\t\t\tconst handle = await resolve(target)\n\t\t\tconst result = await pageController.inputText(handle.index, text)\n\t\t\treturn result.message\n\t\t},\n\t\tasync select(target: SkillPageQuery | SkillElementHandle, optionText: string) {\n\t\t\tconst handle = await resolve(target)\n\t\t\tconst result = await pageController.selectOption(handle.index, optionText)\n\t\t\treturn result.message\n\t\t},\n\t\tasync hover(target: SkillPageQuery | SkillElementHandle) {\n\t\t\tconst handle = await resolve(target)\n\t\t\tconst result = await pageController.hoverElement(handle.index)\n\t\t\treturn result.message\n\t\t},\n\t\tasync drag(\n\t\t\tsource: SkillPageQuery | SkillElementHandle,\n\t\t\ttarget: SkillPageQuery | SkillElementHandle,\n\t\t\tmode: 'html5' | 'pointer' | 'pointer-paced' = 'html5'\n\t\t) {\n\t\t\tconst from = await resolve(source)\n\t\t\tconst to = await resolve(target)\n\t\t\tconst result = await pageController.dragElement(from.index, to.index, mode)\n\t\t\treturn result.message\n\t\t},\n\t\tasync scroll(\n\t\t\toptions: {\n\t\t\t\tdown?: boolean\n\t\t\t\tnumPages?: number\n\t\t\t\tpixels?: number\n\t\t\t\ttarget?: SkillPageQuery | SkillElementHandle\n\t\t\t} = {}\n\t\t) {\n\t\t\tlet index: number | undefined\n\t\t\tif (options.target) {\n\t\t\t\tindex = (await resolve(options.target)).index\n\t\t\t}\n\t\t\tconst result = await pageController.scroll({\n\t\t\t\tdown: options.down ?? true,\n\t\t\t\tnumPages: options.numPages ?? 0.1,\n\t\t\t\tpixels: options.pixels,\n\t\t\t\t...(index !== undefined ? { index } : {}),\n\t\t\t})\n\t\t\treturn result.message\n\t\t},\n\t\tasync pressKey(\n\t\t\ttarget: SkillPageQuery | SkillElementHandle,\n\t\t\tkey: string,\n\t\t\toptions: {\n\t\t\t\tcode?: string\n\t\t\t\tctrlKey?: boolean\n\t\t\t\taltKey?: boolean\n\t\t\t\tshiftKey?: boolean\n\t\t\t\tmetaKey?: boolean\n\t\t\t} = {}\n\t\t) {\n\t\t\tconst handle = await resolve(target)\n\t\t\tconst result = await pageController.pressKey(handle.index, key, options)\n\t\t\treturn result.message\n\t\t},\n\t\tasync waitFor(query: SkillPageQuery, opts: { timeoutMs?: number; intervalMs?: number } = {}) {\n\t\t\tconst timeoutMs = opts.timeoutMs ?? 5000\n\t\t\tconst intervalMs = opts.intervalMs ?? 100\n\t\t\tconst started = Date.now()\n\t\t\twhile (true) {\n\t\t\t\tsignal.throwIfAborted()\n\t\t\t\tawait refresh()\n\t\t\t\ttry {\n\t\t\t\t\treturn toHandle(matchLabel(query))\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!(error instanceof SkillAssertError)) throw error\n\t\t\t\t\tif (Date.now() - started >= timeoutMs) throw error\n\t\t\t\t\tawait new Promise((r) => setTimeout(r, intervalMs))\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tasync observe() {\n\t\t\tawait refresh()\n\t\t\treturn { url: lastUrl, title: lastTitle, content: lastContent }\n\t\t},\n\t}\n\n\tconst ctx: SkillContext = {\n\t\tpage,\n\t\tassert: {\n\t\t\tasync urlMatches(pattern: RegExp | string) {\n\t\t\t\tawait ensureObserved()\n\t\t\t\tconst re = typeof pattern === 'string' ? new RegExp(pattern) : pattern\n\t\t\t\tif (!re.test(lastUrl)) {\n\t\t\t\t\tthrow new SkillAssertError(`urlMatches failed: ${lastUrl} !~ ${re}`)\n\t\t\t\t}\n\t\t\t},\n\t\t\tasync textIncludes(text: string) {\n\t\t\t\tawait ensureObserved()\n\t\t\t\tif (!lastContent.includes(text)) {\n\t\t\t\t\tthrow new SkillAssertError(`textIncludes failed: missing ${JSON.stringify(text)}`)\n\t\t\t\t}\n\t\t\t},\n\t\t\tasync exists(query: SkillPageQuery) {\n\t\t\t\tawait ensureObserved()\n\t\t\t\tmatchLabel(query)\n\t\t\t},\n\t\t},\n\t\tasync ask(question: string) {\n\t\t\tif (!onAskUser) {\n\t\t\t\tthrow new SkillFailError('ask() requires onAskUser on the agent')\n\t\t\t}\n\t\t\treturn onAskUser(question, { signal })\n\t\t},\n\t\tfiles: {\n\t\t\tlist() {\n\t\t\t\treturn files.list().map(({ id, name, mimeType, size }) => ({\n\t\t\t\t\tid,\n\t\t\t\t\tname,\n\t\t\t\t\tmimeType,\n\t\t\t\t\tsize,\n\t\t\t\t}))\n\t\t\t},\n\t\t\tread(id: string) {\n\t\t\t\tconst file = files.read(id)\n\t\t\t\tif (!file) return undefined\n\t\t\t\treturn {\n\t\t\t\t\tid: file.id,\n\t\t\t\t\tname: file.name,\n\t\t\t\t\tmimeType: file.mimeType,\n\t\t\t\t\tsize: file.size,\n\t\t\t\t\ttext: file.text,\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tsignal,\n\t\tok(message: string) {\n\t\t\treturn { ok: true, message }\n\t\t},\n\t\tfail(message: string): never {\n\t\t\tthrow new SkillFailError(message)\n\t\t},\n\t\tmemo: {\n\t\t\tget(key: string) {\n\t\t\t\treturn memo.get(key)\n\t\t\t},\n\t\t\tset(key: string, value: unknown) {\n\t\t\t\tmemo.set(key, value)\n\t\t\t},\n\t\t},\n\t}\n\n\treturn Object.freeze(ctx)\n}\n\n/** Normalize a command return value or thrown fail/assert into a tool string. */\nexport function formatSkillCommandResult(result: unknown, error?: unknown): string {\n\tif (error !== undefined) {\n\t\tif (error instanceof SkillFailError) return `❌ ${error.message}`\n\t\tif (error instanceof SkillAssertError) return `❌ assert failed: ${error.message}`\n\t\tthrow error instanceof Error\n\t\t\t? error\n\t\t\t: new Error(typeof error === 'string' ? error : 'skill command failed')\n\t}\n\tif (typeof result === 'string') return result\n\tif (result && typeof result === 'object' && 'message' in result) {\n\t\tconst raw = (result as SkillResult).message\n\t\tconst message = typeof raw === 'string' ? raw : String(raw)\n\t\tif ('ok' in result && !(result as SkillResult).ok) return `❌ ${message}`\n\t\treturn message.startsWith('✅') || message.startsWith('❌') ? message : `✅ ${message}`\n\t}\n\tif (result === undefined || result === null) return '✅ done'\n\tif (typeof result === 'string' || typeof result === 'number' || typeof result === 'boolean') {\n\t\treturn `✅ ${String(result)}`\n\t}\n\treturn '✅ done'\n}\n","/**\n * Persist agent-authored skill documents.\n * Key: page-agent-skills-v1 (IndexedDB preferred, sessionStorage fallback).\n * Callers: SkillHost save/edit/hydrate.\n */\nimport { SKILL_STORAGE_KEY } from './types'\n\nexport interface StoredSkillRecord {\n\tid: string\n\tdocument: string\n\tupdatedAt: number\n}\n\nexport interface SkillStorage {\n\tlist(): Promise<StoredSkillRecord[]>\n\tget(id: string): Promise<StoredSkillRecord | undefined>\n\tput(record: StoredSkillRecord): Promise<void>\n\tremove(id: string): Promise<void>\n}\n\nconst SESSION_PREFIX = `${SKILL_STORAGE_KEY}:`\n\nfunction sessionAvailable(): Storage | null {\n\ttry {\n\t\tif (typeof sessionStorage === 'undefined') return null\n\t\treturn sessionStorage\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction readSessionAll(): StoredSkillRecord[] {\n\tconst store = sessionAvailable()\n\tif (!store) return []\n\tconst out: StoredSkillRecord[] = []\n\tfor (let i = 0; i < store.length; i++) {\n\t\tconst key = store.key(i)\n\t\tif (!key || !key.startsWith(SESSION_PREFIX)) continue\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(store.getItem(key) || '') as StoredSkillRecord\n\t\t\tif (parsed?.id && typeof parsed.document === 'string') out.push(parsed)\n\t\t} catch {\n\t\t\t// skip corrupt\n\t\t}\n\t}\n\treturn out\n}\n\nfunction writeSession(record: StoredSkillRecord): void {\n\tconst store = sessionAvailable()\n\tif (!store) return\n\tstore.setItem(SESSION_PREFIX + record.id, JSON.stringify(record))\n}\n\nfunction removeSession(id: string): void {\n\tconst store = sessionAvailable()\n\tif (!store) return\n\tstore.removeItem(SESSION_PREFIX + id)\n}\n\n/** Pure in-memory storage for tests. */\nexport function createMemorySkillStorage(seed: StoredSkillRecord[] = []): SkillStorage {\n\tconst map = new Map(seed.map((r) => [r.id, { ...r }]))\n\treturn {\n\t\tasync list() {\n\t\t\treturn [...map.values()]\n\t\t},\n\t\tasync get(id) {\n\t\t\tconst row = map.get(id)\n\t\t\treturn row ? { ...row } : undefined\n\t\t},\n\t\tasync put(record) {\n\t\t\tmap.set(record.id, { ...record })\n\t\t},\n\t\tasync remove(id) {\n\t\t\tmap.delete(id)\n\t\t},\n\t}\n}\n\n/**\n * Browser storage: IndexedDB when available, else sessionStorage.\n * Writes always mirror to sessionStorage when present so sync hydrate works.\n */\nexport function createBrowserSkillStorage(): SkillStorage {\n\tlet dbPromise: Promise<IDBDatabase | null> | null = null\n\n\tasync function openDb(): Promise<IDBDatabase | null> {\n\t\tif (typeof indexedDB === 'undefined') return null\n\t\tif (!dbPromise) {\n\t\t\tdbPromise = new Promise((resolve) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst request = indexedDB.open(SKILL_STORAGE_KEY, 1)\n\t\t\t\t\trequest.onupgradeneeded = () => {\n\t\t\t\t\t\tconst db = request.result\n\t\t\t\t\t\tif (!db.objectStoreNames.contains('skills')) {\n\t\t\t\t\t\t\tdb.createObjectStore('skills', { keyPath: 'id' })\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trequest.onsuccess = () => resolve(request.result)\n\t\t\t\t\trequest.onerror = () => resolve(null)\n\t\t\t\t} catch {\n\t\t\t\t\tresolve(null)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\treturn dbPromise\n\t}\n\n\tasync function idbList(db: IDBDatabase): Promise<StoredSkillRecord[]> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction('skills', 'readonly')\n\t\t\tconst req = tx.objectStore('skills').getAll()\n\t\t\treq.onsuccess = () => resolve((req.result as StoredSkillRecord[]) || [])\n\t\t\treq.onerror = () => reject(req.error ?? new Error('idbList failed'))\n\t\t})\n\t}\n\n\tasync function idbGet(db: IDBDatabase, id: string): Promise<StoredSkillRecord | undefined> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction('skills', 'readonly')\n\t\t\tconst req = tx.objectStore('skills').get(id)\n\t\t\treq.onsuccess = () => resolve(req.result as StoredSkillRecord | undefined)\n\t\t\treq.onerror = () => reject(req.error ?? new Error('idbGet failed'))\n\t\t})\n\t}\n\n\tasync function idbPut(db: IDBDatabase, record: StoredSkillRecord): Promise<void> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction('skills', 'readwrite')\n\t\t\ttx.objectStore('skills').put(record)\n\t\t\ttx.oncomplete = () => resolve()\n\t\t\ttx.onerror = () => reject(tx.error ?? new Error('idbPut failed'))\n\t\t})\n\t}\n\n\tasync function idbRemove(db: IDBDatabase, id: string): Promise<void> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst tx = db.transaction('skills', 'readwrite')\n\t\t\ttx.objectStore('skills').delete(id)\n\t\t\ttx.oncomplete = () => resolve()\n\t\t\ttx.onerror = () => reject(tx.error ?? new Error('idbRemove failed'))\n\t\t})\n\t}\n\n\treturn {\n\t\tasync list() {\n\t\t\tconst db = await openDb()\n\t\t\tif (db) {\n\t\t\t\ttry {\n\t\t\t\t\tconst rows = await idbList(db)\n\t\t\t\t\tif (rows.length > 0) return rows\n\t\t\t\t} catch {\n\t\t\t\t\t// fall through\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn readSessionAll()\n\t\t},\n\t\tasync get(id) {\n\t\t\tconst db = await openDb()\n\t\t\tif (db) {\n\t\t\t\ttry {\n\t\t\t\t\tconst row = await idbGet(db, id)\n\t\t\t\t\tif (row) return row\n\t\t\t\t} catch {\n\t\t\t\t\t// fall through\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn readSessionAll().find((r) => r.id === id)\n\t\t},\n\t\tasync put(record) {\n\t\t\twriteSession(record)\n\t\t\tconst db = await openDb()\n\t\t\tif (db) {\n\t\t\t\ttry {\n\t\t\t\t\tawait idbPut(db, record)\n\t\t\t\t} catch {\n\t\t\t\t\t// session already written\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tasync remove(id) {\n\t\t\tremoveSession(id)\n\t\t\tconst db = await openDb()\n\t\t\tif (db) {\n\t\t\t\ttry {\n\t\t\t\t\tawait idbRemove(db, id)\n\t\t\t\t} catch {\n\t\t\t\t\t// session already cleared\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}\n}\n","/**\n * SkillHost — catalog, load/unload, register skill__* + list/load/save/edit/unload tools.\n * Callers: PageAgentCore constructor / execute finally / dispose.\n */\nimport type { PageController } from '@page-agent/page-controller'\nimport * as z from 'zod/v4'\n\nimport { type PageAgentTool, tool } from '../tools'\nimport { type SkillFileStore, createSkillFileStore } from './files'\nimport { parseSkillDocument } from './parse'\nimport {\n\tSkillAssertError,\n\tSkillFailError,\n\tcreateSkillContext,\n\tformatSkillCommandResult,\n} from './runtime'\nimport {\n\ttype SkillStorage,\n\ttype StoredSkillRecord,\n\tcreateBrowserSkillStorage,\n\tcreateMemorySkillStorage,\n} from './storage'\nimport {\n\tDEFAULT_REMOTE_CACHE_TTL_MS,\n\tMAX_AGENT_SKILLS,\n\tMAX_SKILL_DOCUMENT_BYTES,\n\ttype PublishDocumentResult,\n\tSKILL_COMMAND_TIMEOUT_MS,\n\ttype SkillCatalogRef,\n\ttype SkillListEntry,\n\ttype SkillManifest,\n\tSkillParseError,\n\tSkillRemoteError,\n\ttype SkillsConfig,\n\ttype SkillsRemoteAdapter,\n\tskillToolName,\n} from './types'\n\nconst DEFAULT_MAX_LOADED = 3\n\nexport interface SkillDocumentFetchResult {\n\t/** Body when the server returned content (not 304). */\n\ttext?: string\n\tetag?: string\n\t/** True when the server responded 304 Not Modified. */\n\tnotModified?: boolean\n}\n\nexport type SkillDocumentFetch = (\n\turl: string,\n\topts?: { etag?: string }\n) => Promise<SkillDocumentFetchResult>\n\nexport interface SkillHostDeps {\n\ttools: Map<string, PageAgentTool>\n\tpageController: PageController\n\tconfig: SkillsConfig\n\tgetSignal: () => AbortSignal\n\tgetOnAskUser: () => import('../askUser').AskUserHandler | undefined\n\tstorage?: SkillStorage\n\tfiles?: SkillFileStore\n\t/** Fetch a remote skill document; may honor If-None-Match via opts.etag. */\n\tfetchDocument?: SkillDocumentFetch\n\t/**\n\t * @deprecated Prefer `fetchDocument`. Still accepted for tests that return a plain string body.\n\t */\n\tfetchText?: (url: string) => Promise<string>\n}\n\ninterface CatalogEntry {\n\tid: string\n\tname: string\n\tdescription: string\n\tscope: 'remote' | 'agent'\n\tinline?: string\n\turl?: string\n\tetag?: string\n\t/** Listed via SkillsRemoteAdapter; body fetched with remote.get on load. */\n\tremoteAdapter?: boolean\n\tversion?: number\n}\n\nfunction buildInputSchema(\n\tinput: SkillManifest['commands'][string]['input']\n): z.ZodType<Record<string, unknown>> {\n\tif (!input || Object.keys(input).length === 0) {\n\t\treturn z.object({}).passthrough()\n\t}\n\tconst shape: Record<string, z.ZodType> = {}\n\tfor (const [key, field] of Object.entries(input)) {\n\t\tlet schema: z.ZodType\n\t\tif (field.type === 'number') schema = z.number()\n\t\telse if (field.type === 'boolean') schema = z.boolean()\n\t\telse schema = z.string()\n\t\tif (field.description) schema = schema.describe(field.description)\n\t\tif (field.default !== undefined) {\n\t\t\tschema = schema.default(field.default as never)\n\t\t}\n\t\tshape[key] = schema\n\t}\n\treturn z.object(shape)\n}\n\n/** Compose task/tool abort with a wall-clock timeout for one skill command. */\nexport function createSkillCommandAbort(\n\tparent: AbortSignal,\n\ttimeoutMs: number = SKILL_COMMAND_TIMEOUT_MS\n): { signal: AbortSignal; cleanup: () => void; timeoutPromise: Promise<never> } {\n\tconst controller = new AbortController()\n\tlet settled = false\n\n\tconst onParentAbort = () => {\n\t\tif (settled) return\n\t\tcontroller.abort(parent.reason)\n\t}\n\n\tif (parent.aborted) {\n\t\tcontroller.abort(parent.reason)\n\t} else {\n\t\tparent.addEventListener('abort', onParentAbort)\n\t}\n\n\tlet timeoutReject!: (error: SkillFailError) => void\n\tconst timeoutPromise = new Promise<never>((_resolve, reject) => {\n\t\ttimeoutReject = reject\n\t})\n\n\tconst timer = setTimeout(() => {\n\t\tif (settled) return\n\t\tconst error = new SkillFailError(`skill_timeout: command exceeded ${timeoutMs}ms`)\n\t\tcontroller.abort(error)\n\t\ttimeoutReject(error)\n\t}, timeoutMs)\n\n\tconst cleanup = () => {\n\t\tif (settled) return\n\t\tsettled = true\n\t\tclearTimeout(timer)\n\t\tparent.removeEventListener('abort', onParentAbort)\n\t}\n\n\treturn { signal: controller.signal, cleanup, timeoutPromise }\n}\n\nexport class SkillHost {\n\treadonly files: SkillFileStore\n\treadonly storage: SkillStorage\n\treadonly config: SkillsConfig\n\n\t#tools: Map<string, PageAgentTool>\n\t#pageController: PageController\n\t#getSignal: () => AbortSignal\n\t#getOnAskUser: SkillHostDeps['getOnAskUser']\n\t#fetchDocument: SkillDocumentFetch\n\t#catalog = new Map<string, CatalogEntry>()\n\t#loaded = new Map<string, SkillManifest>()\n\t#memos = new Map<string, Map<string, unknown>>()\n\t#agentToolsAttached = false\n\t#maxLoaded: number\n\t#persistAgentSkills: boolean\n\t#allowedOrigins: string[] | undefined\n\t#remote: SkillsRemoteAdapter | undefined\n\t#remoteCacheTtlMs: number\n\t#remoteListCache: { at: number; ids: string[] } | null = null\n\n\tconstructor(deps: SkillHostDeps) {\n\t\tthis.#tools = deps.tools\n\t\tthis.#pageController = deps.pageController\n\t\tthis.#getSignal = deps.getSignal\n\t\tthis.#getOnAskUser = deps.getOnAskUser\n\t\tthis.config = deps.config\n\t\tthis.files = deps.files ?? createSkillFileStore()\n\t\tthis.storage = deps.storage ?? createBrowserSkillStorage()\n\t\tthis.#fetchDocument = resolveFetchDocument(deps)\n\t\tthis.#maxLoaded = deps.config.maxLoaded ?? DEFAULT_MAX_LOADED\n\t\tthis.#persistAgentSkills = deps.config.persistAgentSkills !== false\n\t\tthis.#allowedOrigins = deps.config.allowedOrigins\n\t\tthis.#remote = deps.config.remote\n\t\tthis.#remoteCacheTtlMs = deps.config.remoteCacheTtlMs ?? DEFAULT_REMOTE_CACHE_TTL_MS\n\n\t\tfor (const ref of deps.config.catalog ?? []) {\n\t\t\tthis.#ingestCatalogRef(ref)\n\t\t}\n\t}\n\n\t/** Whether list/load tools should be present. */\n\tget enabled(): boolean {\n\t\tif (this.config.enabled === false) return false\n\t\tif (this.config.enabled === true) return true\n\t\tif (this.#remote) return true\n\t\tif ((this.config.catalog?.length ?? 0) > 0) return true\n\t\tif (this.#catalog.size > 0) return true\n\t\treturn false\n\t}\n\n\tget loadedIds(): string[] {\n\t\treturn [...this.#loaded.keys()]\n\t}\n\n\t/** Compact prompt block so the LLM sees loaded skill ids + command names. */\n\tformatLoadedSkillsPromptBlock(): string {\n\t\tif (this.#loaded.size === 0) return ''\n\t\tconst lines: string[] = ['<loaded_skills>']\n\t\tfor (const [id, manifest] of this.#loaded) {\n\t\t\tconst commands = Object.keys(manifest.commands).join(', ')\n\t\t\tlines.push(`- ${id}: ${commands}`)\n\t\t}\n\t\tlines.push('</loaded_skills>', '')\n\t\treturn `${lines.join('\\n')}\\n`\n\t}\n\n\t/** Register catalog refs and optional agent-tool set. */\n\tattachAgentTools(): void {\n\t\tif (this.#agentToolsAttached) return\n\t\tthis.#agentToolsAttached = true\n\t\tthis.#tools.set('list_skills', this.#listSkillsTool())\n\t\tthis.#tools.set('load_skill', this.#loadSkillTool())\n\t\tthis.#tools.set('unload_skill', this.#unloadSkillTool())\n\t\tthis.#tools.set('save_skill', this.#saveSkillTool())\n\t\tthis.#tools.set('edit_skill', this.#editSkillTool())\n\t}\n\n\tdetachAgentTools(): void {\n\t\tif (!this.#agentToolsAttached) return\n\t\tthis.#agentToolsAttached = false\n\t\tthis.#tools.delete('list_skills')\n\t\tthis.#tools.delete('load_skill')\n\t\tthis.#tools.delete('unload_skill')\n\t\tthis.#tools.delete('save_skill')\n\t\tthis.#tools.delete('edit_skill')\n\t}\n\n\t/** Load stored agent skills into the catalog; attach tools if anything is present. */\n\tasync hydrate(): Promise<boolean> {\n\t\tconst rows = await this.storage.list()\n\t\tfor (const row of rows) {\n\t\t\ttry {\n\t\t\t\tconst manifest = parseSkillDocument(row.document)\n\t\t\t\tthis.#catalog.set(manifest.id, {\n\t\t\t\t\tid: manifest.id,\n\t\t\t\t\tname: manifest.name,\n\t\t\t\t\tdescription: manifest.description,\n\t\t\t\t\tscope: 'agent',\n\t\t\t\t\tinline: row.document,\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\t// skip corrupt documents\n\t\t\t}\n\t\t}\n\t\tif (this.enabled || rows.length > 0) {\n\t\t\tif (this.config.enabled !== false) this.attachAgentTools()\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tlist(query?: string): SkillListEntry[] {\n\t\tconst q = query?.trim().toLowerCase()\n\t\tconst entries: SkillListEntry[] = []\n\t\tfor (const entry of this.#catalog.values()) {\n\t\t\tconst loaded = this.#loaded.get(entry.id)\n\t\t\tconst hay = `${entry.id} ${entry.name} ${entry.description}`.toLowerCase()\n\t\t\tif (q && !hay.includes(q)) continue\n\t\t\tconst commands = loaded\n\t\t\t\t? Object.entries(loaded.commands).map(([name, cmd]) => ({\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tdescription: cmd.description,\n\t\t\t\t\t}))\n\t\t\t\t: this.#commandsFromInline(entry.inline)\n\t\t\tentries.push({\n\t\t\t\tid: entry.id,\n\t\t\t\tname: entry.name || entry.id,\n\t\t\t\tdescription: entry.description,\n\t\t\t\tscope: entry.scope,\n\t\t\t\tloaded: Boolean(loaded),\n\t\t\t\tcommands,\n\t\t\t})\n\t\t}\n\t\treturn entries\n\t}\n\n\tasync load(id: string): Promise<string> {\n\t\tif (this.#loaded.has(id)) {\n\t\t\treturn `Skill \"${id}\" is already loaded`\n\t\t}\n\t\tif (this.#loaded.size >= this.#maxLoaded) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'max_loaded',\n\t\t\t\t`Cannot load more than ${this.#maxLoaded} skills at once. Unload one first.`\n\t\t\t)\n\t\t}\n\n\t\tconst entry = this.#catalog.get(id)\n\t\tif (!entry) {\n\t\t\tthrow new SkillParseError('unknown_skill', `Unknown skill id \"${id}\"`)\n\t\t}\n\n\t\tconst document = await this.#resolveDocument(entry)\n\t\tconst manifest = parseSkillDocument(document)\n\t\tconst skillId = entry.id\n\t\tconst normalized: SkillManifest = { ...manifest, id: skillId, scope: entry.scope }\n\n\t\tthis.#catalog.set(skillId, {\n\t\t\t...entry,\n\t\t\tname: normalized.name,\n\t\t\tdescription: normalized.description,\n\t\t\tinline: document,\n\t\t})\n\n\t\tthis.#registerCommandTools(normalized)\n\t\tthis.#loaded.set(skillId, normalized)\n\t\tthis.#memos.set(skillId, new Map())\n\n\t\tconst commandNames = Object.keys(normalized.commands).join(', ')\n\t\treturn `✅ Loaded skill \"${skillId}\" with commands: ${commandNames}`\n\t}\n\n\tunload(id?: string): void {\n\t\tif (id) {\n\t\t\tthis.#unloadOne(id)\n\t\t\treturn\n\t\t}\n\t\tfor (const skillId of [...this.#loaded.keys()]) {\n\t\t\tthis.#unloadOne(skillId)\n\t\t}\n\t}\n\n\t/** End of task: drop loaded tools and memos; keep catalog + storage. */\n\tresetTask(): void {\n\t\tthis.unload()\n\t\tthis.files.clear()\n\t}\n\n\tasync save(document: string): Promise<string> {\n\t\tthis.#assertDocumentQuota(document)\n\t\tconst manifest = parseSkillDocument(document)\n\t\tawait this.#assertAgentSkillCountQuota(manifest.id)\n\t\tconst record: StoredSkillRecord = {\n\t\t\tid: manifest.id,\n\t\t\tdocument,\n\t\t\tupdatedAt: Date.now(),\n\t\t}\n\t\tif (this.#persistAgentSkills) {\n\t\t\tawait this.storage.put(record)\n\t\t}\n\t\tthis.#catalog.set(manifest.id, {\n\t\t\tid: manifest.id,\n\t\t\tname: manifest.name,\n\t\t\tdescription: manifest.description,\n\t\t\tscope: 'agent',\n\t\t\tinline: document,\n\t\t})\n\t\tif (this.#loaded.has(manifest.id)) {\n\t\t\tthis.#unloadOne(manifest.id)\n\t\t\tawait this.load(manifest.id)\n\t\t}\n\t\treturn `✅ Saved agent skill \"${manifest.id}\"`\n\t}\n\n\tasync edit(id: string, document: string): Promise<string> {\n\t\tconst existing = this.#catalog.get(id)\n\t\tif (!existing && !(await this.storage.get(id))) {\n\t\t\tthrow new SkillParseError('unknown_skill', `Unknown skill id \"${id}\" to edit`)\n\t\t}\n\t\tthis.#assertDocumentQuota(document)\n\t\tconst record: StoredSkillRecord = {\n\t\t\tid,\n\t\t\tdocument: ensureIdInDocument(document, id),\n\t\t\tupdatedAt: Date.now(),\n\t\t}\n\t\tconst pinned = parseSkillDocument(record.document)\n\t\tconst storedManifest = { ...pinned, id, scope: 'agent' as const }\n\n\t\tif (this.#persistAgentSkills) {\n\t\t\tawait this.storage.put(record)\n\t\t}\n\t\tthis.#catalog.set(id, {\n\t\t\tid,\n\t\t\tname: storedManifest.name,\n\t\t\tdescription: storedManifest.description,\n\t\t\tscope: 'agent',\n\t\t\tinline: record.document,\n\t\t})\n\t\tif (this.#loaded.has(id)) {\n\t\t\tthis.#unloadOne(id)\n\t\t\tawait this.load(id)\n\t\t}\n\t\treturn `✅ Edited agent skill \"${id}\"`\n\t}\n\n\t/**\n\t * Remove an agent-authored skill from storage and catalog.\n\t * Unloads it if currently loaded. Remote catalog entries are not deleted.\n\t */\n\tasync removeAgentSkill(id: string): Promise<string> {\n\t\tconst entry = this.#catalog.get(id)\n\t\tconst stored = await this.storage.get(id)\n\t\tif (!stored && (!entry || entry.scope !== 'agent')) {\n\t\t\tthrow new SkillParseError('unknown_skill', `Unknown agent skill id \"${id}\"`)\n\t\t}\n\t\tif (entry && entry.scope !== 'agent' && !stored) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'not_agent_skill',\n\t\t\t\t`Skill \"${id}\" is remote and cannot be removed from agent storage`\n\t\t\t)\n\t\t}\n\t\tif (this.#loaded.has(id)) this.#unloadOne(id)\n\t\tawait this.storage.remove(id)\n\t\tif (!entry || entry.scope === 'agent') {\n\t\t\tthis.#catalog.delete(id)\n\t\t}\n\t\treturn `✅ Removed agent skill \"${id}\"`\n\t}\n\n\t/**\n\t * Refresh the remote adapter catalog into the local catalog (scope `remote`).\n\t * Results are cached for `remoteCacheTtlMs` unless `force` is set.\n\t */\n\tasync refreshRemote(options?: {\n\t\tforce?: boolean\n\t}): Promise<{ ids: string[]; fromCache: boolean }> {\n\t\tif (!this.#remote) {\n\t\t\treturn { ids: [], fromCache: false }\n\t\t}\n\t\tconst now = Date.now()\n\t\tif (\n\t\t\t!options?.force &&\n\t\t\tthis.#remoteListCache &&\n\t\t\tnow - this.#remoteListCache.at < this.#remoteCacheTtlMs\n\t\t) {\n\t\t\treturn { ids: [...this.#remoteListCache.ids], fromCache: true }\n\t\t}\n\n\t\tlet items: Awaited<ReturnType<SkillsRemoteAdapter['list']>>\n\t\ttry {\n\t\t\titems = await this.#remote.list()\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthrow new SkillRemoteError('remote_list_failed', message)\n\t\t}\n\n\t\tconst ids: string[] = []\n\t\tconst listed = new Set<string>()\n\t\tfor (const item of items) {\n\t\t\tids.push(item.id)\n\t\t\tlisted.add(item.id)\n\t\t\tconst existing = this.#catalog.get(item.id)\n\t\t\tif (existing?.scope === 'agent') continue\n\t\t\tthis.#catalog.set(item.id, {\n\t\t\t\tid: item.id,\n\t\t\t\tname: item.name,\n\t\t\t\tdescription: item.description,\n\t\t\t\tscope: 'remote',\n\t\t\t\tetag: item.etag,\n\t\t\t\tversion: item.version,\n\t\t\t\tremoteAdapter: true,\n\t\t\t\tinline: existing?.remoteAdapter ? existing.inline : undefined,\n\t\t\t})\n\t\t}\n\n\t\tfor (const [id, entry] of [...this.#catalog.entries()]) {\n\t\t\tif (entry.remoteAdapter && !listed.has(id) && !this.#loaded.has(id)) {\n\t\t\t\tthis.#catalog.delete(id)\n\t\t\t}\n\t\t}\n\n\t\tthis.#remoteListCache = { at: now, ids }\n\t\tif (this.enabled && this.config.enabled !== false) this.attachAgentTools()\n\t\treturn { ids: [...ids], fromCache: false }\n\t}\n\n\t/**\n\t * Parse → persist locally (same as `save`) → optional `remote.put`.\n\t * Local copy is kept even when remote.put fails (`remoteError` set).\n\t */\n\tasync publishDocument(document: string): Promise<PublishDocumentResult> {\n\t\tconst manifest = parseSkillDocument(document)\n\t\tconst expectedVersion = this.#catalog.get(manifest.id)?.version\n\t\tawait this.save(document)\n\n\t\tconst result: PublishDocumentResult = {\n\t\t\tid: manifest.id,\n\t\t\tversion: manifest.version,\n\t\t\tdocument,\n\t\t}\n\n\t\tif (!this.#remote) return result\n\n\t\ttry {\n\t\t\tconst remoteResult = await this.#remote.put({\n\t\t\t\tdocument,\n\t\t\t\texpectedVersion,\n\t\t\t})\n\t\t\tresult.remote = true\n\t\t\tresult.id = remoteResult.id || manifest.id\n\t\t\tresult.version = remoteResult.version\n\t\t\tresult.etag = remoteResult.etag\n\t\t\tconst entry = this.#catalog.get(result.id)\n\t\t\tif (entry) {\n\t\t\t\tentry.etag = remoteResult.etag\n\t\t\t\tentry.version = remoteResult.version\n\t\t\t\tentry.inline = document\n\t\t\t}\n\t\t\treturn result\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tresult.remoteError = message\n\t\t\treturn result\n\t\t}\n\t}\n\n\t#unloadOne(id: string): void {\n\t\tconst manifest = this.#loaded.get(id)\n\t\tif (!manifest) return\n\t\tfor (const commandName of Object.keys(manifest.commands)) {\n\t\t\tthis.#tools.delete(skillToolName(id, commandName))\n\t\t}\n\t\tthis.#loaded.delete(id)\n\t\tthis.#memos.delete(id)\n\t}\n\n\t#registerCommandTools(manifest: SkillManifest): void {\n\t\tfor (const [commandName, command] of Object.entries(manifest.commands)) {\n\t\t\tconst toolName = skillToolName(manifest.id, commandName)\n\t\t\tconst inputSchema = buildInputSchema(command.input)\n\t\t\tthis.#tools.set(\n\t\t\t\ttoolName,\n\t\t\t\ttool({\n\t\t\t\t\tdescription: `[skill:${manifest.id}] ${command.description}`,\n\t\t\t\t\tinputSchema,\n\t\t\t\t\texecute: async (_args, { signal }) => {\n\t\t\t\t\t\tconst memo = this.#memos.get(manifest.id) ?? new Map()\n\t\t\t\t\t\tthis.#memos.set(manifest.id, memo)\n\t\t\t\t\t\tconst parent = signal ?? this.#getSignal()\n\t\t\t\t\t\tconst timed = createSkillCommandAbort(parent, SKILL_COMMAND_TIMEOUT_MS)\n\t\t\t\t\t\tconst ctx = createSkillContext({\n\t\t\t\t\t\t\tpageController: this.#pageController,\n\t\t\t\t\t\t\tfiles: this.files,\n\t\t\t\t\t\t\tsignal: timed.signal,\n\t\t\t\t\t\t\tmemo,\n\t\t\t\t\t\t\tonAskUser: this.#getOnAskUser(),\n\t\t\t\t\t\t})\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await Promise.race([\n\t\t\t\t\t\t\t\tPromise.resolve(command.run(ctx, _args as Record<string, unknown>)),\n\t\t\t\t\t\t\t\ttimed.timeoutPromise,\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t\treturn formatSkillCommandResult(result)\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\treturn formatSkillCommandResult(undefined, error)\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\ttimed.cleanup()\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t}\n\n\tasync #resolveDocument(entry: CatalogEntry): Promise<string> {\n\t\tif (entry.url) {\n\t\t\tthis.#assertUrlAllowed(entry.url)\n\t\t\tconst result = await this.#fetchDocument(entry.url, { etag: entry.etag })\n\t\t\tif (result.notModified) {\n\t\t\t\tif (!entry.inline) {\n\t\t\t\t\tthrow new SkillParseError(\n\t\t\t\t\t\t'not_modified_without_cache',\n\t\t\t\t\t\t`Skill \"${entry.id}\" returned 304 but no cached document is available`\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (result.etag) entry.etag = result.etag\n\t\t\t\treturn entry.inline\n\t\t\t}\n\t\t\tconst text = result.text ?? ''\n\t\t\tif (text.length > MAX_SKILL_DOCUMENT_BYTES) {\n\t\t\t\tthrow new SkillParseError(\n\t\t\t\t\t'skill_too_large',\n\t\t\t\t\t`Skill \"${entry.id}\" exceeds ${MAX_SKILL_DOCUMENT_BYTES} bytes`\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (result.etag) entry.etag = result.etag\n\t\t\treturn text\n\t\t}\n\t\tif (entry.remoteAdapter && this.#remote && !entry.inline) {\n\t\t\ttry {\n\t\t\t\tconst remoteDoc = await this.#remote.get(entry.id)\n\t\t\t\tif (remoteDoc.document.length > MAX_SKILL_DOCUMENT_BYTES) {\n\t\t\t\t\tthrow new SkillParseError(\n\t\t\t\t\t\t'skill_too_large',\n\t\t\t\t\t\t`Skill \"${entry.id}\" exceeds ${MAX_SKILL_DOCUMENT_BYTES} bytes`\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tentry.inline = remoteDoc.document\n\t\t\t\tentry.etag = remoteDoc.etag\n\t\t\t\tentry.version = remoteDoc.version\n\t\t\t\treturn remoteDoc.document\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof SkillParseError) throw error\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\t\tthrow new SkillRemoteError('remote_get_failed', message, entry.id)\n\t\t\t}\n\t\t}\n\t\tif (entry.inline) return entry.inline\n\t\tthrow new SkillParseError('missing_document', `Skill \"${entry.id}\" has no document source`)\n\t}\n\n\t#assertUrlAllowed(url: string): void {\n\t\tlet parsed: URL\n\t\ttry {\n\t\t\tparsed = new URL(url)\n\t\t} catch {\n\t\t\tthrow new SkillParseError('invalid_url', `Invalid skill URL: ${url}`)\n\t\t}\n\t\tconst sameOrigin = typeof location !== 'undefined' && parsed.origin === location.origin\n\t\tif (parsed.protocol !== 'https:' && !sameOrigin) {\n\t\t\tthrow new SkillParseError('insecure_url', `Skill URL must be https or same-origin: ${url}`)\n\t\t}\n\t\tif (this.#allowedOrigins && this.#allowedOrigins.length > 0) {\n\t\t\tif (!this.#allowedOrigins.includes(parsed.origin) && !sameOrigin) {\n\t\t\t\tthrow new SkillParseError(\n\t\t\t\t\t'origin_not_allowed',\n\t\t\t\t\t`Skill origin not allowed: ${parsed.origin}`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\t#assertDocumentQuota(document: string): void {\n\t\tconst bytes = new TextEncoder().encode(document).length\n\t\tif (bytes > MAX_SKILL_DOCUMENT_BYTES) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'quota_bytes',\n\t\t\t\t`Agent skill document exceeds ${MAX_SKILL_DOCUMENT_BYTES} bytes (got ${bytes})`\n\t\t\t)\n\t\t}\n\t}\n\n\tasync #assertAgentSkillCountQuota(id: string): Promise<void> {\n\t\tconst stored = await this.storage.get(id)\n\t\tif (stored) return\n\t\tif (this.#catalog.get(id)?.scope === 'agent') return\n\t\tconst count = await this.#countAgentSkills()\n\t\tif (count >= MAX_AGENT_SKILLS) {\n\t\t\tthrow new SkillParseError(\n\t\t\t\t'quota_count',\n\t\t\t\t`Cannot store more than ${MAX_AGENT_SKILLS} agent skills. Remove one first.`\n\t\t\t)\n\t\t}\n\t}\n\n\tasync #countAgentSkills(): Promise<number> {\n\t\tconst ids = new Set<string>()\n\t\tfor (const entry of this.#catalog.values()) {\n\t\t\tif (entry.scope === 'agent') ids.add(entry.id)\n\t\t}\n\t\tfor (const row of await this.storage.list()) {\n\t\t\tids.add(row.id)\n\t\t}\n\t\treturn ids.size\n\t}\n\n\t/**\n\t * Expose command names for catalog UI (Arm watch, etc.) without loading tools.\n\t * Returns [] when there is no inline body or parse fails.\n\t */\n\t#commandsFromInline(inline: string | undefined): { name: string; description: string }[] {\n\t\tif (!inline?.trim()) return []\n\t\ttry {\n\t\t\tconst manifest = parseSkillDocument(inline)\n\t\t\treturn Object.entries(manifest.commands).map(([name, cmd]) => ({\n\t\t\t\tname,\n\t\t\t\tdescription: cmd.description,\n\t\t\t}))\n\t\t} catch {\n\t\t\treturn []\n\t\t}\n\t}\n\n\t#ingestCatalogRef(ref: SkillCatalogRef): void {\n\t\tif ('inline' in ref) {\n\t\t\ttry {\n\t\t\t\tconst manifest = parseSkillDocument(ref.inline)\n\t\t\t\tthis.#catalog.set(ref.id, {\n\t\t\t\t\tid: ref.id,\n\t\t\t\t\tname: manifest.name,\n\t\t\t\t\tdescription: manifest.description,\n\t\t\t\t\tscope: 'remote',\n\t\t\t\t\tinline: ref.inline,\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\tthis.#catalog.set(ref.id, {\n\t\t\t\t\tid: ref.id,\n\t\t\t\t\tname: ref.id,\n\t\t\t\t\tdescription: '',\n\t\t\t\t\tscope: 'remote',\n\t\t\t\t\tinline: ref.inline,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif ('name' in ref && 'description' in ref) {\n\t\t\tthis.#catalog.set(ref.id, {\n\t\t\t\tid: ref.id,\n\t\t\t\tname: ref.name,\n\t\t\t\tdescription: ref.description,\n\t\t\t\tscope: 'remote',\n\t\t\t\turl: ref.url,\n\t\t\t\tetag: ref.etag,\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tthis.#catalog.set(ref.id, {\n\t\t\tid: ref.id,\n\t\t\tname: ref.id,\n\t\t\tdescription: '',\n\t\t\tscope: 'remote',\n\t\t\turl: ref.url,\n\t\t\tetag: ref.etag,\n\t\t})\n\t}\n\n\t#listSkillsTool(): PageAgentTool {\n\t\treturn tool({\n\t\t\tdescription:\n\t\t\t\t'List available Page Agent skills (remote catalog + agent-authored). Optional query filters by id/name/description. Does not fetch remote bodies.',\n\t\t\tinputSchema: z.object({\n\t\t\t\tquery: z.string().optional(),\n\t\t\t}),\n\t\t\texecute: async (input) => {\n\t\t\t\tconst entries = this.list(input.query)\n\t\t\t\treturn JSON.stringify(entries, null, 2)\n\t\t\t},\n\t\t})\n\t}\n\n\t#loadSkillTool(): PageAgentTool {\n\t\treturn tool({\n\t\t\tdescription:\n\t\t\t\t'Load a skill by id. Registers its commands as skill__{id}__{command} tools for this task. Unloads automatically when the task ends. Respects maxLoaded.',\n\t\t\tinputSchema: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t}),\n\t\t\texecute: async (input) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.load(input.id)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof SkillParseError) return `❌ ${error.message}`\n\t\t\t\t\tif (error instanceof SkillFailError || error instanceof SkillAssertError) {\n\t\t\t\t\t\treturn `❌ ${error.message}`\n\t\t\t\t\t}\n\t\t\t\t\tthrow error\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t}\n\n\t#unloadSkillTool(): PageAgentTool {\n\t\treturn tool({\n\t\t\tdescription:\n\t\t\t\t'Unload a previously loaded skill by id for this task. Removes its skill__* tools. Catalog and storage are unchanged.',\n\t\t\tinputSchema: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t}),\n\t\t\texecute: async (input) => {\n\t\t\t\tif (!this.#loaded.has(input.id)) {\n\t\t\t\t\treturn `❌ Skill \"${input.id}\" is not loaded`\n\t\t\t\t}\n\t\t\t\tthis.unload(input.id)\n\t\t\t\treturn `✅ Unloaded skill \"${input.id}\"`\n\t\t\t},\n\t\t})\n\t}\n\n\t#saveSkillTool(): PageAgentTool {\n\t\treturn tool({\n\t\t\tdescription:\n\t\t\t\t'Save an agent-authored skill document (frontmatter + skill-js). Persists in browser storage and adds it to the catalog.',\n\t\t\tinputSchema: z.object({\n\t\t\t\tdocument: z.string(),\n\t\t\t}),\n\t\t\texecute: async (input) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.save(input.document)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof SkillParseError) return `❌ ${error.message}`\n\t\t\t\t\tthrow error\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t}\n\n\t#editSkillTool(): PageAgentTool {\n\t\treturn tool({\n\t\t\tdescription:\n\t\t\t\t'Replace an existing agent skill document by id. Updates storage and reloads the skill if it is currently loaded.',\n\t\t\tinputSchema: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tdocument: z.string(),\n\t\t\t}),\n\t\t\texecute: async (input) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.edit(input.id, input.document)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof SkillParseError) return `❌ ${error.message}`\n\t\t\t\t\tthrow error\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t}\n}\n\nfunction ensureIdInDocument(document: string, id: string): string {\n\tif (/^id:\\s*/m.test(document)) {\n\t\treturn document.replace(/^id:\\s*.+$/m, `id: ${id}`)\n\t}\n\treturn document.replace(/^(---\\r?\\n)/, `$1id: ${id}\\n`)\n}\n\nfunction resolveFetchDocument(deps: SkillHostDeps): SkillDocumentFetch {\n\tif (deps.fetchDocument) return deps.fetchDocument\n\tif (deps.fetchText) {\n\t\treturn async (url: string) => {\n\t\t\tconst text = await deps.fetchText!(url)\n\t\t\treturn { text, notModified: false }\n\t\t}\n\t}\n\treturn defaultFetchDocument\n}\n\nasync function defaultFetchDocument(\n\turl: string,\n\topts?: { etag?: string }\n): Promise<SkillDocumentFetchResult> {\n\tconst headers: Record<string, string> = {}\n\tif (opts?.etag) headers['If-None-Match'] = opts.etag\n\tconst response = await fetch(url, { headers })\n\tif (response.status === 304) {\n\t\treturn { notModified: true, etag: opts?.etag }\n\t}\n\tif (!response.ok) {\n\t\tthrow new SkillParseError(\n\t\t\t'fetch_failed',\n\t\t\t`Failed to fetch skill from ${url}: HTTP ${response.status}`\n\t\t)\n\t}\n\tconst text = await response.text()\n\tconst etag = response.headers.get('etag') ?? undefined\n\treturn { text, etag, notModified: false }\n}\n\n/** Test helper: host with memory storage and no browser APIs. */\nexport function createTestSkillHost(\n\tdeps: Omit<SkillHostDeps, 'storage'> & { storage?: SkillStorage }\n): SkillHost {\n\treturn new SkillHost({\n\t\t...deps,\n\t\tstorage: deps.storage ?? createMemorySkillStorage(),\n\t})\n}\n","/**\n * Skills Studio recorder — capture trusted page interactions as AX-oriented steps.\n * Does not store durable indexes; role/name come from resolveTarget, heuristics, or observation.\n */\nimport { parseObservationLabels } from './runtime'\n\nexport interface RecordedStep {\n\tid: string\n\tkind: 'click' | 'fill' | 'select' | 'note'\n\trole?: string\n\tname?: string\n\tvalue?: string\n\turl: string\n\tts: number\n\trawLabel?: string\n\tparam?: boolean\n}\n\nexport interface SkillRecorderDeps {\n\t/** Refresh page observation; return content like BrowserState.content + url */\n\tobserve: () => Promise<{ url: string; content: string }>\n\t/** Optional: resolve a DOM Element to { role, name } using current observation / page controller */\n\tresolveTarget?: (\n\t\tel: Element\n\t) => Promise<{ role?: string; name?: string; rawLabel?: string } | null>\n\troot?: Document | ParentNode\n\tignoreSelector?: string // default '[data-page-agent-ignore], [data-browser-use-ignore]'\n}\n\nconst DEFAULT_IGNORE = '[data-page-agent-ignore], [data-browser-use-ignore]'\nconst FILL_DEBOUNCE_MS = 300\n\nconst IMPLICIT_ROLES: Record<string, string> = {\n\tA: 'link',\n\tBUTTON: 'button',\n\tSELECT: 'combobox',\n\tTEXTAREA: 'textbox',\n\tIMG: 'img',\n\tSUMMARY: 'button',\n\tH1: 'heading',\n\tH2: 'heading',\n\tH3: 'heading',\n\tH4: 'heading',\n\tH5: 'heading',\n\tH6: 'heading',\n}\n\nfunction newStepId(): string {\n\tif (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n\t\treturn crypto.randomUUID()\n\t}\n\treturn `rec-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n}\n\nfunction eventElement(target: EventTarget | null): Element | null {\n\tif (!target) return null\n\tif (target instanceof Element) return target\n\tif (target instanceof Node && target.parentElement) return target.parentElement\n\treturn null\n}\n\nfunction isIgnored(el: Element, ignoreSelector: string): boolean {\n\ttry {\n\t\treturn Boolean(el.closest(ignoreSelector))\n\t} catch {\n\t\treturn false\n\t}\n}\n\nfunction inputType(el: Element): string {\n\tif (!(el instanceof HTMLInputElement)) return ''\n\treturn (el.type || 'text').toLowerCase()\n}\n\nfunction isTextLike(el: Element): boolean {\n\tif (el instanceof HTMLTextAreaElement) return true\n\tif (el instanceof HTMLElement && el.isContentEditable) return true\n\tif (!(el instanceof HTMLInputElement)) return false\n\tconst type = inputType(el)\n\treturn (\n\t\ttype === '' ||\n\t\ttype === 'text' ||\n\t\ttype === 'search' ||\n\t\ttype === 'email' ||\n\t\ttype === 'password' ||\n\t\ttype === 'tel' ||\n\t\ttype === 'url' ||\n\t\ttype === 'number' ||\n\t\ttype === 'date' ||\n\t\ttype === 'datetime-local' ||\n\t\ttype === 'month' ||\n\t\ttype === 'week' ||\n\t\ttype === 'time'\n\t)\n}\n\nfunction isSelectControl(el: Element): boolean {\n\treturn el instanceof HTMLSelectElement || el.closest('select') instanceof HTMLSelectElement\n}\n\nfunction selectElement(el: Element): HTMLSelectElement | null {\n\tif (el instanceof HTMLSelectElement) return el\n\tconst nested = el.closest('select')\n\treturn nested instanceof HTMLSelectElement ? nested : null\n}\n\nfunction heuristicRole(el: Element): string | undefined {\n\tconst explicit = el.getAttribute('role')?.trim()\n\tif (explicit) return explicit\n\n\tif (el instanceof HTMLInputElement) {\n\t\tconst type = inputType(el)\n\t\tif (type === 'checkbox') return 'checkbox'\n\t\tif (type === 'radio') return 'radio'\n\t\tif (type === 'search') return 'searchbox'\n\t\tif (type === 'range') return 'slider'\n\t\tif (type === 'button' || type === 'submit' || type === 'reset' || type === 'image') {\n\t\t\treturn 'button'\n\t\t}\n\t\tif (isTextLike(el)) return 'textbox'\n\t\treturn 'textbox'\n\t}\n\n\tif (el instanceof HTMLSelectElement) {\n\t\treturn el.multiple ? 'listbox' : 'combobox'\n\t}\n\n\tif (el instanceof HTMLElement && el.isContentEditable) return 'textbox'\n\n\treturn IMPLICIT_ROLES[el.tagName]\n}\n\nfunction associatedLabelText(el: Element): string | undefined {\n\tif (!(el instanceof HTMLElement)) return undefined\n\tconst id = el.id\n\tif (id && el.ownerDocument) {\n\t\tconst label = el.ownerDocument.querySelector(`label[for=\"${CSS.escape(id)}\"]`)\n\t\tconst text = label?.textContent?.trim()\n\t\tif (text) return text\n\t}\n\tconst wrapping = el.closest('label')\n\tif (wrapping) {\n\t\tconst clone = wrapping.cloneNode(true) as HTMLElement\n\t\tfor (const control of clone.querySelectorAll('input, select, textarea, button')) {\n\t\t\tcontrol.remove()\n\t\t}\n\t\tconst text = clone.textContent?.trim()\n\t\tif (text) return text\n\t}\n\treturn undefined\n}\n\nfunction heuristicName(el: Element): string | undefined {\n\tconst aria = el.getAttribute('aria-label')?.trim()\n\tif (aria) return aria\n\n\tconst labelledBy = el.getAttribute('aria-labelledby')?.trim()\n\tif (labelledBy && el.ownerDocument) {\n\t\tconst parts = labelledBy\n\t\t\t.split(/\\s+/)\n\t\t\t.map((id) => el.ownerDocument!.getElementById(id)?.textContent?.trim())\n\t\t\t.filter(Boolean)\n\t\tif (parts.length) return parts.join(' ')\n\t}\n\n\tconst fromLabel = associatedLabelText(el)\n\tif (fromLabel) return fromLabel\n\n\tif (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n\t\tconst title = el.getAttribute('title')?.trim()\n\t\tif (title) return title\n\t\tconst placeholder = el.getAttribute('placeholder')?.trim()\n\t\tif (placeholder) return placeholder\n\t\tconst nameAttr = el.getAttribute('name')?.trim()\n\t\tif (nameAttr) return nameAttr\n\t}\n\n\tif (el instanceof HTMLSelectElement) {\n\t\tconst title = el.getAttribute('title')?.trim()\n\t\tif (title) return title\n\t\tconst nameAttr = el.getAttribute('name')?.trim()\n\t\tif (nameAttr) return nameAttr\n\t}\n\n\tif (el instanceof HTMLImageElement) {\n\t\tconst alt = el.alt?.trim()\n\t\tif (alt) return alt\n\t}\n\n\tif (\n\t\tel instanceof HTMLButtonElement ||\n\t\tel.tagName === 'A' ||\n\t\tel.getAttribute('role') === 'button'\n\t) {\n\t\tconst text = el.textContent?.replace(/\\s+/g, ' ').trim()\n\t\tif (text) return text\n\t}\n\n\tconst text = el.textContent?.replace(/\\s+/g, ' ').trim()\n\tif (text && text.length <= 80) return text\n\n\treturn undefined\n}\n\nfunction heuristicRawLabel(el: Element, role?: string, name?: string): string {\n\tif (role && name) return `${role} \"${name}\"`\n\tif (role) return role\n\tif (name) return name\n\tconst tag = el.tagName.toLowerCase()\n\tconst id = el.id ? `#${el.id}` : ''\n\treturn `${tag}${id}`\n}\n\nfunction controlValue(el: Element): string {\n\tif (el instanceof HTMLSelectElement) {\n\t\tconst selected = el.selectedOptions[0]\n\t\treturn (selected?.textContent ?? selected?.value ?? el.value ?? '').trim()\n\t}\n\tif (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n\t\treturn el.value\n\t}\n\tif (el instanceof HTMLElement && el.isContentEditable) {\n\t\treturn el.textContent ?? ''\n\t}\n\treturn ''\n}\n\nfunction namesEqual(a: string, b: string): boolean {\n\treturn a === b || a.toLowerCase() === b.toLowerCase()\n}\n\nfunction enrichFromObservation(\n\tstep: RecordedStep,\n\tcontent: string\n): Pick<RecordedStep, 'role' | 'name' | 'rawLabel'> {\n\tconst labels = parseObservationLabels(content)\n\tif (!labels.length) return {}\n\n\tconst role = step.role?.toLowerCase()\n\tconst name = step.name\n\tconst raw = step.rawLabel\n\n\t// Prefer an exact role+name hit so resolved identity is not replaced by a sibling control.\n\tif (role && name) {\n\t\tconst exact = labels.find(\n\t\t\t(row) => row.role.toLowerCase() === role && namesEqual(row.name, name)\n\t\t)\n\t\tif (exact) {\n\t\t\treturn {\n\t\t\t\trole: exact.role,\n\t\t\t\tname: exact.name,\n\t\t\t\trawLabel: exact.label || step.rawLabel,\n\t\t\t}\n\t\t}\n\t\treturn {}\n\t}\n\n\tlet match: (typeof labels)[number] | undefined\n\n\tif (role) {\n\t\tconst roleMatches = labels.filter((row) => row.role.toLowerCase() === role)\n\t\tif (roleMatches.length === 1) match = roleMatches[0]\n\t\telse if (raw) {\n\t\t\tmatch = roleMatches.find(\n\t\t\t\t(row) =>\n\t\t\t\t\tnamesEqual(row.name, raw) ||\n\t\t\t\t\trow.label.toLowerCase() === raw.toLowerCase() ||\n\t\t\t\t\t(row.name && raw.toLowerCase().includes(row.name.toLowerCase()))\n\t\t\t)\n\t\t}\n\t}\n\n\tif (!match && name) {\n\t\tconst byName = labels.filter((row) => namesEqual(row.name, name))\n\t\tif (byName.length === 1) match = byName[0]\n\t}\n\n\tif (!match && raw) {\n\t\tmatch = labels.find(\n\t\t\t(row) =>\n\t\t\t\trow.label.toLowerCase() === raw.toLowerCase() ||\n\t\t\t\t(row.name && raw.toLowerCase().includes(`\"${row.name.toLowerCase()}\"`))\n\t\t)\n\t}\n\n\tif (!match) return {}\n\n\treturn {\n\t\trole: step.role ?? match.role,\n\t\tname: step.name ?? (match.name || undefined),\n\t\trawLabel: match.label || step.rawLabel,\n\t}\n}\n\nasync function resolveIdentity(\n\tel: Element,\n\tdeps: SkillRecorderDeps\n): Promise<{ role?: string; name?: string; rawLabel?: string }> {\n\tif (deps.resolveTarget) {\n\t\ttry {\n\t\t\tconst resolved = await deps.resolveTarget(el)\n\t\t\tif (resolved) {\n\t\t\t\tconst role = resolved.role ?? heuristicRole(el)\n\t\t\t\tconst name = resolved.name ?? heuristicName(el)\n\t\t\t\treturn {\n\t\t\t\t\trole,\n\t\t\t\t\tname,\n\t\t\t\t\trawLabel: resolved.rawLabel ?? heuristicRawLabel(el, role, name),\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to heuristics.\n\t\t}\n\t}\n\n\tconst role = heuristicRole(el)\n\tconst name = heuristicName(el)\n\treturn {\n\t\trole,\n\t\tname,\n\t\trawLabel: heuristicRawLabel(el, role, name),\n\t}\n}\n\nexport function createSkillRecorder(deps: SkillRecorderDeps): {\n\tstart(): void\n\tstop(): void\n\tclear(): void\n\tgetSteps(): RecordedStep[]\n\tsetSteps(steps: RecordedStep[]): void\n\tremoveStep(id: string): void\n\ttoggleParam(id: string, param?: boolean): void\n\treadonly recording: boolean\n} {\n\tconst ignoreSelector = deps.ignoreSelector ?? DEFAULT_IGNORE\n\tlet recording = false\n\tlet steps: RecordedStep[] = []\n\tlet fillTimer: ReturnType<typeof setTimeout> | null = null\n\tlet pendingFill: { el: Element; urlHint: string } | null = null\n\tlet lastUrl = ''\n\n\tfunction rootNode(): Document | ParentNode {\n\t\treturn deps.root ?? document\n\t}\n\n\tfunction currentUrl(): string {\n\t\ttry {\n\t\t\tconst root = rootNode()\n\t\t\tconst doc = root instanceof Document ? root : root.ownerDocument\n\t\t\treturn doc?.defaultView?.location?.href ?? lastUrl ?? ''\n\t\t} catch {\n\t\t\treturn lastUrl\n\t\t}\n\t}\n\n\tfunction pushStep(partial: Omit<RecordedStep, 'id' | 'ts'> & { ts?: number }): RecordedStep {\n\t\tconst step: RecordedStep = {\n\t\t\tid: newStepId(),\n\t\t\tts: partial.ts ?? Date.now(),\n\t\t\tkind: partial.kind,\n\t\t\turl: partial.url,\n\t\t\trole: partial.role,\n\t\t\tname: partial.name,\n\t\t\tvalue: partial.value,\n\t\t\trawLabel: partial.rawLabel,\n\t\t\tparam: partial.param,\n\t\t}\n\t\tsteps = [...steps, step]\n\t\treturn step\n\t}\n\n\tfunction updateStep(id: string, patch: Partial<RecordedStep>): void {\n\t\tsteps = steps.map((step) => (step.id === id ? { ...step, ...patch, id: step.id } : step))\n\t}\n\n\tasync function enrichStep(id: string, base: RecordedStep): Promise<void> {\n\t\ttry {\n\t\t\tconst observed = await deps.observe()\n\t\t\tlastUrl = observed.url || lastUrl\n\t\t\tconst patch = enrichFromObservation(\n\t\t\t\t{ ...base, url: observed.url || base.url },\n\t\t\t\tobserved.content\n\t\t\t)\n\t\t\tupdateStep(id, {\n\t\t\t\turl: observed.url || base.url,\n\t\t\t\t...patch,\n\t\t\t})\n\t\t} catch {\n\t\t\t// Observation is best-effort enrichment.\n\t\t}\n\t}\n\n\tasync function recordClick(el: Element): Promise<void> {\n\t\tconst identity = await resolveIdentity(el, deps)\n\t\tconst step = pushStep({\n\t\t\tkind: 'click',\n\t\t\turl: currentUrl(),\n\t\t\trole: identity.role,\n\t\t\tname: identity.name,\n\t\t\trawLabel: identity.rawLabel,\n\t\t})\n\t\tvoid enrichStep(step.id, step)\n\t}\n\n\tasync function flushFill(options: { force?: boolean } = {}): Promise<void> {\n\t\tif (fillTimer) {\n\t\t\tclearTimeout(fillTimer)\n\t\t\tfillTimer = null\n\t\t}\n\t\tconst pending = pendingFill\n\t\tpendingFill = null\n\t\tif (!pending) return\n\t\tif (!options.force && !recording) return\n\t\tif (!pending.el.isConnected) return\n\n\t\tconst identity = await resolveIdentity(pending.el, deps)\n\t\tconst value = controlValue(pending.el)\n\t\tconst step = pushStep({\n\t\t\tkind: 'fill',\n\t\t\turl: pending.urlHint || currentUrl(),\n\t\t\trole: identity.role,\n\t\t\tname: identity.name,\n\t\t\trawLabel: identity.rawLabel,\n\t\t\tvalue,\n\t\t})\n\t\tvoid enrichStep(step.id, step)\n\t}\n\n\tfunction scheduleFill(el: Element): void {\n\t\tpendingFill = { el, urlHint: currentUrl() }\n\t\tif (fillTimer) clearTimeout(fillTimer)\n\t\tfillTimer = setTimeout(() => {\n\t\t\tfillTimer = null\n\t\t\tvoid flushFill()\n\t\t}, FILL_DEBOUNCE_MS)\n\t}\n\n\tasync function recordSelect(el: HTMLSelectElement): Promise<void> {\n\t\tif (pendingFill?.el === el || (pendingFill && el.contains(pendingFill.el))) {\n\t\t\tawait flushFill()\n\t\t}\n\t\tconst identity = await resolveIdentity(el, deps)\n\t\tconst value = controlValue(el)\n\t\tconst step = pushStep({\n\t\t\tkind: 'select',\n\t\t\turl: currentUrl(),\n\t\t\trole: identity.role,\n\t\t\tname: identity.name,\n\t\t\trawLabel: identity.rawLabel,\n\t\t\tvalue,\n\t\t})\n\t\tvoid enrichStep(step.id, step)\n\t}\n\n\tfunction onClick(event: Event): void {\n\t\tif (!recording || !event.isTrusted) return\n\t\tconst el = eventElement(event.target)\n\t\tif (!el || isIgnored(el, ignoreSelector)) return\n\t\tif (isTextLike(el) || isSelectControl(el)) return\n\t\tvoid recordClick(el)\n\t}\n\n\tfunction onInput(event: Event): void {\n\t\tif (!recording || !event.isTrusted) return\n\t\tconst el = eventElement(event.target)\n\t\tif (!el || isIgnored(el, ignoreSelector)) return\n\t\tif (!isTextLike(el)) return\n\t\tscheduleFill(el)\n\t}\n\n\tfunction onChange(event: Event): void {\n\t\tif (!recording || !event.isTrusted) return\n\t\tconst el = eventElement(event.target)\n\t\tif (!el || isIgnored(el, ignoreSelector)) return\n\n\t\tconst select = selectElement(el)\n\t\tif (select) {\n\t\t\tvoid recordSelect(select)\n\t\t\treturn\n\t\t}\n\n\t\tif (isTextLike(el)) {\n\t\t\tscheduleFill(el)\n\t\t}\n\t}\n\n\treturn {\n\t\tstart(): void {\n\t\t\tif (recording) return\n\t\t\trecording = true\n\t\t\tconst root = rootNode()\n\t\t\troot.addEventListener('click', onClick, true)\n\t\t\troot.addEventListener('input', onInput, true)\n\t\t\troot.addEventListener('change', onChange, true)\n\t\t},\n\t\tstop(): void {\n\t\t\tif (!recording) return\n\t\t\trecording = false\n\t\t\tconst root = rootNode()\n\t\t\troot.removeEventListener('click', onClick, true)\n\t\t\troot.removeEventListener('input', onInput, true)\n\t\t\troot.removeEventListener('change', onChange, true)\n\t\t\tvoid flushFill({ force: true })\n\t\t},\n\t\tclear(): void {\n\t\t\tif (fillTimer) {\n\t\t\t\tclearTimeout(fillTimer)\n\t\t\t\tfillTimer = null\n\t\t\t}\n\t\t\tpendingFill = null\n\t\t\tsteps = []\n\t\t},\n\t\tgetSteps(): RecordedStep[] {\n\t\t\treturn steps.map((step) => ({ ...step }))\n\t\t},\n\t\tsetSteps(next: RecordedStep[]): void {\n\t\t\tsteps = next.map((step) => ({ ...step }))\n\t\t},\n\t\tremoveStep(id: string): void {\n\t\t\tsteps = steps.filter((step) => step.id !== id)\n\t\t},\n\t\ttoggleParam(id: string, param?: boolean): void {\n\t\t\tsteps = steps.map((step) => {\n\t\t\t\tif (step.id !== id) return step\n\t\t\t\tconst next = param === undefined ? !step.param : param\n\t\t\t\treturn { ...step, param: next || undefined }\n\t\t\t})\n\t\t},\n\t\tget recording(): boolean {\n\t\t\treturn recording\n\t\t},\n\t}\n}\n","/**\n * Deterministic Skills Studio synthesizer: RecordedStep timeline → skill Markdown + skill-js.\n * Validates with parseSkillDocument before returning.\n */\nimport { parseSkillDocument } from './parse'\nimport type { RecordedStep } from './recorder'\nimport { SKILL_ID_PATTERN, type SkillManifest, SkillParseError } from './types'\n\nexport interface SynthesizeFromStepsOptions {\n\tsteps: RecordedStep[]\n\t/** Natural-language goal (Ask mode or Record annotation). */\n\tgoal?: string\n\tid?: string\n\tname?: string\n\tdescription?: string\n\t/** Primary command name. @default 'run' */\n\tcommandName?: string\n\tversion?: number\n}\n\nexport interface SynthesizeFromStepsResult {\n\tdocument: string\n\tmanifest: SkillManifest\n}\n\nfunction slugify(raw: string): string {\n\tconst slug = raw\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, '-')\n\t\t.replace(/^-+|-+$/g, '')\n\t\t.replace(/-+/g, '-')\n\tif (SKILL_ID_PATTERN.test(slug)) return slug\n\tconst prefixed = `skill-${slug}`.replace(/-+/g, '-').replace(/-$/, '')\n\tif (SKILL_ID_PATTERN.test(prefixed)) return prefixed\n\treturn 'recorded-skill'\n}\n\nfunction jsString(value: string): string {\n\treturn JSON.stringify(value)\n}\n\nfunction fieldNameFromStep(step: RecordedStep, used: Set<string>): string {\n\tconst baseRaw = (step.name || step.role || step.kind || 'value')\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, '_')\n\t\t.replace(/^_+|_+$/g, '')\n\t\t.replace(/_+/g, '_')\n\tlet base = baseRaw && /^[a-z]/.test(baseRaw) ? baseRaw : `value_${baseRaw || 'x'}`\n\tif (!base) base = 'value'\n\tlet name = base\n\tlet n = 2\n\twhile (used.has(name)) {\n\t\tname = `${base}_${n}`\n\t\tn++\n\t}\n\tused.add(name)\n\treturn name\n}\n\nfunction actionableSteps(steps: RecordedStep[]): RecordedStep[] {\n\treturn steps.filter(\n\t\t(step) => step.kind === 'click' || step.kind === 'fill' || step.kind === 'select'\n\t)\n}\n\nfunction shouldParameterize(step: RecordedStep): boolean {\n\tif (step.kind !== 'fill' && step.kind !== 'select') return false\n\tif (step.param) return true\n\tconst value = (step.value ?? '').trim()\n\tif (!value) return false\n\t// Short literals that look like entity names / emails / ids become inputs.\n\tif (value.length >= 2 && value.length <= 64) return true\n\treturn false\n}\n\nfunction queryExpr(step: RecordedStep): string {\n\tconst parts: string[] = []\n\tif (step.role) parts.push(`role: ${jsString(step.role)}`)\n\tif (step.name) parts.push(`name: ${jsString(step.name)}`)\n\tif (parts.length === 0) {\n\t\tthrow new SkillParseError(\n\t\t\t'synthesize_unresolved',\n\t\t\t`Step ${step.id} (${step.kind}) has no role/name; fix it in the Studio timeline before synthesizing`\n\t\t)\n\t}\n\treturn `{ ${parts.join(', ')} }`\n}\n\nfunction deriveAssert(steps: RecordedStep[]): string | null {\n\tconst urls = steps.map((s) => s.url).filter(Boolean)\n\tif (urls.length < 2) return null\n\tconst first = urls[0]\n\tconst last = urls[urls.length - 1]\n\tif (!last || last === first) return null\n\ttry {\n\t\tconst path = new URL(last).pathname\n\t\tif (!path || path === '/') return null\n\t\t// Prefer RegExp constructor so `/` in paths cannot open a `//` line comment.\n\t\tconst escaped = path.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\t\treturn `await ctx.assert.urlMatches(new RegExp(${jsString(escaped)}))`\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction yamlFold(text: string): string {\n\tconst clean = text.replace(/\\s+/g, ' ').trim()\n\tif (clean.length <= 70) return clean\n\treturn `>\\n ${clean}`\n}\n\n/**\n * Build a skill document from a recorded timeline.\n * Variable fill/select values become command inputs; unresolved AX steps throw.\n */\nexport function synthesizeFromSteps(\n\toptions: SynthesizeFromStepsOptions\n): SynthesizeFromStepsResult {\n\tconst steps = options.steps\n\tif (!steps.length) {\n\t\tthrow new SkillParseError(\n\t\t\t'synthesize_empty',\n\t\t\t'Cannot synthesize a skill from an empty timeline'\n\t\t)\n\t}\n\n\tconst actions = actionableSteps(steps)\n\tif (!actions.length) {\n\t\tthrow new SkillParseError(\n\t\t\t'synthesize_no_actions',\n\t\t\t'Timeline has no click/fill/select steps to turn into skill-js'\n\t\t)\n\t}\n\n\tconst goal = options.goal?.trim()\n\tconst name = options.name?.trim() || (goal ? slugify(goal) : 'recorded-flow')\n\tconst id = options.id?.trim() || slugify(name)\n\tif (!SKILL_ID_PATTERN.test(id)) {\n\t\tthrow new SkillParseError('invalid_id', `Synthesized id \"${id}\" is invalid`)\n\t}\n\n\tconst description =\n\t\toptions.description?.trim() || goal || `Replay the recorded flow (${actions.length} steps).`\n\n\tconst commandName = options.commandName?.trim() || 'run'\n\tconst version = options.version ?? 1\n\n\tconst usedFields = new Set<string>()\n\tconst inputs: { field: string; description: string; sample: string }[] = []\n\tconst lines: string[] = []\n\n\tfor (const step of actions) {\n\t\tif (step.kind === 'click') {\n\t\t\tlines.push(` await ctx.page.click(${queryExpr(step)})`)\n\t\t\tcontinue\n\t\t}\n\n\t\tif (step.kind === 'fill') {\n\t\t\tif (shouldParameterize(step)) {\n\t\t\t\tconst field = fieldNameFromStep(step, usedFields)\n\t\t\t\tinputs.push({\n\t\t\t\t\tfield,\n\t\t\t\t\tdescription: step.name ? `Value for ${step.name}` : 'Fill value',\n\t\t\t\t\tsample: step.value ?? '',\n\t\t\t\t})\n\t\t\t\tlines.push(` await ctx.page.fill(${queryExpr(step)}, ${field})`)\n\t\t\t} else {\n\t\t\t\tlines.push(` await ctx.page.fill(${queryExpr(step)}, ${jsString(step.value ?? '')})`)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif (step.kind === 'select') {\n\t\t\tif (shouldParameterize(step)) {\n\t\t\t\tconst field = fieldNameFromStep(step, usedFields)\n\t\t\t\tinputs.push({\n\t\t\t\t\tfield,\n\t\t\t\t\tdescription: step.name ? `Option for ${step.name}` : 'Select option',\n\t\t\t\t\tsample: step.value ?? '',\n\t\t\t\t})\n\t\t\t\tlines.push(` await ctx.page.select(${queryExpr(step)}, ${field})`)\n\t\t\t} else {\n\t\t\t\tlines.push(` await ctx.page.select(${queryExpr(step)}, ${jsString(step.value ?? '')})`)\n\t\t\t}\n\t\t}\n\t}\n\n\tconst assertLine = deriveAssert(steps)\n\tif (assertLine) lines.push(` ${assertLine}`)\n\n\tconst inputBlock =\n\t\tinputs.length === 0\n\t\t\t? ''\n\t\t\t: ` input: {\\n${inputs\n\t\t\t\t\t.map(\n\t\t\t\t\t\t(row) =>\n\t\t\t\t\t\t\t` ${row.field}: { type: 'string', description: ${jsString(row.description)} },`\n\t\t\t\t\t)\n\t\t\t\t\t.join('\\n')}\\n },\\n`\n\n\tconst destructure =\n\t\tinputs.length === 0 ? '_input' : `{ ${inputs.map((row) => row.field).join(', ')} }`\n\n\tconst okMessage = `Completed recorded flow \"${id}\"`\n\n\tconst whenToUse = goal\n\t\t? `- ${goal}`\n\t\t: '- Replay this recorded interaction sequence on a matching page.'\n\n\tconst document = `---\nname: ${id}\ndescription: ${yamlFold(description)}\nversion: ${version}\nid: ${id}\nscope: agent\n---\n\n# ${name}\n\n## When to use\n\n${whenToUse}\n\n## Notes\n\n- Re-find controls each run. Do not cache accessibility indexes across observes.\n- Generated from Skills Studio recording (${actions.length} actions).\n\n## Commands\n\n\\`\\`\\`skill-js\nexport const commands = {\n ${commandName}: {\n description: ${jsString(description)},\n${inputBlock} async run(ctx, ${destructure}) {\n${lines.join('\\n')}\n return ctx.ok(${jsString(okMessage)})\n },\n },\n}\n\\`\\`\\`\n`\n\n\tconst manifest = parseSkillDocument(document)\n\treturn { document, manifest }\n}\n","/**\n * SkillWatcher — same-tab scheduled skill ticks (observe/assert preferred).\n * Does not call PageAgentCore.execute; ticks go through runCommand.\n */\nimport {\n\tDEFAULT_SKILL_WATCH_INTERVAL_MS,\n\tMAX_SKILL_WATCHES,\n\tMIN_SKILL_WATCH_INTERVAL_MS,\n\tSkillParseError,\n\ttype SkillWatchEntry,\n\ttype SkillWatchSpec,\n\ttype SkillWatchTrigger,\n} from './types'\n\nexport interface SkillWatcherDeps {\n\t/** Run one skill command without taking the main execute lock. */\n\trunCommand: (skillId: string, command: string, input: Record<string, unknown>) => Promise<string>\n\tisTaskRunning: () => boolean\n\tgetUrl?: () => string\n\tonArmed?: (entry: SkillWatchEntry) => void\n\tonFired?: (detail: { id: string; skillId: string; command: string; message: string }) => void\n\tonStopped?: (detail: { id: string; skillId: string; reason: string }) => void\n\tnow?: () => number\n}\n\ninterface ArmedWatch {\n\tspec: Required<\n\t\tPick<\n\t\t\tSkillWatchSpec,\n\t\t\t'id' | 'skillId' | 'command' | 'everyMs' | 'trigger' | 'pauseWhileTaskRunning' | 'once'\n\t\t>\n\t> &\n\t\tPick<SkillWatchSpec, 'input' | 'urlIncludes'>\n\ttimer: ReturnType<typeof setInterval> | null\n\tlastFiredAt?: number\n\tlastError?: string\n\t/** For on-enter: already ran once since arm. */\n\tenterDone: boolean\n\t/** Last href seen for on-url edge detection. */\n\tlastUrl?: string\n\tticking: boolean\n}\n\nfunction normalizeSpec(spec: SkillWatchSpec): ArmedWatch['spec'] {\n\tconst everyMs = Math.max(\n\t\tMIN_SKILL_WATCH_INTERVAL_MS,\n\t\tspec.everyMs ?? DEFAULT_SKILL_WATCH_INTERVAL_MS\n\t)\n\tconst trigger: SkillWatchTrigger = spec.trigger ?? 'interval'\n\treturn {\n\t\tid: spec.id,\n\t\tskillId: spec.skillId,\n\t\tcommand: spec.command,\n\t\tinput: spec.input,\n\t\teveryMs,\n\t\ttrigger,\n\t\turlIncludes: spec.urlIncludes,\n\t\tpauseWhileTaskRunning: spec.pauseWhileTaskRunning !== false,\n\t\tonce: spec.once !== false,\n\t}\n}\n\nfunction isFireResult(message: string): boolean {\n\tconst trimmed = message.trim()\n\tif (!trimmed) return false\n\tif (trimmed.startsWith('❌')) return false\n\tif (/assert failed/i.test(trimmed)) return false\n\tif (/^⏳|waiting|not yet/i.test(trimmed)) return false\n\treturn trimmed.startsWith('✅') || /watch[_ ]?fire|detected|matched|changed/i.test(trimmed)\n}\n\nexport function createSkillWatcher(deps: SkillWatcherDeps): {\n\tarm(spec: SkillWatchSpec): SkillWatchEntry\n\tdisarm(id: string, reason?: string): boolean\n\tdisarmAll(reason?: string): void\n\tlist(): SkillWatchEntry[]\n\t/** Manual tick (tests / on-enter from Panel show). */\n\ttick(id: string): Promise<'fired' | 'skipped' | 'waiting' | 'error' | 'missing'>\n\tnotifyEnter(): void\n\tdispose(): void\n} {\n\tconst watches = new Map<string, ArmedWatch>()\n\tconst now = () => (deps.now ? deps.now() : Date.now())\n\n\tfunction toEntry(watch: ArmedWatch): SkillWatchEntry {\n\t\treturn {\n\t\t\tid: watch.spec.id,\n\t\t\tskillId: watch.spec.skillId,\n\t\t\tcommand: watch.spec.command,\n\t\t\ttrigger: watch.spec.trigger,\n\t\t\teveryMs: watch.spec.everyMs,\n\t\t\tarmed: true,\n\t\t\tlastFiredAt: watch.lastFiredAt,\n\t\t\tlastError: watch.lastError,\n\t\t}\n\t}\n\n\tfunction clearTimer(watch: ArmedWatch): void {\n\t\tif (watch.timer) {\n\t\t\tclearInterval(watch.timer)\n\t\t\twatch.timer = null\n\t\t}\n\t}\n\n\tfunction disarm(id: string, reason = 'disarmed'): boolean {\n\t\tconst watch = watches.get(id)\n\t\tif (!watch) return false\n\t\tclearTimer(watch)\n\t\twatches.delete(id)\n\t\tdeps.onStopped?.({ id, skillId: watch.spec.skillId, reason })\n\t\treturn true\n\t}\n\n\tasync function runTick(\n\t\tid: string\n\t): Promise<'fired' | 'skipped' | 'waiting' | 'error' | 'missing'> {\n\t\tconst watch = watches.get(id)\n\t\tif (!watch) return 'missing'\n\t\tif (watch.ticking) return 'skipped'\n\t\tif (watch.spec.pauseWhileTaskRunning && deps.isTaskRunning()) return 'skipped'\n\n\t\tif (watch.spec.trigger === 'on-url') {\n\t\t\tconst href = deps.getUrl?.() ?? ''\n\t\t\tconst needle = watch.spec.urlIncludes ?? ''\n\t\t\tif (needle && !href.includes(needle)) {\n\t\t\t\twatch.lastUrl = href\n\t\t\t\treturn 'skipped'\n\t\t\t}\n\t\t\tif (watch.lastUrl === href && watch.enterDone) return 'skipped'\n\t\t}\n\n\t\tif (watch.spec.trigger === 'on-enter' && watch.enterDone) return 'skipped'\n\n\t\twatch.ticking = true\n\t\ttry {\n\t\t\tconst message = await deps.runCommand(\n\t\t\t\twatch.spec.skillId,\n\t\t\t\twatch.spec.command,\n\t\t\t\twatch.spec.input ?? {}\n\t\t\t)\n\t\t\twatch.lastError = undefined\n\t\t\tif (!isFireResult(message)) {\n\t\t\t\treturn 'waiting'\n\t\t\t}\n\t\t\twatch.lastFiredAt = now()\n\t\t\twatch.enterDone = true\n\t\t\twatch.lastUrl = deps.getUrl?.() ?? watch.lastUrl\n\t\t\tdeps.onFired?.({\n\t\t\t\tid: watch.spec.id,\n\t\t\t\tskillId: watch.spec.skillId,\n\t\t\t\tcommand: watch.spec.command,\n\t\t\t\tmessage,\n\t\t\t})\n\t\t\tif (watch.spec.once) {\n\t\t\t\tdisarm(id, 'fired-once')\n\t\t\t}\n\t\t\treturn 'fired'\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\twatch.lastError = message\n\t\t\treturn 'error'\n\t\t} finally {\n\t\t\twatch.ticking = false\n\t\t}\n\t}\n\n\tfunction arm(spec: SkillWatchSpec): SkillWatchEntry {\n\t\tif (!spec.id?.trim() || !spec.skillId?.trim() || !spec.command?.trim()) {\n\t\t\tthrow new SkillParseError('invalid_watch', 'Watch requires id, skillId, and command')\n\t\t}\n\t\tif (watches.has(spec.id)) {\n\t\t\tdisarm(spec.id, 're-armed')\n\t\t}\n\t\tif (watches.size >= MAX_SKILL_WATCHES) {\n\t\t\tthrow new SkillParseError('watch_quota', `At most ${MAX_SKILL_WATCHES} watches can be armed`)\n\t\t}\n\n\t\tconst normalized = normalizeSpec(spec)\n\t\tconst watch: ArmedWatch = {\n\t\t\tspec: normalized,\n\t\t\ttimer: null,\n\t\t\tenterDone: false,\n\t\t\tticking: false,\n\t\t\tlastUrl: deps.getUrl?.(),\n\t\t}\n\t\twatches.set(normalized.id, watch)\n\n\t\tif (normalized.trigger === 'interval') {\n\t\t\twatch.timer = setInterval(() => {\n\t\t\t\tvoid runTick(normalized.id)\n\t\t\t}, normalized.everyMs)\n\t\t}\n\n\t\tconst entry = toEntry(watch)\n\t\tdeps.onArmed?.(entry)\n\n\t\tif (normalized.trigger === 'on-enter') {\n\t\t\tvoid runTick(normalized.id)\n\t\t}\n\n\t\treturn entry\n\t}\n\n\treturn {\n\t\tarm,\n\t\tdisarm,\n\t\tdisarmAll(reason = 'dispose') {\n\t\t\tfor (const id of [...watches.keys()]) disarm(id, reason)\n\t\t},\n\t\tlist() {\n\t\t\treturn [...watches.values()].map(toEntry)\n\t\t},\n\t\ttick: runTick,\n\t\tnotifyEnter() {\n\t\t\tfor (const watch of watches.values()) {\n\t\t\t\tif (watch.spec.trigger !== 'on-enter') continue\n\t\t\t\twatch.enterDone = false\n\t\t\t\tvoid runTick(watch.spec.id)\n\t\t\t}\n\t\t},\n\t\tdispose() {\n\t\t\tfor (const watch of watches.values()) clearTimer(watch)\n\t\t\twatches.clear()\n\t\t},\n\t}\n}\n\nexport type SkillWatcher = ReturnType<typeof createSkillWatcher>\n","/**\n * Copyright (C) 2025 Alibaba Group Holding Limited\n * Copyright (C) 2026 SimonLuvRamen\n * All rights reserved.\n */\nimport { InvokeError, LLM, type Tool } from '@page-agent/llms'\nimport type { BrowserState, PageController } from '@page-agent/page-controller'\nimport chalk from 'chalk'\nimport * as z from 'zod/v4'\n\nimport SYSTEM_PROMPT from './prompts/system_prompt.md?raw'\nimport {\n\tMAX_TASK_FILE_BYTES,\n\ttype PublishDocumentResult,\n\ttype RecordedStep,\n\ttype SkillAttachment,\n\ttype SkillListEntry,\n\ttype SkillWatchEntry,\n\ttype SkillWatchSpec,\n\ttype SynthesizeFromStepsOptions,\n\ttype SynthesizeFromStepsResult,\n\tcreateSkillRecorder,\n\tcreateSkillWatcher,\n\tparseSkillDocument,\n\treadTaskFileBlob,\n\tskillToolName,\n\tsynthesizeFromSteps,\n} from './skills'\nimport { SkillHost } from './skills/host'\nimport { tools } from './tools'\nimport type {\n\tAgentActivity,\n\tAgentConfig,\n\tAgentReflection,\n\tAgentStatus,\n\tAgentStepEvent,\n\tExecutionResult,\n\tHistoricalEvent,\n\tMacroToolInput,\n\tMacroToolResult,\n} from './types'\nimport { assert, fetchLlmsTxt, normalizeResponse, suppress, uid, waitFor } from './utils'\n\nexport { tool, type PageAgentTool, type ToolContext } from './tools'\nexport type * from './types'\n/** Skills protocol, runtime host, and storage helpers. */\nexport {\n\tDEFAULT_REMOTE_CACHE_TTL_MS,\n\tSKILL_COMMAND_PATTERN,\n\tSKILL_COMMAND_TIMEOUT_MS,\n\tSKILL_ID_PATTERN,\n\tSKILL_JS_FENCE,\n\tSKILL_STORAGE_KEY,\n\tSkillHost,\n\tSkillParseError,\n\tSkillRemoteError,\n\tMAX_AGENT_SKILLS,\n\tMAX_SKILL_DOCUMENT_BYTES,\n\tMAX_TASK_FILE_BYTES,\n\tcreateBrowserSkillStorage,\n\tcreateMemorySkillStorage,\n\tcreateSkillCommandAbort,\n\tcreateSkillFileStore,\n\tcreateSkillRecorder,\n\tcreateTestSkillHost,\n\tevaluateSkillCommands,\n\textractSkillJs,\n\tparseFrontmatterYaml,\n\tparseSkillDocument,\n\treadTaskFileBlob,\n\tskillToolName,\n\tsplitFrontmatter,\n\tsynthesizeFromSteps,\n\ttype PublishDocumentResult,\n\ttype SkillAttachment,\n\ttype SkillCatalogRef,\n\ttype SkillCommandDefinition,\n\ttype SkillContext,\n\ttype SkillDocumentFetch,\n\ttype SkillDocumentFetchResult,\n\ttype SkillFileStore,\n\ttype SkillInputField,\n\ttype SkillInputType,\n\ttype SkillListEntry,\n\ttype SkillManifest,\n\ttype SkillScope,\n\ttype SkillStorage,\n\ttype SkillsConfig,\n\ttype SkillsRemoteAdapter,\n\ttype RecordedStep,\n\ttype SkillRecorderDeps,\n\ttype SynthesizeFromStepsOptions,\n\ttype SynthesizeFromStepsResult,\n} from './skills'\n\nexport type PageAgentCoreConfig = AgentConfig & { pageController: PageController }\n\n/**\n * AI agent for browser automation.\n *\n * @remarks\n * ## Re-act Agent Loop\n * - step\n * - observe (gather information about current environment and context)\n * - think (LLM calling)\n * - reflection (evaluate history, generate memory, short-term planning)\n * - action (give the action to approach the next goal)\n * - act (execute the action)\n * - loop\n *\n * ## Event System\n * - `statuschange` - Agent status transitions (idle → running → completed/error/stopped)\n * - `historychange` - History events updated (persistent, part of agent memory)\n * - `activity` - Real-time activity feedback (transient, for UI only)\n * - `dispose` - Agent cleanup triggered\n * - `skills:publish` / `skills:published` / `skills:publish-failed` - Studio publish path\n * - `skills:remote-refresh` - Remote adapter catalog refresh\n * - `skills:removed` - Agent skill removed from storage\n *\n * ## Information Streams\n * 1. **History Events** (`history` array)\n * - Persistent event stream that forms agent's memory\n * - Included in LLM context across steps\n * - Types: steps, observations, user takeovers, llm errors\n *\n * 2. **Activity Events** (via `activity` event)\n * - Transient UI feedback during task execution\n * - NOT included in LLM context\n * - Types: thinking, executing, executed, retrying, error\n */\nexport class PageAgentCore extends EventTarget {\n\treadonly id = uid()\n\treadonly config: PageAgentCoreConfig & { maxSteps: number }\n\treadonly tools: typeof tools\n\t/** PageController for DOM operations */\n\treadonly pageController: PageController\n\n\ttask = ''\n\ttaskId = ''\n\t/** History events */\n\thistory: HistoricalEvent[] = []\n\t/** Whether this agent has been disposed */\n\tdisposed = false\n\n\t/**\n\t * Called when the agent needs to ask the user questions.\n\t * If unset, the `ask_user` tool will be disabled.\n\t * Implementations should reject the promise when `signal` aborts.\n\t * @example onAskUser: (q) => window.prompt(q) || ''\n\t */\n\tonAskUser?: import('./askUser').AskUserHandler\n\n\t#status: AgentStatus = 'idle'\n\t#llm: LLM\n\t/**\n\t * Task cancellation primitive: its signal reaches the LLM fetch, tools\n\t * (via `ctx.signal`) and async callbacks. Aborted only by `stop`/`dispose`\n\t * (during a task) or task setup, always WITHOUT a reason so `signal.reason`\n\t * stays a standard `AbortError`.\n\t */\n\t#abortController = new AbortController()\n\t#observations: string[] = []\n\n\t/** Resolves when the current run has fully settled. Awaited by `stop()`. */\n\t#running: Promise<void> = Promise.resolve()\n\t#lastResult: ExecutionResult | null = null\n\t#skillHost: SkillHost | null = null\n\t#skillRecorder: ReturnType<typeof createSkillRecorder> | null = null\n\t#skillWatcher: ReturnType<typeof createSkillWatcher> | null = null\n\n\t/** internal states during a single task execution */\n\t#states = {\n\t\t/** Accumulated wait time in seconds */\n\t\ttotalWaitTime: 0,\n\t\t/** For detecting navigation */\n\t\tlastURL: '',\n\t\t/** Browser state */\n\t\tbrowserState: null as BrowserState | null,\n\t}\n\n\tconstructor(config: PageAgentCoreConfig) {\n\t\tsuper()\n\n\t\tthis.config = { ...config, maxSteps: config.maxSteps ?? 40 }\n\n\t\tthis.#llm = new LLM(this.config)\n\t\tthis.tools = new Map(tools)\n\t\tthis.pageController = config.pageController\n\n\t\tthis.#llm.addEventListener('retry', (e) => {\n\t\t\tconst { attempt, maxAttempts, lastError } = (e as CustomEvent).detail\n\t\t\tthis.#emitActivity({ type: 'retrying', attempt, maxAttempts })\n\t\t\tthis.history.push({\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: String(lastError),\n\t\t\t\trawResponse: (lastError as InvokeError).rawResponse,\n\t\t\t})\n\t\t\tthis.history.push({\n\t\t\t\ttype: 'retry',\n\t\t\t\tmessage: `LLM retry attempt ${attempt} of ${maxAttempts}`,\n\t\t\t\tattempt,\n\t\t\t\tmaxAttempts,\n\t\t\t})\n\t\t\tthis.#emitHistoryChange()\n\t\t})\n\n\t\tif (this.config.customTools) {\n\t\t\tfor (const [name, tool] of Object.entries(this.config.customTools)) {\n\t\t\t\tif (tool === null) {\n\t\t\t\t\tthis.tools.delete(name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tthis.tools.set(name, tool)\n\t\t\t}\n\t\t}\n\n\t\t// On by default. Set `experimentalScriptExecutionTool: false` to remove the tool.\n\t\tif (this.config.experimentalScriptExecutionTool === false) {\n\t\t\tthis.tools.delete('execute_javascript')\n\t\t}\n\n\t\tthis.#initSkills()\n\t}\n\n\t/** Optional skills host (null when skills are not configured / hydrated). */\n\tget skillHost(): SkillHost | null {\n\t\treturn this.#skillHost\n\t}\n\n\t/**\n\t * Attach a file for the current task so skill-js can read it via `ctx.files`.\n\t * Accepts a browser `File`/`Blob` or a pre-read payload. Cleared when the task ends.\n\t */\n\tasync attachTaskFile(\n\t\tfile:\n\t\t\t| (Blob & { name?: string })\n\t\t\t| {\n\t\t\t\t\tname: string\n\t\t\t\t\tmimeType?: string\n\t\t\t\t\ttext?: string\n\t\t\t\t\tdataBase64?: string\n\t\t\t\t\tsize?: number\n\t\t\t }\n\t): Promise<SkillAttachment> {\n\t\tif (!this.#skillHost) {\n\t\t\tthrow new Error('Task file attachments are unavailable because skills are disabled.')\n\t\t}\n\t\tif (typeof Blob !== 'undefined' && file instanceof Blob) {\n\t\t\tconst payload = await readTaskFileBlob(file)\n\t\t\treturn this.#skillHost.files.add(payload)\n\t\t}\n\t\tconst plain = file as {\n\t\t\tname: string\n\t\t\tmimeType?: string\n\t\t\ttext?: string\n\t\t\tdataBase64?: string\n\t\t\tsize?: number\n\t\t}\n\t\tif (!plain.name?.trim()) throw new Error('Attachment name is required')\n\t\tif (plain.text === undefined && plain.dataBase64 === undefined) {\n\t\t\tthrow new Error('Attachment needs text or dataBase64 content')\n\t\t}\n\t\tconst size =\n\t\t\tplain.size ??\n\t\t\t(plain.text !== undefined\n\t\t\t\t? new TextEncoder().encode(plain.text).length\n\t\t\t\t: Math.ceil(((plain.dataBase64?.length ?? 0) * 3) / 4))\n\t\tif (size > MAX_TASK_FILE_BYTES) {\n\t\t\tthrow new Error(`File \"${plain.name}\" is too large (max ${MAX_TASK_FILE_BYTES} bytes)`)\n\t\t}\n\t\treturn this.#skillHost.files.add({\n\t\t\tname: plain.name.trim(),\n\t\t\tmimeType: plain.mimeType || 'application/octet-stream',\n\t\t\ttext: plain.text,\n\t\t\tdataBase64: plain.dataBase64,\n\t\t\tsize,\n\t\t})\n\t}\n\n\t/** List files attached for the current task (for panel chips / debugging). */\n\tlistTaskFiles(): SkillAttachment[] {\n\t\treturn this.#skillHost?.files.list() ?? []\n\t}\n\n\t/** Remove one attached file before the task ends. */\n\tremoveTaskFile(id: string): boolean {\n\t\treturn this.#skillHost?.files.remove(id) ?? false\n\t}\n\n\t/**\n\t * Publish a skill document: local save first, then optional remote.put.\n\t * Dispatches `skills:publish`, then `skills:published` or `skills:publish-failed`.\n\t * On remote failure the local copy is kept and `skills:publish-failed` fires with `remote: true`.\n\t */\n\tasync publishSkill(document: string, source?: string): Promise<PublishDocumentResult> {\n\t\tif (!this.#skillHost) {\n\t\t\tthrow new Error('Skills are disabled.')\n\t\t}\n\n\t\tlet manifestSummary: {\n\t\t\tid: string\n\t\t\tname: string\n\t\t\tdescription: string\n\t\t\tversion: number\n\t\t}\n\t\ttry {\n\t\t\tconst manifest = parseSkillDocument(document)\n\t\t\tmanifestSummary = {\n\t\t\t\tid: manifest.id,\n\t\t\t\tname: manifest.name,\n\t\t\t\tdescription: manifest.description,\n\t\t\t\tversion: manifest.version,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.dispatchEvent(\n\t\t\t\tnew CustomEvent('skills:publish-failed', {\n\t\t\t\t\tdetail: { error: message, remote: false },\n\t\t\t\t})\n\t\t\t)\n\t\t\tthrow error\n\t\t}\n\n\t\tthis.dispatchEvent(\n\t\t\tnew CustomEvent('skills:publish', {\n\t\t\t\tdetail: { document, manifest: manifestSummary, source },\n\t\t\t})\n\t\t)\n\n\t\ttry {\n\t\t\tconst result = await this.#skillHost.publishDocument(document)\n\t\t\tif (result.remoteError) {\n\t\t\t\tthis.dispatchEvent(\n\t\t\t\t\tnew CustomEvent('skills:publish-failed', {\n\t\t\t\t\t\tdetail: {\n\t\t\t\t\t\t\tid: result.id,\n\t\t\t\t\t\t\terror: result.remoteError,\n\t\t\t\t\t\t\tremote: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\treturn result\n\t\t\t}\n\t\t\tthis.dispatchEvent(\n\t\t\t\tnew CustomEvent('skills:published', {\n\t\t\t\t\tdetail: {\n\t\t\t\t\t\tid: result.id,\n\t\t\t\t\t\tversion: result.version,\n\t\t\t\t\t\tdocument: result.document,\n\t\t\t\t\t\tremote: Boolean(result.remote),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t)\n\t\t\treturn result\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.dispatchEvent(\n\t\t\t\tnew CustomEvent('skills:publish-failed', {\n\t\t\t\t\tdetail: {\n\t\t\t\t\t\tid: manifestSummary.id,\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tremote: false,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t)\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/**\n\t * Refresh remote adapter catalog into the host. Dispatches `skills:remote-refresh`.\n\t */\n\tasync refreshRemoteSkills(options?: {\n\t\tforce?: boolean\n\t}): Promise<{ ids: string[]; fromCache: boolean }> {\n\t\tif (!this.#skillHost) {\n\t\t\treturn { ids: [], fromCache: false }\n\t\t}\n\t\tconst result = await this.#skillHost.refreshRemote(options)\n\t\tthis.dispatchEvent(\n\t\t\tnew CustomEvent('skills:remote-refresh', {\n\t\t\t\tdetail: { ids: result.ids, fromCache: result.fromCache },\n\t\t\t})\n\t\t)\n\t\treturn result\n\t}\n\n\t/**\n\t * Remove an agent-authored skill from storage + catalog.\n\t * Dispatches `skills:removed` on success.\n\t */\n\tasync removeAgentSkill(id: string): Promise<string> {\n\t\tif (!this.#skillHost) {\n\t\t\tthrow new Error('Skills are disabled.')\n\t\t}\n\t\tconst result = await this.#skillHost.removeAgentSkill(id)\n\t\tthis.dispatchEvent(new CustomEvent('skills:removed', { detail: { id } }))\n\t\treturn result\n\t}\n\n\t/** Ensure a SkillHost exists for Studio (unless skills were explicitly disabled). */\n\t#ensureSkillHost(): SkillHost {\n\t\tif (this.#skillHost) return this.#skillHost\n\t\tif (this.config.skills?.enabled === false) {\n\t\t\tthrow new Error('Skills are disabled.')\n\t\t}\n\t\tconst host = new SkillHost({\n\t\t\ttools: this.tools,\n\t\t\tpageController: this.pageController,\n\t\t\tconfig: { ...(this.config.skills ?? {}), enabled: true },\n\t\t\tgetSignal: () => this.#abortController.signal,\n\t\t\tgetOnAskUser: () => this.onAskUser,\n\t\t})\n\t\thost.attachAgentTools()\n\t\tthis.#skillHost = host\n\t\tvoid host.hydrate().catch((error) => {\n\t\t\tconsole.warn('[PageAgent] skills hydrate failed', error)\n\t\t})\n\t\treturn host\n\t}\n\n\t/** Start capturing trusted page interactions for Skills Studio Record. */\n\tasync startSkillRecording(): Promise<void> {\n\t\tthis.#ensureSkillHost()\n\t\tif (this.#skillRecorder?.recording) return\n\t\tawait suppress(() => this.pageController.hideMask())\n\t\tif (!this.#skillRecorder) {\n\t\t\tthis.#skillRecorder = createSkillRecorder({\n\t\t\t\tobserve: async () => {\n\t\t\t\t\tconst state = await this.pageController.getBrowserState()\n\t\t\t\t\treturn { url: state.url, content: state.content }\n\t\t\t\t},\n\t\t\t\troot: typeof document !== 'undefined' ? document : undefined,\n\t\t\t})\n\t\t}\n\t\tthis.#skillRecorder.start()\n\t\tthis.dispatchEvent(new CustomEvent('skills:recording', { detail: { recording: true } }))\n\t}\n\n\t/** Stop capturing interactions (keeps the current timeline). */\n\tstopSkillRecording(): void {\n\t\tif (!this.#skillRecorder) return\n\t\tthis.#skillRecorder.stop()\n\t\tthis.dispatchEvent(new CustomEvent('skills:recording', { detail: { recording: false } }))\n\t}\n\n\tisSkillRecording(): boolean {\n\t\treturn Boolean(this.#skillRecorder?.recording)\n\t}\n\n\tgetRecordedSteps(): RecordedStep[] {\n\t\treturn this.#skillRecorder?.getSteps() ?? []\n\t}\n\n\tsetRecordedSteps(steps: RecordedStep[]): void {\n\t\tif (!this.#skillRecorder) {\n\t\t\tthis.#skillRecorder = createSkillRecorder({\n\t\t\t\tobserve: async () => {\n\t\t\t\t\tconst state = await this.pageController.getBrowserState()\n\t\t\t\t\treturn { url: state.url, content: state.content }\n\t\t\t\t},\n\t\t\t\troot: typeof document !== 'undefined' ? document : undefined,\n\t\t\t})\n\t\t}\n\t\tthis.#skillRecorder.setSteps(steps)\n\t}\n\n\tremoveRecordedStep(id: string): void {\n\t\tthis.#skillRecorder?.removeStep(id)\n\t}\n\n\ttoggleRecordedStepParam(id: string, param?: boolean): void {\n\t\tthis.#skillRecorder?.toggleParam(id, param)\n\t}\n\n\tclearRecordedSteps(): void {\n\t\tthis.#skillRecorder?.clear()\n\t}\n\n\t/** Deterministic timeline → skill document (validated via parseSkillDocument). */\n\tsynthesizeSkill(\n\t\toptions: Omit<SynthesizeFromStepsOptions, 'steps'> = {}\n\t): SynthesizeFromStepsResult {\n\t\tconst steps = this.getRecordedSteps()\n\t\treturn synthesizeFromSteps({ ...options, steps })\n\t}\n\n\tlistSkillsCatalog(query?: string): SkillListEntry[] {\n\t\treturn this.#ensureSkillHost().list(query)\n\t}\n\n\tasync loadSkill(id: string): Promise<string> {\n\t\treturn this.#ensureSkillHost().load(id)\n\t}\n\n\tunloadSkill(id?: string): void {\n\t\tthis.#ensureSkillHost().unload(id)\n\t}\n\n\t/**\n\t * Load a skill and execute its primary command (`run` or the first command).\n\t * Returns the tool output string.\n\t */\n\tasync testSkill(id: string, input: Record<string, unknown> = {}): Promise<string> {\n\t\tconst host = this.#ensureSkillHost()\n\t\tawait host.load(id)\n\t\tconst entry = host.list().find((row) => row.id === id)\n\t\tconst commands = entry?.commands ?? []\n\t\tconst commandName = commands.find((c) => c.name === 'run')?.name ?? commands[0]?.name\n\t\tif (!commandName) {\n\t\t\tthrow new Error(`Skill \"${id}\" has no commands to test`)\n\t\t}\n\t\tconst toolName = `skill__${id}__${commandName}`\n\t\tconst tool = this.tools.get(toolName)\n\t\tif (!tool) {\n\t\t\tthrow new Error(`Tool \"${toolName}\" is not registered after load`)\n\t\t}\n\t\tconst result = await tool.execute.call(this, input, {\n\t\t\tsignal: this.#abortController.signal,\n\t\t})\n\t\treturn typeof result === 'string' ? result : String(result ?? '')\n\t}\n\n\t#ensureSkillWatcher(): ReturnType<typeof createSkillWatcher> {\n\t\tif (this.#skillWatcher) return this.#skillWatcher\n\t\tthis.#ensureSkillHost()\n\t\tthis.#skillWatcher = createSkillWatcher({\n\t\t\trunCommand: async (skillId, command, input) => {\n\t\t\t\tawait this.loadSkill(skillId)\n\t\t\t\tconst toolName = skillToolName(skillId, command)\n\t\t\t\tconst tool = this.tools.get(toolName)\n\t\t\t\tif (!tool) {\n\t\t\t\t\tthrow new Error(`Watch tool \"${toolName}\" is not registered`)\n\t\t\t\t}\n\t\t\t\tconst result = await tool.execute.call(this, input, {\n\t\t\t\t\tsignal: this.#abortController.signal,\n\t\t\t\t})\n\t\t\t\treturn typeof result === 'string' ? result : String(result ?? '')\n\t\t\t},\n\t\t\tisTaskRunning: () => this.#status === 'running',\n\t\t\tgetUrl: () => {\n\t\t\t\ttry {\n\t\t\t\t\treturn typeof location !== 'undefined' ? location.href : ''\n\t\t\t\t} catch {\n\t\t\t\t\treturn ''\n\t\t\t\t}\n\t\t\t},\n\t\t\tonArmed: (entry) => {\n\t\t\t\tthis.dispatchEvent(new CustomEvent('skills:watch-armed', { detail: entry }))\n\t\t\t},\n\t\t\tonFired: (detail) => {\n\t\t\t\tthis.dispatchEvent(new CustomEvent('skills:watch-fired', { detail }))\n\t\t\t\tthis.#emitHistoryChange({\n\t\t\t\t\ttype: 'observation',\n\t\t\t\t\tcontent: `Watch fired (${detail.skillId}/${detail.command}): ${detail.message}`,\n\t\t\t\t})\n\t\t\t},\n\t\t\tonStopped: (detail) => {\n\t\t\t\tthis.dispatchEvent(new CustomEvent('skills:watch-stopped', { detail }))\n\t\t\t},\n\t\t})\n\t\treturn this.#skillWatcher\n\t}\n\n\tarmSkillWatch(spec: SkillWatchSpec): SkillWatchEntry {\n\t\treturn this.#ensureSkillWatcher().arm(spec)\n\t}\n\n\tdisarmSkillWatch(id: string): boolean {\n\t\treturn this.#skillWatcher?.disarm(id) ?? false\n\t}\n\n\tlistSkillWatches(): SkillWatchEntry[] {\n\t\treturn this.#skillWatcher?.list() ?? []\n\t}\n\n\t/** Re-run on-enter watches (call when the panel is shown). */\n\tnotifySkillWatchEnter(): void {\n\t\tthis.#skillWatcher?.notifyEnter()\n\t}\n\n\t#initSkills(): void {\n\t\tconst skillsConfig = this.config.skills\n\t\tif (skillsConfig?.enabled === false) return\n\n\t\tconst host = new SkillHost({\n\t\t\ttools: this.tools,\n\t\t\tpageController: this.pageController,\n\t\t\tconfig: skillsConfig ?? {},\n\t\t\tgetSignal: () => this.#abortController.signal,\n\t\t\tgetOnAskUser: () => this.onAskUser,\n\t\t})\n\t\tthis.#skillHost = host\n\n\t\tif (skillsConfig) {\n\t\t\thost.attachAgentTools()\n\t\t}\n\n\t\t// Agent-authored skills in storage also enable list/load without config.catalog.\n\t\tvoid host.hydrate().catch((error) => {\n\t\t\tconsole.warn('[PageAgent] skills hydrate failed', error)\n\t\t})\n\t}\n\n\t#resetSkillsForTaskEnd(): void {\n\t\tthis.#skillHost?.resetTask()\n\t}\n\n\t/** Get current agent status */\n\tget status(): AgentStatus {\n\t\treturn this.#status\n\t}\n\n\t/** Result of the most recent run, or `null` before the first run completes. */\n\tget lastResult(): ExecutionResult | null {\n\t\treturn this.#lastResult\n\t}\n\n\t/** Emit statuschange event */\n\t#emitStatusChange(): void {\n\t\tthis.dispatchEvent(new Event('statuschange'))\n\t}\n\n\t/** Emit historychange event */\n\t#emitHistoryChange(pushHistoricalEvent?: HistoricalEvent): void {\n\t\tif (pushHistoricalEvent) this.history.push(pushHistoricalEvent)\n\t\tthis.dispatchEvent(new Event('historychange'))\n\t}\n\n\t/**\n\t * Emit activity event - for transient UI feedback\n\t * @param activity - Current agent activity\n\t */\n\t#emitActivity(activity: AgentActivity): void {\n\t\tthis.dispatchEvent(new CustomEvent('activity', { detail: activity }))\n\t}\n\n\t/** Update status and emit event */\n\t#setStatus(status: AgentStatus): void {\n\t\tif (this.#status !== status) {\n\t\t\tthis.#status = status\n\t\t\tthis.#emitStatusChange()\n\t\t}\n\t}\n\n\t/**\n\t * Push an observation message to the history event stream.\n\t * This will be visible in <agent_history> and remain persistent in memory across steps.\n\t * @experimental @internal\n\t * @note history change will be emitted before next step starts\n\t */\n\tpushObservation(content: string): void {\n\t\tthis.#observations.push(content)\n\t}\n\n\t/**\n\t * Stop the current task and wait until the run has fully settled (including lifecycle hooks).\n\t * @note never await .stop() in a lifecycle hook.\n\t */\n\tasync stop(): Promise<void> {\n\t\tif (this.#status !== 'running') return\n\t\tthis.#abortController.abort()\n\t\tawait this.#running\n\t}\n\n\t/**\n\t * external errors (pre-checks/config/hooks) will threw;\n\t * agent errors will be caught and added to history, and return a failed result\n\t */\n\tasync execute(task: string): Promise<ExecutionResult> {\n\t\t// pre-checks\n\t\tif (this.disposed) throw new Error('PageAgent has been disposed. Create a new instance.')\n\t\tif (this.#status === 'running') throw new Error('A task is already running.')\n\t\tif (!task) throw new Error('Task is required')\n\n\t\tthis.task = task\n\t\tthis.taskId = uid()\n\n\t\tthis.history = []\n\t\tthis.#observations = []\n\t\tthis.#states = { totalWaitTime: 0, lastURL: '', browserState: null }\n\t\tthis.#abortController = new AbortController()\n\t\tconst signal = this.#abortController.signal\n\n\t\tlet resolveRunning!: () => void\n\t\tthis.#running = new Promise<void>((r) => (resolveRunning = r))\n\n\t\tthis.#setStatus('running')\n\t\tthis.#emitHistoryChange()\n\n\t\t// Disable ask_user tool if onAskUser is not set\n\t\tif (!this.onAskUser) this.tools.delete('ask_user')\n\n\t\tconst onBeforeStep = this.config.onBeforeStep\n\t\tconst onAfterStep = this.config.onAfterStep\n\t\tconst onBeforeTask = this.config.onBeforeTask\n\t\tconst onAfterTask = this.config.onAfterTask\n\t\tconst stepDelay = this.config.stepDelay ?? 0.4\n\t\tconst maxSteps = this.config.maxSteps\n\n\t\tlet step = 0\n\t\tlet taskResult: ExecutionResult\n\t\tlet finalStatus: AgentStatus = 'error'\n\n\t\tawait suppress(() => this.pageController.showMask())\n\n\t\t// graceful exit\n\t\ttry {\n\t\t\tawait onBeforeTask?.(this)\n\n\t\t\twhile (true) {\n\t\t\t\tawait onBeforeStep?.(this, step)\n\n\t\t\t\t// handle internal agent errors\n\t\t\t\ttry {\n\t\t\t\t\tconsole.group(`step: ${step}`)\n\n\t\t\t\t\t// @note It's convenient to treat stepDelay as part of the next step.\n\t\t\t\t\t// Maybe move it to a dedicated try block for better semantics?\n\t\t\t\t\tif (step > 0) await waitFor(stepDelay, signal)\n\n\t\t\t\t\tsignal.throwIfAborted()\n\n\t\t\t\t\t// observe\n\n\t\t\t\t\tconsole.log(chalk.blue.bold('👀 Observing...'))\n\n\t\t\t\t\tthis.#states.browserState = await this.pageController.getBrowserState()\n\t\t\t\t\tawait this.#handleObservations(step)\n\n\t\t\t\t\t// assemble prompts\n\n\t\t\t\t\tconst messages = [\n\t\t\t\t\t\t{ role: 'system' as const, content: this.#getSystemPrompt() },\n\t\t\t\t\t\t{ role: 'user' as const, content: await this.#assembleUserPrompt() },\n\t\t\t\t\t]\n\n\t\t\t\t\tconst macroTool = { AgentOutput: this.#packMacroTool() }\n\n\t\t\t\t\t// invoke LLM\n\n\t\t\t\t\tconsole.log(chalk.blue.bold('🧠 Thinking...'))\n\t\t\t\t\tthis.#emitActivity({ type: 'thinking' })\n\n\t\t\t\t\tconst result = await this.#llm.invoke(messages, macroTool, signal, {\n\t\t\t\t\t\ttoolChoiceName: 'AgentOutput',\n\t\t\t\t\t\tnormalizeResponse: (res) => normalizeResponse(res, this.tools),\n\t\t\t\t\t})\n\n\t\t\t\t\t// assemble history\n\n\t\t\t\t\tconst macroResult = result.toolResult as MacroToolResult\n\t\t\t\t\tconst input = macroResult.input\n\t\t\t\t\tconst output = macroResult.output\n\t\t\t\t\tconst reflection: Partial<AgentReflection> = {\n\t\t\t\t\t\tevaluation_previous_goal: input.evaluation_previous_goal,\n\t\t\t\t\t\tmemory: input.memory,\n\t\t\t\t\t\tnext_goal: input.next_goal,\n\t\t\t\t\t}\n\t\t\t\t\tconst actionName = Object.keys(input.action)[0]\n\t\t\t\t\tconst action: AgentStepEvent['action'] = {\n\t\t\t\t\t\tname: actionName,\n\t\t\t\t\t\tinput: input.action[actionName],\n\t\t\t\t\t\toutput: output,\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.#emitHistoryChange({\n\t\t\t\t\t\ttype: 'step',\n\t\t\t\t\t\tstepIndex: step,\n\t\t\t\t\t\treflection,\n\t\t\t\t\t\taction,\n\t\t\t\t\t\tusage: result.usage,\n\t\t\t\t\t\trawResponse: result.rawResponse,\n\t\t\t\t\t\trawRequest: result.rawRequest,\n\t\t\t\t\t})\n\n\t\t\t\t\tif (actionName === 'done') {\n\t\t\t\t\t\tconst success = action.input?.success ?? false\n\t\t\t\t\t\tconst data = action.input?.text || 'no text provided'\n\t\t\t\t\t\tconsole.log(chalk.green.bold('Task completed'), success, data)\n\t\t\t\t\t\ttaskResult = { success, data, history: this.history }\n\t\t\t\t\t\tthis.#lastResult = taskResult\n\t\t\t\t\t\tfinalStatus = 'completed'\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t// catch block must not throw error. otherwise the error may be overridden if finally block also throws error.\n\n\t\t\t\t\tconst isAbortError = (error as any)?.name === 'AbortError'\n\t\t\t\t\tif (!isAbortError) console.error('Task failed', error)\n\t\t\t\t\tconst message = isAbortError ? 'Task aborted' : String(error)\n\t\t\t\t\tthis.#emitActivity({ type: 'error', message: message })\n\t\t\t\t\tthis.#emitHistoryChange({ type: 'error', message: message, rawResponse: error })\n\t\t\t\t\ttaskResult = { success: false, data: message, history: this.history }\n\t\t\t\t\tthis.#lastResult = taskResult\n\t\t\t\t\tfinalStatus = isAbortError ? 'stopped' : 'error'\n\t\t\t\t\tbreak\n\t\t\t\t} finally {\n\t\t\t\t\t// finally block runs before the break above.\n\n\t\t\t\t\tconsole.groupEnd()\n\t\t\t\t\t// @note hook may throw error.\n\t\t\t\t\t// which will override the `break` above and be handled as an external error.\n\t\t\t\t\t// as expected.\n\t\t\t\t\tawait onAfterStep?.(this, this.history)\n\t\t\t\t}\n\n\t\t\t\tstep++\n\t\t\t\tif (step > maxSteps) {\n\t\t\t\t\tconst message = 'Step count exceeded maximum limit'\n\t\t\t\t\tconsole.error(message)\n\t\t\t\t\tthis.#emitActivity({ type: 'error', message: message })\n\t\t\t\t\tthis.#emitHistoryChange({ type: 'error', message: message })\n\t\t\t\t\ttaskResult = { success: false, data: message, history: this.history }\n\t\t\t\t\tthis.#lastResult = taskResult\n\t\t\t\t\tfinalStatus = 'error'\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} // while\n\n\t\t\tawait onAfterTask?.(this, taskResult)\n\n\t\t\treturn taskResult\n\t\t} catch (error) {\n\t\t\tthis.#emitActivity({ type: 'error', message: String(error) })\n\t\t\tfinalStatus = 'error'\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tthis.#resetSkillsForTaskEnd()\n\t\t\tawait suppress(() => this.pageController.cleanUpHighlights())\n\t\t\tawait suppress(() => this.pageController.hideMask())\n\t\t\tthis.#abortController.abort()\n\t\t\tresolveRunning()\n\t\t\tthis.#setStatus(finalStatus)\n\t\t}\n\t}\n\n\t/**\n\t * Merge all tools into a single MacroTool with the following input:\n\t * - thinking: string\n\t * - evaluation_previous_goal: string\n\t * - memory: string\n\t * - next_goal: string\n\t * - action: { toolName: toolInput }\n\t * where action must be selected from tools defined in this.tools\n\t */\n\t#packMacroTool(): Tool<MacroToolInput, MacroToolResult> {\n\t\tconst tools = this.tools\n\n\t\tconst actionSchemas = Array.from(tools.entries()).map(([toolName, tool]) => {\n\t\t\treturn z.object({ [toolName]: tool.inputSchema }).describe(tool.description)\n\t\t})\n\n\t\tconst actionSchema = z.union(actionSchemas as unknown as [z.ZodType, z.ZodType, ...z.ZodType[]])\n\n\t\tconst macroToolSchema = z.object({\n\t\t\t// thinking: z.string().optional(),\n\t\t\tevaluation_previous_goal: z.string().optional(),\n\t\t\tmemory: z.string().optional(),\n\t\t\tnext_goal: z.string().optional(),\n\t\t\taction: actionSchema,\n\t\t})\n\n\t\treturn {\n\t\t\tdescription: 'You MUST call this tool every step!',\n\t\t\tinputSchema: macroToolSchema as z.ZodType<MacroToolInput>,\n\t\t\texecute: async (input: MacroToolInput): Promise<MacroToolResult> => {\n\t\t\t\tconst signal = this.#abortController.signal\n\t\t\t\tsignal.throwIfAborted()\n\n\t\t\t\tconsole.log(chalk.blue.bold('MacroTool input'), input)\n\t\t\t\tconst action = input.action\n\n\t\t\t\tconst toolName = Object.keys(action)[0]\n\t\t\t\tconst toolInput = action[toolName]\n\n\t\t\t\t// Build reflection text, only include non-empty fields\n\t\t\t\tconst reflectionLines: string[] = []\n\t\t\t\tif (input.evaluation_previous_goal)\n\t\t\t\t\treflectionLines.push(`✅: ${input.evaluation_previous_goal}`)\n\t\t\t\tif (input.memory) reflectionLines.push(`💾: ${input.memory}`)\n\t\t\t\tif (input.next_goal) reflectionLines.push(`🎯: ${input.next_goal}`)\n\n\t\t\t\tconst reflectionText = reflectionLines.length > 0 ? reflectionLines.join('\\n') : ''\n\n\t\t\t\tif (reflectionText) {\n\t\t\t\t\tconsole.log(reflectionText)\n\t\t\t\t}\n\n\t\t\t\t// Find the corresponding tool\n\t\t\t\tconst tool = tools.get(toolName)\n\t\t\t\tassert(tool, `Tool ${toolName} not found`)\n\n\t\t\t\tconsole.log(chalk.blue.bold(`Executing tool: ${toolName}`), toolInput)\n\n\t\t\t\t// Emit executing activity\n\t\t\t\tthis.#emitActivity({ type: 'executing', tool: toolName, input: toolInput })\n\n\t\t\t\tconst startTime = Date.now()\n\n\t\t\t\tconst result = await tool.execute.bind(this)(toolInput, { signal })\n\t\t\t\t// Enforce abort even if the tool ignored the signal and resolved normally.\n\t\t\t\tsignal.throwIfAborted()\n\n\t\t\t\tconst duration = Date.now() - startTime\n\t\t\t\tconsole.log(chalk.green.bold(`Tool (${toolName}) executed for ${duration}ms`), result)\n\n\t\t\t\t// Emit executed activity\n\t\t\t\tthis.#emitActivity({\n\t\t\t\t\ttype: 'executed',\n\t\t\t\t\ttool: toolName,\n\t\t\t\t\tinput: toolInput,\n\t\t\t\t\toutput: result,\n\t\t\t\t\tduration,\n\t\t\t\t})\n\n\t\t\t\t// counting wait time\n\t\t\t\tif (toolName === 'wait') {\n\t\t\t\t\tthis.#states.totalWaitTime += toolInput?.seconds || 0\n\t\t\t\t} else {\n\t\t\t\t\tthis.#states.totalWaitTime = 0\n\t\t\t\t}\n\n\t\t\t\t// Return structured result\n\t\t\t\treturn {\n\t\t\t\t\tinput,\n\t\t\t\t\toutput: result,\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t}\n\n\t/**\n\t * Get system prompt, dynamically replace language settings based on configured language.\n\t *\n\t * REVERSIBLE (2026-11-23, system prompt override): a custom prompt is added to the built-in one. It\n\t * replaces it only with `overrideSystemPrompt: true`, so the built-in rules are never lost by accident.\n\t */\n\t#getSystemPrompt(): string {\n\t\tconst custom = this.config.customSystemPrompt\n\t\tif (custom?.trim() && this.config.overrideSystemPrompt === true) {\n\t\t\treturn custom\n\t\t}\n\n\t\tconst targetLanguage = this.config.language === 'zh-CN' ? '中文' : 'English'\n\t\tconst systemPrompt = SYSTEM_PROMPT.replace(\n\t\t\t/Default working language: \\*\\*.*?\\*\\*/,\n\t\t\t`Default working language: **${targetLanguage}**`\n\t\t)\n\n\t\tif (!custom?.trim()) return systemPrompt\n\t\treturn `${systemPrompt}\\n\\n<additional_instructions>\\n${custom.trim()}\\n</additional_instructions>`\n\t}\n\n\t/**\n\t * Get instructions from config\n\t */\n\tasync #getInstructions(): Promise<string> {\n\t\tconst { instructions, experimentalLlmsTxt } = this.config\n\n\t\tconst systemInstructions = instructions?.system?.trim()\n\t\tlet pageInstructions: string | undefined\n\n\t\tconst url = this.#states.browserState?.url || ''\n\t\tif (instructions?.getPageInstructions && url) {\n\t\t\ttry {\n\t\t\t\tpageInstructions = instructions.getPageInstructions(url)?.trim()\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\n\t\t\t\t\tchalk.red('[PageAgent] Failed to execute getPageInstructions callback:'),\n\t\t\t\t\terror\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst llmsTxt = experimentalLlmsTxt && url ? await fetchLlmsTxt(url) : undefined\n\n\t\tif (!systemInstructions && !pageInstructions && !llmsTxt) return ''\n\n\t\tlet result = '<instructions>\\n'\n\n\t\tif (systemInstructions) {\n\t\t\tresult += `<system_instructions>\\n${systemInstructions}\\n</system_instructions>\\n`\n\t\t}\n\n\t\tif (pageInstructions) {\n\t\t\tresult += `<page_instructions>\\n${pageInstructions}\\n</page_instructions>\\n`\n\t\t}\n\n\t\tif (llmsTxt) {\n\t\t\tresult += `<llms_txt>\\n${llmsTxt}\\n</llms_txt>\\n`\n\t\t}\n\n\t\tresult += '</instructions>\\n\\n'\n\n\t\treturn result\n\t}\n\n\t/**\n\t * Generate system observations before each step\n\t * @todo loop detection\n\t * @todo console error\n\t */\n\tasync #handleObservations(step: number): Promise<void> {\n\t\t// Accumulated wait time warning\n\t\tif (this.#states.totalWaitTime >= 3) {\n\t\t\tthis.pushObservation(\n\t\t\t\t`You have waited ${this.#states.totalWaitTime} seconds accumulatively. ` +\n\t\t\t\t\t`DO NOT wait any longer unless you have a good reason.`\n\t\t\t)\n\t\t}\n\n\t\t// Detect URL change\n\t\tconst currentURL = this.#states.browserState?.url || ''\n\t\tif (currentURL !== this.#states.lastURL) {\n\t\t\tthis.pushObservation(`Page navigated to → ${currentURL}`)\n\t\t\tthis.#states.lastURL = currentURL\n\t\t\tawait waitFor(0.5) // wait for page to stabilize\n\t\t}\n\n\t\t// Remaining steps warning\n\t\tconst remaining = this.config.maxSteps - step\n\t\tif (remaining === 5) {\n\t\t\tthis.pushObservation(\n\t\t\t\t`⚠️ Only ${remaining} steps remaining. ` +\n\t\t\t\t\t`Consider wrapping up or calling done with partial results.`\n\t\t\t)\n\t\t} else if (remaining === 2) {\n\t\t\tthis.pushObservation(\n\t\t\t\t`⚠️ Critical: Only ${remaining} steps left! You must finish the task or call done immediately.`\n\t\t\t)\n\t\t}\n\n\t\t// Push observations to history and emit\n\t\tif (this.#observations.length > 0) {\n\t\t\tfor (const content of this.#observations) {\n\t\t\t\tthis.history.push({ type: 'observation', content })\n\t\t\t\tconsole.log(chalk.cyan('Observation:'), content)\n\t\t\t}\n\t\t\tthis.#observations = []\n\t\t\tthis.#emitHistoryChange()\n\t\t}\n\t}\n\n\tasync #assembleUserPrompt(): Promise<string> {\n\t\tconst browserState = this.#states.browserState!\n\n\t\tlet prompt = ''\n\n\t\t// <instructions> (optional)\n\n\t\tprompt += await this.#getInstructions()\n\n\t\t// <agent_state>\n\t\t// - <user_request>\n\t\t// - <step_info>\n\t\t// <agent_state>\n\n\t\tconst stepCount = this.history.filter((e) => e.type === 'step').length\n\n\t\tprompt += '<agent_state>\\n'\n\t\tprompt += '<user_request>\\n'\n\t\tprompt += `${this.task}\\n`\n\t\tprompt += '</user_request>\\n'\n\t\tprompt += '<step_info>\\n'\n\t\tprompt += `Step ${stepCount + 1} of ${this.config.maxSteps} max possible steps\\n`\n\t\tprompt += `Current time: ${new Date().toLocaleString()} (${Intl.DateTimeFormat().resolvedOptions().timeZone})\\n`\n\t\tprompt += '</step_info>\\n'\n\t\tprompt += '</agent_state>\\n\\n'\n\n\t\tconst loadedSkillsBlock = this.#skillHost?.formatLoadedSkillsPromptBlock() ?? ''\n\t\tif (loadedSkillsBlock) prompt += loadedSkillsBlock\n\n\t\t// <agent_history>\n\t\t// - <step_N> for steps\n\t\t// - <sys> for observations and system messages\n\n\t\tprompt += '<agent_history>\\n'\n\n\t\tlet stepIndex = 0\n\t\tfor (const event of this.history) {\n\t\t\tif (event.type === 'step') {\n\t\t\t\tstepIndex++\n\t\t\t\tprompt += `<step_${stepIndex}>\\n`\n\t\t\t\tprompt += `Evaluation of Previous Step: ${event.reflection.evaluation_previous_goal}\\n`\n\t\t\t\tprompt += `Memory: ${event.reflection.memory}\\n`\n\t\t\t\tprompt += `Next Goal: ${event.reflection.next_goal}\\n`\n\t\t\t\tprompt += `Action Results: ${event.action.output}\\n`\n\t\t\t\tprompt += `</step_${stepIndex}>\\n`\n\t\t\t} else if (event.type === 'observation') {\n\t\t\t\tprompt += `<sys>${event.content}</sys>\\n`\n\t\t\t} else if (event.type === 'user_takeover') {\n\t\t\t\tprompt += `<sys>User took over control and made changes to the page</sys>\\n`\n\t\t\t} else if (event.type === 'error') {\n\t\t\t\t// Error events are mainly for panel rendering, not included in LLM context\n\t\t\t\t// to avoid polluting the agent's reasoning with transient errors\n\t\t\t}\n\t\t}\n\n\t\tprompt += '</agent_history>\\n\\n'\n\n\t\t// <browser_state>\n\n\t\tlet pageContent = browserState.content\n\t\tif (this.config.transformPageContent) {\n\t\t\tpageContent = await this.config.transformPageContent(pageContent)\n\t\t}\n\n\t\tprompt += '<browser_state>\\n'\n\t\tprompt += browserState.header + '\\n'\n\t\tprompt += pageContent + '\\n'\n\t\tprompt += browserState.footer + '\\n\\n'\n\t\tprompt += '</browser_state>\\n\\n'\n\n\t\treturn prompt\n\t}\n\n\tdispose() {\n\t\tconsole.log('Disposing PageAgent...')\n\t\tthis.disposed = true\n\t\tthis.#skillWatcher?.dispose()\n\t\tthis.#skillWatcher = null\n\t\tthis.stopSkillRecording()\n\t\tthis.#resetSkillsForTaskEnd()\n\t\tthis.pageController.dispose()\n\t\t// this.history = []\n\t\tthis.#abortController.abort()\n\n\t\t// Emit dispose event for UI cleanup\n\t\tthis.dispatchEvent(new Event('dispose'))\n\n\t\tthis.config.onDispose?.(this)\n\t}\n}\n","// ======= type guards =======\n// @note instanceof fails for elements inside iframes\n\nexport function isHTMLElement(el: unknown): el is HTMLElement {\n\t// @todo either specify to HTMLElement or allow Element here.\n\treturn !!el && (el as Node).nodeType === 1\n}\n\nexport function isInputElement(el: Element): el is HTMLInputElement {\n\treturn el?.nodeType === 1 && el.tagName === 'INPUT'\n}\n\nexport function isTextAreaElement(el: Element): el is HTMLTextAreaElement {\n\treturn el?.nodeType === 1 && el.tagName === 'TEXTAREA'\n}\n\nexport function isSelectElement(el: Element): el is HTMLSelectElement {\n\treturn el?.nodeType === 1 && el.tagName === 'SELECT'\n}\n\nexport function isAnchorElement(el: Element): el is HTMLAnchorElement {\n\treturn el?.nodeType === 1 && el.tagName === 'A'\n}\n\n// ======= iframe helpers =======\n\n/** Iframe offset for translating element coordinates to top-frame viewport. */\nexport function getIframeOffset(element: HTMLElement): { x: number; y: number } {\n\tconst frame = element.ownerDocument.defaultView?.frameElement as HTMLElement | null\n\tif (!frame) return { x: 0, y: 0 }\n\tconst rect = frame.getBoundingClientRect()\n\treturn { x: rect.left, y: rect.top }\n}\n\n/**\n * Get native value setter from the element's own prototype (iframe-safe).\n * @note for React\n */\nexport function getNativeValueSetter(element: HTMLInputElement | HTMLTextAreaElement) {\n\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\treturn Object.getOwnPropertyDescriptor(Object.getPrototypeOf(element) as object, 'value')!\n\t\t.set as (v: string) => void\n}\n\n// ======= general utils =======\n\nexport async function waitFor(seconds: number): Promise<void> {\n\tawait new Promise((resolve) => setTimeout(resolve, seconds * 1000))\n}\n\n// ======= mask events =======\n\n/**\n * Move the visual pointer to a position within an element.\n * @param x - x coordinate in the element's document viewport\n * @param y - y coordinate in the element's document viewport\n */\nexport async function movePointerToElement(element: HTMLElement, x: number, y: number) {\n\tconst offset = getIframeOffset(element)\n\n\twindow.dispatchEvent(\n\t\tnew CustomEvent('PageAgent::MovePointerTo', {\n\t\t\tdetail: { x: x + offset.x, y: y + offset.y },\n\t\t})\n\t)\n\n\tawait waitFor(0.3)\n}\n\nexport async function clickPointer() {\n\twindow.dispatchEvent(new CustomEvent('PageAgent::ClickPointer'))\n}\n\nexport async function enablePassThrough() {\n\twindow.dispatchEvent(new CustomEvent('PageAgent::EnablePassThrough'))\n}\n\nexport async function disablePassThrough() {\n\twindow.dispatchEvent(new CustomEvent('PageAgent::DisablePassThrough'))\n}\n","/**\n * Copyright (C) 2025 Alibaba Group Holding Limited\n * All rights reserved.\n */\nimport type { InteractiveElementDomNode } from './dom/dom_tree/type'\nimport {\n\tclickPointer,\n\tdisablePassThrough,\n\tenablePassThrough,\n\tgetNativeValueSetter,\n\tisHTMLElement,\n\tisInputElement,\n\tisSelectElement,\n\tisTextAreaElement,\n\tmovePointerToElement,\n\twaitFor,\n} from './utils'\n\n/**\n * Get the HTMLElement by index from a selectorMap.\n * @private Internal method, subject to change at any time.\n */\nexport function getElementByIndex(\n\tselectorMap: Map<number, InteractiveElementDomNode>,\n\tindex: number\n): HTMLElement {\n\tconst interactiveNode = selectorMap.get(index)\n\tif (!interactiveNode) {\n\t\tthrow new Error(`No interactive element found at index ${index}`)\n\t}\n\n\tconst element = interactiveNode.ref\n\tif (!element) {\n\t\tthrow new Error(`Element at index ${index} does not have a reference`)\n\t}\n\n\tif (!isHTMLElement(element)) {\n\t\tthrow new Error(`Element at index ${index} is not an HTMLElement`)\n\t}\n\n\treturn element\n}\n\nlet lastClickedElement: HTMLElement | null = null\n\nfunction blurLastClickedElement() {\n\tif (lastClickedElement) {\n\t\tlastClickedElement.dispatchEvent(new PointerEvent('pointerout', { bubbles: true }))\n\t\tlastClickedElement.dispatchEvent(new PointerEvent('pointerleave', { bubbles: false }))\n\t\tlastClickedElement.dispatchEvent(new MouseEvent('mouseout', { bubbles: true }))\n\t\tlastClickedElement.dispatchEvent(new MouseEvent('mouseleave', { bubbles: false }))\n\t\tlastClickedElement.blur()\n\t\tlastClickedElement = null\n\t}\n}\n\n/**\n * Simulate a full click following W3C Pointer Events + UI Events spec order:\n * pointerover/enter → mouseover/enter → pointerdown → mousedown → [focus] →\n * pointerup → mouseup → click\n *\n * @private Internal method, subject to change at any time.\n */\nexport async function clickElement(element: HTMLElement) {\n\tblurLastClickedElement()\n\n\tlastClickedElement = element\n\n\tawait scrollIntoViewIfNeeded(element)\n\tconst frame = element.ownerDocument.defaultView?.frameElement\n\tif (frame) await scrollIntoViewIfNeeded(frame)\n\n\tconst rect = element.getBoundingClientRect()\n\tconst x = rect.left + rect.width / 2\n\tconst y = rect.top + rect.height / 2\n\n\tawait movePointerToElement(element, x, y)\n\tawait clickPointer()\n\n\tawait waitFor(0.1)\n\n\t// Hit-test to find the deepest element at click coordinates, matching\n\t// real browser behavior where events target the innermost element.\n\t// @note This may hit a element in the blacklist\n\t// TODO: This is a temporary workaround. Should have been handled during dom extraction.\n\tconst doc = element.ownerDocument\n\tawait enablePassThrough()\n\tconst hitTarget = doc.elementFromPoint(x, y)\n\tawait disablePassThrough()\n\tconst target =\n\t\thitTarget instanceof HTMLElement && element.contains(hitTarget) ? hitTarget : element\n\n\tconst pointerOpts = {\n\t\tbubbles: true,\n\t\tcancelable: true,\n\t\tclientX: x,\n\t\tclientY: y,\n\t\tpointerType: 'mouse',\n\t}\n\tconst mouseOpts = { bubbles: true, cancelable: true, clientX: x, clientY: y, button: 0 }\n\n\t// Hover — pointer events first, then mouse events (spec order)\n\ttarget.dispatchEvent(new PointerEvent('pointerover', pointerOpts))\n\ttarget.dispatchEvent(new PointerEvent('pointerenter', { ...pointerOpts, bubbles: false }))\n\ttarget.dispatchEvent(new MouseEvent('mouseover', mouseOpts))\n\ttarget.dispatchEvent(new MouseEvent('mouseenter', { ...mouseOpts, bubbles: false }))\n\n\t// Press\n\ttarget.dispatchEvent(new PointerEvent('pointerdown', pointerOpts))\n\ttarget.dispatchEvent(new MouseEvent('mousedown', mouseOpts))\n\n\t// Focus is not part of the standard pointer/mouse event sequence\n\t// \"undefined and varies between user agents\".\n\t// We focus the original element (nearest focusable ancestor), not the hit-test target, matching browser behavior.\n\telement.focus({ preventScroll: true })\n\n\t// Release\n\ttarget.dispatchEvent(new PointerEvent('pointerup', pointerOpts))\n\ttarget.dispatchEvent(new MouseEvent('mouseup', mouseOpts))\n\n\t// Click — activation behavior (navigation, form submit, etc.) triggers\n\t// via bubbling from target up to the interactive ancestor.\n\ttarget.click()\n\n\tawait waitFor(0.2)\n}\n\n/**\n * @private Internal method, subject to change at any time.\n */\nexport async function inputTextElement(element: HTMLElement, text: string) {\n\tconst isContentEditable = element.isContentEditable\n\tif (!isInputElement(element) && !isTextAreaElement(element) && !isContentEditable) {\n\t\tthrow new Error('Element is not an input, textarea, or contenteditable')\n\t}\n\n\tawait clickElement(element)\n\n\tif (isContentEditable) {\n\t\t// Contenteditable support (partial)\n\t\t// Not supported:\n\t\t// - Monaco/CodeMirror: Require direct JS instance access. No universal way to obtain.\n\t\t// - Draft.js: Not responsive to synthetic/execCommand/Range/DataTransfer. Unmaintained.\n\t\t//\n\t\t// Strategy: Try Plan A (synthetic events) first, then verify and fall back\n\t\t// to Plan B (execCommand) if the text wasn't actually inserted.\n\t\t//\n\t\t// Plan A: Dispatch synthetic events\n\t\t// Works: React contenteditable, Quill.\n\t\t// Fails: Slate.js, some contenteditable editors that ignore synthetic events.\n\t\t// Sequence: beforeinput -> mutation -> input -> change -> blur\n\n\t\t// Dispatch beforeinput + mutation + input for clearing\n\t\tif (\n\t\t\telement.dispatchEvent(\n\t\t\t\tnew InputEvent('beforeinput', {\n\t\t\t\t\tbubbles: true,\n\t\t\t\t\tcancelable: true,\n\t\t\t\t\tinputType: 'deleteContent',\n\t\t\t\t})\n\t\t\t)\n\t\t) {\n\t\t\telement.innerText = ''\n\t\t\telement.dispatchEvent(\n\t\t\t\tnew InputEvent('input', {\n\t\t\t\t\tbubbles: true,\n\t\t\t\t\tinputType: 'deleteContent',\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\n\t\t// Dispatch beforeinput + mutation + input for insertion (important for React apps)\n\t\tif (\n\t\t\telement.dispatchEvent(\n\t\t\t\tnew InputEvent('beforeinput', {\n\t\t\t\t\tbubbles: true,\n\t\t\t\t\tcancelable: true,\n\t\t\t\t\tinputType: 'insertText',\n\t\t\t\t\tdata: text,\n\t\t\t\t})\n\t\t\t)\n\t\t) {\n\t\t\telement.innerText = text\n\t\t\telement.dispatchEvent(\n\t\t\t\tnew InputEvent('input', {\n\t\t\t\t\tbubbles: true,\n\t\t\t\t\tinputType: 'insertText',\n\t\t\t\t\tdata: text,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\n\t\t// Verify Plan A worked by checking if the text was actually inserted\n\t\tconst planASucceeded = element.innerText.trim() === text.trim()\n\n\t\tif (!planASucceeded) {\n\t\t\t// Plan B: execCommand fallback (deprecated but widely supported)\n\t\t\t// Works: Quill, Slate.js, react contenteditable components.\n\t\t\t// This approach integrates with the browser's undo stack and is handled\n\t\t\t// natively by most rich-text editors.\n\t\t\telement.focus()\n\n\t\t\t// Select all existing content and delete it\n\t\t\tconst doc = element.ownerDocument\n\t\t\tconst selection = (doc.defaultView || window).getSelection()\n\t\t\tconst range = doc.createRange()\n\t\t\trange.selectNodeContents(element)\n\t\t\tselection?.removeAllRanges()\n\t\t\tselection?.addRange(range)\n\n\t\t\tdoc.execCommand('delete', false)\n\t\t\tdoc.execCommand('insertText', false, text)\n\t\t}\n\n\t\t// Dispatch change event (for good measure)\n\t\telement.dispatchEvent(new Event('change', { bubbles: true }))\n\n\t\t// Trigger blur for validation\n\t\telement.blur()\n\t} else {\n\t\tgetNativeValueSetter(element as HTMLInputElement | HTMLTextAreaElement).call(element, text)\n\t}\n\n\t// Only dispatch shared input event for non-contenteditable (contenteditable has its own)\n\tif (!isContentEditable) {\n\t\telement.dispatchEvent(new Event('input', { bubbles: true }))\n\t}\n\n\tawait waitFor(0.1)\n}\n\n/**\n * @todo browser-use version is very complex and supports menu tags, need to follow up\n * @private Internal method, subject to change at any time.\n */\nexport async function selectOptionElement(selectElement: HTMLSelectElement, optionText: string) {\n\tif (!isSelectElement(selectElement)) {\n\t\tthrow new Error('Element is not a select element')\n\t}\n\n\tconst options = Array.from(selectElement.options)\n\tconst option = options.find((opt) => opt.textContent?.trim() === optionText.trim())\n\n\tif (!option) {\n\t\tthrow new Error(`Option with text \"${optionText}\" not found in select element`)\n\t}\n\n\tselectElement.value = option.value\n\tselectElement.dispatchEvent(new Event('change', { bubbles: true }))\n\n\tawait waitFor(0.1) // Wait to ensure change event processing completes\n}\n\ninterface ScrollableElement extends Element {\n\tscrollIntoViewIfNeeded?: (centerIfNeeded?: boolean) => void\n}\n\n/**\n * @private Internal method, subject to change at any time.\n */\nexport async function scrollIntoViewIfNeeded(element: Element) {\n\tconst el = element as ScrollableElement\n\tif (typeof el.scrollIntoViewIfNeeded === 'function') {\n\t\tel.scrollIntoViewIfNeeded()\n\t\t// await waitFor(0.5) // Animation playback\n\t} else {\n\t\t// @todo visibility check\n\t\telement.scrollIntoView({ behavior: 'auto', block: 'center', inline: 'nearest' })\n\t\t// await waitFor(0.5) // Animation playback\n\t}\n}\n\nexport async function scrollVertically(scroll_amount: number, element?: HTMLElement | null) {\n\t// Element-specific scrolling if element is provided\n\tif (element) {\n\t\tconst targetElement = element\n\t\tlet currentElement = targetElement as HTMLElement | null\n\t\tlet scrollSuccess = false\n\t\tlet scrolledElement: HTMLElement | null = null\n\t\tlet scrollDelta = 0\n\t\tlet attempts = 0\n\t\tconst dy = scroll_amount\n\n\t\twhile (currentElement && attempts < 10) {\n\t\t\tconst computedStyle = window.getComputedStyle(currentElement)\n\t\t\tconst hasScrollableY =\n\t\t\t\t/(auto|scroll|overlay)/.test(computedStyle.overflowY) ||\n\t\t\t\t(computedStyle.scrollbarWidth && computedStyle.scrollbarWidth !== 'auto') ||\n\t\t\t\t(computedStyle.scrollbarGutter && computedStyle.scrollbarGutter !== 'auto')\n\t\t\tconst canScrollVertically = currentElement.scrollHeight > currentElement.clientHeight\n\n\t\t\tif (hasScrollableY && canScrollVertically) {\n\t\t\t\tconst beforeScroll = currentElement.scrollTop\n\t\t\t\tconst maxScroll = currentElement.scrollHeight - currentElement.clientHeight\n\n\t\t\t\tlet scrollAmount = dy / 3\n\n\t\t\t\tif (scrollAmount > 0) {\n\t\t\t\t\tscrollAmount = Math.min(scrollAmount, maxScroll - beforeScroll)\n\t\t\t\t} else {\n\t\t\t\t\tscrollAmount = Math.max(scrollAmount, -beforeScroll)\n\t\t\t\t}\n\n\t\t\t\tcurrentElement.scrollTop = beforeScroll + scrollAmount\n\n\t\t\t\tconst afterScroll = currentElement.scrollTop\n\t\t\t\tconst actualScrollDelta = afterScroll - beforeScroll\n\n\t\t\t\tif (Math.abs(actualScrollDelta) > 0.5) {\n\t\t\t\t\tscrollSuccess = true\n\t\t\t\t\tscrolledElement = currentElement\n\t\t\t\t\tscrollDelta = actualScrollDelta\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (currentElement === document.body || currentElement === document.documentElement) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcurrentElement = currentElement.parentElement\n\t\t\tattempts++\n\t\t}\n\n\t\tif (scrollSuccess) {\n\t\t\treturn `Scrolled container (${scrolledElement?.tagName}) by ${scrollDelta}px`\n\t\t} else {\n\t\t\treturn `No scrollable container found for element (${targetElement.tagName})`\n\t\t}\n\t}\n\n\t// Page-level scrolling (default or fallback)\n\n\tconst dy = scroll_amount\n\tconst bigEnough = (el: HTMLElement) => el.clientHeight >= window.innerHeight * 0.5\n\tconst canScroll = (el: HTMLElement | null): boolean =>\n\t\tBoolean(\n\t\t\tel &&\n\t\t\t/(auto|scroll|overlay)/.test(getComputedStyle(el).overflowY) &&\n\t\t\tel.scrollHeight > el.clientHeight &&\n\t\t\tbigEnough(el)\n\t\t)\n\n\t// @deprecated Heuristic container search.\n\t// Unreliable in multi-panel layouts. Should guide LLMs to use indexed scroll for consistency.\n\t// TODO: remove this fallback\n\n\t// try to find the nearest scrollable container\n\t// document.activeElement is usually body.\n\t// After a successful element.focus(), activeElement become the nearest focusable parent\n\n\tlet el: HTMLElement | null = document.activeElement as HTMLElement | null\n\twhile (el && !canScroll(el) && el !== document.body) el = el.parentElement\n\n\t// Something is wrong if it falls back to global '*' search\n\t// TODO: Return error message instead of global '*' search\n\n\tel = canScroll(el)\n\t\t? el\n\t\t: Array.from(document.querySelectorAll<HTMLElement>('*')).find(canScroll) ||\n\t\t\t(document.scrollingElement as HTMLElement) ||\n\t\t\t(document.documentElement as HTMLElement)\n\n\tif (el === document.scrollingElement || el === document.documentElement || el === document.body) {\n\t\t// Page-level scroll\n\t\tconst scrollBefore = window.scrollY\n\t\tconst scrollMax = document.documentElement.scrollHeight - window.innerHeight\n\n\t\twindow.scrollBy(0, dy)\n\n\t\tconst scrollAfter = window.scrollY\n\t\tconst scrolled = scrollAfter - scrollBefore\n\n\t\tif (Math.abs(scrolled) < 1) {\n\t\t\treturn dy > 0\n\t\t\t\t? `⚠️ Already at the bottom of the page, cannot scroll down further.`\n\t\t\t\t: `⚠️ Already at the top of the page, cannot scroll up further.`\n\t\t}\n\n\t\tconst reachedBottom = dy > 0 && scrollAfter >= scrollMax - 1\n\t\tconst reachedTop = dy < 0 && scrollAfter <= 1\n\n\t\tif (reachedBottom) return `✅ Scrolled page by ${scrolled}px. Reached the bottom of the page.`\n\t\tif (reachedTop) return `✅ Scrolled page by ${scrolled}px. Reached the top of the page.`\n\t\treturn `✅ Scrolled page by ${scrolled}px.`\n\t} else {\n\t\t// Container scroll\n\n\t\tconst warningMsg = `The document is not scrollable. Falling back to container scroll.`\n\t\tconsole.log(`[PageController] ${warningMsg}`)\n\n\t\tconst scrollBefore = el!.scrollTop\n\t\tconst scrollMax = el!.scrollHeight - el!.clientHeight\n\n\t\tel!.scrollBy({ top: dy, behavior: 'smooth' })\n\t\tawait waitFor(0.1)\n\n\t\tconst scrollAfter = el!.scrollTop\n\t\tconst scrolled = scrollAfter - scrollBefore\n\n\t\tif (Math.abs(scrolled) < 1) {\n\t\t\treturn dy > 0\n\t\t\t\t? `⚠️ ${warningMsg} Already at the bottom of container (${el!.tagName}), cannot scroll down further.`\n\t\t\t\t: `⚠️ ${warningMsg} Already at the top of container (${el!.tagName}), cannot scroll up further.`\n\t\t}\n\n\t\tconst reachedBottom = dy > 0 && scrollAfter >= scrollMax - 1\n\t\tconst reachedTop = dy < 0 && scrollAfter <= 1\n\n\t\tif (reachedBottom)\n\t\t\treturn `✅ ${warningMsg} Scrolled container (${el!.tagName}) by ${scrolled}px. Reached the bottom.`\n\t\tif (reachedTop)\n\t\t\treturn `✅ ${warningMsg} Scrolled container (${el!.tagName}) by ${scrolled}px. Reached the top.`\n\t\treturn `✅ ${warningMsg} Scrolled container (${el!.tagName}) by ${scrolled}px.`\n\t}\n}\n\nexport async function scrollHorizontally(scroll_amount: number, element?: HTMLElement | null) {\n\t// Element-specific scrolling if element is provided\n\tif (element) {\n\t\tconst targetElement = element\n\t\tlet currentElement = targetElement as HTMLElement | null\n\t\tlet scrollSuccess = false\n\t\tlet scrolledElement: HTMLElement | null = null\n\t\tlet scrollDelta = 0\n\t\tlet attempts = 0\n\t\tconst dx = scroll_amount\n\n\t\twhile (currentElement && attempts < 10) {\n\t\t\tconst computedStyle = window.getComputedStyle(currentElement)\n\t\t\tconst hasScrollableX =\n\t\t\t\t/(auto|scroll|overlay)/.test(computedStyle.overflowX) ||\n\t\t\t\t(computedStyle.scrollbarWidth && computedStyle.scrollbarWidth !== 'auto') ||\n\t\t\t\t(computedStyle.scrollbarGutter && computedStyle.scrollbarGutter !== 'auto')\n\t\t\tconst canScrollHorizontally = currentElement.scrollWidth > currentElement.clientWidth\n\n\t\t\tif (hasScrollableX && canScrollHorizontally) {\n\t\t\t\tconst beforeScroll = currentElement.scrollLeft\n\t\t\t\tconst maxScroll = currentElement.scrollWidth - currentElement.clientWidth\n\n\t\t\t\tlet scrollAmount = dx / 3\n\n\t\t\t\tif (scrollAmount > 0) {\n\t\t\t\t\tscrollAmount = Math.min(scrollAmount, maxScroll - beforeScroll)\n\t\t\t\t} else {\n\t\t\t\t\tscrollAmount = Math.max(scrollAmount, -beforeScroll)\n\t\t\t\t}\n\n\t\t\t\tcurrentElement.scrollLeft = beforeScroll + scrollAmount\n\n\t\t\t\tconst afterScroll = currentElement.scrollLeft\n\t\t\t\tconst actualScrollDelta = afterScroll - beforeScroll\n\n\t\t\t\tif (Math.abs(actualScrollDelta) > 0.5) {\n\t\t\t\t\tscrollSuccess = true\n\t\t\t\t\tscrolledElement = currentElement\n\t\t\t\t\tscrollDelta = actualScrollDelta\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (currentElement === document.body || currentElement === document.documentElement) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcurrentElement = currentElement.parentElement\n\t\t\tattempts++\n\t\t}\n\n\t\tif (scrollSuccess) {\n\t\t\treturn `Scrolled container (${scrolledElement?.tagName}) horizontally by ${scrollDelta}px`\n\t\t} else {\n\t\t\treturn `No horizontally scrollable container found for element (${targetElement.tagName})`\n\t\t}\n\t}\n\n\t// Page-level scrolling (default or fallback)\n\n\tconst dx = scroll_amount\n\n\tconst bigEnough = (el: HTMLElement) => el.clientWidth >= window.innerWidth * 0.5\n\tconst canScroll = (el: HTMLElement | null): boolean =>\n\t\tBoolean(\n\t\t\tel &&\n\t\t\t/(auto|scroll|overlay)/.test(getComputedStyle(el).overflowX) &&\n\t\t\tel.scrollWidth > el.clientWidth &&\n\t\t\tbigEnough(el)\n\t\t)\n\n\t// @deprecated Same heuristic container search as scrollVertically.\n\t// TODO: Remove once LLMs reliably use indexed scrolling via data-scrollable.\n\n\tlet el: HTMLElement | null = document.activeElement as HTMLElement | null\n\twhile (el && !canScroll(el) && el !== document.body) el = el.parentElement\n\n\tel = canScroll(el)\n\t\t? el\n\t\t: Array.from(document.querySelectorAll<HTMLElement>('*')).find(canScroll) ||\n\t\t\t(document.scrollingElement as HTMLElement) ||\n\t\t\t(document.documentElement as HTMLElement)\n\n\tif (el === document.scrollingElement || el === document.documentElement || el === document.body) {\n\t\t// Page-level scroll\n\t\tconst scrollBefore = window.scrollX\n\t\tconst scrollMax = document.documentElement.scrollWidth - window.innerWidth\n\n\t\twindow.scrollBy(dx, 0)\n\n\t\tconst scrollAfter = window.scrollX\n\t\tconst scrolled = scrollAfter - scrollBefore\n\n\t\tif (Math.abs(scrolled) < 1) {\n\t\t\treturn dx > 0\n\t\t\t\t? `⚠️ Already at the right edge of the page, cannot scroll right further.`\n\t\t\t\t: `⚠️ Already at the left edge of the page, cannot scroll left further.`\n\t\t}\n\n\t\tconst reachedRight = dx > 0 && scrollAfter >= scrollMax - 1\n\t\tconst reachedLeft = dx < 0 && scrollAfter <= 1\n\n\t\tif (reachedRight)\n\t\t\treturn `✅ Scrolled page by ${scrolled}px. Reached the right edge of the page.`\n\t\tif (reachedLeft) return `✅ Scrolled page by ${scrolled}px. Reached the left edge of the page.`\n\t\treturn `✅ Scrolled page horizontally by ${scrolled}px.`\n\t} else {\n\t\t// Container scroll\n\t\tconst warningMsg = `The document is not scrollable. Falling back to container scroll.`\n\t\tconsole.log(`[PageController] ${warningMsg}`)\n\n\t\tconst scrollBefore = el!.scrollLeft\n\t\tconst scrollMax = el!.scrollWidth - el!.clientWidth\n\n\t\tel!.scrollBy({ left: dx, behavior: 'smooth' })\n\t\tawait waitFor(0.1)\n\n\t\tconst scrollAfter = el!.scrollLeft\n\t\tconst scrolled = scrollAfter - scrollBefore\n\n\t\tif (Math.abs(scrolled) < 1) {\n\t\t\treturn dx > 0\n\t\t\t\t? `⚠️ ${warningMsg} Already at the right edge of container (${el!.tagName}), cannot scroll right further.`\n\t\t\t\t: `⚠️ ${warningMsg} Already at the left edge of container (${el!.tagName}), cannot scroll left further.`\n\t\t}\n\n\t\tconst reachedRight = dx > 0 && scrollAfter >= scrollMax - 1\n\t\tconst reachedLeft = dx < 0 && scrollAfter <= 1\n\n\t\tif (reachedRight)\n\t\t\treturn `✅ ${warningMsg} Scrolled container (${el!.tagName}) by ${scrolled}px. Reached the right edge.`\n\t\tif (reachedLeft)\n\t\t\treturn `✅ ${warningMsg} Scrolled container (${el!.tagName}) by ${scrolled}px. Reached the left edge.`\n\t\treturn `✅ ${warningMsg} Scrolled container (${el!.tagName}) horizontally by ${scrolled}px.`\n\t}\n}\n","/**\n * The core identifies each node by a capture-local DOM path (`html[1]/body[2]/div[0]`), which it\n * publishes on every node as `domPath`. These helpers read and write that same format so the adapter\n * can relate nodes to elements it owns (the agent's own interface, frame documents) without reaching\n * into the core. Real-browser tests check them against the core's output.\n */\n\n/** The core's path for `node` inside `root`: child index among all siblings, tag in lower case. */\nexport function domPathOf(node: Node, root: Document): string {\n\tconst parts: string[] = []\n\tlet current: Node | null = node\n\twhile (current && current !== root) {\n\t\tif (current.nodeType === 1 || current.nodeType === 3) {\n\t\t\tlet index = 0\n\t\t\tfor (let previous = current.previousSibling; previous; previous = previous.previousSibling)\n\t\t\t\tindex++\n\t\t\tparts.push(`${current.nodeType === 1 ? (current as Element).localName : '#text'}[${index}]`)\n\t\t} else if (current.nodeType === 11 && (current as ShadowRoot).host) {\n\t\t\tparts.push('#shadow-root[0]')\n\t\t}\n\t\tcurrent = current.parentNode ?? (current as ShadowRoot).host ?? null\n\t}\n\treturn parts.reverse().join('/')\n}\n\n/** The node a core path points to now, or null when the document no longer matches the path. */\nexport function resolveDomPath(root: Document, path: string): Node | null {\n\tif (!path) return null\n\tlet current: Node = root\n\tfor (const part of path.split('/')) {\n\t\tconst match = /^(.+)\\[(\\d+)\\]$/.exec(part)\n\t\tif (!match) return null\n\t\tconst [, name, index] = match\n\t\tif (name === '#shadow-root') {\n\t\t\tconst shadow = (current as Element).shadowRoot\n\t\t\tif (!shadow) return null\n\t\t\tcurrent = shadow\n\t\t\tcontinue\n\t\t}\n\t\tconst child = current.childNodes[Number(index)] as Node | undefined\n\t\tif (!child) return null\n\t\tif (name === '#text' ? child.nodeType !== 3 : (child as Element).localName !== name) return null\n\t\tcurrent = child\n\t}\n\treturn current\n}\n\n/** Whether `path` is `ancestor` or lies below it. */\nexport function isWithinPath(path: string, ancestor: string): boolean {\n\treturn path === ancestor || path.startsWith(`${ancestor}/`)\n}\n","/**\n * What an action demonstrably sent to the page, observed independently of the core.\n *\n * This is evidence of delivery only. It never shows that the page accepted, applied or saved\n * anything: that needs a new capture or a query of the page.\n */\nexport interface AxEvidence {\n\t/**\n\t * Untrusted (`isTrusted === false`) events seen at the session window while the action ran, by type.\n\t * Null when the session window is unknown.\n\t *\n\t * It is an observation of the window, not a log of the action: it also counts untrusted events the\n\t * page itself dispatched meanwhile, and it misses events the page stops before the window and\n\t * events that do not leave a shadow root (a `change` fired inside one, for example).\n\t */\n\tsyntheticEvents: Record<string, number> | null\n\t/** Whether the focused element changed while the action ran. Null when the document is unknown. */\n\tfocusMoved: boolean | null\n\t/** Whether `scrollIntoView` was requested on the target before the action itself. */\n\tscrollIntoViewRequested: boolean\n}\n\nconst OBSERVED_EVENTS = [\n\t'pointerover',\n\t'pointerenter',\n\t'pointerdown',\n\t'pointermove',\n\t'pointerup',\n\t'pointercancel',\n\t'pointerout',\n\t'pointerleave',\n\t'mouseover',\n\t'mouseenter',\n\t'mousedown',\n\t'mousemove',\n\t'mouseup',\n\t'mouseout',\n\t'mouseleave',\n\t'click',\n\t'dblclick',\n\t'dragstart',\n\t'dragenter',\n\t'dragover',\n\t'drop',\n\t'dragend',\n\t'keydown',\n\t'keyup',\n\t'input',\n\t'change',\n\t'wheel',\n] as const\n\nfunction deepActiveElement(doc: Document): Element | null {\n\tlet active = doc.activeElement\n\twhile (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement\n\treturn active\n}\n\n/**\n * Starts counting untrusted events at the document's window (capture phase, so non-bubbling events\n * are included). Call `stop()` exactly once to remove the listeners and read the evidence.\n */\nexport function observeAction(doc: Document | null): { stop: () => AxEvidence } {\n\t// A frame document that navigated away has no window any more.\n\tconst target = doc?.defaultView ?? null\n\tif (!doc || !target)\n\t\treturn {\n\t\t\tstop: () => ({ syntheticEvents: null, focusMoved: null, scrollIntoViewRequested: false }),\n\t\t}\n\n\tconst counts: Record<string, number> = {}\n\tconst listener = (event: Event) => {\n\t\tif (!event.isTrusted) counts[event.type] = (counts[event.type] ?? 0) + 1\n\t}\n\tfor (const type of OBSERVED_EVENTS) target.addEventListener(type, listener, true)\n\tconst focusedBefore = deepActiveElement(doc)\n\n\treturn {\n\t\tstop: () => {\n\t\t\tfor (const type of OBSERVED_EVENTS) target.removeEventListener(type, listener, true)\n\t\t\tlet focusMoved: boolean | null\n\t\t\ttry {\n\t\t\t\tfocusMoved = deepActiveElement(doc) !== focusedBefore\n\t\t\t} catch {\n\t\t\t\tfocusMoved = null\n\t\t\t}\n\t\t\treturn { syntheticEvents: counts, focusMoved, scrollIntoViewRequested: false }\n\t\t},\n\t}\n}\n\n/** `click ×2, dblclick ×1`, or an empty string when nothing was seen. */\nexport function describeEvents(evidence: AxEvidence | null): string {\n\tconst events = evidence?.syntheticEvents\n\tif (!events) return ''\n\treturn Object.entries(events)\n\t\t.map(([type, count]) => `${type} ×${count}`)\n\t\t.join(', ')\n}\n","import { type AxEvidence, describeEvents } from './evidence'\n\n/**\n * Failure classes. All but the last four come straight from the core's `code: message` errors.\n *\n * - `stale_id`, `no_capture`, `engine_unavailable` and `unknown` are raised by this adapter.\n */\nexport type AxErrorCode =\n\t| 'stale_snapshot'\n\t| 'stale_node'\n\t| 'stale_document'\n\t| 'session_closed'\n\t| 'blocked'\n\t| 'invalid'\n\t| 'unsupported'\n\t| 'budget_exceeded'\n\t| 'gesture_active'\n\t| 'frame_unavailable'\n\t| 'timeout'\n\t| 'aborted'\n\t| 'stale_id'\n\t| 'no_capture'\n\t| 'engine_unavailable'\n\t| 'unknown'\n\nconst CORE_CODES = new Set<string>([\n\t'stale_snapshot',\n\t'stale_node',\n\t'stale_document',\n\t'session_closed',\n\t'blocked',\n\t'invalid',\n\t'unsupported',\n\t'budget_exceeded',\n\t'gesture_active',\n\t'frame_unavailable',\n\t'timeout',\n\t'aborted',\n])\n\n/**\n * An accessibility operation that did not complete.\n *\n * `partial` is set when synthetic events were already delivered, or focus already moved, before the\n * failure. Those effects are not undone: treat the page as possibly changed and capture again.\n */\nexport class AxError extends Error {\n\treadonly code: AxErrorCode\n\treadonly action: string | null\n\treadonly partial: AxEvidence | null\n\n\tconstructor(\n\t\tcode: AxErrorCode,\n\t\tmessage: string,\n\t\toptions: { action?: string; partial?: AxEvidence | null; cause?: unknown } = {}\n\t) {\n\t\tsuper(message, options.cause === undefined ? undefined : { cause: options.cause })\n\t\tthis.name = 'AxError'\n\t\tthis.code = code\n\t\tthis.action = options.action ?? null\n\t\tthis.partial = options.partial ?? null\n\t}\n\n\t/**\n\t * What had already reached the page when the action failed, in words, or an empty string. For\n\t * example `untrusted events already observed: pointerover ×1; focus already moved`.\n\t */\n\tget effects(): string {\n\t\tif (!this.partial) return ''\n\t\tconst events = describeEvents(this.partial)\n\t\tconst parts: string[] = []\n\t\tif (this.partial.scrollIntoViewRequested) parts.push('scrollIntoView already requested')\n\t\tif (events) parts.push(`untrusted events already observed: ${events}`)\n\t\tif (this.partial.focusMoved) parts.push('focus already moved')\n\t\treturn parts.join('; ')\n\t}\n}\n\n/** True when the evidence shows the page already received something from the action. */\nexport function hasEffects(evidence: AxEvidence | null | undefined): evidence is AxEvidence {\n\tif (!evidence) return false\n\tconst events = evidence.syntheticEvents\n\treturn (\n\t\tevidence.scrollIntoViewRequested ||\n\t\tevidence.focusMoved === true ||\n\t\t(!!events && Object.keys(events).length > 0)\n\t)\n}\n\n/**\n * Wraps any thrown value as an `AxError`, keeping the core's message unchanged.\n * The code is the `code:` prefix the core puts on its errors.\n */\nexport function toAxError(error: unknown, action?: string, evidence?: AxEvidence | null): AxError {\n\tconst partial = hasEffects(evidence) ? evidence : null\n\tif (error instanceof AxError) {\n\t\tif (!partial && !action) return error\n\t\treturn new AxError(error.code, error.message, {\n\t\t\taction: error.action ?? action,\n\t\t\tpartial: error.partial ?? partial,\n\t\t\tcause: error.cause,\n\t\t})\n\t}\n\tconst message = error instanceof Error ? error.message : String(error)\n\tconst prefix = /^([a-z_]+): /.exec(message)?.[1]\n\tconst code: AxErrorCode = prefix && CORE_CODES.has(prefix) ? (prefix as AxErrorCode) : 'unknown'\n\treturn new AxError(code, message, { action, partial, cause: error })\n}\n","import type { AxNode, AxTreeFormatOptions, AxTreeText } from './types'\n\ninterface Entry {\n\tnode: AxNode\n\tdepth: number\n\t/** Index of the nearest printed-candidate ancestor in the entry list, or -1. */\n\tparent: number\n}\n\nconst collapseSpaces = (text: string) => text.replace(/\\s+/g, ' ').trim()\n\n/** JSON text of a value. Long strings are cut at `maxTextLength`, and the cut is stated. */\nfunction quote(value: unknown, options: AxTreeFormatOptions): string {\n\tconst limit = options.maxTextLength\n\tif (typeof value !== 'string' || limit === undefined || value.length <= limit)\n\t\treturn JSON.stringify(value)\n\treturn `${JSON.stringify(`${value.slice(0, limit)}…`)} (+${value.length - limit} chars)`\n}\n\n/**\n * One line per node, in the same shape as the core's console interface:\n * `[id] role \"name\" value: ... description: ... key: value`.\n */\nfunction formatLine(node: AxNode, depth: number, options: AxTreeFormatOptions): string {\n\tconst properties = Object.entries(node.properties ?? {})\n\t\t.filter(([, value]) => value !== null && value !== undefined && typeof value !== 'object')\n\t\t.map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`)\n\t\t.join('')\n\tconst description = node.description ? ` description: ${quote(node.description, options)}` : ''\n\tconst value =\n\t\tnode.value !== undefined && node.value !== null ? ` value: ${quote(node.value, options)}` : ''\n\tconst name = options.compact && !node.name ? '' : ` ${quote(node.name || '', options)}`\n\n\tlet relations = ''\n\tif (options.relations) {\n\t\tconst omitted = new Set(options.omitRelationTypes ?? [])\n\t\trelations = (node.relations ?? [])\n\t\t\t.filter((relation) => !omitted.has(relation.type))\n\t\t\t.map((relation) => ` ${relation.type}=>[${relation.targetId ?? 'unresolved'}]`)\n\t\t\t.join('')\n\t}\n\n\tconst label = options.idLabel ? options.idLabel(node) : node.id\n\tconst bracket = label === null ? '' : `[${label}] `\n\tconst annotation = options.annotation?.(node)\n\treturn `${' '.repeat(depth)}${bracket}${node.role}${name}${value}${description}${properties}${relations}${annotation ? ` ${annotation}` : ''}`\n}\n\n/**\n * Hierarchical text for a capture's nodes. Ignored nodes are not printed and their children take\n * their place, as in the core's console interface.\n *\n * With `maxLines`, whole levels are printed from the top down and the remaining budget is spent on\n * the next level in document order. Nothing is dropped silently: every printed node that has\n * unprinted descendants ends with `… +N hidden`.\n */\nexport function formatTree(nodes: AxNode[], options: AxTreeFormatOptions = {}): AxTreeText {\n\t// A node whose parent is not in the list (it was left out of the capture) is printed as a root,\n\t// so it is never lost without a trace.\n\tconst ids = new Set(nodes.map((node) => node.id))\n\tconst children = new Map<string | null, AxNode[]>()\n\tfor (const node of nodes) {\n\t\tconst parentId = node.parentId !== null && ids.has(node.parentId) ? node.parentId : null\n\t\tconst siblings = children.get(parentId)\n\t\tif (siblings) siblings.push(node)\n\t\telse children.set(parentId, [node])\n\t}\n\n\tconst entries: Entry[] = []\n\tlet foldedTextNodes = 0\n\n\tconst visit = (parentId: string | null, depth: number, parent: number) => {\n\t\tfor (const node of children.get(parentId) ?? []) {\n\t\t\tif (node.ignored) {\n\t\t\t\tvisit(node.id, depth, parent)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (options.compact && node.role === 'StaticText' && !children.has(node.id)) {\n\t\t\t\tconst text = collapseSpaces(node.name)\n\t\t\t\tconst repeatsParent = parent >= 0 && text === collapseSpaces(entries[parent].node.name)\n\t\t\t\tif (!text || repeatsParent) {\n\t\t\t\t\tfoldedTextNodes++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst index = entries.push({ node, depth, parent }) - 1\n\t\t\tvisit(node.id, depth + 1, index)\n\t\t}\n\t}\n\n\tif (options.rootId === undefined) {\n\t\tvisit(null, 0, -1)\n\t} else {\n\t\tconst root = nodes.find((node) => node.id === options.rootId)\n\t\tif (root) {\n\t\t\tif (root.ignored) visit(root.id, 0, -1)\n\t\t\telse {\n\t\t\t\tentries.push({ node: root, depth: 0, parent: -1 })\n\t\t\t\tvisit(root.id, 1, 0)\n\t\t\t}\n\t\t}\n\t}\n\n\t// With a filter, a node stays when it passes or when something below it does, so what is printed\n\t// is still a tree with its context. Everything else is counted as filtered.\n\tconst totalNodes = entries.length\n\tif (options.filter) {\n\t\tconst keep = entries.map((entry) => options.filter!(entry.node))\n\t\tfor (let index = entries.length - 1; index >= 0; index--)\n\t\t\tif (keep[index] && entries[index].parent >= 0) keep[entries[index].parent] = true\n\t\tconst moved = new Array<number>(entries.length).fill(-1)\n\t\tconst kept: Entry[] = []\n\t\tentries.forEach((entry, index) => {\n\t\t\tif (!keep[index]) return\n\t\t\tmoved[index] =\n\t\t\t\tkept.push({ ...entry, parent: entry.parent < 0 ? -1 : moved[entry.parent] }) - 1\n\t\t})\n\t\tentries.length = 0\n\t\tentries.push(...kept)\n\t}\n\tconst filteredNodes = totalNodes - entries.length\n\n\tconst printed = new Array<boolean>(entries.length).fill(true)\n\tconst maxLines = options.maxLines\n\tif (maxLines !== undefined && entries.length > maxLines) {\n\t\tconst perDepth: number[] = []\n\t\tfor (const entry of entries) perDepth[entry.depth] = (perDepth[entry.depth] ?? 0) + 1\n\n\t\t// Deepest level that still fits whole.\n\t\tlet fullDepth = -1\n\t\tlet used = 0\n\t\tfor (let depth = 0; depth < perDepth.length; depth++) {\n\t\t\tif (used + (perDepth[depth] ?? 0) > maxLines) break\n\t\t\tused += perDepth[depth] ?? 0\n\t\t\tfullDepth = depth\n\t\t}\n\n\t\tlet remaining = maxLines - used\n\t\tentries.forEach((entry, index) => {\n\t\t\tif (entry.depth <= fullDepth) return\n\t\t\t// A node is printed only under a printed parent, so the output stays a tree.\n\t\t\tconst parentPrinted = entry.parent < 0 || printed[entry.parent]\n\t\t\tif (entry.depth === fullDepth + 1 && parentPrinted && remaining > 0) remaining--\n\t\t\telse printed[index] = false\n\t\t})\n\t}\n\n\tconst hidden = new Array<number>(entries.length).fill(0)\n\tlet orphans = 0\n\tentries.forEach((entry, index) => {\n\t\tif (printed[index]) return\n\t\tlet ancestor = entry.parent\n\t\twhile (ancestor >= 0 && !printed[ancestor]) ancestor = entries[ancestor].parent\n\t\tif (ancestor >= 0) hidden[ancestor]++\n\t\telse orphans++\n\t})\n\n\tconst lines: string[] = []\n\tlet shownNodes = 0\n\tentries.forEach((entry, index) => {\n\t\tif (!printed[index]) return\n\t\tshownNodes++\n\t\tconst suffix = hidden[index] > 0 ? ` … +${hidden[index]} hidden` : ''\n\t\tlines.push(formatLine(entry.node, entry.depth, options) + suffix)\n\t})\n\tif (orphans > 0) lines.push(`… +${orphans} hidden`)\n\n\treturn {\n\t\ttext: lines.join('\\n'),\n\t\tshownNodes,\n\t\ttotalNodes,\n\t\thiddenNodes: entries.length - shownNodes,\n\t\tfilteredNodes,\n\t\tfoldedTextNodes,\n\t}\n}\n","/**\n * Public node IDs: `<session token>.<capture generation>:<core node id>`, e.g. `k3m9x2pa.4:h12`.\n *\n * The token binds an ID to one session and the generation binds it to one capture of that session,\n * so an ID from an earlier capture, another frame or a destroyed session can never address a node\n * of the current capture by accident.\n */\n\nexport interface ParsedAxId {\n\ttoken: string\n\tgeneration: number\n\tnodeId: string\n}\n\nconst ID_PATTERN = /^([0-9a-z]{8})\\.([1-9]\\d*):(\\S+)$/\n\n/** 40 random bits as 8 base-36 characters. */\nexport function createSessionToken(): string {\n\tconst bytes = crypto.getRandomValues(new Uint8Array(5))\n\tlet value = 0\n\tfor (const byte of bytes) value = value * 256 + byte\n\treturn value.toString(36).padStart(8, '0').slice(-8)\n}\n\nexport function captureIdOf(token: string, generation: number): string {\n\treturn `${token}.${generation}`\n}\n\nexport function publicId(captureId: string, nodeId: string): string {\n\treturn `${captureId}:${nodeId}`\n}\n\nexport function parseAxId(id: unknown): ParsedAxId | null {\n\tif (typeof id !== 'string') return null\n\tconst match = ID_PATTERN.exec(id)\n\tif (!match) return null\n\treturn { token: match[1], generation: Number(match[2]), nodeId: match[3] }\n}\n","import type { AxTreeFormatOptions, AxTreeView } from './types'\n\n/** How the tree is printed when it is added to the browser state at every step. */\nexport const OBSERVATION_FORMAT: AxTreeFormatOptions = {\n\tcompact: true,\n\trelations: true,\n\t// The accessible name already carries what a labelledby relation contributes.\n\tomitRelationTypes: ['labelledby'],\n\t// A container can be reconstructed with its whole text as its name; its children carry that text.\n\tmaxTextLength: 160,\n}\n\nexport const DEFAULT_OBSERVATION_MAX_LINES = 400\n\n/** Header and tree text for one capture, as it is shown to a model. */\nexport function formatAccessibilityObservation(view: AxTreeView, subtreeOf?: string): string {\n\tconst counts = [`${view.shownNodes} of ${view.totalNodes} nodes shown`]\n\tif (view.hiddenNodes > 0)\n\t\tcounts.push('\"… +N hidden\" marks collapsed descendants that can be expanded by ID')\n\tif (view.foldedTextNodes > 0)\n\t\tcounts.push(`${view.foldedTextNodes} blank or repeated text leaves folded`)\n\treturn [\n\t\tsubtreeOf === undefined\n\t\t\t? `Accessibility tree, capture ${view.captureId} (${counts.join('; ')}).`\n\t\t\t: `Subtree of [${subtreeOf}] in capture ${view.captureId}, not captured again (${counts.join('; ')}).`,\n\t\t\"It is a reconstruction from the page's observable state, not the browser's native accessibility tree, and it can differ from it.\",\n\t\t'Each line is [id] role \"name\" followed by value, description, states and relations. IDs are valid only until the next capture.',\n\t\t'',\n\t\tview.text,\n\t].join('\\n')\n}\n","/**\n * AccessibilityController - reads the page as a reconstructed accessibility tree and acts on its\n * nodes by ID.\n *\n * It is an adapter around the preserved core in `vendor/ax-core.js`. The core does the\n * reconstruction, the semantic computation, the identity checks and the gestures; this class only\n * adds what the project needs around it: public IDs bound to a session and a capture, sessions for\n * same-origin frames, exclusion of the agent's own interface, lazy loading, and results that keep\n * \"event sent\", \"effect observed\" and \"change persisted\" apart.\n *\n * Contract, in short:\n * - The tree is an approximation built from the page's observable state. It is not the browser's\n * native accessibility tree.\n * - Actions are synthetic DOM events and API calls (`isTrusted === false`). They are not physical\n * input: synthetic hover does not set CSS `:hover`, a synthetic `wheel` does not scroll, and a page\n * may ignore any of them.\n * - An ID is valid only for the capture that produced it. A new capture of the same session, or a\n * new session, invalidates it (`stale_id`).\n * - Closed shadow roots, cross-origin frames and browser-internal structures are out of reach.\n */\nimport { domPathOf, isWithinPath, resolveDomPath } from './domPath'\nimport type {\n\tAxCoreAgent,\n\tAxCoreFactory,\n\tAxCoreNode,\n\tAxCoreRequest,\n\tAxCoreSnapshot,\n\tAxCoreTextFragments,\n\tAxDragMode,\n\tAxStandardsCatalog,\n} from './engine'\nimport { AxError, toAxError } from './errors'\nimport { type AxEvidence, observeAction } from './evidence'\nimport { formatTree } from './format'\nimport { captureIdOf, createSessionToken, parseAxId, publicId } from './ids'\nimport {\n\tDEFAULT_OBSERVATION_MAX_LINES,\n\tOBSERVATION_FORMAT,\n\tformatAccessibilityObservation,\n} from './observation'\nimport type {\n\tAccessibilityConfig,\n\tAxActionName,\n\tAxActionOptions,\n\tAxActionOutcome,\n\tAxActionStatus,\n\tAxAttributeStandards,\n\tAxCapture,\n\tAxClickOutcome,\n\tAxDragOutcome,\n\tAxDraggable,\n\tAxElementStandards,\n\tAxFillOutcome,\n\tAxFindQuery,\n\tAxFocusOutcome,\n\tAxHoverOutcome,\n\tAxIndexedObservation,\n\tAxKeyOptions,\n\tAxKeyOutcome,\n\tAxNode,\n\tAxScrollIntoViewOutcome,\n\tAxScrollOffsets,\n\tAxScrollOutcome,\n\tAxSessionInfo,\n\tAxStateOutcome,\n\tAxSurface,\n\tAxTreeFormatOptions,\n\tAxTreeText,\n\tAxTreeView,\n\tAxVisualTarget,\n\tAxWaitQuery,\n\tAxWheelOutcome,\n} from './types'\n\nexport const DEFAULT_IGNORE_SELECTOR = '[data-page-agent-ignore], #playwright-highlight-container'\nconst DEFAULT_MAX_FRAME_SESSIONS = 8\nconst NOT_VERIFIED = 'The effect on the page was not verified; capture again to check it.'\n\n/** Collaborators the controller cannot own itself. All have working defaults except for tests. */\nexport interface AccessibilityControllerOptions extends AccessibilityConfig {\n\t/** Document of the root session. @default the global document */\n\tdocument?: Document\n\t/**\n\t * Runs an interaction with the agent's own overlays out of the way. The core hit-tests its\n\t * targets, so a visible mask would make every target look obscured.\n\t */\n\trunInteraction?: <T>(interaction: () => Promise<T>) => Promise<T>\n\t/** Loads the core. @default dynamic import of the vendored module */\n\tloadCore?: () => Promise<{ createPageAgent: AxCoreFactory }>\n\t/** Loads the standards catalog. @default dynamic import of the vendored module */\n\tloadStandards?: () => Promise<{ standardsCatalog: AxStandardsCatalog }>\n}\n\ninterface Session {\n\ttoken: string\n\tkind: 'root' | 'frame'\n\tparent: Session | null\n\tchildren: Set<Session>\n\tcore: AxCoreAgent\n\t/** Null when the frame document could not be identified; evidence is then unavailable. */\n\tdocument: Document | null\n\tgeneration: number\n\tcurrent: {\n\t\tcaptureId: string\n\t\tsnapshot: AxCoreSnapshot\n\t\tcapture: AxCapture\n\t\tcoreNodes: Map<string, AxCoreNode>\n\t\t/** Core node IDs of the agent's own interface. */\n\t\texcluded: Set<string>\n\t\t/** Temporary IDs issued by `targetAt` for this capture. */\n\t\tvisualIds: Set<string>\n\t} | null\n\tlastUsed: number\n\t/** The capture that observers asking right now will share, until it runs. */\n\tpending: Promise<AxCapture> | null\n}\n\ninterface Target {\n\tsession: Session\n\trequest: AxCoreRequest\n\tnodeId: string\n\t/** True for IDs that came from `targetAt`. */\n\tvisual: boolean\n}\n\nexport class AccessibilityController {\n\treadonly #options: AccessibilityControllerOptions\n\treadonly #sessions = new Map<string, Session>()\n\t#root: Session | null = null\n\t#factory: Promise<AxCoreFactory> | null = null\n\t#destroyed = false\n\t#clock = 0\n\n\tconstructor(options: AccessibilityControllerOptions = {}) {\n\t\tthis.#options = options\n\t}\n\n\t// ======= Capture =======\n\n\t/**\n\t * Captures the tree of a session as structured data. Every ID from an earlier capture of the same\n\t * session stops working.\n\t */\n\tasync capture(options: { sessionId?: string } = {}): Promise<AxCapture> {\n\t\tconst session = await this.#session(options.sessionId)\n\t\treturn structuredClone(await this.#observation(session))\n\t}\n\n\t/** Captures the tree of a session and returns it as readable hierarchical text. */\n\tasync tree(options: AxTreeFormatOptions & { sessionId?: string } = {}): Promise<AxTreeView> {\n\t\tconst session = await this.#session(options.sessionId)\n\t\tconst capture = await this.#observation(session)\n\t\treturn this.#view(capture, options)\n\t}\n\n\t/**\n\t * The last capture of a session as structured data, without reading the page again. It can be out\n\t * of date; its IDs are still the valid ones.\n\t */\n\tasync current(options: { sessionId?: string } = {}): Promise<AxCapture> {\n\t\tconst session = await this.#session(options.sessionId)\n\t\treturn structuredClone(this.#requireCurrent(session).capture)\n\t}\n\n\t/** Readable text of the last capture, or of one subtree of it, without reading the page again. */\n\tasync describe(options: AxTreeFormatOptions & { sessionId?: string } = {}): Promise<AxTreeView> {\n\t\tlet session: Session\n\t\tif (options.rootId !== undefined) session = this.#locate(options.rootId).session\n\t\telse session = await this.#session(options.sessionId)\n\t\treturn this.#view(this.#requireCurrent(session).capture, options)\n\t}\n\n\t/**\n\t * Captures a session and returns the text a model reads: a short header that states what the tree\n\t * is, then the compact tree, collapsed to `maxLines`.\n\t */\n\tasync observe(options: { sessionId?: string; maxLines?: number } = {}): Promise<string> {\n\t\tconst view = await this.tree({\n\t\t\t...OBSERVATION_FORMAT,\n\t\t\tsessionId: options.sessionId,\n\t\t\tmaxLines:\n\t\t\t\toptions.maxLines ?? this.#options.observationMaxLines ?? DEFAULT_OBSERVATION_MAX_LINES,\n\t\t})\n\t\treturn formatAccessibilityObservation(view)\n\t}\n\n\t/** The same text for one subtree of the current capture, without capturing again. */\n\tasync expand(id: string, options: { maxLines?: number } = {}): Promise<string> {\n\t\tconst view = await this.describe({\n\t\t\t...OBSERVATION_FORMAT,\n\t\t\trootId: id,\n\t\t\tmaxLines:\n\t\t\t\toptions.maxLines ?? this.#options.observationMaxLines ?? DEFAULT_OBSERVATION_MAX_LINES,\n\t\t})\n\t\treturn formatAccessibilityObservation(view, id)\n\t}\n\n\t/**\n\t * Captures the page and returns the tree the agent reads, with a short numeric index on every node\n\t * that has an element. The indexes are the handles of the existing index-based tools; `ids` maps\n\t * each one to the node ID to act on.\n\t *\n\t * `viewportExpansion` is the margin around the viewport, in CSS pixels, within which nodes are\n\t * listed; `-1` lists the whole page. A whole page that does not fit in `maxLines` is narrowed to the\n\t * viewport instead of being cut arbitrarily.\n\t */\n\tasync observeIndexed(\n\t\toptions: {\n\t\t\tmaxLines?: number\n\t\t\tviewportExpansion?: number\n\t\t\t/** Document Y start (page coordinates, CSS px). Inclusive overlap with node bounds. */\n\t\t\tyMin?: number\n\t\t\t/** Document Y end (page coordinates, CSS px). Inclusive overlap with node bounds. */\n\t\t\tyMax?: number\n\t\t\t/** Case-insensitive match against role, name, description or string value. */\n\t\t\tquery?: string\n\t\t\t/**\n\t\t\t * When false, lines keep role/name but no `[index]` action handles.\n\t\t\t * Use for read-only context slices that must not replace the agent indexes.\n\t\t\t * @default true\n\t\t\t */\n\t\t\tindexLabels?: boolean\n\t\t} = {}\n\t): Promise<AxIndexedObservation> {\n\t\tconst session = await this.#session()\n\t\tconst capture = await this.#observation(session)\n\t\tconst doc = session.document\n\t\tconst maxLines =\n\t\t\toptions.maxLines ?? this.#options.observationMaxLines ?? DEFAULT_OBSERVATION_MAX_LINES\n\t\tconst indexLabels = options.indexLabels !== false\n\t\tconst query = options.query?.trim().toLowerCase() || ''\n\t\tconst hasYRange = options.yMin !== undefined || options.yMax !== undefined\n\t\tconst yMin = options.yMin ?? Number.NEGATIVE_INFINITY\n\t\tconst yMax = options.yMax ?? Number.POSITIVE_INFINITY\n\n\t\t// The capture was made in this same task, so each path still points at the node it came from.\n\t\tconst domNodes = new Map<string, Node | null>()\n\t\tfor (const node of capture.nodes)\n\t\t\tdomNodes.set(\n\t\t\t\tnode.id,\n\t\t\t\t!doc ? null : node.domPath === '' ? doc : resolveDomPath(doc, node.domPath)\n\t\t\t)\n\t\tconst view = doc?.defaultView\n\t\tconst scrollY = view?.scrollY ?? 0\n\t\t// This is geometry, not a claim that the element is visible or unobscured.\n\t\t// Missing and zero-size geometry is left unannotated; no nodes are filtered.\n\t\tconst viewportAnnotation = (node: AxNode): string | null => {\n\t\t\tconst domNode = domNodes.get(node.id)\n\t\t\tif (!view || !domNode || domNode.nodeType !== 1) return null\n\t\t\ttry {\n\t\t\t\tconst rect = (domNode as Element).getBoundingClientRect()\n\t\t\t\tif (\n\t\t\t\t\t![rect.left, rect.top, rect.right, rect.bottom, rect.width, rect.height].every(\n\t\t\t\t\t\tNumber.isFinite\n\t\t\t\t\t) ||\n\t\t\t\t\trect.width <= 0 ||\n\t\t\t\t\trect.height <= 0\n\t\t\t\t)\n\t\t\t\t\treturn null\n\t\t\t\tif (rect.bottom <= 0) return 'viewport: outside-above'\n\t\t\t\tif (rect.top >= view.innerHeight) return 'viewport: outside-below'\n\t\t\t\tif (rect.right <= 0) return 'viewport: outside-left'\n\t\t\t\tif (rect.left >= view.innerWidth) return 'viewport: outside-right'\n\t\t\t\treturn 'viewport: intersects'\n\t\t\t} catch {\n\t\t\t\treturn null\n\t\t\t}\n\t\t}\n\t\tconst documentBand = (node: AxNode): { top: number; bottom: number } | null => {\n\t\t\tconst domNode = domNodes.get(node.id)\n\t\t\tif (!view || !domNode || domNode === doc) return null\n\t\t\tconst element = domNode.nodeType === 1 ? (domNode as Element) : domNode.parentElement\n\t\t\tif (!element) return null\n\t\t\ttry {\n\t\t\t\tconst rect = element.getBoundingClientRect()\n\t\t\t\tif (\n\t\t\t\t\t![rect.top, rect.bottom, rect.width, rect.height].every(Number.isFinite) ||\n\t\t\t\t\trect.width <= 0 ||\n\t\t\t\t\trect.height <= 0\n\t\t\t\t)\n\t\t\t\t\treturn null\n\t\t\t\treturn { top: rect.top + scrollY, bottom: rect.bottom + scrollY }\n\t\t\t} catch {\n\t\t\t\treturn null\n\t\t\t}\n\t\t}\n\t\tconst inViewport = (margin: number) => (node: AxNode) => {\n\t\t\tconst domNode = domNodes.get(node.id)\n\t\t\tif (!view || !domNode || domNode === doc) return true\n\t\t\tconst element = domNode.nodeType === 1 ? (domNode as Element) : domNode.parentElement\n\t\t\tif (!element) return true\n\t\t\tconst rect = element.getBoundingClientRect()\n\t\t\treturn (\n\t\t\t\trect.bottom >= -margin &&\n\t\t\t\trect.top <= view.innerHeight + margin &&\n\t\t\t\trect.right >= -margin &&\n\t\t\t\trect.left <= view.innerWidth + margin\n\t\t\t)\n\t\t}\n\t\tconst matchesQuery = (node: AxNode) => {\n\t\t\tif (!query) return true\n\t\t\tconst value =\n\t\t\t\ttypeof node.value === 'string' || typeof node.value === 'number' ? String(node.value) : ''\n\t\t\tconst haystack = [node.role, node.name, node.description, value].join(' ').toLowerCase()\n\t\t\treturn haystack.includes(query)\n\t\t}\n\t\tconst inDocumentY = (node: AxNode) => {\n\t\t\tif (!hasYRange) return true\n\t\t\tconst band = documentBand(node)\n\t\t\tif (!band) return true\n\t\t\treturn band.bottom >= yMin && band.top <= yMax\n\t\t}\n\n\t\tconst format = (filter?: (node: AxNode) => boolean) => {\n\t\t\tconst ids: string[] = []\n\t\t\tconst labels: string[] = []\n\t\t\tconst combined =\n\t\t\t\tfilter || hasYRange || query\n\t\t\t\t\t? (node: AxNode) =>\n\t\t\t\t\t\t\t(filter ? filter(node) : true) && inDocumentY(node) && matchesQuery(node)\n\t\t\t\t\t: undefined\n\t\t\tconst text = formatTree(capture.nodes, {\n\t\t\t\t...OBSERVATION_FORMAT,\n\t\t\t\tmaxLines,\n\t\t\t\tfilter: combined,\n\t\t\t\tannotation: viewportAnnotation,\n\t\t\t\tidLabel: (node) => {\n\t\t\t\t\tif (domNodes.get(node.id)?.nodeType !== 1) return null\n\t\t\t\t\tlabels.push(`${node.role} ${JSON.stringify(clip(node.name))}`)\n\t\t\t\t\tif (!indexLabels) return null\n\t\t\t\t\treturn String(ids.push(node.id) - 1)\n\t\t\t\t},\n\t\t\t})\n\t\t\treturn { ...text, ids, labels }\n\t\t}\n\n\t\tconst expansion = options.viewportExpansion ?? -1\n\t\tconst sliceMode = hasYRange || Boolean(query)\n\t\tlet viewportOnly = expansion !== -1 && !sliceMode\n\t\tlet result = format(viewportOnly ? inViewport(expansion) : undefined)\n\t\tif (!viewportOnly && !sliceMode && result.hiddenNodes > 0) {\n\t\t\tviewportOnly = true\n\t\t\tresult = format(inViewport(0))\n\t\t}\n\n\t\treturn {\n\t\t\t...result,\n\t\t\tcaptureId: capture.captureId,\n\t\t\tviewportOnly,\n\t\t\texcludedNodeCount: capture.excludedNodeCount,\n\t\t\tdurationMs: capture.durationMs,\n\t\t}\n\t}\n\n\t/**\n\t * The element now at the captured path of a node, or null. It is for visual feedback and for\n\t * reading, and it is not validated: always act through the action methods, which are.\n\t */\n\tasync elementAt(id: string): Promise<Element | null> {\n\t\tconst { session, nodeId } = this.#locate(id)\n\t\tconst domPath = session.current?.coreNodes.get(nodeId)?.domPath\n\t\tif (!session.document || !domPath) return null\n\t\tconst node = resolveDomPath(session.document, domPath)\n\t\treturn node?.nodeType === 1 ? (node as Element) : null\n\t}\n\n\t/** Captures and returns the non-ignored nodes with this role and, if given, this exact name. */\n\tasync find(query: AxFindQuery): Promise<{ captureId: string; nodes: AxNode[] }> {\n\t\tif (\n\t\t\ttypeof query?.role !== 'string' ||\n\t\t\t!query.role ||\n\t\t\t!(query.name === undefined || typeof query.name === 'string')\n\t\t)\n\t\t\tthrow new AxError('invalid', 'invalid: role is required and name must be a string')\n\t\tconst capture = await this.capture({ sessionId: query.sessionId })\n\t\treturn {\n\t\t\tcaptureId: capture.captureId,\n\t\t\tnodes: capture.nodes.filter(\n\t\t\t\t(node) =>\n\t\t\t\t\t!node.ignored &&\n\t\t\t\t\tnode.role === query.role &&\n\t\t\t\t\t(query.name === undefined || node.name === query.name)\n\t\t\t),\n\t\t}\n\t}\n\n\t/**\n\t * Polls `find` until a node matches, the timeout passes or the signal aborts. Each poll is a full\n\t * synchronous reconstruction, and very brief states can be missed.\n\t */\n\tasync waitFor(query: AxWaitQuery): Promise<{ captureId: string; nodes: AxNode[] }> {\n\t\tconst { timeoutMs = 5000, intervalMs = 100, signal } = query\n\t\tif (\n\t\t\t!Number.isInteger(timeoutMs) ||\n\t\t\ttimeoutMs < 0 ||\n\t\t\ttimeoutMs > 60000 ||\n\t\t\t!Number.isInteger(intervalMs) ||\n\t\t\tintervalMs < 20 ||\n\t\t\tintervalMs > 1000\n\t\t)\n\t\t\tthrow new AxError('invalid', 'invalid: wait timeout or interval')\n\n\t\tconst started = performance.now()\n\t\tfor (;;) {\n\t\t\tif (signal?.aborted) throw new AxError('aborted', 'aborted: wait cancelled')\n\t\t\tconst result = await this.find(query)\n\t\t\tif (result.nodes.length > 0) return result\n\t\t\tconst remaining = timeoutMs - (performance.now() - started)\n\t\t\tif (remaining <= 0) throw new AxError('timeout', 'timeout: element not found')\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tconst done = () => {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\tsignal?.removeEventListener('abort', done)\n\t\t\t\t\tresolve()\n\t\t\t\t}\n\t\t\t\tconst timer = setTimeout(done, Math.min(intervalMs, remaining))\n\t\t\t\tsignal?.addEventListener('abort', done, { once: true })\n\t\t\t})\n\t\t}\n\t}\n\n\t// ======= Actions =======\n\n\t/** Synthetic click through the element's own `click()`. It can navigate or submit a form. */\n\tasync click(id: string, options: AxActionOptions = {}): Promise<AxClickOutcome> {\n\t\treturn this.#act('click', id, options, (core, request) => core.click(request), {\n\t\t\tstatus: () => 'dispatched',\n\t\t\tsummary: () => `Synthetic click dispatched (isTrusted is false). ${NOT_VERIFIED}`,\n\t\t})\n\t}\n\n\t/** Two synthetic pointer, mouse and click sequences followed by `dblclick`. */\n\tasync doubleClick(id: string, options: AxActionOptions = {}): Promise<AxClickOutcome> {\n\t\treturn this.#act('doubleClick', id, options, (core, request) => core.doubleClick(request), {\n\t\t\tstatus: () => 'dispatched',\n\t\t\tsummary: () =>\n\t\t\t\t`Two synthetic click sequences and a dblclick were dispatched (isTrusted is false). It is not a physical double click and does not select text natively. ${NOT_VERIFIED}`,\n\t\t})\n\t}\n\n\t/** Calls `focus()` and reports whether the element is focused afterwards. */\n\tasync focus(id: string): Promise<AxFocusOutcome> {\n\t\treturn this.#act('focus', id, {}, (core, request) => core.focus(request), {\n\t\t\tstatus: (result) => (result.focused ? 'applied' : 'not_applied'),\n\t\t\tsummary: (result) =>\n\t\t\t\tresult.focused\n\t\t\t\t\t? 'The element is focused.'\n\t\t\t\t\t: 'focus() was called but the element is not the focused element.',\n\t\t})\n\t}\n\n\t/**\n\t * Replaces the value of a text-like input, textarea or contenteditable element and dispatches\n\t * `input` and `change`. It does not type key by key.\n\t */\n\tasync fill(id: string, value: string, options: AxActionOptions = {}): Promise<AxFillOutcome> {\n\t\treturn this.#act('fill', id, options, (core, request) => core.fill({ ...request, value }), {\n\t\t\tstatus: (result) => (result.applied ? 'applied' : 'not_applied'),\n\t\t\tsummary: (result) =>\n\t\t\t\t(result.applied\n\t\t\t\t\t? 'Right after the events the control held the requested value.'\n\t\t\t\t\t: 'Right after the events the control did not hold the requested value.') +\n\t\t\t\tchangeNote(result.changeDispatched) +\n\t\t\t\t' This does not show that the page validated or saved it.',\n\t\t})\n\t}\n\n\t/** Selects by option value in a native `<select>`. Pass an array for `<select multiple>`. */\n\tasync select(\n\t\tid: string,\n\t\tvalue: string | string[],\n\t\toptions: AxActionOptions = {}\n\t): Promise<AxStateOutcome> {\n\t\t// The core reads `value` for a single select and `values` for a multiple one. A single value is\n\t\t// sent in both shapes, so one option can be chosen in either kind of control.\n\t\tconst values = Array.isArray(value) ? value : [value]\n\t\tconst selection = values.length === 1 ? { value: values[0], values } : { values }\n\t\treturn this.#act(\n\t\t\t'select',\n\t\t\tid,\n\t\t\toptions,\n\t\t\t(core, request) => core.select({ ...request, ...selection }),\n\t\t\t{\n\t\t\t\tstatus: stateStatus,\n\t\t\t\tsummary: (result) => stateSummary(result, 'selection'),\n\t\t\t}\n\t\t)\n\t}\n\n\t/** Checks or unchecks a native checkbox, or selects a native radio. */\n\tasync setChecked(\n\t\tid: string,\n\t\tchecked = true,\n\t\toptions: AxActionOptions = {}\n\t): Promise<AxStateOutcome> {\n\t\treturn this.#act(\n\t\t\t'setChecked',\n\t\t\tid,\n\t\t\toptions,\n\t\t\t(core, request) => core.setChecked({ ...request, checked }),\n\t\t\t{\n\t\t\t\tstatus: stateStatus,\n\t\t\t\tsummary: (result) => stateSummary(result, 'checked state'),\n\t\t\t}\n\t\t)\n\t}\n\n\t/** Sets a native `<input type=\"range\">`. Values the browser would clamp or round are refused. */\n\tasync setRange(\n\t\tid: string,\n\t\tvalue: number,\n\t\toptions: AxActionOptions = {}\n\t): Promise<AxStateOutcome> {\n\t\treturn this.#act(\n\t\t\t'setRange',\n\t\t\tid,\n\t\t\toptions,\n\t\t\t(core, request) => core.setRange({ ...request, value }),\n\t\t\t{\n\t\t\t\tstatus: stateStatus,\n\t\t\t\tsummary: (result) => stateSummary(result, 'value'),\n\t\t\t}\n\t\t)\n\t}\n\n\t/**\n\t * Dispatches synthetic `keydown` and `keyup` to the focused target. The key's native behaviour is\n\t * not performed: no character is typed and `Tab` does not move focus.\n\t */\n\tasync pressKey(\n\t\tid: string,\n\t\tkey: string,\n\t\toptions: AxKeyOptions & AxActionOptions = {}\n\t): Promise<AxKeyOutcome> {\n\t\tconst { scrollIntoView, ...keyOptions } = options\n\t\treturn this.#act(\n\t\t\t'pressKey',\n\t\t\tid,\n\t\t\t{ scrollIntoView },\n\t\t\t(core, request) => core.key({ ...request, key, ...keyOptions }),\n\t\t\t{\n\t\t\t\tstatus: () => 'dispatched',\n\t\t\t\tsummary: (result) =>\n\t\t\t\t\t`Synthetic keydown${result.keyupDispatched ? ' and keyup' : ''} dispatched` +\n\t\t\t\t\t(result.keyupDispatched ? '' : ' (keyup withheld: the target lost focus)') +\n\t\t\t\t\t`; the page ${result.defaultPrevented ? 'cancelled' : 'did not cancel'} keydown. ` +\n\t\t\t\t\t`The key's native behaviour was not performed. ${NOT_VERIFIED}`,\n\t\t\t}\n\t\t)\n\t}\n\n\t/**\n\t * Dispatches synthetic pointer and mouse enter, over and move events. The real pointer does not\n\t * move and CSS `:hover` is not activated, so CSS-only menus may stay closed.\n\t */\n\tasync hover(id: string, options: AxActionOptions = {}): Promise<AxHoverOutcome> {\n\t\treturn this.#act('hover', id, options, (core, request) => core.hover(request), {\n\t\t\tstatus: () => 'dispatched',\n\t\t\tsummary: () =>\n\t\t\t\t`Synthetic hover events dispatched (isTrusted is false). CSS :hover was not activated and the real pointer did not move. ${NOT_VERIFIED}`,\n\t\t})\n\t}\n\n\t/**\n\t * Drags a source node to a destination node of the same capture.\n\t *\n\t * - `html5`: DragEvents with a synthetic DataTransfer. `drop` is sent only if the destination\n\t * cancels `dragover`.\n\t * - `pointer`: a short pointer and mouse sequence with one intermediate point.\n\t * - `pointer-paced`: the same sequence spaced in time for libraries that wait between events.\n\t * The session refuses captures and actions until it settles.\n\t */\n\tasync drag(\n\t\tsourceId: string,\n\t\ttargetId: string,\n\t\tmode: AxDragMode = 'html5'\n\t): Promise<AxDragOutcome> {\n\t\tconst source = this.#locate(sourceId)\n\t\tconst target = this.#locate(targetId)\n\t\tif (source.session !== target.session)\n\t\t\tthrow new AxError(\n\t\t\t\t'invalid',\n\t\t\t\t'invalid: source and destination must belong to the same session and capture',\n\t\t\t\t{ action: 'drag' }\n\t\t\t)\n\t\tconst { result, evidence } = await this.#run('drag', source.session, false, () =>\n\t\t\tsource.session.core.dragTo({ ...source.request, targetNodeId: target.nodeId, mode })\n\t\t)\n\t\treturn {\n\t\t\taction: 'drag',\n\t\t\tstatus: result.mode === 'html5' && !result.dropDispatched ? 'not_applied' : 'dispatched',\n\t\t\tresult,\n\t\t\tevidence,\n\t\t\tscrolledIntoView: false,\n\t\t\t...PAGE_SCRIPT,\n\t\t\tsummary: dragSummary(result),\n\t\t}\n\t}\n\n\t/**\n\t * Programmatic scroll of a container, or of the session viewport when no ID is given, in CSS\n\t * pixels. Reports the positions right before and after.\n\t */\n\tasync scroll(offsets: AxScrollOffsets & { sessionId?: string }): Promise<AxScrollOutcome>\n\tasync scroll(id: string, offsets: AxScrollOffsets): Promise<AxScrollOutcome>\n\tasync scroll(\n\t\tidOrOffsets: string | (AxScrollOffsets & { sessionId?: string }),\n\t\toffsets?: AxScrollOffsets\n\t): Promise<AxScrollOutcome> {\n\t\tconst { session, request } = await this.#motion(idOrOffsets, offsets)\n\t\tconst { result, evidence } = await this.#run('scroll', session, false, () =>\n\t\t\tsession.core.scroll(request)\n\t\t)\n\t\treturn {\n\t\t\taction: 'scroll',\n\t\t\tstatus: result.moved ? 'applied' : 'not_applied',\n\t\t\tresult,\n\t\t\tevidence,\n\t\t\tscrolledIntoView: false,\n\t\t\t...PAGE_SCRIPT,\n\t\t\tsummary: result.moved\n\t\t\t\t? `Scrolled from (${result.before.x}, ${result.before.y}) to (${result.after.x}, ${result.after.y}). Effects the page runs after scrolling may not have finished.`\n\t\t\t\t: 'The scroll was requested but the position did not change (edge reached, not scrollable, or limited by the page).',\n\t\t}\n\t}\n\n\t/**\n\t * Dispatches one synthetic `WheelEvent` to a container or to the session document. It does not\n\t * scroll: use `scroll` to move content, and this only when a component needs the event.\n\t */\n\tasync wheel(offsets: AxScrollOffsets & { sessionId?: string }): Promise<AxWheelOutcome>\n\tasync wheel(id: string, offsets: AxScrollOffsets): Promise<AxWheelOutcome>\n\tasync wheel(\n\t\tidOrOffsets: string | (AxScrollOffsets & { sessionId?: string }),\n\t\toffsets?: AxScrollOffsets\n\t): Promise<AxWheelOutcome> {\n\t\tconst { session, request } = await this.#motion(idOrOffsets, offsets)\n\t\tconst { result, evidence } = await this.#run('wheel', session, false, () =>\n\t\t\tsession.core.wheel(request)\n\t\t)\n\t\treturn {\n\t\t\taction: 'wheel',\n\t\t\tstatus: 'dispatched',\n\t\t\tresult,\n\t\t\tevidence,\n\t\t\tscrolledIntoView: false,\n\t\t\t...PAGE_SCRIPT,\n\t\t\tsummary: `Synthetic wheel event dispatched; the page ${result.defaultPrevented ? 'cancelled' : 'did not cancel'} it. It does not perform native scrolling. ${NOT_VERIFIED}`,\n\t\t}\n\t}\n\n\t/** Calls `scrollIntoView` on the element. Movement is not measured. */\n\tasync scrollIntoView(id: string): Promise<AxScrollIntoViewOutcome> {\n\t\treturn this.#act('scrollIntoView', id, {}, (core, request) => core.scrollIntoView(request), {\n\t\t\tstatus: () => 'requested',\n\t\t\tsummary: () => 'scrollIntoView was called. Whether anything moved was not measured.',\n\t\t})\n\t}\n\n\t// ======= Inspection =======\n\n\t/**\n\t * Nodes of the current capture that look draggable (`draggable`, `aria-grabbed`, grab cursor).\n\t * A heuristic: it can list false positives and miss components that drag through handlers.\n\t */\n\tasync draggables(options: { sessionId?: string } = {}): Promise<AxDraggable[]> {\n\t\tconst session = await this.#session(options.sessionId)\n\t\tconst current = this.#requireCurrent(session)\n\t\treturn this.#guard('draggables', () =>\n\t\t\tsession.core\n\t\t\t\t.draggableCandidates({ snapshotId: current.snapshot.snapshotId })\n\t\t\t\t.filter((candidate) => !current.excluded.has(candidate.nodeId))\n\t\t\t\t.map(({ nodeId, ...rest }) => ({ id: publicId(current.captureId, nodeId), ...rest }))\n\t\t)\n\t}\n\n\t/**\n\t * Hit-tests viewport coordinates (CSS pixels) and returns a temporary ID for the element found.\n\t * It reads no pixels and invents no role. The ID can be a drag source or destination and uses\n\t * exactly this point.\n\t */\n\tasync targetAt(\n\t\tx: number,\n\t\ty: number,\n\t\toptions: { sessionId?: string } = {}\n\t): Promise<AxVisualTarget> {\n\t\tconst session = await this.#session(options.sessionId)\n\t\tconst current = this.#requireCurrent(session)\n\t\tconst { result } = await this.#run('targetAt', session, true, () => {\n\t\t\tif (this.#hitsOwnInterface(session, x, y))\n\t\t\t\tthrow new AxError('blocked', \"blocked: the point is on the agent's own interface\")\n\t\t\treturn session.core.targetAt({ snapshotId: current.snapshot.snapshotId, x, y })\n\t\t})\n\t\tconst { nodeId, snapshotId: _snapshotId, ...target } = result\n\t\tcurrent.visualIds.add(nodeId)\n\t\treturn { id: publicId(current.captureId, nodeId), ...target }\n\t}\n\n\t/**\n\t * `canvas`, `svg` and `role=application` elements, including those in open shadow roots. This is a\n\t * list of DOM surfaces, not of what is drawn on them, and a null ID cannot be a target.\n\t */\n\tasync surfaces(options: { sessionId?: string } = {}): Promise<AxSurface[]> {\n\t\tconst session = await this.#session(options.sessionId)\n\t\tconst current = this.#requireCurrent(session)\n\t\treturn this.#guard('surfaces', () => {\n\t\t\tconst own = this.#ownSurfaceKeys(session)\n\t\t\treturn session.core\n\t\t\t\t.visualSurfaces({ snapshotId: current.snapshot.snapshotId })\n\t\t\t\t.filter((surface) => {\n\t\t\t\t\tif (surface.nodeId !== null) return !current.excluded.has(surface.nodeId)\n\t\t\t\t\tconst key = surfaceKey(surface.tag, surface.bounds)\n\t\t\t\t\tconst count = own.get(key) ?? 0\n\t\t\t\t\tif (count === 0) return true\n\t\t\t\t\town.set(key, count - 1)\n\t\t\t\t\treturn false\n\t\t\t\t})\n\t\t\t\t.map(({ nodeId, ...rest }) => ({\n\t\t\t\t\tid: nodeId === null ? null : publicId(current.captureId, nodeId),\n\t\t\t\t\t...rest,\n\t\t\t\t}))\n\t\t})\n\t}\n\n\t/** Geometric estimate of the visual runs of one `StaticText` node. Not part of the tree. */\n\tasync textFragments(id: string): Promise<AxCoreTextFragments> {\n\t\tconst target = this.#locate(id)\n\t\treturn this.#guard('textFragments', () => target.session.core.textFragments(target.request))\n\t}\n\n\t// ======= Frames =======\n\n\t/**\n\t * Opens a separate session for a same-origin iframe node. Capture it with the returned\n\t * `sessionId` to get its own IDs. Cross-origin and sandboxed frames are not available.\n\t */\n\tasync openFrame(id: string): Promise<{ sessionId: string; closedSessionIds: string[] }> {\n\t\tconst target = this.#locate(id)\n\t\tconst { session: parent } = target\n\t\tconst core = this.#guard('openFrame', () => parent.core.frame(target.request))\n\n\t\t// The core has just confirmed that the captured element is still at its captured path.\n\t\tlet frameDocument: Document | null = null\n\t\tconst domPath = parent.current?.coreNodes.get(target.nodeId)?.domPath\n\t\tif (parent.document && domPath) {\n\t\t\tconst element = resolveDomPath(parent.document, domPath) as HTMLIFrameElement | null\n\t\t\ttry {\n\t\t\t\tframeDocument = element?.contentDocument ?? null\n\t\t\t} catch {\n\t\t\t\tframeDocument = null\n\t\t\t}\n\t\t}\n\n\t\tconst session = this.#register({ kind: 'frame', parent, core, document: frameDocument })\n\t\treturn { sessionId: session.token, closedSessionIds: this.#evictFrameSessions(session) }\n\t}\n\n\t/** Closes a frame session and the sessions opened from it. Its IDs stop working. */\n\tasync closeSession(sessionId: string): Promise<void> {\n\t\tconst session = this.#sessions.get(sessionId)\n\t\tif (!session) return\n\t\tif (session.kind === 'root')\n\t\t\tthrow new AxError('invalid', 'invalid: the root session is closed with destroy()')\n\t\tthis.#close(session)\n\t}\n\n\t/** Open sessions, root first. */\n\tasync sessions(): Promise<AxSessionInfo[]> {\n\t\treturn [...this.#sessions.values()].map((session) => ({\n\t\t\tsessionId: session.token,\n\t\t\tkind: session.kind,\n\t\t\tparentSessionId: session.parent?.token ?? null,\n\t\t\tcaptureId: session.current?.captureId ?? null,\n\t\t\tframeUrl: session.current?.capture.frameUrl ?? null,\n\t\t}))\n\t}\n\n\t// ======= Standards index =======\n\n\t/**\n\t * HTML-AAM cases indexed for an element, with the AccName step order. A lookup of candidate roles\n\t * from two Working Drafts: it does not evaluate conditions and does not show what the\n\t * reconstruction implements.\n\t */\n\tasync standards(element: string): Promise<AxElementStandards> {\n\t\tif (typeof element !== 'string' || !element.trim())\n\t\t\tthrow new AxError('invalid', 'invalid: provide an HTML element name, for example \"button\"')\n\t\tconst catalog = await this.#standards()\n\t\tconst name = element.trim().toLowerCase()\n\t\treturn {\n\t\t\telement: name,\n\t\t\tcases: catalog.htmlAam.cases.filter((item) => item.element === name),\n\t\t\thtmlAam: catalog.htmlAam.document,\n\t\t\taccname: {\n\t\t\t\tdocument: catalog.accname.document,\n\t\t\t\tnameSteps: catalog.accname.nameSteps,\n\t\t\t\tdescriptionSteps: catalog.accname.descriptionSteps,\n\t\t\t},\n\t\t\tnote: catalog.disclaimer,\n\t\t}\n\t}\n\n\t/** HTML-AAM cases indexed for an attribute. Same caveats as `standards`. */\n\tasync attributeStandards(attribute: string): Promise<AxAttributeStandards> {\n\t\tif (typeof attribute !== 'string' || !attribute.trim())\n\t\t\tthrow new AxError('invalid', 'invalid: provide an HTML attribute name, for example \"checked\"')\n\t\tconst catalog = await this.#standards()\n\t\tconst name = attribute.trim().toLowerCase()\n\t\treturn {\n\t\t\tattribute: name,\n\t\t\tcases: catalog.htmlAam.attributeCases.filter((item) => item.attribute === name),\n\t\t\thtmlAam: catalog.htmlAam.document,\n\t\t\tnote: catalog.disclaimer,\n\t\t}\n\t}\n\n\t// ======= Lifecycle =======\n\n\t/** Ends every session. All IDs stop working and the controller cannot be used again. */\n\tdestroy(): void {\n\t\tthis.#destroyed = true\n\t\tif (this.#root) this.#close(this.#root)\n\t\tthis.#root = null\n\t}\n\n\t// ======= Internals =======\n\n\tasync #core(): Promise<AxCoreFactory> {\n\t\tthis.#factory ??= (this.#options.loadCore ?? (() => import('./vendor/ax-core.js')))().then(\n\t\t\t(module) => module.createPageAgent,\n\t\t\t(error: unknown) => {\n\t\t\t\tthis.#factory = null\n\t\t\t\tthrow new AxError(\n\t\t\t\t\t'engine_unavailable',\n\t\t\t\t\t`engine_unavailable: the accessibility core could not be loaded (${String(error)})`,\n\t\t\t\t\t{ cause: error }\n\t\t\t\t)\n\t\t\t}\n\t\t)\n\t\treturn this.#factory\n\t}\n\n\tasync #standards(): Promise<AxStandardsCatalog> {\n\t\tconst load = this.#options.loadStandards ?? (() => import('./vendor/ax-standards.js'))\n\t\treturn (await load()).standardsCatalog\n\t}\n\n\t/** The root session, created on first use, or an open session by ID. */\n\tasync #session(sessionId?: string): Promise<Session> {\n\t\tif (this.#destroyed)\n\t\t\tthrow new AxError(\n\t\t\t\t'session_closed',\n\t\t\t\t'session_closed: the accessibility controller was destroyed'\n\t\t\t)\n\t\tif (sessionId !== undefined) {\n\t\t\tconst session = this.#sessions.get(sessionId)\n\t\t\tif (!session)\n\t\t\t\tthrow new AxError('session_closed', `session_closed: no open session \"${sessionId}\"`)\n\t\t\tthis.#touch(session)\n\t\t\treturn session\n\t\t}\n\t\tif (!this.#root) {\n\t\t\tconst createPageAgent = await this.#core()\n\t\t\tif (this.#destroyed)\n\t\t\t\tthrow new AxError(\n\t\t\t\t\t'session_closed',\n\t\t\t\t\t'session_closed: the accessibility controller was destroyed'\n\t\t\t\t)\n\t\t\t// A concurrent call may have created it while the core was loading.\n\t\t\tif (!this.#root) {\n\t\t\t\tconst doc = this.#options.document ?? document\n\t\t\t\tconst core = this.#guard('session', () =>\n\t\t\t\t\tcreatePageAgent({\n\t\t\t\t\t\tdocument: doc,\n\t\t\t\t\t\t...(this.#options.maxNodes !== undefined && { maxNodes: this.#options.maxNodes }),\n\t\t\t\t\t\t...(this.#options.maxDurationMs !== undefined && {\n\t\t\t\t\t\t\tmaxDurationMs: this.#options.maxDurationMs,\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t\tthis.#root = this.#register({ kind: 'root', parent: null, core, document: doc })\n\t\t\t}\n\t\t}\n\t\tthis.#touch(this.#root)\n\t\treturn this.#root\n\t}\n\n\t#register(init: Pick<Session, 'kind' | 'parent' | 'core' | 'document'>): Session {\n\t\tlet token = createSessionToken()\n\t\twhile (this.#sessions.has(token)) token = createSessionToken()\n\t\tconst session: Session = {\n\t\t\t...init,\n\t\t\ttoken,\n\t\t\tchildren: new Set(),\n\t\t\tgeneration: 0,\n\t\t\tcurrent: null,\n\t\t\tlastUsed: ++this.#clock,\n\t\t\tpending: null,\n\t\t}\n\t\tinit.parent?.children.add(session)\n\t\tthis.#sessions.set(token, session)\n\t\treturn session\n\t}\n\n\t/** Closes a session and the sessions opened from it. Returns the IDs of all that were closed. */\n\t#close(session: Session): string[] {\n\t\tconst closed = [...session.children].flatMap((child) => this.#close(child))\n\t\tsession.parent?.children.delete(session)\n\t\tthis.#sessions.delete(session.token)\n\t\tsession.current = null\n\t\ttry {\n\t\t\tsession.core.destroy()\n\t\t} catch (error) {\n\t\t\tconsole.warn('[AccessibilityController] core session did not close cleanly', error)\n\t\t}\n\t\treturn [...closed, session.token]\n\t}\n\n\t/** Marks a session as just used. A frame in use keeps the frames it was opened from in use too. */\n\t#touch(session: Session): void {\n\t\tconst now = ++this.#clock\n\t\tfor (let current: Session | null = session; current; current = current.parent)\n\t\t\tcurrent.lastUsed = now\n\t}\n\n\t/** Keeps at most `maxFrameSessions` frame sessions, closing the least recently used first. */\n\t#evictFrameSessions(keep: Session): string[] {\n\t\tconst limit = this.#options.maxFrameSessions ?? DEFAULT_MAX_FRAME_SESSIONS\n\t\tconst closed: string[] = []\n\t\tconst isAncestorOfKept = (session: Session) => {\n\t\t\tfor (let current = keep.parent; current; current = current.parent)\n\t\t\t\tif (current === session) return true\n\t\t\treturn false\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst frames = [...this.#sessions.values()].filter((session) => session.kind === 'frame')\n\t\t\tif (frames.length <= limit) break\n\t\t\tconst victim = frames\n\t\t\t\t.filter((session) => session !== keep && !isAncestorOfKept(session))\n\t\t\t\t.sort((a, b) => a.lastUsed - b.lastUsed)[0]\n\t\t\tif (!victim) break\n\t\t\tclosed.push(...this.#close(victim))\n\t\t}\n\t\treturn closed\n\t}\n\n\t/**\n\t * One capture for every observer that asks before it runs. A capture voids the IDs of the one\n\t * before it, so two observers reading at the same moment (the agent's step and a script, say) would\n\t * otherwise invalidate each other, and pay for two reconstructions.\n\t *\n\t * Nothing is reused across time: the shared capture runs after every request that joins it, and a\n\t * request made once it has run starts a new one. Actions never use it; they are validated by the\n\t * core against the live page every time.\n\t *\n\t * It runs in a microtask, not a timer: timers are throttled in background tabs, and a microtask\n\t * leaves the page no chance to change between the request and the capture.\n\t */\n\t#observation(session: Session): Promise<AxCapture> {\n\t\tsession.pending ??= new Promise<AxCapture>((resolve, reject) => {\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tsession.pending = null\n\t\t\t\ttry {\n\t\t\t\t\tif (!this.#sessions.has(session.token))\n\t\t\t\t\t\tthrow new AxError('session_closed', 'session_closed: the session was closed')\n\t\t\t\t\tresolve(this.#capture(session))\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(toAxError(error, 'capture'))\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t\treturn session.pending\n\t}\n\n\t#capture(session: Session): AxCapture {\n\t\tconst started = performance.now()\n\t\tconst snapshot = this.#guard('capture', () => session.core.snapshot())\n\t\tconst durationMs = Math.round((performance.now() - started) * 10) / 10\n\n\t\t// The core now holds a new snapshot, so everything issued before is void from here on, whether\n\t\t// or not the rest of this method succeeds.\n\t\tsession.generation++\n\t\tsession.current = null\n\t\treturn this.#guard('capture', () => this.#commit(session, snapshot, durationMs))\n\t}\n\n\t/** Builds the public capture of a snapshot and makes it the session's current one. */\n\t#commit(session: Session, snapshot: AxCoreSnapshot, durationMs: number): AxCapture {\n\t\tconst captureId = captureIdOf(session.token, session.generation)\n\t\tconst toPublic = (nodeId: string | null | undefined) =>\n\t\t\tnodeId === null || nodeId === undefined ? null : publicId(captureId, nodeId)\n\n\t\tconst ownPaths = this.#ownInterfacePaths(session)\n\t\tconst excluded = new Set<string>()\n\t\tconst coreNodes = new Map<string, AxCoreNode>()\n\t\tfor (const node of snapshot.tree.nodes) {\n\t\t\tcoreNodes.set(node.id, node)\n\t\t\tif (ownPaths.some((path) => isWithinPath(node.domPath, path))) excluded.add(node.id)\n\t\t}\n\n\t\t// A private copy: callers and the core never share objects through a capture.\n\t\tconst tree = structuredClone(snapshot.tree)\n\t\tconst nodes: AxNode[] = tree.nodes\n\t\t\t.filter((node) => !excluded.has(node.id))\n\t\t\t.map((node) => ({\n\t\t\t\tid: publicId(captureId, node.id),\n\t\t\t\tparentId: toPublic(node.parentId),\n\t\t\t\trole: node.role,\n\t\t\t\tname: node.name,\n\t\t\t\tdescription: node.description,\n\t\t\t\t...(node.value !== undefined && { value: node.value }),\n\t\t\t\tignored: node.ignored,\n\t\t\t\tignoredReason: node.ignoredReason,\n\t\t\t\tproperties: node.properties ?? {},\n\t\t\t\trelations: (node.relations ?? []).map((relation) => ({\n\t\t\t\t\ttype: relation.type,\n\t\t\t\t\ttargetId:\n\t\t\t\t\t\trelation.targetId !== null && !excluded.has(relation.targetId)\n\t\t\t\t\t\t\t? toPublic(relation.targetId)\n\t\t\t\t\t\t\t: null,\n\t\t\t\t})),\n\t\t\t\tdomPath: node.domPath,\n\t\t\t}))\n\n\t\tconst capture: AxCapture = {\n\t\t\tcaptureId,\n\t\t\tsessionId: session.token,\n\t\t\tframeUrl: tree.frameUrl,\n\t\t\trootId: publicId(captureId, tree.rootId),\n\t\t\tnodes,\n\t\t\tunresolvedRelations: (tree.unresolvedRelations ?? [])\n\t\t\t\t.filter((relation) => !relation.sourceId || !excluded.has(relation.sourceId))\n\t\t\t\t.map((relation) => ({\n\t\t\t\t\t...relation,\n\t\t\t\t\tsourceId: toPublic(relation.sourceId),\n\t\t\t\t\t...(relation.targetId !== undefined && {\n\t\t\t\t\t\ttargetId:\n\t\t\t\t\t\t\trelation.targetId && excluded.has(relation.targetId)\n\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t: toPublic(relation.targetId),\n\t\t\t\t\t}),\n\t\t\t\t})),\n\t\t\tlimitations: [...new Set([...snapshot.limitations, ...tree.limitations])],\n\t\t\texcludedNodeCount: excluded.size,\n\t\t\tdurationMs,\n\t\t}\n\t\tsession.current = { captureId, snapshot, capture, coreNodes, excluded, visualIds: new Set() }\n\t\treturn capture\n\t}\n\n\t#view(capture: AxCapture, options: AxTreeFormatOptions): AxTreeView {\n\t\tconst text: AxTreeText = formatTree(capture.nodes, options)\n\t\treturn {\n\t\t\t...text,\n\t\t\tcaptureId: capture.captureId,\n\t\t\tsessionId: capture.sessionId,\n\t\t\tframeUrl: capture.frameUrl,\n\t\t\tlimitations: [...capture.limitations],\n\t\t\texcludedNodeCount: capture.excludedNodeCount,\n\t\t\tdurationMs: capture.durationMs,\n\t\t}\n\t}\n\n\t#requireCurrent(session: Session): NonNullable<Session['current']> {\n\t\tif (!session.current)\n\t\t\tthrow new AxError('no_capture', 'no_capture: capture the tree of this session first')\n\t\treturn session.current\n\t}\n\n\t/** Resolves a public ID to its session and the core request, or fails with `stale_id`. */\n\t#locate(id: string): Target {\n\t\tif (this.#destroyed)\n\t\t\tthrow new AxError(\n\t\t\t\t'session_closed',\n\t\t\t\t'session_closed: the accessibility controller was destroyed'\n\t\t\t)\n\t\tconst parsed = parseAxId(id)\n\t\tif (!parsed)\n\t\t\tthrow new AxError(\n\t\t\t\t'stale_id',\n\t\t\t\t'stale_id: not an ID of the accessibility tree; capture the tree and use an ID from it'\n\t\t\t)\n\t\tconst session = this.#sessions.get(parsed.token)\n\t\tif (!session)\n\t\t\tthrow new AxError(\n\t\t\t\t'stale_id',\n\t\t\t\t'stale_id: this ID belongs to a session that is closed; capture the tree again and use a current ID'\n\t\t\t)\n\t\tif (!session.current || parsed.generation !== session.generation)\n\t\t\tthrow new AxError(\n\t\t\t\t'stale_id',\n\t\t\t\t'stale_id: this ID is from an earlier capture; capture the tree again and use a current ID'\n\t\t\t)\n\t\tif (session.current.excluded.has(parsed.nodeId))\n\t\t\tthrow new AxError('blocked', \"blocked: the node belongs to the agent's own interface\")\n\t\tconst visual = session.current.visualIds.has(parsed.nodeId)\n\t\tif (!visual && !session.current.coreNodes.has(parsed.nodeId))\n\t\t\tthrow new AxError('invalid', 'invalid: the current capture has no node with this ID')\n\t\tthis.#touch(session)\n\t\treturn {\n\t\t\tsession,\n\t\t\trequest: { snapshotId: session.current.snapshot.snapshotId, nodeId: parsed.nodeId },\n\t\t\tnodeId: parsed.nodeId,\n\t\t\tvisual,\n\t\t}\n\t}\n\n\tasync #motion(\n\t\tidOrOffsets: string | (AxScrollOffsets & { sessionId?: string }),\n\t\toffsets?: AxScrollOffsets\n\t): Promise<{\n\t\tsession: Session\n\t\trequest: { snapshotId: string; nodeId?: string; x?: number; y?: number }\n\t}> {\n\t\tif (typeof idOrOffsets === 'string') {\n\t\t\tif (!offsets || typeof offsets !== 'object')\n\t\t\t\tthrow new AxError('invalid', 'invalid: provide scroll offsets as {x, y}')\n\t\t\tconst target = this.#locate(idOrOffsets)\n\t\t\treturn { session: target.session, request: { ...target.request, x: offsets.x, y: offsets.y } }\n\t\t}\n\t\tif (!idOrOffsets || typeof idOrOffsets !== 'object' || offsets !== undefined)\n\t\t\tthrow new AxError('invalid', 'invalid: provide scroll offsets as {x, y}')\n\t\tconst session = await this.#session(idOrOffsets.sessionId)\n\t\tconst current = this.#requireCurrent(session)\n\t\treturn {\n\t\t\tsession,\n\t\t\trequest: { snapshotId: current.snapshot.snapshotId, x: idOrOffsets.x, y: idOrOffsets.y },\n\t\t}\n\t}\n\n\t/** Runs a synchronous core call and turns its failure into an `AxError`. */\n\t#guard<T>(action: string, call: () => T): T {\n\t\ttry {\n\t\t\treturn call()\n\t\t} catch (error) {\n\t\t\tthrow toAxError(error, action)\n\t\t}\n\t}\n\n\t/**\n\t * Runs one core call as an interaction: overlays out of the way, synthetic events observed, and\n\t * failures reported with whatever had already reached the page.\n\t */\n\tasync #run<T>(\n\t\taction: string,\n\t\tsession: Session,\n\t\tquiet: boolean,\n\t\tcall: () => T | Promise<T>,\n\t\tscrollRequested: () => boolean = () => false\n\t): Promise<{ result: T; evidence: AxEvidence }> {\n\t\tconst runInteraction =\n\t\t\tthis.#options.runInteraction ?? (<R>(interaction: () => Promise<R>) => interaction())\n\t\treturn runInteraction(async () => {\n\t\t\tconst observer = quiet ? null : observeAction(session.document)\n\t\t\tconst stop = (): AxEvidence => ({\n\t\t\t\t...(observer?.stop() ?? { syntheticEvents: null, focusMoved: null }),\n\t\t\t\tscrollIntoViewRequested: scrollRequested(),\n\t\t\t})\n\t\t\ttry {\n\t\t\t\tconst result = await call()\n\t\t\t\treturn { result, evidence: stop() }\n\t\t\t} catch (error) {\n\t\t\t\tthrow toAxError(error, action, stop())\n\t\t\t}\n\t\t})\n\t}\n\n\tasync #act<TResult>(\n\t\taction: AxActionName,\n\t\tid: string,\n\t\toptions: AxActionOptions,\n\t\tcall: (core: AxCoreAgent, request: AxCoreRequest) => TResult,\n\t\tdescribe: {\n\t\t\tstatus: (result: TResult) => AxActionStatus\n\t\t\tsummary: (result: TResult) => string\n\t\t}\n\t): Promise<AxActionOutcome<TResult>> {\n\t\tconst target = this.#locate(id)\n\t\tconst scrolledIntoView = options.scrollIntoView === true && !target.visual\n\t\tlet scrollRequested = false\n\t\tconst { result, evidence } = await this.#run(\n\t\t\taction,\n\t\t\ttarget.session,\n\t\t\tfalse,\n\t\t\t() => {\n\t\t\t\tif (scrolledIntoView) {\n\t\t\t\t\ttarget.session.core.scrollIntoView(target.request)\n\t\t\t\t\tscrollRequested = true\n\t\t\t\t}\n\t\t\t\treturn call(target.session.core, target.request)\n\t\t\t},\n\t\t\t() => scrollRequested\n\t\t)\n\t\treturn {\n\t\t\taction,\n\t\t\tstatus: describe.status(result),\n\t\t\tresult,\n\t\t\tevidence,\n\t\t\tscrolledIntoView,\n\t\t\t...PAGE_SCRIPT,\n\t\t\tsummary: describe.summary(result),\n\t\t}\n\t}\n\n\t#ownInterfaceRoots(session: Session): Element[] {\n\t\t// The agent mounts its interface in the top document only.\n\t\tif (session.kind !== 'root' || !session.document) return []\n\t\tconst selector = this.#options.ignoreSelector ?? DEFAULT_IGNORE_SELECTOR\n\t\tif (!selector) return []\n\t\ttry {\n\t\t\treturn [...session.document.querySelectorAll(selector)]\n\t\t} catch (error) {\n\t\t\tthrow new AxError(\n\t\t\t\t'invalid',\n\t\t\t\t`invalid: ignoreSelector is not a valid selector (${selector})`,\n\t\t\t\t{\n\t\t\t\t\tcause: error,\n\t\t\t\t}\n\t\t\t)\n\t\t}\n\t}\n\n\t#ownInterfacePaths(session: Session): string[] {\n\t\tconst doc = session.document\n\t\tif (!doc) return []\n\t\treturn this.#ownInterfaceRoots(session).map((element) => domPathOf(element, doc))\n\t}\n\n\t#hitsOwnInterface(session: Session, x: number, y: number): boolean {\n\t\tconst roots = this.#ownInterfaceRoots(session)\n\t\tif (roots.length === 0 || !session.document) return false\n\t\tconst hit = session.document.elementFromPoint(x, y)\n\t\treturn !!hit && roots.some((root) => root.contains(hit))\n\t}\n\n\t/** Surfaces inside the agent's own interface, keyed by tag and geometry, with their counts. */\n\t#ownSurfaceKeys(session: Session): Map<string, number> {\n\t\tconst keys = new Map<string, number>()\n\t\tfor (const root of this.#ownInterfaceRoots(session)) {\n\t\t\tconst candidates = [\n\t\t\t\t...(root.matches('canvas, svg, [role=\"application\"]') ? [root] : []),\n\t\t\t\t...root.querySelectorAll('canvas, svg, [role=\"application\"]'),\n\t\t\t]\n\t\t\tfor (const element of candidates) {\n\t\t\t\tconst key = surfaceKey(element.localName, element.getBoundingClientRect())\n\t\t\t\tkeys.set(key, (keys.get(key) ?? 0) + 1)\n\t\t\t}\n\t\t}\n\t\treturn keys\n\t}\n}\n\n/** A name short enough for a message. */\nfunction clip(text: string, limit = 60): string {\n\treturn text.length > limit ? `${text.slice(0, limit)}…` : text\n}\n\n/**\n * How every action here is performed, in the same terms a native-input executor would use: page\n * JavaScript, never physical input, and never a confirmation of the effect on the application.\n */\nconst PAGE_SCRIPT = { backend: 'page-script', nativeInput: false, verifiedOutcome: false } as const\n\nfunction surfaceKey(\n\ttag: string,\n\tbounds: { x: number; y: number; width: number; height: number }\n): string {\n\treturn `${tag}|${bounds.x}|${bounds.y}|${bounds.width}|${bounds.height}`\n}\n\nfunction changeNote(changeDispatched: boolean | undefined): string {\n\treturn changeDispatched === false\n\t\t? ' The change event was withheld because the control, its value or its form target changed during input; the value and the input event may already have had effects.'\n\t\t: ''\n}\n\nfunction stateStatus(result: { dispatched: boolean; applied: boolean }): AxActionStatus {\n\tif (!result.dispatched) return 'noop'\n\treturn result.applied ? 'applied' : 'not_applied'\n}\n\nfunction stateSummary(\n\tresult: { dispatched: boolean; applied: boolean; changeDispatched?: boolean },\n\twhat: string\n): string {\n\tif (!result.dispatched)\n\t\treturn `The control already had the requested ${what}; nothing was dispatched.`\n\treturn (\n\t\t(result.applied\n\t\t\t? `Right after the events the control had the requested ${what}.`\n\t\t\t: `Right after the events the control did not have the requested ${what}.`) +\n\t\tchangeNote(result.changeDispatched) +\n\t\t' This does not show that the page validated or saved it.'\n\t)\n}\n\nfunction dragSummary(result: {\n\tmode: AxDragMode\n\tdropDispatched?: boolean\n\taccepted?: boolean\n\treason?: string\n}): string {\n\tif (result.mode === 'html5') {\n\t\tif (result.reason === 'dragstart_cancelled')\n\t\t\treturn 'The page cancelled dragstart, so nothing else was dispatched and there was no drop.'\n\t\tif (!result.dropDispatched)\n\t\t\treturn 'The destination did not cancel dragover, so no drop was dispatched. dragstart, dragenter, dragover and dragend were.'\n\t\treturn `Synthetic dragstart, dragenter, dragover, drop and dragend were dispatched with a synthetic DataTransfer. ${NOT_VERIFIED}`\n\t}\n\treturn `Synthetic pointer and mouse press, move and release events were dispatched${result.mode === 'pointer-paced' ? ', spaced in time' : ''}. There is no native pointer capture and a library may ignore them. ${NOT_VERIFIED}`\n}\n","/**\n * @file port from browser-use\n * @see https://github.com/browser-use/browser-use/commits/main/browser_use/dom/dom_tree/index.js\n * @match 0.5.9 d51b6e73daff7165fdd3e44debd667e7f5f7fdc5\n *\n * search @edit for all the changed lines.\n *\n * @edit export\n * @edit add interactiveBlacklist interactiveWhitelist\n * @edit adjustable opacity\n * @edit direct dom ref\n * @edit @workaround input.checked\n * @edit smaller zIndex for highlight\n * @edit no need for xpath\n * @edit add `extra` field for extra data\n * @edit scrollable element detection\n * @edit add `data-browser-use-ignore` attribute\n * @edit improve `sampleRect`, filter out rects with 0 area\n * @edit exclude aria-hidden elements\n * @edit make sure attributes exist for interactive candidates.\n * @edit fix \"aria-*\" attributes check\n */\n\nexport default (\n\targs = {\n\t\tdoHighlightElements: true,\n\t\tfocusHighlightIndex: -1,\n\t\tviewportExpansion: 0,\n\t\tdebugMode: false,\n\n\t\t/**\n\t\t * @edit\n\t\t */\n\t\t/** @type {Element[]} */\n\t\tinteractiveBlacklist: [],\n\t\t/** @type {Element[]} */\n\t\tinteractiveWhitelist: [],\n\t\thighlightOpacity: 0.1,\n\t\thighlightLabelOpacity: 0.5,\n\t}\n) => {\n\t/**\n\t * @edit\n\t */\n\tconst { interactiveBlacklist, interactiveWhitelist, highlightOpacity, highlightLabelOpacity } =\n\t\targs\n\n\tconst { doHighlightElements, focusHighlightIndex, viewportExpansion, debugMode } = args\n\tlet highlightIndex = 0 // Reset highlight index\n\n\t/**\n\t * @edit add `extra` field for extra data\n\t */\n\tconst extraData = new WeakMap()\n\tfunction addExtraData(element, data) {\n\t\tif (!element || element.nodeType !== Node.ELEMENT_NODE) return\n\t\textraData.set(element, { ...extraData.get(element), ...data })\n\t}\n\n\t// Add caching mechanisms at the top level\n\tconst DOM_CACHE = {\n\t\tboundingRects: new WeakMap(),\n\t\tclientRects: new WeakMap(),\n\t\tcomputedStyles: new WeakMap(),\n\t\tclearCache: () => {\n\t\t\tDOM_CACHE.boundingRects = new WeakMap()\n\t\t\tDOM_CACHE.clientRects = new WeakMap()\n\t\t\tDOM_CACHE.computedStyles = new WeakMap()\n\t\t},\n\t}\n\n\t/**\n\t * Gets the cached bounding rect for an element.\n\t *\n\t * @param {HTMLElement} element - The element to get the bounding rect for.\n\t * @returns {DOMRect | null} The cached bounding rect, or null if the element is not found.\n\t */\n\tfunction getCachedBoundingRect(element) {\n\t\tif (!element) return null\n\n\t\tif (DOM_CACHE.boundingRects.has(element)) {\n\t\t\treturn DOM_CACHE.boundingRects.get(element)\n\t\t}\n\n\t\tconst rect = element.getBoundingClientRect()\n\n\t\tif (rect) {\n\t\t\tDOM_CACHE.boundingRects.set(element, rect)\n\t\t}\n\t\treturn rect\n\t}\n\n\t/**\n\t * Gets the cached computed style for an element.\n\t *\n\t * @param {HTMLElement} element - The element to get the computed style for.\n\t * @returns {CSSStyleDeclaration | null} The cached computed style, or null if the element is not found.\n\t */\n\tfunction getCachedComputedStyle(element) {\n\t\tif (!element) return null\n\n\t\tif (DOM_CACHE.computedStyles.has(element)) {\n\t\t\treturn DOM_CACHE.computedStyles.get(element)\n\t\t}\n\n\t\tconst style = window.getComputedStyle(element)\n\n\t\tif (style) {\n\t\t\tDOM_CACHE.computedStyles.set(element, style)\n\t\t}\n\t\treturn style\n\t}\n\n\t/**\n\t * Gets the cached client rects for an element.\n\t *\n\t * @param {HTMLElement} element - The element to get the client rects for.\n\t * @returns {DOMRectList | null} The cached client rects, or null if the element is not found.\n\t */\n\tfunction getCachedClientRects(element) {\n\t\tif (!element) return null\n\n\t\tif (DOM_CACHE.clientRects.has(element)) {\n\t\t\treturn DOM_CACHE.clientRects.get(element)\n\t\t}\n\n\t\tconst rects = element.getClientRects()\n\n\t\tif (rects) {\n\t\t\tDOM_CACHE.clientRects.set(element, rects)\n\t\t}\n\t\treturn rects\n\t}\n\n\t/**\n\t * Hash map of DOM nodes indexed by their highlight index.\n\t *\n\t * @type {Object<string, any>}\n\t */\n\tconst DOM_HASH_MAP = {}\n\n\tconst ID = { current: 0 }\n\n\tconst HIGHLIGHT_CONTAINER_ID = 'playwright-highlight-container'\n\n\t// Add a WeakMap cache for XPath strings\n\tconst xpathCache = new WeakMap()\n\n\t// // Initialize once and reuse\n\t// const viewportObserver = new IntersectionObserver(\n\t// (entries) => {\n\t// entries.forEach(entry => {\n\t// elementVisibilityMap.set(entry.target, entry.isIntersecting);\n\t// });\n\t// },\n\t// { rootMargin: `${viewportExpansion}px` }\n\t// );\n\n\t/**\n\t * Highlights an element in the DOM and returns the index of the next element.\n\t *\n\t * @param {HTMLElement} element - The element to highlight.\n\t * @param {number} index - The index of the element.\n\t * @param {HTMLElement | null} parentIframe - The parent iframe node.\n\t * @returns {number} The index of the next element.\n\t */\n\tfunction highlightElement(element, index, parentIframe = null) {\n\t\tif (!element) return index\n\n\t\tconst overlays = []\n\t\t/**\n\t\t * @type {HTMLElement | null}\n\t\t */\n\t\tlet label = null\n\t\tlet labelWidth = 20\n\t\tlet labelHeight = 16\n\t\tlet cleanupFn = null\n\n\t\ttry {\n\t\t\t// Create or get highlight container\n\t\t\tlet container = document.getElementById(HIGHLIGHT_CONTAINER_ID)\n\t\t\tif (!container) {\n\t\t\t\tcontainer = document.createElement('div')\n\t\t\t\tcontainer.id = HIGHLIGHT_CONTAINER_ID\n\t\t\t\tcontainer.style.position = 'fixed'\n\t\t\t\tcontainer.style.pointerEvents = 'none'\n\t\t\t\tcontainer.style.top = '0'\n\t\t\t\tcontainer.style.left = '0'\n\t\t\t\tcontainer.style.width = '100%'\n\t\t\t\tcontainer.style.height = '100%'\n\n\t\t\t\t/**\n\t\t\t\t * @edit smaller zIndex for highlight\n\t\t\t\t */\n\t\t\t\t// Use the maximum valid value in zIndex to ensure the element is not blocked by overlapping elements.\n\t\t\t\t// container.style.zIndex = \"2147483647\";\n\t\t\t\tcontainer.style.zIndex = '2147483640'\n\n\t\t\t\tcontainer.style.backgroundColor = 'transparent'\n\t\t\t\tdocument.body.appendChild(container)\n\t\t\t}\n\n\t\t\t// Get element client rects\n\t\t\tconst rects = element.getClientRects() // Use getClientRects()\n\n\t\t\tif (!rects || rects.length === 0) return index // Exit if no rects\n\n\t\t\t// Generate a color based on the index\n\t\t\tconst colors = [\n\t\t\t\t'#FF0000',\n\t\t\t\t'#00FF00',\n\t\t\t\t'#0000FF',\n\t\t\t\t'#FFA500',\n\t\t\t\t'#800080',\n\t\t\t\t'#008080',\n\t\t\t\t'#FF69B4',\n\t\t\t\t'#4B0082',\n\t\t\t\t'#FF4500',\n\t\t\t\t'#2E8B57',\n\t\t\t\t'#DC143C',\n\t\t\t\t'#4682B4',\n\t\t\t]\n\t\t\tconst colorIndex = index % colors.length\n\t\t\tlet baseColor = colors[colorIndex]\n\n\t\t\t/**\n\t\t\t * @edit adjustable opacity\n\t\t\t */\n\t\t\t// const backgroundColor = baseColor + \"1A\"; // 10% opacity version of the color\n\t\t\tconst backgroundColor =\n\t\t\t\tbaseColor +\n\t\t\t\tMath.floor(highlightOpacity * 255)\n\t\t\t\t\t.toString(16)\n\t\t\t\t\t.padStart(2, '0')\n\t\t\tbaseColor =\n\t\t\t\tbaseColor +\n\t\t\t\tMath.floor(highlightLabelOpacity * 255)\n\t\t\t\t\t.toString(16)\n\t\t\t\t\t.padStart(2, '0')\n\n\t\t\t// Get iframe offset if necessary\n\t\t\tlet iframeOffset = { x: 0, y: 0 }\n\t\t\tif (parentIframe) {\n\t\t\t\tconst iframeRect = parentIframe.getBoundingClientRect() // Keep getBoundingClientRect for iframe offset\n\t\t\t\tiframeOffset.x = iframeRect.left\n\t\t\t\tiframeOffset.y = iframeRect.top\n\t\t\t}\n\n\t\t\t// Create fragment to hold overlay elements\n\t\t\tconst fragment = document.createDocumentFragment()\n\n\t\t\t// Create highlight overlays for each client rect\n\t\t\tfor (const rect of rects) {\n\t\t\t\tif (rect.width === 0 || rect.height === 0) continue // Skip empty rects\n\n\t\t\t\tconst overlay = document.createElement('div')\n\t\t\t\toverlay.style.position = 'fixed'\n\t\t\t\toverlay.style.border = `2px solid ${baseColor}`\n\t\t\t\toverlay.style.backgroundColor = backgroundColor\n\t\t\t\toverlay.style.pointerEvents = 'none'\n\t\t\t\toverlay.style.boxSizing = 'border-box'\n\n\t\t\t\tconst top = rect.top + iframeOffset.y\n\t\t\t\tconst left = rect.left + iframeOffset.x\n\n\t\t\t\toverlay.style.top = `${top}px`\n\t\t\t\toverlay.style.left = `${left}px`\n\t\t\t\toverlay.style.width = `${rect.width}px`\n\t\t\t\toverlay.style.height = `${rect.height}px`\n\n\t\t\t\tfragment.appendChild(overlay)\n\t\t\t\toverlays.push({ element: overlay, initialRect: rect }) // Store overlay and its rect\n\t\t\t}\n\n\t\t\t// Create and position a single label relative to the first rect\n\t\t\tconst firstRect = rects[0]\n\t\t\tlabel = document.createElement('div')\n\t\t\tlabel.className = 'playwright-highlight-label'\n\t\t\tlabel.style.position = 'fixed'\n\t\t\tlabel.style.background = baseColor\n\t\t\tlabel.style.color = 'white'\n\t\t\tlabel.style.padding = '1px 4px'\n\t\t\tlabel.style.borderRadius = '4px'\n\t\t\tlabel.style.fontSize = `${Math.min(12, Math.max(8, firstRect.height / 2))}px`\n\t\t\tlabel.textContent = index.toString()\n\n\t\t\tlabelWidth = label.offsetWidth > 0 ? label.offsetWidth : labelWidth // Update actual width if possible\n\t\t\tlabelHeight = label.offsetHeight > 0 ? label.offsetHeight : labelHeight // Update actual height if possible\n\n\t\t\tconst firstRectTop = firstRect.top + iframeOffset.y\n\t\t\tconst firstRectLeft = firstRect.left + iframeOffset.x\n\n\t\t\tlet labelTop = firstRectTop + 2\n\t\t\tlet labelLeft = firstRectLeft + firstRect.width - labelWidth - 2\n\n\t\t\t// Adjust label position if first rect is too small\n\t\t\tif (firstRect.width < labelWidth + 4 || firstRect.height < labelHeight + 4) {\n\t\t\t\tlabelTop = firstRectTop - labelHeight - 2\n\t\t\t\tlabelLeft = firstRectLeft + firstRect.width - labelWidth // Align with right edge\n\t\t\t\tif (labelLeft < iframeOffset.x) labelLeft = firstRectLeft // Prevent going off-left\n\t\t\t}\n\n\t\t\t// Ensure label stays within viewport bounds slightly better\n\t\t\tlabelTop = Math.max(0, Math.min(labelTop, window.innerHeight - labelHeight))\n\t\t\tlabelLeft = Math.max(0, Math.min(labelLeft, window.innerWidth - labelWidth))\n\n\t\t\tlabel.style.top = `${labelTop}px`\n\t\t\tlabel.style.left = `${labelLeft}px`\n\n\t\t\tfragment.appendChild(label)\n\n\t\t\t// Update positions on scroll/resize\n\t\t\tconst updatePositions = () => {\n\t\t\t\tconst newRects = element.getClientRects() // Get fresh rects\n\t\t\t\tlet newIframeOffset = { x: 0, y: 0 }\n\n\t\t\t\tif (parentIframe) {\n\t\t\t\t\tconst iframeRect = parentIframe.getBoundingClientRect() // Keep getBoundingClientRect for iframe\n\t\t\t\t\tnewIframeOffset.x = iframeRect.left\n\t\t\t\t\tnewIframeOffset.y = iframeRect.top\n\t\t\t\t}\n\n\t\t\t\t// Update each overlay\n\t\t\t\toverlays.forEach((overlayData, i) => {\n\t\t\t\t\tif (i < newRects.length) {\n\t\t\t\t\t\t// Check if rect still exists\n\t\t\t\t\t\tconst newRect = newRects[i]\n\t\t\t\t\t\tconst newTop = newRect.top + newIframeOffset.y\n\t\t\t\t\t\tconst newLeft = newRect.left + newIframeOffset.x\n\n\t\t\t\t\t\toverlayData.element.style.top = `${newTop}px`\n\t\t\t\t\t\toverlayData.element.style.left = `${newLeft}px`\n\t\t\t\t\t\toverlayData.element.style.width = `${newRect.width}px`\n\t\t\t\t\t\toverlayData.element.style.height = `${newRect.height}px`\n\t\t\t\t\t\toverlayData.element.style.display =\n\t\t\t\t\t\t\tnewRect.width === 0 || newRect.height === 0 ? 'none' : 'block'\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// If fewer rects now, hide extra overlays\n\t\t\t\t\t\toverlayData.element.style.display = 'none'\n\t\t\t\t\t}\n\t\t\t\t})\n\n\t\t\t\t// If there are fewer new rects than overlays, hide the extras\n\t\t\t\tif (newRects.length < overlays.length) {\n\t\t\t\t\tfor (let i = newRects.length; i < overlays.length; i++) {\n\t\t\t\t\t\toverlays[i].element.style.display = 'none'\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Update label position based on the first new rect\n\t\t\t\tif (label && newRects.length > 0) {\n\t\t\t\t\tconst firstNewRect = newRects[0]\n\t\t\t\t\tconst firstNewRectTop = firstNewRect.top + newIframeOffset.y\n\t\t\t\t\tconst firstNewRectLeft = firstNewRect.left + newIframeOffset.x\n\n\t\t\t\t\tlet newLabelTop = firstNewRectTop + 2\n\t\t\t\t\tlet newLabelLeft = firstNewRectLeft + firstNewRect.width - labelWidth - 2\n\n\t\t\t\t\tif (firstNewRect.width < labelWidth + 4 || firstNewRect.height < labelHeight + 4) {\n\t\t\t\t\t\tnewLabelTop = firstNewRectTop - labelHeight - 2\n\t\t\t\t\t\tnewLabelLeft = firstNewRectLeft + firstNewRect.width - labelWidth\n\t\t\t\t\t\tif (newLabelLeft < newIframeOffset.x) newLabelLeft = firstNewRectLeft\n\t\t\t\t\t}\n\n\t\t\t\t\t// Ensure label stays within viewport bounds\n\t\t\t\t\tnewLabelTop = Math.max(0, Math.min(newLabelTop, window.innerHeight - labelHeight))\n\t\t\t\t\tnewLabelLeft = Math.max(0, Math.min(newLabelLeft, window.innerWidth - labelWidth))\n\n\t\t\t\t\tlabel.style.top = `${newLabelTop}px`\n\t\t\t\t\tlabel.style.left = `${newLabelLeft}px`\n\t\t\t\t\tlabel.style.display = 'block'\n\t\t\t\t} else if (label) {\n\t\t\t\t\t// Hide label if element has no rects anymore\n\t\t\t\t\tlabel.style.display = 'none'\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst throttleFunction = (func, delay) => {\n\t\t\t\tlet lastCall = 0\n\t\t\t\treturn (...args) => {\n\t\t\t\t\tconst now = performance.now()\n\t\t\t\t\tif (now - lastCall < delay) return\n\t\t\t\t\tlastCall = now\n\t\t\t\t\treturn func(...args)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst throttledUpdatePositions = throttleFunction(updatePositions, 16) // ~60fps\n\t\t\twindow.addEventListener('scroll', throttledUpdatePositions, true)\n\t\t\twindow.addEventListener('resize', throttledUpdatePositions)\n\n\t\t\t// Add cleanup function\n\t\t\tcleanupFn = () => {\n\t\t\t\twindow.removeEventListener('scroll', throttledUpdatePositions, true)\n\t\t\t\twindow.removeEventListener('resize', throttledUpdatePositions)\n\t\t\t\t// Remove overlay elements if needed\n\t\t\t\toverlays.forEach((overlay) => overlay.element.remove())\n\t\t\t\tif (label) label.remove()\n\t\t\t}\n\n\t\t\t// Then add fragment to container in one operation\n\t\t\tcontainer.appendChild(fragment)\n\n\t\t\treturn index + 1\n\t\t} finally {\n\t\t\t// Store cleanup function for later use\n\t\t\tif (cleanupFn) {\n\t\t\t\t// Keep a reference to cleanup functions in a global array\n\t\t\t\t;(window._highlightCleanupFunctions = window._highlightCleanupFunctions || []).push(\n\t\t\t\t\tcleanupFn\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\t// // Add this function to perform cleanup when needed\n\t// function cleanupHighlights() {\n\t// if (window._highlightCleanupFunctions && window._highlightCleanupFunctions.length) {\n\t// window._highlightCleanupFunctions.forEach(fn => fn());\n\t// window._highlightCleanupFunctions = [];\n\t// }\n\n\t// // Also remove the container\n\t// const container = document.getElementById(HIGHLIGHT_CONTAINER_ID);\n\t// if (container) container.remove();\n\t// }\n\n\t/**\n\t * Gets the position of an element in its parent.\n\t *\n\t * @param {HTMLElement} currentElement - The element to get the position for.\n\t * @returns {number} The position of the element in its parent.\n\t */\n\tfunction getElementPosition(currentElement) {\n\t\tif (!currentElement.parentElement) {\n\t\t\treturn 0 // No parent means no siblings\n\t\t}\n\n\t\tconst tagName = currentElement.nodeName.toLowerCase()\n\n\t\tconst siblings = Array.from(currentElement.parentElement.children).filter(\n\t\t\t(sib) => sib.nodeName.toLowerCase() === tagName\n\t\t)\n\n\t\tif (siblings.length === 1) {\n\t\t\treturn 0 // Only element of its type\n\t\t}\n\n\t\tconst index = siblings.indexOf(currentElement) + 1 // 1-based index\n\t\treturn index\n\t}\n\n\tfunction getXPathTree(element, stopAtBoundary = true) {\n\t\tif (xpathCache.has(element)) return xpathCache.get(element)\n\n\t\tconst segments = []\n\t\tlet currentElement = element\n\n\t\twhile (currentElement && currentElement.nodeType === Node.ELEMENT_NODE) {\n\t\t\t// Stop if we hit a shadow root or iframe\n\t\t\tif (\n\t\t\t\tstopAtBoundary &&\n\t\t\t\t(currentElement.parentNode instanceof ShadowRoot ||\n\t\t\t\t\tcurrentElement.parentNode instanceof HTMLIFrameElement)\n\t\t\t) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tconst position = getElementPosition(currentElement)\n\t\t\tconst tagName = currentElement.nodeName.toLowerCase()\n\t\t\tconst xpathIndex = position > 0 ? `[${position}]` : ''\n\t\t\tsegments.unshift(`${tagName}${xpathIndex}`)\n\n\t\t\tcurrentElement = currentElement.parentNode\n\t\t}\n\n\t\tconst result = segments.join('/')\n\t\txpathCache.set(element, result)\n\t\treturn result\n\t}\n\n\t/**\n\t * @edit scrollable element detection\n\t * Checks if an element is scrollable. if so, return the scrollable distance on each direction (left right top bottom). if not return null.\n\t * @note distance smaller than 4 will be considered as not scrollable.\n\t * @note only check block elements, not inline elements.\n\t */\n\tfunction isScrollableElement(element) {\n\t\tif (!element || element.nodeType !== Node.ELEMENT_NODE) {\n\t\t\treturn null // Not a valid element\n\t\t}\n\n\t\tconst style = getCachedComputedStyle(element)\n\t\tif (!style) return null\n\n\t\t// Check if the element is a block-level element\n\t\tconst display = style.display\n\t\tif (display === 'inline' || display === 'inline-block') {\n\t\t\treturn null // Not a block-level element\n\t\t}\n\n\t\t// Check overflow properties\n\t\tconst overflowX = style.overflowX\n\t\tconst overflowY = style.overflowY\n\n\t\t// scrollbar-width/scrollbar-gutter are only set on elements designed to scroll;\n\t\t// their presence signals scroll intent even when overflow is hidden (e.g. overflow: auto on :hover)\n\t\tconst hasScrollbarSignal =\n\t\t\t(style.scrollbarWidth && style.scrollbarWidth !== 'auto') ||\n\t\t\t(style.scrollbarGutter && style.scrollbarGutter !== 'auto')\n\n\t\tconst scrollableX = overflowX === 'auto' || overflowX === 'scroll'\n\t\tconst scrollableY = overflowY === 'auto' || overflowY === 'scroll'\n\n\t\tif (!scrollableX && !scrollableY && !hasScrollbarSignal) {\n\t\t\treturn null // Not scrollable in any direction\n\t\t}\n\n\t\tconst scrollWidth = element.scrollWidth - element.clientWidth\n\t\tconst scrollHeight = element.scrollHeight - element.clientHeight\n\n\t\t// Consider small distances as not scrollable\n\t\tconst threshold = 4\n\n\t\tif (scrollWidth < threshold && scrollHeight < threshold) {\n\t\t\treturn null // Not scrollable\n\t\t}\n\n\t\tif (!scrollableY && !hasScrollbarSignal && scrollWidth < threshold) {\n\t\t\treturn null // Not scrollable horizontally\n\t\t}\n\n\t\tif (!scrollableX && !hasScrollbarSignal && scrollHeight < threshold) {\n\t\t\treturn null // Not scrollable vertically\n\t\t}\n\n\t\tconst distanceToTop = element.scrollTop\n\t\tconst distanceToLeft = element.scrollLeft\n\t\tconst distanceToRight = element.scrollWidth - element.clientWidth - element.scrollLeft\n\t\tconst distanceToBottom = element.scrollHeight - element.clientHeight - element.scrollTop\n\n\t\tconst scrollData = {\n\t\t\ttop: distanceToTop,\n\t\t\tright: distanceToRight,\n\t\t\tbottom: distanceToBottom,\n\t\t\tleft: distanceToLeft,\n\t\t}\n\n\t\t// Store extra data for the element\n\t\taddExtraData(element, {\n\t\t\tscrollable: true,\n\t\t\tscrollData: scrollData,\n\t\t})\n\n\t\treturn scrollData\n\t}\n\n\t/**\n\t * Checks if a text node is visible.\n\t *\n\t * @param {Text} textNode - The text node to check.\n\t * @returns {boolean} Whether the text node is visible.\n\t */\n\tfunction isTextNodeVisible(textNode) {\n\t\ttry {\n\t\t\t// Special case: when viewportExpansion is -1, consider all text nodes as visible\n\t\t\tif (viewportExpansion === -1) {\n\t\t\t\t// Still check parent visibility for basic filtering\n\t\t\t\tconst parentElement = textNode.parentElement\n\t\t\t\tif (!parentElement) return false\n\n\t\t\t\ttry {\n\t\t\t\t\treturn parentElement.checkVisibility({\n\t\t\t\t\t\tcheckOpacity: true,\n\t\t\t\t\t\tcheckVisibilityCSS: true,\n\t\t\t\t\t})\n\t\t\t\t} catch (e) {\n\t\t\t\t\t// Fallback if checkVisibility is not supported\n\t\t\t\t\tconst style = window.getComputedStyle(parentElement)\n\t\t\t\t\treturn style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0'\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst range = document.createRange()\n\t\t\trange.selectNodeContents(textNode)\n\t\t\tconst rects = range.getClientRects() // Use getClientRects for Range\n\n\t\t\tif (!rects || rects.length === 0) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tlet isAnyRectVisible = false\n\t\t\tlet isAnyRectInViewport = false\n\n\t\t\tfor (const rect of rects) {\n\t\t\t\t// Check size\n\t\t\t\tif (rect.width > 0 && rect.height > 0) {\n\t\t\t\t\tisAnyRectVisible = true\n\n\t\t\t\t\t// Viewport check for this rect\n\t\t\t\t\tif (!(\n\t\t\t\t\t\trect.bottom < -viewportExpansion ||\n\t\t\t\t\t\trect.top > window.innerHeight + viewportExpansion ||\n\t\t\t\t\t\trect.right < -viewportExpansion ||\n\t\t\t\t\t\trect.left > window.innerWidth + viewportExpansion\n\t\t\t\t\t)) {\n\t\t\t\t\t\tisAnyRectInViewport = true\n\t\t\t\t\t\tbreak // Found a visible rect in viewport, no need to check others\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!isAnyRectVisible || !isAnyRectInViewport) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// Check parent visibility\n\t\t\tconst parentElement = textNode.parentElement\n\t\t\tif (!parentElement) return false\n\n\t\t\ttry {\n\t\t\t\treturn parentElement.checkVisibility({\n\t\t\t\t\tcheckOpacity: true,\n\t\t\t\t\tcheckVisibilityCSS: true,\n\t\t\t\t})\n\t\t\t} catch (e) {\n\t\t\t\t// Fallback if checkVisibility is not supported\n\t\t\t\tconst style = window.getComputedStyle(parentElement)\n\t\t\t\treturn style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0'\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tconsole.warn('Error checking text node visibility:', e)\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/**\n\t * Checks if an element is accepted.\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @returns {boolean} Whether the element is accepted.\n\t */\n\tfunction isElementAccepted(element) {\n\t\tif (!element || !element.tagName) return false\n\n\t\t// Always accept body and common container elements\n\t\tconst alwaysAccept = new Set([\n\t\t\t'body',\n\t\t\t'div',\n\t\t\t'main',\n\t\t\t'article',\n\t\t\t'section',\n\t\t\t'nav',\n\t\t\t'header',\n\t\t\t'footer',\n\t\t])\n\t\tconst tagName = element.tagName.toLowerCase()\n\n\t\tif (alwaysAccept.has(tagName)) return true\n\n\t\tconst leafElementDenyList = new Set([\n\t\t\t'svg',\n\t\t\t'script',\n\t\t\t'style',\n\t\t\t'link',\n\t\t\t'meta',\n\t\t\t'noscript',\n\t\t\t'template',\n\t\t])\n\n\t\treturn !leafElementDenyList.has(tagName)\n\t}\n\n\t/**\n\t * Checks if an element is visible.\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @returns {boolean} Whether the element is visible.\n\t */\n\tfunction isElementVisible(element) {\n\t\tconst style = getCachedComputedStyle(element)\n\t\treturn (\n\t\t\telement.offsetWidth > 0 &&\n\t\t\telement.offsetHeight > 0 &&\n\t\t\tstyle?.visibility !== 'hidden' &&\n\t\t\tstyle?.display !== 'none'\n\t\t)\n\t}\n\n\t/**\n\t * Checks if an element is interactive.\n\t *\n\t * lots of comments, and uncommented code - to show the logic of what we already tried\n\t *\n\t * One of the things we tried at the beginning was also to use event listeners, and other fancy class, style stuff -> what actually worked best was just combining most things with computed cursor style :)\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t */\n\tfunction isInteractiveElement(element) {\n\t\tif (!element || element.nodeType !== Node.ELEMENT_NODE) {\n\t\t\treturn false\n\t\t}\n\n\t\t/**\n\t\t * @edit add interactiveBlacklist interactiveWhitelist\n\t\t */\n\t\tif (interactiveBlacklist.includes(element)) {\n\t\t\treturn false // Skip blacklisted elements\n\t\t}\n\t\tif (interactiveWhitelist.includes(element)) {\n\t\t\treturn true // Skip whitelisted elements\n\t\t}\n\n\t\t// Cache the tagName and style lookups\n\t\tconst tagName = element.tagName.toLowerCase()\n\t\tconst style = getCachedComputedStyle(element)\n\n\t\t// Define interactive cursors\n\t\tconst interactiveCursors = new Set([\n\t\t\t'pointer', // Link/clickable elements\n\t\t\t'move', // Movable elements\n\t\t\t'text', // Text selection\n\t\t\t'grab', // Grabbable elements\n\t\t\t'grabbing', // Currently grabbing\n\t\t\t'cell', // Table cell selection\n\t\t\t'copy', // Copy operation\n\t\t\t'alias', // Alias creation\n\t\t\t'all-scroll', // Scrollable content\n\t\t\t'col-resize', // Column resize\n\t\t\t'context-menu', // Context menu available\n\t\t\t'crosshair', // Precise selection\n\t\t\t'e-resize', // East resize\n\t\t\t'ew-resize', // East-west resize\n\t\t\t'help', // Help available\n\t\t\t'n-resize', // North resize\n\t\t\t'ne-resize', // Northeast resize\n\t\t\t'nesw-resize', // Northeast-southwest resize\n\t\t\t'ns-resize', // North-south resize\n\t\t\t'nw-resize', // Northwest resize\n\t\t\t'nwse-resize', // Northwest-southeast resize\n\t\t\t'row-resize', // Row resize\n\t\t\t's-resize', // South resize\n\t\t\t'se-resize', // Southeast resize\n\t\t\t'sw-resize', // Southwest resize\n\t\t\t'vertical-text', // Vertical text selection\n\t\t\t'w-resize', // West resize\n\t\t\t'zoom-in', // Zoom in\n\t\t\t'zoom-out', // Zoom out\n\t\t])\n\n\t\t// Define non-interactive cursors\n\t\tconst nonInteractiveCursors = new Set([\n\t\t\t'not-allowed', // Action not allowed\n\t\t\t'no-drop', // Drop not allowed\n\t\t\t'wait', // Processing\n\t\t\t'progress', // In progress\n\t\t\t'initial', // Initial value\n\t\t\t'inherit', // Inherited value\n\t\t\t//? Let's just include all potentially clickable elements that are not specifically blocked\n\t\t\t// 'none', // No cursor\n\t\t\t// 'default', // Default cursor\n\t\t\t// 'auto', // Browser default\n\t\t])\n\n\t\t/**\n\t\t * Checks if an element has an interactive pointer.\n\t\t *\n\t\t * @param {HTMLElement} element - The element to check.\n\t\t * @returns {boolean} Whether the element has an interactive pointer.\n\t\t */\n\t\tfunction doesElementHaveInteractivePointer(element) {\n\t\t\tif (element.tagName.toLowerCase() === 'html') return false\n\n\t\t\tif (style?.cursor && interactiveCursors.has(style.cursor)) return true\n\n\t\t\treturn false\n\t\t}\n\n\t\tlet isInteractiveCursor = doesElementHaveInteractivePointer(element)\n\n\t\t// Genius fix for almost all interactive elements\n\t\tif (isInteractiveCursor) {\n\t\t\treturn true\n\t\t}\n\n\t\tconst interactiveElements = new Set([\n\t\t\t'a', // Links\n\t\t\t'button', // Buttons\n\t\t\t'input', // All input types (text, checkbox, radio, etc.)\n\t\t\t'select', // Dropdown menus\n\t\t\t'textarea', // Text areas\n\t\t\t'details', // Expandable details\n\t\t\t'summary', // Summary element (clickable part of details)\n\t\t\t'label', // Form labels (often clickable)\n\t\t\t'option', // Select options\n\t\t\t'optgroup', // Option groups\n\t\t\t'fieldset', // Form fieldsets (can be interactive with legend)\n\t\t\t'legend', // Fieldset legends\n\t\t])\n\n\t\t// Define explicit disable attributes and properties\n\t\tconst explicitDisableTags = new Set([\n\t\t\t'disabled', // Standard disabled attribute\n\t\t\t// 'aria-disabled', // ARIA disabled state\n\t\t\t'readonly', // Read-only state\n\t\t\t// 'aria-readonly', // ARIA read-only state\n\t\t\t// 'aria-hidden', // Hidden from accessibility\n\t\t\t// 'hidden', // Hidden attribute\n\t\t\t// 'inert', // Inert attribute\n\t\t\t// 'aria-inert', // ARIA inert state\n\t\t\t// 'tabindex=\"-1\"', // Removed from tab order\n\t\t\t// 'aria-hidden=\"true\"' // Hidden from screen readers\n\t\t])\n\n\t\t// handle inputs, select, checkbox, radio, textarea, button and make sure they are not cursor style disabled/not-allowed\n\t\tif (interactiveElements.has(tagName)) {\n\t\t\t// Check for non-interactive cursor\n\t\t\tif (style?.cursor && nonInteractiveCursors.has(style.cursor)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// Check for explicit disable attributes\n\t\t\tfor (const disableTag of explicitDisableTags) {\n\t\t\t\tif (\n\t\t\t\t\telement.hasAttribute(disableTag) ||\n\t\t\t\t\telement.getAttribute(disableTag) === 'true' ||\n\t\t\t\t\telement.getAttribute(disableTag) === ''\n\t\t\t\t) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check for disabled property on form elements\n\t\t\tif (element.disabled) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// Check for readonly property on form elements\n\t\t\tif (element.readOnly) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// Check for inert property\n\t\t\tif (element.inert) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\treturn true\n\t\t}\n\n\t\tconst role = element.getAttribute('role')\n\t\tconst ariaRole = element.getAttribute('aria-role')\n\n\t\t// Check for contenteditable attribute\n\t\tif (element.getAttribute('contenteditable') === 'true' || element.isContentEditable) {\n\t\t\treturn true\n\t\t}\n\n\t\t// Added enhancement to capture dropdown interactive elements\n\t\tif (\n\t\t\telement.classList &&\n\t\t\t(element.classList.contains('button') ||\n\t\t\t\telement.classList.contains('dropdown-toggle') ||\n\t\t\t\telement.getAttribute('data-index') ||\n\t\t\t\telement.getAttribute('data-toggle') === 'dropdown' ||\n\t\t\t\telement.getAttribute('aria-haspopup') === 'true')\n\t\t) {\n\t\t\treturn true\n\t\t}\n\n\t\tconst interactiveRoles = new Set([\n\t\t\t'button', // Directly clickable element\n\t\t\t// 'link', // Clickable link\n\t\t\t'menu', // Menu container (ARIA menus)\n\t\t\t'menubar', // Menu bar container\n\t\t\t'menuitem', // Clickable menu item\n\t\t\t'menuitemradio', // Radio-style menu item (selectable)\n\t\t\t'menuitemcheckbox', // Checkbox-style menu item (toggleable)\n\t\t\t'radio', // Radio button (selectable)\n\t\t\t'checkbox', // Checkbox (toggleable)\n\t\t\t'tab', // Tab (clickable to switch content)\n\t\t\t'switch', // Toggle switch (clickable to change state)\n\t\t\t'slider', // Slider control (draggable)\n\t\t\t'spinbutton', // Number input with up/down controls\n\t\t\t'combobox', // Dropdown with text input\n\t\t\t'searchbox', // Search input field\n\t\t\t'textbox', // Text input field\n\t\t\t'listbox', // Selectable list\n\t\t\t'option', // Selectable option in a list\n\t\t\t'scrollbar', // Scrollable control\n\t\t])\n\n\t\t// Basic role/attribute checks\n\t\tconst hasInteractiveRole =\n\t\t\tinteractiveElements.has(tagName) ||\n\t\t\t(role && interactiveRoles.has(role)) ||\n\t\t\t(ariaRole && interactiveRoles.has(ariaRole))\n\n\t\tif (hasInteractiveRole) return true\n\n\t\t// check whether element has event listeners by window.getEventListeners\n\t\ttry {\n\t\t\tif (typeof getEventListeners === 'function') {\n\t\t\t\tconst listeners = getEventListeners(element)\n\t\t\t\tconst mouseEvents = ['click', 'mousedown', 'mouseup', 'dblclick']\n\t\t\t\tfor (const eventType of mouseEvents) {\n\t\t\t\t\tif (listeners[eventType] && listeners[eventType].length > 0) {\n\t\t\t\t\t\treturn true // Found a mouse interaction listener\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst getEventListenersForNode =\n\t\t\t\telement?.ownerDocument?.defaultView?.getEventListenersForNode ||\n\t\t\t\twindow.getEventListenersForNode\n\t\t\tif (typeof getEventListenersForNode === 'function') {\n\t\t\t\tconst listeners = getEventListenersForNode(element)\n\t\t\t\tconst interactionEvents = [\n\t\t\t\t\t'click',\n\t\t\t\t\t'mousedown',\n\t\t\t\t\t'mouseup',\n\t\t\t\t\t'keydown',\n\t\t\t\t\t'keyup',\n\t\t\t\t\t'submit',\n\t\t\t\t\t'change',\n\t\t\t\t\t'input',\n\t\t\t\t\t'focus',\n\t\t\t\t\t'blur',\n\t\t\t\t]\n\t\t\t\tfor (const eventType of interactionEvents) {\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tif (listener.type === eventType) {\n\t\t\t\t\t\t\treturn true // Found a common interaction listener\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Fallback: Check common event attributes if getEventListeners is not available (getEventListeners doesn't work in page.evaluate context)\n\t\t\tconst commonMouseAttrs = ['onclick', 'onmousedown', 'onmouseup', 'ondblclick']\n\t\t\tfor (const attr of commonMouseAttrs) {\n\t\t\t\tif (element.hasAttribute(attr) || typeof element[attr] === 'function') {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// console.warn(`Could not check event listeners for ${element.tagName}:`, e);\n\t\t\t// If checking listeners fails, rely on other checks\n\t\t}\n\n\t\t/**\n\t\t * @edit scrollable element detection\n\t\t */\n\t\tif (isScrollableElement(element)) {\n\t\t\treturn true\n\t\t}\n\n\t\treturn false\n\t}\n\n\t/**\n\t * Checks if an element is the topmost element at its position.\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @returns {boolean} Whether the element is the topmost element at its position.\n\t */\n\tfunction isTopElement(element) {\n\t\t// Special case: when viewportExpansion is -1, consider all elements as \"top\" elements\n\t\tif (viewportExpansion === -1) {\n\t\t\treturn true\n\t\t}\n\n\t\tconst rects = getCachedClientRects(element) // Replace element.getClientRects()\n\n\t\tif (!rects || rects.length === 0) {\n\t\t\treturn false // No geometry, cannot be top\n\t\t}\n\n\t\tlet isAnyRectInViewport = false\n\t\tfor (const rect of rects) {\n\t\t\t// Use the same logic as isInExpandedViewport check\n\t\t\tif (\n\t\t\t\trect.width > 0 &&\n\t\t\t\trect.height > 0 &&\n\t\t\t\t!(\n\t\t\t\t\t// Only check non-empty rects\n\t\t\t\t\trect.bottom < -viewportExpansion ||\n\t\t\t\t\trect.top > window.innerHeight + viewportExpansion ||\n\t\t\t\t\trect.right < -viewportExpansion ||\n\t\t\t\t\trect.left > window.innerWidth + viewportExpansion\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tisAnyRectInViewport = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif (!isAnyRectInViewport) {\n\t\t\treturn false // All rects are outside the viewport area\n\t\t}\n\n\t\t// Find the correct document context and root element\n\t\tlet doc = element.ownerDocument\n\n\t\t// If we're in an iframe, elements are considered top by default\n\t\tif (doc !== window.document) {\n\t\t\treturn true\n\t\t}\n\n\t\t/**\n\t\t * @edit improve `sampleRect`, filter out rects with 0 area\n\t\t */\n\t\t// find a rect that has width and height as sample\n\t\tlet rect = Array.from(rects).find((r) => r.width > 0 && r.height > 0)\n\t\tif (!rect) {\n\t\t\treturn false // No valid rect found\n\t\t}\n\n\t\t// For shadow DOM, we need to check within its own root context\n\t\tconst shadowRoot = element.getRootNode()\n\t\tif (shadowRoot instanceof ShadowRoot) {\n\t\t\tconst centerX = rect.left + rect.width / 2\n\t\t\tconst centerY = rect.top + rect.height / 2\n\n\t\t\ttry {\n\t\t\t\tconst topEl = shadowRoot.elementFromPoint(centerX, centerY)\n\t\t\t\tif (!topEl) return false\n\n\t\t\t\tlet current = topEl\n\t\t\t\twhile (current && current !== shadowRoot) {\n\t\t\t\t\tif (current === element) return true\n\t\t\t\t\tcurrent = current.parentElement\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t} catch (e) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\tconst margin = 5\n\n\t\t// For elements in viewport, check if they're topmost. Do the check in the\n\t\t// center of the element and at the corners to ensure we catch more cases.\n\t\tconst checkPoints = [\n\t\t\t// Initially only this was used, but it was not enough\n\t\t\t{ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 },\n\t\t\t{ x: rect.left + margin, y: rect.top + margin }, // top left\n\t\t\t// { x: rect.right - margin, y: rect.top + margin }, // top right\n\t\t\t// { x: rect.left + margin, y: rect.bottom - margin }, // bottom left\n\t\t\t{ x: rect.right - margin, y: rect.bottom - margin }, // bottom right\n\t\t]\n\n\t\treturn checkPoints.some(({ x, y }) => {\n\t\t\ttry {\n\t\t\t\tconst topEl = document.elementFromPoint(x, y)\n\t\t\t\tif (!topEl) return false\n\n\t\t\t\tlet current = topEl\n\t\t\t\twhile (current && current !== document.documentElement) {\n\t\t\t\t\tif (current === element) return true\n\t\t\t\t\tcurrent = current.parentElement\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t} catch (e) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Checks if an element is within the expanded viewport.\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @param {number} viewportExpansion - The viewport expansion.\n\t * @returns {boolean} Whether the element is within the expanded viewport.\n\t */\n\tfunction isInExpandedViewport(element, viewportExpansion) {\n\t\tif (viewportExpansion === -1) {\n\t\t\treturn true\n\t\t}\n\n\t\tconst rects = element.getClientRects() // Use getClientRects\n\n\t\tif (!rects || rects.length === 0) {\n\t\t\t// Fallback to getBoundingClientRect if getClientRects is empty,\n\t\t\t// useful for elements like <svg> that might not have client rects but have a bounding box.\n\t\t\tconst boundingRect = getCachedBoundingRect(element)\n\t\t\tif (!boundingRect || boundingRect.width === 0 || boundingRect.height === 0) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn !(\n\t\t\t\tboundingRect.bottom < -viewportExpansion ||\n\t\t\t\tboundingRect.top > window.innerHeight + viewportExpansion ||\n\t\t\t\tboundingRect.right < -viewportExpansion ||\n\t\t\t\tboundingRect.left > window.innerWidth + viewportExpansion\n\t\t\t)\n\t\t}\n\n\t\t// Check if *any* client rect is within the viewport\n\t\tfor (const rect of rects) {\n\t\t\tif (rect.width === 0 || rect.height === 0) continue // Skip empty rects\n\n\t\t\tif (!(\n\t\t\t\trect.bottom < -viewportExpansion ||\n\t\t\t\trect.top > window.innerHeight + viewportExpansion ||\n\t\t\t\trect.right < -viewportExpansion ||\n\t\t\t\trect.left > window.innerWidth + viewportExpansion\n\t\t\t)) {\n\t\t\t\treturn true // Found at least one rect in the viewport\n\t\t\t}\n\t\t}\n\n\t\treturn false // No rects were found in the viewport\n\t}\n\n\t// /**\n\t// * Gets the effective scroll of an element.\n\t// *\n\t// * @param {HTMLElement} element - The element to get the effective scroll for.\n\t// * @returns {Object} The effective scroll of the element.\n\t// */\n\t// function getEffectiveScroll(element) {\n\t// let currentEl = element;\n\t// let scrollX = 0;\n\t// let scrollY = 0;\n\n\t// while (currentEl && currentEl !== document.documentElement) {\n\t// if (currentEl.scrollLeft || currentEl.scrollTop) {\n\t// scrollX += currentEl.scrollLeft;\n\t// scrollY += currentEl.scrollTop;\n\t// }\n\t// currentEl = currentEl.parentElement;\n\t// }\n\n\t// scrollX += window.scrollX;\n\t// scrollY += window.scrollY;\n\n\t// return { scrollX, scrollY };\n\t// }\n\n\t/**\n\t * Checks if an element is an interactive candidate.\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @returns {boolean} Whether the element is an interactive candidate.\n\t */\n\n\t// @edit fix \"aria-*\" attributes check\n\tconst INTERACTIVE_ARIA_ATTRS = [\n\t\t'aria-expanded',\n\t\t'aria-checked',\n\t\t'aria-selected',\n\t\t'aria-pressed',\n\t\t'aria-haspopup',\n\t\t'aria-controls',\n\t\t'aria-owns',\n\t\t'aria-activedescendant',\n\t\t'aria-valuenow',\n\t\t'aria-valuetext',\n\t\t'aria-valuemax',\n\t\t'aria-valuemin',\n\t\t'aria-autocomplete',\n\t]\n\n\tfunction hasInteractiveAria(el) {\n\t\tfor (let i = 0; i < INTERACTIVE_ARIA_ATTRS.length; i++) {\n\t\t\tif (el.hasAttribute(INTERACTIVE_ARIA_ATTRS[i])) return true\n\t\t}\n\t\treturn false\n\t}\n\n\tfunction isInteractiveCandidate(element) {\n\t\tif (!element || element.nodeType !== Node.ELEMENT_NODE) return false\n\n\t\tconst tagName = element.tagName.toLowerCase()\n\n\t\t// Fast-path for common interactive elements\n\t\tconst interactiveElements = new Set([\n\t\t\t'a',\n\t\t\t'button',\n\t\t\t'input',\n\t\t\t'select',\n\t\t\t'textarea',\n\t\t\t'details',\n\t\t\t'summary',\n\t\t\t'label',\n\t\t])\n\n\t\tif (interactiveElements.has(tagName)) return true\n\n\t\t// Quick attribute checks without getting full lists\n\t\tconst hasQuickInteractiveAttr =\n\t\t\telement.hasAttribute('onclick') ||\n\t\t\telement.hasAttribute('role') ||\n\t\t\telement.hasAttribute('tabindex') ||\n\t\t\thasInteractiveAria(element) ||\n\t\t\telement.hasAttribute('data-action') ||\n\t\t\telement.getAttribute('contenteditable') === 'true'\n\n\t\treturn hasQuickInteractiveAttr\n\t}\n\n\t// --- Define constants for distinct interaction check ---\n\tconst DISTINCT_INTERACTIVE_TAGS = new Set([\n\t\t'a',\n\t\t'button',\n\t\t'input',\n\t\t'select',\n\t\t'textarea',\n\t\t'summary',\n\t\t'details',\n\t\t'label',\n\t\t'option',\n\t\t'li',\n\t])\n\tconst DISTINCT_INTERACTIVE_ROLES = new Set([\n\t\t'button',\n\t\t'link',\n\t\t'menuitem',\n\t\t'menuitemradio',\n\t\t'menuitemcheckbox',\n\t\t'radio',\n\t\t'checkbox',\n\t\t'tab',\n\t\t'switch',\n\t\t'slider',\n\t\t'spinbutton',\n\t\t'combobox',\n\t\t'searchbox',\n\t\t'textbox',\n\t\t'listbox',\n\t\t'listitem',\n\t\t'treeitem',\n\t\t'row',\n\t\t'option',\n\t\t'scrollbar',\n\t])\n\n\t/**\n\t * Heuristically determines if an element should be considered as independently interactive,\n\t * even if it's nested inside another interactive container.\n\t *\n\t * This function helps detect deeply nested actionable elements (e.g., menu items within a button)\n\t * that may not be picked up by strict interactivity checks.\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @returns {boolean} Whether the element is heuristically interactive.\n\t */\n\tfunction isHeuristicallyInteractive(element) {\n\t\tif (!element || element.nodeType !== Node.ELEMENT_NODE) return false\n\n\t\t// Skip non-visible elements early for performance\n\t\tif (!isElementVisible(element)) return false\n\n\t\t// Check for common attributes that often indicate interactivity\n\t\tconst hasInteractiveAttributes =\n\t\t\telement.hasAttribute('role') ||\n\t\t\telement.hasAttribute('tabindex') ||\n\t\t\telement.hasAttribute('onclick') ||\n\t\t\ttypeof element.onclick === 'function'\n\n\t\t// Check for semantic class names suggesting interactivity\n\t\tconst hasInteractiveClass = /\\b(btn|clickable|menu|item|entry|link)\\b/i.test(\n\t\t\telement.className || ''\n\t\t)\n\n\t\t// Determine whether the element is inside a known interactive container\n\t\tconst isInKnownContainer = Boolean(\n\t\t\telement.closest('button,a,[role=\"button\"],.menu,.dropdown,.list,.toolbar')\n\t\t)\n\n\t\t// Ensure the element has at least one visible child (to avoid marking empty wrappers)\n\t\tconst hasVisibleChildren = [...element.children].some(isElementVisible)\n\n\t\t// Avoid highlighting elements whose parent is <body> (top-level wrappers)\n\t\tconst isParentBody = element.parentElement && element.parentElement.isSameNode(document.body)\n\n\t\treturn (\n\t\t\t(isInteractiveElement(element) || hasInteractiveAttributes || hasInteractiveClass) &&\n\t\t\thasVisibleChildren &&\n\t\t\tisInKnownContainer &&\n\t\t\t!isParentBody\n\t\t)\n\t}\n\n\t/**\n\t * Checks if an element likely represents a distinct interaction\n\t * separate from its parent (if the parent is also interactive).\n\t *\n\t * @param {HTMLElement} element - The element to check.\n\t * @returns {boolean} Whether the element is a distinct interaction.\n\t */\n\tfunction isElementDistinctInteraction(element) {\n\t\tif (!element || element.nodeType !== Node.ELEMENT_NODE) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst tagName = element.tagName.toLowerCase()\n\t\tconst role = element.getAttribute('role')\n\n\t\t// Check if it's an iframe - always distinct boundary\n\t\tif (tagName === 'iframe') {\n\t\t\treturn true\n\t\t}\n\n\t\t// Check tag name\n\t\tif (DISTINCT_INTERACTIVE_TAGS.has(tagName)) {\n\t\t\treturn true\n\t\t}\n\t\t// Check interactive roles\n\t\tif (role && DISTINCT_INTERACTIVE_ROLES.has(role)) {\n\t\t\treturn true\n\t\t}\n\t\t// Check contenteditable\n\t\tif (element.isContentEditable || element.getAttribute('contenteditable') === 'true') {\n\t\t\treturn true\n\t\t}\n\t\t// Check for common testing/automation attributes\n\t\tif (\n\t\t\telement.hasAttribute('data-testid') ||\n\t\t\telement.hasAttribute('data-cy') ||\n\t\t\telement.hasAttribute('data-test')\n\t\t) {\n\t\t\treturn true\n\t\t}\n\t\t// Check for explicit onclick handler (attribute or property)\n\t\tif (element.hasAttribute('onclick') || typeof element.onclick === 'function') {\n\t\t\treturn true\n\t\t}\n\t\t// ARIA state attributes imply the element manages its own interaction state\n\t\tif (hasInteractiveAria(element)) {\n\t\t\treturn true\n\t\t}\n\n\t\t// return false\n\n\t\t// Check for other common interaction event listeners\n\t\ttry {\n\t\t\tconst getEventListenersForNode =\n\t\t\t\telement?.ownerDocument?.defaultView?.getEventListenersForNode ||\n\t\t\t\twindow.getEventListenersForNode\n\t\t\tif (typeof getEventListenersForNode === 'function') {\n\t\t\t\tconst listeners = getEventListenersForNode(element)\n\t\t\t\tconst interactionEvents = [\n\t\t\t\t\t'click',\n\t\t\t\t\t'mousedown',\n\t\t\t\t\t'mouseup',\n\t\t\t\t\t'keydown',\n\t\t\t\t\t'keyup',\n\t\t\t\t\t'submit',\n\t\t\t\t\t'change',\n\t\t\t\t\t'input',\n\t\t\t\t\t'focus',\n\t\t\t\t\t'blur',\n\t\t\t\t]\n\t\t\t\tfor (const eventType of interactionEvents) {\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tif (listener.type === eventType) {\n\t\t\t\t\t\t\treturn true // Found a common interaction listener\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Fallback: Check common event attributes if getEventListeners is not available (getEventListenersForNode doesn't work in page.evaluate context)\n\t\t\tconst commonEventAttrs = [\n\t\t\t\t'onmousedown',\n\t\t\t\t'onmouseup',\n\t\t\t\t'onkeydown',\n\t\t\t\t'onkeyup',\n\t\t\t\t'onsubmit',\n\t\t\t\t'onchange',\n\t\t\t\t'oninput',\n\t\t\t\t'onfocus',\n\t\t\t\t'onblur',\n\t\t\t]\n\t\t\tif (commonEventAttrs.some((attr) => element.hasAttribute(attr))) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// console.warn(`Could not check event listeners for ${element.tagName}:`, e);\n\t\t\t// If checking listeners fails, rely on other checks\n\t\t}\n\n\t\t// if the element is not strictly interactive but appears clickable based on heuristic signals\n\t\tif (isHeuristicallyInteractive(element)) {\n\t\t\treturn true\n\t\t}\n\n\t\t// Scrollable containers are always distinct — the LLM needs their index for targeted scrolling.\n\t\t// Check extraData (already set by isScrollableElement in isInteractiveElement) to avoid redundant layout reads.\n\t\tif (extraData.get(element)?.scrollable) {\n\t\t\treturn true\n\t\t}\n\n\t\t// Default to false: if it's interactive but doesn't match above,\n\t\t// assume it triggers the same action as the parent.\n\t\treturn false\n\t}\n\t// --- End distinct interaction check ---\n\n\t/**\n * Handles the logic for deciding whether to highlight an element and performing the highlight.\n * @param {\n {\n tagName: string;\n attributes: Record<string, string>;\n xpath: any;\n children: never[];\n isVisible?: boolean;\n isTopElement?: boolean;\n isInteractive?: boolean;\n isInViewport?: boolean;\n highlightIndex?: number;\n shadowRoot?: boolean;\n }} nodeData - The node data object.\n * @param {HTMLElement} node - The node to highlight.\n * @param {HTMLElement | null} parentIframe - The parent iframe node.\n * @param {boolean} isParentHighlighted - Whether the parent node is highlighted.\n * @returns {boolean} Whether the element was highlighted.\n */\n\tfunction handleHighlighting(nodeData, node, parentIframe, isParentHighlighted) {\n\t\tif (!nodeData.isInteractive) return false // Not interactive, definitely don't highlight\n\n\t\tlet shouldHighlight = false\n\t\tif (!isParentHighlighted) {\n\t\t\t// Parent wasn't highlighted, this interactive node can be highlighted.\n\t\t\tshouldHighlight = true\n\t\t} else {\n\t\t\t// Parent *was* highlighted. Only highlight this node if it represents a distinct interaction.\n\t\t\tif (isElementDistinctInteraction(node)) {\n\t\t\t\tshouldHighlight = true\n\t\t\t} else {\n\t\t\t\t// console.log(`Skipping highlight for ${nodeData.tagName} (parent highlighted)`);\n\t\t\t\tshouldHighlight = false\n\t\t\t}\n\t\t}\n\n\t\tif (shouldHighlight) {\n\t\t\t// Check viewport status before assigning index and highlighting\n\t\t\tnodeData.isInViewport = isInExpandedViewport(node, viewportExpansion)\n\n\t\t\t// When viewportExpansion is -1, all interactive elements should get a highlight index\n\t\t\t// regardless of viewport status\n\t\t\tif (nodeData.isInViewport || viewportExpansion === -1) {\n\t\t\t\tnodeData.highlightIndex = highlightIndex++\n\n\t\t\t\tif (doHighlightElements) {\n\t\t\t\t\tif (focusHighlightIndex >= 0) {\n\t\t\t\t\t\tif (focusHighlightIndex === nodeData.highlightIndex) {\n\t\t\t\t\t\t\thighlightElement(node, nodeData.highlightIndex, parentIframe)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\thighlightElement(node, nodeData.highlightIndex, parentIframe)\n\t\t\t\t\t}\n\t\t\t\t\treturn true // Successfully highlighted\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// console.log(`Skipping highlight for ${nodeData.tagName} (outside viewport)`);\n\t\t\t}\n\t\t}\n\n\t\treturn false // Did not highlight\n\t}\n\n\t/**\n\t * Creates a node data object for a given node and its descendants.\n\t *\n\t * @param {HTMLElement} node - The node to process.\n\t * @param {HTMLElement | null} parentIframe - The parent iframe node.\n\t * @param {boolean} isParentHighlighted - Whether the parent node is highlighted.\n\t * @returns {string | null} The ID of the node data object, or null if the node is not processed.\n\t */\n\tfunction buildDomTree(node, parentIframe = null, isParentHighlighted = false) {\n\t\t// Fast rejection checks first\n\t\tif (\n\t\t\t!node ||\n\t\t\tnode.id === HIGHLIGHT_CONTAINER_ID ||\n\t\t\t(node.nodeType !== Node.ELEMENT_NODE && node.nodeType !== Node.TEXT_NODE)\n\t\t) {\n\t\t\treturn null\n\t\t}\n\n\t\tif (!node || node.id === HIGHLIGHT_CONTAINER_ID) {\n\t\t\treturn null\n\t\t}\n\n\t\t/**\n\t\t * @edit add `data-browser-use-ignore` attribute\n\t\t */\n\t\tif (node.dataset?.browserUseIgnore === 'true' || node.dataset?.pageAgentIgnore === 'true') {\n\t\t\treturn null // Skip this node and its children\n\t\t}\n\n\t\t/**\n\t\t * @edit exclude aria-hidden elements\n\t\t */\n\t\tif (node.getAttribute && node.getAttribute('aria-hidden') === 'true') {\n\t\t\treturn null // Skip this node and its children\n\t\t}\n\n\t\t// Special handling for root node (body)\n\t\tif (node === document.body) {\n\t\t\tconst nodeData = {\n\t\t\t\ttagName: 'body',\n\t\t\t\tattributes: {},\n\t\t\t\txpath: '/body',\n\t\t\t\tchildren: [],\n\t\t\t}\n\n\t\t\t// Process children of body\n\t\t\tfor (const child of node.childNodes) {\n\t\t\t\tconst domElement = buildDomTree(child, parentIframe, false) // Body's children have no highlighted parent initially\n\t\t\t\tif (domElement) nodeData.children.push(domElement)\n\t\t\t}\n\n\t\t\tconst id = `${ID.current++}`\n\t\t\tDOM_HASH_MAP[id] = nodeData\n\t\t\treturn id\n\t\t}\n\n\t\t// Early bailout for non-element nodes except text\n\t\tif (node.nodeType !== Node.ELEMENT_NODE && node.nodeType !== Node.TEXT_NODE) {\n\t\t\treturn null\n\t\t}\n\n\t\t// Process text nodes\n\t\tif (node.nodeType === Node.TEXT_NODE) {\n\t\t\tconst textContent = node.textContent?.trim()\n\t\t\tif (!textContent) {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\t// Only check visibility for text nodes that might be visible\n\t\t\tconst parentElement = node.parentElement\n\t\t\tif (!parentElement || parentElement.tagName.toLowerCase() === 'script') {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\tconst id = `${ID.current++}`\n\t\t\tDOM_HASH_MAP[id] = {\n\t\t\t\ttype: 'TEXT_NODE',\n\t\t\t\ttext: textContent,\n\t\t\t\tisVisible: isTextNodeVisible(node),\n\t\t\t}\n\t\t\treturn id\n\t\t}\n\n\t\t// Quick checks for element nodes\n\t\tif (node.nodeType === Node.ELEMENT_NODE && !isElementAccepted(node)) {\n\t\t\treturn null\n\t\t}\n\n\t\t// Early viewport check - only filter out elements clearly outside viewport\n\t\t// The getBoundingClientRect() of the Shadow DOM host element may return width/height = 0\n\t\tif (viewportExpansion !== -1 && !node.shadowRoot) {\n\t\t\tconst rect = getCachedBoundingRect(node) // Keep for initial quick check\n\t\t\tconst style = getCachedComputedStyle(node)\n\n\t\t\t// Skip viewport check for fixed/sticky elements as they may appear anywhere\n\t\t\tconst isFixedOrSticky = style && (style.position === 'fixed' || style.position === 'sticky')\n\n\t\t\t// Check if element has actual dimensions using offsetWidth/Height (quick check)\n\t\t\tconst hasSize = node.offsetWidth > 0 || node.offsetHeight > 0\n\n\t\t\t// Use getBoundingClientRect for the quick OUTSIDE check.\n\t\t\t// isInExpandedViewport will do the more accurate check later if needed.\n\t\t\tif (\n\t\t\t\t!rect ||\n\t\t\t\t(!isFixedOrSticky &&\n\t\t\t\t\t!hasSize &&\n\t\t\t\t\t(rect.bottom < -viewportExpansion ||\n\t\t\t\t\t\trect.top > window.innerHeight + viewportExpansion ||\n\t\t\t\t\t\trect.right < -viewportExpansion ||\n\t\t\t\t\t\trect.left > window.innerWidth + viewportExpansion))\n\t\t\t) {\n\t\t\t\t// console.log(\"Skipping node outside viewport (quick check):\", node.tagName, rect);\n\t\t\t\treturn null\n\t\t\t}\n\t\t}\n\n\t\t/**\n * @type {\n {\n tagName: string;\n attributes: Record<string, string | null>;\n xpath: any;\n children: never[];\n isVisible?: boolean;\n isTopElement?: boolean;\n isInteractive?: boolean;\n isInViewport?: boolean;\n highlightIndex?: number;\n shadowRoot?: boolean;\n }\n } nodeData - The node data object.\n */\n\t\tconst nodeData = {\n\t\t\ttagName: node.tagName.toLowerCase(),\n\t\t\tattributes: {},\n\n\t\t\t/**\n\t\t\t * @edit no need for xpath\n\t\t\t */\n\t\t\t// xpath: getXPathTree(node, true),\n\n\t\t\tchildren: [],\n\t\t}\n\n\t\t// Get attributes for interactive elements or potential text containers\n\t\tif (\n\t\t\tisInteractiveCandidate(node) ||\n\t\t\tnode.tagName.toLowerCase() === 'iframe' ||\n\t\t\tnode.tagName.toLowerCase() === 'body'\n\t\t) {\n\t\t\tconst attributeNames = node.getAttributeNames?.() || []\n\t\t\tfor (const name of attributeNames) {\n\t\t\t\tconst value = node.getAttribute(name)\n\t\t\t\tnodeData.attributes[name] = value\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * @edit @workaround input.checked\n\t\t\t */\n\t\t\tif (\n\t\t\t\tnode.tagName.toLowerCase() === 'input' &&\n\t\t\t\t(node.type === 'checkbox' || node.type === 'radio')\n\t\t\t) {\n\t\t\t\tnodeData.attributes.checked = node.checked ? 'true' : 'false' // Store as string for consistency\n\t\t\t}\n\t\t}\n\n\t\tlet nodeWasHighlighted = false\n\t\t// Perform visibility, interactivity, and highlighting checks\n\t\tif (node.nodeType === Node.ELEMENT_NODE) {\n\t\t\tnodeData.isVisible = isElementVisible(node) // isElementVisible uses offsetWidth/Height, which is fine\n\t\t\tif (nodeData.isVisible) {\n\t\t\t\tnodeData.isTopElement = isTopElement(node)\n\n\t\t\t\t// Special handling for ARIA menu containers - check interactivity even if not top element\n\t\t\t\tconst role = node.getAttribute('role')\n\t\t\t\tconst isMenuContainer = role === 'menu' || role === 'menubar' || role === 'listbox'\n\n\t\t\t\tif (nodeData.isTopElement || isMenuContainer) {\n\t\t\t\t\tnodeData.isInteractive = isInteractiveElement(node)\n\t\t\t\t\t// Call the dedicated highlighting function\n\t\t\t\t\tnodeWasHighlighted = handleHighlighting(nodeData, node, parentIframe, isParentHighlighted)\n\n\t\t\t\t\t/**\n\t\t\t\t\t * @edit direct dom ref\n\t\t\t\t\t */\n\t\t\t\t\tnodeData.ref = node\n\n\t\t\t\t\t/**\n\t\t\t\t\t * @edit make sure attributes exist for interactive candidates.\n\t\t\t\t\t * @note if the element failed the isInteractiveCandidate, attributes would be empty.\n\t\t\t\t\t */\n\t\t\t\t\tif (nodeData.isInteractive && Object.keys(nodeData.attributes).length === 0) {\n\t\t\t\t\t\tconst attributeNames = node.getAttributeNames?.() || []\n\t\t\t\t\t\tfor (const name of attributeNames) {\n\t\t\t\t\t\t\tconst value = node.getAttribute(name)\n\t\t\t\t\t\t\tnodeData.attributes[name] = value\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Process children, with special handling for iframes and rich text editors\n\t\tif (node.tagName) {\n\t\t\tconst tagName = node.tagName.toLowerCase()\n\n\t\t\t// Handle iframes\n\t\t\tif (tagName === 'iframe') {\n\t\t\t\ttry {\n\t\t\t\t\tconst iframeDoc = node.contentDocument || node.contentWindow?.document\n\t\t\t\t\tif (iframeDoc) {\n\t\t\t\t\t\tfor (const child of iframeDoc.childNodes) {\n\t\t\t\t\t\t\tconst domElement = buildDomTree(child, node, false)\n\t\t\t\t\t\t\tif (domElement) nodeData.children.push(domElement)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconsole.warn('Unable to access iframe:', e)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Handle rich text editors and contenteditable elements\n\t\t\telse if (\n\t\t\t\tnode.isContentEditable ||\n\t\t\t\tnode.getAttribute('contenteditable') === 'true' ||\n\t\t\t\tnode.id === 'tinymce' ||\n\t\t\t\tnode.classList.contains('mce-content-body') ||\n\t\t\t\t(tagName === 'body' && node.getAttribute('data-id')?.startsWith('mce_'))\n\t\t\t) {\n\t\t\t\t// Process all child nodes to capture formatted text\n\t\t\t\tfor (const child of node.childNodes) {\n\t\t\t\t\tconst domElement = buildDomTree(child, parentIframe, nodeWasHighlighted)\n\t\t\t\t\tif (domElement) nodeData.children.push(domElement)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Handle shadow DOM\n\t\t\t\tif (node.shadowRoot) {\n\t\t\t\t\tnodeData.shadowRoot = true\n\t\t\t\t\tfor (const child of node.shadowRoot.childNodes) {\n\t\t\t\t\t\tconst domElement = buildDomTree(child, parentIframe, nodeWasHighlighted)\n\t\t\t\t\t\tif (domElement) nodeData.children.push(domElement)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Handle regular elements\n\t\t\t\tfor (const child of node.childNodes) {\n\t\t\t\t\t// Pass the highlighted status of the *current* node to its children\n\t\t\t\t\tconst passHighlightStatusToChild = nodeWasHighlighted || isParentHighlighted\n\t\t\t\t\tconst domElement = buildDomTree(child, parentIframe, passHighlightStatusToChild)\n\t\t\t\t\tif (domElement) nodeData.children.push(domElement)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Skip empty anchor tags only if they have no dimensions and no children\n\t\tif (nodeData.tagName === 'a' && nodeData.children.length === 0 && !nodeData.attributes.href) {\n\t\t\t// Check if the anchor has actual dimensions\n\t\t\tconst rect = getCachedBoundingRect(node)\n\t\t\tconst hasSize =\n\t\t\t\t(rect && rect.width > 0 && rect.height > 0) || node.offsetWidth > 0 || node.offsetHeight > 0\n\n\t\t\tif (!hasSize) {\n\t\t\t\treturn null\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * @edit add `extra` field for extra data\n\t\t */\n\t\tnodeData.extra = extraData.get(node) || null\n\n\t\tconst id = `${ID.current++}`\n\t\tDOM_HASH_MAP[id] = nodeData\n\t\treturn id\n\t}\n\n\tconst rootId = buildDomTree(document.body)\n\n\t// Clear the cache before starting\n\tDOM_CACHE.clearCache()\n\n\treturn { rootId, map: DOM_HASH_MAP }\n}\n","import domTree from './dom_tree/index.js'\nimport {\n\tElementDomNode,\n\tFlatDomTree,\n\tInteractiveElementDomNode,\n\tTextDomNode,\n} from './dom_tree/type'\n\n/**\n * Viewport expansion for DOM tree extraction.\n * -1 means full page (no viewport restriction)\n * 0 means viewport only\n * positive values expand the viewport by that many pixels\n *\n * @note Since isTopElement depends on elementFromPoint,\n * it returns null when out of viewport, this feature has no practical use, only differ between -1 and 0\n */\nconst DEFAULT_VIEWPORT_EXPANSION = -1\n\nexport function resolveViewportExpansion(viewportExpansion?: number): number {\n\treturn viewportExpansion ?? DEFAULT_VIEWPORT_EXPANSION\n}\n\nexport interface DomConfig {\n\tviewportExpansion?: number\n\tinteractiveBlacklist?: (Element | (() => Element))[]\n\tinteractiveWhitelist?: (Element | (() => Element))[]\n\tincludeAttributes?: string[]\n\thighlightOpacity?: number\n\thighlightLabelOpacity?: number\n\n\t/**\n\t * Preserve semantic landmark tags in dehydrated output even if not interactive\n\t * @note maybe confusing for LLM combining with page scrolling, use with caution\n\t **/\n\tkeepSemanticTags?: boolean\n}\n\n// TODO: corresponding roles\nconst SEMANTIC_TAGS = new Set([\n\t'nav',\n\t'menu',\n\t// 'main',\n\t'header',\n\t'footer',\n\t'aside',\n\t// 'article',\n\t// 'form',\n\t'dialog',\n])\n\n/**\n * 用于检测可交互元素是否是新出现的。\n */\nconst newElementsCache = new WeakMap<HTMLElement, string>()\n\nexport function getFlatTree(config: DomConfig): FlatDomTree {\n\tconst viewportExpansion = resolveViewportExpansion(config.viewportExpansion)\n\n\tconst interactiveBlacklist = [] as Element[]\n\tfor (const item of config.interactiveBlacklist || []) {\n\t\tif (typeof item === 'function') {\n\t\t\tinteractiveBlacklist.push(item())\n\t\t} else {\n\t\t\tinteractiveBlacklist.push(item)\n\t\t}\n\t}\n\n\tconst interactiveWhitelist = [] as Element[]\n\tfor (const item of config.interactiveWhitelist || []) {\n\t\tif (typeof item === 'function') {\n\t\t\tinteractiveWhitelist.push(item())\n\t\t} else {\n\t\t\tinteractiveWhitelist.push(item)\n\t\t}\n\t}\n\n\tconst elements = domTree({\n\t\tdoHighlightElements: true,\n\t\tdebugMode: true,\n\t\tfocusHighlightIndex: -1,\n\t\tviewportExpansion,\n\t\tinteractiveBlacklist,\n\t\tinteractiveWhitelist,\n\t\thighlightOpacity: config.highlightOpacity ?? 0.0,\n\t\thighlightLabelOpacity: config.highlightLabelOpacity ?? 0.1,\n\t}) as FlatDomTree\n\n\tconst currentUrl = window.location.href\n\n\t/**\n\t * 标记新出现的元素\n\t * @todo browser-use 使用 hash(位置,属性等信息) 来判断是否同一个元素,\n\t * 能够解决 1. 元素被删除后重新添加 2. 页面卸载 等问题。\n\t * 这里先简单做.\n\t */\n\tfor (const nodeId in elements.map) {\n\t\tconst node = elements.map[nodeId]\n\t\tif (node.isInteractive && node.ref) {\n\t\t\tconst ref = node.ref as HTMLElement\n\t\t\t// @note 这样太严格,元素是可以跨页面存在的\n\t\t\t// if (newElementsCache.get(ref) !== currentUrl) {\n\t\t\tif (!newElementsCache.has(ref)) {\n\t\t\t\tnewElementsCache.set(ref, currentUrl)\n\t\t\t\tnode.isNew = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn elements\n}\n\nconst globRegexCache = new Map<string, RegExp>()\n\nfunction globToRegex(pattern: string): RegExp {\n\tlet regex = globRegexCache.get(pattern)\n\tif (!regex) {\n\t\tconst escaped = pattern.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n\t\tregex = new RegExp(`^${escaped.replace(/\\*/g, '.*')}$`)\n\t\tglobRegexCache.set(pattern, regex)\n\t}\n\treturn regex\n}\n\nfunction matchAttributes(\n\tattrs: Record<string, string>,\n\tpatterns: string[]\n): Record<string, string> {\n\tconst result: Record<string, string> = {}\n\n\tfor (const pattern of patterns) {\n\t\tif (pattern.includes('*')) {\n\t\t\tconst regex = globToRegex(pattern)\n\t\t\tfor (const key of Object.keys(attrs)) {\n\t\t\t\tif (regex.test(key) && attrs[key].trim()) {\n\t\t\t\t\tresult[key] = attrs[key].trim()\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tconst value = attrs[pattern]\n\t\t\tif (value && value.trim()) {\n\t\t\t\tresult[pattern] = value.trim()\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}\n\n/**\n * elementsToString 内部使用的类型\n */\ninterface TreeNode {\n\ttype: 'text' | 'element'\n\tparent: TreeNode | null\n\tchildren: TreeNode[]\n\tisVisible: boolean\n\t// Text node properties\n\ttext?: string\n\t// Element node properties\n\ttagName?: string\n\tattributes?: Record<string, string>\n\tisInteractive?: boolean\n\tisTopElement?: boolean\n\tisNew?: boolean\n\thighlightIndex?: number\n\textra?: Record<string, any>\n}\n\n/**\n * 对应 python 中的 views::clickable_elements_to_string,\n * 将 dom 信息处理成适合 llm 阅读的文本格式\n * @形如\n * ``` text\n * [0]<a aria-label=page-agent.js 首页 />\n * [1]<div >P />\n * [2]<div >page-agent.js\n * UI Agent in your webpage />\n * [3]<a >文档 />\n * [4]<a aria-label=查看源码(在新窗口打开)>源码 />\n * UI Agent in your webpage\n * 用户输入需求,AI 理解页面并自动操作。\n * [5]<a role=button>快速开始 />\n * [6]<a role=button>查看文档 />\n * 无需后端\n * ```\n * 其中可交互元素用序号标出,提示llm可以用序号操作。\n * 缩进代表父子关系。\n * 普通文本则直接列出来。\n *\n * @todo 数据脱敏过滤器\n */\nexport function flatTreeToString(\n\tflatTree: FlatDomTree,\n\tincludeAttributes: string[] = [],\n\tkeepSemanticTags = false\n): string {\n\tconst DEFAULT_INCLUDE_ATTRIBUTES = [\n\t\t'title',\n\t\t'type',\n\t\t'checked',\n\t\t'name',\n\t\t'role',\n\t\t'value',\n\t\t'placeholder',\n\t\t'data-date-format',\n\t\t'alt',\n\t\t'aria-label',\n\t\t'aria-expanded',\n\t\t'data-state',\n\t\t'aria-checked',\n\n\t\t// @edit added for better form handling\n\t\t'id',\n\t\t'for',\n\n\t\t// for jump check\n\t\t'target',\n\n\t\t// absolute position dropdown menu\n\t\t'aria-haspopup',\n\t\t'aria-controls',\n\t\t'aria-owns',\n\n\t\t// content editable\n\t\t'contenteditable',\n\t]\n\n\tconst includeAttrs = [...includeAttributes, ...DEFAULT_INCLUDE_ATTRIBUTES]\n\n\t// Helper function to cap text length\n\tconst capTextLength = (text: string, maxLength: number): string => {\n\t\tif (text.length > maxLength) {\n\t\t\treturn text.substring(0, maxLength) + '...'\n\t\t}\n\t\treturn text\n\t}\n\n\t// Build tree structure from flat map\n\tconst buildTreeNode = (nodeId: string): TreeNode | null => {\n\t\tconst node = flatTree.map[nodeId]\n\t\tif (!node) return null\n\n\t\tif (node.type === 'TEXT_NODE') {\n\t\t\tconst textNode = node as TextDomNode\n\t\t\treturn {\n\t\t\t\ttype: 'text',\n\t\t\t\ttext: textNode.text,\n\t\t\t\tisVisible: textNode.isVisible,\n\t\t\t\tparent: null,\n\t\t\t\tchildren: [],\n\t\t\t}\n\t\t} else {\n\t\t\tconst elementNode = node as ElementDomNode\n\t\t\tconst children: TreeNode[] = []\n\n\t\t\tif (elementNode.children) {\n\t\t\t\tfor (const childId of elementNode.children) {\n\t\t\t\t\tconst child = buildTreeNode(childId)\n\t\t\t\t\tif (child) {\n\t\t\t\t\t\tchild.parent = null // Will be set later\n\t\t\t\t\t\tchildren.push(child)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\ttype: 'element',\n\t\t\t\ttagName: elementNode.tagName,\n\t\t\t\tattributes: elementNode.attributes ?? {},\n\t\t\t\tisVisible: elementNode.isVisible ?? false,\n\t\t\t\tisInteractive: elementNode.isInteractive ?? false,\n\t\t\t\tisTopElement: elementNode.isTopElement ?? false,\n\t\t\t\tisNew: elementNode.isNew ?? false,\n\t\t\t\thighlightIndex: elementNode.highlightIndex,\n\t\t\t\tparent: null,\n\t\t\t\tchildren,\n\t\t\t\textra: elementNode.extra ?? {},\n\t\t\t}\n\t\t}\n\t}\n\n\t// Set parent references\n\tconst setParentReferences = (node: TreeNode, parent: TreeNode | null = null) => {\n\t\tnode.parent = parent\n\t\tfor (const child of node.children) {\n\t\t\tsetParentReferences(child, node)\n\t\t}\n\t}\n\n\t// Build root node\n\tconst rootNode = buildTreeNode(flatTree.rootId)\n\tif (!rootNode) return ''\n\n\tsetParentReferences(rootNode)\n\n\t// Helper to check if text node has parent with highlight index\n\tconst hasParentWithHighlightIndex = (node: TreeNode): boolean => {\n\t\tlet current = node.parent\n\t\twhile (current) {\n\t\t\tif (current.type === 'element' && current.highlightIndex !== undefined) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tcurrent = current.parent\n\t\t}\n\t\treturn false\n\t}\n\n\t// Helper to check if parent is top element\n\t// const isParentTopElement = (node: TreeNode): boolean => {\n\t// \treturn node.parent?.type === 'element' && node.parent.isTopElement === true\n\t// }\n\n\t// Main processing function\n\tconst processNode = (node: TreeNode, depth: number, result: string[]): void => {\n\t\tlet nextDepth = depth\n\t\tconst depthStr = '\\t'.repeat(depth)\n\n\t\tif (node.type === 'element') {\n\t\t\tconst isSemantic = keepSemanticTags && node.tagName && SEMANTIC_TAGS.has(node.tagName)\n\n\t\t\t// Add element with highlight_index\n\t\t\tif (node.highlightIndex !== undefined) {\n\t\t\t\tnextDepth += 1\n\n\t\t\t\tconst text = getAllTextTillNextClickableElement(node)\n\t\t\t\tlet attributesHtmlStr = ''\n\n\t\t\t\tif (includeAttrs.length > 0 && node.attributes) {\n\t\t\t\t\tconst attributesToInclude = matchAttributes(node.attributes, includeAttrs)\n\n\t\t\t\t\t// Remove duplicate values (for attributes longer than 5 chars)\n\t\t\t\t\tconst keys = Object.keys(attributesToInclude)\n\t\t\t\t\tif (keys.length > 1) {\n\t\t\t\t\t\tconst keysToRemove = new Set<string>()\n\t\t\t\t\t\tconst seenValues: Record<string, string> = {}\n\n\t\t\t\t\t\tfor (const key of keys) {\n\t\t\t\t\t\t\tconst value = attributesToInclude[key]\n\t\t\t\t\t\t\tif (value.length > 5) {\n\t\t\t\t\t\t\t\tif (value in seenValues) {\n\t\t\t\t\t\t\t\t\tkeysToRemove.add(key)\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tseenValues[value] = key\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (const key of keysToRemove) {\n\t\t\t\t\t\t\tdelete attributesToInclude[key]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Remove role if it matches tagName\n\t\t\t\t\tif (attributesToInclude.role === node.tagName) {\n\t\t\t\t\t\tdelete attributesToInclude.role\n\t\t\t\t\t}\n\n\t\t\t\t\t// Remove attributes that duplicate text content\n\t\t\t\t\tconst attrsToRemoveIfTextMatches = ['aria-label', 'placeholder', 'title']\n\t\t\t\t\tfor (const attr of attrsToRemoveIfTextMatches) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tattributesToInclude[attr] &&\n\t\t\t\t\t\t\tattributesToInclude[attr].toLowerCase().trim() === text.toLowerCase().trim()\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tdelete attributesToInclude[attr]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (Object.keys(attributesToInclude).length > 0) {\n\t\t\t\t\t\tattributesHtmlStr = Object.entries(attributesToInclude)\n\t\t\t\t\t\t\t.map(([key, value]) => `${key}=${capTextLength(value, 20)}`)\n\t\t\t\t\t\t\t.join(' ')\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Build the line\n\t\t\t\tconst highlightIndicator = node.isNew\n\t\t\t\t\t? `*[${node.highlightIndex}]`\n\t\t\t\t\t: `[${node.highlightIndex}]`\n\t\t\t\tlet line = `${depthStr}${highlightIndicator}<${node.tagName ?? ''}`\n\n\t\t\t\tif (attributesHtmlStr) {\n\t\t\t\t\tline += ` ${attributesHtmlStr}`\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * @edit scrollable 数据\n\t\t\t\t */\n\t\t\t\tif (node.extra) {\n\t\t\t\t\tif (node.extra.scrollable) {\n\t\t\t\t\t\tlet scrollDataText = ''\n\t\t\t\t\t\tif (node.extra.scrollData?.left)\n\t\t\t\t\t\t\tscrollDataText += `left=${node.extra.scrollData.left}, `\n\t\t\t\t\t\tif (node.extra.scrollData?.top) scrollDataText += `top=${node.extra.scrollData.top}, `\n\t\t\t\t\t\tif (node.extra.scrollData?.right)\n\t\t\t\t\t\t\tscrollDataText += `right=${node.extra.scrollData.right}, `\n\t\t\t\t\t\tif (node.extra.scrollData?.bottom)\n\t\t\t\t\t\t\tscrollDataText += `bottom=${node.extra.scrollData.bottom}`\n\n\t\t\t\t\t\tline += ` data-scrollable=\"${scrollDataText}\"`\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (text) {\n\t\t\t\t\tconst trimmedText = text.trim()\n\t\t\t\t\tif (!attributesHtmlStr) {\n\t\t\t\t\t\tline += ' '\n\t\t\t\t\t}\n\t\t\t\t\tline += `>${trimmedText}`\n\t\t\t\t} else if (!attributesHtmlStr) {\n\t\t\t\t\tline += ' '\n\t\t\t\t}\n\n\t\t\t\tline += ' />'\n\t\t\t\tresult.push(line)\n\t\t\t}\n\n\t\t\t// special treatment for semantic tags\n\t\t\t// even if they are not interactive, we can keep them for clear context\n\n\t\t\tconst emitSemantic = isSemantic && node.highlightIndex === undefined\n\t\t\t// to check if this tag is empty\n\t\t\tconst mark = emitSemantic ? result.length : -1\n\n\t\t\tif (emitSemantic) {\n\t\t\t\tresult.push(`${depthStr}<${node.tagName}>`)\n\t\t\t\tnextDepth += 1\n\t\t\t}\n\n\t\t\tfor (const child of node.children) {\n\t\t\t\tprocessNode(child, nextDepth, result)\n\t\t\t}\n\n\t\t\tif (emitSemantic) {\n\t\t\t\t// empty tag should be removed\n\t\t\t\tif (result.length === mark + 1) {\n\t\t\t\t\tresult.pop()\n\t\t\t\t} else {\n\t\t\t\t\tresult.push(`${depthStr}</${node.tagName}>`)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (node.type === 'text') {\n\t\t\t// Add text only if it doesn't have a highlighted parent\n\t\t\tif (hasParentWithHighlightIndex(node)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tnode.parent &&\n\t\t\t\tnode.parent.type === 'element' &&\n\t\t\t\tnode.parent.isVisible &&\n\t\t\t\tnode.parent.isTopElement\n\t\t\t) {\n\t\t\t\tresult.push(`${depthStr}${node.text ?? ''}`)\n\t\t\t}\n\t\t}\n\t}\n\n\tconst result: string[] = []\n\tprocessNode(rootNode, 0, result)\n\treturn result.join('\\n')\n}\n\n// Get all text until next clickable element\nexport const getAllTextTillNextClickableElement = (node: TreeNode, maxDepth = -1): string => {\n\tconst textParts: string[] = []\n\n\tconst collectText = (currentNode: TreeNode, currentDepth: number) => {\n\t\tif (maxDepth !== -1 && currentDepth > maxDepth) {\n\t\t\treturn\n\t\t}\n\n\t\t// Skip this branch if we hit a highlighted element (except for the current node)\n\t\tif (\n\t\t\tcurrentNode.type === 'element' &&\n\t\t\tcurrentNode !== node &&\n\t\t\tcurrentNode.highlightIndex !== undefined\n\t\t) {\n\t\t\treturn\n\t\t}\n\n\t\tif (currentNode.type === 'text' && currentNode.text) {\n\t\t\ttextParts.push(currentNode.text)\n\t\t} else if (currentNode.type === 'element') {\n\t\t\tfor (const child of currentNode.children) {\n\t\t\t\tcollectText(child, currentDepth + 1)\n\t\t\t}\n\t\t}\n\t}\n\n\tcollectText(node, 0)\n\treturn textParts.join('\\n').trim()\n}\n\nexport function getSelectorMap(flatTree: FlatDomTree): Map<number, InteractiveElementDomNode> {\n\tconst selectorMap = new Map<number, InteractiveElementDomNode>()\n\n\tconst keys = Object.keys(flatTree.map)\n\tfor (const key of keys) {\n\t\tconst node = flatTree.map[key]\n\t\tif (node.isInteractive && typeof node.highlightIndex === 'number') {\n\t\t\tselectorMap.set(node.highlightIndex, node as InteractiveElementDomNode)\n\t\t}\n\t}\n\n\treturn selectorMap\n}\n\nexport function getElementTextMap(simplifiedHTML: string) {\n\tconst lines = simplifiedHTML\n\t\t.split('\\n')\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0)\n\tconst elementTextMap = new Map<number, string>()\n\tfor (const line of lines) {\n\t\tconst regex = /^\\[(\\d+)\\]<[^>]+>([^<]*)/\n\t\tconst match = regex.exec(line)\n\t\tif (match) {\n\t\t\tconst index = parseInt(match[1], 10)\n\t\t\telementTextMap.set(index, line)\n\t\t}\n\t}\n\n\treturn elementTextMap\n}\n\nexport function cleanUpHighlights() {\n\tconst cleanupFunctions = (window as any)._highlightCleanupFunctions || []\n\tfor (const cleanup of cleanupFunctions) {\n\t\tif (typeof cleanup === 'function') {\n\t\t\tcleanup()\n\t\t}\n\t}\n\n\t;(window as any)._highlightCleanupFunctions = []\n}\n\n// 监听 URL 的任何变化,立刻清空 highLights\nwindow.addEventListener('popstate', () => {\n\t// console.log('URL changed (popstate), highlights cleaned up.')\n\tcleanUpHighlights()\n})\nwindow.addEventListener('hashchange', () => {\n\t// console.log('URL changed (hashchange), highlights cleaned up.')\n\tcleanUpHighlights()\n})\nwindow.addEventListener('beforeunload', () => {\n\t// console.log('Page is unloading, highlights cleaned up.')\n\tcleanUpHighlights()\n})\n\nconst navigation = (window as any).navigation\nif (navigation && typeof navigation.addEventListener === 'function') {\n\tnavigation.addEventListener('navigate', () => {\n\t\t// console.log('Navigation event detected, highlights cleaned up.')\n\t\tcleanUpHighlights()\n\t})\n} else {\n\t// 定时器\n\tlet currentUrl = window.location.href\n\tsetInterval(() => {\n\t\tif (window.location.href !== currentUrl) {\n\t\t\tcurrentUrl = window.location.href\n\t\t\t// console.log('URL changed (interval), highlights cleaned up.')\n\t\t\tcleanUpHighlights()\n\t\t}\n\t}, 500)\n}\n","export function getPageInfo() {\n\tconst viewport_width = window.innerWidth\n\tconst viewport_height = window.innerHeight\n\n\tconst page_width = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth || 0)\n\tconst page_height = Math.max(\n\t\tdocument.documentElement.scrollHeight,\n\t\tdocument.body.scrollHeight || 0\n\t)\n\n\tconst scroll_x = window.scrollX || window.pageXOffset || document.documentElement.scrollLeft || 0\n\tconst scroll_y = window.scrollY || window.pageYOffset || document.documentElement.scrollTop || 0\n\n\tconst pixels_below = Math.max(0, page_height - (window.innerHeight + scroll_y))\n\tconst pixels_right = Math.max(0, page_width - (window.innerWidth + scroll_x))\n\n\treturn {\n\t\t// Current viewport dimensions\n\t\tviewport_width,\n\t\tviewport_height,\n\n\t\t// Total page dimensions\n\t\tpage_width,\n\t\tpage_height,\n\n\t\t// Current scroll position\n\t\tscroll_x,\n\t\tscroll_y,\n\n\t\tpixels_above: scroll_y,\n\t\tpixels_below,\n\n\t\tpages_above: viewport_height > 0 ? scroll_y / viewport_height : 0,\n\t\tpages_below: viewport_height > 0 ? pixels_below / viewport_height : 0,\n\t\ttotal_pages: viewport_height > 0 ? page_height / viewport_height : 0,\n\n\t\tcurrent_page_position: scroll_y / Math.max(1, page_height - viewport_height),\n\n\t\tpixels_left: scroll_x,\n\t\tpixels_right,\n\t}\n}\n","import type { PageController } from '../PageController'\n\n// Find common React root elements and add data-page-agent-not-interactive attribute\nexport function patchReact(pageController: PageController) {\n\tconst reactRootElements = document.querySelectorAll(\n\t\t'[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^=\"root-\"], [id^=\"app-\"], #adex-wrapper, #adex-root'\n\t)\n\n\tfor (const element of reactRootElements) {\n\t\telement.setAttribute('data-page-agent-not-interactive', 'true')\n\t}\n}\n\n/**\n * @todo (Heavy, might have false negatives) Interaction detection, if element width/height equals body offsetWidth/Height, consider it root element and non-interactive (React often attaches many events to root elements, causing false positives)\n */\n","/**\n * Whether generated JavaScript can run in this page.\n *\n * A site Content Security Policy that omits `unsafe-eval` rejects `eval` and `new Function`.\n * No browser permission dialog adds `unsafe-eval` to that policy. The probe runs once per origin.\n */\n\nexport type ScriptAccess = 'allowed' | 'blocked_by_csp'\n\nconst accessByOrigin = new Map<string, ScriptAccess>()\n\nexport const SCRIPT_BLOCKED_BY_CSP =\n\t\"blocked_by_csp: This site's Content Security Policy disallows generated JavaScript (unsafe-eval). The user cannot grant this on the page. Do not call execute_javascript again here. Use the indexed tools, including drag_element to move one index onto another.\"\n\nexport const SCRIPT_USER_DENIED =\n\t'user_denied: The user did not allow generated JavaScript in this browser. Do not call execute_javascript again here. Use the indexed tools.'\n\nexport const SCRIPT_UNAVAILABLE =\n\t'unavailable: Generated JavaScript cannot run in this browser. Do not call execute_javascript again here. Use the indexed tools.'\n\n/** True when the tool result closes generated scripts for the rest of the task. */\nexport function scriptAccessClosed(message: string): boolean {\n\treturn /^(blocked_by_csp|user_denied|unavailable):/.test(message)\n}\n\nexport function scriptOrigin(): string {\n\ttry {\n\t\treturn globalThis.location?.origin || 'unknown'\n\t} catch {\n\t\treturn 'unknown'\n\t}\n}\n\n/** A CSP refusal is an EvalError, sometimes wrapped as a plain Error with the policy text. */\nexport function isEvalBlocked(error: unknown): boolean {\n\tif (typeof EvalError !== 'undefined' && error instanceof EvalError) return true\n\tconst message = error instanceof Error ? error.message : String(error)\n\treturn /unsafe-eval|Content Security Policy|Refused to evaluate a string as JavaScript/i.test(\n\t\tmessage\n\t)\n}\n\n/**\n * Probe `new Function` once per origin and remember the answer.\n * Pass an origin in tests. The page path uses `scriptOrigin()`.\n */\nexport function generatedScriptAccess(origin = scriptOrigin()): ScriptAccess {\n\tconst cached = accessByOrigin.get(origin)\n\tif (cached) return cached\n\tlet access: ScriptAccess = 'allowed'\n\ttry {\n\t\t// The empty function is never called. Compiling it is the only way to ask\n\t\t// whether this page's Content Security Policy allows generated scripts.\n\t\t// eslint-disable-next-line @typescript-eslint/no-implied-eval\n\t\tnew Function('')\n\t} catch (error) {\n\t\tif (!isEvalBlocked(error)) throw error\n\t\taccess = 'blocked_by_csp'\n\t}\n\taccessByOrigin.set(origin, access)\n\treturn access\n}\n\nexport function rememberScriptAccess(origin: string, access: ScriptAccess): void {\n\taccessByOrigin.set(origin, access)\n}\n\n/** Test-only. Production never forgets a probe during the page session. */\nexport function clearScriptAccessForTests(): void {\n\taccessByOrigin.clear()\n}\n","/** Longest script result sent back to the model. Longer results are cut and say so. */\nexport const SCRIPT_RESULT_MAX_CHARS = 4000\n\n/**\n * Turns the value returned by a page script into text the model can read.\n * Objects and arrays become JSON (a template literal would print \"[object Object]\").\n * Functions show their source; values JSON cannot represent (cycles) are named as such.\n */\nexport function formatScriptResult(result: unknown): string {\n\tif (typeof result === 'string') return truncate(result)\n\tif (result === undefined) return 'undefined'\n\tif (typeof result === 'function') return truncate(result.toString())\n\tlet text: string\n\ttry {\n\t\ttext = JSON.stringify(result) ?? '[unserializable value]'\n\t} catch {\n\t\ttext = '[unserializable value]'\n\t}\n\treturn truncate(text)\n}\n\nfunction truncate(text: string): string {\n\tif (text.length <= SCRIPT_RESULT_MAX_CHARS) return text\n\treturn `${text.slice(0, SCRIPT_RESULT_MAX_CHARS)}... [truncated, ${text.length - SCRIPT_RESULT_MAX_CHARS} more characters]`\n}\n","/** How old, in seconds, a read of the element list may be and still confirm a fact about the page. */\nexport const STATE_FRESH_SECONDS = 10\n\n/** Seconds since the element list was read. Never negative. */\nexport function stateAgeSeconds(lastUpdate: number, now: number): number {\n\treturn Math.max(0, (now - lastUpdate) / 1000)\n}\n\n/** Whether a read of the given age may still be used to confirm a fact. */\nexport function isStateFresh(ageSeconds: number): boolean {\n\treturn ageSeconds <= STATE_FRESH_SECONDS\n}\n\n/**\n * Whether a script should read the page before answering. It reads when the page was never read, or the last read\n * is older than the limit. It never reads while the agent is busy: the agent owns the element list then.\n */\nexport function shouldRefresh(input: {\n\tneverRead: boolean\n\tageSeconds: number\n\tmaxAgeSeconds: number\n\tbusy: boolean\n}): boolean {\n\tif (input.busy) return false\n\treturn input.neverRead || input.ageSeconds > input.maxAgeSeconds\n}\n","/**\n * Indexes for canvas, svg and role=application surfaces that are not nodes of the accessibility\n * tree. The index is a public id from `targetAt`, so the existing drag tool can aim at it.\n * A surface that already has an id is a tree node and is left as it is. No role is invented.\n *\n * Called from PageController.updateAccessibilityTree after observeIndexed.\n */\nimport type { AxBounds, AxIndexedObservation, AxSurface } from './ax'\n\nexport interface ViewportSize {\n\twidth: number\n\theight: number\n}\n\nexport interface SurfaceHit {\n\tid: string\n\ttag: string\n}\n\n/**\n * A point inside both the surface rectangle and the viewport.\n * `targetAt` rejects coordinates outside the viewport, so a center that falls outside is moved\n * into the visible overlap. Returns null when that overlap is empty or thinner than one pixel.\n */\nexport function visibleSurfacePoint(\n\tbounds: AxBounds,\n\tviewport: ViewportSize\n): { x: number; y: number } | null {\n\tif (!(viewport.width >= 1) || !(viewport.height >= 1)) return null\n\tif (![bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isFinite)) return null\n\tif (!(bounds.width > 0) || !(bounds.height > 0)) return null\n\n\tconst left = Math.max(bounds.x, 0)\n\tconst top = Math.max(bounds.y, 0)\n\tconst right = Math.min(bounds.x + bounds.width, viewport.width)\n\tconst bottom = Math.min(bounds.y + bounds.height, viewport.height)\n\tif (right - left < 1 || bottom - top < 1) return null\n\n\tconst x = clamp(Math.round((left + right) / 2), 0, viewport.width - 1)\n\tconst y = clamp(Math.round((top + bottom) / 2), 0, viewport.height - 1)\n\tif (x >= left && x < right && y >= top && y < bottom) return { x, y }\n\n\tconst fallbackX = clamp(Math.floor(left), 0, viewport.width - 1)\n\tconst fallbackY = clamp(Math.floor(top), 0, viewport.height - 1)\n\tif (fallbackX >= left && fallbackX < right && fallbackY >= top && fallbackY < bottom)\n\t\treturn { x: fallbackX, y: fallbackY }\n\treturn null\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n\treturn Math.min(max, Math.max(min, value))\n}\n\nexport interface IndexedSurfaces {\n\tobservation: AxIndexedObservation\n\t/** Viewport point passed to `targetAt` for each new index. */\n\tpoints: Map<number, { x: number; y: number }>\n}\n\n/**\n * Appends one numbered line per surface that has bounds and no tree id.\n * A failed hit-test is skipped. The original observation is not mutated.\n */\nexport async function appendSurfaceIndexes(\n\tobservation: AxIndexedObservation,\n\tsurfaces: readonly AxSurface[],\n\ttargetAt: (x: number, y: number) => Promise<SurfaceHit>,\n\tviewport: ViewportSize\n): Promise<IndexedSurfaces> {\n\tconst ids = observation.ids.slice()\n\tconst labels = observation.labels.slice()\n\tconst lines: string[] = []\n\tconst points = new Map<number, { x: number; y: number }>()\n\n\tfor (const surface of surfaces) {\n\t\tif (surface.id !== null) continue\n\t\tconst point = visibleSurfacePoint(surface.bounds, viewport)\n\t\tif (!point) continue\n\t\ttry {\n\t\t\tconst hit = await targetAt(point.x, point.y)\n\t\t\tif (hit.tag.toLowerCase() !== surface.tag.toLowerCase()) continue\n\t\t\tif (ids.includes(hit.id)) continue\n\t\t\tconst index = ids.length\n\t\t\tconst quoted = JSON.stringify(surface.label ?? '')\n\t\t\tids.push(hit.id)\n\t\t\tlabels.push(`${surface.tag} ${quoted}`)\n\t\t\tpoints.set(index, point)\n\t\t\tlines.push(`[${index}] ${surface.tag} ${quoted} (not in the tree; drag target for this read)`)\n\t\t} catch {\n\t\t\t// One surface that cannot be addressed must not drop the rest of the read.\n\t\t}\n\t}\n\n\tif (lines.length === 0) return { observation, points }\n\treturn {\n\t\tobservation: {\n\t\t\t...observation,\n\t\t\ttext: `${observation.text.replace(/\\s*$/, '')}\\n${lines.join('\\n')}`,\n\t\t\tids,\n\t\t\tlabels,\n\t\t},\n\t\tpoints,\n\t}\n}\n","/**\n * Copyright (C) 2025 Alibaba Group Holding Limited\n * All rights reserved.\n *\n * PageController - Manages DOM operations and element interactions.\n * Designed to be independent of LLM and can be tested in unit tests.\n * All public methods are async for potential remote calling support.\n */\nimport {\n\tclickElement,\n\tgetElementByIndex,\n\tinputTextElement,\n\tscrollHorizontally,\n\tscrollIntoViewIfNeeded,\n\tscrollVertically,\n\tselectOptionElement,\n} from './actions'\nimport {\n\ttype AccessibilityConfig,\n\tAccessibilityController,\n\ttype AxActionOutcome,\n\ttype AxDragMode,\n\tAxError,\n\ttype AxIndexedObservation,\n\ttype AxKeyOptions,\n} from './ax'\nimport * as dom from './dom'\nimport type { FlatDomTree, InteractiveElementDomNode } from './dom/dom_tree/type'\nimport { getPageInfo } from './dom/getPageInfo'\nimport { patchReact } from './patches/react'\nimport {\n\tSCRIPT_BLOCKED_BY_CSP,\n\tgeneratedScriptAccess,\n\tisEvalBlocked,\n\trememberScriptAccess,\n\tscriptOrigin,\n} from './scriptAccess'\nimport { formatScriptResult } from './scriptResult'\nimport { STATE_FRESH_SECONDS, isStateFresh, shouldRefresh, stateAgeSeconds } from './stateFreshness'\nimport { appendSurfaceIndexes } from './surfaceIndexes'\nimport {\n\tclickPointer,\n\tdisablePassThrough,\n\tenablePassThrough,\n\tisAnchorElement,\n\tisHTMLElement,\n\tisSelectElement,\n\tmovePointerToElement,\n} from './utils'\n\n/**\n * Configuration for PageController\n */\nexport interface PageControllerConfig extends dom.DomConfig {\n\t/** Enable visual mask overlay during operations (default: false) */\n\tenableMask?: boolean\n\n\t/**\n\t * How the page is read for the agent, and therefore what the element indexes point at.\n\t *\n\t * - `'accessibility'` (default): a reconstructed accessibility tree. Each index is a node of the\n\t * tree, and the index-based actions (click, input, select, scroll) go through the tree's\n\t * identity checks: a target that changed since it was read is refused instead of guessed.\n\t * - `'dom'`: the list of interactive elements with numbered highlights on the page.\n\t *\n\t * The methods, the tools and the indexes are the same in both. If the tree cannot be built for a\n\t * step, that step falls back to `'dom'` and says so in the state.\n\t * @note The tree is an approximation of the browser's accessibility tree, and its actions are\n\t * synthetic events that a page may ignore.\n\t */\n\tobservation?: 'accessibility' | 'dom'\n\n\t/** Budgets and limits of the accessibility tree. */\n\taccessibility?: AccessibilityConfig\n\n\t/**\n\t * Print to the console what the agent reads at every step, exactly as it receives it, and what\n\t * each action targeted. The text is the page's own content, before `transformPageContent`.\n\t * @default true\n\t */\n\tlogObservations?: boolean\n}\n\n/**\n * Structured browser state for LLM consumption\n */\nexport interface BrowserState {\n\turl: string\n\ttitle: string\n\t/** Page info + scroll position hint (e.g. \"Page info: 1920x1080px...\\n[Start of page]\") */\n\theader: string\n\t/** Simplified HTML of interactive elements */\n\tcontent: string\n\t/** Page footer hint (e.g. \"... 300 pixels below ...\" or \"[End of page]\") */\n\tfooter: string\n}\n\ninterface ActionResult {\n\tsuccess: boolean\n\tmessage: string\n}\n\nconst LOG_STYLE = 'color:#7c5cff;font-weight:600'\n\n/** What a failed accessibility action tells the agent: the reason, and what had already happened. */\nfunction describeFailure(error: unknown): string {\n\tconst message = error instanceof Error ? error.message : String(error)\n\tif (!(error instanceof AxError)) return `${message}.`\n\tlet text = `${message}.`\n\tif (error.effects)\n\t\ttext += ` ⚠️ Partially executed (${error.effects}); this was not undone and may have changed the page.`\n\tif (error.code === 'stale_id' || error.code === 'stale_snapshot' || error.code === 'stale_node')\n\t\ttext +=\n\t\t\t' The page changed since it was read: use the indexes of the next page state, and do not assume the same element is behind this index.'\n\treturn text\n}\n\n/** Window scroll position. A missing or non-finite value is reported as zero. */\nfunction readWindowScroll(): { x: number; y: number } {\n\tconst x = window.scrollX\n\tconst y = window.scrollY\n\treturn {\n\t\tx: Number.isFinite(x) ? Math.round(x) : 0,\n\t\ty: Number.isFinite(y) ? Math.round(y) : 0,\n\t}\n}\n\n/** Index actions that exist only on the accessibility tree. */\nfunction treeRequired(action: string): ActionResult {\n\treturn {\n\t\tsuccess: false,\n\t\tmessage: `❌ ${action} needs the accessibility tree. This step is the element list, so these indexes cannot be used.`,\n\t}\n}\n\n/**\n * PageController manages DOM state and element interactions.\n * It provides async methods for all DOM operations, keeping state isolated.\n *\n * @lifecycle\n * - beforeUpdate: Emitted before the DOM tree is updated.\n * - afterUpdate: Emitted after the DOM tree is updated.\n */\nexport class PageController extends EventTarget {\n\tprivate config: PageControllerConfig\n\n\t/** Corresponds to eval_page in browser-use */\n\tprivate flatTree: FlatDomTree | null = null\n\n\t/**\n\t * All highlighted index-mapped interactive elements\n\t * Corresponds to DOMState.selector_map in browser-use\n\t */\n\tprivate selectorMap = new Map<number, InteractiveElementDomNode>()\n\n\t/** Index -> element text description mapping */\n\tprivate elementTextMap = new Map<number, string>()\n\n\t/**\n\t * Simplified HTML for LLM consumption.\n\t * Corresponds to clickable_elements_to_string in browser-use\n\t */\n\tprivate simplifiedHTML = '<EMPTY>'\n\n\t/** last time the tree was updated */\n\tprivate lastTimeUpdate = 0\n\n\t/** Whether the tree has been indexed at least once */\n\tprivate isIndexed = false\n\n\t/** Visual mask overlay for blocking user interaction during automation */\n\tprivate mask: InstanceType<typeof import('./mask/SimulatorMask').SimulatorMask> | null = null\n\tprivate maskReady: Promise<void> | null = null\n\n\t/** What the indexes of the last read point at. A failed tree read makes a step `'dom'`. */\n\tprivate indexSource: 'accessibility' | 'dom' = 'dom'\n\n\t/** The last accessibility read: index -> node ID and label. */\n\tprivate axObservation: AxIndexedObservation | null = null\n\n\t/**\n\t * Viewport point of a surface index added after the tree. The id behind that index is a visual\n\t * target, so later gestures use this point instead of looking the element up again.\n\t */\n\tprivate surfacePoints = new Map<number, { x: number; y: number }>()\n\n\t/** Why the last read fell back from the accessibility tree to the element list, if it did. */\n\tprivate fallbackNote = ''\n\n\t/**\n\t * Milliseconds of the last successful accessibility read, including surface indexes.\n\t * Null until that read succeeds. A fallback to the element list does not invent a duration.\n\t * This is not a precision score and it is not a speed budget.\n\t */\n\tprivate lastTreeReadMs: number | null = null\n\n\t/** Created on first use; the core behind it is loaded on the first capture. */\n\tprivate accessibilityController: AccessibilityController | null = null\n\t/** Accessibility interactions in progress that need the mask out of the way. */\n\tprivate accessibilityInteractions = 0\n\n\tconstructor(config: PageControllerConfig = {}) {\n\t\tsuper()\n\n\t\tthis.config = config\n\n\t\tpatchReact(this)\n\n\t\tif (config.enableMask) this.initMask()\n\t}\n\n\t/**\n\t * Initialize mask asynchronously (dynamic import to avoid CSS loading in Node)\n\t */\n\tinitMask() {\n\t\tif (this.maskReady !== null) return\n\t\tthis.maskReady = (async () => {\n\t\t\tconst { SimulatorMask } = await import('./mask/SimulatorMask')\n\t\t\tthis.mask = new SimulatorMask()\n\t\t})()\n\t}\n\t// ======= State Queries =======\n\n\t/**\n\t * Get current page URL\n\t */\n\tasync getCurrentUrl(): Promise<string> {\n\t\treturn window.location.href\n\t}\n\n\t/**\n\t * Get last tree update timestamp\n\t */\n\tasync getLastUpdateTime(): Promise<number> {\n\t\treturn this.lastTimeUpdate\n\t}\n\n\t/**\n\t * Duration of the last successful accessibility read, in milliseconds.\n\t * Null when that read has not succeeded. The number is not a precision score.\n\t */\n\tasync getLastTreeReadMs(): Promise<number | null> {\n\t\treturn this.lastTreeReadMs\n\t}\n\n\t/** Set by the agent: true while a task runs. Scripts never refresh the element list then. */\n\tisBusy: () => boolean = () => false\n\n\t/**\n\t * The page state a script should use. Reads the page only when it was never read or the last read is older than\n\t * `maxAgeSeconds`, and only while the agent is idle. Otherwise it returns the last read as it is.\n\t */\n\tasync getState(options: { maxAgeSeconds?: number } = {}): Promise<{\n\t\tpageInfo: ReturnType<typeof getPageInfo>\n\t\tsimplifiedHTML: string\n\t\tageSeconds: number\n\t\tfresh: boolean\n\t\trefreshed: boolean\n\t}> {\n\t\tconst maxAgeSeconds = options.maxAgeSeconds ?? STATE_FRESH_SECONDS\n\t\tconst refreshed = shouldRefresh({\n\t\t\tneverRead: this.lastTimeUpdate === 0,\n\t\t\tageSeconds: stateAgeSeconds(this.lastTimeUpdate, Date.now()),\n\t\t\tmaxAgeSeconds,\n\t\t\tbusy: this.isBusy(),\n\t\t})\n\t\tif (refreshed) await this.updateTree()\n\t\tconst ageSeconds = stateAgeSeconds(this.lastTimeUpdate, Date.now())\n\t\treturn {\n\t\t\tpageInfo: getPageInfo(),\n\t\t\tsimplifiedHTML: this.simplifiedHTML,\n\t\t\tageSeconds,\n\t\t\tfresh: ageSeconds <= maxAgeSeconds,\n\t\t\trefreshed,\n\t\t}\n\t}\n\n\t/**\n\t * The element list from the agent's last read, with its age, and the page position measured now.\n\t * Read-only: it does not refresh the tree, move the highlights or change any element index.\n\t */\n\tasync getLastState(): Promise<{\n\t\tpageInfo: ReturnType<typeof getPageInfo>\n\t\tsimplifiedHTML: string\n\t\tageSeconds: number\n\t\tfresh: boolean\n\t}> {\n\t\tconst ageSeconds = stateAgeSeconds(this.lastTimeUpdate, Date.now())\n\t\treturn {\n\t\t\tpageInfo: getPageInfo(),\n\t\t\tsimplifiedHTML: this.simplifiedHTML,\n\t\t\tageSeconds,\n\t\t\tfresh: isStateFresh(ageSeconds),\n\t\t}\n\t}\n\n\t/**\n\t * Read a vertical slice of the accessibility tree by document Y (page coordinates).\n\t * Use it to skim large pages in pieces. When `bindIndexes` is true, the returned `[index]`\n\t * handles replace the current action indexes for this step. When false, the text is read-only\n\t * (no indexes) and the agent's current indexes stay as they are.\n\t */\n\tasync getContext(\n\t\toptions: {\n\t\t\tyMin?: number\n\t\t\tyMax?: number\n\t\t\tmaxLines?: number\n\t\t\tquery?: string\n\t\t\tbindIndexes?: boolean\n\t\t} = {}\n\t): Promise<{\n\t\ttext: string\n\t\tyMin: number\n\t\tyMax: number\n\t\tpageHeight: number\n\t\tscrollY: number\n\t\tviewportHeight: number\n\t\tshownNodes: number\n\t\ttotalNodes: number\n\t\thiddenNodes: number\n\t\tfilteredNodes: number\n\t\tboundIndexes: boolean\n\t\tmessage: string\n\t}> {\n\t\tconst page = getPageInfo()\n\t\tconst bindIndexes = options.bindIndexes === true\n\t\tconst maxLines = Math.max(10, Math.min(options.maxLines ?? 80, 200))\n\t\tconst hasY = options.yMin !== undefined || options.yMax !== undefined\n\t\tconst yMin = hasY ? Math.max(0, options.yMin ?? 0) : Math.max(0, Math.floor(page.scroll_y))\n\t\tconst yMax = hasY\n\t\t\t? Math.max(yMin, options.yMax ?? page.page_height)\n\t\t\t: Math.max(yMin + 1, Math.floor(page.scroll_y + page.viewport_height))\n\n\t\tif (!this.usesAccessibility()) {\n\t\t\tconst message =\n\t\t\t\t'get_context needs observation: accessibility. The current mode is the element list; scroll and read browser_state instead.'\n\t\t\treturn {\n\t\t\t\ttext: '',\n\t\t\t\tyMin,\n\t\t\t\tyMax,\n\t\t\t\tpageHeight: page.page_height,\n\t\t\t\tscrollY: page.scroll_y,\n\t\t\t\tviewportHeight: page.viewport_height,\n\t\t\t\tshownNodes: 0,\n\t\t\t\ttotalNodes: 0,\n\t\t\t\thiddenNodes: 0,\n\t\t\t\tfilteredNodes: 0,\n\t\t\t\tboundIndexes: false,\n\t\t\t\tmessage,\n\t\t\t}\n\t\t}\n\n\t\tawait this.mask?.startProgress()\n\t\tconst started = performance.now()\n\t\ttry {\n\t\t\tconst observation = await this.accessibility.observeIndexed({\n\t\t\t\tmaxLines,\n\t\t\t\tviewportExpansion: -1,\n\t\t\t\tyMin,\n\t\t\t\tyMax,\n\t\t\t\tquery: options.query,\n\t\t\t\tindexLabels: bindIndexes,\n\t\t\t})\n\t\t\tif (bindIndexes) {\n\t\t\t\tconst indexed = await this.withSurfaceIndexes(observation)\n\t\t\t\tthis.axObservation = indexed\n\t\t\t\tthis.simplifiedHTML = indexed.text\n\t\t\t\tthis.indexSource = 'accessibility'\n\t\t\t\tthis.selectorMap.clear()\n\t\t\t\tthis.elementTextMap = new Map(indexed.labels.map((label, index) => [index, label]))\n\t\t\t\tthis.lastTimeUpdate = Date.now()\n\t\t\t\tthis.lastTreeReadMs = Math.round(performance.now() - started)\n\t\t\t\tthis.isIndexed = true\n\t\t\t}\n\n\t\t\tconst header = [\n\t\t\t\t`Context slice y=${Math.round(yMin)}..${Math.round(yMax)} of page_height=${Math.round(page.page_height)} (scrollY=${Math.round(page.scroll_y)}, viewport=${Math.round(page.viewport_height)}).`,\n\t\t\t\toptions.query ? `Query: ${JSON.stringify(options.query)}.` : null,\n\t\t\t\tbindIndexes\n\t\t\t\t\t? 'Indexes in this slice replace the previous action indexes for this step.'\n\t\t\t\t\t: 'Read-only: no action indexes. Current agent indexes are unchanged.',\n\t\t\t\t`Nodes shown ${observation.shownNodes}/${observation.totalNodes}; hidden ${observation.hiddenNodes}; filtered ${observation.filteredNodes}.`,\n\t\t\t]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(' ')\n\n\t\t\tconst text = observation.text.trim() ? `${header}\\n\\n${observation.text}` : header\n\t\t\treturn {\n\t\t\t\ttext,\n\t\t\t\tyMin,\n\t\t\t\tyMax,\n\t\t\t\tpageHeight: page.page_height,\n\t\t\t\tscrollY: page.scroll_y,\n\t\t\t\tviewportHeight: page.viewport_height,\n\t\t\t\tshownNodes: observation.shownNodes,\n\t\t\t\ttotalNodes: observation.totalNodes,\n\t\t\t\thiddenNodes: observation.hiddenNodes,\n\t\t\t\tfilteredNodes: observation.filteredNodes,\n\t\t\t\tboundIndexes: bindIndexes,\n\t\t\t\tmessage: text,\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.mask?.stopProgress()\n\t\t}\n\t}\n\n\t/**\n\t * Get structured browser state for LLM consumption.\n\t * Automatically calls updateTree() to refresh the DOM state.\n\t */\n\tasync getBrowserState(): Promise<BrowserState> {\n\t\tconst url = window.location.href\n\t\tconst title = document.title\n\t\tconst pi = getPageInfo()\n\t\tconst viewportExpansion = dom.resolveViewportExpansion(this.config.viewportExpansion)\n\n\t\tawait this.updateTree()\n\n\t\tconst content = this.fallbackNote\n\t\t\t? `${this.fallbackNote}\\n\\n${this.simplifiedHTML}`\n\t\t\t: this.simplifiedHTML\n\t\tconst tree = this.indexSource === 'accessibility' ? this.axObservation : null\n\t\t// The tree is narrowed to the viewport when it is asked to be, or when the whole page is too long.\n\t\tconst fullPage = tree ? !tree.viewportOnly : viewportExpansion === -1\n\n\t\t// Build header: page info + scroll position hint\n\t\tconst titleLine = `Current Page: [${title}](${url})`\n\n\t\tconst pageInfoLine = `Page info: ${pi.viewport_width}x${pi.viewport_height}px viewport, ${pi.page_width}x${pi.page_height}px total page size, ${pi.pages_above.toFixed(1)} pages above, ${pi.pages_below.toFixed(1)} pages below, ${pi.total_pages.toFixed(1)} total pages, at ${(pi.current_page_position * 100).toFixed(0)}% of page`\n\n\t\tlet elementsLabel = fullPage\n\t\t\t? 'Interactive elements from top layer of the current page (full page):'\n\t\t\t: 'Interactive elements from top layer of the current page inside the viewport:'\n\t\tif (tree) {\n\t\t\tconst notes = [\n\t\t\t\t`Accessibility tree of the current page ${fullPage ? '(full page)' : 'inside the viewport'}, reconstructed from what the page exposes. It is not the browser's native accessibility tree and can differ from it.`,\n\t\t\t\t'Each line is [index] role \"name\", then value, description and states; indentation is nesting. Only lines with a numeric [index] can be acted on, and an index is valid for this step only.',\n\t\t\t\t'Viewport annotations describe element geometry at capture time. An intersection does not prove the element is visible or unobscured. Unannotated elements remain in the tree; their viewport position is not stated.',\n\t\t\t]\n\t\t\tif (tree.filteredNodes > 0)\n\t\t\t\tnotes.push(\n\t\t\t\t\t`${tree.filteredNodes} nodes outside the viewport are not listed: scroll to list them.`\n\t\t\t\t)\n\t\t\tif (tree.hiddenNodes > 0)\n\t\t\t\tnotes.push(\n\t\t\t\t\t`\"… +N hidden\" marks ${tree.hiddenNodes} nodes that did not fit: scroll so that fewer are in view.`\n\t\t\t\t)\n\t\t\tif (this.surfacePoints.size > 0)\n\t\t\t\tnotes.push(\n\t\t\t\t\t`${this.surfacePoints.size} surface${this.surfacePoints.size === 1 ? '' : 's'} with no tree node (canvas, svg or role=application) are listed after the tree. The line gives the tag and label, not a role. The index is a drag target for this step only.`\n\t\t\t\t)\n\t\t\telementsLabel = notes.join('\\n')\n\t\t}\n\n\t\tconst hasContentAbove = pi.pixels_above > 4\n\t\tconst scrollHintAbove =\n\t\t\thasContentAbove && !fullPage\n\t\t\t\t? `... ${pi.pixels_above} pixels above (${pi.pages_above.toFixed(1)} pages) - scroll to see more ...`\n\t\t\t\t: fullPage\n\t\t\t\t\t? '[Start of full-page tree]'\n\t\t\t\t\t: '[Start of page]'\n\n\t\tconst header = `${titleLine}\\n${pageInfoLine}\\n\\n${elementsLabel}\\n\\n${scrollHintAbove}`\n\n\t\t// Build footer: scroll position hint\n\t\tconst hasContentBelow = pi.pixels_below > 4\n\t\tconst footer =\n\t\t\thasContentBelow && !fullPage\n\t\t\t\t? `... ${pi.pixels_below} pixels below (${pi.pages_below.toFixed(1)} pages) - scroll to see more ...`\n\t\t\t\t: fullPage\n\t\t\t\t\t? `[End of full-page tree; ${pi.pixels_below} pixels below the viewport]`\n\t\t\t\t\t: '[End of page]'\n\n\t\tif (this.config.logObservations !== false) {\n\t\t\tconst summary = tree\n\t\t\t\t? `accessibility tree · ${tree.ids.length} indexed · ${tree.shownNodes}/${tree.totalNodes} nodes · ${tree.durationMs} ms`\n\t\t\t\t: 'element list'\n\t\t\t// An open group: what the agent received is on screen without a click, and can still be folded.\n\t\t\tconsole.group(`%c[page-agent] observed · ${summary}`, LOG_STYLE)\n\t\t\tconsole.log(`${header}\\n${content}\\n${footer}`)\n\t\t\tconsole.groupEnd()\n\t\t}\n\n\t\treturn { url, title, header, content, footer }\n\t}\n\n\t// ======= Accessibility Tree =======\n\n\t/**\n\t * The page as a reconstructed accessibility tree, with interactions addressed by node ID: capture,\n\t * click, fill, select, keyboard, hover, drag, scroll, frames. Every method is async.\n\t *\n\t * The tree approximates the browser's accessibility tree from what page JavaScript can observe, and\n\t * the interactions are synthetic events, not physical input. See `AccessibilityController`.\n\t */\n\tget accessibility(): AccessibilityController {\n\t\tthis.accessibilityController ??= new AccessibilityController({\n\t\t\t...this.config.accessibility,\n\t\t\t// The core hit-tests its targets, so the mask must not be on top while it acts. Interactions\n\t\t\t// can overlap (a paced drag takes time), so the mask returns only when the last one ends.\n\t\t\trunInteraction: async (interaction) => {\n\t\t\t\tif (this.accessibilityInteractions++ === 0) await enablePassThrough()\n\t\t\t\ttry {\n\t\t\t\t\treturn await interaction()\n\t\t\t\t} finally {\n\t\t\t\t\tif (--this.accessibilityInteractions === 0) await disablePassThrough()\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t\treturn this.accessibilityController\n\t}\n\n\t/** Whether the page is read as the accessibility tree. The default. */\n\tprivate usesAccessibility(): boolean {\n\t\treturn (this.config.observation ?? 'accessibility') === 'accessibility'\n\t}\n\n\t/**\n\t * The ID of the accessibility node behind an index of the last read, for use with\n\t * `accessibility` (the same node the index tools act on).\n\t */\n\tasync accessibilityId(index: number): Promise<string> {\n\t\treturn this.axTarget(index).id\n\t}\n\n\tprivate axTarget(index: number): { id: string; label: string } {\n\t\tconst id = this.axObservation?.ids[index]\n\t\tif (this.indexSource !== 'accessibility' || id === undefined)\n\t\t\tthrow new Error(`No element with index ${index} in the current page state`)\n\t\treturn { id, label: `[${index}] ${this.axObservation!.labels[index]}` }\n\t}\n\n\t/**\n\t * Scrolls the target into view and moves the visual pointer to it, so a person watching sees where\n\t * the agent is about to act. Feedback only: the action that follows checks the target itself.\n\t */\n\tprivate async pointAt(id: string): Promise<{ x: number; y: number } | null> {\n\t\tconst element = await this.accessibility.elementAt(id)\n\t\tif (!element || !isHTMLElement(element)) return null\n\t\tawait scrollIntoViewIfNeeded(element)\n\t\tconst rect = element.getBoundingClientRect()\n\t\tconst point = {\n\t\t\tx: Math.round(rect.left + rect.width / 2),\n\t\t\ty: Math.round(rect.top + rect.height / 2),\n\t\t}\n\t\tif (this.mask) {\n\t\t\tawait movePointerToElement(element, point.x, point.y)\n\t\t\tawait clickPointer()\n\t\t}\n\t\treturn point\n\t}\n\n\t/** Runs one index-based action on the accessibility tree and words its result for the agent. */\n\tprivate async axAction(\n\t\tverb: string,\n\t\tindex: number,\n\t\tact: (id: string) => Promise<AxActionOutcome>,\n\t\tdescribe: (outcome: AxActionOutcome, label: string) => string\n\t): Promise<ActionResult> {\n\t\tlet label = `[${index}]`\n\t\tlet point: { x: number; y: number } | null = null\n\t\tlet result: ActionResult\n\t\ttry {\n\t\t\tconst target = this.axTarget(index)\n\t\t\tlabel = target.label\n\t\t\tpoint = await this.pointAt(target.id)\n\t\t\tconst outcome = await act(target.id)\n\t\t\tresult = { success: outcome.status !== 'not_applied', message: describe(outcome, label) }\n\t\t} catch (error) {\n\t\t\tresult = { success: false, message: `❌ Failed to ${verb}: ${describeFailure(error)}` }\n\t\t}\n\t\tif (this.config.logObservations !== false)\n\t\t\tconsole.log(\n\t\t\t\t`%c[page-agent] ${verb}`,\n\t\t\t\tLOG_STYLE,\n\t\t\t\tlabel,\n\t\t\t\tpoint ? `at (${point.x}, ${point.y})` : '',\n\t\t\t\t'→',\n\t\t\t\tresult.message\n\t\t\t)\n\t\treturn result\n\t}\n\n\t// ======= DOM Tree Operations =======\n\n\t/**\n\t * Update DOM tree, returns simplified HTML for LLM.\n\t * This is the main method to refresh the page state.\n\t * Automatically bypasses mask during DOM extraction if enabled.\n\t */\n\tasync updateTree(): Promise<string> {\n\t\tthis.dispatchEvent(new Event('beforeUpdate'))\n\n\t\tthis.lastTimeUpdate = Date.now()\n\t\tthis.fallbackNote = ''\n\n\t\tif (this.usesAccessibility()) {\n\t\t\ttry {\n\t\t\t\tawait this.updateAccessibilityTree()\n\t\t\t\tthis.isIndexed = true\n\t\t\t\tthis.dispatchEvent(new Event('afterUpdate'))\n\t\t\t\treturn this.simplifiedHTML\n\t\t\t} catch (error) {\n\t\t\t\t// The step still gets a readable page: the element list, with the reason stated.\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'[PageController] accessibility tree unavailable, using the element list',\n\t\t\t\t\terror\n\t\t\t\t)\n\t\t\t\tthis.fallbackNote = `Accessibility tree unavailable for this step (${error instanceof Error ? error.message : String(error)}). Showing the list of interactive elements instead; its indexes work the same way.`\n\t\t\t}\n\t\t}\n\t\tthis.indexSource = 'dom'\n\t\tthis.axObservation = null\n\t\tthis.surfacePoints.clear()\n\n\t\t// Temporarily bypass mask to allow DOM extraction\n\t\tif (this.mask) {\n\t\t\tthis.mask.wrapper.style.pointerEvents = 'none'\n\t\t}\n\n\t\tdom.cleanUpHighlights()\n\n\t\tconst blacklist = [\n\t\t\t...(this.config.interactiveBlacklist || []),\n\t\t\t...Array.from(document.querySelectorAll('[data-page-agent-not-interactive]')),\n\t\t]\n\n\t\tthis.flatTree = dom.getFlatTree({\n\t\t\t...this.config,\n\t\t\tinteractiveBlacklist: blacklist,\n\t\t})\n\n\t\tthis.simplifiedHTML = dom.flatTreeToString(\n\t\t\tthis.flatTree,\n\t\t\tthis.config.includeAttributes,\n\t\t\tthis.config.keepSemanticTags\n\t\t)\n\n\t\tthis.selectorMap.clear()\n\t\tthis.selectorMap = dom.getSelectorMap(this.flatTree)\n\n\t\tthis.elementTextMap.clear()\n\t\tthis.elementTextMap = dom.getElementTextMap(this.simplifiedHTML)\n\n\t\t// Mark as indexed - now element actions are allowed\n\t\tthis.isIndexed = true\n\n\t\t// Restore mask blocking\n\t\tif (this.mask) {\n\t\t\tthis.mask.wrapper.style.pointerEvents = 'auto'\n\t\t}\n\n\t\tthis.dispatchEvent(new Event('afterUpdate'))\n\n\t\treturn this.simplifiedHTML\n\t}\n\n\t/**\n\t * Reads the page as the accessibility tree and makes its indexes the current ones. The read is\n\t * synchronous and can take long on a large page, so the mask shows a progress bar meanwhile.\n\t */\n\tprivate async updateAccessibilityTree(): Promise<void> {\n\t\t// The numbered highlights belong to the element list and would not match these indexes.\n\t\tdom.cleanUpHighlights()\n\t\tawait this.mask?.startProgress()\n\t\tconst started = performance.now()\n\t\ttry {\n\t\t\tconst observation = await this.accessibility.observeIndexed({\n\t\t\t\tviewportExpansion: dom.resolveViewportExpansion(this.config.viewportExpansion),\n\t\t\t})\n\t\t\tconst indexed = await this.withSurfaceIndexes(observation)\n\t\t\tthis.axObservation = indexed\n\t\t\tthis.simplifiedHTML = indexed.text\n\t\t\tthis.indexSource = 'accessibility'\n\t\t\tthis.selectorMap.clear()\n\t\t\tthis.elementTextMap = new Map(indexed.labels.map((label, index) => [index, label]))\n\t\t\tthis.lastTreeReadMs = Math.round(performance.now() - started)\n\t\t\tif (this.config.logObservations !== false) {\n\t\t\t\tconsole.log('%c[page-agent] accessibility read', LOG_STYLE, `${this.lastTreeReadMs}ms`)\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.mask?.stopProgress()\n\t\t}\n\t}\n\n\t/**\n\t * Gives a numeric index to canvas, svg and role=application surfaces that are not tree nodes.\n\t * A failure here keeps the tree that was already read.\n\t */\n\tprivate async withSurfaceIndexes(\n\t\tobservation: AxIndexedObservation\n\t): Promise<AxIndexedObservation> {\n\t\tthis.surfacePoints = new Map()\n\t\ttry {\n\t\t\tconst surfaces = await this.accessibility.surfaces()\n\t\t\tconst indexed = await appendSurfaceIndexes(\n\t\t\t\tobservation,\n\t\t\t\tsurfaces,\n\t\t\t\tasync (x, y) => {\n\t\t\t\t\tconst hit = await this.accessibility.targetAt(x, y)\n\t\t\t\t\treturn { id: hit.id, tag: hit.tag }\n\t\t\t\t},\n\t\t\t\t{ width: window.innerWidth, height: window.innerHeight }\n\t\t\t)\n\t\t\tthis.surfacePoints = indexed.points\n\t\t\treturn indexed.observation\n\t\t} catch (error) {\n\t\t\tconsole.warn('[PageController] surface indexes unavailable for this read', error)\n\t\t\treturn observation\n\t\t}\n\t}\n\n\t/**\n\t * Clean up all element highlights\n\t */\n\tasync cleanUpHighlights(): Promise<void> {\n\t\tconsole.log('[PageController] cleanUpHighlights')\n\t\tdom.cleanUpHighlights()\n\t}\n\n\t// ======= Element Actions =======\n\n\t/**\n\t * Ensure the tree has been indexed before any index-based operation.\n\t * Throws if updateTree() hasn't been called yet.\n\t */\n\tprivate assertIndexed(): void {\n\t\tif (!this.isIndexed) {\n\t\t\tthrow new Error('DOM tree not indexed yet. Can not perform actions on elements.')\n\t\t}\n\t}\n\n\t/**\n\t * Click element by index\n\t */\n\tasync clickElement(index: number): Promise<ActionResult> {\n\t\tif (this.indexSource === 'accessibility')\n\t\t\treturn this.axAction(\n\t\t\t\t'click element',\n\t\t\t\tindex,\n\t\t\t\t(id) => this.accessibility.click(id),\n\t\t\t\t(_outcome, label) =>\n\t\t\t\t\t`📤 Clicked element (${label}) with a synthetic click. What it did is not verified: check the next page state.`\n\t\t\t)\n\t\ttry {\n\t\t\tthis.assertIndexed()\n\t\t\tconst element = getElementByIndex(this.selectorMap, index)\n\t\t\tconst elemText = this.elementTextMap.get(index)\n\t\t\tawait clickElement(element)\n\n\t\t\t// Handle links that open in new tabs\n\t\t\tif (isAnchorElement(element) && element.target === '_blank') {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tmessage: `✅ Clicked element (${elemText ?? index}). ⚠️ Link opened in a new tab.`,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tmessage: `✅ Clicked element (${elemText ?? index}).`,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Failed to click element: ${error}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Input text into element by index\n\t */\n\tasync inputText(index: number, text: string): Promise<ActionResult> {\n\t\tif (this.indexSource === 'accessibility')\n\t\t\treturn this.axAction(\n\t\t\t\t'input text',\n\t\t\t\tindex,\n\t\t\t\t(id) => this.accessibility.fill(id, text),\n\t\t\t\t(outcome, label) =>\n\t\t\t\t\toutcome.status === 'applied'\n\t\t\t\t\t\t? `✅ Input text (${text}) into element (${label}). The field held it right after; that does not show the page accepted it.`\n\t\t\t\t\t\t: `⚠️ Input text (${text}) was sent to element (${label}). ${outcome.summary}`\n\t\t\t)\n\t\ttry {\n\t\t\tthis.assertIndexed()\n\t\t\tconst element = getElementByIndex(this.selectorMap, index)\n\t\t\tconst elemText = this.elementTextMap.get(index)\n\t\t\tawait inputTextElement(element, text)\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tmessage: `✅ Input text (${text}) into element (${elemText ?? index}).`,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Failed to input text: ${error}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Select dropdown option by index and option text\n\t */\n\tasync selectOption(index: number, optionText: string): Promise<ActionResult> {\n\t\tif (this.indexSource === 'accessibility')\n\t\t\treturn this.axAction(\n\t\t\t\t'select option',\n\t\t\t\tindex,\n\t\t\t\tasync (id) => {\n\t\t\t\t\t// The tool names an option by its text; the tree selects by option value.\n\t\t\t\t\tconst element = await this.accessibility.elementAt(id)\n\t\t\t\t\tif (!element || !isSelectElement(element))\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'the element is not a native select. Click it to open it, then click the option'\n\t\t\t\t\t\t)\n\t\t\t\t\tconst option = Array.from(element.options).find(\n\t\t\t\t\t\t(candidate) => candidate.textContent?.trim() === optionText.trim()\n\t\t\t\t\t)\n\t\t\t\t\tif (!option)\n\t\t\t\t\t\tthrow new Error(`Option with text \"${optionText}\" not found in select element`)\n\t\t\t\t\treturn this.accessibility.select(id, option.value)\n\t\t\t\t},\n\t\t\t\t(outcome, label) =>\n\t\t\t\t\toutcome.status === 'not_applied'\n\t\t\t\t\t\t? `⚠️ Option (${optionText}) was sent to element (${label}). ${outcome.summary}`\n\t\t\t\t\t\t: `✅ Selected option (${optionText}) in element (${label}).`\n\t\t\t)\n\t\ttry {\n\t\t\tthis.assertIndexed()\n\t\t\tconst element = getElementByIndex(this.selectorMap, index)\n\t\t\tconst elemText = this.elementTextMap.get(index)\n\t\t\tawait selectOptionElement(element as HTMLSelectElement, optionText)\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tmessage: `✅ Selected option (${optionText}) in element (${elemText ?? index}).`,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Failed to select option: ${error}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Scroll vertically\n\t */\n\tasync scroll(options: {\n\t\tdown: boolean\n\t\tnumPages: number\n\t\tpixels?: number\n\t\tindex?: number\n\t}): Promise<ActionResult> {\n\t\ttry {\n\t\t\tconst { down, numPages, pixels, index } = options\n\n\t\t\tthis.assertIndexed()\n\n\t\t\tconst scrollAmount = (pixels ?? numPages * window.innerHeight) * (down ? 1 : -1)\n\n\t\t\tif (this.indexSource === 'accessibility')\n\t\t\t\treturn await this.axScroll({ y: scrollAmount }, index)\n\n\t\t\tconst element = index !== undefined ? getElementByIndex(this.selectorMap, index) : null\n\n\t\t\tconst message = await scrollVertically(scrollAmount, element)\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tmessage,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Failed to scroll: ${error}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Scroll horizontally\n\t */\n\tasync scrollHorizontally(options: {\n\t\tright: boolean\n\t\tpixels: number\n\t\tindex?: number\n\t}): Promise<ActionResult> {\n\t\ttry {\n\t\t\tconst { right, pixels, index } = options\n\n\t\t\tthis.assertIndexed()\n\n\t\t\tconst scrollAmount = pixels * (right ? 1 : -1)\n\n\t\t\tif (this.indexSource === 'accessibility')\n\t\t\t\treturn await this.axScroll({ x: scrollAmount }, index)\n\n\t\t\tconst element = index !== undefined ? getElementByIndex(this.selectorMap, index) : null\n\n\t\t\tconst message = await scrollHorizontally(scrollAmount, element)\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tmessage,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Failed to scroll horizontally: ${error}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Scrolls the page, or the container behind an index, and reports the measured movement. */\n\tprivate async axScroll(\n\t\toffsets: { x?: number; y?: number },\n\t\tindex?: number\n\t): Promise<ActionResult> {\n\t\tconst target = index === undefined ? null : this.axTarget(index)\n\t\tconst outcome = target\n\t\t\t? await this.accessibility.scroll(target.id, offsets)\n\t\t\t: await this.accessibility.scroll(offsets)\n\t\tconst { before, after, moved } = outcome.result\n\t\tconst where = target ? `container (${target.label})` : 'page'\n\t\tconst dx = after.x - before.x\n\t\tconst dy = after.y - before.y\n\t\tconst message = moved\n\t\t\t? `✅ Scrolled ${where} by ${offsets.y === undefined ? dx : dy}px (now at x=${after.x}, y=${after.y}).`\n\t\t\t: `⚠️ Scroll of ${where} requested, but the position did not change: the edge was reached or it does not scroll.`\n\t\tif (this.config.logObservations !== false)\n\t\t\tconsole.log('%c[page-agent] scroll', LOG_STYLE, where, offsets, '→', message)\n\t\treturn { success: moved, message }\n\t}\n\n\t/**\n\t * Drag one index of the current read onto another.\n\t * Accessibility indexes only. The events are synthetic (`isTrusted` is false).\n\t * `html5` drops only when the destination cancels `dragover`.\n\t */\n\tasync dragElement(\n\t\tsourceIndex: number,\n\t\ttargetIndex: number,\n\t\tmode: AxDragMode = 'html5'\n\t): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage:\n\t\t\t\t\t'❌ Drag needs the accessibility tree. This step is the element list, so these indexes cannot be dragged.',\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst source = this.axTarget(sourceIndex)\n\t\t\tconst target = this.axTarget(targetIndex)\n\t\t\tconst outcome = await this.accessibility.drag(source.id, target.id, mode)\n\t\t\tconst followUp =\n\t\t\t\tmode === 'html5' && outcome.status === 'not_applied'\n\t\t\t\t\t? ' On the next step, call drag_element once with mode \"pointer-paced\". Neither result proves the effect.'\n\t\t\t\t\t: ''\n\t\t\treturn {\n\t\t\t\tsuccess: outcome.status !== 'not_applied',\n\t\t\t\tmessage:\n\t\t\t\t\t`📤 Dragged ${source.label} onto ${target.label} (${mode}). ${outcome.summary} ` +\n\t\t\t\t\t'Event sent. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.' +\n\t\t\t\t\tfollowUp,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Failed to drag: ${describeFailure(error)}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Synthetic hover. CSS `:hover` stays off. One index of this read. */\n\tasync hoverElement(index: number): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Hover')\n\t\treturn this.axAction(\n\t\t\t'hover element',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.hover(id),\n\t\t\t(outcome, label) =>\n\t\t\t\t`📤 Hover events sent to ${label}. ${outcome.summary} Event sent. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/**\n\t * Synthetic keydown and keyup. The key's native default does not run: no character is typed,\n\t * Tab does not move focus and Enter does not activate the control.\n\t */\n\tasync pressKey(index: number, key: string, options: AxKeyOptions = {}): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Key')\n\t\treturn this.axAction(\n\t\t\t'press key',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.pressKey(id, key, options),\n\t\t\t(outcome, label) =>\n\t\t\t\t`📤 Key ${JSON.stringify(key)} sent to ${label}. ${outcome.summary} Event sent. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/** Synthetic double click. It does not select text the way a physical double click does. */\n\tasync doubleClickElement(index: number): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Double-click')\n\t\treturn this.axAction(\n\t\t\t'double-click element',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.doubleClick(id),\n\t\t\t(outcome, label) =>\n\t\t\t\t`📤 Double-click events sent to ${label}. ${outcome.summary} Event sent. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/**\n\t * Calls `focus()` on an index. The result says whether that element was focused right after.\n\t * Focus is not a saved change.\n\t */\n\tasync focusElement(index: number): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Focus')\n\t\treturn this.axAction(\n\t\t\t'focus element',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.focus(id),\n\t\t\t(outcome, label) =>\n\t\t\t\toutcome.status === 'applied'\n\t\t\t\t\t? `✅ Focus observed on ${label}. ${outcome.summary} Observed right after focus(). Not persisted. These indexes die on the next read.`\n\t\t\t\t\t: `⚠️ Focus was requested on ${label}. ${outcome.summary} Effect not observed. Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/** Checks or unchecks a native checkbox, or selects a native radio. One index of this read. */\n\tasync setChecked(index: number, checked: boolean): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Set-checked')\n\t\treturn this.axAction(\n\t\t\t'set checked',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.setChecked(id, checked),\n\t\t\t(outcome, label) =>\n\t\t\t\t`📤 Set checked=${checked} on ${label}. ${outcome.summary} Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/** Sets a native range input. A value the browser would clamp or round is refused by the core. */\n\tasync setRange(index: number, value: number): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Set-range')\n\t\treturn this.axAction(\n\t\t\t'set range',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.setRange(id, value),\n\t\t\t(outcome, label) =>\n\t\t\t\t`📤 Set range=${value} on ${label}. ${outcome.summary} Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/**\n\t * Calls `scrollIntoView`. The message reports window scroll before and after.\n\t * A scroller inside the page is not measured. The status stays `requested`.\n\t */\n\tasync scrollIntoView(index: number): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Scroll-into-view')\n\t\tconst before = readWindowScroll()\n\t\tconst result = await this.axAction(\n\t\t\t'scroll into view',\n\t\t\tindex,\n\t\t\t(id) => this.accessibility.scrollIntoView(id),\n\t\t\t(_outcome, label) =>\n\t\t\t\t`📤 scrollIntoView called on ${label}. Not persisted. These indexes die on the next read.`\n\t\t)\n\t\tconst after = readWindowScroll()\n\t\tresult.message += ` Window scroll went from (${before.x}, ${before.y}) to (${after.x}, ${after.y}). Nested scrollers were not measured.`\n\t\treturn result\n\t}\n\n\t/**\n\t * One synthetic wheel event. It does not scroll. Without an index the event goes to the page.\n\t */\n\tasync wheel(input: { x?: number; y?: number; index?: number }): Promise<ActionResult> {\n\t\tif (this.indexSource !== 'accessibility') return treeRequired('Wheel')\n\t\tconst offsets = { x: input.x, y: input.y }\n\t\tif (input.index === undefined) {\n\t\t\ttry {\n\t\t\t\tconst outcome = await this.accessibility.wheel(offsets)\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t`📤 Wheel event sent to the page. ${outcome.summary} ` +\n\t\t\t\t\t\t'Event sent. This tool did not scroll. Effect not verified: check the next page state. Not persisted.',\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\treturn { success: false, message: `❌ Failed to wheel: ${describeFailure(error)}` }\n\t\t\t}\n\t\t}\n\t\treturn this.axAction(\n\t\t\t'wheel',\n\t\t\tinput.index,\n\t\t\t(id) => this.accessibility.wheel(id, offsets),\n\t\t\t(outcome, label) =>\n\t\t\t\t`📤 Wheel event sent to ${label}. ${outcome.summary} Event sent. This tool did not scroll. Effect not verified: check the next page state. Not persisted. These indexes die on the next read.`\n\t\t)\n\t}\n\n\t/**\n\t * Execute arbitrary JavaScript on the page.\n\t * The optional `signal` is exposed to the script scope so cooperative code\n\t * can abort promptly when the task is stopped.\n\t *\n\t * When the page CSP disallows `unsafe-eval`, this does not call `eval`. The same origin\n\t * keeps that answer, and the message tells the agent not to try again.\n\t */\n\tasync executeJavascript(\n\t\tscript: string,\n\t\tsignal?: AbortSignal,\n\t\tscope: Record<string, unknown> = {}\n\t): Promise<ActionResult> {\n\t\tconst origin = scriptOrigin()\n\t\tif (generatedScriptAccess(origin) === 'blocked_by_csp') {\n\t\t\treturn { success: false, message: SCRIPT_BLOCKED_BY_CSP }\n\t\t}\n\t\ttry {\n\t\t\t// Wrap the script in an async function so it can await. `signal` and the scope names are parameters.\n\t\t\tconst names = Object.keys(scope)\n\t\t\tconst asyncFunction = eval(`(async (${[...names, 'signal'].join(', ')}) => { ${script} })`)\n\t\t\tconst result = await asyncFunction(...names.map((name) => scope[name]), signal)\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tmessage: `✅ Executed JavaScript. Result: ${formatScriptResult(result)}`,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (isEvalBlocked(error)) {\n\t\t\t\trememberScriptAccess(origin, 'blocked_by_csp')\n\t\t\t\treturn { success: false, message: SCRIPT_BLOCKED_BY_CSP }\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `❌ Error executing JavaScript: ${error}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t// ======= Mask Operations =======\n\n\t/**\n\t * Show the visual mask overlay.\n\t * Only works after mask is setup.\n\t */\n\tasync showMask(): Promise<void> {\n\t\tawait this.maskReady\n\t\tthis.mask?.show()\n\t}\n\n\t/**\n\t * Hide the visual mask overlay.\n\t * Only works after mask is setup.\n\t */\n\tasync hideMask(): Promise<void> {\n\t\tawait this.maskReady\n\t\tthis.mask?.hide()\n\t}\n\n\t/**\n\t * Dispose and clean up resources\n\t */\n\tdispose(): void {\n\t\tdom.cleanUpHighlights()\n\t\tthis.flatTree = null\n\t\tthis.selectorMap.clear()\n\t\tthis.elementTextMap.clear()\n\t\tthis.simplifiedHTML = '<EMPTY>'\n\t\tthis.isIndexed = false\n\t\tthis.indexSource = 'dom'\n\t\tthis.axObservation = null\n\t\tthis.surfacePoints.clear()\n\t\tthis.fallbackNote = ''\n\t\tthis.accessibilityController?.destroy()\n\t\tthis.accessibilityController = null\n\t\tthis.mask?.dispose()\n\t\tthis.mask = null\n\t}\n}\n\nexport * from './actions'\nexport * from './ax'\nexport {\n\tscriptAccessClosed,\n\tSCRIPT_BLOCKED_BY_CSP,\n\tSCRIPT_UNAVAILABLE,\n\tSCRIPT_USER_DENIED,\n} from './scriptAccess'\n","// English translations (base/reference language)\nconst enUS = {\n\tui: {\n\t\tpanel: {\n\t\t\tready: 'Ready',\n\t\t\tthinking: 'Thinking...',\n\t\t\ttaskInput: 'Enter new task, describe steps in detail, press Enter to submit',\n\t\t\tuserAnswerPrompt: 'Please answer the question above, press Enter to submit',\n\t\t\ttaskTerminated: 'Task terminated',\n\t\t\ttaskCompleted: 'Task completed',\n\t\t\tuserAnswer: 'User answer: {{input}}',\n\t\t\tquestion: 'Question: {{question}}',\n\t\t\twaitingPlaceholder: 'Waiting for task to start...',\n\t\t\tstop: 'Stop task',\n\t\t\tclose: 'Minimize',\n\t\t\tsend: 'Send',\n\t\t\topen: 'Open assistant',\n\t\t\tnewCount: '{{count}} new',\n\t\t\tnewTask: 'New task',\n\t\t\texportLog: 'Export log',\n\t\t\tcodeTitle: 'JavaScript',\n\t\t\tcodeScript: 'Script',\n\t\t\tcodeResult: 'Result',\n\t\t\tcodeError: 'Error',\n\t\t\tcodeRunning: 'running',\n\t\t\tcodeDone: 'done',\n\t\t\tcodeFailed: 'failed',\n\t\t\tcodeVoice: 'Voice',\n\t\t\tcodeRefused: 'refused',\n\t\t\tcodeShowMore: 'show more',\n\t\t\tcodeShowLess: 'show less',\n\t\t\tlogTask: 'Task',\n\t\t\tlogAction: 'Action',\n\t\t\tlogResult: 'Result',\n\t\t\tresultTitle: 'Result',\n\t\t\tmsgAborted: 'Task stopped',\n\t\t\tmsgStepLimit: 'Step limit reached',\n\t\t\tmsgRetry: 'Model retry {{attempt}} of {{max}}',\n\t\t\tmsgNavigated: 'Page changed to → {{url}}',\n\t\t\tmsgWaited: 'Waited {{seconds}} seconds in total. Do not wait longer without a reason.',\n\t\t\tmsgStepsLeft: '{{count}} steps left. Consider wrapping up.',\n\t\t\tmsgStepsCritical: 'Critical: only {{count}} steps left.',\n\t\t\tmsgCompleted: 'Task completed',\n\t\t\tpin: 'Pin task',\n\t\t\tunpin: 'Unpin task',\n\t\t\tjumpLatest: 'Latest',\n\t\t\texpand: 'Show conversation',\n\t\t\tcollapse: 'Hide conversation',\n\t\t\texpandFromFab: 'Open assistant',\n\t\t\tfollowModeBar: 'Status bar',\n\t\t\tfollowModeMinimize: 'Minimize',\n\t\t\tstep: 'Step {{number}}',\n\t\t\thideCursor: 'Hide agent cursor',\n\t\t\tshowCursor: 'Show agent cursor',\n\t\t\tstatusRunning: 'Working...',\n\t\t\tstatusRetrying: 'Retrying ({{attempt}}/{{max}})',\n\t\t\tstatusDone: 'Done',\n\t\t\tstatusNotDone: 'Not completed',\n\t\t\tstatusStopped: 'Stopped',\n\t\t\tstatusError: 'Error',\n\t\t\tstatusWaiting: 'Waiting for you',\n\t\t\tcomposerPlaceholder: 'Describe a task…',\n\t\t\tcomposerRunning: 'Task in progress…',\n\t\t\tcomposerAnswer: 'Answer the agent…',\n\t\t\tattachFile: 'Attach file',\n\t\t\tattachRemove: 'Remove {{name}}',\n\t\t\tattachFailed: 'Could not attach file',\n\t\t\tskillsStudio: 'Skills Studio',\n\t\t\tskillsStudioBack: 'Back to chat',\n\t\t\tskillsStudioRecord: 'Record',\n\t\t\tskillsStudioAsk: 'Ask',\n\t\t\tskillsStudioCatalog: 'Catalog',\n\t\t\tskillsStudioRecordHint:\n\t\t\t\t'Click the page to capture steps. Finish later to turn them into a skill.',\n\t\t\tskillsStudioAskHint:\n\t\t\t\t'Describe the skill you want. The agent will walk the flow and draft it.',\n\t\t\tskillsStudioAskPlaceholder: 'e.g. Switch workspace by name…',\n\t\t\tskillsStudioEmptyCatalog: 'No skills in this browser yet.',\n\t\t\tskillsStudioUnavailable: 'Skills Studio needs a skills-enabled agent.',\n\t\t\tskillsStudioStart: 'Start recording',\n\t\t\tskillsStudioStop: 'Stop',\n\t\t\tskillsStudioFinish: 'Finish & synthesize',\n\t\t\tskillsStudioClear: 'Clear',\n\t\t\tskillsStudioSave: 'Save',\n\t\t\tskillsStudioTest: 'Test',\n\t\t\tskillsStudioParam: 'Parameterize',\n\t\t\tskillsStudioUnparam: 'Keep literal',\n\t\t\tskillsStudioRemoveStep: 'Remove step',\n\t\t\tskillsStudioEmptySteps: 'No steps recorded yet.',\n\t\t\tskillsStudioPreview: 'Skill preview',\n\t\t\tskillsStudioAskStart: 'Start',\n\t\t\tskillsStudioRefreshRemote: 'Refresh remote',\n\t\t\tskillsStudioRemoveSkill: 'Remove',\n\t\t\tskillsStudioRemoveAgentSkills: 'Remove agent skills',\n\t\t\tskillsStudioRecording: 'Recording…',\n\t\t\tskillsStudioIdle: 'Not recording',\n\t\t\tskillsStudioSaved: 'Saved {{id}} v{{version}}',\n\t\t\tskillsStudioRemoteWarn: 'Saved locally; remote sync failed: {{error}}',\n\t\t\tskillsStudioSynthesized: 'Synthesized {{id}}',\n\t\t\tskillsStudioTested: 'Test: {{result}}',\n\t\t\tskillsStudioAskQueued: 'Authoring skill for your goal…',\n\t\t\tskillsStudioError: '{{message}}',\n\t\t\tskillsStudioScopeAgent: 'agent',\n\t\t\tskillsStudioScopeRemote: 'remote',\n\t\t\tskillsStudioLoaded: 'loaded',\n\t\t\tskillsStudioCatalogCount: '{{count}} skills',\n\t\t\tskillsStudioArmWatch: 'Arm watch',\n\t\t\tskillsStudioDisarmWatch: 'Disarm',\n\t\t\tskillsStudioWatchers: 'Watchers',\n\t\t\tskillsStudioWatchArmed: 'Armed {{id}}',\n\t\t\tskillsStudioWatchFired: 'Watch fired: {{message}}',\n\t\t\tskillsStudioWatchEmpty: 'No active watches',\n\t\t\tskillsStudioWatchNeedlePrompt: 'Text to watch for (default: reply)',\n\t\t\tswitchToVoice: 'Use voice',\n\t\t\tswitchToText: 'Use text',\n\t\t\tvoiceUnavailable: 'Unavailable',\n\t\t\tvoiceConnecting: 'Connecting…',\n\t\t\tvoiceListening: 'Listening',\n\t\t\tvoiceSpeaking: 'Speaking',\n\t\t\tvoiceBusy: 'Still on the previous task.',\n\t\t\tvoiceNoKey: 'Voice needs an API key',\n\t\t\tvoiceConnectFailed: 'Could not connect voice',\n\t\t\tvoiceOn: 'Mic on',\n\t\t\tvoiceOff: 'Mic off',\n\t\t\tvoiceMuted: 'Muted',\n\t\t\tvoiceDenied: 'Mic blocked',\n\t\t\tvoiceMicBusy: 'Mic in use by another app',\n\t\t\tvoiceMicSilent: 'This mic is silent — try another',\n\t\t\tswitchMic: 'Switch microphone',\n\t\t\tmute: 'Mute mic',\n\t\t\tunmute: 'Unmute mic',\n\t\t\tresultDone: 'Task completed',\n\t\t\tresultNotDone: 'Task not completed',\n\t\t\tresultStopped: 'Task stopped',\n\t\t\tresultError: 'Task failed',\n\t\t\tquestionTitle: 'Question',\n\t\t\tanswerTitle: 'Your answer',\n\t\t\tanswerTitleChoice: 'Choose one',\n\t\t\tanswerTitleMulti: 'Choose all that apply',\n\t\t\tanswerConfirmMulti: 'Confirm selection',\n\t\t\tcomposerAnswerChoice: 'Tap an option above…',\n\t\t\tcomposerAnswerMulti: 'Select options, then confirm…',\n\t\t\tmemory: 'Memory',\n\t\t\tnextGoal: 'Next goal',\n\t\t\tevaluation: 'Last step',\n\t\t\tuserTakeover: 'You took control',\n\t\t\temptyHint: 'Describe a task to get started.',\n\t\t},\n\t\ttools: {\n\t\t\tclicking: 'Clicking element [{{index}}]...',\n\t\t\tinputting: 'Inputting text to element [{{index}}]...',\n\t\t\tselecting: 'Selecting option \"{{text}}\"...',\n\t\t\tscrolling: 'Scrolling page...',\n\t\t\twaiting: 'Waiting {{seconds}} seconds...',\n\t\t\taskingUser: 'Asking user...',\n\t\t\tdone: 'Task done',\n\t\t\tclicked: '🖱️ Clicked element [{{index}}]',\n\t\t\tinputted: '⌨️ Inputted text \"{{text}}\"',\n\t\t\tselected: '☑️ Selected option \"{{text}}\"',\n\t\t\tscrolled: '🛞 Page scrolled',\n\t\t\twaited: '⌛️ Wait completed',\n\t\t\texecuting: 'Executing {{toolName}}...',\n\t\t\tresultSuccess: 'success',\n\t\t\tresultFailure: 'failed',\n\t\t\tresultError: 'error',\n\t\t},\n\t\terrors: {\n\t\t\telementNotFound: 'No interactive element found at index {{index}}',\n\t\t\ttaskRequired: 'Task description is required',\n\t\t\texecutionFailed: 'Task execution failed',\n\t\t\tnotInputElement: 'Element is not an input or textarea',\n\t\t\tnotSelectElement: 'Element is not a select element',\n\t\t\toptionNotFound: 'Option \"{{text}}\" not found',\n\t\t},\n\t},\n} as const\n\n// Portuguese (Brazil) translations (must match the structure of enUS)\nconst ptBR = {\n\tui: {\n\t\tpanel: {\n\t\t\tready: 'Pronto',\n\t\t\tthinking: 'Pensando...',\n\t\t\ttaskInput: 'Digite uma nova tarefa, descreva os passos com detalhes e pressione Enter',\n\t\t\tuserAnswerPrompt: 'Responda à pergunta acima e pressione Enter',\n\t\t\ttaskTerminated: 'Tarefa encerrada',\n\t\t\ttaskCompleted: 'Tarefa concluída',\n\t\t\tuserAnswer: 'Resposta do usuário: {{input}}',\n\t\t\tquestion: 'Pergunta: {{question}}',\n\t\t\twaitingPlaceholder: 'Aguardando o início da tarefa...',\n\t\t\tstop: 'Parar tarefa',\n\t\t\tclose: 'Minimizar',\n\t\t\tsend: 'Enviar',\n\t\t\topen: 'Abrir assistente',\n\t\t\tnewCount: '{{count}} novas',\n\t\t\tnewTask: 'Nova tarefa',\n\t\t\texportLog: 'Exportar log',\n\t\t\tcodeTitle: 'JavaScript',\n\t\t\tcodeScript: 'Código',\n\t\t\tcodeResult: 'Resultado',\n\t\t\tcodeError: 'Erro',\n\t\t\tcodeRunning: 'executando',\n\t\t\tcodeDone: 'executado',\n\t\t\tcodeFailed: 'falhou',\n\t\t\tcodeVoice: 'Voz',\n\t\t\tcodeRefused: 'recusado',\n\t\t\tcodeShowMore: 'mostrar mais',\n\t\t\tcodeShowLess: 'recolher',\n\t\t\tlogTask: 'Tarefa',\n\t\t\tlogAction: 'Ação',\n\t\t\tlogResult: 'Resultado',\n\t\t\tresultTitle: 'Resultado',\n\t\t\tmsgAborted: 'Tarefa interrompida',\n\t\t\tmsgStepLimit: 'Limite de passos atingido',\n\t\t\tmsgRetry: 'Nova tentativa do modelo {{attempt}} de {{max}}',\n\t\t\tmsgNavigated: 'Página mudou para → {{url}}',\n\t\t\tmsgWaited: 'Esperou {{seconds}} segundos no total. Não espere mais sem motivo.',\n\t\t\tmsgStepsLeft: '{{count}} passos restantes. Considere concluir.',\n\t\t\tmsgStepsCritical: 'Crítico: restam só {{count}} passos.',\n\t\t\tmsgCompleted: 'Tarefa concluída',\n\t\t\tpin: 'Fixar tarefa',\n\t\t\tunpin: 'Desafixar tarefa',\n\t\t\tjumpLatest: 'Mais recentes',\n\t\t\texpand: 'Mostrar conversa',\n\t\t\tcollapse: 'Ocultar conversa',\n\t\t\texpandFromFab: 'Abrir assistente',\n\t\t\tfollowModeBar: 'Barra de status',\n\t\t\tfollowModeMinimize: 'Minimizar',\n\t\t\tstep: 'Passo {{number}}',\n\t\t\thideCursor: 'Ocultar cursor do agente',\n\t\t\tshowCursor: 'Mostrar cursor do agente',\n\t\t\tstatusRunning: 'Trabalhando...',\n\t\t\tstatusRetrying: 'Tentando de novo ({{attempt}}/{{max}})',\n\t\t\tstatusDone: 'Concluído',\n\t\t\tstatusNotDone: 'Não concluído',\n\t\t\tstatusStopped: 'Parado',\n\t\t\tstatusError: 'Erro',\n\t\t\tstatusWaiting: 'Aguardando você',\n\t\t\tcomposerPlaceholder: 'Descreva uma tarefa…',\n\t\t\tcomposerRunning: 'Tarefa em andamento…',\n\t\t\tcomposerAnswer: 'Responda ao agente…',\n\t\t\tattachFile: 'Anexar arquivo',\n\t\t\tattachRemove: 'Remover {{name}}',\n\t\t\tattachFailed: 'Não foi possível anexar o arquivo',\n\t\t\tskillsStudio: 'Skills Studio',\n\t\t\tskillsStudioBack: 'Voltar ao chat',\n\t\t\tskillsStudioRecord: 'Gravar',\n\t\t\tskillsStudioAsk: 'Pedir',\n\t\t\tskillsStudioCatalog: 'Catálogo',\n\t\t\tskillsStudioRecordHint:\n\t\t\t\t'Clique na página para capturar passos. Depois finalize para virar uma skill.',\n\t\t\tskillsStudioAskHint: 'Descreva a skill. O agente percorre o fluxo e monta o rascunho.',\n\t\t\tskillsStudioAskPlaceholder: 'ex.: Trocar workspace pelo nome…',\n\t\t\tskillsStudioEmptyCatalog: 'Nenhuma skill neste browser ainda.',\n\t\t\tskillsStudioUnavailable: 'O Skills Studio precisa de um agente com skills habilitadas.',\n\t\t\tskillsStudioStart: 'Começar gravação',\n\t\t\tskillsStudioStop: 'Parar',\n\t\t\tskillsStudioFinish: 'Finalizar e sintetizar',\n\t\t\tskillsStudioClear: 'Limpar',\n\t\t\tskillsStudioSave: 'Salvar',\n\t\t\tskillsStudioTest: 'Testar',\n\t\t\tskillsStudioParam: 'Parametrizar',\n\t\t\tskillsStudioUnparam: 'Manter literal',\n\t\t\tskillsStudioRemoveStep: 'Remover passo',\n\t\t\tskillsStudioEmptySteps: 'Nenhum passo gravado ainda.',\n\t\t\tskillsStudioPreview: 'Prévia da skill',\n\t\t\tskillsStudioAskStart: 'Começar',\n\t\t\tskillsStudioRefreshRemote: 'Atualizar remoto',\n\t\t\tskillsStudioRemoveSkill: 'Remover',\n\t\t\tskillsStudioRemoveAgentSkills: 'Remover skills do agente',\n\t\t\tskillsStudioRecording: 'Gravando…',\n\t\t\tskillsStudioIdle: 'Sem gravação',\n\t\t\tskillsStudioSaved: 'Salva {{id}} v{{version}}',\n\t\t\tskillsStudioRemoteWarn: 'Salva localmente; sync remoto falhou: {{error}}',\n\t\t\tskillsStudioSynthesized: 'Sintetizada {{id}}',\n\t\t\tskillsStudioTested: 'Teste: {{result}}',\n\t\t\tskillsStudioAskQueued: 'Criando skill para o seu objetivo…',\n\t\t\tskillsStudioError: '{{message}}',\n\t\t\tskillsStudioScopeAgent: 'agente',\n\t\t\tskillsStudioScopeRemote: 'remoto',\n\t\t\tskillsStudioLoaded: 'carregada',\n\t\t\tskillsStudioCatalogCount: '{{count}} skills',\n\t\t\tskillsStudioArmWatch: 'Armar watch',\n\t\t\tskillsStudioDisarmWatch: 'Desarmar',\n\t\t\tskillsStudioWatchers: 'Watches',\n\t\t\tskillsStudioWatchArmed: 'Armado {{id}}',\n\t\t\tskillsStudioWatchFired: 'Watch disparou: {{message}}',\n\t\t\tskillsStudioWatchEmpty: 'Nenhum watch ativo',\n\t\t\tskillsStudioWatchNeedlePrompt: 'Texto a observar (padrão: reply)',\n\t\t\tswitchToVoice: 'Usar voz',\n\t\t\tswitchToText: 'Usar texto',\n\t\t\tvoiceUnavailable: 'Indisponível',\n\t\t\tvoiceConnecting: 'Conectando…',\n\t\t\tvoiceListening: 'Ouvindo',\n\t\t\tvoiceSpeaking: 'Falando',\n\t\t\tvoiceBusy: 'Ainda estou na tarefa anterior.',\n\t\t\tvoiceNoKey: 'A voz precisa de uma chave de API',\n\t\t\tvoiceConnectFailed: 'Não consegui conectar a voz',\n\t\t\tvoiceOn: 'Mic ativo',\n\t\t\tvoiceOff: 'Mic desligado',\n\t\t\tvoiceMuted: 'Mudo',\n\t\t\tvoiceDenied: 'Mic bloqueado',\n\t\t\tvoiceMicBusy: 'Mic em uso por outro app',\n\t\t\tvoiceMicSilent: 'Este mic está mudo — tente outro',\n\t\t\tswitchMic: 'Trocar microfone',\n\t\t\tmute: 'Silenciar',\n\t\t\tunmute: 'Ativar microfone',\n\t\t\tresultDone: 'Tarefa concluída',\n\t\t\tresultNotDone: 'Tarefa não concluída',\n\t\t\tresultStopped: 'Tarefa parada',\n\t\t\tresultError: 'Tarefa falhou',\n\t\t\tquestionTitle: 'Pergunta',\n\t\t\tanswerTitle: 'Sua resposta',\n\t\t\tanswerTitleChoice: 'Escolha uma',\n\t\t\tanswerTitleMulti: 'Escolha todas que se aplicam',\n\t\t\tanswerConfirmMulti: 'Confirmar seleção',\n\t\t\tcomposerAnswerChoice: 'Toque em uma opção acima…',\n\t\t\tcomposerAnswerMulti: 'Selecione as opções e confirme…',\n\t\t\tmemory: 'Memória',\n\t\t\tnextGoal: 'Próximo objetivo',\n\t\t\tevaluation: 'Último passo',\n\t\t\tuserTakeover: 'Você assumiu o controle',\n\t\t\temptyHint: 'Descreva uma tarefa para começar.',\n\t\t},\n\t\ttools: {\n\t\t\tclicking: 'Clicando no elemento [{{index}}]...',\n\t\t\tinputting: 'Digitando texto no elemento [{{index}}]...',\n\t\t\tselecting: 'Selecionando a opção \"{{text}}\"...',\n\t\t\tscrolling: 'Rolando a página...',\n\t\t\twaiting: 'Aguardando {{seconds}} segundos...',\n\t\t\taskingUser: 'Perguntando ao usuário...',\n\t\t\tdone: 'Tarefa concluída',\n\t\t\tclicked: '🖱️ Clicou no elemento [{{index}}]',\n\t\t\tinputted: '⌨️ Digitou o texto \"{{text}}\"',\n\t\t\tselected: '☑️ Selecionou a opção \"{{text}}\"',\n\t\t\tscrolled: '🛞 Página rolada',\n\t\t\twaited: '⌛️ Espera concluída',\n\t\t\texecuting: 'Executando {{toolName}}...',\n\t\t\tresultSuccess: 'sucesso',\n\t\t\tresultFailure: 'falhou',\n\t\t\tresultError: 'erro',\n\t\t},\n\t\terrors: {\n\t\t\telementNotFound: 'Nenhum elemento interativo encontrado no índice {{index}}',\n\t\t\ttaskRequired: 'A descrição da tarefa é obrigatória',\n\t\t\texecutionFailed: 'Falha na execução da tarefa',\n\t\t\tnotInputElement: 'O elemento não é um campo de texto',\n\t\t\tnotSelectElement: 'O elemento não é uma lista de seleção',\n\t\t\toptionNotFound: 'Opção \"{{text}}\" não encontrada',\n\t\t},\n\t},\n} as const\n\n// Type definitions generated from English base structure (but with string values)\ntype DeepStringify<T> = {\n\t[K in keyof T]: T[K] extends string ? string : T[K] extends object ? DeepStringify<T[K]> : T[K]\n}\n\nexport type TranslationSchema = DeepStringify<typeof enUS>\n\n// Utility type: Extract all nested paths from translation object\ntype NestedKeyOf<ObjectType extends object> = {\n\t[Key in keyof ObjectType & (string | number)]: ObjectType[Key] extends object\n\t\t? `${Key}` | `${Key}.${NestedKeyOf<ObjectType[Key]>}`\n\t\t: `${Key}`\n}[keyof ObjectType & (string | number)]\n\n// Extract all possible key paths from translation structure\nexport type TranslationKey = NestedKeyOf<TranslationSchema>\n\n// Parameterized translation types\nexport type TranslationParams = Record<string, string | number>\n\nexport const locales = {\n\t'en-US': enUS,\n\t'pt-BR': ptBR,\n} as const\n\nexport type SupportedLanguage = keyof typeof locales\n","import {\n\ttype SupportedLanguage,\n\ttype TranslationKey,\n\ttype TranslationParams,\n\ttype TranslationSchema,\n\tlocales,\n} from './locales'\n\nexport class I18n {\n\tprivate language: SupportedLanguage\n\tprivate translations: TranslationSchema\n\n\tconstructor(language: string = 'en-US') {\n\t\t// Languages without a translation (for example, codes the core still accepts) fall back to English.\n\t\tthis.language = (language in locales ? language : 'en-US') as SupportedLanguage\n\t\tthis.translations = locales[this.language]\n\t}\n\n\t// 类型安全的翻译方法\n\tt(key: TranslationKey, params?: TranslationParams): string {\n\t\tconst value = this.getNestedValue(this.translations, key)\n\t\tif (!value) {\n\t\t\tconsole.warn(`Translation key \"${key}\" not found for language \"${this.language}\"`)\n\t\t\treturn key\n\t\t}\n\n\t\tif (params) {\n\t\t\treturn this.interpolate(value, params)\n\t\t}\n\t\treturn value\n\t}\n\n\tprivate getNestedValue(obj: any, path: string): string | undefined {\n\t\treturn path.split('.').reduce((current, key) => current?.[key], obj)\n\t}\n\n\tprivate interpolate(template: string, params: TranslationParams): string {\n\t\treturn template.replace(/\\{\\{(\\w+)\\}\\}/g, (match, key) => {\n\t\t\t// Use != null to check for both null and undefined, allow empty strings\n\t\t\treturn params[key] != null ? params[key].toString() : match\n\t\t})\n\t}\n\n\tgetLanguage(): SupportedLanguage {\n\t\treturn this.language\n\t}\n}\n\n// 导出类型和实例创建函数\nexport type { TranslationKey, SupportedLanguage, TranslationParams }\nexport { locales }\n","/**\n * Messages of the OpenAI Realtime API used by the panel's voice mode.\n * Pure functions only: building and reading messages, no network.\n */\n\nexport const REALTIME_MODEL = 'gpt-realtime-2.1-mini'\nexport const TRANSCRIPTION_MODEL = 'gpt-4o-mini-transcribe'\nexport const REALTIME_VOICE = 'marin'\nexport const RUN_TASK = 'run_task'\nexport const EXECUTE_JS = 'execute_javascript'\nexport const ANSWER_QUESTION = 'answer_question'\nexport const GET_CONTEXT = 'get_context'\n\nexport interface RealtimeSettings {\n\tinstructions: string\n\tlanguage: string\n\tvoice?: string\n}\n\n/** Hands a multi-step task or a judgment about the page to the agent. */\nexport const RUN_TASK_TOOL = {\n\ttype: 'function',\n\tname: RUN_TASK,\n\tdescription:\n\t\t'Gives a task to the page agent, which carries it out in several steps. Use it for a task that needs several steps or a judgment about the page. For one simple action or a read, use execute_javascript.',\n\tparameters: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\ttask: {\n\t\t\t\ttype: 'string',\n\t\t\t\t// REVERSIBLE (2026-11-17, task intake): the request goes as the user said it.\n\t\t\t\tdescription:\n\t\t\t\t\t\"The user's request, exactly as the user said it. Do not rewrite it or add context.\",\n\t\t\t},\n\t\t},\n\t\trequired: ['task'],\n\t},\n} as const\n\n/** Runs JavaScript in the page, with the page-agent instance in scope as `agent`. */\nexport const EXECUTE_JS_TOOL = {\n\ttype: 'function',\n\tname: EXECUTE_JS,\n\tdescription:\n\t\t'Runs JavaScript in this page and returns its result. The variable `agent` is the page-agent instance (`agent.pageController`, `agent.tools`). Use it to read the page, measure positions, or act on an element, without starting an agent task. Prefer get_context for a vertical tree slice. `await agent.pageController.getState()` reads the page only when needed. Write one script for the whole job, and return a small object with the values you need.',\n\tparameters: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\tscript: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'The JavaScript body. Use `return` to send a value back.',\n\t\t\t},\n\t\t},\n\t\trequired: ['script'],\n\t},\n} as const\n\n/** Sends the user's spoken answer to a pending agent ask_user. */\nexport const ANSWER_QUESTION_TOOL = {\n\ttype: 'function',\n\tname: ANSWER_QUESTION,\n\tdescription:\n\t\t\"Send the user's answer to the agent's pending question. Use this only after the agent asked something (report kind question). Pass the answer exactly as the user said it, or the chosen option label(s).\",\n\tparameters: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\tanswer: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: \"The user's answer, exactly as spoken or the chosen option text.\",\n\t\t\t},\n\t\t},\n\t\trequired: ['answer'],\n\t},\n} as const\n\n/** Read-only vertical slice of the accessibility tree. */\nexport const GET_CONTEXT_TOOL = {\n\ttype: 'function',\n\tname: GET_CONTEXT,\n\tdescription:\n\t\t'Read a vertical slice of the page accessibility tree by document Y (page coordinates). Use to skim large pages. Omit y_min/y_max to read the current viewport band. query filters role/name. Read-only for voice: does not change agent action indexes.',\n\tparameters: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\ty_min: { type: 'number', description: 'Document Y start in CSS pixels.' },\n\t\t\ty_max: { type: 'number', description: 'Document Y end in CSS pixels.' },\n\t\t\tmax_lines: { type: 'number', description: 'Max tree lines (10–200). Default 60.' },\n\t\t\tquery: { type: 'string', description: 'Optional case-insensitive filter on role/name.' },\n\t\t},\n\t\trequired: [],\n\t},\n} as const\n\n/**\n * Session configuration sent when the call is created. The model answers conversation by itself and uses its\n * two tools for the page. Speech interrupts the model (barge-in) through server-side turn detection.\n */\nexport function callSessionConfig(settings: RealtimeSettings): string {\n\treturn JSON.stringify({\n\t\ttype: 'realtime',\n\t\tmodel: REALTIME_MODEL,\n\t\tinstructions: settings.instructions,\n\t\toutput_modalities: ['audio'],\n\t\ttools: [RUN_TASK_TOOL, ANSWER_QUESTION_TOOL, GET_CONTEXT_TOOL, EXECUTE_JS_TOOL],\n\t\ttool_choice: 'auto',\n\t\taudio: {\n\t\t\tinput: {\n\t\t\t\ttranscription: { model: TRANSCRIPTION_MODEL, language: settings.language },\n\t\t\t\tturn_detection: { type: 'server_vad', create_response: true, interrupt_response: true },\n\t\t\t},\n\t\t\toutput: { voice: settings.voice ?? REALTIME_VOICE },\n\t\t},\n\t})\n}\n\n/**\n * The current date, time and time zone. Sent with each response, so a long voice session does not keep a\n * stale time from when it started.\n */\nexport function currentTimeLine(now: Date = new Date()): string {\n\tconst zone = Intl.DateTimeFormat().resolvedOptions().timeZone\n\tconst formatted = new Intl.DateTimeFormat('en-US', {\n\t\tdateStyle: 'full',\n\t\ttimeStyle: 'medium',\n\t\ttimeZone: zone,\n\t}).format(now)\n\treturn `Current time: ${formatted} (${zone}).`\n}\n\n/** What the agent reports to the voice. Facts only; the voice model turns them into one spoken sentence. */\nexport interface VoiceReport {\n\tkind: 'question' | 'done' | 'not-done' | 'stopped' | 'error' | 'notice'\n\ttext: string\n}\n\nconst KIND_LABEL: Record<VoiceReport['kind'], string> = {\n\tquestion:\n\t\t'The agent needs an answer from the user. Speak the question. When the user answers, call answer_question with their answer exactly. Do not call run_task for that answer',\n\tdone: 'The task was completed',\n\t'not-done': 'The task was not completed',\n\tstopped: 'The task was stopped',\n\terror: 'The task failed',\n\tnotice: 'System notice',\n}\n\nconst REPORT_MAX_CHARS = 600\n\n/** Sends a report as context and asks for one short spoken sentence. The model does not repeat the text. */\nexport function reportCommand(report: VoiceReport): string {\n\tconst body = report.text.trim().slice(0, REPORT_MAX_CHARS)\n\treturn JSON.stringify({\n\t\ttype: 'response.create',\n\t\tresponse: {\n\t\t\toutput_modalities: ['audio'],\n\t\t\tinstructions: `${KIND_LABEL[report.kind]}. ${currentTimeLine()}\\nData for you to use with judgment; do not read technical details:\\n${body}\\nAnswer in one short sentence.`,\n\t\t},\n\t})\n}\n\n/** Stops the model's speech in progress. Only send it while a response is running. */\nexport function cancelResponseCommand(): string {\n\treturn JSON.stringify({ type: 'response.cancel' })\n}\n\n/** Returns the result of a tool call to the model, then asks it to continue speaking. */\nexport function toolResultCommands(callId: string, output: string): string[] {\n\treturn [\n\t\tJSON.stringify({\n\t\t\ttype: 'conversation.item.create',\n\t\t\titem: { type: 'function_call_output', call_id: callId, output },\n\t\t}),\n\t\tJSON.stringify({\n\t\t\ttype: 'response.create',\n\t\t\t// REVERSIBLE (2026-11-17, task intake): after a tool result, speak only the result in one sentence.\n\t\t\tresponse: {\n\t\t\t\toutput_modalities: ['audio'],\n\t\t\t\tinstructions: `${currentTimeLine()} Give only the result of the tool in one short sentence. Do not describe what you are about to do.`,\n\t\t\t},\n\t\t}),\n\t]\n}\n\nexport type ServerEvent =\n\t| { type: 'ready' }\n\t| { type: 'transcript'; text: string }\n\t| { type: 'speech_started' }\n\t| { type: 'response_started' }\n\t| { type: 'response_done' }\n\t| { type: 'tool_call'; name: string; callId: string; args: Record<string, unknown> }\n\t| { type: 'error'; message: string }\n\t| { type: 'other' }\n\n/** Reads the arguments of a tool call. Missing or malformed arguments give an empty object. */\nfunction argsFrom(raw: unknown): Record<string, unknown> {\n\tif (typeof raw !== 'string') return {}\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(raw)\n\t\treturn typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {}\n\t} catch {\n\t\treturn {}\n\t}\n}\n\n/** Reads one message from the data channel. Unknown or malformed messages become `other`. */\nexport function parseServerEvent(raw: string): ServerEvent {\n\tlet data: unknown\n\ttry {\n\t\tdata = JSON.parse(raw)\n\t} catch {\n\t\treturn { type: 'other' }\n\t}\n\tif (typeof data !== 'object' || data === null) return { type: 'other' }\n\tconst event = data as Record<string, unknown>\n\tswitch (event.type) {\n\t\tcase 'session.created':\n\t\tcase 'session.started':\n\t\tcase 'session.updated':\n\t\t\treturn { type: 'ready' }\n\t\tcase 'conversation.item.input_audio_transcription.completed':\n\t\t\treturn typeof event.transcript === 'string'\n\t\t\t\t? { type: 'transcript', text: event.transcript.trim() }\n\t\t\t\t: { type: 'other' }\n\t\tcase 'input_audio_buffer.speech_started':\n\t\t\treturn { type: 'speech_started' }\n\t\tcase 'response.created':\n\t\t\treturn { type: 'response_started' }\n\t\tcase 'response.done':\n\t\t\treturn { type: 'response_done' }\n\t\tcase 'response.function_call_arguments.done':\n\t\t\treturn typeof event.name === 'string' && typeof event.call_id === 'string'\n\t\t\t\t? {\n\t\t\t\t\t\ttype: 'tool_call',\n\t\t\t\t\t\tname: event.name,\n\t\t\t\t\t\tcallId: event.call_id,\n\t\t\t\t\t\targs: argsFrom(event.arguments),\n\t\t\t\t\t}\n\t\t\t\t: { type: 'other' }\n\t\tcase 'error': {\n\t\t\tconst error = event.error as { message?: unknown } | undefined\n\t\t\treturn {\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: typeof error?.message === 'string' ? error.message : 'error',\n\t\t\t}\n\t\t}\n\t\tdefault:\n\t\t\treturn { type: 'other' }\n\t}\n}\n","/**\n * Gemini Live protocol for the voice panel. Pure functions only: no network, no audio devices.\n * REVERSIBLE (2026-11-17, gemini provider): delete this file and gemini-client.ts to remove Gemini support.\n *\n * The session sends commands in the shape the OpenAI client already uses. `translateCommand` turns each one into a\n * Gemini client message, so the session does not change for either provider.\n */\nimport {\n\tANSWER_QUESTION_TOOL,\n\tEXECUTE_JS_TOOL,\n\tGET_CONTEXT_TOOL,\n\tRUN_TASK_TOOL,\n\ttype RealtimeSettings,\n\ttype ServerEvent,\n} from './realtime-protocol'\n\nexport const GEMINI_LIVE_MODEL = 'gemini-3.8-live'\nexport const GEMINI_VOICE = 'Leda'\nconst LIVE_ENDPOINT =\n\t'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent'\n\nexport function liveUrl(apiKey: string): string {\n\treturn `${LIVE_ENDPOINT}?key=${encodeURIComponent(apiKey)}`\n}\n\n/** Gemini wants schema types in upper case (OBJECT, STRING); the tool definitions use lower case. */\nfunction toGeminiSchema(schema: unknown): unknown {\n\tif (Array.isArray(schema)) return schema.map(toGeminiSchema)\n\tif (typeof schema !== 'object' || schema === null) return schema\n\tconst out: Record<string, unknown> = {}\n\tfor (const [key, value] of Object.entries(schema)) {\n\t\tout[key] =\n\t\t\tkey === 'type' && typeof value === 'string' ? value.toUpperCase() : toGeminiSchema(value)\n\t}\n\treturn out\n}\n\n/** The two tools, declared with the same names, descriptions and parameters as for OpenAI. */\nexport function geminiTools(): unknown[] {\n\treturn [\n\t\t{\n\t\t\tfunctionDeclarations: [\n\t\t\t\tRUN_TASK_TOOL,\n\t\t\t\tANSWER_QUESTION_TOOL,\n\t\t\t\tGET_CONTEXT_TOOL,\n\t\t\t\tEXECUTE_JS_TOOL,\n\t\t\t].map((tool) => ({\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tparameters: toGeminiSchema(tool.parameters),\n\t\t\t})),\n\t\t},\n\t]\n}\n\n/** The first message on a new connection: model, voice, instructions and tools. */\nexport function geminiSetup(settings: RealtimeSettings): string {\n\treturn JSON.stringify({\n\t\tsetup: {\n\t\t\tmodel: `models/${GEMINI_LIVE_MODEL}`,\n\t\t\tgenerationConfig: {\n\t\t\t\tresponseModalities: ['AUDIO'],\n\t\t\t\tspeechConfig: {\n\t\t\t\t\tvoiceConfig: { prebuiltVoiceConfig: { voiceName: GEMINI_VOICE } },\n\t\t\t\t},\n\t\t\t},\n\t\t\tsystemInstruction: { parts: [{ text: settings.instructions }] },\n\t\t\ttools: geminiTools(),\n\t\t\tinputAudioTranscription: {},\n\t\t\toutputAudioTranscription: {},\n\t\t},\n\t})\n}\n\n/** State the translation needs between commands: the name of each tool call, and whether a tool reply is pending. */\nexport interface GeminiSendState {\n\tcallNames: Map<string, string>\n\tawaitingToolReply: boolean\n}\n\nexport function newSendState(): GeminiSendState {\n\treturn { callNames: new Map(), awaitingToolReply: false }\n}\n\n/** A command as the session builds it (OpenAI Realtime shape). Only the fields used here are typed. */\ninterface Command {\n\ttype?: string\n\tresponse?: { instructions?: string }\n\titem?: {\n\t\ttype?: string\n\t\trole?: string\n\t\tcall_id?: string\n\t\toutput?: string\n\t\tcontent?: { text?: string }[]\n\t}\n}\n\nfunction userText(text: string, turnComplete: boolean): unknown {\n\treturn { clientContent: { turns: [{ role: 'user', parts: [{ text }] }], turnComplete } }\n}\n\n/**\n * Turns one session command into Gemini client messages.\n * - A report (response.create) asks the model to speak: it ends the user turn.\n * - A silent note (system item) is added without asking for a reply.\n * - A tool result is a tool response; Gemini then continues by itself, so the response.create that follows is dropped.\n * - Cancel and delete have no Gemini equivalent here: the client stops local playback for cancel.\n */\nexport function translateCommand(raw: string, state: GeminiSendState): unknown[] {\n\tlet cmd: Command\n\ttry {\n\t\tcmd = JSON.parse(raw) as Command\n\t} catch {\n\t\treturn []\n\t}\n\tswitch (cmd.type) {\n\t\tcase 'response.create': {\n\t\t\tif (state.awaitingToolReply) {\n\t\t\t\tstate.awaitingToolReply = false\n\t\t\t\treturn []\n\t\t\t}\n\t\t\tconst text = cmd.response?.instructions\n\t\t\treturn text ? [userText(text, true)] : []\n\t\t}\n\t\tcase 'conversation.item.create': {\n\t\t\tconst item = cmd.item\n\t\t\tif (item?.type === 'function_call_output') {\n\t\t\t\tconst callId = item.call_id ?? ''\n\t\t\t\tstate.awaitingToolReply = true\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\ttoolResponse: {\n\t\t\t\t\t\t\tfunctionResponses: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tid: callId,\n\t\t\t\t\t\t\t\t\tname: state.callNames.get(callId) ?? '',\n\t\t\t\t\t\t\t\t\tresponse: { output: item.output ?? '' },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t}\n\t\t\tconst text = item?.content?.[0]?.text\n\t\t\treturn item?.role === 'system' && text ? [userText(text, false)] : []\n\t\t}\n\t\tdefault:\n\t\t\treturn []\n\t}\n}\n\ninterface GeminiServerMessage {\n\tsetupComplete?: unknown\n\tserverContent?: {\n\t\tinterrupted?: boolean\n\t\tturnComplete?: boolean\n\t\tinputTranscription?: { text?: string }\n\t\tmodelTurn?: { parts?: { inlineData?: { data?: string } }[] }\n\t}\n\ttoolCall?: { functionCalls?: { id?: string; name?: string; args?: Record<string, unknown> }[] }\n\terror?: { message?: string }\n}\n\n/** What the client needs from a server message: the shared events, plus audio and the end of a turn. */\nexport type GeminiEvent = ServerEvent | { type: 'audio'; data: string } | { type: 'turn_complete' }\n\n/** Reads one server message. Unknown or malformed messages give no events. */\nexport function parseGeminiMessage(data: unknown): GeminiEvent[] {\n\tif (typeof data !== 'object' || data === null) return []\n\tconst msg = data as GeminiServerMessage\n\tconst events: GeminiEvent[] = []\n\tif (msg.setupComplete !== undefined) events.push({ type: 'ready' })\n\tconst content = msg.serverContent\n\tif (content) {\n\t\tif (content.interrupted) events.push({ type: 'speech_started' })\n\t\tconst transcript = content.inputTranscription?.text?.trim()\n\t\tif (transcript) events.push({ type: 'transcript', text: transcript })\n\t\tfor (const part of content.modelTurn?.parts ?? []) {\n\t\t\tif (part.inlineData?.data) events.push({ type: 'audio', data: part.inlineData.data })\n\t\t}\n\t\tif (content.turnComplete) events.push({ type: 'turn_complete' })\n\t}\n\tfor (const call of msg.toolCall?.functionCalls ?? []) {\n\t\tif (call.id && call.name) {\n\t\t\tevents.push({ type: 'tool_call', name: call.name, callId: call.id, args: call.args ?? {} })\n\t\t}\n\t}\n\tif (msg.error?.message) events.push({ type: 'error', message: msg.error.message })\n\treturn events\n}\n\n/** Microphone samples (float, -1..1) to 16-bit little-endian PCM, as base64. */\nexport function floatToPcm16Base64(samples: Float32Array): string {\n\tconst bytes = new Uint8Array(samples.length * 2)\n\tconst view = new DataView(bytes.buffer)\n\tfor (let i = 0; i < samples.length; i++) {\n\t\tconst s = Math.max(-1, Math.min(1, samples[i]))\n\t\tview.setInt16(i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true)\n\t}\n\treturn bytesToBase64(bytes)\n}\n\n/** 16-bit little-endian PCM, as base64, to float samples (-1..1). */\nexport function pcm16Base64ToFloat(base64: string): Float32Array {\n\tconst bytes = base64ToBytes(base64)\n\tconst view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n\tconst out = new Float32Array(bytes.byteLength / 2)\n\tfor (let i = 0; i < out.length; i++) out[i] = view.getInt16(i * 2, true) / 0x8000\n\treturn out\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\tlet binary = ''\n\tfor (const byte of bytes) binary += String.fromCharCode(byte)\n\treturn btoa(binary)\n}\n\nfunction base64ToBytes(base64: string): Uint8Array {\n\tconst binary = atob(base64)\n\tconst bytes = new Uint8Array(binary.length)\n\tfor (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n\treturn bytes\n}\n\n/**\n * Fades the first `ms` milliseconds in, from silence. Used at the start of a model response only.\n * REVERSIBLE (2026-11-17, playback blocks).\n */\nexport function fadeIn(samples: Float32Array, sampleRate: number, ms: number): void {\n\tconst n = Math.min(Math.floor((sampleRate * ms) / 1000), samples.length)\n\tfor (let i = 0; i < n; i++) samples[i] *= i / n\n}\n\n/**\n * Fades the last `ms` milliseconds out, to silence. Used at the end of a model response only.\n * REVERSIBLE (2026-11-17, playback blocks).\n */\nexport function fadeOut(samples: Float32Array, sampleRate: number, ms: number): void {\n\tconst n = Math.min(Math.floor((sampleRate * ms) / 1000), samples.length)\n\tfor (let i = 0; i < n; i++) samples[samples.length - 1 - i] *= i / n\n}\n","/**\n * WebSocket connection to the Gemini Live API. Same interface as the OpenAI client (connect, send, replaceTrack,\n * close) and the same normalized events, so the voice session does not know which provider it talks to.\n * The browser calls the API directly with the key it was given (development setup, no backend yet).\n * REVERSIBLE (2026-11-17, gemini provider): delete this file and gemini-protocol.ts to remove Gemini support.\n */\nimport {\n\ttype GeminiSendState,\n\tfadeIn,\n\tfadeOut,\n\tfloatToPcm16Base64,\n\tgeminiSetup,\n\tliveUrl,\n\tnewSendState,\n\tparseGeminiMessage,\n\tpcm16Base64ToFloat,\n\ttranslateCommand,\n} from './gemini-protocol'\nimport type { RealtimeCallbacks, RealtimeConnectOptions } from './realtime-client'\nimport type { RealtimeSettings, ServerEvent } from './realtime-protocol'\n\nconst READY_TIMEOUT_MS = 10000\nconst CAPTURE_RATE = 16000\nconst PLAYBACK_RATE = 24000\n// REVERSIBLE (2026-11-17, playback blocks): model audio is played in blocks of about 150 ms, with a fade only at the\n// start and end of each response. Fades on every chunk made audible dips inside the speech.\nconst BLOCK_SECONDS = 0.15\nconst BLOCK_SAMPLES = Math.round(PLAYBACK_RATE * BLOCK_SECONDS)\nconst EDGE_FADE_MS = 5\n/** Collects microphone samples in blocks of about 128 ms before sending them. */\nconst CAPTURE_BLOCK = 2048\n\nconst CAPTURE_WORKLET = `\nclass PaCapture extends AudioWorkletProcessor {\n constructor() { super(); this.block = []; this.size = 0 }\n process(inputs) {\n const channel = inputs[0] && inputs[0][0];\n if (channel) {\n this.block.push(channel.slice(0));\n this.size += channel.length;\n if (this.size >= ${CAPTURE_BLOCK}) {\n const out = new Float32Array(this.size);\n let at = 0;\n for (const part of this.block) { out.set(part, at); at += part.length; }\n this.port.postMessage(out, [out.buffer]);\n this.block = []; this.size = 0;\n }\n }\n return true;\n }\n}\nregisterProcessor('pa-capture', PaCapture);\n`\n\nexport class GeminiLiveClient {\n\t#callbacks: RealtimeCallbacks\n\t#ws: WebSocket | null = null\n\t#ctx: AudioContext | null = null\n\t// REVERSIBLE (2026-11-17, playback fix): plays the model's audio at the device's own rate, apart from the 16 kHz capture context.\n\t#playCtx: AudioContext | null = null\n\t#capture: AudioWorkletNode | null = null\n\t#source: MediaStreamAudioSourceNode | null = null\n\t#sending = false\n\t#closing = false\n\t#onReady: (() => void) | null = null\n\t#send: GeminiSendState = newSendState()\n\t#playing: AudioBufferSourceNode[] = []\n\t#nextPlayTime = 0\n\t#inTurn = false\n\t// REVERSIBLE (2026-11-17, playback blocks)\n\t#pending: Float32Array[] = []\n\t#pendingLength = 0\n\t#turnStart = true\n\n\tconstructor(callbacks: RealtimeCallbacks) {\n\t\tthis.#callbacks = callbacks\n\t}\n\n\t/** Opens the connection. Resolves once the server confirms the setup; rejects on any failure. */\n\tasync connect(options: RealtimeConnectOptions): Promise<void> {\n\t\ttry {\n\t\t\tawait this.#open(options.apiKey, options.settings)\n\t\t\tthis.#ctx = new AudioContext({ sampleRate: CAPTURE_RATE })\n\t\t\tawait this.#ctx.resume()\n\t\t\tthis.#playCtx = new AudioContext()\n\t\t\tawait this.#playCtx.resume()\n\t\t\t// Mobile browsers often start AudioContext suspended until a fresh resume after setup.\n\t\t\tif (this.#ctx.state !== 'running') await this.#ctx.resume()\n\t\t\tif (this.#playCtx.state !== 'running') await this.#playCtx.resume()\n\t\t\tawait this.#startCapture(options.track)\n\t\t} catch (error) {\n\t\t\tthis.close()\n\t\t\tthrow error\n\t\t}\n\t\tawait this.#ready\n\t}\n\n\t#ready: Promise<void> = Promise.resolve()\n\n\t#open(apiKey: string, settings: RealtimeSettings): Promise<void> {\n\t\tconst ws = new WebSocket(liveUrl(apiKey))\n\t\tws.binaryType = 'blob'\n\t\tthis.#ws = ws\n\t\tthis.#ready = new Promise<void>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => reject(new Error('session timeout')), READY_TIMEOUT_MS)\n\t\t\tthis.#onReady = () => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tresolve()\n\t\t\t}\n\t\t})\n\t\tws.onmessage = (event: MessageEvent<unknown>) => void this.#receive(event.data)\n\t\tws.onclose = () => {\n\t\t\tif (!this.#closing) this.#callbacks.onClosed()\n\t\t}\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tws.onopen = () => {\n\t\t\t\tws.send(geminiSetup(settings))\n\t\t\t\tresolve()\n\t\t\t}\n\t\t\tws.onerror = () => reject(new Error('connection failed'))\n\t\t})\n\t}\n\n\tasync #receive(data: unknown): Promise<void> {\n\t\tconst text = data instanceof Blob ? await data.text() : String(data)\n\t\tlet parsed: unknown\n\t\ttry {\n\t\t\tparsed = JSON.parse(text)\n\t\t} catch {\n\t\t\treturn\n\t\t}\n\t\tfor (const event of parseGeminiMessage(parsed)) this.#handle(event)\n\t}\n\n\t#handle(event: ReturnType<typeof parseGeminiMessage>[number]): void {\n\t\tswitch (event.type) {\n\t\t\tcase 'audio':\n\t\t\t\tthis.#play(event.data)\n\t\t\t\tif (!this.#inTurn) {\n\t\t\t\t\tthis.#inTurn = true\n\t\t\t\t\tthis.#callbacks.onEvent({ type: 'response_started' })\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase 'turn_complete':\n\t\t\t\tthis.#inTurn = false\n\t\t\t\tthis.#flush(true)\n\t\t\t\tthis.#turnStart = true\n\t\t\t\tvoid this.#resumeAudio()\n\t\t\t\tthis.#callbacks.onEvent({ type: 'response_done' })\n\t\t\t\treturn\n\t\t\tcase 'speech_started':\n\t\t\t\tthis.#stopPlayback()\n\t\t\t\tthis.#inTurn = false\n\t\t\t\tvoid this.#resumeAudio()\n\t\t\t\tthis.#callbacks.onEvent({ type: 'speech_started' })\n\t\t\t\treturn\n\t\t\tcase 'ready':\n\t\t\t\tthis.#onReady?.()\n\t\t\t\tvoid this.#resumeAudio()\n\t\t\t\tthis.#callbacks.onEvent({ type: 'ready' })\n\t\t\t\treturn\n\t\t\tcase 'tool_call':\n\t\t\t\tthis.#send.callNames.set(event.callId, event.name)\n\t\t\t\tvoid this.#resumeAudio()\n\t\t\t\tthis.#callbacks.onEvent(event as ServerEvent)\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tthis.#callbacks.onEvent(event as ServerEvent)\n\t\t}\n\t}\n\n\t/** Mobile and Bluetooth speaker paths often suspend AudioContext; resume on every turn edge. */\n\tasync #resumeAudio(): Promise<void> {\n\t\ttry {\n\t\t\tif (this.#ctx && this.#ctx.state !== 'running') await this.#ctx.resume()\n\t\t\tif (this.#playCtx && this.#playCtx.state !== 'running') await this.#playCtx.resume()\n\t\t} catch {\n\t\t\t// Resume can fail if the context was closed; the next connect recreates it.\n\t\t}\n\t}\n\n\t/** Sends a command in the session's shape, translated for Gemini. Cancel stops the local playback. */\n\tsend(message: string): void {\n\t\tif (this.#ws?.readyState !== WebSocket.OPEN) return\n\t\tif ((JSON.parse(message) as { type?: string }).type === 'response.cancel') this.#stopPlayback()\n\t\tfor (const out of translateCommand(message, this.#send)) this.#ws.send(JSON.stringify(out))\n\t}\n\n\t/** Swaps the microphone track. A null track stops sending audio (mute). */\n\tasync replaceTrack(track: MediaStreamTrack | null): Promise<void> {\n\t\tif (!track) {\n\t\t\tthis.#sending = false\n\t\t\tthis.#source?.disconnect()\n\t\t\tthis.#source = null\n\t\t\treturn\n\t\t}\n\t\tawait this.#startCapture(track)\n\t}\n\n\tclose(): void {\n\t\tthis.#closing = true\n\t\tthis.#ws?.close()\n\t\tthis.#stopPlayback()\n\t\tthis.#source?.disconnect()\n\t\tthis.#capture?.disconnect()\n\t\tvoid this.#ctx?.close()\n\t\tvoid this.#playCtx?.close()\n\t\tthis.#playCtx = null\n\t\tthis.#ws = null\n\t\tthis.#ctx = null\n\t\tthis.#capture = null\n\t\tthis.#source = null\n\t\tthis.#sending = false\n\t}\n\n\tasync #startCapture(track: MediaStreamTrack): Promise<void> {\n\t\tconst ctx = this.#ctx\n\t\tif (!ctx) return\n\t\tif (!this.#capture) {\n\t\t\tconst url = URL.createObjectURL(\n\t\t\t\tnew Blob([CAPTURE_WORKLET], { type: 'application/javascript' })\n\t\t\t)\n\t\t\tawait ctx.audioWorklet.addModule(url)\n\t\t\tURL.revokeObjectURL(url)\n\t\t\tconst capture = new AudioWorkletNode(ctx, 'pa-capture')\n\t\t\tconst silent = new GainNode(ctx, { gain: 0 })\n\t\t\tcapture.connect(silent)\n\t\t\tsilent.connect(ctx.destination)\n\t\t\tcapture.port.onmessage = (event: MessageEvent<Float32Array>) => this.#sendAudio(event.data)\n\t\t\tthis.#capture = capture\n\t\t}\n\t\tthis.#source?.disconnect()\n\t\tthis.#source = ctx.createMediaStreamSource(new MediaStream([track]))\n\t\tthis.#source.connect(this.#capture)\n\t\tthis.#sending = true\n\t}\n\n\t#sendAudio(samples: Float32Array): void {\n\t\tif (!this.#sending || this.#ws?.readyState !== WebSocket.OPEN) return\n\t\tthis.#ws.send(\n\t\t\tJSON.stringify({\n\t\t\t\trealtimeInput: {\n\t\t\t\t\taudio: { data: floatToPcm16Base64(samples), mimeType: `audio/pcm;rate=${CAPTURE_RATE}` },\n\t\t\t\t},\n\t\t\t})\n\t\t)\n\t}\n\n\t#play(base64: string): void {\n\t\tif (!this.#playCtx) return\n\t\tthis.#pending.push(pcm16Base64ToFloat(base64))\n\t\tthis.#pendingLength += this.#pending[this.#pending.length - 1].length\n\t\tif (this.#pendingLength >= BLOCK_SAMPLES) this.#flush(false)\n\t}\n\n\t/** Schedules everything queued as one buffer. The start of a response fades in, and the end fades out when final. */\n\t#flush(final: boolean): void {\n\t\tconst ctx = this.#playCtx\n\t\tif (!ctx || this.#pendingLength === 0) return\n\t\tconst samples = new Float32Array(this.#pendingLength)\n\t\tlet at = 0\n\t\tfor (const part of this.#pending) {\n\t\t\tsamples.set(part, at)\n\t\t\tat += part.length\n\t\t}\n\t\tthis.#pending = []\n\t\tthis.#pendingLength = 0\n\t\tif (this.#turnStart) fadeIn(samples, PLAYBACK_RATE, EDGE_FADE_MS)\n\t\tif (final) fadeOut(samples, PLAYBACK_RATE, EDGE_FADE_MS)\n\t\tthis.#turnStart = false\n\n\t\tconst buffer = ctx.createBuffer(1, samples.length, PLAYBACK_RATE)\n\t\tbuffer.getChannelData(0).set(samples)\n\t\tconst node = ctx.createBufferSource()\n\t\tnode.buffer = buffer\n\t\tnode.connect(ctx.destination)\n\t\tconst now = ctx.currentTime\n\t\t// Nothing is queued any more (a gap in the stream): start a little later so the next block can arrive.\n\t\tif (this.#nextPlayTime <= now) this.#nextPlayTime = now + 0.05\n\t\tconst start = this.#nextPlayTime\n\t\tnode.start(start)\n\t\tthis.#nextPlayTime = start + buffer.duration\n\t\tthis.#playing.push(node)\n\t\tnode.onended = () => {\n\t\t\tthis.#playing = this.#playing.filter((n) => n !== node)\n\t\t}\n\t}\n\n\t#stopPlayback(): void {\n\t\tfor (const node of this.#playing) {\n\t\t\ttry {\n\t\t\t\tnode.stop()\n\t\t\t} catch {\n\t\t\t\t// already stopped\n\t\t\t}\n\t\t}\n\t\tthis.#playing = []\n\t\tthis.#pending = []\n\t\tthis.#pendingLength = 0\n\t\tthis.#turnStart = true\n\t\tthis.#nextPlayTime = this.#playCtx?.currentTime ?? 0\n\t}\n}\n","/**\n * WebRTC connection to the OpenAI Realtime API. The browser calls the API directly with the key it was given\n * (development setup, no backend yet). Microphone and speech travel on media tracks; JSON events on a data channel.\n */\nimport {\n\ttype RealtimeSettings,\n\ttype ServerEvent,\n\tcallSessionConfig,\n\tparseServerEvent,\n} from './realtime-protocol'\n\nconst CALLS_URL = 'https://api.openai.com/v1/realtime/calls'\nconst READY_TIMEOUT_MS = 10000\n\nexport interface RealtimeCallbacks {\n\tonEvent: (event: ServerEvent) => void\n\tonClosed: () => void\n}\n\nexport interface RealtimeConnectOptions {\n\tapiKey: string\n\tsettings: RealtimeSettings\n\ttrack: MediaStreamTrack\n}\n\nexport class RealtimeClient {\n\t#callbacks: RealtimeCallbacks\n\t#pc: RTCPeerConnection | null = null\n\t#channel: RTCDataChannel | null = null\n\t#audio: HTMLAudioElement | null = null\n\n\tconstructor(callbacks: RealtimeCallbacks) {\n\t\tthis.#callbacks = callbacks\n\t}\n\n\t/** Opens the call. Resolves once the server confirms the session; rejects on any failure. */\n\tasync connect(options: RealtimeConnectOptions): Promise<void> {\n\t\tconst pc = new RTCPeerConnection()\n\t\tthis.#pc = pc\n\t\tconst audio = document.createElement('audio')\n\t\taudio.autoplay = true\n\t\t// Mobile Safari needs playsInline and a connected element before remote audio can start.\n\t\taudio.setAttribute('playsinline', 'true')\n\t\t;(audio as HTMLAudioElement & { playsInline?: boolean }).playsInline = true\n\t\taudio.setAttribute('aria-hidden', 'true')\n\t\taudio.style.display = 'none'\n\t\tdocument.body.appendChild(audio)\n\t\tthis.#audio = audio\n\t\tpc.ontrack = (event) => {\n\t\t\taudio.srcObject = event.streams[0] ?? null\n\t\t\tvoid audio.play().catch((error) => {\n\t\t\t\tconsole.warn('[page-agent voice] remote audio playback blocked', error)\n\t\t\t})\n\t\t}\n\t\tpc.addTrack(options.track)\n\n\t\tconst channel = pc.createDataChannel('oai-events')\n\t\tthis.#channel = channel\n\t\tconst ready = new Promise<void>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => reject(new Error('session timeout')), READY_TIMEOUT_MS)\n\t\t\tchannel.onmessage = (message) => {\n\t\t\t\tconst event = parseServerEvent(String(message.data))\n\t\t\t\tif (event.type === 'ready') {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\tresolve()\n\t\t\t\t}\n\t\t\t\tthis.#callbacks.onEvent(event)\n\t\t\t}\n\t\t})\n\t\tchannel.onclose = () => this.#callbacks.onClosed()\n\n\t\tconst offer = await pc.createOffer()\n\t\tawait pc.setLocalDescription(offer)\n\t\tconst form = new FormData()\n\t\tform.set('sdp', offer.sdp ?? '')\n\t\tform.set('session', callSessionConfig(options.settings))\n\t\tconst response = await fetch(CALLS_URL, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { Authorization: `Bearer ${options.apiKey}` },\n\t\t\tbody: form,\n\t\t})\n\t\tif (!response.ok) throw new Error(`realtime call failed: ${response.status}`)\n\t\tawait pc.setRemoteDescription({ type: 'answer', sdp: await response.text() })\n\t\tawait ready\n\t}\n\n\t/** Sends a JSON command on the data channel, if the channel is open. */\n\tsend(message: string): void {\n\t\tif (this.#channel?.readyState === 'open') this.#channel.send(message)\n\t}\n\n\t/** Swaps the microphone track (used after mute and unmute). A null track stops sending audio. */\n\tasync replaceTrack(track: MediaStreamTrack | null): Promise<void> {\n\t\tconst sender = this.#pc?.getSenders().find((s) => s.track === null || s.track.kind === 'audio')\n\t\tawait sender?.replaceTrack(track)\n\t}\n\n\tclose(): void {\n\t\tthis.#channel?.close()\n\t\tthis.#pc?.close()\n\t\tthis.#audio?.remove()\n\t\tthis.#channel = null\n\t\tthis.#pc = null\n\t\tthis.#audio = null\n\t}\n}\n","import defaultPrompt from './prompts/voice.md?raw'\n\n/**\n * The language rule the panel's configured language imposes on the voice. Always in English, like the prompt.\n * It is added after the prompt, so the model replies in the panel's language even if the user speaks another one.\n */\nexport function languageRule(language: string): string {\n\tconst name = language === 'pt-BR' ? 'Brazilian Portuguese' : 'English'\n\treturn `Always reply in ${name}, whatever language the user speaks. The panel's language is fixed.`\n}\n\n/**\n * The voice model's system prompt. A custom text is added after the default one, which is kept whole. It replaces the\n * default only when `override` is true, like `overrideSystemPrompt` does for the agent. `null` or empty means the default.\n * REVERSIBLE (2026-11-23, system prompt override): the `override` parameter and the merge.\n */\nexport function resolveVoicePrompt(custom: string | null | undefined, override = false): string {\n\tconst text = custom?.trim()\n\tif (!text) return defaultPrompt\n\treturn override ? text : `${defaultPrompt}\\n\\n${text}`\n}\n","/**\n * Voice mode of the panel. The only owner of the voice state.\n * The voice model talks with the user and hands page actions to the agent through `run_task`.\n * The panel gives it reports from the agent; the session queues them so they never overlap a spoken answer.\n */\nimport type { MicState } from '../panel/microphone'\nimport {\n\tANSWER_QUESTION,\n\tEXECUTE_JS,\n\tGET_CONTEXT,\n\tRUN_TASK,\n\ttype RealtimeSettings,\n\ttype ServerEvent,\n\ttype VoiceReport,\n\tcancelResponseCommand,\n\treportCommand,\n\ttoolResultCommands,\n} from './realtime-protocol'\n\nexport type VoiceState = 'off' | 'connecting' | 'listening' | 'speaking' | 'muted' | 'error'\nexport type VoiceError = 'no-key' | 'mic-denied' | 'mic-unsupported' | 'mic-busy' | 'connect-failed'\n\n/** Result given to the model when the agent is already busy. */\nexport const BUSY_OUTPUT =\n\t'O agente está ocupado com outra tarefa. Avise o usuário e não repita o pedido agora.'\n/** Result given to the model when the task was started. */\nexport const STARTED_OUTPUT = 'Tarefa iniciada no agente. Confirme ao usuário em uma frase.'\n/** Result when a mid-task spoken note was delivered to the running agent. */\nexport const NOTE_OUTPUT =\n\t'Mensagem do usuário entregue ao agente em execução. Confirme ao usuário em uma frase.'\n/** Result when answer_question is used without a pending ask. */\nexport const NO_PENDING_QUESTION_OUTPUT =\n\t'Não há pergunta pendente do agente. Se o usuário pediu uma tarefa, use run_task.'\n/** Result when the answer was delivered to the agent. */\nexport const ANSWERED_OUTPUT = 'Resposta enviada ao agente. Confirme ao usuário em uma frase.'\n/** Empty tool args must still get a tool result, or Gemini Live waits forever. */\nexport const EMPTY_TASK_OUTPUT = 'No task was given. Ask the user what to do, then call run_task.'\nexport const EMPTY_ANSWER_OUTPUT =\n\t'No answer was given. Ask the user again, then call answer_question with their reply.'\n/** Default cap so a stuck page tree read cannot freeze the voice session. */\nexport const DEFAULT_CONTEXT_TIMEOUT_MS = 8000\n\n/** The part of the microphone control the voice session uses. */\nexport interface VoiceMic {\n\treadonly state: MicState\n\treadonly stream: MediaStream | null\n\treadonly label: string\n\treadonly hardwareMuted: boolean\n\tenable(deviceId?: string): Promise<void>\n\tcycleInput(): Promise<boolean>\n\tsetMuted(muted: boolean): void\n\tdisable(): void\n}\n\n/** The part of the realtime client the voice session uses. */\nexport interface VoiceClient {\n\tconnect(options: {\n\t\tapiKey: string\n\t\tsettings: RealtimeSettings\n\t\ttrack: MediaStreamTrack\n\t}): Promise<void>\n\tsend(message: string): void\n\treplaceTrack(track: MediaStreamTrack | null): Promise<void>\n\tclose(): void\n}\n\nexport interface VoiceSessionOptions {\n\tapiKey?: string\n\tsettings: RealtimeSettings\n\tmic: VoiceMic\n\tcreateClient: (callbacks: {\n\t\tonEvent: (event: ServerEvent) => void\n\t\tonClosed: () => void\n\t}) => VoiceClient\n\t/** Starts a task in the agent. Returns false when the agent is busy. */\n\tonTask: (task: string) => boolean\n\t/**\n\t * Runs a script for the voice and returns the text the model receives. The panel refuses it with a\n\t * message while the agent is running.\n\t */\n\tonScript?: (script: string) => Promise<string>\n\t/** True while the agent is waiting on ask_user. */\n\tisWaitingForAnswer?: () => boolean\n\t/**\n\t * Delivers the user's spoken answer to a pending ask_user. Returns false when there is no\n\t * pending question.\n\t */\n\tonAnswer?: (answer: string) => boolean\n\t/**\n\t * Delivers a spoken note to the running agent (observation). Used when run_task is refused as busy.\n\t * Returns false when no running task can take the note.\n\t */\n\tonNote?: (text: string) => boolean\n\t/**\n\t * Read-only page context slice for the voice. Allowed while the agent is running.\n\t */\n\tonGetContext?: (args: {\n\t\tyMin?: number\n\t\tyMax?: number\n\t\tmaxLines?: number\n\t\tquery?: string\n\t}) => Promise<string>\n\t/** Override get_context hang timeout (tests). Default DEFAULT_CONTEXT_TIMEOUT_MS. */\n\tcontextTimeoutMs?: number\n\tonChange: () => void\n}\n\n/** Errors about cancelling a response that is not running are harmless and must not end the call. */\nfunction isHarmlessCancelError(message: string): boolean {\n\treturn /cancel/i.test(message)\n}\n\nexport class VoiceSession {\n\t#options: VoiceSessionOptions\n\t#state: VoiceState = 'off'\n\t#error: VoiceError | null = null\n\t#client: VoiceClient | null = null\n\t#wanted = false\n\t/** Reports that arrived while the model was speaking. */\n\t#queue: VoiceReport[] = []\n\n\tconstructor(options: VoiceSessionOptions) {\n\t\tthis.#options = options\n\t}\n\n\tget state(): VoiceState {\n\t\treturn this.#state\n\t}\n\n\tget error(): VoiceError | null {\n\t\treturn this.#error\n\t}\n\n\tget muted(): boolean {\n\t\treturn this.#state === 'muted'\n\t}\n\n\t/** The user turned voice on: ask for the microphone, then open the realtime call. */\n\tasync enable(): Promise<void> {\n\t\tconst { apiKey, mic } = this.#options\n\t\tif (!apiKey) return this.#fail('no-key')\n\t\tthis.#wanted = true\n\t\tthis.#error = null\n\t\tthis.#set('connecting')\n\t\tawait mic.enable()\n\t\tif (!this.#wanted) return\n\t\tif (mic.state === 'denied') return this.#fail('mic-denied')\n\t\tif (mic.state === 'busy') return this.#fail('mic-busy')\n\t\tif (mic.state === 'unsupported') return this.#fail('mic-unsupported')\n\t\tconst track = mic.stream?.getAudioTracks()[0]\n\t\tif (!track) return this.#fail('mic-denied')\n\t\tconst client = this.#options.createClient({\n\t\t\tonEvent: (event) => this.#onEvent(event),\n\t\t\tonClosed: () => this.#fail('connect-failed'),\n\t\t})\n\t\tthis.#client = client\n\t\ttry {\n\t\t\tawait client.connect({ apiKey, settings: this.#options.settings, track })\n\t\t} catch {\n\t\t\tthis.#client = null\n\t\t\tthis.#fail('connect-failed')\n\t\t\treturn\n\t\t}\n\t\tif (this.#wanted && this.#state === 'connecting') this.#set('listening')\n\t}\n\n\t/**\n\t * Cycle to the next microphone while the call is open and send that track.\n\t * Returns false when there is no other device or the session is not live.\n\t */\n\tasync changeInput(): Promise<boolean> {\n\t\tif (this.#state !== 'listening' && this.#state !== 'speaking' && this.#state !== 'connecting') {\n\t\t\treturn false\n\t\t}\n\t\tconst changed = await this.#options.mic.cycleInput()\n\t\tif (!changed) return false\n\t\tconst track = this.#options.mic.stream?.getAudioTracks()[0]\n\t\tif (!track) {\n\t\t\tthis.#fail('mic-denied')\n\t\t\treturn false\n\t\t}\n\t\tawait this.#client?.replaceTrack(track)\n\t\tthis.#options.onChange()\n\t\treturn true\n\t}\n\n\t/** The user turned voice off: close the call and release the microphone. */\n\tdisable(): void {\n\t\tthis.#wanted = false\n\t\tthis.#queue = []\n\t\tthis.#client?.close()\n\t\tthis.#client = null\n\t\tthis.#options.mic.disable()\n\t\tthis.#error = null\n\t\tthis.#set('off')\n\t}\n\n\t/**\n\t * Mute stops the microphone and the audio sent, and stops the model if it is speaking.\n\t * The call stays open until the user goes back to text.\n\t */\n\tasync setMuted(muted: boolean): Promise<void> {\n\t\tif (muted) {\n\t\t\tif (this.#state === 'speaking') this.#client?.send(cancelResponseCommand())\n\t\t\tthis.#queue = []\n\t\t\tthis.#options.mic.setMuted(true)\n\t\t\tawait this.#client?.replaceTrack(null)\n\t\t\tthis.#set('muted')\n\t\t\treturn\n\t\t}\n\t\tthis.#options.mic.setMuted(false)\n\t\tawait this.#options.mic.enable()\n\t\tconst track = this.#options.mic.stream?.getAudioTracks()[0]\n\t\tif (track) await this.#client?.replaceTrack(track)\n\t\tthis.#set('listening')\n\t}\n\n\t/**\n\t * Gives the voice a report from the agent. It is spoken when the model is not speaking already.\n\t * Ignored while voice is off, muted or in error.\n\t */\n\treport(report: VoiceReport): void {\n\t\tif (!this.#client || (this.#state !== 'listening' && this.#state !== 'speaking')) return\n\t\tif (!report.text.trim()) return\n\t\tif (this.#state === 'speaking') {\n\t\t\tthis.#queue.push(report)\n\t\t\treturn\n\t\t}\n\t\tthis.#client.send(reportCommand(report))\n\t\tthis.#set('speaking')\n\t}\n\n\t#onEvent(event: ServerEvent): void {\n\t\tif (this.#state === 'off' || this.#state === 'muted') return\n\t\tswitch (event.type) {\n\t\t\tcase 'ready':\n\t\t\t\tif (this.#state === 'connecting') this.#set('listening')\n\t\t\t\treturn\n\t\t\tcase 'transcript':\n\t\t\t\t// What the user says is conversation: the voice model answers it. Only run_task reaches the agent.\n\t\t\t\treturn\n\t\t\tcase 'speech_started':\n\t\t\t\t// The server cuts the model's voice when the user talks. The state changes when the response ends.\n\t\t\t\treturn\n\t\t\tcase 'response_started':\n\t\t\t\tthis.#set('speaking')\n\t\t\t\treturn\n\t\t\tcase 'response_done':\n\t\t\t\tthis.#flushQueue()\n\t\t\t\treturn\n\t\t\tcase 'tool_call':\n\t\t\t\tthis.#handleToolCall(event.name, event.callId, event.args)\n\t\t\t\treturn\n\t\t\tcase 'error':\n\t\t\t\tif (isHarmlessCancelError(event.message)) return\n\t\t\t\tthis.#fail('connect-failed')\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\treturn\n\t\t}\n\t}\n\n\t#handleToolCall(name: string, callId: string, args: Record<string, unknown>): void {\n\t\t// Every tool_call must get a tool result. Gemini Live waits forever otherwise; only\n\t\t// deactivate/activate recovers the session.\n\t\tif (name === ANSWER_QUESTION) {\n\t\t\tconst answer = typeof args.answer === 'string' ? args.answer.trim() : ''\n\t\t\tif (!answer) {\n\t\t\t\tthis.#answer(callId, EMPTY_ANSWER_OUTPUT)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst delivered = this.#options.onAnswer?.(answer) ?? false\n\t\t\tthis.#answer(callId, delivered ? ANSWERED_OUTPUT : NO_PENDING_QUESTION_OUTPUT)\n\t\t\treturn\n\t\t}\n\t\tif (name === RUN_TASK) {\n\t\t\tconst task = typeof args.task === 'string' ? args.task.trim() : ''\n\t\t\tif (!task) {\n\t\t\t\tthis.#answer(callId, EMPTY_TASK_OUTPUT)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// A pending ask_user must receive the spoken answer through the answer path.\n\t\t\tif (this.#options.isWaitingForAnswer?.()) {\n\t\t\t\tconst delivered = this.#options.onAnswer?.(task) ?? this.#options.onTask(task)\n\t\t\t\tthis.#answer(callId, delivered ? ANSWERED_OUTPUT : NO_PENDING_QUESTION_OUTPUT)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (this.#options.onTask(task)) {\n\t\t\t\tthis.#answer(callId, STARTED_OUTPUT)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Task already running: deliver as a note so the user is not stuck repeating themselves.\n\t\t\tif (this.#options.onNote?.(task)) {\n\t\t\t\tthis.#answer(callId, NOTE_OUTPUT)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.#answer(callId, BUSY_OUTPUT)\n\t\t\treturn\n\t\t}\n\t\tif (name === GET_CONTEXT) {\n\t\t\tif (!this.#options.onGetContext) {\n\t\t\t\tthis.#answer(callId, 'get_context is not available in this session.')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvoid this.#runGetContext(callId, args)\n\t\t\treturn\n\t\t}\n\t\tif (name === EXECUTE_JS) {\n\t\t\tconst script = typeof args.script === 'string' ? args.script : ''\n\t\t\tif (!this.#options.onScript) {\n\t\t\t\tthis.#answer(callId, 'Running scripts is not available in this session.')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (!script) {\n\t\t\t\tthis.#answer(callId, 'No script was given.')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvoid this.#runScript(callId, script)\n\t\t\treturn\n\t\t}\n\t\tthis.#answer(callId, `Unknown tool ${name}.`)\n\t}\n\n\tasync #runGetContext(callId: string, args: Record<string, unknown>): Promise<void> {\n\t\tconst client = this.#client\n\t\tconst run = this.#options.onGetContext\n\t\tif (!client || !run) {\n\t\t\tthis.#answer(callId, 'get_context is not available in this session.')\n\t\t\treturn\n\t\t}\n\t\tconst num = (value: unknown) =>\n\t\t\ttypeof value === 'number' && Number.isFinite(value) ? value : undefined\n\t\tconst timeoutMs = Math.max(50, this.#options.contextTimeoutMs ?? DEFAULT_CONTEXT_TIMEOUT_MS)\n\t\tlet output: string\n\t\ttry {\n\t\t\tconst result = run({\n\t\t\t\tyMin: num(args.y_min),\n\t\t\t\tyMax: num(args.y_max),\n\t\t\t\tmaxLines: num(args.max_lines),\n\t\t\t\tquery: typeof args.query === 'string' ? args.query : undefined,\n\t\t\t})\n\t\t\toutput = await Promise.race([\n\t\t\t\tresult,\n\t\t\t\tnew Promise<string>((resolve) =>\n\t\t\t\t\tsetTimeout(\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tresolve(\n\t\t\t\t\t\t\t\t'get_context timed out. Tell the user briefly and try a smaller y band or query.'\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\ttimeoutMs\n\t\t\t\t\t)\n\t\t\t\t),\n\t\t\t])\n\t\t} catch (error) {\n\t\t\toutput = `get_context failed: ${error instanceof Error ? error.message : 'unknown error'}`\n\t\t}\n\t\tif (this.#client !== client) return\n\t\tthis.#answer(callId, output.slice(0, 2500))\n\t}\n\n\t/** Sends the result of a tool call back to the model, then the model speaks again. */\n\t#answer(callId: string, output: string): void {\n\t\tfor (const message of toolResultCommands(callId, output)) this.#client?.send(message)\n\t\tthis.#set('speaking')\n\t}\n\n\tasync #runScript(callId: string, script: string): Promise<void> {\n\t\tconst client = this.#client\n\t\tconst run = this.#options.onScript\n\t\tif (!client || !run) {\n\t\t\tthis.#answer(callId, 'Running scripts is not available in this session.')\n\t\t\treturn\n\t\t}\n\t\tlet output: string\n\t\ttry {\n\t\t\toutput = await run(script)\n\t\t} catch (error) {\n\t\t\toutput = `The script failed: ${error instanceof Error ? error.message : 'unknown error'}`\n\t\t}\n\t\t// The call may have been turned off while the script ran: then there is no one to answer.\n\t\tif (this.#client !== client) return\n\t\tthis.#answer(callId, output)\n\t}\n\n\t#flushQueue(): void {\n\t\tif (this.#state !== 'speaking') return\n\t\tconst next = this.#queue.shift()\n\t\tif (next) {\n\t\t\tthis.#client?.send(reportCommand(next))\n\t\t\treturn\n\t\t}\n\t\tthis.#set('listening')\n\t}\n\n\t#fail(error: VoiceError): void {\n\t\tthis.#error = error\n\t\tthis.#wanted = false\n\t\tthis.#queue = []\n\t\tthis.#client?.close()\n\t\tthis.#client = null\n\t\tthis.#options.mic.disable()\n\t\tthis.#set('error')\n\t}\n\n\t#set(state: VoiceState): void {\n\t\tif (this.#state === state) return\n\t\tthis.#state = state\n\t\tthis.#options.onChange()\n\t}\n}\n","export function truncate(text: string, maxLength: number): string {\n\tif (text.length > maxLength) {\n\t\treturn text.substring(0, maxLength) + '...'\n\t}\n\treturn text\n}\n\n/**\n * Escape HTML special characters to prevent XSS and rendering issues\n */\nexport function escapeHtml(text: string): string {\n\treturn text\n\t\t.replace(/&/g, '&')\n\t\t.replace(/</g, '<')\n\t\t.replace(/>/g, '>')\n\t\t.replace(/\"/g, '"')\n\t\t.replace(/'/g, ''')\n}\n","/* Page Agent panel. Design from the modern renderer; dark by default, light when the system asks for it. */\n\n.wrapper {\n\toverscroll-behavior: contain;\n\t--pa-fg: #f4f3ee;\n\t--pa-muted: #aaa9a1;\n\t--pa-accent: #fa8d45;\n\t--pa-surface: #191918;\n\t--pa-raised: #20201e;\n\t--pa-line: rgba(244, 243, 238, 0.12);\n\t--pa-ok: #b1d8b8;\n\t--pa-warn: #ead39a;\n\t--pa-err: #ffb9a9;\n\t--pa-radius: 18px;\n\t--pa-c-keyword: #fa8d45;\n\t--pa-c-string: #b1d8b8;\n\t--pa-c-number: #ead39a;\n\t--pa-c-key: #9ec5f0;\n\t--pa-c-bool: #ffb9a9;\n\t--pa-c-comment: #7d7c75;\n\t--pa-c-name: #f4f3ee;\n\t--pa-c-punct: #aaa9a1;\n\n\tposition: fixed;\n\tbottom: 100px;\n\tleft: 0;\n\tright: 0;\n\tmargin: 0 auto;\n\ttransform: translateY(20px);\n\topacity: 0;\n\tz-index: 2147483642;\n\tbox-sizing: border-box;\n\t/* 100% of the fixed containing block — avoids the classic 100vw horizontal overflow on mobile. */\n\twidth: min(414px, calc(100% - 24px));\n\tmax-height: min(640px, calc(100svh - 120px));\n\tdisplay: none;\n\tflex-direction: column;\n\toverflow: hidden;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: var(--pa-radius);\n\tbackground: var(--pa-surface);\n\tcolor: var(--pa-fg);\n\tbox-shadow: 0 16px 40px rgba(0, 0, 0, 0.35);\n\tfont:\n\t\t13px/1.4 system-ui,\n\t\t-apple-system,\n\t\t'Segoe UI',\n\t\tsans-serif;\n\ttransition:\n\t\topacity 0.2s ease,\n\t\ttransform 0.2s ease,\n\t\tbox-shadow 0.3s ease,\n\t\twidth 0.2s ease;\n}\n\n@media (min-width: 481px) {\n\t.wrapper[data-mode='skills-studio'] {\n\t\twidth: min(560px, calc(100vw - 24px));\n\t}\n}\n\n.wrapper *,\n.wrapper *::before,\n.wrapper *::after {\n\tbox-sizing: border-box;\n}\n\n.wrapper[data-state='running'] {\n\tbox-shadow:\n\t\t0 0 0 1px color-mix(in srgb, var(--pa-accent) 55%, transparent),\n\t\t0 16px 40px rgba(0, 0, 0, 0.35);\n}\n\n.wrapper[data-state='waiting'] {\n\tbox-shadow:\n\t\t0 0 0 1px color-mix(in srgb, var(--pa-accent) 80%, transparent),\n\t\t0 16px 40px rgba(0, 0, 0, 0.35);\n}\n\n.wrapper.collapsed .feedWrap {\n\tdisplay: none;\n}\n\n/* Follow bar (mobile peek strip). Hidden unless data-follow=\"bar\" on narrow viewports. */\n.followBar {\n\tdisplay: none;\n\tflex: none;\n\talign-items: center;\n\tgap: 8px;\n\tmin-height: 56px;\n\tpadding: 8px 10px;\n\tpadding-bottom: max(8px, env(safe-area-inset-bottom, 0px));\n}\n\n.followBarBody {\n\tflex: 1;\n\tmin-width: 0;\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 10px;\n\tpadding: 0;\n\tborder: 0;\n\tbackground: transparent;\n\tcolor: inherit;\n\tfont: inherit;\n\ttext-align: left;\n\tcursor: pointer;\n}\n\n.followBarStatus {\n\tflex: 1;\n\tmin-width: 0;\n\tfont-size: 13px;\n\tfont-weight: 600;\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n\n.followBarLens {\n\twidth: 28px;\n\theight: 28px;\n}\n\n.followBarLens svg {\n\twidth: 14px;\n\theight: 14px;\n}\n\n.voiceActions {\n\tflex: none;\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 8px;\n}\n\n/* Voice stop is for the mobile expanded voice layout; desktop keeps Stop in the header. */\n.voiceActions [data-role='voice-stop'] {\n\tdisplay: none;\n}\n\n[hidden] {\n\tdisplay: none !important;\n}\n\n/* Header */\n\n.header {\n\tflex: none;\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 10px;\n\theight: 52px;\n\tpadding: 0 12px 0 14px;\n\tborder-bottom: 1px solid var(--pa-line);\n\tcursor: grab;\n\ttouch-action: none;\n\tuser-select: none;\n}\n\n.brand:has(img) {\n\tbackground: transparent;\n}\n\n.brand img {\n\twidth: 100%;\n\theight: 100%;\n\tobject-fit: contain;\n\tborder-radius: inherit;\n}\n\n.brand {\n\tflex: none;\n\twidth: 30px;\n\theight: 30px;\n\tdisplay: grid;\n\tplace-items: center;\n\tborder-radius: 10px;\n\tbackground: var(--pa-accent);\n\tcolor: #20150e;\n\tfont-weight: 800;\n\tfont-size: 16px;\n}\n\n.titleBlock {\n\tflex: 1;\n\tmin-width: 0;\n\tdisplay: flex;\n\tflex-direction: column;\n}\n\n.title {\n\tfont-size: 12px;\n\tfont-weight: 650;\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n\n.status {\n\tfont-size: 10.5px;\n\tcolor: var(--pa-muted);\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n\n.controls {\n\tflex: none;\n\tdisplay: flex;\n\tgap: 2px;\n}\n\n.iconButton {\n\tdisplay: grid;\n\tplace-items: center;\n\tmin-width: 28px;\n\tmin-height: 28px;\n\tpadding: 0;\n\tborder: 0;\n\tborder-radius: 8px;\n\tbackground: transparent;\n\tcolor: inherit;\n\tfont-size: 14px;\n\tcursor: pointer;\n}\n\n.iconButton:hover {\n\tbackground: rgba(255, 255, 255, 0.08);\n}\n\n.stopButton {\n\tcolor: #ff8a80;\n}\n\n/* Feed */\n\n.feedWrap {\n\tposition: relative;\n\tflex: 1;\n\tdisplay: flex;\n\tflex-direction: column;\n\tmin-height: 120px;\n\tmax-height: 380px;\n}\n\n.feed {\n\tposition: relative;\n\tflex: 1;\n\tmin-height: 0;\n\toverflow-y: auto;\n\toverscroll-behavior: contain;\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 10px;\n\tpadding: 14px 18px 14px 14px;\n\tscroll-behavior: auto;\n\tscrollbar-width: thin;\n\tscrollbar-color: color-mix(in srgb, var(--pa-muted) 40%, transparent) transparent;\n}\n\n/* Right-edge rail: viewport thumb plus one marker per turn, question and result. Click a marker to jump. */\n.rail {\n\tposition: absolute;\n\ttop: 8px;\n\tbottom: 8px;\n\tright: 0;\n\twidth: 16px;\n\topacity: 0.55;\n\ttransition: opacity 0.2s ease;\n}\n\n.rail::before {\n\tcontent: '';\n\tposition: absolute;\n\ttop: 0;\n\tbottom: 0;\n\tright: 6px;\n\twidth: 2px;\n\tborder-radius: 2px;\n\tbackground: var(--pa-line);\n}\n\n.feedWrap:hover .rail,\n.feedWrap:focus-within .rail {\n\topacity: 1;\n}\n\n.feedWrap:hover .rail,\n.feedWrap:focus-within .rail {\n\topacity: 1;\n}\n\n.railThumb {\n\tposition: absolute;\n\tright: 6px;\n\twidth: 2px;\n\tborder-radius: 2px;\n\tbackground: var(--pa-muted);\n\ttransition: top 0.12s ease;\n}\n\n.railMark {\n\tposition: absolute;\n\tright: 2px;\n\theight: 3px;\n\twidth: 10px;\n\tmargin-top: -1px;\n\tpadding: 0;\n\tborder: 0;\n\tborder-radius: 3px;\n\tbackground: var(--pa-muted);\n\topacity: 0.7;\n\tcursor: pointer;\n\ttransition:\n\t\twidth 0.15s ease,\n\t\topacity 0.15s ease,\n\t\tbackground-color 0.15s ease;\n}\n\n.railMark[data-kind='turn'] {\n\twidth: 14px;\n}\n\n.railMark[data-kind='question'],\n.railMark[data-kind='result'] {\n\twidth: 6px;\n\theight: 6px;\n\tright: 4px;\n\tmargin-top: -2px;\n\tborder-radius: 50%;\n}\n\n.railMark[data-kind='question'] {\n\tbackground: var(--pa-accent);\n\topacity: 1;\n}\n\n.railMark[data-kind='result'] {\n\tbackground: var(--pa-ok);\n\topacity: 1;\n}\n\n.railMark[data-active='true'] {\n\twidth: 18px;\n\topacity: 1;\n\tbackground: var(--pa-fg);\n}\n\n.railMark[data-pinned='true'] {\n\tbackground: var(--pa-accent);\n\topacity: 1;\n}\n\n.railMark:hover {\n\twidth: 18px;\n\topacity: 1;\n}\n\n.railMark[data-kind='question'] {\n\tbackground: var(--pa-accent);\n}\n\n.railMark[data-kind='turn'] {\n\tbackground: var(--pa-muted);\n}\n\n.railMark[data-kind='result'] {\n\tbackground: var(--pa-ok);\n}\n\n/* Divider between finished tasks and the current one. */\n.divider {\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 10px;\n\tmargin: 6px 0;\n\tcolor: var(--pa-muted);\n\tfont-size: 10.5px;\n\ttext-transform: uppercase;\n\tletter-spacing: 0.06em;\n}\n\n.divider::before,\n.divider::after {\n\tcontent: '';\n\tflex: 1;\n\theight: 1px;\n\tbackground: var(--pa-line);\n}\n\n/* Hover card for a rail tick. */\n.peek {\n\tposition: absolute;\n\tright: 26px;\n\tz-index: 6;\n\twidth: min(260px, calc(100% - 56px));\n\tpadding: 10px 12px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 12px;\n\tbackground: var(--pa-surface);\n\tbox-shadow: 0 12px 30px rgba(0, 0, 0, 0.3);\n\tanimation: peekIn 0.16s ease-out both;\n}\n\n.peek[hidden] {\n\tdisplay: none !important;\n}\n\n@keyframes peekIn {\n\tfrom {\n\t\topacity: 0;\n\t\ttransform: translateX(6px);\n\t}\n\tto {\n\t\topacity: 1;\n\t\ttransform: none;\n\t}\n}\n\n.peekHead {\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 8px;\n}\n\n.peekHead strong {\n\tflex: 1;\n\tmin-width: 0;\n\tfont-size: 12px;\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n\n.peekText {\n\tmargin: 6px 0 0;\n\tmax-height: 4.2em;\n\toverflow: hidden;\n\tcolor: var(--pa-muted);\n\tfont-size: 11.5px;\n\tline-height: 1.4;\n\twhite-space: pre-wrap;\n\toverflow-wrap: anywhere;\n\t-webkit-mask-image: linear-gradient(to bottom, #000 60%, transparent);\n\tmask-image: linear-gradient(to bottom, #000 60%, transparent);\n}\n\n.pin {\n\tflex: none;\n\tdisplay: grid;\n\tplace-items: center;\n\twidth: 26px;\n\theight: 26px;\n\tpadding: 0;\n\tborder: 0;\n\tborder-radius: 7px;\n\tbackground: transparent;\n\tcolor: var(--pa-muted);\n\tcursor: pointer;\n}\n\n.pin:hover {\n\tbackground: rgba(255, 255, 255, 0.08);\n\tcolor: var(--pa-fg);\n}\n\n.pin[aria-pressed='true'] {\n\tcolor: var(--pa-accent);\n}\n\n.pin[aria-pressed='true'] svg {\n\tfill: currentColor;\n}\n\n.pin svg {\n\twidth: 14px;\n\theight: 14px;\n}\n\n/* Jump pill: appears while reading above, shows how many new events arrived. */\n.jump {\n\tposition: absolute;\n\tleft: 50%;\n\tbottom: 10px;\n\ttransform: translateX(-50%);\n\tdisplay: inline-flex;\n\talign-items: center;\n\tgap: 6px;\n\tpadding: 6px 12px 6px 9px;\n\tborder: 0;\n\tborder-radius: 999px;\n\tbackground: var(--pa-fg);\n\tcolor: var(--pa-surface);\n\tfont-size: 11px;\n\tfont-weight: 600;\n\twhite-space: nowrap;\n\tbox-shadow: 0 6px 18px rgba(0, 0, 0, 0.25);\n\tcursor: pointer;\n\tanimation: jumpIn 0.22s ease-out both;\n}\n\n.jump svg {\n\twidth: 14px;\n\theight: 14px;\n}\n\n.jump[hidden] {\n\tdisplay: none !important;\n}\n\n@keyframes jumpIn {\n\tfrom {\n\t\topacity: 0;\n\t\ttransform: translate(-50%, 6px);\n\t}\n\tto {\n\t\topacity: 1;\n\t\ttransform: translate(-50%, 0);\n\t}\n}\n\n.empty {\n\tmargin: auto;\n\tpadding: 24px 8px;\n\ttext-align: center;\n\tcolor: var(--pa-muted);\n\tfont-size: 13px;\n}\n\n.enter {\n\tanimation: enter 0.2s ease-out both;\n}\n\n@keyframes enter {\n\tfrom {\n\t\topacity: 0;\n\t\ttransform: translateY(4px);\n\t}\n\tto {\n\t\topacity: 1;\n\t\ttransform: none;\n\t}\n}\n\n.bubble {\n\talign-self: flex-end;\n\tmax-width: 85%;\n\tpadding: 8px 12px;\n\tborder-radius: 14px 14px 4px 14px;\n\tbackground: var(--pa-raised);\n\twhite-space: pre-wrap;\n\toverflow-wrap: anywhere;\n}\n\n.line {\n\tfont-size: 12px;\n\tcolor: var(--pa-muted);\n\twhite-space: pre-wrap;\n\toverflow-wrap: anywhere;\n}\n\n.reflection {\n\tpadding-left: 8px;\n\tborder-left: 2px solid var(--pa-line);\n}\n\n.observation {\n\tfont-size: 12px;\n}\n\n.warning {\n\tcolor: var(--pa-warn);\n}\n\n.live {\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 8px;\n\tcolor: var(--pa-accent);\n}\n\n.live::before {\n\tcontent: '';\n\tflex: none;\n\twidth: 8px;\n\theight: 8px;\n\tborder-radius: 50%;\n\tbackground: var(--pa-accent);\n\tanimation: pulse 1.6s ease-in-out infinite;\n}\n\n@keyframes pulse {\n\t0%,\n\t100% {\n\t\topacity: 0.35;\n\t}\n\t50% {\n\t\topacity: 1;\n\t}\n}\n\n/* Tool cards */\n\n.tool {\n\tpadding: 9px 11px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 11px;\n\tbackground: var(--pa-raised);\n\tfont-size: 12px;\n}\n\n.tool[data-status='running'] {\n\tborder-color: color-mix(in srgb, var(--pa-accent) 50%, transparent);\n}\n\n.tool[data-status='error'] {\n\tborder-color: color-mix(in srgb, var(--pa-err) 55%, transparent);\n\tcolor: var(--pa-err);\n}\n\n.toolHead {\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 8px;\n}\n\n.toolDot {\n\tflex: none;\n\twidth: 7px;\n\theight: 7px;\n\tborder-radius: 50%;\n\tbackground: var(--pa-ok);\n}\n\n.toolLabel {\n\tfont-weight: 600;\n\toverflow-wrap: anywhere;\n}\n\n.toolDetail {\n\tmargin-top: 5px;\n\tpadding-left: 15px;\n\tcolor: var(--pa-muted);\n\twhite-space: pre-wrap;\n\toverflow-wrap: anywhere;\n}\n\n.spinner {\n\tflex: none;\n\twidth: 11px;\n\theight: 11px;\n\tborder: 1.5px solid var(--pa-accent);\n\tborder-right-color: transparent;\n\tborder-radius: 50%;\n\tanimation: spin 0.9s linear infinite;\n}\n\n@keyframes spin {\n\tto {\n\t\ttransform: rotate(360deg);\n\t}\n}\n\n/* Question and result cards */\n\n.question {\n\tpadding: 2px 0 2px 12px;\n\tborder-left: 2px solid var(--pa-accent);\n}\n\n.questionTag {\n\tdisplay: block;\n\tmargin-bottom: 4px;\n\tcolor: var(--pa-accent);\n\tfont-size: 11px;\n\tfont-weight: 650;\n}\n\n.questionText {\n\tmargin: 0;\n\tfont-size: 14px;\n}\n\n.result {\n\tpadding: 11px 12px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 12px;\n\tbackground: var(--pa-raised);\n\tfont-size: 12px;\n}\n\n.result strong {\n\tdisplay: block;\n\tmargin-bottom: 4px;\n\tfont-size: 13px;\n}\n\n.result[data-kind='done'] strong {\n\tcolor: var(--pa-ok);\n}\n\n.result[data-kind='notDone'] strong,\n.result[data-kind='stopped'] strong {\n\tcolor: var(--pa-warn);\n}\n\n.result[data-kind='error'] strong {\n\tcolor: var(--pa-err);\n}\n\n.resultText {\n\tcolor: var(--pa-muted);\n\twhite-space: pre-wrap;\n\toverflow-wrap: anywhere;\n}\n\n/* Composer (text input and voice toggle share this area) */\n\n.composer {\n\tflex: none;\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 6px;\n\tpadding: 10px 12px 12px;\n\tborder-top: 1px solid var(--pa-line);\n}\n\n.answerContext {\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 8px;\n\tfont-size: 11px;\n\tcolor: var(--pa-accent);\n\tfont-weight: 650;\n}\n\n.choiceRow {\n\tdisplay: flex;\n\tflex-wrap: wrap;\n\tgap: 6px;\n}\n\n.choiceChip {\n\tappearance: none;\n\tborder: 1px solid var(--pa-line);\n\tbackground: var(--pa-raised);\n\tcolor: inherit;\n\tborder-radius: 999px;\n\tpadding: 6px 12px;\n\tfont: inherit;\n\tfont-size: 12px;\n\tfont-weight: 600;\n\tcursor: pointer;\n\tmin-height: 32px;\n}\n\n.choiceChip:hover {\n\tborder-color: var(--pa-accent);\n}\n\n.choiceChip[data-selected='true'],\n.choiceChip[aria-pressed='true'] {\n\tborder-color: var(--pa-accent);\n\tbackground: color-mix(in srgb, var(--pa-accent) 16%, var(--pa-raised));\n\tcolor: var(--pa-accent);\n}\n\n.choiceConfirm {\n\tappearance: none;\n\tborder: 0;\n\tbackground: var(--pa-accent);\n\tcolor: #fff;\n\tborder-radius: 999px;\n\tpadding: 6px 14px;\n\tfont: inherit;\n\tfont-size: 12px;\n\tfont-weight: 700;\n\tcursor: pointer;\n\tmin-height: 32px;\n}\n\n.choiceConfirm:disabled {\n\topacity: 0.45;\n\tcursor: not-allowed;\n}\n\n.box {\n\tdisplay: flex;\n\talign-items: flex-end;\n\tgap: 6px;\n\tpadding: 6px 6px 6px 12px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 16px;\n\tbackground: var(--pa-raised);\n}\n\n.box:focus-within {\n\toutline: 2px solid var(--pa-accent);\n\toutline-offset: 2px;\n}\n\n.box textarea {\n\tflex: 1;\n\tmin-width: 0;\n\tmin-height: 28px;\n\tmax-height: 120px;\n\tresize: none;\n\tborder: 0;\n\toutline: none;\n\tbackground: transparent;\n\tcolor: inherit;\n\tfont: inherit;\n\tfont-size: 13px;\n\tline-height: 1.4;\n\tpadding: 5px 0;\n}\n\n.box textarea:disabled {\n\topacity: 0.6;\n}\n\n.box textarea::placeholder {\n\tcolor: var(--pa-muted);\n}\n\n.actions {\n\tflex: none;\n\tdisplay: flex;\n\tgap: 4px;\n}\n\n.attachList {\n\tdisplay: flex;\n\tflex-wrap: wrap;\n\tgap: 6px;\n\talign-items: center;\n}\n\n.attachChip {\n\tdisplay: inline-flex;\n\talign-items: center;\n\tgap: 4px;\n\tmax-width: 100%;\n\tpadding: 2px 4px 2px 8px;\n\tborder-radius: 999px;\n\tbackground: rgba(255, 255, 255, 0.08);\n\tfont-size: 12px;\n\tline-height: 1.3;\n}\n\n.attachName {\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\twhite-space: nowrap;\n\tmax-width: 180px;\n}\n\n.attachRemove {\n\tdisplay: grid;\n\tplace-items: center;\n\tpadding: 0;\n\twidth: 20px;\n\theight: 20px;\n\tborder: 0;\n\tborder-radius: 50%;\n\tbackground: transparent;\n\tcolor: inherit;\n\tcursor: pointer;\n\topacity: 0.7;\n}\n\n.attachRemove:hover {\n\topacity: 1;\n\tbackground: rgba(255, 255, 255, 0.1);\n}\n\n.attachRemove svg {\n\twidth: 12px;\n\theight: 12px;\n}\n\n.attachError {\n\tcolor: #f5a3a3;\n\tfont-size: 12px;\n\tline-height: 1.3;\n}\n\n.roundButton {\n\tdisplay: grid;\n\tplace-items: center;\n\tpadding: 0;\n\twidth: 30px;\n\theight: 30px;\n\tborder: 0;\n\tborder-radius: 50%;\n\tbackground: rgba(255, 255, 255, 0.08);\n\tcolor: inherit;\n\tfont-size: 14px;\n\tcursor: pointer;\n}\n\n.roundButton[aria-pressed='true'] {\n\tbackground: color-mix(in srgb, var(--pa-accent) 35%, transparent);\n}\n\n.send {\n\tbackground: var(--pa-accent);\n\tcolor: #20150e;\n\tfont-weight: 800;\n}\n\n.roundButton:disabled {\n\topacity: 0.4;\n\tcursor: not-allowed;\n}\n\n/* Skills Studio (replaces feed + composer while authoring skills) */\n\n.studio {\n\tflex: 1;\n\tmin-height: 0;\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 10px;\n\tpadding: 10px 12px 12px;\n\tborder-top: 1px solid var(--pa-line);\n}\n\n.studioHeader {\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: space-between;\n\tgap: 8px;\n}\n\n.studioTitle {\n\tfont-size: 14px;\n\tfont-weight: 700;\n}\n\n.studioTabs {\n\tdisplay: flex;\n\tgap: 4px;\n}\n\n.studioTab {\n\tflex: 1;\n\tpadding: 6px 8px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 10px;\n\tbackground: transparent;\n\tcolor: inherit;\n\tfont-size: 12px;\n\tfont-weight: 600;\n\tcursor: pointer;\n}\n\n.studioTab[aria-selected='true'] {\n\tbackground: color-mix(in srgb, var(--pa-accent) 28%, transparent);\n\tborder-color: color-mix(in srgb, var(--pa-accent) 55%, var(--pa-line));\n}\n\n.studioBody {\n\tflex: 1;\n\tmin-height: 0;\n\toverflow: auto;\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 8px;\n}\n\n.studioHint {\n\tmargin: 0;\n\tcolor: var(--pa-muted);\n\tfont-size: 12px;\n\tline-height: 1.4;\n}\n\n.studioToolbar {\n\tdisplay: flex;\n\tflex-wrap: wrap;\n\tgap: 6px;\n}\n\n.studioToolButton {\n\tflex: none;\n\tpadding: 6px 10px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 10px;\n\tbackground: var(--pa-raised);\n\tcolor: inherit;\n\tfont-size: 12px;\n\tfont-weight: 600;\n\tcursor: pointer;\n}\n\n.studioToolButton:disabled {\n\topacity: 0.45;\n\tcursor: default;\n}\n\n.studioToolButton[data-variant='accent'] {\n\tbackground: color-mix(in srgb, var(--pa-accent) 28%, transparent);\n\tborder-color: color-mix(in srgb, var(--pa-accent) 55%, var(--pa-line));\n}\n\n.studioToolButton[data-variant='danger'] {\n\tcolor: var(--pa-err);\n}\n\n.studioStatus {\n\tmargin: 0;\n\tcolor: var(--pa-muted);\n\tfont-size: 11px;\n\tline-height: 1.4;\n\twhite-space: pre-wrap;\n}\n\n.studioStatus[data-tone='ok'] {\n\tcolor: var(--pa-ok);\n}\n\n.studioStatus[data-tone='warn'] {\n\tcolor: var(--pa-warn);\n}\n\n.studioStatus[data-tone='err'] {\n\tcolor: var(--pa-err);\n}\n\n.studioAsk {\n\twidth: 100%;\n\tmin-height: 72px;\n\tresize: vertical;\n\tpadding: 8px 10px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 12px;\n\tbackground: var(--pa-raised);\n\tcolor: inherit;\n\tfont: inherit;\n\tline-height: 1.4;\n}\n\n.studioAsk:focus {\n\toutline: 2px solid var(--pa-accent);\n\toutline-offset: 2px;\n}\n\n.studioSteps,\n.studioCatalog {\n\tlist-style: none;\n\tmargin: 0;\n\tpadding: 0;\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 6px;\n\tfont-size: 12px;\n\tline-height: 1.45;\n}\n\n.studioStep,\n.studioCatalogRow {\n\tdisplay: flex;\n\talign-items: flex-start;\n\tgap: 8px;\n\tpadding: 8px 10px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 10px;\n\tbackground: rgba(255, 255, 255, 0.04);\n}\n\n.studioCatalogRow {\n\tpadding: 6px 8px;\n\tgap: 6px;\n}\n\n.studioWatchers {\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 6px;\n\tpadding: 8px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 12px;\n\tbackground: color-mix(in srgb, var(--pa-raised) 85%, transparent);\n}\n\n.studioWatchersHead {\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: space-between;\n\tgap: 8px;\n}\n\n.studioWatchersTitle {\n\tfont-size: 11px;\n\tfont-weight: 700;\n\ttext-transform: uppercase;\n\tletter-spacing: 0.04em;\n\tcolor: var(--pa-muted);\n}\n\n.studioWatchersEmpty {\n\tmargin: 0;\n\tcolor: var(--pa-muted);\n\tfont-size: 11px;\n}\n\n.studioWatchersList {\n\tlist-style: none;\n\tmargin: 0;\n\tpadding: 0;\n\tdisplay: flex;\n\tflex-wrap: wrap;\n\tgap: 6px;\n}\n\n.studioWatcherChip {\n\tdisplay: inline-flex;\n\talign-items: center;\n\tgap: 6px;\n\tmax-width: 100%;\n\tpadding: 4px 6px 4px 8px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 999px;\n\tbackground: rgba(255, 255, 255, 0.06);\n\tfont-size: 11px;\n\tline-height: 1.3;\n}\n\n.studioWatcherLabel {\n\tmin-width: 0;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\twhite-space: nowrap;\n\tfont-weight: 600;\n}\n\n.studioWatcherMeta {\n\tcolor: var(--pa-muted);\n\tfont-size: 10px;\n\ttext-transform: uppercase;\n\tletter-spacing: 0.03em;\n}\n\n.studioWatcherChip button {\n\tpadding: 2px 8px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 999px;\n\tbackground: transparent;\n\tcolor: inherit;\n\tfont-size: 10px;\n\tfont-weight: 600;\n\tcursor: pointer;\n}\n\n.studioWatcherChip button:disabled {\n\topacity: 0.45;\n\tcursor: default;\n}\n\n.studioStepBody,\n.studioCatalogBody {\n\tflex: 1;\n\tmin-width: 0;\n}\n\n.studioStepKind {\n\tdisplay: inline-block;\n\tmargin-right: 6px;\n\tpadding: 1px 6px;\n\tborder-radius: 999px;\n\tbackground: color-mix(in srgb, var(--pa-accent) 22%, transparent);\n\tfont-size: 10px;\n\tfont-weight: 700;\n\ttext-transform: uppercase;\n\tletter-spacing: 0.04em;\n}\n\n.studioStepMeta,\n.studioCatalogMeta {\n\tcolor: var(--pa-muted);\n\tfont-size: 11px;\n}\n\n.studioStepActions,\n.studioCatalogActions {\n\tdisplay: flex;\n\tflex-wrap: wrap;\n\tgap: 4px;\n}\n\n.studioStepActions button,\n.studioCatalogActions button {\n\tpadding: 4px 8px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 8px;\n\tbackground: transparent;\n\tcolor: inherit;\n\tfont-size: 11px;\n\tcursor: pointer;\n}\n\n.studioCatalogActions button[data-variant='accent'] {\n\tbackground: color-mix(in srgb, var(--pa-accent) 28%, transparent);\n\tborder-color: color-mix(in srgb, var(--pa-accent) 55%, var(--pa-line));\n\tfont-weight: 700;\n}\n\n.studioStepActions button:disabled,\n.studioCatalogActions button:disabled {\n\topacity: 0.45;\n\tcursor: default;\n}\n\n@media (min-width: 768px) {\n\t.wrapper[data-mode='skills-studio'] .studioToolbar {\n\t\tgap: 8px;\n\t}\n\n\t.wrapper[data-mode='skills-studio'] .studioToolButton {\n\t\tpadding: 7px 12px;\n\t}\n\n\t.wrapper[data-mode='skills-studio'] .studioCatalog {\n\t\tgap: 5px;\n\t}\n}\n\n.studioPreviewLabel {\n\tmargin: 0;\n\tfont-size: 11px;\n\tfont-weight: 700;\n\tcolor: var(--pa-muted);\n\ttext-transform: uppercase;\n\tletter-spacing: 0.04em;\n}\n\n.studioPreview {\n\tmargin: 0;\n\tmax-height: 180px;\n\toverflow: auto;\n\tpadding: 8px 10px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 10px;\n\tbackground: var(--pa-raised);\n\tfont:\n\t\t11px/1.45 ui-monospace,\n\t\tSFMono-Regular,\n\t\tMenlo,\n\t\tConsolas,\n\t\tmonospace;\n\twhite-space: pre-wrap;\n\tword-break: break-word;\n}\n\n/* Voice stage (replaces the composer while voice is selected) */\n\n.voice {\n\tflex: none;\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 10px;\n\tpadding: 12px 12px;\n\tborder-top: 1px solid var(--pa-line);\n}\n\n.voiceMeta {\n\tflex: 1;\n\tmin-width: 0;\n\tdisplay: flex;\n\tflex-direction: column;\n\tgap: 2px;\n}\n\n.lens {\n\tflex: none;\n\tdisplay: grid;\n\tplace-items: center;\n\twidth: 30px;\n\theight: 30px;\n\tborder-radius: 50%;\n\tcolor: var(--pa-muted);\n\tbackground: var(--pa-raised);\n\tborder: 1px solid var(--pa-line);\n\ttransition:\n\t\tborder-color 0.3s ease,\n\t\tcolor 0.3s ease,\n\t\topacity 0.3s ease;\n}\n\n.lens svg {\n\twidth: 15px;\n\theight: 15px;\n}\n\n/* Microphone state: active breathes in accent, muted is dimmed, blocked or unavailable is red. */\n.lens[data-state='active'] {\n\tcolor: var(--pa-accent);\n\tborder-color: var(--pa-accent);\n\tanimation: breathe 2.8s ease-in-out infinite;\n}\n\n.lens[data-state='muted'] {\n\topacity: 0.5;\n}\n\n.lens[data-state='denied'],\n.lens[data-state='unsupported'] {\n\tcolor: var(--pa-err);\n\tborder-color: var(--pa-err);\n}\n\n@keyframes breathe {\n\t50% {\n\t\ttransform: scale(1.06);\n\t}\n}\n\n.voiceText {\n\tmin-width: 0;\n\tfont-size: 12px;\n\tfont-weight: 600;\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n\n.micDevice {\n\tmin-width: 0;\n\tmax-width: 100%;\n\talign-self: start;\n\tpadding: 0;\n\tborder: 0;\n\tborder-radius: 4px;\n\tbackground: transparent;\n\tcolor: var(--pa-muted);\n\tfont: inherit;\n\tfont-size: 10.5px;\n\tfont-weight: 500;\n\tline-height: 1.3;\n\ttext-align: left;\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\tcursor: pointer;\n}\n\n.micDevice:disabled {\n\tcursor: default;\n\topacity: 0.7;\n}\n\n.micDevice:not(:disabled):hover {\n\tcolor: var(--pa-accent);\n}\n\n.textButton {\n\tflex: none;\n\twhite-space: nowrap;\n\tpadding: 8px 10px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 9px;\n\tbackground: var(--pa-raised);\n\tcolor: inherit;\n\tfont-size: 12px;\n\tcursor: pointer;\n}\n\n/* Pressed toggles (agent cursor visible, microphone on) read as on: tinted background and accent icon. */\n.iconButton[aria-pressed='true'] {\n\tbackground: color-mix(in srgb, var(--pa-accent) 22%, transparent);\n\tcolor: var(--pa-accent);\n}\n\n/* Floating button shown while the panel is closed. Snaps to a corner after dragging. */\n.fab {\n\tposition: fixed;\n\tz-index: 2147483642;\n\tdisplay: grid;\n\tplace-items: center;\n\twidth: 46px;\n\theight: 46px;\n\tpadding: 0;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 50%;\n\tbackground: var(--pa-surface);\n\tcolor: var(--pa-accent);\n\tbox-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);\n\tcursor: grab;\n\ttouch-action: none;\n\tuser-select: none;\n\ttransition:\n\t\ttransform 0.2s ease,\n\t\tbox-shadow 0.2s ease;\n}\n\n.fab:hover {\n\ttransform: scale(1.06);\n\tbox-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);\n}\n\n.fab[hidden] {\n\tdisplay: none !important;\n}\n\n.fab img {\n\twidth: 26px;\n\theight: 26px;\n\tobject-fit: contain;\n\tborder-radius: 6px;\n\tpointer-events: none;\n}\n\n.fab svg {\n\twidth: 20px;\n\theight: 20px;\n\tpointer-events: none;\n}\n\n.fabLeft::after {\n\tleft: 0;\n\tright: auto;\n}\n\n/* Icon hints: a short label on hover or keyboard focus. */\n.tip:not(.fab) {\n\tposition: relative;\n}\n\n.tip::after {\n\tcontent: attr(data-tip);\n\tposition: absolute;\n\ttop: calc(100% + 6px);\n\tright: 0;\n\tz-index: 10;\n\tpadding: 4px 8px;\n\tborder-radius: 6px;\n\tbackground: var(--pa-fg);\n\tcolor: var(--pa-surface);\n\tfont-size: 11px;\n\tfont-weight: 550;\n\tline-height: 1.3;\n\twhite-space: nowrap;\n\tpointer-events: none;\n\topacity: 0;\n\ttransition: opacity 0.15s ease;\n}\n\n.tipUp::after {\n\ttop: auto;\n\tbottom: calc(100% + 6px);\n}\n\n.tip:hover::after,\n.tip:focus-visible::after {\n\topacity: 1;\n}\n\n.iconButton svg,\n.roundButton svg {\n\tdisplay: block;\n}\n\n/* Light theme */\n\n@media (prefers-color-scheme: light) {\n\t.wrapper {\n\t\t--pa-fg: #171716;\n\t\t--pa-muted: #61615b;\n\t\t--pa-accent: #c25a16;\n\t\t--pa-surface: #ffffff;\n\t\t--pa-raised: #f1f0ec;\n\t\t--pa-line: rgba(23, 23, 22, 0.12);\n\t\t--pa-ok: #1f6b3a;\n\t\t--pa-warn: #7a5a00;\n\t\t--pa-err: #a33a2a;\n\t\t--pa-c-keyword: #c25a16;\n\t\t--pa-c-string: #1f6b3a;\n\t\t--pa-c-number: #7a5a00;\n\t\t--pa-c-key: #1f4f8a;\n\t\t--pa-c-bool: #a33a2a;\n\t\t--pa-c-comment: #7a796f;\n\t\t--pa-c-name: #171716;\n\t\t--pa-c-punct: #61615b;\n\t\tbox-shadow: 0 16px 40px rgba(0, 0, 0, 0.12);\n\t}\n\t.stopButton {\n\t\tcolor: #a33a2a;\n\t}\n\t.iconButton:hover {\n\t\tbackground: rgba(0, 0, 0, 0.06);\n\t}\n\t.roundButton {\n\t\tbackground: rgba(0, 0, 0, 0.06);\n\t}\n\t.attachChip {\n\t\tbackground: rgba(0, 0, 0, 0.06);\n\t}\n\t.attachRemove:hover {\n\t\tbackground: rgba(0, 0, 0, 0.08);\n\t}\n\t.attachError {\n\t\tcolor: #b42318;\n\t}\n\t.send {\n\t\tcolor: #ffffff;\n\t}\n\t.brand {\n\t\tcolor: #ffffff;\n\t}\n}\n\n/* Mobile: follow modes (expanded / bar / fab), larger hit areas, no sticky hover tips. */\n\n@media (max-width: 480px) {\n\t.wrapper {\n\t\tleft: 0;\n\t\tright: 0;\n\t\tbottom: 0;\n\t\tmargin: 0;\n\t\twidth: auto;\n\t\tmax-height: min(560px, calc(100svh - env(safe-area-inset-top, 0px) - 12px));\n\t\tborder-radius: 18px 18px 0 0;\n\t\tborder-bottom: 0;\n\t\tpadding-bottom: env(safe-area-inset-bottom, 0px);\n\t\tbackground: color-mix(in srgb, var(--pa-surface) 92%, transparent);\n\t\tbackdrop-filter: blur(18px);\n\t\t-webkit-backdrop-filter: blur(18px);\n\t}\n\n\t.wrapper[data-follow='bar'] {\n\t\tleft: 8px;\n\t\tright: 8px;\n\t\tbottom: max(10px, env(safe-area-inset-bottom, 0px));\n\t\tmax-height: none;\n\t\tborder-radius: 16px;\n\t\tborder: 1px solid var(--pa-line);\n\t\tpadding-bottom: 0;\n\t\tbox-shadow: 0 12px 32px rgba(0, 0, 0, 0.4);\n\t}\n\n\t.wrapper[data-follow='bar'] .header,\n\t.wrapper[data-follow='bar'] .feedWrap,\n\t.wrapper[data-follow='bar'] .composer,\n\t.wrapper[data-follow='bar'] .voice,\n\t.wrapper[data-follow='bar'] .studio {\n\t\tdisplay: none !important;\n\t}\n\n\t.wrapper[data-follow='bar'] .followBar {\n\t\tdisplay: flex;\n\t}\n\n\t.header {\n\t\theight: 48px;\n\t\tgap: 6px;\n\t\tpadding: 0 8px 0 12px;\n\t}\n\n\t.brand {\n\t\twidth: 26px;\n\t\theight: 26px;\n\t\tborder-radius: 8px;\n\t\tfont-size: 13px;\n\t}\n\n\t.title {\n\t\tfont-size: 13px;\n\t}\n\n\t.status {\n\t\tfont-size: 10.5px;\n\t}\n\n\t/* Compact visuals with an expanded hit area (~44px) via ::before. */\n\t.controls {\n\t\tgap: 6px;\n\t}\n\n\t.iconButton {\n\t\tposition: relative;\n\t\tmin-width: 32px;\n\t\tmin-height: 32px;\n\t\twidth: 32px;\n\t\theight: 32px;\n\t\tborder-radius: 9px;\n\t}\n\n\t.iconButton::before {\n\t\tcontent: '';\n\t\tposition: absolute;\n\t\tinset: -6px;\n\t}\n\n\t.feed {\n\t\tpadding: 8px 10px 8px 8px;\n\t\tgap: 6px;\n\t}\n\n\t.feedWrap {\n\t\tmin-height: 72px;\n\t\tmax-height: 240px;\n\t}\n\n\t.composer {\n\t\tpadding: 8px 8px 10px;\n\t}\n\n\t.box {\n\t\tpadding: 4px 4px 4px 10px;\n\t\tborder-radius: 14px;\n\t}\n\n\t.actions {\n\t\tgap: 8px;\n\t}\n\n\t.roundButton {\n\t\tposition: relative;\n\t\twidth: 40px;\n\t\theight: 40px;\n\t}\n\n\t.roundButton::before {\n\t\tcontent: '';\n\t\tposition: absolute;\n\t\tinset: -4px;\n\t}\n\n\t/* Voice expanded: large lens, status, device, Mute + Stop row. */\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .voice {\n\t\tflex-direction: column;\n\t\talign-items: center;\n\t\tgap: 12px;\n\t\tpadding: 16px 14px 18px;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .lens {\n\t\twidth: 72px;\n\t\theight: 72px;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .lens svg {\n\t\twidth: 28px;\n\t\theight: 28px;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .voiceMeta {\n\t\talign-items: center;\n\t\ttext-align: center;\n\t\twidth: 100%;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .voiceText {\n\t\tfont-size: 15px;\n\t\twhite-space: normal;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .micDevice {\n\t\talign-self: center;\n\t\ttext-align: center;\n\t\tfont-size: 12px;\n\t\tmin-height: 28px;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .voiceActions {\n\t\tgap: 12px;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .voiceActions [data-role='voice-stop'] {\n\t\tdisplay: grid;\n\t}\n\n\t.wrapper[data-mode='voice'][data-follow='expanded'] .voiceActions [data-role='back'] {\n\t\tdisplay: none;\n\t}\n\n\t.voice {\n\t\tgap: 8px;\n\t\tpadding: 8px 10px 10px;\n\t}\n\n\t.lens {\n\t\twidth: 26px;\n\t\theight: 26px;\n\t}\n\n\t.micDevice {\n\t\tmin-height: 32px;\n\t\tpadding: 6px 0;\n\t\tfont-size: 11px;\n\t}\n\n\t.followBar {\n\t\tmin-height: 60px;\n\t\tpadding: 10px 12px;\n\t\tpadding-bottom: max(10px, env(safe-area-inset-bottom, 0px));\n\t}\n\n\t.followBar .roundButton {\n\t\twidth: 40px;\n\t\theight: 40px;\n\t}\n\n\t/* Skills Studio: wrap toolbars, full-width preview, no horizontal overflow. */\n\t.studio {\n\t\toverflow-x: hidden;\n\t\tpadding: 10px 10px 14px;\n\t\tgap: 8px;\n\t}\n\n\t.studioTabs {\n\t\tflex-wrap: wrap;\n\t\tgap: 6px;\n\t}\n\n\t.studioTab {\n\t\tflex: 1 1 auto;\n\t\tmin-width: calc(33% - 6px);\n\t\tpadding: 10px 8px;\n\t\tfont-size: 12px;\n\t}\n\n\t.studioToolbar {\n\t\tgap: 8px;\n\t}\n\n\t.studioToolButton {\n\t\tflex: 1 1 auto;\n\t\tmin-height: 40px;\n\t\tpadding: 8px 12px;\n\t\tfont-size: 13px;\n\t}\n\n\t.studioStep,\n\t.studioCatalogRow {\n\t\tflex-wrap: wrap;\n\t\tpadding: 10px 12px;\n\t\tgap: 10px;\n\t}\n\n\t.studioStepActions,\n\t.studioCatalogActions {\n\t\twidth: 100%;\n\t\tjustify-content: flex-start;\n\t\tgap: 6px;\n\t}\n\n\t.studioStepActions button,\n\t.studioCatalogActions button {\n\t\tmin-height: 36px;\n\t\tpadding: 6px 10px;\n\t\tfont-size: 12px;\n\t}\n\n\t.studioPreview {\n\t\tmax-height: none;\n\t\twidth: 100%;\n\t\toverflow-x: auto;\n\t}\n\n\t.studioAsk {\n\t\tmin-height: 88px;\n\t}\n\n\t.fab {\n\t\twidth: 56px;\n\t\theight: 56px;\n\t\tbottom: max(16px, env(safe-area-inset-bottom, 0px));\n\t\tright: max(16px, env(safe-area-inset-right, 0px));\n\t\tbackground: color-mix(in srgb, var(--pa-surface) 88%, transparent);\n\t\tbackdrop-filter: blur(14px);\n\t\t-webkit-backdrop-filter: blur(14px);\n\t\tbox-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);\n\t}\n\n\t.fab img {\n\t\twidth: 28px;\n\t\theight: 28px;\n\t}\n\n\t.fab svg {\n\t\twidth: 24px;\n\t\theight: 24px;\n\t}\n\n\t.tip::after {\n\t\tdisplay: none;\n\t}\n}\n\n@media (hover: none) {\n\t.tip::after {\n\t\tdisplay: none;\n\t}\n}\n\n/* Desktop (≥768px): keep binary collapse; never show the mobile follow strip. */\n@media (min-width: 768px) {\n\t.followBar {\n\t\tdisplay: none !important;\n\t}\n}\n\n/* Reduced motion: keep the state text; drop the animation */\n\n@media (prefers-reduced-motion: reduce) {\n\t.wrapper,\n\t.enter,\n\t.live::before,\n\t.lens,\n\t.spinner {\n\t\tanimation: none !important;\n\t\ttransition: none !important;\n\t}\n}\n\n/* Script card: compact. Each block shows a preview that fades out; a click opens it, a second click closes it. */\n.code {\n\tpadding: 6px 8px;\n\tborder: 1px solid var(--pa-line);\n\tborder-radius: 9px;\n\tbackground: var(--pa-raised);\n\tfont-size: 11px;\n\tline-height: 1.3;\n}\n\n.code[data-status='running'] {\n\tborder-color: color-mix(in srgb, var(--pa-accent) 50%, transparent);\n}\n\n.code[data-status='error'],\n.code[data-status='refused'] {\n\tborder-color: color-mix(in srgb, var(--pa-err) 55%, transparent);\n}\n\n.codeHead {\n\tdisplay: flex;\n\talign-items: center;\n\tgap: 6px;\n\tmin-width: 0;\n}\n\n.codeTitle {\n\tfont-weight: 600;\n\tcolor: var(--pa-accent);\n}\n\n.codeMeta {\n\tflex: 1;\n\tmin-width: 0;\n\toverflow: hidden;\n\twhite-space: nowrap;\n\ttext-overflow: ellipsis;\n\tcolor: var(--pa-muted);\n\tfont-size: 10px;\n}\n\n.codeStatus {\n\tfont-size: 10px;\n\tcolor: var(--pa-muted);\n}\n\n.code[data-status='error'] .codeStatus,\n.code[data-status='refused'] .codeStatus {\n\tcolor: var(--pa-err);\n}\n\n.codeBadge {\n\tpadding: 0 5px;\n\tmargin-right: 4px;\n\tborder-radius: 999px;\n\tbackground: color-mix(in srgb, var(--pa-accent) 18%, transparent);\n\tcolor: var(--pa-accent);\n\tfont-size: 9px;\n\tfont-weight: 600;\n}\n\n.codeSection {\n\tmargin-top: 4px;\n\tmin-width: 0;\n}\n\n.codeLabel {\n\tdisplay: block;\n\tmargin-bottom: 2px;\n\tfont-size: 9px;\n\tletter-spacing: 0.05em;\n\ttext-transform: uppercase;\n\tcolor: var(--pa-muted);\n}\n\n.clip {\n\tposition: relative;\n\tmin-width: 0;\n}\n\n.codeBlock,\n.resultBlock {\n\tmargin: 0;\n\tpadding: 4px 6px;\n\tborder-radius: 6px;\n\tbackground: var(--pa-surface);\n\tborder: 1px solid var(--pa-line);\n\tfont:\n\t\t10px/1.35 ui-monospace,\n\t\tSFMono-Regular,\n\t\tMenlo,\n\t\tConsolas,\n\t\tmonospace;\n\twhite-space: pre-wrap;\n\toverflow-wrap: anywhere;\n\tcolor: var(--pa-c-name);\n}\n\n.clipBody {\n\tposition: relative;\n\tmax-height: 4.1em;\n\toverflow: hidden;\n\tcursor: pointer;\n}\n\n.clip[data-open='true'] .clipBody {\n\tmax-height: 14em;\n\toverflow: auto;\n}\n\n.clip[data-clipped='true'][data-open='false'] .clipBody::after {\n\tcontent: '';\n\tposition: absolute;\n\tleft: 0;\n\tright: 0;\n\tbottom: 0;\n\theight: 1.5em;\n\tbackground: linear-gradient(to bottom, transparent, var(--pa-surface));\n\tpointer-events: none;\n}\n\n.clipToggle {\n\tmargin-top: 2px;\n\tpadding: 0;\n\tborder: 0;\n\tbackground: none;\n\tcolor: var(--pa-muted);\n\tfont: inherit;\n\tfont-size: 10px;\n\tcursor: pointer;\n}\n\n.clipToggle:hover {\n\tcolor: var(--pa-fg);\n}\n\n.resultBlock[data-ok='false'] {\n\tcolor: var(--pa-err);\n}\n\n.tkComment {\n\tcolor: var(--pa-c-comment);\n\tfont-style: italic;\n}\n\n.tkString {\n\tcolor: var(--pa-c-string);\n}\n\n.tkNumber {\n\tcolor: var(--pa-c-number);\n}\n\n.tkKeyword {\n\tcolor: var(--pa-c-keyword);\n}\n\n.tkName {\n\tcolor: var(--pa-c-name);\n}\n\n.tkPunct {\n\tcolor: var(--pa-c-punct);\n}\n\n.tkKey {\n\tcolor: var(--pa-c-key);\n}\n\n.tkBool {\n\tcolor: var(--pa-c-bool);\n}\n\n/* REVERSIBLE (2026-11-17, card scale): tool cards and script cards at 75% of their size, with their contents.\n Remove this block to return to full size. */\n.tool,\n.code {\n\tzoom: 0.75;\n}\n\n/* REVERSIBLE (2026-11-17, card folding): folded cards. Each card starts folded; its head shows the state. */\n.foldHead {\n\tcursor: pointer;\n\tuser-select: none;\n}\n\n.foldHead::after {\n\tcontent: '';\n\tflex: none;\n\twidth: 6px;\n\theight: 6px;\n\tmargin-left: auto;\n\tborder-right: 1.5px solid var(--pa-muted);\n\tborder-bottom: 1.5px solid var(--pa-muted);\n\ttransform: rotate(45deg);\n\ttransition: transform 0.22s ease;\n}\n\n.foldHead:focus-visible {\n\toutline: 1px solid var(--pa-accent);\n\toutline-offset: 2px;\n\tborder-radius: 4px;\n}\n\n.foldBody {\n\tdisplay: grid;\n\tgrid-template-rows: 0fr;\n\ttransition: grid-template-rows 0.24s ease;\n}\n\n.foldInner {\n\tmin-height: 0;\n\toverflow: hidden;\n}\n\n.fold[data-open='true'] > .foldBody,\n[data-open='true'] > .foldBody {\n\tgrid-template-rows: 1fr;\n}\n\n[data-open='true'] > .foldHead::after {\n\ttransform: rotate(-135deg);\n}\n\n.toolState {\n\tmargin-left: auto;\n\tfont-size: 10px;\n\tcolor: var(--pa-muted);\n}\n\n.tool[data-status='done'] .toolState {\n\tcolor: var(--pa-ok);\n}\n\n.tool[data-status='error'] .toolState {\n\tcolor: var(--pa-err);\n}\n\n.codeRunning,\n.codeDot {\n\tflex: none;\n\twidth: 6px;\n\theight: 6px;\n\tborder-radius: 50%;\n\tbackground: var(--pa-accent);\n}\n\n.codeDot {\n\tbackground: var(--pa-ok);\n\tanimation: pop 0.32s ease-out both;\n}\n\n.codeRunning {\n\tanimation: pulse 1.2s ease-in-out infinite;\n}\n\n.toolDot {\n\tanimation: pop 0.32s ease-out both;\n}\n\n@keyframes pop {\n\tfrom {\n\t\ttransform: scale(0.3);\n\t\topacity: 0;\n\t}\n\tto {\n\t\ttransform: scale(1);\n\t\topacity: 1;\n\t}\n}\n\n@keyframes pulse {\n\t0%,\n\t100% {\n\t\topacity: 1;\n\t\ttransform: scale(1);\n\t}\n\t50% {\n\t\topacity: 0.35;\n\t\ttransform: scale(0.7);\n\t}\n}\n\n@media (prefers-reduced-motion: reduce) {\n\t.foldBody,\n\t.foldHead::after {\n\t\ttransition: none;\n\t}\n\t.codeDot,\n\t.codeRunning,\n\t.toolDot {\n\t\tanimation: none;\n\t}\n}\n\n/* REVERSIBLE (2026-11-17, tool visuals): each tool has its own tone: a left stripe, a tinted icon chip and a short summary. */\n.tool,\n.code {\n\t--tone: var(--pa-muted);\n\tborder-left: 2px solid var(--tone);\n}\n\n.tool[data-tone='js'],\n.code[data-tone='js'] {\n\t--tone: #b58cff;\n}\n\n.tool[data-tone='task'] {\n\t--tone: var(--pa-accent);\n}\n\n.tool[data-tone='move'] {\n\t--tone: #7cb8ff;\n}\n\n.tool[data-tone='act'] {\n\t--tone: #7fd9a4;\n}\n\n.tool[data-tone='time'] {\n\t--tone: var(--pa-muted);\n}\n\n.tool[data-tone='done'] {\n\t--tone: var(--pa-ok);\n}\n\n.tool[data-tone='ask'] {\n\t--tone: var(--pa-warn);\n}\n\n.tool[data-tone='generic'] {\n\t--tone: var(--pa-muted);\n}\n\n.toolChip {\n\tflex: none;\n\tdisplay: grid;\n\tplace-items: center;\n\twidth: 18px;\n\theight: 18px;\n\tborder-radius: 6px;\n\tbackground: color-mix(in srgb, var(--tone) 18%, transparent);\n\tcolor: var(--tone);\n}\n\n.toolSummary {\n\tmin-width: 0;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\twhite-space: nowrap;\n\tcolor: var(--pa-muted);\n\tfont-size: 10px;\n}\n\n.toolLabel {\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\tmin-width: 0;\n}\n\n.toolState {\n\tmargin-left: auto;\n}\n","/**\n * A card that starts folded: its head always shows, its body opens and closes with a short animation.\n * The open state is remembered by key, so a redraw of the feed keeps the cards the user opened.\n * REVERSIBLE (2026-11-17, card folding): delete this file and its uses in feed.ts and scriptCard.ts.\n */\nimport styles from './Panel.module.css'\n\nconst openCards = new Set<string>()\n\n/** Wraps a card head and body in a folding region. Clicking the head (or pressing Enter/Space) toggles it. */\nexport function foldable(\n\thead: HTMLElement,\n\tbody: HTMLElement,\n\tkey: string,\n\tcardClass: string\n): HTMLElement {\n\tconst card = document.createElement('div')\n\tcard.className = cardClass\n\tconst open = openCards.has(key)\n\tcard.dataset.open = String(open)\n\thead.classList.add(styles.foldHead)\n\thead.setAttribute('role', 'button')\n\thead.setAttribute('tabindex', '0')\n\thead.setAttribute('aria-expanded', String(open))\n\n\tconst toggle = (): void => {\n\t\tconst next = card.dataset.open !== 'true'\n\t\tcard.dataset.open = String(next)\n\t\thead.setAttribute('aria-expanded', String(next))\n\t\tif (next) openCards.add(key)\n\t\telse openCards.delete(key)\n\t}\n\thead.addEventListener('click', toggle)\n\thead.addEventListener('keydown', (event) => {\n\t\tif (event.key === 'Enter' || event.key === ' ') {\n\t\t\tevent.preventDefault()\n\t\t\ttoggle()\n\t\t}\n\t})\n\n\tconst inner = document.createElement('div')\n\tinner.className = styles.foldInner\n\tinner.append(body)\n\tconst region = document.createElement('div')\n\tregion.className = styles.foldBody\n\tregion.append(inner)\n\tcard.append(head, region)\n\treturn card\n}\n","/**\n * One icon set for the whole panel: 24px grid, 2px rounded strokes, currentColor.\n * Every button uses these so the panel reads as one visual system.\n */\n\nexport type IconName =\n\t| 'code'\n\t| 'scroll'\n\t| 'clock'\n\t| 'check'\n\t| 'question'\n\t| 'list'\n\t| 'cursor'\n\t| 'cursorOff'\n\t| 'chevronUp'\n\t| 'chevronDown'\n\t| 'close'\n\t| 'stop'\n\t| 'mic'\n\t| 'micOff'\n\t| 'keyboard'\n\t| 'send'\n\t| 'spark'\n\t| 'arrowDown'\n\t| 'bookmark'\n\t| 'download'\n\t| 'paperclip'\n\t| 'skills'\n\nconst PATHS: Record<IconName, string> = {\n\tcode: '<path d=\"M8 8l-4 4 4 4\"/><path d=\"M16 8l4 4-4 4\"/><path d=\"M14 5l-4 14\"/>',\n\tscroll: '<path d=\"M12 4v16\"/><path d=\"M8 8l4-4 4 4\"/><path d=\"M8 16l4 4 4-4\"/>',\n\tclock: '<circle cx=\"12\" cy=\"12\" r=\"8\"/><path d=\"M12 8v4l2.5 2\"/>',\n\tcheck: '<path d=\"M5 12.5l4.5 4.5L19 7.5\"/>',\n\tquestion:\n\t\t'<circle cx=\"12\" cy=\"12\" r=\"8\"/><path d=\"M9.5 9.5a2.5 2.5 0 1 1 3.5 2.3c-.7.4-1 .9-1 1.7\"/><path d=\"M12 17h.01\"/>',\n\tlist: '<path d=\"M9 6h11M9 12h11M9 18h11\"/><path d=\"M4 6h.01M4 12h.01M4 18h.01\"/>',\n\tcursor: '<path d=\"M4 4l6.5 16 2.5-6.5L19.5 11z\"/>',\n\tcursorOff: '<path d=\"M4 4l6.5 16 2.5-6.5L19.5 11z\"/><path d=\"M3 3l18 18\"/>',\n\tchevronUp: '<path d=\"M6 15l6-6 6 6\"/>',\n\tchevronDown: '<path d=\"M6 9l6 6 6-6\"/>',\n\tclose: '<path d=\"M6 6l12 12M18 6L6 18\"/>',\n\tstop: '<rect x=\"6\" y=\"6\" width=\"12\" height=\"12\" rx=\"2\"/>',\n\tmic: '<rect x=\"9\" y=\"3\" width=\"6\" height=\"11\" rx=\"3\"/><path d=\"M5 11a7 7 0 0 0 14 0\"/><path d=\"M12 18v3\"/>',\n\tmicOff:\n\t\t'<rect x=\"9\" y=\"3\" width=\"6\" height=\"11\" rx=\"3\"/><path d=\"M5 11a7 7 0 0 0 14 0\"/><path d=\"M12 18v3\"/><path d=\"M3 3l18 18\"/>',\n\tkeyboard:\n\t\t'<rect x=\"2\" y=\"6\" width=\"20\" height=\"12\" rx=\"2\"/><path d=\"M6 10h.01M10 10h.01M14 10h.01M18 10h.01M7 14h10\"/>',\n\tsend: '<path d=\"M12 19V5\"/><path d=\"M5 12l7-7 7 7\"/>',\n\tarrowDown: '<path d=\"M12 5v14\"/><path d=\"M6 13l6 6 6-6\"/>',\n\tbookmark: '<path d=\"M6 3h12v18l-6-4-6 4z\"/>',\n\tdownload: '<path d=\"M12 4v11\"/><path d=\"M7 10l5 5 5-5\"/><path d=\"M5 20h14\"/>',\n\tpaperclip:\n\t\t'<path d=\"M15.5 7.5l-6.8 6.8a2.5 2.5 0 0 0 3.5 3.5l7.2-7.2a4 4 0 0 0-5.7-5.7L6.2 12.4a5.5 5.5 0 0 0 7.8 7.8l6-6\"/>',\n\tskills:\n\t\t'<path d=\"M12 3l2.2 4.5L19 9l-3.5 3.4L16.4 18 12 15.6 7.6 18l.9-5.6L5 9l4.8-1.5L12 3z\"/><circle cx=\"12\" cy=\"12\" r=\"2\"/>',\n\tspark: '<path d=\"M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z\"/>',\n}\n\nexport function icon(name: IconName): string {\n\treturn `<svg viewBox=\"0 0 24 24\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">${PATHS[name]}</svg>`\n}\n","/**\n * Tokenizers for the script card: JavaScript code and the JSON a script returns.\n * Pure functions. Tokens hold plain text only, so rendering them never parses HTML.\n */\n\nexport type TokenKind =\n\t'plain' | 'comment' | 'string' | 'number' | 'keyword' | 'name' | 'punct' | 'key' | 'bool' | 'null'\n\nexport interface Token {\n\tkind: TokenKind\n\ttext: string\n}\n\nconst JS_KEYWORDS = new Set([\n\t'async',\n\t'await',\n\t'break',\n\t'case',\n\t'catch',\n\t'class',\n\t'const',\n\t'continue',\n\t'default',\n\t'delete',\n\t'do',\n\t'else',\n\t'export',\n\t'extends',\n\t'finally',\n\t'for',\n\t'function',\n\t'if',\n\t'import',\n\t'in',\n\t'instanceof',\n\t'let',\n\t'new',\n\t'of',\n\t'return',\n\t'switch',\n\t'throw',\n\t'try',\n\t'typeof',\n\t'var',\n\t'void',\n\t'while',\n\t'yield',\n\t'true',\n\t'false',\n\t'null',\n\t'undefined',\n\t'this',\n])\n\n// Comments, strings (including unterminated ones at the end of a line), numbers, words, whitespace,\n// and any other single character. The alternatives cover every character, so no text is lost.\nconst JS_TOKEN =\n\t/\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$)|'(?:[^'\\\\\\n]|\\\\.)*'?|\"(?:[^\"\\\\\\n]|\\\\.)*\"?|`(?:[^`\\\\]|\\\\.)*`?|\\d+(?:\\.\\d+)?|[A-Za-z_$][\\w$]*|\\s+|[\\s\\S]/g\n\n/** Splits JavaScript source into coloured tokens. Words inside strings and comments are not keywords. */\nexport function jsTokens(code: string): Token[] {\n\tconst tokens: Token[] = []\n\tfor (const match of code.matchAll(JS_TOKEN)) {\n\t\tconst text = match[0]\n\t\ttokens.push({ kind: classifyJs(text), text })\n\t}\n\treturn tokens\n}\n\nfunction classifyJs(text: string): TokenKind {\n\tif (text.startsWith('//') || text.startsWith('/*')) return 'comment'\n\tconst first = text[0]\n\tif (first === \"'\" || first === '\"' || first === '`') return 'string'\n\tif (/^\\d/.test(text)) return 'number'\n\tif (/^[A-Za-z_$]/.test(text)) return JS_KEYWORDS.has(text) ? 'keyword' : 'name'\n\tif (/^\\s+$/.test(text)) return 'plain'\n\treturn 'punct'\n}\n\nconst JSON_TOKEN = /\"(?:[^\"\\\\]|\\\\.)*\"|-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?|true|false|null|\\s+|[\\s\\S]/g\n\n/**\n * Pretty-prints a JSON text and colours it. Returns null when the text is not JSON, so the caller can show it\n * as plain text (for example a string a script returned, or a result cut in the middle).\n */\nexport function jsonTokens(raw: string): Token[] | null {\n\tlet value: unknown\n\ttry {\n\t\tvalue = JSON.parse(raw)\n\t} catch {\n\t\treturn null\n\t}\n\tconst pretty = JSON.stringify(value, null, 2) ?? 'undefined'\n\tconst tokens: Token[] = []\n\tfor (const match of pretty.matchAll(JSON_TOKEN)) {\n\t\tconst text = match[0]\n\t\tconst end = (match.index ?? 0) + text.length\n\t\ttokens.push({ kind: classifyJson(text, pretty.slice(end)), text })\n\t}\n\treturn tokens\n}\n\nfunction classifyJson(text: string, after: string): TokenKind {\n\tif (text.startsWith('\"')) return /^\\s*:/.test(after) ? 'key' : 'string'\n\tif (text === 'true' || text === 'false') return 'bool'\n\tif (text === 'null') return 'null'\n\tif (/^-?\\d/.test(text)) return 'number'\n\tif (/^\\s+$/.test(text)) return 'plain'\n\treturn 'punct'\n}\n\n/** Text without colour, one token. Used for values that are not JSON. */\nexport function plainTokens(text: string): Token[] {\n\treturn [{ kind: 'plain', text }]\n}\n","import type { TranslationKey, TranslationParams } from '../i18n'\nimport { foldable } from './fold'\nimport { type Token, type TokenKind, jsTokens, jsonTokens, plainTokens } from './highlight'\nimport { icon } from './icons'\n\nimport styles from './Panel.module.css'\n\ntype Translate = (key: TranslationKey, params?: TranslationParams) => string\n\nconst OK_PREFIX = '✅ Executed JavaScript. Result: '\nconst ERROR_PREFIX = '❌ Error executing JavaScript: '\n\nconst TOKEN_CLASS: Record<TokenKind, string> = {\n\tplain: '',\n\tcomment: styles.tkComment,\n\tstring: styles.tkString,\n\tnumber: styles.tkNumber,\n\tkeyword: styles.tkKeyword,\n\tname: styles.tkName,\n\tpunct: styles.tkPunct,\n\tkey: styles.tkKey,\n\tbool: styles.tkBool,\n\tnull: styles.tkBool,\n}\n\n/** Splits the text the page controller returns into the value and whether the script succeeded. */\nexport function parseScriptOutput(output: string): { ok: boolean; value: string } {\n\tif (output.startsWith(OK_PREFIX)) return { ok: true, value: output.slice(OK_PREFIX.length) }\n\tif (output.startsWith(ERROR_PREFIX))\n\t\treturn { ok: false, value: output.slice(ERROR_PREFIX.length) }\n\treturn { ok: true, value: output }\n}\n\nfunction codeBlock(tokens: Token[], className: string): HTMLElement {\n\tconst pre = document.createElement('pre')\n\tpre.className = className\n\tfor (const token of tokens) {\n\t\tconst cls = TOKEN_CLASS[token.kind]\n\t\tif (!cls) {\n\t\t\tpre.append(token.text)\n\t\t\tcontinue\n\t\t}\n\t\tconst span = document.createElement('span')\n\t\tspan.className = cls\n\t\tspan.textContent = token.text\n\t\tpre.append(span)\n\t}\n\treturn pre\n}\n\n/**\n * A short preview of a code or result block. It fades out at the bottom when there is more; a click on the block\n * or on its button opens the whole text, and a second click returns to the preview.\n */\nfunction previewBlock(tokens: Token[], className: string, t: Translate): HTMLElement {\n\tconst wrap = document.createElement('div')\n\twrap.className = styles.clip\n\twrap.dataset.open = 'false'\n\tconst pre = codeBlock(tokens, `${className} ${styles.clipBody}`)\n\tconst toggle = document.createElement('button')\n\ttoggle.type = 'button'\n\ttoggle.className = styles.clipToggle\n\ttoggle.hidden = true\n\ttoggle.textContent = t('ui.panel.codeShowMore')\n\tconst flip = (): void => {\n\t\tconst open = wrap.dataset.open !== 'true'\n\t\twrap.dataset.open = String(open)\n\t\ttoggle.textContent = open ? t('ui.panel.codeShowLess') : t('ui.panel.codeShowMore')\n\t}\n\tpre.addEventListener('click', flip)\n\ttoggle.addEventListener('click', flip)\n\twrap.append(pre, toggle)\n\t// Measured after the card is in the feed: only blocks taller than the preview get the fade and the button.\n\trequestAnimationFrame(() => {\n\t\tconst clipped = pre.scrollHeight > pre.clientHeight + 1\n\t\twrap.dataset.clipped = String(clipped)\n\t\ttoggle.hidden = !clipped\n\t})\n\treturn wrap\n}\n\nfunction section(label: string, body: HTMLElement): HTMLElement {\n\tconst wrap = document.createElement('div')\n\twrap.className = styles.codeSection\n\tconst title = document.createElement('small')\n\ttitle.className = styles.codeLabel\n\ttitle.textContent = label\n\twrap.append(title, body)\n\treturn wrap\n}\n\n/**\n * Card for one execute_javascript call. It starts folded, showing its title and state; opened, it shows the script\n * coloured as JavaScript and the result coloured as JSON (plain text when it is not JSON).\n */\nexport function scriptCard(options: {\n\tscript: string\n\toutput?: string\n\tt: Translate\n\t/** Where the script came from. Voice scripts are labelled as such. */\n\tsource?: 'agent' | 'voice'\n\t/** A voice script the panel did not run. */\n\trefused?: boolean\n\t/** Time the script was requested, shown in the header. */\n\ttime?: string\n\t/** Stable key for remembering whether the card is open. */\n\tkey: string\n}): HTMLElement {\n\tconst { script, output, t, source = 'agent', refused = false, time, key } = options\n\tconst parsed = output === undefined ? null : parseScriptOutput(output)\n\tconst status = refused ? 'refused' : parsed === null ? 'running' : parsed.ok ? 'done' : 'error'\n\n\tconst head = document.createElement('div')\n\thead.className = styles.codeHead\n\tconst title = document.createElement('span')\n\ttitle.className = styles.codeTitle\n\ttitle.textContent = t('ui.panel.codeTitle')\n\tconst meta = document.createElement('span')\n\tmeta.className = styles.codeMeta\n\tif (source === 'voice') {\n\t\tconst badge = document.createElement('span')\n\t\tbadge.className = styles.codeBadge\n\t\tbadge.textContent = t('ui.panel.codeVoice')\n\t\tmeta.append(badge)\n\t}\n\tif (time) meta.append(time)\n\tconst state = document.createElement('span')\n\tstate.className = styles.codeStatus\n\tstate.textContent =\n\t\tstatus === 'running'\n\t\t\t? t('ui.panel.codeRunning')\n\t\t\t: status === 'done'\n\t\t\t\t? t('ui.panel.codeDone')\n\t\t\t\t: status === 'refused'\n\t\t\t\t\t? t('ui.panel.codeRefused')\n\t\t\t\t\t: t('ui.panel.codeFailed')\n\tconst chip = document.createElement('span')\n\tchip.className = styles.toolChip\n\tchip.innerHTML = icon('code')\n\thead.append(chip, title, meta, state)\n\n\tconst body = document.createElement('div')\n\tbody.append(\n\t\tsection(t('ui.panel.codeScript'), previewBlock(jsTokens(script), styles.codeBlock, t))\n\t)\n\tif (refused && output !== undefined) {\n\t\tbody.append(\n\t\t\tsection(t('ui.panel.codeRefused'), previewBlock(plainTokens(output), styles.resultBlock, t))\n\t\t)\n\t} else if (parsed) {\n\t\tconst value = parsed.value\n\t\tconst tokens = parsed.ok ? (jsonTokens(value) ?? plainTokens(value)) : plainTokens(value)\n\t\tconst label = t(parsed.ok ? 'ui.panel.codeResult' : 'ui.panel.codeError')\n\t\tbody.append(section(label, previewBlock(tokens, styles.resultBlock, t)))\n\t}\n\n\tconst card = foldable(head, body, key, styles.code)\n\tcard.dataset.status = status\n\tcard.dataset.tone = 'js'\n\treturn card\n}\n","/**\n * The visual identity of each tool: an icon, a colour tone and a one-line summary. Pure functions.\n * REVERSIBLE (2026-11-17, tool visuals): delete this file and its uses in feed.ts and scriptCard.ts.\n */\nimport { truncate } from '../utils'\nimport type { IconName } from './icons'\n\nexport type ToolTone = 'js' | 'task' | 'move' | 'act' | 'time' | 'done' | 'ask' | 'generic'\n\nexport interface ToolVisual {\n\ticon: IconName\n\ttone: ToolTone\n\t/** Short, factual detail for the folded card. Empty when there is nothing short to show. */\n\tsummary: string\n}\n\n/** Reads a value as text only when it already is text or a number; anything else gives an empty string. */\nconst textOf = (value: unknown): string =>\n\ttypeof value === 'string' || typeof value === 'number' ? String(value) : ''\n\nconst indexOf = (input: unknown): string => {\n\tconst index = (input as { index?: unknown } | undefined)?.index\n\treturn typeof index === 'number' ? `#${index}` : ''\n}\n\n/** The visual of a tool call, from its name, its input and its output text. */\nexport function toolVisual(name: string, input: unknown, output: string | undefined): ToolVisual {\n\tconst args = (input ?? {}) as Record<string, unknown>\n\tswitch (name) {\n\t\tcase 'execute_javascript':\n\t\t\treturn { icon: 'code', tone: 'js', summary: '' }\n\t\tcase 'run_task':\n\t\t\treturn { icon: 'spark', tone: 'task', summary: truncate(textOf(args.task), 32) }\n\t\tcase 'scroll': {\n\t\t\tconst px = /([\\d.]+)px/.exec(output ?? '')?.[1]\n\t\t\treturn { icon: 'scroll', tone: 'move', summary: px ? `${Math.round(Number(px))} px` : '' }\n\t\t}\n\t\tcase 'click_element_by_index':\n\t\t\treturn { icon: 'cursor', tone: 'act', summary: indexOf(input) }\n\t\tcase 'hover_element':\n\t\t\treturn { icon: 'cursor', tone: 'move', summary: indexOf(input) }\n\t\tcase 'double_click_element':\n\t\t\treturn { icon: 'cursor', tone: 'act', summary: indexOf(input) }\n\t\tcase 'press_key':\n\t\t\treturn { icon: 'keyboard', tone: 'act', summary: truncate(textOf(args.key), 24) }\n\t\tcase 'focus_element':\n\t\t\treturn { icon: 'cursor', tone: 'act', summary: indexOf(input) }\n\t\tcase 'set_checked':\n\t\t\treturn {\n\t\t\t\ticon: 'check',\n\t\t\t\ttone: 'act',\n\t\t\t\tsummary: `${indexOf(input)} ${args.checked === false ? 'off' : 'on'}`.trim(),\n\t\t\t}\n\t\tcase 'set_range':\n\t\t\treturn {\n\t\t\t\ticon: 'list',\n\t\t\t\ttone: 'act',\n\t\t\t\tsummary: `${indexOf(input)} ${textOf(args.value)}`.trim(),\n\t\t\t}\n\t\tcase 'scroll_into_view':\n\t\t\treturn { icon: 'scroll', tone: 'move', summary: indexOf(input) }\n\t\tcase 'wheel': {\n\t\t\tconst delta = textOf(args.delta_y)\n\t\t\treturn {\n\t\t\t\ticon: 'scroll',\n\t\t\t\ttone: 'move',\n\t\t\t\tsummary: delta || indexOf(input),\n\t\t\t}\n\t\t}\n\t\tcase 'drag_element': {\n\t\t\tconst from = (input as { source_index?: unknown } | undefined)?.source_index\n\t\t\tconst to = (input as { target_index?: unknown } | undefined)?.target_index\n\t\t\tconst summary = typeof from === 'number' && typeof to === 'number' ? `#${from} → #${to}` : ''\n\t\t\treturn { icon: 'cursor', tone: 'move', summary }\n\t\t}\n\t\tcase 'input_text':\n\t\t\treturn { icon: 'keyboard', tone: 'act', summary: indexOf(input) }\n\t\tcase 'select_dropdown_option':\n\t\t\treturn { icon: 'list', tone: 'act', summary: truncate(textOf(args.text), 24) }\n\t\tcase 'wait':\n\t\t\treturn {\n\t\t\t\ticon: 'clock',\n\t\t\t\ttone: 'time',\n\t\t\t\tsummary: textOf(args.seconds) ? `${textOf(args.seconds)}s` : '',\n\t\t\t}\n\t\tcase 'done':\n\t\t\treturn { icon: 'check', tone: 'done', summary: args.success === false ? 'não' : 'ok' }\n\t\tcase 'ask_user':\n\t\t\treturn { icon: 'question', tone: 'ask', summary: truncate(textOf(args.question), 32) }\n\t\tcase 'get_context': {\n\t\t\tconst yMin = textOf(args.y_min)\n\t\t\tconst yMax = textOf(args.y_max)\n\t\t\tconst band = yMin || yMax ? `${yMin || '0'}–${yMax || '…'}` : 'viewport'\n\t\t\treturn { icon: 'list', tone: 'generic', summary: truncate(band, 24) }\n\t\t}\n\t\tdefault:\n\t\t\treturn { icon: 'spark', tone: 'generic', summary: '' }\n\t}\n}\n","import type { TranslationKey, TranslationParams } from '../i18n'\nimport { truncate } from '../utils'\nimport { foldable } from './fold'\nimport { icon } from './icons'\nimport { scriptCard } from './scriptCard'\nimport { type ToolVisual, toolVisual } from './toolVisual'\nimport type { AgentActivity, PanelAgentAdapter } from './types'\n\nimport styles from './Panel.module.css'\n\ntype Translate = (key: TranslationKey, params?: TranslationParams) => string\ntype HistoryEvent = PanelAgentAdapter['history'][number]\n\nexport type ResultKind = 'done' | 'notDone' | 'stopped' | 'error'\n\n/**\n * The core reports some events as English sentences. Translate the known ones for display only;\n * anything else (the model's own words, page text, tool outputs) is shown as it is.\n */\nexport function localizeCore(text: string, t: Translate): string {\n\tlet m: RegExpMatchArray | null\n\tif (text === 'Task aborted') return t('ui.panel.msgAborted')\n\tif (text === 'Task completed') return t('ui.panel.msgCompleted')\n\tif (text === 'Step count exceeded maximum limit') return t('ui.panel.msgStepLimit')\n\tif ((m = /^LLM retry attempt (\\d+) of (\\d+)$/.exec(text)))\n\t\treturn t('ui.panel.msgRetry', { attempt: m[1], max: m[2] })\n\tif ((m = /^Page navigated to → (.*)$/.exec(text)))\n\t\treturn t('ui.panel.msgNavigated', { url: m[1] })\n\tif ((m = /^You have waited (\\d+) seconds accumulatively/.exec(text)))\n\t\treturn t('ui.panel.msgWaited', { seconds: m[1] })\n\tif ((m = /^⚠️ Only (\\d+) steps remaining/.exec(text)))\n\t\treturn t('ui.panel.msgStepsLeft', { count: m[1] })\n\tif ((m = /^⚠️ Critical: Only (\\d+) steps left/.exec(text)))\n\t\treturn t('ui.panel.msgStepsCritical', { count: m[1] })\n\treturn text\n}\n\nexport interface FeedModel {\n\t/** Keys the cards of this run, so their open state is remembered. */\n\tkey?: string\n\ttask: string\n\thistory: readonly HistoryEvent[]\n\tlive: AgentActivity | null\n\tquestion: string | null\n\tresult: { kind: ResultKind; text: string } | null\n}\n\nfunction node<K extends keyof HTMLElementTagNameMap>(\n\ttag: K,\n\tclassName: string,\n\ttext?: string\n): HTMLElementTagNameMap[K] {\n\tconst el = document.createElement(tag)\n\tel.className = className\n\tif (text !== undefined) el.textContent = text\n\treturn el\n}\n\nfunction spinner(): HTMLElement {\n\treturn node('span', styles.spinner)\n}\n\n/** Human-readable label for a tool call, shown on the tool card. */\nexport function toolLabel(name: string, input: unknown, t: Translate): string {\n\tconst a = (input ?? {}) as Record<string, string | number>\n\tswitch (name) {\n\t\tcase 'click_element_by_index':\n\t\t\treturn t('ui.tools.clicking', { index: a.index })\n\t\tcase 'input_text':\n\t\t\treturn t('ui.tools.inputting', { index: a.index })\n\t\tcase 'select_dropdown_option':\n\t\t\treturn t('ui.tools.selecting', { text: a.text })\n\t\tcase 'scroll':\n\t\t\treturn t('ui.tools.scrolling')\n\t\tcase 'wait':\n\t\t\treturn t('ui.tools.waiting', { seconds: a.seconds })\n\t\tcase 'ask_user':\n\t\t\treturn t('ui.tools.askingUser')\n\t\tcase 'done':\n\t\t\treturn t('ui.tools.done')\n\t\tdefault:\n\t\t\treturn t('ui.tools.executing', { toolName: name })\n\t}\n}\n\nfunction stepPrefix(event: HistoryEvent, t: Translate): string | undefined {\n\treturn event.type === 'step' && event.stepIndex !== undefined\n\t\t? t('ui.panel.step', { number: String(event.stepIndex + 1) })\n\t\t: undefined\n}\n\nfunction userBubble(text: string): HTMLElement {\n\treturn node('div', styles.bubble, text)\n}\n\nfunction line(text: string, extraClass = ''): HTMLElement {\n\treturn node('div', `${styles.line} ${extraClass}`.trim(), text)\n}\n\n/**\n * A tool call card. It starts folded, with its label and state; opened, it shows the detail text.\n * REVERSIBLE (2026-11-17, card folding).\n */\nfunction toolCard(\n\tlabel: string,\n\tdetail: string,\n\tstatus: 'done' | 'running' | 'error',\n\tkey: string,\n\tvisual: ToolVisual = { icon: 'spark', tone: 'generic', summary: '' }\n): HTMLElement {\n\tconst chip = node('span', styles.toolChip)\n\tchip.innerHTML = icon(visual.icon)\n\tconst head = node('div', styles.toolHead)\n\thead.append(\n\t\tchip,\n\t\tnode('span', styles.toolLabel, label),\n\t\tnode('span', styles.toolSummary, visual.summary),\n\t\tstatus === 'running'\n\t\t\t? spinner()\n\t\t\t: node('span', styles.toolState, status === 'error' ? '!' : '✓')\n\t)\n\tconst body = node('div', '')\n\tif (detail) body.append(node('div', styles.toolDetail, truncate(detail, 240)))\n\tconst card = foldable(head, body, key, styles.tool)\n\tcard.dataset.status = status\n\tcard.dataset.tone = visual.tone\n\treturn card\n}\n\nfunction questionCard(text: string, t: Translate, pending: boolean): HTMLElement {\n\tconst card = node('div', styles.question)\n\tcard.dataset.pending = String(pending)\n\tcard.append(\n\t\tnode('small', styles.questionTag, t('ui.panel.questionTitle')),\n\t\tnode('p', styles.questionText, text)\n\t)\n\treturn card\n}\n\nfunction markedQuestion(text: string, t: Translate, pending: boolean): HTMLElement {\n\tconst card = questionCard(text, t, pending)\n\tcard.dataset.mark = 'question'\n\treturn card\n}\n\nfunction resultCard(kind: ResultKind, text: string, t: Translate): HTMLElement {\n\tconst titles: Record<ResultKind, TranslationKey> = {\n\t\tdone: 'ui.panel.resultDone',\n\t\tnotDone: 'ui.panel.resultNotDone',\n\t\tstopped: 'ui.panel.resultStopped',\n\t\terror: 'ui.panel.resultError',\n\t}\n\tconst card = node('div', styles.result)\n\tcard.dataset.kind = kind\n\tcard.append(node('strong', '', t(titles[kind])))\n\tif (text) card.append(node('div', styles.resultText, localizeCore(text, t)))\n\treturn card\n}\n\n/** Turns the agent history and live activity into feed nodes. Only text is set via textContent. */\nexport function buildFeed(model: FeedModel, t: Translate): HTMLElement[] {\n\tconst nodes: HTMLElement[] = []\n\tif (model.task) {\n\t\tconst turn = userBubble(model.task)\n\t\tturn.dataset.mark = 'turn'\n\t\tnodes.push(turn)\n\t}\n\n\tconst runKey = model.key ?? 'current'\n\tfor (const [index, event] of model.history.entries()) {\n\t\tconst prefix = stepPrefix(event, t)\n\t\tif (event.type === 'step') {\n\t\t\tconst r = event.reflection\n\t\t\tif (r) {\n\t\t\t\tconst parts: string[] = []\n\t\t\t\tif (r.evaluation_previous_goal)\n\t\t\t\t\tparts.push(`${t('ui.panel.evaluation')}: ${r.evaluation_previous_goal}`)\n\t\t\t\tif (r.memory) parts.push(`${t('ui.panel.memory')}: ${r.memory}`)\n\t\t\t\tif (r.next_goal) parts.push(`${t('ui.panel.nextGoal')}: ${r.next_goal}`)\n\t\t\t\tif (parts.length) nodes.push(line(parts.join('\\n'), styles.reflection))\n\t\t\t}\n\t\t\tconst action = event.action\n\t\t\tif (!action || action.name === 'done') continue\n\t\t\tif (action.name === 'ask_user') {\n\t\t\t\tconst question = (action.input as { question?: string })?.question ?? ''\n\t\t\t\tnodes.push(markedQuestion(question, t, false))\n\t\t\t\tconst answer = action.output.replace(/^User answered:\\s*/i, '')\n\t\t\t\tif (answer) nodes.push(userBubble(answer))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (action.name === 'execute_javascript') {\n\t\t\t\tconst script = (action.input as { script?: string })?.script ?? ''\n\t\t\t\tnodes.push(scriptCard({ script, output: action.output, t, key: `${runKey}:${index}` }))\n\t\t\t\tif (prefix) nodes[nodes.length - 1].dataset.step = prefix\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnodes.push(\n\t\t\t\ttoolCard(\n\t\t\t\t\ttoolLabel(action.name, action.input, t),\n\t\t\t\t\taction.output,\n\t\t\t\t\t'done',\n\t\t\t\t\t`${runKey}:${index}`,\n\t\t\t\t\ttoolVisual(action.name, action.input, action.output)\n\t\t\t\t)\n\t\t\t)\n\t\t\tif (prefix) nodes[nodes.length - 1].dataset.step = prefix\n\t\t} else if (event.type === 'observation') {\n\t\t\tif (event.content) nodes.push(line(localizeCore(event.content, t), styles.observation))\n\t\t} else if (event.type === 'user_takeover') {\n\t\t\tnodes.push(line(t('ui.panel.userTakeover'), styles.observation))\n\t\t} else if (event.type === 'retry') {\n\t\t\tnodes.push(line(localizeCore(event.message ?? '', t), styles.warning))\n\t\t} else if (event.type === 'error') {\n\t\t\tnodes.push(\n\t\t\t\ttoolCard(localizeCore(event.message ?? 'Error', t), '', 'error', `${runKey}:${index}`)\n\t\t\t)\n\t\t}\n\t}\n\n\tconst live = model.live\n\tif (live?.type === 'thinking') nodes.push(line(t('ui.panel.thinking'), styles.live))\n\tif (live?.type === 'executing' && live.tool === 'execute_javascript')\n\t\tnodes.push(\n\t\t\tscriptCard({\n\t\t\t\tscript: (live.input as { script?: string })?.script ?? '',\n\t\t\t\tt,\n\t\t\t\tkey: `${runKey}:live`,\n\t\t\t})\n\t\t)\n\telse if (live?.type === 'executing')\n\t\tnodes.push(\n\t\t\ttoolCard(\n\t\t\t\ttoolLabel(live.tool, live.input, t),\n\t\t\t\t'',\n\t\t\t\t'running',\n\t\t\t\t`${runKey}:live`,\n\t\t\t\ttoolVisual(live.tool, live.input, undefined)\n\t\t\t)\n\t\t)\n\tif (live?.type === 'retrying')\n\t\tnodes.push(\n\t\t\tline(\n\t\t\t\tt('ui.panel.statusRetrying', {\n\t\t\t\t\tattempt: String(live.attempt),\n\t\t\t\t\tmax: String(live.maxAttempts),\n\t\t\t\t}),\n\t\t\t\tstyles.live\n\t\t\t)\n\t\t)\n\n\tif (model.question) nodes.push(markedQuestion(model.question, t, true))\n\tif (model.result) {\n\t\tconst result = resultCard(model.result.kind, model.result.text, t)\n\t\tresult.dataset.mark = 'result'\n\t\tnodes.push(result)\n\t}\n\n\tfor (const n of nodes) n.classList.add(styles.enter)\n\treturn nodes\n}\n\n/** Latest text the agent reported with `done`, or the latest error message. */\nexport function lastOutcomeText(history: readonly HistoryEvent[]): string {\n\tfor (let i = history.length - 1; i >= 0; i--) {\n\t\tconst e = history[i]\n\t\tif (e.type === 'step' && e.action?.name === 'done') {\n\t\t\tconst input = e.action.input as { text?: string }\n\t\t\treturn input?.text || e.action.output || ''\n\t\t}\n\t\tif (e.type === 'error' && e.message) return e.message\n\t}\n\treturn ''\n}\n","/**\n * Microphone lifecycle for the panel's voice mode.\n *\n * - Enabling asks the browser for permission and opens the microphone.\n * - Muting or turning voice off stops every track, so the browser stops showing the mic as in use.\n * - After permission, the control can list inputs and switch between them (phone vs Bluetooth, etc.).\n * - No audio is recorded or sent here. A voice engine that needs audio reads `stream` while it is open.\n */\n\nexport type MicState = 'off' | 'active' | 'muted' | 'denied' | 'unsupported' | 'busy'\n\nexport interface MicDevice {\n\tdeviceId: string\n\tlabel: string\n}\n\n/** Score used to prefer a built-in mic over a Bluetooth headset when several inputs exist. */\nexport function micPreferenceScore(label: string): number {\n\tconst l = label.toLowerCase()\n\tif (/bluetooth|airpods|headset|hands[- ]?free|\\bwh-|\\bbuds\\b|galaxy buds|freebuds/.test(l))\n\t\treturn 0\n\tif (/default|communications/.test(l)) return 1\n\tif (/built-?in|internal|iphone|android|pixel|samsung|macbook|realtek|microphone \\(/.test(l))\n\t\treturn 3\n\tif (/microphone|mic/.test(l)) return 2\n\treturn 1\n}\n\nexport class MicrophoneControl {\n\t#stream: MediaStream | null = null\n\t#state: MicState = 'off'\n\t#wanted = false\n\t#attempt = 0\n\t#deviceId: string | null = null\n\t#label = ''\n\t#hardwareMuted = false\n\t#onChange: () => void\n\t#trackCleanups: (() => void)[] = []\n\n\tconstructor(onChange: () => void) {\n\t\tthis.#onChange = onChange\n\t}\n\n\tget state(): MicState {\n\t\treturn this.#state\n\t}\n\n\t/** Open stream while the microphone is in use; null when released (off, muted, denied). */\n\tget stream(): MediaStream | null {\n\t\treturn this.#stream\n\t}\n\n\t/** Label of the open input, once permission has been granted. Empty before that. */\n\tget label(): string {\n\t\treturn this.#label\n\t}\n\n\t/** deviceId of the open input, when known. */\n\tget deviceId(): string | null {\n\t\treturn this.#deviceId\n\t}\n\n\t/**\n\t * True when the OS reports the track as muted (common with a Bluetooth headset that is not\n\t * sending audio). The stream can still look \"active\" while nothing reaches the model.\n\t */\n\tget hardwareMuted(): boolean {\n\t\treturn this.#hardwareMuted\n\t}\n\n\t/** Inputs available after permission. Labels are empty before the first successful enable. */\n\tasync listInputs(): Promise<MicDevice[]> {\n\t\tif (!navigator.mediaDevices?.enumerateDevices) return []\n\t\tconst devices = await navigator.mediaDevices.enumerateDevices()\n\t\treturn devices\n\t\t\t.filter((d) => d.kind === 'audioinput' && d.deviceId)\n\t\t\t.map((d) => ({\n\t\t\t\tdeviceId: d.deviceId,\n\t\t\t\tlabel: d.label || `Microphone ${d.deviceId.slice(0, 6)}`,\n\t\t\t}))\n\t}\n\n\t/** User turned voice on: request permission and open the microphone. */\n\tasync enable(deviceId?: string): Promise<void> {\n\t\tthis.#wanted = true\n\t\tconst attempt = ++this.#attempt\n\t\tif (!navigator.mediaDevices?.getUserMedia) {\n\t\t\tthis.#set('unsupported')\n\t\t\treturn\n\t\t}\n\t\tconst preferred = deviceId ?? this.#deviceId ?? undefined\n\t\ttry {\n\t\t\tconst stream = await navigator.mediaDevices.getUserMedia({\n\t\t\t\taudio: audioConstraints(preferred),\n\t\t\t})\n\t\t\t// The user may have muted or left voice while the prompt was open.\n\t\t\tif (attempt !== this.#attempt || !this.#wanted) {\n\t\t\t\tstopTracks(stream)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.#adopt(stream)\n\n\t\t\t// After permission, labels exist. Prefer a built-in mic over Bluetooth when the caller\n\t\t\t// did not ask for a specific device and a better one is available.\n\t\t\tif (!preferred) {\n\t\t\t\tconst better = await this.#preferredDeviceId(stream)\n\t\t\t\tif (better && better !== this.#deviceId && attempt === this.#attempt && this.#wanted) {\n\t\t\t\t\tconst switched = await navigator.mediaDevices.getUserMedia({\n\t\t\t\t\t\taudio: audioConstraints(better),\n\t\t\t\t\t})\n\t\t\t\t\tif (attempt !== this.#attempt || !this.#wanted) {\n\t\t\t\t\t\tstopTracks(switched)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tstopTracks(stream)\n\t\t\t\t\tthis.#adopt(switched)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.#set('active')\n\t\t} catch (error) {\n\t\t\tif (attempt !== this.#attempt) return\n\t\t\tthis.#set(classifyGetUserMediaError(error))\n\t\t}\n\t}\n\n\t/**\n\t * Switch to the next audio input and reopen the stream. No-op with fewer than two devices.\n\t * Returns true when the stream was reopened on a different device.\n\t */\n\tasync cycleInput(): Promise<boolean> {\n\t\tconst devices = await this.listInputs()\n\t\tif (devices.length < 2) return false\n\t\tconst current = this.#deviceId ?? devices[0]!.deviceId\n\t\tconst index = Math.max(\n\t\t\t0,\n\t\t\tdevices.findIndex((d) => d.deviceId === current)\n\t\t)\n\t\tconst next = devices[(index + 1) % devices.length]!\n\t\tif (next.deviceId === current) return false\n\t\tthis.#deviceId = next.deviceId\n\t\tif (!this.#wanted || this.#state === 'muted' || this.#state === 'off') return false\n\t\tawait this.enable(next.deviceId)\n\t\treturn this.#state === 'active' && this.#deviceId === next.deviceId\n\t}\n\n\t/** Mute releases the microphone; unmute asks again. */\n\tsetMuted(muted: boolean): void {\n\t\tif (muted) {\n\t\t\tthis.#attempt++\n\t\t\tthis.#release()\n\t\t\tthis.#set('muted')\n\t\t\treturn\n\t\t}\n\t\tvoid this.enable(this.#deviceId ?? undefined)\n\t}\n\n\t/** Voice turned off: release the microphone and forget the request. */\n\tdisable(): void {\n\t\tthis.#wanted = false\n\t\tthis.#attempt++\n\t\tthis.#release()\n\t\tthis.#set('off')\n\t}\n\n\t#adopt(stream: MediaStream): void {\n\t\tthis.#clearTrackListeners()\n\t\tthis.#stream = stream\n\t\tconst track = stream.getAudioTracks()[0]\n\t\tif (!track) {\n\t\t\tthis.#label = ''\n\t\t\tthis.#deviceId = null\n\t\t\tthis.#hardwareMuted = false\n\t\t\treturn\n\t\t}\n\t\tthis.#label = track.label || this.#label\n\t\tconst settings = track.getSettings?.() ?? {}\n\t\tif (typeof settings.deviceId === 'string' && settings.deviceId) {\n\t\t\tthis.#deviceId = settings.deviceId\n\t\t}\n\t\tthis.#hardwareMuted = track.muted\n\t\tconst onMute = () => {\n\t\t\tthis.#hardwareMuted = true\n\t\t\tthis.#onChange()\n\t\t}\n\t\tconst onUnmute = () => {\n\t\t\tthis.#hardwareMuted = false\n\t\t\tthis.#onChange()\n\t\t}\n\t\tconst onEnded = () => {\n\t\t\tif (this.#stream === stream) {\n\t\t\t\tthis.#release()\n\t\t\t\tif (this.#wanted) this.#set('unsupported')\n\t\t\t}\n\t\t}\n\t\ttrack.addEventListener('mute', onMute)\n\t\ttrack.addEventListener('unmute', onUnmute)\n\t\ttrack.addEventListener('ended', onEnded)\n\t\tthis.#trackCleanups.push(() => {\n\t\t\ttrack.removeEventListener('mute', onMute)\n\t\t\ttrack.removeEventListener('unmute', onUnmute)\n\t\t\ttrack.removeEventListener('ended', onEnded)\n\t\t})\n\t}\n\n\tasync #preferredDeviceId(current: MediaStream): Promise<string | null> {\n\t\tconst devices = await this.listInputs()\n\t\tif (devices.length < 2) return null\n\t\tconst currentId =\n\t\t\tcurrent.getAudioTracks()[0]?.getSettings?.().deviceId ??\n\t\t\tthis.#deviceId ??\n\t\t\tdevices[0]!.deviceId\n\t\tconst currentLabel =\n\t\t\tdevices.find((d) => d.deviceId === currentId)?.label ??\n\t\t\tcurrent.getAudioTracks()[0]?.label ??\n\t\t\t''\n\t\tconst ranked = [...devices].sort(\n\t\t\t(a, b) => micPreferenceScore(b.label) - micPreferenceScore(a.label)\n\t\t)\n\t\tconst best = ranked[0]!\n\t\tif (micPreferenceScore(best.label) <= micPreferenceScore(currentLabel)) return null\n\t\tif (best.deviceId === currentId) return null\n\t\treturn best.deviceId\n\t}\n\n\t#clearTrackListeners(): void {\n\t\tfor (const stop of this.#trackCleanups) stop()\n\t\tthis.#trackCleanups = []\n\t}\n\n\t#release(): void {\n\t\tthis.#clearTrackListeners()\n\t\tif (this.#stream) stopTracks(this.#stream)\n\t\tthis.#stream = null\n\t\tthis.#hardwareMuted = false\n\t\t// Keep deviceId and label so unmute / cycle reopen the same choice and the UI can still name it.\n\t}\n\n\t#set(state: MicState): void {\n\t\tif (this.#state === state) return\n\t\tthis.#state = state\n\t\tthis.#onChange()\n\t}\n}\n\nfunction audioConstraints(deviceId?: string): MediaTrackConstraints {\n\tconst constraints: MediaTrackConstraints = {\n\t\techoCancellation: true,\n\t\tnoiseSuppression: true,\n\t\tautoGainControl: true,\n\t}\n\tif (deviceId) constraints.deviceId = { exact: deviceId }\n\treturn constraints\n}\n\nfunction classifyGetUserMediaError(error: unknown): MicState {\n\tconst name = error instanceof DOMException ? error.name : ''\n\tif (name === 'NotAllowedError' || name === 'SecurityError') return 'denied'\n\tif (name === 'NotReadableError' || name === 'AbortError') return 'busy'\n\treturn 'unsupported'\n}\n\nfunction stopTracks(stream: MediaStream): void {\n\tfor (const track of stream.getTracks()) track.stop()\n}\n","import type { ResultKind } from './feed'\nimport type { PanelAgentAdapter } from './types'\nimport type { VoiceRun } from './voiceRuns'\n\ntype HistoryEvent = PanelAgentAdapter['history'][number]\nexport interface RecoveredRun {\n\ttask: string\n\thistory: HistoryEvent[]\n\tresult: { kind: ResultKind; text: string } | null\n\tvoiceRuns: VoiceRun[]\n}\ntype StoragePort = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>\nconst KEY = 'page-agent-panel-recovery-v1'\nconst sensitive = /password|passwd|secret|token|api.?key|authorization|cookie/i\n\nfunction redact(value: unknown, depth = 0): unknown {\n\tif (depth > 8) return '[omitted]'\n\tif (Array.isArray(value)) return value.map((item) => redact(item, depth + 1))\n\tif (value && typeof value === 'object')\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(value).map(([key, item]) => [\n\t\t\t\tkey,\n\t\t\t\tsensitive.test(key) ? '[hidden]' : redact(item, depth + 1),\n\t\t\t])\n\t\t)\n\treturn value\n}\n\nfunction cleanEvent(event: HistoryEvent): HistoryEvent {\n\treturn {\n\t\ttype: event.type,\n\t\t...(event.stepIndex !== undefined ? { stepIndex: event.stepIndex } : {}),\n\t\t...(event.reflection ? { reflection: event.reflection } : {}),\n\t\t...(event.action\n\t\t\t? {\n\t\t\t\t\taction: {\n\t\t\t\t\t\tname: event.action.name,\n\t\t\t\t\t\tinput: redact(event.action.input),\n\t\t\t\t\t\toutput: event.action.output,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(event.content !== undefined ? { content: event.content } : {}),\n\t\t...(event.attempt !== undefined ? { attempt: event.attempt } : {}),\n\t\t...(event.maxAttempts !== undefined ? { maxAttempts: event.maxAttempts } : {}),\n\t\t...(event.message !== undefined ? { message: event.message } : {}),\n\t}\n}\n\n/** Tab-scoped display recovery. It never resumes a task or replays an action. */\nexport function createPanelRecovery(storage: StoragePort, key = KEY) {\n\treturn {\n\t\tload(): RecoveredRun[] {\n\t\t\tconst raw = storage.getItem(key)\n\t\t\tif (raw === null) return []\n\t\t\tconst data: unknown = JSON.parse(raw)\n\t\t\tif (\n\t\t\t\t!data ||\n\t\t\t\ttypeof data !== 'object' ||\n\t\t\t\t!('version' in data) ||\n\t\t\t\tdata.version !== 1 ||\n\t\t\t\t!('runs' in data) ||\n\t\t\t\t!Array.isArray(data.runs)\n\t\t\t)\n\t\t\t\tthrow new Error('Invalid recovery data')\n\t\t\tfor (const run of data.runs) {\n\t\t\t\tif (\n\t\t\t\t\t!run ||\n\t\t\t\t\ttypeof run !== 'object' ||\n\t\t\t\t\ttypeof run.task !== 'string' ||\n\t\t\t\t\t!Array.isArray(run.history) ||\n\t\t\t\t\t!Array.isArray(run.voiceRuns) ||\n\t\t\t\t\trun.history.some(\n\t\t\t\t\t\t(event: unknown) =>\n\t\t\t\t\t\t\t!event ||\n\t\t\t\t\t\t\ttypeof event !== 'object' ||\n\t\t\t\t\t\t\t!('type' in event) ||\n\t\t\t\t\t\t\t!['step', 'observation', 'user_takeover', 'retry', 'error'].includes(\n\t\t\t\t\t\t\t\tString(event.type)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t) ||\n\t\t\t\t\trun.voiceRuns.some(\n\t\t\t\t\t\t(voice: unknown) =>\n\t\t\t\t\t\t\t!voice ||\n\t\t\t\t\t\t\ttypeof voice !== 'object' ||\n\t\t\t\t\t\t\t!('id' in voice) ||\n\t\t\t\t\t\t\t!('script' in voice) ||\n\t\t\t\t\t\t\t!('status' in voice) ||\n\t\t\t\t\t\t\t!('at' in voice)\n\t\t\t\t\t) ||\n\t\t\t\t\t(run.result !== null &&\n\t\t\t\t\t\t(!run.result ||\n\t\t\t\t\t\t\ttypeof run.result !== 'object' ||\n\t\t\t\t\t\t\t!['done', 'notDone', 'stopped', 'error'].includes(run.result.kind) ||\n\t\t\t\t\t\t\ttypeof run.result.text !== 'string'))\n\t\t\t\t)\n\t\t\t\t\tthrow new Error('Invalid recovery run')\n\t\t\t}\n\t\t\treturn data.runs as RecoveredRun[]\n\t\t},\n\t\tsave(runs: RecoveredRun[]): void {\n\t\t\tconst clean = runs.map((run) => ({ ...run, history: run.history.map(cleanEvent) }))\n\t\t\tstorage.setItem(key, JSON.stringify({ version: 1, runs: clean }))\n\t\t},\n\t\tclear(): void {\n\t\t\tstorage.removeItem(key)\n\t\t},\n\t}\n}\n","import type { TranslationKey, TranslationParams } from '../i18n'\nimport type { PanelAgentAdapter } from './types'\n\ntype Translate = (key: TranslationKey, params?: TranslationParams) => string\ntype HistoryEvent = PanelAgentAdapter['history'][number]\n\nexport interface TraceRun {\n\ttask: string\n\thistory: readonly HistoryEvent[]\n\toutcome: string\n}\n\n/**\n * Compact plain-text trace of one or more tasks, one block per step. Built only from the history the\n * panel already receives; it is read-only and does not change what the agent sees or does.\n */\nexport function formatTrace(runs: readonly TraceRun[], t: Translate, now: Date): string {\n\tconst lines: string[] = [`NoStop log ${now.toISOString()}`]\n\truns.forEach((run, index) => {\n\t\tlines.push('', `== ${t('ui.panel.logTask')} ${index + 1}: ${run.task}`)\n\t\tfor (const e of run.history) {\n\t\t\tif (e.type === 'step') {\n\t\t\t\tconst step = e.stepIndex !== undefined ? `step ${e.stepIndex + 1}` : 'step'\n\t\t\t\tconst r = e.reflection\n\t\t\t\tif (r?.evaluation_previous_goal)\n\t\t\t\t\tlines.push(`${step} | ${t('ui.panel.evaluation')}: ${r.evaluation_previous_goal}`)\n\t\t\t\tif (r?.memory) lines.push(`${step} | ${t('ui.panel.memory')}: ${r.memory}`)\n\t\t\t\tif (r?.next_goal) lines.push(`${step} | ${t('ui.panel.nextGoal')}: ${r.next_goal}`)\n\t\t\t\tif (e.action) {\n\t\t\t\t\tconst input = JSON.stringify(e.action.input ?? {})\n\t\t\t\t\tlines.push(\n\t\t\t\t\t\t`${step} | ${t('ui.panel.logAction')}: ${e.action.name} ${input} -> ${e.action.output ?? ''}`\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t} else if (e.type === 'observation') {\n\t\t\t\tlines.push(`obs | ${e.content ?? ''}`)\n\t\t\t} else if (e.type === 'retry') {\n\t\t\t\tlines.push(`retry | ${e.message ?? ''} (${e.attempt}/${e.maxAttempts})`)\n\t\t\t} else if (e.type === 'error') {\n\t\t\t\tlines.push(`error | ${e.message ?? ''}`)\n\t\t\t} else if (e.type === 'user_takeover') {\n\t\t\t\tlines.push(`user | ${t('ui.panel.userTakeover')}`)\n\t\t\t}\n\t\t}\n\t\tif (run.outcome) lines.push(`${t('ui.panel.logResult')}: ${run.outcome}`)\n\t})\n\treturn lines.join('\\n') + '\\n'\n}\n","/**\n * Scripts the voice ran in the page, shown in the conversation. The panel owns this list; it is separate from\n * the agent history, which only records the agent's own steps.\n */\nexport type VoiceRunStatus = 'running' | 'done' | 'refused'\n\nexport interface VoiceRun {\n\tid: number\n\tscript: string\n\t/** What the model received back. Undefined while the script runs. */\n\toutput?: string\n\tstatus: VoiceRunStatus\n\t/** When the script was requested (epoch milliseconds). */\n\tat: number\n}\n\nexport class VoiceRuns {\n\t#runs: VoiceRun[] = []\n\t#nextId = 1\n\n\tget list(): readonly VoiceRun[] {\n\t\treturn this.#runs\n\t}\n\n\t/** A script that starts running now. */\n\tstart(script: string, at: number): VoiceRun {\n\t\tconst run: VoiceRun = { id: this.#nextId++, script, status: 'running', at }\n\t\tthis.#runs.push(run)\n\t\treturn run\n\t}\n\n\t/** Records the output of a running script. Unknown ids are ignored. */\n\tfinish(id: number, output: string): void {\n\t\tconst run = this.#runs.find((r) => r.id === id)\n\t\tif (!run) return\n\t\trun.status = 'done'\n\t\trun.output = output\n\t}\n\n\t/** A script the panel did not run, with the reason it gave the model. */\n\trefuse(script: string, output: string, at: number): void {\n\t\tthis.#runs.push({ id: this.#nextId++, script, output, status: 'refused', at })\n\t}\n\n\t/** Hands every run to the caller and empties the list. Used when the conversation is archived. */\n\ttakeAll(): VoiceRun[] {\n\t\tconst runs = this.#runs\n\t\tthis.#runs = []\n\t\treturn runs\n\t}\n}\n","import { I18n, type TranslationKey, type TranslationParams } from '../i18n'\nimport { GeminiLiveClient } from '../voice/gemini-client'\nimport { RealtimeClient } from '../voice/realtime-client'\nimport { languageRule, resolveVoicePrompt } from '../voice/voice-prompt'\nimport { type VoiceError, VoiceSession, type VoiceState } from '../voice/voice-session'\nimport { type ResultKind, buildFeed, lastOutcomeText, localizeCore, toolLabel } from './feed'\nimport { type IconName, icon } from './icons'\nimport { MicrophoneControl } from './microphone'\nimport { createPanelRecovery } from './recovery'\nimport { scriptCard } from './scriptCard'\nimport { formatTrace } from './trace'\nimport type {\n\tAgentActivity,\n\tPanelAgentAdapter,\n\tStudioRecordedStep,\n\tStudioSkillCatalogEntry,\n\tStudioSkillWatchEntry,\n} from './types'\nimport { type VoiceRun, VoiceRuns } from './voiceRuns'\n\nimport styles from './Panel.module.css'\n\n/**\n * Panel configuration\n */\nexport interface PanelConfig {\n\t/** Restore this tab's displayed conversation after reload. Disabled by default. */\n\tsessionRecovery?: boolean\n\t/** Storage key used to isolate independent agents on the same origin. */\n\tsessionRecoveryKey?: string\n\t/** 'en-US' or 'pt-BR'; any other value falls back to English. */\n\tlanguage?: string\n\t/**\n\t * Whether to keep the composer available after a task ends\n\t * @default true\n\t */\n\tpromptForNextTask?: boolean\n\t/** Name shown in the header. @default 'NoStop' */\n\tname?: string\n\t/** Voice mode through the OpenAI Realtime API. Development setup: the key is used directly from the browser. */\n\t/** Runs a script in the page for the voice, with the page-agent instance in scope as `agent`. */\n\trunScript?: (script: string) => Promise<string>\n\t/**\n\t * Read-only page context slice for the voice (`get_context` tool). Allowed while the agent runs.\n\t */\n\tgetContext?: (args: {\n\t\tyMin?: number\n\t\tyMax?: number\n\t\tmaxLines?: number\n\t\tquery?: string\n\t}) => Promise<string>\n\tvoice?: {\n\t\tapiKey: string\n\t\t/** Voice provider. Default 'openai'. REVERSIBLE (2026-11-17, gemini provider). */\n\t\tprovider?: 'openai' | 'gemini'\n\t\t/** Added after the default voice prompt, which is kept. `null` or empty keeps only the default. */\n\t\tsystemPrompt?: string | null\n\t\t/**\n\t\t * Let `systemPrompt` replace the default voice prompt instead of being added to it.\n\t\t * REVERSIBLE (2026-11-23, system prompt override). @default false\n\t\t */\n\t\toverrideSystemPrompt?: boolean\n\t}\n}\n\nconst DRAG_KEY = 'page-agent-panel-position'\nconst FAB_KEY = 'page-agent-fab-corner'\nconst FAB_MARGIN = 16\nconst CORNERS = ['left-top', 'right-top', 'left-bottom', 'right-bottom'] as const\ntype Corner = (typeof CORNERS)[number]\n\ntype HistoryEvent = PanelAgentAdapter['history'][number]\n\n/** Latest meaningful text of a run: its outcome, else the last step output or observation. */\nfunction excerptOf(history: readonly HistoryEvent[], outcome: string): string {\n\tif (outcome) return outcome\n\tfor (let i = history.length - 1; i >= 0; i--) {\n\t\tconst e = history[i]\n\t\tif (e.type === 'step' && e.action?.output) return e.action.output\n\t\tif (e.type === 'observation' && e.content) return e.content\n\t}\n\treturn ''\n}\n\n/** Site favicon when available; the brand glyph otherwise. */\nfunction fillBrand(el: HTMLElement): void {\n\tel.textContent = ''\n\tconst siteIcon = document.querySelector<HTMLLinkElement>('link[rel~=\"icon\"][href]')\n\tif (!siteIcon) {\n\t\tel.innerHTML = icon('spark')\n\t\treturn\n\t}\n\tconst img = document.createElement('img')\n\timg.alt = ''\n\timg.src = siteIcon.href\n\timg.onerror = () => {\n\t\tel.innerHTML = icon('spark')\n\t}\n\tel.append(img)\n}\n\n/** Icon button: icon plus a short hover/focus hint, also used as the accessible name. */\nfunction setButton(el: HTMLElement, name: IconName, tip: string): void {\n\tel.innerHTML = icon(name)\n\tel.dataset.tip = tip\n\tel.setAttribute('aria-label', tip)\n\tel.removeAttribute('title')\n}\nconst CURSOR_ATTR = 'data-pa-cursor-hidden'\n/** Distance from the end (px) that still counts as \"following the conversation\". */\nconst PIN_PX = 72\n/** Window after a user scroll gesture (wheel, touch, keys, scrollbar) in which scrolling away unpins the feed. */\nconst INTENT_MS = 600\n/** Narrow viewports use expanded → bar → fab follow-mode cycling. */\nconst FOLLOW_CYCLE_MQ = '(max-width: 480px)'\ntype FollowMode = 'fab' | 'bar' | 'expanded'\n\n/**\n * Agent control panel.\n *\n * The conversation is rebuilt from `agent.history`, `agent.task`, the live\n * `activity` events and the pending question. History is the single source of\n * truth for what happened; activity only describes what is happening now.\n */\nexport class Panel {\n\t#wrapper: HTMLElement\n\t#agent: PanelAgentAdapter\n\t#config: PanelConfig\n\t#i18n: I18n\n\n\t#feed: HTMLElement\n\t#statusText: HTMLElement\n\t#textarea: HTMLTextAreaElement\n\t#answerContext: HTMLElement\n\t#sendButton: HTMLButtonElement\n\t#micButton: HTMLButtonElement\n\t#attachButton: HTMLButtonElement | null = null\n\t#attachInput: HTMLInputElement | null = null\n\t#attachList: HTMLElement | null = null\n\t#composer: HTMLFormElement\n\t#voiceStage: HTMLElement\n\t#studioStage: HTMLElement\n\t#skillsButton!: HTMLButtonElement\n\t#feedWrap: HTMLElement\n\t#stopButton: HTMLButtonElement\n\t#collapseButton: HTMLButtonElement\n\t#cursorButton: HTMLButtonElement\n\t#exportButton!: HTMLButtonElement\n\t#attachError = ''\n\t#studioTab: 'record' | 'ask' | 'catalog' = 'record'\n\t#studioMessage = ''\n\t#studioMessageTone: 'ok' | 'warn' | 'err' | '' = ''\n\t#studioPreview = ''\n\t#studioPreviewId = ''\n\t#studioBusy = false\n\t#studioPoll: ReturnType<typeof setInterval> | null = null\n\t#studioCatalog: StudioSkillCatalogEntry[] = []\n\t#studioWatches: StudioSkillWatchEntry[] = []\n\t#studioListenersBound = false\n\n\t#collapsed = false\n\t/** Mobile follow chrome: expanded card, slim status bar, or floating orb. */\n\t#followMode: FollowMode = 'expanded'\n\t#followBar!: HTMLElement\n\t#mode: 'text' | 'voice' | 'skills-studio' = 'text'\n\t/** Mode to restore when leaving Skills Studio. */\n\t#modeBeforeStudio: 'text' | 'voice' = 'text'\n\t#mic = new MicrophoneControl(() => this.#render())\n\t#voice!: VoiceSession\n\t/** Whether the outcome of the current run was already spoken. */\n\t#outcomeSpoken = false\n\t#live: AgentActivity | null = null\n\t#question: {\n\t\ttext: string\n\t\tkind: 'text' | 'choice' | 'multi'\n\t\tchoices: string[]\n\t\tselected: Set<string>\n\t\tresolve: (answer: string) => void\n\t} | null = null\n\t#choiceRow: HTMLElement | null = null\n\n\t#fab!: HTMLButtonElement\n\t#rail!: HTMLElement\n\t#thumb!: HTMLElement\n\t#jump!: HTMLButtonElement\n\t/** true while the feed follows new content (pinned to the end). */\n\t#follow = true\n\t/** New history events that arrived while the user was reading above. */\n\t#pending = 0\n\t#seen = 0\n\t/** Pin the latest user turn to the top after a new task is sent. */\n\t#anchorTurn = false\n\t#intentUntil = 0\n\t/** Finished tasks kept on screen (in memory). The agent itself still starts each task fresh. */\n\t#archive: {\n\t\ttask: string\n\t\thistory: HistoryEvent[]\n\t\tresult: { kind: ResultKind; text: string } | null\n\t\tvoiceRuns: VoiceRun[]\n\t}[] = []\n\t#recovery: ReturnType<typeof createPanelRecovery> | null = null\n\t#recoveryWarning = false\n\t/** Scripts the voice ran during the current turn. */\n\t#voiceRuns = new VoiceRuns()\n\t// REVERSIBLE (2026-11-17, feed stability): key and count of the last feed build. Remove both fields and the block at #render to revert.\n\t#lastRenderKey = ''\n\t#renderedCount = 0\n\t/** Pinned tasks, by run index. */\n\t#pins = new Set<number>()\n\t#peek!: HTMLElement\n\t#peekTimer: ReturnType<typeof setTimeout> | undefined\n\t#dragOrigin: { dx: number; dy: number } | null = null\n\t#dragged = false\n\n\t#onStatusChange = () => {\n\t\tthis.#speakOutcome()\n\t\tthis.#render()\n\t}\n\t#onHistoryChange = () => {\n\t\tif (this.#live?.type === 'executing') this.#live = null\n\t\tthis.#render()\n\t}\n\t#onActivity = (e: Event) => {\n\t\tthis.#live = (e as CustomEvent<AgentActivity>).detail\n\t\tthis.#render()\n\t}\n\t#onAgentDispose = () => this.dispose()\n\t#onSkillWatchEvent = (e: Event) => {\n\t\tthis.#refreshStudioWatches()\n\t\tif (e.type === 'skills:watch-fired') {\n\t\t\tconst detail = (e as CustomEvent<{ message?: string; skillId?: string; command?: string }>)\n\t\t\t\t.detail\n\t\t\tconst message = detail?.message?.trim() || detail?.skillId || 'ok'\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioWatchFired', { message }), 'ok')\n\t\t}\n\t\tif (this.#mode === 'skills-studio') this.#renderSkillsStudio()\n\t}\n\n\tget wrapper(): HTMLElement {\n\t\treturn this.#wrapper\n\t}\n\n\t/**\n\t * Create a Panel bound to an agent\n\t * @param agent - Agent instance that implements PanelAgentAdapter\n\t * @param config - Optional panel configuration\n\t */\n\tconstructor(agent: PanelAgentAdapter, config: PanelConfig = {}) {\n\t\tthis.#agent = agent\n\t\tthis.#config = config\n\t\tthis.#i18n = new I18n(config.language ?? 'en-US')\n\t\tif (config.sessionRecovery === true) {\n\t\t\ttry {\n\t\t\t\tthis.#recovery = createPanelRecovery(window.sessionStorage, config.sessionRecoveryKey)\n\t\t\t\tthis.#archive = this.#recovery.load()\n\t\t\t} catch (error) {\n\t\t\t\tthis.#recovery = null\n\t\t\t\tconsole.warn('[page-agent] Conversation recovery unavailable', error)\n\t\t\t}\n\t\t}\n\n\t\tthis.#agent.onAskUser = (question, options) => this.#askUser(question, options)\n\n\t\tthis.#wrapper = this.#createWrapper()\n\t\tthis.#feed = this.#wrapper.querySelector<HTMLElement>('[data-role=\"feed\"]')!\n\t\t// REVERSIBLE (2026-11-17, autoscroll): when the feed gets shorter (the composer grows, the reply strip appears),\n\t\t// keep the newest item visible while the user is following the conversation. Remove this observer to revert.\n\t\tif (typeof ResizeObserver !== 'undefined')\n\t\t\tnew ResizeObserver(() => {\n\t\t\t\tif (this.#follow) this.#feed.scrollTop = this.#feed.scrollHeight\n\t\t\t}).observe(this.#feed)\n\t\tthis.#statusText = this.#wrapper.querySelector<HTMLElement>('[data-role=\"status\"]')!\n\t\tthis.#textarea = this.#wrapper.querySelector<HTMLTextAreaElement>('[data-role=\"input\"]')!\n\t\tthis.#answerContext = this.#wrapper.querySelector<HTMLElement>('[data-role=\"answer-context\"]')!\n\t\tthis.#sendButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"send\"]')!\n\t\tthis.#micButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"mic\"]')!\n\t\tthis.#attachButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"attach\"]')\n\t\tthis.#attachInput = this.#wrapper.querySelector<HTMLInputElement>('[data-role=\"attach-input\"]')\n\t\tthis.#attachList = this.#wrapper.querySelector<HTMLElement>('[data-role=\"attach-list\"]')\n\t\tthis.#composer = this.#wrapper.querySelector<HTMLFormElement>('[data-role=\"composer\"]')!\n\t\tthis.#voiceStage = this.#wrapper.querySelector<HTMLElement>('[data-role=\"voice\"]')!\n\t\tthis.#studioStage = this.#wrapper.querySelector<HTMLElement>('[data-role=\"skills-studio\"]')!\n\t\tthis.#feedWrap = this.#wrapper.querySelector<HTMLElement>('[data-role=\"feed-wrap\"]')!\n\t\tthis.#skillsButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"skills\"]')!\n\t\tthis.#stopButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"action\"]')!\n\t\tthis.#collapseButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"collapse\"]')!\n\t\tthis.#cursorButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"cursor\"]')!\n\t\tthis.#exportButton = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"export\"]')!\n\t\tthis.#followBar = this.#wrapper.querySelector<HTMLElement>('[data-role=\"follow-bar\"]')!\n\t\tthis.#exportButton.addEventListener('click', (e) => {\n\t\t\te.stopPropagation()\n\t\t\tthis.#exportLog()\n\t\t})\n\n\t\tthis.#agent.addEventListener('statuschange', this.#onStatusChange)\n\t\tthis.#agent.addEventListener('historychange', this.#onHistoryChange)\n\t\tthis.#agent.addEventListener('activity', this.#onActivity)\n\t\tthis.#agent.addEventListener('dispose', this.#onAgentDispose)\n\t\tthis.#agent.addEventListener('skills:watch-armed', this.#onSkillWatchEvent)\n\t\tthis.#agent.addEventListener('skills:watch-fired', this.#onSkillWatchEvent)\n\t\tthis.#agent.addEventListener('skills:watch-stopped', this.#onSkillWatchEvent)\n\n\t\tthis.#voice = this.#createVoice()\n\t\tthis.#setupEventListeners()\n\t\tthis.#setupFeed()\n\t\tthis.#setupPlacement()\n\t\tthis.#refreshStudioWatches()\n\t\tthis.#render()\n\n\t\tthis.#setupFab()\n\t\tthis.hide() // Start hidden, as the floating button\n\t}\n\n\t// ========== Public control methods ==========\n\n\tshow(): void {\n\t\tif (this.#followMode === 'fab') {\n\t\t\tthis.#followMode = 'expanded'\n\t\t\tthis.#collapsed = false\n\t\t}\n\t\tthis.#fab.hidden = true\n\t\tthis.wrapper.dataset.follow = this.#followMode\n\t\tthis.wrapper.style.display = 'flex'\n\t\tthis.wrapper.getBoundingClientRect() // force reflow before opacity transition\n\t\tthis.wrapper.style.opacity = '1'\n\t\tthis.wrapper.style.transform = 'translateY(0)'\n\t\tthis.#render()\n\t}\n\n\thide(): void {\n\t\tthis.#followMode = 'fab'\n\t\tthis.#collapsed = true\n\t\tthis.wrapper.dataset.follow = 'fab'\n\t\tthis.wrapper.style.opacity = '0'\n\t\tthis.wrapper.style.transform = 'translateY(20px)'\n\t\tthis.wrapper.style.display = 'none'\n\t\tthis.#fab.hidden = false\n\t\tthis.#syncFollowFabLabel()\n\t}\n\n\treset(): void {\n\t\tthis.#question = null\n\t\tthis.#live = null\n\t\tthis.#mode = 'text'\n\t\tthis.#followMode = 'bar'\n\t\tthis.#collapsed = true\n\t\tthis.#render()\n\t}\n\n\texpand(): void {\n\t\tthis.#setFollowMode('expanded')\n\t}\n\n\tcollapse(): void {\n\t\tthis.#setFollowMode('bar')\n\t}\n\n\t/**\n\t * Dispose panel and clean up event listeners\n\t */\n\tdispose(): void {\n\t\tthis.#stopStudioPolling()\n\t\tif (this.#agent.isSkillRecording?.()) this.#agent.stopSkillRecording?.()\n\t\tthis.#voice.disable()\n\t\tthis.#fab.remove()\n\t\tthis.#agent.removeEventListener('statuschange', this.#onStatusChange)\n\t\tthis.#agent.removeEventListener('historychange', this.#onHistoryChange)\n\t\tthis.#agent.removeEventListener('activity', this.#onActivity)\n\t\tthis.#agent.removeEventListener('dispose', this.#onAgentDispose)\n\t\tthis.#agent.removeEventListener('skills:watch-armed', this.#onSkillWatchEvent)\n\t\tthis.#agent.removeEventListener('skills:watch-fired', this.#onSkillWatchEvent)\n\t\tthis.#agent.removeEventListener('skills:watch-stopped', this.#onSkillWatchEvent)\n\t\tthis.#question = null\n\t\tthis.wrapper.remove()\n\t}\n\n\t// ========== Feed scrolling ==========\n\n\t/**\n\t * Smart follow: the feed sticks to the end only while the user is near it. A scroll the user\n\t * started (wheel, touch, keys, scrollbar) unpins it; content growing does not. A new task pins\n\t * its turn to the top; new events while reading above are counted on a jump pill.\n\t */\n\t#afterFeedUpdate(): void {\n\t\tconst feed = this.#feed\n\t\tconst total = this.#agent.history.length\n\t\tconst added = Math.max(0, total - this.#seen)\n\t\tthis.#seen = total\n\n\t\tif (this.#question) this.#follow = true\n\t\tif (this.#anchorTurn) {\n\t\t\tthis.#anchorTurn = false\n\t\t\tconst turns = feed.querySelectorAll<HTMLElement>('[data-mark=\"turn\"]')\n\t\t\tconst last = turns[turns.length - 1]\n\t\t\tif (last) {\n\t\t\t\tthis.#follow = false\n\t\t\t\tfeed.scrollTop = last.offsetTop - 12\n\t\t\t}\n\t\t} else if (this.#follow) {\n\t\t\tfeed.scrollTop = feed.scrollHeight\n\t\t} else if (added > 0 || this.#question) {\n\t\t\tthis.#pending += added\n\t\t}\n\t\tthis.#placeRailMarks()\n\t\tthis.#refreshFeed()\n\t}\n\n\t#setupFeed(): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\t// The page may run its own smooth scrolling (for example Lenis). Keep wheel and touch inside the panel:\n\t\t// Lenis skips elements marked with data-lenis-prevent, and the event never reaches page listeners.\n\t\tthis.#wrapper.setAttribute('data-lenis-prevent', '')\n\t\tconst keepInside = (e: Event) => e.stopPropagation()\n\t\tthis.#wrapper.addEventListener('wheel', keepInside, { passive: true })\n\t\tthis.#wrapper.addEventListener('touchmove', keepInside, { passive: true })\n\t\tthis.#rail = this.#wrapper.querySelector<HTMLElement>('[data-role=\"rail\"]')!\n\t\tthis.#thumb = this.#wrapper.querySelector<HTMLElement>('[data-role=\"thumb\"]')!\n\t\tthis.#jump = this.#wrapper.querySelector<HTMLButtonElement>('[data-role=\"jump\"]')!\n\t\tconst feed = this.#feed\n\n\t\tconst intent = () => {\n\t\t\tthis.#intentUntil = performance.now() + INTENT_MS\n\t\t}\n\t\tfeed.addEventListener('wheel', intent, { passive: true })\n\t\tfeed.addEventListener('touchstart', intent, { passive: true })\n\t\tfeed.addEventListener('mousedown', intent)\n\t\tfeed.addEventListener('keydown', (e) => {\n\t\t\tif (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '].includes(e.key))\n\t\t\t\tintent()\n\t\t\tif (e.key === 'Home' || e.key === 'End') {\n\t\t\t\te.preventDefault()\n\t\t\t\tthis.#scrollFeed(e.key === 'End' ? 'end' : 'start')\n\t\t\t}\n\t\t})\n\t\tfeed.addEventListener('scroll', () => {\n\t\t\tconst atEnd = feed.scrollHeight - feed.scrollTop - feed.clientHeight < PIN_PX\n\t\t\tif (atEnd) {\n\t\t\t\tthis.#follow = true\n\t\t\t\tthis.#pending = 0\n\t\t\t} else if (performance.now() < this.#intentUntil) {\n\t\t\t\tthis.#follow = false\n\t\t\t}\n\t\t\tthis.#refreshFeed()\n\t\t})\n\t\tnew ResizeObserver(() => {\n\t\t\tthis.#placeRailMarks()\n\t\t\tthis.#refreshFeed()\n\t\t}).observe(feed)\n\n\t\tthis.#jump.addEventListener('click', () => this.#scrollFeed('end'))\n\t\tthis.#peek = this.#wrapper.querySelector<HTMLElement>('[data-role=\"peek\"]')!\n\t\tthis.#rail.addEventListener('pointerover', (e) => {\n\t\t\tconst tick = (e.target as HTMLElement).closest<HTMLElement>('[data-mark-dot]')\n\t\t\tif (tick) this.#showPeek(tick)\n\t\t})\n\t\tthis.#rail.addEventListener('pointerleave', () => this.#scheduleHidePeek())\n\t\tthis.#peek.addEventListener('pointerenter', () => clearTimeout(this.#peekTimer))\n\t\tthis.#peek.addEventListener('pointerleave', () => this.#scheduleHidePeek())\n\t\tthis.#peek.addEventListener('click', (e) => {\n\t\t\tconst pin = (e.target as HTMLElement).closest<HTMLElement>('[data-role=\"pin\"]')\n\t\t\tif (!pin) return\n\t\t\tconst run = Number(pin.dataset.run)\n\t\t\tif (this.#pins.has(run)) this.#pins.delete(run)\n\t\t\telse this.#pins.add(run)\n\t\t\tthis.#peek.hidden = true\n\t\t\tthis.#render()\n\t\t})\n\t\tthis.#jump.setAttribute('aria-label', t('ui.panel.jumpLatest'))\n\t\tthis.#rail.addEventListener('click', (e) => {\n\t\t\tconst mark = (e.target as HTMLElement).closest<HTMLElement>('[data-target]')\n\t\t\tif (!mark) return\n\t\t\tconst target = feed.querySelector<HTMLElement>(`[data-id=\"${mark.dataset.target}\"]`)\n\t\t\tif (!target) return\n\t\t\tthis.#follow = false\n\t\t\tfeed.scrollTo({ top: target.offsetTop - 12, behavior: this.#motion() })\n\t\t})\n\t}\n\n\t#motion(): ScrollBehavior {\n\t\treturn window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth'\n\t}\n\n\t#scrollFeed(where: 'start' | 'end'): void {\n\t\tconst feed = this.#feed\n\t\tthis.#follow = where === 'end'\n\t\tif (where === 'end') this.#pending = 0\n\t\tfeed.scrollTo({ top: where === 'end' ? feed.scrollHeight : 0, behavior: this.#motion() })\n\t\tthis.#refreshFeed()\n\t}\n\n\t/** Thumb, markers, edge fades and jump pill, derived from the current scroll position. */\n\t#refreshFeed(): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst feed = this.#feed\n\t\tconst max = feed.scrollHeight - feed.clientHeight\n\t\tconst overflow = max > 4\n\t\tconst top = feed.scrollTop > 8\n\t\tconst bottom = max - feed.scrollTop > 8\n\n\t\t// Edge fades only on the sides that have more content.\n\t\tconst start = top ? 'transparent 0, #000 24px' : '#000 0'\n\t\tconst end = bottom ? '#000 calc(100% - 24px), transparent 100%' : '#000 100%'\n\t\tconst mask = overflow ? `linear-gradient(to bottom, ${start}, ${end})` : 'none'\n\t\tfeed.style.maskImage = mask\n\t\tfeed.style.webkitMaskImage = mask\n\n\t\tthis.#rail.hidden = !overflow\n\t\tconst turns = feed.querySelectorAll<HTMLElement>('[data-mark=\"turn\"]')\n\t\tlet activeId = ''\n\t\tturns.forEach((el) => {\n\t\t\tif (el.offsetTop <= feed.scrollTop + 48) activeId = el.dataset.id ?? ''\n\t\t})\n\t\tthis.#rail.querySelectorAll<HTMLElement>('[data-mark-dot]').forEach((tick) => {\n\t\t\ttick.dataset.active = String(tick.dataset.target === activeId)\n\t\t})\n\t\tif (overflow) {\n\t\t\tconst ratio = feed.clientHeight / feed.scrollHeight\n\t\t\tconst railHeight = this.#rail.clientHeight\n\t\t\tthis.#thumb.style.height = `${Math.max(24, ratio * railHeight)}px`\n\t\t\tthis.#thumb.style.top = `${(feed.scrollTop / feed.scrollHeight) * railHeight}px`\n\t\t}\n\n\t\tconst showJump =\n\t\t\t!this.#follow && (this.#pending > 0 || this.#question !== null || (overflow && bottom))\n\t\tthis.#jump.hidden = !showJump\n\t\tif (showJump) {\n\t\t\tthis.#jump.innerHTML = `${icon('arrowDown')}<span>${this.#pending > 0 ? t('ui.panel.newCount', { count: String(this.#pending) }) : t('ui.panel.jumpLatest')}</span>`\n\t\t}\n\t}\n\n\t/** Ticks on the rail for turns (tasks), questions and results. Each one jumps to its place. */\n\t#placeRailMarks(): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst feed = this.#feed\n\t\tconst railHeight = this.#rail.clientHeight\n\t\tthis.#rail.querySelectorAll('[data-mark-dot]').forEach((n) => n.remove())\n\t\tfeed.querySelectorAll<HTMLElement>('[data-mark]').forEach((el, index) => {\n\t\t\tconst id = `m${index}`\n\t\t\tel.dataset.id = id\n\t\t\tconst kind = el.dataset.mark ?? ''\n\t\t\tconst tick = document.createElement('button')\n\t\t\ttick.type = 'button'\n\t\t\ttick.className = styles.railMark\n\t\t\ttick.dataset.markDot = ''\n\t\t\ttick.dataset.kind = kind\n\t\t\ttick.dataset.target = id\n\t\t\ttick.dataset.run = el.dataset.run ?? ''\n\t\t\ttick.dataset.pinned = el.dataset.pinned ?? 'false'\n\t\t\ttick.dataset.title = kind === 'turn' ? (el.textContent ?? '') : ''\n\t\t\ttick.dataset.preview = el.dataset.preview ?? ''\n\t\t\ttick.style.top = `${(el.offsetTop / feed.scrollHeight) * railHeight}px`\n\t\t\ttick.setAttribute(\n\t\t\t\t'aria-label',\n\t\t\t\tkind === 'turn' ? (el.textContent ?? '') : t('ui.panel.step', { number: String(index + 1) })\n\t\t\t)\n\t\t\tthis.#rail.append(tick)\n\t\t})\n\t}\n\n\t/** Hover card for a rail tick: title, short excerpt and a pin toggle for tasks. */\n\t#showPeek(tick: HTMLElement): void {\n\t\tclearTimeout(this.#peekTimer)\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst peek = this.#peek\n\t\tconst run = tick.dataset.run ?? ''\n\t\tpeek.replaceChildren()\n\t\tconst head = document.createElement('div')\n\t\thead.className = styles.peekHead\n\t\tconst title = document.createElement('strong')\n\t\tconst kindTitle =\n\t\t\ttick.dataset.kind === 'question'\n\t\t\t\t? t('ui.panel.questionTitle')\n\t\t\t\t: tick.dataset.kind === 'result'\n\t\t\t\t\t? t('ui.panel.resultTitle')\n\t\t\t\t\t: ''\n\t\ttitle.textContent = tick.dataset.title || kindTitle\n\t\thead.append(title)\n\t\tif (run !== '') {\n\t\t\tconst pin = document.createElement('button')\n\t\t\tconst pinned = this.#pins.has(Number(run))\n\t\t\tpin.type = 'button'\n\t\t\tpin.className = styles.pin\n\t\t\tpin.dataset.role = 'pin'\n\t\t\tpin.dataset.run = run\n\t\t\tpin.setAttribute('aria-pressed', String(pinned))\n\t\t\tpin.setAttribute('aria-label', t(pinned ? 'ui.panel.unpin' : 'ui.panel.pin'))\n\t\t\tpin.innerHTML = icon('bookmark')\n\t\t\thead.append(pin)\n\t\t}\n\t\tconst body = document.createElement('p')\n\t\tbody.className = styles.peekText\n\t\tbody.textContent = localizeCore(tick.dataset.preview ?? '', t)\n\t\tpeek.append(head, body)\n\t\tpeek.hidden = false\n\t\t// Align with the tick, kept inside the feed area.\n\t\tconst wrap = this.#feed.parentElement!.getBoundingClientRect()\n\t\tconst here = tick.getBoundingClientRect()\n\t\tconst top = Math.min(Math.max(8, here.top - wrap.top - 16), wrap.height - peek.offsetHeight - 8)\n\t\tpeek.style.top = `${top}px`\n\t}\n\n\t#scheduleHidePeek(): void {\n\t\tclearTimeout(this.#peekTimer)\n\t\tthis.#peekTimer = setTimeout(() => {\n\t\t\tthis.#peek.hidden = true\n\t\t}, 140)\n\t}\n\n\t/** Keep the run index on turn nodes so pins and the rail can refer to them. */\n\t#annotate(\n\t\tnodes: HTMLElement[],\n\t\tindex: number,\n\t\thistory: readonly HistoryEvent[],\n\t\tresult: { kind: ResultKind; text: string } | null\n\t): void {\n\t\tconst excerpt = excerptOf(history, result?.text ?? '')\n\t\tfor (const node of nodes) {\n\t\t\tif (node.dataset.mark !== 'turn') continue\n\t\t\tnode.dataset.run = String(index)\n\t\t\tnode.dataset.pinned = String(this.#pins.has(index))\n\t\t\tnode.dataset.preview = excerpt\n\t\t}\n\t}\n\n\t#saveRecovery(): void {\n\t\tif (!this.#recovery) return\n\t\tconst runs = [...this.#archive]\n\t\tif (this.#agent.task || this.#agent.history.length || this.#voiceRuns.list.length) {\n\t\t\truns.push({\n\t\t\t\ttask: this.#agent.task || '',\n\t\t\t\thistory: [...this.#agent.history],\n\t\t\t\tresult:\n\t\t\t\t\tthis.#agent.status === 'running'\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tkind: 'stopped',\n\t\t\t\t\t\t\t\ttext: 'Interrupted by reload or navigation. Actions were not replayed.',\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: this.#resultKind(),\n\t\t\t\tvoiceRuns: [...this.#voiceRuns.list],\n\t\t\t})\n\t\t}\n\t\ttry {\n\t\t\tthis.#recovery.save(runs)\n\t\t} catch (error) {\n\t\t\tif (!this.#recoveryWarning)\n\t\t\t\tconsole.warn('[page-agent] Could not save conversation recovery', error)\n\t\t\tthis.#recoveryWarning = true\n\t\t}\n\t}\n\n\t#archiveCurrent(): void {\n\t\tconst task = this.#agent.task || ''\n\t\tconst history = [...this.#agent.history]\n\t\tconst voiceRuns = this.#voiceRuns.takeAll()\n\t\tif (!task && history.length === 0 && voiceRuns.length === 0) return\n\t\tthis.#archive.push({ task, history, result: this.#resultKind(), voiceRuns })\n\t}\n\n\t/** Scripts the voice ran, as script cards, each with its time. */\n\t#voiceRunNodes(\n\t\truns: readonly VoiceRun[],\n\t\tt: (key: TranslationKey, params?: TranslationParams) => string\n\t): HTMLElement[] {\n\t\treturn runs.map((run) => {\n\t\t\tconst card = scriptCard({\n\t\t\t\tkey: `voice-${run.id}`,\n\t\t\t\tscript: run.script,\n\t\t\t\toutput: run.output,\n\t\t\t\tt,\n\t\t\t\tsource: 'voice',\n\t\t\t\trefused: run.status === 'refused',\n\t\t\t\ttime: new Date(run.at).toLocaleTimeString(),\n\t\t\t})\n\t\t\tcard.classList.add(styles.enter)\n\t\t\tcard.dataset.mark = 'voice'\n\t\t\treturn card\n\t\t})\n\t}\n\n\t/** Finished tasks, each followed by a divider, shown above the current task. */\n\t#archivedNodes(t: (key: TranslationKey, params?: TranslationParams) => string): HTMLElement[] {\n\t\tconst out: HTMLElement[] = []\n\t\tthis.#archive.forEach((run, index) => {\n\t\t\tconst nodes = buildFeed(\n\t\t\t\t{\n\t\t\t\t\tkey: `run-${index}`,\n\t\t\t\t\ttask: run.task,\n\t\t\t\t\thistory: run.history,\n\t\t\t\t\tlive: null,\n\t\t\t\t\tquestion: null,\n\t\t\t\t\tresult: run.result,\n\t\t\t\t},\n\t\t\t\tt\n\t\t\t)\n\t\t\tthis.#annotate(nodes, index, run.history, run.result)\n\t\t\tout.push(...nodes, ...this.#voiceRunNodes(run.voiceRuns, t))\n\t\t\tconst divider = document.createElement('div')\n\t\t\tdivider.className = styles.divider\n\t\t\tdivider.textContent = t('ui.panel.newTask')\n\t\t\tout.push(divider)\n\t\t})\n\t\treturn out\n\t}\n\n\t// ========== Agent interaction ==========\n\n\t/**\n\t * Ask the user a question on behalf of the agent. Rejects when `signal` aborts\n\t * (task stopped or disposed), so the agent loop can settle.\n\t */\n\t#askUser(\n\t\tquestion: string,\n\t\toptions?: {\n\t\t\tsignal?: AbortSignal\n\t\t\tkind?: 'text' | 'choice' | 'multi'\n\t\t\tchoices?: string[]\n\t\t}\n\t): Promise<string> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst choices = (options?.choices ?? []).map((c) => c.trim()).filter(Boolean)\n\t\t\tlet kind: 'text' | 'choice' | 'multi' = options?.kind ?? 'text'\n\t\t\tif ((kind === 'choice' || kind === 'multi') && choices.length < 2) kind = 'text'\n\t\t\tthis.#question = {\n\t\t\t\ttext: question.trim(),\n\t\t\t\tkind,\n\t\t\t\tchoices,\n\t\t\t\tselected: new Set(),\n\t\t\t\tresolve,\n\t\t\t}\n\t\t\tthis.#setCollapsed(false)\n\t\t\tthis.#render()\n\t\t\tconst choiceLine =\n\t\t\t\tkind === 'text' || choices.length === 0\n\t\t\t\t\t? ''\n\t\t\t\t\t: `\\nOptions (${kind}): ${choices.map((c, i) => `${i + 1}. ${c}`).join('; ')}`\n\t\t\tthis.#voice.report({ kind: 'question', text: `${question.trim()}${choiceLine}` })\n\t\t\tif (kind === 'text') this.#textarea.focus()\n\n\t\t\toptions?.signal?.addEventListener(\n\t\t\t\t'abort',\n\t\t\t\t() => {\n\t\t\t\t\tthis.#question = null\n\t\t\t\t\tthis.#render()\n\t\t\t\t\treject(options.signal!.reason as DOMException)\n\t\t\t\t},\n\t\t\t\t{ once: true }\n\t\t\t)\n\t\t})\n\t}\n\n\t/** Resolve a pending ask from text, voice, or a choice chip. */\n\t#resolveQuestion(answer: string): boolean {\n\t\tif (!this.#question) return false\n\t\tconst value = answer.trim()\n\t\tif (!value) return false\n\t\tconst { resolve } = this.#question\n\t\tthis.#question = null\n\t\tthis.#choiceRow?.remove()\n\t\tthis.#choiceRow = null\n\t\tresolve(value)\n\t\tthis.#render()\n\t\treturn true\n\t}\n\n\t/** Choice / multi-choice chips under the ask prompt. */\n\t#renderChoiceChips(): void {\n\t\tconst q = this.#question\n\t\tif (!q || (q.kind !== 'choice' && q.kind !== 'multi') || q.choices.length === 0) {\n\t\t\tthis.#choiceRow?.remove()\n\t\t\tthis.#choiceRow = null\n\t\t\treturn\n\t\t}\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tlet row = this.#choiceRow\n\t\tif (!row) {\n\t\t\trow = document.createElement('div')\n\t\t\trow.className = styles.choiceRow\n\t\t\trow.dataset.role = 'choice-row'\n\t\t\tthis.#answerContext.append(row)\n\t\t\tthis.#choiceRow = row\n\t\t}\n\t\trow.replaceChildren()\n\t\tfor (const choice of q.choices) {\n\t\t\tconst btn = document.createElement('button')\n\t\t\tbtn.type = 'button'\n\t\t\tbtn.className = styles.choiceChip\n\t\t\tbtn.textContent = choice\n\t\t\tconst selected = q.selected.has(choice)\n\t\t\tbtn.setAttribute('aria-pressed', String(selected))\n\t\t\tif (selected) btn.dataset.selected = 'true'\n\t\t\tbtn.addEventListener('click', () => {\n\t\t\t\tif (!this.#question) return\n\t\t\t\tif (this.#question.kind === 'choice') {\n\t\t\t\t\tthis.#resolveQuestion(choice)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (this.#question.selected.has(choice)) this.#question.selected.delete(choice)\n\t\t\t\telse this.#question.selected.add(choice)\n\t\t\t\tthis.#render()\n\t\t\t})\n\t\t\trow.append(btn)\n\t\t}\n\t\tif (q.kind === 'multi') {\n\t\t\tconst confirm = document.createElement('button')\n\t\t\tconfirm.type = 'button'\n\t\t\tconfirm.className = styles.choiceConfirm\n\t\t\tconfirm.textContent = t('ui.panel.answerConfirmMulti')\n\t\t\tconfirm.disabled = q.selected.size === 0\n\t\t\tconfirm.addEventListener('click', () => {\n\t\t\t\tif (!this.#question || this.#question.selected.size === 0) return\n\t\t\t\tthis.#resolveQuestion([...this.#question.selected].join('; '))\n\t\t\t})\n\t\t\trow.append(confirm)\n\t\t}\n\t}\n\n\t#submit(): void {\n\t\tconst value = this.#textarea.value.trim()\n\t\tif (!value) return\n\t\tif (!this.#send(value)) return\n\t\tthis.#textarea.value = ''\n\t\tthis.#autoSize()\n\t}\n\n\t/**\n\t * Mid-task user note for the running agent. Returns false when there is no running task\n\t * or the agent cannot take observations.\n\t */\n\t#noteRunning(text: string): boolean {\n\t\tconst value = text.trim()\n\t\tif (!value || this.#agent.status !== 'running') return false\n\t\tif (typeof this.#agent.pushObservation !== 'function') return false\n\t\tthis.#agent.pushObservation(`User said while the task was running: ${value}`)\n\t\tthis.#render()\n\t\treturn true\n\t}\n\n\t/** Sends a task or answers a pending question. The text field and voice both use this path. */\n\t#send(value: string): boolean {\n\t\tif (this.#question) return this.#resolveQuestion(value)\n\t\tif (this.#agent.status === 'running') return false\n\t\tthis.#archiveCurrent()\n\t\tthis.#anchorTurn = true\n\t\tthis.#outcomeSpoken = false\n\t\tthis.#agent.execute(value)\n\t\treturn true\n\t}\n\n\t/** Reads the outcome of a finished run once, while voice is on. */\n\t#speakOutcome(): void {\n\t\tconst status = this.#agent.status\n\t\tif (\n\t\t\tthis.#outcomeSpoken ||\n\t\t\t(status !== 'completed' && status !== 'error' && status !== 'stopped')\n\t\t)\n\t\t\treturn\n\t\tthis.#outcomeSpoken = true\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst outcome = this.#resultKind()\n\t\tconst titles: Record<ResultKind, TranslationKey> = {\n\t\t\tdone: 'ui.panel.resultDone',\n\t\t\tnotDone: 'ui.panel.resultNotDone',\n\t\t\tstopped: 'ui.panel.resultStopped',\n\t\t\terror: 'ui.panel.resultError',\n\t\t}\n\t\tconst kind = outcome?.kind ?? 'stopped'\n\t\tthis.#voice.report({\n\t\t\tkind: kind === 'notDone' ? 'not-done' : kind,\n\t\t\ttext: outcome?.text || t(titles[kind]),\n\t\t})\n\t}\n\n\t/** Runs a script for the voice. Refused while the agent is running, because the agent owns the page then. */\n\tasync #runVoiceScript(script: string): Promise<string> {\n\t\tconst at = Date.now()\n\t\tif (this.#agent.status === 'running') {\n\t\t\tconst reason =\n\t\t\t\t'The agent is busy with a task, so the page cannot be changed now. Tell the user to try again when the task ends.'\n\t\t\tthis.#voiceRuns.refuse(script, reason, at)\n\t\t\tconsole.debug('[page-agent voice] refused', { script, reason })\n\t\t\tthis.#render()\n\t\t\treturn reason\n\t\t}\n\t\tconst run = this.#config.runScript\n\t\tconst entry = this.#voiceRuns.start(script, at)\n\t\tthis.#render()\n\t\tlet output: string\n\t\ttry {\n\t\t\toutput = run ? await run(script) : 'Running scripts is not available in this session.'\n\t\t} catch (error) {\n\t\t\toutput = `The script failed: ${error instanceof Error ? error.message : 'unknown error'}`\n\t\t}\n\t\tthis.#voiceRuns.finish(entry.id, output)\n\t\tconsole.debug('[page-agent voice]', { script, output })\n\t\tthis.#render()\n\t\treturn output\n\t}\n\n\t/** Active task / ask / recent steps so the voice can explain without losing prior context. */\n\t#voiceAgentBrief(): string {\n\t\tconst lines: string[] = []\n\t\tconst status = this.#agent.status\n\t\tconst task = this.#agent.task?.trim()\n\t\tif (task) lines.push(`Active task (${status}): ${task}`)\n\t\telse lines.push(`Agent status: ${status}`)\n\t\tif (this.#question) {\n\t\t\tlines.push(\n\t\t\t\t`Pending ask (${this.#question.kind}): ${this.#question.text}` +\n\t\t\t\t\t(this.#question.choices.length ? ` Options: ${this.#question.choices.join(' | ')}` : '')\n\t\t\t)\n\t\t}\n\t\tconst recent = this.#agent.history.slice(-6)\n\t\tfor (const event of recent) {\n\t\t\tif (event.type === 'observation' && event.content) {\n\t\t\t\tlines.push(`obs: ${event.content.slice(0, 180)}`)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (event.type === 'step') {\n\t\t\t\tconst goal = event.reflection?.next_goal?.trim()\n\t\t\t\tconst action = event.action?.name\n\t\t\t\tconst bit = [goal && `goal=${goal}`, action && `action=${action}`]\n\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t.join(', ')\n\t\t\t\tif (bit) lines.push(`step: ${bit}`)\n\t\t\t}\n\t\t}\n\t\treturn lines.join('\\n')\n\t}\n\n\t/** Read-only context slice for the voice; allowed while the agent is running. */\n\tasync #runVoiceGetContext(args: {\n\t\tyMin?: number\n\t\tyMax?: number\n\t\tmaxLines?: number\n\t\tquery?: string\n\t}): Promise<string> {\n\t\tconst brief = this.#voiceAgentBrief()\n\t\tconst run = this.#config.getContext\n\t\tif (!run) return `${brief}\\n\\nget_context is not available in this session.`\n\t\ttry {\n\t\t\tconst slice = await run(args)\n\t\t\treturn `${brief}\\n\\n${slice}`\n\t\t} catch (error) {\n\t\t\treturn `${brief}\\n\\nget_context failed: ${error instanceof Error ? error.message : 'unknown error'}`\n\t\t}\n\t}\n\n\t/**\n\t * The voice session. The voice model hands a task to the agent through run_task; a task that the agent\n\t * cannot take now (already running) is answered back to the model by the session.\n\t */\n\t#createVoice(): VoiceSession {\n\t\treturn new VoiceSession({\n\t\t\tapiKey: this.#config.voice?.apiKey,\n\t\t\tsettings: {\n\t\t\t\tinstructions: `${resolveVoicePrompt(this.#config.voice?.systemPrompt, this.#config.voice?.overrideSystemPrompt === true)}\\n\\n${languageRule(this.#i18n.getLanguage())}`,\n\t\t\t\tlanguage: this.#i18n.getLanguage() === 'pt-BR' ? 'pt' : 'en',\n\t\t\t},\n\t\t\tmic: this.#mic,\n\t\t\t// REVERSIBLE (2026-11-17, gemini provider): the provider is chosen by configuration; default is OpenAI.\n\t\t\tcreateClient: (callbacks) =>\n\t\t\t\tthis.#config.voice?.provider === 'gemini'\n\t\t\t\t\t? new GeminiLiveClient(callbacks)\n\t\t\t\t\t: new RealtimeClient(callbacks),\n\t\t\tonTask: (task) => this.#send(task),\n\t\t\tonScript: (script) => this.#runVoiceScript(script),\n\t\t\tisWaitingForAnswer: () => this.#question !== null,\n\t\t\tonAnswer: (answer) => this.#resolveQuestion(answer),\n\t\t\tonNote: (text) => this.#noteRunning(text),\n\t\t\tonGetContext: (args) => this.#runVoiceGetContext(args),\n\t\t\tonChange: () => this.#render(),\n\t\t})\n\t}\n\n\t#onActionButton(): void {\n\t\tif (this.#agent.status === 'running') {\n\t\t\tthis.#agent.stop()\n\t\t} else {\n\t\t\t// Close minimizes to the floating button; the agent stays alive.\n\t\t\tthis.hide()\n\t\t}\n\t}\n\n\t// ========== Rendering ==========\n\n\t#resultKind(): { kind: ResultKind; text: string } | null {\n\t\tconst status = this.#agent.status\n\t\tif (status === 'completed') {\n\t\t\tconst notDone = this.#agent.lastResult?.success === false\n\t\t\treturn { kind: notDone ? 'notDone' : 'done', text: lastOutcomeText(this.#agent.history) }\n\t\t}\n\t\tif (status === 'error') return { kind: 'error', text: lastOutcomeText(this.#agent.history) }\n\t\tif (status === 'stopped') return { kind: 'stopped', text: '' }\n\t\treturn null\n\t}\n\n\t#stateName(): string {\n\t\tif (this.#question) return 'waiting'\n\t\tconst status = this.#agent.status\n\t\tif (status === 'running') return 'running'\n\t\tconst kind = this.#resultKind()?.kind\n\t\treturn kind ?? 'idle'\n\t}\n\n\t#statusLabel(): string {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tif (this.#question) return t('ui.panel.statusWaiting')\n\t\tconst status = this.#agent.status\n\t\tif (status === 'running') {\n\t\t\tif (this.#live?.type === 'retrying')\n\t\t\t\treturn t('ui.panel.statusRetrying', {\n\t\t\t\t\tattempt: String(this.#live.attempt),\n\t\t\t\t\tmax: String(this.#live.maxAttempts),\n\t\t\t\t})\n\t\t\tif (this.#live?.type === 'executing') return toolLabel(this.#live.tool, this.#live.input, t)\n\t\t\tif (this.#live?.type === 'thinking') return t('ui.panel.thinking')\n\t\t\treturn t('ui.panel.statusRunning')\n\t\t}\n\t\tswitch (this.#resultKind()?.kind) {\n\t\t\tcase 'done':\n\t\t\t\treturn t('ui.panel.statusDone')\n\t\t\tcase 'notDone':\n\t\t\t\treturn t('ui.panel.statusNotDone')\n\t\t\tcase 'stopped':\n\t\t\t\treturn t('ui.panel.statusStopped')\n\t\t\tcase 'error':\n\t\t\t\treturn t('ui.panel.statusError')\n\t\t\tdefault:\n\t\t\t\treturn t('ui.panel.ready')\n\t\t}\n\t}\n\n\t#render(): void {\n\t\tthis.#saveRecovery()\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst state = this.#stateName()\n\t\tthis.#wrapper.dataset.state = state\n\t\tthis.#wrapper.dataset.mode = this.#mode\n\t\tthis.#wrapper.dataset.follow = this.#followMode\n\t\tthis.#wrapper.classList.toggle(styles.collapsed, this.#collapsed)\n\t\tthis.#statusText.textContent = this.#statusLabel()\n\n\t\tconst nodes = buildFeed(\n\t\t\t{\n\t\t\t\tkey: 'current',\n\t\t\t\ttask: this.#agent.task || '',\n\t\t\t\thistory: this.#agent.history,\n\t\t\t\tlive: this.#agent.status === 'running' ? this.#live : null,\n\t\t\t\tquestion: this.#question?.text ?? null,\n\t\t\t\tresult: this.#question ? null : this.#resultKind(),\n\t\t\t},\n\t\t\tt\n\t\t)\n\t\tthis.#annotate(nodes, this.#archive.length, this.#agent.history, this.#resultKind())\n\t\tconst conversation = [\n\t\t\t...this.#archivedNodes(t),\n\t\t\t...nodes,\n\t\t\t...this.#voiceRunNodes(this.#voiceRuns.list, t),\n\t\t]\n\t\tif (conversation.length === 0) {\n\t\t\tconst hint = document.createElement('div')\n\t\t\thint.className = styles.empty\n\t\t\thint.textContent = t('ui.panel.emptyHint')\n\t\t\tconversation.push(hint)\n\t\t}\n\t\t// REVERSIBLE (2026-11-17, feed stability): rebuild the feed only when what it shows changed. Otherwise the\n\t\t// nodes, their open previews and their place stay, and old nodes do not replay the entrance animation.\n\t\tconst key = JSON.stringify([\n\t\t\tthis.#agent.task,\n\t\t\tthis.#agent.history.length,\n\t\t\tthis.#agent.history.at(-1) ?? null,\n\t\t\tthis.#agent.status === 'running' ? this.#live : null,\n\t\t\tthis.#question\n\t\t\t\t? {\n\t\t\t\t\t\ttext: this.#question.text,\n\t\t\t\t\t\tkind: this.#question.kind,\n\t\t\t\t\t\tchoices: this.#question.choices,\n\t\t\t\t\t\tselected: [...this.#question.selected],\n\t\t\t\t\t}\n\t\t\t\t: null,\n\t\t\tthis.#question ? null : this.#resultKind(),\n\t\t\tthis.#voiceRuns.list,\n\t\t\tthis.#archive.length,\n\t\t\tthis.#collapsed,\n\t\t\tthis.#followMode,\n\t\t\tthis.#mode,\n\t\t])\n\t\tif (key !== this.#lastRenderKey) {\n\t\t\tthis.#lastRenderKey = key\n\t\t\tconst appended = conversation.length > this.#renderedCount\n\t\t\tconversation.forEach((node, i) => {\n\t\t\t\tif (!appended || i < this.#renderedCount) node.classList.remove(styles.enter)\n\t\t\t})\n\t\t\tthis.#renderedCount = conversation.length\n\t\t\tthis.#feed.replaceChildren(...conversation)\n\t\t}\n\t\tthis.#afterFeedUpdate()\n\n\t\tconst running = this.#agent.status === 'running'\n\t\tconst answering = this.#question !== null\n\t\tconst finished = !running && !answering && this.#resultKind() !== null\n\t\tconst inStudio = this.#mode === 'skills-studio'\n\t\tconst mobileBar = this.#followMode === 'bar' && this.#useFollowCycle()\n\t\tconst composerHidden = finished && this.#config.promptForNextTask === false\n\t\tthis.#feedWrap.hidden = inStudio || mobileBar\n\t\tthis.#composer.hidden = composerHidden || this.#mode !== 'text' || inStudio || mobileBar\n\t\tthis.#voiceStage.hidden = this.#mode !== 'voice' || mobileBar\n\t\tthis.#studioStage.hidden = !inStudio || mobileBar\n\t\tthis.#followBar.hidden = !mobileBar\n\t\tthis.#renderVoice()\n\t\tthis.#renderFollowBar()\n\t\tthis.#renderSkillsStudio()\n\t\tthis.#answerContext.hidden = !answering\n\t\tif (answering && this.#question) {\n\t\t\tconst q = this.#question\n\t\t\tconst title =\n\t\t\t\tq.kind === 'multi'\n\t\t\t\t\t? t('ui.panel.answerTitleMulti')\n\t\t\t\t\t: q.kind === 'choice'\n\t\t\t\t\t\t? t('ui.panel.answerTitleChoice')\n\t\t\t\t\t\t: t('ui.panel.answerTitle')\n\t\t\tthis.#choiceRow = null\n\t\t\tthis.#answerContext.replaceChildren()\n\t\t\tconst label = document.createElement('div')\n\t\t\tlabel.textContent = `${title}: ${q.text}`\n\t\t\tthis.#answerContext.append(label)\n\t\t\tthis.#renderChoiceChips()\n\t\t} else {\n\t\t\tthis.#answerContext.textContent = ''\n\t\t\tthis.#choiceRow?.remove()\n\t\t\tthis.#choiceRow = null\n\t\t}\n\t\tconst choiceOnly = answering && this.#question !== null && this.#question.kind === 'choice'\n\t\tthis.#textarea.disabled = (running && !answering) || choiceOnly\n\t\tthis.#textarea.placeholder = answering\n\t\t\t? this.#question?.kind === 'multi'\n\t\t\t\t? t('ui.panel.composerAnswerMulti')\n\t\t\t\t: this.#question?.kind === 'choice'\n\t\t\t\t\t? t('ui.panel.composerAnswerChoice')\n\t\t\t\t\t: t('ui.panel.composerAnswer')\n\t\t\t: running\n\t\t\t\t? t('ui.panel.composerRunning')\n\t\t\t\t: t('ui.panel.composerPlaceholder')\n\t\tthis.#sendButton.disabled = (running && !answering) || choiceOnly\n\t\tsetButton(this.#sendButton, 'send', t('ui.panel.send'))\n\t\tsetButton(this.#exportButton, 'download', t('ui.panel.exportLog'))\n\t\tthis.#exportButton.hidden = this.#archive.length === 0 && this.#agent.history.length === 0\n\t\tthis.#renderAttachments()\n\n\t\tif (running) setButton(this.#stopButton, 'stop', t('ui.panel.stop'))\n\t\telse setButton(this.#stopButton, 'close', t('ui.panel.close'))\n\t\tconst collapseTip =\n\t\t\tthis.#followMode === 'expanded'\n\t\t\t\t? this.#useFollowCycle()\n\t\t\t\t\t? t('ui.panel.followModeBar')\n\t\t\t\t\t: t('ui.panel.collapse')\n\t\t\t\t: this.#followMode === 'bar'\n\t\t\t\t\t? t('ui.panel.expand')\n\t\t\t\t\t: t('ui.panel.expandFromFab')\n\t\tsetButton(\n\t\t\tthis.#collapseButton,\n\t\t\tthis.#followMode === 'expanded' ? 'chevronUp' : 'chevronDown',\n\t\t\tcollapseTip\n\t\t)\n\t\tthis.#collapseButton.setAttribute('aria-expanded', String(this.#followMode === 'expanded'))\n\t\tsetButton(this.#skillsButton, 'skills', t('ui.panel.skillsStudio'))\n\t\tthis.#skillsButton.setAttribute('aria-pressed', String(inStudio))\n\t\tthis.#skillsButton.hidden = this.#mode === 'voice'\n\t\tif (this.#mode === 'voice') setButton(this.#micButton, 'keyboard', t('ui.panel.switchToText'))\n\t\telse setButton(this.#micButton, 'mic', t('ui.panel.switchToVoice'))\n\t\tthis.#micButton.setAttribute('aria-pressed', String(this.#mode === 'voice'))\n\t\tthis.#micButton.hidden = inStudio\n\t}\n\n\t#studioSupported(): boolean {\n\t\treturn (\n\t\t\ttypeof this.#agent.startSkillRecording === 'function' &&\n\t\t\ttypeof this.#agent.listSkillsCatalog === 'function' &&\n\t\t\ttypeof this.#agent.synthesizeSkill === 'function'\n\t\t)\n\t}\n\n\t#setStudioMessage(message: string, tone: 'ok' | 'warn' | 'err' | '' = ''): void {\n\t\tthis.#studioMessage = message\n\t\tthis.#studioMessageTone = tone\n\t}\n\n\t#stopStudioPolling(): void {\n\t\tif (!this.#studioPoll) return\n\t\tclearInterval(this.#studioPoll)\n\t\tthis.#studioPoll = null\n\t}\n\n\t#syncStudioPolling(): void {\n\t\tconst recording = Boolean(this.#agent.isSkillRecording?.())\n\t\tif (recording && this.#mode === 'skills-studio') {\n\t\t\tif (!this.#studioPoll) {\n\t\t\t\tthis.#studioPoll = setInterval(() => {\n\t\t\t\t\tif (this.#mode !== 'skills-studio' || !this.#agent.isSkillRecording?.()) {\n\t\t\t\t\t\tthis.#stopStudioPolling()\n\t\t\t\t\t\tthis.#renderSkillsStudio()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tthis.#renderSkillsStudio()\n\t\t\t\t}, 400)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tthis.#stopStudioPolling()\n\t}\n\n\t#refreshStudioCatalog(): void {\n\t\ttry {\n\t\t\tthis.#studioCatalog = this.#agent.listSkillsCatalog?.() ?? []\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t\tthis.#studioCatalog = []\n\t\t}\n\t}\n\n\t#refreshStudioWatches(): void {\n\t\ttry {\n\t\t\tthis.#studioWatches = this.#agent.listSkillWatches?.() ?? []\n\t\t} catch {\n\t\t\tthis.#studioWatches = []\n\t\t}\n\t}\n\n\t#watcherCommandFor(entry: StudioSkillCatalogEntry): string | null {\n\t\tconst names = new Set(entry.commands.map((c) => c.name))\n\t\tif (names.has('check')) return 'check'\n\t\tif (names.has('watch_reply')) return 'watch_reply'\n\t\tif (names.has('run')) return 'run'\n\t\treturn null\n\t}\n\n\t#canArmSkillWatch(): boolean {\n\t\treturn typeof this.#agent.armSkillWatch === 'function'\n\t}\n\n\t#notifySkillWatchEnter(): void {\n\t\tthis.#agent.notifySkillWatchEnter?.()\n\t}\n\n\t#renderSkillsStudio(): void {\n\t\tif (this.#mode !== 'skills-studio') return\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst supported = this.#studioSupported()\n\t\tconst recording = Boolean(this.#agent.isSkillRecording?.())\n\t\tconst steps = this.#agent.getRecordedSteps?.() ?? []\n\t\tconst busy = this.#studioBusy || this.#agent.status === 'running'\n\n\t\tconst back = this.#studioStage.querySelector<HTMLButtonElement>('[data-role=\"skills-back\"]')!\n\t\tsetButton(back, 'close', t('ui.panel.skillsStudioBack'))\n\t\tconst tabs = this.#studioStage.querySelectorAll<HTMLButtonElement>('[data-role=\"skills-tab\"]')\n\t\tfor (const button of tabs) {\n\t\t\tconst selected = button.dataset.tab === this.#studioTab\n\t\t\tbutton.setAttribute('aria-selected', String(selected))\n\t\t}\n\t\tconst panes = this.#studioStage.querySelectorAll<HTMLElement>('[data-role=\"skills-pane\"]')\n\t\tfor (const pane of panes) {\n\t\t\tpane.hidden = pane.dataset.tab !== this.#studioTab\n\t\t}\n\n\t\tconst unavailable = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-unavailable\"]'\n\t\t)!\n\t\tunavailable.hidden = supported\n\t\tunavailable.textContent = t('ui.panel.skillsStudioUnavailable')\n\n\t\tfor (const pane of panes) {\n\t\t\tif (pane.dataset.tab) pane.toggleAttribute('data-disabled', !supported)\n\t\t}\n\n\t\tconst recordStatus = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-record-status\"]'\n\t\t)!\n\t\tconst askStatus = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-ask-status\"]'\n\t\t)!\n\t\tconst catalogStatus = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-catalog-status\"]'\n\t\t)!\n\t\tconst statusText =\n\t\t\tthis.#studioMessage ||\n\t\t\t(recording ? t('ui.panel.skillsStudioRecording') : t('ui.panel.skillsStudioIdle'))\n\t\tconst statusTone = this.#studioMessage ? this.#studioMessageTone : recording ? 'warn' : ''\n\t\tfor (const el of [recordStatus, askStatus, catalogStatus]) {\n\t\t\tel.textContent = statusText\n\t\t\tif (statusTone) el.dataset.tone = statusTone\n\t\t\telse delete el.dataset.tone\n\t\t}\n\n\t\tconst startBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-record-start\"]'\n\t\t)!\n\t\tconst stopBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-record-stop\"]'\n\t\t)!\n\t\tconst finishBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-record-finish\"]'\n\t\t)!\n\t\tconst clearBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-record-clear\"]'\n\t\t)!\n\t\tconst saveBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-record-save\"]'\n\t\t)!\n\t\tconst testBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-record-test\"]'\n\t\t)!\n\t\tstartBtn.textContent = t('ui.panel.skillsStudioStart')\n\t\tstopBtn.textContent = t('ui.panel.skillsStudioStop')\n\t\tfinishBtn.textContent = t('ui.panel.skillsStudioFinish')\n\t\tclearBtn.textContent = t('ui.panel.skillsStudioClear')\n\t\tsaveBtn.textContent = t('ui.panel.skillsStudioSave')\n\t\ttestBtn.textContent = t('ui.panel.skillsStudioTest')\n\t\tstartBtn.disabled = !supported || busy || recording\n\t\tstopBtn.disabled = !supported || busy || !recording\n\t\tfinishBtn.disabled = !supported || busy || (!recording && steps.length === 0)\n\t\tclearBtn.disabled = !supported || busy || (steps.length === 0 && !this.#studioPreview)\n\t\tsaveBtn.disabled = !supported || busy || !this.#studioPreview\n\t\ttestBtn.disabled = !supported || busy || !this.#studioPreviewId\n\n\t\tconst stepsList = this.#studioStage.querySelector<HTMLOListElement>(\n\t\t\t'[data-role=\"skills-steps\"]'\n\t\t)!\n\t\tconst emptySteps = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-steps-empty\"]'\n\t\t)!\n\t\temptySteps.textContent = t('ui.panel.skillsStudioEmptySteps')\n\t\temptySteps.hidden = steps.length > 0\n\t\tstepsList.hidden = steps.length === 0\n\t\tstepsList.replaceChildren()\n\t\tfor (const step of steps) {\n\t\t\tstepsList.append(this.#createStudioStepRow(step, supported && !busy))\n\t\t}\n\n\t\tconst previewLabel = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-preview-label\"]'\n\t\t)!\n\t\tconst preview = this.#studioStage.querySelector<HTMLElement>('[data-role=\"skills-preview\"]')!\n\t\tconst previewActions = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-preview-actions\"]'\n\t\t)!\n\t\tpreviewLabel.textContent = t('ui.panel.skillsStudioPreview')\n\t\tconst hasPreview = Boolean(this.#studioPreview)\n\t\tpreviewLabel.hidden = !hasPreview\n\t\tpreview.hidden = !hasPreview\n\t\tpreviewActions.hidden = !hasPreview\n\t\tpreview.textContent = this.#studioPreview\n\n\t\tconst askStart = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-ask-start\"]'\n\t\t)!\n\t\tconst askInput = this.#studioStage.querySelector<HTMLTextAreaElement>(\n\t\t\t'[data-role=\"skills-ask-input\"]'\n\t\t)!\n\t\taskStart.textContent = t('ui.panel.skillsStudioAskStart')\n\t\taskStart.disabled = !supported || busy || !askInput.value.trim()\n\t\taskInput.disabled = !supported || busy\n\n\t\tconst refreshBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-catalog-refresh\"]'\n\t\t)!\n\t\tconst removeAgentBtn = this.#studioStage.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-catalog-remove-agent\"]'\n\t\t)!\n\t\trefreshBtn.textContent = t('ui.panel.skillsStudioRefreshRemote')\n\t\tremoveAgentBtn.textContent = t('ui.panel.skillsStudioRemoveAgentSkills')\n\t\tconst agentRows = this.#studioCatalog.filter((row) => row.scope === 'agent')\n\t\trefreshBtn.disabled = !supported || busy\n\t\tremoveAgentBtn.disabled = !supported || busy || agentRows.length === 0\n\n\t\tconst catalogEmpty = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-catalog-empty\"]'\n\t\t)!\n\t\tconst catalogList = this.#studioStage.querySelector<HTMLUListElement>(\n\t\t\t'[data-role=\"skills-catalog-list\"]'\n\t\t)!\n\t\tconst catalogCount = this.#studioStage.querySelector<HTMLElement>(\n\t\t\t'[data-role=\"skills-catalog-count\"]'\n\t\t)!\n\t\tcatalogCount.textContent = t('ui.panel.skillsStudioCatalogCount', {\n\t\t\tcount: String(this.#studioCatalog.length),\n\t\t})\n\t\tcatalogEmpty.textContent = t('ui.panel.skillsStudioEmptyCatalog')\n\t\tcatalogEmpty.hidden = this.#studioCatalog.length > 0\n\t\tcatalogList.hidden = this.#studioCatalog.length === 0\n\t\tcatalogList.replaceChildren()\n\t\tfor (const entry of this.#studioCatalog) {\n\t\t\tcatalogList.append(this.#createStudioCatalogRow(entry, supported && !busy))\n\t\t}\n\n\t\tthis.#renderStudioWatchers(supported && !busy)\n\n\t\tthis.#syncStudioPolling()\n\t}\n\n\t#renderStudioWatchers(enabled: boolean): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst strip = this.#studioStage.querySelector<HTMLElement>('[data-role=\"skills-watchers\"]')\n\t\tif (!strip) return\n\n\t\tconst canWatch = this.#canArmSkillWatch()\n\t\tstrip.hidden = !canWatch\n\t\tif (!canWatch) return\n\n\t\tthis.#refreshStudioWatches()\n\t\tconst title = strip.querySelector<HTMLElement>('[data-role=\"skills-watchers-title\"]')!\n\t\tconst empty = strip.querySelector<HTMLElement>('[data-role=\"skills-watchers-empty\"]')!\n\t\tconst list = strip.querySelector<HTMLUListElement>('[data-role=\"skills-watchers-list\"]')!\n\t\ttitle.textContent = t('ui.panel.skillsStudioWatchers')\n\t\tempty.textContent = t('ui.panel.skillsStudioWatchEmpty')\n\t\tempty.hidden = this.#studioWatches.length > 0\n\t\tlist.hidden = this.#studioWatches.length === 0\n\t\tlist.replaceChildren()\n\t\tfor (const watch of this.#studioWatches) {\n\t\t\tlist.append(this.#createStudioWatcherChip(watch, enabled))\n\t\t}\n\t}\n\n\t#createStudioWatcherChip(watch: StudioSkillWatchEntry, enabled: boolean): HTMLLIElement {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst chip = document.createElement('li')\n\t\tchip.className = styles.studioWatcherChip\n\t\tchip.dataset.watchId = watch.id\n\n\t\tconst label = document.createElement('span')\n\t\tlabel.className = styles.studioWatcherLabel\n\t\tlabel.textContent = `${watch.skillId}/${watch.command}`\n\t\tconst meta = document.createElement('span')\n\t\tmeta.className = styles.studioWatcherMeta\n\t\tmeta.textContent = watch.trigger\n\n\t\tconst disarm = document.createElement('button')\n\t\tdisarm.type = 'button'\n\t\tdisarm.textContent = t('ui.panel.skillsStudioDisarmWatch')\n\t\tdisarm.disabled = !enabled || typeof this.#agent.disarmSkillWatch !== 'function'\n\t\tdisarm.addEventListener('click', () => this.#onStudioDisarmWatch(watch.id))\n\n\t\tchip.append(label, meta, disarm)\n\t\treturn chip\n\t}\n\n\t#createStudioStepRow(step: StudioRecordedStep, enabled: boolean): HTMLLIElement {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst row = document.createElement('li')\n\t\trow.className = styles.studioStep\n\t\trow.dataset.stepId = step.id\n\n\t\tconst body = document.createElement('div')\n\t\tbody.className = styles.studioStepBody\n\t\tconst kind = document.createElement('span')\n\t\tkind.className = styles.studioStepKind\n\t\tkind.textContent = step.kind\n\t\tconst title = document.createElement('div')\n\t\tconst label =\n\t\t\tstep.rawLabel ||\n\t\t\t[step.role, step.name ? `\"${step.name}\"` : ''].filter(Boolean).join(' ') ||\n\t\t\tstep.kind\n\t\ttitle.append(kind, document.createTextNode(label))\n\t\tconst meta = document.createElement('div')\n\t\tmeta.className = styles.studioStepMeta\n\t\tconst bits = [\n\t\t\tstep.value !== undefined ? `value=${JSON.stringify(step.value)}` : '',\n\t\t\tstep.param ? 'param' : '',\n\t\t].filter(Boolean)\n\t\tmeta.textContent = bits.join(' · ')\n\t\tbody.append(title)\n\t\tif (bits.length) body.append(meta)\n\n\t\tconst actions = document.createElement('div')\n\t\tactions.className = styles.studioStepActions\n\t\tif (step.kind === 'fill' || step.kind === 'select') {\n\t\t\tconst paramBtn = document.createElement('button')\n\t\t\tparamBtn.type = 'button'\n\t\t\tparamBtn.textContent = step.param\n\t\t\t\t? t('ui.panel.skillsStudioUnparam')\n\t\t\t\t: t('ui.panel.skillsStudioParam')\n\t\t\tparamBtn.disabled = !enabled\n\t\t\tparamBtn.addEventListener('click', () => {\n\t\t\t\tthis.#agent.toggleRecordedStepParam?.(step.id)\n\t\t\t\tthis.#studioPreview = ''\n\t\t\t\tthis.#studioPreviewId = ''\n\t\t\t\tthis.#renderSkillsStudio()\n\t\t\t})\n\t\t\tactions.append(paramBtn)\n\t\t}\n\t\tconst removeBtn = document.createElement('button')\n\t\tremoveBtn.type = 'button'\n\t\tremoveBtn.textContent = t('ui.panel.skillsStudioRemoveStep')\n\t\tremoveBtn.disabled = !enabled\n\t\tremoveBtn.addEventListener('click', () => {\n\t\t\tthis.#agent.removeRecordedStep?.(step.id)\n\t\t\tthis.#studioPreview = ''\n\t\t\tthis.#studioPreviewId = ''\n\t\t\tthis.#renderSkillsStudio()\n\t\t})\n\t\tactions.append(removeBtn)\n\n\t\trow.append(body, actions)\n\t\treturn row\n\t}\n\n\t#createStudioCatalogRow(entry: StudioSkillCatalogEntry, enabled: boolean): HTMLLIElement {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst row = document.createElement('li')\n\t\trow.className = styles.studioCatalogRow\n\n\t\tconst body = document.createElement('div')\n\t\tbody.className = styles.studioCatalogBody\n\t\tconst title = document.createElement('div')\n\t\ttitle.textContent = entry.name || entry.id\n\t\tconst meta = document.createElement('div')\n\t\tmeta.className = styles.studioCatalogMeta\n\t\tconst scopeLabel =\n\t\t\tentry.scope === 'remote'\n\t\t\t\t? t('ui.panel.skillsStudioScopeRemote')\n\t\t\t\t: t('ui.panel.skillsStudioScopeAgent')\n\t\tconst bits = [\n\t\t\tentry.id,\n\t\t\tscopeLabel,\n\t\t\tentry.loaded ? t('ui.panel.skillsStudioLoaded') : '',\n\t\t\tentry.description,\n\t\t].filter(Boolean)\n\t\tmeta.textContent = bits.join(' · ')\n\t\tbody.append(title, meta)\n\n\t\tconst actions = document.createElement('div')\n\t\tactions.className = styles.studioCatalogActions\n\t\tconst watchCommand = this.#watcherCommandFor(entry)\n\t\tif (watchCommand && this.#canArmSkillWatch()) {\n\t\t\tconst armBtn = document.createElement('button')\n\t\t\tarmBtn.type = 'button'\n\t\t\tarmBtn.dataset.variant = 'accent'\n\t\t\tarmBtn.textContent = t('ui.panel.skillsStudioArmWatch')\n\t\t\tarmBtn.disabled = !enabled\n\t\t\tarmBtn.addEventListener('click', () => void this.#onStudioArmWatch(entry))\n\t\t\tactions.append(armBtn)\n\t\t}\n\t\tconst testBtn = document.createElement('button')\n\t\ttestBtn.type = 'button'\n\t\ttestBtn.textContent = t('ui.panel.skillsStudioTest')\n\t\ttestBtn.disabled = !enabled\n\t\ttestBtn.addEventListener('click', () => void this.#onStudioTestSkill(entry.id))\n\t\tactions.append(testBtn)\n\t\tif (entry.scope === 'agent') {\n\t\t\tconst removeBtn = document.createElement('button')\n\t\t\tremoveBtn.type = 'button'\n\t\t\tremoveBtn.textContent = t('ui.panel.skillsStudioRemoveSkill')\n\t\t\tremoveBtn.disabled = !enabled\n\t\t\tremoveBtn.addEventListener('click', () => void this.#onStudioRemoveSkill(entry.id))\n\t\t\tactions.append(removeBtn)\n\t\t}\n\n\t\trow.append(body, actions)\n\t\treturn row\n\t}\n\n\tasync #onStudioStartRecording(): Promise<void> {\n\t\tif (!this.#studioSupported() || this.#studioBusy) return\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tawait this.#agent.startSkillRecording?.()\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\t#onStudioStopRecording(): void {\n\t\tthis.#agent.stopSkillRecording?.()\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t}\n\n\t#onStudioFinishSynthesize(): void {\n\t\tif (!this.#studioSupported() || this.#studioBusy) return\n\t\tthis.#agent.stopSkillRecording?.()\n\t\ttry {\n\t\t\tconst result = this.#agent.synthesizeSkill?.()\n\t\t\tif (!result) throw new Error('synthesizeSkill is unavailable')\n\t\t\tthis.#studioPreview = result.document\n\t\t\tthis.#studioPreviewId = result.manifest.id\n\t\t\tthis.#setStudioMessage(\n\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioSynthesized', { id: result.manifest.id }),\n\t\t\t\t'ok'\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t}\n\t\tthis.#renderSkillsStudio()\n\t}\n\n\t#onStudioClearRecording(): void {\n\t\tthis.#agent.clearRecordedSteps?.()\n\t\tthis.#studioPreview = ''\n\t\tthis.#studioPreviewId = ''\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t}\n\n\tasync #onStudioSavePreview(): Promise<void> {\n\t\tif (!this.#studioPreview || !this.#agent.publishSkill || this.#studioBusy) return\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tconst result = await this.#agent.publishSkill(this.#studioPreview, 'studio-record')\n\t\t\tthis.#studioPreviewId = result.id\n\t\t\tif (result.remoteError) {\n\t\t\t\tthis.#setStudioMessage(\n\t\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioRemoteWarn', { error: result.remoteError }),\n\t\t\t\t\t'warn'\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tthis.#setStudioMessage(\n\t\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioSaved', {\n\t\t\t\t\t\tid: result.id,\n\t\t\t\t\t\tversion: String(result.version),\n\t\t\t\t\t}),\n\t\t\t\t\t'ok'\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.#refreshStudioCatalog()\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\tasync #onStudioTestSkill(id: string): Promise<void> {\n\t\tif (!id || !this.#agent.testSkill || this.#studioBusy) return\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tconst result = await this.#agent.testSkill(id)\n\t\t\tconst trimmed = result.length > 180 ? `${result.slice(0, 177)}…` : result\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioTested', { result: trimmed }), 'ok')\n\t\t\tthis.#refreshStudioCatalog()\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\tasync #onStudioAskStart(): Promise<void> {\n\t\tif (!this.#studioSupported() || this.#studioBusy) return\n\t\tconst input = this.#studioStage.querySelector<HTMLTextAreaElement>(\n\t\t\t'[data-role=\"skills-ask-input\"]'\n\t\t)!\n\t\tconst goal = input.value.trim()\n\t\tif (!goal) return\n\n\t\tconst prompt = [\n\t\t\t'You are authoring a reusable Page Agent skill for the goal below.',\n\t\t\t'Explore the current page only as needed, then call save_skill with one complete skill Markdown document:',\n\t\t\t'YAML frontmatter (name, description, version, id, scope: agent), a short guidance body, and exactly one skill-js fence exporting commands.',\n\t\t\t'Keep the skill generic: parameterize values that change between runs as command inputs.',\n\t\t\t'Do not ask the user unless you are blocked. Finish after save_skill succeeds.',\n\t\t\t`Goal: ${goal}`,\n\t\t].join('\\n')\n\n\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioAskQueued'), 'warn')\n\t\tthis.#leaveSkillsStudio()\n\t\ttry {\n\t\t\tawait this.#agent.execute(prompt)\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tthis.#refreshStudioCatalog()\n\t\t\t} catch {\n\t\t\t\t/* catalog refresh is best-effort after Ask */\n\t\t\t}\n\t\t}\n\t}\n\n\tasync #onStudioRefreshRemote(): Promise<void> {\n\t\tif (!this.#agent.refreshRemoteSkills || this.#studioBusy) return\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tconst result = await this.#agent.refreshRemoteSkills({ force: true })\n\t\t\tthis.#refreshStudioCatalog()\n\t\t\tthis.#setStudioMessage(\n\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioCatalogCount', {\n\t\t\t\t\tcount: String(result.ids.length || this.#studioCatalog.length),\n\t\t\t\t}),\n\t\t\t\t'ok'\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\tasync #onStudioRemoveSkill(id: string): Promise<void> {\n\t\tif (!this.#agent.removeAgentSkill || this.#studioBusy) return\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tawait this.#agent.removeAgentSkill(id)\n\t\t\tif (this.#studioPreviewId === id) {\n\t\t\t\tthis.#studioPreviewId = ''\n\t\t\t}\n\t\t\tthis.#refreshStudioCatalog()\n\t\t\tthis.#setStudioMessage(\n\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioCatalogCount', {\n\t\t\t\t\tcount: String(this.#studioCatalog.length),\n\t\t\t\t}),\n\t\t\t\t'ok'\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\tasync #onStudioArmWatch(entry: StudioSkillCatalogEntry): Promise<void> {\n\t\tif (!this.#agent.armSkillWatch || this.#studioBusy) return\n\t\tconst command = this.#watcherCommandFor(entry)\n\t\tif (!command) return\n\n\t\tconst commandNames = new Set(entry.commands.map((c) => c.name))\n\t\tconst watchId = `watch-${entry.id}`\n\t\tlet input: Record<string, unknown> | undefined\n\t\tlet trigger: 'interval' | 'on-enter' | 'on-url' = 'interval'\n\n\t\tif (command === 'watch_reply') {\n\t\t\tconst promptLabel = this.#i18n.t('ui.panel.skillsStudioWatchNeedlePrompt')\n\t\t\tconst raw = typeof window.prompt === 'function' ? window.prompt(promptLabel, 'reply') : null\n\t\t\tconst needle = (raw ?? 'reply').trim() || 'reply'\n\t\t\tinput = { needle }\n\t\t} else if (entry.id === 'on-enter') {\n\t\t\ttrigger = 'on-enter'\n\t\t}\n\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tif (commandNames.has('snapshot')) {\n\t\t\t\tawait this.#agent.loadSkill?.(entry.id)\n\t\t\t\t// testSkill runs `run` or the first command; for watch-page-change that is snapshot.\n\t\t\t\tif (this.#agent.testSkill && !commandNames.has('run')) {\n\t\t\t\t\tawait this.#agent.testSkill(entry.id)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tawait this.#agent.loadSkill?.(entry.id)\n\t\t\t}\n\n\t\t\tconst armed = this.#agent.armSkillWatch({\n\t\t\t\tid: watchId,\n\t\t\t\tskillId: entry.id,\n\t\t\t\tcommand,\n\t\t\t\tinput,\n\t\t\t\ttrigger,\n\t\t\t\teveryMs: 15_000,\n\t\t\t})\n\t\t\tthis.#refreshStudioWatches()\n\t\t\tthis.#setStudioMessage(\n\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioWatchArmed', { id: armed.id }),\n\t\t\t\t'ok'\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\t#onStudioDisarmWatch(id: string): void {\n\t\tif (!this.#agent.disarmSkillWatch) return\n\t\ttry {\n\t\t\tthis.#agent.disarmSkillWatch(id)\n\t\t\tthis.#refreshStudioWatches()\n\t\t\tthis.#setStudioMessage('')\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t}\n\t\tthis.#renderSkillsStudio()\n\t}\n\n\tasync #onStudioRemoveAgentSkills(): Promise<void> {\n\t\tif (!this.#agent.removeAgentSkill || this.#studioBusy) return\n\t\tconst ids = this.#studioCatalog.filter((row) => row.scope === 'agent').map((row) => row.id)\n\t\tif (!ids.length) return\n\t\tthis.#studioBusy = true\n\t\tthis.#setStudioMessage('')\n\t\tthis.#renderSkillsStudio()\n\t\ttry {\n\t\t\tfor (const id of ids) {\n\t\t\t\tawait this.#agent.removeAgentSkill(id)\n\t\t\t}\n\t\t\tif (ids.includes(this.#studioPreviewId)) this.#studioPreviewId = ''\n\t\t\tthis.#refreshStudioCatalog()\n\t\t\tthis.#setStudioMessage(\n\t\t\t\tthis.#i18n.t('ui.panel.skillsStudioCatalogCount', {\n\t\t\t\t\tcount: String(this.#studioCatalog.length),\n\t\t\t\t}),\n\t\t\t\t'ok'\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\tthis.#setStudioMessage(this.#i18n.t('ui.panel.skillsStudioError', { message }), 'err')\n\t\t\tthis.#refreshStudioCatalog()\n\t\t} finally {\n\t\t\tthis.#studioBusy = false\n\t\t\tthis.#renderSkillsStudio()\n\t\t}\n\t}\n\n\t#enterSkillsStudio(): void {\n\t\tif (this.#mode === 'skills-studio') return\n\t\tif (this.#mode === 'voice') this.#voice.disable()\n\t\tthis.#modeBeforeStudio = this.#mode === 'voice' ? 'voice' : 'text'\n\t\tthis.#mode = 'skills-studio'\n\t\tthis.#studioTab = 'record'\n\t\tthis.#setStudioMessage('')\n\t\tif (this.#studioSupported()) {\n\t\t\tthis.#refreshStudioCatalog()\n\t\t\tthis.#refreshStudioWatches()\n\t\t}\n\t\tthis.#followMode = 'expanded'\n\t\tthis.#collapsed = false\n\t\tthis.#wrapper.dataset.follow = 'expanded'\n\t\tthis.#notifySkillWatchEnter()\n\t\tthis.#render()\n\t}\n\n\t#leaveSkillsStudio(): void {\n\t\tif (this.#mode !== 'skills-studio') return\n\t\tif (this.#agent.isSkillRecording?.()) this.#agent.stopSkillRecording?.()\n\t\tthis.#stopStudioPolling()\n\t\tconst next = this.#modeBeforeStudio\n\t\tthis.#mode = next\n\t\tif (next === 'voice') void this.#voice.enable()\n\t\tthis.#render()\n\t\tif (next === 'text') this.#textarea.focus()\n\t}\n\n\t#setStudioTab(tab: 'record' | 'ask' | 'catalog'): void {\n\t\tthis.#studioTab = tab\n\t\tif (tab === 'catalog' && this.#studioSupported()) this.#refreshStudioCatalog()\n\t\tthis.#renderSkillsStudio()\n\t}\n\n\t#canAttachFiles(): boolean {\n\t\treturn typeof this.#agent.attachTaskFile === 'function'\n\t}\n\n\t#renderAttachments(): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst button = this.#attachButton\n\t\tconst list = this.#attachList\n\t\tif (!button || !list) return\n\n\t\tconst supported = this.#canAttachFiles()\n\t\tbutton.hidden = !supported || this.#mode === 'voice'\n\t\tsetButton(button, 'paperclip', t('ui.panel.attachFile'))\n\t\tbutton.disabled = !supported\n\n\t\tconst files = supported ? (this.#agent.listTaskFiles?.() ?? []) : []\n\t\tlist.replaceChildren()\n\t\tlist.hidden = files.length === 0 && !this.#attachError\n\n\t\tfor (const file of files) {\n\t\t\tconst chip = document.createElement('span')\n\t\t\tchip.className = styles.attachChip\n\t\t\tconst label = document.createElement('span')\n\t\t\tlabel.className = styles.attachName\n\t\t\tlabel.textContent = file.name\n\t\t\tchip.append(label)\n\t\t\tif (typeof this.#agent.removeTaskFile === 'function') {\n\t\t\t\tconst remove = document.createElement('button')\n\t\t\t\tremove.type = 'button'\n\t\t\t\tremove.className = styles.attachRemove\n\t\t\t\tremove.setAttribute('aria-label', t('ui.panel.attachRemove', { name: file.name }))\n\t\t\t\tremove.innerHTML = icon('close')\n\t\t\t\tremove.addEventListener('click', () => {\n\t\t\t\t\tthis.#agent.removeTaskFile?.(file.id)\n\t\t\t\t\tthis.#attachError = ''\n\t\t\t\t\tthis.#renderAttachments()\n\t\t\t\t})\n\t\t\t\tchip.append(remove)\n\t\t\t}\n\t\t\tlist.append(chip)\n\t\t}\n\n\t\tif (this.#attachError) {\n\t\t\tconst err = document.createElement('span')\n\t\t\terr.className = styles.attachError\n\t\t\terr.textContent = this.#attachError\n\t\t\tlist.append(err)\n\t\t}\n\t}\n\n\tasync #onAttachFiles(fileList: FileList | null): Promise<void> {\n\t\tif (!fileList?.length || !this.#agent.attachTaskFile) return\n\t\tthis.#attachError = ''\n\t\tfor (const file of Array.from(fileList)) {\n\t\t\ttry {\n\t\t\t\tawait this.#agent.attachTaskFile(file)\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\t\tthis.#attachError = message || this.#i18n.t('ui.panel.attachFailed')\n\t\t\t\tconsole.warn('[page-agent] attachTaskFile failed', error)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (this.#attachInput) this.#attachInput.value = ''\n\t\tthis.#renderAttachments()\n\t}\n\n\t/** Download a compact text trace of every task in this panel session. */\n\t#exportLog(): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst runs = this.#archive.map((run) => ({\n\t\t\ttask: run.task,\n\t\t\thistory: run.history,\n\t\t\toutcome: run.result ? `${run.result.kind}: ${run.result.text}` : '',\n\t\t}))\n\t\tif (this.#agent.task || this.#agent.history.length > 0) {\n\t\t\tconst outcome = this.#resultKind()\n\t\t\truns.push({\n\t\t\t\ttask: this.#agent.task || '',\n\t\t\t\thistory: [...this.#agent.history],\n\t\t\t\toutcome: outcome ? `${outcome.kind}: ${outcome.text}` : '',\n\t\t\t})\n\t\t}\n\t\tconst now = new Date()\n\t\tconst text = formatTrace(runs, t, now)\n\t\tconst stamp = now.toISOString().replace(/[:.]/g, '-').slice(0, 19)\n\t\tconst url = URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' }))\n\t\tconst link = document.createElement('a')\n\t\tlink.href = url\n\t\tlink.download = `nostop-log-${stamp}.txt`\n\t\tdocument.body.appendChild(link)\n\t\tlink.click()\n\t\tlink.remove()\n\t\tsetTimeout(() => URL.revokeObjectURL(url), 1000)\n\t}\n\n\t#useFollowCycle(): boolean {\n\t\treturn typeof window !== 'undefined' && window.matchMedia(FOLLOW_CYCLE_MQ).matches\n\t}\n\n\t#syncFollowFabLabel(): void {\n\t\tconst tip = this.#i18n.t('ui.panel.expandFromFab')\n\t\tthis.#fab.dataset.tip = tip\n\t\tthis.#fab.setAttribute('aria-label', tip)\n\t}\n\n\t#setFollowMode(mode: FollowMode): void {\n\t\tconst wasCollapsed = this.#collapsed\n\t\tthis.#followMode = mode\n\t\tthis.#collapsed = mode !== 'expanded'\n\t\tthis.#wrapper.dataset.follow = mode\n\t\tif (mode === 'fab') {\n\t\t\tthis.wrapper.style.opacity = '0'\n\t\t\tthis.wrapper.style.transform = 'translateY(20px)'\n\t\t\tthis.wrapper.style.display = 'none'\n\t\t\tthis.#fab.hidden = false\n\t\t\tthis.#syncFollowFabLabel()\n\t\t} else {\n\t\t\tthis.#fab.hidden = true\n\t\t\tif (this.wrapper.style.display === 'none') {\n\t\t\t\tthis.wrapper.style.display = 'flex'\n\t\t\t\tthis.wrapper.getBoundingClientRect()\n\t\t\t\tthis.wrapper.style.opacity = '1'\n\t\t\t\tthis.wrapper.style.transform = 'translateY(0)'\n\t\t\t}\n\t\t}\n\t\tif (wasCollapsed && !this.#collapsed) this.#notifySkillWatchEnter()\n\t\tthis.#render()\n\t}\n\n\t#cycleFollowMode(): void {\n\t\tif (!this.#useFollowCycle()) {\n\t\t\tthis.#setFollowMode(this.#followMode === 'expanded' ? 'bar' : 'expanded')\n\t\t\treturn\n\t\t}\n\t\tconst next: Record<FollowMode, FollowMode> = {\n\t\t\texpanded: 'bar',\n\t\t\tbar: 'fab',\n\t\t\tfab: 'expanded',\n\t\t}\n\t\tthis.#setFollowMode(next[this.#followMode])\n\t}\n\n\t#setCollapsed(collapsed: boolean): void {\n\t\tif (this.#useFollowCycle()) {\n\t\t\tif (!collapsed) this.#setFollowMode('expanded')\n\t\t\telse if (this.#followMode === 'expanded') this.#setFollowMode('bar')\n\t\t\telse this.#setFollowMode('fab')\n\t\t\treturn\n\t\t}\n\t\tthis.#setFollowMode(collapsed ? 'bar' : 'expanded')\n\t}\n\n\t#setMode(mode: 'text' | 'voice'): void {\n\t\tif (this.#mode === 'skills-studio') this.#modeBeforeStudio = mode\n\t\tif (this.#mode === 'voice' && mode !== 'voice') this.#voice.disable()\n\t\tif (mode === 'voice') void this.#voice.enable()\n\t\telse this.#voice.disable()\n\t\tthis.#mode = mode\n\t\tthis.#render()\n\t\tif (mode === 'text') this.#textarea.focus()\n\t}\n\n\t/** Voice stage: one status word, mic name, a mute toggle and a way back to text. */\n\t#renderVoice(): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst state = this.#voice.state\n\t\tconst errorLabels: Record<VoiceError, string> = {\n\t\t\t'no-key': t('ui.panel.voiceNoKey'),\n\t\t\t'mic-denied': t('ui.panel.voiceDenied'),\n\t\t\t'mic-unsupported': t('ui.panel.voiceUnavailable'),\n\t\t\t'mic-busy': t('ui.panel.voiceMicBusy'),\n\t\t\t'connect-failed': t('ui.panel.voiceConnectFailed'),\n\t\t}\n\t\tconst live = state === 'listening' || state === 'speaking' || state === 'connecting'\n\t\tconst silent = live && this.#mic.hardwareMuted\n\t\tconst labels: Record<VoiceState, string> = {\n\t\t\toff: t('ui.panel.voiceOff'),\n\t\t\tconnecting: t('ui.panel.voiceConnecting'),\n\t\t\tlistening: silent ? t('ui.panel.voiceMicSilent') : t('ui.panel.voiceListening'),\n\t\t\tspeaking: t('ui.panel.voiceSpeaking'),\n\t\t\tmuted: t('ui.panel.voiceMuted'),\n\t\t\terror: this.#voice.error ? errorLabels[this.#voice.error] : t('ui.panel.voiceConnectFailed'),\n\t\t}\n\t\tconst lensState = {\n\t\t\toff: 'off',\n\t\t\tconnecting: 'active',\n\t\t\tlistening: silent ? 'denied' : 'active',\n\t\t\tspeaking: 'active',\n\t\t\tmuted: 'muted',\n\t\t\terror: 'denied',\n\t\t}[state]\n\t\tthis.#voiceStage.dataset.voiceState = state\n\t\tconst lens = this.#voiceStage.querySelector<HTMLElement>('[data-role=\"lens\"]')!\n\t\tlens.dataset.state = lensState\n\t\tlens.innerHTML = icon(lensState === 'active' ? 'mic' : 'micOff')\n\t\tthis.#voiceStage.querySelector<HTMLElement>('[data-role=\"voice-state\"]')!.textContent =\n\t\t\tlabels[state]\n\t\tconst device = this.#voiceStage.querySelector<HTMLButtonElement>('[data-role=\"mic-device\"]')!\n\t\tconst deviceLabel = this.#mic.label.trim()\n\t\tconst showDevice = Boolean(deviceLabel) && (live || state === 'muted' || state === 'error')\n\t\tdevice.hidden = !showDevice\n\t\tdevice.textContent = deviceLabel\n\t\tdevice.disabled = !live\n\t\tdevice.setAttribute('aria-label', t('ui.panel.switchMic'))\n\t\tdevice.dataset.tip = t('ui.panel.switchMic')\n\t\tconst mute = this.#voiceStage.querySelector<HTMLButtonElement>('[data-role=\"mute\"]')!\n\t\tconst muted = this.#voice.muted\n\t\tsetButton(mute, muted ? 'mic' : 'micOff', t(muted ? 'ui.panel.unmute' : 'ui.panel.mute'))\n\t\tmute.setAttribute('aria-pressed', String(muted))\n\t\tmute.disabled = state === 'error' || state === 'off'\n\t\tconst voiceStop = this.#voiceStage.querySelector<HTMLButtonElement>('[data-role=\"voice-stop\"]')\n\t\tif (voiceStop) {\n\t\t\tconst running = this.#agent.status === 'running'\n\t\t\tsetButton(\n\t\t\t\tvoiceStop,\n\t\t\t\trunning ? 'stop' : 'close',\n\t\t\t\tt(running ? 'ui.panel.stop' : 'ui.panel.close')\n\t\t\t)\n\t\t}\n\t\tsetButton(\n\t\t\tthis.#voiceStage.querySelector<HTMLButtonElement>('[data-role=\"back\"]')!,\n\t\t\t'keyboard',\n\t\t\tt('ui.panel.switchToText')\n\t\t)\n\t}\n\n\t/** Slim follow strip: status + optional voice lens/mute + stop, without the full feed. */\n\t#renderFollowBar(): void {\n\t\tif (this.#followMode !== 'bar') return\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst voiceMode = this.#mode === 'voice'\n\t\tconst status = this.#followBar.querySelector<HTMLElement>('[data-role=\"follow-bar-status\"]')!\n\t\tconst lens = this.#followBar.querySelector<HTMLElement>('[data-role=\"follow-bar-lens\"]')!\n\t\tconst mute = this.#followBar.querySelector<HTMLButtonElement>('[data-role=\"follow-bar-mute\"]')!\n\t\tconst action = this.#followBar.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"follow-bar-action\"]'\n\t\t)!\n\t\tconst minimize = this.#followBar.querySelector<HTMLButtonElement>(\n\t\t\t'[data-role=\"follow-bar-minimize\"]'\n\t\t)!\n\n\t\tif (voiceMode) {\n\t\t\tconst state = this.#voice.state\n\t\t\tconst live = state === 'listening' || state === 'speaking' || state === 'connecting'\n\t\t\tconst silent = live && this.#mic.hardwareMuted\n\t\t\tconst labels: Record<VoiceState, string> = {\n\t\t\t\toff: t('ui.panel.voiceOff'),\n\t\t\t\tconnecting: t('ui.panel.voiceConnecting'),\n\t\t\t\tlistening: silent ? t('ui.panel.voiceMicSilent') : t('ui.panel.voiceListening'),\n\t\t\t\tspeaking: t('ui.panel.voiceSpeaking'),\n\t\t\t\tmuted: t('ui.panel.voiceMuted'),\n\t\t\t\terror: t('ui.panel.voiceConnectFailed'),\n\t\t\t}\n\t\t\tstatus.textContent = labels[state]\n\t\t\tconst lensState = {\n\t\t\t\toff: 'off',\n\t\t\t\tconnecting: 'active',\n\t\t\t\tlistening: silent ? 'denied' : 'active',\n\t\t\t\tspeaking: 'active',\n\t\t\t\tmuted: 'muted',\n\t\t\t\terror: 'denied',\n\t\t\t}[state]\n\t\t\tlens.hidden = false\n\t\t\tlens.dataset.state = lensState\n\t\t\tlens.innerHTML = icon(lensState === 'active' ? 'mic' : 'micOff')\n\t\t\tmute.hidden = false\n\t\t\tconst muted = this.#voice.muted\n\t\t\tsetButton(mute, muted ? 'mic' : 'micOff', t(muted ? 'ui.panel.unmute' : 'ui.panel.mute'))\n\t\t\tmute.setAttribute('aria-pressed', String(muted))\n\t\t\tmute.disabled = state === 'error' || state === 'off'\n\t\t} else {\n\t\t\tstatus.textContent = this.#statusLabel()\n\t\t\tlens.hidden = true\n\t\t\tmute.hidden = true\n\t\t}\n\n\t\tconst running = this.#agent.status === 'running'\n\t\tsetButton(action, running ? 'stop' : 'close', t(running ? 'ui.panel.stop' : 'ui.panel.close'))\n\t\tsetButton(minimize, 'chevronDown', t('ui.panel.followModeMinimize'))\n\t}\n\n\t#autoSize(): void {\n\t\tthis.#textarea.style.height = 'auto'\n\t\tthis.#textarea.style.height = `${Math.min(this.#textarea.scrollHeight, 120)}px`\n\t}\n\n\t// ========== DOM ==========\n\n\t#createWrapper(): HTMLElement {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst wrapper = document.createElement('div')\n\t\twrapper.id = 'page-agent-runtime_agent-panel'\n\t\twrapper.className = styles.wrapper\n\t\twrapper.setAttribute('data-browser-use-ignore', 'true')\n\t\twrapper.setAttribute('data-page-agent-ignore', 'true')\n\t\twrapper.dataset.state = 'idle'\n\t\twrapper.dataset.follow = 'expanded'\n\n\t\t// Built from static markup plus textContent; no user text is parsed as HTML.\n\t\twrapper.innerHTML = `\n\t\t\t<header class=\"${styles.header}\">\n\t\t\t\t<span class=\"${styles.brand}\" data-role=\"brand\" aria-hidden=\"true\">${icon('spark')}</span>\n\t\t\t\t<div class=\"${styles.titleBlock}\">\n\t\t\t\t\t<strong class=\"${styles.title}\" data-role=\"title\"></strong>\n\t\t\t\t\t<span class=\"${styles.status}\" role=\"status\" data-role=\"status\"></span>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"${styles.controls}\">\n\t\t\t\t\t<button type=\"button\" class=\"${styles.iconButton} ${styles.tip}\" data-role=\"skills\" aria-pressed=\"false\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.iconButton} ${styles.tip}\" data-role=\"export\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.iconButton} ${styles.tip}\" data-role=\"cursor\" aria-pressed=\"false\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.iconButton} ${styles.tip}\" data-role=\"collapse\" aria-expanded=\"true\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.iconButton} ${styles.stopButton} ${styles.tip}\" data-role=\"action\"></button>\n\t\t\t\t</div>\n\t\t\t</header>\n\t\t\t<div class=\"${styles.feedWrap}\" data-role=\"feed-wrap\">\n\t\t\t\t<div class=\"${styles.feed}\" data-role=\"feed\" role=\"log\" aria-live=\"polite\" tabindex=\"0\"></div>\n\t\t\t\t<div class=\"${styles.rail}\" data-role=\"rail\" hidden><span class=\"${styles.railThumb}\" data-role=\"thumb\"></span></div>\n\t\t\t\t<button type=\"button\" class=\"${styles.jump}\" data-role=\"jump\" hidden></button>\n\t\t\t\t<div class=\"${styles.peek}\" data-role=\"peek\" hidden></div>\n\t\t\t</div>\n\t\t\t<form class=\"${styles.composer}\" data-role=\"composer\" autocomplete=\"off\">\n\t\t\t\t<div class=\"${styles.answerContext}\" data-role=\"answer-context\" hidden></div>\n\t\t\t\t<div class=\"${styles.attachList}\" data-role=\"attach-list\" hidden></div>\n\t\t\t\t<div class=\"${styles.box}\">\n\t\t\t\t\t<textarea rows=\"1\" data-role=\"input\" maxlength=\"1000\" aria-label=\"${t('ui.panel.composerPlaceholder')}\"></textarea>\n\t\t\t\t\t<div class=\"${styles.actions}\">\n\t\t\t\t\t\t<input type=\"file\" data-role=\"attach-input\" multiple hidden />\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.roundButton} ${styles.tip} ${styles.tipUp}\" data-role=\"attach\" hidden></button>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.roundButton} ${styles.tip} ${styles.tipUp}\" data-role=\"mic\" aria-pressed=\"false\"></button>\n\t\t\t\t\t\t<button type=\"submit\" class=\"${styles.roundButton} ${styles.send} ${styles.tip} ${styles.tipUp}\" data-role=\"send\"></button>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</form>\n\t\t\t<div class=\"${styles.voice}\" data-role=\"voice\" hidden>\n\t\t\t\t<span class=\"${styles.lens}\" data-role=\"lens\" data-state=\"off\" aria-hidden=\"true\"></span>\n\t\t\t\t<div class=\"${styles.voiceMeta}\">\n\t\t\t\t\t<span class=\"${styles.voiceText}\" data-role=\"voice-state\"></span>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.micDevice} ${styles.tip} ${styles.tipUp}\" data-role=\"mic-device\" hidden></button>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"${styles.voiceActions}\">\n\t\t\t\t\t<button type=\"button\" class=\"${styles.roundButton} ${styles.tip} ${styles.tipUp}\" data-role=\"mute\" aria-pressed=\"false\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.roundButton} ${styles.tip} ${styles.tipUp}\" data-role=\"voice-stop\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.roundButton} ${styles.tip} ${styles.tipUp}\" data-role=\"back\"></button>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div class=\"${styles.followBar}\" data-role=\"follow-bar\" hidden>\n\t\t\t\t<button type=\"button\" class=\"${styles.followBarBody}\" data-role=\"follow-bar-body\">\n\t\t\t\t\t<span class=\"${styles.followBarStatus}\" data-role=\"follow-bar-status\"></span>\n\t\t\t\t\t<span class=\"${styles.lens} ${styles.followBarLens}\" data-role=\"follow-bar-lens\" data-state=\"off\" hidden aria-hidden=\"true\"></span>\n\t\t\t\t</button>\n\t\t\t\t<button type=\"button\" class=\"${styles.roundButton}\" data-role=\"follow-bar-mute\" aria-pressed=\"false\" hidden></button>\n\t\t\t\t<button type=\"button\" class=\"${styles.roundButton}\" data-role=\"follow-bar-action\"></button>\n\t\t\t\t<button type=\"button\" class=\"${styles.roundButton}\" data-role=\"follow-bar-minimize\"></button>\n\t\t\t</div>\n\t\t\t<section class=\"${styles.studio}\" data-role=\"skills-studio\" hidden>\n\t\t\t\t<header class=\"${styles.studioHeader}\">\n\t\t\t\t\t<strong class=\"${styles.studioTitle}\" data-role=\"skills-title\"></strong>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.iconButton} ${styles.tip} ${styles.tipUp}\" data-role=\"skills-back\"></button>\n\t\t\t\t</header>\n\t\t\t\t<nav class=\"${styles.studioTabs}\" role=\"tablist\" data-role=\"skills-tablist\">\n\t\t\t\t\t<button type=\"button\" class=\"${styles.studioTab}\" role=\"tab\" data-role=\"skills-tab\" data-tab=\"record\" aria-selected=\"true\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.studioTab}\" role=\"tab\" data-role=\"skills-tab\" data-tab=\"ask\" aria-selected=\"false\"></button>\n\t\t\t\t\t<button type=\"button\" class=\"${styles.studioTab}\" role=\"tab\" data-role=\"skills-tab\" data-tab=\"catalog\" aria-selected=\"false\"></button>\n\t\t\t\t</nav>\n\t\t\t\t<p class=\"${styles.studioStatus}\" data-role=\"skills-unavailable\" hidden></p>\n\t\t\t\t<div class=\"${styles.studioBody}\" data-role=\"skills-pane\" data-tab=\"record\">\n\t\t\t\t\t<p class=\"${styles.studioHint}\" data-role=\"skills-record-hint\"></p>\n\t\t\t\t\t<div class=\"${styles.studioToolbar}\" data-role=\"skills-record-toolbar\">\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-record-start\" data-variant=\"accent\"></button>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-record-stop\"></button>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-record-finish\" data-variant=\"accent\"></button>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-record-clear\"></button>\n\t\t\t\t\t</div>\n\t\t\t\t\t<p class=\"${styles.studioStatus}\" data-role=\"skills-record-status\"></p>\n\t\t\t\t\t<p class=\"${styles.studioHint}\" data-role=\"skills-steps-empty\"></p>\n\t\t\t\t\t<ol class=\"${styles.studioSteps}\" data-role=\"skills-steps\" hidden></ol>\n\t\t\t\t\t<p class=\"${styles.studioPreviewLabel}\" data-role=\"skills-preview-label\" hidden></p>\n\t\t\t\t\t<pre class=\"${styles.studioPreview}\" data-role=\"skills-preview\" hidden></pre>\n\t\t\t\t\t<div class=\"${styles.studioToolbar}\" data-role=\"skills-preview-actions\" hidden>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-record-save\" data-variant=\"accent\"></button>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-record-test\"></button>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"${styles.studioBody}\" data-role=\"skills-pane\" data-tab=\"ask\" hidden>\n\t\t\t\t\t<p class=\"${styles.studioHint}\" data-role=\"skills-ask-hint\"></p>\n\t\t\t\t\t<textarea class=\"${styles.studioAsk}\" data-role=\"skills-ask-input\" rows=\"3\" maxlength=\"2000\"></textarea>\n\t\t\t\t\t<div class=\"${styles.studioToolbar}\">\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-ask-start\" data-variant=\"accent\"></button>\n\t\t\t\t\t</div>\n\t\t\t\t\t<p class=\"${styles.studioStatus}\" data-role=\"skills-ask-status\"></p>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"${styles.studioBody}\" data-role=\"skills-pane\" data-tab=\"catalog\" hidden>\n\t\t\t\t\t<div class=\"${styles.studioToolbar}\" data-role=\"skills-catalog-toolbar\">\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-catalog-refresh\"></button>\n\t\t\t\t\t\t<button type=\"button\" class=\"${styles.studioToolButton}\" data-role=\"skills-catalog-remove-agent\" data-variant=\"danger\"></button>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"${styles.studioWatchers}\" data-role=\"skills-watchers\" hidden>\n\t\t\t\t\t\t<div class=\"${styles.studioWatchersHead}\">\n\t\t\t\t\t\t\t<strong class=\"${styles.studioWatchersTitle}\" data-role=\"skills-watchers-title\"></strong>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<p class=\"${styles.studioWatchersEmpty}\" data-role=\"skills-watchers-empty\"></p>\n\t\t\t\t\t\t<ul class=\"${styles.studioWatchersList}\" data-role=\"skills-watchers-list\"></ul>\n\t\t\t\t\t</div>\n\t\t\t\t\t<p class=\"${styles.studioStatus}\" data-role=\"skills-catalog-count\"></p>\n\t\t\t\t\t<p class=\"${styles.studioHint}\" data-role=\"skills-catalog-empty\"></p>\n\t\t\t\t\t<ul class=\"${styles.studioCatalog}\" data-role=\"skills-catalog-list\"></ul>\n\t\t\t\t\t<p class=\"${styles.studioStatus}\" data-role=\"skills-catalog-status\"></p>\n\t\t\t\t</div>\n\t\t\t</section>\n\t\t`\n\n\t\twrapper.querySelector<HTMLElement>('[data-role=\"title\"]')!.textContent =\n\t\t\tthis.#config.name?.trim() || 'NoStop'\n\t\tthis.#fillSkillsStudioStatic(wrapper)\n\n\t\tfillBrand(wrapper.querySelector<HTMLElement>('[data-role=\"brand\"]')!)\n\n\t\tdocument.body.appendChild(wrapper)\n\t\treturn wrapper\n\t}\n\n\t#fillSkillsStudioStatic(root: HTMLElement = this.#wrapper): void {\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\troot.querySelector<HTMLElement>('[data-role=\"skills-title\"]')!.textContent =\n\t\t\tt('ui.panel.skillsStudio')\n\t\tconst tabLabels: Record<'record' | 'ask' | 'catalog', string> = {\n\t\t\trecord: t('ui.panel.skillsStudioRecord'),\n\t\t\task: t('ui.panel.skillsStudioAsk'),\n\t\t\tcatalog: t('ui.panel.skillsStudioCatalog'),\n\t\t}\n\t\tfor (const button of root.querySelectorAll<HTMLButtonElement>('[data-role=\"skills-tab\"]')) {\n\t\t\tconst tab = button.dataset.tab as 'record' | 'ask' | 'catalog'\n\t\t\tbutton.textContent = tabLabels[tab]\n\t\t}\n\t\troot.querySelector<HTMLElement>('[data-role=\"skills-record-hint\"]')!.textContent = t(\n\t\t\t'ui.panel.skillsStudioRecordHint'\n\t\t)\n\t\troot.querySelector<HTMLElement>('[data-role=\"skills-ask-hint\"]')!.textContent = t(\n\t\t\t'ui.panel.skillsStudioAskHint'\n\t\t)\n\t\troot.querySelector<HTMLTextAreaElement>('[data-role=\"skills-ask-input\"]')!.placeholder = t(\n\t\t\t'ui.panel.skillsStudioAskPlaceholder'\n\t\t)\n\t\troot.querySelector<HTMLElement>('[data-role=\"skills-catalog-empty\"]')!.textContent = t(\n\t\t\t'ui.panel.skillsStudioEmptyCatalog'\n\t\t)\n\t}\n\n\t#setupEventListeners(): void {\n\t\tconst header = this.#wrapper.querySelector<HTMLElement>(`.${styles.header}`)!\n\t\theader.addEventListener('click', (e) => {\n\t\t\tif ((e.target as HTMLElement).closest('button')) return\n\t\t\tif (this.#useFollowCycle()) this.#cycleFollowMode()\n\t\t\telse this.#setCollapsed(!this.#collapsed)\n\t\t})\n\t\tthis.#collapseButton.addEventListener('click', (e) => {\n\t\t\te.stopPropagation()\n\t\t\tif (this.#useFollowCycle()) this.#cycleFollowMode()\n\t\t\telse this.#setCollapsed(!this.#collapsed)\n\t\t})\n\t\tthis.#stopButton.addEventListener('click', (e) => {\n\t\t\te.stopPropagation()\n\t\t\tthis.#onActionButton()\n\t\t})\n\t\tthis.#followBar\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"follow-bar-body\"]')!\n\t\t\t.addEventListener('click', () => this.#setFollowMode('expanded'))\n\t\tthis.#followBar\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"follow-bar-mute\"]')!\n\t\t\t.addEventListener('click', (e) => {\n\t\t\t\te.stopPropagation()\n\t\t\t\tvoid this.#voice.setMuted(!this.#voice.muted)\n\t\t\t})\n\t\tthis.#followBar\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"follow-bar-action\"]')!\n\t\t\t.addEventListener('click', (e) => {\n\t\t\t\te.stopPropagation()\n\t\t\t\tthis.#onActionButton()\n\t\t\t})\n\t\tthis.#followBar\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"follow-bar-minimize\"]')!\n\t\t\t.addEventListener('click', (e) => {\n\t\t\t\te.stopPropagation()\n\t\t\t\tthis.#setFollowMode('fab')\n\t\t\t})\n\t\tthis.#voiceStage\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"voice-stop\"]')\n\t\t\t?.addEventListener('click', () => this.#onActionButton())\n\t\tthis.#skillsButton.addEventListener('click', (e) => {\n\t\t\te.stopPropagation()\n\t\t\tif (this.#mode === 'skills-studio') this.#leaveSkillsStudio()\n\t\t\telse this.#enterSkillsStudio()\n\t\t})\n\t\tthis.#studioStage\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-back\"]')!\n\t\t\t.addEventListener('click', () => this.#leaveSkillsStudio())\n\t\tfor (const button of this.#studioStage.querySelectorAll<HTMLButtonElement>(\n\t\t\t'[data-role=\"skills-tab\"]'\n\t\t)) {\n\t\t\tbutton.addEventListener('click', () => {\n\t\t\t\tconst tab = button.dataset.tab\n\t\t\t\tif (tab === 'record' || tab === 'ask' || tab === 'catalog') this.#setStudioTab(tab)\n\t\t\t})\n\t\t}\n\t\tif (!this.#studioListenersBound) {\n\t\t\tthis.#studioListenersBound = true\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-record-start\"]')!\n\t\t\t\t.addEventListener('click', () => void this.#onStudioStartRecording())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-record-stop\"]')!\n\t\t\t\t.addEventListener('click', () => this.#onStudioStopRecording())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-record-finish\"]')!\n\t\t\t\t.addEventListener('click', () => this.#onStudioFinishSynthesize())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-record-clear\"]')!\n\t\t\t\t.addEventListener('click', () => this.#onStudioClearRecording())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-record-save\"]')!\n\t\t\t\t.addEventListener('click', () => void this.#onStudioSavePreview())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-record-test\"]')!\n\t\t\t\t.addEventListener('click', () => {\n\t\t\t\t\tif (this.#studioPreviewId) void this.#onStudioTestSkill(this.#studioPreviewId)\n\t\t\t\t})\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-ask-start\"]')!\n\t\t\t\t.addEventListener('click', () => void this.#onStudioAskStart())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLTextAreaElement>('[data-role=\"skills-ask-input\"]')!\n\t\t\t\t.addEventListener('input', () => this.#renderSkillsStudio())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-catalog-refresh\"]')!\n\t\t\t\t.addEventListener('click', () => void this.#onStudioRefreshRemote())\n\t\t\tthis.#studioStage\n\t\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"skills-catalog-remove-agent\"]')!\n\t\t\t\t.addEventListener('click', () => void this.#onStudioRemoveAgentSkills())\n\t\t}\n\t\tthis.#micButton.addEventListener('click', () =>\n\t\t\tthis.#setMode(this.#mode === 'voice' ? 'text' : 'voice')\n\t\t)\n\t\tthis.#voiceStage\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"mute\"]')!\n\t\t\t.addEventListener('click', () => void this.#voice.setMuted(!this.#voice.muted))\n\t\tthis.#voiceStage\n\t\t\t.querySelector<HTMLButtonElement>('[data-role=\"mic-device\"]')!\n\t\t\t.addEventListener('click', () => void this.#voice.changeInput())\n\t\tthis.#wrapper\n\t\t\t.querySelector<HTMLElement>('[data-role=\"back\"]')!\n\t\t\t.addEventListener('click', () => this.#setMode('text'))\n\n\t\tthis.#composer.addEventListener('submit', (e) => {\n\t\t\te.preventDefault()\n\t\t\tthis.#submit()\n\t\t})\n\t\tthis.#textarea.addEventListener('keydown', (e) => {\n\t\t\tif (e.isComposing || e.keyCode === 229) return\n\t\t\tif (e.key === 'Enter' && !e.shiftKey) {\n\t\t\t\te.preventDefault()\n\t\t\t\tthis.#submit()\n\t\t\t}\n\t\t})\n\t\tthis.#textarea.addEventListener('input', () => this.#autoSize())\n\t\tthis.#attachButton?.addEventListener('click', () => this.#attachInput?.click())\n\t\tthis.#attachInput?.addEventListener('change', () => {\n\t\t\tvoid this.#onAttachFiles(this.#attachInput?.files ?? null)\n\t\t})\n\t}\n\n\t/**\n\t * Floating button shown while the panel is closed. Drag it; on release it snaps to the nearest corner.\n\t * A click (without dragging) reopens the panel.\n\t */\n\t#setupFab(): void {\n\t\tconst fab = document.createElement('button')\n\t\tfab.type = 'button'\n\t\tfab.id = 'page-agent-runtime_agent-fab'\n\t\tfab.className = `${styles.fab} ${styles.tip} ${styles.tipUp}`\n\t\tfab.setAttribute('data-browser-use-ignore', 'true')\n\t\tfab.setAttribute('data-page-agent-ignore', 'true')\n\t\tfillBrand(fab)\n\t\tconst tip = this.#i18n.t('ui.panel.open')\n\t\tfab.dataset.tip = tip\n\t\tfab.setAttribute('aria-label', tip)\n\t\tdocument.body.appendChild(fab)\n\t\tthis.#fab = fab\n\n\t\tconst applyCorner = (corner: Corner) => {\n\t\t\tconst [h, v] = corner.split('-')\n\t\t\tfab.style.left = h === 'left' ? `${FAB_MARGIN}px` : 'auto'\n\t\t\tfab.style.right = h === 'right' ? `${FAB_MARGIN}px` : 'auto'\n\t\t\tfab.style.top = v === 'top' ? `${FAB_MARGIN}px` : 'auto'\n\t\t\tfab.style.bottom = v === 'bottom' ? `${FAB_MARGIN}px` : 'auto'\n\t\t\tfab.classList.toggle(styles.fabLeft, h === 'left')\n\t\t}\n\t\tconst saved = (() => {\n\t\t\ttry {\n\t\t\t\treturn localStorage.getItem(FAB_KEY)\n\t\t\t} catch {\n\t\t\t\treturn null\n\t\t\t}\n\t\t})()\n\t\tapplyCorner(CORNERS.includes(saved as Corner) ? (saved as Corner) : 'right-bottom')\n\n\t\tlet origin: { dx: number; dy: number } | null = null\n\t\tlet dragged = false\n\t\tlet longPress = false\n\t\tlet longPressTimer: ReturnType<typeof setTimeout> | undefined\n\t\tconst clearLongPress = () => {\n\t\t\tif (longPressTimer !== undefined) clearTimeout(longPressTimer)\n\t\t\tlongPressTimer = undefined\n\t\t}\n\t\tfab.addEventListener('pointerdown', (event) => {\n\t\t\tif (event.button !== 0) return\n\t\t\tconst rect = fab.getBoundingClientRect()\n\t\t\torigin = { dx: event.clientX - rect.left, dy: event.clientY - rect.top }\n\t\t\tdragged = false\n\t\t\tlongPress = false\n\t\t\tclearLongPress()\n\t\t\tif (this.#useFollowCycle()) {\n\t\t\t\tlongPressTimer = setTimeout(() => {\n\t\t\t\t\tlongPress = true\n\t\t\t\t\tthis.#setFollowMode('bar')\n\t\t\t\t}, 480)\n\t\t\t}\n\t\t\tfab.style.transition = 'none'\n\t\t\tfab.setPointerCapture(event.pointerId)\n\t\t})\n\t\tfab.addEventListener('pointermove', (event) => {\n\t\t\tif (!origin) return\n\t\t\tdragged = true\n\t\t\tclearLongPress()\n\t\t\tconst x = Math.min(\n\t\t\t\tMath.max(0, event.clientX - origin.dx),\n\t\t\t\twindow.innerWidth - fab.offsetWidth\n\t\t\t)\n\t\t\tconst y = Math.min(\n\t\t\t\tMath.max(0, event.clientY - origin.dy),\n\t\t\t\twindow.innerHeight - fab.offsetHeight\n\t\t\t)\n\t\t\tfab.style.left = `${x}px`\n\t\t\tfab.style.top = `${y}px`\n\t\t\tfab.style.right = 'auto'\n\t\t\tfab.style.bottom = 'auto'\n\t\t})\n\t\tconst endDrag = () => {\n\t\t\tclearLongPress()\n\t\t\tif (!origin) return\n\t\t\torigin = null\n\t\t\tfab.style.transition = ''\n\t\t\tif (!dragged) return\n\t\t\tconst rect = fab.getBoundingClientRect()\n\t\t\tconst h = rect.left + rect.width / 2 < window.innerWidth / 2 ? 'left' : 'right'\n\t\t\tconst v = rect.top + rect.height / 2 < window.innerHeight / 2 ? 'top' : 'bottom'\n\t\t\tconst corner: Corner = `${h}-${v}` as Corner\n\t\t\tapplyCorner(corner)\n\t\t\ttry {\n\t\t\t\tlocalStorage.setItem(FAB_KEY, corner)\n\t\t\t} catch {\n\t\t\t\t/* without storage, the corner only lasts for this page */\n\t\t\t}\n\t\t}\n\t\tfab.addEventListener('pointerup', endDrag)\n\t\tfab.addEventListener('pointercancel', endDrag)\n\t\tfab.addEventListener('click', (event) => {\n\t\t\tif (dragged || longPress) {\n\t\t\t\tdragged = false\n\t\t\t\tlongPress = false\n\t\t\t\tevent.preventDefault()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.#setFollowMode('expanded')\n\t\t})\n\t}\n\n\t/**\n\t * Drag by the header, hide the agent cursor and remember the panel position.\n\t * The position is clamped to the viewport and stored in the browser; without storage it lasts only for this page.\n\t */\n\t#setupPlacement(): void {\n\t\tconst header = this.#wrapper.querySelector<HTMLElement>(`.${styles.header}`)!\n\n\t\tconst place = (x: number, y: number) => {\n\t\t\tconst width = this.#wrapper.offsetWidth || 414\n\t\t\tconst height = this.#wrapper.offsetHeight || 0\n\t\t\tconst left = Math.min(Math.max(0, x), Math.max(0, window.innerWidth - width))\n\t\t\tconst top = Math.min(Math.max(0, y), Math.max(0, window.innerHeight - height))\n\t\t\tthis.#wrapper.style.left = `${left}px`\n\t\t\tthis.#wrapper.style.top = `${top}px`\n\t\t\tthis.#wrapper.style.right = 'auto'\n\t\t\tthis.#wrapper.style.bottom = 'auto'\n\t\t\tthis.#wrapper.style.margin = '0'\n\t\t}\n\n\t\ttry {\n\t\t\tconst saved = JSON.parse(localStorage.getItem(DRAG_KEY) ?? 'null')\n\t\t\tif (\n\t\t\t\tsaved &&\n\t\t\t\ttypeof saved.x === 'number' &&\n\t\t\t\ttypeof saved.y === 'number' &&\n\t\t\t\tsaved.x < window.innerWidth - 60 &&\n\t\t\t\tsaved.y < window.innerHeight - 60\n\t\t\t)\n\t\t\t\tplace(saved.x, saved.y)\n\t\t} catch {\n\t\t\t/* default position when storage is unavailable */\n\t\t}\n\n\t\theader.addEventListener('pointerdown', (event) => {\n\t\t\tif (event.button !== 0 || (event.target as HTMLElement).closest('button')) return\n\t\t\tconst rect = this.#wrapper.getBoundingClientRect()\n\t\t\tthis.#dragOrigin = { dx: event.clientX - rect.left, dy: event.clientY - rect.top }\n\t\t\tthis.#dragged = false\n\t\t\t// Disable inherited position transitions so the panel follows the pointer exactly.\n\t\t\tthis.#wrapper.style.transition = 'none'\n\t\t\theader.setPointerCapture(event.pointerId)\n\t\t})\n\t\theader.addEventListener('pointermove', (event) => {\n\t\t\tif (!this.#dragOrigin) return\n\t\t\tthis.#dragged = true\n\t\t\tplace(event.clientX - this.#dragOrigin.dx, event.clientY - this.#dragOrigin.dy)\n\t\t})\n\t\tconst endDrag = () => {\n\t\t\tif (!this.#dragOrigin) return\n\t\t\tthis.#dragOrigin = null\n\t\t\tthis.#wrapper.style.transition = ''\n\t\t\tconst rect = this.#wrapper.getBoundingClientRect()\n\t\t\ttry {\n\t\t\t\tlocalStorage.setItem(DRAG_KEY, JSON.stringify({ x: rect.left, y: rect.top }))\n\t\t\t} catch {\n\t\t\t\t/* without storage, the position only lasts for this page */\n\t\t\t}\n\t\t}\n\t\theader.addEventListener('pointerup', endDrag)\n\t\theader.addEventListener('pointercancel', endDrag)\n\t\t// A drag ends with a click on the header; that click must not collapse or expand the feed.\n\t\theader.addEventListener(\n\t\t\t'click',\n\t\t\t(event) => {\n\t\t\t\tif (!this.#dragged) return\n\t\t\t\tthis.#dragged = false\n\t\t\t\tevent.stopPropagation()\n\t\t\t\tevent.preventDefault()\n\t\t\t},\n\t\t\ttrue\n\t\t)\n\n\t\tconst t = this.#i18n.t.bind(this.#i18n)\n\t\tconst setCursorHidden = (hidden: boolean) => {\n\t\t\tdocument.documentElement.toggleAttribute(CURSOR_ATTR, hidden)\n\t\t\t// Pressed means the agent cursor is visible.\n\t\t\tthis.#cursorButton.setAttribute('aria-pressed', String(!hidden))\n\t\t\tsetButton(\n\t\t\t\tthis.#cursorButton,\n\t\t\t\thidden ? 'cursorOff' : 'cursor',\n\t\t\t\tt(hidden ? 'ui.panel.showCursor' : 'ui.panel.hideCursor')\n\t\t\t)\n\t\t}\n\t\tsetCursorHidden(false)\n\t\tthis.#cursorButton.addEventListener('click', (event) => {\n\t\t\tevent.stopPropagation()\n\t\t\tsetCursorHidden(!document.documentElement.hasAttribute(CURSOR_ATTR))\n\t\t})\n\t}\n}\n","/**\n * Copyright (C) 2025 Alibaba Group Holding Limited\n * All rights reserved.\n */\nimport { type AgentConfig, PageAgentCore } from '@page-agent/core'\nimport { PageController, type PageControllerConfig } from '@page-agent/page-controller'\nimport { Panel, type PanelConfig } from '@page-agent/ui'\n\nexport * from '@page-agent/core'\nexport {\n\ttype AccessibilityConfig,\n\ttype AccessibilityController,\n\tAxError,\n\ttype AxErrorCode,\n} from '@page-agent/page-controller'\n\nexport type PageAgentConfig = AgentConfig & PageControllerConfig & Omit<PanelConfig, 'language'>\n\nexport class PageAgent extends PageAgentCore {\n\tpanel: Panel\n\n\tconstructor(config: PageAgentConfig) {\n\t\tconst pageController = new PageController({\n\t\t\t...config,\n\t\t\tenableMask: config.enableMask ?? true,\n\t\t})\n\n\t\tsuper({ ...config, pageController })\n\n\t\tpageController.isBusy = () => this.status === 'running'\n\n\t\tthis.panel = new Panel(this, {\n\t\t\tlanguage: config.language,\n\t\t\tsessionRecovery: config.sessionRecovery,\n\t\t\tsessionRecoveryKey: config.sessionRecoveryKey,\n\t\t\tpromptForNextTask: config.promptForNextTask,\n\t\t\tname: config.name,\n\t\t\tvoice: config.voice,\n\t\t\trunScript: (script) => this.#runScript(script),\n\t\t\tgetContext: (args) => this.#getContext(args),\n\t\t})\n\t}\n\n\t/** Runs a script in the page with this agent in scope, through the same tool the executor uses. */\n\t#runScript(script: string): Promise<string> {\n\t\tconst tool = this.tools.get('execute_javascript')\n\t\tif (!tool) return Promise.resolve('execute_javascript is not available in this session.')\n\t\tconst controller = new AbortController()\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined\n\t\tconst limit = new Promise<string>((resolve) => {\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\tcontroller.abort()\n\t\t\t\tresolve('The script took longer than 20 seconds, so the voice stopped waiting for it.')\n\t\t\t}, 20_000)\n\t\t})\n\t\tconst run = tool.execute.call(this, { script }, { signal: controller.signal })\n\t\treturn Promise.race([run, limit]).finally(() => clearTimeout(timer))\n\t}\n\n\t/** Read-only context slice for the voice tool (does not rebind agent indexes). */\n\tasync #getContext(args: {\n\t\tyMin?: number\n\t\tyMax?: number\n\t\tmaxLines?: number\n\t\tquery?: string\n\t}): Promise<string> {\n\t\tconst result = await this.pageController.getContext({\n\t\t\tyMin: args.yMin,\n\t\t\tyMax: args.yMax,\n\t\t\tmaxLines: args.maxLines ?? 60,\n\t\t\tquery: args.query,\n\t\t\tbindIndexes: false,\n\t\t})\n\t\treturn result.message\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAIA,IAAa,mBAAmB;CAE/B,eAAe;CACf,YAAY;CACZ,cAAc;CACd,cAAc;CACd,mBAAmB;CACnB,sBAAsB;CACtB,kBAAkB;CAClB,gBAAgB;CAEhB,SAAS;CAGT,cAAc;CACd,YAAY;CACZ,gBAAgB;CAChB,gBAAgB;AACjB;AAIA,IAAM,kBAA8C;CACnD,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;CACjB,iBAAiB;AAClB;AAEA,IAAa,cAAb,cAAiC,MAAM;CACtC;CACA;CACA;CAEA;CAEA;CAEA,YAAY,MAAuB,SAAiB,UAAoB,aAAuB;EAC9F,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,YAAY,gBAAgB,SAAS,IAAI;EAC9C,KAAK,WAAW;EAChB,KAAK,cAAc;CACpB;AACD;;;;;;AC/CA,SAAS,MAAM,GAAG,MAAiB;CAClC,QAAQ,MAAM,MAAM,KAAK,OAAO,GAAG,GAAG,IAAI;AAC3C;;;;;AAMA,SAAgB,gBAAgB,MAAc,MAAY;CACzD,OAAO;EACN,MAAM;EACN,UAAU;GACT;GACA,aAAa,KAAK;GAClB,YAAY,EAAE,aAAa,KAA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