@opencode/browse 0.0.15-dev.97 → 0.0.15

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 (35) hide show
  1. package/dist/{Undici-88kyhfpm.mjs → Undici-mxpvn7gy.mjs} +1 -1
  2. package/dist/{cli-t7r3wnv8.mjs → cli-xke2d25m.mjs} +139 -135
  3. package/dist/cli.mjs +17 -16
  4. package/dist/{helpers-j683tr91.mjs → helpers-tsvynww5.mjs} +4 -2
  5. package/dist/{index-yzz55kxm.mjs → index-6gkr235e.mjs} +1 -1
  6. package/dist/{main-8fkq5dgw.mjs → main-3esbykhb.mjs} +4 -4
  7. package/dist/{main-r62eef6t.mjs → main-70y5racc.mjs} +2 -2
  8. package/dist/main-7y3pj4rc.mjs +1694 -0
  9. package/dist/{main-7n3prtjk.mjs → main-9kxgkcse.mjs} +2 -2
  10. package/dist/main-9t2s5ptx.mjs +5405 -0
  11. package/dist/{main-vgzr4689.mjs → main-azpzpy0x.mjs} +1 -1
  12. package/dist/main-ckssvk4c.mjs +18 -0
  13. package/dist/{main-d0vkm24t.mjs → main-crssg4wd.mjs} +25 -11
  14. package/dist/{main-b3w2ntyc.mjs → main-d79nrcqc.mjs} +67 -58
  15. package/dist/{main-8z9d979q.mjs → main-er120rjm.mjs} +2 -2
  16. package/dist/{main-yf9xhpn4.mjs → main-ken6azcs.mjs} +2 -2
  17. package/dist/main-m05te79v.mjs +1255 -0
  18. package/dist/{main-fed0em2f.mjs → main-rycc0g05.mjs} +3 -3
  19. package/dist/{main-azv7pxzm.mjs → main-sfb6r1ye.mjs} +2 -2
  20. package/dist/{main-y22dyw2e.mjs → main-w9h0wtxs.mjs} +57 -10
  21. package/dist/main-xkbs0qyx.mjs +4 -0
  22. package/dist/{main-csnx585b.mjs → main-yf5j8g79.mjs} +2800 -8017
  23. package/dist/{mcp-fvd77dd5.mjs → mcp-qzkz0rbx.mjs} +418 -414
  24. package/dist/{migrate-mbbpx6fe.mjs → migrate-bcea81cv.mjs} +11 -14
  25. package/dist/{relay-gm2rz6ag.mjs → relay-pc2ke2t2.mjs} +1489 -473
  26. package/dist/{runtime-update-yr9prapz.mjs → runtime-update-jaxftsqk.mjs} +7 -6
  27. package/dist/{setup-wq76tmbx.mjs → setup-cpr4psvg.mjs} +30 -20
  28. package/dist/{skill-text-x30agn5m.mjs → skill-text-v0etv8b7.mjs} +26 -8
  29. package/dist/{supervisor-e5k91ga8.mjs → supervisor-recc7rne.mjs} +5 -5
  30. package/dist/{update-mk60neam.mjs → update-0vgwjjha.mjs} +3 -3
  31. package/dist/{version-hwm41j2w.mjs → version-67w7t6ce.mjs} +1 -1
  32. package/package.json +1 -1
  33. package/skills/browse/SKILL.md +26 -8
  34. package/dist/main-afz4wktv.mjs +0 -4
  35. package/dist/main-e0wy6qvy.mjs +0 -2924
@@ -1,10 +1,15 @@
1
1
  import {
2
2
  opencodeBrowserVersion2,
3
3
  opencodeBrowserBuildId2
4
- } from "./main-afz4wktv.mjs";
4
+ } from "./main-xkbs0qyx.mjs";
5
5
  import {
6
+ defaultRoots,
7
+ configRoot2,
6
8
  dataRoot,
7
9
  stateRoot,
10
+ cacheRoot,
11
+ installedBinaryPath,
12
+ installerBinaryPath,
8
13
  oldStoreMarker,
9
14
  fromCheckout,
10
15
  cliCommand,
@@ -20,7 +25,7 @@ import {
20
25
  setStoredMode,
21
26
  autoUpdateStatus,
22
27
  createAutoUpdater
23
- } from "./main-y22dyw2e.mjs";
28
+ } from "./main-w9h0wtxs.mjs";
24
29
  import {
25
30
  extensionProtocolVersion,
26
31
  minExtensionProtocolVersion,
@@ -41,7 +46,7 @@ import {
41
46
  writeJsonFileAtomically,
42
47
  ensurePrivateDirectorySync,
43
48
  writePrivateJsonFileSync
44
- } from "./main-vgzr4689.mjs";
49
+ } from "./main-azpzpy0x.mjs";
45
50
  import {
46
51
  withDefault,
47
52
  option,
@@ -88,6 +93,7 @@ import {
88
93
  sendCdpEvent2,
89
94
  getObject2,
90
95
  getString2,
96
+ createTargetUrl2,
91
97
  getNumber2,
92
98
  getIdText2,
93
99
  headerValue2,
@@ -95,7 +101,7 @@ import {
95
101
  isRestrictedTarget2,
96
102
  isRestrictedUrl2,
97
103
  dataUrlDocument2
98
- } from "./main-b3w2ntyc.mjs";
104
+ } from "./main-d79nrcqc.mjs";
99
105
  import {
100
106
  context,
101
107
  pendingPairingCodeKeys,
@@ -113,15 +119,9 @@ import {
113
119
  pairingSessionKey,
114
120
  sessionProof,
115
121
  wrapToken
116
- } from "./main-7n3prtjk.mjs";
122
+ } from "./main-9kxgkcse.mjs";
117
123
  import {
118
124
  makeUnsafe,
119
- SettingsInputError,
120
- parseSettingChanges,
121
- settingsFromExtension,
122
- settingsToExtension,
123
- describeSettings,
124
- describeChanges,
125
125
  terminateChildProcess,
126
126
  SecretCollector,
127
127
  looksLikeTokenSegment,
@@ -141,29 +141,51 @@ import {
141
141
  checkNavigationUrl,
142
142
  readSecret,
143
143
  secretText
144
- } from "./main-e0wy6qvy.mjs";
144
+ } from "./main-m05te79v.mjs";
145
145
  import {
146
146
  defaultJournalBaseDir,
147
147
  makeJournalEntry,
148
148
  appendJournalEntry,
149
149
  startJournalRetention
150
- } from "./main-8fkq5dgw.mjs";
150
+ } from "./main-3esbykhb.mjs";
151
151
  import {
152
152
  createUpdateWatcher2
153
- } from "./main-azv7pxzm.mjs";
153
+ } from "./main-sfb6r1ye.mjs";
154
+ import {
155
+ SettingsInputError,
156
+ parseSettingChanges,
157
+ settingsFromExtension,
158
+ settingsToExtension,
159
+ describeSettings,
160
+ describeChanges
161
+ } from "./main-7y3pj4rc.mjs";
154
162
  import {
155
163
  relayHostname,
156
164
  isLocalPeer,
157
165
  installedDevExtension,
158
166
  syncDevExtension
159
- } from "./main-fed0em2f.mjs";
167
+ } from "./main-rycc0g05.mjs";
168
+ import {
169
+ legacyRoots
170
+ } from "./main-ckssvk4c.mjs";
160
171
  import {
161
172
  currentTimeMillis,
162
173
  value,
163
174
  when,
164
175
  orElse,
165
176
  exhaustive
166
- } from "./main-8z9d979q.mjs";
177
+ } from "./main-er120rjm.mjs";
178
+ import {
179
+ join,
180
+ interrupt,
181
+ makeUnsafe2
182
+ } from "./main-9t2s5ptx.mjs";
183
+ import {
184
+ relayTokenQueryParam,
185
+ relayToken,
186
+ secretsEqual,
187
+ ensurePrivateDirectory
188
+ } from "./main-70y5racc.mjs";
167
189
  import {
168
190
  isNone,
169
191
  isSome,
@@ -176,14 +198,14 @@ import {
176
198
  isSuccess2,
177
199
  isFailure2,
178
200
  asVoid,
179
- makeUnsafe3,
180
- make5,
201
+ makeUnsafe4,
202
+ make10,
181
203
  _await,
182
- done,
183
- fail4,
204
+ done2,
205
+ fail5,
184
206
  succeed4,
185
207
  doneUnsafe,
186
- make6,
208
+ make11,
187
209
  close,
188
210
  modifyDelay,
189
211
  spaced,
@@ -199,10 +221,10 @@ import {
199
221
  callback2,
200
222
  never,
201
223
  gen,
202
- fail5,
203
- try_,
224
+ fail6,
225
+ try_2,
204
226
  flatMap3,
205
- andThen,
227
+ andThen2,
206
228
  tap,
207
229
  result,
208
230
  exit,
@@ -210,6 +232,7 @@ import {
210
232
  asVoid2,
211
233
  catch_,
212
234
  catchCause,
235
+ catchIf,
213
236
  mapError,
214
237
  tapError,
215
238
  retry,
@@ -221,7 +244,7 @@ import {
221
244
  sleep,
222
245
  raceFirst,
223
246
  match3,
224
- matchEffect,
247
+ matchEffect2,
225
248
  context2,
226
249
  scoped,
227
250
  acquireRelease,
@@ -258,17 +281,8 @@ import {
258
281
  TaggedUnion,
259
282
  Int2,
260
283
  Defect,
261
- TaggedError2,
262
- join,
263
- interrupt3,
264
- makeUnsafe5
265
- } from "./main-csnx585b.mjs";
266
- import {
267
- relayTokenQueryParam,
268
- relayToken,
269
- secretsEqual,
270
- ensurePrivateDirectory
271
- } from "./main-r62eef6t.mjs";
284
+ TaggedError2
285
+ } from "./main-yf5j8g79.mjs";
272
286
  import {
273
287
  isString,
274
288
  isNumber,
@@ -278,11 +292,11 @@ import {
278
292
  isFunction,
279
293
  isObjectOrArray,
280
294
  isObject
281
- } from "./main-yf9xhpn4.mjs";
295
+ } from "./main-ken6azcs.mjs";
282
296
 
283
297
  // src/relay.ts
284
298
  import crypto10 from "node:crypto";
285
- import path14 from "node:path";
299
+ import path15 from "node:path";
286
300
 
287
301
  // src/relay/browser-links.ts
288
302
  import dns from "node:dns/promises";
@@ -391,11 +405,11 @@ class ExtensionRpc {
391
405
  return callback2((resume) => {
392
406
  const socket = this.socket;
393
407
  if (this.protocolCompatible === false) {
394
- resume(fail5(new Error(extensionProtocolAdvice(this.protocolVersion, { install: installCommand() }))));
408
+ resume(fail6(new Error(extensionProtocolAdvice(this.protocolVersion, { install: installCommand() }))));
395
409
  return void_3;
396
410
  }
397
411
  if (!socket || socket.readyState !== WebSocket.OPEN || !this.acceptsEvents) {
398
- resume(fail5(new Error("browse extension is not connected")));
412
+ resume(fail6(new Error("browse extension is not connected")));
399
413
  return void_3;
400
414
  }
401
415
  const id = this.nextRequestId++;
@@ -417,10 +431,10 @@ class ExtensionRpc {
417
431
  if (this.replies !== replies)
418
432
  return finish(succeed6({}));
419
433
  this.unresponsive = true;
420
- return finish(fail5(new Error(browserUnresponsive)));
434
+ return finish(fail6(new Error(browserUnresponsive)));
421
435
  }
422
436
  this.probeLiveness(socket);
423
- finish(fail5(new Error(`Extension command timed out after ${timeoutMs}ms: ${command.method}`)));
437
+ finish(fail6(new Error(`Extension command timed out after ${timeoutMs}ms: ${command.method}`)));
424
438
  }, timeoutMs);
425
439
  const debuggerTabId = command.method === "debugger.sendCommand" && isNumber(command.params?.tabId) ? command.params.tabId : undefined;
426
440
  this.pendingRequests.set(id, {
@@ -428,18 +442,18 @@ class ExtensionRpc {
428
442
  finish(succeed6(value));
429
443
  },
430
444
  reject: (error) => {
431
- finish(fail5(error));
445
+ finish(fail6(error));
432
446
  },
433
447
  ...debuggerTabId === undefined ? {} : { debuggerTabId }
434
448
  });
435
449
  try {
436
450
  socket.send(JSON.stringify(message), (error) => {
437
451
  if (error) {
438
- finish(fail5(new Error(`send extension command: ${command.method}`, { cause: error })));
452
+ finish(fail6(new Error(`send extension command: ${command.method}`, { cause: error })));
439
453
  }
440
454
  });
441
455
  } catch (error) {
442
- finish(fail5(new Error(`send extension command: ${command.method}`, { cause: error })));
456
+ finish(fail6(new Error(`send extension command: ${command.method}`, { cause: error })));
443
457
  }
444
458
  return sync2(() => {
445
459
  completed = true;
@@ -1623,7 +1637,7 @@ class CdpRuntime {
1623
1637
  method: "Runtime.enable",
1624
1638
  params,
1625
1639
  ...route.chromeSessionId === undefined ? {} : { sessionId: route.chromeSessionId }
1626
- }) : fail5(new Error("CDP target changed before Runtime.enable"))), client && requester ? {
1640
+ }) : fail6(new Error("CDP target changed before Runtime.enable"))), client && requester ? {
1627
1641
  replay: () => {
1628
1642
  const frameId = rootFrame();
1629
1643
  return frameId !== undefined && this.replayCached(client, route, frameId);
@@ -1635,7 +1649,7 @@ class CdpRuntime {
1635
1649
  } : {});
1636
1650
  this.trace(route, `runtime-enable defaultContextSeen=${first.seen}`);
1637
1651
  if (!first.seen && permitted()) {
1638
- const retry = yield* this.observe(route, this.reset(route, "Runtime.disable", {}, permitted).pipe(andThen(() => this.reset(route, "Runtime.enable", params, permitted))));
1652
+ const retry = yield* this.observe(route, this.reset(route, "Runtime.disable", {}, permitted).pipe(andThen2(() => this.reset(route, "Runtime.enable", params, permitted))));
1639
1653
  this.trace(route, `runtime-reset phase=missing-default-context defaultContextSeen=${retry.seen}`);
1640
1654
  }
1641
1655
  return first.result;
@@ -1675,7 +1689,7 @@ class CdpRuntime {
1675
1689
  observe(route, command, options = {}) {
1676
1690
  const runtime = this;
1677
1691
  return acquireUseRelease(sync2(() => {
1678
- const waiter = { sessionId: routeSessionId(route), ready: makeUnsafe3(), nativeReady: options.nativeReady ?? (() => true) };
1692
+ const waiter = { sessionId: routeSessionId(route), ready: makeUnsafe4(), nativeReady: options.nativeReady ?? (() => true) };
1679
1693
  runtime.waiters.add(waiter);
1680
1694
  return waiter;
1681
1695
  }), (waiter) => gen(function* () {
@@ -1941,7 +1955,7 @@ class AuthenticatedOriginError extends TaggedError2()("AuthenticatedOrigin.Error
1941
1955
  }) {
1942
1956
  }
1943
1957
  var requestJson = fn("AuthenticatedOrigin.requestJson")(function* (page, request) {
1944
- const target = yield* try_({
1958
+ const target = yield* try_2({
1945
1959
  try: () => {
1946
1960
  const origin = normalizeOrigin(request.origin);
1947
1961
  return {
@@ -2286,23 +2300,454 @@ function challengeWarning(outcome) {
2286
2300
  }
2287
2301
 
2288
2302
  // src/execute-realm.ts
2289
- import buffer2 from "node:buffer";
2303
+ import buffer3 from "node:buffer";
2290
2304
  import crypto5 from "node:crypto";
2291
- import util3 from "node:util";
2305
+ import util6 from "node:util";
2292
2306
  import vm3 from "node:vm";
2293
2307
 
2294
2308
  // src/execute-realm/file-roots.ts
2295
- import buffer from "node:buffer";
2309
+ import buffer2 from "node:buffer";
2296
2310
  import crypto3 from "node:crypto";
2297
2311
  import events from "node:events";
2298
- import fs2 from "node:fs";
2312
+ import fs3 from "node:fs";
2299
2313
  import fsPromises from "node:fs/promises";
2300
2314
  import os2 from "node:os";
2301
- import path2 from "node:path";
2315
+ import path3 from "node:path";
2302
2316
  import stream from "node:stream";
2303
2317
  import url from "node:url";
2304
- import util from "node:util";
2318
+ import util3 from "node:util";
2305
2319
  import zlib from "node:zlib";
2320
+
2321
+ // src/execute-realm/cdp-send.ts
2322
+ import util from "node:util";
2323
+
2324
+ // src/execute-realm/errors.ts
2325
+ class ExecuteFileAccessError extends Error {
2326
+ name = "ExecuteFileAccessError";
2327
+ }
2328
+
2329
+ // src/execute-realm/cdp-send.ts
2330
+ var cdpMethodPattern = /^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]*$/;
2331
+ function isCdpMethodName(value) {
2332
+ return cdpMethodPattern.test(value);
2333
+ }
2334
+ function isCdpSession(receiver) {
2335
+ if (receiver === null || typeof receiver !== "object" || util.types.isProxy(receiver))
2336
+ return false;
2337
+ try {
2338
+ const prototype = Object.getPrototypeOf(receiver);
2339
+ const name = prototype?.constructor?.name;
2340
+ if (typeof name === "string" && name.replace(/\d+$/, "") === "CDPSession")
2341
+ return true;
2342
+ return typeof Reflect.get(receiver, "detach") === "function" && typeof Reflect.get(receiver, "send") === "function";
2343
+ } catch {
2344
+ return false;
2345
+ }
2346
+ }
2347
+ function invalidCdpParameters(operation, why) {
2348
+ return new ExecuteFileAccessError(`${operation}: CDP parameters must be plain JSON data, ${why}`);
2349
+ }
2350
+ function copyCdpParameters(value, operation) {
2351
+ return copyJsonValue(value, operation, new Set);
2352
+ }
2353
+ function copyJsonValue(value, operation, stack) {
2354
+ if (value === null)
2355
+ return null;
2356
+ if (typeof value === "string" || typeof value === "boolean")
2357
+ return value;
2358
+ if (typeof value === "number") {
2359
+ if (!Number.isFinite(value))
2360
+ throw invalidCdpParameters(operation, "which cannot contain non-finite numbers");
2361
+ return value;
2362
+ }
2363
+ if (typeof value !== "object")
2364
+ throw invalidCdpParameters(operation, "which cannot contain functions, symbols or undefined values");
2365
+ if (util.types.isProxy(value))
2366
+ throw invalidCdpParameters(operation, "which cannot contain proxies");
2367
+ if (stack.has(value))
2368
+ throw invalidCdpParameters(operation, "which cannot be cyclical");
2369
+ stack.add(value);
2370
+ try {
2371
+ if (Array.isArray(value))
2372
+ return copyJsonArray(value, operation, stack);
2373
+ const prototype = Object.getPrototypeOf(value);
2374
+ if (prototype !== Object.prototype && prototype !== null) {
2375
+ throw invalidCdpParameters(operation, "which cannot contain class instances, dates, maps or other host objects");
2376
+ }
2377
+ const copy = {};
2378
+ for (const key of Reflect.ownKeys(value)) {
2379
+ if (typeof key !== "string")
2380
+ throw invalidCdpParameters(operation, "which cannot contain symbol keys");
2381
+ const descriptor = Reflect.getOwnPropertyDescriptor(value, key);
2382
+ if (descriptor === undefined || !("value" in descriptor) || descriptor.enumerable !== true) {
2383
+ throw invalidCdpParameters(operation, "which cannot contain getters, setters or non-enumerable properties");
2384
+ }
2385
+ if (descriptor.value === undefined)
2386
+ continue;
2387
+ Object.defineProperty(copy, key, {
2388
+ value: copyJsonValue(descriptor.value, operation, stack),
2389
+ writable: true,
2390
+ enumerable: true,
2391
+ configurable: true
2392
+ });
2393
+ }
2394
+ if (typeof Reflect.get(value, "toJSON") === "function")
2395
+ throw invalidCdpParameters(operation, "which cannot contain toJSON");
2396
+ return copy;
2397
+ } finally {
2398
+ stack.delete(value);
2399
+ }
2400
+ }
2401
+ function copyJsonArray(value, operation, stack) {
2402
+ const copy = new Array(value.length);
2403
+ let count = 0;
2404
+ for (const key of Reflect.ownKeys(value)) {
2405
+ if (key === "length")
2406
+ continue;
2407
+ if (typeof key !== "string" || !/^(0|[1-9]\d*)$/.test(key) || Number(key) >= value.length) {
2408
+ throw invalidCdpParameters(operation, "whose arrays cannot have extra properties");
2409
+ }
2410
+ const descriptor = Reflect.getOwnPropertyDescriptor(value, key);
2411
+ if (descriptor === undefined || !("value" in descriptor) || descriptor.enumerable !== true) {
2412
+ throw invalidCdpParameters(operation, "which cannot contain getters, setters or non-enumerable properties");
2413
+ }
2414
+ if (descriptor.value === undefined) {
2415
+ throw new ExecuteFileAccessError(`${operation}: CDP parameters must be plain JSON data; arrays cannot contain undefined, use null`);
2416
+ }
2417
+ copy[Number(key)] = copyJsonValue(descriptor.value, operation, stack);
2418
+ count += 1;
2419
+ }
2420
+ if (count !== value.length)
2421
+ throw invalidCdpParameters(operation, "whose arrays cannot have holes");
2422
+ if (typeof Reflect.get(value, "toJSON") === "function")
2423
+ throw invalidCdpParameters(operation, "which cannot contain toJSON");
2424
+ return copy;
2425
+ }
2426
+ var cdpFileInputMethods = new Set(["DOM.setFileInputFiles", "PWA.launchFilesInApp"]);
2427
+ var cdpDownloadPathMethods = new Set(["Browser.setDownloadBehavior", "Page.setDownloadBehavior"]);
2428
+ var cdpRefusedMethods = new Map([
2429
+ ["PWA.install", "installing a web app"],
2430
+ ["DOM.getFileInfo", "revealing local file paths"],
2431
+ ["Target.sendMessageToTarget", "forwarding a raw CDP message would bypass these file checks"],
2432
+ ["Target.exposeDevToolsProtocol", "exposing raw CDP to page script would bypass these file checks"]
2433
+ ]);
2434
+ function isPlainRecord(value) {
2435
+ if (value === null || typeof value !== "object" || Array.isArray(value))
2436
+ return false;
2437
+ const prototype = Object.getPrototypeOf(value);
2438
+ return prototype === Object.prototype || prototype === null;
2439
+ }
2440
+ function requireParamsObject(method, value) {
2441
+ if (!isPlainRecord(value))
2442
+ throw new ExecuteFileAccessError(`${method}: params must be an object`);
2443
+ return value;
2444
+ }
2445
+ function checkCdpFiles(container, key, method, check) {
2446
+ if (!Object.hasOwn(container, key))
2447
+ return;
2448
+ const files = container[key];
2449
+ if (!Array.isArray(files) || !files.every((file) => typeof file === "string")) {
2450
+ throw new ExecuteFileAccessError(`${method}: ${key} must be an array of file paths`);
2451
+ }
2452
+ const resolved = files.map((file) => check.fileInput(file, `${method}({ ${key} })`));
2453
+ Reflect.set(container, key, resolved);
2454
+ }
2455
+ function checkCdpSend(method, params, check) {
2456
+ if (method.startsWith("Extensions.")) {
2457
+ throw new ExecuteFileAccessError(`${method}: extension control is not available in execute code`);
2458
+ }
2459
+ const refusal = cdpRefusedMethods.get(method);
2460
+ if (refusal !== undefined)
2461
+ throw new ExecuteFileAccessError(`${method}: ${refusal}, so it is not available in execute code`);
2462
+ if (cdpFileInputMethods.has(method)) {
2463
+ checkCdpFiles(requireParamsObject(method, params), "files", method, check);
2464
+ return {};
2465
+ }
2466
+ if (method === "Input.dispatchDragEvent") {
2467
+ const object = requireParamsObject(method, params);
2468
+ if (Object.hasOwn(object, "data")) {
2469
+ const data = object.data;
2470
+ if (!isPlainRecord(data))
2471
+ throw new ExecuteFileAccessError(`${method}: data must be an object`);
2472
+ checkCdpFiles(data, "files", method, check);
2473
+ }
2474
+ return {};
2475
+ }
2476
+ if (!cdpDownloadPathMethods.has(method))
2477
+ return {};
2478
+ const object = requireParamsObject(method, params);
2479
+ const behavior = object.behavior;
2480
+ const downloadPath = object.downloadPath;
2481
+ if (downloadPath !== undefined && typeof downloadPath !== "string") {
2482
+ throw new ExecuteFileAccessError(`${method}: downloadPath must be a string`);
2483
+ }
2484
+ if (behavior === "default") {
2485
+ throw new ExecuteFileAccessError(`${method}: default downloads go outside the execute file roots; use behavior "allow" with a downloadPath`);
2486
+ }
2487
+ if (behavior !== "allow" && behavior !== "allowAndName" && behavior !== "deny") {
2488
+ throw new ExecuteFileAccessError(`${method}: behavior must be allow, allowAndName or deny in execute code`);
2489
+ }
2490
+ if (downloadPath === undefined) {
2491
+ if (behavior !== "deny")
2492
+ throw new ExecuteFileAccessError(`${method}: behavior ${behavior} requires a downloadPath`);
2493
+ return {};
2494
+ }
2495
+ const resolved = check.downloadDirectory(downloadPath, `${method}({ downloadPath })`);
2496
+ Reflect.set(object, "downloadPath", resolved);
2497
+ return behavior === "deny" ? {} : { downloadDirectory: resolved };
2498
+ }
2499
+
2500
+ // src/execute-realm/directory-uploads.ts
2501
+ import fs2 from "node:fs";
2502
+ import path2 from "node:path";
2503
+
2504
+ // src/execute-realm/file-options.ts
2505
+ import buffer from "node:buffer";
2506
+ import util2 from "node:util";
2507
+ var fileOptionMethods = new Set([
2508
+ "screenshot",
2509
+ "pdf",
2510
+ "storageState",
2511
+ "start",
2512
+ "stop",
2513
+ "startChunk",
2514
+ "stopChunk",
2515
+ "startTracing",
2516
+ "stopTracing",
2517
+ "addScriptTag",
2518
+ "addStyleTag",
2519
+ "addInitScript",
2520
+ "fulfill",
2521
+ "newContext",
2522
+ "newPage",
2523
+ "routeFromHAR",
2524
+ "screenshotWithLabels",
2525
+ "screenshotDiff"
2526
+ ]);
2527
+ var fileOptionKeys = new Set(["path", "dir", "har", "storageState"]);
2528
+ var alwaysFileOptionKeys = new Set(["outputPath", "baseline", "certPath", "keyPath", "pfxPath", "tracesDir", "downloadsPath"]);
2529
+ var forbiddenOptionKeys = new Set(["executablePath", "recordHar", "recordVideo"]);
2530
+ var allFileOptionKeys = new Set([...fileOptionKeys, ...alwaysFileOptionKeys, ...forbiddenOptionKeys]);
2531
+ var fileOutputMethods = new Set(["screenshot", "pdf", "storageState", "stop", "stopChunk", "screenshotWithLabels", "screenshotDiff"]);
2532
+ var isFileOutputOption = (method, key) => key === "path" && fileOutputMethods.has(method) || key === "outputPath" && method === "stop";
2533
+ var clientCertificatePathKeys = new Set(["certPath", "keyPath", "pfxPath"]);
2534
+ function isPlainRecord2(value) {
2535
+ if (value === null || typeof value !== "object" || Array.isArray(value) || util2.types.isProxy(value))
2536
+ return false;
2537
+ const prototype = Object.getPrototypeOf(value);
2538
+ return prototype === Object.prototype || prototype === null;
2539
+ }
2540
+ function checkClientCertificates(value, method) {
2541
+ if (!Array.isArray(value) || util2.types.isProxy(value)) {
2542
+ throw new ExecuteFileAccessError(`${method}: clientCertificates must be an array of plain objects`);
2543
+ }
2544
+ const copy = new Array(value.length);
2545
+ let count = 0;
2546
+ for (const key of Reflect.ownKeys(value)) {
2547
+ if (key === "length" || typeof key !== "string" || !/^(0|[1-9]\d*)$/.test(key))
2548
+ continue;
2549
+ const index = Number(key);
2550
+ if (index >= value.length)
2551
+ continue;
2552
+ const descriptor = Reflect.getOwnPropertyDescriptor(value, key);
2553
+ if (!("value" in descriptor)) {
2554
+ throw new ExecuteFileAccessError(`${method}: clientCertificates entries must be own data properties`);
2555
+ }
2556
+ copy[index] = descriptor.value;
2557
+ count += 1;
2558
+ }
2559
+ if (count !== value.length)
2560
+ throw new ExecuteFileAccessError(`${method}: clientCertificates must be a dense array`);
2561
+ for (const item of copy) {
2562
+ if (item === null || typeof item !== "object" || Array.isArray(item) || util2.types.isProxy(item)) {
2563
+ throw new ExecuteFileAccessError(`${method}: clientCertificates entries must be plain objects`);
2564
+ }
2565
+ const prototype = Object.getPrototypeOf(item);
2566
+ if (prototype !== Object.prototype && prototype !== null) {
2567
+ throw new ExecuteFileAccessError(`${method}: clientCertificates entries must be plain objects`);
2568
+ }
2569
+ for (const key of Reflect.ownKeys(item)) {
2570
+ if (typeof key !== "string")
2571
+ throw new ExecuteFileAccessError(`${method}: clientCertificates entries cannot have symbol properties`);
2572
+ const descriptor = Reflect.getOwnPropertyDescriptor(item, key);
2573
+ if (descriptor === undefined || !("value" in descriptor) || descriptor.enumerable !== true) {
2574
+ throw new ExecuteFileAccessError(`${method}: clientCertificates entries must have own enumerable data properties`);
2575
+ }
2576
+ if (clientCertificatePathKeys.has(key)) {
2577
+ const path = descriptor.value;
2578
+ if (path !== undefined && path !== null && typeof path !== "string") {
2579
+ throw new ExecuteFileAccessError(`${method}: clientCertificates ${key} must be a string`);
2580
+ }
2581
+ }
2582
+ }
2583
+ }
2584
+ return copy;
2585
+ }
2586
+ function checkFileStrings(value, method, checkPath) {
2587
+ if (value === undefined || value === null)
2588
+ return;
2589
+ if (typeof value === "string")
2590
+ return checkPath(value, method);
2591
+ if (Array.isArray(value)) {
2592
+ for (const item of value) {
2593
+ if (item === undefined || item === null)
2594
+ continue;
2595
+ if (typeof item !== "string")
2596
+ throw new ExecuteFileAccessError(`${method}: file paths must be strings`);
2597
+ checkPath(item, method);
2598
+ }
2599
+ return;
2600
+ }
2601
+ throw new ExecuteFileAccessError(`${method}: file paths must be strings`);
2602
+ }
2603
+ function checkFileOptions(value, method, includeMethodKeys, candidates, checkPath, depth = 0) {
2604
+ if (typeof value === "function") {
2605
+ if (depth === 0 && includeMethodKeys && method !== "addInitScript") {
2606
+ throw new ExecuteFileAccessError(`${method}: function arguments cannot be used as options`);
2607
+ }
2608
+ for (const key of allFileOptionKeys) {
2609
+ if (key in value || Reflect.get(value, key) !== undefined) {
2610
+ throw new ExecuteFileAccessError(`${method}: function arguments cannot carry the ${key} file option`);
2611
+ }
2612
+ }
2613
+ return;
2614
+ }
2615
+ if (depth > 4 || value === null || typeof value !== "object")
2616
+ return;
2617
+ if (Array.isArray(value)) {
2618
+ for (const item of value)
2619
+ checkFileOptions(item, method, includeMethodKeys, candidates, checkPath, depth + 1);
2620
+ return;
2621
+ }
2622
+ const prototype = Object.getPrototypeOf(value);
2623
+ if (prototype !== Object.prototype && prototype !== null)
2624
+ return;
2625
+ for (const [key, entry] of Object.entries(value)) {
2626
+ let item = entry;
2627
+ if (key === "clientCertificates" && includeMethodKeys && depth === 0 && item !== undefined && item !== null) {
2628
+ item = checkClientCertificates(item, method);
2629
+ if (!Reflect.set(value, key, item))
2630
+ throw new ExecuteFileAccessError(`${method}: could not store clientCertificates`);
2631
+ }
2632
+ if (forbiddenOptionKeys.has(key))
2633
+ throw new ExecuteFileAccessError(`${method}: the ${key} option is not available in execute code`);
2634
+ if (method === "fulfill" && depth === 0 && key === "json") {
2635
+ checkFileOptions(item, method, false, candidates, checkPath, depth + 1);
2636
+ continue;
2637
+ }
2638
+ if (alwaysFileOptionKeys.has(key) || includeMethodKeys && fileOptionKeys.has(key)) {
2639
+ if (item === undefined || item === null)
2640
+ continue;
2641
+ if (typeof item === "string") {
2642
+ const resolved = checkPath(item, `${method}({ ${key} })`);
2643
+ if (depth === 0 && isFileOutputOption(method, key))
2644
+ candidates.push({ path: resolved });
2645
+ Reflect.set(value, key, resolved);
2646
+ continue;
2647
+ }
2648
+ if (includeMethodKeys && depth === 0) {
2649
+ if (key === "baseline" && buffer.Buffer.isBuffer(item))
2650
+ continue;
2651
+ if (key === "storageState" && isPlainRecord2(item)) {
2652
+ checkFileOptions(item, method, false, candidates, checkPath, depth + 1);
2653
+ continue;
2654
+ }
2655
+ const allowed = key === "storageState" ? "a path string or inline state object" : key === "baseline" ? "a path string or Buffer" : "a path string";
2656
+ throw new ExecuteFileAccessError(`${method}: ${key} must be ${allowed}`);
2657
+ }
2658
+ }
2659
+ checkFileOptions(item, method, includeMethodKeys, candidates, checkPath, depth + 1);
2660
+ }
2661
+ }
2662
+
2663
+ // src/execute-realm/directory-uploads.ts
2664
+ var maxDirectoryUploadEntries = 1000;
2665
+ function checkDirectoryUpload(root, operation, check, budget) {
2666
+ let rootStat;
2667
+ try {
2668
+ rootStat = fs2.lstatSync(root);
2669
+ } catch (error) {
2670
+ if (error.code === "ENOENT")
2671
+ return;
2672
+ throw error;
2673
+ }
2674
+ if (rootStat.isSymbolicLink()) {
2675
+ throw new ExecuteFileAccessError(`${operation}: ${root} is a symlink; directory uploads cannot follow symlinks`);
2676
+ }
2677
+ if (!rootStat.isDirectory())
2678
+ return;
2679
+ const pending = [root];
2680
+ while (pending.length > 0) {
2681
+ const directory = pending.pop();
2682
+ for (const entry of fs2.readdirSync(directory, { withFileTypes: true })) {
2683
+ budget.entries += 1;
2684
+ if (budget.entries > maxDirectoryUploadEntries) {
2685
+ throw new ExecuteFileAccessError(`${operation}: folder uploads are limited to ${maxDirectoryUploadEntries} files and subfolders`);
2686
+ }
2687
+ const child = path2.join(directory, entry.name);
2688
+ if (entry.isSymbolicLink()) {
2689
+ throw new ExecuteFileAccessError(`${operation}: ${child} is a symlink; directory uploads cannot follow symlinks`);
2690
+ }
2691
+ const resolved = check(child, operation);
2692
+ const stat = fs2.lstatSync(resolved);
2693
+ if (stat.isSymbolicLink()) {
2694
+ throw new ExecuteFileAccessError(`${operation}: ${resolved} is a symlink; directory uploads cannot follow symlinks`);
2695
+ }
2696
+ if (stat.isDirectory())
2697
+ pending.push(resolved);
2698
+ }
2699
+ }
2700
+ }
2701
+ function checkFileInputValue(value, method, assertPath, checkEntry) {
2702
+ const budget = { entries: 0 };
2703
+ const check = (target) => {
2704
+ const resolved = assertPath(target, method);
2705
+ checkDirectoryUpload(resolved, method, checkEntry, budget);
2706
+ return resolved;
2707
+ };
2708
+ const checkValue = (item) => {
2709
+ if (typeof item === "string")
2710
+ return check(item);
2711
+ if (isPlainRecord2(item))
2712
+ return item;
2713
+ throw new ExecuteFileAccessError(`${method}: file inputs must be strings or file payload objects`);
2714
+ };
2715
+ if (Array.isArray(value))
2716
+ return value.map(checkValue);
2717
+ return checkValue(value);
2718
+ }
2719
+
2720
+ // src/execute-realm/drop-payload.ts
2721
+ function checkDropFile(value, checkFile) {
2722
+ if (typeof value === "string")
2723
+ return checkFile(value, "drop");
2724
+ if (isPlainRecord2(value))
2725
+ return value;
2726
+ throw new ExecuteFileAccessError("drop: files must be strings or file payload objects");
2727
+ }
2728
+ function checkDropFiles(value, checkFile) {
2729
+ if (Array.isArray(value))
2730
+ return value.map((item) => checkDropFile(item, checkFile));
2731
+ return checkDropFile(value, checkFile);
2732
+ }
2733
+ function checkDropPayload(value, checkFile) {
2734
+ if (!isPlainRecord2(value))
2735
+ throw new ExecuteFileAccessError("drop: the payload must be a plain object");
2736
+ const object = value;
2737
+ const files = Object.getOwnPropertyDescriptor(object, "files");
2738
+ if (files === undefined && "files" in object) {
2739
+ throw new ExecuteFileAccessError("drop: files must be an own property of the payload");
2740
+ }
2741
+ if (files !== undefined && !("value" in files)) {
2742
+ throw new ExecuteFileAccessError("drop: files must be a data property");
2743
+ }
2744
+ const copy = { ...object };
2745
+ if (files !== undefined && files.value !== undefined)
2746
+ copy.files = checkDropFiles(files.value, checkFile);
2747
+ return copy;
2748
+ }
2749
+
2750
+ // src/execute-realm/file-roots.ts
2306
2751
  var allowNodeEnvironmentVariable = "OPENCODE_BROWSER_ALLOW_NODE";
2307
2752
  var allowForegroundEnvironmentVariable = "OPENCODE_BROWSER_ALLOW_FOREGROUND";
2308
2753
  var fileRootsEnvironmentVariable = "OPENCODE_BROWSER_FILE_ROOTS";
@@ -2314,24 +2759,24 @@ function executeSliceMs() {
2314
2759
  var executeAllowsNode = () => process.env[allowNodeEnvironmentVariable] === "1";
2315
2760
  var executeAllowsForeground = () => process.env[allowForegroundEnvironmentVariable] === "1";
2316
2761
  var bringToFrontBlockedMessage = "page.bringToFront() is blocked: it raises the user's browser window over their work. Use handoff(message) when the user needs to act in the tab, or set OPENCODE_BROWSER_ALLOW_FOREGROUND=1 for the relay to allow it.";
2317
- var sandboxModules = { path: path2, url, util, crypto: crypto3, buffer, zlib, events, stream };
2762
+ var sandboxModules = { path: path3, url, util: util3, crypto: crypto3, buffer: buffer2, zlib, events, stream };
2318
2763
  var filesDirectoryPrefix = "opencode-browser-files-";
2319
2764
  var filesDirectoryPattern = /^opencode-browser-files-(\d+)-[A-Za-z0-9]{6}$/;
2320
2765
  var filesDirectory;
2321
2766
  var filesDirectoryExitHook = false;
2322
2767
  function executeFilesDirectory() {
2323
2768
  if (filesDirectory === undefined) {
2324
- filesDirectory = fs2.mkdtempSync(path2.join(os2.tmpdir(), `${filesDirectoryPrefix}${process.pid}-`));
2769
+ filesDirectory = fs3.mkdtempSync(path3.join(os2.tmpdir(), `${filesDirectoryPrefix}${process.pid}-`));
2325
2770
  if (!filesDirectoryExitHook) {
2326
2771
  filesDirectoryExitHook = true;
2327
2772
  process.once("exit", removeExecuteFilesDirectory);
2328
2773
  }
2329
2774
  }
2330
- const stat = fs2.lstatSync(filesDirectory);
2775
+ const stat = fs3.lstatSync(filesDirectory);
2331
2776
  if (!stat.isDirectory() || stat.isSymbolicLink() || process.getuid && (stat.uid !== process.getuid() || (stat.mode & 511) !== 448)) {
2332
2777
  throw new ExecuteFileAccessError("files.dir must be an owned, private directory, not a symlink");
2333
2778
  }
2334
- return fs2.realpathSync(filesDirectory);
2779
+ return fs3.realpathSync(filesDirectory);
2335
2780
  }
2336
2781
  function removeExecuteFilesDirectory() {
2337
2782
  const directory = filesDirectory;
@@ -2339,10 +2784,10 @@ function removeExecuteFilesDirectory() {
2339
2784
  if (directory === undefined)
2340
2785
  return;
2341
2786
  try {
2342
- const stat = fs2.lstatSync(directory);
2787
+ const stat = fs3.lstatSync(directory);
2343
2788
  if (!stat.isDirectory() || stat.isSymbolicLink())
2344
2789
  return;
2345
- fs2.rmSync(directory, { recursive: true, force: true });
2790
+ fs3.rmSync(directory, { recursive: true, force: true });
2346
2791
  } catch {}
2347
2792
  }
2348
2793
  var processAlive = (pid) => {
@@ -2357,7 +2802,7 @@ function pruneStaleExecuteFilesDirectories(tmp = os2.tmpdir()) {
2357
2802
  const removed = [];
2358
2803
  let entries;
2359
2804
  try {
2360
- entries = fs2.readdirSync(tmp);
2805
+ entries = fs3.readdirSync(tmp);
2361
2806
  } catch {
2362
2807
  return removed;
2363
2808
  }
@@ -2368,14 +2813,14 @@ function pruneStaleExecuteFilesDirectories(tmp = os2.tmpdir()) {
2368
2813
  const pid = Number(match[1]);
2369
2814
  if (!Number.isSafeInteger(pid) || pid <= 0 || pid === process.pid || processAlive(pid))
2370
2815
  continue;
2371
- const directory = path2.join(tmp, entry);
2816
+ const directory = path3.join(tmp, entry);
2372
2817
  try {
2373
- const stat = fs2.lstatSync(directory);
2818
+ const stat = fs3.lstatSync(directory);
2374
2819
  if (!stat.isDirectory() || stat.isSymbolicLink())
2375
2820
  continue;
2376
2821
  if (process.getuid && stat.uid !== process.getuid())
2377
2822
  continue;
2378
- fs2.rmSync(directory, { recursive: true, force: true });
2823
+ fs3.rmSync(directory, { recursive: true, force: true });
2379
2824
  removed.push(directory);
2380
2825
  } catch {}
2381
2826
  }
@@ -2383,67 +2828,104 @@ function pruneStaleExecuteFilesDirectories(tmp = os2.tmpdir()) {
2383
2828
  }
2384
2829
  function realpathOrSelf(target) {
2385
2830
  try {
2386
- return fs2.realpathSync(target);
2831
+ return fs3.realpathSync(target);
2387
2832
  } catch {
2388
- return path2.resolve(target);
2833
+ return path3.resolve(target);
2389
2834
  }
2390
2835
  }
2391
2836
  function executeFileRoots() {
2392
- const extra = (process.env[fileRootsEnvironmentVariable] ?? "").split(path2.delimiter).filter((entry) => path2.isAbsolute(entry));
2837
+ const extra = (process.env[fileRootsEnvironmentVariable] ?? "").split(path3.delimiter).filter((entry) => path3.isAbsolute(entry));
2393
2838
  const roots = [os2.tmpdir(), ...process.platform === "win32" ? [] : ["/tmp"], ...extra];
2394
2839
  return [...new Set(roots.map(realpathOrSelf))];
2395
2840
  }
2396
- function isInside(child, parent) {
2397
- const relative = path2.relative(parent, child);
2398
- return relative === "" || !relative.startsWith("..") && !path2.isAbsolute(relative);
2841
+ var pathFlavor = (platform) => platform === "win32" ? path3.win32 : path3.posix;
2842
+ var foldCase = (value, platform) => platform === "win32" || platform === "darwin" ? value.toLowerCase() : value;
2843
+ function isInside(child, parent, platform = process.platform) {
2844
+ const paths = pathFlavor(platform);
2845
+ const relative = paths.relative(foldCase(parent, platform), foldCase(child, platform));
2846
+ return relative === "" || !paths.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${paths.sep}`);
2847
+ }
2848
+ function isSamePath(a, b) {
2849
+ return isInside(a, b) && isInside(b, a);
2399
2850
  }
2400
2851
  function realTarget(target) {
2401
- let current = path2.resolve(target);
2852
+ let current = path3.resolve(target);
2402
2853
  const rest = [];
2403
2854
  for (;; ) {
2404
2855
  try {
2405
- return path2.join(fs2.realpathSync(current), ...rest.reverse());
2856
+ return path3.join(fs3.realpathSync(current), ...rest.reverse());
2406
2857
  } catch {
2407
- const parent = path2.dirname(current);
2858
+ const parent = path3.dirname(current);
2408
2859
  if (parent === current)
2409
- return path2.join(current, ...rest.reverse());
2410
- rest.push(path2.basename(current));
2860
+ return path3.join(current, ...rest.reverse());
2861
+ rest.push(path3.basename(current));
2411
2862
  current = parent;
2412
2863
  }
2413
2864
  }
2414
2865
  }
2415
-
2416
- class ExecuteFileAccessError extends Error {
2417
- name = "ExecuteFileAccessError";
2866
+ function browseDirectories() {
2867
+ return [...new Set([
2868
+ configRoot2(),
2869
+ dataRoot(),
2870
+ stateRoot(),
2871
+ cacheRoot(),
2872
+ ...Object.values(defaultRoots()),
2873
+ ...legacyRoots()
2874
+ ])];
2418
2875
  }
2419
- function assertExecuteFilePath(target, operation) {
2876
+ function isInstallSibling(target, binary, platform = process.platform) {
2877
+ const paths = pathFlavor(platform);
2878
+ const folder = foldCase(paths.dirname(binary), platform);
2879
+ const relative = paths.relative(folder, foldCase(target, platform));
2880
+ if (relative === "" || paths.isAbsolute(relative))
2881
+ return false;
2882
+ const [first] = relative.split(paths.sep);
2883
+ const name = foldCase(paths.basename(binary), platform);
2884
+ if (!first?.startsWith(`${name}.`))
2885
+ return false;
2886
+ const staged = first.slice(name.length + 1);
2887
+ return staged === "new" || staged.startsWith("old-") || staged.startsWith("migrate-") || /^\d+\.new$/.test(staged);
2888
+ }
2889
+ function isBinaryOrStaging(target, binary, platform) {
2890
+ const resolved = realTarget(binary);
2891
+ const stagedAt = path3.join(realTarget(path3.dirname(binary)), path3.basename(binary));
2892
+ return isInside(target, resolved, platform) || isInside(target, stagedAt, platform) || isInstallSibling(target, resolved, platform) || isInstallSibling(target, stagedAt, platform);
2893
+ }
2894
+ function browseOwnedDirectories() {
2895
+ return browseDirectories().map((root) => realTarget(root));
2896
+ }
2897
+ function isBrowseOwned(target, platform = process.platform, browse = browseOwnedDirectories()) {
2898
+ if (browse.some((root) => isInside(target, root, platform)))
2899
+ return true;
2900
+ return [installedBinaryPath(), installerBinaryPath()].some((binary) => isBinaryOrStaging(target, binary, platform));
2901
+ }
2902
+ function assertExecuteFilePath(target, operation, options = {}) {
2420
2903
  if (typeof target !== "string" || target.length === 0) {
2421
2904
  throw new ExecuteFileAccessError(`${operation}: file paths must be non-empty strings`);
2422
2905
  }
2423
- const roots = executeFileRoots();
2906
+ const roots = options.roots ?? executeFileRoots();
2424
2907
  const describeRoots = () => `${roots.join(", ")} (add more with ${fileRootsEnvironmentVariable})`;
2425
- if (!path2.isAbsolute(target)) {
2908
+ if (!path3.isAbsolute(target)) {
2426
2909
  throw new ExecuteFileAccessError(`${operation}: use an absolute path inside ${describeRoots()}, for example files.path("name.png")`);
2427
2910
  }
2428
2911
  const resolved = realTarget(target);
2429
- const data = realTarget(dataRoot());
2430
- if (isInside(resolved, data)) {
2431
- throw new ExecuteFileAccessError(`${operation}: ${target} is inside browse's data directory, which execute code cannot access`);
2912
+ if (isBrowseOwned(resolved, process.platform, options.browseOwned)) {
2913
+ throw new ExecuteFileAccessError(`${operation}: ${target} is inside browse's own files, which execute code cannot access`);
2432
2914
  }
2433
2915
  if (!roots.some((root) => isInside(resolved, root))) {
2434
2916
  throw new ExecuteFileAccessError(`${operation}: ${target} is outside the execute file roots ${describeRoots()}. Set ${allowNodeEnvironmentVariable}=1 for unrestricted file access.`);
2435
2917
  }
2436
2918
  const root = roots.filter((root) => isInside(resolved, root)).sort((a, b) => b.length - a.length)[0];
2437
- const rootStat = fs2.statSync(root);
2919
+ const rootStat = fs3.statSync(root);
2438
2920
  if (process.getuid && (rootStat.mode & 18) !== 0 && (rootStat.mode & 512) === 0) {
2439
2921
  throw new ExecuteFileAccessError(`${operation}: shared writable roots must have the sticky bit set`);
2440
2922
  }
2441
- let spelling = path2.resolve(target);
2923
+ let spelling = path3.resolve(target);
2442
2924
  for (;; ) {
2443
2925
  try {
2444
- const stat = fs2.lstatSync(spelling);
2926
+ const stat = fs3.lstatSync(spelling);
2445
2927
  if (stat.isSymbolicLink()) {
2446
- const real = fs2.realpathSync(spelling);
2928
+ const real = fs3.realpathSync(spelling);
2447
2929
  if (stat.uid !== 0 || !roots.some((root) => isInside(root, real))) {
2448
2930
  throw new ExecuteFileAccessError(`${operation}: symlink paths are not available in execute code`);
2449
2931
  }
@@ -2452,7 +2934,7 @@ function assertExecuteFilePath(target, operation) {
2452
2934
  if (error.code !== "ENOENT")
2453
2935
  throw error;
2454
2936
  }
2455
- const parent = path2.dirname(spelling);
2937
+ const parent = path3.dirname(spelling);
2456
2938
  if (parent === spelling)
2457
2939
  break;
2458
2940
  spelling = parent;
@@ -2461,7 +2943,7 @@ function assertExecuteFilePath(target, operation) {
2461
2943
  while (isInside(current, root)) {
2462
2944
  let stat;
2463
2945
  try {
2464
- stat = fs2.lstatSync(current);
2946
+ stat = fs3.lstatSync(current);
2465
2947
  } catch (error) {
2466
2948
  if (error.code !== "ENOENT")
2467
2949
  throw error;
@@ -2476,24 +2958,88 @@ function assertExecuteFilePath(target, operation) {
2476
2958
  }
2477
2959
  if (current === root)
2478
2960
  break;
2479
- current = path2.dirname(current);
2961
+ current = path3.dirname(current);
2480
2962
  }
2481
- const parent = path2.dirname(resolved);
2482
- if (parent === root && process.getuid) {
2483
- const stat = fs2.statSync(parent);
2963
+ const parent = path3.dirname(resolved);
2964
+ const isFilesDirectory = options.directory === true && isSamePath(resolved, executeFilesDirectory());
2965
+ if (parent === root && process.getuid && !isFilesDirectory) {
2966
+ const stat = fs3.statSync(parent);
2484
2967
  if (stat.uid !== process.getuid() || (stat.mode & 18) !== 0) {
2485
2968
  throw new ExecuteFileAccessError(`${operation}: use a private subdirectory such as files.dir, not a shared temporary directory`);
2486
2969
  }
2487
2970
  }
2488
2971
  return resolved;
2489
2972
  }
2973
+ function executeFileRootOf(resolved, roots = executeFileRoots()) {
2974
+ return roots.find((root) => isSamePath(resolved, root));
2975
+ }
2976
+ function assertExecuteFilePathNotRoot(target, operation, options = {}) {
2977
+ const resolved = assertExecuteFilePath(target, operation, options);
2978
+ if (executeFileRootOf(resolved, options.roots) !== undefined) {
2979
+ throw new ExecuteFileAccessError(`${operation}: ${target} is an execute file root; use a path inside it`);
2980
+ }
2981
+ return resolved;
2982
+ }
2983
+ function checkUploadValue(value, method) {
2984
+ const options = { roots: executeFileRoots(), browseOwned: browseOwnedDirectories() };
2985
+ const assertPath = (target, operation) => assertExecuteFilePathNotRoot(target, operation, options);
2986
+ const checkEntry = (target, operation) => assertExecuteFilePath(target, operation, options);
2987
+ return checkFileInputValue(value, method, assertPath, checkEntry);
2988
+ }
2989
+ function isStreamReceiver(receiver) {
2990
+ try {
2991
+ return receiver instanceof stream.Stream;
2992
+ } catch {
2993
+ return false;
2994
+ }
2995
+ }
2996
+ function isIteratorReceiver(receiver) {
2997
+ try {
2998
+ const Iterator = globalThis.Iterator;
2999
+ return typeof Iterator === "function" && receiver instanceof Iterator;
3000
+ } catch {
3001
+ return false;
3002
+ }
3003
+ }
3004
+ function isBrowserReceiver(receiver) {
3005
+ if (receiver === null || typeof receiver !== "object" || util3.types.isProxy(receiver))
3006
+ return false;
3007
+ try {
3008
+ const prototype = Object.getPrototypeOf(receiver);
3009
+ const name = prototype?.constructor?.name;
3010
+ return typeof name === "string" && name.replace(/\d+$/, "") === "Browser";
3011
+ } catch {
3012
+ return false;
3013
+ }
3014
+ }
3015
+ function assertExecuteFileInputPath(target, operation) {
3016
+ const resolved = assertExecuteFilePathNotRoot(target, operation);
3017
+ let stat;
3018
+ try {
3019
+ stat = fs3.lstatSync(resolved);
3020
+ } catch (error) {
3021
+ if (error.code !== "ENOENT")
3022
+ throw error;
3023
+ }
3024
+ if (stat?.isDirectory()) {
3025
+ throw new ExecuteFileAccessError(`${operation}: ${target} is a directory; use a file inside the execute file roots`);
3026
+ }
3027
+ return resolved;
3028
+ }
3029
+ function assertExecuteDownloadDirectory(target, operation) {
3030
+ const resolved = assertExecuteFilePath(target, operation, { directory: true });
3031
+ if (executeFileRootOf(resolved) !== undefined) {
3032
+ throw new ExecuteFileAccessError(`${operation}: ${target} is an execute file root; use a subfolder such as files.path("downloads")`);
3033
+ }
3034
+ return resolved;
3035
+ }
2490
3036
  async function openExecuteFile(target, write) {
2491
3037
  const operation = write ? "files.write" : "files.read";
2492
3038
  const resolved = assertExecuteFilePath(target, operation);
2493
3039
  if (write)
2494
- await fsPromises.mkdir(path2.dirname(resolved), { recursive: true, mode: 448 });
3040
+ await fsPromises.mkdir(path3.dirname(resolved), { recursive: true, mode: 448 });
2495
3041
  assertExecuteFilePath(resolved, operation);
2496
- const handle = await fsPromises.open(resolved, fs2.constants.O_NOFOLLOW | fs2.constants.O_NONBLOCK | (write ? fs2.constants.O_WRONLY | fs2.constants.O_CREAT : fs2.constants.O_RDONLY), 384);
3042
+ const handle = await fsPromises.open(resolved, fs3.constants.O_NOFOLLOW | fs3.constants.O_NONBLOCK | (write ? fs3.constants.O_WRONLY | fs3.constants.O_CREAT : fs3.constants.O_RDONLY), 384);
2497
3043
  try {
2498
3044
  const stat = await handle.stat();
2499
3045
  const current = await fsPromises.lstat(resolved);
@@ -2511,7 +3057,7 @@ async function openExecuteFile(target, write) {
2511
3057
  }
2512
3058
  function createExecuteFiles() {
2513
3059
  const dir = executeFilesDirectory();
2514
- const resolveTarget = (target) => path2.isAbsolute(target) ? target : path2.join(dir, target);
3060
+ const resolveTarget = (target) => path3.isAbsolute(target) ? target : path3.join(dir, target);
2515
3061
  return {
2516
3062
  dir,
2517
3063
  roots: executeFileRoots(),
@@ -2542,65 +3088,166 @@ function createExecuteFiles() {
2542
3088
  }
2543
3089
  };
2544
3090
  }
2545
- var fileOptionMethods = new Set([
2546
- "screenshot",
2547
- "pdf",
2548
- "storageState",
2549
- "start",
2550
- "stop",
2551
- "startChunk",
2552
- "stopChunk",
2553
- "startTracing",
2554
- "stopTracing",
2555
- "addScriptTag",
2556
- "addStyleTag",
2557
- "addInitScript",
2558
- "fulfill",
2559
- "newContext",
2560
- "newPage",
2561
- "routeFromHAR",
2562
- "screenshotWithLabels",
2563
- "screenshotDiff"
2564
- ]);
2565
- var fileOptionKeys = new Set(["path", "dir", "har", "storageState"]);
2566
- var alwaysFileOptionKeys = new Set(["outputPath", "baseline", "certPath", "keyPath", "pfxPath", "tracesDir", "downloadsPath"]);
2567
- var forbiddenOptionKeys = new Set(["executablePath", "recordHar", "recordVideo"]);
2568
- function checkFileOptions(value, method, includeMethodKeys, depth = 0) {
2569
- if (depth > 4 || value === null || typeof value !== "object")
2570
- return;
2571
- if (Array.isArray(value)) {
2572
- for (const item of value)
2573
- checkFileOptions(item, method, includeMethodKeys, depth + 1);
3091
+ var startedTraces = new WeakMap;
3092
+ var isObject2 = (value) => value !== null && typeof value === "object";
3093
+ function fileExists(target) {
3094
+ try {
3095
+ fs3.lstatSync(target);
3096
+ return true;
3097
+ } catch (error) {
3098
+ if (error.code === "ENOENT")
3099
+ return false;
3100
+ throw error;
3101
+ }
3102
+ }
3103
+ function outputDirectoryError(directory) {
3104
+ return new ExecuteFileAccessError(`file outputs must use real, owned directories without group/world write access, not ${directory}`);
3105
+ }
3106
+ function pinPrivateDirectory(directory, uid) {
3107
+ const descriptor = fs3.openSync(directory, fs3.constants.O_RDONLY | fs3.constants.O_DIRECTORY | fs3.constants.O_NOFOLLOW);
3108
+ try {
3109
+ const opened = fs3.fstatSync(descriptor);
3110
+ const current = fs3.lstatSync(directory);
3111
+ if (!opened.isDirectory() || opened.uid !== uid || current.isSymbolicLink() || current.dev !== opened.dev || current.ino !== opened.ino) {
3112
+ throw outputDirectoryError(directory);
3113
+ }
3114
+ if ((opened.mode & 511) !== 448)
3115
+ fs3.fchmodSync(descriptor, 448);
3116
+ } finally {
3117
+ fs3.closeSync(descriptor);
3118
+ }
3119
+ }
3120
+ function ensureExecuteOutputDirectory(directory) {
3121
+ const resolved = path3.resolve(directory);
3122
+ const roots = executeFileRoots();
3123
+ const root = roots.filter((candidate) => isInside(resolved, candidate)).sort((a, b) => b.length - a.length)[0];
3124
+ if (root === undefined)
3125
+ throw outputDirectoryError(resolved);
3126
+ const uid = process.getuid?.();
3127
+ const missing = [];
3128
+ let current = resolved;
3129
+ for (;; ) {
3130
+ let stat;
3131
+ try {
3132
+ stat = fs3.lstatSync(current);
3133
+ } catch (error) {
3134
+ if (error.code !== "ENOENT")
3135
+ throw error;
3136
+ }
3137
+ if (stat) {
3138
+ if (!stat.isDirectory() || stat.isSymbolicLink())
3139
+ throw outputDirectoryError(current);
3140
+ if (!isSamePath(current, root) && uid !== undefined && (stat.uid !== uid || (stat.mode & 18) !== 0))
3141
+ throw outputDirectoryError(current);
3142
+ } else if (isSamePath(current, root)) {
3143
+ throw outputDirectoryError(current);
3144
+ } else {
3145
+ missing.push(current);
3146
+ }
3147
+ if (isSamePath(current, root))
3148
+ break;
3149
+ const parent = path3.dirname(current);
3150
+ if (parent === current)
3151
+ throw outputDirectoryError(current);
3152
+ current = parent;
3153
+ }
3154
+ for (const step of missing.reverse()) {
3155
+ let created = false;
3156
+ try {
3157
+ fs3.mkdirSync(step, { mode: 448 });
3158
+ created = true;
3159
+ } catch (error) {
3160
+ if (error.code !== "EEXIST")
3161
+ throw error;
3162
+ }
3163
+ if (created && uid !== undefined && process.platform !== "win32")
3164
+ pinPrivateDirectory(step, uid);
3165
+ const stat = fs3.lstatSync(step);
3166
+ if (!stat.isDirectory() || stat.isSymbolicLink() || uid !== undefined && (stat.uid !== uid || (stat.mode & 18) !== 0)) {
3167
+ throw outputDirectoryError(step);
3168
+ }
3169
+ }
3170
+ }
3171
+ function secureExecuteFileOutputs(outputs) {
3172
+ const uid = process.getuid?.();
3173
+ if (uid === undefined)
2574
3174
  return;
3175
+ const operation = "execute file output";
3176
+ for (const output of outputs) {
3177
+ if (output.existed)
3178
+ continue;
3179
+ try {
3180
+ const before = fs3.lstatSync(output.path);
3181
+ if (!before.isFile() || before.uid !== uid || before.nlink !== 1)
3182
+ continue;
3183
+ const descriptor = fs3.openSync(output.path, fs3.constants.O_RDONLY | fs3.constants.O_NOFOLLOW | fs3.constants.O_NONBLOCK);
3184
+ try {
3185
+ const opened = fs3.fstatSync(descriptor);
3186
+ const current = fs3.lstatSync(output.path);
3187
+ if (!opened.isFile() || opened.uid !== uid || opened.nlink !== 1 || current.isSymbolicLink() || current.dev !== opened.dev || current.ino !== opened.ino)
3188
+ continue;
3189
+ assertExecuteFilePath(path3.join(path3.dirname(output.path), `.execute-output-${crypto3.randomUUID()}`), operation);
3190
+ fs3.fchmodSync(descriptor, 384);
3191
+ assertExecuteFilePath(output.path, operation);
3192
+ if (process.platform === "linux")
3193
+ assertExecuteFilePath(fs3.realpathSync(`/proc/self/fd/${descriptor}`), operation);
3194
+ } finally {
3195
+ fs3.closeSync(descriptor);
3196
+ }
3197
+ } catch {}
2575
3198
  }
2576
- const prototype = Object.getPrototypeOf(value);
2577
- if (prototype !== Object.prototype && prototype !== null)
2578
- return;
2579
- for (const [key, item] of Object.entries(value)) {
2580
- if (forbiddenOptionKeys.has(key))
2581
- throw new ExecuteFileAccessError(`${method}: the ${key} option is not available in execute code`);
2582
- if (typeof item === "string" && (alwaysFileOptionKeys.has(key) || includeMethodKeys && fileOptionKeys.has(key))) {
2583
- Reflect.set(value, key, assertExecuteFilePath(item, `${method}({ ${key} })`));
2584
- } else {
2585
- checkFileOptions(item, method, includeMethodKeys, depth + 1);
2586
- }
3199
+ }
3200
+ function prepareExecuteFileOutputs(call) {
3201
+ const trace = call.trace;
3202
+ if (trace !== undefined) {
3203
+ if (trace.path === undefined)
3204
+ startedTraces.delete(trace.receiver);
3205
+ else
3206
+ startedTraces.set(trace.receiver, trace.path);
3207
+ }
3208
+ const outputs = [];
3209
+ for (const candidate of call.outputs) {
3210
+ assertExecuteFilePath(candidate.path, "execute file output", { directory: candidate.directory === true });
3211
+ ensureExecuteOutputDirectory(candidate.directory === true ? candidate.path : path3.dirname(candidate.path));
3212
+ const resolved = assertExecuteFilePath(candidate.path, "execute file output", { directory: candidate.directory === true });
3213
+ if (candidate.directory === true)
3214
+ continue;
3215
+ outputs.push({ path: resolved, existed: fileExists(resolved) });
2587
3216
  }
3217
+ const stop = call.traceStop;
3218
+ return stop === undefined ? { outputs } : { outputs, forgetTrace: () => startedTraces.delete(stop) };
2588
3219
  }
2589
- function checkFileStrings(value, method) {
2590
- if (typeof value === "string")
2591
- assertExecuteFilePath(value, method);
2592
- else if (Array.isArray(value)) {
2593
- for (const item of value)
2594
- if (typeof item === "string")
2595
- assertExecuteFilePath(item, method);
3220
+ function completeExecuteFileOutputs(result, prepared) {
3221
+ const settle = (resolved) => {
3222
+ if (resolved)
3223
+ prepared.forgetTrace?.();
3224
+ secureExecuteFileOutputs(prepared.outputs);
3225
+ };
3226
+ if (prepared.outputs.length === 0 && prepared.forgetTrace === undefined)
3227
+ return result;
3228
+ if (!util3.types.isPromise(result)) {
3229
+ settle(true);
3230
+ return result;
2596
3231
  }
3232
+ return result.then((value) => {
3233
+ settle(true);
3234
+ return value;
3235
+ }, (error) => {
3236
+ settle(false);
3237
+ throw error;
3238
+ });
2597
3239
  }
2598
- var promiseReturningNames = new Set([...fileOptionMethods, "setInputFiles", "setFiles", "saveAs", "bringToFront", "send"]);
3240
+ var promiseReturningNames = new Set([...fileOptionMethods, "setInputFiles", "setFiles", "saveAs", "bringToFront"]);
2599
3241
  function returnsPromise(fn) {
2600
- return util.types.isAsyncFunction(fn) || promiseReturningNames.has(typeof fn.name === "string" ? fn.name.replace(/^bound /, "") : "");
3242
+ return util3.types.isAsyncFunction(fn) || promiseReturningNames.has(typeof fn.name === "string" ? fn.name.replace(/^bound /, "") : "");
2601
3243
  }
2602
3244
  function checkHostCall(fn, receiver, args) {
2603
3245
  const name = typeof fn.name === "string" ? fn.name.replace(/^bound /, "") : "";
3246
+ const setArgument = (index, value) => {
3247
+ args[index] = value;
3248
+ };
3249
+ const sendMethod = name === "send" ? args[0] : undefined;
3250
+ const cdpSessionSend = name === "send" && isCdpSession(receiver);
2604
3251
  if (receiver !== null && typeof receiver === "object") {
2605
3252
  const constructor = Reflect.getOwnPropertyDescriptor(receiver, "constructor")?.value;
2606
3253
  if (typeof constructor === "function" && constructor.prototype === receiver) {
@@ -2610,18 +3257,81 @@ function checkHostCall(fn, receiver, args) {
2610
3257
  if (name === "fetch" || name === "routeFromHAR" || name === "fulfill" && args.some((arg) => arg !== null && typeof arg === "object" && ("response" in arg))) {
2611
3258
  throw new Error(`${name}: Node-side requests and response/HAR replay are not available in execute code; use browser requests or route.fulfill({ body })`);
2612
3259
  }
2613
- if ((name === "bringToFront" || name === "send" && args[0] === "Page.bringToFront") && !executeAllowsForeground()) {
3260
+ if (name === "bind" && isBrowserReceiver(receiver)) {
3261
+ throw new ExecuteFileAccessError("bind: starting a browser server is not available in execute code");
3262
+ }
3263
+ if ((name === "bringToFront" || name === "send" && sendMethod === "Page.bringToFront") && !executeAllowsForeground()) {
2614
3264
  throw new Error(bringToFrontBlockedMessage);
2615
3265
  }
2616
- if (name === "setInputFiles") {
3266
+ const candidates = [];
3267
+ if (name === "send") {
3268
+ const bufferMessage = buffer2.Buffer.isBuffer(sendMethod) || util3.types.isUint8Array(sendMethod);
3269
+ if (typeof sendMethod !== "string" && (cdpSessionSend || !bufferMessage)) {
3270
+ throw new ExecuteFileAccessError(cdpSessionSend ? "CDPSession.send: the method must be a primitive string" : "send: the message must be a string or Buffer");
3271
+ }
3272
+ let method;
3273
+ if (typeof sendMethod === "string") {
3274
+ if (cdpSessionSend) {
3275
+ if (!isCdpMethodName(sendMethod))
3276
+ throw new ExecuteFileAccessError(`CDPSession.send: ${JSON.stringify(sendMethod)} is not a CDP method name`);
3277
+ method = sendMethod;
3278
+ } else if (isCdpMethodName(sendMethod)) {
3279
+ method = sendMethod;
3280
+ }
3281
+ }
3282
+ if (method !== undefined) {
3283
+ const sendParams = args.length > 1 ? args[1] : undefined;
3284
+ const params = sendParams === undefined ? undefined : copyCdpParameters(sendParams, method);
3285
+ if (params !== undefined)
3286
+ setArgument(1, params);
3287
+ const checked = checkCdpSend(method, params, { fileInput: assertExecuteFileInputPath, downloadDirectory: assertExecuteDownloadDirectory });
3288
+ if (checked.downloadDirectory !== undefined)
3289
+ candidates.push({ path: checked.downloadDirectory, directory: true });
3290
+ }
3291
+ } else if (name === "setInputFiles") {
2617
3292
  const isFrameLike = receiver !== null && typeof receiver === "object" && typeof receiver.goto === "function";
2618
- checkFileStrings(isFrameLike ? args[1] : args[0], "setInputFiles");
2619
- } else if (name === "setFiles" || name === "saveAs" || name === "routeFromHAR") {
2620
- checkFileStrings(args[0], name);
3293
+ if (isFrameLike)
3294
+ setArgument(1, checkUploadValue(args[1], "setInputFiles"));
3295
+ else
3296
+ setArgument(0, checkUploadValue(args[0], "setInputFiles"));
3297
+ } else if (name === "setFiles") {
3298
+ setArgument(0, checkUploadValue(args[0], name));
3299
+ } else if (name === "drop") {
3300
+ const payload = args[0];
3301
+ if (payload !== undefined && !isStreamReceiver(receiver) && !isIteratorReceiver(receiver)) {
3302
+ setArgument(0, checkDropPayload(payload, assertExecuteFileInputPath));
3303
+ }
3304
+ } else if (name === "setStorageState") {
3305
+ const value = args[0];
3306
+ if (typeof value === "string")
3307
+ setArgument(0, assertExecuteFilePathNotRoot(value, name));
3308
+ else if (value !== undefined && value !== null && !isPlainRecord2(value)) {
3309
+ throw new ExecuteFileAccessError(`${name}: storage state must be a path string or a plain object`);
3310
+ }
3311
+ } else if (name === "saveAs") {
3312
+ const target = checkFileStrings(args[0], name, assertExecuteFilePath);
3313
+ if (target !== undefined)
3314
+ candidates.push({ path: target });
3315
+ } else if (name === "routeFromHAR") {
3316
+ checkFileStrings(args[0], name, assertExecuteFilePath);
2621
3317
  }
2622
3318
  const includeMethodKeys = fileOptionMethods.has(name);
2623
- for (const arg of args)
2624
- checkFileOptions(arg, name || "call", includeMethodKeys);
3319
+ for (let index = 0;index < args.length; index += 1) {
3320
+ const methodKeys = includeMethodKeys && !(name === "addInitScript" && index === 1 && typeof args[0] === "function");
3321
+ checkFileOptions(args[index], name || "call", methodKeys, candidates, assertExecuteFilePath);
3322
+ }
3323
+ if (name === "startTracing" && isObject2(receiver)) {
3324
+ const path = isObject2(args[1]) ? Reflect.get(args[1], "path") : undefined;
3325
+ const trace = typeof path === "string" ? assertExecuteFilePath(path, "startTracing({ path })") : undefined;
3326
+ return { outputs: candidates, trace: { receiver, path: trace } };
3327
+ }
3328
+ if (name === "stopTracing" && isObject2(receiver)) {
3329
+ const remembered = startedTraces.get(receiver);
3330
+ if (remembered === undefined)
3331
+ return { outputs: candidates };
3332
+ return { outputs: [...candidates, { path: assertExecuteFilePath(remembered, "stopTracing()") }], traceStop: receiver };
3333
+ }
3334
+ return { outputs: candidates };
2625
3335
  }
2626
3336
  function pageVisibleApiWarningForName(name) {
2627
3337
  if (name === "addInitScript" || name === "exposeFunction" || name === "exposeBinding") {
@@ -2659,7 +3369,7 @@ import crypto4 from "node:crypto";
2659
3369
  import dgram from "node:dgram";
2660
3370
  import dns2 from "node:dns";
2661
3371
  import events2 from "node:events";
2662
- import fs3 from "node:fs";
3372
+ import fs4 from "node:fs";
2663
3373
  import fsPromises2 from "node:fs/promises";
2664
3374
  import http from "node:http";
2665
3375
  import http2 from "node:http2";
@@ -2668,18 +3378,74 @@ import inspector from "node:inspector";
2668
3378
  import module from "node:module";
2669
3379
  import net from "node:net";
2670
3380
  import os3 from "node:os";
3381
+ import { AsyncLocalStorage } from "node:async_hooks";
2671
3382
  import tls from "node:tls";
2672
- import util2 from "node:util";
3383
+ import util5 from "node:util";
2673
3384
  import v8 from "node:v8";
2674
3385
  import vm from "node:vm";
2675
3386
  import workerThreads from "node:worker_threads";
2676
3387
  import * as acorn from "acorn";
3388
+
3389
+ // src/execute-realm/rejection-text.ts
3390
+ import util4 from "node:util";
3391
+ var placeholder = "reason not shown";
3392
+ var nativeStackGetter = Object.getOwnPropertyDescriptor(new Error, "stack")?.get;
3393
+ function safeErrorMessage(value, maxLength = 300) {
3394
+ if (typeof value === "string")
3395
+ return value.length > 0 ? value.slice(0, maxLength) : placeholder;
3396
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || typeof value === "symbol") {
3397
+ return String(value).slice(0, maxLength);
3398
+ }
3399
+ if (!isSafeNativeError(value))
3400
+ return placeholder;
3401
+ const message = ownDataProperty(value, "message");
3402
+ return typeof message === "string" && message.length > 0 ? message.slice(0, maxLength) : placeholder;
3403
+ }
3404
+ function safeErrorStack(value) {
3405
+ if (!isSafeHostError(value))
3406
+ return;
3407
+ const descriptor = Object.getOwnPropertyDescriptor(value, "stack");
3408
+ if (descriptor === undefined)
3409
+ return;
3410
+ if ("value" in descriptor)
3411
+ return typeof descriptor.value === "string" ? descriptor.value : undefined;
3412
+ if (descriptor.get === undefined || descriptor.get !== nativeStackGetter)
3413
+ return;
3414
+ try {
3415
+ const stack = descriptor.get.call(value);
3416
+ return typeof stack === "string" ? stack : undefined;
3417
+ } catch {
3418
+ return;
3419
+ }
3420
+ }
3421
+ function isSafeNativeError(value) {
3422
+ return typeof value === "object" && value !== null && !util4.types.isProxy(value) && util4.types.isNativeError(value);
3423
+ }
3424
+ function isSafeHostError(value) {
3425
+ if (!isSafeNativeError(value))
3426
+ return false;
3427
+ let prototype = Object.getPrototypeOf(value);
3428
+ for (let depth = 0;prototype !== null && depth < 32; depth += 1) {
3429
+ if (prototype === Error.prototype)
3430
+ return true;
3431
+ if (util4.types.isProxy(prototype))
3432
+ return false;
3433
+ prototype = Object.getPrototypeOf(prototype);
3434
+ }
3435
+ return false;
3436
+ }
3437
+ function ownDataProperty(value, key) {
3438
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
3439
+ return descriptor !== undefined && "value" in descriptor ? descriptor.value : undefined;
3440
+ }
3441
+
3442
+ // src/execute-realm/membrane-policy.ts
2677
3443
  var deniedHostValues = new Map([
2678
3444
  [process, "process"],
2679
3445
  [globalThis, "the relay's global object"],
2680
- [fs3, "fs"],
3446
+ [fs4, "fs"],
2681
3447
  [fsPromises2, "fs/promises"],
2682
- [fs3.promises, "fs/promises"],
3448
+ [fs4.promises, "fs/promises"],
2683
3449
  [childProcess, "child_process"],
2684
3450
  [cluster, "cluster"],
2685
3451
  [dgram, "dgram"],
@@ -2697,9 +3463,9 @@ var deniedHostValues = new Map([
2697
3463
  [workerThreads, "worker_threads"],
2698
3464
  [globalThis.fetch, "Node fetch"],
2699
3465
  [eval, "eval"],
2700
- [util2.inspect, "host object inspection"],
2701
- [util2.format, "host object formatting"],
2702
- [util2.formatWithOptions, "host object formatting"],
3466
+ [util5.inspect, "host object inspection"],
3467
+ [util5.format, "host object formatting"],
3468
+ [util5.formatWithOptions, "host object formatting"],
2703
3469
  [crypto4.setEngine, "loading native crypto engines"],
2704
3470
  [events2.setMaxListeners, "changing shared event-emitter defaults or prototypes"],
2705
3471
  ...[crypto4.pbkdf2Sync, crypto4.scryptSync, crypto4.hkdfSync, crypto4.generateKeyPairSync, crypto4.generateKeySync, crypto4.generatePrimeSync, crypto4.checkPrimeSync].map((fn) => [fn, `crypto.${fn.name} (blocks the relay; use the async version)`])
@@ -2805,56 +3571,111 @@ function isObjectLike(value) {
2805
3571
  return typeof value === "object" && value !== null || typeof value === "function";
2806
3572
  }
2807
3573
  var isHiddenKey = (key) => typeof key === "string" && key.startsWith("_");
2808
- var activeRealm;
2809
- var promiseRealms = new WeakMap;
3574
+ var activeOwner;
3575
+ var rejectionContext = new AsyncLocalStorage;
3576
+ var promiseOwners = new WeakMap;
2810
3577
  var stopPromiseHook;
2811
- function trackPromisesOf(realm) {
2812
- const previous = activeRealm;
2813
- activeRealm = realm;
2814
- if (process.versions.bun) {
2815
- const entered = { realm, at: Date.now() };
2816
- lastRealm = entered;
2817
- return () => {
2818
- activeRealm = previous;
2819
- entered.at = Date.now();
2820
- };
2821
- }
2822
- if (!stopPromiseHook) {
2823
- stopPromiseHook = v8.promiseHooks.createHook({ init(promise) {
2824
- if (activeRealm)
2825
- promiseRealms.set(promise, activeRealm);
3578
+ var promiseHookUsers = 0;
3579
+ function enterRejectionOwner(owner) {
3580
+ const previous = activeOwner;
3581
+ activeOwner = owner;
3582
+ return () => {
3583
+ activeOwner = previous;
3584
+ };
3585
+ }
3586
+ function runWithRejectionOwner(owner, run) {
3587
+ return rejectionContext.run(owner, () => {
3588
+ const restore = enterRejectionOwner(owner);
3589
+ try {
3590
+ return run();
3591
+ } finally {
3592
+ restore();
3593
+ }
3594
+ });
3595
+ }
3596
+ function retainPromiseHook() {
3597
+ promiseHookUsers += 1;
3598
+ if (promiseHookUsers === 1) {
3599
+ stopPromiseHook = v8.promiseHooks.createHook({ init(promise, parent) {
3600
+ const owner = activeOwner ?? rejectionContext.getStore() ?? (parent ? promiseOwners.get(parent) : undefined);
3601
+ if (owner)
3602
+ promiseOwners.set(promise, owner);
2826
3603
  } });
2827
3604
  }
3605
+ let released = false;
2828
3606
  return () => {
2829
- activeRealm = previous;
2830
- if (!activeRealm && stopPromiseHook) {
3607
+ if (released)
3608
+ return;
3609
+ released = true;
3610
+ promiseHookUsers -= 1;
3611
+ if (promiseHookUsers === 0 && stopPromiseHook) {
2831
3612
  stopPromiseHook();
2832
3613
  stopPromiseHook = undefined;
2833
3614
  }
2834
3615
  };
2835
3616
  }
3617
+ function trackPromisesOf(owner) {
3618
+ const restoreOwner = enterRejectionOwner(owner);
3619
+ if (process.versions.bun) {
3620
+ const entered = { owner, at: Date.now() };
3621
+ lastOwner = entered;
3622
+ return () => {
3623
+ restoreOwner();
3624
+ entered.at = Date.now();
3625
+ };
3626
+ }
3627
+ const releaseHook = retainPromiseHook();
3628
+ return () => {
3629
+ restoreOwner();
3630
+ releaseHook();
3631
+ };
3632
+ }
2836
3633
  var realmsByPromisePrototype = new WeakMap;
2837
- var lastRealm;
2838
- var lastRealmWindowMs = 1000;
3634
+ var lastOwner;
3635
+ var lastOwnerWindowMs = 1000;
2839
3636
  function registerRealmPromisePrototype(prototype, realm) {
2840
3637
  if (process.versions.bun)
2841
3638
  realmsByPromisePrototype.set(prototype, realm);
2842
3639
  }
2843
- function bunRejectionRealm(promise) {
2844
- const byPrototype = realmsByPromisePrototype.get(Object.getPrototypeOf(promise));
2845
- if (byPrototype)
2846
- return byPrototype;
2847
- if (!lastRealm || lastRealm.realm.isStopped)
3640
+ function bunRejectionOwner(promise) {
3641
+ if (!lastOwner || lastOwner.owner.isStopped)
2848
3642
  return;
2849
- return activeRealm === lastRealm.realm || Date.now() - lastRealm.at <= lastRealmWindowMs ? lastRealm.realm : undefined;
3643
+ return activeOwner === lastOwner.owner || Date.now() - lastOwner.at <= lastOwnerWindowMs ? lastOwner.owner : undefined;
2850
3644
  }
2851
- function handleExecuteRealmRejection(promise) {
2852
- const realm = promiseRealms.get(promise) ?? (process.versions.bun ? bunRejectionRealm(promise) : undefined);
2853
- if (!realm)
3645
+ function handleExecuteRealmRejection(promise, reason) {
3646
+ const byPrototype = process.versions.bun ? realmsByPromisePrototype.get(Object.getPrototypeOf(promise)) : undefined;
3647
+ const exact = promiseOwners.get(promise) ?? byPrototype;
3648
+ const owner = exact ?? (process.versions.bun ? bunRejectionOwner(promise) : undefined);
3649
+ if (!owner)
2854
3650
  return false;
2855
- realm.dispose(new Error("Unhandled execute rejection; JavaScript state will reset before the next execute"));
3651
+ owner.handleUnhandledRejection(reason, exact !== undefined);
2856
3652
  return true;
2857
3653
  }
3654
+ function unhandledExecuteRejectionWarning(detail, certain) {
3655
+ if (!certain) {
3656
+ return "Execute code may have started a promise that rejected and was never awaited. The rejection was contained and the relay kept running; await the promise or handle its rejection to return the error from execute.";
3657
+ }
3658
+ return `Execute code started a promise that rejected and was never awaited: ${detail}. The rejection was contained and the relay kept running; await the promise or handle its rejection to return the error from execute.`;
3659
+ }
3660
+ function handleRealmUnhandledRejection(realm, cause, certain, warn, pending) {
3661
+ if (realm.isStopped)
3662
+ return;
3663
+ const description = certain ? rejectionDescription(realm, cause) : "a rejected promise";
3664
+ if (!pending) {
3665
+ try {
3666
+ warn?.(unhandledExecuteRejectionWarning(description, certain));
3667
+ } catch {}
3668
+ }
3669
+ realm.dispose(new Error(`Unhandled execute rejection: ${description}; JavaScript state will reset before the next execute`));
3670
+ }
3671
+ function rejectionDescription(realm, cause) {
3672
+ if (isObjectLike(cause)) {
3673
+ const host = realm.hostValueForSandboxValue(cause);
3674
+ if (host !== undefined)
3675
+ return safeErrorMessage(host);
3676
+ }
3677
+ return safeErrorMessage(cause);
3678
+ }
2858
3679
  var thrownByRealm = new WeakMap;
2859
3680
  function tagThrownByRealm(value, realm) {
2860
3681
  if (!thrownByRealm.has(value))
@@ -2987,11 +3808,13 @@ class ExecuteRealm {
2987
3808
  entryScript;
2988
3809
  global;
2989
3810
  onHostCall;
3811
+ onUnhandledRejection;
2990
3812
  refuseDynamicImport = () => {
2991
3813
  throw new this.SandboxError("import() is not available in execute code");
2992
3814
  };
2993
3815
  constructor(options = {}) {
2994
3816
  this.onHostCall = options.onHostCall;
3817
+ this.onUnhandledRejection = options.onUnhandledRejection;
2995
3818
  const importModuleDynamically = this.refuseDynamicImport;
2996
3819
  const dontContextify = vm3.constants?.DONT_CONTEXTIFY;
2997
3820
  this.context = vm3.createContext(dontContextify ?? Object.create(null), {
@@ -3036,6 +3859,12 @@ class ExecuteRealm {
3036
3859
  get isStopped() {
3037
3860
  return this.stopped !== undefined;
3038
3861
  }
3862
+ handleUnhandledRejection(cause, certain) {
3863
+ handleRealmUnhandledRejection(this, cause, certain, this.onUnhandledRejection, this.pendingRuns.size > 0);
3864
+ }
3865
+ hostValueForSandboxValue(value) {
3866
+ return isObjectLike(value) ? this.hostBySandboxProxy.get(value) : undefined;
3867
+ }
3039
3868
  enter(entry) {
3040
3869
  if (this.stopped)
3041
3870
  throw this.stopped;
@@ -3134,7 +3963,7 @@ class ExecuteRealm {
3134
3963
  toSandbox(value, seen = new Map) {
3135
3964
  if (!isObjectLike(value))
3136
3965
  return value;
3137
- if (value === Buffer.allocUnsafe || value === Buffer.allocUnsafeSlow || value === buffer2.SlowBuffer)
3966
+ if (value === Buffer.allocUnsafe || value === Buffer.allocUnsafeSlow || value === buffer3.SlowBuffer)
3138
3967
  return this.toSandbox(Buffer.alloc);
3139
3968
  if (this.hostBySandboxProxy.has(value))
3140
3969
  return value;
@@ -3154,7 +3983,7 @@ class ExecuteRealm {
3154
3983
  throw this.sandboxError(`${denied} is not available in execute code. Set ${allowNodeEnvironmentVariable}=1 for full Node access.`);
3155
3984
  if (this.isSandboxNative(value))
3156
3985
  return value;
3157
- if (util3.types.isPromise(value))
3986
+ if (util6.types.isPromise(value))
3158
3987
  return this.toSandboxPromise(value);
3159
3988
  if (Buffer.isBuffer(value)) {
3160
3989
  const copy = Buffer.alloc(value.length);
@@ -3163,11 +3992,11 @@ class ExecuteRealm {
3163
3992
  this.sandboxProxyByHost.set(value, proxy);
3164
3993
  return proxy;
3165
3994
  }
3166
- if (util3.types.isArrayBuffer(value)) {
3995
+ if (util6.types.isArrayBuffer(value)) {
3167
3996
  const SandboxUint8Array = this.sandboxIntrinsics.Uint8Array;
3168
3997
  return new SandboxUint8Array(new Uint8Array(value)).buffer;
3169
3998
  }
3170
- if (util3.types.isTypedArray(value) && !Buffer.isBuffer(value)) {
3999
+ if (util6.types.isTypedArray(value) && !Buffer.isBuffer(value)) {
3171
4000
  const name = Object.prototype.toString.call(value).slice(8, -1);
3172
4001
  const Constructor = this.sandboxIntrinsics[name] ?? this.sandboxIntrinsics.Uint8Array;
3173
4002
  return new Constructor(value);
@@ -3177,7 +4006,7 @@ class ExecuteRealm {
3177
4006
  throw this.sandboxError(deniedClass);
3178
4007
  if (!this.forceProxy.has(value) && typeof value === "object") {
3179
4008
  const prototype = Reflect.getPrototypeOf(value);
3180
- if (Array.isArray(value) && prototype === Array.prototype || util3.types.isArgumentsObject(value)) {
4009
+ if (Array.isArray(value) && prototype === Array.prototype || util6.types.isArgumentsObject(value)) {
3181
4010
  const output = [];
3182
4011
  Reflect.setPrototypeOf(output, this.sandboxArrayPrototype);
3183
4012
  seen.set(value, output);
@@ -3186,7 +4015,7 @@ class ExecuteRealm {
3186
4015
  output[index] = this.toSandbox(array[index], seen);
3187
4016
  return output;
3188
4017
  }
3189
- if ((prototype === Object.prototype || prototype === null) && !Object.hasOwn(value, "constructor") && !util3.types.isProxy(value)) {
4018
+ if ((prototype === Object.prototype || prototype === null) && !Object.hasOwn(value, "constructor") && !util6.types.isProxy(value)) {
3190
4019
  const output = Object.create(prototype === null ? null : this.sandboxObjectPrototype);
3191
4020
  seen.set(value, output);
3192
4021
  for (const key of Object.keys(value)) {
@@ -3344,8 +4173,9 @@ class ExecuteRealm {
3344
4173
  apply(_shadow, thisArgument, args) {
3345
4174
  const hostThis = isObjectLike(thisArgument) && realm.hostBySandboxProxy.has(thisArgument) ? realm.hostBySandboxProxy.get(thisArgument) : realm.toHost(thisArgument);
3346
4175
  const hostArgs = args.map((arg) => realm.toHost(arg));
4176
+ let prepared;
3347
4177
  try {
3348
- checkHostCall(target, hostThis, hostArgs);
4178
+ prepared = prepareExecuteFileOutputs(checkHostCall(target, hostThis, hostArgs));
3349
4179
  } catch (error) {
3350
4180
  if (returnsPromise(target))
3351
4181
  return realm.SandboxPromise.reject(realm.toSandboxThrown(error));
@@ -3361,7 +4191,7 @@ class ExecuteRealm {
3361
4191
  throw realm.toSandboxThrown(error);
3362
4192
  }
3363
4193
  try {
3364
- return realm.toSandbox(result);
4194
+ return realm.toSandbox(completeExecuteFileOutputs(result, prepared));
3365
4195
  } catch (error) {
3366
4196
  throw realm.sanitizeThrown(error);
3367
4197
  }
@@ -3403,8 +4233,8 @@ class ExecuteRealm {
3403
4233
  if (!guarded) {
3404
4234
  guarded = new Proxy(host, {
3405
4235
  apply(target, receiver, args) {
3406
- checkHostCall(target, receiver, args);
3407
- return Reflect.apply(target, receiver, args);
4236
+ const prepared = prepareExecuteFileOutputs(checkHostCall(target, receiver, args));
4237
+ return completeExecuteFileOutputs(Reflect.apply(target, receiver, args), prepared);
3408
4238
  },
3409
4239
  construct(target, args, newTarget) {
3410
4240
  checkHostCall(target, undefined, args);
@@ -3438,16 +4268,16 @@ class ExecuteRealm {
3438
4268
  }
3439
4269
  }
3440
4270
  copyToHost(value, seen) {
3441
- if (util3.types.isPromise(value))
4271
+ if (util6.types.isPromise(value))
3442
4272
  return this.toHostPromise(value);
3443
- if (util3.types.isDate(value))
4273
+ if (util6.types.isDate(value))
3444
4274
  return new Date(Date.prototype.getTime.call(value));
3445
- if (util3.types.isRegExp(value)) {
4275
+ if (util6.types.isRegExp(value)) {
3446
4276
  const source = Reflect.get(value, "source");
3447
4277
  const flags = Reflect.get(value, "flags");
3448
4278
  return new RegExp(String(source), String(flags));
3449
4279
  }
3450
- if (util3.types.isNativeError(value) || value instanceof this.SandboxError) {
4280
+ if (util6.types.isNativeError(value) || value instanceof this.SandboxError) {
3451
4281
  const name = String(Reflect.get(value, "name") ?? "Error");
3452
4282
  const output = new Error(String(Reflect.get(value, "message") ?? ""));
3453
4283
  seen.set(value, output);
@@ -3465,26 +4295,26 @@ class ExecuteRealm {
3465
4295
  Object.defineProperty(output, "cause", { value: this.toHost(cause, seen), configurable: true, writable: true });
3466
4296
  return output;
3467
4297
  }
3468
- if (util3.types.isMap(value)) {
4298
+ if (util6.types.isMap(value)) {
3469
4299
  const output = new Map;
3470
4300
  seen.set(value, output);
3471
4301
  Map.prototype.forEach.call(value, (item, key) => output.set(this.toHost(key, seen), this.toHost(item, seen)));
3472
4302
  return output;
3473
4303
  }
3474
- if (util3.types.isSet(value)) {
4304
+ if (util6.types.isSet(value)) {
3475
4305
  const output = new Set;
3476
4306
  seen.set(value, output);
3477
4307
  Set.prototype.forEach.call(value, (item) => output.add(this.toHost(item, seen)));
3478
4308
  return output;
3479
4309
  }
3480
- if (util3.types.isArrayBuffer(value))
4310
+ if (util6.types.isArrayBuffer(value))
3481
4311
  return new Uint8Array(new Uint8Array(value)).buffer;
3482
- if (util3.types.isTypedArray(value)) {
4312
+ if (util6.types.isTypedArray(value)) {
3483
4313
  const name = Object.prototype.toString.call(value).slice(8, -1);
3484
4314
  const Constructor = globalThis[name] ?? Uint8Array;
3485
4315
  return new Constructor(value);
3486
4316
  }
3487
- if (Array.isArray(value) || util3.types.isArgumentsObject(value)) {
4317
+ if (Array.isArray(value) || util6.types.isArgumentsObject(value)) {
3488
4318
  const output = [];
3489
4319
  seen.set(value, output);
3490
4320
  const array = value;
@@ -3609,12 +4439,51 @@ class ExecuteRealm {
3609
4439
  }
3610
4440
 
3611
4441
  // src/execute/code-runner.ts
3612
- import fs4 from "node:fs";
4442
+ import fs5 from "node:fs";
3613
4443
  import http3 from "node:http";
3614
4444
  import https2 from "node:https";
3615
4445
  import os4 from "node:os";
3616
4446
  import * as acorn2 from "acorn";
3617
4447
 
4448
+ // src/execute/rejection-scope.ts
4449
+ var defaultRejectionOwnershipExpiryMs = 10 * 60000;
4450
+
4451
+ class ExecuteRejectionScope {
4452
+ releaseHook;
4453
+ expiry;
4454
+ expiryMs;
4455
+ onRejection;
4456
+ constructor(options = {}) {
4457
+ this.onRejection = options.onRejection;
4458
+ this.expiryMs = options.expiryMs ?? defaultRejectionOwnershipExpiryMs;
4459
+ }
4460
+ begin() {
4461
+ if (process.versions.bun || this.releaseHook)
4462
+ return;
4463
+ this.releaseHook = retainPromiseHook();
4464
+ this.expiry = setTimeout(() => this.end(), this.expiryMs);
4465
+ this.expiry.unref?.();
4466
+ }
4467
+ invoke(run) {
4468
+ if (process.versions.bun)
4469
+ return run();
4470
+ return runWithRejectionOwner(this, run);
4471
+ }
4472
+ end() {
4473
+ if (this.expiry !== undefined) {
4474
+ clearTimeout(this.expiry);
4475
+ this.expiry = undefined;
4476
+ }
4477
+ this.releaseHook?.();
4478
+ this.releaseHook = undefined;
4479
+ }
4480
+ handleUnhandledRejection(cause, certain) {
4481
+ try {
4482
+ this.onRejection?.(unhandledExecuteRejectionWarning(safeErrorMessage(cause), certain));
4483
+ } catch {}
4484
+ }
4485
+ }
4486
+
3618
4487
  // src/execute/console.ts
3619
4488
  var sessions = new WeakMap;
3620
4489
  var listeners = new WeakMap;
@@ -3675,7 +4544,7 @@ function describe(arg) {
3675
4544
  }
3676
4545
 
3677
4546
  // src/execute/log-capture.ts
3678
- import util4 from "node:util";
4547
+ import util7 from "node:util";
3679
4548
  var maxCapturedPageLogs = 50;
3680
4549
  var maxCapturedScriptLogs = 100;
3681
4550
  function createExecuteLogCapture(limits = {}) {
@@ -3864,7 +4733,7 @@ function formatLogValue(value) {
3864
4733
  if (isString(value)) {
3865
4734
  return value;
3866
4735
  }
3867
- return util4.inspect(value, { depth: 4, colors: false, maxArrayLength: 100, maxStringLength: 1000 });
4736
+ return util7.inspect(value, { depth: 4, colors: false, maxArrayLength: 100, maxStringLength: 1000 });
3868
4737
  }
3869
4738
 
3870
4739
  // src/execute/target-selection.ts
@@ -3982,6 +4851,8 @@ var defaultHandoffTimeoutMs = 10 * 60 * 1000;
3982
4851
  var defaultHandoffMessage = "Complete the requested task, then use the in-page continue control.";
3983
4852
  var timedOut = Symbol("timed-out");
3984
4853
  var defaultPageClosedWarning = "The session default page was closed; created a new page. References to the old page in state are stale.";
4854
+ var debuggingBarDismissedWarning = "The user dismissed the browser's debugging bar (Cancel/OK), which disconnects browse from every tab. Browse no longer controls the session's page; tabs an agent opened stay open until idle cleanup closes them. To use a tab the user lent, ask them to lend it again with the browse toolbar button.";
4855
+ var debuggingBarDismissedStop = "The user dismissed the browser's debugging bar (Cancel/OK) while this script ran, which disconnects browse from every tab, so it was stopped. The tab may still be open but browse no longer controls it. Run execute again to continue in a new tab; to use a tab the user lent, ask them to lend it again with the browse toolbar button.";
3985
4856
  var defaultPageRecoveredWarning = "The session default page was unresponsive; created a new page. References to the old page in state are stale.";
3986
4857
  var defaultPageCrashedWarning = "The session default page target crashed; checking it before the next execute.";
3987
4858
  var defaultPageRepairedWarning = "The session default page stopped answering automation; browse reconnected and re-resolved the same tab. References to the old page in state are stale.";
@@ -4029,7 +4900,7 @@ var runPlaywrightOperation = fn("Execute.playwrightOperation")((options) => tryP
4029
4900
  catch: (cause) => operationFailure(options.label, cause)
4030
4901
  }).pipe(timeoutOrElse({
4031
4902
  duration: options.timeoutMs,
4032
- orElse: () => fail5(new PlaywrightOperationError({
4903
+ orElse: () => fail6(new PlaywrightOperationError({
4033
4904
  message: `${options.label} timed out after ${options.timeoutMs}ms`,
4034
4905
  operation: options.label,
4035
4906
  reason: "timeout"
@@ -4252,7 +5123,7 @@ function installClosedPageReplacementGuard(page, clearRecreatedFromClosedUrl) {
4252
5123
  }
4253
5124
 
4254
5125
  // src/execute/code-runner.ts
4255
- var nodeModules = { ...sandboxModules, fs: fs4, os: os4, http: http3, https: https2 };
5126
+ var nodeModules = { ...sandboxModules, fs: fs5, os: os4, http: http3, https: https2 };
4256
5127
 
4257
5128
  class ExecuteCodeError extends Error {
4258
5129
  originalError;
@@ -4369,7 +5240,7 @@ var sandboxGlobalKeys = [
4369
5240
  "pageConsole",
4370
5241
  "secrets"
4371
5242
  ];
4372
- async function runUserCode({ code, globals, realm }) {
5243
+ async function runUserCode({ code, globals, realm, onUnhandledRejection }) {
4373
5244
  const logCapture = createExecuteLogCapture();
4374
5245
  const navigations = [];
4375
5246
  const onConsole = (message) => {
@@ -4432,8 +5303,14 @@ ${wrapCodeWithModuleAliases(code, Object.keys(sandboxModules))}
4432
5303
  const AsyncFunction = async function() {}.constructor;
4433
5304
  const fn = new AsyncFunction("console", ...sandboxGlobalKeys, `${wrapCodeWithModuleAliases(code, Object.keys(nodeModules))}
4434
5305
  //# sourceURL=${executeFilename}`);
4435
- const result = await fn(...values);
4436
- return { result, ...buildResultMetadata() };
5306
+ const scope = process.versions.bun || !onUnhandledRejection ? undefined : new ExecuteRejectionScope({ onRejection: onUnhandledRejection });
5307
+ scope?.begin();
5308
+ try {
5309
+ const result = await (scope ? scope.invoke(() => fn(...values)) : fn(...values));
5310
+ return { result, ...buildResultMetadata() };
5311
+ } finally {
5312
+ scope?.end();
5313
+ }
4437
5314
  } catch (cause) {
4438
5315
  const error = cause instanceof Error ? cause : new Error("execute sandbox code", { cause });
4439
5316
  const metadata = buildResultMetadata();
@@ -4605,6 +5482,7 @@ class DefaultPageHost {
4605
5482
  pendingTargetRebind;
4606
5483
  lastKnownNonBlankUrl;
4607
5484
  recreatedFromClosedUrl;
5485
+ pageReleasedByDebuggingBar = false;
4608
5486
  explicitMediaFeatures = new Map;
4609
5487
  explicitMedia;
4610
5488
  pendingWarnings = [];
@@ -4648,15 +5526,18 @@ class DefaultPageHost {
4648
5526
  this.pageProtectedUi = protectedUi;
4649
5527
  return true;
4650
5528
  }
4651
- markTargetDetached(targetId) {
5529
+ markTargetDetached(targetId, options = {}) {
4652
5530
  if (this.defaultPageTargetId !== targetId) {
4653
5531
  return false;
4654
5532
  }
4655
- if (this.lastKnownNonBlankUrl) {
5533
+ const releasedByUser = options.releasedByUser === true;
5534
+ if (releasedByUser)
5535
+ this.recreatedFromClosedUrl = undefined;
5536
+ else if (this.lastKnownNonBlankUrl)
4656
5537
  this.recreatedFromClosedUrl = this.lastKnownNonBlankUrl;
4657
- }
5538
+ this.pageReleasedByDebuggingBar = releasedByUser;
4658
5539
  this.unbindDefaultPage(undefined);
4659
- this.addWarningOnce(defaultPageClosedWarning);
5540
+ this.addWarningOnce(releasedByUser ? debuggingBarDismissedWarning : defaultPageClosedWarning);
4660
5541
  return true;
4661
5542
  }
4662
5543
  markTargetReplaced(previousTargetId, targetId) {
@@ -4693,6 +5574,7 @@ class DefaultPageHost {
4693
5574
  this.defaultPageTargetId = targetId;
4694
5575
  this.ownsPage = ownsPage;
4695
5576
  this.pendingTargetRebind = undefined;
5577
+ this.pageReleasedByDebuggingBar = false;
4696
5578
  this.recordNonBlankUrl(safePageUrl(page));
4697
5579
  const close = () => {
4698
5580
  if (this.page !== page)
@@ -4801,6 +5683,10 @@ class DefaultPageHost {
4801
5683
  });
4802
5684
  this.pendingWarnings.push(defaultPageClosedWarning);
4803
5685
  }
5686
+ if (this.pageReleasedByDebuggingBar) {
5687
+ this.pageReleasedByDebuggingBar = false;
5688
+ this.addWarningOnce(debuggingBarDismissedWarning);
5689
+ }
4804
5690
  const page = await context.newPage();
4805
5691
  const targetId = await resolvePageTargetId(page);
4806
5692
  this.bindDefaultPage(page, targetId, true, true);
@@ -4847,7 +5733,7 @@ class DefaultPageHost {
4847
5733
  }
4848
5734
 
4849
5735
  // src/execute/result-formatting.ts
4850
- import util5 from "node:util";
5736
+ import util8 from "node:util";
4851
5737
  var maxExecuteResultChars = 1e5;
4852
5738
  function boundExecuteResult(text, value, hasValue) {
4853
5739
  const valueChars = hasValue && value !== null && typeof value === "object" ? safeJsonStringify(value)?.length ?? 0 : typeof value === "string" ? value.length : 0;
@@ -4869,7 +5755,7 @@ function stringifyResult(result) {
4869
5755
  if (result === undefined) {
4870
5756
  return "undefined";
4871
5757
  }
4872
- return util5.inspect(result, { depth: 3, colors: false, maxArrayLength: 50, maxStringLength: 4000 });
5758
+ return util8.inspect(result, { depth: 3, colors: false, maxArrayLength: 50, maxStringLength: 4000 });
4873
5759
  }
4874
5760
  var maxJsonSafeDepth = 8;
4875
5761
  var maxJsonSafeBytes = 32 * 1024;
@@ -6499,7 +7385,7 @@ class GhostCursorTabs {
6499
7385
  command = fnUntraced(function* (tabId, params) {
6500
7386
  const operation = params?.op;
6501
7387
  if (!isString(operation) || !ghostCursorOperations.has(operation)) {
6502
- return yield* fail5(new Error(`Unknown ghost cursor operation: ${String(operation)}`));
7388
+ return yield* fail6(new Error(`Unknown ghost cursor operation: ${String(operation)}`));
6503
7389
  }
6504
7390
  const payload = params?.payload ?? null;
6505
7391
  const state = this.state(tabId);
@@ -6609,8 +7495,8 @@ function parseButton(value2) {
6609
7495
  }
6610
7496
 
6611
7497
  // src/snapshot/screenshot-diff.ts
6612
- import fs5 from "node:fs/promises";
6613
- import path3 from "node:path";
7498
+ import fs6 from "node:fs/promises";
7499
+ import path4 from "node:path";
6614
7500
  import pixelmatch from "pixelmatch";
6615
7501
  import { PNG } from "pngjs";
6616
7502
  var maxImageBytes = 32 * 1024 * 1024;
@@ -6619,7 +7505,7 @@ var pngSignature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
6619
7505
  function createScreenshotDiff(page) {
6620
7506
  return async (options) => {
6621
7507
  const threshold = validateThreshold(options.threshold ?? 0.1);
6622
- if (options.path !== undefined && (!path3.isAbsolute(options.path) || path3.extname(options.path).toLowerCase() !== ".png")) {
7508
+ if (options.path !== undefined && (!path4.isAbsolute(options.path) || path4.extname(options.path).toLowerCase() !== ".png")) {
6623
7509
  throw new Error("screenshotDiff output path must be an absolute .png path");
6624
7510
  }
6625
7511
  const baseline = isString(options.baseline) ? await readBaseline(options.baseline) : options.baseline;
@@ -6637,7 +7523,7 @@ function createScreenshotDiff(page) {
6637
7523
  const image = PNG.sync.write(diff);
6638
7524
  const totalPixels = before.width * before.height;
6639
7525
  if (options.path)
6640
- await fs5.writeFile(options.path, image, { flag: "wx", mode: 384 });
7526
+ await fs6.writeFile(options.path, image, { flag: "wx", mode: 384 });
6641
7527
  return {
6642
7528
  matches: changedPixels === 0,
6643
7529
  width: before.width,
@@ -6651,9 +7537,9 @@ function createScreenshotDiff(page) {
6651
7537
  };
6652
7538
  }
6653
7539
  async function readBaseline(filename) {
6654
- if (!path3.isAbsolute(filename))
7540
+ if (!path4.isAbsolute(filename))
6655
7541
  throw new Error("screenshotDiff baseline path must be absolute");
6656
- const file = await fs5.open(filename, "r");
7542
+ const file = await fs6.open(filename, "r");
6657
7543
  try {
6658
7544
  const stat = await file.stat();
6659
7545
  if (!stat.isFile() || stat.size > maxImageBytes)
@@ -7917,14 +8803,14 @@ async function fillInputs(page, fields) {
7917
8803
  }
7918
8804
  }
7919
8805
  // src/snapshot/screenshot-labels.ts
7920
- import fs6 from "node:fs/promises";
7921
- import path4 from "node:path";
8806
+ import fs7 from "node:fs/promises";
8807
+ import path5 from "node:path";
7922
8808
  import { PNG as PNG2 } from "pngjs";
7923
8809
  async function screenshotWithLabels(options = {}) {
7924
8810
  if (!options.page) {
7925
8811
  throw new Error("screenshotWithLabels requires a page");
7926
8812
  }
7927
- if (options.path !== undefined && !path4.isAbsolute(options.path)) {
8813
+ if (options.path !== undefined && !path5.isAbsolute(options.path)) {
7928
8814
  throw new Error("screenshotWithLabels requires an absolute path");
7929
8815
  }
7930
8816
  const page = options.page;
@@ -7954,7 +8840,7 @@ async function screenshotWithLabels(options = {}) {
7954
8840
  try {
7955
8841
  const screenshot = offPage ? drawScreenshotLabels(await page.screenshot(), labels, viewportWidth) : await page.screenshot(options.path ? { path: options.path } : {});
7956
8842
  if (offPage && options.path)
7957
- await fs6.writeFile(options.path, screenshot);
8843
+ await fs7.writeFile(options.path, screenshot);
7958
8844
  return {
7959
8845
  ...options.path ? { path: options.path } : { image: screenshot },
7960
8846
  size: screenshot.byteLength,
@@ -8617,6 +9503,10 @@ function collectWebMcpToolsInPage() {
8617
9503
  }));
8618
9504
  }
8619
9505
  function callWebMcpToolInPage(options) {
9506
+ function isInputEncodingError(error) {
9507
+ const message = typeof error === "object" && error !== null && "message" in error ? String(error.message) : String(error);
9508
+ return message.includes("parameter 2 is not of type 'object'") || message.includes("Failed to parse input arguments");
9509
+ }
8620
9510
  const context = document.modelContext ?? navigator.modelContext;
8621
9511
  if (!context?.getTools)
8622
9512
  throw new Error("WebMCP is not available on this page");
@@ -8624,9 +9514,21 @@ function callWebMcpToolInPage(options) {
8624
9514
  const tool = tools.filter((candidate) => !("window" in candidate) || candidate.window === window).find((candidate) => candidate.name === options.name);
8625
9515
  if (!tool)
8626
9516
  throw new Error(`WebMCP tool ${JSON.stringify(options.name)} is not registered in this frame`);
8627
- const result = context.executeTool ? await context.executeTool(tool, options.inputJson) : context.invokeTool ? await context.invokeTool(options.name, JSON.parse(options.inputJson)) : (() => {
9517
+ const input = JSON.parse(options.inputJson);
9518
+ let result;
9519
+ if (context.executeTool) {
9520
+ try {
9521
+ result = await context.executeTool(tool, input);
9522
+ } catch (error) {
9523
+ if (!isInputEncodingError(error))
9524
+ throw error;
9525
+ result = await context.executeTool(tool, options.inputJson);
9526
+ }
9527
+ } else if (context.invokeTool) {
9528
+ result = await context.invokeTool(options.name, input);
9529
+ } else {
8628
9530
  throw new Error("WebMCP tool execution is not available on this page");
8629
- })();
9531
+ }
8630
9532
  if (typeof result !== "string")
8631
9533
  return result ?? null;
8632
9534
  try {
@@ -8961,10 +9863,10 @@ class ExecuteSecretsBridge {
8961
9863
  }
8962
9864
 
8963
9865
  // src/network-capture.ts
8964
- import path6 from "node:path";
9866
+ import path7 from "node:path";
8965
9867
 
8966
9868
  // src/network-capture/har-redaction.ts
8967
- import path5 from "node:path";
9869
+ import path6 from "node:path";
8968
9870
 
8969
9871
  // src/network-capture/types.ts
8970
9872
  var defaultNetworkCaptureMaxDurationMs = 30 * 60000;
@@ -9296,7 +10198,7 @@ function toHarEntry(entry) {
9296
10198
  }
9297
10199
  function writeArtifact(outputPath, value) {
9298
10200
  return tryPromise({
9299
- try: () => writeJsonFileAtomically(path5.resolve(outputPath), value),
10201
+ try: () => writeJsonFileAtomically(path6.resolve(outputPath), value),
9300
10202
  catch: (cause) => new NetworkCaptureError({ message: `Could not write network capture: ${outputPath}`, operation: "write", reason: "persistence-failed", cause })
9301
10203
  });
9302
10204
  }
@@ -9403,7 +10305,7 @@ class Recorder {
9403
10305
  }
9404
10306
  start(page, options = {}) {
9405
10307
  const capture = this;
9406
- return this.transition.withPermit(try_({
10308
+ return this.transition.withPermit(try_2({
9407
10309
  try: () => {
9408
10310
  validateOptions(options);
9409
10311
  if (capture.active) {
@@ -9535,7 +10437,7 @@ class Recorder {
9535
10437
  truncatedBodyCount: finalStatus.truncatedBodyCount + finished.redactionOmissionCount,
9536
10438
  active: false,
9537
10439
  stoppedAt: new Date().toISOString(),
9538
- ...options.outputPath ? { outputPath: path6.resolve(options.outputPath) } : {},
10440
+ ...options.outputPath ? { outputPath: path7.resolve(options.outputPath) } : {},
9539
10441
  ...finished.authProfile ? { authProfile: finished.authProfile } : {},
9540
10442
  updatedSecretRefs: finished.updatedSecretRefs,
9541
10443
  observedSecretRefs: finished.observedSecretRefs,
@@ -9767,25 +10669,25 @@ class Recorder {
9767
10669
  }
9768
10670
 
9769
10671
  // src/relay/log.ts
9770
- import fs7 from "node:fs";
10672
+ import fs8 from "node:fs";
9771
10673
  import os5 from "node:os";
9772
- import path7 from "node:path";
10674
+ import path8 from "node:path";
9773
10675
  var maxLogBytes = 1e6;
9774
10676
  var maxEntryCharacters = 64000;
9775
10677
  function managedRelayLogPath(home = os5.homedir()) {
9776
- return path7.join(stateRoot(home), "logs", "relay.log");
10678
+ return path8.join(stateRoot(home), "logs", "relay.log");
9777
10679
  }
9778
10680
  function appendManagedRelayProcessLog(message, home = os5.homedir()) {
9779
10681
  try {
9780
10682
  const logPath = managedRelayLogPath(home);
9781
- ensurePrivateDirectorySync(path7.dirname(logPath));
10683
+ ensurePrivateDirectorySync(path8.dirname(logPath));
9782
10684
  const entry = `${new Date().toISOString()} ${message.slice(0, maxEntryCharacters)}
9783
10685
  `;
9784
- const stat = fs7.statSync(logPath, { throwIfNoEntry: false });
10686
+ const stat = fs8.statSync(logPath, { throwIfNoEntry: false });
9785
10687
  if (stat && stat.size + Buffer.byteLength(entry) > maxLogBytes)
9786
- fs7.renameSync(logPath, `${logPath}.1`);
9787
- fs7.appendFileSync(logPath, entry, { encoding: "utf8", mode: 384 });
9788
- fs7.chmodSync(logPath, 384);
10688
+ fs8.renameSync(logPath, `${logPath}.1`);
10689
+ fs8.appendFileSync(logPath, entry, { encoding: "utf8", mode: 384 });
10690
+ fs8.chmodSync(logPath, 384);
9789
10691
  } catch {}
9790
10692
  }
9791
10693
  function relayLog(event, fields = {}) {
@@ -9859,7 +10761,8 @@ class ExecuteSandbox extends DefaultPageHost {
9859
10761
  return new ExecuteRealm({
9860
10762
  onHostCall: (fn, receiver, args) => {
9861
10763
  this.addWarningOnce(pageVisibleApiWarning(fn, receiver, args));
9862
- }
10764
+ },
10765
+ onUnhandledRejection: (warning) => this.addWarningOnce(warning)
9863
10766
  });
9864
10767
  }
9865
10768
  execute(code, options = {}) {
@@ -9874,7 +10777,12 @@ class ExecuteSandbox extends DefaultPageHost {
9874
10777
  for (const warning of pageVisibleApiSourceWarnings(code))
9875
10778
  this.addWarningOnce(warning);
9876
10779
  const globals = await this.getGlobals(options);
9877
- const { result, logs, logSummary, aftermath } = await runUserCode({ code, globals, ...this.realm ? { realm: this.realm } : {} }).then(async (completed) => ({ ...completed, aftermath: await this.withChallenge(globals.page, completed.aftermath, false) })).catch(async (error) => {
10780
+ const { result, logs, logSummary, aftermath } = await runUserCode({
10781
+ code,
10782
+ globals,
10783
+ ...this.realm ? { realm: this.realm } : {},
10784
+ onUnhandledRejection: (warning) => this.addWarningOnce(warning)
10785
+ }).then(async (completed) => ({ ...completed, aftermath: await this.withChallenge(globals.page, completed.aftermath, false) })).catch(async (error) => {
9878
10786
  if (!(error instanceof ExecuteCodeError) || !error.aftermath)
9879
10787
  throw error;
9880
10788
  throw new ExecuteCodeError(error.originalError, error.logs, error.logSummary, await this.withChallenge(globals.page, error.aftermath, true));
@@ -10249,15 +11157,15 @@ class ExecuteSandbox extends DefaultPageHost {
10249
11157
  }
10250
11158
 
10251
11159
  // src/recording-relay/flight-recorder.ts
10252
- import fs9 from "node:fs/promises";
10253
- import path9 from "node:path";
11160
+ import fs10 from "node:fs/promises";
11161
+ import path10 from "node:path";
10254
11162
  import { performance as performance3 } from "node:perf_hooks";
10255
11163
 
10256
11164
  // src/recording-relay/ffmpeg-encoder.ts
10257
11165
  import { execFile, spawn } from "node:child_process";
10258
11166
  import crypto6 from "node:crypto";
10259
11167
  import { once } from "node:events";
10260
- import fs8 from "node:fs/promises";
11168
+ import fs9 from "node:fs/promises";
10261
11169
 
10262
11170
  // src/recording-relay/mjpeg-matroska.ts
10263
11171
  var ebml = Buffer.from("1A45DFA3", "hex");
@@ -10374,7 +11282,7 @@ function mjpegMatroskaFrame(timestampMs, durationMs, frameLength) {
10374
11282
  import { performance as performance2 } from "node:perf_hooks";
10375
11283
 
10376
11284
  // src/recording-relay/types.ts
10377
- import path8 from "node:path";
11285
+ import path9 from "node:path";
10378
11286
  var defaultMaxDurationMs = 15 * 60 * 1000;
10379
11287
  var defaultCdpFrameRate = 60;
10380
11288
  var maxRecordingFrameRate = 60;
@@ -10470,7 +11378,7 @@ function findByRecordingTarget(map, target, ambiguousMessage) {
10470
11378
  return map.values().next().value;
10471
11379
  }
10472
11380
  function cdpArtifactType(outputPath) {
10473
- const extension = path8.extname(outputPath).toLowerCase();
11381
+ const extension = path9.extname(outputPath).toLowerCase();
10474
11382
  if (extension === ".webm")
10475
11383
  return "webm";
10476
11384
  if (extension === ".mp4")
@@ -10665,7 +11573,7 @@ async function createFfmpegVideoEncoder(options) {
10665
11573
  await writeStreamChunk(child.stdin, mjpegMatroskaHeader(options.width, options.height));
10666
11574
  } catch (error) {
10667
11575
  await exit;
10668
- await fs8.rm(temporaryOutputPath, { force: true });
11576
+ await fs9.rm(temporaryOutputPath, { force: true });
10669
11577
  throw error;
10670
11578
  }
10671
11579
  let completed = false;
@@ -10705,10 +11613,10 @@ async function createFfmpegVideoEncoder(options) {
10705
11613
  const error = await exit;
10706
11614
  if (error)
10707
11615
  throw error;
10708
- await fs8.rename(temporaryOutputPath, options.outputPath);
11616
+ await fs9.rename(temporaryOutputPath, options.outputPath);
10709
11617
  completed = true;
10710
11618
  })().catch(async (error) => {
10711
- await fs8.rm(temporaryOutputPath, { force: true });
11619
+ await fs9.rm(temporaryOutputPath, { force: true });
10712
11620
  throw error;
10713
11621
  });
10714
11622
  return finishingPromise;
@@ -10720,7 +11628,7 @@ async function createFfmpegVideoEncoder(options) {
10720
11628
  return cancelPromise;
10721
11629
  cancelPromise = (async () => {
10722
11630
  await terminate();
10723
- await fs8.rm(temporaryOutputPath, { force: true });
11631
+ await fs9.rm(temporaryOutputPath, { force: true });
10724
11632
  })();
10725
11633
  return cancelPromise;
10726
11634
  }
@@ -10884,7 +11792,7 @@ class FlightRecorderRelay {
10884
11792
  const startAt = frames[0].receivedAt;
10885
11793
  const endAt = frames.at(-1).receivedAt;
10886
11794
  const durationMs = Math.max(1, endAt - startAt);
10887
- await fs9.mkdir(path9.dirname(target.outputPath), { recursive: true });
11795
+ await fs10.mkdir(path10.dirname(target.outputPath), { recursive: true });
10888
11796
  let encoder;
10889
11797
  try {
10890
11798
  encoder = await (this.options.startVideoEncoder ?? startFfmpegVideoEncoder)({
@@ -10908,7 +11816,7 @@ class FlightRecorderRelay {
10908
11816
  sourceFrameCount: recorder.sourceFrameCount,
10909
11817
  droppedFrameCount: recorder.droppedFrameCount
10910
11818
  };
10911
- await fs9.writeFile(`${target.outputPath}.json`, `${JSON.stringify({ ...receipt, savedAt: new Date(this.now()).toISOString(), retainedDurationMs: this.retainedDuration(recorder) }, null, 2)}
11819
+ await fs10.writeFile(`${target.outputPath}.json`, `${JSON.stringify({ ...receipt, savedAt: new Date(this.now()).toISOString(), retainedDurationMs: this.retainedDuration(recorder) }, null, 2)}
10912
11820
  `, "utf8");
10913
11821
  return receipt;
10914
11822
  } catch (error) {
@@ -11009,7 +11917,7 @@ class FlightRecorderRelay {
11009
11917
  }
11010
11918
  async function assertOutputAvailable(filePath) {
11011
11919
  try {
11012
- await fs9.stat(filePath);
11920
+ await fs10.stat(filePath);
11013
11921
  } catch (error) {
11014
11922
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
11015
11923
  return;
@@ -11202,8 +12110,8 @@ function resolveExactHandoffTarget(options) {
11202
12110
  }
11203
12111
 
11204
12112
  // src/relay/lifecycle-log.ts
11205
- import fs10 from "node:fs";
11206
- import path10 from "node:path";
12113
+ import fs11 from "node:fs";
12114
+ import path11 from "node:path";
11207
12115
  var requestFields = {
11208
12116
  instanceId: RelayShutdownRequest.fields.instanceId,
11209
12117
  requestId: RelayShutdownRequest.fields.requestId,
@@ -11221,30 +12129,30 @@ var RelayLifecycleEvent = TaggedUnion({
11221
12129
  }
11222
12130
  });
11223
12131
  function appendRelayLifecycleEvent(filePath, event) {
11224
- const directory = path10.dirname(filePath);
12132
+ const directory = path11.dirname(filePath);
11225
12133
  ensurePrivateDirectorySync(directory);
11226
12134
  const entry = `${JSON.stringify({ ...encodeSync(RelayLifecycleEvent)(event), timestamp: new Date().toISOString() })}
11227
12135
  `;
11228
- const file = fs10.openSync(filePath, "a+", 384);
12136
+ const file = fs11.openSync(filePath, "a+", 384);
11229
12137
  try {
11230
- fs10.fchmodSync(file, 384);
11231
- if (fs10.fstatSync(file).size + Buffer.byteLength(entry) > 256000)
11232
- fs10.ftruncateSync(file, 0);
11233
- fs10.writeFileSync(file, entry);
11234
- fs10.fsyncSync(file);
12138
+ fs11.fchmodSync(file, 384);
12139
+ if (fs11.fstatSync(file).size + Buffer.byteLength(entry) > 256000)
12140
+ fs11.ftruncateSync(file, 0);
12141
+ fs11.writeFileSync(file, entry);
12142
+ fs11.fsyncSync(file);
11235
12143
  } finally {
11236
- fs10.closeSync(file);
12144
+ fs11.closeSync(file);
11237
12145
  }
11238
- const parent = fs10.openSync(directory, "r");
12146
+ const parent = fs11.openSync(directory, "r");
11239
12147
  try {
11240
12148
  try {
11241
- fs10.fsyncSync(parent);
12149
+ fs11.fsyncSync(parent);
11242
12150
  } catch (error) {
11243
12151
  if (!isUnsupportedDirectorySyncError(error))
11244
12152
  throw error;
11245
12153
  }
11246
12154
  } finally {
11247
- fs10.closeSync(parent);
12155
+ fs11.closeSync(parent);
11248
12156
  }
11249
12157
  }
11250
12158
 
@@ -11261,7 +12169,7 @@ class RelayShutdown {
11261
12169
  options;
11262
12170
  state = State.Running();
11263
12171
  requests = 0;
11264
- idle = makeUnsafe5(true);
12172
+ idle = makeUnsafe2(true);
11265
12173
  constructor(options) {
11266
12174
  this.options = options;
11267
12175
  }
@@ -11279,7 +12187,7 @@ class RelayShutdown {
11279
12187
  yield* control.options.settle;
11280
12188
  }).pipe(timeoutOrElse({
11281
12189
  duration: control.options.timeoutMs ?? 1e4,
11282
- orElse: () => fail5(control.busyError("timeout"))
12190
+ orElse: () => fail6(control.busyError("timeout"))
11283
12191
  }));
11284
12192
  }
11285
12193
  close() {
@@ -11293,7 +12201,7 @@ class RelayShutdown {
11293
12201
  const control = this;
11294
12202
  return acquireUseRelease(suspend2(() => {
11295
12203
  if (!control.accepting)
11296
- return fail5(control.busyError());
12204
+ return fail6(control.busyError());
11297
12205
  return sync2(() => control.retain());
11298
12206
  }), () => effect, (release) => sync2(release));
11299
12207
  }
@@ -11444,7 +12352,7 @@ class SessionError extends TaggedError2()("OpenCodeBrowserSessions.SessionError"
11444
12352
  }) {
11445
12353
  }
11446
12354
  var sessionError = (reason, message, sessionId) => new SessionError({ message, reason, ...sessionId ? { sessionId } : {} });
11447
- var trySession = (work) => try_({ try: work, catch: (cause) => cause instanceof Error ? cause : new Error(String(cause)) });
12355
+ var trySession = (work) => try_2({ try: work, catch: (cause) => cause instanceof Error ? cause : new Error(String(cause)) });
11448
12356
  var adoptionTipForUrl = (url) => {
11449
12357
  const selector = targetUrlHintSelector(url);
11450
12358
  return `Tip: an attached tab is open (${url}). Use session_adopt with targetUrl '${selector}' (CLI: ${cliCommand(`session adopt --target-url '${selector}'`)}) to drive it instead of this new tab.`;
@@ -11517,7 +12425,7 @@ class SessionAdmission {
11517
12425
  pendingWork = 0;
11518
12426
  pendingSessionWork = new Map;
11519
12427
  identityChanges = new Map;
11520
- idle = makeUnsafe5(true);
12428
+ idle = makeUnsafe2(true);
11521
12429
  constructor(sessions, hooks) {
11522
12430
  this.sessions = sessions;
11523
12431
  this.hooks = hooks;
@@ -11538,20 +12446,20 @@ class SessionAdmission {
11538
12446
  awaitStableIdentity(id) {
11539
12447
  return suspend2(() => {
11540
12448
  const pending = id === undefined ? undefined : this.identityChanges.get(id);
11541
- return pending ? _await(pending).pipe(andThen(this.awaitStableIdentity(id))) : void_3;
12449
+ return pending ? _await(pending).pipe(andThen2(this.awaitStableIdentity(id))) : void_3;
11542
12450
  });
11543
12451
  }
11544
12452
  withIdentityChange(id, effect) {
11545
12453
  return suspend2(() => {
11546
12454
  const pending = this.identityChanges.get(id);
11547
12455
  if (pending)
11548
- return _await(pending).pipe(andThen(this.withIdentityChange(id, effect)));
11549
- const settled = makeUnsafe3();
12456
+ return _await(pending).pipe(andThen2(this.withIdentityChange(id, effect)));
12457
+ const settled = makeUnsafe4();
11550
12458
  this.identityChanges.set(id, settled);
11551
12459
  return effect.pipe(onExit((exit) => suspend2(() => {
11552
12460
  if (this.identityChanges.get(id) === settled)
11553
12461
  this.identityChanges.delete(id);
11554
- return done(settled, asVoid(exit));
12462
+ return done2(settled, asVoid(exit));
11555
12463
  })));
11556
12464
  });
11557
12465
  }
@@ -11574,13 +12482,13 @@ class SessionAdmission {
11574
12482
  };
11575
12483
  }
11576
12484
  withAdmission(sessionId, effect) {
11577
- return acquireUseRelease(try_({
12485
+ return acquireUseRelease(try_2({
11578
12486
  try: () => {
11579
12487
  this.assertAdmission();
11580
12488
  return this.retainWork(sessionId);
11581
12489
  },
11582
12490
  catch: (cause) => cause instanceof Error ? cause : new Error("Admit session operation", { cause })
11583
- }), () => this.awaitStableIdentity(sessionId).pipe(andThen(effect)), (release) => sync2(release));
12491
+ }), () => this.awaitStableIdentity(sessionId).pipe(andThen2(effect)), (release) => sync2(release));
11584
12492
  }
11585
12493
  forkTracked(effect, sessionId) {
11586
12494
  return uninterruptibleMask2(() => suspend2(() => {
@@ -11624,7 +12532,7 @@ class SessionAdmission {
11624
12532
  yield* rollback();
11625
12533
  this.schedulePersistence();
11626
12534
  yield* this.flushPersistence().pipe(ignore);
11627
- return yield* fail5(error);
12535
+ return yield* fail6(error);
11628
12536
  })));
11629
12537
  }
11630
12538
  beginDrain() {
@@ -11660,7 +12568,7 @@ function adoptTargetForSession(context, options) {
11660
12568
  return context.admission.withAdmission(options.sessionId, uninterruptibleMask2((restore) => gen(function* () {
11661
12569
  const resolved = yield* context.resolveWorkSession(options.sessionId, options.createIfMissing);
11662
12570
  const session = resolved.session;
11663
- const result2 = yield* make5();
12571
+ const result2 = yield* make10();
11664
12572
  let state = "pending";
11665
12573
  let cancelled = false;
11666
12574
  let reservation;
@@ -11689,7 +12597,7 @@ function adoptTargetForSession(context, options) {
11689
12597
  if (options.tabId !== undefined && browser?.key && context.hooks.targetBrowserKey?.(options.tabId) !== browser.key) {
11690
12598
  return yield* sessionError("invalid-request", `Tab ${options.tabId} is not in session ${session.id}'s browser '${browser.id}'. Start a new session for its browser.`, session.id);
11691
12599
  }
11692
- reservation = yield* try_({
12600
+ reservation = yield* try_2({
11693
12601
  try: () => context.targetOwnership.reserveTargetOwnership(options.targetId, session.id),
11694
12602
  catch: (cause) => cause instanceof Error ? cause : new Error("Reserve target ownership", { cause })
11695
12603
  });
@@ -11713,7 +12621,7 @@ function adoptTargetForSession(context, options) {
11713
12621
  if (adoptionCancelled()) {
11714
12622
  return yield* timeoutError;
11715
12623
  }
11716
- yield* try_({
12624
+ yield* try_2({
11717
12625
  try: () => {
11718
12626
  context.notifyTargetOwnershipChange(context.targetOwnership.commitTargetOwnership({
11719
12627
  reservation: activeReservation,
@@ -11728,7 +12636,7 @@ function adoptTargetForSession(context, options) {
11728
12636
  yield* succeed4(result2, value);
11729
12637
  return value;
11730
12638
  });
11731
- const transaction = session.executeSemaphore.withPermit(operation.pipe(matchEffect({
12639
+ const transaction = session.executeSemaphore.withPermit(operation.pipe(matchEffect2({
11732
12640
  onFailure: (error) => gen(function* () {
11733
12641
  if (reservation && state !== "committed") {
11734
12642
  context.notifyTargetOwnershipChange(context.targetOwnership.rollbackTargetOwnership(reservation));
@@ -11736,11 +12644,11 @@ function adoptTargetForSession(context, options) {
11736
12644
  if (context.sessions.get(session.id) === session && (resolved.created || state !== "pending")) {
11737
12645
  const cleanup = yield* result(cleanupSettledAdoption(context, session, resolved.created, previousTarget, previousRelayClosed));
11738
12646
  if (isFailure(cleanup)) {
11739
- yield* fail4(result2, cleanup.failure);
12647
+ yield* fail5(result2, cleanup.failure);
11740
12648
  return;
11741
12649
  }
11742
12650
  }
11743
- yield* fail4(result2, error);
12651
+ yield* fail5(result2, error);
11744
12652
  }),
11745
12653
  onSuccess: () => void_3
11746
12654
  })));
@@ -11748,7 +12656,7 @@ function adoptTargetForSession(context, options) {
11748
12656
  yield* context.admission.forkTracked(worker, session.id);
11749
12657
  return yield* restore(_await(result2).pipe(timeoutOrElse({
11750
12658
  duration: timeoutMs,
11751
- orElse: () => cancel.pipe(andThen(fail5(timeoutError)))
12659
+ orElse: () => cancel.pipe(andThen2(fail6(timeoutError)))
11752
12660
  }), onInterrupt(() => cancel)));
11753
12661
  })));
11754
12662
  }
@@ -11797,7 +12705,7 @@ function withLifecycleTimeout(hooks, effect, label) {
11797
12705
  const timeoutMs = hooks.lifecycleTimeoutMs ?? 1e4;
11798
12706
  return effect.pipe(timeoutOrElse({
11799
12707
  duration: timeoutMs,
11800
- orElse: () => fail5(sessionError("timeout", `${label} timed out after ${timeoutMs}ms`))
12708
+ orElse: () => fail6(sessionError("timeout", `${label} timed out after ${timeoutMs}ms`))
11801
12709
  }));
11802
12710
  }
11803
12711
  function closeSessionSettledWithTimeout(admission, hooks, session, closeSettled) {
@@ -11812,7 +12720,7 @@ function executeInSession(ctx, options) {
11812
12720
  }
11813
12721
  const resolved = yield* ctx.resolveWorkSession(options.sessionId, options.createIfMissing, options.browser);
11814
12722
  const session = resolved.session;
11815
- const response = yield* make5();
12723
+ const response = yield* make10();
11816
12724
  let started = false;
11817
12725
  let cancelled = false;
11818
12726
  const operation = gen(function* () {
@@ -11828,8 +12736,8 @@ function executeInSession(ctx, options) {
11828
12736
  started = true;
11829
12737
  session.updatedAt = new Date().toISOString();
11830
12738
  yield* ctx.setExecuting(session.id, true);
11831
- const stopSignal = makeUnsafe3();
11832
- const released = makeUnsafe3();
12739
+ const stopSignal = makeUnsafe4();
12740
+ const released = makeUnsafe4();
11833
12741
  const effectiveTimeoutMs = options.timeoutMs ?? ctx.hooks.executeTimeoutMs ?? defaultExecuteTimeoutMs;
11834
12742
  let deadline;
11835
12743
  const stopRunning = (message, diagnostic) => {
@@ -11893,9 +12801,9 @@ function executeInSession(ctx, options) {
11893
12801
  yield* ctx.admission.commitPersistence();
11894
12802
  return { result: resultWithHint, session: createdSummary(session, resolved.created) };
11895
12803
  });
11896
- const worker = session.executeSemaphore.withPermit(operation.pipe(matchEffect({
11897
- onFailure: (error) => (resolved.created ? ctx.cleanupCreatedSession(session) : void_3).pipe(andThen(fail4(response, error))),
11898
- onSuccess: (value) => (options.removeAfterExecute ? ctx.cleanupCreatedSession(session) : void_3).pipe(andThen(succeed4(response, value)))
12804
+ const worker = session.executeSemaphore.withPermit(operation.pipe(matchEffect2({
12805
+ onFailure: (error) => (resolved.created ? ctx.cleanupCreatedSession(session) : void_3).pipe(andThen2(fail5(response, error))),
12806
+ onSuccess: (value) => (options.removeAfterExecute ? ctx.cleanupCreatedSession(session) : void_3).pipe(andThen2(succeed4(response, value)))
11899
12807
  })));
11900
12808
  const workerFiber = yield* ctx.admission.forkTracked(worker, session.id);
11901
12809
  return yield* restore(_await(response)).pipe(onInterrupt(() => suspend2(() => {
@@ -11904,7 +12812,7 @@ function executeInSession(ctx, options) {
11904
12812
  return void_3;
11905
12813
  }
11906
12814
  cancelled = true;
11907
- return interrupt3(workerFiber).pipe(asVoid2, andThen(resolved.created ? session.executeSemaphore.withPermit(ctx.cleanupCreatedSession(session)) : void_3));
12815
+ return interrupt(workerFiber).pipe(asVoid2, andThen2(resolved.created ? session.executeSemaphore.withPermit(ctx.cleanupCreatedSession(session)) : void_3));
11908
12816
  })));
11909
12817
  })));
11910
12818
  }
@@ -12185,9 +13093,9 @@ class OpenCodeBrowserSessions {
12185
13093
  markTargetProtectedUi(targetId, protectedUi) {
12186
13094
  return this.collectSessionIds((session) => session.sandbox.markTargetProtectedUi(targetId, protectedUi));
12187
13095
  }
12188
- markTargetDetached(targetId) {
13096
+ markTargetDetached(targetId, options = {}) {
12189
13097
  return this.collectSessionIds((session) => {
12190
- const detached = session.sandbox.markTargetDetached(targetId);
13098
+ const detached = session.sandbox.markTargetDetached(targetId, options);
12191
13099
  if (session.target?.id === targetId && session.target.owner === "user") {
12192
13100
  this.notifyTargetOwnershipChange(this.targetOwnership.releaseTargetOwnership(targetId, session.id));
12193
13101
  }
@@ -12268,7 +13176,7 @@ class OpenCodeBrowserSessions {
12268
13176
  }
12269
13177
  networkStatus(id) {
12270
13178
  const session = this.sessions.get(id);
12271
- return session ? succeed6(session.sandbox.networkStatus()) : fail5(sessionError("not-found", `Session not found: ${id}`, id));
13179
+ return session ? succeed6(session.sandbox.networkStatus()) : fail6(sessionError("not-found", `Session not found: ${id}`, id));
12272
13180
  }
12273
13181
  networkStop(id, options = {}) {
12274
13182
  return this.withSessionOperation(id, "network stop", (session) => session.sandbox.networkStop(options));
@@ -12284,8 +13192,8 @@ class OpenCodeBrowserSessions {
12284
13192
  return this.admission.withAdmission(id, suspend2(() => {
12285
13193
  const session = manager.sessions.get(id);
12286
13194
  if (!session)
12287
- return fail5(sessionError("not-found", `Session not found: ${id}`, id));
12288
- return (beforePermit ? beforePermit(session) : void_3).pipe(andThen(manager.withLifecyclePermit(session, operation, gen(function* () {
13195
+ return fail6(sessionError("not-found", `Session not found: ${id}`, id));
13196
+ return (beforePermit ? beforePermit(session) : void_3).pipe(andThen2(manager.withLifecyclePermit(session, operation, gen(function* () {
12289
13197
  if (manager.sessions.get(id) !== session) {
12290
13198
  return yield* sessionError("inactive", `Session is no longer active: ${id}`, id);
12291
13199
  }
@@ -12303,7 +13211,7 @@ class OpenCodeBrowserSessions {
12303
13211
  session.updatedAt = new Date().toISOString();
12304
13212
  yield* manager.admission.commitPersistence();
12305
13213
  return result;
12306
- }), (session) => session.readOnly && request.method !== "GET" ? fail5(sessionError("invalid-request", `Read-only session ${sessionId} cannot make ${request.method} authenticated requests`, sessionId)) : void_3);
13214
+ }), (session) => session.readOnly && request.method !== "GET" ? fail6(sessionError("invalid-request", `Read-only session ${sessionId} cannot make ${request.method} authenticated requests`, sessionId)) : void_3);
12307
13215
  }
12308
13216
  execute(options) {
12309
13217
  return executeInSession(this.executionContext, options);
@@ -12408,7 +13316,7 @@ class OpenCodeBrowserSessions {
12408
13316
  catch: (cause) => cause
12409
13317
  }).pipe(timeoutOrElse({
12410
13318
  duration: this.hooks.journalTimeoutMs ?? 2000,
12411
- orElse: () => fail5(new Error(`Session journal write timed out after ${this.hooks.journalTimeoutMs ?? 2000}ms`))
13319
+ orElse: () => fail6(new Error(`Session journal write timed out after ${this.hooks.journalTimeoutMs ?? 2000}ms`))
12412
13320
  }), catch_((error) => sync2(() => {
12413
13321
  console.error("Session execute-record hook failed", error);
12414
13322
  })), asVoid2);
@@ -12492,7 +13400,7 @@ class OpenCodeBrowserSessions {
12492
13400
  const pending = Array.from(sessionRelayTargetIds(this.hooks, session)).filter((id) => !closed.has(id));
12493
13401
  if (pending.length === 0)
12494
13402
  return;
12495
- yield* forEach(pending, (targetId) => this.closeRelayTarget(targetId).pipe(ignore, andThen(sync2(() => {
13403
+ yield* forEach(pending, (targetId) => this.closeRelayTarget(targetId).pipe(ignore, andThen2(sync2(() => {
12496
13404
  closed.add(targetId);
12497
13405
  }))), { concurrency: 4, discard: true });
12498
13406
  }
@@ -12528,14 +13436,14 @@ class OpenCodeBrowserSessions {
12528
13436
  const timeout = sessionError("timeout", `Session ${operation} timed out waiting for active execute in ${session.id}`, session.id);
12529
13437
  return raceFirst(session.executeSemaphore.withPermit(suspend2(() => {
12530
13438
  if (state === "timed-out")
12531
- return fail5(timeout);
13439
+ return fail6(timeout);
12532
13440
  state = "started";
12533
13441
  return effect;
12534
13442
  }).pipe(uninterruptible)), sleep(this.hooks.lifecycleTimeoutMs ?? 1e4).pipe(flatMap3(() => {
12535
13443
  if (state === "started")
12536
13444
  return never;
12537
13445
  state = "timed-out";
12538
- return fail5(timeout);
13446
+ return fail6(timeout);
12539
13447
  })));
12540
13448
  });
12541
13449
  }
@@ -12637,7 +13545,7 @@ function relayHttpError(error) {
12637
13545
  return routeError(error instanceof Error ? error.message : String(error), 500, "internal");
12638
13546
  }
12639
13547
  function originPatterns(raw) {
12640
- return try_({
13548
+ return try_2({
12641
13549
  try: () => normalizeOriginPatterns(raw),
12642
13550
  catch: (cause) => cause instanceof OriginPatternError ? new Error(cause.message) : new Error("Invalid origin patterns", { cause })
12643
13551
  });
@@ -12649,8 +13557,8 @@ function sendNotFound(response) {
12649
13557
 
12650
13558
  // src/recording-relay.ts
12651
13559
  import crypto7 from "node:crypto";
12652
- import fs12 from "node:fs/promises";
12653
- import path12 from "node:path";
13560
+ import fs13 from "node:fs/promises";
13561
+ import path13 from "node:path";
12654
13562
  import { performance as performance4 } from "node:perf_hooks";
12655
13563
 
12656
13564
  // src/recording-relay/protocol.ts
@@ -12718,8 +13626,8 @@ function validateUint32(value, field, positive) {
12718
13626
  }
12719
13627
 
12720
13628
  // src/recording-relay/cdp-capture.ts
12721
- import fs11 from "node:fs/promises";
12722
- import path11 from "node:path";
13629
+ import fs12 from "node:fs/promises";
13630
+ import path12 from "node:path";
12723
13631
  function handleCdpScreencastFrame(context, recording, options) {
12724
13632
  const frame = parseScreencastFrame(options.params);
12725
13633
  acknowledgeScreencastFrame({
@@ -12784,7 +13692,7 @@ async function startCdpRecording(context, options, starting) {
12784
13692
  if (!artifactType) {
12785
13693
  return { success: false, error: "CDP recording output path must end in .webm or .mp4" };
12786
13694
  }
12787
- await fs11.mkdir(path11.dirname(options.outputPath), { recursive: true });
13695
+ await fs12.mkdir(path12.dirname(options.outputPath), { recursive: true });
12788
13696
  if (starting.cancelled)
12789
13697
  return cancelledResult();
12790
13698
  const frameRate = options.frameRate ?? defaultCdpFrameRate;
@@ -12923,7 +13831,7 @@ async function finishCdpRecording(context, recording) {
12923
13831
  await writeSourceFrame(recording, recording.lastFrame, endFrameNumber);
12924
13832
  recording.frameCount = endFrameNumber;
12925
13833
  await recording.encoder.finish();
12926
- const stat = await fs11.stat(recording.outputPath);
13834
+ const stat = await fs12.stat(recording.outputPath);
12927
13835
  const quality = recordingQuality(recording, durationMs);
12928
13836
  const metadata = {
12929
13837
  mode: "cdp",
@@ -12937,7 +13845,7 @@ async function finishCdpRecording(context, recording) {
12937
13845
  ...quality,
12938
13846
  mimeType: recording.artifactType === "mp4" ? "video/mp4" : "video/webm"
12939
13847
  };
12940
- await fs11.writeFile(`${recording.outputPath}.json`, `${JSON.stringify(metadata, null, 2)}
13848
+ await fs12.writeFile(`${recording.outputPath}.json`, `${JSON.stringify(metadata, null, 2)}
12941
13849
  `, "utf8");
12942
13850
  return {
12943
13851
  success: true,
@@ -13301,7 +14209,7 @@ class RecordingRelay {
13301
14209
  throw new Error("No tab capture data was received");
13302
14210
  await recording.file.sync();
13303
14211
  await recording.file.close();
13304
- await fs12.rename(recording.temporaryPath, recording.outputPath);
14212
+ await fs13.rename(recording.temporaryPath, recording.outputPath);
13305
14213
  recording.finalized = true;
13306
14214
  recording.resolveStop?.({
13307
14215
  success: true,
@@ -13347,7 +14255,7 @@ class RecordingRelay {
13347
14255
  await recording.writePromise.catch(() => {});
13348
14256
  await recording.file.close().catch(() => {});
13349
14257
  if (!recording.finalized)
13350
- await fs12.rm(recording.temporaryPath, { force: true }).catch(() => {});
14258
+ await fs13.rm(recording.temporaryPath, { force: true }).catch(() => {});
13351
14259
  if (this.activeRecordings.get(recording.tabId) === recording) {
13352
14260
  this.activeRecordings.delete(recording.tabId);
13353
14261
  this.recordingChanged(recording.tabId);
@@ -13371,11 +14279,11 @@ class RecordingRelay {
13371
14279
  if (cdpArtifactType(options.outputPath) !== "webm") {
13372
14280
  return { success: false, error: "tabCapture recording output path must end in .webm; use --mode cdp for MP4" };
13373
14281
  }
13374
- await fs12.mkdir(path12.dirname(options.outputPath), { recursive: true });
14282
+ await fs13.mkdir(path13.dirname(options.outputPath), { recursive: true });
13375
14283
  if (starting.cancelled)
13376
14284
  return { success: false, error: "Recording was cancelled while starting" };
13377
14285
  const temporaryPath = `${options.outputPath}.partial-${process.pid}-${crypto7.randomUUID()}`;
13378
- const file = await fs12.open(temporaryPath, "wx", 384);
14286
+ const file = await fs13.open(temporaryPath, "wx", 384);
13379
14287
  const recording = {
13380
14288
  tabId: options.tabId,
13381
14289
  ...options.sessionId ? { sessionId: options.sessionId } : {},
@@ -14621,28 +15529,56 @@ function replayTargetCreated(options) {
14621
15529
  }
14622
15530
  }
14623
15531
 
14624
- // src/relay/process-guard.ts
14625
- import http4 from "node:http";
14626
- var installRelayProcessGuard = acquireRelease(sync2(() => {
14627
- const onUncaughtException = (error, origin) => {
14628
- if (handleExecuteRealmException(error))
14629
- return;
14630
- handleRelayProcessFault("uncaughtException", error, { origin });
14631
- };
14632
- const onUnhandledRejection = (reason, promise) => {
14633
- if (handleExecuteRealmRejection(promise))
15532
+ // src/relay/data-navigation.ts
15533
+ var navigateTopFrameToDataUrl = fnUntraced(function* (options) {
15534
+ const url = getString2(options.params, "url")?.trim();
15535
+ if (!url || !/^data:/i.test(url))
15536
+ return;
15537
+ const { tabId, mainFrameIdsByTab, blankNavigationWaiters, registry, sendDebuggerCommand } = options;
15538
+ const frameId = mainFrameIdsByTab.get(tabId) ?? registry.tabTargets.get(tabId)?.targetInfo.targetId;
15539
+ const requestedFrameId = getString2(options.params, "frameId");
15540
+ if (!frameId || requestedFrameId !== undefined && requestedFrameId !== frameId || blankNavigationWaiters.has(tabId))
15541
+ return;
15542
+ const html = yield* tryPromise(() => dataUrlDocument2(url)).pipe(orElseSucceed(() => {
15543
+ return;
15544
+ }));
15545
+ if (html === undefined)
15546
+ return;
15547
+ const committedLoaders = new Set;
15548
+ let loaderCommitted = () => {};
15549
+ blankNavigationWaiters.set(tabId, (frameUrl, loaderId) => {
15550
+ if (frameUrl !== "about:blank" || loaderId === undefined)
14634
15551
  return;
14635
- handleRelayProcessFault("unhandledRejection", reason, { promise });
14636
- };
14637
- process.on("uncaughtException", onUncaughtException);
14638
- process.on("unhandledRejection", onUnhandledRejection);
14639
- return { onUncaughtException, onUnhandledRejection };
14640
- }), (handlers) => {
14641
- return sync2(() => {
14642
- process.off("uncaughtException", handlers.onUncaughtException);
14643
- process.off("unhandledRejection", handlers.onUnhandledRejection);
15552
+ committedLoaders.add(loaderId);
15553
+ loaderCommitted(loaderId);
14644
15554
  });
15555
+ return yield* gen(function* () {
15556
+ const navigated = yield* sendDebuggerCommand({ tabId, method: "Page.navigate", params: { url: "about:blank", frameId } });
15557
+ const loaderId = getString2(navigated, "loaderId");
15558
+ if (getString2(navigated, "errorText") || loaderId === undefined)
15559
+ return navigated;
15560
+ if (!committedLoaders.has(loaderId)) {
15561
+ const committed = yield* promise(() => new Promise((resolve) => {
15562
+ loaderCommitted = (id) => {
15563
+ if (id === loaderId)
15564
+ resolve();
15565
+ };
15566
+ })).pipe(timeoutOption(1e4));
15567
+ if (committed._tag === "None")
15568
+ return navigated;
15569
+ }
15570
+ yield* sendDebuggerCommand({ tabId, method: "Page.setDocumentContent", params: { frameId, html } });
15571
+ relayLog("navigate.data", { tabId, chars: html.length });
15572
+ return { frameId: getString2(navigated, "frameId") ?? frameId, loaderId };
15573
+ }).pipe(ensuring(sync2(() => {
15574
+ blankNavigationWaiters.delete(tabId);
15575
+ })));
14645
15576
  });
15577
+
15578
+ // src/relay/process-guard.ts
15579
+ import http4 from "node:http";
15580
+
15581
+ // src/relay/process-faults.ts
14646
15582
  var suppressedProcessFaults = { count: 0 };
14647
15583
  function relayProcessFaultSummary() {
14648
15584
  return {
@@ -14654,21 +15590,25 @@ function relayProcessFaultSummary() {
14654
15590
  function shouldSuppressRelayProcessFault(cause) {
14655
15591
  if (isPatchrightProtocolError(cause))
14656
15592
  return true;
14657
- const errorText = cause instanceof Error ? `${cause.message}
14658
- ${cause.stack ?? ""}` : String(cause);
15593
+ const errorText = `${safeErrorMessage(cause)}
15594
+ ${safeErrorStack(cause) ?? ""}`;
14659
15595
  return /playwright-core|patchright-core|coreBundle|Duplicate target/i.test(errorText);
14660
15596
  }
14661
15597
  function isPatchrightProtocolError(cause) {
14662
- return cause instanceof Error && Object.hasOwn(cause, "method") && Object.hasOwn(cause, "logs") && "type" in cause && (cause.type === "error" || cause.type === "closed" || cause.type === "crashed");
15598
+ if (!isSafeHostError(cause))
15599
+ return false;
15600
+ const type = Object.getOwnPropertyDescriptor(cause, "type")?.value;
15601
+ return Object.getOwnPropertyDescriptor(cause, "method") !== undefined && Object.getOwnPropertyDescriptor(cause, "logs") !== undefined && (type === "error" || type === "closed" || type === "crashed");
14663
15602
  }
14664
15603
  function isBenignClosedSessionRejection(cause) {
14665
- if (!(cause instanceof Error))
15604
+ if (!isSafeHostError(cause))
14666
15605
  return false;
14667
- if (!isPatchrightProtocolError(cause) && !/patchright-core|playwright-core|coreBundle/.test(cause.stack ?? ""))
15606
+ if (!isPatchrightProtocolError(cause) && !/patchright-core|playwright-core|coreBundle/.test(safeErrorStack(cause) ?? ""))
14668
15607
  return false;
14669
- return /^Protocol error \([\w.]+\): .*(session closed|Target closed|Extension disconnected|extension is not connected|Unknown CDP session|Detached while handling command|Relay closed)/i.test(cause.message);
15608
+ return /^Protocol error \([\w.]+\): .*(session closed|Target closed|Extension disconnected|extension is not connected|Unknown CDP session|Detached while handling command|Relay closed)/i.test(safeErrorMessage(cause));
14670
15609
  }
14671
15610
  var benignRejections = { count: 0, logged: 0, lastLogAt: 0 };
15611
+ var unattributedRejections = { count: 0, logged: 0, lastLogAt: 0 };
14672
15612
  function handleRelayProcessFault(kind, cause, detail, options = {}) {
14673
15613
  if (kind === "unhandledRejection" && isBenignClosedSessionRejection(cause)) {
14674
15614
  benignRejections.count += 1;
@@ -14677,31 +15617,46 @@ function handleRelayProcessFault(kind, cause, detail, options = {}) {
14677
15617
  const since = benignRejections.count - benignRejections.logged;
14678
15618
  benignRejections.lastLogAt = now;
14679
15619
  benignRejections.logged = benignRejections.count;
14680
- relayLog("process.benignRejections", { count: since, total: benignRejections.count, example: cause.message.slice(0, 160) });
15620
+ relayLog("process.benignRejections", { count: since, total: benignRejections.count, example: safeErrorMessage(cause).slice(0, 160) });
14681
15621
  }
14682
15622
  return;
14683
15623
  }
14684
15624
  if (shouldSuppressRelayProcessFault(cause)) {
14685
15625
  suppressedProcessFaults.count += 1;
14686
15626
  suppressedProcessFaults.lastAt = new Date().toISOString();
14687
- suppressedProcessFaults.lastMessage = (cause instanceof Error ? cause.message : String(cause)).slice(0, 300);
15627
+ suppressedProcessFaults.lastMessage = safeErrorMessage(cause).slice(0, 300);
14688
15628
  logProcessFault(kind, cause, detail, "keeping relay alive");
14689
15629
  return;
14690
15630
  }
15631
+ if (kind === "unhandledRejection") {
15632
+ const description = safeErrorMessage(cause);
15633
+ suppressedProcessFaults.count += 1;
15634
+ suppressedProcessFaults.lastAt = new Date().toISOString();
15635
+ suppressedProcessFaults.lastMessage = description.slice(0, 300);
15636
+ unattributedRejections.count += 1;
15637
+ const now = Date.now();
15638
+ if (description !== unattributedRejections.lastMessage || now - unattributedRejections.lastLogAt >= 60000) {
15639
+ const since = unattributedRejections.count - unattributedRejections.logged;
15640
+ unattributedRejections.lastLogAt = now;
15641
+ unattributedRejections.logged = unattributedRejections.count;
15642
+ unattributedRejections.lastMessage = description;
15643
+ logProcessFault(kind, cause, { suppressed: since }, "keeping relay alive; an unhandled rejection never stops the relay");
15644
+ }
15645
+ return;
15646
+ }
14691
15647
  logProcessFault(kind, cause, detail, "not a known Playwright dispatch fault; rethrowing");
14692
15648
  const rethrow = options.rethrow ?? rethrowProcessFault;
14693
15649
  rethrow(cause);
14694
15650
  }
14695
15651
  function rethrowProcessFault(cause) {
14696
- if (cause instanceof Error) {
15652
+ if (isSafeHostError(cause)) {
14697
15653
  throw cause;
14698
15654
  }
14699
- throw new Error(String(cause));
15655
+ throw new Error(safeErrorMessage(cause));
14700
15656
  }
14701
15657
  function logProcessFault(kind, cause, detail, disposition) {
14702
- const errorText = cause instanceof Error ? cause.stack ?? cause.message : String(cause);
14703
15658
  const message = `[browse relay] ${kind}; ${disposition}
14704
- ${errorText}`;
15659
+ ${safeErrorStack(cause) ?? safeErrorMessage(cause)}`;
14705
15660
  console.error(message);
14706
15661
  if (process.env.OPENCODE_BROWSER_MANAGED_RELAY === "1")
14707
15662
  appendManagedRelayProcessLog(message);
@@ -14712,6 +15667,30 @@ ${errorText}`;
14712
15667
  function debugEnvironmentEnabled(value) {
14713
15668
  return value !== undefined && ["1", "true", "yes", "on"].includes(value.toLowerCase());
14714
15669
  }
15670
+
15671
+ // src/relay/process-guard.ts
15672
+ var installRelayProcessGuard = acquireRelease(sync2(() => {
15673
+ const onUncaughtException = (error, origin) => {
15674
+ if (handleExecuteRealmException(error))
15675
+ return;
15676
+ handleRelayProcessFault("uncaughtException", error, { origin });
15677
+ };
15678
+ const onUnhandledRejection = (reason, promise) => {
15679
+ if (handleExecuteRealmRejection(promise, reason)) {
15680
+ relayLog("process.executeRejection");
15681
+ return;
15682
+ }
15683
+ handleRelayProcessFault("unhandledRejection", reason, {});
15684
+ };
15685
+ process.on("uncaughtException", onUncaughtException);
15686
+ process.on("unhandledRejection", onUnhandledRejection);
15687
+ return { onUncaughtException, onUnhandledRejection };
15688
+ }), (handlers) => {
15689
+ return sync2(() => {
15690
+ process.off("uncaughtException", handlers.onUncaughtException);
15691
+ process.off("unhandledRejection", handlers.onUnhandledRejection);
15692
+ });
15693
+ });
14715
15694
  function processAlive2(pid) {
14716
15695
  try {
14717
15696
  process.kill(pid, 0);
@@ -14797,7 +15776,15 @@ function createCdpDispatcher(options) {
14797
15776
  return;
14798
15777
  yield* ghostCursor.mouseEvent(mouseOptions.tabId, mouseOptions.message.params);
14799
15778
  });
15779
+ function captureScreenshotNudgeParams(params) {
15780
+ const nudge = { ...params, format: "jpeg", quality: 1 };
15781
+ if (nudge.clip === undefined)
15782
+ return nudge;
15783
+ const { captureBeyondViewport: _fullPage, ...clipped } = nudge;
15784
+ return clipped;
15785
+ }
14800
15786
  function captureScreenshotNudged(command) {
15787
+ const nudgeParams = captureScreenshotNudgeParams(command.params);
14801
15788
  const nudges = gen(function* () {
14802
15789
  for (const delayMs of [600, 1000, 1500, 2000, 3000, 5000, 8000]) {
14803
15790
  yield* sleep(delayMs);
@@ -14805,60 +15792,17 @@ function createCdpDispatcher(options) {
14805
15792
  yield* forkDetach(sendDebuggerCommand({
14806
15793
  tabId: command.tabId,
14807
15794
  method: "Page.captureScreenshot",
14808
- params: { format: "jpeg", quality: 1, clip: { x: 0, y: 0, width: 1, height: 1, scale: 1 } }
15795
+ params: nudgeParams
14809
15796
  }).pipe(ignore));
14810
15797
  }
14811
15798
  return yield* never;
14812
15799
  });
14813
15800
  return raceFirst(sendDebuggerCommand(command), nudges);
14814
15801
  }
14815
- const navigateTopFrameToDataUrl = fnUntraced(function* (tabId, params) {
14816
- const url = getString2(params, "url")?.trim();
14817
- if (!url || !/^data:/i.test(url))
14818
- return;
14819
- const frameId = mainFrameIdsByTab.get(tabId) ?? registry.tabTargets.get(tabId)?.targetInfo.targetId;
14820
- const requestedFrameId = getString2(params, "frameId");
14821
- if (!frameId || requestedFrameId !== undefined && requestedFrameId !== frameId || blankNavigationWaiters.has(tabId))
14822
- return;
14823
- const html = yield* tryPromise(() => dataUrlDocument2(url)).pipe(orElseSucceed(() => {
14824
- return;
14825
- }));
14826
- if (html === undefined)
14827
- return;
14828
- const committedLoaders = new Set;
14829
- let loaderCommitted = () => {};
14830
- blankNavigationWaiters.set(tabId, (frameUrl, loaderId) => {
14831
- if (frameUrl !== "about:blank" || loaderId === undefined)
14832
- return;
14833
- committedLoaders.add(loaderId);
14834
- loaderCommitted(loaderId);
14835
- });
14836
- return yield* gen(function* () {
14837
- const navigated = yield* sendDebuggerCommand({ tabId, method: "Page.navigate", params: { url: "about:blank", frameId } });
14838
- const loaderId = getString2(navigated, "loaderId");
14839
- if (getString2(navigated, "errorText") || loaderId === undefined)
14840
- return navigated;
14841
- if (!committedLoaders.has(loaderId)) {
14842
- const committed = yield* promise(() => new Promise((resolve) => {
14843
- loaderCommitted = (id) => {
14844
- if (id === loaderId)
14845
- resolve();
14846
- };
14847
- })).pipe(timeoutOption(1e4));
14848
- if (committed._tag === "None")
14849
- return navigated;
14850
- }
14851
- yield* sendDebuggerCommand({ tabId, method: "Page.setDocumentContent", params: { frameId, html } });
14852
- relayLog("navigate.data", { tabId, chars: html.length });
14853
- return { frameId: getString2(navigated, "frameId") ?? frameId, loaderId };
14854
- }).pipe(ensuring(sync2(() => {
14855
- blankNavigationWaiters.delete(tabId);
14856
- })));
14857
- });
14858
15802
  const routeCdpCommand = fn("Relay.routeCdpCommand")(function* (socket, message) {
14859
15803
  const clientOpenCodeBrowserSessionId = cdpClients.sessionId(socket);
14860
15804
  if (!shutdownControl.accepting && (!cdpClients.isSandbox(socket) || !clientOpenCodeBrowserSessionId || !sessions.hasPendingWork(clientOpenCodeBrowserSessionId))) {
14861
- return yield* fail5(new Error("Relay is draining for an explicit restart"));
15805
+ return yield* fail6(new Error("Relay is draining for an explicit restart"));
14862
15806
  }
14863
15807
  const guardMessage = guardCdpMethod({
14864
15808
  method: message.method,
@@ -14868,7 +15812,7 @@ function createCdpDispatcher(options) {
14868
15812
  pageUrls: () => cdpRouter.visibleRoots(socket).map((target) => target.targetInfo.url)
14869
15813
  });
14870
15814
  if (guardMessage) {
14871
- return yield* fail5(new Error(guardMessage));
15815
+ return yield* fail6(new Error(guardMessage));
14872
15816
  }
14873
15817
  if (message.method === "Page.navigate" || message.method === "Target.createTarget") {
14874
15818
  const tabSessionId = message.method === "Page.navigate" ? (() => {
@@ -14884,7 +15828,7 @@ function createCdpDispatcher(options) {
14884
15828
  sessionId: tabSessionId ?? clientOpenCodeBrowserSessionId
14885
15829
  }));
14886
15830
  if (refusal)
14887
- return yield* fail5(new Error(refusal));
15831
+ return yield* fail6(new Error(refusal));
14888
15832
  }
14889
15833
  if (message.method === "Browser.getVersion") {
14890
15834
  return {
@@ -14915,7 +15859,7 @@ function createCdpDispatcher(options) {
14915
15859
  if (message.method === "Target.setAutoAttach" && message.sessionId && registry.targets.has(message.sessionId)) {
14916
15860
  const target = cdpRouter.rootForSession(socket, message.sessionId);
14917
15861
  if (!target) {
14918
- return yield* fail5(new Error(`Target not found: ${message.sessionId}`));
15862
+ return yield* fail6(new Error(`Target not found: ${message.sessionId}`));
14919
15863
  }
14920
15864
  const result = yield* sendDebuggerCommand({ tabId: target.tabId, method: "Target.setAutoAttach", params: message.params ?? {} });
14921
15865
  replayChildTargetsForParent({ socket, parentSessionId: target.sessionId, registry, clients: cdpClients });
@@ -14941,7 +15885,7 @@ function createCdpDispatcher(options) {
14941
15885
  replayChildFrameNavigation({ socket, registry, target });
14942
15886
  return { sessionId: target.sessionId };
14943
15887
  }
14944
- return yield* fail5(new Error(`Target not found: ${targetId}`));
15888
+ return yield* fail6(new Error(`Target not found: ${targetId}`));
14945
15889
  }
14946
15890
  if (message.method === "Target.getTargetInfo") {
14947
15891
  const targetId = getString2(message.params, "targetId") ?? "";
@@ -14952,13 +15896,13 @@ function createCdpDispatcher(options) {
14952
15896
  if (!target) {
14953
15897
  if (!targetId && !message.sessionId)
14954
15898
  return {};
14955
- return yield* fail5(new Error(`Target not found: ${targetId || message.sessionId || "unknown"}`));
15899
+ return yield* fail6(new Error(`Target not found: ${targetId || message.sessionId || "unknown"}`));
14956
15900
  }
14957
15901
  return { targetInfo: target.targetInfo };
14958
15902
  }
14959
15903
  if (message.method === "Target.createTarget" || message.method === "Target.closeTarget") {
14960
15904
  if (message.method === "Target.createTarget") {
14961
- const url = getString2(message.params, "url") ?? "about:blank";
15905
+ const url = createTargetUrl2(message.params);
14962
15906
  const opencodeBrowserSessionId = cdpClients.sessionId(socket);
14963
15907
  const autoAttachParams = cdpClients.autoAttachParams(socket);
14964
15908
  const target = yield* createAndAttachTab({
@@ -14989,7 +15933,7 @@ function createCdpDispatcher(options) {
14989
15933
  return {};
14990
15934
  }
14991
15935
  const normalizedMessage = removeDefaultLightColorSchemeEmulation(message);
14992
- const route = yield* try_({
15936
+ const route = yield* try_2({
14993
15937
  try: () => cdpRouter.resolveCommandRoute(socket, message),
14994
15938
  catch: (error) => error instanceof Error ? error : new Error(String(error))
14995
15939
  });
@@ -15002,7 +15946,14 @@ function createCdpDispatcher(options) {
15002
15946
  if (message.method === ghostCursorCommandMethod)
15003
15947
  return yield* ghostCursor.command(tabId, message.params);
15004
15948
  if (message.method === "Page.navigate" && route.chromeSessionId === undefined) {
15005
- const dataNavigation = yield* navigateTopFrameToDataUrl(tabId, message.params);
15949
+ const dataNavigation = yield* navigateTopFrameToDataUrl({
15950
+ tabId,
15951
+ params: message.params,
15952
+ mainFrameIdsByTab,
15953
+ blankNavigationWaiters,
15954
+ registry,
15955
+ sendDebuggerCommand
15956
+ });
15006
15957
  if (dataNavigation)
15007
15958
  return dataNavigation;
15008
15959
  }
@@ -15029,11 +15980,11 @@ function createCdpDispatcher(options) {
15029
15980
  return fnUntraced(function* (socket, raw) {
15030
15981
  const message = parseJsonObject(raw);
15031
15982
  if (!isCdpRequest(message)) {
15032
- return yield* fail5(new Error("Invalid CDP request"));
15983
+ return yield* fail6(new Error("Invalid CDP request"));
15033
15984
  }
15034
15985
  const frameTreeSent = message.method === "Page.getFrameTree" ? admitFrameTreeResponse(socket, message.sessionId) : undefined;
15035
15986
  debugLog?.(`cdp<- ${cdpClients.sessionId(socket) ?? "raw"} #${message.id} ${message.method} ${message.sessionId ?? ""}`);
15036
- yield* matchEffect(routeCdpCommand(socket, message), {
15987
+ yield* matchEffect2(routeCdpCommand(socket, message), {
15037
15988
  onFailure: (error) => {
15038
15989
  return sync2(() => {
15039
15990
  const runtimeEvaluation = isRuntimeEvaluationMethod(message.method);
@@ -15081,11 +16032,11 @@ function createExtensionCommands(options) {
15081
16032
  if (tabId !== undefined) {
15082
16033
  const owner = browsers.browserTab(tabId);
15083
16034
  if (!owner)
15084
- return fail5(new Error("browse extension is not connected"));
16035
+ return fail6(new Error("browse extension is not connected"));
15085
16036
  return sendToBrowser(owner.link, { ...command, params: { ...command.params, tabId: owner.tabId } });
15086
16037
  }
15087
16038
  const target = link ?? browsers.defaultLink();
15088
- return target ? sendToBrowser(target, command) : fail5(new Error("browse extension is not connected"));
16039
+ return target ? sendToBrowser(target, command) : fail6(new Error("browse extension is not connected"));
15089
16040
  };
15090
16041
  const sendExtensionBestEffort = (command, link) => {
15091
16042
  runPromise(ignore(sendToExtension(command, link))).catch(() => {});
@@ -15098,13 +16049,13 @@ function createExtensionCommands(options) {
15098
16049
  const sendToEach = (command) => gen(function* () {
15099
16050
  const links = browsers.list().filter((link) => link.rpc.connected);
15100
16051
  if (links.length === 0)
15101
- return yield* fail5(new Error("browse extension is not connected"));
16052
+ return yield* fail6(new Error("browse extension is not connected"));
15102
16053
  const results = yield* forEach(links, (link) => result(sendToBrowser(link, command)), { concurrency: "unbounded" });
15103
16054
  const succeeded = results.find(isSuccess);
15104
16055
  if (succeeded)
15105
16056
  return succeeded.success;
15106
16057
  const failed = results.find(isFailure);
15107
- return yield* fail5(failed?.failure ?? new Error("browse extension is not connected"));
16058
+ return yield* fail6(failed?.failure ?? new Error("browse extension is not connected"));
15108
16059
  });
15109
16060
  return { sendToExtension, sendExtensionBestEffort, sendToEveryBrowser, sendToEach };
15110
16061
  }
@@ -15140,6 +16091,7 @@ function createExtensionEventHandler(options) {
15140
16091
  refreshPageStatus,
15141
16092
  refreshTabGrouping,
15142
16093
  handleToolbarClick,
16094
+ handleDebuggingBarCancel,
15143
16095
  cancelTargetHandoffs,
15144
16096
  detachTargetState,
15145
16097
  detachChildTargetState,
@@ -15394,6 +16346,13 @@ function createExtensionEventHandler(options) {
15394
16346
  }
15395
16347
  return;
15396
16348
  }
16349
+ if (reason === "canceled_by_user") {
16350
+ if (eventTabId) {
16351
+ handleDebuggingBarCancel(eventTabId);
16352
+ detachTargetState(eventTabId, { releasedByUser: true });
16353
+ }
16354
+ return;
16355
+ }
15397
16356
  if (eventTabId)
15398
16357
  detachTargetState(eventTabId);
15399
16358
  return;
@@ -15628,7 +16587,7 @@ function createExtensionEventHandler(options) {
15628
16587
 
15629
16588
  // src/relay/extension-handshake.ts
15630
16589
  import crypto8 from "node:crypto";
15631
- import fs13 from "node:fs";
16590
+ import fs14 from "node:fs";
15632
16591
  import { WebSocket as WebSocket3 } from "ws";
15633
16592
  var maxPreAuthMessageBytes = 64 * 1024;
15634
16593
  var preAuthHandshakeTimeoutMs = 1e4;
@@ -15650,7 +16609,7 @@ class ExtensionHandshake {
15650
16609
  this.options = options;
15651
16610
  }
15652
16611
  rejectedProtocol() {
15653
- return this.mismatch ?? (fs13.existsSync(oldStoreMarker()) ? extensionProtocolCompatibility(2) : undefined);
16612
+ return this.mismatch ?? (fs14.existsSync(oldStoreMarker()) ? extensionProtocolCompatibility(2) : undefined);
15654
16613
  }
15655
16614
  mismatchAdvice(version) {
15656
16615
  return extensionProtocolAdvice(version, { install: installCommand() }, !this.mismatch || this.mismatch.origin === `chrome-extension://${this.options.storeId}` ? "store" : this.mismatch.origin === stableUnpackedExtensionOrigin2 ? "unpacked" : undefined);
@@ -15805,8 +16764,8 @@ class ExtensionHandshake {
15805
16764
  return;
15806
16765
  }
15807
16766
  this.mismatch = undefined;
15808
- if (fs13.existsSync(oldStoreMarker()))
15809
- fs13.rmSync(oldStoreMarker(), { force: true });
16767
+ if (fs14.existsSync(oldStoreMarker()))
16768
+ fs14.rmSync(oldStoreMarker(), { force: true });
15810
16769
  if (message.method === "protocol") {
15811
16770
  if (message.params?.unpaired === true) {
15812
16771
  this.lastUnpaired = Date.now();
@@ -16205,7 +17164,7 @@ function createRelayHousekeeping(options) {
16205
17164
  const target = registry.targetsByTargetId.get(targetId);
16206
17165
  return target ? isTabBusy(target.tabId) : false;
16207
17166
  }
16208
- }).pipe(andThen(() => forEach(tabActivity.idleUserTargets(registry.listRootTargets(), Date.now(), idleTabTtlMs), (target) => detachIdleUserTarget(target.targetInfo.targetId).pipe(ignore), { discard: true })))).catch(() => {});
17167
+ }).pipe(andThen2(() => forEach(tabActivity.idleUserTargets(registry.listRootTargets(), Date.now(), idleTabTtlMs), (target) => detachIdleUserTarget(target.targetInfo.targetId).pipe(ignore), { discard: true })))).catch(() => {});
16209
17168
  }, 60000);
16210
17169
  idleReapTimer.unref();
16211
17170
  }
@@ -16242,7 +17201,7 @@ function createRelaySettingsSync(options) {
16242
17201
  const extensionSettings = (method, values) => gen(function* () {
16243
17202
  if (!browsers.connected) {
16244
17203
  const rejected = handshake.rejectedProtocol();
16245
- return yield* fail5(new Error(rejected ? handshake.mismatchAdvice(rejected.version) : "The browse extension isn't connected, so its settings can't be read or changed. Ask the user to open the browser with the extension; its options page shows whether it's connected."));
17204
+ return yield* fail6(new Error(rejected ? handshake.mismatchAdvice(rejected.version) : "The browse extension isn't connected, so its settings can't be read or changed. Ask the user to open the browser with the extension; its options page shows whether it's connected."));
16246
17205
  }
16247
17206
  const result = yield* sendToExtension({ method, ...values ? { params: { values } } : {} }).pipe(mapError((error) => /Invalid extension command/.test(error.message) ? new Error(`The connected browse extension is too old to read or change settings from here. Update browse (\`${installCommand()}\`) and reload the extension, or change them on its options page.`) : error));
16248
17207
  return settingsFromExtension(result);
@@ -16284,7 +17243,7 @@ function createRelaySettingsSync(options) {
16284
17243
  const httpSettings = {
16285
17244
  get: () => extensionSettings("settings.get").pipe(map5((stored) => describeSettings(withRelaySettings(stored), userSettingOverrides()))),
16286
17245
  set: (input) => gen(function* () {
16287
- const requested = yield* try_({
17246
+ const requested = yield* try_2({
16288
17247
  try: () => parseSettingChanges(input),
16289
17248
  catch: (error) => error instanceof SettingsInputError ? new HttpRouteError2({ message: error.message, status: 400, code: "invalid-request" }) : new Error(String(error))
16290
17249
  });
@@ -16533,6 +17492,17 @@ function createTabPresentation(options) {
16533
17492
  console.error("Toolbar toggle failed", error);
16534
17493
  });
16535
17494
  }
17495
+ function handleDebuggingBarCancel(tabId) {
17496
+ const sessions = getSessions();
17497
+ const target = registry.tabTargets.get(tabId);
17498
+ if (!target)
17499
+ return;
17500
+ const sessionId = pageStatusSessionId(target) ?? activeHandoffSessionIdForTab(tabId);
17501
+ if (sessionId && sessions.isExecuting(sessionId)) {
17502
+ relayLog("execute.stopped", { tabId, session: sessionId, from: "debugging-bar" });
17503
+ sessions.stopExecution(sessionId, debuggingBarDismissedStop, "debugging-bar-cancel");
17504
+ }
17505
+ }
16536
17506
  function presentAttachedTarget(committedTarget) {
16537
17507
  tabActivity.touch(committedTarget.tabId);
16538
17508
  const tabId = committedTarget.tabId;
@@ -16567,6 +17537,7 @@ function createTabPresentation(options) {
16567
17537
  requestHandoff,
16568
17538
  onSessionExecuteStateChange,
16569
17539
  handleToolbarClick,
17540
+ handleDebuggingBarCancel,
16570
17541
  presentAttachedTarget
16571
17542
  };
16572
17543
  }
@@ -16715,8 +17686,9 @@ function createRelayTransportServers(deps) {
16715
17686
 
16716
17687
  // src/cdp/root-target-lifecycle.ts
16717
17688
  var DEFAULT_INVENTORY_COMMAND_TIMEOUT_MS = 5000;
17689
+ var DEFAULT_ATTACH_COMMAND_TIMEOUT_MS = 1e4;
16718
17690
 
16719
- class InventoryTimeout extends TaggedError2()("RootTargetLifecycle.InventoryTimeout", {
17691
+ class RootTargetTimeout extends TaggedError2()("RootTargetLifecycle.CommandTimeout", {
16720
17692
  message: String3
16721
17693
  }) {
16722
17694
  }
@@ -16731,13 +17703,13 @@ class RootTargetLifecycle {
16731
17703
  scope;
16732
17704
  run;
16733
17705
  static make = fn("RootTargetLifecycle.make")(function* (options) {
16734
- const scope = yield* make6();
17706
+ const scope = yield* make11();
16735
17707
  const run = runForkWith(yield* context2());
16736
17708
  return yield* acquireRelease(sync2(() => new RootTargetLifecycle(options, scope, run)), (lifecycle) => lifecycle.close());
16737
17709
  });
16738
17710
  tabs = new Map;
16739
17711
  workers = new Map;
16740
- idle = makeUnsafe5(true);
17712
+ idle = makeUnsafe2(true);
16741
17713
  active = 0;
16742
17714
  closing = false;
16743
17715
  failedTabs = new Map;
@@ -16756,7 +17728,7 @@ class RootTargetLifecycle {
16756
17728
  work.revision += 1;
16757
17729
  this.failedTabs.delete(tabId);
16758
17730
  }
16759
- attach = fn("RootTargetLifecycle.attach")((options) => this.withPermit(options.tabId, options.expectedExtensionGeneration, (transition) => this.attachUnlocked(transition, options)));
17731
+ attach = fn("RootTargetLifecycle.attach")((options) => this.withPermit(options.tabId, options.expectedExtensionGeneration, (transition) => this.attachUnlocked(transition, options), this.options.attachCommandTimeoutMs ?? DEFAULT_ATTACH_COMMAND_TIMEOUT_MS));
16760
17732
  reconcile = fn("RootTargetLifecycle.reconcile")((tabId, generation) => this.withPermit(tabId, generation, (transition) => this.reconcileUnlocked(transition)));
16761
17733
  queue(options) {
16762
17734
  if (this.closing)
@@ -16783,7 +17755,7 @@ class RootTargetLifecycle {
16783
17755
  work.users += 1;
16784
17756
  const worker = {
16785
17757
  generation,
16786
- done: makeUnsafe5(),
17758
+ done: makeUnsafe2(),
16787
17759
  attachIfMissing: options.attachIfMissing,
16788
17760
  renewed: options.renewed === true,
16789
17761
  pending: false,
@@ -16816,7 +17788,7 @@ class RootTargetLifecycle {
16816
17788
  }).pipe(tapError((error) => sync2(() => lifecycle.options.reportError(options.errorMessage, error))), retry({
16817
17789
  times: 2,
16818
17790
  schedule: spaced(0).pipe(modifyDelay(({ attempt }) => succeed6(100 * attempt))),
16819
- while: (error) => !(error instanceof GenerationChanged) && !(error instanceof InventoryTimeout) && !lifecycle.closing && generation === lifecycle.options.extension.generation(options.tabId) && revision === work.revision
17791
+ while: (error) => !(error instanceof GenerationChanged) && !(error instanceof RootTargetTimeout) && !lifecycle.closing && generation === lifecycle.options.extension.generation(options.tabId) && revision === work.revision
16820
17792
  }));
16821
17793
  if (lifecycle.closing || generation !== lifecycle.options.extension.generation(options.tabId))
16822
17794
  return null;
@@ -16867,7 +17839,7 @@ class RootTargetLifecycle {
16867
17839
  const lifecycle = this;
16868
17840
  return suspend2(() => {
16869
17841
  if (lifecycle.closing)
16870
- return fail5(new Error("Relay is closing"));
17842
+ return fail6(new Error("Relay is closing"));
16871
17843
  const generation = expectedGeneration ?? lifecycle.options.extension.generation(tabId);
16872
17844
  const work = lifecycle.tabWork(tabId);
16873
17845
  const revision = work.revision;
@@ -16884,7 +17856,7 @@ class RootTargetLifecycle {
16884
17856
  root: lifecycle.options.registry.tabTargets.get(tabId),
16885
17857
  staged: lifecycle.options.registry.stagedRootTarget(tabId)
16886
17858
  };
16887
- return lifecycle.check(transition).pipe(andThen(() => use(transition)));
17859
+ return lifecycle.check(transition).pipe(andThen2(() => use(transition)));
16888
17860
  })).pipe(ensuring(sync2(() => {
16889
17861
  if (--work.users === 0 && !lifecycle.options.registry.routingRootTarget(tabId))
16890
17862
  lifecycle.tabs.delete(tabId);
@@ -16906,14 +17878,14 @@ class RootTargetLifecycle {
16906
17878
  return yield* new GenerationChanged({ message: "Root target generation changed during reconciliation" });
16907
17879
  });
16908
17880
  step(transition, effect) {
16909
- return this.check(transition).pipe(andThen(effect), catch_((error) => this.check(transition).pipe(andThen(fail5(error)))), tap(() => this.check(transition)));
17881
+ return this.check(transition).pipe(andThen2(effect), catch_((error) => this.check(transition).pipe(andThen2(fail6(error)))), tap(() => this.check(transition)));
16910
17882
  }
16911
17883
  command(transition, method, params = {}) {
16912
17884
  const send = this.options.extension.send({ method: "debugger.sendCommand", params: { tabId: transition.tabId, method, params } });
16913
17885
  const timeoutMs = transition.timeoutMs;
16914
17886
  return this.step(transition, timeoutMs === undefined ? send : send.pipe(timeoutOrElse({
16915
17887
  duration: timeoutMs,
16916
- orElse: () => fail5(new InventoryTimeout({ message: `${method} did not answer within ${timeoutMs} ms while reconciling tab ${transition.tabId}` }))
17888
+ orElse: () => fail6(new RootTargetTimeout({ message: `${method} did not answer within ${timeoutMs} ms on tab ${transition.tabId}` }))
16917
17889
  })));
16918
17890
  }
16919
17891
  attachUnlocked = fnUntraced(function* (transition, options) {
@@ -16921,14 +17893,12 @@ class RootTargetLifecycle {
16921
17893
  if (!options.alreadyAttached)
16922
17894
  yield* this.step(transition, this.options.extension.send({ method: "debugger.attach", params: { tabId } }));
16923
17895
  yield* this.command(transition, "Page.enable");
16924
- yield* gen({ self: this }, function* () {
16925
- yield* this.command(transition, "Emulation.setFocusEmulationEnabled", { enabled: false });
16926
- }).pipe(ignore);
17896
+ yield* this.command(transition, "Emulation.setFocusEmulationEnabled", { enabled: false }).pipe(catchIf((error) => !(error instanceof RootTargetTimeout), () => void_3));
16927
17897
  yield* this.check(transition);
16928
17898
  const result = yield* this.command(transition, "Target.getTargetInfo");
16929
17899
  const reportedTargetInfo = getTargetInfo2(result.targetInfo);
16930
17900
  if (!reportedTargetInfo)
16931
- return yield* fail5(new Error("Target.getTargetInfo did not return targetInfo"));
17901
+ return yield* fail6(new Error("Target.getTargetInfo did not return targetInfo"));
16932
17902
  const targetInfo = options.openerTargetId && !reportedTargetInfo.openerId ? { ...reportedTargetInfo, openerId: options.openerTargetId } : reportedTargetInfo;
16933
17903
  const restored = options.opencodeBrowserSessionId ? undefined : this.options.sessions.persistedTargetOwner(targetInfo.targetId);
16934
17904
  const opencodeBrowserSessionId = options.opencodeBrowserSessionId ?? restored?.sessionId;
@@ -16952,7 +17922,7 @@ class RootTargetLifecycle {
16952
17922
  yield* this.check(transition);
16953
17923
  const targetInfo = getTargetInfo2(result.targetInfo);
16954
17924
  if (!targetInfo) {
16955
- return yield* fail5(new Error(staged ? "Unable to verify staged root target" : "Unable to verify committed root target"));
17925
+ return yield* fail6(new Error(staged ? "Unable to verify staged root target" : "Unable to verify committed root target"));
16956
17926
  }
16957
17927
  if (staged?.targetInfo.targetId === targetInfo.targetId) {
16958
17928
  yield* this.finish(transition, staged);
@@ -16975,11 +17945,11 @@ class RootTargetLifecycle {
16975
17945
  yield* this.command(transition, "Target.setAutoAttach", autoAttachParams ?? { autoAttach: true, waitForDebuggerOnStart: false, flatten: true });
16976
17946
  const result = yield* this.command(transition, "Target.getTargetInfo");
16977
17947
  if (getTargetInfo2(result.targetInfo)?.targetId !== target.targetInfo.targetId) {
16978
- return yield* fail5(new Error(`Root target changed while preparing ${target.targetInfo.targetId}`));
17948
+ return yield* fail6(new Error(`Root target changed while preparing ${target.targetInfo.targetId}`));
16979
17949
  }
16980
17950
  const change = registry.commitStagedRootTarget(target.tabId, target.sessionId);
16981
17951
  if (!change)
16982
- return yield* fail5(new Error(`Staged root target changed before commit: ${target.targetInfo.targetId}`));
17952
+ return yield* fail6(new Error(`Staged root target changed before commit: ${target.targetInfo.targetId}`));
16983
17953
  transition.root = change.target;
16984
17954
  transition.staged = undefined;
16985
17955
  if (change.kind === "replaced") {
@@ -17007,9 +17977,9 @@ class RootTargetLifecycle {
17007
17977
  }
17008
17978
 
17009
17979
  // src/session-manager/catalog.ts
17010
- import fs14 from "node:fs/promises";
17980
+ import fs15 from "node:fs/promises";
17011
17981
  import os6 from "node:os";
17012
- import path13 from "node:path";
17982
+ import path14 from "node:path";
17013
17983
  import crypto9 from "node:crypto";
17014
17984
  var PersistedSession = Struct({
17015
17985
  id: String3,
@@ -17030,7 +18000,7 @@ var Catalog = Struct({
17030
18000
  sessions: ArraySchema(PersistedSession)
17031
18001
  });
17032
18002
  function defaultSessionCatalogPath(port, home = os6.homedir()) {
17033
- return path13.join(dataRoot(home), "relays", String(port), "sessions.json");
18003
+ return path14.join(dataRoot(home), "relays", String(port), "sessions.json");
17034
18004
  }
17035
18005
 
17036
18006
  class SessionCatalog {
@@ -17041,7 +18011,7 @@ class SessionCatalog {
17041
18011
  async load() {
17042
18012
  let text;
17043
18013
  try {
17044
- text = await fs14.readFile(this.filePath, "utf8");
18014
+ text = await fs15.readFile(this.filePath, "utf8");
17045
18015
  } catch (error) {
17046
18016
  if (isNodeError(error) && error.code === "ENOENT")
17047
18017
  return [];
@@ -17057,7 +18027,7 @@ class SessionCatalog {
17057
18027
  const detail = error instanceof Error && error.message ? `: ${error.message}` : "";
17058
18028
  const corruptPath = `${this.filePath}.corrupt-${Date.now()}`;
17059
18029
  try {
17060
- await fs14.rename(this.filePath, corruptPath);
18030
+ await fs15.rename(this.filePath, corruptPath);
17061
18031
  console.error(`Browse session catalog at ${this.filePath} was unreadable${detail}; moved it to ${corruptPath} and started with no saved sessions`);
17062
18032
  } catch (moveError) {
17063
18033
  console.error(`Browse session catalog at ${this.filePath} was unreadable${detail}; could not move it aside (${moveError instanceof Error ? moveError.message : String(moveError)}), starting with no saved sessions`);
@@ -17066,21 +18036,21 @@ class SessionCatalog {
17066
18036
  }
17067
18037
  }
17068
18038
  async save(sessions) {
17069
- const directory = path13.dirname(this.filePath);
18039
+ const directory = path14.dirname(this.filePath);
17070
18040
  const temporaryPath = `${this.filePath}.${process.pid}.${crypto9.randomUUID()}.tmp`;
17071
18041
  const contents = `${JSON.stringify({ version: 1, sessions }, null, 2)}
17072
18042
  `;
17073
18043
  let temporaryFile;
17074
18044
  try {
17075
- await fs14.mkdir(directory, { recursive: true, mode: 448 });
17076
- await fs14.chmod(directory, 448);
17077
- temporaryFile = await fs14.open(temporaryPath, "wx", 384);
18045
+ await fs15.mkdir(directory, { recursive: true, mode: 448 });
18046
+ await fs15.chmod(directory, 448);
18047
+ temporaryFile = await fs15.open(temporaryPath, "wx", 384);
17078
18048
  await temporaryFile.writeFile(contents, "utf8");
17079
18049
  await temporaryFile.sync();
17080
18050
  await temporaryFile.close();
17081
18051
  temporaryFile = undefined;
17082
- await fs14.rename(temporaryPath, this.filePath);
17083
- const directoryHandle = await fs14.open(directory, "r");
18052
+ await fs15.rename(temporaryPath, this.filePath);
18053
+ const directoryHandle = await fs15.open(directory, "r");
17084
18054
  try {
17085
18055
  try {
17086
18056
  await directoryHandle.sync();
@@ -17096,7 +18066,7 @@ class SessionCatalog {
17096
18066
  await temporaryFile?.close();
17097
18067
  } catch {}
17098
18068
  try {
17099
- await fs14.rm(temporaryPath, { force: true });
18069
+ await fs15.rm(temporaryPath, { force: true });
17100
18070
  } catch {}
17101
18071
  throw new Error(`Could not write browse session catalog at ${this.filePath}`, { cause: error });
17102
18072
  }
@@ -17119,6 +18089,7 @@ class SessionNavigationGuard {
17119
18089
  warnings = new Map;
17120
18090
  rulesCache = new Map;
17121
18091
  freshPopups = new Set;
18092
+ blanking = new Map;
17122
18093
  constructor(dependencies) {
17123
18094
  this.dependencies = dependencies;
17124
18095
  }
@@ -17148,7 +18119,7 @@ class SessionNavigationGuard {
17148
18119
  const rules = this.rules(options.sessionId);
17149
18120
  if (!rules)
17150
18121
  return;
17151
- const url = getString2(options.params, "url") ?? (options.method === "Target.createTarget" ? "about:blank" : undefined);
18122
+ const url = options.method === "Target.createTarget" ? createTargetUrl2(options.params) : getString2(options.params, "url");
17152
18123
  if (url === undefined)
17153
18124
  return;
17154
18125
  const decision = await checkNavigationUrl(url, rules);
@@ -17163,8 +18134,16 @@ class SessionNavigationGuard {
17163
18134
  this.freshPopups.add(target.tabId);
17164
18135
  this.observeCommittedUrl(target, target.targetInfo.url);
17165
18136
  }
18137
+ createdTabNavigated(target) {
18138
+ if (!this.enforced(target))
18139
+ return true;
18140
+ if ((this.blanking.get(target.tabId) ?? 0) > 0)
18141
+ return false;
18142
+ return this.observeCommittedUrl(target, target.targetInfo.url);
18143
+ }
17166
18144
  forgetTab(tabId) {
17167
18145
  this.freshPopups.delete(tabId);
18146
+ this.blanking.delete(tabId);
17168
18147
  }
17169
18148
  observeEvent(target, method, params) {
17170
18149
  if (method !== "Page.frameNavigated" && method !== "Page.frameRequestedNavigation" && method !== "Page.frameStartedNavigating" && method !== "Network.responseReceived")
@@ -17215,14 +18194,15 @@ class SessionNavigationGuard {
17215
18194
  observeCommittedUrl(target, url) {
17216
18195
  const rules = this.rules(target.opencodeBrowserSessionId);
17217
18196
  if (!rules)
17218
- return;
18197
+ return true;
17219
18198
  const decision = checkUrl(url, rules);
17220
18199
  if (decision.allowed) {
17221
18200
  if (!/^about:/.test(url))
17222
18201
  this.freshPopups.delete(target.tabId);
17223
- return;
18202
+ return true;
17224
18203
  }
17225
18204
  this.violation(target, url, decision.reason, "commit");
18205
+ return false;
17226
18206
  }
17227
18207
  violation(target, url, reason, _stage) {
17228
18208
  const sessionId = target.opencodeBrowserSessionId;
@@ -17238,7 +18218,14 @@ class SessionNavigationGuard {
17238
18218
  });
17239
18219
  return;
17240
18220
  }
17241
- this.dependencies.send(target.tabId, "Page.stopLoading", {}).catch(() => {}).then(() => this.dependencies.send(target.tabId, "Page.navigate", { url: "about:blank" })).catch(() => {});
18221
+ this.blanking.set(target.tabId, (this.blanking.get(target.tabId) ?? 0) + 1);
18222
+ this.dependencies.send(target.tabId, "Page.stopLoading", {}).catch(() => {}).then(() => this.dependencies.send(target.tabId, "Page.navigate", { url: "about:blank" })).catch(() => {}).finally(() => {
18223
+ const remaining = (this.blanking.get(target.tabId) ?? 1) - 1;
18224
+ if (remaining > 0)
18225
+ this.blanking.set(target.tabId, remaining);
18226
+ else
18227
+ this.blanking.delete(target.tabId);
18228
+ });
17242
18229
  }
17243
18230
  addWarning(sessionId, warning) {
17244
18231
  const pending = this.warnings.get(sessionId) ?? [];
@@ -17314,7 +18301,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17314
18301
  const sessionCatalog = options.sessionCatalogPath === null ? undefined : new SessionCatalog(options.sessionCatalogPath ?? defaultSessionCatalogPath(port));
17315
18302
  let catalogWritesEnabled = false;
17316
18303
  const registry = new TargetRegistry;
17317
- const authToken = yield* try_({
18304
+ const authToken = yield* try_2({
17318
18305
  try: () => {
17319
18306
  ensurePrivateDirectory();
17320
18307
  return relayToken();
@@ -17474,7 +18461,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17474
18461
  },
17475
18462
  checkBrowserResponsive: (key) => {
17476
18463
  const link = browsers.byKey(key);
17477
- return link ? link.rpc.send({ method: "ping" }).pipe(asVoid2) : fail5(new Error("The browser disconnected before execution."));
18464
+ return link ? link.rpc.send({ method: "ping" }).pipe(asVoid2) : fail6(new Error("The browser disconnected before execution."));
17478
18465
  },
17479
18466
  targetBrowserKey: (tabId) => browsers.ownerKey(tabId),
17480
18467
  getUserAttachedPageUrls: (session) => registry.listRootTargets().filter((target) => target.owner === "user" && browsers.ownerKey(target.tabId) === session.browser?.key).map((target) => target.targetInfo.url || "about:blank"),
@@ -17534,6 +18521,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17534
18521
  const known = ownersAcrossReconnect.get(targetId);
17535
18522
  return known?.sessionId !== undefined && sessions.sessions.has(known.sessionId) ? { sessionId: known.sessionId, owner: known.owner } : undefined;
17536
18523
  };
18524
+ const attachTimeoutMs = yield* Int("OPENCODE_BROWSER_ATTACH_TIMEOUT_MS").pipe(withDefault(1e4));
17537
18525
  const rootLifecycle = yield* RootTargetLifecycle.make({
17538
18526
  registry,
17539
18527
  sessions: {
@@ -17553,7 +18541,8 @@ var makeRelay = fnUntraced(function* (options = {}) {
17553
18541
  announceRoot: announceAttachedTarget,
17554
18542
  announceChild: announceAttachedChildTarget
17555
18543
  },
17556
- reportError: (message, error) => console.error(message, error)
18544
+ reportError: (message, error) => console.error(message, error),
18545
+ attachCommandTimeoutMs: attachTimeoutMs
17557
18546
  });
17558
18547
  const settingsSync = createRelaySettingsSync({
17559
18548
  browsers,
@@ -17568,8 +18557,8 @@ var makeRelay = fnUntraced(function* (options = {}) {
17568
18557
  const restartTimeoutMs = yield* Int("OPENCODE_BROWSER_RESTART_TIMEOUT_MS").pipe(withDefault(1e4));
17569
18558
  const clientGoneGraceMs = yield* Int("OPENCODE_BROWSER_CLIENT_GONE_GRACE_MS").pipe(withDefault(60000));
17570
18559
  const restartRequestId = yield* option(String2("OPENCODE_BROWSER_RESTART_REQUEST_ID"));
17571
- const lifecycleLogPath = path14.join(stateRoot(), "relays", String(port), "lifecycle.jsonl");
17572
- const audit = (event) => try_(() => appendRelayLifecycleEvent(lifecycleLogPath, event));
18560
+ const lifecycleLogPath = path15.join(stateRoot(), "relays", String(port), "lifecycle.jsonl");
18561
+ const audit = (event) => try_2(() => appendRelayLifecycleEvent(lifecycleLogPath, event));
17573
18562
  function setProtectedUi(tabId, protectedUi) {
17574
18563
  const changed = registry.markRootTargetProtectedUi(tabId, protectedUi);
17575
18564
  if (!changed)
@@ -17618,25 +18607,50 @@ var makeRelay = fnUntraced(function* (options = {}) {
17618
18607
  const session = sessionId && sessions.sessions.get(sessionId);
17619
18608
  if (session) {
17620
18609
  const link = handshake.resolveSessionBrowser(undefined, session);
17621
- return "error" in link ? fail5(new Error(link.error)) : succeed6(link);
18610
+ return "error" in link ? fail6(new Error(link.error)) : succeed6(link);
17622
18611
  }
17623
18612
  const existing = sessionId ? registry.listRootTargets().find((target) => target.opencodeBrowserSessionId === sessionId && target.owner === "relay") : undefined;
17624
18613
  const link = (existing && browsers.browserTab(existing.tabId)?.link) ?? browsers.defaultLink();
17625
- return link ? succeed6(link) : fail5(new Error("browse extension is not connected"));
18614
+ return link ? succeed6(link) : fail6(new Error("browse extension is not connected"));
17626
18615
  });
17627
18616
  const createAndAttachTab = fnUntraced(function* (createOptions) {
17628
18617
  const link = yield* sessionBrowser(createOptions.opencodeBrowserSessionId);
17629
- const result = yield* sendToExtension({ method: "tabs.create", params: { url: createOptions.url, active: createOptions.active, ...agentWindow ? { window: agentWindow } : {} } }, link);
18618
+ const result = yield* sendToExtension({ method: "tabs.create", params: { url: "about:blank", active: createOptions.active, ...agentWindow ? { window: agentWindow } : {} } }, link);
17630
18619
  const tabId = getNumber2(result, "tabId");
17631
18620
  if (!tabId)
17632
- return yield* fail5(new Error("tabs.create did not return a tabId"));
18621
+ return yield* fail6(new Error("tabs.create did not return a tabId"));
17633
18622
  announceTab(tabId);
17634
- return yield* rootLifecycle.attach({
18623
+ const target = yield* rootLifecycle.attach({
17635
18624
  tabId,
17636
18625
  owner: "relay",
17637
18626
  ...createOptions.opencodeBrowserSessionId ? { opencodeBrowserSessionId: createOptions.opencodeBrowserSessionId } : {},
17638
18627
  ...createOptions.autoAttachParams ? { autoAttachParams: createOptions.autoAttachParams } : {}
17639
- });
18628
+ }).pipe(tapError((error) => sync2(() => {
18629
+ relayLog("create.attach-failed", { tabId, error: error instanceof Error ? error.message : String(error) });
18630
+ sendExtensionBestEffort({ method: "tabs.remove", params: { tabId } });
18631
+ detachTargetState(tabId);
18632
+ })));
18633
+ const requested = createTargetUrl2({ url: createOptions.url });
18634
+ if (requested !== "about:blank") {
18635
+ const data = /^data:/i.test(requested.trim());
18636
+ const navigation = yield* (data ? navigateTopFrameToDataUrl({ tabId, params: { url: requested }, mainFrameIdsByTab, blankNavigationWaiters, registry, sendDebuggerCommand }) : sendDebuggerCommand({ tabId, method: "Page.navigate", params: { url: requested } })).pipe(catch_((error) => sync2(() => {
18637
+ relayLog("create.navigate-failed", { tabId, error: error instanceof Error ? error.message : String(error) });
18638
+ return;
18639
+ })));
18640
+ const errorText = getString2(navigation, "errorText");
18641
+ if (errorText)
18642
+ relayLog("create.navigate-failed", { tabId, errorText });
18643
+ else if (data && navigation === undefined)
18644
+ relayLog("create.data-skipped", { tabId });
18645
+ const current = yield* sendDebuggerCommand({ tabId, method: "Target.getTargetInfo", params: {} }).pipe(orElseSucceed(() => ({})));
18646
+ const targetInfo = getTargetInfo2(current.targetInfo);
18647
+ if (targetInfo && !isRestrictedTarget2(targetInfo) && navigationGuard.createdTabNavigated({ ...target, targetInfo })) {
18648
+ const updated = registry.updateConnectedTargetInfo({ tabId, targetInfo });
18649
+ if (updated?.kind === "root")
18650
+ return updated.target;
18651
+ }
18652
+ }
18653
+ return target;
17640
18654
  });
17641
18655
  const closeTargetByTargetId = fnUntraced(function* (targetId) {
17642
18656
  const target = registry.targetsByTargetId.get(targetId);
@@ -17663,7 +18677,8 @@ var makeRelay = fnUntraced(function* (options = {}) {
17663
18677
  rootLifecycle.invalidate(tabId);
17664
18678
  if (detachOptions.updateExtension !== false) {
17665
18679
  sendExtensionBestEffort({ method: "pageStatus.clear", params: { tabId } });
17666
- presentation.scheduleTabGrouping(tabId, "tabs.ungroup");
18680
+ if (detachOptions.releasedByUser !== true || registry.tabTargets.get(tabId)?.owner !== "relay")
18681
+ presentation.scheduleTabGrouping(tabId, "tabs.ungroup");
17667
18682
  sendExtensionBestEffort({ method: "action.setAttached", params: { tabId, attached: false } });
17668
18683
  recordingRelay.abortRecordingForTab({ tabId, reason: "Tab detached" }).catch((error) => {
17669
18684
  console.error("Failed to abort recording for detached tab", error);
@@ -17676,7 +18691,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17676
18691
  if (detached) {
17677
18692
  presentation.cancelTargetHandoffs(detached.target, "target-detached");
17678
18693
  if (!detachOptions.preserveSessionTarget)
17679
- sessions.markTargetDetached(detached.target.targetInfo.targetId);
18694
+ sessions.markTargetDetached(detached.target.targetInfo.targetId, { releasedByUser: detachOptions.releasedByUser === true });
17680
18695
  contextDebugLog?.(`target-detached kind=root ${targetDiagnosticIdentity(registry, detached.target)}`);
17681
18696
  }
17682
18697
  cdpClients.detachTab(tabId, { destroyed: true });
@@ -17753,6 +18768,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17753
18768
  refreshPageStatus: presentation.refreshPageStatus,
17754
18769
  refreshTabGrouping: presentation.refreshTabGrouping,
17755
18770
  handleToolbarClick: presentation.handleToolbarClick,
18771
+ handleDebuggingBarCancel: presentation.handleDebuggingBarCancel,
17756
18772
  cancelTargetHandoffs: presentation.cancelTargetHandoffs,
17757
18773
  detachTargetState,
17758
18774
  detachChildTargetState,
@@ -17846,7 +18862,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17846
18862
  yield* catch_(listenHttpServer2({ server: httpServer, host: listenHost, port }), (error) => {
17847
18863
  return gen(function* () {
17848
18864
  yield* cleanup();
17849
- return yield* fail5(error);
18865
+ return yield* fail6(error);
17850
18866
  });
17851
18867
  });
17852
18868
  yield* sync2(() => pruneStaleExecuteFilesDirectories());
@@ -17866,7 +18882,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17866
18882
  },
17867
18883
  catch: (cause) => cause instanceof Error ? cause : new Error("Load browse session catalog", { cause })
17868
18884
  });
17869
- yield* try_({
18885
+ yield* try_2({
17870
18886
  try: () => sessions.restore(restoredSessions),
17871
18887
  catch: (cause) => cause instanceof Error ? cause : new Error("Restore browse sessions", { cause })
17872
18888
  });
@@ -17904,7 +18920,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17904
18920
  relayLog("relay.ready", { url: endpointUrl, version: opencodeBrowserVersion2, build: opencodeBrowserBuildId2, pid: process.pid, managed });
17905
18921
  }), (error) => gen(function* () {
17906
18922
  yield* cleanup();
17907
- return yield* fail5(error);
18923
+ return yield* fail6(error);
17908
18924
  }));
17909
18925
  return {
17910
18926
  url: endpointUrl,