surf-cli 2.19.0 → 2.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +169 -3
- package/dist/content/index.js +4 -4
- package/dist/content/index.js.map +1 -1
- package/dist/options/options.html +1 -18
- package/dist/service-worker/index.js +44 -15
- package/dist/service-worker/index.js.map +1 -1
- package/native/cli.cjs +109 -6
- package/native/do-executor.cjs +35 -8
- package/native/doctor.cjs +200 -40
- package/native/host-helpers.cjs +95 -10
- package/native/host.cjs +24 -2
- package/native/native-host-launch-probe.cjs +69 -0
- package/native/private-state.cjs +25 -1
- package/native/semantic-cli.cjs +764 -0
- package/native/semantic-core.cjs +369 -0
- package/native/semantic-credentials.cjs +207 -0
- package/native/semantic-provider.cjs +61 -0
- package/native/semantic-workflow-executor.cjs +65 -0
- package/native/semantic-workflow-state.cjs +271 -0
- package/native/semantic-workflow.cjs +398 -0
- package/native/tool-scope.cjs +1 -0
- package/native/workflow-definition.cjs +125 -1
- package/native/workflow-runtime.cjs +71 -5
- package/package.json +8 -4
- package/scripts/install-native-host.cjs +103 -60
- package/scripts/uninstall-native-host.cjs +40 -38
- package/scripts/windows-interop.cjs +89 -0
- package/skills/surf/SKILL.md +78 -1
package/README.md
CHANGED
|
@@ -726,6 +726,9 @@ surf do 'go "url" | click e5 | screenshot' --dry-run
|
|
|
726
726
|
- `--step-delay <ms>` - Delay between steps (default: 100, use 0 to disable)
|
|
727
727
|
- `--no-auto-wait` - Disable automatic waits between steps
|
|
728
728
|
- `--json` - Output structured JSON result
|
|
729
|
+
- `--allow-semantic` - Opt in to bounded TypeSafe decisions for a semantic workflow
|
|
730
|
+
- `--allow-write` - Additionally authorize declared `fill`, `ensureChecked`, and `click` steps
|
|
731
|
+
- `--inputs-stdin` - Read one bounded JSON object of private local input slots from stdin
|
|
729
732
|
- `--<arg> <value>` - Pass arguments to workflow (e.g., `--url "..."`)
|
|
730
733
|
|
|
731
734
|
**Auto-waits:** Commands that trigger page changes automatically wait for completion:
|
|
@@ -820,7 +823,67 @@ surf workflow.info my-workflow
|
|
|
820
823
|
surf workflow.validate ./my-workflow.json
|
|
821
824
|
```
|
|
822
825
|
|
|
823
|
-
|
|
826
|
+
#### Bounded semantic workflow steps
|
|
827
|
+
|
|
828
|
+
Semantic workflow files declare `"semantic": { "version": 1 }` and use only
|
|
829
|
+
linear `semantic.step` operations: `find`, `open`, `ensureChecked`, `fill`,
|
|
830
|
+
`click`, and `assert`. Validate or dry-run them offline, then opt in explicitly:
|
|
831
|
+
|
|
832
|
+
```bash
|
|
833
|
+
surf workflow.validate ./product.json
|
|
834
|
+
surf do --file product.json --dry-run
|
|
835
|
+
printf '%s' '{"quantity":"2"}' | SURF_SESSION=shopping surf do \
|
|
836
|
+
--file product.json --inputs-stdin --allow-semantic --allow-write --json
|
|
837
|
+
```
|
|
838
|
+
|
|
839
|
+
```json
|
|
840
|
+
{
|
|
841
|
+
"name": "configure-matching-product",
|
|
842
|
+
"semantic": { "version": 1, "deadlineMs": 60000, "maxProviderCalls": 32 },
|
|
843
|
+
"steps": [
|
|
844
|
+
{ "id": "find-product", "tool": "semantic.step", "as": "product", "args": {
|
|
845
|
+
"op": "find", "target": { "query": "The in-stock blue insulated bottle", "role": "link" },
|
|
846
|
+
"search": { "mode": "scroll", "maxObservations": 12 }
|
|
847
|
+
} },
|
|
848
|
+
{ "id": "open-product", "tool": "semantic.step", "args": {
|
|
849
|
+
"op": "open", "target": { "binding": "product" }
|
|
850
|
+
} },
|
|
851
|
+
{ "id": "select-gift-wrap", "tool": "semantic.step", "args": {
|
|
852
|
+
"op": "ensureChecked", "target": { "query": "Gift wrap", "role": "checkbox" },
|
|
853
|
+
"checked": true
|
|
854
|
+
} },
|
|
855
|
+
{ "id": "set-quantity", "tool": "semantic.step", "args": {
|
|
856
|
+
"op": "fill", "target": { "query": "Quantity", "role": "spinbutton" },
|
|
857
|
+
"input": "quantity"
|
|
858
|
+
} },
|
|
859
|
+
{ "id": "add-to-cart", "tool": "semantic.step", "args": {
|
|
860
|
+
"op": "click", "target": { "query": "Add to cart", "role": "button" },
|
|
861
|
+
"expect": { "kind": "visible", "target": { "query": "Remove from cart", "role": "button" } }
|
|
862
|
+
} },
|
|
863
|
+
{ "id": "verify-cart", "tool": "semantic.step", "args": {
|
|
864
|
+
"op": "assert", "mode": "semantic",
|
|
865
|
+
"claim": "The cart contains the selected product with gift wrap enabled",
|
|
866
|
+
"bindings": ["product"]
|
|
867
|
+
} }
|
|
868
|
+
]
|
|
869
|
+
}
|
|
870
|
+
```
|
|
871
|
+
|
|
872
|
+
This example includes every supported operation and the required `claim` for a
|
|
873
|
+
semantic `assert`. Use it as a valid starting shape, then remove steps the task
|
|
874
|
+
does not need.
|
|
875
|
+
|
|
876
|
+
`open` performs freshly validated same-origin HTTP(S) navigation; it never falls
|
|
877
|
+
back to a click. Model-derived writes retain the `0.95` gate, dispatch at most
|
|
878
|
+
once in a run, and require local/read-only verification. A stopped or uncertain
|
|
879
|
+
step fails the workflow. Search reports bounded overlapping coverage and does
|
|
880
|
+
not prove global ranking or absence outside that scope. Local input values are
|
|
881
|
+
sent only to their browser fill/compare operation, not to TypeSafe, workflow
|
|
882
|
+
variables, events, output, or checkpoints. A new run can repeat an external
|
|
883
|
+
effect: Surf does not claim exactly-once server behavior or automatic resume.
|
|
884
|
+
|
|
885
|
+
**Supported commands:** Ordinary workflows support all Surf commands. Semantic
|
|
886
|
+
v1 workflows intentionally support only the six closed operations above.
|
|
824
887
|
|
|
825
888
|
### Playbooks
|
|
826
889
|
|
|
@@ -913,11 +976,109 @@ successful result payloads retain their existing behavior. In particular, a
|
|
|
913
976
|
connection failure still prints stderr, leaves stdout empty and exits 1 with
|
|
914
977
|
`--json`, even with `--soft-fail`.
|
|
915
978
|
|
|
979
|
+
## Optional Jev semantic commands
|
|
980
|
+
|
|
981
|
+
`semantic.act` is a bounded, goal-driven website controller. Give it an outcome
|
|
982
|
+
and it repeatedly observes the current page, asks Jev to select the next action
|
|
983
|
+
from Surf's allowed menu, validates and executes that action, then checks whether
|
|
984
|
+
the overall goal is complete. It stops when the goal is satisfied, a decision is
|
|
985
|
+
uncertain, or a step, provider-call, or time budget is exhausted.
|
|
986
|
+
|
|
987
|
+
```text
|
|
988
|
+
agent goal
|
|
989
|
+
|
|
|
990
|
+
v
|
|
991
|
+
Surf observes -> Jev selects -> Surf validates + acts -> Jev checks goal
|
|
992
|
+
^ |
|
|
993
|
+
+---------------- goal incomplete -----------------------+
|
|
994
|
+
|
|
|
995
|
+
complete / uncertain / budget reached
|
|
996
|
+
|
|
|
997
|
+
v
|
|
998
|
+
return result
|
|
999
|
+
```
|
|
1000
|
+
|
|
1001
|
+
The other semantic commands expose individual parts of that loop:
|
|
1002
|
+
|
|
1003
|
+
```text
|
|
1004
|
+
semantic.find select one control matching a goal
|
|
1005
|
+
semantic.filter rank the page regions relevant to a goal
|
|
1006
|
+
semantic.verify check whether one outcome is visible
|
|
1007
|
+
semantic.act run the bounded observe/choose/act/verify loop
|
|
1008
|
+
```
|
|
1009
|
+
|
|
1010
|
+
This is most useful when the agent does not yet know a site's structure or happy
|
|
1011
|
+
path: Jev handles next-action selection and goal verification while Surf builds
|
|
1012
|
+
the allowed action menu and enforces permissions, confidence thresholds, and
|
|
1013
|
+
element freshness. The agent owns the goal and final confirmation. Once the path
|
|
1014
|
+
is known and stable, deterministic Surf commands are usually faster and more
|
|
1015
|
+
reliable for repeated execution.
|
|
1016
|
+
|
|
1017
|
+
Semantic commands are an explicit remote-AI boundary: only `surf semantic.*`
|
|
1018
|
+
sends a bounded, value-free current-page observation to TypeSafe. Existing Surf
|
|
1019
|
+
commands do not read a TypeSafe credential, load the SDK, or make provider calls.
|
|
1020
|
+
|
|
1021
|
+
```bash
|
|
1022
|
+
surf semantic.find "the control for notification preferences"
|
|
1023
|
+
surf semantic.verify "Notification preferences were saved" --json
|
|
1024
|
+
surf semantic.filter "notification preferences" --top 6
|
|
1025
|
+
surf semantic.act "Open notification settings" --max-steps 5
|
|
1026
|
+
surf semantic.act "Fill the email field" --input email="$EMAIL" --allow-write
|
|
1027
|
+
surf semantic.act 'Add the selected item to the cart' --allow-write --threshold write=0.85
|
|
1028
|
+
surf semantic auth set # hidden prompt, or exactly one stdin line
|
|
1029
|
+
surf semantic auth status # source and redacted fingerprint only
|
|
1030
|
+
surf semantic auth clear # removes the shared credential for all clients
|
|
1031
|
+
|
|
1032
|
+
# Ephemeral/CI override (highest precedence; does not modify the stored key)
|
|
1033
|
+
TYPESAFE_API_KEY="$CI_TYPESAFE_KEY" surf semantic.find "the checkout link"
|
|
1034
|
+
|
|
1035
|
+
# Non-interactive persisted setup (exactly one bounded line on stdin)
|
|
1036
|
+
printf '%s\n' "$TYPESAFE_KEY" | surf semantic auth set
|
|
1037
|
+
```
|
|
1038
|
+
|
|
1039
|
+
The provider-neutral shared schema is `{"version":1,"apiKey":"..."}`. Persisted
|
|
1040
|
+
setup lives at `${XDG_CONFIG_HOME:-~/.config}/typesafe/credentials.json` on
|
|
1041
|
+
Unix/macOS and `%APPDATA%\TypeSafe\credentials.json` on Windows, independent of
|
|
1042
|
+
`SURF_STATE_DIR`, project, and cwd. On POSIX, directories use mode `0700` and the
|
|
1043
|
+
file mode `0600`; writes are atomic and symlinked paths are rejected. Windows
|
|
1044
|
+
uses the current user's profile and ACL semantics. A nonblank `TYPESAFE_API_KEY`
|
|
1045
|
+
always wins over the shared file; `auth status` prints only `environment`,
|
|
1046
|
+
`shared-store`, or `not-configured` plus a short fingerprint. `auth clear`
|
|
1047
|
+
removes the shared file for every client that uses it while an environment
|
|
1048
|
+
override remains effective. Keys are never accepted on argv or from
|
|
1049
|
+
`surf.json`, project config, or auto-loaded `.env` files, and are never sent to
|
|
1050
|
+
the host/extension or included in logs, errors, or JSON output. Install,
|
|
1051
|
+
configuration, doctor, startup, and non-semantic commands never prompt for a key
|
|
1052
|
+
or load the TypeSafe SDK.
|
|
1053
|
+
|
|
1054
|
+
`semantic.act` is bounded to observed same-origin HTTP(S) links, fixed scrolling
|
|
1055
|
+
and waits, and observed refs. Every DOM click and fill is mutation-capable and is
|
|
1056
|
+
excluded unless `--allow-write` is present. That flag intentionally permits
|
|
1057
|
+
high-impact submit, purchase, delete, send, and publish controls; repeat
|
|
1058
|
+
`--allow-ref <ref>` to narrow authorization to exact current refs. Fill values
|
|
1059
|
+
come only from named `--input name=value` slots and are never sent to TypeSafe or
|
|
1060
|
+
included in traces. Broad and ambiguous writes require probability `0.95`. The
|
|
1061
|
+
threshold is `0.65` only when exactly one `--allow-ref` names exactly one
|
|
1062
|
+
applicable click, or one fill with one input slot; the applied threshold appears
|
|
1063
|
+
in decision/trace output and never grants authority. Repeatable
|
|
1064
|
+
`--threshold name=value` overrides applicable confidence thresholds for one run
|
|
1065
|
+
only; defaults remain safer, and overrides never replace `--allow-write` or
|
|
1066
|
+
`--allow-ref` authority. Actions are
|
|
1067
|
+
freshness-guarded and uncertain writes are not replayed. Each provider choice is
|
|
1068
|
+
capped at 70 actions: six fixed scroll/wait
|
|
1069
|
+
actions plus at least one action for each of the 64 observed refs explicitly
|
|
1070
|
+
authorized with `--allow-ref`; additional variants are omitted deterministically.
|
|
1071
|
+
An oversized mandatory authorized set fails before provider selection. Page text
|
|
1072
|
+
remains adversarial data; model output never grants authority.
|
|
1073
|
+
|
|
1074
|
+
The real-Jev evaluation harness is opt-in and excluded from CI:
|
|
1075
|
+
`SURF_REAL_JEV=1 TYPESAFE_API_KEY=... npm run eval:jev`.
|
|
1076
|
+
|
|
916
1077
|
## Environment Variables
|
|
917
1078
|
|
|
918
1079
|
```bash
|
|
919
1080
|
SURF_NETWORK_PATH # Native-host network state root (default: ~/.surf/state/network)
|
|
920
|
-
SURF_STATE_DIR # Private Surf state root
|
|
1081
|
+
SURF_STATE_DIR # Private Surf state root; does not affect shared TypeSafe credentials
|
|
921
1082
|
SURF_SESSION # Default named browser session for tab-scoped commands
|
|
922
1083
|
SURF_SOCKET # Socket path or named pipe (default: /tmp/surf.sock, Windows: //./pipe/surf)
|
|
923
1084
|
SURF_REMOTE # Remote Surf endpoint as host:port (overrides SURF_SOCKET)
|
|
@@ -932,6 +1093,9 @@ SURF_SOCKET_GROUP # Group name or numeric gid required with mode 660
|
|
|
932
1093
|
SURF_NODE_PATH # Path to node binary (for native host wrapper)
|
|
933
1094
|
SURF_HOST_PATH # Path to native/host.cjs (for native host wrapper)
|
|
934
1095
|
SURF_EXTENSION_PATH # Path to extension dist/ directory
|
|
1096
|
+
TYPESAFE_API_KEY # Optional semantic-command credential; overrides the shared store
|
|
1097
|
+
SURF_JEV_MODEL # Optional observable Jev model override (default: jev-1.13.0)
|
|
1098
|
+
XDG_CONFIG_HOME # Unix/macOS base for shared TypeSafe credentials (default: ~/.config)
|
|
935
1099
|
```
|
|
936
1100
|
|
|
937
1101
|
**Use cases:**
|
|
@@ -948,6 +1112,8 @@ SURF_EXTENSION_PATH # Path to extension dist/ directory
|
|
|
948
1112
|
- `SURF_SOCKET_MODE` / `SURF_SOCKET_GROUP`: Advanced POSIX native-host settings. Use `surf install ... --socket-mode 660 --socket-group <group>` to persist group access; mode `660` grants full Surf authority to every member of that group.
|
|
949
1113
|
- `SURF_NODE_PATH` / `SURF_HOST_PATH`: Package manager installs (e.g., Nix) that store binaries in non-standard locations
|
|
950
1114
|
- `SURF_EXTENSION_PATH`: Package managers that create stable symlinks instead of changing paths on reinstall
|
|
1115
|
+
- `TYPESAFE_API_KEY`: Used only by explicit `semantic.*` networked commands. Otherwise use `surf semantic auth set` for the provider-neutral shared store.
|
|
1116
|
+
- `SURF_JEV_MODEL`: Explicit model override for semantic commands; Surf otherwise pins `jev-1.13.0`.
|
|
951
1117
|
|
|
952
1118
|
**Example (Nix):**
|
|
953
1119
|
```bash
|
|
@@ -981,7 +1147,7 @@ macOS checklist:
|
|
|
981
1147
|
- Confirm the manifest `allowed_origins` entry uses the same extension ID shown on `chrome://extensions` for the Surf extension.
|
|
982
1148
|
- Reinstall the manifest with `surf install <extension-id>` after copying a fresh extension build or if the extension ID changed.
|
|
983
1149
|
- Fully restart Chrome, then reload the Surf extension on `chrome://extensions`.
|
|
984
|
-
- Open
|
|
1150
|
+
- Open Surf's service worker console from `chrome://extensions`. In Surf's **Details > Extension options**, enable **Debug Mode**, reproduce the failure, then disable **Debug Mode** when finished.
|
|
985
1151
|
- If `SURF_SOCKET` is set in your shell, make sure Chrome launches the native host with the same value; otherwise both sides should use `/tmp/surf.sock`.
|
|
986
1152
|
- Run a simple CLI command such as `surf tab.list`; if it fails, compare its `Attempted socket:` line with the socket expected by the native host.
|
|
987
1153
|
|
package/dist/content/index.js
CHANGED
|
@@ -107,10 +107,10 @@ var e=`59, 178, 191`,t=1e4,n=null,r=null,i=null,a=!1,o=!1,s=!1,c=!1,l=null,u=t,d
|
|
|
107
107
|
white-space: nowrap;
|
|
108
108
|
user-select: none;
|
|
109
109
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
|
110
|
-
`;let n=t.querySelector(`#pi-static-chat-button`),r=t.querySelector(`#pi-static-close-button`);return n&&(n.style.pointerEvents=`auto`,n.addEventListener(`mouseenter`,()=>n.style.background=`#F0EEE6`),n.addEventListener(`mouseleave`,()=>n.style.background=`transparent`),n.addEventListener(`click`,async()=>{await chrome.runtime.sendMessage({type:`OPEN_SIDEPANEL`})})),r&&(r.style.pointerEvents=`auto`,r.addEventListener(`mouseenter`,()=>r.style.background=`#F0EEE6`),r.addEventListener(`mouseleave`,()=>r.style.background=`transparent`),r.addEventListener(`click`,async()=>{await chrome.runtime.sendMessage({type:`DISMISS_STATIC_INDICATOR`}),S()})),t}function y(){if(!document.body){d||(d=!0,window.addEventListener(`DOMContentLoaded`,()=>{d&&(d=!1,y())},{once:!0}));return}d=!1,!a&&(a=!0,h(),n?n.style.display=``:(n=g(),document.body.appendChild(n)),r?r.style.display=``:(r=_(),document.body.appendChild(r)),requestAnimationFrame(()=>{if(n&&(n.style.opacity=`1`),r){let e=r.querySelector(`#pi-agent-stop-button`);e&&(e.style.transform=`translateY(0)`,e.style.opacity=`1`)}}))}function b(){if(d=!1,a){if(a=!1,n&&(n.style.opacity=`0`),r){let e=r.querySelector(`#pi-agent-stop-button`);e&&(e.style.transform=`translateY(100px)`,e.style.opacity=`0`)}setTimeout(()=>{a||(n?.parentNode&&(n.parentNode.removeChild(n),n=null),r?.parentNode&&(r.parentNode.removeChild(r),r=null))},300)}}function x(){if(!document.body){f||(f=!0,window.addEventListener(`DOMContentLoaded`,()=>{f&&(f=!1,x())},{once:!0}));return}f=!1,!o&&(o=!0,i?i.style.display=``:(i=v(),document.body.appendChild(i)),l&&clearInterval(l),m())}function S(){f=!1,o&&(o=!1,l&&=(clearInterval(l),null),i?.parentNode&&(i.parentNode.removeChild(i),i=null))}p&&(window.__piVisualIndicatorMessageHandler=e=>{switch(e){case`SHOW_AGENT_INDICATORS`:y();break;case`HIDE_AGENT_INDICATORS`:b();break;case`HIDE_FOR_TOOL_USE`:s=a||d,c=o||f,d=!1,f=!1,n&&(n.style.display=`none`),r&&(r.style.display=`none`),i&&o&&(i.style.display=`none`);break;case`SHOW_AFTER_TOOL_USE`:s&&(a?(n&&(n.style.display=``),r&&(r.style.display=``)):y()),c&&(o&&i?i.style.display=``:x()),s=!1,c=!1;break;case`SHOW_STATIC_INDICATOR`:x();break;case`HIDE_STATIC_INDICATOR`:S()}},window.addEventListener(`beforeunload`,()=>{b(),S()}));var C=new Set(`alert.alertdialog.application.article.banner.blockquote.button.caption.cell.checkbox.code.columnheader.combobox.complementary.contentinfo.definition.deletion.dialog.directory.document.emphasis.feed.figure.form.generic.grid.gridcell.group.heading.img.insertion.link.list.listbox.listitem.log.main.mark.marquee.math.menu.menubar.menuitem.menuitemcheckbox.menuitemradio.meter.navigation.none.note.option.paragraph.presentation.progressbar.radio.radiogroup.region.row.rowgroup.rowheader.scrollbar.search.searchbox.separator.slider.spinbutton.status.strong.subscript.superscript.switch.tab.table.tablist.tabpanel.term.textbox.time.timer.toolbar.tooltip.tree.treegrid.treeitem`.split(`.`));function w(e){let t=e.tagName.toLowerCase();if([`button`,`input`,`select`,`textarea`].includes(t))return!e.disabled;if(t===`a`&&e.hasAttribute(`href`))return!0;if(e.hasAttribute(`tabindex`)){let t=parseInt(e.getAttribute(`tabindex`)||``,10);return!isNaN(t)&&t>=0}return e.getAttribute(`contenteditable`)===`true`}function T(e){let t=e.getAttribute(`role`);if(!t)return null;let n=t.split(/\s+/).filter(e=>e);for(let e of n)if(C.has(e))return e;return null}function E(e){let t=e.tagName.toLowerCase(),n=e.getAttribute(`type`),r={a:e=>e.hasAttribute(`href`)?`link`:`generic`,article:`article`,aside:`complementary`,button:`button`,datalist:`listbox`,dd:`definition`,details:`group`,dialog:`dialog`,dt:`term`,fieldset:`group`,figure:`figure`,footer:e=>e.closest(`article, aside, main, nav, section`)?`generic`:`contentinfo`,form:e=>e.hasAttribute(`aria-label`)||e.hasAttribute(`aria-labelledby`)?`form`:`generic`,h1:`heading`,h2:`heading`,h3:`heading`,h4:`heading`,h5:`heading`,h6:`heading`,header:e=>e.closest(`article, aside, main, nav, section`)?`generic`:`banner`,hr:`separator`,img:e=>e.getAttribute(`alt`)===``?`presentation`:`img`,li:`listitem`,main:`main`,math:`math`,menu:`list`,meter:`meter`,nav:`navigation`,ol:`list`,optgroup:`group`,option:`option`,output:`status`,p:`paragraph`,progress:`progressbar`,search:`search`,section:e=>e.hasAttribute(`aria-label`)||e.hasAttribute(`aria-labelledby`)?`region`:`generic`,select:e=>{let t=e;return t.hasAttribute(`multiple`)||t.size&&t.size>1?`listbox`:`combobox`},table:`table`,tbody:`rowgroup`,td:`cell`,textarea:`textbox`,tfoot:`rowgroup`,th:`columnheader`,thead:`rowgroup`,time:`time`,tr:`row`,ul:`list`};if(t===`input`)return{button:`button`,checkbox:`checkbox`,email:`textbox`,file:`button`,image:`button`,number:`spinbutton`,radio:`radio`,range:`slider`,reset:`button`,search:`searchbox`,submit:`button`,tel:`textbox`,text:`textbox`,url:`textbox`}[n||``]||`textbox`;let i=r[t];return typeof i==`function`?i(e):i||`generic`}function D(e){let t=T(e);return!t||(t===`none`||t===`presentation`)&&w(e)?E(e):t}window.__piElementMap||(window.__piElementMap={});var O=new WeakMap,k=0;function A(e,t,n){let r=O.get(e);if(r&&r.role===t&&r.name===n)return r.ref;let i=`e${++k}`;return O.set(e,{role:t,name:n,ref:i}),i}function j(){let e=[];return document.querySelectorAll(`[role="dialog"], [role="alertdialog"], dialog[open]`).forEach(t=>{let n=window.getComputedStyle(t);if(!(n.display!==`none`&&n.visibility!==`hidden`&&n.opacity!==`0`&&t.offsetWidth>0&&t.offsetHeight>0))return;let r=t.getAttribute(`role`)||`dialog`,i=t.getAttribute(`aria-label`)||t.querySelector(`[role="heading"], h1, h2, h3`)?.textContent?.trim()||`Dialog`;i.length>100&&(i=i.substring(0,100)+`...`),e.push({type:r,description:`${r}: ${i}`,clearedBy:`computer(action=key, text=Escape)`})}),e}var M={wait(e){return new Promise(t=>setTimeout(t,e))},async waitForSelector(e,t={}){let{state:n=`visible`,timeout:r=2e4}=t,i=e=>{if(!e)return!1;let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`&&t.opacity!==`0`&&e.offsetWidth>0&&e.offsetHeight>0},a=()=>{let t=document.querySelector(e);switch(n){case`attached`:return t;case`detached`:return t?null:document.body;case`hidden`:return t?i(t)?null:t:document.body;default:return i(t)?t:null}};return new Promise((t,i)=>{let o=a();if(o){t(n===`detached`||n===`hidden`?null:o);return}let s=new MutationObserver(()=>{let e=a();e&&(s.disconnect(),clearTimeout(c),t(n===`detached`||n===`hidden`?null:e))}),c=setTimeout(()=>{s.disconnect(),i(Error(`Timeout waiting for "${e}" to be ${n}`))},r);s.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`,`class`,`hidden`]})})},async waitForText(e,t={}){let{selector:n,timeout:r=2e4}=t,i=()=>{let t=n?document.querySelector(n):document.body;if(!t)return null;let r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);for(;r.nextNode();)if(r.currentNode.textContent?.includes(e))return r.currentNode.parentElement;return null};return new Promise((t,n)=>{let a=i();if(a){t(a);return}let o=new MutationObserver(()=>{let e=i();e&&(o.disconnect(),clearTimeout(s),t(e))}),s=setTimeout(()=>{o.disconnect(),n(Error(`Timeout waiting for text "${e}"`))},r);o.observe(document.documentElement,{childList:!0,subtree:!0,characterData:!0})})},async waitForHidden(e,t=2e4){await M.waitForSelector(e,{state:`hidden`,timeout:t})},getByRole(e,t={}){let{name:n}=t,r={button:[`button`,`input[type="button"]`,`input[type="submit"]`,`input[type="reset"]`],link:[`a[href]`],textbox:[`input:not([type])`,`input[type="text"]`,`input[type="email"]`,`input[type="password"]`,`input[type="search"]`,`input[type="tel"]`,`input[type="url"]`,`textarea`],checkbox:[`input[type="checkbox"]`],radio:[`input[type="radio"]`],combobox:[`select`],heading:[`h1`,`h2`,`h3`,`h4`,`h5`,`h6`],list:[`ul`,`ol`],listitem:[`li`],navigation:[`nav`],main:[`main`],banner:[`header`],contentinfo:[`footer`],form:[`form`],img:[`img`],table:[`table`]},i=[];i.push(...document.querySelectorAll(`[role="${e}"]`));let a=r[e];if(a)for(let e of a)i.push(...document.querySelectorAll(`${e}:not([role])`));if(!n)return i[0]||null;let o=n.toLowerCase().trim();for(let e of i){let t=e.getAttribute(`aria-label`)?.toLowerCase().trim(),n=e.textContent?.toLowerCase().trim(),r=e.getAttribute(`title`)?.toLowerCase().trim(),i=e.getAttribute(`placeholder`)?.toLowerCase().trim();if(t===o||n===o||r===o||i===o||t?.includes(o)||n?.includes(o))return e}return null}};window.__piHelpers||(window.__piHelpers=M,window.piHelpers=M);function N(){return window.__piElementMap}function P(e=`interactive`,t=15,n,r=!1,i=!1){try{window.__piRefs={};function a(e){return D(e)}function o(e){let t=e.tagName.toLowerCase(),n=e.getAttribute(`aria-labelledby`);if(n){let e=n.split(/\s+/).map(e=>document.getElementById(e)?.textContent?.trim()||``).filter(Boolean);if(e.length){let t=e.join(` `);return t.length>100?t.substring(0,100)+`...`:t}}if(t===`select`){let t=e,n=t.querySelector(`option[selected]`)||(t.selectedIndex>=0?t.options[t.selectedIndex]:null);if(n?.textContent?.trim())return n.textContent.trim()}let r=e.getAttribute(`aria-label`);if(r?.trim())return r.trim();let i=e.getAttribute(`placeholder`);if(i?.trim())return i.trim();let a=e.getAttribute(`title`);if(a?.trim())return a.trim();let o=e.getAttribute(`alt`);if(o?.trim())return o.trim();if(e.id){let t=document.querySelector(`label[for="${e.id}"]`);if(t?.textContent?.trim())return t.textContent.trim()}if(t===`input`){let t=e,n=e.getAttribute(`type`)||``,r=e.getAttribute(`value`);if(n===`submit`&&r?.trim())return r.trim();if(t.value&&t.value.length<50&&t.value.trim())return t.value.trim()}if([`button`,`a`,`summary`].includes(t)){let t=e.textContent||``;if(t.trim())return t.trim()}if(/^h[1-6]$/.test(t)){let t=e.textContent;if(t?.trim()){let e=t.trim();return e.length>100?e.substring(0,100)+`...`:e}}if(t===`img`)return``;let s=``;for(let t of e.childNodes)t.nodeType===Node.TEXT_NODE&&(s+=t.textContent);if(s?.trim()&&s.trim().length>=3){let e=s.trim();return e.length>100?e.substring(0,100)+`...`:e}return``}function s(e){let t={},n=e.getAttribute(`aria-checked`);n===`true`?t.checked=!0:n===`false`?t.checked=!1:n===`mixed`?t.checked=`mixed`:e instanceof HTMLInputElement&&(e.type===`checkbox`||e.type===`radio`)&&(t.checked=e.type===`checkbox`&&e.indeterminate?`mixed`:e.checked);let r=e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement;(e.getAttribute(`aria-disabled`)===`true`||r&&e.disabled||e.closest(`fieldset:disabled`))&&(t.disabled=!0);let i=e.getAttribute(`aria-expanded`);i===`true`?t.expanded=!0:i===`false`&&(t.expanded=!1);let a=e.getAttribute(`aria-pressed`);a===`true`?t.pressed=!0:a===`false`?t.pressed=!1:a===`mixed`&&(t.pressed=`mixed`);let o=e.getAttribute(`aria-selected`);o===`true`?t.selected=!0:o===`false`&&(t.selected=!1);let s=e.getAttribute(`aria-current`);s&&s!==`false`&&(t.active=!0);let c=e.tagName.toLowerCase();if(/^h[1-6]$/.test(c))t.level=parseInt(c[1],10);else{let n=e.getAttribute(`aria-level`);n&&(t.level=parseInt(n,10))}return t}function c(e){let t=[];return e.checked!==void 0&&t.push(e.checked===`mixed`?`[checked=mixed]`:e.checked?`[checked]`:`[unchecked]`),e.disabled&&t.push(`[disabled]`),e.expanded!==void 0&&t.push(e.expanded?`[expanded]`:`[collapsed]`),e.pressed!==void 0&&t.push(e.pressed===`mixed`?`[pressed=mixed]`:e.pressed?`[pressed]`:`[not-pressed]`),e.selected!==void 0&&t.push(e.selected?`[selected]`:`[not-selected]`),e.active&&t.push(`[active]`),e.level!==void 0&&t.push(`[level=${e.level}]`),t.join(` `)}function l(e){let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`&&t.opacity!==`0`&&e.offsetWidth>0&&e.offsetHeight>0}function u(e){let t=e.tagName.toLowerCase();return[`a`,`button`,`input`,`select`,`textarea`,`details`,`summary`].includes(t)||e.hasAttribute(`onclick`)||e.hasAttribute(`tabindex`)||e.getAttribute(`role`)===`button`||e.getAttribute(`role`)===`link`||e.getAttribute(`contenteditable`)===`true`}function d(e){let t=e.tagName.toLowerCase();return[`h1`,`h2`,`h3`,`h4`,`h5`,`h6`,`nav`,`main`,`header`,`footer`,`section`,`article`,`aside`].includes(t)||e.hasAttribute(`role`)}function f(e){return window.getComputedStyle(e).cursor===`pointer`}function p(e,t){let n=e.tagName.toLowerCase();if([`script`,`style`,`meta`,`link`,`title`,`noscript`].includes(n)||t.filter!==`all`&&e.getAttribute(`aria-hidden`)===`true`||t.filter!==`all`&&!l(e))return!1;if(t.filter!==`all`&&!t.refId){let t=e.getBoundingClientRect();if(!(t.top<window.innerHeight&&t.bottom>0&&t.left<window.innerWidth&&t.right>0))return!1}if(t.filter===`interactive`)return u(e);if(u(e)||d(e)||o(e).length>0)return!0;let r=a(e);return t.compact&&new Set([`generic`,`group`,`region`,`article`,`section`,`complementary`]).has(r)&&o(e).length===0?!1:r!==`generic`&&r!==`img`}function m(r,l){let u=[],d={filter:e,refId:n||null,compact:i},h=N(),g=p(r,d)||n&&l===0;if(g){let e=a(r),t=o(r),n=s(r),i=A(r,e,t);window.__piRefs[i]=r,h[i]={element:new WeakRef(r),role:e,name:t};let d=`${` `.repeat(l)}${e}`;if(t){let e=t.replace(/\s+/g,` `).replace(/"/g,`\\"`);d+=` "${e}"`}d+=` [${i}]`;let p=c(n);p&&(d+=` ${p}`),f(r)&&(d+=` [cursor=pointer]`);let m=r.getAttribute(`href`);m&&(d+=` href="${m}"`);let g=r.getAttribute(`type`);g&&(d+=` type="${g}"`);let _=r.getAttribute(`placeholder`);_&&(d+=` placeholder="${_}"`),u.push(d)}if(l<t)for(let e of r.children)u.push(...m(e,g?l+1:l));return u}function h(e){return e.replace(/\[e\d+\]/g,`[REF]`)}function g(e){let t=new Map;for(let n of e){if(!n.trim())continue;let e=h(n);t.set(e,(t.get(e)||0)+1)}return t}function _(e,t){let n=e.split(`
|
|
110
|
+
`;let n=t.querySelector(`#pi-static-chat-button`),r=t.querySelector(`#pi-static-close-button`);return n&&(n.style.pointerEvents=`auto`,n.addEventListener(`mouseenter`,()=>n.style.background=`#F0EEE6`),n.addEventListener(`mouseleave`,()=>n.style.background=`transparent`),n.addEventListener(`click`,async()=>{await chrome.runtime.sendMessage({type:`OPEN_SIDEPANEL`})})),r&&(r.style.pointerEvents=`auto`,r.addEventListener(`mouseenter`,()=>r.style.background=`#F0EEE6`),r.addEventListener(`mouseleave`,()=>r.style.background=`transparent`),r.addEventListener(`click`,async()=>{await chrome.runtime.sendMessage({type:`DISMISS_STATIC_INDICATOR`}),S()})),t}function y(){if(!document.body){d||(d=!0,window.addEventListener(`DOMContentLoaded`,()=>{d&&(d=!1,y())},{once:!0}));return}d=!1,!a&&(a=!0,h(),n?n.style.display=``:(n=g(),document.body.appendChild(n)),r?r.style.display=``:(r=_(),document.body.appendChild(r)),requestAnimationFrame(()=>{if(n&&(n.style.opacity=`1`),r){let e=r.querySelector(`#pi-agent-stop-button`);e&&(e.style.transform=`translateY(0)`,e.style.opacity=`1`)}}))}function b(){if(d=!1,a){if(a=!1,n&&(n.style.opacity=`0`),r){let e=r.querySelector(`#pi-agent-stop-button`);e&&(e.style.transform=`translateY(100px)`,e.style.opacity=`0`)}setTimeout(()=>{a||(n?.parentNode&&(n.parentNode.removeChild(n),n=null),r?.parentNode&&(r.parentNode.removeChild(r),r=null))},300)}}function x(){if(!document.body){f||(f=!0,window.addEventListener(`DOMContentLoaded`,()=>{f&&(f=!1,x())},{once:!0}));return}f=!1,!o&&(o=!0,i?i.style.display=``:(i=v(),document.body.appendChild(i)),l&&clearInterval(l),m())}function S(){f=!1,o&&(o=!1,l&&=(clearInterval(l),null),i?.parentNode&&(i.parentNode.removeChild(i),i=null))}p&&(window.__piVisualIndicatorMessageHandler=e=>{switch(e){case`SHOW_AGENT_INDICATORS`:y();break;case`HIDE_AGENT_INDICATORS`:b();break;case`HIDE_FOR_TOOL_USE`:s=a||d,c=o||f,d=!1,f=!1,n&&(n.style.display=`none`),r&&(r.style.display=`none`),i&&o&&(i.style.display=`none`);break;case`SHOW_AFTER_TOOL_USE`:s&&(a?(n&&(n.style.display=``),r&&(r.style.display=``)):y()),c&&(o&&i?i.style.display=``:x()),s=!1,c=!1;break;case`SHOW_STATIC_INDICATOR`:x();break;case`HIDE_STATIC_INDICATOR`:S()}},window.addEventListener(`beforeunload`,()=>{b(),S()}));var C=[`input`,`change`];function w(e){let t=Object.getPrototypeOf(e);for(;t&&t!==Object.prototype;){let e=Object.getOwnPropertyDescriptor(t,`value`);if(e?.set)return e.set;t=Object.getPrototypeOf(t)}return null}function T(e,t,n=C){let r=w(e);r?r.call(e,t):e.value=t;for(let t of n)e.dispatchEvent(new Event(t,{bubbles:t!==`blur`}));return{method:r?`native-setter`:`assignment`,events:[...n]}}var ee=[`#challenge-running`,`#challenge-form`,`#challenge-stage`,`#cf-challenge-running`,`form[action*='captcha' i]`,`[data-sitekey][data-callback]`],te=[`iframe[src*='captcha' i]`,`iframe[src*='challenge' i]`,`iframe[title*='captcha' i]`],E=/just a moment|attention required|access denied|verify(?:ing)? (?:that )?you are (?:a )?human|security check|checking your browser|are you a robot|bot (?:detection|check|protection)|captcha|one more step|please wait while we verify/i,ne=/verify(?:ing)? (?:that )?you are (?:a )?human|checking (?:your|the) browser|enable javascript and cookies|unusual traffic|automated (?:access|requests|queries)|complete the security check|prove you are human/i,D=/\b404\b|\bnot found\b|page (?:doesn.t|does not|cannot be|could not be|can.t be) (?:exist|found)|no longer (?:available|exists)|(?:doesn.t|does not) exist\b/i,re=/(?:^|\/)(?:log-?in|sign-?in|sign-?on|auth|authenticate|authorize|sso|oauth2?|session\/new|users\/sign_in|account\/login)(?:\/|$|\?|#)/i,ie=/\b(?:log ?in|sign ?in|sign ?on|authenticate|authentication)\b/i,ae=/this site can.t be reached|took too long to respond|ERR_[A-Z_]{4,}|no internet|connection (?:was )?(?:reset|refused)/i;function O(e){return(e??``).replace(/\s+/g,` `).trim()}function k(e){try{return new URL(e).pathname}catch{return``}}function oe(e){return e===``||e===`about:blank`||e.startsWith(`about:blank?`)}function se(e){if(e.href.startsWith(`chrome-error://`))return{state:`error`,evidence:[`browser error page ${e.href}`]};if(e.bodyTextLength<800){let t=e.bodyTextSample.match(ae);if(t)return{state:`error`,evidence:[`page text reads like a browser error: "${t[0]}"`]}}return null}function ce(e){let t=[],n=e.bodyTextLength<800;n&&e.challengeMarkers.length>0&&t.push(`challenge markup present: ${e.challengeMarkers.join(`, `)}`);let r=e.title.match(E);if(r&&t.push(`title "${e.title}" matches challenge wording`),n){let n=e.headings.find(e=>E.test(e));n&&t.push(`heading "${n}" matches challenge wording`);let r=e.bodyTextSample.match(ne);r&&t.push(`short page text contains "${r[0]}"`),e.captchaFrames>0&&t.push(`${e.captchaFrames} captcha frame(s) on a short page`)}return t.length===0||t.length===1&&e.captchaFrames>0&&e.challengeMarkers.length===0&&!r?null:{state:`challenge`,evidence:t}}function le(e){if(e.title.match(D))return{state:`not-found`,evidence:[`title "${e.title}" matches not-found wording`]};let t=e.headings.find(e=>D.test(e));return t?{state:`not-found`,evidence:[`heading "${t}" matches not-found wording`]}:null}function ue(e){let t=[],n=e.visiblePasswordInputs>0,r=re.test(k(e.href)),i=ie.test(e.title),a=e.urlPrefix!==void 0&&!e.urlPrefix.matched;return n&&t.push(`${e.visiblePasswordInputs} visible password field(s)`),r&&t.push(`URL path ${k(e.href)} looks like a login route`),i&&t.push(`title "${e.title}" mentions signing in`),a&&e.urlPrefix&&t.push(`URL ${e.href} left the expected prefix ${e.urlPrefix.expected}`),n&&(r||i||a)||r&&(i||a)?{state:`login`,evidence:t}:null}function A(e,t){return t?`${e} "${t.expected}" ${t.matched?`found`:`not found`}`:null}function de(e){let t=se(e)??ce(e)??le(e)??ue(e);if(t)return t;let n=[],r=oe(e.href),i=e.urlPrefix?.expected.startsWith(`about:blank`)===!0;if(r&&!i)return{state:`loading`,evidence:[`URL is ${e.href||`empty`}`]};if(e.urlPrefix&&!e.urlPrefix.matched)return{state:`loading`,evidence:[`URL ${e.href} does not start with ${e.urlPrefix.expected}`]};let a=e.selector?.matched===!0||e.text?.matched===!0;if(e.readyState!==`complete`&&!a)return n.push(`document.readyState is ${e.readyState}`),e.tabStatus&&e.tabStatus!==`complete`&&n.push(`tab status is ${e.tabStatus}`),{state:`loading`,evidence:n};if(e.emptyText?.matched)return{state:`empty`,evidence:[`empty-state text "${e.emptyText.expected}" found`]};let o=[e.selector&&!e.selector.matched?A(`selector`,e.selector):null,e.text&&!e.text.matched?A(`text`,e.text):null].filter(e=>e!==null);if(o.length>0)return{state:`loading`,evidence:o};let s=[A(`selector`,e.selector),A(`text`,e.text)].filter(e=>e!==null);return s.length===0&&s.push(`document.readyState is ${e.readyState}`),e.visiblePasswordInputs>0&&s.push(`${e.visiblePasswordInputs} visible password field(s), page otherwise looks ready`),{state:`ready`,evidence:s}}var fe=4e3,pe=`input:not([type]), input[type='text'], input[type='email'], input[type='tel'], input[type='search'], input[type='url'], textarea`,j=class extends Error{constructor(e,t){let n=t instanceof Error?t.message:String(t);super(`Invalid CSS selector "${e}": ${n}`),this.name=`InvalidReadinessSelectorError`}};function M(e,t){try{return e.countVisible(t)}catch{return 0}}function me(e,t={}){let n=e.bodyText(),r=n.toLowerCase(),i={href:e.href,title:O(e.title),readyState:e.readyState,bodyTextSample:n.slice(0,fe),bodyTextLength:n.length,headings:e.visibleHeadings().map(O).filter(Boolean).slice(0,5),visiblePasswordInputs:M(e,`input[type='password']`),visibleTextInputs:M(e,pe),challengeMarkers:ee.filter(t=>M(e,t)>0),captchaFrames:te.reduce((t,n)=>t+M(e,n),0)};if(t.selector)try{i.selector={expected:t.selector,matched:e.countVisible(t.selector)>0}}catch(e){throw new j(t.selector,e)}return t.text&&(i.text={expected:t.text,matched:r.includes(O(t.text).toLowerCase())}),t.urlPrefix&&(i.urlPrefix={expected:t.urlPrefix,matched:e.href.startsWith(t.urlPrefix)}),t.emptyText&&(i.emptyText={expected:t.emptyText,matched:r.includes(O(t.emptyText).toLowerCase())}),i}function he(e,t={}){let n=me(e,t),r=de(n),{bodyTextSample:i,...a}=n;return{...r,href:n.href,title:n.title,readyState:n.readyState,snapshot:a}}function ge(e,t){let n=e=>{let n=t.getComputedStyle(e),r=e;return n.display!==`none`&&n.visibility!==`hidden`&&n.opacity!==`0`&&r.offsetWidth>0&&r.offsetHeight>0};return{href:t.location.href,title:e.title,readyState:e.readyState,bodyText:()=>O(e.body?.innerText??e.body?.textContent??``),countVisible:t=>Array.from(e.querySelectorAll(t)).filter(n).length,visibleHeadings:()=>Array.from(e.querySelectorAll(`h1, h2`)).filter(n).map(e=>O(e.textContent))}}function N(e,t=null){let n=t&&document.querySelector(t)||[...document.querySelectorAll(`*`)].filter(e=>e.scrollHeight>e.clientHeight&&e.clientHeight>200).sort((e,t)=>t.scrollHeight-e.scrollHeight)[0]||document.documentElement;return n?(e===`bottom`?n.scrollTop=n.scrollHeight:e===`top`?n.scrollTop=0:typeof e==`number`&&(n.scrollTop=e),{scrollTop:n.scrollTop,scrollHeight:n.scrollHeight,clientHeight:n.clientHeight,atBottom:n.scrollTop+n.clientHeight>=n.scrollHeight-10,atTop:n.scrollTop<10}):{error:`No scrollable container found`}}var P=new Map;function _e(){return[...document.querySelectorAll(`*`)].filter(e=>e.scrollHeight>e.clientHeight&&e.clientHeight>0).sort((e,t)=>t.scrollHeight-e.scrollHeight)[0]||document.scrollingElement||document.documentElement||null}function F(e){let t=Math.max(0,Number(e.scrollHeight)||0),n=Math.max(0,Number(e.clientHeight)||0),r=Math.min(Math.max(0,Number(e.scrollTop)||0),Math.max(0,t-n)),i=e===document.documentElement||e===document.scrollingElement,a=0,o=Math.min(n||window.innerHeight,window.innerHeight);if(!i){let t=e.getBoundingClientRect(),r=Math.max(0,t.top),i=Math.min(window.innerHeight,t.bottom);o=Math.max(0,Math.min(n,i-r)),a=Math.max(0,r-t.top)}if(o<=0)return null;let s=Math.min(t,r+a),c=Math.min(t,s+o);return{scrollTop:r,scrollHeight:t,clientHeight:o,intervalStart:s,intervalEnd:c,atTop:s<=0,atBottom:c>=t}}function ve(e){let t=_e();if(!t)return{success:!1,reason:`unsupported_scroll_scope`};let n=F(t);if(!n)return{success:!1,reason:`unsupported_scroll_scope`};let r=globalThis.crypto?.randomUUID?.()||`scope-${Date.now()}-${Math.random().toString(36).slice(2)}`;return P.set(r,{element:new WeakRef(t),documentToken:e}),{success:!0,scopeToken:r,geometry:n}}function ye(e,t,n){let r=P.get(t),i=r?.element.deref();if(!r||r.documentToken!==n||!i||`isConnected`in i&&i.isConnected===!1)return P.delete(t),{success:!1,reason:`stale_scroll_scope`};let a=F(i);if(!a)return{success:!1,reason:`stale_scroll_scope`};if(e===`top`)i.scrollTop=0;else if(e===`advance`)i.scrollTop=a.scrollTop+Math.floor(a.clientHeight*.75);else return{success:!1,reason:`unsupported_scroll_action`};let o=F(i);return o?{success:!0,scopeToken:t,geometry:o}:{success:!1,reason:`stale_scroll_scope`}}var be=64,xe=48,I=24576,L=(()=>{try{return globalThis.crypto?.randomUUID?.()||`doc-${Date.now()}-${Math.random().toString(36).slice(2)}`}catch{return`doc-${Date.now()}-${Math.random().toString(36).slice(2)}`}})();function R(e,t){return(e||``).replace(/\s+/g,` `).trim().slice(0,t)}function z(e){let t=e.tagName.toLowerCase();return t===`input`?R(e.getAttribute(`type`)||`text`,32).toLowerCase():t}function Se(e){let t={},n=e.getAttribute(`aria-checked`);n===`true`||n===`false`||n===`mixed`?t.checked=n===`mixed`?`mixed`:n===`true`:e instanceof HTMLInputElement&&(e.type===`checkbox`||e.type===`radio`)&&(t.checked=e.type===`checkbox`&&e.indeterminate?`mixed`:e.checked);let r=e.getAttribute(`aria-selected`);return r===`true`||r===`false`?t.selected=r===`true`:e.tagName.toLowerCase()===`option`&&(t.selected=e.selected),Object.keys(t).length?t:void 0}function Ce(e){if(!e.state)return``;let t=[];e.state.checked!==void 0&&t.push(e.state.checked===`mixed`?`[checked=mixed]`:e.state.checked?`[checked]`:`[unchecked]`),e.state.selected!==void 0&&t.push(e.state.selected?`[selected]`:`[not-selected]`);let n=e.name?` "${e.name.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:``;return R(`${e.role}${n} ${t.join(` `)}`,240)}function B(e){let t=e.getAttribute(`aria-labelledby`);if(t){let e=t.split(/\s+/).map(e=>document.getElementById(e)?.textContent||``).join(` `);if(R(e,160))return R(e,160)}for(let t of[`aria-label`,`placeholder`,`title`,`alt`]){let n=R(e.getAttribute(t),160);if(n)return n}if(e.id){let t=R(document.querySelector(`label[for="${e.id}"]`)?.textContent,160);if(t)return t}let n=e.tagName.toLowerCase();if([`button`,`a`,`summary`].includes(n)){let t=R(e.textContent,160);if(t)return t;if(n===`a`){let t=e.querySelector(`img`);for(let e of[`aria-label`,`alt`,`title`]){let n=R(t?.getAttribute(e),160);if(n)return n}}}return``}function we(e){let t=e.tagName.toLowerCase();return[`input`,`textarea`,`select`,`option`,`button`].includes(t)||e.getAttribute(`contenteditable`)===`true`}function V(e){let t=window.getComputedStyle(e),n=e.getBoundingClientRect();return t.display!==`none`&&t.visibility!==`hidden`&&t.opacity!==`0`&&n.top<window.innerHeight&&n.bottom>0&&n.left<window.innerWidth&&n.right>0}function H(e,t){let n=[],r=e=>{if(n.join(` `).length>=t)return;if(e.nodeType===Node.TEXT_NODE){let r=R(e.textContent,t);r&&n.push(r);return}if(!(e instanceof Element)||we(e))return;let i=e.tagName.toLowerCase();if(![`script`,`style`,`noscript`,`template`].includes(i))for(let t of Array.from(e.childNodes))r(t)};return r(e),R(n.join(` `),t)}function Te(e,t){let n=R(t,160).toLocaleLowerCase(),r=``,i=e.parentElement;for(let e=0;i&&e<4;e++,i=i.parentElement){let e=H(i,240);if(e&&(r=e,e.toLocaleLowerCase()!==n))return e}return r}function Ee(){let e=new Set,t=Object.entries(X()).flatMap(([t,n])=>{let r=n.element.deref();if(!r||e.has(r)||`isConnected`in r&&r.isConnected===!1||!V(r))return[];e.add(r);let i=G(r);if(!W(r)&&i===`generic`)return[];let a=B(r);return[{ref:t,role:R(i,40),name:a,type:z(r),state:Se(r),representation:r.tagName.toLowerCase()===`a`?R(r.textContent,160)?`text`:r.querySelector(`img`)?`image`:`other`:void 0,href:r.tagName.toLowerCase()===`a`&&R(r.getAttribute(`href`),2048)||void 0,download:r.tagName.toLowerCase()===`a`&&r.hasAttribute(`download`)||void 0,nearbyText:Te(r,a)}]}),n=t.slice(0,be),r=n.flatMap(e=>{let t=Ce(e);return t?[{text:t,refs:[e.ref]}]:[]}),i=new Map;for(let e of n){if(!e.nearbyText)continue;let t=i.get(e.nearbyText)||[];t.push(e.ref),i.set(e.nearbyText,t)}let a=(document.body?H(document.body,12288):``).match(/.{1,400}(?:\s|$)/g)?.map(e=>R(e,400)).filter(Boolean)||[],o=[...r,...Array.from(i,([e,t])=>({text:e,refs:t})),...a.filter(e=>!i.has(e)).map(e=>({text:e,refs:[]}))],s=o.slice(0,xe).map(({text:e,refs:t},n)=>({id:`c${n+1}`,text:e,refs:t})),c={version:1,identity:{fullUrl:window.location.href,documentToken:L},page:{title:R(document.title,300),readyState:document.readyState,modals:J().slice(0,8)},candidates:n,chunks:s,omitted:{candidates:Math.max(0,t.length-n.length),chunks:Math.max(0,o.length-s.length)}};for(;new TextEncoder().encode(JSON.stringify(c)).length>I&&c.chunks.length;)c.chunks.pop(),c.omitted.chunks++;for(;new TextEncoder().encode(JSON.stringify(c)).length>I&&c.candidates.length;)c.candidates.pop(),c.omitted.candidates++;return c}function U(e,t,n=!0){return!t||typeof t!=`object`?null:window.location.href!==t.fullUrl||L!==t.documentToken||n&&(!e||`isConnected`in e&&e.isConnected===!1||t.ref!==void 0&&(G(e)!==t.role||B(e)!==t.name||z(e)!==t.type))?`stale_observation`:null}function De(e,t){return{fullUrl:window.location.href,documentToken:L,...e&&t?{ref:t,role:G(e),name:B(e),type:z(e)}:{}}}function Oe(e,t){if(!t||typeof t!=`object`||typeof t.kind!=`string`)return{success:!1,matches:!1,reason:`unsupported_predicate`};switch(t.kind){case`visible`:return{success:!0,matches:V(e),reason:`compared`};case`checkedEquals`:{if(typeof t.expected!=`boolean`)return{success:!1,matches:!1,reason:`unsupported_predicate`};let n=e.tagName.toLowerCase(),r=z(e);if(n===`input`&&(r===`checkbox`||r===`radio`)){let n=e;return n.indeterminate?{success:!0,matches:!1,reason:`indeterminate`}:{success:!0,matches:n.checked===t.expected,reason:`compared`}}let i=G(e);if([`checkbox`,`radio`,`switch`,`menuitemcheckbox`,`menuitemradio`].includes(i)){let n=e.getAttribute(`aria-checked`);return n!==`true`&&n!==`false`?{success:!1,matches:!1,reason:`unsupported_control`}:{success:!0,matches:n===`true`===t.expected,reason:`compared`}}return{success:!1,matches:!1,reason:`unsupported_control`}}case`valueEquals`:{if(typeof t.expected!=`string`)return{success:!1,matches:!1,reason:`unsupported_predicate`};let n=e.tagName.toLowerCase();return![`input`,`textarea`,`select`].includes(n)||n===`input`&&z(e)===`file`?{success:!1,matches:!1,reason:`unsupported_control`}:{success:!0,matches:e.value===t.expected,reason:`compared`}}case`textEquals`:case`textContains`:{if(typeof t.expected!=`string`)return{success:!1,matches:!1,reason:`unsupported_predicate`};let n=R(e.textContent,16384),r=R(t.expected,16384);return{success:!0,matches:t.kind===`textEquals`?n===r:n.includes(r),reason:`compared`}}default:return{success:!1,matches:!1,reason:`unsupported_predicate`}}}var ke=new Set(`alert.alertdialog.application.article.banner.blockquote.button.caption.cell.checkbox.code.columnheader.combobox.complementary.contentinfo.definition.deletion.dialog.directory.document.emphasis.feed.figure.form.generic.grid.gridcell.group.heading.img.insertion.link.list.listbox.listitem.log.main.mark.marquee.math.menu.menubar.menuitem.menuitemcheckbox.menuitemradio.meter.navigation.none.note.option.paragraph.presentation.progressbar.radio.radiogroup.region.row.rowgroup.rowheader.scrollbar.search.searchbox.separator.slider.spinbutton.status.strong.subscript.superscript.switch.tab.table.tablist.tabpanel.term.textbox.time.timer.toolbar.tooltip.tree.treegrid.treeitem`.split(`.`));function W(e){let t=e.tagName.toLowerCase();if([`button`,`input`,`select`,`textarea`].includes(t))return!e.disabled;if(t===`a`&&e.hasAttribute(`href`))return!0;if(e.hasAttribute(`tabindex`)){let t=parseInt(e.getAttribute(`tabindex`)||``,10);return!isNaN(t)&&t>=0}return e.getAttribute(`contenteditable`)===`true`}function Ae(e){let t=e.getAttribute(`role`);if(!t)return null;let n=t.split(/\s+/).filter(e=>e);for(let e of n)if(ke.has(e))return e;return null}function je(e){let t=e.tagName.toLowerCase(),n=e.getAttribute(`type`),r={a:e=>e.hasAttribute(`href`)?`link`:`generic`,article:`article`,aside:`complementary`,button:`button`,datalist:`listbox`,dd:`definition`,details:`group`,dialog:`dialog`,dt:`term`,fieldset:`group`,figure:`figure`,footer:e=>e.closest(`article, aside, main, nav, section`)?`generic`:`contentinfo`,form:e=>e.hasAttribute(`aria-label`)||e.hasAttribute(`aria-labelledby`)?`form`:`generic`,h1:`heading`,h2:`heading`,h3:`heading`,h4:`heading`,h5:`heading`,h6:`heading`,header:e=>e.closest(`article, aside, main, nav, section`)?`generic`:`banner`,hr:`separator`,img:e=>e.getAttribute(`alt`)===``?`presentation`:`img`,li:`listitem`,main:`main`,math:`math`,menu:`list`,meter:`meter`,nav:`navigation`,ol:`list`,optgroup:`group`,option:`option`,output:`status`,p:`paragraph`,progress:`progressbar`,search:`search`,section:e=>e.hasAttribute(`aria-label`)||e.hasAttribute(`aria-labelledby`)?`region`:`generic`,select:e=>{let t=e;return t.hasAttribute(`multiple`)||t.size&&t.size>1?`listbox`:`combobox`},table:`table`,tbody:`rowgroup`,td:`cell`,textarea:`textbox`,tfoot:`rowgroup`,th:`columnheader`,thead:`rowgroup`,time:`time`,tr:`row`,ul:`list`};if(t===`input`)return{button:`button`,checkbox:`checkbox`,email:`textbox`,file:`button`,image:`button`,number:`spinbutton`,radio:`radio`,range:`slider`,reset:`button`,search:`searchbox`,submit:`button`,tel:`textbox`,text:`textbox`,url:`textbox`}[n||``]||`textbox`;let i=r[t];return typeof i==`function`?i(e):i||`generic`}function G(e){let t=Ae(e);return!t||(t===`none`||t===`presentation`)&&W(e)?je(e):t}window.__piElementMap||(window.__piElementMap={});var K=new WeakMap,Me=0;function q(e,t,n){let r=K.get(e);if(r&&r.role===t&&r.name===n)return r.ref;let i=`e${++Me}`;return K.set(e,{role:t,name:n,ref:i}),i}function J(){let e=[];return document.querySelectorAll(`[role="dialog"], [role="alertdialog"], dialog[open]`).forEach(t=>{let n=window.getComputedStyle(t);if(!(n.display!==`none`&&n.visibility!==`hidden`&&n.opacity!==`0`&&t.offsetWidth>0&&t.offsetHeight>0))return;let r=t.getAttribute(`role`)||`dialog`,i=t.getAttribute(`aria-label`)||t.querySelector(`[role="heading"], h1, h2, h3`)?.textContent?.trim()||`Dialog`;i.length>100&&(i=i.substring(0,100)+`...`),e.push({type:r,description:`${r}: ${i}`,clearedBy:`computer(action=key, text=Escape)`})}),e}var Y={wait(e){return new Promise(t=>setTimeout(t,e))},async waitForSelector(e,t={}){let{state:n=`visible`,timeout:r=2e4}=t,i=e=>{if(!e)return!1;let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`&&t.opacity!==`0`&&e.offsetWidth>0&&e.offsetHeight>0},a=()=>{let t=document.querySelector(e);switch(n){case`attached`:return t;case`detached`:return t?null:document.body;case`hidden`:return t?i(t)?null:t:document.body;default:return i(t)?t:null}};return new Promise((t,i)=>{let o=a();if(o){t(n===`detached`||n===`hidden`?null:o);return}let s=new MutationObserver(()=>{let e=a();e&&(s.disconnect(),clearTimeout(c),t(n===`detached`||n===`hidden`?null:e))}),c=setTimeout(()=>{s.disconnect(),i(Error(`Timeout waiting for "${e}" to be ${n}`))},r);s.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`,`class`,`hidden`]})})},async waitForText(e,t={}){let{selector:n,timeout:r=2e4}=t,i=()=>{let t=n?document.querySelector(n):document.body;if(!t)return null;let r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);for(;r.nextNode();)if(r.currentNode.textContent?.includes(e))return r.currentNode.parentElement;return null};return new Promise((t,n)=>{let a=i();if(a){t(a);return}let o=new MutationObserver(()=>{let e=i();e&&(o.disconnect(),clearTimeout(s),t(e))}),s=setTimeout(()=>{o.disconnect(),n(Error(`Timeout waiting for text "${e}"`))},r);o.observe(document.documentElement,{childList:!0,subtree:!0,characterData:!0})})},async waitForHidden(e,t=2e4){await Y.waitForSelector(e,{state:`hidden`,timeout:t})},getByRole(e,t={}){let{name:n}=t,r={button:[`button`,`input[type="button"]`,`input[type="submit"]`,`input[type="reset"]`],link:[`a[href]`],textbox:[`input:not([type])`,`input[type="text"]`,`input[type="email"]`,`input[type="password"]`,`input[type="search"]`,`input[type="tel"]`,`input[type="url"]`,`textarea`],checkbox:[`input[type="checkbox"]`],radio:[`input[type="radio"]`],combobox:[`select`],heading:[`h1`,`h2`,`h3`,`h4`,`h5`,`h6`],list:[`ul`,`ol`],listitem:[`li`],navigation:[`nav`],main:[`main`],banner:[`header`],contentinfo:[`footer`],form:[`form`],img:[`img`],table:[`table`]},i=[];i.push(...document.querySelectorAll(`[role="${e}"]`));let a=r[e];if(a)for(let e of a)i.push(...document.querySelectorAll(`${e}:not([role])`));if(!n)return i[0]||null;let o=n.toLowerCase().trim();for(let e of i){let t=e.getAttribute(`aria-label`)?.toLowerCase().trim(),n=e.textContent?.toLowerCase().trim(),r=e.getAttribute(`title`)?.toLowerCase().trim(),i=e.getAttribute(`placeholder`)?.toLowerCase().trim();if(t===o||n===o||r===o||i===o||t?.includes(o)||n?.includes(o))return e}return null}};window.__piHelpers||(window.__piHelpers=Y,window.piHelpers=Y);function X(){return window.__piElementMap}function Z(e=`interactive`,t=15,n,r=!1,i=!1){try{window.__piRefs={};function a(e){return G(e)}function o(e){let t=e.tagName.toLowerCase(),n=e.getAttribute(`aria-labelledby`);if(n){let e=n.split(/\s+/).map(e=>document.getElementById(e)?.textContent?.trim()||``).filter(Boolean);if(e.length){let t=e.join(` `);return t.length>100?t.substring(0,100)+`...`:t}}if(t===`select`){let t=e,n=t.querySelector(`option[selected]`)||(t.selectedIndex>=0?t.options[t.selectedIndex]:null);if(n?.textContent?.trim())return n.textContent.trim()}let r=e.getAttribute(`aria-label`);if(r?.trim())return r.trim();let i=e.getAttribute(`placeholder`);if(i?.trim())return i.trim();let a=e.getAttribute(`title`);if(a?.trim())return a.trim();let o=e.getAttribute(`alt`);if(o?.trim())return o.trim();if(e.id){let t=document.querySelector(`label[for="${e.id}"]`);if(t?.textContent?.trim())return t.textContent.trim()}if(t===`input`){let t=e,n=e.getAttribute(`type`)||``,r=e.getAttribute(`value`);if(n===`submit`&&r?.trim())return r.trim();if(t.value&&t.value.length<50&&t.value.trim())return t.value.trim()}if([`button`,`a`,`summary`].includes(t)){let t=e.textContent||``;if(t.trim())return t.trim()}if(/^h[1-6]$/.test(t)){let t=e.textContent;if(t?.trim()){let e=t.trim();return e.length>100?e.substring(0,100)+`...`:e}}if(t===`img`)return``;let s=``;for(let t of e.childNodes)t.nodeType===Node.TEXT_NODE&&(s+=t.textContent);if(s?.trim()&&s.trim().length>=3){let e=s.trim();return e.length>100?e.substring(0,100)+`...`:e}return``}function s(e){let t={},n=e.getAttribute(`aria-checked`);n===`true`?t.checked=!0:n===`false`?t.checked=!1:n===`mixed`?t.checked=`mixed`:e instanceof HTMLInputElement&&(e.type===`checkbox`||e.type===`radio`)&&(t.checked=e.type===`checkbox`&&e.indeterminate?`mixed`:e.checked);let r=e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement;(e.getAttribute(`aria-disabled`)===`true`||r&&e.disabled||e.closest(`fieldset:disabled`))&&(t.disabled=!0);let i=e.getAttribute(`aria-expanded`);i===`true`?t.expanded=!0:i===`false`&&(t.expanded=!1);let a=e.getAttribute(`aria-pressed`);a===`true`?t.pressed=!0:a===`false`?t.pressed=!1:a===`mixed`&&(t.pressed=`mixed`);let o=e.getAttribute(`aria-selected`);o===`true`?t.selected=!0:o===`false`&&(t.selected=!1);let s=e.getAttribute(`aria-current`);s&&s!==`false`&&(t.active=!0);let c=e.tagName.toLowerCase();if(/^h[1-6]$/.test(c))t.level=parseInt(c[1],10);else{let n=e.getAttribute(`aria-level`);n&&(t.level=parseInt(n,10))}return t}function c(e){let t=[];return e.checked!==void 0&&t.push(e.checked===`mixed`?`[checked=mixed]`:e.checked?`[checked]`:`[unchecked]`),e.disabled&&t.push(`[disabled]`),e.expanded!==void 0&&t.push(e.expanded?`[expanded]`:`[collapsed]`),e.pressed!==void 0&&t.push(e.pressed===`mixed`?`[pressed=mixed]`:e.pressed?`[pressed]`:`[not-pressed]`),e.selected!==void 0&&t.push(e.selected?`[selected]`:`[not-selected]`),e.active&&t.push(`[active]`),e.level!==void 0&&t.push(`[level=${e.level}]`),t.join(` `)}function l(e){let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`&&t.opacity!==`0`&&e.offsetWidth>0&&e.offsetHeight>0}function u(e){let t=e.tagName.toLowerCase();return[`a`,`button`,`input`,`select`,`textarea`,`details`,`summary`].includes(t)||e.hasAttribute(`onclick`)||e.hasAttribute(`tabindex`)||e.getAttribute(`role`)===`button`||e.getAttribute(`role`)===`link`||e.getAttribute(`contenteditable`)===`true`}function d(e){let t=e.tagName.toLowerCase();return[`h1`,`h2`,`h3`,`h4`,`h5`,`h6`,`nav`,`main`,`header`,`footer`,`section`,`article`,`aside`].includes(t)||e.hasAttribute(`role`)}function f(e){return window.getComputedStyle(e).cursor===`pointer`}function p(e,t){let n=e.tagName.toLowerCase();if([`script`,`style`,`meta`,`link`,`title`,`noscript`].includes(n)||t.filter!==`all`&&e.getAttribute(`aria-hidden`)===`true`||t.filter!==`all`&&!l(e))return!1;if(t.filter!==`all`&&!t.refId){let t=e.getBoundingClientRect();if(!(t.top<window.innerHeight&&t.bottom>0&&t.left<window.innerWidth&&t.right>0))return!1}if(t.filter===`interactive`)return u(e);if(u(e)||d(e)||o(e).length>0)return!0;let r=a(e);return t.compact&&new Set([`generic`,`group`,`region`,`article`,`section`,`complementary`]).has(r)&&o(e).length===0?!1:r!==`generic`&&r!==`img`}function m(r,l){let u=[],d={filter:e,refId:n||null,compact:i},h=X(),g=p(r,d)||n&&l===0;if(g){let e=a(r),t=o(r),n=s(r),i=q(r,e,t);window.__piRefs[i]=r,h[i]={element:new WeakRef(r),role:e,name:t};let d=`${` `.repeat(l)}${e}`;if(t){let e=t.replace(/\s+/g,` `).replace(/"/g,`\\"`);d+=` "${e}"`}d+=` [${i}]`;let p=c(n);p&&(d+=` ${p}`),f(r)&&(d+=` [cursor=pointer]`);let m=r.getAttribute(`href`);m&&(d+=` href="${m}"`);let g=r.getAttribute(`type`);g&&(d+=` type="${g}"`);let _=r.getAttribute(`placeholder`);_&&(d+=` placeholder="${_}"`),u.push(d)}if(l<t)for(let e of r.children)u.push(...m(e,g?l+1:l));return u}function h(e){return e.replace(/\[e\d+\]/g,`[REF]`)}function g(e){let t=new Map;for(let n of e){if(!n.trim())continue;let e=h(n);t.set(e,(t.get(e)||0)+1)}return t}function _(e,t){let n=e.split(`
|
|
111
111
|
`),r=t.split(`
|
|
112
112
|
`),i=g(n),a=g(r),o=[],s=[];for(let e of r){if(!e.trim())continue;let t=h(e),n=i.get(t)||0;(a.get(t)||0)>n&&(o.push(e),i.set(t,n+1))}let c=g(n);for(let e of n){if(!e.trim())continue;let t=h(e),n=c.get(t)||0;n>(a.get(t)||0)&&(s.push(e),c.set(t,n-1))}if(o.length===0&&s.length===0)return{diff:`[NO CHANGES]`,hasChanges:!1};let l=[];return s.length>0&&l.push(...s.map(e=>`- ${e}`)),o.length>0&&l.push(...o.map(e=>`+ ${e}`)),{diff:l.join(`
|
|
113
|
-
`),hasChanges:!0}}let v=
|
|
114
|
-
`);if(x.length>5e4)return{error:`Output exceeds 50000 character limit (${x.length} characters). Try using filter="interactive" or specify a ref_id.`,pageContent:``,viewport:{width:window.innerWidth,height:window.innerHeight}};let S=
|
|
115
|
-
`);return m.length>5e4?{error:`Output exceeds 50000 character limit (${m.length} characters). Try using filter="interactive".`,yaml:``,viewport:{width:window.innerWidth,height:window.innerHeight}}:{yaml:m+`\n\n[Viewport: ${window.innerWidth}x${window.innerHeight}]`,viewport:{width:window.innerWidth,height:window.innerHeight}}}catch(e){return{error:`Error generating YAML tree: ${e instanceof Error?e.message:`Unknown error`}`,yaml:``,viewport:{width:window.innerWidth,height:window.innerHeight}}}}function L(e){let t=N(),n=t[e],r;if(n&&(r=n.element.deref(),r||delete t[e]),!r&&window.__piRefs&&(r=window.__piRefs[e]),!r)return{x:0,y:0,error:`Element ${e} not found. Use read_page to get current elements.`};let i=r.getBoundingClientRect();return{x:Math.round(i.left+i.width/2),y:Math.round(i.top+i.height/2)}}function R(e,t){let n=N(),r=n[e],i;if(r&&(i=r.element.deref(),i||delete n[e]),!i&&window.__piRefs&&(i=window.__piRefs[e]),!i)return{success:!1,error:`Element ${e} not found. Use read_page to get current elements.`};let a=i.tagName.toLowerCase();try{if(a===`input`){let e=i,n=e.type.toLowerCase();n===`checkbox`||n===`radio`?(e.checked=!!t,e.dispatchEvent(new Event(`change`,{bubbles:!0}))):(e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})))}else if(a===`textarea`){let e=i;e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0}))}else if(a===`select`){let n=i,r=String(t),a=!1;for(let e of n.options)if(e.value===r||e.textContent?.trim()===r){n.value=e.value,a=!0;break}if(!a)return{success:!1,error:`Option "${t}" not found in select element ${e}`};n.dispatchEvent(new Event(`change`,{bubbles:!0}))}else if(i.getAttribute(`contenteditable`)===`true`)i.textContent=String(t),i.dispatchEvent(new Event(`input`,{bubbles:!0}));else return{success:!1,error:`Element ${e} (${a}) is not a form field`};return{success:!0}}catch(e){return{success:!1,error:`Failed to set value: ${e instanceof Error?e.message:`Unknown error`}`}}}function z(e,t,n=!0,r=!1){try{let i=document.querySelector(e);if(!i)return{success:!1,error:`Element not found: ${e}`};let a=i.querySelector(`[contenteditable="true"]`),o=a||i,s=i.isContentEditable||!!a;if(o.focus(),n&&(s?o.textContent=``:o.value=``),s?o.textContent=t:o.value=t,o.dispatchEvent(new Event(`input`,{bubbles:!0})),o.dispatchEvent(new Event(`change`,{bubbles:!0})),r){let e=i.closest(`form`),t=e?.querySelector(`button[type="submit"], input[type="submit"]`)||document.querySelector(`button[type="submit"], button[data-testid*="send"], button[aria-label*="Send"]`);t?t.click():e?e.dispatchEvent(new Event(`submit`,{bubbles:!0})):o.dispatchEvent(new KeyboardEvent(`keydown`,{key:`Enter`,code:`Enter`,keyCode:13,bubbles:!0}))}return{success:!0,contentEditable:s}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}function B(e,t){let n=new TextEncoder().encode(e);if(n.length<=t)return e;let r=t;for(;r>0&&(n[r]&192)==128;)r--;return new TextDecoder(`utf-8`,{fatal:!1}).decode(n.subarray(0,r))}function V(e={}){try{let t=document.querySelector(`article`),n=document.querySelector(`main`),r=(t||n||document.body).textContent?.replace(/\s+/g,` `).trim()||``;return{text:Number.isFinite(e.maxBytes)&&e.maxBytes>0?B(r,e.maxBytes):r.substring(0,5e4),title:document.title,url:window.location.href}}catch(e){return{text:``,title:``,url:``,error:`Failed to extract text: ${e instanceof Error?e.message:`Unknown error`}`}}}function H(e){let t=N(),n=t[e],r;return n&&(r=n.element.deref(),r||delete t[e]),!r&&window.__piRefs&&(r=window.__piRefs[e]),r?(r.scrollIntoView({behavior:`smooth`,block:`center`}),{success:!0}):{success:!1,error:`Element ${e} not found. Run read_page to get current element refs.`}}function U(e,t,n,r=`screenshot.png`){try{let i=atob(e),a=new ArrayBuffer(i.length),o=new Uint8Array(a);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);let s=new Blob([a],{type:`image/png`}),c=new File([s],r,{type:`image/png`}),l=null;if(t){let e=N(),n=e[t];if(n&&(l=n.element.deref(),l||delete e[t]),!l&&window.__piRefs&&(l=window.__piRefs[t]),!l)return{success:!1,error:`Element ${t} not found. Run read_page to get current element refs.`}}else if(n&&(l=document.elementFromPoint(n[0],n[1]),!l))return{success:!1,error:`No element at (${n[0]}, ${n[1]})`};if(!l)return{success:!1,error:`No target element`};if(l.tagName===`INPUT`&&l.type===`file`){let e=l,t=new DataTransfer;return t.items.add(c),e.files=t.files,e.dispatchEvent(new Event(`change`,{bubbles:!0})),{success:!0}}let u=new DataTransfer;u.items.add(c);let d=new DragEvent(`drop`,{bubbles:!0,cancelable:!0,dataTransfer:u});return l.dispatchEvent(d),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Upload failed`}}}var W=null;function G(e){if(e.id)return`#${CSS.escape(e.id)}`;for(let t of[`data-testid`,`data-test-id`,`name`,`aria-label`]){let n=e.getAttribute(t);if(n)return`${e.tagName.toLowerCase()}[${t}=${JSON.stringify(n)}]`}return e.tagName.toLowerCase()}function K(e,t,n){W&&chrome.runtime.sendMessage({type:`PLAYBOOK_WATCH_EVENT`,event:e,selector:t?G(t):void 0,value:n,url:location.href,timestamp:new Date().toISOString()}).catch(()=>{})}typeof document.addEventListener==`function`&&(document.addEventListener(`click`,e=>{e.isTrusted&&e.target instanceof Element&&K(`click`,e.target)},!0),document.addEventListener(`change`,e=>{if(!e.isTrusted||!(e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement||e.target instanceof HTMLSelectElement))return;let t=e.target,n=t instanceof HTMLInputElement&&t.type===`password`;K(`input`,t,W?.includeInputValues&&!n?t.value:`<input>`)},!0)),typeof window.addEventListener==`function`&&(window.addEventListener(`popstate`,()=>K(`navigation`)),window.addEventListener(`hashchange`,()=>K(`navigation`))),chrome.runtime.onMessage.addListener((e,t,n)=>{switch(e.type){case`PLAYBOOK_WATCH_START`:W={includeInputValues:e.includeInputValues===!0},n({success:!0});break;case`PLAYBOOK_WATCH_STOP`:W=null,n({success:!0});break;case`SHOW_AGENT_INDICATORS`:case`HIDE_AGENT_INDICATORS`:case`HIDE_FOR_TOOL_USE`:case`SHOW_AFTER_TOOL_USE`:case`SHOW_STATIC_INDICATOR`:case`HIDE_STATIC_INDICATOR`:if(!window.__piVisualIndicatorMessageHandler){n({error:`Visual indicator content script not loaded.`});break}window.__piVisualIndicatorMessageHandler(e.type),n({success:!0});break;case`GENERATE_ACCESSIBILITY_TREE`:{let t=e.options||{};if(t.format===`yaml`){let e=I(t.filter||`interactive`,t.depth??15),r=j();e.error?n({error:e.error,pageContent:``,viewport:e.viewport}):n({pageContent:e.yaml,viewport:e.viewport,modalStates:r.length>0?r:void 0,modalLimitations:`Only custom modals ([role=dialog]) detected. Native alert/confirm/prompt dialogs and system file choosers cannot be detected from content scripts.`})}else n(P(t.filter||`interactive`,t.depth??15,t.refId,t.forceFullSnapshot??!1,t.compact??!1));break}case`GET_ELEMENT_COORDINATES`:n(L(e.ref));break;case`CLICK_ELEMENT`:{let t=N(),r=t[e.ref],i;if(r&&(i=r.element.deref(),i||delete t[e.ref]),!i&&window.__piRefs&&(i=window.__piRefs[e.ref]),!i){n({error:`Element ${e.ref} not found. Use read_page to get current elements.`});break}if(e.button===`triple`){let e=new MouseEvent(`click`,{bubbles:!0,cancelable:!0,view:window,detail:3});i.dispatchEvent(e)}else e.button===`double`?i.dispatchEvent(new MouseEvent(`dblclick`,{bubbles:!0,cancelable:!0,view:window})):e.button===`right`?i.dispatchEvent(new MouseEvent(`contextmenu`,{bubbles:!0,cancelable:!0,view:window})):i.click();n({success:!0});break}case`FORM_INPUT`:n(R(e.ref,e.value));break;case`EVAL_IN_PAGE`:try{let t=document.createElement(`script`);t.textContent=`(function() { ${e.code} })();`,document.documentElement.appendChild(t),t.remove(),n({success:!0})}catch(e){n({success:!1,error:e instanceof Error?e.message:String(e)})}break;case`GET_PAGE_TEXT`:n(V(e.options||{}));break;case`SMART_TYPE`:n(z(e.selector,e.text,e.clear,e.submit));break;case`GET_FRAME_BY_SELECTOR`:try{let t=document.querySelector(e.selector);if(!t||t.tagName.toLowerCase()!==`iframe`){n({error:`No iframe found with selector "${e.selector}"`});break}n({url:t.src,name:t.name||void 0})}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`GET_FRAME_NAME`:try{n({name:window.name||null})}catch{n({name:null})}break;case`LOCATE_ROLE`:try{let{role:t,name:r,all:i}=e,a=N(),o={button:[`button`,`input[type="button"]`,`input[type="submit"]`,`input[type="reset"]`,`[role="button"]`],link:[`a[href]`,`[role="link"]`],textbox:[`input:not([type])`,`input[type="text"]`,`input[type="email"]`,`input[type="password"]`,`input[type="search"]`,`input[type="tel"]`,`input[type="url"]`,`textarea`,`[role="textbox"]`],checkbox:[`input[type="checkbox"]`,`[role="checkbox"]`],radio:[`input[type="radio"]`,`[role="radio"]`],combobox:[`select`,`[role="combobox"]`],listbox:[`[role="listbox"]`,`select[multiple]`],option:[`option`,`[role="option"]`],heading:[`h1`,`h2`,`h3`,`h4`,`h5`,`h6`,`[role="heading"]`],navigation:[`nav`,`[role="navigation"]`],main:[`main`,`[role="main"]`],img:[`img[alt]`,`[role="img"]`],dialog:[`dialog`,`[role="dialog"]`,`[role="alertdialog"]`],tab:[`[role="tab"]`],tabpanel:[`[role="tabpanel"]`],menu:[`[role="menu"]`],menuitem:[`[role="menuitem"]`]}[t]||[`[role="${t}"]`],s=[];for(let e of o)try{s.push(...document.querySelectorAll(e))}catch{}let c=s.filter(e=>{let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`&&e.offsetWidth>0&&e.offsetHeight>0}),l=c;if(r){let e=r.toLowerCase();l=c.filter(t=>{let n=t.getAttribute(`aria-label`)?.toLowerCase(),r=t.textContent?.trim().toLowerCase(),i=t.getAttribute(`title`)?.toLowerCase(),a=t.placeholder?.toLowerCase(),o=t.value?.toLowerCase();return n?.includes(e)||r?.includes(e)||i?.includes(e)||a?.includes(e)||o?.includes(e)})}if(l.length===0){n({error:`No element found with role "${t}"${r?` and name "${r}"`:``}`});break}let u=l.map(e=>{let n=A(e,t,r||``);return window.__piRefs=window.__piRefs||{},window.__piRefs[n]=e,a[n]={element:new WeakRef(e),role:t,name:r||``},{ref:n,text:e.textContent?.trim().slice(0,50)}});n(i?{matches:u}:{ref:u[0].ref,text:u[0].text})}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`LOCATE_TEXT`:try{let{text:t,exact:r}=e,i=N(),a=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),o=[];for(;a.nextNode();){let e=a.currentNode.textContent||``;if(r?e.trim()===t:e.toLowerCase().includes(t.toLowerCase())){let e=a.currentNode.parentElement;if(e&&!o.includes(e)){let t=window.getComputedStyle(e);t.display!==`none`&&t.visibility!==`hidden`&&o.push(e)}}}if(o.length===0){n({error:`No element found with text "${t}"`});break}let s=o.sort((e,t)=>(e.textContent?.length||0)-(t.textContent?.length||0))[0],c=D(s),l=A(s,c,t);window.__piRefs=window.__piRefs||{},window.__piRefs[l]=s,i[l]={element:new WeakRef(s),role:c,name:t},n({ref:l,text:s.textContent?.trim().slice(0,50)})}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`LOCATE_LABEL`:try{let{label:t}=e,r=N(),i=document.querySelectorAll(`label`),a=null;for(let e of i)if((e.textContent?.trim().toLowerCase())?.includes(t.toLowerCase())){let t=e.getAttribute(`for`);if(t&&(a=document.getElementById(t)),a||=e.querySelector(`input, select, textarea`),a)break}if(a||=(t.toLowerCase(),document.querySelector(`input[aria-label*="${t}" i], input[placeholder*="${t}" i], textarea[aria-label*="${t}" i], textarea[placeholder*="${t}" i], select[aria-label*="${t}" i]`)),!a){n({error:`No form field found with label "${t}"`});break}let o=D(a),s=A(a,o,t);window.__piRefs=window.__piRefs||{},window.__piRefs[s]=a,r[s]={element:new WeakRef(a),role:o,name:t},n({ref:s,label:t})}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`GET_ELEMENT_STYLES`:try{let{selector:t}=e,r=N(),i=e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{tag:e.tagName.toLowerCase(),text:e.innerText?.trim().slice(0,80)||null,box:{x:Math.round(n.x),y:Math.round(n.y),width:Math.round(n.width),height:Math.round(n.height)},styles:{fontSize:t.fontSize,fontWeight:t.fontWeight,fontFamily:t.fontFamily.split(`,`)[0].trim().replace(/"/g,``),color:t.color,backgroundColor:t.backgroundColor,borderRadius:t.borderRadius,border:t.border!==`none`&&t.borderWidth!==`0px`?t.border:null,boxShadow:t.boxShadow===`none`?null:t.boxShadow,padding:t.padding}}};if(/^e\d+$/.test(t)){let e=r[t],a;if(e&&(a=e.element.deref(),a||delete r[t]),!a&&window.__piRefs&&(a=window.__piRefs[t]),!a){n({error:`Element ${t} not found`});break}n({styles:[i(a)]})}else{let e=document.querySelectorAll(t);if(e.length===0){n({error:`No elements found matching "${t}"`});break}n({styles:Array.from(e).map(i)})}}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`SELECT_OPTION`:try{let{selector:t,values:r,by:i}=e,a=N(),o=null;if(/^e\d+$/.test(t)){let e=a[t],r;if(e&&(r=e.element.deref(),r||delete a[t]),!r&&window.__piRefs&&(r=window.__piRefs[t]),!r){n({error:`Element ${t} not found`});break}if(r.tagName!==`SELECT`){n({error:`Element ${t} is not a <select>`});break}o=r}else{if(o=document.querySelector(t),!o){n({error:`No element found matching "${t}"`});break}if(o.tagName!==`SELECT`){n({error:`Element "${t}" is not a <select>`});break}}if(o.multiple)for(let e of o.options)e.selected=!1;let s=[],c=[],l=o.multiple?r:[r[0]];for(let e of l){let t=!1;for(let n of o.options){let r=!1;if(r=i===`index`?n.index===parseInt(e,10):i===`label`?n.text.toLowerCase().includes(e.toLowerCase()):n.value===e,r){n.selected=!0,s.push(n.value),t=!0;break}}t||c.push(e)}o.dispatchEvent(new Event(`change`,{bubbles:!0})),c.length>0?n({selected:s,warning:`Values not found: ${c.join(`, `)}`}):n({selected:s})}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`GET_ELEMENT_TEXT`:try{let{ref:t}=e,r=N(),i=r[t],a;if(i&&(a=i.element.deref(),a||delete r[t]),!a&&window.__piRefs&&(a=window.__piRefs[t]),!a){n({error:`Element ${t} not found`});break}n({text:a.textContent?.trim()||``})}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`SCROLL_TO_ELEMENT`:n(H(e.ref));break;case`UPLOAD_IMAGE`:n(U(e.base64,e.ref,e.coordinate,e.filename));break;case`WAIT_FOR_ELEMENT`:{let{selector:t,state:r=`visible`,timeout:i=2e4}=e,a=Math.min(i,6e4),o=e=>{if(!e)return!1;let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`&&t.opacity!==`0`&&e.offsetWidth>0&&e.offsetHeight>0},s=()=>{let e=document.querySelector(t);switch(r){case`attached`:return!!e;case`detached`:return!e;case`hidden`:return!e||!o(e);default:return o(e)}},c=Date.now();return new Promise(e=>{if(s()){e({success:!0,waited:Date.now()-c});return}let n=new MutationObserver(()=>{s()&&(n.disconnect(),clearTimeout(i),e({success:!0,waited:Date.now()-c}))}),i=setTimeout(()=>{n.disconnect(),e({success:!1,waited:Date.now()-c,error:`Timeout waiting for "${t}" to be ${r}`})},a);n.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`,`class`,`hidden`,`disabled`]})}).then(e=>{if(!e.success){n({error:e.error,waited:e.waited,pageContent:``,viewport:{width:window.innerWidth,height:window.innerHeight}});return}n({...P(`interactive`,15,void 0,!0),waited:e.waited})}),!0}case`WAIT_FOR_URL`:{let{pattern:t,timeout:r=2e4}=e,i=Math.min(r,6e4),a=e=>{if(t.includes(`*`)){let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`<<<GLOBSTAR>>>`).replace(/\*/g,`[^/]*`).replace(/<<<GLOBSTAR>>>/g,`.*`);return RegExp(`^${n}$`).test(e)}return e.includes(t)},o=Date.now();return new Promise(e=>{if(a(window.location.href)){e({success:!0,waited:Date.now()-o});return}let n=!1,r=()=>{n||a(window.location.href)&&(n=!0,clearInterval(s),clearTimeout(c),window.removeEventListener(`popstate`,r),window.removeEventListener(`hashchange`,r),e({success:!0,waited:Date.now()-o}))},s=setInterval(r,100),c=setTimeout(()=>{n||(n=!0,clearInterval(s),window.removeEventListener(`popstate`,r),window.removeEventListener(`hashchange`,r),e({success:!1,waited:Date.now()-o,error:`Timeout waiting for URL to match "${t}". Current: ${window.location.href}`}))},i);window.addEventListener(`popstate`,r),window.addEventListener(`hashchange`,r)}).then(e=>{if(!e.success){n({error:e.error,waited:e.waited,pageContent:``,viewport:{width:window.innerWidth,height:window.innerHeight}});return}n({...P(`interactive`,15,void 0,!0),waited:e.waited})}),!0}case`WAIT_FOR_DOM_STABLE`:{let{stable:t=100,timeout:r=5e3}=e,i=Math.min(r,3e4),a=Date.now();return new Promise(e=>{let n=Date.now(),r=!1,o=()=>{r||Date.now()-n>=t&&(r=!0,s.disconnect(),clearTimeout(c),clearInterval(l),e({success:!0,waited:Date.now()-a}))},s=new MutationObserver(()=>{n=Date.now()}),c=setTimeout(()=>{r||(r=!0,s.disconnect(),clearInterval(l),e({success:!1,waited:Date.now()-a,error:`Timeout: DOM did not stabilize within ${i}ms`}))},i),l=setInterval(o,Math.max(10,Math.min(50,t/2)));s.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),o()}).then(e=>{if(!e.success){n({error:e.error,waited:e.waited,pageContent:``,viewport:{width:window.innerWidth,height:window.innerHeight}});return}n({...P(`interactive`,15,void 0,!0),waited:e.waited})}),!0}case`FORM_FILL`:{let{data:t}=e;if(!Array.isArray(t))return n({error:`data must be an array of {ref, value} pairs`}),!0;let r=N(),i=[];for(let e of t){let{ref:t,value:n}=e;if(!t){i.push({ref:t||`unknown`,success:!1,error:`Missing ref`});continue}let a=r[t];if(!a){i.push({ref:t,success:!1,error:`Element not found (run page.read first)`});continue}let o=a.element.deref();if(!o){delete r[t],i.push({ref:t,success:!1,error:`Element no longer exists`});continue}try{if(o instanceof HTMLInputElement){let e=o.type.toLowerCase();e===`checkbox`||e===`radio`?(o.checked=n===!0||n===`true`||n===`1`||n===`checked`,o.dispatchEvent(new Event(`change`,{bubbles:!0}))):(o.focus(),o.value=String(n),o.dispatchEvent(new Event(`input`,{bubbles:!0})),o.dispatchEvent(new Event(`change`,{bubbles:!0}))),i.push({ref:t,success:!0})}else o instanceof HTMLTextAreaElement?(o.focus(),o.value=String(n),o.dispatchEvent(new Event(`input`,{bubbles:!0})),o.dispatchEvent(new Event(`change`,{bubbles:!0})),i.push({ref:t,success:!0})):o instanceof HTMLSelectElement?(o.value=String(n),o.dispatchEvent(new Event(`change`,{bubbles:!0})),i.push({ref:t,success:!0})):o.isContentEditable?(o.focus(),o.textContent=String(n),o.dispatchEvent(new Event(`input`,{bubbles:!0})),i.push({ref:t,success:!0})):i.push({ref:t,success:!1,error:`Element is not fillable`})}catch(e){i.push({ref:t,success:!1,error:e instanceof Error?e.message:String(e)})}}let a=i.filter(e=>!e.success);return n({success:a.length===0,filled:i.filter(e=>e.success).length,failed:a.length,results:i}),!0}case`GET_FILE_INPUT_SELECTOR`:{let{ref:t}=e;if(!t)return n({error:`No ref provided`}),!0;let r=N(),i=r[t];if(!i)return n({error:`Element not found (run page.read first)`}),!0;let a=i.element.deref();if(!a)return delete r[t],n({error:`Element no longer exists`}),!0;if(!(a instanceof HTMLInputElement)||a.type!==`file`)return n({error:`Element is not a file input`}),!0;let o=`__pi_file_${Date.now()}`;return a.setAttribute(`data-pi-file-id`,o),n({selector:`[data-pi-file-id="${o}"]`}),!0}case`WAIT_FOR_NETWORK_IDLE`:{let{timeout:t=1e4}=e,r=Math.min(t,6e4),i=[`doubleclick.net`,`googlesyndication.com`,`googletagmanager.com`,`google-analytics.com`,`facebook.net`,`connect.facebook.net`,`analytics`,`ads`,`tracking`,`pixel`,`hotjar.com`,`clarity.ms`,`mixpanel.com`,`segment.com`,`newrelic.com`,`nr-data.net`,`/tracker/`,`/collector/`,`/beacon/`,`/telemetry/`,`/log/`,`/events/`,`/track.`,`/metrics/`],a=[`img`,`image`,`font`,`icon`],o=e=>i.some(t=>e.includes(t)),s=e=>{let t=e.initiatorType||`unknown`;return!!(a.includes(t)||/\.(jpg|jpeg|png|gif|webp|svg|ico|woff|woff2|ttf|eot)(\?|$)/i.test(e.name))},c=()=>{let e=performance.now();return performance.getEntriesByType(`resource`).filter(t=>{if(t.responseEnd!==0||t.name.startsWith(`data:`)||t.name.length>500||o(t.name))return!1;let n=e-t.startTime;return!(n>1e4||s(t)&&n>3e3)})},l=Date.now();return new Promise(e=>{let t=()=>{let n=c(),i=Date.now()-l;if(n.length===0){e({success:!0,waited:i});return}if(i>=r){e({success:!1,waited:i,pendingCount:n.length});return}setTimeout(t,100)};t()}).then(e=>{if(!e.success){n({error:`Network not idle after ${e.waited}ms (${e.pendingCount} requests pending)`,waited:e.waited,pageContent:``,viewport:{width:window.innerWidth,height:window.innerHeight}});return}n({...P(`interactive`,15,void 0,!0),waited:e.waited})}),!0}case`SEARCH_PAGE`:{let{term:t,caseSensitive:r,limit:i}=e,a=q(t,r||!1,i||10);n({query:t,count:a.length,matches:a});break}case`GET_ELEMENT_BOUNDS_FOR_ANNOTATION`:{let e=N(),t=[];for(let[n,r]of Object.entries(e)){let e=r.element.deref();if(!e)continue;let i=e.getBoundingClientRect();i.width<=0||i.height<=0||i.bottom<0||i.top>window.innerHeight||i.right<0||i.left>window.innerWidth||t.push({ref:n,tag:e.tagName.toLowerCase(),bounds:{x:i.x,y:i.y,width:i.width,height:i.height}})}n({elements:t});break}default:return!1}return!1});function q(e,t,n){let r=[],i=t?e:e.toLowerCase(),a=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),o=N(),s=0;for(;a.nextNode()&&r.length<n;){let c=a.currentNode,l=c.textContent||``,u=t?l:l.toLowerCase(),d=0;for(;(d=u.indexOf(i,d))!==-1&&r.length<n;){let t=c.parentElement;if(!t){d++;continue}let n=document.createRange();n.setStart(c,d),n.setEnd(c,Math.min(d+e.length,l.length));let i=n.getBoundingClientRect();if(i.width===0||i.height===0){d++;continue}let a=c.textContent||``,u=Math.max(0,d-30),f=Math.min(a.length,d+e.length+30),p=a.slice(u,f).trim(),m=null;for(let[e,n]of Object.entries(o)){let r=n.element.deref();if(r&&(r===t||r.contains(t))){m=e;break}}r.push({ref:`m${++s}`,text:a.slice(d,d+e.length),context:p,bounds:{x:Math.round(i.x),y:Math.round(i.y),width:Math.round(i.width),height:Math.round(i.height)},elementRef:m}),d++}}return r}
|
|
113
|
+
`),hasChanges:!0}}let v=X(),y=null;if(n){let e=v[n];if(!e)return{error:`Element with ref_id '${n}' not found. Use read_page without ref_id to get current elements.`,pageContent:``,viewport:{width:window.innerWidth,height:window.innerHeight}};let t=e.element.deref();if(!t)return delete v[n],{error:`Element with ref_id '${n}' no longer exists. Use read_page without ref_id to get current elements.`,pageContent:``,viewport:{width:window.innerWidth,height:window.innerHeight}};y=t}else y=document.body;let b=y?m(y,0):[];for(let e of Object.keys(v))v[e].element.deref()||delete v[e];let x=b.join(`
|
|
114
|
+
`);if(x.length>5e4)return{error:`Output exceeds 50000 character limit (${x.length} characters). Try using filter="interactive" or specify a ref_id.`,pageContent:``,viewport:{width:window.innerWidth,height:window.innerHeight}};let S=J(),C,w=!1,T=window.__piLastSnapshot;return!r&&!n&&T&&Date.now()-T.timestamp<5e3&&(C=_(T.content,x).diff,w=!0),window.__piLastSnapshot={content:x,timestamp:Date.now()},{pageContent:x+`\n\n[Viewport: ${window.innerWidth}x${window.innerHeight}]`,diff:w?C:void 0,viewport:{width:window.innerWidth,height:window.innerHeight},modalStates:S.length>0?S:void 0,modalLimitations:`Only custom modals ([role=dialog]) detected. Native alert/confirm/prompt dialogs and system file choosers cannot be detected from content scripts.`,isIncremental:w}}catch(e){return{error:`Error generating accessibility tree: ${e instanceof Error?e.message:`Unknown error`}`,pageContent:``,viewport:{width:window.innerWidth,height:window.innerHeight}}}}function Ne(e){return e.length?/[\n\r]/.test(e)||/^[\s]/.test(e)||/[\s]$/.test(e)||/[:"{}[\]]/.test(e)?`"`+e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`)+`"`:e:`""`}function Pe(e=`interactive`,t=15){try{window.__piRefs={};let n=[];function r(e){return G(e)}function i(e){let t=e.tagName.toLowerCase(),n=e.getAttribute(`aria-labelledby`);if(n){let e=n.split(/\s+/).map(e=>document.getElementById(e)?.textContent?.trim()||``).filter(Boolean);if(e.length){let t=e.join(` `);return t.length>100?t.substring(0,100)+`...`:t}}if(t===`select`){let t=e,n=t.querySelector(`option[selected]`)||(t.selectedIndex>=0?t.options[t.selectedIndex]:null);if(n?.textContent?.trim())return n.textContent.trim()}let r=e.getAttribute(`aria-label`);if(r?.trim())return r.trim();let i=e.getAttribute(`placeholder`);if(i?.trim())return i.trim();let a=e.getAttribute(`title`);if(a?.trim())return a.trim();let o=e.getAttribute(`alt`);if(o?.trim())return o.trim();if(e.id){let t=document.querySelector(`label[for="${e.id}"]`);if(t?.textContent?.trim())return t.textContent.trim()}if(t===`input`){let t=e,n=e.getAttribute(`type`)||``,r=e.getAttribute(`value`);if(n===`submit`&&r?.trim())return r.trim();if(t.value&&t.value.length<50&&t.value.trim())return t.value.trim()}if([`button`,`a`,`summary`].includes(t)){let t=e.textContent||``;if(t.trim())return t.trim()}if(/^h[1-6]$/.test(t)){let t=e.textContent;if(t?.trim()){let e=t.trim();return e.length>100?e.substring(0,100)+`...`:e}}if(t===`img`)return``;let s=``;for(let t of e.childNodes)t.nodeType===Node.TEXT_NODE&&(s+=t.textContent);if(s?.trim()&&s.trim().length>=3){let e=s.trim();return e.length>100?e.substring(0,100)+`...`:e}return``}function a(e){let t={},n=e.getAttribute(`aria-checked`);n===`true`?t.checked=!0:n===`false`?t.checked=!1:n===`mixed`?t.checked=`mixed`:e instanceof HTMLInputElement&&(e.type===`checkbox`||e.type===`radio`)&&(t.checked=e.type===`checkbox`&&e.indeterminate?`mixed`:e.checked);let r=e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement;(e.getAttribute(`aria-disabled`)===`true`||r&&e.disabled||e.closest(`fieldset:disabled`))&&(t.disabled=!0);let i=e.getAttribute(`aria-expanded`);i===`true`?t.expanded=!0:i===`false`&&(t.expanded=!1);let a=e.getAttribute(`aria-pressed`);a===`true`?t.pressed=!0:a===`false`?t.pressed=!1:a===`mixed`&&(t.pressed=`mixed`);let o=e.getAttribute(`aria-selected`);o===`true`?t.selected=!0:o===`false`&&(t.selected=!1);let s=e.getAttribute(`aria-current`);s&&s!==`false`&&(t.active=!0);let c=e.tagName.toLowerCase();if(/^h[1-6]$/.test(c))t.level=parseInt(c[1],10);else{let n=e.getAttribute(`aria-level`);n&&(t.level=parseInt(n,10))}return t}function o(e){let t=[];return e.checked!==void 0&&t.push(e.checked===`mixed`?`[checked=mixed]`:e.checked?`[checked]`:`[unchecked]`),e.disabled&&t.push(`[disabled]`),e.expanded!==void 0&&t.push(e.expanded?`[expanded]`:`[collapsed]`),e.pressed!==void 0&&t.push(e.pressed===`mixed`?`[pressed=mixed]`:e.pressed?`[pressed]`:`[not-pressed]`),e.selected!==void 0&&t.push(e.selected?`[selected]`:`[not-selected]`),e.active&&t.push(`[active]`),e.level!==void 0&&t.push(`[level=${e.level}]`),t.join(` `)}function s(e){let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`&&t.opacity!==`0`&&e.offsetWidth>0&&e.offsetHeight>0}function c(e){let t=e.tagName.toLowerCase();return[`a`,`button`,`input`,`select`,`textarea`,`details`,`summary`].includes(t)||e.hasAttribute(`onclick`)||e.hasAttribute(`tabindex`)||e.getAttribute(`role`)===`button`||e.getAttribute(`role`)===`link`||e.getAttribute(`contenteditable`)===`true`}function l(e){let t=e.tagName.toLowerCase();return[`h1`,`h2`,`h3`,`h4`,`h5`,`h6`,`nav`,`main`,`header`,`footer`,`section`,`article`,`aside`].includes(t)||e.hasAttribute(`role`)}function u(e){return window.getComputedStyle(e).cursor===`pointer`}function d(e,t,n,r){let i=e;t&&(i+=` `+Ne(t));let a=q(n,e,t);window.__piRefs[a]=n,i+=` [ref=${a}]`;let s=o(r);return s&&(i+=` ${s}`),u(n)&&(i+=` [cursor=pointer]`),i}function f(e){let t={},n=e.getAttribute(`href`);n&&(t.url=n);let r=e.getAttribute(`placeholder`);return r&&(t.placeholder=r),t}function p(o,u,m){if(u>t)return;let h=o.tagName.toLowerCase();if([`script`,`style`,`meta`,`link`,`title`,`noscript`].includes(h)||e!==`all`&&o.getAttribute(`aria-hidden`)===`true`||e!==`all`&&!s(o))return;if(e!==`all`){let e=o.getBoundingClientRect();if(!(e.top<window.innerHeight&&e.bottom>0&&e.left<window.innerWidth&&e.right>0))return}let g=r(o),_=i(o),v=a(o),y=c(o),b=l(o),x=_.length>0,S;if(S=e===`interactive`?y:e===`all`||y||b||x||g!==`generic`&&g!==`img`,S){let e=` `.repeat(u),t=d(g,_,o,v),r=f(o),i=[];for(let e of o.children)i.push(e);let a=i.length>0,s=Object.keys(r).length>0;if(!a&&!s)n.push(`${e}- ${t}`);else{n.push(`${e}- ${t}:`);for(let[t,i]of Object.entries(r))n.push(`${e} - /${t}: ${Ne(i)}`);for(let e of i)p(e,u+1,!0)}}else for(let e of o.children)p(e,u,m)}p(document.body,0,!1);let m=n.join(`
|
|
115
|
+
`);return m.length>5e4?{error:`Output exceeds 50000 character limit (${m.length} characters). Try using filter="interactive".`,yaml:``,viewport:{width:window.innerWidth,height:window.innerHeight}}:{yaml:m+`\n\n[Viewport: ${window.innerWidth}x${window.innerHeight}]`,viewport:{width:window.innerWidth,height:window.innerHeight}}}catch(e){return{error:`Error generating YAML tree: ${e instanceof Error?e.message:`Unknown error`}`,yaml:``,viewport:{width:window.innerWidth,height:window.innerHeight}}}}function Fe(e){let t=X(),n=t[e],r;if(n&&(r=n.element.deref(),r||delete t[e]),!r&&window.__piRefs&&(r=window.__piRefs[e]),!r)return{x:0,y:0,error:`Element ${e} not found. Use read_page to get current elements.`};let i=r.getBoundingClientRect();return{x:Math.round(i.left+i.width/2),y:Math.round(i.top+i.height/2)}}function Ie(e,t){let n=X(),r=n[e],i;if(r&&(i=r.element.deref(),i||delete n[e]),!i&&window.__piRefs&&(i=window.__piRefs[e]),!i)return{success:!1,error:`Element ${e} not found. Use read_page to get current elements.`};let a=i.tagName.toLowerCase();try{if(a===`input`){let e=i,n=e.type.toLowerCase();n===`checkbox`||n===`radio`?(e.checked=!!t,e.dispatchEvent(new Event(`change`,{bubbles:!0}))):T(e,String(t))}else if(a===`textarea`)T(i,String(t));else if(a===`select`){let n=i,r=String(t),a=!1;for(let e of n.options)if(e.value===r||e.textContent?.trim()===r){n.value=e.value,a=!0;break}if(!a)return{success:!1,error:`Option "${t}" not found in select element ${e}`};n.dispatchEvent(new Event(`change`,{bubbles:!0}))}else if(i.getAttribute(`contenteditable`)===`true`)i.textContent=String(t),i.dispatchEvent(new Event(`input`,{bubbles:!0}));else return{success:!1,error:`Element ${e} (${a}) is not a form field`};return{success:!0}}catch(e){return{success:!1,error:`Failed to set value: ${e instanceof Error?e.message:`Unknown error`}`}}}function Le(e,t,n=!0,r=!1){try{let i=document.querySelector(e);if(!i)return{success:!1,error:`Element not found: ${e}`};let a=i.querySelector(`[contenteditable="true"]`),o=a||i,s=i.isContentEditable||!!a;if(o.focus(),s?(n&&(o.textContent=``),o.textContent=t,o.dispatchEvent(new Event(`input`,{bubbles:!0})),o.dispatchEvent(new Event(`change`,{bubbles:!0}))):T(o,t),r){let e=i.closest(`form`),t=e?.querySelector(`button[type="submit"], input[type="submit"]`)||document.querySelector(`button[type="submit"], button[data-testid*="send"], button[aria-label*="Send"]`);t?t.click():e?e.dispatchEvent(new Event(`submit`,{bubbles:!0})):o.dispatchEvent(new KeyboardEvent(`keydown`,{key:`Enter`,code:`Enter`,keyCode:13,bubbles:!0}))}return{success:!0,contentEditable:s}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}function Re(e,t){let n=new TextEncoder().encode(e);if(n.length<=t)return e;let r=t;for(;r>0&&(n[r]&192)==128;)r--;return new TextDecoder(`utf-8`,{fatal:!1}).decode(n.subarray(0,r))}function ze(e={}){try{let t=document.querySelector(`article`),n=document.querySelector(`main`),r=(t||n||document.body).textContent?.replace(/\s+/g,` `).trim()||``;return{text:Number.isFinite(e.maxBytes)&&e.maxBytes>0?Re(r,e.maxBytes):r.substring(0,5e4),title:document.title,url:window.location.href}}catch(e){return{text:``,title:``,url:``,error:`Failed to extract text: ${e instanceof Error?e.message:`Unknown error`}`}}}function Be(e){let t=X(),n=t[e],r;return n&&(r=n.element.deref(),r||delete t[e]),!r&&window.__piRefs&&(r=window.__piRefs[e]),r?(r.scrollIntoView({behavior:`smooth`,block:`center`}),{success:!0}):{success:!1,error:`Element ${e} not found. Run read_page to get current element refs.`}}function Ve(e,t,n,r=`screenshot.png`){try{let i=atob(e),a=new ArrayBuffer(i.length),o=new Uint8Array(a);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);let s=new Blob([a],{type:`image/png`}),c=new File([s],r,{type:`image/png`}),l=null;if(t){let e=X(),n=e[t];if(n&&(l=n.element.deref(),l||delete e[t]),!l&&window.__piRefs&&(l=window.__piRefs[t]),!l)return{success:!1,error:`Element ${t} not found. Run read_page to get current element refs.`}}else if(n&&(l=document.elementFromPoint(n[0],n[1]),!l))return{success:!1,error:`No element at (${n[0]}, ${n[1]})`};if(!l)return{success:!1,error:`No target element`};if(l.tagName===`INPUT`&&l.type===`file`){let e=l,t=new DataTransfer;return t.items.add(c),e.files=t.files,e.dispatchEvent(new Event(`change`,{bubbles:!0})),{success:!0}}let u=new DataTransfer;u.items.add(c);let d=new DragEvent(`drop`,{bubbles:!0,cancelable:!0,dataTransfer:u});return l.dispatchEvent(d),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Upload failed`}}}var Q=null;function He(e){if(e.id)return`#${CSS.escape(e.id)}`;for(let t of[`data-testid`,`data-test-id`,`name`,`aria-label`]){let n=e.getAttribute(t);if(n)return`${e.tagName.toLowerCase()}[${t}=${JSON.stringify(n)}]`}return e.tagName.toLowerCase()}function $(e,t,n){Q&&chrome.runtime.sendMessage({type:`PLAYBOOK_WATCH_EVENT`,event:e,selector:t?He(t):void 0,value:n,url:location.href,timestamp:new Date().toISOString()}).catch(()=>{})}typeof document.addEventListener==`function`&&(document.addEventListener(`click`,e=>{e.isTrusted&&e.target instanceof Element&&$(`click`,e.target)},!0),document.addEventListener(`change`,e=>{if(!e.isTrusted||!(e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement||e.target instanceof HTMLSelectElement))return;let t=e.target,n=t instanceof HTMLInputElement&&t.type===`password`;$(`input`,t,Q?.includeInputValues&&!n?t.value:`<input>`)},!0)),typeof window.addEventListener==`function`&&(window.addEventListener(`popstate`,()=>$(`navigation`)),window.addEventListener(`hashchange`,()=>$(`navigation`))),chrome.runtime.onMessage.addListener((e,t,n)=>{switch(e.type){case`PLAYBOOK_WATCH_START`:Q={includeInputValues:e.includeInputValues===!0},n({success:!0});break;case`PLAYBOOK_WATCH_STOP`:Q=null,n({success:!0});break;case`SHOW_AGENT_INDICATORS`:case`HIDE_AGENT_INDICATORS`:case`HIDE_FOR_TOOL_USE`:case`SHOW_AFTER_TOOL_USE`:case`SHOW_STATIC_INDICATOR`:case`HIDE_STATIC_INDICATOR`:if(!window.__piVisualIndicatorMessageHandler){n({error:`Visual indicator content script not loaded.`});break}window.__piVisualIndicatorMessageHandler(e.type),n({success:!0});break;case`GENERATE_ACCESSIBILITY_TREE`:{let t=e.options||{};if(t.format===`yaml`){let e=Pe(t.filter||`interactive`,t.depth??15),r=J();e.error?n({error:e.error,pageContent:``,viewport:e.viewport}):n({pageContent:e.yaml,viewport:e.viewport,modalStates:r.length>0?r:void 0,modalLimitations:`Only custom modals ([role=dialog]) detected. Native alert/confirm/prompt dialogs and system file choosers cannot be detected from content scripts.`})}else{let e=Z(t.filter||`interactive`,t.depth??15,t.refId,t.forceFullSnapshot??!1,t.compact??!1);t.semanticObservation===!0&&!e.error&&(e.semanticObservation=Ee()),n(e)}break}case`GET_ELEMENT_COORDINATES`:n(Fe(e.ref));break;case`SEMANTIC_NAVIGATE`:{let t=U(void 0,e.expectedIdentity,!1);if(t){n({error:t,code:t});break}window.location.href=e.url,n({success:!0});break}case`SEMANTIC_LOCAL_COMPARE`:{let t=X()[e.ref]?.element.deref(),r=De(t,e.ref);if(!e.expectedIdentity){n({success:!1,matches:!1,reason:`invalid_expected_identity`,identity:r});break}let i=U(t,e.expectedIdentity);if(i){n({success:!1,matches:!1,reason:i,identity:r});break}n({...Oe(t,e.predicate),identity:r});break}case`SEMANTIC_SCROLL_SCOPE`:{if(!e.expectedIdentity){n({success:!1,reason:`invalid_expected_identity`});break}let t=U(void 0,e.expectedIdentity,!1);if(t){n({success:!1,reason:t});break}e.action===`inspect`?n(ve(L)):n(ye(e.action,e.scopeToken,L));break}case`SEMANTIC_SCROLL`:{let t=U(void 0,e.expectedIdentity,!1);if(t){n({error:t,code:t});break}if(e.position===`top`||e.position===`bottom`){n(N(e.position));break}window.scrollBy(e.deltaX||0,e.deltaY||0),n({success:!0,scrollX:window.scrollX,scrollY:window.scrollY});break}case`SCROLL_TO_POSITION`:n(N(e.position,e.selector||null));break;case`CLICK_ELEMENT`:{let t=X(),r=t[e.ref],i;if(r&&(i=r.element.deref(),i||delete t[e.ref]),!i&&window.__piRefs&&(i=window.__piRefs[e.ref]),!i){n({error:`Element ${e.ref} not found. Use read_page to get current elements.`});break}let a=U(i,e.expectedIdentity);if(a){n({error:a,code:a});break}if(e.button===`triple`){let e=new MouseEvent(`click`,{bubbles:!0,cancelable:!0,view:window,detail:3});i.dispatchEvent(e)}else e.button===`double`?i.dispatchEvent(new MouseEvent(`dblclick`,{bubbles:!0,cancelable:!0,view:window})):e.button===`right`?i.dispatchEvent(new MouseEvent(`contextmenu`,{bubbles:!0,cancelable:!0,view:window})):i.click();n({success:!0});break}case`FORM_INPUT`:n(Ie(e.ref,e.value));break;case`PAGE_READINESS`:try{n(he(ge(document,window),e.expect||{}))}catch(e){n({error:e instanceof Error?e.message:String(e),code:e instanceof j?`invalid_selector`:`page_probe_error`})}break;case`PING`:n({success:!0,href:location.href,readyState:document.readyState});break;case`EVAL_IN_PAGE`:try{let t=document.createElement(`script`);t.textContent=`(function() { ${e.code} })();`,document.documentElement.appendChild(t),t.remove(),n({success:!0})}catch(e){n({success:!1,error:e instanceof Error?e.message:String(e)})}break;case`GET_PAGE_TEXT`:n(ze(e.options||{}));break;case`SMART_TYPE`:n(Le(e.selector,e.text,e.clear,e.submit));break;case`GET_FRAME_BY_SELECTOR`:try{let t=document.querySelector(e.selector);if(!t||t.tagName.toLowerCase()!==`iframe`){n({error:`No iframe found with selector "${e.selector}"`});break}n({url:t.src,name:t.name||void 0})}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`GET_FRAME_NAME`:try{n({name:window.name||null})}catch{n({name:null})}break;case`LOCATE_ROLE`:try{let{role:t,name:r,all:i}=e,a=X(),o={button:[`button`,`input[type="button"]`,`input[type="submit"]`,`input[type="reset"]`,`[role="button"]`],link:[`a[href]`,`[role="link"]`],textbox:[`input:not([type])`,`input[type="text"]`,`input[type="email"]`,`input[type="password"]`,`input[type="search"]`,`input[type="tel"]`,`input[type="url"]`,`textarea`,`[role="textbox"]`],checkbox:[`input[type="checkbox"]`,`[role="checkbox"]`],radio:[`input[type="radio"]`,`[role="radio"]`],combobox:[`select`,`[role="combobox"]`],listbox:[`[role="listbox"]`,`select[multiple]`],option:[`option`,`[role="option"]`],heading:[`h1`,`h2`,`h3`,`h4`,`h5`,`h6`,`[role="heading"]`],navigation:[`nav`,`[role="navigation"]`],main:[`main`,`[role="main"]`],img:[`img[alt]`,`[role="img"]`],dialog:[`dialog`,`[role="dialog"]`,`[role="alertdialog"]`],tab:[`[role="tab"]`],tabpanel:[`[role="tabpanel"]`],menu:[`[role="menu"]`],menuitem:[`[role="menuitem"]`]}[t]||[`[role="${t}"]`],s=[];for(let e of o)try{s.push(...document.querySelectorAll(e))}catch{}let c=s.filter(e=>{let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`&&e.offsetWidth>0&&e.offsetHeight>0}),l=c;if(r){let e=r.toLowerCase();l=c.filter(t=>{let n=t.getAttribute(`aria-label`)?.toLowerCase(),r=t.textContent?.trim().toLowerCase(),i=t.getAttribute(`title`)?.toLowerCase(),a=t.placeholder?.toLowerCase(),o=t.value?.toLowerCase();return n?.includes(e)||r?.includes(e)||i?.includes(e)||a?.includes(e)||o?.includes(e)})}if(l.length===0){n({error:`No element found with role "${t}"${r?` and name "${r}"`:``}`});break}let u=l.map(e=>{let n=q(e,t,r||``);return window.__piRefs=window.__piRefs||{},window.__piRefs[n]=e,a[n]={element:new WeakRef(e),role:t,name:r||``},{ref:n,text:e.textContent?.trim().slice(0,50)}});n(i?{matches:u}:{ref:u[0].ref,text:u[0].text})}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`LOCATE_TEXT`:try{let{text:t,exact:r}=e,i=X(),a=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),o=[];for(;a.nextNode();){let e=a.currentNode.textContent||``;if(r?e.trim()===t:e.toLowerCase().includes(t.toLowerCase())){let e=a.currentNode.parentElement;if(e&&!o.includes(e)){let t=window.getComputedStyle(e);t.display!==`none`&&t.visibility!==`hidden`&&o.push(e)}}}if(o.length===0){n({error:`No element found with text "${t}"`});break}let s=o.sort((e,t)=>(e.textContent?.length||0)-(t.textContent?.length||0))[0],c=G(s),l=q(s,c,t);window.__piRefs=window.__piRefs||{},window.__piRefs[l]=s,i[l]={element:new WeakRef(s),role:c,name:t},n({ref:l,text:s.textContent?.trim().slice(0,50)})}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`LOCATE_LABEL`:try{let{label:t}=e,r=X(),i=document.querySelectorAll(`label`),a=null;for(let e of i)if((e.textContent?.trim().toLowerCase())?.includes(t.toLowerCase())){let t=e.getAttribute(`for`);if(t&&(a=document.getElementById(t)),a||=e.querySelector(`input, select, textarea`),a)break}if(a||=(t.toLowerCase(),document.querySelector(`input[aria-label*="${t}" i], input[placeholder*="${t}" i], textarea[aria-label*="${t}" i], textarea[placeholder*="${t}" i], select[aria-label*="${t}" i]`)),!a){n({error:`No form field found with label "${t}"`});break}let o=G(a),s=q(a,o,t);window.__piRefs=window.__piRefs||{},window.__piRefs[s]=a,r[s]={element:new WeakRef(a),role:o,name:t},n({ref:s,label:t})}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`GET_ELEMENT_STYLES`:try{let{selector:t}=e,r=X(),i=e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{tag:e.tagName.toLowerCase(),text:e.innerText?.trim().slice(0,80)||null,box:{x:Math.round(n.x),y:Math.round(n.y),width:Math.round(n.width),height:Math.round(n.height)},styles:{fontSize:t.fontSize,fontWeight:t.fontWeight,fontFamily:t.fontFamily.split(`,`)[0].trim().replace(/"/g,``),color:t.color,backgroundColor:t.backgroundColor,borderRadius:t.borderRadius,border:t.border!==`none`&&t.borderWidth!==`0px`?t.border:null,boxShadow:t.boxShadow===`none`?null:t.boxShadow,padding:t.padding}}};if(/^e\d+$/.test(t)){let e=r[t],a;if(e&&(a=e.element.deref(),a||delete r[t]),!a&&window.__piRefs&&(a=window.__piRefs[t]),!a){n({error:`Element ${t} not found`});break}n({styles:[i(a)]})}else{let e=document.querySelectorAll(t);if(e.length===0){n({error:`No elements found matching "${t}"`});break}n({styles:Array.from(e).map(i)})}}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`SELECT_OPTION`:try{let{selector:t,values:r,by:i}=e,a=X(),o=null;if(/^e\d+$/.test(t)){let e=a[t],r;if(e&&(r=e.element.deref(),r||delete a[t]),!r&&window.__piRefs&&(r=window.__piRefs[t]),!r){n({error:`Element ${t} not found`});break}if(r.tagName!==`SELECT`){n({error:`Element ${t} is not a <select>`});break}o=r}else{if(o=document.querySelector(t),!o){n({error:`No element found matching "${t}"`});break}if(o.tagName!==`SELECT`){n({error:`Element "${t}" is not a <select>`});break}}if(o.multiple)for(let e of o.options)e.selected=!1;let s=[],c=[],l=o.multiple?r:[r[0]];for(let e of l){let t=!1;for(let n of o.options){let r=!1;if(r=i===`index`?n.index===parseInt(e,10):i===`label`?n.text.toLowerCase().includes(e.toLowerCase()):n.value===e,r){n.selected=!0,s.push(n.value),t=!0;break}}t||c.push(e)}o.dispatchEvent(new Event(`change`,{bubbles:!0})),c.length>0?n({selected:s,warning:`Values not found: ${c.join(`, `)}`}):n({selected:s})}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`GET_ELEMENT_TEXT`:try{let{ref:t}=e,r=X(),i=r[t],a;if(i&&(a=i.element.deref(),a||delete r[t]),!a&&window.__piRefs&&(a=window.__piRefs[t]),!a){n({error:`Element ${t} not found`});break}n({text:a.textContent?.trim()||``})}catch(e){n({error:e instanceof Error?e.message:String(e)})}break;case`SCROLL_TO_ELEMENT`:n(Be(e.ref));break;case`UPLOAD_IMAGE`:n(Ve(e.base64,e.ref,e.coordinate,e.filename));break;case`WAIT_FOR_ELEMENT`:{let{selector:t,state:r=`visible`,timeout:i=2e4}=e,a=Math.min(i,6e4),o=e=>{if(!e)return!1;let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`&&t.opacity!==`0`&&e.offsetWidth>0&&e.offsetHeight>0},s=()=>{let e=document.querySelector(t);switch(r){case`attached`:return!!e;case`detached`:return!e;case`hidden`:return!e||!o(e);default:return o(e)}},c=Date.now();return new Promise(e=>{if(s()){e({success:!0,waited:Date.now()-c});return}let n=new MutationObserver(()=>{s()&&(n.disconnect(),clearTimeout(i),e({success:!0,waited:Date.now()-c}))}),i=setTimeout(()=>{n.disconnect(),e({success:!1,waited:Date.now()-c,error:`Timeout waiting for "${t}" to be ${r}`})},a);n.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`,`class`,`hidden`,`disabled`]})}).then(e=>{if(!e.success){n({error:e.error,waited:e.waited,pageContent:``,viewport:{width:window.innerWidth,height:window.innerHeight}});return}n({...Z(`interactive`,15,void 0,!0),waited:e.waited})}),!0}case`WAIT_FOR_URL`:{let{pattern:t,timeout:r=2e4}=e,i=Math.min(r,6e4),a=e=>{if(t.includes(`*`)){let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`<<<GLOBSTAR>>>`).replace(/\*/g,`[^/]*`).replace(/<<<GLOBSTAR>>>/g,`.*`);return RegExp(`^${n}$`).test(e)}return e.includes(t)},o=Date.now();return new Promise(e=>{if(a(window.location.href)){e({success:!0,waited:Date.now()-o});return}let n=!1,r=()=>{n||a(window.location.href)&&(n=!0,clearInterval(s),clearTimeout(c),window.removeEventListener(`popstate`,r),window.removeEventListener(`hashchange`,r),e({success:!0,waited:Date.now()-o}))},s=setInterval(r,100),c=setTimeout(()=>{n||(n=!0,clearInterval(s),window.removeEventListener(`popstate`,r),window.removeEventListener(`hashchange`,r),e({success:!1,waited:Date.now()-o,error:`Timeout waiting for URL to match "${t}". Current: ${window.location.href}`}))},i);window.addEventListener(`popstate`,r),window.addEventListener(`hashchange`,r)}).then(e=>{if(!e.success){n({error:e.error,waited:e.waited,pageContent:``,viewport:{width:window.innerWidth,height:window.innerHeight}});return}n({...Z(`interactive`,15,void 0,!0),waited:e.waited})}),!0}case`WAIT_FOR_DOM_STABLE`:{let{stable:t=100,timeout:r=5e3}=e,i=Math.min(r,3e4),a=Date.now();return new Promise(e=>{let n=Date.now(),r=!1,o=()=>{r||Date.now()-n>=t&&(r=!0,s.disconnect(),clearTimeout(c),clearInterval(l),e({success:!0,waited:Date.now()-a}))},s=new MutationObserver(()=>{n=Date.now()}),c=setTimeout(()=>{r||(r=!0,s.disconnect(),clearInterval(l),e({success:!1,waited:Date.now()-a,error:`Timeout: DOM did not stabilize within ${i}ms`}))},i),l=setInterval(o,Math.max(10,Math.min(50,t/2)));s.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),o()}).then(e=>{if(!e.success){n({error:e.error,waited:e.waited,pageContent:``,viewport:{width:window.innerWidth,height:window.innerHeight}});return}n({...Z(`interactive`,15,void 0,!0),waited:e.waited})}),!0}case`FORM_FILL`:{let{data:t}=e;if(!Array.isArray(t))return n({error:`data must be an array of {ref, value} pairs`}),!0;if(e.expectedIdentity&&t.length!==1)return n({error:`guarded fill requires exactly one field`,code:`stale_observation`}),!0;let r=X(),i=[];for(let a of t){let{ref:t,value:o}=a;if(!t){i.push({ref:t||`unknown`,success:!1,error:`Missing ref`});continue}let s=r[t];if(!s){i.push({ref:t,success:!1,error:`Element not found (run page.read first)`});continue}let c=s.element.deref();if(!c){delete r[t],i.push({ref:t,success:!1,error:`Element no longer exists`});continue}let l=U(c,e.expectedIdentity);if(l)return n({success:!1,error:l,code:l,filled:0,failed:1,results:[]}),!0;try{if(c instanceof HTMLInputElement){let e=c.type.toLowerCase();e===`checkbox`||e===`radio`?(c.checked=o===!0||o===`true`||o===`1`||o===`checked`,c.dispatchEvent(new Event(`change`,{bubbles:!0}))):(c.focus(),T(c,String(o))),i.push({ref:t,success:!0})}else c instanceof HTMLTextAreaElement?(c.focus(),T(c,String(o)),i.push({ref:t,success:!0})):c instanceof HTMLSelectElement?(c.value=String(o),c.dispatchEvent(new Event(`change`,{bubbles:!0})),i.push({ref:t,success:!0})):c.isContentEditable?(c.focus(),c.textContent=String(o),c.dispatchEvent(new Event(`input`,{bubbles:!0})),i.push({ref:t,success:!0})):i.push({ref:t,success:!1,error:`Element is not fillable`})}catch(e){i.push({ref:t,success:!1,error:e instanceof Error?e.message:String(e)})}}let a=i.filter(e=>!e.success);return n({success:a.length===0,filled:i.filter(e=>e.success).length,failed:a.length,results:i}),!0}case`GET_FILE_INPUT_SELECTOR`:{let{ref:t}=e;if(!t)return n({error:`No ref provided`}),!0;let r=X(),i=r[t];if(!i)return n({error:`Element not found (run page.read first)`}),!0;let a=i.element.deref();if(!a)return delete r[t],n({error:`Element no longer exists`}),!0;if(!(a instanceof HTMLInputElement)||a.type!==`file`)return n({error:`Element is not a file input`}),!0;let o=`__pi_file_${Date.now()}`;return a.setAttribute(`data-pi-file-id`,o),n({selector:`[data-pi-file-id="${o}"]`}),!0}case`WAIT_FOR_NETWORK_IDLE`:{let{timeout:t=1e4}=e,r=Math.min(t,6e4),i=[`doubleclick.net`,`googlesyndication.com`,`googletagmanager.com`,`google-analytics.com`,`facebook.net`,`connect.facebook.net`,`analytics`,`ads`,`tracking`,`pixel`,`hotjar.com`,`clarity.ms`,`mixpanel.com`,`segment.com`,`newrelic.com`,`nr-data.net`,`/tracker/`,`/collector/`,`/beacon/`,`/telemetry/`,`/log/`,`/events/`,`/track.`,`/metrics/`],a=[`img`,`image`,`font`,`icon`],o=e=>i.some(t=>e.includes(t)),s=e=>{let t=e.initiatorType||`unknown`;return!!(a.includes(t)||/\.(jpg|jpeg|png|gif|webp|svg|ico|woff|woff2|ttf|eot)(\?|$)/i.test(e.name))},c=()=>{let e=performance.now();return performance.getEntriesByType(`resource`).filter(t=>{if(t.responseEnd!==0||t.name.startsWith(`data:`)||t.name.length>500||o(t.name))return!1;let n=e-t.startTime;return!(n>1e4||s(t)&&n>3e3)})},l=Date.now();return new Promise(e=>{let t=()=>{let n=c(),i=Date.now()-l;if(n.length===0){e({success:!0,waited:i});return}if(i>=r){e({success:!1,waited:i,pendingCount:n.length});return}setTimeout(t,100)};t()}).then(e=>{if(!e.success){n({error:`Network not idle after ${e.waited}ms (${e.pendingCount} requests pending)`,waited:e.waited,pageContent:``,viewport:{width:window.innerWidth,height:window.innerHeight}});return}n({...Z(`interactive`,15,void 0,!0),waited:e.waited})}),!0}case`SEARCH_PAGE`:{let{term:t,caseSensitive:r,limit:i}=e,a=Ue(t,r||!1,i||10);n({query:t,count:a.length,matches:a});break}case`GET_ELEMENT_BOUNDS_FOR_ANNOTATION`:{let e=X(),t=[];for(let[n,r]of Object.entries(e)){let e=r.element.deref();if(!e)continue;let i=e.getBoundingClientRect();i.width<=0||i.height<=0||i.bottom<0||i.top>window.innerHeight||i.right<0||i.left>window.innerWidth||t.push({ref:n,tag:e.tagName.toLowerCase(),bounds:{x:i.x,y:i.y,width:i.width,height:i.height}})}n({elements:t});break}default:return!1}return!1});function Ue(e,t,n){let r=[],i=t?e:e.toLowerCase(),a=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),o=X(),s=0;for(;a.nextNode()&&r.length<n;){let c=a.currentNode,l=c.textContent||``,u=t?l:l.toLowerCase(),d=0;for(;(d=u.indexOf(i,d))!==-1&&r.length<n;){let t=c.parentElement;if(!t){d++;continue}let n=document.createRange();n.setStart(c,d),n.setEnd(c,Math.min(d+e.length,l.length));let i=n.getBoundingClientRect();if(i.width===0||i.height===0){d++;continue}let a=c.textContent||``,u=Math.max(0,d-30),f=Math.min(a.length,d+e.length+30),p=a.slice(u,f).trim(),m=null;for(let[e,n]of Object.entries(o)){let r=n.element.deref();if(r&&(r===t||r.contains(t))){m=e;break}}r.push({ref:`m${++s}`,text:a.slice(d,d+e.length),context:p,bounds:{x:Math.round(i.x),y:Math.round(i.y),width:Math.round(i.width),height:Math.round(i.height)},elementRef:m}),d++}}return r}
|
|
116
116
|
//# sourceMappingURL=index.js.map
|