webhand 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sakamoto66
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,253 @@
1
- # Temporary Holding Version
1
+ # webhand
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Claude が頭、Jev が手。Claude Code のスキルとして、Web ページでの用事を Claude と Jev が役割を分担して進めます。Claude は GOAL と手順の計画、入力値、結果の確認、計画の見直しを担い、Jev(TypeSafe)は GOAL までの操作を選びます。
4
+
5
+ Anthropic の API キーは使いません。作業中の Claude Code がスキルの手順に沿って CLI を実行し、Claude の役割を担います。**操作中のページの内容は Jev(TypeSafe の API)に送られます。**
6
+
7
+ ## インストール
8
+
9
+ 1. プラグインを追加します(Claude Code)。
10
+
11
+ ```text
12
+ /plugin install webhand --marketplace sakamoto66/webhand
13
+ ```
14
+
15
+ 2. Jev の API キーを環境変数に設定し、Claude Code を起動し直します(`TYPESAFE_MODEL` で使うモデルも変えられます)。
16
+
17
+ ```bash
18
+ echo 'export TYPESAFE_API_KEY=...' >> ~/.bashrc # 使っているシェルの設定ファイルに
19
+ ```
20
+
21
+ CLI はインストール不要です。スキルが `npx -y webhand@0.2 ...` で実行します。Node.js 22 以上と Google Chrome(Linux、または WSL から Windows 側)が必要です。毎回の起動を速くしたい場合は、`npm i -g webhand` で入れておくと、スキルは `webhand ...` を使います。
22
+
23
+ ```bash
24
+ npx -y webhand@0.2 catalog # 動作確認
25
+ ```
26
+
27
+ ### 保存場所
28
+
29
+ Claude Code の `~/.claude/` と `.claude/` と同じように、ユーザー単位とプロジェクト単位の2か所を使います。
30
+
31
+ | 場所 | パス | 内容 |
32
+ | --- | --- | --- |
33
+ | ユーザー | `~/.webhand/`(`WEBHAND_HOME` で変更可) | `runbooks/`(どのプロジェクトでも使うサービス情報と手順書)、`runs/`(実行と学習の記録。ページ本文を含む)、`state/`(実行中のセッションと保存プロファイル) |
34
+ | プロジェクト | 現在のディレクトリから上にたどって最初に見つかる `.webhand/`(ホームディレクトリで止まる) | `runbooks/`(そのプロジェクトのサービス情報と手順書。git で共有できる) |
35
+
36
+ - 手順書とサービス情報は、プロジェクト、ユーザーの順に探します。同じ名前ならプロジェクトのものを使います。`catalog` は両方を一覧し、それぞれの出所を `(project)` / `(user)` で示します。
37
+ - `learn` は既定でプロジェクトに書きます(`.webhand/` がなければ git のルート、なければ現在のディレクトリに作ります)。`--scope user` でユーザーに書きます。
38
+ - ログイン状態と実行記録はユーザー単位にだけ置き、プロジェクトには置きません。API キーはファイルに置かず、環境変数(`TYPESAFE_API_KEY`)からだけ読みます。
39
+
40
+ ```
41
+ Claude Code ── /webhand-learn ──> .webhand/runbooks/<service>/ または ~/.webhand/runbooks/<service>/
42
+ │
43
+ └──────── /webhand ── CLI webhand ── CDP ──> Chrome(新規 / 保存プロファイル、WSL では Windows 側も可)
44
+ 計画・入力値・確認・見直し └── run ──> Jev(GOAL までの操作を選択)
45
+ ```
46
+
47
+ ## ユーザー体験
48
+
49
+ 1. **学習する**: `/webhand-learn` で、人の操作の記録またはソースコードから、サービス情報と手順書を作ります。
50
+ 2. **頼む**: `/webhand ホテルを予約して` のように投稿します。Claude が学習済みのデータから GOAL、手順、入力値を計画し、足りない情報はユーザーに質問します。
51
+ 3. **セッションを選ぶ**: 新規(使い捨て)か、ログイン状態を残した保存プロファイルかを選びます。
52
+ 4. **実行する**: 計画した URL を開きます。Jev は、サービス情報、計画、表示中のページ、これまでの操作履歴をもとに次の操作を選び、GOAL までループします。
53
+ 5. **見直す**: GOAL に届かなければ、Claude が原因を書いて計画を見直し、再挑戦します(既定で最大3回)。
54
+
55
+ ## 役割分担
56
+
57
+ | 担当 | 役割 |
58
+ | --- | --- |
59
+ | Claude | GOAL と手順を計画する、入力値を書く、足りない情報を質問する、結果を確認する、計画を見直す、実行を締める |
60
+ | Jev | GOAL までの操作ごとに、対象の要素と Claude の入力値のどれを使うかを番号で選ぶ |
61
+ | コード | 選択を観測済み要素と Claude の値に限定し、鮮度を確認して実行する。独立検証を行う |
62
+
63
+ `run` は、次のいずれかの場合にだけ Claude に制御を返します。
64
+
65
+ | 結果 | 発生条件 | Claude の対応 |
66
+ | --- | --- | --- |
67
+ | `GOAL_REPORTED` | Jev が GOAL 達成を申告した | ページを GOAL と照合し、`finish` か `replan` |
68
+ | `NEEDS_VALUE` | 入力欄に合う値が計画にない | `run --value "ラベル=値"`。わからなければユーザーに聞く |
69
+ | `NEEDS_HUMAN` | ログイン、認証コード、CAPTCHA、`[person]` の手順 | ユーザーに依頼し、`run --human-done` |
70
+ | `BLOCKED` / `STUCK` / `ATTEMPT_BUDGET` | 進めなくなった | `replan` で再挑戦、`act` で1手補う、または `finish` |
71
+ | `JEV_FAILED` | Jev の応答が使えない(何も実行していない) | もう一度 `run`、`replan`、または `act` |
72
+ | `UNCERTAIN` | 操作が実行されたかどうか不明 | 繰り返さず、`finish --status error` |
73
+
74
+ 確信度は記録しますが、Jev を止める条件には使いません。
75
+
76
+ ## セッション
77
+
78
+ | `--session` | 内容 |
79
+ | --- | --- |
80
+ | `new`(既定) | 一時プロファイル。ログインしていない状態で始まり、終了時に削除されます |
81
+ | `profile:NAME` | webhand 専用の保存プロファイル。ログイン状態が次回も残ります |
82
+
83
+ ```bash
84
+ webhand profile login work --url https://example.com/login # 人がログインしてウィンドウを閉じる
85
+ webhand profile list
86
+ webhand profile delete work
87
+ ```
88
+
89
+ 普段使いの Chrome プロファイルには接続しません。Chrome 136 以降は、既定のプロファイルへのデバッグ接続ができないためです。保存プロファイルは、Linux では `~/.webhand/state/profiles/`、Windows では `%LOCALAPPDATA%\webhand\profiles\` に置かれます。
90
+
91
+ **ログイン後のページの内容は Jev(TypeSafe の API)に送られます。** 個人情報を含む画面を扱うかどうかは、実行前に判断してください。
92
+
93
+ ## WSL で Windows 側の Chrome を使う
94
+
95
+ `--chrome auto`(既定)は、WSL 上で Windows の `chrome.exe` に接続できればそれを使い、できなければ Linux の Chrome を使います。`--chrome windows` または `--chrome linux` で固定でき、`WEBHAND_CHROME` でも指定できます。
96
+
97
+ Windows の Chrome は、デバッグポートを Windows の 127.0.0.1 で待ち受けます。そのため、WSL のネットワークを mirrored にする必要があります。
98
+
99
+ ```ini
100
+ # %USERPROFILE%\.wslconfig
101
+ [wsl2]
102
+ networkingMode=mirrored
103
+ ```
104
+
105
+ 設定したら、PowerShell で `wsl --shutdown` を実行して WSL を再起動します。ローカルファイルの URL は `file://wsl.localhost/...` に変換して開きます。
106
+
107
+ ## 使い方
108
+
109
+ Claude Code のセッションで、スキルを呼び出します。
110
+
111
+ ```text
112
+ /webhand HOTEL PLANISPHERE で来月の土曜から2泊、2名で予約して
113
+ ```
114
+
115
+ 下の表の `webhand` は、インストールしていなければ `npx -y webhand@0.2` と読み替えてください。`webhand --version` で版を確認できます。
116
+
117
+
118
+ | コマンド | 担当 | 内容 |
119
+ | --- | --- | --- |
120
+ | `webhand catalog` | Claude | 学習済みのサービス、手順書、保存プロファイルを一覧する |
121
+ | `webhand start --goal G --url U --step S ... --value L=V ... --session ...` | Claude | 計画を記録し、Chrome で開始 URL を開く |
122
+ | `webhand run` | Jev | GOAL まで操作する |
123
+ | `webhand replan --reason R [--step ...] [--value ...] [--focus ...] [--skip ...] [--restart]` | Claude | 計画を見直して、次の試行を始める |
124
+ | `webhand act OP [TARGET]` | Claude | Jev の代わりに操作を1つ実行する |
125
+ | `webhand observe` | Claude | 現在のページを表示する |
126
+ | `webhand finish --status STATUS` | Claude | 独立検証、ログ記録、Chrome の終了 |
127
+ | `webhand learn --name NAME --url URL [--scope project\|user]` | 人 | 操作を記録する |
128
+ | `webhand profile login/list/delete` | 人 | 保存プロファイルを管理する |
129
+
130
+ 手順の先頭に `[person]` を付けると、人が行う手順になります(`--headed` が必須です)。`start` と `replan` の `--focus REGION` / `--skip REGION` で、観測する領域を選べます(下の「ページの領域」)。`--runbook NAME --param k=v` を指定すると、手順書の GOAL、開始 URL、手順が既定値になり、params は入力値として Jev に渡されます。
131
+
132
+ ## 学習モード
133
+
134
+ 人の操作、またはサービスのソースコードから、次の2種類のファイルを作ります。
135
+
136
+ | ファイル | 内容 | 使われ方 |
137
+ | --- | --- | --- |
138
+ | `runbooks/<service>/service.toml` | サービスの説明、ログインの要否、ページと領域の一覧、Jev 向けの事実 | `catalog` で Claude が読み、`--service` で Jev に渡す |
139
+ | `runbooks/<service>/<name>.toml` | 手順書(goal、params、steps、hints、done_when、focus、skip) | Claude の計画の下敷き。手順と hints は Jev にも渡す |
140
+
141
+ どちらも、プロジェクトの `.webhand/` かユーザーの `~/.webhand/` に置きます(「保存場所」)。`learn` は書き込み先を `WRITE THE RUNBOOK TO ...` として表示します。`start_url` にローカルファイルの相対パスを書くと、その `.webhand/` を含むディレクトリからのパスになります。
142
+
143
+ ```text
144
+ /webhand-learn --name myservice/search --url https://example.com
145
+ ```
146
+
147
+ 1. `webhand learn` が Chrome を開き、ユーザーの操作を記録します。ウィンドウを閉じると終了します。ログインした状態で操作を見せる場合は、`--session profile:NAME` を付けます。バックグラウンドのジョブを止めても(SIGTERM、または npx の終了)、記録を保存して Chrome を閉じます。
148
+ 2. Claude が記録またはソースコードから、サービス情報と手順書の下書きを書きます。
149
+ 3. `--runbook NAME --param k=v --allow-draft` で試行します。
150
+ 4. ユーザーが内容を確認し、`status = "approved"` にします。
151
+
152
+ 手順書は機械的に再生しません。
153
+
154
+ 記録の扱い:
155
+
156
+ - キー入力は記録しません。パスワード、ワンタイムコード、カード番号などの欄の値は `<redacted>` になります。ただし秘匿の判定は欄の属性と名前によるため、見分けられない欄の値は `runs/` の記録に残ります
157
+ - URL のクエリの値はすべて伏せます
158
+ - 記録はワークスペースの `runs/` に保存されます。ページ本文を含むため、共有しないでください
159
+ - iframe 内の操作、ファイル選択、新しいタブは再現できないため、`unsupported` として残します
160
+ - ページのスクリプトは記録を偽装できるため、記録は信頼せず、手順書はユーザーが承認します
161
+
162
+ ## ページの領域
163
+
164
+ 観測は、テキスト 6000 文字、操作 250 件が上限です。ページは領域(header、nav、main、form、fieldset、table、dialog、ラベル付きの section など)に分けて観測します。領域のキーは、外側の領域からの並びです。
165
+
166
+ ```text
167
+ main/form:宿泊予約/fieldset:追加プラン # 種類:名前。名前は aria-label、legend、caption、領域の先頭の見出しから取る
168
+ nav#2 # 名前のない同じ種類が並ぶときは順番
169
+ ```
170
+
171
+ - 観測結果の `regions` には、領域ごとに位置(`above` / `visible` / `below`)、テキストと操作の表示数と全数、画面外の操作の数が入ります。Claude には `REGIONS`、Jev には `page.regions` として渡ります。何が切り捨てられたかがわかります。
172
+ - `focus` の領域は先頭に並び、テキストはページ全体から取ります。`skip` の領域は要約にだけ出ます。どちらもないときは、今までどおり画面内を DOM 順に取ります。開いた dialog は、view があるときは常に先頭です。
173
+ - パターンはキーのどこに一致してもよく、一致した領域の内側も含みます。名前や番号のない段(`form`)は、その種類のどの領域にも一致します。focus と skip の両方に一致したら、深いほうが勝ちます(同じ深さなら focus)。
174
+ - 操作の対象は今までどおり画面内だけです。鮮度の判定(`marker`、`page_key`、`guards`)は、view に関係なく同じ入力から計算します。
175
+ - view は、service.toml の `default`、手順書の `focus` / `skip`、Claude の `--focus` / `--skip` の順に重ね、後のものが勝ちます。`run_start` と `plan` のイベントに `view` が残ります。
176
+
177
+ ```toml
178
+ # service.toml
179
+ [[pages.regions]]
180
+ key = "main/form:宿泊予約"
181
+ purpose = "予約フォーム"
182
+ [[pages.regions]]
183
+ key = "footer"
184
+ purpose = "サイト共通のリンク"
185
+ default = "skip" # focus か skip。なしなら通常
186
+
187
+ # 手順書
188
+ focus = ["form:宿泊予約"]
189
+ skip = ["header", "footer"]
190
+ ```
191
+
192
+ 学習の記録では、`page` イベントに領域の要約(キーと件数だけ)、`action` イベントに対象の領域キーが入ります。秘密に見える名前の段は `form:<redacted>` になります。
193
+
194
+ `verify()` のないサービスでは `verified` は `None` です。手順書の `done_when` は Claude の確認材料で、成功の証拠にはなりません。
195
+
196
+ ## ログ
197
+
198
+ ワークスペースの `runs/<時刻>/` に JSONL で出力されます。
199
+
200
+ | type | 内容 |
201
+ | --- | --- |
202
+ | `run_start` | 目標、Chrome(linux / windows)、セッションの種類、git commit、手順書、サービス |
203
+ | `plan` | 試行ごとの手順、入力値のラベル、その出所(`claude` / `runbook`)、`restart` |
204
+ | `call` | Jev の呼び出しごとのトークンと遅延 |
205
+ | `step` / `step_result` | 実行した操作、試行番号、判断者、確信度、ページの変化 |
206
+ | `escalation` | `run` が Claude に返した結果 |
207
+ | `human_step` / `values` | 人の手順の依頼と完了、追加された入力値のラベル |
208
+ | `attempt_end` | 試行の結果と、Claude が書いた見直しの理由 |
209
+ | `handoff` | Claude が読む CLI 出力の文字数 |
210
+ | `run_end` | 自己申告の状態、独立検証の結果、試行回数と試行ごとの結果、役割ごとの集計 |
211
+
212
+ 成功判定は `run_end.verified` です。`status=done` は申告にすぎません。Claude Code のトークン数は取得しないため、`handoffs`(Claude に戻した回数)と `handoff_chars`(読ませた文字数)を代理指標にします。
213
+
214
+ ## タスクの追加(研究用)
215
+
216
+ タスクは研究用リポジトリの `tasks/` にだけ置き、npm の配布物には含めません。`tasks/<名前>.ts` で次を export します。
217
+
218
+ - `GOAL`: 自然言語の目標
219
+ - `startUrl(root)`: 開始 URL(`root` はリポジトリのルート)
220
+ - `verify(browser)`: `{success, evidence}` を返す独立検証(async)
221
+ - `SCRIPT`: 基盤の動作確認用の固定手順
222
+
223
+ `--task` はリポジトリのルートで実行します。Node の型除去でそのまま読み込むため、型注釈を消すだけで動く構文で書きます(Node 22.18 以上)。
224
+
225
+ ## 開発
226
+
227
+ このリポジトリは研究基盤も兼ねています(実験設計は `docs/research-plan.md`)。TypeScript で書かれ、Node.js 22 以上で動きます(開発は Node 24)。リポジトリの `.webhand/runbooks/` が、このリポジトリのプロジェクト単位の手順書です。
228
+
229
+ ```bash
230
+ npm ci
231
+ npm run build && npm link # webhand コマンドを作業ツリーのビルドに向ける
232
+ claude --plugin-dir .
233
+ ```
234
+
235
+ 実行記録をリポジトリの `runs/` に残したい場合は、`.claude/settings.local.json` に `{"env": {"WEBHAND_HOME": "<このリポジトリの絶対パス>"}}` を書きます。このときユーザー単位の手順書は `~/.webhand/runbooks/` ではなく、リポジトリの `runbooks/` から読みます。
236
+
237
+ ```bash
238
+ npm run lint # Biome
239
+ npm run typecheck
240
+ npm test # 有料 API は呼びません。Linux の Chrome を使います
241
+ npm run test:coverage # カバレッジ(coverage/index.html)
242
+ npm run smoke -- --task hotel_filter # モデルなしの動作確認
243
+ ```
244
+
245
+ `tests/golden/` は Python 版の出力の記録です。Claude と Jev が読む文字列(`render`、`report`、Jev への state と質問など)が移行の前後で同じであることを確かめます。
246
+
247
+ 公開は `npm publish`(`prepublishOnly` で lint、型チェック、ビルド)です。`package.json` と `.claude-plugin/plugin.json` の版を揃え、スキルの `webhand@0.2` も合わせて更新します。
248
+
249
+ ## ライセンス
250
+
251
+ MIT License(`LICENSE`)。
252
+
253
+ `assets/snapshot.js`、`src/policies/base.ts`、`src/policies/jev.ts`、`tasks/fixtures/hotel.html` は [jev-ultrafast](https://github.com/browser-use/jev-ultrafast)(MIT)を改変したものです。`THIRD_PARTY_LICENSE_jev-ultrafast.txt` を参照してください。
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Browser Use
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,113 @@
1
+ (() => {
2
+ if (window.__browserLabRecorder) return;
3
+ window.__browserLabRecorder = true;
4
+ const read = () => __SNAPSHOT__;
5
+ const inFrame = window !== window.top;
6
+ const secretWords = /pass|pwd|\bpw\b|secret|token|otp|cvv|cvc|card|ssn|\bpin\b|パスワード|暗証|認証コード|カード/i;
7
+ const secretAutocomplete = /(^|\s)(current-password|new-password|one-time-code|cc-[a-z-]+)(\s|$)/;
8
+ const everPassword = new WeakSet();
9
+ const secret = (e, label) => e.type === 'password' || everPassword.has(e) ||
10
+ secretAutocomplete.test(e.getAttribute('autocomplete') || '') ||
11
+ secretWords.test([e.name, e.id, e.getAttribute('aria-label'), e.getAttribute('placeholder'), label].join(' '));
12
+ // A GET form copies field values into the URL under any key, so no query value is kept.
13
+ const safeUrl = () => {
14
+ const url = new URL(location.href);
15
+ for (const key of [...url.searchParams.keys()]) url.searchParams.set(key, '<redacted>');
16
+ if (url.hash.includes('=')) url.hash = '<redacted>';
17
+ return url.href;
18
+ };
19
+ // A region key is built from labels and headings. A segment whose name looks secret keeps only its kind.
20
+ const safeRegion = key => (key || '').split('/').map(segment => {
21
+ const [kind, ...name] = segment.split(':');
22
+ return name.length && secretWords.test(name.join(':')) ? kind + ':<redacted>' : segment;
23
+ }).join('/');
24
+ const send = event => {
25
+ const payload = {...event, url: safeUrl()};
26
+ window.__browserLabRecord?.(inFrame ? {...payload, kind: 'unsupported', reason: 'iframe'} : payload);
27
+ };
28
+ // Listeners on window see shadow DOM events retargeted to the host; use the original target.
29
+ const origin = event => event.composedPath()[0];
30
+ const describe = target => {
31
+ const element = target instanceof Element ? target : target?.parentElement;
32
+ if (!element) return null;
33
+ read();
34
+ const lab = window.__browserLab;
35
+ const found = lab?.describe(element) ??
36
+ {role: 'none', label: (element.innerText || '').trim().slice(0, 80), element};
37
+ return {...found, region: safeRegion(lab?.region?.(found.element))};
38
+ };
39
+ let timer = null;
40
+ const sendPage = () => {
41
+ if (inFrame) return;
42
+ const state = read();
43
+ if (!state) return;
44
+ // The outline only: where each region is and how much it holds. No text from inside it.
45
+ const regions = state.regions.map(r => ({key: safeRegion(r.key), position: r.position,
46
+ text_chars: r.text_chars, actions: r.actions, offscreen_actions: r.offscreen_actions}));
47
+ window.__browserLabRecord?.({kind: 'page', url: safeUrl(), title: state.title, text: state.text.slice(0, 2000), regions});
48
+ };
49
+ const action = event => {
50
+ send({kind: 'action', ...event});
51
+ clearTimeout(timer);
52
+ timer = setTimeout(sendPage, 400);
53
+ };
54
+ const textField = e => e.matches?.('input:not([type=checkbox],[type=radio],[type=button],[type=submit],[type=reset],[type=image]),textarea,select');
55
+
56
+ addEventListener('focusin', event => {
57
+ if (event.isTrusted && origin(event).type === 'password') everPassword.add(origin(event));
58
+ }, true);
59
+ addEventListener('click', event => {
60
+ if (!event.isTrusted) return;
61
+ const found = describe(origin(event));
62
+ if (!found || textField(found.element) || ['checkbox', 'radio'].includes(found.element.type)) return;
63
+ action({operation: 'click', role: found.role, label: found.label, region: found.region});
64
+ }, true);
65
+ const onChange = event => {
66
+ if (!event.isTrusted) return;
67
+ const found = describe(origin(event)), e = found?.element;
68
+ if (!e) return;
69
+ const base = {role: found.role, label: found.label, region: found.region};
70
+ if (e.type === 'file') send({kind: 'unsupported', reason: 'file_input', ...base});
71
+ else if (['checkbox', 'radio'].includes(e.type)) action({operation: 'toggle', checked: e.checked, ...base});
72
+ else if (secret(e, found.label)) action({operation: 'fill', value: '<redacted>', ...base});
73
+ else if (e.tagName === 'SELECT') {
74
+ action({operation: 'select', value: [...e.selectedOptions].map(o => o.label).join(', '), ...base});
75
+ } else action({operation: 'fill', value: e.value, ...base});
76
+ };
77
+ addEventListener('focusout', event => {
78
+ if (!event.isTrusted || !origin(event).isContentEditable) return;
79
+ const found = describe(origin(event));
80
+ if (found) action({operation: 'fill', role: found.role, label: found.label, region: found.region,
81
+ value: secret(found.element, found.label) ? '<redacted>' : found.element.innerText.slice(0, 500)});
82
+ }, true);
83
+ const onSubmit = event => {
84
+ if (!event.isTrusted) return;
85
+ action({operation: 'submit', role: 'form', label: event.target.getAttribute('aria-label') || event.target.name || ''});
86
+ };
87
+ // change and submit are not composed, so they stop at their shadow root and never reach window.
88
+ // Each open shadow root gets these two listeners; composed events are heard on window only once.
89
+ const listen = root => {
90
+ root.addEventListener('change', onChange, true);
91
+ root.addEventListener('submit', onSubmit, true);
92
+ };
93
+ listen(window);
94
+ const attach = Element.prototype.attachShadow;
95
+ Element.prototype.attachShadow = function (...args) {
96
+ const root = attach.apply(this, args);
97
+ if (root.mode === 'open') listen(root);
98
+ return root;
99
+ };
100
+ // Declarative shadow roots are created by the parser without attachShadow.
101
+ const listenDeclarative = () => {
102
+ const walker = document.createTreeWalker(document, NodeFilter.SHOW_ELEMENT);
103
+ for (let e = walker.nextNode(); e; e = walker.nextNode()) if (e.shadowRoot) listen(e.shadowRoot);
104
+ };
105
+ addEventListener('DOMContentLoaded', listenDeclarative);
106
+ // Enter is the only key ever looked at. Nothing else typed reaches this listener's output.
107
+ addEventListener('keydown', event => {
108
+ if (!event.isTrusted || event.key !== 'Enter') return;
109
+ const found = describe(origin(event));
110
+ if (found) action({operation: 'press_enter', role: found.role, label: found.label, region: found.region});
111
+ }, true);
112
+ addEventListener('load', sendPage);
113
+ })();