page-agent 0.0.7 → 0.0.9

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.
@@ -1,38 +1,26 @@
1
- (function() {
2
- "use strict";
3
- try {
4
- if (typeof document != "undefined") {
5
- var elementStyle = document.createElement("style");
6
- elementStyle.appendChild(document.createTextNode("._wrapper_1j0ct_1 {\n position: fixed;\n bottom: 100px;\n left: 50%;\n transform: translateX(-50%) translateY(20px);\n opacity: 0;\n z-index: 2147483642; /* 比 SimulatorMask 高一层 */\n box-sizing: border-box;\n\n overflow: visible;\n\n * {\n box-sizing: border-box;\n }\n\n --width: 360px;\n --height: 40px;\n --border-radius: 12px;\n\n --side-space: 12px; /* 控制栏两侧的间距 */\n --history-width: calc(var(--width) - var(--side-space) * 2);\n\n --color-1: rgb(57, 182, 255);\n --color-2: rgb(189, 69, 251);\n --color-3: rgb(255, 87, 51);\n --color-4: rgb(255, 214, 0);\n\n width: var(--width);\n height: var(--height);\n\n transition: all 0.3s ease-in-out;\n\n /* 响应式设计 */\n @media (max-width: 480px) {\n width: calc(100vw - 40px);\n --width: calc(100vw - 40px);\n }\n\n ._background_1j0ct_39 {\n position: absolute;\n inset: -2px -8px;\n border-radius: calc(var(--border-radius) + 4px);\n filter: blur(16px);\n overflow: hidden;\n /* mix-blend-mode: lighten; */\n /* display: none; */\n\n &::before {\n content: '';\n z-index: -1;\n pointer-events: none;\n position: absolute;\n width: 100%;\n height: 100%;\n /* left: -100%; */\n left: 0;\n top: 0;\n\n background-image: linear-gradient(\n to bottom left,\n var(--color-1),\n var(--color-2),\n var(--color-1)\n );\n animation: _mask-running_1j0ct_1 2s linear infinite;\n }\n &::after {\n content: '';\n z-index: -1;\n pointer-events: none;\n position: absolute;\n width: 100%;\n height: 100%;\n left: 0;\n top: 0;\n\n background-image: linear-gradient(\n to bottom left,\n var(--color-2),\n var(--color-1),\n var(--color-2)\n );\n animation: _mask-running_1j0ct_1 2s linear infinite;\n animation-delay: 1s;\n }\n }\n}\n\n@keyframes _mask-running_1j0ct_1 {\n from {\n transform: translateX(-100%);\n }\n to {\n transform: translateX(100%);\n }\n}\n\n/* 控制栏 */\n._header_1j0ct_99 {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 8px 12px;\n user-select: none;\n\n position: absolute;\n inset: 0;\n\n cursor: pointer;\n flex-shrink: 0; /* 防止 header 被压缩 */\n\n background: rgba(0, 0, 0, 0.5);\n backdrop-filter: blur(10px);\n border-radius: var(--border-radius);\n background-clip: padding-box;\n\n box-shadow:\n 0 0 0px 2px rgba(255, 255, 255, 0.4),\n 0 0 5px 1px rgba(255, 255, 255, 0.3);\n\n ._statusSection_1j0ct_121 {\n display: flex;\n align-items: center;\n gap: 8px;\n flex: 1;\n min-height: 24px; /* 确保垂直居中 */\n\n ._indicator_1j0ct_128 {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: rgba(255, 255, 255, 0.5);\n flex-shrink: 0;\n animation: none; /* 默认无动画 */\n\n /* 运行状态 - 有动画 */\n &._thinking_1j0ct_137 {\n background: rgb(57, 182, 255);\n animation: _pulse_1j0ct_1 0.8s ease-in-out infinite;\n }\n\n &._tool_executing_1j0ct_142 {\n background: rgb(189, 69, 251);\n animation: _pulse_1j0ct_1 0.6s ease-in-out infinite;\n }\n\n &._retry_1j0ct_147 {\n background: rgb(255, 214, 0);\n animation: _retryPulse_1j0ct_1 1s ease-in-out infinite;\n }\n\n /* 静止状态 - 无动画 */\n &._completed_1j0ct_153,\n &._input_1j0ct_154,\n &._output_1j0ct_155 {\n background: rgb(34, 197, 94);\n animation: none;\n }\n\n &._error_1j0ct_160 {\n background: rgb(239, 68, 68);\n animation: none;\n }\n }\n\n ._statusText_1j0ct_166 {\n color: white;\n font-size: 12px;\n line-height: 1;\n font-weight: 500;\n transition: all 0.3s ease-in-out;\n position: relative;\n overflow: hidden;\n display: flex;\n align-items: center;\n min-height: 24px; /* 确保垂直居中 */\n\n &._fadeOut_1j0ct_178 {\n animation: _statusTextFadeOut_1j0ct_1 0.3s ease forwards;\n }\n\n &._fadeIn_1j0ct_182 {\n animation: _statusTextFadeIn_1j0ct_1 0.3s ease forwards;\n }\n }\n }\n\n ._controls_1j0ct_188 {\n display: flex;\n align-items: center;\n gap: 4px;\n\n ._controlButton_1j0ct_193 {\n width: 24px;\n height: 24px;\n border: none;\n border-radius: 4px;\n background: rgba(255, 255, 255, 0.1);\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 12px;\n line-height: 1;\n\n &:hover {\n background: rgba(255, 255, 255, 0.2);\n }\n }\n\n ._pauseButton_1j0ct_212 {\n font-weight: 600;\n &._paused_1j0ct_214 {\n background: rgba(34, 197, 94, 0.2); /* 绿色背景表示可以继续 */\n color: rgb(34, 197, 94);\n\n &:hover {\n background: rgba(34, 197, 94, 0.3);\n }\n }\n }\n\n ._stopButton_1j0ct_224 {\n background: rgba(239, 68, 68, 0.2);\n color: rgb(255, 41, 41);\n font-weight: 600;\n\n &:hover {\n background: rgba(239, 68, 68, 0.3);\n }\n }\n }\n}\n\n@keyframes _statusTextFadeIn_1j0ct_1 {\n 0% {\n opacity: 0;\n transform: translateY(5px);\n }\n 100% {\n opacity: 1;\n transform: translateY(0);\n }\n}\n\n@keyframes _statusTextFadeOut_1j0ct_1 {\n 0% {\n opacity: 1;\n transform: translateY(0);\n }\n 100% {\n opacity: 0;\n transform: translateY(-5px);\n }\n}\n\n._historySectionWrapper_1j0ct_258 {\n position: absolute;\n width: var(--history-width);\n bottom: var(--height);\n left: var(--side-space);\n z-index: -2;\n\n padding-top: 0px;\n visibility: collapse;\n overflow: hidden;\n\n transition: all 0.2s;\n\n background: rgba(2, 0, 20, 0.5);\n /* background: rgba(186, 186, 186, 0.2); */\n backdrop-filter: blur(10px);\n\n text-shadow: 0 0 1px rgba(0, 0, 0, 0.2);\n\n border-top-left-radius: calc(var(--border-radius) + 4px);\n border-top-right-radius: calc(var(--border-radius) + 4px);\n\n /* border: 2px solid rgba(255, 255, 255, 0.8); */\n border: 2px solid rgba(255, 255, 255, 0.4);\n box-shadow: 0 4px 16px rgba(0, 0, 0, 0.6);\n\n /* @media (prefers-color-scheme: dark) {\n box-shadow:\n 0 8px 32px 0 rgba(0, 0, 0, 0.85),\n 0 2px 12px 0 rgba(57, 182, 255, 0.1);\n } */\n\n ._expanded_1j0ct_290 & {\n padding-top: 8px;\n visibility: visible;\n }\n\n ._historySection_1j0ct_258 {\n position: relative;\n overflow-y: auto;\n overscroll-behavior: contain;\n scrollbar-width: none;\n max-height: 0;\n padding-inline: 8px;\n\n transition: max-height 0.2s;\n\n ._expanded_1j0ct_290 & {\n max-height: 400px;\n }\n\n ._historyItem_1j0ct_309 {\n /* backdrop-filter: blur(10px); */\n padding: 8px 10px;\n margin-bottom: 6px;\n background: linear-gradient(135deg, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0.03));\n border-radius: 8px;\n border-left: 2px solid rgba(57, 182, 255, 0.5);\n font-size: 12px;\n color: white;\n /* color: black; */\n line-height: 1.3;\n position: relative;\n overflow: hidden;\n\n /* 微妙的内阴影 */\n box-shadow:\n inset 0 1px 0 rgba(255, 255, 255, 0.1),\n 0 1px 3px rgba(0, 0, 0, 0.1);\n\n &::before {\n content: '';\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n height: 1px;\n background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);\n }\n\n &:hover {\n background: linear-gradient(135deg, rgba(255, 255, 255, 0.12), rgba(255, 255, 255, 0.06));\n /* transform: translateY(-1px); */\n box-shadow:\n inset 0 1px 0 rgba(255, 255, 255, 0.15),\n 0 2px 4px rgba(0, 0, 0, 0.15);\n }\n\n &:last-child {\n margin-bottom: 10px;\n }\n\n &._completed_1j0ct_153,\n &._input_1j0ct_154,\n &._output_1j0ct_155 {\n border-left-color: rgb(34, 197, 94);\n background: linear-gradient(135deg, rgba(34, 197, 94, 0.1), rgba(34, 197, 94, 0.05));\n }\n\n &._error_1j0ct_160 {\n border-left-color: rgb(239, 68, 68);\n background: linear-gradient(135deg, rgba(239, 68, 68, 0.1), rgba(239, 68, 68, 0.05));\n }\n\n &._retry_1j0ct_147 {\n border-left-color: rgb(255, 214, 0);\n background: linear-gradient(135deg, rgba(255, 214, 0, 0.1), rgba(255, 214, 0, 0.05));\n }\n\n /* 突出显示 done 成功结果 */\n &._doneSuccess_1j0ct_368 {\n background: linear-gradient(\n 135deg,\n rgba(34, 197, 94, 0.25),\n rgba(34, 197, 94, 0.15),\n rgba(34, 197, 94, 0.08)\n );\n border: none;\n border-left: 4px solid rgb(34, 197, 94);\n box-shadow:\n 0 4px 12px rgba(34, 197, 94, 0.3),\n inset 0 1px 0 rgba(255, 255, 255, 0.2),\n 0 0 20px rgba(34, 197, 94, 0.1);\n font-weight: 600;\n color: rgb(220, 252, 231);\n padding: 10px 12px;\n margin-bottom: 8px;\n border-radius: 8px;\n position: relative;\n overflow: hidden;\n\n &::before {\n background: linear-gradient(90deg, transparent, rgba(34, 197, 94, 0.4), transparent);\n }\n\n &::after {\n content: '';\n position: absolute;\n top: 0;\n left: -100%;\n width: 100%;\n height: 100%;\n background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);\n animation: _shimmer_1j0ct_1 2s ease-in-out infinite;\n }\n\n ._historyContent_1j0ct_404 {\n ._statusIcon_1j0ct_405 {\n font-size: 16px;\n animation: _celebrate_1j0ct_1 0.8s ease-in-out;\n filter: drop-shadow(0 2px 4px rgba(34, 197, 94, 0.5));\n }\n }\n }\n\n /* 突出显示 done 失败结果 */\n &._doneError_1j0ct_414 {\n background: linear-gradient(\n 135deg,\n rgba(239, 68, 68, 0.25),\n rgba(239, 68, 68, 0.15),\n rgba(239, 68, 68, 0.08)\n );\n border: none;\n border-left: 4px solid rgb(239, 68, 68);\n box-shadow:\n 0 4px 12px rgba(239, 68, 68, 0.3),\n inset 0 1px 0 rgba(255, 255, 255, 0.2),\n 0 0 20px rgba(239, 68, 68, 0.1);\n font-weight: 600;\n color: rgb(254, 226, 226);\n padding: 10px 12px;\n margin-bottom: 8px;\n border-radius: 8px;\n position: relative;\n overflow: hidden;\n\n &::before {\n background: linear-gradient(90deg, transparent, rgba(239, 68, 68, 0.4), transparent);\n }\n\n ._historyContent_1j0ct_404 {\n ._statusIcon_1j0ct_405 {\n font-size: 16px;\n filter: drop-shadow(0 2px 4px rgba(239, 68, 68, 0.5));\n }\n }\n }\n\n ._historyContent_1j0ct_404 {\n display: flex;\n align-items: center;\n gap: 8px;\n\n word-break: break-all;\n white-space: pre-wrap;\n\n /* overflow-x: auto; */\n\n ._statusIcon_1j0ct_405 {\n font-size: 12px;\n flex-shrink: 0;\n line-height: 1;\n transition: all 0.3s ease;\n }\n }\n\n ._historyMeta_1j0ct_465 {\n font-size: 10px;\n color: rgba(255, 255, 255, 0.6);\n /* color: rgb(61, 61, 61); */\n margin-top: 8px;\n line-height: 1;\n }\n }\n }\n}\n\n/* 动画关键帧 - 更快的闪烁 */\n@keyframes _pulse_1j0ct_1 {\n 0%,\n 100% {\n opacity: 1;\n transform: scale(1);\n }\n 50% {\n opacity: 0.4;\n transform: scale(1.3);\n }\n}\n\n/* 重试动画 - 旋转脉冲 */\n@keyframes _retryPulse_1j0ct_1 {\n 0%,\n 100% {\n opacity: 1;\n transform: scale(1) rotate(0deg);\n }\n 25% {\n opacity: 0.6;\n transform: scale(1.2) rotate(90deg);\n }\n 50% {\n opacity: 0.8;\n transform: scale(1.1) rotate(180deg);\n }\n 75% {\n opacity: 0.6;\n transform: scale(1.2) rotate(270deg);\n }\n}\n\n/* 庆祝动画 */\n@keyframes _celebrate_1j0ct_1 {\n 0%,\n 100% {\n transform: scale(1);\n }\n 25% {\n transform: scale(1.2) rotate(-5deg);\n }\n 75% {\n transform: scale(1.2) rotate(5deg);\n }\n}\n\n/* done 卡片的光泽效果 */\n@keyframes _shimmer_1j0ct_1 {\n 0% {\n left: -100%;\n }\n 100% {\n left: 100%;\n }\n}\n\n/* 输入区域样式 */\n._inputSectionWrapper_1j0ct_535 {\n position: absolute;\n width: var(--history-width);\n top: var(--height);\n left: var(--side-space);\n z-index: -1;\n\n visibility: visible;\n overflow: hidden;\n\n height: 48px;\n\n transition: all 0.2s;\n\n background: rgba(186, 186, 186, 0.2);\n backdrop-filter: blur(10px);\n\n border-bottom-left-radius: calc(var(--border-radius) + 4px);\n border-bottom-right-radius: calc(var(--border-radius) + 4px);\n\n border: 2px solid rgba(255, 255, 255, 0.3);\n box-shadow: 0 1px 16px rgba(0, 0, 0, 0.4);\n\n &._hidden_1j0ct_558 {\n visibility: collapse;\n height: 0;\n }\n\n ._inputSection_1j0ct_535 {\n display: flex;\n align-items: center;\n gap: 4px;\n padding: 8px 8px;\n\n ._taskInput_1j0ct_569 {\n flex: 1;\n background: rgba(255, 255, 255, 0.4);\n border: 1px solid rgba(255, 255, 255, 0.3);\n border-radius: 10px;\n padding-inline: 10px;\n color: rgb(20, 20, 20);\n font-size: 12px;\n height: 28px;\n line-height: 1;\n outline: none;\n transition: all 0.2s ease;\n\n /* text-shadow: 0 0 2px rgba(255, 255, 255, 0.8); */\n\n /* border-color: rgba(57, 182, 255, 0.3); */\n\n &::placeholder {\n color: rgb(53, 53, 53);\n }\n\n &:focus {\n background: rgba(255, 255, 255, 0.8);\n border-color: rgba(57, 182, 255, 0.6);\n box-shadow: 0 0 0 2px rgba(57, 182, 255, 0.2);\n }\n }\n }\n}\n._wrapper_1oy2s_1 {\n position: fixed;\n inset: 0;\n z-index: 2147483641; /* 确保在所有元素之上,除了 panel */\n /* pointer-events: none; */\n cursor: not-allowed;\n overflow: hidden;\n\n display: none;\n}\n/* AI 光标样式 */\n._cursor_1vrf3_2 {\n position: absolute;\n width: var(--cursor-size, 75px);\n height: var(--cursor-size, 75px);\n pointer-events: none;\n z-index: 10000;\n transform: translate(-30%, -30%);\n\n animation: _cursor-enter_1vrf3_1 300ms ease-out forwards;\n}\n\n._cursorBorder_1vrf3_13 {\n position: absolute;\n inset: 0;\n background: linear-gradient(45deg, rgb(57, 182, 255), rgb(189, 69, 251));\n mask-image: url(https://img.alicdn.com/imgextra/i1/O1CN01YHLVYR1LvqWIyo5kH_!!6000000001362-2-tps-202-202.png);\n mask-size: 100% 100%;\n mask-repeat: no-repeat;\n animation: _cursor-breathe_1vrf3_1 2s ease-in-out infinite;\n}\n\n._cursorFilling_1vrf3_23 {\n position: absolute;\n inset: 0;\n background: url(https://img.alicdn.com/imgextra/i3/O1CN01JZOqOS1Tu1sIKbPLW_!!6000000002441-2-tps-202-202.png);\n background-size: 100% 100%;\n background-repeat: no-repeat;\n}\n\n._cursorRipple_1vrf3_31 {\n position: absolute;\n inset: 0;\n pointer-events: none;\n}\n\n._cursor_1vrf3_2._clicking_1vrf3_37 ._cursorRipple_1vrf3_31::after {\n content: '';\n position: absolute;\n width: 100%;\n height: 100%;\n left: -30%;\n top: -30%;\n border: 4px solid rgba(57, 182, 255, 1);\n border-radius: 50%;\n animation: _cursor-ripple_1vrf3_1 300ms ease-out forwards;\n}\n\n/* 光标动画关键帧 */\n@keyframes _cursor-breathe_1vrf3_1 {\n 0%,\n 100% {\n transform: scale(1);\n opacity: 0.9;\n }\n 50% {\n transform: scale(1.05);\n opacity: 1;\n }\n}\n\n@keyframes _cursor-rotate_1vrf3_1 {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n}\n\n@keyframes _cursor-enter_1vrf3_1 {\n 0% {\n transform: translate(-30%, -30%) scale(0.5);\n opacity: 0;\n }\n 100% {\n transform: translate(-30%, -30%) scale(1);\n opacity: 1;\n }\n}\n\n@keyframes _cursor-ripple_1vrf3_1 {\n 0% {\n transform: scale(0);\n opacity: 1;\n }\n 100% {\n transform: scale(2);\n opacity: 0;\n }\n}"));
7
- document.head.appendChild(elementStyle);
8
- }
9
- } catch (e) {
10
- console.error("vite-plugin-css-injected-by-js", e);
11
- }
12
- })();
13
1
  var __defProp2 = Object.defineProperty;
14
- var __typeError = (msg) => {
2
+ var __typeError2 = (msg) => {
15
3
  throw TypeError(msg);
16
4
  };
17
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
18
6
  var __name2 = (target, value) => __defProp2(target, "name", { value, configurable: true });
19
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
20
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
21
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
22
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
23
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
24
- var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
25
- var __PageController, _bus, _wrapper, _indicator, _statusText, _historySection, _expandButton, _pauseButton, _stopButton, _inputSection, _taskInput, _bus2, _state, _isExpanded, _pageAgent, _userAnswerResolver, _isWaitingForUserAnswer, _headerUpdateTimer, _pendingHeaderText, _isAnimating, _Panel_instances, update_fn, show_fn, hide_fn, reset_fn, togglePause_fn, updatePauseButton_fn, stopAgent_fn, submitTask_fn, handleUserAnswer_fn, showInputArea_fn, hideInputArea_fn, shouldShowInputArea_fn, createWrapper_fn, setupEventListeners_fn, toggle_fn, expand_fn, collapse_fn, startHeaderUpdateLoop_fn, stopHeaderUpdateLoop_fn, checkAndUpdateHeader_fn, animateTextChange_fn, updateStatusIndicator_fn, updateHistory_fn, scrollToBottom_fn, createHistoryItem_fn, _cursor, _currentCursorX, _currentCursorY, _targetCursorX, _targetCursorY, _SimulatorMask_instances, createCursor_fn, moveCursorToTarget_fn, _llm, _totalWaitTime, _abortController, _PageAgent_instances, packMacroTool_fn, getSystemPrompt_fn, assembleUserPrompt_fn, onDone_fn, getBrowserState_fn;
7
+ var __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
8
+ var __accessCheck2 = (obj, member, msg) => member.has(obj) || __typeError2("Cannot " + msg);
9
+ var __privateGet2 = (obj, member, getter) => (__accessCheck2(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
10
+ var __privateAdd2 = (obj, member, value) => member.has(obj) ? __typeError2("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
11
+ var __privateSet2 = (obj, member, value, setter) => (__accessCheck2(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
12
+ var __privateMethod2 = (obj, member, method) => (__accessCheck2(obj, member, "access private method"), method);
13
+ var __PageController, _b, _c, _d, _e, _llm, _totalWaitTime, _abortController, _llmRetryListener, _llmErrorListener, _beforeUnloadListener, _PageAgent_instances, packMacroTool_fn, getSystemPrompt_fn, assembleUserPrompt_fn, onDone_fn, getBrowserState_fn;
14
+ import { Motion } from "ai-motion";
26
15
  import chalk from "chalk";
27
16
  import zod, { z } from "zod";
28
- import { Motion } from "ai-motion";
29
- var __defProp = Object.defineProperty;
30
- var __name = /* @__PURE__ */ __name2((target, value) => __defProp(target, "name", { value, configurable: true }), "__name");
17
+ var __defProp$1 = Object.defineProperty;
18
+ var __name$1 = /* @__PURE__ */ __name2((target, value) => __defProp$1(target, "name", { value, configurable: true }), "__name$1");
31
19
  async function waitFor$1(seconds) {
32
20
  await new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
33
21
  }
34
22
  __name2(waitFor$1, "waitFor$1");
35
- __name(waitFor$1, "waitFor");
23
+ __name$1(waitFor$1, "waitFor");
36
24
  async function movePointerToElement(element) {
37
25
  const rect = element.getBoundingClientRect();
38
26
  const x = rect.left + rect.width / 2;
@@ -41,7 +29,7 @@ async function movePointerToElement(element) {
41
29
  await waitFor$1(0.3);
42
30
  }
43
31
  __name2(movePointerToElement, "movePointerToElement");
44
- __name(movePointerToElement, "movePointerToElement");
32
+ __name$1(movePointerToElement, "movePointerToElement");
45
33
  function getElementByIndex(selectorMap, index) {
46
34
  const interactiveNode = selectorMap.get(index);
47
35
  if (!interactiveNode) {
@@ -57,7 +45,7 @@ function getElementByIndex(selectorMap, index) {
57
45
  return element;
58
46
  }
59
47
  __name2(getElementByIndex, "getElementByIndex");
60
- __name(getElementByIndex, "getElementByIndex");
48
+ __name$1(getElementByIndex, "getElementByIndex");
61
49
  let lastClickedElement = null;
62
50
  function blurLastClickedElement() {
63
51
  if (lastClickedElement) {
@@ -69,7 +57,7 @@ function blurLastClickedElement() {
69
57
  }
70
58
  }
71
59
  __name2(blurLastClickedElement, "blurLastClickedElement");
72
- __name(blurLastClickedElement, "blurLastClickedElement");
60
+ __name$1(blurLastClickedElement, "blurLastClickedElement");
73
61
  async function clickElement(element) {
74
62
  blurLastClickedElement();
75
63
  lastClickedElement = element;
@@ -86,7 +74,7 @@ async function clickElement(element) {
86
74
  await waitFor$1(0.1);
87
75
  }
88
76
  __name2(clickElement, "clickElement");
89
- __name(clickElement, "clickElement");
77
+ __name$1(clickElement, "clickElement");
90
78
  const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
91
79
  window.HTMLInputElement.prototype,
92
80
  "value"
@@ -111,7 +99,7 @@ async function inputTextElement(element, text) {
111
99
  blurLastClickedElement();
112
100
  }
113
101
  __name2(inputTextElement, "inputTextElement");
114
- __name(inputTextElement, "inputTextElement");
102
+ __name$1(inputTextElement, "inputTextElement");
115
103
  async function selectOptionElement(selectElement, optionText) {
116
104
  if (!(selectElement instanceof HTMLSelectElement)) {
117
105
  throw new Error("Element is not a select element");
@@ -126,7 +114,7 @@ async function selectOptionElement(selectElement, optionText) {
126
114
  await waitFor$1(0.1);
127
115
  }
128
116
  __name2(selectOptionElement, "selectOptionElement");
129
- __name(selectOptionElement, "selectOptionElement");
117
+ __name$1(selectOptionElement, "selectOptionElement");
130
118
  async function scrollIntoViewIfNeeded(element) {
131
119
  const el = element;
132
120
  if (el.scrollIntoViewIfNeeded) {
@@ -136,7 +124,7 @@ async function scrollIntoViewIfNeeded(element) {
136
124
  }
137
125
  }
138
126
  __name2(scrollIntoViewIfNeeded, "scrollIntoViewIfNeeded");
139
- __name(scrollIntoViewIfNeeded, "scrollIntoViewIfNeeded");
127
+ __name$1(scrollIntoViewIfNeeded, "scrollIntoViewIfNeeded");
140
128
  async function scrollVertically(down, scroll_amount, element) {
141
129
  if (element) {
142
130
  const targetElement = element;
@@ -214,8 +202,8 @@ async function scrollVertically(down, scroll_amount, element) {
214
202
  }
215
203
  }
216
204
  const dy = scroll_amount;
217
- const bigEnough = /* @__PURE__ */ __name((el2) => el2.clientHeight >= window.innerHeight * 0.5, "bigEnough");
218
- const canScroll = /* @__PURE__ */ __name((el2) => el2 && /(auto|scroll|overlay)/.test(getComputedStyle(el2).overflowY) && el2.scrollHeight > el2.clientHeight && bigEnough(el2), "canScroll");
205
+ const bigEnough = /* @__PURE__ */ __name$1((el2) => el2.clientHeight >= window.innerHeight * 0.5, "bigEnough");
206
+ const canScroll = /* @__PURE__ */ __name$1((el2) => el2 && /(auto|scroll|overlay)/.test(getComputedStyle(el2).overflowY) && el2.scrollHeight > el2.clientHeight && bigEnough(el2), "canScroll");
219
207
  let el = document.activeElement;
220
208
  while (el && !canScroll(el) && el !== document.body) el = el.parentElement;
221
209
  el = canScroll(el) ? el : Array.from(document.querySelectorAll("*")).find(canScroll) || document.scrollingElement || document.documentElement;
@@ -229,7 +217,7 @@ async function scrollVertically(down, scroll_amount, element) {
229
217
  }
230
218
  }
231
219
  __name2(scrollVertically, "scrollVertically");
232
- __name(scrollVertically, "scrollVertically");
220
+ __name$1(scrollVertically, "scrollVertically");
233
221
  async function scrollHorizontally(right, scroll_amount, element) {
234
222
  if (element) {
235
223
  const targetElement = element;
@@ -307,8 +295,8 @@ async function scrollHorizontally(right, scroll_amount, element) {
307
295
  }
308
296
  }
309
297
  const dx = right ? scroll_amount : -scroll_amount;
310
- const bigEnough = /* @__PURE__ */ __name((el2) => el2.clientWidth >= window.innerWidth * 0.5, "bigEnough");
311
- const canScroll = /* @__PURE__ */ __name((el2) => el2 && /(auto|scroll|overlay)/.test(getComputedStyle(el2).overflowX) && el2.scrollWidth > el2.clientWidth && bigEnough(el2), "canScroll");
298
+ const bigEnough = /* @__PURE__ */ __name$1((el2) => el2.clientWidth >= window.innerWidth * 0.5, "bigEnough");
299
+ const canScroll = /* @__PURE__ */ __name$1((el2) => el2 && /(auto|scroll|overlay)/.test(getComputedStyle(el2).overflowX) && el2.scrollWidth > el2.clientWidth && bigEnough(el2), "canScroll");
312
300
  let el = document.activeElement;
313
301
  while (el && !canScroll(el) && el !== document.body) el = el.parentElement;
314
302
  el = canScroll(el) ? el : Array.from(document.querySelectorAll("*")).find(canScroll) || document.scrollingElement || document.documentElement;
@@ -322,9 +310,9 @@ async function scrollHorizontally(right, scroll_amount, element) {
322
310
  }
323
311
  }
324
312
  __name2(scrollHorizontally, "scrollHorizontally");
325
- __name(scrollHorizontally, "scrollHorizontally");
313
+ __name$1(scrollHorizontally, "scrollHorizontally");
326
314
  const VIEWPORT_EXPANSION = -1;
327
- const domTree = /* @__PURE__ */ __name((args = {
315
+ const domTree = /* @__PURE__ */ __name$1((args = {
328
316
  doHighlightElements: true,
329
317
  focusHighlightIndex: -1,
330
318
  viewportExpansion: 0,
@@ -348,12 +336,12 @@ const domTree = /* @__PURE__ */ __name((args = {
348
336
  extraData.set(element, { ...extraData.get(element), ...data });
349
337
  }
350
338
  __name2(addExtraData, "addExtraData");
351
- __name(addExtraData, "addExtraData");
339
+ __name$1(addExtraData, "addExtraData");
352
340
  const DOM_CACHE = {
353
341
  boundingRects: /* @__PURE__ */ new WeakMap(),
354
342
  clientRects: /* @__PURE__ */ new WeakMap(),
355
343
  computedStyles: /* @__PURE__ */ new WeakMap(),
356
- clearCache: /* @__PURE__ */ __name(() => {
344
+ clearCache: /* @__PURE__ */ __name$1(() => {
357
345
  DOM_CACHE.boundingRects = /* @__PURE__ */ new WeakMap();
358
346
  DOM_CACHE.clientRects = /* @__PURE__ */ new WeakMap();
359
347
  DOM_CACHE.computedStyles = /* @__PURE__ */ new WeakMap();
@@ -371,7 +359,7 @@ const domTree = /* @__PURE__ */ __name((args = {
371
359
  return rect;
372
360
  }
373
361
  __name2(getCachedBoundingRect, "getCachedBoundingRect");
374
- __name(getCachedBoundingRect, "getCachedBoundingRect");
362
+ __name$1(getCachedBoundingRect, "getCachedBoundingRect");
375
363
  function getCachedComputedStyle(element) {
376
364
  if (!element) return null;
377
365
  if (DOM_CACHE.computedStyles.has(element)) {
@@ -384,7 +372,7 @@ const domTree = /* @__PURE__ */ __name((args = {
384
372
  return style;
385
373
  }
386
374
  __name2(getCachedComputedStyle, "getCachedComputedStyle");
387
- __name(getCachedComputedStyle, "getCachedComputedStyle");
375
+ __name$1(getCachedComputedStyle, "getCachedComputedStyle");
388
376
  function getCachedClientRects(element) {
389
377
  if (!element) return null;
390
378
  if (DOM_CACHE.clientRects.has(element)) {
@@ -397,7 +385,7 @@ const domTree = /* @__PURE__ */ __name((args = {
397
385
  return rects;
398
386
  }
399
387
  __name2(getCachedClientRects, "getCachedClientRects");
400
- __name(getCachedClientRects, "getCachedClientRects");
388
+ __name$1(getCachedClientRects, "getCachedClientRects");
401
389
  const DOM_HASH_MAP = {};
402
390
  const ID = { current: 0 };
403
391
  const HIGHLIGHT_CONTAINER_ID = "playwright-highlight-container";
@@ -493,7 +481,7 @@ const domTree = /* @__PURE__ */ __name((args = {
493
481
  label.style.top = `${labelTop}px`;
494
482
  label.style.left = `${labelLeft}px`;
495
483
  fragment.appendChild(label);
496
- const updatePositions = /* @__PURE__ */ __name(() => {
484
+ const updatePositions = /* @__PURE__ */ __name$1(() => {
497
485
  const newRects = element.getClientRects();
498
486
  let newIframeOffset = { x: 0, y: 0 };
499
487
  if (parentIframe) {
@@ -540,7 +528,7 @@ const domTree = /* @__PURE__ */ __name((args = {
540
528
  label.style.display = "none";
541
529
  }
542
530
  }, "updatePositions");
543
- const throttleFunction = /* @__PURE__ */ __name((func, delay) => {
531
+ const throttleFunction = /* @__PURE__ */ __name$1((func, delay) => {
544
532
  let lastCall = 0;
545
533
  return (...args2) => {
546
534
  const now = performance.now();
@@ -552,7 +540,7 @@ const domTree = /* @__PURE__ */ __name((args = {
552
540
  const throttledUpdatePositions = throttleFunction(updatePositions, 16);
553
541
  window.addEventListener("scroll", throttledUpdatePositions, true);
554
542
  window.addEventListener("resize", throttledUpdatePositions);
555
- cleanupFn = /* @__PURE__ */ __name(() => {
543
+ cleanupFn = /* @__PURE__ */ __name$1(() => {
556
544
  window.removeEventListener("scroll", throttledUpdatePositions, true);
557
545
  window.removeEventListener("resize", throttledUpdatePositions);
558
546
  overlays.forEach((overlay) => overlay.element.remove());
@@ -569,7 +557,7 @@ const domTree = /* @__PURE__ */ __name((args = {
569
557
  }
570
558
  }
571
559
  __name2(highlightElement, "highlightElement");
572
- __name(highlightElement, "highlightElement");
560
+ __name$1(highlightElement, "highlightElement");
573
561
  function isScrollableElement(element) {
574
562
  if (!element || element.nodeType !== Node.ELEMENT_NODE) {
575
563
  return null;
@@ -616,7 +604,7 @@ const domTree = /* @__PURE__ */ __name((args = {
616
604
  return scrollData;
617
605
  }
618
606
  __name2(isScrollableElement, "isScrollableElement");
619
- __name(isScrollableElement, "isScrollableElement");
607
+ __name$1(isScrollableElement, "isScrollableElement");
620
608
  function isTextNodeVisible(textNode) {
621
609
  try {
622
610
  if (viewportExpansion === -1) {
@@ -669,7 +657,7 @@ const domTree = /* @__PURE__ */ __name((args = {
669
657
  }
670
658
  }
671
659
  __name2(isTextNodeVisible, "isTextNodeVisible");
672
- __name(isTextNodeVisible, "isTextNodeVisible");
660
+ __name$1(isTextNodeVisible, "isTextNodeVisible");
673
661
  function isElementAccepted(element) {
674
662
  if (!element || !element.tagName) return false;
675
663
  const alwaysAccept = /* @__PURE__ */ new Set([
@@ -696,13 +684,13 @@ const domTree = /* @__PURE__ */ __name((args = {
696
684
  return !leafElementDenyList.has(tagName);
697
685
  }
698
686
  __name2(isElementAccepted, "isElementAccepted");
699
- __name(isElementAccepted, "isElementAccepted");
687
+ __name$1(isElementAccepted, "isElementAccepted");
700
688
  function isElementVisible(element) {
701
689
  const style = getCachedComputedStyle(element);
702
690
  return element.offsetWidth > 0 && element.offsetHeight > 0 && style?.visibility !== "hidden" && style?.display !== "none";
703
691
  }
704
692
  __name2(isElementVisible, "isElementVisible");
705
- __name(isElementVisible, "isElementVisible");
693
+ __name$1(isElementVisible, "isElementVisible");
706
694
  function isInteractiveElement(element) {
707
695
  if (!element || element.nodeType !== Node.ELEMENT_NODE) {
708
696
  return false;
@@ -799,7 +787,7 @@ const domTree = /* @__PURE__ */ __name((args = {
799
787
  return false;
800
788
  }
801
789
  __name2(doesElementHaveInteractivePointer, "doesElementHaveInteractivePointer");
802
- __name(doesElementHaveInteractivePointer, "doesElementHaveInteractivePointer");
790
+ __name$1(doesElementHaveInteractivePointer, "doesElementHaveInteractivePointer");
803
791
  let isInteractiveCursor = doesElementHaveInteractivePointer(element);
804
792
  if (isInteractiveCursor) {
805
793
  return true;
@@ -960,7 +948,7 @@ const domTree = /* @__PURE__ */ __name((args = {
960
948
  return false;
961
949
  }
962
950
  __name2(isInteractiveElement, "isInteractiveElement");
963
- __name(isInteractiveElement, "isInteractiveElement");
951
+ __name$1(isInteractiveElement, "isInteractiveElement");
964
952
  function isTopElement(element) {
965
953
  if (viewportExpansion === -1) {
966
954
  return true;
@@ -1032,7 +1020,7 @@ const domTree = /* @__PURE__ */ __name((args = {
1032
1020
  });
1033
1021
  }
1034
1022
  __name2(isTopElement, "isTopElement");
1035
- __name(isTopElement, "isTopElement");
1023
+ __name$1(isTopElement, "isTopElement");
1036
1024
  function isInExpandedViewport(element, viewportExpansion2) {
1037
1025
  if (viewportExpansion2 === -1) {
1038
1026
  return true;
@@ -1054,7 +1042,7 @@ const domTree = /* @__PURE__ */ __name((args = {
1054
1042
  return false;
1055
1043
  }
1056
1044
  __name2(isInExpandedViewport, "isInExpandedViewport");
1057
- __name(isInExpandedViewport, "isInExpandedViewport");
1045
+ __name$1(isInExpandedViewport, "isInExpandedViewport");
1058
1046
  function isInteractiveCandidate(element) {
1059
1047
  if (!element || element.nodeType !== Node.ELEMENT_NODE) return false;
1060
1048
  const tagName = element.tagName.toLowerCase();
@@ -1073,7 +1061,7 @@ const domTree = /* @__PURE__ */ __name((args = {
1073
1061
  return hasQuickInteractiveAttr;
1074
1062
  }
1075
1063
  __name2(isInteractiveCandidate, "isInteractiveCandidate");
1076
- __name(isInteractiveCandidate, "isInteractiveCandidate");
1064
+ __name$1(isInteractiveCandidate, "isInteractiveCandidate");
1077
1065
  const DISTINCT_INTERACTIVE_TAGS = /* @__PURE__ */ new Set([
1078
1066
  "a",
1079
1067
  "button",
@@ -1119,7 +1107,7 @@ const domTree = /* @__PURE__ */ __name((args = {
1119
1107
  return (isInteractiveElement(element) || hasInteractiveAttributes || hasInteractiveClass) && hasVisibleChildren && isInKnownContainer && !isParentBody;
1120
1108
  }
1121
1109
  __name2(isHeuristicallyInteractive, "isHeuristicallyInteractive");
1122
- __name(isHeuristicallyInteractive, "isHeuristicallyInteractive");
1110
+ __name$1(isHeuristicallyInteractive, "isHeuristicallyInteractive");
1123
1111
  function isElementDistinctInteraction(element) {
1124
1112
  if (!element || element.nodeType !== Node.ELEMENT_NODE) {
1125
1113
  return false;
@@ -1190,7 +1178,7 @@ const domTree = /* @__PURE__ */ __name((args = {
1190
1178
  return false;
1191
1179
  }
1192
1180
  __name2(isElementDistinctInteraction, "isElementDistinctInteraction");
1193
- __name(isElementDistinctInteraction, "isElementDistinctInteraction");
1181
+ __name$1(isElementDistinctInteraction, "isElementDistinctInteraction");
1194
1182
  function handleHighlighting(nodeData, node, parentIframe, isParentHighlighted) {
1195
1183
  if (!nodeData.isInteractive) return false;
1196
1184
  let shouldHighlight = false;
@@ -1222,7 +1210,7 @@ const domTree = /* @__PURE__ */ __name((args = {
1222
1210
  return false;
1223
1211
  }
1224
1212
  __name2(handleHighlighting, "handleHighlighting");
1225
- __name(handleHighlighting, "handleHighlighting");
1213
+ __name$1(handleHighlighting, "handleHighlighting");
1226
1214
  function buildDomTree(node, parentIframe = null, isParentHighlighted = false) {
1227
1215
  if (!node || node.id === HIGHLIGHT_CONTAINER_ID || node.nodeType !== Node.ELEMENT_NODE && node.nodeType !== Node.TEXT_NODE) {
1228
1216
  return null;
@@ -1360,7 +1348,7 @@ const domTree = /* @__PURE__ */ __name((args = {
1360
1348
  return id;
1361
1349
  }
1362
1350
  __name2(buildDomTree, "buildDomTree");
1363
- __name(buildDomTree, "buildDomTree");
1351
+ __name$1(buildDomTree, "buildDomTree");
1364
1352
  const rootId = buildDomTree(document.body);
1365
1353
  DOM_CACHE.clearCache();
1366
1354
  return { rootId, map: DOM_HASH_MAP };
@@ -1407,7 +1395,7 @@ function getFlatTree(config) {
1407
1395
  return elements;
1408
1396
  }
1409
1397
  __name2(getFlatTree, "getFlatTree");
1410
- __name(getFlatTree, "getFlatTree");
1398
+ __name$1(getFlatTree, "getFlatTree");
1411
1399
  function flatTreeToString(flatTree, include_attributes) {
1412
1400
  const DEFAULT_INCLUDE_ATTRIBUTES = [
1413
1401
  "title",
@@ -1434,13 +1422,13 @@ function flatTreeToString(flatTree, include_attributes) {
1434
1422
  "aria-owns"
1435
1423
  ];
1436
1424
  const includeAttrs = [...include_attributes || [], ...DEFAULT_INCLUDE_ATTRIBUTES];
1437
- const capTextLength = /* @__PURE__ */ __name((text, maxLength) => {
1425
+ const capTextLength = /* @__PURE__ */ __name$1((text, maxLength) => {
1438
1426
  if (text.length > maxLength) {
1439
1427
  return text.substring(0, maxLength) + "...";
1440
1428
  }
1441
1429
  return text;
1442
1430
  }, "capTextLength");
1443
- const buildTreeNode = /* @__PURE__ */ __name((nodeId) => {
1431
+ const buildTreeNode = /* @__PURE__ */ __name$1((nodeId) => {
1444
1432
  const node = flatTree.map[nodeId];
1445
1433
  if (!node) return null;
1446
1434
  if (node.type === "TEXT_NODE") {
@@ -1479,7 +1467,7 @@ function flatTreeToString(flatTree, include_attributes) {
1479
1467
  };
1480
1468
  }
1481
1469
  }, "buildTreeNode");
1482
- const setParentReferences = /* @__PURE__ */ __name((node, parent = null) => {
1470
+ const setParentReferences = /* @__PURE__ */ __name$1((node, parent = null) => {
1483
1471
  node.parent = parent;
1484
1472
  for (const child of node.children) {
1485
1473
  setParentReferences(child, node);
@@ -1488,7 +1476,7 @@ function flatTreeToString(flatTree, include_attributes) {
1488
1476
  const rootNode = buildTreeNode(flatTree.rootId);
1489
1477
  if (!rootNode) return "";
1490
1478
  setParentReferences(rootNode);
1491
- const hasParentWithHighlightIndex = /* @__PURE__ */ __name((node) => {
1479
+ const hasParentWithHighlightIndex = /* @__PURE__ */ __name$1((node) => {
1492
1480
  let current = node.parent;
1493
1481
  while (current) {
1494
1482
  if (current.type === "element" && current.highlightIndex !== void 0) {
@@ -1498,7 +1486,7 @@ function flatTreeToString(flatTree, include_attributes) {
1498
1486
  }
1499
1487
  return false;
1500
1488
  }, "hasParentWithHighlightIndex");
1501
- const processNode = /* @__PURE__ */ __name((node, depth, result22) => {
1489
+ const processNode = /* @__PURE__ */ __name$1((node, depth, result22) => {
1502
1490
  let nextDepth = depth;
1503
1491
  const depthStr = " ".repeat(depth);
1504
1492
  if (node.type === "element") {
@@ -1592,10 +1580,10 @@ function flatTreeToString(flatTree, include_attributes) {
1592
1580
  return result2.join("\n");
1593
1581
  }
1594
1582
  __name2(flatTreeToString, "flatTreeToString");
1595
- __name(flatTreeToString, "flatTreeToString");
1596
- const getAllTextTillNextClickableElement = /* @__PURE__ */ __name((node, maxDepth = -1) => {
1583
+ __name$1(flatTreeToString, "flatTreeToString");
1584
+ const getAllTextTillNextClickableElement = /* @__PURE__ */ __name$1((node, maxDepth = -1) => {
1597
1585
  const textParts = [];
1598
- const collectText = /* @__PURE__ */ __name((currentNode, currentDepth) => {
1586
+ const collectText = /* @__PURE__ */ __name$1((currentNode, currentDepth) => {
1599
1587
  if (maxDepth !== -1 && currentDepth > maxDepth) {
1600
1588
  return;
1601
1589
  }
@@ -1625,7 +1613,7 @@ function getSelectorMap(flatTree) {
1625
1613
  return selectorMap;
1626
1614
  }
1627
1615
  __name2(getSelectorMap, "getSelectorMap");
1628
- __name(getSelectorMap, "getSelectorMap");
1616
+ __name$1(getSelectorMap, "getSelectorMap");
1629
1617
  function getElementTextMap(simplifiedHTML) {
1630
1618
  const lines = simplifiedHTML.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
1631
1619
  const elementTextMap = /* @__PURE__ */ new Map();
@@ -1640,7 +1628,7 @@ function getElementTextMap(simplifiedHTML) {
1640
1628
  return elementTextMap;
1641
1629
  }
1642
1630
  __name2(getElementTextMap, "getElementTextMap");
1643
- __name(getElementTextMap, "getElementTextMap");
1631
+ __name$1(getElementTextMap, "getElementTextMap");
1644
1632
  function cleanUpHighlights() {
1645
1633
  const cleanupFunctions = window._highlightCleanupFunctions || [];
1646
1634
  for (const cleanup of cleanupFunctions) {
@@ -1651,7 +1639,7 @@ function cleanUpHighlights() {
1651
1639
  window._highlightCleanupFunctions = [];
1652
1640
  }
1653
1641
  __name2(cleanUpHighlights, "cleanUpHighlights");
1654
- __name(cleanUpHighlights, "cleanUpHighlights");
1642
+ __name$1(cleanUpHighlights, "cleanUpHighlights");
1655
1643
  window.addEventListener("popstate", () => {
1656
1644
  cleanUpHighlights();
1657
1645
  });
@@ -1708,7 +1696,7 @@ function getPageInfo() {
1708
1696
  };
1709
1697
  }
1710
1698
  __name2(getPageInfo, "getPageInfo");
1711
- __name(getPageInfo, "getPageInfo");
1699
+ __name$1(getPageInfo, "getPageInfo");
1712
1700
  function patchReact(pageController) {
1713
1701
  const reactRootElements = document.querySelectorAll(
1714
1702
  '[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root'
@@ -1718,7 +1706,7 @@ function patchReact(pageController) {
1718
1706
  }
1719
1707
  }
1720
1708
  __name2(patchReact, "patchReact");
1721
- __name(patchReact, "patchReact");
1709
+ __name$1(patchReact, "patchReact");
1722
1710
  const _PageController = (__PageController = class extends EventTarget {
1723
1711
  config;
1724
1712
  /** Corresponds to eval_page in browser-use */
@@ -1956,15 +1944,92 @@ const _PageController = (__PageController = class extends EventTarget {
1956
1944
  this.simplifiedHTML = "<EMPTY>";
1957
1945
  }
1958
1946
  }, __name2(__PageController, "_PageController"), __PageController);
1959
- __name(_PageController, "PageController");
1947
+ __name$1(_PageController, "PageController");
1960
1948
  let PageController = _PageController;
1961
- const DEFAULT_MODEL_NAME = "PAGE-AGENT-FREE-TESTING-RANDOM";
1962
- const DEFAULT_API_KEY = "PAGE-AGENT-FREE-TESTING-RANDOM";
1963
- const DEFAULT_BASE_URL = "https://hwcxiuzfylggtcktqgij.supabase.co/functions/v1/llm-testing-proxy";
1964
- const LLM_MAX_RETRIES = 2;
1965
- const MAX_STEPS = 20;
1966
- const DEFAULT_TEMPERATURE = 0.7;
1967
- const DEFAULT_MAX_TOKENS = 4096;
1949
+ (function() {
1950
+ try {
1951
+ if (typeof document != "undefined") {
1952
+ var elementStyle = document.createElement("style");
1953
+ elementStyle.appendChild(document.createTextNode("._wrapper_1j0ct_1 {\n position: fixed;\n bottom: 100px;\n left: 50%;\n transform: translateX(-50%) translateY(20px);\n opacity: 0;\n z-index: 2147483642; /* 比 SimulatorMask 高一层 */\n box-sizing: border-box;\n\n overflow: visible;\n\n * {\n box-sizing: border-box;\n }\n\n --width: 360px;\n --height: 40px;\n --border-radius: 12px;\n\n --side-space: 12px; /* 控制栏两侧的间距 */\n --history-width: calc(var(--width) - var(--side-space) * 2);\n\n --color-1: rgb(57, 182, 255);\n --color-2: rgb(189, 69, 251);\n --color-3: rgb(255, 87, 51);\n --color-4: rgb(255, 214, 0);\n\n width: var(--width);\n height: var(--height);\n\n transition: all 0.3s ease-in-out;\n\n /* 响应式设计 */\n @media (max-width: 480px) {\n width: calc(100vw - 40px);\n --width: calc(100vw - 40px);\n }\n\n ._background_1j0ct_39 {\n position: absolute;\n inset: -2px -8px;\n border-radius: calc(var(--border-radius) + 4px);\n filter: blur(16px);\n overflow: hidden;\n /* mix-blend-mode: lighten; */\n /* display: none; */\n\n &::before {\n content: '';\n z-index: -1;\n pointer-events: none;\n position: absolute;\n width: 100%;\n height: 100%;\n /* left: -100%; */\n left: 0;\n top: 0;\n\n background-image: linear-gradient(\n to bottom left,\n var(--color-1),\n var(--color-2),\n var(--color-1)\n );\n animation: _mask-running_1j0ct_1 2s linear infinite;\n }\n &::after {\n content: '';\n z-index: -1;\n pointer-events: none;\n position: absolute;\n width: 100%;\n height: 100%;\n left: 0;\n top: 0;\n\n background-image: linear-gradient(\n to bottom left,\n var(--color-2),\n var(--color-1),\n var(--color-2)\n );\n animation: _mask-running_1j0ct_1 2s linear infinite;\n animation-delay: 1s;\n }\n }\n}\n\n@keyframes _mask-running_1j0ct_1 {\n from {\n transform: translateX(-100%);\n }\n to {\n transform: translateX(100%);\n }\n}\n\n/* 控制栏 */\n._header_1j0ct_99 {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 8px 12px;\n user-select: none;\n\n position: absolute;\n inset: 0;\n\n cursor: pointer;\n flex-shrink: 0; /* 防止 header 被压缩 */\n\n background: rgba(0, 0, 0, 0.5);\n backdrop-filter: blur(10px);\n border-radius: var(--border-radius);\n background-clip: padding-box;\n\n box-shadow:\n 0 0 0px 2px rgba(255, 255, 255, 0.4),\n 0 0 5px 1px rgba(255, 255, 255, 0.3);\n\n ._statusSection_1j0ct_121 {\n display: flex;\n align-items: center;\n gap: 8px;\n flex: 1;\n min-height: 24px; /* 确保垂直居中 */\n\n ._indicator_1j0ct_128 {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: rgba(255, 255, 255, 0.5);\n flex-shrink: 0;\n animation: none; /* 默认无动画 */\n\n /* 运行状态 - 有动画 */\n &._thinking_1j0ct_137 {\n background: rgb(57, 182, 255);\n animation: _pulse_1j0ct_1 0.8s ease-in-out infinite;\n }\n\n &._tool_executing_1j0ct_142 {\n background: rgb(189, 69, 251);\n animation: _pulse_1j0ct_1 0.6s ease-in-out infinite;\n }\n\n &._retry_1j0ct_147 {\n background: rgb(255, 214, 0);\n animation: _retryPulse_1j0ct_1 1s ease-in-out infinite;\n }\n\n /* 静止状态 - 无动画 */\n &._completed_1j0ct_153,\n &._input_1j0ct_154,\n &._output_1j0ct_155 {\n background: rgb(34, 197, 94);\n animation: none;\n }\n\n &._error_1j0ct_160 {\n background: rgb(239, 68, 68);\n animation: none;\n }\n }\n\n ._statusText_1j0ct_166 {\n color: white;\n font-size: 12px;\n line-height: 1;\n font-weight: 500;\n transition: all 0.3s ease-in-out;\n position: relative;\n overflow: hidden;\n display: flex;\n align-items: center;\n min-height: 24px; /* 确保垂直居中 */\n\n &._fadeOut_1j0ct_178 {\n animation: _statusTextFadeOut_1j0ct_1 0.3s ease forwards;\n }\n\n &._fadeIn_1j0ct_182 {\n animation: _statusTextFadeIn_1j0ct_1 0.3s ease forwards;\n }\n }\n }\n\n ._controls_1j0ct_188 {\n display: flex;\n align-items: center;\n gap: 4px;\n\n ._controlButton_1j0ct_193 {\n width: 24px;\n height: 24px;\n border: none;\n border-radius: 4px;\n background: rgba(255, 255, 255, 0.1);\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 12px;\n line-height: 1;\n\n &:hover {\n background: rgba(255, 255, 255, 0.2);\n }\n }\n\n ._pauseButton_1j0ct_212 {\n font-weight: 600;\n &._paused_1j0ct_214 {\n background: rgba(34, 197, 94, 0.2); /* 绿色背景表示可以继续 */\n color: rgb(34, 197, 94);\n\n &:hover {\n background: rgba(34, 197, 94, 0.3);\n }\n }\n }\n\n ._stopButton_1j0ct_224 {\n background: rgba(239, 68, 68, 0.2);\n color: rgb(255, 41, 41);\n font-weight: 600;\n\n &:hover {\n background: rgba(239, 68, 68, 0.3);\n }\n }\n }\n}\n\n@keyframes _statusTextFadeIn_1j0ct_1 {\n 0% {\n opacity: 0;\n transform: translateY(5px);\n }\n 100% {\n opacity: 1;\n transform: translateY(0);\n }\n}\n\n@keyframes _statusTextFadeOut_1j0ct_1 {\n 0% {\n opacity: 1;\n transform: translateY(0);\n }\n 100% {\n opacity: 0;\n transform: translateY(-5px);\n }\n}\n\n._historySectionWrapper_1j0ct_258 {\n position: absolute;\n width: var(--history-width);\n bottom: var(--height);\n left: var(--side-space);\n z-index: -2;\n\n padding-top: 0px;\n visibility: collapse;\n overflow: hidden;\n\n transition: all 0.2s;\n\n background: rgba(2, 0, 20, 0.5);\n /* background: rgba(186, 186, 186, 0.2); */\n backdrop-filter: blur(10px);\n\n text-shadow: 0 0 1px rgba(0, 0, 0, 0.2);\n\n border-top-left-radius: calc(var(--border-radius) + 4px);\n border-top-right-radius: calc(var(--border-radius) + 4px);\n\n /* border: 2px solid rgba(255, 255, 255, 0.8); */\n border: 2px solid rgba(255, 255, 255, 0.4);\n box-shadow: 0 4px 16px rgba(0, 0, 0, 0.6);\n\n /* @media (prefers-color-scheme: dark) {\n box-shadow:\n 0 8px 32px 0 rgba(0, 0, 0, 0.85),\n 0 2px 12px 0 rgba(57, 182, 255, 0.1);\n } */\n\n ._expanded_1j0ct_290 & {\n padding-top: 8px;\n visibility: visible;\n }\n\n ._historySection_1j0ct_258 {\n position: relative;\n overflow-y: auto;\n overscroll-behavior: contain;\n scrollbar-width: none;\n max-height: 0;\n padding-inline: 8px;\n\n transition: max-height 0.2s;\n\n ._expanded_1j0ct_290 & {\n max-height: 400px;\n }\n\n ._historyItem_1j0ct_309 {\n /* backdrop-filter: blur(10px); */\n padding: 8px 10px;\n margin-bottom: 6px;\n background: linear-gradient(135deg, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0.03));\n border-radius: 8px;\n border-left: 2px solid rgba(57, 182, 255, 0.5);\n font-size: 12px;\n color: white;\n /* color: black; */\n line-height: 1.3;\n position: relative;\n overflow: hidden;\n\n /* 微妙的内阴影 */\n box-shadow:\n inset 0 1px 0 rgba(255, 255, 255, 0.1),\n 0 1px 3px rgba(0, 0, 0, 0.1);\n\n &::before {\n content: '';\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n height: 1px;\n background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);\n }\n\n &:hover {\n background: linear-gradient(135deg, rgba(255, 255, 255, 0.12), rgba(255, 255, 255, 0.06));\n /* transform: translateY(-1px); */\n box-shadow:\n inset 0 1px 0 rgba(255, 255, 255, 0.15),\n 0 2px 4px rgba(0, 0, 0, 0.15);\n }\n\n &:last-child {\n margin-bottom: 10px;\n }\n\n &._completed_1j0ct_153,\n &._input_1j0ct_154,\n &._output_1j0ct_155 {\n border-left-color: rgb(34, 197, 94);\n background: linear-gradient(135deg, rgba(34, 197, 94, 0.1), rgba(34, 197, 94, 0.05));\n }\n\n &._error_1j0ct_160 {\n border-left-color: rgb(239, 68, 68);\n background: linear-gradient(135deg, rgba(239, 68, 68, 0.1), rgba(239, 68, 68, 0.05));\n }\n\n &._retry_1j0ct_147 {\n border-left-color: rgb(255, 214, 0);\n background: linear-gradient(135deg, rgba(255, 214, 0, 0.1), rgba(255, 214, 0, 0.05));\n }\n\n /* 突出显示 done 成功结果 */\n &._doneSuccess_1j0ct_368 {\n background: linear-gradient(\n 135deg,\n rgba(34, 197, 94, 0.25),\n rgba(34, 197, 94, 0.15),\n rgba(34, 197, 94, 0.08)\n );\n border: none;\n border-left: 4px solid rgb(34, 197, 94);\n box-shadow:\n 0 4px 12px rgba(34, 197, 94, 0.3),\n inset 0 1px 0 rgba(255, 255, 255, 0.2),\n 0 0 20px rgba(34, 197, 94, 0.1);\n font-weight: 600;\n color: rgb(220, 252, 231);\n padding: 10px 12px;\n margin-bottom: 8px;\n border-radius: 8px;\n position: relative;\n overflow: hidden;\n\n &::before {\n background: linear-gradient(90deg, transparent, rgba(34, 197, 94, 0.4), transparent);\n }\n\n &::after {\n content: '';\n position: absolute;\n top: 0;\n left: -100%;\n width: 100%;\n height: 100%;\n background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);\n animation: _shimmer_1j0ct_1 2s ease-in-out infinite;\n }\n\n ._historyContent_1j0ct_404 {\n ._statusIcon_1j0ct_405 {\n font-size: 16px;\n animation: _celebrate_1j0ct_1 0.8s ease-in-out;\n filter: drop-shadow(0 2px 4px rgba(34, 197, 94, 0.5));\n }\n }\n }\n\n /* 突出显示 done 失败结果 */\n &._doneError_1j0ct_414 {\n background: linear-gradient(\n 135deg,\n rgba(239, 68, 68, 0.25),\n rgba(239, 68, 68, 0.15),\n rgba(239, 68, 68, 0.08)\n );\n border: none;\n border-left: 4px solid rgb(239, 68, 68);\n box-shadow:\n 0 4px 12px rgba(239, 68, 68, 0.3),\n inset 0 1px 0 rgba(255, 255, 255, 0.2),\n 0 0 20px rgba(239, 68, 68, 0.1);\n font-weight: 600;\n color: rgb(254, 226, 226);\n padding: 10px 12px;\n margin-bottom: 8px;\n border-radius: 8px;\n position: relative;\n overflow: hidden;\n\n &::before {\n background: linear-gradient(90deg, transparent, rgba(239, 68, 68, 0.4), transparent);\n }\n\n ._historyContent_1j0ct_404 {\n ._statusIcon_1j0ct_405 {\n font-size: 16px;\n filter: drop-shadow(0 2px 4px rgba(239, 68, 68, 0.5));\n }\n }\n }\n\n ._historyContent_1j0ct_404 {\n display: flex;\n align-items: center;\n gap: 8px;\n\n word-break: break-all;\n white-space: pre-wrap;\n\n /* overflow-x: auto; */\n\n ._statusIcon_1j0ct_405 {\n font-size: 12px;\n flex-shrink: 0;\n line-height: 1;\n transition: all 0.3s ease;\n }\n }\n\n ._historyMeta_1j0ct_465 {\n font-size: 10px;\n color: rgba(255, 255, 255, 0.6);\n /* color: rgb(61, 61, 61); */\n margin-top: 8px;\n line-height: 1;\n }\n }\n }\n}\n\n/* 动画关键帧 - 更快的闪烁 */\n@keyframes _pulse_1j0ct_1 {\n 0%,\n 100% {\n opacity: 1;\n transform: scale(1);\n }\n 50% {\n opacity: 0.4;\n transform: scale(1.3);\n }\n}\n\n/* 重试动画 - 旋转脉冲 */\n@keyframes _retryPulse_1j0ct_1 {\n 0%,\n 100% {\n opacity: 1;\n transform: scale(1) rotate(0deg);\n }\n 25% {\n opacity: 0.6;\n transform: scale(1.2) rotate(90deg);\n }\n 50% {\n opacity: 0.8;\n transform: scale(1.1) rotate(180deg);\n }\n 75% {\n opacity: 0.6;\n transform: scale(1.2) rotate(270deg);\n }\n}\n\n/* 庆祝动画 */\n@keyframes _celebrate_1j0ct_1 {\n 0%,\n 100% {\n transform: scale(1);\n }\n 25% {\n transform: scale(1.2) rotate(-5deg);\n }\n 75% {\n transform: scale(1.2) rotate(5deg);\n }\n}\n\n/* done 卡片的光泽效果 */\n@keyframes _shimmer_1j0ct_1 {\n 0% {\n left: -100%;\n }\n 100% {\n left: 100%;\n }\n}\n\n/* 输入区域样式 */\n._inputSectionWrapper_1j0ct_535 {\n position: absolute;\n width: var(--history-width);\n top: var(--height);\n left: var(--side-space);\n z-index: -1;\n\n visibility: visible;\n overflow: hidden;\n\n height: 48px;\n\n transition: all 0.2s;\n\n background: rgba(186, 186, 186, 0.2);\n backdrop-filter: blur(10px);\n\n border-bottom-left-radius: calc(var(--border-radius) + 4px);\n border-bottom-right-radius: calc(var(--border-radius) + 4px);\n\n border: 2px solid rgba(255, 255, 255, 0.3);\n box-shadow: 0 1px 16px rgba(0, 0, 0, 0.4);\n\n &._hidden_1j0ct_558 {\n visibility: collapse;\n height: 0;\n }\n\n ._inputSection_1j0ct_535 {\n display: flex;\n align-items: center;\n gap: 4px;\n padding: 8px 8px;\n\n ._taskInput_1j0ct_569 {\n flex: 1;\n background: rgba(255, 255, 255, 0.4);\n border: 1px solid rgba(255, 255, 255, 0.3);\n border-radius: 10px;\n padding-inline: 10px;\n color: rgb(20, 20, 20);\n font-size: 12px;\n height: 28px;\n line-height: 1;\n outline: none;\n transition: all 0.2s ease;\n\n /* text-shadow: 0 0 2px rgba(255, 255, 255, 0.8); */\n\n /* border-color: rgba(57, 182, 255, 0.3); */\n\n &::placeholder {\n color: rgb(53, 53, 53);\n }\n\n &:focus {\n background: rgba(255, 255, 255, 0.8);\n border-color: rgba(57, 182, 255, 0.6);\n box-shadow: 0 0 0 2px rgba(57, 182, 255, 0.2);\n }\n }\n }\n}\n._wrapper_1oy2s_1 {\n position: fixed;\n inset: 0;\n z-index: 2147483641; /* 确保在所有元素之上,除了 panel */\n /* pointer-events: none; */\n cursor: not-allowed;\n overflow: hidden;\n\n display: none;\n}\n/* AI 光标样式 */\n._cursor_1vrf3_2 {\n position: absolute;\n width: var(--cursor-size, 75px);\n height: var(--cursor-size, 75px);\n pointer-events: none;\n z-index: 10000;\n transform: translate(-30%, -30%);\n\n animation: _cursor-enter_1vrf3_1 300ms ease-out forwards;\n}\n\n._cursorBorder_1vrf3_13 {\n position: absolute;\n inset: 0;\n background: linear-gradient(45deg, rgb(57, 182, 255), rgb(189, 69, 251));\n mask-image: url(https://img.alicdn.com/imgextra/i1/O1CN01YHLVYR1LvqWIyo5kH_!!6000000001362-2-tps-202-202.png);\n mask-size: 100% 100%;\n mask-repeat: no-repeat;\n animation: _cursor-breathe_1vrf3_1 2s ease-in-out infinite;\n}\n\n._cursorFilling_1vrf3_23 {\n position: absolute;\n inset: 0;\n background: url(https://img.alicdn.com/imgextra/i3/O1CN01JZOqOS1Tu1sIKbPLW_!!6000000002441-2-tps-202-202.png);\n background-size: 100% 100%;\n background-repeat: no-repeat;\n}\n\n._cursorRipple_1vrf3_31 {\n position: absolute;\n inset: 0;\n pointer-events: none;\n}\n\n._cursor_1vrf3_2._clicking_1vrf3_37 ._cursorRipple_1vrf3_31::after {\n content: '';\n position: absolute;\n width: 100%;\n height: 100%;\n left: -30%;\n top: -30%;\n border: 4px solid rgba(57, 182, 255, 1);\n border-radius: 50%;\n animation: _cursor-ripple_1vrf3_1 300ms ease-out forwards;\n}\n\n/* 光标动画关键帧 */\n@keyframes _cursor-breathe_1vrf3_1 {\n 0%,\n 100% {\n transform: scale(1);\n opacity: 0.9;\n }\n 50% {\n transform: scale(1.05);\n opacity: 1;\n }\n}\n\n@keyframes _cursor-rotate_1vrf3_1 {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n}\n\n@keyframes _cursor-enter_1vrf3_1 {\n 0% {\n transform: translate(-30%, -30%) scale(0.5);\n opacity: 0;\n }\n 100% {\n transform: translate(-30%, -30%) scale(1);\n opacity: 1;\n }\n}\n\n@keyframes _cursor-ripple_1vrf3_1 {\n 0% {\n transform: scale(0);\n opacity: 1;\n }\n 100% {\n transform: scale(2);\n opacity: 0;\n }\n}"));
1954
+ document.head.appendChild(elementStyle);
1955
+ }
1956
+ } catch (e) {
1957
+ console.error("vite-plugin-css-injected-by-js", e);
1958
+ }
1959
+ })();
1960
+ var __defProp = Object.defineProperty;
1961
+ var __typeError = /* @__PURE__ */ __name2((msg) => {
1962
+ throw TypeError(msg);
1963
+ }, "__typeError");
1964
+ var __defNormalProp = /* @__PURE__ */ __name2((obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value, "__defNormalProp");
1965
+ var __name = /* @__PURE__ */ __name2((target, value) => __defProp(target, "name", { value, configurable: true }), "__name");
1966
+ var __publicField = /* @__PURE__ */ __name2((obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value), "__publicField");
1967
+ var __accessCheck = /* @__PURE__ */ __name2((obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg), "__accessCheck");
1968
+ var __privateGet = /* @__PURE__ */ __name2((obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), "__privateGet");
1969
+ var __privateAdd = /* @__PURE__ */ __name2((obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value), "__privateAdd");
1970
+ var __privateSet = /* @__PURE__ */ __name2((obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value), "__privateSet");
1971
+ var __privateMethod = /* @__PURE__ */ __name2((obj, member, method) => (__accessCheck(obj, member, "access private method"), method), "__privateMethod");
1972
+ var _wrapper, _indicator, _statusText, _historySection, _expandButton, _pauseButton, _stopButton, _inputSection, _taskInput, _state, _isExpanded, _config, _i18n, _userAnswerResolver, _isWaitingForUserAnswer, _headerUpdateTimer, _pendingHeaderText, _isAnimating, _Panel_instances, toStepData_fn, getToolExecutingText_fn, getToolCompletedText_fn, updateInternal_fn, togglePause_fn, updatePauseButton_fn, stopAgent_fn, submitTask_fn, handleUserAnswer_fn, showInputArea_fn, hideInputArea_fn, shouldShowInputArea_fn, createWrapper_fn, setupEventListeners_fn, toggle_fn, expand_fn, collapse_fn, startHeaderUpdateLoop_fn, stopHeaderUpdateLoop_fn, checkAndUpdateHeader_fn, animateTextChange_fn, updateStatusIndicator_fn, updateHistory_fn, scrollToBottom_fn, createHistoryItem_fn, _cursor, _currentCursorX, _currentCursorY, _targetCursorX, _targetCursorY, _SimulatorMask_instances, createCursor_fn, moveCursorToTarget_fn;
1973
+ const _UIState = (_b = class {
1974
+ steps = [];
1975
+ currentStep = null;
1976
+ status = "idle";
1977
+ stepCounter = 0;
1978
+ addStep(stepData) {
1979
+ const step = {
1980
+ id: this.generateId(),
1981
+ stepNumber: ++this.stepCounter,
1982
+ timestamp: /* @__PURE__ */ new Date(),
1983
+ ...stepData
1984
+ };
1985
+ this.steps.push(step);
1986
+ this.currentStep = step;
1987
+ this.updateStatus(step.type);
1988
+ return step;
1989
+ }
1990
+ updateCurrentStep(updates) {
1991
+ if (!this.currentStep) return null;
1992
+ Object.assign(this.currentStep, updates);
1993
+ return this.currentStep;
1994
+ }
1995
+ getCurrentStep() {
1996
+ return this.currentStep;
1997
+ }
1998
+ getAllSteps() {
1999
+ return [...this.steps];
2000
+ }
2001
+ getStatus() {
2002
+ return this.status;
2003
+ }
2004
+ reset() {
2005
+ this.steps = [];
2006
+ this.currentStep = null;
2007
+ this.status = "idle";
2008
+ this.stepCounter = 0;
2009
+ }
2010
+ updateStatus(stepType) {
2011
+ switch (stepType) {
2012
+ case "thinking":
2013
+ case "tool_executing":
2014
+ case "output":
2015
+ case "input":
2016
+ case "retry":
2017
+ this.status = "running";
2018
+ break;
2019
+ case "completed":
2020
+ this.status = "completed";
2021
+ break;
2022
+ case "error":
2023
+ this.status = "error";
2024
+ break;
2025
+ }
2026
+ }
2027
+ generateId() {
2028
+ return `step_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
2029
+ }
2030
+ }, __name2(_b, "_UIState"), _b);
2031
+ __name(_UIState, "UIState");
2032
+ let UIState = _UIState;
1968
2033
  const enUS = {
1969
2034
  ui: {
1970
2035
  panel: {
@@ -2065,7 +2130,7 @@ const locales = {
2065
2130
  "en-US": enUS,
2066
2131
  "zh-CN": zhCN
2067
2132
  };
2068
- const _I18n = class _I18n {
2133
+ const _I18n = (_c = class {
2069
2134
  language;
2070
2135
  translations;
2071
2136
  constructor(language = "en-US") {
@@ -2095,996 +2160,383 @@ const _I18n = class _I18n {
2095
2160
  getLanguage() {
2096
2161
  return this.language;
2097
2162
  }
2098
- };
2099
- __name2(_I18n, "I18n");
2163
+ }, __name2(_c, "_I18n"), _c);
2164
+ __name(_I18n, "I18n");
2100
2165
  let I18n = _I18n;
2101
- function parseLLMConfig(config) {
2102
- return {
2103
- baseURL: config.baseURL ?? DEFAULT_BASE_URL,
2104
- apiKey: config.apiKey ?? DEFAULT_API_KEY,
2105
- model: config.model ?? DEFAULT_MODEL_NAME,
2106
- temperature: config.temperature ?? DEFAULT_TEMPERATURE,
2107
- maxTokens: config.maxTokens ?? DEFAULT_MAX_TOKENS,
2108
- maxRetries: config.maxRetries ?? LLM_MAX_RETRIES
2109
- };
2166
+ function truncate(text, maxLength) {
2167
+ if (text.length > maxLength) {
2168
+ return text.substring(0, maxLength) + "...";
2169
+ }
2170
+ return text;
2110
2171
  }
2111
- __name2(parseLLMConfig, "parseLLMConfig");
2112
- const _EventBus = class _EventBus extends EventTarget {
2172
+ __name2(truncate, "truncate");
2173
+ __name(truncate, "truncate");
2174
+ const wrapper$1 = "_wrapper_1j0ct_1";
2175
+ const background = "_background_1j0ct_39";
2176
+ const header = "_header_1j0ct_99";
2177
+ const pulse = "_pulse_1j0ct_1";
2178
+ const retryPulse = "_retryPulse_1j0ct_1";
2179
+ const statusTextFadeOut = "_statusTextFadeOut_1j0ct_1";
2180
+ const statusTextFadeIn = "_statusTextFadeIn_1j0ct_1";
2181
+ const statusSection = "_statusSection_1j0ct_121";
2182
+ const indicator = "_indicator_1j0ct_128";
2183
+ const thinking = "_thinking_1j0ct_137";
2184
+ const tool_executing = "_tool_executing_1j0ct_142";
2185
+ const retry = "_retry_1j0ct_147";
2186
+ const completed = "_completed_1j0ct_153";
2187
+ const input = "_input_1j0ct_154";
2188
+ const output = "_output_1j0ct_155";
2189
+ const error = "_error_1j0ct_160";
2190
+ const statusText = "_statusText_1j0ct_166";
2191
+ const fadeOut = "_fadeOut_1j0ct_178";
2192
+ const fadeIn = "_fadeIn_1j0ct_182";
2193
+ const controls = "_controls_1j0ct_188";
2194
+ const controlButton = "_controlButton_1j0ct_193";
2195
+ const pauseButton = "_pauseButton_1j0ct_212";
2196
+ const paused = "_paused_1j0ct_214";
2197
+ const stopButton = "_stopButton_1j0ct_224";
2198
+ const historySectionWrapper = "_historySectionWrapper_1j0ct_258";
2199
+ const shimmer = "_shimmer_1j0ct_1";
2200
+ const celebrate = "_celebrate_1j0ct_1";
2201
+ const expanded = "_expanded_1j0ct_290";
2202
+ const historySection = "_historySection_1j0ct_258";
2203
+ const historyItem = "_historyItem_1j0ct_309";
2204
+ const doneSuccess = "_doneSuccess_1j0ct_368";
2205
+ const historyContent = "_historyContent_1j0ct_404";
2206
+ const statusIcon = "_statusIcon_1j0ct_405";
2207
+ const doneError = "_doneError_1j0ct_414";
2208
+ const historyMeta = "_historyMeta_1j0ct_465";
2209
+ const inputSectionWrapper = "_inputSectionWrapper_1j0ct_535";
2210
+ const hidden = "_hidden_1j0ct_558";
2211
+ const inputSection = "_inputSection_1j0ct_535";
2212
+ const taskInput = "_taskInput_1j0ct_569";
2213
+ const styles$1 = {
2214
+ wrapper: wrapper$1,
2215
+ "mask-running": "_mask-running_1j0ct_1",
2216
+ background,
2217
+ header,
2218
+ pulse,
2219
+ retryPulse,
2220
+ statusTextFadeOut,
2221
+ statusTextFadeIn,
2222
+ statusSection,
2223
+ indicator,
2224
+ thinking,
2225
+ tool_executing,
2226
+ retry,
2227
+ completed,
2228
+ input,
2229
+ output,
2230
+ error,
2231
+ statusText,
2232
+ fadeOut,
2233
+ fadeIn,
2234
+ controls,
2235
+ controlButton,
2236
+ pauseButton,
2237
+ paused,
2238
+ stopButton,
2239
+ historySectionWrapper,
2240
+ shimmer,
2241
+ celebrate,
2242
+ expanded,
2243
+ historySection,
2244
+ historyItem,
2245
+ doneSuccess,
2246
+ historyContent,
2247
+ statusIcon,
2248
+ doneError,
2249
+ historyMeta,
2250
+ inputSectionWrapper,
2251
+ hidden,
2252
+ inputSection,
2253
+ taskInput
2254
+ };
2255
+ const _Panel = (_d = class {
2256
+ constructor(config) {
2257
+ __privateAdd(this, _Panel_instances);
2258
+ __privateAdd(this, _wrapper);
2259
+ __privateAdd(this, _indicator);
2260
+ __privateAdd(this, _statusText);
2261
+ __privateAdd(this, _historySection);
2262
+ __privateAdd(this, _expandButton);
2263
+ __privateAdd(this, _pauseButton);
2264
+ __privateAdd(this, _stopButton);
2265
+ __privateAdd(this, _inputSection);
2266
+ __privateAdd(this, _taskInput);
2267
+ __privateAdd(this, _state, new UIState());
2268
+ __privateAdd(this, _isExpanded, false);
2269
+ __privateAdd(this, _config);
2270
+ __privateAdd(this, _i18n);
2271
+ __privateAdd(this, _userAnswerResolver, null);
2272
+ __privateAdd(this, _isWaitingForUserAnswer, false);
2273
+ __privateAdd(this, _headerUpdateTimer, null);
2274
+ __privateAdd(this, _pendingHeaderText, null);
2275
+ __privateAdd(this, _isAnimating, false);
2276
+ __privateSet(this, _config, config);
2277
+ __privateSet(this, _i18n, new I18n(config.language ?? "en-US"));
2278
+ __privateSet(this, _wrapper, __privateMethod(this, _Panel_instances, createWrapper_fn).call(this));
2279
+ __privateSet(this, _indicator, __privateGet(this, _wrapper).querySelector(`.${styles$1.indicator}`));
2280
+ __privateSet(this, _statusText, __privateGet(this, _wrapper).querySelector(`.${styles$1.statusText}`));
2281
+ __privateSet(this, _historySection, __privateGet(this, _wrapper).querySelector(`.${styles$1.historySection}`));
2282
+ __privateSet(this, _expandButton, __privateGet(this, _wrapper).querySelector(`.${styles$1.expandButton}`));
2283
+ __privateSet(this, _pauseButton, __privateGet(this, _wrapper).querySelector(`.${styles$1.pauseButton}`));
2284
+ __privateSet(this, _stopButton, __privateGet(this, _wrapper).querySelector(`.${styles$1.stopButton}`));
2285
+ __privateSet(this, _inputSection, __privateGet(this, _wrapper).querySelector(`.${styles$1.inputSectionWrapper}`));
2286
+ __privateSet(this, _taskInput, __privateGet(this, _wrapper).querySelector(`.${styles$1.taskInput}`));
2287
+ __privateMethod(this, _Panel_instances, setupEventListeners_fn).call(this);
2288
+ __privateMethod(this, _Panel_instances, startHeaderUpdateLoop_fn).call(this);
2289
+ __privateMethod(this, _Panel_instances, showInputArea_fn).call(this);
2290
+ }
2291
+ get wrapper() {
2292
+ return __privateGet(this, _wrapper);
2293
+ }
2113
2294
  /**
2114
- * Listen to built-in events
2295
+ * Ask for user input
2115
2296
  */
2116
- on(event, handler) {
2117
- const wrappedHandler = /* @__PURE__ */ __name2((e) => {
2118
- const customEvent = e;
2119
- const params = customEvent.detail?.[0];
2120
- return handler(params);
2121
- }, "wrappedHandler");
2122
- this.addEventListener(event, wrappedHandler);
2297
+ async askUser(question) {
2298
+ return new Promise((resolve) => {
2299
+ __privateSet(this, _isWaitingForUserAnswer, true);
2300
+ __privateSet(this, _userAnswerResolver, resolve);
2301
+ __privateMethod(this, _Panel_instances, updateInternal_fn).call(this, {
2302
+ type: "output",
2303
+ displayText: __privateGet(this, _i18n).t("ui.panel.question", { question })
2304
+ });
2305
+ if (!__privateGet(this, _isExpanded)) {
2306
+ __privateMethod(this, _Panel_instances, expand_fn).call(this);
2307
+ }
2308
+ __privateMethod(this, _Panel_instances, showInputArea_fn).call(this, __privateGet(this, _i18n).t("ui.panel.userAnswerPrompt"));
2309
+ });
2310
+ }
2311
+ // ========== Public control methods ==========
2312
+ show() {
2313
+ this.wrapper.style.display = "block";
2314
+ void this.wrapper.offsetHeight;
2315
+ this.wrapper.style.opacity = "1";
2316
+ this.wrapper.style.transform = "translateX(-50%) translateY(0)";
2317
+ }
2318
+ hide() {
2319
+ this.wrapper.style.opacity = "0";
2320
+ this.wrapper.style.transform = "translateX(-50%) translateY(20px)";
2321
+ this.wrapper.style.display = "none";
2322
+ }
2323
+ reset() {
2324
+ __privateGet(this, _state).reset();
2325
+ __privateGet(this, _statusText).textContent = __privateGet(this, _i18n).t("ui.panel.ready");
2326
+ __privateMethod(this, _Panel_instances, updateStatusIndicator_fn).call(this, "thinking");
2327
+ __privateMethod(this, _Panel_instances, updateHistory_fn).call(this);
2328
+ __privateMethod(this, _Panel_instances, collapse_fn).call(this);
2329
+ if (__privateGet(this, _config).getPaused()) {
2330
+ __privateGet(this, _config).onPauseToggle();
2331
+ }
2332
+ __privateMethod(this, _Panel_instances, updatePauseButton_fn).call(this);
2333
+ __privateSet(this, _isWaitingForUserAnswer, false);
2334
+ __privateSet(this, _userAnswerResolver, null);
2335
+ __privateMethod(this, _Panel_instances, showInputArea_fn).call(this);
2336
+ }
2337
+ expand() {
2338
+ __privateMethod(this, _Panel_instances, expand_fn).call(this);
2339
+ }
2340
+ collapse() {
2341
+ __privateMethod(this, _Panel_instances, collapse_fn).call(this);
2123
2342
  }
2124
2343
  /**
2125
- * Listen to built-in events (one-time)
2344
+ * Update panel with semantic data - i18n handled internally
2126
2345
  */
2127
- once(event, handler) {
2128
- const wrappedHandler = /* @__PURE__ */ __name2((e) => {
2129
- const customEvent = e;
2130
- const params = customEvent.detail?.[0];
2131
- return handler(params);
2132
- }, "wrappedHandler");
2133
- this.addEventListener(event, wrappedHandler, { once: true });
2346
+ update(data) {
2347
+ const stepData = __privateMethod(this, _Panel_instances, toStepData_fn).call(this, data);
2348
+ __privateMethod(this, _Panel_instances, updateInternal_fn).call(this, stepData);
2134
2349
  }
2135
2350
  /**
2136
- * Emit built-in events
2351
+ * Dispose panel
2137
2352
  */
2138
- emit(event, ...args) {
2139
- const customEvent = new CustomEvent(event, { detail: args });
2140
- this.dispatchEvent(customEvent);
2141
- return;
2142
- }
2143
- };
2144
- __name2(_EventBus, "EventBus");
2145
- let EventBus = _EventBus;
2146
- const buses = /* @__PURE__ */ new Map();
2147
- function getEventBus(channel) {
2148
- if (buses.has(channel)) {
2149
- return buses.get(channel);
2150
- }
2151
- const bus = new EventBus();
2152
- buses.set(channel, bus);
2153
- return bus;
2154
- }
2155
- __name2(getEventBus, "getEventBus");
2156
- const InvokeErrorType = {
2157
- // Retryable
2158
- NETWORK_ERROR: "network_error",
2159
- // Network error, retry
2160
- RATE_LIMIT: "rate_limit",
2161
- // Rate limit, retry
2162
- SERVER_ERROR: "server_error",
2163
- // 5xx, retry
2164
- NO_TOOL_CALL: "no_tool_call",
2165
- // Model did not call tool
2166
- INVALID_TOOL_ARGS: "invalid_tool_args",
2167
- // Tool args don't match schema
2168
- TOOL_EXECUTION_ERROR: "tool_execution_error",
2169
- // Tool execution error
2170
- UNKNOWN: "unknown",
2171
- // Non-retryable
2172
- AUTH_ERROR: "auth_error",
2173
- // Authentication failed
2174
- CONTEXT_LENGTH: "context_length",
2175
- // Prompt too long
2176
- CONTENT_FILTER: "content_filter"
2177
- // Content filtered
2178
- };
2179
- const _InvokeError = class _InvokeError extends Error {
2180
- type;
2181
- retryable;
2182
- statusCode;
2183
- rawError;
2184
- constructor(type, message, rawError) {
2185
- super(message);
2186
- this.name = "InvokeError";
2187
- this.type = type;
2188
- this.retryable = this.isRetryable(type);
2189
- this.rawError = rawError;
2190
- }
2191
- isRetryable(type) {
2192
- const retryableTypes = [
2193
- InvokeErrorType.NETWORK_ERROR,
2194
- InvokeErrorType.RATE_LIMIT,
2195
- InvokeErrorType.SERVER_ERROR,
2196
- InvokeErrorType.NO_TOOL_CALL,
2197
- InvokeErrorType.INVALID_TOOL_ARGS,
2198
- InvokeErrorType.TOOL_EXECUTION_ERROR,
2199
- InvokeErrorType.UNKNOWN
2200
- ];
2201
- return retryableTypes.includes(type);
2353
+ dispose() {
2354
+ __privateSet(this, _isWaitingForUserAnswer, false);
2355
+ __privateMethod(this, _Panel_instances, stopHeaderUpdateLoop_fn).call(this);
2356
+ this.wrapper.remove();
2202
2357
  }
2203
- };
2204
- __name2(_InvokeError, "InvokeError");
2205
- let InvokeError = _InvokeError;
2206
- function zodToOpenAITool(name, tool2) {
2207
- return {
2208
- type: "function",
2209
- function: {
2210
- name,
2211
- description: tool2.description,
2212
- parameters: z.toJSONSchema(tool2.inputSchema, { target: "openapi-3.0" })
2358
+ }, __name2(_d, "_Panel"), _d);
2359
+ _wrapper = /* @__PURE__ */ new WeakMap();
2360
+ _indicator = /* @__PURE__ */ new WeakMap();
2361
+ _statusText = /* @__PURE__ */ new WeakMap();
2362
+ _historySection = /* @__PURE__ */ new WeakMap();
2363
+ _expandButton = /* @__PURE__ */ new WeakMap();
2364
+ _pauseButton = /* @__PURE__ */ new WeakMap();
2365
+ _stopButton = /* @__PURE__ */ new WeakMap();
2366
+ _inputSection = /* @__PURE__ */ new WeakMap();
2367
+ _taskInput = /* @__PURE__ */ new WeakMap();
2368
+ _state = /* @__PURE__ */ new WeakMap();
2369
+ _isExpanded = /* @__PURE__ */ new WeakMap();
2370
+ _config = /* @__PURE__ */ new WeakMap();
2371
+ _i18n = /* @__PURE__ */ new WeakMap();
2372
+ _userAnswerResolver = /* @__PURE__ */ new WeakMap();
2373
+ _isWaitingForUserAnswer = /* @__PURE__ */ new WeakMap();
2374
+ _headerUpdateTimer = /* @__PURE__ */ new WeakMap();
2375
+ _pendingHeaderText = /* @__PURE__ */ new WeakMap();
2376
+ _isAnimating = /* @__PURE__ */ new WeakMap();
2377
+ _Panel_instances = /* @__PURE__ */ new WeakSet();
2378
+ toStepData_fn = /* @__PURE__ */ __name(function(data) {
2379
+ switch (data.type) {
2380
+ case "thinking":
2381
+ return { type: "thinking", displayText: data.text ?? __privateGet(this, _i18n).t("ui.panel.thinking") };
2382
+ case "input":
2383
+ return { type: "input", displayText: data.task };
2384
+ case "question":
2385
+ return {
2386
+ type: "output",
2387
+ displayText: __privateGet(this, _i18n).t("ui.panel.question", { question: data.question })
2388
+ };
2389
+ case "userAnswer":
2390
+ return {
2391
+ type: "input",
2392
+ displayText: __privateGet(this, _i18n).t("ui.panel.userAnswer", { input: data.input })
2393
+ };
2394
+ case "retry":
2395
+ return { type: "retry", displayText: `retry-ing (${data.current} / ${data.max})` };
2396
+ case "error":
2397
+ return { type: "error", displayText: data.message };
2398
+ case "output":
2399
+ return { type: "output", displayText: data.text };
2400
+ case "completed":
2401
+ return { type: "completed", displayText: __privateGet(this, _i18n).t("ui.panel.taskCompleted") };
2402
+ case "toolExecuting":
2403
+ return {
2404
+ type: "tool_executing",
2405
+ toolName: data.toolName,
2406
+ toolArgs: data.args,
2407
+ displayText: __privateMethod(this, _Panel_instances, getToolExecutingText_fn).call(this, data.toolName, data.args)
2408
+ };
2409
+ case "toolCompleted": {
2410
+ const displayText = __privateMethod(this, _Panel_instances, getToolCompletedText_fn).call(this, data.toolName, data.args);
2411
+ if (!displayText) return { type: "tool_executing", displayText: "" };
2412
+ return {
2413
+ type: "tool_executing",
2414
+ toolName: data.toolName,
2415
+ toolArgs: data.args,
2416
+ toolResult: data.result,
2417
+ displayText,
2418
+ duration: data.duration
2419
+ };
2213
2420
  }
2214
- };
2215
- }
2216
- __name2(zodToOpenAITool, "zodToOpenAITool");
2217
- function lenientParseMacroToolCall(responseData, inputSchema) {
2218
- const choice = responseData.choices?.[0];
2219
- if (!choice) {
2220
- throw new InvokeError(InvokeErrorType.UNKNOWN, "No choices in response", responseData);
2221
2421
  }
2222
- switch (choice.finish_reason) {
2223
- case "tool_calls":
2224
- case "function_call":
2225
- // gemini
2226
- case "stop":
2227
- break;
2228
- case "length":
2229
- throw new InvokeError(
2230
- InvokeErrorType.CONTEXT_LENGTH,
2231
- "Response truncated: max tokens reached"
2232
- );
2233
- case "content_filter":
2234
- throw new InvokeError(InvokeErrorType.CONTENT_FILTER, "Content filtered by safety system");
2422
+ }, "#toStepData");
2423
+ getToolExecutingText_fn = /* @__PURE__ */ __name(function(toolName, args) {
2424
+ switch (toolName) {
2425
+ case "click_element_by_index":
2426
+ return __privateGet(this, _i18n).t("ui.tools.clicking", { index: args.index });
2427
+ case "input_text":
2428
+ return __privateGet(this, _i18n).t("ui.tools.inputting", { index: args.index });
2429
+ case "select_dropdown_option":
2430
+ return __privateGet(this, _i18n).t("ui.tools.selecting", { text: args.text });
2431
+ case "scroll":
2432
+ return __privateGet(this, _i18n).t("ui.tools.scrolling");
2433
+ case "wait":
2434
+ return __privateGet(this, _i18n).t("ui.tools.waiting", { seconds: args.seconds });
2435
+ case "done":
2436
+ return __privateGet(this, _i18n).t("ui.tools.done");
2235
2437
  default:
2236
- throw new InvokeError(
2237
- InvokeErrorType.UNKNOWN,
2238
- `Unexpected finish_reason: ${choice.finish_reason}`
2239
- );
2438
+ return __privateGet(this, _i18n).t("ui.tools.executing", { toolName });
2240
2439
  }
2241
- const actionSchema = inputSchema.shape.action;
2242
- if (!actionSchema) {
2243
- throw new Error('inputSchema must have an "action" field');
2440
+ }, "#getToolExecutingText");
2441
+ getToolCompletedText_fn = /* @__PURE__ */ __name(function(toolName, args) {
2442
+ switch (toolName) {
2443
+ case "click_element_by_index":
2444
+ return __privateGet(this, _i18n).t("ui.tools.clicked", { index: args.index });
2445
+ case "input_text":
2446
+ return __privateGet(this, _i18n).t("ui.tools.inputted", { text: args.text });
2447
+ case "select_dropdown_option":
2448
+ return __privateGet(this, _i18n).t("ui.tools.selected", { text: args.text });
2449
+ case "scroll":
2450
+ return __privateGet(this, _i18n).t("ui.tools.scrolled");
2451
+ case "wait":
2452
+ return __privateGet(this, _i18n).t("ui.tools.waited");
2453
+ case "done":
2454
+ return null;
2455
+ default:
2456
+ return null;
2244
2457
  }
2245
- let arg = null;
2246
- const toolCall = choice.message?.tool_calls?.[0]?.function;
2247
- arg = toolCall?.arguments ?? null;
2248
- if (arg && toolCall.name !== "AgentOutput") {
2249
- console.log(chalk.yellow("lenientParseMacroToolCall: #1 fixing incorrect tool call"));
2250
- let tmpArg;
2251
- try {
2252
- tmpArg = JSON.parse(arg);
2253
- } catch (error2) {
2254
- throw new InvokeError(
2255
- InvokeErrorType.INVALID_TOOL_ARGS,
2256
- "Failed to parse tool arguments as JSON",
2257
- error2
2258
- );
2458
+ }, "#getToolCompletedText");
2459
+ updateInternal_fn = /* @__PURE__ */ __name(function(stepData) {
2460
+ if (!stepData.displayText) return;
2461
+ const step = __privateGet(this, _state).addStep(stepData);
2462
+ const headerText = truncate(step.displayText, 20);
2463
+ __privateSet(this, _pendingHeaderText, headerText);
2464
+ __privateMethod(this, _Panel_instances, updateStatusIndicator_fn).call(this, step.type);
2465
+ __privateMethod(this, _Panel_instances, updateHistory_fn).call(this);
2466
+ if (step.type === "completed" || step.type === "error") {
2467
+ if (!__privateGet(this, _isExpanded)) {
2468
+ __privateMethod(this, _Panel_instances, expand_fn).call(this);
2259
2469
  }
2260
- arg = JSON.stringify({ action: { [toolCall.name]: tmpArg } });
2261
- }
2262
- if (!arg) {
2263
- arg = choice.message?.content.trim() || null;
2264
- }
2265
- if (!arg) {
2266
- throw new InvokeError(
2267
- InvokeErrorType.NO_TOOL_CALL,
2268
- "No tool call or content found in response",
2269
- responseData
2270
- );
2271
- }
2272
- let parsedArgs;
2273
- try {
2274
- parsedArgs = JSON.parse(arg);
2275
- } catch (error2) {
2276
- throw new InvokeError(
2277
- InvokeErrorType.INVALID_TOOL_ARGS,
2278
- "Failed to parse tool arguments as JSON",
2279
- error2
2280
- );
2281
2470
  }
2282
- if (parsedArgs.action || parsedArgs.evaluation_previous_goal || parsedArgs.next_goal) {
2283
- if (!parsedArgs.action) {
2284
- console.log(chalk.yellow("lenientParseMacroToolCall: #2 fixing incorrect tool call"));
2285
- parsedArgs.action = {
2286
- wait: { seconds: 1 }
2287
- };
2288
- }
2289
- } else if (parsedArgs.type && parsedArgs.function) {
2290
- if (parsedArgs.function.name !== "AgentOutput")
2291
- throw new InvokeError(
2292
- InvokeErrorType.INVALID_TOOL_ARGS,
2293
- `Expected function name "AgentOutput", got "${parsedArgs.function.name}"`,
2294
- null
2295
- );
2296
- console.log(chalk.yellow("lenientParseMacroToolCall: #3 fixing incorrect tool call"));
2297
- parsedArgs = parsedArgs.function.arguments;
2298
- } else if (parsedArgs.name && parsedArgs.arguments) {
2299
- if (parsedArgs.name !== "AgentOutput")
2300
- throw new InvokeError(
2301
- InvokeErrorType.INVALID_TOOL_ARGS,
2302
- `Expected function name "AgentOutput", got "${parsedArgs.name}"`,
2303
- null
2304
- );
2305
- console.log(chalk.yellow("lenientParseMacroToolCall: #4 fixing incorrect tool call"));
2306
- parsedArgs = parsedArgs.arguments;
2471
+ if (__privateMethod(this, _Panel_instances, shouldShowInputArea_fn).call(this)) {
2472
+ __privateMethod(this, _Panel_instances, showInputArea_fn).call(this);
2307
2473
  } else {
2308
- console.log(chalk.yellow("lenientParseMacroToolCall: #5 fixing incorrect tool call"));
2309
- parsedArgs = { action: parsedArgs };
2474
+ __privateMethod(this, _Panel_instances, hideInputArea_fn).call(this);
2310
2475
  }
2311
- if (typeof parsedArgs === "string") {
2312
- console.log(chalk.yellow("lenientParseMacroToolCall: #6 fixing incorrect tool call"));
2313
- try {
2314
- parsedArgs = JSON.parse(parsedArgs);
2315
- } catch (error2) {
2316
- throw new InvokeError(
2317
- InvokeErrorType.INVALID_TOOL_ARGS,
2318
- "Failed to parse nested tool arguments as JSON",
2319
- error2
2320
- );
2321
- }
2476
+ }, "#updateInternal");
2477
+ togglePause_fn = /* @__PURE__ */ __name(function() {
2478
+ const paused2 = __privateGet(this, _config).onPauseToggle();
2479
+ __privateMethod(this, _Panel_instances, updatePauseButton_fn).call(this);
2480
+ if (paused2) {
2481
+ __privateGet(this, _statusText).textContent = __privateGet(this, _i18n).t("ui.panel.paused");
2482
+ __privateMethod(this, _Panel_instances, updateStatusIndicator_fn).call(this, "thinking");
2483
+ } else {
2484
+ __privateGet(this, _statusText).textContent = __privateGet(this, _i18n).t("ui.panel.continueExecution");
2485
+ __privateMethod(this, _Panel_instances, updateStatusIndicator_fn).call(this, "tool_executing");
2322
2486
  }
2323
- const validation = inputSchema.safeParse(parsedArgs);
2324
- if (validation.success) {
2325
- return validation.data;
2487
+ }, "#togglePause");
2488
+ updatePauseButton_fn = /* @__PURE__ */ __name(function() {
2489
+ const paused2 = __privateGet(this, _config).getPaused();
2490
+ if (paused2) {
2491
+ __privateGet(this, _pauseButton).textContent = "▶";
2492
+ __privateGet(this, _pauseButton).title = __privateGet(this, _i18n).t("ui.panel.continue");
2493
+ __privateGet(this, _pauseButton).classList.add(styles$1.paused);
2326
2494
  } else {
2327
- const action = parsedArgs.action ?? {};
2328
- const actionName = Object.keys(action)[0] || "unknown";
2329
- const actionArgs = JSON.stringify(action[actionName] || "unknown");
2330
- throw new InvokeError(
2331
- InvokeErrorType.INVALID_TOOL_ARGS,
2332
- `Tool arguments validation failed: action "${actionName}" with args ${actionArgs}`,
2333
- validation.error
2334
- );
2495
+ __privateGet(this, _pauseButton).textContent = "⏸︎";
2496
+ __privateGet(this, _pauseButton).title = __privateGet(this, _i18n).t("ui.panel.pause");
2497
+ __privateGet(this, _pauseButton).classList.remove(styles$1.paused);
2335
2498
  }
2336
- }
2337
- __name2(lenientParseMacroToolCall, "lenientParseMacroToolCall");
2338
- function modelPatch(body) {
2339
- const model = body.model || "";
2340
- if (model.toLowerCase().startsWith("claude")) {
2341
- body.tool_choice = { type: "tool", name: "AgentOutput" };
2342
- body.thinking = { type: "disabled" };
2499
+ }, "#updatePauseButton");
2500
+ stopAgent_fn = /* @__PURE__ */ __name(function() {
2501
+ __privateMethod(this, _Panel_instances, updateInternal_fn).call(this, {
2502
+ type: "error",
2503
+ displayText: __privateGet(this, _i18n).t("ui.panel.taskTerminated")
2504
+ });
2505
+ __privateGet(this, _config).onStop();
2506
+ }, "#stopAgent");
2507
+ submitTask_fn = /* @__PURE__ */ __name(function() {
2508
+ const input2 = __privateGet(this, _taskInput).value.trim();
2509
+ if (!input2) return;
2510
+ __privateMethod(this, _Panel_instances, hideInputArea_fn).call(this);
2511
+ if (__privateGet(this, _isWaitingForUserAnswer)) {
2512
+ __privateMethod(this, _Panel_instances, handleUserAnswer_fn).call(this, input2);
2513
+ } else {
2514
+ __privateGet(this, _config).onExecuteTask(input2);
2343
2515
  }
2344
- if (model.toLowerCase().includes("grok")) {
2345
- console.log("Applying Grok patch: removing tool_choice");
2346
- delete body.tool_choice;
2347
- console.log("Applying Grok patch: disable reasoning and thinking");
2348
- body.thinking = { type: "disabled", effort: "minimal" };
2349
- body.reasoning = { enabled: false, effort: "low" };
2350
- }
2351
- return body;
2352
- }
2353
- __name2(modelPatch, "modelPatch");
2354
- const _OpenAIClient = class _OpenAIClient {
2355
- config;
2356
- constructor(config) {
2357
- this.config = config;
2358
- }
2359
- async invoke(messages, tools2, abortSignal) {
2360
- const openaiTools = Object.entries(tools2).map(([name, tool22]) => zodToOpenAITool(name, tool22));
2361
- let response;
2362
- try {
2363
- response = await fetch(`${this.config.baseURL}/chat/completions`, {
2364
- method: "POST",
2365
- headers: {
2366
- "Content-Type": "application/json",
2367
- Authorization: `Bearer ${this.config.apiKey}`
2368
- },
2369
- body: JSON.stringify(
2370
- modelPatch({
2371
- model: this.config.model,
2372
- temperature: this.config.temperature,
2373
- max_tokens: this.config.maxTokens,
2374
- messages,
2375
- tools: openaiTools,
2376
- // tool_choice: 'required',
2377
- tool_choice: { type: "function", function: { name: "AgentOutput" } },
2378
- // model specific params
2379
- // reasoning_effort: 'minimal',
2380
- // verbosity: 'low',
2381
- parallel_tool_calls: false
2382
- })
2383
- ),
2384
- signal: abortSignal
2385
- });
2386
- } catch (error2) {
2387
- throw new InvokeError(InvokeErrorType.NETWORK_ERROR, "Network request failed", error2);
2388
- }
2389
- if (!response.ok) {
2390
- const errorData = await response.json().catch();
2391
- const errorMessage = errorData.error?.message || response.statusText;
2392
- if (response.status === 401 || response.status === 403) {
2393
- throw new InvokeError(
2394
- InvokeErrorType.AUTH_ERROR,
2395
- `Authentication failed: ${errorMessage}`,
2396
- errorData
2397
- );
2398
- }
2399
- if (response.status === 429) {
2400
- throw new InvokeError(
2401
- InvokeErrorType.RATE_LIMIT,
2402
- `Rate limit exceeded: ${errorMessage}`,
2403
- errorData
2404
- );
2405
- }
2406
- if (response.status >= 500) {
2407
- throw new InvokeError(
2408
- InvokeErrorType.SERVER_ERROR,
2409
- `Server error: ${errorMessage}`,
2410
- errorData
2411
- );
2412
- }
2413
- throw new InvokeError(
2414
- InvokeErrorType.UNKNOWN,
2415
- `HTTP ${response.status}: ${errorMessage}`,
2416
- errorData
2417
- );
2418
- }
2419
- const data = await response.json();
2420
- const tool2 = tools2.AgentOutput;
2421
- const macroToolInput = lenientParseMacroToolCall(data, tool2.inputSchema);
2422
- let toolResult;
2423
- try {
2424
- toolResult = await tool2.execute(macroToolInput);
2425
- } catch (e) {
2426
- throw new InvokeError(
2427
- InvokeErrorType.TOOL_EXECUTION_ERROR,
2428
- `Tool execution failed: ${e.message}`,
2429
- e
2430
- );
2431
- }
2432
- return {
2433
- toolCall: {
2434
- // id: toolCall.id,
2435
- name: "AgentOutput",
2436
- args: macroToolInput
2437
- },
2438
- toolResult,
2439
- usage: {
2440
- promptTokens: data.usage?.prompt_tokens ?? 0,
2441
- completionTokens: data.usage?.completion_tokens ?? 0,
2442
- totalTokens: data.usage?.total_tokens ?? 0,
2443
- cachedTokens: data.usage?.prompt_tokens_details?.cached_tokens,
2444
- reasoningTokens: data.usage?.completion_tokens_details?.reasoning_tokens
2445
- },
2446
- rawResponse: data
2447
- };
2448
- }
2449
- };
2450
- __name2(_OpenAIClient, "OpenAIClient");
2451
- let OpenAIClient = _OpenAIClient;
2452
- const _LLM = class _LLM {
2453
- constructor(config, id) {
2454
- __publicField(this, "config");
2455
- __publicField(this, "id");
2456
- __publicField(this, "client");
2457
- __privateAdd(this, _bus);
2458
- this.config = parseLLMConfig(config);
2459
- this.id = id;
2460
- __privateSet(this, _bus, getEventBus(id));
2461
- this.client = new OpenAIClient({
2462
- model: this.config.model,
2463
- apiKey: this.config.apiKey,
2464
- baseURL: this.config.baseURL,
2465
- temperature: this.config.temperature,
2466
- maxTokens: this.config.maxTokens
2467
- });
2468
- }
2469
- /**
2470
- * - call llm api *once*
2471
- * - invoke tool call *once*
2472
- * - return the result of the tool
2473
- */
2474
- async invoke(messages, tools2, abortSignal) {
2475
- return await withRetry(
2476
- async () => {
2477
- const result2 = await this.client.invoke(messages, tools2, abortSignal);
2478
- return result2;
2479
- },
2480
- // retry settings
2481
- {
2482
- maxRetries: this.config.maxRetries,
2483
- onRetry: /* @__PURE__ */ __name2((retries) => {
2484
- __privateGet(this, _bus).emit("panel:update", {
2485
- type: "retry",
2486
- displayText: `retry-ing (${retries} / ${this.config.maxRetries})`
2487
- });
2488
- }, "onRetry"),
2489
- onError: /* @__PURE__ */ __name2((error2, withRetry2) => {
2490
- __privateGet(this, _bus).emit("panel:update", {
2491
- type: "error",
2492
- displayText: `step failed: ${error2.message}`
2493
- });
2494
- }, "onError")
2495
- }
2496
- );
2497
- }
2498
- };
2499
- _bus = new WeakMap();
2500
- __name2(_LLM, "LLM");
2501
- let LLM = _LLM;
2502
- async function withRetry(fn, settings) {
2503
- let retries = 0;
2504
- let lastError = null;
2505
- while (retries <= settings.maxRetries) {
2506
- if (retries > 0) {
2507
- settings.onRetry(retries);
2508
- await new Promise((resolve) => setTimeout(resolve, 100));
2509
- }
2510
- try {
2511
- return await fn();
2512
- } catch (error2) {
2513
- console.error(error2);
2514
- settings.onError(error2, retries < settings.maxRetries);
2515
- if (error2?.name === "AbortError") throw error2;
2516
- if (error2 instanceof InvokeError && !error2.retryable) throw error2;
2517
- lastError = error2;
2518
- retries++;
2519
- await new Promise((resolve) => setTimeout(resolve, 100));
2520
- }
2521
- }
2522
- throw lastError;
2523
- }
2524
- __name2(withRetry, "withRetry");
2525
- const SYSTEM_PROMPT = 'You are an AI agent designed to operate in an iterative loop to automate browser tasks. Your ultimate goal is accomplishing the task provided in <user_request>.\n\n<intro>\nYou excel at following tasks:\n1. Navigating complex websites and extracting precise information\n2. Automating form submissions and interactive web actions\n3. Gathering and saving information \n4. Operate effectively in an agent loop\n5. Efficiently performing diverse web tasks\n</intro>\n\n<language_settings>\n- Default working language: **中文**\n- Use the language that user is using. Return in user\'s language.\n</language_settings>\n\n<input>\nAt every step, your input will consist of: \n1. <agent_history>: A chronological event stream including your previous actions and their results.\n2. <agent_state>: Current <user_request> and <step_info>.\n3. <browser_state>: Current URL, interactive elements indexed for actions, and visible page content.\n</input>\n\n<agent_history>\nAgent history will be given as a list of step information as follows:\n\n<step_{step_number}>:\nEvaluation of Previous Step: Assessment of last action\nMemory: Your memory of this step\nNext Goal: Your goal for this step\nAction Results: Your actions and their results\n</step_{step_number}>\n\nand system messages wrapped in <sys> tag.\n</agent_history>\n\n<user_request>\nUSER REQUEST: This is your ultimate objective and always remains visible.\n- This has the highest priority. Make the user happy.\n- If the user request is very specific - then carefully follow each step and dont skip or hallucinate steps.\n- If the task is open ended you can plan yourself how to get it done.\n</user_request>\n\n<browser_state>\n1. Browser State will be given as:\n\nCurrent URL: URL of the page you are currently viewing.\nInteractive Elements: All interactive elements will be provided in format as [index]<type>text</type> where\n- index: Numeric identifier for interaction\n- type: HTML element type (button, input, etc.)\n- text: Element description\n\nExamples:\n[33]<div>User form</div>\n\\t*[35]<button aria-label=\'Submit form\'>Submit</button>\n\nNote that:\n- Only elements with numeric indexes in [] are interactive\n- (stacked) indentation (with \\t) is important and means that the element is a (html) child of the element above (with a lower index)\n- Elements tagged with `*[` are the new clickable elements that appeared on the website since the last step - if url has not changed.\n- Pure text elements without [] are not interactive.\n</browser_state>\n\n<browser_rules>\nStrictly follow these rules while using the browser and navigating the web:\n- Only interact with elements that have a numeric [index] assigned.\n- Only use indexes that are explicitly provided.\n- If the page changes after, for example, an input text action, analyze if you need to interact with new elements, e.g. selecting the right option from the list.\n- By default, only elements in the visible viewport are listed. Use scrolling actions if you suspect relevant content is offscreen which you need to interact with. Scroll ONLY if there are more pixels below or above the page.\n- You can scroll by a specific number of pages using the num_pages parameter (e.g., 0.5 for half page, 2.0 for two pages).\n- All the elements that are scrollable are marked with `data-scrollable` attribute. Including the scrollable distance in every directions. You can scroll *the element* in case some area are overflowed.\n- If a captcha appears, tell user you can not solve captcha. finished the task and ask user to solve it.\n- If expected elements are missing, try scrolling, or navigating back.\n- If the page is not fully loaded, use the `wait` action.\n- Do not repeat one action for more than 3 times unless some conditions changed.\n- If you fill an input field and your action sequence is interrupted, most often something changed e.g. suggestions popped up under the field.\n- If the <user_request> includes specific page information such as product type, rating, price, location, etc., try to apply filters to be more efficient.\n- The <user_request> is the ultimate goal. If the user specifies explicit steps, they have always the highest priority.\n- If you input_text into a field, you might need to press enter, click the search button, or select from dropdown for completion.\n- Don\'t login into a page if you don\'t have to. Don\'t login if you don\'t have the credentials. \n- There are 2 types of tasks always first think which type of request you are dealing with:\n1. Very specific step by step instructions:\n- Follow them as very precise and don\'t skip steps. Try to complete everything as requested.\n2. Open ended tasks. Plan yourself, be creative in achieving them.\n- If you get stuck e.g. with logins or captcha in open-ended tasks you can re-evaluate the task and try alternative ways, e.g. sometimes accidentally login pops up, even though there some part of the page is accessible or you get some information via web search.\n</browser_rules>\n\n<capability>\n- You can only handle single page app. Do not jump out of current page.\n- Do not click on link if it will open in a new page (etc. <a target="_blank">)\n- It is ok to fail the task.\n - User can be wrong. If the request of user is not achievable, inappropriate or you do not have enough information or tools to achieve it. Tell user to make a better request.\n - Webpage can be broken. All webpages or apps have bugs. Some bug will make it hard for your job. It\'s encouraged to tell user the problem of current page. Your feedbacks (including failing) are valuable for user.\n - Trying to hard can be harmful. Repeating some action back and forth or pushing for a complex procedure with little knowledge can cause unwanted result and harmful side-effects. User would rather you to complete the task with a fail.\n- If you are not clear about the request or steps. `ask_user` to clarify it.\n- If you do not have knowledge for the current webpage or task. You must require user to give specific instructions and detailed steps.\n</capability>\n\n<task_completion_rules>\nYou must call the `done` action in one of three cases:\n- When you have fully completed the USER REQUEST.\n- When you reach the final allowed step (`max_steps`), even if the task is incomplete.\n- When you feel stuck or unable to solve user request. Or user request is not clear or contains inappropriate content.\n- If it is ABSOLUTELY IMPOSSIBLE to continue.\n\nThe `done` action is your opportunity to terminate and share your findings with the user.\n- Set `success` to `true` only if the full USER REQUEST has been completed with no missing components.\n- If any part of the request is missing, incomplete, or uncertain, set `success` to `false`.\n- You can use the `text` field of the `done` action to communicate your findings and to provide a coherent reply to the user and fulfill the USER REQUEST.\n- You are ONLY ALLOWED to call `done` as a single action. Don\'t call it together with other actions.\n- If the user asks for specified format, such as "return JSON with following structure", "return a list of format...", MAKE sure to use the right format in your answer.\n- If the user asks for a structured output, your `done` action\'s schema may be modified. Take this schema into account when solving the task!\n</task_completion_rules>\n\n<reasoning_rules>\nExhibit the following reasoning patterns to successfully achieve the <user_request>:\n\n- Reason about <agent_history> to track progress and context toward <user_request>.\n- Analyze the most recent "Next Goal" and "Action Result" in <agent_history> and clearly state what you previously tried to achieve.\n- Analyze all relevant items in <agent_history> and <browser_state> to understand your state.\n- Explicitly judge success/failure/uncertainty of the last action. Never assume an action succeeded just because it appears to be executed in your last step in <agent_history>. If the expected change is missing, mark the last action as failed (or uncertain) and plan a recovery.\n- Analyze whether you are stuck, e.g. when you repeat the same actions multiple times without any progress. Then consider alternative approaches e.g. scrolling for more context or ask user for help.\n- `ask_user` for help if you have any difficulty. Users want to be kept in the loop.\n- If you see information relevant to <user_request>, plan saving the information to memory.\n- Always reason about the <user_request>. Make sure to carefully analyze the specific steps and information required. E.g. specific filters, specific form fields, specific information to search. Make sure to always compare the current trajectory with the user request and think carefully if thats how the user requested it.\n</reasoning_rules>\n\n<examples>\nHere are examples of good output patterns. Use them as reference but never copy them directly.\n\n<evaluation_examples>\n- Positive Examples:\n"evaluation_previous_goal": "Successfully navigated to the product page and found the target information. Verdict: Success"\n"evaluation_previous_goal": "Clicked the login button and user authentication form appeared. Verdict: Success"\n</evaluation_examples>\n\n<memory_examples>\n"memory": "Found many pending reports that need to be analyzed in the main page. Successfully processed the first 2 reports on quarterly sales data and moving on to inventory analysis and customer feedback reports."\n</memory_examples>\n\n<next_goal_examples>\n"next_goal": "Click on the \'Add to Cart\' button to proceed with the purchase flow."\n"next_goal": "Extract details from the first item on the page."\n</next_goal_examples>\n</examples>\n\n<output>\nYou must ALWAYS respond with a valid JSON in this exact format:\n\n{\n "evaluation_previous_goal": "Concise one-sentence analysis of your last action. Clearly state success, failure, or uncertain.",\n "memory": "1-3 concise sentences of specific memory of this step and overall progress. You should put here everything that will help you track progress in future steps. Like counting pages visited, items found, etc.",\n "next_goal": "State the next immediate goal and action to achieve it, in one clear sentence."\n "action":{"one_action_name": {// action-specific parameter}}\n}\n</output>\n';
2526
- async function waitUntil(check, timeout = 60 * 601e3) {
2527
- if (check()) return true;
2528
- return new Promise((resolve, reject) => {
2529
- const start = Date.now();
2530
- const interval = setInterval(() => {
2531
- if (check()) {
2532
- clearInterval(interval);
2533
- resolve(true);
2534
- } else if (Date.now() - start > timeout) {
2535
- clearInterval(interval);
2536
- reject(new Error("Timeout waiting for condition to become true"));
2537
- }
2538
- }, 100);
2539
- });
2540
- }
2541
- __name2(waitUntil, "waitUntil");
2542
- async function waitFor(seconds) {
2543
- await new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
2544
- }
2545
- __name2(waitFor, "waitFor");
2546
- function truncate(text, maxLength) {
2547
- if (text.length > maxLength) {
2548
- return text.substring(0, maxLength) + "...";
2549
- }
2550
- return text;
2551
- }
2552
- __name2(truncate, "truncate");
2553
- function trimLines(text) {
2554
- return text.split("\n").map((line) => line.trim()).join("\n");
2555
- }
2556
- __name2(trimLines, "trimLines");
2557
- function randomID(existingIDs) {
2558
- let id = Math.random().toString(36).substring(2, 11);
2559
- if (!existingIDs) {
2560
- return id;
2561
- }
2562
- const MAX_TRY = 1e3;
2563
- let tryCount = 0;
2564
- while (existingIDs.includes(id)) {
2565
- id = Math.random().toString(36).substring(2, 11);
2566
- tryCount++;
2567
- if (tryCount > MAX_TRY) {
2568
- throw new Error("randomID: too many try");
2569
- }
2570
- }
2571
- return id;
2572
- }
2573
- __name2(randomID, "randomID");
2574
- if (!window.__PAGE_AGENT_IDS__) {
2575
- window.__PAGE_AGENT_IDS__ = [];
2576
- }
2577
- const ids = window.__PAGE_AGENT_IDS__;
2578
- function uid() {
2579
- const id = randomID(ids);
2580
- ids.push(id);
2581
- return id;
2582
- }
2583
- __name2(uid, "uid");
2584
- function tool(options) {
2585
- return options;
2586
- }
2587
- __name2(tool, "tool");
2588
- const tools = /* @__PURE__ */ new Map();
2589
- tools.set(
2590
- "done",
2591
- tool({
2592
- description: "Complete task - provide a summary of results for the user. Set success=True if task completed successfully, false otherwise. Text should be your response to the user summarizing results.",
2593
- inputSchema: zod.object({
2594
- text: zod.string(),
2595
- success: zod.boolean().default(true)
2596
- }),
2597
- execute: /* @__PURE__ */ __name2(async function(input2) {
2598
- return Promise.resolve("Task completed");
2599
- }, "execute")
2600
- })
2601
- );
2602
- tools.set(
2603
- "wait",
2604
- tool({
2605
- description: "Wait for x seconds. default 1s (max 10 seconds, min 1 second). This can be used to wait until the page or data is fully loaded.",
2606
- inputSchema: zod.object({
2607
- seconds: zod.number().min(1).max(10).default(1)
2608
- }),
2609
- execute: /* @__PURE__ */ __name2(async function(input2) {
2610
- const lastTimeUpdate = await this.pageController.getLastUpdateTime();
2611
- const actualWaitTime = Math.max(0, input2.seconds - (Date.now() - lastTimeUpdate) / 1e3);
2612
- console.log(`actualWaitTime: ${actualWaitTime} seconds`);
2613
- await waitFor(actualWaitTime);
2614
- return `✅ Waited for ${input2.seconds} seconds.`;
2615
- }, "execute")
2616
- })
2617
- );
2618
- tools.set(
2619
- "ask_user",
2620
- tool({
2621
- description: "Ask the user a question and wait for their answer. Use this if you need more information or clarification.",
2622
- inputSchema: zod.object({
2623
- question: zod.string()
2624
- }),
2625
- execute: /* @__PURE__ */ __name2(async function(input2) {
2626
- const answer = await this.panel.askUser(input2.question);
2627
- return `✅ Received user answer: ${answer}`;
2628
- }, "execute")
2629
- })
2630
- );
2631
- tools.set(
2632
- "click_element_by_index",
2633
- tool({
2634
- description: "Click element by index",
2635
- inputSchema: zod.object({
2636
- index: zod.int().min(0)
2637
- }),
2638
- execute: /* @__PURE__ */ __name2(async function(input2) {
2639
- const result2 = await this.pageController.clickElement(input2.index);
2640
- return result2.message;
2641
- }, "execute")
2642
- })
2643
- );
2644
- tools.set(
2645
- "input_text",
2646
- tool({
2647
- description: "Click and input text into a input interactive element",
2648
- inputSchema: zod.object({
2649
- index: zod.int().min(0),
2650
- text: zod.string()
2651
- }),
2652
- execute: /* @__PURE__ */ __name2(async function(input2) {
2653
- const result2 = await this.pageController.inputText(input2.index, input2.text);
2654
- return result2.message;
2655
- }, "execute")
2656
- })
2657
- );
2658
- tools.set(
2659
- "select_dropdown_option",
2660
- tool({
2661
- description: "Select dropdown option for interactive element index by the text of the option you want to select",
2662
- inputSchema: zod.object({
2663
- index: zod.int().min(0),
2664
- text: zod.string()
2665
- }),
2666
- execute: /* @__PURE__ */ __name2(async function(input2) {
2667
- const result2 = await this.pageController.selectOption(input2.index, input2.text);
2668
- return result2.message;
2669
- }, "execute")
2670
- })
2671
- );
2672
- tools.set(
2673
- "scroll",
2674
- tool({
2675
- description: "Scroll the page by specified number of pages (set down=True to scroll down, down=False to scroll up, num_pages=number of pages to scroll like 0.5 for half page, 1.0 for one page, etc.). Optional index parameter to scroll within a specific element or its scroll container (works well for dropdowns and custom UI components). Optional pixels parameter to scroll by a specific number of pixels instead of pages.",
2676
- inputSchema: zod.object({
2677
- down: zod.boolean().default(true),
2678
- num_pages: zod.number().min(0).max(10).optional().default(0.1),
2679
- pixels: zod.number().int().min(0).optional(),
2680
- index: zod.number().int().min(0).optional()
2681
- }),
2682
- execute: /* @__PURE__ */ __name2(async function(input2) {
2683
- const result2 = await this.pageController.scroll({
2684
- ...input2,
2685
- numPages: input2.num_pages
2686
- });
2687
- return result2.message;
2688
- }, "execute")
2689
- })
2690
- );
2691
- tools.set(
2692
- "scroll_horizontally",
2693
- tool({
2694
- description: "Scroll the page or element horizontally (set right=True to scroll right, right=False to scroll left, pixels=number of pixels to scroll). Optional index parameter to scroll within a specific element or its scroll container (works well for wide tables).",
2695
- inputSchema: zod.object({
2696
- right: zod.boolean().default(true),
2697
- pixels: zod.number().int().min(0),
2698
- index: zod.number().int().min(0).optional()
2699
- }),
2700
- execute: /* @__PURE__ */ __name2(async function(input2) {
2701
- const result2 = await this.pageController.scrollHorizontally(input2);
2702
- return result2.message;
2703
- }, "execute")
2704
- })
2705
- );
2706
- tools.set(
2707
- "execute_javascript",
2708
- tool({
2709
- description: "Execute JavaScript code on the current page. Supports async/await syntax. Use with caution!",
2710
- inputSchema: zod.object({
2711
- script: zod.string()
2712
- }),
2713
- execute: /* @__PURE__ */ __name2(async function(input2) {
2714
- const result2 = await this.pageController.executeJavascript(input2.script);
2715
- return result2.message;
2716
- }, "execute")
2717
- })
2718
- );
2719
- const _UIState = class _UIState {
2720
- steps = [];
2721
- currentStep = null;
2722
- status = "idle";
2723
- stepCounter = 0;
2724
- addStep(stepData) {
2725
- const step = {
2726
- id: this.generateId(),
2727
- stepNumber: ++this.stepCounter,
2728
- timestamp: /* @__PURE__ */ new Date(),
2729
- ...stepData
2730
- };
2731
- this.steps.push(step);
2732
- this.currentStep = step;
2733
- this.updateStatus(step.type);
2734
- return step;
2735
- }
2736
- updateCurrentStep(updates) {
2737
- if (!this.currentStep) return null;
2738
- Object.assign(this.currentStep, updates);
2739
- return this.currentStep;
2740
- }
2741
- getCurrentStep() {
2742
- return this.currentStep;
2743
- }
2744
- getAllSteps() {
2745
- return [...this.steps];
2746
- }
2747
- getStatus() {
2748
- return this.status;
2749
- }
2750
- reset() {
2751
- this.steps = [];
2752
- this.currentStep = null;
2753
- this.status = "idle";
2754
- this.stepCounter = 0;
2755
- }
2756
- updateStatus(stepType) {
2757
- switch (stepType) {
2758
- case "thinking":
2759
- case "tool_executing":
2760
- case "output":
2761
- case "input":
2762
- case "retry":
2763
- this.status = "running";
2764
- break;
2765
- case "completed":
2766
- this.status = "completed";
2767
- break;
2768
- case "error":
2769
- this.status = "error";
2770
- break;
2771
- }
2772
- }
2773
- generateId() {
2774
- return `step_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
2775
- }
2776
- };
2777
- __name2(_UIState, "UIState");
2778
- let UIState = _UIState;
2779
- const wrapper$1 = "_wrapper_1j0ct_1";
2780
- const background = "_background_1j0ct_39";
2781
- const header = "_header_1j0ct_99";
2782
- const pulse = "_pulse_1j0ct_1";
2783
- const retryPulse = "_retryPulse_1j0ct_1";
2784
- const statusTextFadeOut = "_statusTextFadeOut_1j0ct_1";
2785
- const statusTextFadeIn = "_statusTextFadeIn_1j0ct_1";
2786
- const statusSection = "_statusSection_1j0ct_121";
2787
- const indicator = "_indicator_1j0ct_128";
2788
- const thinking = "_thinking_1j0ct_137";
2789
- const tool_executing = "_tool_executing_1j0ct_142";
2790
- const retry = "_retry_1j0ct_147";
2791
- const completed = "_completed_1j0ct_153";
2792
- const input = "_input_1j0ct_154";
2793
- const output = "_output_1j0ct_155";
2794
- const error = "_error_1j0ct_160";
2795
- const statusText = "_statusText_1j0ct_166";
2796
- const fadeOut = "_fadeOut_1j0ct_178";
2797
- const fadeIn = "_fadeIn_1j0ct_182";
2798
- const controls = "_controls_1j0ct_188";
2799
- const controlButton = "_controlButton_1j0ct_193";
2800
- const pauseButton = "_pauseButton_1j0ct_212";
2801
- const paused = "_paused_1j0ct_214";
2802
- const stopButton = "_stopButton_1j0ct_224";
2803
- const historySectionWrapper = "_historySectionWrapper_1j0ct_258";
2804
- const shimmer = "_shimmer_1j0ct_1";
2805
- const celebrate = "_celebrate_1j0ct_1";
2806
- const expanded = "_expanded_1j0ct_290";
2807
- const historySection = "_historySection_1j0ct_258";
2808
- const historyItem = "_historyItem_1j0ct_309";
2809
- const doneSuccess = "_doneSuccess_1j0ct_368";
2810
- const historyContent = "_historyContent_1j0ct_404";
2811
- const statusIcon = "_statusIcon_1j0ct_405";
2812
- const doneError = "_doneError_1j0ct_414";
2813
- const historyMeta = "_historyMeta_1j0ct_465";
2814
- const inputSectionWrapper = "_inputSectionWrapper_1j0ct_535";
2815
- const hidden = "_hidden_1j0ct_558";
2816
- const inputSection = "_inputSection_1j0ct_535";
2817
- const taskInput = "_taskInput_1j0ct_569";
2818
- const styles$1 = {
2819
- wrapper: wrapper$1,
2820
- "mask-running": "_mask-running_1j0ct_1",
2821
- background,
2822
- header,
2823
- pulse,
2824
- retryPulse,
2825
- statusTextFadeOut,
2826
- statusTextFadeIn,
2827
- statusSection,
2828
- indicator,
2829
- thinking,
2830
- tool_executing,
2831
- retry,
2832
- completed,
2833
- input,
2834
- output,
2835
- error,
2836
- statusText,
2837
- fadeOut,
2838
- fadeIn,
2839
- controls,
2840
- controlButton,
2841
- pauseButton,
2842
- paused,
2843
- stopButton,
2844
- historySectionWrapper,
2845
- shimmer,
2846
- celebrate,
2847
- expanded,
2848
- historySection,
2849
- historyItem,
2850
- doneSuccess,
2851
- historyContent,
2852
- statusIcon,
2853
- doneError,
2854
- historyMeta,
2855
- inputSectionWrapper,
2856
- hidden,
2857
- inputSection,
2858
- taskInput
2859
- };
2860
- const _Panel = class _Panel {
2861
- constructor(pageAgent) {
2862
- __privateAdd(this, _Panel_instances);
2863
- __privateAdd(this, _wrapper);
2864
- __privateAdd(this, _indicator);
2865
- __privateAdd(this, _statusText);
2866
- __privateAdd(this, _historySection);
2867
- __privateAdd(this, _expandButton);
2868
- __privateAdd(this, _pauseButton);
2869
- __privateAdd(this, _stopButton);
2870
- __privateAdd(this, _inputSection);
2871
- __privateAdd(this, _taskInput);
2872
- __privateAdd(this, _bus2);
2873
- __privateAdd(this, _state, new UIState());
2874
- __privateAdd(this, _isExpanded, false);
2875
- __privateAdd(this, _pageAgent);
2876
- __privateAdd(this, _userAnswerResolver, null);
2877
- __privateAdd(this, _isWaitingForUserAnswer, false);
2878
- __privateAdd(this, _headerUpdateTimer, null);
2879
- __privateAdd(this, _pendingHeaderText, null);
2880
- __privateAdd(this, _isAnimating, false);
2881
- __privateSet(this, _pageAgent, pageAgent);
2882
- __privateSet(this, _bus2, pageAgent.bus);
2883
- __privateSet(this, _wrapper, __privateMethod(this, _Panel_instances, createWrapper_fn).call(this));
2884
- __privateSet(this, _indicator, __privateGet(this, _wrapper).querySelector(`.${styles$1.indicator}`));
2885
- __privateSet(this, _statusText, __privateGet(this, _wrapper).querySelector(`.${styles$1.statusText}`));
2886
- __privateSet(this, _historySection, __privateGet(this, _wrapper).querySelector(`.${styles$1.historySection}`));
2887
- __privateSet(this, _expandButton, __privateGet(this, _wrapper).querySelector(`.${styles$1.expandButton}`));
2888
- __privateSet(this, _pauseButton, __privateGet(this, _wrapper).querySelector(`.${styles$1.pauseButton}`));
2889
- __privateSet(this, _stopButton, __privateGet(this, _wrapper).querySelector(`.${styles$1.stopButton}`));
2890
- __privateSet(this, _inputSection, __privateGet(this, _wrapper).querySelector(`.${styles$1.inputSectionWrapper}`));
2891
- __privateSet(this, _taskInput, __privateGet(this, _wrapper).querySelector(`.${styles$1.taskInput}`));
2892
- __privateMethod(this, _Panel_instances, setupEventListeners_fn).call(this);
2893
- __privateMethod(this, _Panel_instances, startHeaderUpdateLoop_fn).call(this);
2894
- __privateMethod(this, _Panel_instances, showInputArea_fn).call(this);
2895
- __privateGet(this, _bus2).on("panel:show", () => __privateMethod(this, _Panel_instances, show_fn).call(this));
2896
- __privateGet(this, _bus2).on("panel:hide", () => __privateMethod(this, _Panel_instances, hide_fn).call(this));
2897
- __privateGet(this, _bus2).on("panel:reset", () => __privateMethod(this, _Panel_instances, reset_fn).call(this));
2898
- __privateGet(this, _bus2).on("panel:update", (stepData) => __privateMethod(this, _Panel_instances, update_fn).call(this, stepData));
2899
- __privateGet(this, _bus2).on("panel:expand", () => __privateMethod(this, _Panel_instances, expand_fn).call(this));
2900
- __privateGet(this, _bus2).on("panel:collapse", () => __privateMethod(this, _Panel_instances, collapse_fn).call(this));
2901
- }
2902
- get wrapper() {
2903
- return __privateGet(this, _wrapper);
2904
- }
2905
- /**
2906
- * Ask for user input
2907
- */
2908
- async askUser(question) {
2909
- return new Promise((resolve) => {
2910
- __privateSet(this, _isWaitingForUserAnswer, true);
2911
- __privateSet(this, _userAnswerResolver, resolve);
2912
- __privateMethod(this, _Panel_instances, update_fn).call(this, {
2913
- type: "output",
2914
- displayText: __privateGet(this, _pageAgent).i18n.t("ui.panel.question", { question })
2915
- });
2916
- if (!__privateGet(this, _isExpanded)) {
2917
- __privateMethod(this, _Panel_instances, expand_fn).call(this);
2918
- }
2919
- __privateMethod(this, _Panel_instances, showInputArea_fn).call(this, __privateGet(this, _pageAgent).i18n.t("ui.panel.userAnswerPrompt"));
2920
- });
2921
- }
2922
- /**
2923
- * Dispose panel
2924
- */
2925
- dispose() {
2926
- __privateSet(this, _isWaitingForUserAnswer, false);
2927
- __privateMethod(this, _Panel_instances, stopHeaderUpdateLoop_fn).call(this);
2928
- this.wrapper.remove();
2929
- }
2930
- };
2931
- _wrapper = new WeakMap();
2932
- _indicator = new WeakMap();
2933
- _statusText = new WeakMap();
2934
- _historySection = new WeakMap();
2935
- _expandButton = new WeakMap();
2936
- _pauseButton = new WeakMap();
2937
- _stopButton = new WeakMap();
2938
- _inputSection = new WeakMap();
2939
- _taskInput = new WeakMap();
2940
- _bus2 = new WeakMap();
2941
- _state = new WeakMap();
2942
- _isExpanded = new WeakMap();
2943
- _pageAgent = new WeakMap();
2944
- _userAnswerResolver = new WeakMap();
2945
- _isWaitingForUserAnswer = new WeakMap();
2946
- _headerUpdateTimer = new WeakMap();
2947
- _pendingHeaderText = new WeakMap();
2948
- _isAnimating = new WeakMap();
2949
- _Panel_instances = new WeakSet();
2950
- /**
2951
- * Update status
2952
- */
2953
- update_fn = /* @__PURE__ */ __name2(function(stepData) {
2954
- const step = __privateGet(this, _state).addStep(stepData);
2955
- const headerText = truncate(step.displayText, 20);
2956
- __privateSet(this, _pendingHeaderText, headerText);
2957
- __privateMethod(this, _Panel_instances, updateStatusIndicator_fn).call(this, step.type);
2958
- __privateMethod(this, _Panel_instances, updateHistory_fn).call(this);
2959
- if (step.type === "completed" || step.type === "error") {
2960
- if (!__privateGet(this, _isExpanded)) {
2961
- __privateMethod(this, _Panel_instances, expand_fn).call(this);
2962
- }
2963
- }
2964
- if (__privateMethod(this, _Panel_instances, shouldShowInputArea_fn).call(this)) {
2965
- __privateMethod(this, _Panel_instances, showInputArea_fn).call(this);
2966
- } else {
2967
- __privateMethod(this, _Panel_instances, hideInputArea_fn).call(this);
2968
- }
2969
- }, "#update");
2970
- /**
2971
- * Show panel
2972
- */
2973
- show_fn = /* @__PURE__ */ __name2(function() {
2974
- this.wrapper.style.display = "block";
2975
- void this.wrapper.offsetHeight;
2976
- this.wrapper.style.opacity = "1";
2977
- this.wrapper.style.transform = "translateX(-50%) translateY(0)";
2978
- }, "#show");
2979
- /**
2980
- * Hide panel
2981
- */
2982
- hide_fn = /* @__PURE__ */ __name2(function() {
2983
- this.wrapper.style.opacity = "0";
2984
- this.wrapper.style.transform = "translateX(-50%) translateY(20px)";
2985
- this.wrapper.style.display = "none";
2986
- }, "#hide");
2987
- /**
2988
- * Reset state
2989
- */
2990
- reset_fn = /* @__PURE__ */ __name2(function() {
2991
- __privateGet(this, _state).reset();
2992
- __privateGet(this, _statusText).textContent = __privateGet(this, _pageAgent).i18n.t("ui.panel.ready");
2993
- __privateMethod(this, _Panel_instances, updateStatusIndicator_fn).call(this, "thinking");
2994
- __privateMethod(this, _Panel_instances, updateHistory_fn).call(this);
2995
- __privateMethod(this, _Panel_instances, collapse_fn).call(this);
2996
- __privateGet(this, _pageAgent).paused = false;
2997
- __privateMethod(this, _Panel_instances, updatePauseButton_fn).call(this);
2998
- __privateSet(this, _isWaitingForUserAnswer, false);
2999
- __privateSet(this, _userAnswerResolver, null);
3000
- __privateMethod(this, _Panel_instances, showInputArea_fn).call(this);
3001
- }, "#reset");
3002
- /**
3003
- * Toggle pause state
3004
- */
3005
- togglePause_fn = /* @__PURE__ */ __name2(function() {
3006
- __privateGet(this, _pageAgent).paused = !__privateGet(this, _pageAgent).paused;
3007
- __privateMethod(this, _Panel_instances, updatePauseButton_fn).call(this);
3008
- if (__privateGet(this, _pageAgent).paused) {
3009
- __privateGet(this, _statusText).textContent = __privateGet(this, _pageAgent).i18n.t("ui.panel.paused");
3010
- __privateMethod(this, _Panel_instances, updateStatusIndicator_fn).call(this, "thinking");
3011
- } else {
3012
- __privateGet(this, _statusText).textContent = __privateGet(this, _pageAgent).i18n.t("ui.panel.continueExecution");
3013
- __privateMethod(this, _Panel_instances, updateStatusIndicator_fn).call(this, "tool_executing");
3014
- }
3015
- }, "#togglePause");
3016
- /**
3017
- * Update pause button state
3018
- */
3019
- updatePauseButton_fn = /* @__PURE__ */ __name2(function() {
3020
- if (__privateGet(this, _pageAgent).paused) {
3021
- __privateGet(this, _pauseButton).textContent = "▶";
3022
- __privateGet(this, _pauseButton).title = __privateGet(this, _pageAgent).i18n.t("ui.panel.continue");
3023
- __privateGet(this, _pauseButton).classList.add(styles$1.paused);
3024
- } else {
3025
- __privateGet(this, _pauseButton).textContent = "⏸︎";
3026
- __privateGet(this, _pauseButton).title = __privateGet(this, _pageAgent).i18n.t("ui.panel.pause");
3027
- __privateGet(this, _pauseButton).classList.remove(styles$1.paused);
3028
- }
3029
- }, "#updatePauseButton");
3030
- /**
3031
- * Stop Agent
3032
- */
3033
- stopAgent_fn = /* @__PURE__ */ __name2(function() {
3034
- __privateMethod(this, _Panel_instances, update_fn).call(this, {
3035
- type: "error",
3036
- displayText: __privateGet(this, _pageAgent).i18n.t("ui.panel.taskTerminated")
3037
- });
3038
- __privateGet(this, _pageAgent).dispose();
3039
- }, "#stopAgent");
3040
- /**
3041
- * Submit task
3042
- */
3043
- submitTask_fn = /* @__PURE__ */ __name2(function() {
3044
- const input2 = __privateGet(this, _taskInput).value.trim();
3045
- if (!input2) return;
3046
- __privateMethod(this, _Panel_instances, hideInputArea_fn).call(this);
3047
- if (__privateGet(this, _isWaitingForUserAnswer)) {
3048
- __privateMethod(this, _Panel_instances, handleUserAnswer_fn).call(this, input2);
3049
- } else {
3050
- __privateGet(this, _pageAgent).execute(input2);
3051
- }
3052
- }, "#submitTask");
3053
- /**
3054
- * Handle user answer
3055
- */
3056
- handleUserAnswer_fn = /* @__PURE__ */ __name2(function(input2) {
3057
- __privateMethod(this, _Panel_instances, update_fn).call(this, {
3058
- type: "input",
3059
- displayText: __privateGet(this, _pageAgent).i18n.t("ui.panel.userAnswer", { input: input2 })
3060
- });
3061
- __privateSet(this, _isWaitingForUserAnswer, false);
3062
- if (__privateGet(this, _userAnswerResolver)) {
3063
- __privateGet(this, _userAnswerResolver).call(this, input2);
3064
- __privateSet(this, _userAnswerResolver, null);
2516
+ }, "#submitTask");
2517
+ handleUserAnswer_fn = /* @__PURE__ */ __name(function(input2) {
2518
+ __privateMethod(this, _Panel_instances, updateInternal_fn).call(this, {
2519
+ type: "input",
2520
+ displayText: __privateGet(this, _i18n).t("ui.panel.userAnswer", { input: input2 })
2521
+ });
2522
+ __privateSet(this, _isWaitingForUserAnswer, false);
2523
+ if (__privateGet(this, _userAnswerResolver)) {
2524
+ __privateGet(this, _userAnswerResolver).call(this, input2);
2525
+ __privateSet(this, _userAnswerResolver, null);
3065
2526
  }
3066
2527
  }, "#handleUserAnswer");
3067
- /**
3068
- * Show input area
3069
- */
3070
- showInputArea_fn = /* @__PURE__ */ __name2(function(placeholder) {
2528
+ showInputArea_fn = /* @__PURE__ */ __name(function(placeholder) {
3071
2529
  __privateGet(this, _taskInput).value = "";
3072
- __privateGet(this, _taskInput).placeholder = placeholder || __privateGet(this, _pageAgent).i18n.t("ui.panel.taskInput");
2530
+ __privateGet(this, _taskInput).placeholder = placeholder || __privateGet(this, _i18n).t("ui.panel.taskInput");
3073
2531
  __privateGet(this, _inputSection).classList.remove(styles$1.hidden);
3074
2532
  setTimeout(() => {
3075
2533
  __privateGet(this, _taskInput).focus();
3076
2534
  }, 100);
3077
2535
  }, "#showInputArea");
3078
- /**
3079
- * Hide input area
3080
- */
3081
- hideInputArea_fn = /* @__PURE__ */ __name2(function() {
2536
+ hideInputArea_fn = /* @__PURE__ */ __name(function() {
3082
2537
  __privateGet(this, _inputSection).classList.add(styles$1.hidden);
3083
2538
  }, "#hideInputArea");
3084
- /**
3085
- * Check if input area should be shown
3086
- */
3087
- shouldShowInputArea_fn = /* @__PURE__ */ __name2(function() {
2539
+ shouldShowInputArea_fn = /* @__PURE__ */ __name(function() {
3088
2540
  if (__privateGet(this, _isWaitingForUserAnswer)) return true;
3089
2541
  const steps = __privateGet(this, _state).getAllSteps();
3090
2542
  if (steps.length === 0) {
@@ -3093,7 +2545,7 @@ shouldShowInputArea_fn = /* @__PURE__ */ __name2(function() {
3093
2545
  const lastStep = steps[steps.length - 1];
3094
2546
  return lastStep.type === "completed" || lastStep.type === "error";
3095
2547
  }, "#shouldShowInputArea");
3096
- createWrapper_fn = /* @__PURE__ */ __name2(function() {
2548
+ createWrapper_fn = /* @__PURE__ */ __name(function() {
3097
2549
  const wrapper2 = document.createElement("div");
3098
2550
  wrapper2.id = "page-agent-runtime_agent-panel";
3099
2551
  wrapper2.className = `${styles$1.wrapper} ${styles$1.collapsed}`;
@@ -3107,23 +2559,23 @@ createWrapper_fn = /* @__PURE__ */ __name2(function() {
3107
2559
  stepNumber: 0,
3108
2560
  timestamp: /* @__PURE__ */ new Date(),
3109
2561
  type: "thinking",
3110
- displayText: __privateGet(this, _pageAgent).i18n.t("ui.panel.waitingPlaceholder")
2562
+ displayText: __privateGet(this, _i18n).t("ui.panel.waitingPlaceholder")
3111
2563
  })}
3112
2564
  </div>
3113
2565
  </div>
3114
2566
  <div class="${styles$1.header}">
3115
2567
  <div class="${styles$1.statusSection}">
3116
2568
  <div class="${styles$1.indicator} ${styles$1.thinking}"></div>
3117
- <div class="${styles$1.statusText}">${__privateGet(this, _pageAgent).i18n.t("ui.panel.ready")}</div>
2569
+ <div class="${styles$1.statusText}">${__privateGet(this, _i18n).t("ui.panel.ready")}</div>
3118
2570
  </div>
3119
2571
  <div class="${styles$1.controls}">
3120
- <button class="${styles$1.controlButton} ${styles$1.expandButton}" title="${__privateGet(this, _pageAgent).i18n.t("ui.panel.expand")}">
2572
+ <button class="${styles$1.controlButton} ${styles$1.expandButton}" title="${__privateGet(this, _i18n).t("ui.panel.expand")}">
3121
2573
 
3122
2574
  </button>
3123
- <button class="${styles$1.controlButton} ${styles$1.pauseButton}" title="${__privateGet(this, _pageAgent).i18n.t("ui.panel.pause")}">
2575
+ <button class="${styles$1.controlButton} ${styles$1.pauseButton}" title="${__privateGet(this, _i18n).t("ui.panel.pause")}">
3124
2576
  ⏸︎
3125
2577
  </button>
3126
- <button class="${styles$1.controlButton} ${styles$1.stopButton}" title="${__privateGet(this, _pageAgent).i18n.t("ui.panel.stop")}">
2578
+ <button class="${styles$1.controlButton} ${styles$1.stopButton}" title="${__privateGet(this, _i18n).t("ui.panel.stop")}">
3127
2579
  X
3128
2580
  </button>
3129
2581
  </div>
@@ -3141,7 +2593,7 @@ createWrapper_fn = /* @__PURE__ */ __name2(function() {
3141
2593
  document.body.appendChild(wrapper2);
3142
2594
  return wrapper2;
3143
2595
  }, "#createWrapper");
3144
- setupEventListeners_fn = /* @__PURE__ */ __name2(function() {
2596
+ setupEventListeners_fn = /* @__PURE__ */ __name(function() {
3145
2597
  const header2 = this.wrapper.querySelector(`.${styles$1.header}`);
3146
2598
  header2.addEventListener("click", (e) => {
3147
2599
  if (e.target.closest(`.${styles$1.controlButton}`)) {
@@ -3172,46 +2624,37 @@ setupEventListeners_fn = /* @__PURE__ */ __name2(function() {
3172
2624
  e.stopPropagation();
3173
2625
  });
3174
2626
  }, "#setupEventListeners");
3175
- toggle_fn = /* @__PURE__ */ __name2(function() {
2627
+ toggle_fn = /* @__PURE__ */ __name(function() {
3176
2628
  if (__privateGet(this, _isExpanded)) {
3177
2629
  __privateMethod(this, _Panel_instances, collapse_fn).call(this);
3178
2630
  } else {
3179
2631
  __privateMethod(this, _Panel_instances, expand_fn).call(this);
3180
2632
  }
3181
2633
  }, "#toggle");
3182
- expand_fn = /* @__PURE__ */ __name2(function() {
2634
+ expand_fn = /* @__PURE__ */ __name(function() {
3183
2635
  __privateSet(this, _isExpanded, true);
3184
2636
  this.wrapper.classList.remove(styles$1.collapsed);
3185
2637
  this.wrapper.classList.add(styles$1.expanded);
3186
2638
  __privateGet(this, _expandButton).textContent = "▲";
3187
2639
  }, "#expand");
3188
- collapse_fn = /* @__PURE__ */ __name2(function() {
2640
+ collapse_fn = /* @__PURE__ */ __name(function() {
3189
2641
  __privateSet(this, _isExpanded, false);
3190
2642
  this.wrapper.classList.remove(styles$1.expanded);
3191
2643
  this.wrapper.classList.add(styles$1.collapsed);
3192
2644
  __privateGet(this, _expandButton).textContent = "▼";
3193
2645
  }, "#collapse");
3194
- /**
3195
- * Start periodic header update loop
3196
- */
3197
- startHeaderUpdateLoop_fn = /* @__PURE__ */ __name2(function() {
2646
+ startHeaderUpdateLoop_fn = /* @__PURE__ */ __name(function() {
3198
2647
  __privateSet(this, _headerUpdateTimer, setInterval(() => {
3199
2648
  __privateMethod(this, _Panel_instances, checkAndUpdateHeader_fn).call(this);
3200
2649
  }, 450));
3201
2650
  }, "#startHeaderUpdateLoop");
3202
- /**
3203
- * Stop periodic header update loop
3204
- */
3205
- stopHeaderUpdateLoop_fn = /* @__PURE__ */ __name2(function() {
2651
+ stopHeaderUpdateLoop_fn = /* @__PURE__ */ __name(function() {
3206
2652
  if (__privateGet(this, _headerUpdateTimer)) {
3207
2653
  clearInterval(__privateGet(this, _headerUpdateTimer));
3208
2654
  __privateSet(this, _headerUpdateTimer, null);
3209
2655
  }
3210
2656
  }, "#stopHeaderUpdateLoop");
3211
- /**
3212
- * Check if header needs update and trigger animation if not currently animating
3213
- */
3214
- checkAndUpdateHeader_fn = /* @__PURE__ */ __name2(function() {
2657
+ checkAndUpdateHeader_fn = /* @__PURE__ */ __name(function() {
3215
2658
  if (!__privateGet(this, _pendingHeaderText) || __privateGet(this, _isAnimating)) {
3216
2659
  return;
3217
2660
  }
@@ -3223,10 +2666,7 @@ checkAndUpdateHeader_fn = /* @__PURE__ */ __name2(function() {
3223
2666
  __privateSet(this, _pendingHeaderText, null);
3224
2667
  __privateMethod(this, _Panel_instances, animateTextChange_fn).call(this, textToShow);
3225
2668
  }, "#checkAndUpdateHeader");
3226
- /**
3227
- * Animate text change with fade out/in effect
3228
- */
3229
- animateTextChange_fn = /* @__PURE__ */ __name2(function(newText) {
2669
+ animateTextChange_fn = /* @__PURE__ */ __name(function(newText) {
3230
2670
  __privateSet(this, _isAnimating, true);
3231
2671
  __privateGet(this, _statusText).classList.add(styles$1.fadeOut);
3232
2672
  setTimeout(() => {
@@ -3239,21 +2679,21 @@ animateTextChange_fn = /* @__PURE__ */ __name2(function(newText) {
3239
2679
  }, 300);
3240
2680
  }, 150);
3241
2681
  }, "#animateTextChange");
3242
- updateStatusIndicator_fn = /* @__PURE__ */ __name2(function(type) {
2682
+ updateStatusIndicator_fn = /* @__PURE__ */ __name(function(type) {
3243
2683
  __privateGet(this, _indicator).className = styles$1.indicator;
3244
2684
  __privateGet(this, _indicator).classList.add(styles$1[type]);
3245
2685
  }, "#updateStatusIndicator");
3246
- updateHistory_fn = /* @__PURE__ */ __name2(function() {
2686
+ updateHistory_fn = /* @__PURE__ */ __name(function() {
3247
2687
  const steps = __privateGet(this, _state).getAllSteps();
3248
2688
  __privateGet(this, _historySection).innerHTML = steps.map((step) => __privateMethod(this, _Panel_instances, createHistoryItem_fn).call(this, step)).join("");
3249
2689
  __privateMethod(this, _Panel_instances, scrollToBottom_fn).call(this);
3250
2690
  }, "#updateHistory");
3251
- scrollToBottom_fn = /* @__PURE__ */ __name2(function() {
2691
+ scrollToBottom_fn = /* @__PURE__ */ __name(function() {
3252
2692
  setTimeout(() => {
3253
2693
  __privateGet(this, _historySection).scrollTop = __privateGet(this, _historySection).scrollHeight;
3254
2694
  }, 0);
3255
2695
  }, "#scrollToBottom");
3256
- createHistoryItem_fn = /* @__PURE__ */ __name2(function(step) {
2696
+ createHistoryItem_fn = /* @__PURE__ */ __name(function(step) {
3257
2697
  const time = step.timestamp.toLocaleTimeString("zh-CN", {
3258
2698
  hour12: false,
3259
2699
  hour: "2-digit",
@@ -3264,8 +2704,8 @@ createHistoryItem_fn = /* @__PURE__ */ __name2(function(step) {
3264
2704
  let statusIcon2 = "";
3265
2705
  if (step.type === "completed") {
3266
2706
  if (step.toolName === "done") {
3267
- const failureKeyword = __privateGet(this, _pageAgent).i18n.t("ui.tools.resultFailure");
3268
- const errorKeyword = __privateGet(this, _pageAgent).i18n.t("ui.tools.resultError");
2707
+ const failureKeyword = __privateGet(this, _i18n).t("ui.tools.resultFailure");
2708
+ const errorKeyword = __privateGet(this, _i18n).t("ui.tools.resultError");
3269
2709
  const isSuccess = !step.toolResult || !step.toolResult.includes(failureKeyword) && !step.toolResult.includes(errorKeyword);
3270
2710
  typeClass = isSuccess ? styles$1.doneSuccess : styles$1.doneError;
3271
2711
  statusIcon2 = isSuccess ? "🎉" : "❌";
@@ -3291,7 +2731,7 @@ createHistoryItem_fn = /* @__PURE__ */ __name2(function(step) {
3291
2731
  statusIcon2 = "🧠";
3292
2732
  }
3293
2733
  const durationText = step.duration ? ` · ${step.duration}ms` : "";
3294
- const stepLabel = __privateGet(this, _pageAgent).i18n.t("ui.panel.step", {
2734
+ const stepLabel = __privateGet(this, _i18n).t("ui.panel.step", {
3295
2735
  number: step.stepNumber.toString(),
3296
2736
  time,
3297
2737
  duration: durationText || ""
@@ -3309,46 +2749,8 @@ createHistoryItem_fn = /* @__PURE__ */ __name2(function(step) {
3309
2749
  </div>
3310
2750
  `;
3311
2751
  }, "#createHistoryItem");
3312
- __name2(_Panel, "Panel");
2752
+ __name(_Panel, "Panel");
3313
2753
  let Panel = _Panel;
3314
- function getToolExecutingText(toolName, args, i18n) {
3315
- switch (toolName) {
3316
- case "click_element_by_index":
3317
- return i18n.t("ui.tools.clicking", { index: args.index });
3318
- case "input_text":
3319
- return i18n.t("ui.tools.inputting", { index: args.index });
3320
- case "select_dropdown_option":
3321
- return i18n.t("ui.tools.selecting", { text: args.text });
3322
- case "scroll":
3323
- return i18n.t("ui.tools.scrolling");
3324
- case "wait":
3325
- return i18n.t("ui.tools.waiting", { seconds: args.seconds });
3326
- case "done":
3327
- return i18n.t("ui.tools.done");
3328
- default:
3329
- return i18n.t("ui.tools.executing", { toolName });
3330
- }
3331
- }
3332
- __name2(getToolExecutingText, "getToolExecutingText");
3333
- function getToolCompletedText(toolName, args, i18n) {
3334
- switch (toolName) {
3335
- case "click_element_by_index":
3336
- return i18n.t("ui.tools.clicked", { index: args.index });
3337
- case "input_text":
3338
- return i18n.t("ui.tools.inputted", { text: args.text });
3339
- case "select_dropdown_option":
3340
- return i18n.t("ui.tools.selected", { text: args.text });
3341
- case "scroll":
3342
- return i18n.t("ui.tools.scrolled");
3343
- case "wait":
3344
- return i18n.t("ui.tools.waited");
3345
- case "done":
3346
- return null;
3347
- default:
3348
- return null;
3349
- }
3350
- }
3351
- __name2(getToolCompletedText, "getToolCompletedText");
3352
2754
  function hasDarkModeClass() {
3353
2755
  const DFEAULT_DARK_MODE_CLASSES = ["dark", "dark-mode", "theme-dark", "night", "night-mode"];
3354
2756
  const htmlElement = document.documentElement;
@@ -3365,6 +2767,7 @@ function hasDarkModeClass() {
3365
2767
  return false;
3366
2768
  }
3367
2769
  __name2(hasDarkModeClass, "hasDarkModeClass");
2770
+ __name(hasDarkModeClass, "hasDarkModeClass");
3368
2771
  function parseRgbColor(colorString) {
3369
2772
  const rgbMatch = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(colorString);
3370
2773
  if (!rgbMatch) {
@@ -3377,6 +2780,7 @@ function parseRgbColor(colorString) {
3377
2780
  };
3378
2781
  }
3379
2782
  __name2(parseRgbColor, "parseRgbColor");
2783
+ __name(parseRgbColor, "parseRgbColor");
3380
2784
  function isColorDark(colorString, threshold = 128) {
3381
2785
  if (!colorString || colorString === "transparent" || colorString.startsWith("rgba(0, 0, 0, 0)")) {
3382
2786
  return false;
@@ -3389,6 +2793,7 @@ function isColorDark(colorString, threshold = 128) {
3389
2793
  return luminance < threshold;
3390
2794
  }
3391
2795
  __name2(isColorDark, "isColorDark");
2796
+ __name(isColorDark, "isColorDark");
3392
2797
  function isBackgroundDark() {
3393
2798
  const htmlStyle = window.getComputedStyle(document.documentElement);
3394
2799
  const bodyStyle = window.getComputedStyle(document.body);
@@ -3402,6 +2807,7 @@ function isBackgroundDark() {
3402
2807
  return false;
3403
2808
  }
3404
2809
  __name2(isBackgroundDark, "isBackgroundDark");
2810
+ __name(isBackgroundDark, "isBackgroundDark");
3405
2811
  function isPageDark() {
3406
2812
  if (hasDarkModeClass()) {
3407
2813
  return true;
@@ -3412,6 +2818,7 @@ function isPageDark() {
3412
2818
  return false;
3413
2819
  }
3414
2820
  __name2(isPageDark, "isPageDark");
2821
+ __name(isPageDark, "isPageDark");
3415
2822
  const wrapper = "_wrapper_1oy2s_1";
3416
2823
  const styles = {
3417
2824
  wrapper
@@ -3428,7 +2835,7 @@ const cursorStyles = {
3428
2835
  cursorRipple,
3429
2836
  clicking
3430
2837
  };
3431
- const _SimulatorMask = class _SimulatorMask {
2838
+ const _SimulatorMask = (_e = class {
3432
2839
  constructor() {
3433
2840
  __privateAdd(this, _SimulatorMask_instances);
3434
2841
  __publicField(this, "wrapper", document.createElement("div"));
@@ -3488,83 +2895,649 @@ const _SimulatorMask = class _SimulatorMask {
3488
2895
  this.triggerClickAnimation();
3489
2896
  });
3490
2897
  }
3491
- setCursorPosition(x, y) {
3492
- __privateSet(this, _targetCursorX, x);
3493
- __privateSet(this, _targetCursorY, y);
2898
+ setCursorPosition(x, y) {
2899
+ __privateSet(this, _targetCursorX, x);
2900
+ __privateSet(this, _targetCursorY, y);
2901
+ }
2902
+ triggerClickAnimation() {
2903
+ __privateGet(this, _cursor).classList.remove(cursorStyles.clicking);
2904
+ void __privateGet(this, _cursor).offsetHeight;
2905
+ __privateGet(this, _cursor).classList.add(cursorStyles.clicking);
2906
+ }
2907
+ show() {
2908
+ this.motion.start();
2909
+ this.motion.fadeIn();
2910
+ this.wrapper.style.display = "block";
2911
+ __privateSet(this, _currentCursorX, window.innerWidth / 2);
2912
+ __privateSet(this, _currentCursorY, window.innerHeight / 2);
2913
+ __privateSet(this, _targetCursorX, __privateGet(this, _currentCursorX));
2914
+ __privateSet(this, _targetCursorY, __privateGet(this, _currentCursorY));
2915
+ __privateGet(this, _cursor).style.left = `${__privateGet(this, _currentCursorX)}px`;
2916
+ __privateGet(this, _cursor).style.top = `${__privateGet(this, _currentCursorY)}px`;
2917
+ }
2918
+ hide() {
2919
+ this.motion.fadeOut();
2920
+ this.motion.pause();
2921
+ __privateGet(this, _cursor).classList.remove(cursorStyles.clicking);
2922
+ setTimeout(() => {
2923
+ this.wrapper.style.display = "none";
2924
+ }, 800);
2925
+ }
2926
+ dispose() {
2927
+ this.motion.dispose();
2928
+ this.wrapper.remove();
2929
+ }
2930
+ }, __name2(_e, "_SimulatorMask"), _e);
2931
+ _cursor = /* @__PURE__ */ new WeakMap();
2932
+ _currentCursorX = /* @__PURE__ */ new WeakMap();
2933
+ _currentCursorY = /* @__PURE__ */ new WeakMap();
2934
+ _targetCursorX = /* @__PURE__ */ new WeakMap();
2935
+ _targetCursorY = /* @__PURE__ */ new WeakMap();
2936
+ _SimulatorMask_instances = /* @__PURE__ */ new WeakSet();
2937
+ createCursor_fn = /* @__PURE__ */ __name(function() {
2938
+ __privateGet(this, _cursor).className = cursorStyles.cursor;
2939
+ const rippleContainer = document.createElement("div");
2940
+ rippleContainer.className = cursorStyles.cursorRipple;
2941
+ __privateGet(this, _cursor).appendChild(rippleContainer);
2942
+ const fillingLayer = document.createElement("div");
2943
+ fillingLayer.className = cursorStyles.cursorFilling;
2944
+ __privateGet(this, _cursor).appendChild(fillingLayer);
2945
+ const borderLayer = document.createElement("div");
2946
+ borderLayer.className = cursorStyles.cursorBorder;
2947
+ __privateGet(this, _cursor).appendChild(borderLayer);
2948
+ this.wrapper.appendChild(__privateGet(this, _cursor));
2949
+ }, "#createCursor");
2950
+ moveCursorToTarget_fn = /* @__PURE__ */ __name(function() {
2951
+ const newX = __privateGet(this, _currentCursorX) + (__privateGet(this, _targetCursorX) - __privateGet(this, _currentCursorX)) * 0.2;
2952
+ const newY = __privateGet(this, _currentCursorY) + (__privateGet(this, _targetCursorY) - __privateGet(this, _currentCursorY)) * 0.2;
2953
+ const xDistance = Math.abs(newX - __privateGet(this, _targetCursorX));
2954
+ if (xDistance > 0) {
2955
+ if (xDistance < 2) {
2956
+ __privateSet(this, _currentCursorX, __privateGet(this, _targetCursorX));
2957
+ } else {
2958
+ __privateSet(this, _currentCursorX, newX);
2959
+ }
2960
+ __privateGet(this, _cursor).style.left = `${__privateGet(this, _currentCursorX)}px`;
2961
+ }
2962
+ const yDistance = Math.abs(newY - __privateGet(this, _targetCursorY));
2963
+ if (yDistance > 0) {
2964
+ if (yDistance < 2) {
2965
+ __privateSet(this, _currentCursorY, __privateGet(this, _targetCursorY));
2966
+ } else {
2967
+ __privateSet(this, _currentCursorY, newY);
2968
+ }
2969
+ __privateGet(this, _cursor).style.top = `${__privateGet(this, _currentCursorY)}px`;
2970
+ }
2971
+ requestAnimationFrame(() => __privateMethod(this, _SimulatorMask_instances, moveCursorToTarget_fn).call(this));
2972
+ }, "#moveCursorToTarget");
2973
+ __name(_SimulatorMask, "SimulatorMask");
2974
+ let SimulatorMask = _SimulatorMask;
2975
+ const DEFAULT_MODEL_NAME = "PAGE-AGENT-FREE-TESTING-RANDOM";
2976
+ const DEFAULT_API_KEY = "PAGE-AGENT-FREE-TESTING-RANDOM";
2977
+ const DEFAULT_BASE_URL = "https://hwcxiuzfylggtcktqgij.supabase.co/functions/v1/llm-testing-proxy";
2978
+ const LLM_MAX_RETRIES = 2;
2979
+ const MAX_STEPS = 20;
2980
+ const DEFAULT_TEMPERATURE = 0.7;
2981
+ const DEFAULT_MAX_TOKENS = 4096;
2982
+ function parseLLMConfig(config) {
2983
+ return {
2984
+ baseURL: config.baseURL ?? DEFAULT_BASE_URL,
2985
+ apiKey: config.apiKey ?? DEFAULT_API_KEY,
2986
+ model: config.model ?? DEFAULT_MODEL_NAME,
2987
+ temperature: config.temperature ?? DEFAULT_TEMPERATURE,
2988
+ maxTokens: config.maxTokens ?? DEFAULT_MAX_TOKENS,
2989
+ maxRetries: config.maxRetries ?? LLM_MAX_RETRIES
2990
+ };
2991
+ }
2992
+ __name2(parseLLMConfig, "parseLLMConfig");
2993
+ const InvokeErrorType = {
2994
+ // Retryable
2995
+ NETWORK_ERROR: "network_error",
2996
+ // Network error, retry
2997
+ RATE_LIMIT: "rate_limit",
2998
+ // Rate limit, retry
2999
+ SERVER_ERROR: "server_error",
3000
+ // 5xx, retry
3001
+ NO_TOOL_CALL: "no_tool_call",
3002
+ // Model did not call tool
3003
+ INVALID_TOOL_ARGS: "invalid_tool_args",
3004
+ // Tool args don't match schema
3005
+ TOOL_EXECUTION_ERROR: "tool_execution_error",
3006
+ // Tool execution error
3007
+ UNKNOWN: "unknown",
3008
+ // Non-retryable
3009
+ AUTH_ERROR: "auth_error",
3010
+ // Authentication failed
3011
+ CONTEXT_LENGTH: "context_length",
3012
+ // Prompt too long
3013
+ CONTENT_FILTER: "content_filter"
3014
+ // Content filtered
3015
+ };
3016
+ const _InvokeError = class _InvokeError extends Error {
3017
+ type;
3018
+ retryable;
3019
+ statusCode;
3020
+ rawError;
3021
+ constructor(type, message, rawError) {
3022
+ super(message);
3023
+ this.name = "InvokeError";
3024
+ this.type = type;
3025
+ this.retryable = this.isRetryable(type);
3026
+ this.rawError = rawError;
3027
+ }
3028
+ isRetryable(type) {
3029
+ const retryableTypes = [
3030
+ InvokeErrorType.NETWORK_ERROR,
3031
+ InvokeErrorType.RATE_LIMIT,
3032
+ InvokeErrorType.SERVER_ERROR,
3033
+ InvokeErrorType.NO_TOOL_CALL,
3034
+ InvokeErrorType.INVALID_TOOL_ARGS,
3035
+ InvokeErrorType.TOOL_EXECUTION_ERROR,
3036
+ InvokeErrorType.UNKNOWN
3037
+ ];
3038
+ return retryableTypes.includes(type);
3039
+ }
3040
+ };
3041
+ __name2(_InvokeError, "InvokeError");
3042
+ let InvokeError = _InvokeError;
3043
+ function zodToOpenAITool(name, tool2) {
3044
+ return {
3045
+ type: "function",
3046
+ function: {
3047
+ name,
3048
+ description: tool2.description,
3049
+ parameters: z.toJSONSchema(tool2.inputSchema, { target: "openapi-3.0" })
3050
+ }
3051
+ };
3052
+ }
3053
+ __name2(zodToOpenAITool, "zodToOpenAITool");
3054
+ function lenientParseMacroToolCall(responseData, inputSchema) {
3055
+ const choice = responseData.choices?.[0];
3056
+ if (!choice) {
3057
+ throw new InvokeError(InvokeErrorType.UNKNOWN, "No choices in response", responseData);
3058
+ }
3059
+ switch (choice.finish_reason) {
3060
+ case "tool_calls":
3061
+ case "function_call":
3062
+ // gemini
3063
+ case "stop":
3064
+ break;
3065
+ case "length":
3066
+ throw new InvokeError(
3067
+ InvokeErrorType.CONTEXT_LENGTH,
3068
+ "Response truncated: max tokens reached"
3069
+ );
3070
+ case "content_filter":
3071
+ throw new InvokeError(InvokeErrorType.CONTENT_FILTER, "Content filtered by safety system");
3072
+ default:
3073
+ throw new InvokeError(
3074
+ InvokeErrorType.UNKNOWN,
3075
+ `Unexpected finish_reason: ${choice.finish_reason}`
3076
+ );
3077
+ }
3078
+ const actionSchema = inputSchema.shape.action;
3079
+ if (!actionSchema) {
3080
+ throw new Error('inputSchema must have an "action" field');
3081
+ }
3082
+ let arg = null;
3083
+ const toolCall = choice.message?.tool_calls?.[0]?.function;
3084
+ arg = toolCall?.arguments ?? null;
3085
+ if (arg && toolCall.name !== "AgentOutput") {
3086
+ console.log(chalk.yellow("lenientParseMacroToolCall: #1 fixing incorrect tool call"));
3087
+ let tmpArg;
3088
+ try {
3089
+ tmpArg = JSON.parse(arg);
3090
+ } catch (error2) {
3091
+ throw new InvokeError(
3092
+ InvokeErrorType.INVALID_TOOL_ARGS,
3093
+ "Failed to parse tool arguments as JSON",
3094
+ error2
3095
+ );
3096
+ }
3097
+ arg = JSON.stringify({ action: { [toolCall.name]: tmpArg } });
3098
+ }
3099
+ if (!arg) {
3100
+ arg = choice.message?.content.trim() || null;
3494
3101
  }
3495
- triggerClickAnimation() {
3496
- __privateGet(this, _cursor).classList.remove(cursorStyles.clicking);
3497
- void __privateGet(this, _cursor).offsetHeight;
3498
- __privateGet(this, _cursor).classList.add(cursorStyles.clicking);
3102
+ if (!arg) {
3103
+ throw new InvokeError(
3104
+ InvokeErrorType.NO_TOOL_CALL,
3105
+ "No tool call or content found in response",
3106
+ responseData
3107
+ );
3499
3108
  }
3500
- show() {
3501
- this.motion.start();
3502
- this.motion.fadeIn();
3503
- this.wrapper.style.display = "block";
3504
- __privateSet(this, _currentCursorX, window.innerWidth / 2);
3505
- __privateSet(this, _currentCursorY, window.innerHeight / 2);
3506
- __privateSet(this, _targetCursorX, __privateGet(this, _currentCursorX));
3507
- __privateSet(this, _targetCursorY, __privateGet(this, _currentCursorY));
3508
- __privateGet(this, _cursor).style.left = `${__privateGet(this, _currentCursorX)}px`;
3509
- __privateGet(this, _cursor).style.top = `${__privateGet(this, _currentCursorY)}px`;
3109
+ let parsedArgs;
3110
+ try {
3111
+ parsedArgs = JSON.parse(arg);
3112
+ } catch (error2) {
3113
+ throw new InvokeError(
3114
+ InvokeErrorType.INVALID_TOOL_ARGS,
3115
+ "Failed to parse tool arguments as JSON",
3116
+ error2
3117
+ );
3510
3118
  }
3511
- hide() {
3512
- this.motion.fadeOut();
3513
- this.motion.pause();
3514
- __privateGet(this, _cursor).classList.remove(cursorStyles.clicking);
3515
- setTimeout(() => {
3516
- this.wrapper.style.display = "none";
3517
- }, 800);
3119
+ if (parsedArgs.action || parsedArgs.evaluation_previous_goal || parsedArgs.next_goal) {
3120
+ if (!parsedArgs.action) {
3121
+ console.log(chalk.yellow("lenientParseMacroToolCall: #2 fixing incorrect tool call"));
3122
+ parsedArgs.action = {
3123
+ wait: { seconds: 1 }
3124
+ };
3125
+ }
3126
+ } else if (parsedArgs.type && parsedArgs.function) {
3127
+ if (parsedArgs.function.name !== "AgentOutput")
3128
+ throw new InvokeError(
3129
+ InvokeErrorType.INVALID_TOOL_ARGS,
3130
+ `Expected function name "AgentOutput", got "${parsedArgs.function.name}"`,
3131
+ null
3132
+ );
3133
+ console.log(chalk.yellow("lenientParseMacroToolCall: #3 fixing incorrect tool call"));
3134
+ parsedArgs = parsedArgs.function.arguments;
3135
+ } else if (parsedArgs.name && parsedArgs.arguments) {
3136
+ if (parsedArgs.name !== "AgentOutput")
3137
+ throw new InvokeError(
3138
+ InvokeErrorType.INVALID_TOOL_ARGS,
3139
+ `Expected function name "AgentOutput", got "${parsedArgs.name}"`,
3140
+ null
3141
+ );
3142
+ console.log(chalk.yellow("lenientParseMacroToolCall: #4 fixing incorrect tool call"));
3143
+ parsedArgs = parsedArgs.arguments;
3144
+ } else {
3145
+ console.log(chalk.yellow("lenientParseMacroToolCall: #5 fixing incorrect tool call"));
3146
+ parsedArgs = { action: parsedArgs };
3518
3147
  }
3519
- dispose() {
3520
- this.motion.dispose();
3521
- this.wrapper.remove();
3148
+ if (typeof parsedArgs === "string") {
3149
+ console.log(chalk.yellow("lenientParseMacroToolCall: #6 fixing incorrect tool call"));
3150
+ try {
3151
+ parsedArgs = JSON.parse(parsedArgs);
3152
+ } catch (error2) {
3153
+ throw new InvokeError(
3154
+ InvokeErrorType.INVALID_TOOL_ARGS,
3155
+ "Failed to parse nested tool arguments as JSON",
3156
+ error2
3157
+ );
3158
+ }
3159
+ }
3160
+ const validation = inputSchema.safeParse(parsedArgs);
3161
+ if (validation.success) {
3162
+ return validation.data;
3163
+ } else {
3164
+ const action = parsedArgs.action ?? {};
3165
+ const actionName = Object.keys(action)[0] || "unknown";
3166
+ const actionArgs = JSON.stringify(action[actionName] || "unknown");
3167
+ throw new InvokeError(
3168
+ InvokeErrorType.INVALID_TOOL_ARGS,
3169
+ `Tool arguments validation failed: action "${actionName}" with args ${actionArgs}`,
3170
+ validation.error
3171
+ );
3172
+ }
3173
+ }
3174
+ __name2(lenientParseMacroToolCall, "lenientParseMacroToolCall");
3175
+ function modelPatch(body) {
3176
+ const model = body.model || "";
3177
+ if (model.toLowerCase().startsWith("claude")) {
3178
+ body.tool_choice = { type: "tool", name: "AgentOutput" };
3179
+ body.thinking = { type: "disabled" };
3180
+ }
3181
+ if (model.toLowerCase().includes("grok")) {
3182
+ console.log("Applying Grok patch: removing tool_choice");
3183
+ delete body.tool_choice;
3184
+ console.log("Applying Grok patch: disable reasoning and thinking");
3185
+ body.thinking = { type: "disabled", effort: "minimal" };
3186
+ body.reasoning = { enabled: false, effort: "low" };
3187
+ }
3188
+ return body;
3189
+ }
3190
+ __name2(modelPatch, "modelPatch");
3191
+ const _OpenAIClient = class _OpenAIClient {
3192
+ config;
3193
+ constructor(config) {
3194
+ this.config = config;
3195
+ }
3196
+ async invoke(messages, tools2, abortSignal) {
3197
+ const openaiTools = Object.entries(tools2).map(([name, tool22]) => zodToOpenAITool(name, tool22));
3198
+ let response;
3199
+ try {
3200
+ response = await fetch(`${this.config.baseURL}/chat/completions`, {
3201
+ method: "POST",
3202
+ headers: {
3203
+ "Content-Type": "application/json",
3204
+ Authorization: `Bearer ${this.config.apiKey}`
3205
+ },
3206
+ body: JSON.stringify(
3207
+ modelPatch({
3208
+ model: this.config.model,
3209
+ temperature: this.config.temperature,
3210
+ max_tokens: this.config.maxTokens,
3211
+ messages,
3212
+ tools: openaiTools,
3213
+ // tool_choice: 'required',
3214
+ tool_choice: { type: "function", function: { name: "AgentOutput" } },
3215
+ // model specific params
3216
+ // reasoning_effort: 'minimal',
3217
+ // verbosity: 'low',
3218
+ parallel_tool_calls: false
3219
+ })
3220
+ ),
3221
+ signal: abortSignal
3222
+ });
3223
+ } catch (error2) {
3224
+ throw new InvokeError(InvokeErrorType.NETWORK_ERROR, "Network request failed", error2);
3225
+ }
3226
+ if (!response.ok) {
3227
+ const errorData = await response.json().catch();
3228
+ const errorMessage = errorData.error?.message || response.statusText;
3229
+ if (response.status === 401 || response.status === 403) {
3230
+ throw new InvokeError(
3231
+ InvokeErrorType.AUTH_ERROR,
3232
+ `Authentication failed: ${errorMessage}`,
3233
+ errorData
3234
+ );
3235
+ }
3236
+ if (response.status === 429) {
3237
+ throw new InvokeError(
3238
+ InvokeErrorType.RATE_LIMIT,
3239
+ `Rate limit exceeded: ${errorMessage}`,
3240
+ errorData
3241
+ );
3242
+ }
3243
+ if (response.status >= 500) {
3244
+ throw new InvokeError(
3245
+ InvokeErrorType.SERVER_ERROR,
3246
+ `Server error: ${errorMessage}`,
3247
+ errorData
3248
+ );
3249
+ }
3250
+ throw new InvokeError(
3251
+ InvokeErrorType.UNKNOWN,
3252
+ `HTTP ${response.status}: ${errorMessage}`,
3253
+ errorData
3254
+ );
3255
+ }
3256
+ const data = await response.json();
3257
+ const tool2 = tools2.AgentOutput;
3258
+ const macroToolInput = lenientParseMacroToolCall(data, tool2.inputSchema);
3259
+ let toolResult;
3260
+ try {
3261
+ toolResult = await tool2.execute(macroToolInput);
3262
+ } catch (e) {
3263
+ throw new InvokeError(
3264
+ InvokeErrorType.TOOL_EXECUTION_ERROR,
3265
+ `Tool execution failed: ${e.message}`,
3266
+ e
3267
+ );
3268
+ }
3269
+ return {
3270
+ toolCall: {
3271
+ // id: toolCall.id,
3272
+ name: "AgentOutput",
3273
+ args: macroToolInput
3274
+ },
3275
+ toolResult,
3276
+ usage: {
3277
+ promptTokens: data.usage?.prompt_tokens ?? 0,
3278
+ completionTokens: data.usage?.completion_tokens ?? 0,
3279
+ totalTokens: data.usage?.total_tokens ?? 0,
3280
+ cachedTokens: data.usage?.prompt_tokens_details?.cached_tokens,
3281
+ reasoningTokens: data.usage?.completion_tokens_details?.reasoning_tokens
3282
+ },
3283
+ rawResponse: data
3284
+ };
3522
3285
  }
3523
3286
  };
3524
- _cursor = new WeakMap();
3525
- _currentCursorX = new WeakMap();
3526
- _currentCursorY = new WeakMap();
3527
- _targetCursorX = new WeakMap();
3528
- _targetCursorY = new WeakMap();
3529
- _SimulatorMask_instances = new WeakSet();
3530
- createCursor_fn = /* @__PURE__ */ __name2(function() {
3531
- __privateGet(this, _cursor).className = cursorStyles.cursor;
3532
- const rippleContainer = document.createElement("div");
3533
- rippleContainer.className = cursorStyles.cursorRipple;
3534
- __privateGet(this, _cursor).appendChild(rippleContainer);
3535
- const fillingLayer = document.createElement("div");
3536
- fillingLayer.className = cursorStyles.cursorFilling;
3537
- __privateGet(this, _cursor).appendChild(fillingLayer);
3538
- const borderLayer = document.createElement("div");
3539
- borderLayer.className = cursorStyles.cursorBorder;
3540
- __privateGet(this, _cursor).appendChild(borderLayer);
3541
- this.wrapper.appendChild(__privateGet(this, _cursor));
3542
- }, "#createCursor");
3543
- moveCursorToTarget_fn = /* @__PURE__ */ __name2(function() {
3544
- const newX = __privateGet(this, _currentCursorX) + (__privateGet(this, _targetCursorX) - __privateGet(this, _currentCursorX)) * 0.2;
3545
- const newY = __privateGet(this, _currentCursorY) + (__privateGet(this, _targetCursorY) - __privateGet(this, _currentCursorY)) * 0.2;
3546
- const xDistance = Math.abs(newX - __privateGet(this, _targetCursorX));
3547
- if (xDistance > 0) {
3548
- if (xDistance < 2) {
3549
- __privateSet(this, _currentCursorX, __privateGet(this, _targetCursorX));
3550
- } else {
3551
- __privateSet(this, _currentCursorX, newX);
3287
+ __name2(_OpenAIClient, "OpenAIClient");
3288
+ let OpenAIClient = _OpenAIClient;
3289
+ const _LLM = class _LLM extends EventTarget {
3290
+ config;
3291
+ client;
3292
+ constructor(config) {
3293
+ super();
3294
+ this.config = parseLLMConfig(config);
3295
+ this.client = new OpenAIClient({
3296
+ model: this.config.model,
3297
+ apiKey: this.config.apiKey,
3298
+ baseURL: this.config.baseURL,
3299
+ temperature: this.config.temperature,
3300
+ maxTokens: this.config.maxTokens
3301
+ });
3302
+ }
3303
+ /**
3304
+ * - call llm api *once*
3305
+ * - invoke tool call *once*
3306
+ * - return the result of the tool
3307
+ */
3308
+ async invoke(messages, tools2, abortSignal) {
3309
+ return await withRetry(
3310
+ async () => {
3311
+ const result2 = await this.client.invoke(messages, tools2, abortSignal);
3312
+ return result2;
3313
+ },
3314
+ // retry settings
3315
+ {
3316
+ maxRetries: this.config.maxRetries,
3317
+ onRetry: /* @__PURE__ */ __name2((current) => {
3318
+ this.dispatchEvent(
3319
+ new CustomEvent("retry", { detail: { current, max: this.config.maxRetries } })
3320
+ );
3321
+ }, "onRetry"),
3322
+ onError: /* @__PURE__ */ __name2((error2) => {
3323
+ this.dispatchEvent(new CustomEvent("error", { detail: { error: error2 } }));
3324
+ }, "onError")
3325
+ }
3326
+ );
3327
+ }
3328
+ };
3329
+ __name2(_LLM, "LLM");
3330
+ let LLM = _LLM;
3331
+ async function withRetry(fn, settings) {
3332
+ let retries = 0;
3333
+ let lastError = null;
3334
+ while (retries <= settings.maxRetries) {
3335
+ if (retries > 0) {
3336
+ settings.onRetry(retries);
3337
+ await new Promise((resolve) => setTimeout(resolve, 100));
3338
+ }
3339
+ try {
3340
+ return await fn();
3341
+ } catch (error2) {
3342
+ console.error(error2);
3343
+ settings.onError(error2);
3344
+ if (error2?.name === "AbortError") throw error2;
3345
+ if (error2 instanceof InvokeError && !error2.retryable) throw error2;
3346
+ lastError = error2;
3347
+ retries++;
3348
+ await new Promise((resolve) => setTimeout(resolve, 100));
3552
3349
  }
3553
- __privateGet(this, _cursor).style.left = `${__privateGet(this, _currentCursorX)}px`;
3554
3350
  }
3555
- const yDistance = Math.abs(newY - __privateGet(this, _targetCursorY));
3556
- if (yDistance > 0) {
3557
- if (yDistance < 2) {
3558
- __privateSet(this, _currentCursorY, __privateGet(this, _targetCursorY));
3559
- } else {
3560
- __privateSet(this, _currentCursorY, newY);
3351
+ throw lastError;
3352
+ }
3353
+ __name2(withRetry, "withRetry");
3354
+ const SYSTEM_PROMPT = 'You are an AI agent designed to operate in an iterative loop to automate browser tasks. Your ultimate goal is accomplishing the task provided in <user_request>.\n\n<intro>\nYou excel at following tasks:\n1. Navigating complex websites and extracting precise information\n2. Automating form submissions and interactive web actions\n3. Gathering and saving information \n4. Operate effectively in an agent loop\n5. Efficiently performing diverse web tasks\n</intro>\n\n<language_settings>\n- Default working language: **中文**\n- Use the language that user is using. Return in user\'s language.\n</language_settings>\n\n<input>\nAt every step, your input will consist of: \n1. <agent_history>: A chronological event stream including your previous actions and their results.\n2. <agent_state>: Current <user_request> and <step_info>.\n3. <browser_state>: Current URL, interactive elements indexed for actions, and visible page content.\n</input>\n\n<agent_history>\nAgent history will be given as a list of step information as follows:\n\n<step_{step_number}>:\nEvaluation of Previous Step: Assessment of last action\nMemory: Your memory of this step\nNext Goal: Your goal for this step\nAction Results: Your actions and their results\n</step_{step_number}>\n\nand system messages wrapped in <sys> tag.\n</agent_history>\n\n<user_request>\nUSER REQUEST: This is your ultimate objective and always remains visible.\n- This has the highest priority. Make the user happy.\n- If the user request is very specific - then carefully follow each step and dont skip or hallucinate steps.\n- If the task is open ended you can plan yourself how to get it done.\n</user_request>\n\n<browser_state>\n1. Browser State will be given as:\n\nCurrent URL: URL of the page you are currently viewing.\nInteractive Elements: All interactive elements will be provided in format as [index]<type>text</type> where\n- index: Numeric identifier for interaction\n- type: HTML element type (button, input, etc.)\n- text: Element description\n\nExamples:\n[33]<div>User form</div>\n\\t*[35]<button aria-label=\'Submit form\'>Submit</button>\n\nNote that:\n- Only elements with numeric indexes in [] are interactive\n- (stacked) indentation (with \\t) is important and means that the element is a (html) child of the element above (with a lower index)\n- Elements tagged with `*[` are the new clickable elements that appeared on the website since the last step - if url has not changed.\n- Pure text elements without [] are not interactive.\n</browser_state>\n\n<browser_rules>\nStrictly follow these rules while using the browser and navigating the web:\n- Only interact with elements that have a numeric [index] assigned.\n- Only use indexes that are explicitly provided.\n- If the page changes after, for example, an input text action, analyze if you need to interact with new elements, e.g. selecting the right option from the list.\n- By default, only elements in the visible viewport are listed. Use scrolling actions if you suspect relevant content is offscreen which you need to interact with. Scroll ONLY if there are more pixels below or above the page.\n- You can scroll by a specific number of pages using the num_pages parameter (e.g., 0.5 for half page, 2.0 for two pages).\n- All the elements that are scrollable are marked with `data-scrollable` attribute. Including the scrollable distance in every directions. You can scroll *the element* in case some area are overflowed.\n- If a captcha appears, tell user you can not solve captcha. finished the task and ask user to solve it.\n- If expected elements are missing, try scrolling, or navigating back.\n- If the page is not fully loaded, use the `wait` action.\n- Do not repeat one action for more than 3 times unless some conditions changed.\n- If you fill an input field and your action sequence is interrupted, most often something changed e.g. suggestions popped up under the field.\n- If the <user_request> includes specific page information such as product type, rating, price, location, etc., try to apply filters to be more efficient.\n- The <user_request> is the ultimate goal. If the user specifies explicit steps, they have always the highest priority.\n- If you input_text into a field, you might need to press enter, click the search button, or select from dropdown for completion.\n- Don\'t login into a page if you don\'t have to. Don\'t login if you don\'t have the credentials. \n- There are 2 types of tasks always first think which type of request you are dealing with:\n1. Very specific step by step instructions:\n- Follow them as very precise and don\'t skip steps. Try to complete everything as requested.\n2. Open ended tasks. Plan yourself, be creative in achieving them.\n- If you get stuck e.g. with logins or captcha in open-ended tasks you can re-evaluate the task and try alternative ways, e.g. sometimes accidentally login pops up, even though there some part of the page is accessible or you get some information via web search.\n</browser_rules>\n\n<capability>\n- You can only handle single page app. Do not jump out of current page.\n- Do not click on link if it will open in a new page (etc. <a target="_blank">)\n- It is ok to fail the task.\n - User can be wrong. If the request of user is not achievable, inappropriate or you do not have enough information or tools to achieve it. Tell user to make a better request.\n - Webpage can be broken. All webpages or apps have bugs. Some bug will make it hard for your job. It\'s encouraged to tell user the problem of current page. Your feedbacks (including failing) are valuable for user.\n - Trying to hard can be harmful. Repeating some action back and forth or pushing for a complex procedure with little knowledge can cause unwanted result and harmful side-effects. User would rather you to complete the task with a fail.\n- If you are not clear about the request or steps. `ask_user` to clarify it.\n- If you do not have knowledge for the current webpage or task. You must require user to give specific instructions and detailed steps.\n</capability>\n\n<task_completion_rules>\nYou must call the `done` action in one of three cases:\n- When you have fully completed the USER REQUEST.\n- When you reach the final allowed step (`max_steps`), even if the task is incomplete.\n- When you feel stuck or unable to solve user request. Or user request is not clear or contains inappropriate content.\n- If it is ABSOLUTELY IMPOSSIBLE to continue.\n\nThe `done` action is your opportunity to terminate and share your findings with the user.\n- Set `success` to `true` only if the full USER REQUEST has been completed with no missing components.\n- If any part of the request is missing, incomplete, or uncertain, set `success` to `false`.\n- You can use the `text` field of the `done` action to communicate your findings and to provide a coherent reply to the user and fulfill the USER REQUEST.\n- You are ONLY ALLOWED to call `done` as a single action. Don\'t call it together with other actions.\n- If the user asks for specified format, such as "return JSON with following structure", "return a list of format...", MAKE sure to use the right format in your answer.\n- If the user asks for a structured output, your `done` action\'s schema may be modified. Take this schema into account when solving the task!\n</task_completion_rules>\n\n<reasoning_rules>\nExhibit the following reasoning patterns to successfully achieve the <user_request>:\n\n- Reason about <agent_history> to track progress and context toward <user_request>.\n- Analyze the most recent "Next Goal" and "Action Result" in <agent_history> and clearly state what you previously tried to achieve.\n- Analyze all relevant items in <agent_history> and <browser_state> to understand your state.\n- Explicitly judge success/failure/uncertainty of the last action. Never assume an action succeeded just because it appears to be executed in your last step in <agent_history>. If the expected change is missing, mark the last action as failed (or uncertain) and plan a recovery.\n- Analyze whether you are stuck, e.g. when you repeat the same actions multiple times without any progress. Then consider alternative approaches e.g. scrolling for more context or ask user for help.\n- `ask_user` for help if you have any difficulty. Users want to be kept in the loop.\n- If you see information relevant to <user_request>, plan saving the information to memory.\n- Always reason about the <user_request>. Make sure to carefully analyze the specific steps and information required. E.g. specific filters, specific form fields, specific information to search. Make sure to always compare the current trajectory with the user request and think carefully if thats how the user requested it.\n</reasoning_rules>\n\n<examples>\nHere are examples of good output patterns. Use them as reference but never copy them directly.\n\n<evaluation_examples>\n- Positive Examples:\n"evaluation_previous_goal": "Successfully navigated to the product page and found the target information. Verdict: Success"\n"evaluation_previous_goal": "Clicked the login button and user authentication form appeared. Verdict: Success"\n</evaluation_examples>\n\n<memory_examples>\n"memory": "Found many pending reports that need to be analyzed in the main page. Successfully processed the first 2 reports on quarterly sales data and moving on to inventory analysis and customer feedback reports."\n</memory_examples>\n\n<next_goal_examples>\n"next_goal": "Click on the \'Add to Cart\' button to proceed with the purchase flow."\n"next_goal": "Extract details from the first item on the page."\n</next_goal_examples>\n</examples>\n\n<output>\nYou must ALWAYS respond with a valid JSON in this exact format:\n\n{\n "evaluation_previous_goal": "Concise one-sentence analysis of your last action. Clearly state success, failure, or uncertain.",\n "memory": "1-3 concise sentences of specific memory of this step and overall progress. You should put here everything that will help you track progress in future steps. Like counting pages visited, items found, etc.",\n "next_goal": "State the next immediate goal and action to achieve it, in one clear sentence."\n "action":{"one_action_name": {// action-specific parameter}}\n}\n</output>\n';
3355
+ async function waitUntil(check, timeout = 60 * 601e3) {
3356
+ if (check()) return true;
3357
+ return new Promise((resolve, reject) => {
3358
+ const start = Date.now();
3359
+ const interval = setInterval(() => {
3360
+ if (check()) {
3361
+ clearInterval(interval);
3362
+ resolve(true);
3363
+ } else if (Date.now() - start > timeout) {
3364
+ clearInterval(interval);
3365
+ reject(new Error("Timeout waiting for condition to become true"));
3366
+ }
3367
+ }, 100);
3368
+ });
3369
+ }
3370
+ __name2(waitUntil, "waitUntil");
3371
+ async function waitFor(seconds) {
3372
+ await new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
3373
+ }
3374
+ __name2(waitFor, "waitFor");
3375
+ function trimLines(text) {
3376
+ return text.split("\n").map((line) => line.trim()).join("\n");
3377
+ }
3378
+ __name2(trimLines, "trimLines");
3379
+ function randomID(existingIDs) {
3380
+ let id = Math.random().toString(36).substring(2, 11);
3381
+ if (!existingIDs) {
3382
+ return id;
3383
+ }
3384
+ const MAX_TRY = 1e3;
3385
+ let tryCount = 0;
3386
+ while (existingIDs.includes(id)) {
3387
+ id = Math.random().toString(36).substring(2, 11);
3388
+ tryCount++;
3389
+ if (tryCount > MAX_TRY) {
3390
+ throw new Error("randomID: too many try");
3561
3391
  }
3562
- __privateGet(this, _cursor).style.top = `${__privateGet(this, _currentCursorY)}px`;
3563
3392
  }
3564
- requestAnimationFrame(() => __privateMethod(this, _SimulatorMask_instances, moveCursorToTarget_fn).call(this));
3565
- }, "#moveCursorToTarget");
3566
- __name2(_SimulatorMask, "SimulatorMask");
3567
- let SimulatorMask = _SimulatorMask;
3393
+ return id;
3394
+ }
3395
+ __name2(randomID, "randomID");
3396
+ if (!window.__PAGE_AGENT_IDS__) {
3397
+ window.__PAGE_AGENT_IDS__ = [];
3398
+ }
3399
+ const ids = window.__PAGE_AGENT_IDS__;
3400
+ function uid() {
3401
+ const id = randomID(ids);
3402
+ ids.push(id);
3403
+ return id;
3404
+ }
3405
+ __name2(uid, "uid");
3406
+ function tool(options) {
3407
+ return options;
3408
+ }
3409
+ __name2(tool, "tool");
3410
+ const tools = /* @__PURE__ */ new Map();
3411
+ tools.set(
3412
+ "done",
3413
+ tool({
3414
+ description: "Complete task - provide a summary of results for the user. Set success=True if task completed successfully, false otherwise. Text should be your response to the user summarizing results.",
3415
+ inputSchema: zod.object({
3416
+ text: zod.string(),
3417
+ success: zod.boolean().default(true)
3418
+ }),
3419
+ execute: /* @__PURE__ */ __name2(async function(input2) {
3420
+ return Promise.resolve("Task completed");
3421
+ }, "execute")
3422
+ })
3423
+ );
3424
+ tools.set(
3425
+ "wait",
3426
+ tool({
3427
+ description: "Wait for x seconds. default 1s (max 10 seconds, min 1 second). This can be used to wait until the page or data is fully loaded.",
3428
+ inputSchema: zod.object({
3429
+ seconds: zod.number().min(1).max(10).default(1)
3430
+ }),
3431
+ execute: /* @__PURE__ */ __name2(async function(input2) {
3432
+ const lastTimeUpdate = await this.pageController.getLastUpdateTime();
3433
+ const actualWaitTime = Math.max(0, input2.seconds - (Date.now() - lastTimeUpdate) / 1e3);
3434
+ console.log(`actualWaitTime: ${actualWaitTime} seconds`);
3435
+ await waitFor(actualWaitTime);
3436
+ return `✅ Waited for ${input2.seconds} seconds.`;
3437
+ }, "execute")
3438
+ })
3439
+ );
3440
+ tools.set(
3441
+ "ask_user",
3442
+ tool({
3443
+ description: "Ask the user a question and wait for their answer. Use this if you need more information or clarification.",
3444
+ inputSchema: zod.object({
3445
+ question: zod.string()
3446
+ }),
3447
+ execute: /* @__PURE__ */ __name2(async function(input2) {
3448
+ const answer = await this.panel.askUser(input2.question);
3449
+ return `✅ Received user answer: ${answer}`;
3450
+ }, "execute")
3451
+ })
3452
+ );
3453
+ tools.set(
3454
+ "click_element_by_index",
3455
+ tool({
3456
+ description: "Click element by index",
3457
+ inputSchema: zod.object({
3458
+ index: zod.int().min(0)
3459
+ }),
3460
+ execute: /* @__PURE__ */ __name2(async function(input2) {
3461
+ const result2 = await this.pageController.clickElement(input2.index);
3462
+ return result2.message;
3463
+ }, "execute")
3464
+ })
3465
+ );
3466
+ tools.set(
3467
+ "input_text",
3468
+ tool({
3469
+ description: "Click and input text into a input interactive element",
3470
+ inputSchema: zod.object({
3471
+ index: zod.int().min(0),
3472
+ text: zod.string()
3473
+ }),
3474
+ execute: /* @__PURE__ */ __name2(async function(input2) {
3475
+ const result2 = await this.pageController.inputText(input2.index, input2.text);
3476
+ return result2.message;
3477
+ }, "execute")
3478
+ })
3479
+ );
3480
+ tools.set(
3481
+ "select_dropdown_option",
3482
+ tool({
3483
+ description: "Select dropdown option for interactive element index by the text of the option you want to select",
3484
+ inputSchema: zod.object({
3485
+ index: zod.int().min(0),
3486
+ text: zod.string()
3487
+ }),
3488
+ execute: /* @__PURE__ */ __name2(async function(input2) {
3489
+ const result2 = await this.pageController.selectOption(input2.index, input2.text);
3490
+ return result2.message;
3491
+ }, "execute")
3492
+ })
3493
+ );
3494
+ tools.set(
3495
+ "scroll",
3496
+ tool({
3497
+ description: "Scroll the page by specified number of pages (set down=True to scroll down, down=False to scroll up, num_pages=number of pages to scroll like 0.5 for half page, 1.0 for one page, etc.). Optional index parameter to scroll within a specific element or its scroll container (works well for dropdowns and custom UI components). Optional pixels parameter to scroll by a specific number of pixels instead of pages.",
3498
+ inputSchema: zod.object({
3499
+ down: zod.boolean().default(true),
3500
+ num_pages: zod.number().min(0).max(10).optional().default(0.1),
3501
+ pixels: zod.number().int().min(0).optional(),
3502
+ index: zod.number().int().min(0).optional()
3503
+ }),
3504
+ execute: /* @__PURE__ */ __name2(async function(input2) {
3505
+ const result2 = await this.pageController.scroll({
3506
+ ...input2,
3507
+ numPages: input2.num_pages
3508
+ });
3509
+ return result2.message;
3510
+ }, "execute")
3511
+ })
3512
+ );
3513
+ tools.set(
3514
+ "scroll_horizontally",
3515
+ tool({
3516
+ description: "Scroll the page or element horizontally (set right=True to scroll right, right=False to scroll left, pixels=number of pixels to scroll). Optional index parameter to scroll within a specific element or its scroll container (works well for wide tables).",
3517
+ inputSchema: zod.object({
3518
+ right: zod.boolean().default(true),
3519
+ pixels: zod.number().int().min(0),
3520
+ index: zod.number().int().min(0).optional()
3521
+ }),
3522
+ execute: /* @__PURE__ */ __name2(async function(input2) {
3523
+ const result2 = await this.pageController.scrollHorizontally(input2);
3524
+ return result2.message;
3525
+ }, "execute")
3526
+ })
3527
+ );
3528
+ tools.set(
3529
+ "execute_javascript",
3530
+ tool({
3531
+ description: "Execute JavaScript code on the current page. Supports async/await syntax. Use with caution!",
3532
+ inputSchema: zod.object({
3533
+ script: zod.string()
3534
+ }),
3535
+ execute: /* @__PURE__ */ __name2(async function(input2) {
3536
+ const result2 = await this.pageController.executeJavascript(input2.script);
3537
+ return result2.message;
3538
+ }, "execute")
3539
+ })
3540
+ );
3568
3541
  function assert(condition, message, silent) {
3569
3542
  if (!condition) {
3570
3543
  const errorMessage = message ?? "Assertion failed";
@@ -3576,32 +3549,51 @@ __name2(assert, "assert");
3576
3549
  const _PageAgent = class _PageAgent extends EventTarget {
3577
3550
  constructor(config = {}) {
3578
3551
  super();
3579
- __privateAdd(this, _PageAgent_instances);
3580
- __publicField(this, "config");
3581
- __publicField(this, "id", uid());
3582
- __publicField(this, "bus", getEventBus(this.id));
3583
- __publicField(this, "i18n");
3584
- __publicField(this, "panel");
3585
- __publicField(this, "tools");
3586
- __publicField(this, "paused", false);
3587
- __publicField(this, "disposed", false);
3588
- __publicField(this, "task", "");
3589
- __publicField(this, "taskId", "");
3590
- __privateAdd(this, _llm);
3591
- __privateAdd(this, _totalWaitTime, 0);
3592
- __privateAdd(this, _abortController, new AbortController());
3552
+ __privateAdd2(this, _PageAgent_instances);
3553
+ __publicField2(this, "config");
3554
+ __publicField2(this, "id", uid());
3555
+ __publicField2(this, "panel");
3556
+ __publicField2(this, "tools");
3557
+ __publicField2(this, "paused", false);
3558
+ __publicField2(this, "disposed", false);
3559
+ __publicField2(this, "task", "");
3560
+ __publicField2(this, "taskId", "");
3561
+ __privateAdd2(this, _llm);
3562
+ __privateAdd2(this, _totalWaitTime, 0);
3563
+ __privateAdd2(this, _abortController, new AbortController());
3564
+ __privateAdd2(this, _llmRetryListener, null);
3565
+ __privateAdd2(this, _llmErrorListener, null);
3566
+ __privateAdd2(this, _beforeUnloadListener, null);
3593
3567
  /** PageController for DOM operations */
3594
- __publicField(this, "pageController");
3568
+ __publicField2(this, "pageController");
3595
3569
  /** Fullscreen mask */
3596
- __publicField(this, "mask", new SimulatorMask());
3570
+ __publicField2(this, "mask", new SimulatorMask());
3597
3571
  /** History records */
3598
- __publicField(this, "history", []);
3572
+ __publicField2(this, "history", []);
3599
3573
  this.config = config;
3600
- __privateSet(this, _llm, new LLM(this.config, this.id));
3601
- this.i18n = new I18n(this.config.language);
3602
- this.panel = new Panel(this);
3574
+ __privateSet2(this, _llm, new LLM(this.config));
3575
+ this.panel = new Panel({
3576
+ language: this.config.language,
3577
+ onExecuteTask: /* @__PURE__ */ __name2((task) => this.execute(task), "onExecuteTask"),
3578
+ onStop: /* @__PURE__ */ __name2(() => this.dispose(), "onStop"),
3579
+ onPauseToggle: /* @__PURE__ */ __name2(() => {
3580
+ this.paused = !this.paused;
3581
+ return this.paused;
3582
+ }, "onPauseToggle"),
3583
+ getPaused: /* @__PURE__ */ __name2(() => this.paused, "getPaused")
3584
+ });
3603
3585
  this.tools = new Map(tools);
3604
3586
  this.pageController = new PageController(this.config);
3587
+ __privateSet2(this, _llmRetryListener, (e) => {
3588
+ const { current, max } = e.detail;
3589
+ this.panel.update({ type: "retry", current, max });
3590
+ });
3591
+ __privateSet2(this, _llmErrorListener, (e) => {
3592
+ const { error: error2 } = e.detail;
3593
+ this.panel.update({ type: "error", message: `step failed: ${error2.message}` });
3594
+ });
3595
+ __privateGet2(this, _llm).addEventListener("retry", __privateGet2(this, _llmRetryListener));
3596
+ __privateGet2(this, _llm).addEventListener("error", __privateGet2(this, _llmErrorListener));
3605
3597
  if (this.config.customTools) {
3606
3598
  for (const [name, tool2] of Object.entries(this.config.customTools)) {
3607
3599
  if (tool2 === null) {
@@ -3614,9 +3606,10 @@ const _PageAgent = class _PageAgent extends EventTarget {
3614
3606
  if (!this.config.experimentalScriptExecutionTool) {
3615
3607
  this.tools.delete("execute_javascript");
3616
3608
  }
3617
- window.addEventListener("beforeunload", (e) => {
3609
+ __privateSet2(this, _beforeUnloadListener, (e) => {
3618
3610
  if (!this.disposed) this.dispose("PAGE_UNLOADING");
3619
3611
  });
3612
+ window.addEventListener("beforeunload", __privateGet2(this, _beforeUnloadListener));
3620
3613
  }
3621
3614
  /**
3622
3615
  * @todo maybe return something?
@@ -3631,15 +3624,12 @@ const _PageAgent = class _PageAgent extends EventTarget {
3631
3624
  const onAfterTask = this.config.onAfterTask || (() => void 0);
3632
3625
  await onBeforeTask.call(this);
3633
3626
  this.mask.show();
3634
- this.bus.emit("panel:show");
3635
- this.bus.emit("panel:reset");
3636
- this.bus.emit("panel:update", {
3637
- type: "input",
3638
- displayText: this.task
3639
- });
3640
- if (__privateGet(this, _abortController)) {
3641
- __privateGet(this, _abortController).abort();
3642
- __privateSet(this, _abortController, new AbortController());
3627
+ this.panel.show();
3628
+ this.panel.reset();
3629
+ this.panel.update({ type: "input", task: this.task });
3630
+ if (__privateGet2(this, _abortController)) {
3631
+ __privateGet2(this, _abortController).abort();
3632
+ __privateSet2(this, _abortController, new AbortController());
3643
3633
  }
3644
3634
  this.history = [];
3645
3635
  try {
@@ -3647,26 +3637,23 @@ const _PageAgent = class _PageAgent extends EventTarget {
3647
3637
  while (true) {
3648
3638
  await onBeforeStep.call(this, step);
3649
3639
  console.group(`step: ${step}`);
3650
- if (__privateGet(this, _abortController).signal.aborted) throw new Error("AbortError");
3640
+ if (__privateGet2(this, _abortController).signal.aborted) throw new Error("AbortError");
3651
3641
  await waitUntil(() => !this.paused);
3652
3642
  console.log(chalk.blue("Thinking..."));
3653
- this.bus.emit("panel:update", {
3654
- type: "thinking",
3655
- displayText: this.i18n.t("ui.panel.thinking")
3656
- });
3657
- const result2 = await __privateGet(this, _llm).invoke(
3643
+ this.panel.update({ type: "thinking" });
3644
+ const result2 = await __privateGet2(this, _llm).invoke(
3658
3645
  [
3659
3646
  {
3660
3647
  role: "system",
3661
- content: __privateMethod(this, _PageAgent_instances, getSystemPrompt_fn).call(this)
3648
+ content: __privateMethod2(this, _PageAgent_instances, getSystemPrompt_fn).call(this)
3662
3649
  },
3663
3650
  {
3664
3651
  role: "user",
3665
- content: await __privateMethod(this, _PageAgent_instances, assembleUserPrompt_fn).call(this)
3652
+ content: await __privateMethod2(this, _PageAgent_instances, assembleUserPrompt_fn).call(this)
3666
3653
  }
3667
3654
  ],
3668
- { AgentOutput: __privateMethod(this, _PageAgent_instances, packMacroTool_fn).call(this) },
3669
- __privateGet(this, _abortController).signal
3655
+ { AgentOutput: __privateMethod2(this, _PageAgent_instances, packMacroTool_fn).call(this) },
3656
+ __privateGet2(this, _abortController).signal
3670
3657
  );
3671
3658
  const macroResult = result2.toolResult;
3672
3659
  const input2 = macroResult.input;
@@ -3692,7 +3679,7 @@ const _PageAgent = class _PageAgent extends EventTarget {
3692
3679
  await onAfterStep.call(this, step, this.history);
3693
3680
  step++;
3694
3681
  if (step > MAX_STEPS) {
3695
- __privateMethod(this, _PageAgent_instances, onDone_fn).call(this, "Step count exceeded maximum limit", false);
3682
+ __privateMethod2(this, _PageAgent_instances, onDone_fn).call(this, "Step count exceeded maximum limit", false);
3696
3683
  const result22 = {
3697
3684
  success: false,
3698
3685
  data: "Step count exceeded maximum limit",
@@ -3705,7 +3692,7 @@ const _PageAgent = class _PageAgent extends EventTarget {
3705
3692
  const success = action.input?.success ?? false;
3706
3693
  const text = action.input?.text || "no text provided";
3707
3694
  console.log(chalk.green.bold("Task completed"), success, text);
3708
- __privateMethod(this, _PageAgent_instances, onDone_fn).call(this, text, success);
3695
+ __privateMethod2(this, _PageAgent_instances, onDone_fn).call(this, text, success);
3709
3696
  const result22 = {
3710
3697
  success,
3711
3698
  data: text,
@@ -3717,7 +3704,7 @@ const _PageAgent = class _PageAgent extends EventTarget {
3717
3704
  }
3718
3705
  } catch (error2) {
3719
3706
  console.error("Task failed", error2);
3720
- __privateMethod(this, _PageAgent_instances, onDone_fn).call(this, String(error2), false);
3707
+ __privateMethod2(this, _PageAgent_instances, onDone_fn).call(this, String(error2), false);
3721
3708
  const result2 = {
3722
3709
  success: false,
3723
3710
  data: String(error2),
@@ -3734,13 +3721,28 @@ const _PageAgent = class _PageAgent extends EventTarget {
3734
3721
  this.panel.dispose();
3735
3722
  this.mask.dispose();
3736
3723
  this.history = [];
3737
- __privateGet(this, _abortController).abort(reason ?? "PageAgent disposed");
3724
+ __privateGet2(this, _abortController).abort(reason ?? "PageAgent disposed");
3725
+ if (__privateGet2(this, _llmRetryListener)) {
3726
+ __privateGet2(this, _llm).removeEventListener("retry", __privateGet2(this, _llmRetryListener));
3727
+ __privateSet2(this, _llmRetryListener, null);
3728
+ }
3729
+ if (__privateGet2(this, _llmErrorListener)) {
3730
+ __privateGet2(this, _llm).removeEventListener("error", __privateGet2(this, _llmErrorListener));
3731
+ __privateSet2(this, _llmErrorListener, null);
3732
+ }
3733
+ if (__privateGet2(this, _beforeUnloadListener)) {
3734
+ window.removeEventListener("beforeunload", __privateGet2(this, _beforeUnloadListener));
3735
+ __privateSet2(this, _beforeUnloadListener, null);
3736
+ }
3738
3737
  this.config.onDispose?.call(this, reason);
3739
3738
  }
3740
3739
  };
3741
3740
  _llm = new WeakMap();
3742
3741
  _totalWaitTime = new WeakMap();
3743
3742
  _abortController = new WeakMap();
3743
+ _llmRetryListener = new WeakMap();
3744
+ _llmErrorListener = new WeakMap();
3745
+ _beforeUnloadListener = new WeakMap();
3744
3746
  _PageAgent_instances = new WeakSet();
3745
3747
  /**
3746
3748
  * Merge all tools into a single MacroTool with the following input:
@@ -3771,7 +3773,7 @@ packMacroTool_fn = /* @__PURE__ */ __name2(function() {
3771
3773
  return {
3772
3774
  inputSchema: macroToolSchema,
3773
3775
  execute: /* @__PURE__ */ __name2(async (input2) => {
3774
- if (__privateGet(this, _abortController).signal.aborted) throw new Error("AbortError");
3776
+ if (__privateGet2(this, _abortController).signal.aborted) throw new Error("AbortError");
3775
3777
  await waitUntil(() => !this.paused);
3776
3778
  console.log(chalk.blue.bold("MacroTool execute"), input2);
3777
3779
  const action = input2.action;
@@ -3782,43 +3784,32 @@ packMacroTool_fn = /* @__PURE__ */ __name2(function() {
3782
3784
  🎯: ${input2.next_goal}
3783
3785
  `);
3784
3786
  console.log(brain);
3785
- this.bus.emit("panel:update", {
3786
- type: "thinking",
3787
- displayText: brain
3788
- });
3787
+ this.panel.update({ type: "thinking", text: brain });
3789
3788
  const tool2 = tools2.get(toolName);
3790
3789
  assert(tool2, `Tool ${toolName} not found. (@note should have been caught before this!!!)`);
3791
3790
  console.log(chalk.blue.bold(`Executing tool: ${toolName}`), toolInput);
3792
- this.bus.emit("panel:update", {
3793
- type: "tool_executing",
3794
- toolName,
3795
- toolArgs: toolInput,
3796
- displayText: getToolExecutingText(toolName, toolInput, this.i18n)
3797
- });
3791
+ this.panel.update({ type: "toolExecuting", toolName, args: toolInput });
3798
3792
  const startTime = Date.now();
3799
3793
  let result2 = await tool2.execute.bind(this)(toolInput);
3800
3794
  const duration = Date.now() - startTime;
3801
3795
  console.log(chalk.green.bold(`Tool (${toolName}) executed for ${duration}ms`), result2);
3802
3796
  if (toolName === "wait") {
3803
- __privateSet(this, _totalWaitTime, __privateGet(this, _totalWaitTime) + Math.round(toolInput.seconds + duration / 1e3));
3797
+ __privateSet2(this, _totalWaitTime, __privateGet2(this, _totalWaitTime) + Math.round(toolInput.seconds + duration / 1e3));
3804
3798
  result2 += `
3805
- <sys> You have waited ${__privateGet(this, _totalWaitTime)} seconds accumulatively.`;
3806
- if (__privateGet(this, _totalWaitTime) >= 3)
3799
+ <sys> You have waited ${__privateGet2(this, _totalWaitTime)} seconds accumulatively.`;
3800
+ if (__privateGet2(this, _totalWaitTime) >= 3)
3807
3801
  result2 += "\nDo NOT wait any longer unless you have a good reason.\n";
3808
3802
  result2 += "</sys>";
3809
3803
  } else {
3810
- __privateSet(this, _totalWaitTime, 0);
3804
+ __privateSet2(this, _totalWaitTime, 0);
3811
3805
  }
3812
- const displayResult = getToolCompletedText(toolName, toolInput, this.i18n);
3813
- if (displayResult)
3814
- this.bus.emit("panel:update", {
3815
- type: "tool_executing",
3816
- toolName,
3817
- toolArgs: toolInput,
3818
- toolResult: result2,
3819
- displayText: displayResult,
3820
- duration
3821
- });
3806
+ this.panel.update({
3807
+ type: "toolCompleted",
3808
+ toolName,
3809
+ args: toolInput,
3810
+ result: result2,
3811
+ duration
3812
+ });
3822
3813
  await new Promise((resolve) => setTimeout(resolve, 100));
3823
3814
  return {
3824
3815
  input: input2,
@@ -3862,21 +3853,19 @@ assembleUserPrompt_fn = /* @__PURE__ */ __name2(async function() {
3862
3853
  </step_info>
3863
3854
  </agent_state>
3864
3855
  `;
3865
- prompt += await __privateMethod(this, _PageAgent_instances, getBrowserState_fn).call(this);
3856
+ prompt += await __privateMethod2(this, _PageAgent_instances, getBrowserState_fn).call(this);
3866
3857
  return trimLines(prompt);
3867
3858
  }, "#assembleUserPrompt");
3868
3859
  onDone_fn = /* @__PURE__ */ __name2(function(text, success = true) {
3869
3860
  this.pageController.cleanUpHighlights();
3870
- this.bus.emit("panel:update", {
3871
- type: success ? "output" : "error",
3872
- displayText: text
3873
- });
3874
- this.bus.emit("panel:update", {
3875
- type: "completed",
3876
- displayText: this.i18n.t("ui.panel.taskCompleted")
3877
- });
3861
+ if (success) {
3862
+ this.panel.update({ type: "output", text });
3863
+ } else {
3864
+ this.panel.update({ type: "error", message: text });
3865
+ }
3866
+ this.panel.update({ type: "completed" });
3878
3867
  this.mask.hide();
3879
- __privateGet(this, _abortController).abort();
3868
+ __privateGet2(this, _abortController).abort();
3880
3869
  }, "#onDone");
3881
3870
  getBrowserState_fn = /* @__PURE__ */ __name2(async function() {
3882
3871
  const pageUrl = await this.pageController.getCurrentUrl();