@howaboua/pi-browser 0.0.3 → 0.0.4

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +4 -0
  3. package/dist/index.js +2 -2
  4. package/dist/remote-worker.js +978 -136
  5. package/dist/src/browser/bounds.d.ts +1 -1
  6. package/dist/src/browser/bounds.js +6 -3
  7. package/dist/src/browser/help.js +8 -3
  8. package/dist/src/browser/operation-executor.js +15 -1
  9. package/dist/src/browser/operation.d.ts +25 -2
  10. package/dist/src/browser/operation.js +5 -0
  11. package/dist/src/browser/parse-operation.js +61 -2
  12. package/dist/src/browser/remote.d.ts +1 -1
  13. package/dist/src/browser/remote.js +2 -2
  14. package/dist/src/browser/runtime.d.ts +8 -3
  15. package/dist/src/browser/runtime.js +91 -25
  16. package/dist/src/browser/worker-server.js +12 -6
  17. package/dist/src/browser-parameters.d.ts +10 -0
  18. package/dist/src/browser-parameters.js +32 -0
  19. package/dist/src/browser-tool.d.ts +10 -0
  20. package/dist/src/browser-tool.js +2 -1
  21. package/dist/src/cdp/actions/click.d.ts +2 -0
  22. package/dist/src/cdp/actions/click.js +1 -1
  23. package/dist/src/cdp/actions/fill.d.ts +8 -0
  24. package/dist/src/cdp/actions/fill.js +175 -0
  25. package/dist/src/cdp/actions/key.d.ts +20 -0
  26. package/dist/src/cdp/actions/key.js +166 -0
  27. package/dist/src/cdp/actions/wait.d.ts +9 -0
  28. package/dist/src/cdp/actions/wait.js +95 -0
  29. package/dist/src/cdp/pages.d.ts +2 -1
  30. package/dist/src/cdp/pages.js +8 -4
  31. package/dist/src/cdp/session.d.ts +7 -1
  32. package/dist/src/cdp/session.js +79 -27
  33. package/dist/src/cdp/snapshot-contract.d.ts +4 -0
  34. package/dist/src/cdp/snapshot.js +67 -11
  35. package/dist/src/cdp/tabs.d.ts +32 -0
  36. package/dist/src/cdp/tabs.js +226 -0
  37. package/dist/src/cdp/types.d.ts +2 -0
  38. package/index.ts +2 -2
  39. package/package.json +5 -5
  40. package/src/browser/bounds.ts +7 -2
  41. package/src/browser/help.ts +8 -3
  42. package/src/browser/operation-executor.ts +34 -0
  43. package/src/browser/operation.ts +19 -1
  44. package/src/browser/parse-operation.ts +63 -2
  45. package/src/browser/remote.ts +2 -1
  46. package/src/browser/runtime.ts +115 -26
  47. package/src/browser/worker-server.ts +24 -7
  48. package/src/browser-parameters.ts +34 -0
  49. package/src/browser-tool.ts +2 -1
  50. package/src/cdp/actions/click.ts +1 -1
  51. package/src/cdp/actions/fill.ts +246 -0
  52. package/src/cdp/actions/key.ts +202 -0
  53. package/src/cdp/actions/wait.ts +117 -0
  54. package/src/cdp/pages.ts +9 -6
  55. package/src/cdp/session.ts +98 -46
  56. package/src/cdp/snapshot-contract.ts +4 -0
  57. package/src/cdp/snapshot.ts +86 -17
  58. package/src/cdp/tabs.ts +292 -0
  59. package/src/cdp/types.ts +2 -0
@@ -2,28 +2,190 @@
2
2
  // @howaboua/pi-browser managed worker
3
3
 
4
4
  // remote-worker.ts
5
- import { createHash } from "node:crypto";
5
+ import { createHash as createHash2 } from "node:crypto";
6
6
  import { readFileSync as readFileSync3, realpathSync } from "node:fs";
7
7
  import { resolve as resolve2 } from "node:path";
8
8
  import { fileURLToPath as fileURLToPath2 } from "node:url";
9
9
 
10
10
  // src/browser/worker-server.ts
11
11
  import { spawn as spawn3 } from "node:child_process";
12
- import { chmod, lstat, mkdir as mkdir3, rm as rm3 } from "node:fs/promises";
12
+ import { chmod, lstat as lstat2, mkdir as mkdir4, rm as rm4 } from "node:fs/promises";
13
13
  import { createConnection, createServer } from "node:net";
14
14
  import { tmpdir as tmpdir2 } from "node:os";
15
- import { dirname as dirname2, join as join4 } from "node:path";
15
+ import { dirname as dirname2, join as join6 } from "node:path";
16
16
  import { StringDecoder as StringDecoder3 } from "node:string_decoder";
17
17
 
18
+ // src/cdp/actions/key.ts
19
+ var MODIFIERS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
20
+ var ALIASES = {
21
+ Ctrl: "Control",
22
+ Cmd: "Meta",
23
+ Option: "Alt"
24
+ };
25
+ var NAMED_KEYS = {
26
+ Backspace: 8,
27
+ Tab: 9,
28
+ Enter: 13,
29
+ Escape: 27,
30
+ Space: 32,
31
+ PageUp: 33,
32
+ PageDown: 34,
33
+ End: 35,
34
+ Home: 36,
35
+ ArrowLeft: 37,
36
+ ArrowUp: 38,
37
+ ArrowRight: 39,
38
+ ArrowDown: 40,
39
+ Insert: 45,
40
+ Delete: 46
41
+ };
42
+ var PUNCTUATION = {
43
+ "`~": { code: "Backquote", keyCode: 192 },
44
+ "-_": { code: "Minus", keyCode: 189 },
45
+ "=+": { code: "Equal", keyCode: 187 },
46
+ "[{": { code: "BracketLeft", keyCode: 219 },
47
+ "]}": { code: "BracketRight", keyCode: 221 },
48
+ "\\|": { code: "Backslash", keyCode: 220 },
49
+ ";:": { code: "Semicolon", keyCode: 186 },
50
+ "'\"": { code: "Quote", keyCode: 222 },
51
+ ",<": { code: "Comma", keyCode: 188 },
52
+ ".>": { code: "Period", keyCode: 190 },
53
+ "/?": { code: "Slash", keyCode: 191 }
54
+ };
55
+ function keyDefinition(name, shift) {
56
+ const namedCode = Object.hasOwn(NAMED_KEYS, name) ? NAMED_KEYS[name] : undefined;
57
+ if (namedCode !== undefined) {
58
+ return {
59
+ key: name === "Space" ? " " : name,
60
+ code: name,
61
+ windowsVirtualKeyCode: namedCode,
62
+ ...name === "Enter" ? { text: "\r" } : name === "Space" ? { text: " " } : {}
63
+ };
64
+ }
65
+ if (/^F(?:[1-9]|1[0-2])$/.test(name)) {
66
+ return {
67
+ key: name,
68
+ code: name,
69
+ windowsVirtualKeyCode: 111 + Number(name.slice(1))
70
+ };
71
+ }
72
+ const key = name === "Plus" ? "+" : name;
73
+ if ([...key].length !== 1) {
74
+ throw new Error(`Unknown key ${name}; use a character, Enter, Tab, Escape, arrows, or a chord such as Control+a`);
75
+ }
76
+ if (/^[a-z]$/i.test(key)) {
77
+ const text = shift ? key.toUpperCase() : key;
78
+ return {
79
+ key: text,
80
+ code: `Key${key.toUpperCase()}`,
81
+ windowsVirtualKeyCode: key.toUpperCase().charCodeAt(0),
82
+ text
83
+ };
84
+ }
85
+ const digit = "0123456789".indexOf(key);
86
+ const shiftedDigit = ")!@#$%^&*(".indexOf(key);
87
+ if (digit >= 0 || shiftedDigit >= 0) {
88
+ const number = digit >= 0 ? digit : shiftedDigit;
89
+ const text = shift && digit >= 0 ? ")!@#$%^&*(".charAt(number) : key;
90
+ return {
91
+ key: text,
92
+ code: `Digit${number}`,
93
+ windowsVirtualKeyCode: 48 + number,
94
+ text
95
+ };
96
+ }
97
+ for (const [characters, definition] of Object.entries(PUNCTUATION)) {
98
+ if (!characters.includes(key))
99
+ continue;
100
+ const text = shift ? characters.charAt(1) : key;
101
+ return {
102
+ key: text,
103
+ code: definition.code,
104
+ windowsVirtualKeyCode: definition.keyCode,
105
+ text
106
+ };
107
+ }
108
+ return { key, code: "", windowsVirtualKeyCode: 0, text: key };
109
+ }
110
+ function parseKeyChord(chord) {
111
+ const parts = chord === "+" ? ["Plus"] : chord.split("+").map((part) => part.trim());
112
+ const name = parts.pop();
113
+ if (!name)
114
+ throw new Error("Missing key; use Plus for + in a chord");
115
+ const modifiers = [];
116
+ for (const part of parts) {
117
+ const modifier = ALIASES[part] ?? part;
118
+ if (!Object.hasOwn(MODIFIERS, modifier))
119
+ throw new Error(`Unknown modifier ${part}; use Control, Alt, Shift, or Meta`);
120
+ const valid = modifier;
121
+ if (modifiers.includes(valid))
122
+ throw new Error(`Repeated modifier ${part}`);
123
+ modifiers.push(valid);
124
+ }
125
+ return { modifiers, key: keyDefinition(name, modifiers.includes("Shift")) };
126
+ }
127
+ async function pressKey(cdp, sessionId, chord, signal) {
128
+ const { modifiers, key } = parseKeyChord(chord);
129
+ const held = [];
130
+ let mask = 0;
131
+ let failure;
132
+ try {
133
+ for (const modifier of modifiers) {
134
+ signal?.throwIfAborted();
135
+ const bit = MODIFIERS[modifier];
136
+ const keyCode = { Alt: 18, Control: 17, Meta: 91, Shift: 16 }[modifier];
137
+ const modifierKey = {
138
+ key: modifier,
139
+ code: `${modifier}Left`,
140
+ windowsVirtualKeyCode: keyCode
141
+ };
142
+ mask |= bit;
143
+ held.push({ key: modifierKey, bit });
144
+ await cdp.send("Input.dispatchKeyEvent", { ...modifierKey, type: "rawKeyDown", modifiers: mask }, sessionId, signal);
145
+ }
146
+ signal?.throwIfAborted();
147
+ held.push({ key, bit: 0 });
148
+ const { text, ...identity } = key;
149
+ const insertsText = text !== undefined && (mask & ~MODIFIERS.Shift) === 0;
150
+ await cdp.send("Input.dispatchKeyEvent", {
151
+ ...identity,
152
+ type: insertsText ? "keyDown" : "rawKeyDown",
153
+ modifiers: mask,
154
+ ...insertsText ? { text } : {}
155
+ }, sessionId, signal);
156
+ } catch (error) {
157
+ failure = error;
158
+ } finally {
159
+ for (const heldKey of held.reverse()) {
160
+ mask &= ~heldKey.bit;
161
+ const { text: _text, ...identity } = heldKey.key;
162
+ try {
163
+ await cdp.send("Input.dispatchKeyEvent", { ...identity, type: "keyUp", modifiers: mask }, sessionId);
164
+ } catch (error) {
165
+ failure = failure ? new AggregateError([failure, error], "Key press failed; key release also failed") : error;
166
+ }
167
+ }
168
+ }
169
+ if (failure)
170
+ throw failure;
171
+ signal?.throwIfAborted();
172
+ return `Pressed ${chord}`;
173
+ }
174
+
18
175
  // src/browser/operation.ts
19
176
  var BROWSER_ACTIONS = [
20
177
  "help",
21
178
  "start",
22
179
  "tabs",
23
180
  "open",
181
+ "show",
182
+ "close",
24
183
  "find",
25
184
  "click",
26
185
  "type",
186
+ "fill",
187
+ "press",
188
+ "wait",
27
189
  "screenshot",
28
190
  "html",
29
191
  "navigate",
@@ -42,11 +204,16 @@ var fields = (...names) => new Set(["action", ...names]);
42
204
  var ACTION_FIELDS = {
43
205
  help: fields(),
44
206
  start: fields(),
45
- tabs: fields("query", "offset"),
207
+ tabs: fields("query", "offset", "owned_only"),
46
208
  open: fields("ref_id", "url", "lineno", "response_length"),
209
+ show: fields("ref_id"),
210
+ close: fields("ref_id"),
47
211
  find: fields("ref_id", "pattern", "lineno", "response_length"),
48
212
  click: fields("ref_id", "id", "selector", "x", "y"),
49
213
  type: fields("ref_id", "id", "text"),
214
+ fill: fields("ref_id", "id", "selector", "value"),
215
+ press: fields("ref_id", "key"),
216
+ wait: fields("ref_id", "selector", "text", "url_includes", "timeout_ms"),
50
217
  screenshot: fields("ref_id", "id", "selector"),
51
218
  html: fields("ref_id", "id", "selector"),
52
219
  navigate: fields("ref_id", "url"),
@@ -133,10 +300,14 @@ function parseActionRequest(value) {
133
300
  return { action };
134
301
  if (action === "tabs") {
135
302
  const query = optionalString(value["query"], "query");
303
+ const ownedOnly = value["owned_only"];
304
+ if (ownedOnly !== undefined && typeof ownedOnly !== "boolean")
305
+ throw new Error("owned_only must be a boolean");
136
306
  return {
137
307
  action,
138
308
  ...query ? { query } : {},
139
- offset: offset(value["offset"])
309
+ offset: offset(value["offset"]),
310
+ ...ownedOnly === undefined ? {} : { owned_only: ownedOnly }
140
311
  };
141
312
  }
142
313
  if (action === "open") {
@@ -180,7 +351,7 @@ function parseActionRequest(value) {
180
351
  return { action, ...refId2 ? { ref_id: refId2 } : {} };
181
352
  }
182
353
  const refId = requiredRef(value["ref_id"], action);
183
- if (action === "network")
354
+ if (action === "network" || action === "show" || action === "close")
184
355
  return { action, ref_id: refId };
185
356
  if (action === "navigate") {
186
357
  return {
@@ -248,6 +419,53 @@ function parseActionRequest(value) {
248
419
  ...selector ? { selector } : {}
249
420
  };
250
421
  }
422
+ if (action === "fill") {
423
+ const id = elementId(value["id"]);
424
+ const selector = optionalString(value["selector"], "selector");
425
+ if (Number(id !== undefined) + Number(selector !== undefined) !== 1) {
426
+ throw new Error("fill requires exactly one of id or selector");
427
+ }
428
+ const fillValue = value["value"];
429
+ if (typeof fillValue !== "string" && typeof fillValue !== "boolean") {
430
+ throw new Error("value must be text or a boolean for checkbox/radio");
431
+ }
432
+ if (id !== undefined)
433
+ return { action, ref_id: refId, id, value: fillValue };
434
+ if (selector)
435
+ return { action, ref_id: refId, selector, value: fillValue };
436
+ throw new Error("fill requires id or selector");
437
+ }
438
+ if (action === "press") {
439
+ const key = requiredString(value["key"], "key");
440
+ parseKeyChord(key);
441
+ return { action, ref_id: refId, key };
442
+ }
443
+ if (action === "wait") {
444
+ const conditions = ["selector", "text", "url_includes"];
445
+ const provided = conditions.filter((field2) => value[field2] !== undefined);
446
+ const field = provided[0];
447
+ if (provided.length !== 1 || !field) {
448
+ throw new Error("wait requires exactly one of selector, text, or url_includes");
449
+ }
450
+ const match = value[field];
451
+ if (typeof match !== "string" || !match.trim()) {
452
+ throw new Error(`${field} must be a non-empty string`);
453
+ }
454
+ const timeout = value["timeout_ms"] ?? 1e4;
455
+ if (!Number.isInteger(timeout) || Number(timeout) < 1 || Number(timeout) > 60000) {
456
+ throw new Error("timeout_ms must be an integer from 1 to 60000");
457
+ }
458
+ const base = {
459
+ action,
460
+ ref_id: refId,
461
+ timeout_ms: Number(timeout)
462
+ };
463
+ if (field === "selector")
464
+ return { ...base, selector: match };
465
+ if (field === "text")
466
+ return { ...base, text: match };
467
+ return { ...base, url_includes: match };
468
+ }
251
469
  if (action === "load_all") {
252
470
  const interval = value["interval_ms"] ?? 1500;
253
471
  if (!Number.isInteger(interval) || Number(interval) < 0 || Number(interval) > 60000) {
@@ -401,6 +619,30 @@ function loadBrowserRoutes(path, currentHostname = hostname()) {
401
619
  return routesFromConfig(readBrowserRouteConfig(path), currentHostname);
402
620
  }
403
621
 
622
+ // src/browser/runtime.ts
623
+ import { randomUUID } from "node:crypto";
624
+ import { join as join5 } from "node:path";
625
+
626
+ // src/cdp/serial.ts
627
+ function waitForTurn(promise, signal) {
628
+ if (!signal)
629
+ return promise;
630
+ if (signal.aborted) {
631
+ return Promise.reject(signal.reason ?? new Error("Operation aborted"));
632
+ }
633
+ return new Promise((resolveValue, reject) => {
634
+ const abort = () => reject(signal.reason ?? new Error("Operation aborted"));
635
+ signal.addEventListener("abort", abort, { once: true });
636
+ promise.then((value) => {
637
+ signal.removeEventListener("abort", abort);
638
+ resolveValue(value);
639
+ }, (error) => {
640
+ signal.removeEventListener("abort", abort);
641
+ reject(error);
642
+ });
643
+ });
644
+ }
645
+
404
646
  // src/cdp/discovery.ts
405
647
  import { existsSync, readFileSync as readFileSync2 } from "node:fs";
406
648
  import http from "node:http";
@@ -814,6 +1056,11 @@ class CdpClient {
814
1056
  }
815
1057
  }
816
1058
 
1059
+ // src/cdp/tabs.ts
1060
+ import { createHash } from "node:crypto";
1061
+ import { lstat, mkdir, readdir, rm, utimes, writeFile } from "node:fs/promises";
1062
+ import { join as join2 } from "node:path";
1063
+
817
1064
  // src/cdp/pages.ts
818
1065
  function pageInfo(value) {
819
1066
  const record = asRecord(value, "CDP target");
@@ -821,16 +1068,20 @@ function pageInfo(value) {
821
1068
  targetId: asString(record["targetId"], "targetId"),
822
1069
  title: typeof record["title"] === "string" ? record["title"] : "",
823
1070
  url: asString(record["url"], "target URL"),
824
- ...typeof record["type"] === "string" ? { type: record["type"] } : {}
1071
+ ...typeof record["type"] === "string" ? { type: record["type"] } : {},
1072
+ ...typeof record["openerId"] === "string" ? { openerId: record["openerId"] } : {}
825
1073
  };
826
1074
  }
827
- async function getPages(cdp, signal) {
1075
+ async function getPageTargets(cdp, signal) {
828
1076
  const response = asRecord(await cdp.send("Target.getTargets", {}, undefined, signal), "Target.getTargets response");
829
1077
  const targetInfos = response["targetInfos"];
830
1078
  if (!Array.isArray(targetInfos)) {
831
1079
  throw new Error("Target.getTargets response has no targetInfos");
832
1080
  }
833
- return targetInfos.map(pageInfo).filter((target) => target.type === "page" && !target.url.startsWith("chrome://"));
1081
+ return targetInfos.map(pageInfo).filter((target) => target.type === "page");
1082
+ }
1083
+ function getDisplayedPages(targets) {
1084
+ return targets.filter((target) => !target.url.startsWith("chrome://"));
834
1085
  }
835
1086
  async function waitForOpenedTarget(cdp, targetId, requestedUrl, timeout = 5000, signal) {
836
1087
  if (requestedUrl === "about:blank") {
@@ -852,26 +1103,6 @@ async function waitForOpenedTarget(cdp, targetId, requestedUrl, timeout = 5000,
852
1103
  throw new Error(`New tab did not begin navigating to ${requestedUrl}`);
853
1104
  }
854
1105
 
855
- // src/cdp/serial.ts
856
- function waitForTurn(promise, signal) {
857
- if (!signal)
858
- return promise;
859
- if (signal.aborted) {
860
- return Promise.reject(signal.reason ?? new Error("Operation aborted"));
861
- }
862
- return new Promise((resolveValue, reject) => {
863
- const abort = () => reject(signal.reason ?? new Error("Operation aborted"));
864
- signal.addEventListener("abort", abort, { once: true });
865
- promise.then((value) => {
866
- signal.removeEventListener("abort", abort);
867
- resolveValue(value);
868
- }, (error) => {
869
- signal.removeEventListener("abort", abort);
870
- reject(error);
871
- });
872
- });
873
- }
874
-
875
1106
  // src/cdp/url.ts
876
1107
  function assertHttpUrl(value) {
877
1108
  let parsed;
@@ -885,6 +1116,203 @@ function assertHttpUrl(value) {
885
1116
  }
886
1117
  }
887
1118
 
1119
+ // src/cdp/tabs.ts
1120
+ var TARGET_ID = /^[A-Za-z0-9_-]{1,128}$/;
1121
+ var SCOPE_ID = /^[a-f0-9]{64}$/;
1122
+ var SCOPE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
1123
+ var SCOPE_PRUNE_LIMIT = 32;
1124
+ function missing(error) {
1125
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
1126
+ }
1127
+ async function pruneOwnershipScopes(directory, currentScope, now = Date.now()) {
1128
+ let entries;
1129
+ try {
1130
+ entries = await readdir(directory, { withFileTypes: true });
1131
+ } catch (error) {
1132
+ if (missing(error))
1133
+ return;
1134
+ throw error;
1135
+ }
1136
+ const stale = [];
1137
+ for (const entry of entries) {
1138
+ if (entry.name === currentScope || !SCOPE_ID.test(entry.name) || !entry.isDirectory())
1139
+ continue;
1140
+ const path = join2(directory, entry.name);
1141
+ try {
1142
+ const info = await lstat(path);
1143
+ if (info.isDirectory() && !info.isSymbolicLink() && now - info.mtimeMs > SCOPE_TTL_MS) {
1144
+ stale.push({ path, mtimeMs: info.mtimeMs });
1145
+ }
1146
+ } catch (error) {
1147
+ if (!missing(error))
1148
+ throw error;
1149
+ }
1150
+ }
1151
+ stale.sort((left, right) => left.mtimeMs - right.mtimeMs);
1152
+ await Promise.all(stale.slice(0, SCOPE_PRUNE_LIMIT).map((scope) => rm(scope.path, { force: true, recursive: true })));
1153
+ }
1154
+
1155
+ class BrowserTabs {
1156
+ cdp;
1157
+ directory;
1158
+ ownershipDirectory;
1159
+ scope;
1160
+ tail = Promise.resolve();
1161
+ closed = false;
1162
+ prepared = false;
1163
+ constructor(cdp, ownerId, directory, browserUrl) {
1164
+ this.cdp = cdp;
1165
+ this.ownershipDirectory = directory;
1166
+ this.scope = createHash("sha256").update(`${browserUrl}\x00${ownerId}`).digest("hex");
1167
+ this.directory = join2(directory, this.scope);
1168
+ }
1169
+ list(signal) {
1170
+ return this.enqueue(() => this.listNow(signal), signal);
1171
+ }
1172
+ async shutdown() {
1173
+ this.closed = true;
1174
+ await this.tail;
1175
+ }
1176
+ enqueue(action, signal) {
1177
+ const pending = this.tail.then(async () => {
1178
+ signal?.throwIfAborted();
1179
+ if (this.closed)
1180
+ throw new Error("Browser session closed");
1181
+ if (!this.prepared) {
1182
+ await this.touchDirectory();
1183
+ await pruneOwnershipScopes(this.ownershipDirectory, this.scope);
1184
+ this.prepared = true;
1185
+ }
1186
+ return action();
1187
+ });
1188
+ this.tail = pending.then(() => {
1189
+ return;
1190
+ }, () => {
1191
+ return;
1192
+ });
1193
+ return waitForTurn(pending, signal);
1194
+ }
1195
+ async listNow(signal) {
1196
+ const owned = await this.readOwned();
1197
+ const targets = await getPageTargets(this.cdp, signal);
1198
+ const pages = getDisplayedPages(targets);
1199
+ const known = new Set(owned);
1200
+ let changed = true;
1201
+ while (changed) {
1202
+ changed = false;
1203
+ for (const page of pages) {
1204
+ if (!page.openerId || !known.has(page.openerId) || known.has(page.targetId))
1205
+ continue;
1206
+ await this.remember(page.targetId);
1207
+ known.add(page.targetId);
1208
+ changed = true;
1209
+ }
1210
+ }
1211
+ const live = new Set(targets.map((page) => page.targetId));
1212
+ await Promise.all(owned.filter((id) => !live.has(id)).map((id) => this.forget(id)));
1213
+ return pages.map((page) => ({ ...page, owned: known.has(page.targetId) }));
1214
+ }
1215
+ async resolve(refId, signal) {
1216
+ const pages = await this.list(signal);
1217
+ const ids = pages.map((page2) => page2.targetId);
1218
+ const targetId = resolvePrefix(refId, ids, "target", "Run tabs.");
1219
+ const page = pages.find((candidate) => candidate.targetId === targetId);
1220
+ if (!page)
1221
+ throw new Error("Tab disappeared; run tabs again");
1222
+ return { page, refId: targetId.slice(0, getDisplayPrefixLength(ids)) };
1223
+ }
1224
+ async open(url, signal) {
1225
+ assertHttpUrl(url);
1226
+ const targetId = await this.enqueue(async () => {
1227
+ let response;
1228
+ try {
1229
+ response = asRecord(await this.cdp.send("Target.createTarget", { url, background: true }), "Target.createTarget response");
1230
+ } catch (error) {
1231
+ throw new Error(`Chrome did not confirm tab creation; a shared tab may exist. Run tabs before retrying: ${errorMessage(error)}`);
1232
+ }
1233
+ if (typeof response["targetId"] !== "string")
1234
+ throw new Error("Chrome did not return a new tab target; run tabs before retrying");
1235
+ const created = response["targetId"];
1236
+ try {
1237
+ await this.remember(created);
1238
+ } catch (error) {
1239
+ throw new Error(`Opened tab ${created} but could not save ownership; it remains shared: ${errorMessage(error)}`);
1240
+ }
1241
+ return created;
1242
+ }, signal);
1243
+ await waitForOpenedTarget(this.cdp, targetId, url, 5000, signal);
1244
+ const { refId } = await this.resolve(targetId, signal);
1245
+ return { refId };
1246
+ }
1247
+ async show(refId, signal) {
1248
+ const resolved = await this.resolve(refId, signal);
1249
+ await this.cdp.send("Target.activateTarget", { targetId: resolved.page.targetId }, undefined, signal);
1250
+ return resolved.refId;
1251
+ }
1252
+ async close(refId, signal) {
1253
+ const resolved = await this.resolve(refId, signal);
1254
+ const targetId = resolved.page.targetId;
1255
+ const response = asRecord(await this.cdp.send("Target.closeTarget", { targetId }, undefined, signal), "Target.closeTarget response");
1256
+ if (response["success"] !== true)
1257
+ throw new Error("Chrome did not close the tab; run tabs to inspect it");
1258
+ await this.forget(targetId);
1259
+ return { targetId, refId: resolved.refId };
1260
+ }
1261
+ targetPath(targetId) {
1262
+ if (!TARGET_ID.test(targetId))
1263
+ throw new Error("Chrome returned an invalid target id");
1264
+ return join2(this.directory, targetId);
1265
+ }
1266
+ async readOwned() {
1267
+ if (!await this.touchDirectory())
1268
+ return [];
1269
+ try {
1270
+ const files = await readdir(this.directory, { withFileTypes: true });
1271
+ for (const file of files) {
1272
+ if (!file.isFile() || !TARGET_ID.test(file.name))
1273
+ throw new Error("Invalid browser ownership record; refusing to infer tab ownership");
1274
+ }
1275
+ return files.map((file) => file.name);
1276
+ } catch (error) {
1277
+ if (missing(error))
1278
+ return [];
1279
+ throw error;
1280
+ }
1281
+ }
1282
+ async touchDirectory() {
1283
+ try {
1284
+ const info = await lstat(this.directory);
1285
+ if (!info.isDirectory() || info.isSymbolicLink())
1286
+ throw new Error("Invalid browser ownership directory");
1287
+ const now = new Date;
1288
+ await utimes(this.directory, now, now);
1289
+ return true;
1290
+ } catch (error) {
1291
+ if (missing(error))
1292
+ return false;
1293
+ throw error;
1294
+ }
1295
+ }
1296
+ async remember(targetId) {
1297
+ const path = this.targetPath(targetId);
1298
+ await mkdir(this.directory, { recursive: true, mode: 448 });
1299
+ const info = await lstat(this.directory);
1300
+ if (!info.isDirectory() || info.isSymbolicLink())
1301
+ throw new Error("Invalid browser ownership directory");
1302
+ try {
1303
+ await writeFile(path, "", { flag: "wx", mode: 384 });
1304
+ } catch (error) {
1305
+ if (!(error instanceof Error && ("code" in error) && error.code === "EEXIST"))
1306
+ throw error;
1307
+ if (!(await lstat(path)).isFile())
1308
+ throw new Error("Invalid browser ownership record");
1309
+ }
1310
+ }
1311
+ async forget(targetId) {
1312
+ await rm(this.targetPath(targetId), { force: true });
1313
+ }
1314
+ }
1315
+
888
1316
  // src/cdp/session.ts
889
1317
  var TAB_IDLE_MS = 20 * 60 * 1000;
890
1318
 
@@ -896,6 +1324,7 @@ class TabBridge {
896
1324
  tail = Promise.resolve();
897
1325
  idleTimer;
898
1326
  closed = false;
1327
+ backgroundRendering = false;
899
1328
  onClose;
900
1329
  constructor(targetId, cdp, sessionId, onClose) {
901
1330
  this.targetId = targetId;
@@ -953,6 +1382,13 @@ class TabBridge {
953
1382
  release();
954
1383
  }
955
1384
  }
1385
+ async setBackgroundRendering(enabled, signal) {
1386
+ if (this.backgroundRendering === enabled)
1387
+ return;
1388
+ this.backgroundRendering = undefined;
1389
+ await this.cdp.send("Emulation.setFocusEmulationEnabled", { enabled }, this.sessionId, signal);
1390
+ this.backgroundRendering = enabled;
1391
+ }
956
1392
  close(detach = true) {
957
1393
  if (this.closed)
958
1394
  return;
@@ -978,29 +1414,36 @@ class TabBridge {
978
1414
  }
979
1415
 
980
1416
  class BrowserCdpSession {
1417
+ closing;
981
1418
  root;
982
1419
  rootPending;
1420
+ ownerId;
1421
+ ownershipDirectory;
983
1422
  tabs = new Map;
984
1423
  tabPromises = new Map;
1424
+ constructor(ownerId, ownershipDirectory) {
1425
+ this.ownerId = ownerId;
1426
+ this.ownershipDirectory = ownershipDirectory;
1427
+ }
985
1428
  async pages(signal) {
986
- return getPages(await this.rootConnection(signal), signal);
1429
+ return (await this.rootConnection(signal)).tabs.list(signal);
987
1430
  }
988
1431
  async open(url, signal) {
989
- assertHttpUrl(url);
1432
+ return (await this.rootConnection(signal)).tabs.open(url, signal);
1433
+ }
1434
+ async show(refId, signal) {
1435
+ return (await this.rootConnection(signal)).tabs.show(refId, signal);
1436
+ }
1437
+ async closeTab(refId, signal) {
990
1438
  const root = await this.rootConnection(signal);
991
- const response = asRecord(await root.send("Target.createTarget", { url }, undefined, signal), "Target.createTarget response");
992
- if (typeof response["targetId"] !== "string") {
993
- throw new Error("Chrome did not return a new tab target");
994
- }
995
- const page = await waitForOpenedTarget(root, response["targetId"], url, 5000, signal);
996
- const pages = await getPages(root, signal);
997
- if (!pages.some((candidate) => candidate.targetId === page.targetId)) {
998
- pages.push(page);
999
- }
1000
- const prefixLength = getDisplayPrefixLength(pages.map((candidate) => candidate.targetId));
1001
- return {
1002
- refId: page.targetId.slice(0, prefixLength)
1003
- };
1439
+ const resolved = await root.tabs.resolve(refId, signal);
1440
+ const targetId = resolved.page.targetId;
1441
+ this.stopPendingTab(targetId, "Tab is closing");
1442
+ const bridge = this.tabs.get(targetId);
1443
+ const close = () => root.tabs.close(targetId, signal);
1444
+ const closed = bridge ? await bridge.run(resolved.refId, signal, close) : await close();
1445
+ bridge?.close(false);
1446
+ return closed.refId;
1004
1447
  }
1005
1448
  async withTab(refId, signal, action) {
1006
1449
  const pages = await this.pages(signal);
@@ -1036,7 +1479,12 @@ class BrowserCdpSession {
1036
1479
  }
1037
1480
  }
1038
1481
  const prefixLength = getDisplayPrefixLength(pages.map((page) => page.targetId));
1039
- return bridge.run(targetId.slice(0, prefixLength), signal, action);
1482
+ const owned = pages.some((page) => page.targetId === targetId && page.owned === true);
1483
+ const current = bridge;
1484
+ return current.run(targetId.slice(0, prefixLength), signal, async (tab) => {
1485
+ await current.setBackgroundRendering(owned, signal);
1486
+ return action(tab);
1487
+ });
1040
1488
  }
1041
1489
  async stop(refId) {
1042
1490
  if (!refId) {
@@ -1055,6 +1503,8 @@ class BrowserCdpSession {
1055
1503
  this.tabs.delete(targetId);
1056
1504
  }
1057
1505
  close() {
1506
+ if (this.closing)
1507
+ return this.closing;
1058
1508
  for (const targetId of this.tabPromises.keys()) {
1059
1509
  this.stopPendingTab(targetId, "Browser session closed");
1060
1510
  }
@@ -1063,16 +1513,28 @@ class BrowserCdpSession {
1063
1513
  this.tabs.clear();
1064
1514
  const rootPending = this.rootPending;
1065
1515
  this.rootPending = undefined;
1066
- if (rootPending) {
1067
- rootPending.controller.abort(new Error("Browser session closed"));
1068
- rootPending.promise.then((client) => client.close(), () => {
1516
+ rootPending?.controller.abort(new Error("Browser session closed"));
1517
+ const root = this.root;
1518
+ this.root = undefined;
1519
+ this.closing = (async () => {
1520
+ const connected = await rootPending?.promise.catch(() => {
1069
1521
  return;
1070
1522
  });
1071
- }
1072
- this.root?.close();
1073
- this.root = undefined;
1523
+ for (const connection of new Set([root, connected])) {
1524
+ if (!connection)
1525
+ continue;
1526
+ try {
1527
+ await connection.tabs.shutdown();
1528
+ } finally {
1529
+ connection.cdp.close();
1530
+ }
1531
+ }
1532
+ })();
1533
+ return this.closing;
1074
1534
  }
1075
1535
  async rootConnection(signal) {
1536
+ if (this.closing)
1537
+ throw new Error("Browser session closed");
1076
1538
  if (this.root)
1077
1539
  return this.root;
1078
1540
  let pending = this.rootPending;
@@ -1117,50 +1579,63 @@ class BrowserCdpSession {
1117
1579
  }
1118
1580
  async connectRoot(signal) {
1119
1581
  const client = new CdpClient;
1120
- await client.connect(await getWebSocketUrl(), signal);
1121
- this.root = client;
1582
+ const url = await getWebSocketUrl();
1583
+ try {
1584
+ await client.connect(url, signal);
1585
+ signal.throwIfAborted();
1586
+ if (this.closing)
1587
+ throw new Error("Browser session closed");
1588
+ } catch (error) {
1589
+ client.close();
1590
+ throw error;
1591
+ }
1592
+ const connection = {
1593
+ cdp: client,
1594
+ tabs: new BrowserTabs(client, this.ownerId, this.ownershipDirectory, url)
1595
+ };
1596
+ this.root = connection;
1122
1597
  client.onClose(() => {
1123
- if (this.root !== client)
1598
+ if (this.root !== connection)
1124
1599
  return;
1125
1600
  this.root = undefined;
1126
1601
  });
1127
- return client;
1602
+ return connection;
1128
1603
  }
1129
1604
  }
1130
1605
 
1131
1606
  // src/browser/artifacts.ts
1132
1607
  import {
1133
- mkdir,
1134
- readdir,
1608
+ mkdir as mkdir2,
1609
+ readdir as readdir2,
1135
1610
  readFile,
1136
- rm,
1611
+ rm as rm2,
1137
1612
  stat,
1138
- writeFile
1613
+ writeFile as writeFile2
1139
1614
  } from "node:fs/promises";
1140
1615
  import { tmpdir } from "node:os";
1141
- import { join as join2 } from "node:path";
1616
+ import { join as join3 } from "node:path";
1142
1617
  var RESULT_TTL_MS = 60 * 60 * 1000;
1143
1618
  var SCREENSHOT_TTL_MS = 24 * 60 * 60 * 1000;
1144
1619
  var TEXT_BUDGET_BYTES = 32000;
1145
1620
  function artifactDirectory() {
1146
- return process.env["XDG_RUNTIME_DIR"] ? join2(process.env["XDG_RUNTIME_DIR"], "browser-tool") : join2(tmpdir(), `browser-tool-${process.getuid?.() ?? "user"}`);
1621
+ return process.env["XDG_RUNTIME_DIR"] ? join3(process.env["XDG_RUNTIME_DIR"], "browser-tool") : join3(tmpdir(), `browser-tool-${process.getuid?.() ?? "user"}`);
1147
1622
  }
1148
1623
  function resultPath(handle) {
1149
- return join2(artifactDirectory(), `result-${handle}.txt`);
1624
+ return join3(artifactDirectory(), `result-${handle}.txt`);
1150
1625
  }
1151
1626
  async function screenshotPath(request) {
1152
- await mkdir(artifactDirectory(), {
1627
+ await mkdir2(artifactDirectory(), {
1153
1628
  recursive: true,
1154
1629
  mode: 448
1155
1630
  });
1156
1631
  const suffix = request.id !== undefined ? `-element-${request.id}` : request.selector ? "-element" : "";
1157
1632
  const safeRef = request.ref_id.slice(0, 12).replace(/[^A-Za-z0-9_-]/g, "_");
1158
- return join2(artifactDirectory(), `browser-${safeRef}${suffix}-${crypto.randomUUID()}.png`);
1633
+ return join3(artifactDirectory(), `browser-${safeRef}${suffix}-${crypto.randomUUID()}.png`);
1159
1634
  }
1160
1635
  async function pruneArtifacts(now = Date.now()) {
1161
1636
  let names;
1162
1637
  try {
1163
- names = await readdir(artifactDirectory());
1638
+ names = await readdir2(artifactDirectory());
1164
1639
  } catch (error) {
1165
1640
  if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
1166
1641
  return 0;
@@ -1169,11 +1644,11 @@ async function pruneArtifacts(now = Date.now()) {
1169
1644
  }
1170
1645
  let removed = 0;
1171
1646
  for (const name of names.filter((candidate) => /^(?:result-[a-f0-9-]{36}\.txt|browser-.*\.png)$/.test(candidate))) {
1172
- const path = join2(artifactDirectory(), name);
1647
+ const path = join3(artifactDirectory(), name);
1173
1648
  try {
1174
1649
  const maxAge = name.startsWith("result-") ? RESULT_TTL_MS : SCREENSHOT_TTL_MS;
1175
1650
  if (now - (await stat(path)).mtimeMs > maxAge) {
1176
- await rm(path, { force: true });
1651
+ await rm2(path, { force: true });
1177
1652
  removed++;
1178
1653
  }
1179
1654
  } catch (error) {
@@ -1198,11 +1673,11 @@ function chunkForJson(value, offset2 = 0, budget = TEXT_BUDGET_BYTES) {
1198
1673
  }
1199
1674
  async function cacheResult(value) {
1200
1675
  const handle = crypto.randomUUID();
1201
- await mkdir(artifactDirectory(), {
1676
+ await mkdir2(artifactDirectory(), {
1202
1677
  recursive: true,
1203
1678
  mode: 448
1204
1679
  });
1205
- await writeFile(resultPath(handle), value, { mode: 384 });
1680
+ await writeFile2(resultPath(handle), value, { mode: 384 });
1206
1681
  return handle;
1207
1682
  }
1208
1683
  async function limitedText(base, field, value) {
@@ -1235,7 +1710,7 @@ async function readCachedResult(request) {
1235
1710
  const chunk = chunkForJson(value, request.offset);
1236
1711
  const complete = chunk.end >= value.length;
1237
1712
  if (complete) {
1238
- await rm(resultPath(request.handle), { force: true });
1713
+ await rm2(resultPath(request.handle), { force: true });
1239
1714
  }
1240
1715
  return {
1241
1716
  handle: request.handle,
@@ -1246,7 +1721,7 @@ async function readCachedResult(request) {
1246
1721
  };
1247
1722
  }
1248
1723
  async function discardCachedResult(handle) {
1249
- await rm(resultPath(handle), { force: true });
1724
+ await rm2(resultPath(handle), { force: true });
1250
1725
  return { discarded: handle };
1251
1726
  }
1252
1727
 
@@ -1262,11 +1737,16 @@ function browserHelp(hosts = []) {
1262
1737
  safety: "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
1263
1738
  batch: "top-level nonempty action arrays; items omit action/host/response_length; independent only",
1264
1739
  actions: {
1265
- tabs: "query? offset? -> ref_id title url",
1266
- open: "ref_id lineno? response_length? | url",
1740
+ tabs: "query? offset? owned_only? -> ref_id title url owned",
1741
+ open: "ref_id lineno? response_length? | url; new tabs open in background",
1742
+ show: "ref_id; bring tab to foreground",
1743
+ close: "ref_id",
1267
1744
  find: "ref_id pattern lineno? response_length?",
1268
1745
  click: "ref_id id|selector|x+y",
1269
1746
  type: "ref_id text id?; id focuses",
1747
+ fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
1748
+ press: "ref_id key; focused element, e.g. Enter or Control+a",
1749
+ wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring, default 10000ms",
1270
1750
  screenshot: "ref_id id?|selector? -> file",
1271
1751
  navigate: "ref_id url",
1272
1752
  html: "ref_id id?|selector?",
@@ -1275,7 +1755,7 @@ function browserHelp(hosts = []) {
1275
1755
  load_all: "ref_id selector interval_ms?",
1276
1756
  raw: "ref_id method params?",
1277
1757
  start: "",
1278
- stop: "ref_id?",
1758
+ stop: "ref_id?; detach without closing tabs",
1279
1759
  read_result: "handle offset",
1280
1760
  discard_result: "handle"
1281
1761
  },
@@ -1519,6 +1999,156 @@ async function clickCoordinates(cdp, sessionId, x, y, signal) {
1519
1999
  return `Clicked at CSS (${x}, ${y})`;
1520
2000
  }
1521
2001
 
2002
+ // src/cdp/actions/fill.ts
2003
+ function prepareFill(value) {
2004
+ if (!this.isConnected)
2005
+ throw new Error("Element detached; run open again");
2006
+ if (this.matches(":disabled") || this.getAttribute("aria-disabled") === "true" || this.closest("[inert]")) {
2007
+ throw new Error("Element is disabled or inert");
2008
+ }
2009
+ const input = this instanceof HTMLInputElement;
2010
+ const textarea = this instanceof HTMLTextAreaElement;
2011
+ const select = this instanceof HTMLSelectElement;
2012
+ if ((input || textarea) && this.readOnly)
2013
+ throw new Error("Element is read-only");
2014
+ const toggle = input && (this.type === "checkbox" || this.type === "radio");
2015
+ if (toggle) {
2016
+ if (typeof value !== "boolean")
2017
+ throw new Error("Checkbox/radio requires a boolean value");
2018
+ if (this.type === "radio" && !value && this.checked) {
2019
+ throw new Error("Select another radio option with value true instead of unchecking this one");
2020
+ }
2021
+ const indeterminate = this.type === "checkbox" && this.indeterminate;
2022
+ if (indeterminate && this.checked === value) {
2023
+ const setter2 = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "checked")?.set;
2024
+ if (!setter2)
2025
+ throw new Error("Checkbox has no native checked setter");
2026
+ setter2.call(this, !value);
2027
+ }
2028
+ return {
2029
+ kind: "checked",
2030
+ expected: value,
2031
+ needsClick: this.checked !== value || indeterminate
2032
+ };
2033
+ }
2034
+ if (typeof value !== "string")
2035
+ throw new Error("Text fields and selects require a string value");
2036
+ if (input && ![
2037
+ "text",
2038
+ "search",
2039
+ "email",
2040
+ "url",
2041
+ "tel",
2042
+ "password",
2043
+ "number",
2044
+ "date",
2045
+ "time",
2046
+ "datetime-local",
2047
+ "month",
2048
+ "week"
2049
+ ].includes(this.type)) {
2050
+ throw new Error(`Input type ${this.type} does not support fill`);
2051
+ }
2052
+ if (!input && !textarea && !select && !this.isContentEditable) {
2053
+ throw new Error("Element is not an editable form control");
2054
+ }
2055
+ let replacement = value;
2056
+ if (select) {
2057
+ if (this.multiple)
2058
+ throw new Error("fill requires a single-select control");
2059
+ const options = Array.from(this.options);
2060
+ const byValue = options.filter((option2) => option2.value === value);
2061
+ const matches = byValue.length ? byValue : options.filter((option2) => option2.label.trim() === value);
2062
+ const option = matches[0];
2063
+ if (matches.length !== 1 || !option)
2064
+ throw new Error("Option value/label must match exactly one option");
2065
+ if (option.matches(":disabled"))
2066
+ throw new Error("Option is disabled");
2067
+ replacement = option.value;
2068
+ }
2069
+ this.focus({ preventScroll: true });
2070
+ const root = this.getRootNode();
2071
+ if (!this.isConnected || root.activeElement !== this) {
2072
+ throw new Error("Could not focus element; fill was not sent");
2073
+ }
2074
+ if (!input && !textarea && !select) {
2075
+ const selection = this.ownerDocument.getSelection();
2076
+ if (!selection)
2077
+ throw new Error("Could not select editable text");
2078
+ const range = this.ownerDocument.createRange();
2079
+ range.selectNodeContents(this);
2080
+ selection.removeAllRanges();
2081
+ selection.addRange(range);
2082
+ return { kind: "contenteditable", expected: value };
2083
+ }
2084
+ const prototype = input ? HTMLInputElement.prototype : textarea ? HTMLTextAreaElement.prototype : HTMLSelectElement.prototype;
2085
+ const setter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
2086
+ if (!setter)
2087
+ throw new Error("Form control has no native value setter");
2088
+ if (input || textarea) {
2089
+ const probe = this.cloneNode(false);
2090
+ setter.call(probe, replacement);
2091
+ if (probe.value !== replacement)
2092
+ throw new Error("Value is not accepted by this control; fill was not sent");
2093
+ }
2094
+ setter.call(this, replacement);
2095
+ this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
2096
+ this.dispatchEvent(new Event("change", { bubbles: true }));
2097
+ return { kind: "value", expected: replacement };
2098
+ }
2099
+ async function callElement(cdp, sessionId, objectId, declaration, value, signal) {
2100
+ const response = asRecord(await cdp.send("Runtime.callFunctionOn", {
2101
+ objectId,
2102
+ functionDeclaration: declaration,
2103
+ arguments: [{ value }],
2104
+ returnByValue: true
2105
+ }, sessionId, signal));
2106
+ if (response["exceptionDetails"]) {
2107
+ const details = asRecord(response["exceptionDetails"]);
2108
+ const exception = details["exception"] ? asRecord(details["exception"]) : {};
2109
+ throw new Error(typeof exception["description"] === "string" ? exception["description"] : "Fill failed; run open to inspect the control before retrying");
2110
+ }
2111
+ return asRecord(asRecord(response["result"])["value"], "fill result");
2112
+ }
2113
+ async function fillElement(cdp, sessionId, elementRefs, target, value, signal) {
2114
+ const backendNodeId = target.id !== undefined ? requireElementRef(elementRefs, target.id).backendNodeId : await selectorBackendNode(cdp, sessionId, target.selector, signal);
2115
+ await backendCenter(cdp, sessionId, backendNodeId, true, signal);
2116
+ return withBackendObject(cdp, sessionId, backendNodeId, async (objectId) => {
2117
+ const prepared = await callElement(cdp, sessionId, objectId, prepareFill.toString(), value, signal);
2118
+ if (prepared["kind"] === "checked" && prepared["needsClick"] === true) {
2119
+ await clickBackendNode(cdp, sessionId, backendNodeId, signal);
2120
+ } else if (prepared["kind"] === "contenteditable") {
2121
+ const focused = await callElement(cdp, sessionId, objectId, `function() {
2122
+ const selection = this.ownerDocument.getSelection();
2123
+ return { ok: this.isConnected && this.getRootNode().activeElement === this &&
2124
+ selection && this.contains(selection.anchorNode) && this.contains(selection.focusNode) };
2125
+ }`, null, signal);
2126
+ if (focused["ok"] !== true)
2127
+ throw new Error("Focus or selection changed; fill was not sent");
2128
+ if (value === "")
2129
+ await pressKey(cdp, sessionId, "Backspace", signal);
2130
+ else
2131
+ await cdp.send("Input.insertText", { text: value }, sessionId, signal);
2132
+ }
2133
+ const verified = await callElement(cdp, sessionId, objectId, `function(expected) {
2134
+ if (!this.isConnected) return { ok: false };
2135
+ const toggle = this instanceof HTMLInputElement && (this.type === 'checkbox' || this.type === 'radio');
2136
+ // Editable DOM has no value property. Native editing introduces NBSPs
2137
+ // and block/BR nodes, so compare equivalent rendered text, not markup.
2138
+ if (this.isContentEditable) {
2139
+ const normalize = text => text.replace(/\\s+/g, ' ').trim();
2140
+ return { ok: normalize(this.innerText) === normalize(expected) };
2141
+ }
2142
+ const actual = toggle ? this.checked : this.value;
2143
+ return { ok: actual === expected && (!toggle || !this.indeterminate) };
2144
+ }`, prepared["expected"], signal);
2145
+ if (verified["ok"] !== true) {
2146
+ throw new Error("Fill did not retain the requested value; run open to inspect the control before retrying");
2147
+ }
2148
+ return target.id === undefined ? "Filled selected element" : `Filled element ${target.id}`;
2149
+ }, signal);
2150
+ }
2151
+
1522
2152
  // src/cdp/evaluate.ts
1523
2153
  async function evaluate(cdp, sessionId, expression, signal) {
1524
2154
  await cdp.send("Runtime.enable", {}, sessionId, signal);
@@ -1879,6 +2509,94 @@ async function typeRef(cdp, sessionId, elementRefs, id, text, signal) {
1879
2509
  }, signal);
1880
2510
  }
1881
2511
 
2512
+ // src/cdp/actions/wait.ts
2513
+ var POLL_INTERVAL_MS = 100;
2514
+ var SUMMARY_LENGTH = 120;
2515
+ var NAVIGATION_CONTEXT_ERRORS = [
2516
+ /(?:^|: )Execution context was destroyed\b/i,
2517
+ /(?:^|: )Cannot find context with specified id\b/i,
2518
+ /(?:^|: )Cannot find (?:default )?execution context\b/i,
2519
+ /(?:^|: )No execution context with given id\b/i
2520
+ ];
2521
+ function conditionDetails(condition) {
2522
+ if ("selector" in condition) {
2523
+ return {
2524
+ expression: `document.querySelector(${JSON.stringify(condition.selector)}) !== null`,
2525
+ label: `selector ${summary(condition.selector)}`,
2526
+ matched: `Matched selector ${summary(condition.selector)}`
2527
+ };
2528
+ }
2529
+ if ("text" in condition) {
2530
+ return {
2531
+ expression: `document.body?.innerText.includes(${JSON.stringify(condition.text)}) ?? false`,
2532
+ label: `text ${summary(condition.text)}`,
2533
+ matched: `Matched text ${summary(condition.text)}`
2534
+ };
2535
+ }
2536
+ return {
2537
+ expression: `location.href.includes(${JSON.stringify(condition.url_includes)})`,
2538
+ label: `URL containing ${summary(condition.url_includes)}`,
2539
+ matched: `Matched URL containing ${summary(condition.url_includes)}`
2540
+ };
2541
+ }
2542
+ function summary(value) {
2543
+ const normalized = value.replace(/\s+/g, " ").trim();
2544
+ const bounded = normalized.length > SUMMARY_LENGTH ? `${normalized.slice(0, SUMMARY_LENGTH - 3)}...` : normalized;
2545
+ return JSON.stringify(bounded);
2546
+ }
2547
+ function isNavigationContextError(error) {
2548
+ const message = errorMessage(error);
2549
+ return NAVIGATION_CONTEXT_ERRORS.some((pattern) => pattern.test(message));
2550
+ }
2551
+ async function waitForCondition(cdp, sessionId, condition, timeoutMs, signal) {
2552
+ const details = conditionDetails(condition);
2553
+ const timeoutError2 = new Error(`Timed out after ${timeoutMs}ms waiting for ${details.label}`);
2554
+ const deadline = Date.now() + timeoutMs;
2555
+ const controller = new AbortController;
2556
+ let timedOut = false;
2557
+ const abort = () => {
2558
+ controller.abort(signal?.reason ?? new Error("Wait aborted"));
2559
+ };
2560
+ if (signal?.aborted) {
2561
+ abort();
2562
+ } else {
2563
+ signal?.addEventListener("abort", abort, { once: true });
2564
+ }
2565
+ const timer = setTimeout(() => {
2566
+ timedOut = true;
2567
+ controller.abort(timeoutError2);
2568
+ }, timeoutMs);
2569
+ try {
2570
+ while (Date.now() < deadline) {
2571
+ try {
2572
+ const matched = await evaluate(cdp, sessionId, details.expression, controller.signal);
2573
+ if (matched === true)
2574
+ return details.matched;
2575
+ if (matched !== false) {
2576
+ throw new Error("Wait condition returned a non-boolean result");
2577
+ }
2578
+ } catch (error) {
2579
+ if (controller.signal.aborted)
2580
+ throw controller.signal.reason;
2581
+ if (!isNavigationContextError(error))
2582
+ throw error;
2583
+ }
2584
+ const remaining = deadline - Date.now();
2585
+ if (remaining <= 0)
2586
+ break;
2587
+ await sleep(Math.min(POLL_INTERVAL_MS, remaining), controller.signal);
2588
+ }
2589
+ throw timeoutError2;
2590
+ } catch (error) {
2591
+ if (timedOut)
2592
+ throw timeoutError2;
2593
+ throw error;
2594
+ } finally {
2595
+ clearTimeout(timer);
2596
+ signal?.removeEventListener("abort", abort);
2597
+ }
2598
+ }
2599
+
1882
2600
  // src/cdp/snapshot.ts
1883
2601
  var INTERACTIVE_ROLES = new Set([
1884
2602
  "button",
@@ -1900,6 +2618,16 @@ var INTERACTIVE_ROLES = new Set([
1900
2618
  "treeitem"
1901
2619
  ]);
1902
2620
  var NEXT_ELEMENT_IDS = new WeakMap;
2621
+ function axProperty(value) {
2622
+ const record = asRecord(value, "accessibility property");
2623
+ if (typeof record["name"] !== "string") {
2624
+ throw new Error("Accessibility property has no name");
2625
+ }
2626
+ return {
2627
+ name: record["name"],
2628
+ ...record["value"] ? { value: asRecord(record["value"]) } : {}
2629
+ };
2630
+ }
1903
2631
  function axNode(value) {
1904
2632
  const record = asRecord(value, "accessibility node");
1905
2633
  if (typeof record["nodeId"] !== "string") {
@@ -1915,7 +2643,8 @@ function axNode(value) {
1915
2643
  ...typeof record["ignored"] === "boolean" ? { ignored: record["ignored"] } : {},
1916
2644
  ...record["role"] ? { role: asRecord(record["role"]) } : {},
1917
2645
  ...record["name"] ? { name: asRecord(record["name"]) } : {},
1918
- ...record["value"] ? { value: asRecord(record["value"]) } : {}
2646
+ ...record["value"] ? { value: asRecord(record["value"]) } : {},
2647
+ ...Array.isArray(record["properties"]) ? { properties: record["properties"].map(axProperty) } : {}
1919
2648
  };
1920
2649
  }
1921
2650
  function shouldShow(node) {
@@ -1924,6 +2653,8 @@ function shouldShow(node) {
1924
2653
  const value = node.value?.value;
1925
2654
  if (role === "InlineTextBox")
1926
2655
  return false;
2656
+ if (INTERACTIVE_ROLES.has(role))
2657
+ return true;
1927
2658
  return role !== "none" && role !== "generic" && !(name === "" && (value === "" || value == null));
1928
2659
  }
1929
2660
  function orderedChildren(node, nodesById, childrenByParent) {
@@ -1957,6 +2688,32 @@ function splitText(value, max = 700) {
1957
2688
  }
1958
2689
  return parts;
1959
2690
  }
2691
+ function interactiveState(node) {
2692
+ const values = new Map((node.properties ?? []).map((property) => [
2693
+ property.name,
2694
+ property.value?.value
2695
+ ]));
2696
+ const checkedValue = values.get("checked");
2697
+ const checked = checkedValue === "true" ? true : checkedValue === "false" ? false : typeof checkedValue === "boolean" || checkedValue === "mixed" ? checkedValue : undefined;
2698
+ const selected = values.get("selected");
2699
+ const expanded = values.get("expanded");
2700
+ const disabled = values.get("disabled");
2701
+ return {
2702
+ ...checked === undefined ? {} : { checked },
2703
+ ...typeof selected === "boolean" ? { selected } : {},
2704
+ ...typeof expanded === "boolean" ? { expanded } : {},
2705
+ ...typeof disabled === "boolean" ? { disabled } : {}
2706
+ };
2707
+ }
2708
+ function interactiveText(role, name, value, state) {
2709
+ const states = [
2710
+ state.checked === undefined ? undefined : `checked=${state.checked}`,
2711
+ state.selected === undefined ? undefined : `selected=${state.selected}`,
2712
+ state.expanded === undefined ? undefined : `expanded=${state.expanded}`,
2713
+ state.disabled === undefined ? undefined : `disabled=${state.disabled}`
2714
+ ].filter((entry) => entry !== undefined);
2715
+ return `${role}${name ? ` ${name}` : ""}${value === "" || value == null ? "" : ` = ${JSON.stringify(value)}`}${states.length > 0 ? ` [${states.join(", ")}]` : ""}`;
2716
+ }
1960
2717
  async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
1961
2718
  const lineno = positiveInteger(options.lineno ?? 1, "line cursor");
1962
2719
  const responseLength2 = snapshotResponseLength(options.responseLength);
@@ -2016,17 +2773,25 @@ async function snapshotData(cdp, sessionId, elementRefs, options = {}) {
2016
2773
  const value = node.value?.value;
2017
2774
  let renderedName = parentName;
2018
2775
  if (!node.ignored && shouldShow(node)) {
2019
- if (INTERACTIVE_ROLES.has(role) && node.backendDOMNodeId) {
2020
- const element = {
2021
- id: nextElementId(),
2022
- role,
2023
- ...name ? { name } : {},
2024
- ...value === "" || value == null ? {} : { value }
2025
- };
2026
- elementRefs.set(element.id, node.backendDOMNodeId);
2027
- elements.push(element);
2028
- addLine(`[${element.id}] ${role}${name ? ` ${name}` : ""}${value === "" || value == null ? "" : ` = ${JSON.stringify(value)}`}`, element, "interactive");
2029
- renderedName = name;
2776
+ if (INTERACTIVE_ROLES.has(role)) {
2777
+ const state = interactiveState(node);
2778
+ const text = interactiveText(role, name, value, state);
2779
+ if (!node.backendDOMNodeId) {
2780
+ addLine(text, undefined, "interactive");
2781
+ renderedName = name;
2782
+ } else {
2783
+ const element = {
2784
+ id: nextElementId(),
2785
+ role,
2786
+ ...name ? { name } : {},
2787
+ ...value === "" || value == null ? {} : { value },
2788
+ ...state
2789
+ };
2790
+ elementRefs.set(element.id, node.backendDOMNodeId);
2791
+ elements.push(element);
2792
+ addLine(`[${element.id}] ${text}`, element, "interactive");
2793
+ renderedName = name;
2794
+ }
2030
2795
  } else if (role === "StaticText") {
2031
2796
  if (name && name !== parentName)
2032
2797
  addStaticText(name);
@@ -2098,12 +2863,12 @@ function boundedElement(element) {
2098
2863
  ...value === undefined ? {} : { value }
2099
2864
  };
2100
2865
  }
2101
- function boundTabs(pages, query, offset2) {
2866
+ function boundTabs(pages, query, offset2, ownedOnly = false) {
2102
2867
  const prefixLength = getDisplayPrefixLength(pages.map((page) => page.targetId));
2103
- let filtered = pages;
2868
+ let filtered = ownedOnly ? pages.filter((page) => page.owned === true) : pages;
2104
2869
  if (query) {
2105
2870
  const normalized = query.toLowerCase();
2106
- filtered = pages.filter((page) => `${page.title}
2871
+ filtered = filtered.filter((page) => `${page.title}
2107
2872
  ${page.url}`.toLowerCase().includes(normalized));
2108
2873
  }
2109
2874
  if (offset2 > filtered.length) {
@@ -2114,7 +2879,8 @@ ${page.url}`.toLowerCase().includes(normalized));
2114
2879
  const compact = {
2115
2880
  ref_id: page.targetId.slice(0, prefixLength),
2116
2881
  title: page.title.slice(0, 500),
2117
- url: page.url.slice(0, 8000)
2882
+ url: page.url.slice(0, 8000),
2883
+ owned: page.owned === true
2118
2884
  };
2119
2885
  if (byteLength({ tabs: [...tabs, compact] }) > OUTPUT_BUDGET_BYTES) {
2120
2886
  break;
@@ -2350,13 +3116,14 @@ class BrowserOperationExecutor {
2350
3116
  case "start":
2351
3117
  return { result: await startBrowser(signal) };
2352
3118
  case "tabs":
2353
- return boundTabs(await this.cdp.pages(signal), operation.query, operation.offset);
3119
+ return boundTabs(await this.cdp.pages(signal), operation.query, operation.offset, operation.owned_only);
2354
3120
  case "open":
2355
3121
  if ("url" in operation) {
2356
3122
  const opened = await this.cdp.open(operation.url, signal);
2357
3123
  return {
2358
3124
  ref_id: opened.refId,
2359
- url: operation.url
3125
+ url: operation.url,
3126
+ owned: true
2360
3127
  };
2361
3128
  }
2362
3129
  return this.cdp.withTab(operation.ref_id, signal, async (tab) => boundSnapshot(await snapshotData(tab.cdp, tab.sessionId, tab.elementRefs, {
@@ -2373,6 +3140,10 @@ class BrowserOperationExecutor {
2373
3140
  responseLength: operation.response_length,
2374
3141
  signal
2375
3142
  })));
3143
+ case "show":
3144
+ return { shown: await this.cdp.show(operation.ref_id, signal) };
3145
+ case "close":
3146
+ return { closed: await this.cdp.closeTab(operation.ref_id, signal) };
2376
3147
  case "read_result":
2377
3148
  return readCachedResult(operation);
2378
3149
  case "discard_result":
@@ -2411,6 +3182,12 @@ class BrowserOperationExecutor {
2411
3182
  return this.tabResult(operation.ref_id, signal, (tab) => operation.id === undefined ? typeAtFocus(tab.cdp, tab.sessionId, operation.text, signal) : typeRef(tab.cdp, tab.sessionId, tab.elementRefs, operation.id, operation.text, signal));
2412
3183
  case "load_all":
2413
3184
  return this.tabResult(operation.ref_id, signal, (tab) => loadAll(tab.cdp, tab.sessionId, operation.selector, operation.interval_ms, signal));
3185
+ case "fill":
3186
+ return this.tabResult(operation.ref_id, signal, (tab) => fillElement(tab.cdp, tab.sessionId, tab.elementRefs, operation, operation.value, signal));
3187
+ case "press":
3188
+ return this.tabResult(operation.ref_id, signal, (tab) => pressKey(tab.cdp, tab.sessionId, operation.key, signal));
3189
+ case "wait":
3190
+ return this.tabResult(operation.ref_id, signal, (tab) => waitForCondition(tab.cdp, tab.sessionId, operation, operation.timeout_ms, signal));
2414
3191
  }
2415
3192
  }
2416
3193
  async screenshot(operation, signal) {
@@ -2436,8 +3213,8 @@ class BrowserOperationExecutor {
2436
3213
  }
2437
3214
 
2438
3215
  // src/browser/remote.ts
2439
- import { mkdir as mkdir2, rm as rm2 } from "node:fs/promises";
2440
- import { basename as basename2, join as join3 } from "node:path";
3216
+ import { mkdir as mkdir3, rm as rm3 } from "node:fs/promises";
3217
+ import { basename as basename2, join as join4 } from "node:path";
2441
3218
 
2442
3219
  // src/browser/remote-helper.ts
2443
3220
  import { readFile as readFile2 } from "node:fs/promises";
@@ -2639,8 +3416,8 @@ async function copyRemoteArtifact(host, remoteFile, signal) {
2639
3416
  if (!SAFE_REMOTE_FILE.test(remoteFile)) {
2640
3417
  throw new Error(`remote browser returned an unsafe artifact path: ${remoteFile}`);
2641
3418
  }
2642
- await mkdir2(artifactDirectory(), { recursive: true, mode: 448 });
2643
- const localFile = join3(artifactDirectory(), `${host}-${basename2(remoteFile)}`);
3419
+ await mkdir3(artifactDirectory(), { recursive: true, mode: 448 });
3420
+ const localFile = join4(artifactDirectory(), `${host}-${basename2(remoteFile)}`);
2644
3421
  const copied = await runProgram("scp", ["-q", `${host}:${remoteFile}`, localFile], undefined, signal);
2645
3422
  if (copied.code !== 0) {
2646
3423
  throw new Error(copied.stderr || copied.stdout || "could not copy remote screenshot");
@@ -2652,7 +3429,7 @@ async function copyRemoteArtifact(host, remoteFile, signal) {
2652
3429
  }
2653
3430
  return localFile;
2654
3431
  } catch (error) {
2655
- await rm2(localFile, { force: true });
3432
+ await rm3(localFile, { force: true });
2656
3433
  throw error;
2657
3434
  }
2658
3435
  }
@@ -2667,12 +3444,12 @@ async function localizeScreenshots(host, operations, result, signal) {
2667
3444
  item["file"] = await copyRemoteArtifact(host, item["file"], signal);
2668
3445
  }
2669
3446
  }
2670
- async function executeRemoteBrowser(route, operations, signal) {
3447
+ async function executeRemoteBrowser(route, operations, ownerId, signal) {
2671
3448
  if (!route.remote) {
2672
3449
  throw new Error(`Browser host ${route.name} has no remote command`);
2673
3450
  }
2674
3451
  await ensureRemoteHelper(route.name, route.remote, signal);
2675
- const executed = await runProgram("ssh", [route.name, remoteNodeCommand(route.remote)], JSON.stringify({ operations }), signal);
3452
+ const executed = await runProgram("ssh", [route.name, remoteNodeCommand(route.remote)], JSON.stringify({ owner_id: ownerId, operations }), signal);
2676
3453
  if (executed.code !== 0) {
2677
3454
  throw new Error(executed.stderr || executed.stdout || `remote browser exited with code ${executed.code}`);
2678
3455
  }
@@ -2690,20 +3467,31 @@ async function executeRemoteBrowser(route, operations, signal) {
2690
3467
  }
2691
3468
 
2692
3469
  // src/browser/runtime.ts
3470
+ var LOCAL_SESSION_IDLE_MS = 20 * 60 * 1000;
3471
+
2693
3472
  class BrowserRuntime {
2694
3473
  hosts;
2695
- cdp = new BrowserCdpSession;
2696
- operations = new BrowserOperationExecutor(this.cdp);
3474
+ defaultOwnerId = randomUUID();
3475
+ lifetime = new AbortController;
3476
+ closing;
3477
+ localSessions = new Map;
2697
3478
  routes;
2698
3479
  constructor(routes = loadBrowserRoutes()) {
2699
3480
  this.routes = routes;
2700
3481
  this.hosts = routes.names;
2701
3482
  }
2702
3483
  async execute(request, options = {}) {
3484
+ options = {
3485
+ ...options,
3486
+ signal: options.signal ? AbortSignal.any([options.signal, this.lifetime.signal]) : this.lifetime.signal
3487
+ };
2703
3488
  options.signal?.throwIfAborted();
3489
+ await waitForTurn(this.pruneLocalSessions(), options.signal);
2704
3490
  await pruneArtifacts();
3491
+ options.signal?.throwIfAborted();
2705
3492
  if ("help" in request)
2706
3493
  return browserHelp(this.hosts);
3494
+ const ownerId = options.ownerId ?? this.defaultOwnerId;
2707
3495
  if (request.host) {
2708
3496
  const route = this.routes.resolve(request.host);
2709
3497
  if (!route.local) {
@@ -2711,37 +3499,87 @@ class BrowserRuntime {
2711
3499
  if (first) {
2712
3500
  options.onOperation?.(first, 0, request.operations.length);
2713
3501
  }
2714
- const result2 = await executeRemoteBrowser(route, request.operations, options.signal);
3502
+ const result2 = await executeRemoteBrowser(route, request.operations, ownerId, options.signal);
2715
3503
  return { host: request.host, ...result2 };
2716
3504
  }
2717
3505
  }
2718
- const result = await this.executeLocal(request.operations, options);
3506
+ const result = await this.executeLocal(request.operations, ownerId, options);
2719
3507
  return request.host ? { host: request.host, ...result } : result;
2720
3508
  }
2721
3509
  close() {
2722
- this.cdp.close();
3510
+ if (this.closing)
3511
+ return this.closing;
3512
+ this.lifetime.abort(new Error("Browser runtime closed"));
3513
+ const closing = [...this.localSessions.values()].map((session) => session.cdp.close());
3514
+ this.localSessions.clear();
3515
+ this.closing = Promise.all(closing).then(() => {
3516
+ return;
3517
+ });
3518
+ return this.closing;
2723
3519
  }
2724
- async executeLocal(operations, options) {
2725
- const results = [];
2726
- for (const [index, operation] of operations.entries()) {
2727
- try {
2728
- options.signal?.throwIfAborted();
2729
- options.onOperation?.(operation, index, operations.length);
2730
- results.push(await this.operations.execute(operation, options.signal));
2731
- } catch (error) {
2732
- throw new Error(`batch failed at ${operation.action}[${index}] after ${results.length} completed operation(s): ${error instanceof Error ? error.message : String(error)}`);
2733
- }
3520
+ async executeLocal(operations, ownerId, options) {
3521
+ let pendingClose = this.localSessions.get(ownerId)?.closing;
3522
+ while (pendingClose) {
3523
+ await waitForTurn(pendingClose, options.signal);
3524
+ pendingClose = this.localSessions.get(ownerId)?.closing;
2734
3525
  }
2735
- const first = results[0];
2736
- if (results.length === 1 && first)
2737
- return first;
2738
- return {
2739
- results: results.map((result, index) => ({
2740
- operation: operations[index]?.action ?? "unknown",
2741
- index,
2742
- ...result
2743
- }))
3526
+ options.signal?.throwIfAborted();
3527
+ const session = this.localSession(ownerId);
3528
+ session.activeCalls++;
3529
+ try {
3530
+ const results = [];
3531
+ for (const [index, operation] of operations.entries()) {
3532
+ try {
3533
+ options.signal?.throwIfAborted();
3534
+ options.onOperation?.(operation, index, operations.length);
3535
+ results.push(await session.operations.execute(operation, options.signal));
3536
+ } catch (error) {
3537
+ throw new Error(`batch failed at ${operation.action}[${index}] after ${results.length} completed operation(s): ${error instanceof Error ? error.message : String(error)}`);
3538
+ }
3539
+ }
3540
+ const first = results[0];
3541
+ if (results.length === 1 && first)
3542
+ return first;
3543
+ return {
3544
+ results: results.map((result, index) => ({
3545
+ operation: operations[index]?.action ?? "unknown",
3546
+ index,
3547
+ ...result
3548
+ }))
3549
+ };
3550
+ } finally {
3551
+ session.activeCalls--;
3552
+ session.lastUsed = Date.now();
3553
+ }
3554
+ }
3555
+ localSession(ownerId) {
3556
+ let session = this.localSessions.get(ownerId);
3557
+ if (session)
3558
+ return session;
3559
+ const cdp = new BrowserCdpSession(ownerId, join5(artifactDirectory(), "tabs"));
3560
+ session = {
3561
+ activeCalls: 0,
3562
+ cdp,
3563
+ lastUsed: Date.now(),
3564
+ operations: new BrowserOperationExecutor(cdp)
2744
3565
  };
3566
+ this.localSessions.set(ownerId, session);
3567
+ return session;
3568
+ }
3569
+ async pruneLocalSessions(now = Date.now()) {
3570
+ const closing = [];
3571
+ for (const [ownerId, session] of this.localSessions) {
3572
+ if (!session.closing && session.activeCalls === 0 && now - session.lastUsed >= LOCAL_SESSION_IDLE_MS) {
3573
+ session.closing = session.cdp.close().finally(() => {
3574
+ if (this.localSessions.get(ownerId) === session) {
3575
+ this.localSessions.delete(ownerId);
3576
+ }
3577
+ });
3578
+ }
3579
+ if (session.closing)
3580
+ closing.push(session.closing);
3581
+ }
3582
+ await Promise.all(closing);
2745
3583
  }
2746
3584
  }
2747
3585
 
@@ -2753,15 +3591,15 @@ var IS_WINDOWS2 = process.platform === "win32";
2753
3591
  function workerSocketPath(workerId) {
2754
3592
  if (IS_WINDOWS2)
2755
3593
  return `\\\\.\\pipe\\pi-browser-worker-${workerId}`;
2756
- const directory = process.env["XDG_RUNTIME_DIR"] ? join4(process.env["XDG_RUNTIME_DIR"], "browser-tool") : join4(tmpdir2(), `browser-tool-${process.getuid?.() ?? "user"}`);
2757
- return join4(directory, `worker-${workerId}.sock`);
3594
+ const directory = process.env["XDG_RUNTIME_DIR"] ? join6(process.env["XDG_RUNTIME_DIR"], "browser-tool") : join6(tmpdir2(), `browser-tool-${process.getuid?.() ?? "user"}`);
3595
+ return join6(directory, `worker-${workerId}.sock`);
2758
3596
  }
2759
3597
  async function ensureWorkerSocketDirectory(workerId) {
2760
3598
  if (IS_WINDOWS2)
2761
3599
  return;
2762
3600
  const directory = dirname2(workerSocketPath(workerId));
2763
- await mkdir3(directory, { recursive: true, mode: 448 });
2764
- const info = await lstat(directory);
3601
+ await mkdir4(directory, { recursive: true, mode: 448 });
3602
+ const info = await lstat2(directory);
2765
3603
  const uid = process.getuid?.();
2766
3604
  if (info.isSymbolicLink() || !info.isDirectory()) {
2767
3605
  throw new Error(`Browser worker socket directory is not a directory: ${directory}`);
@@ -2772,7 +3610,7 @@ async function ensureWorkerSocketDirectory(workerId) {
2772
3610
  if ((info.mode & 63) !== 0)
2773
3611
  await chmod(directory, 448);
2774
3612
  }
2775
- function parseWorkerOperations(input) {
3613
+ function parseWorkerRequest(input) {
2776
3614
  let value;
2777
3615
  try {
2778
3616
  value = JSON.parse(input);
@@ -2781,14 +3619,17 @@ function parseWorkerOperations(input) {
2781
3619
  }
2782
3620
  if (!isRecordValue(value))
2783
3621
  throw new Error("worker input must be an object");
2784
- const unknown = Object.keys(value).filter((key) => key !== "operations");
3622
+ const unknown = Object.keys(value).filter((key) => key !== "owner_id" && key !== "operations");
2785
3623
  if (unknown.length > 0) {
2786
3624
  throw new Error(`unknown worker field(s): ${unknown.join(", ")}`);
2787
3625
  }
3626
+ if (typeof value["owner_id"] !== "string" || value["owner_id"].length === 0 || value["owner_id"].length > 256) {
3627
+ throw new Error("worker owner_id must be a non-empty string no longer than 256 characters");
3628
+ }
2788
3629
  if (!Array.isArray(value["operations"]) || value["operations"].length === 0) {
2789
3630
  throw new Error("worker operations must be a non-empty array");
2790
3631
  }
2791
- return value["operations"].map((operation, index) => {
3632
+ const operations = value["operations"].map((operation, index) => {
2792
3633
  if (!isRecordValue(operation)) {
2793
3634
  throw new Error(`worker operations[${index}] must be an object`);
2794
3635
  }
@@ -2798,6 +3639,7 @@ function parseWorkerOperations(input) {
2798
3639
  }
2799
3640
  return parsed;
2800
3641
  });
3642
+ return { operations, ownerId: value["owner_id"] };
2801
3643
  }
2802
3644
  function readLine(socket) {
2803
3645
  return new Promise((resolveValue, reject) => {
@@ -2841,10 +3683,10 @@ async function handleConnection(socket, runtime) {
2841
3683
  socket.once("error", abort);
2842
3684
  let response;
2843
3685
  try {
2844
- const operations = parseWorkerOperations(await readLine(socket));
3686
+ const request = parseWorkerRequest(await readLine(socket));
2845
3687
  response = {
2846
3688
  ok: true,
2847
- result: await runtime.execute({ operations }, { signal: controller.signal })
3689
+ result: await runtime.execute({ operations: request.operations }, { ownerId: request.ownerId, signal: controller.signal })
2848
3690
  };
2849
3691
  } catch (error) {
2850
3692
  response = {
@@ -2892,9 +3734,9 @@ async function serveBrowserWorker(workerId) {
2892
3734
  clearTimeout(idleTimer);
2893
3735
  process.removeListener("SIGINT", close);
2894
3736
  process.removeListener("SIGTERM", close);
2895
- runtime.close();
3737
+ await runtime.close();
2896
3738
  if (!IS_WINDOWS2 && ownsSocket)
2897
- await rm3(path, { force: true });
3739
+ await rm4(path, { force: true });
2898
3740
  }
2899
3741
  }
2900
3742
  async function requestOnce(input, workerId, signal) {
@@ -2949,7 +3791,7 @@ async function requestBrowserWorker(input, entryPath, workerId, signal) {
2949
3791
  throw error;
2950
3792
  }
2951
3793
  if (!IS_WINDOWS2)
2952
- await rm3(workerSocketPath(workerId), { force: true });
3794
+ await rm4(workerSocketPath(workerId), { force: true });
2953
3795
  const child = spawn3(process.execPath, ["--preserve-symlinks-main", entryPath, "--daemon"], { detached: true, stdio: "ignore" });
2954
3796
  child.unref();
2955
3797
  const deadline = Date.now() + START_TIMEOUT_MS;
@@ -2982,7 +3824,7 @@ async function readStdin() {
2982
3824
  }
2983
3825
  async function main() {
2984
3826
  const entryPath = fileURLToPath2(import.meta.url);
2985
- const workerId = createHash("sha256").update(readFileSync3(entryPath)).digest("hex").slice(0, 12);
3827
+ const workerId = createHash2("sha256").update(readFileSync3(entryPath)).digest("hex").slice(0, 12);
2986
3828
  if (process.argv.includes("--daemon")) {
2987
3829
  await serveBrowserWorker(workerId);
2988
3830
  return;