@opencode/browse 0.0.15-dev.98 → 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-yw23xxk6.mjs → cli-xke2d25m.mjs} +136 -132
  3. package/dist/cli.mjs +17 -16
  4. package/dist/{helpers-5bz1ykzf.mjs → helpers-tsvynww5.mjs} +4 -2
  5. package/dist/{index-yzz55kxm.mjs → index-6gkr235e.mjs} +1 -1
  6. package/dist/{main-sr7x6ex2.mjs → main-3esbykhb.mjs} +4 -4
  7. package/dist/{main-y2e9e5kz.mjs → main-70y5racc.mjs} +2 -2
  8. package/dist/main-7y3pj4rc.mjs +1694 -0
  9. package/dist/{main-br0znez7.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-nf4p3mes.mjs → main-crssg4wd.mjs} +25 -11
  14. package/dist/{main-hz7wj5ze.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-x58yhgrq.mjs → main-rycc0g05.mjs} +3 -3
  19. package/dist/{main-z0a00g4g.mjs → main-sfb6r1ye.mjs} +2 -2
  20. package/dist/{main-n0qm6500.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-q0wgd05d.mjs → mcp-qzkz0rbx.mjs} +418 -414
  24. package/dist/{migrate-tmsm0mc7.mjs → migrate-bcea81cv.mjs} +11 -14
  25. package/dist/{relay-pg3r3re0.mjs → relay-pc2ke2t2.mjs} +1229 -408
  26. package/dist/{runtime-update-65ffn31x.mjs → runtime-update-jaxftsqk.mjs} +7 -6
  27. package/dist/{setup-wkp99mwd.mjs → setup-cpr4psvg.mjs} +30 -20
  28. package/dist/{skill-text-28va391t.mjs → skill-text-v0etv8b7.mjs} +20 -8
  29. package/dist/{supervisor-p0agjsxt.mjs → supervisor-recc7rne.mjs} +5 -5
  30. package/dist/{update-rrk7rh0w.mjs → update-0vgwjjha.mjs} +3 -3
  31. package/dist/{version-t3shmxrb.mjs → version-67w7t6ce.mjs} +1 -1
  32. package/package.json +1 -1
  33. package/skills/browse/SKILL.md +20 -8
  34. package/dist/main-630yypmy.mjs +0 -2924
  35. package/dist/main-bccm3dk2.mjs +0 -4
@@ -1,10 +1,15 @@
1
1
  import {
2
2
  opencodeBrowserVersion2,
3
3
  opencodeBrowserBuildId2
4
- } from "./main-bccm3dk2.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-n0qm6500.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-hz7wj5ze.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-br0znez7.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-630yypmy.mjs";
144
+ } from "./main-m05te79v.mjs";
145
145
  import {
146
146
  defaultJournalBaseDir,
147
147
  makeJournalEntry,
148
148
  appendJournalEntry,
149
149
  startJournalRetention
150
- } from "./main-sr7x6ex2.mjs";
150
+ } from "./main-3esbykhb.mjs";
151
151
  import {
152
152
  createUpdateWatcher2
153
- } from "./main-z0a00g4g.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-x58yhgrq.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-y2e9e5kz.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 util4 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
+ ])];
2875
+ }
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);
2418
2888
  }
2419
- function assertExecuteFilePath(target, operation) {
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);
2574
- return;
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;
2575
3101
  }
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} })`));
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);
2584
3144
  } else {
2585
- checkFileOptions(item, method, includeMethodKeys, depth + 1);
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);
2586
3168
  }
2587
3169
  }
2588
3170
  }
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);
3171
+ function secureExecuteFileOutputs(outputs) {
3172
+ const uid = process.getuid?.();
3173
+ if (uid === undefined)
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 {}
3198
+ }
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) });
2596
3216
  }
3217
+ const stop = call.traceStop;
3218
+ return stop === undefined ? { outputs } : { outputs, forgetTrace: () => startedTraces.delete(stop) };
2597
3219
  }
2598
- var promiseReturningNames = new Set([...fileOptionMethods, "setInputFiles", "setFiles", "saveAs", "bringToFront", "send"]);
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;
3231
+ }
3232
+ return result.then((value) => {
3233
+ settle(true);
3234
+ return value;
3235
+ }, (error) => {
3236
+ settle(false);
3237
+ throw error;
3238
+ });
3239
+ }
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";
@@ -2670,14 +3380,14 @@ import net from "node:net";
2670
3380
  import os3 from "node:os";
2671
3381
  import { AsyncLocalStorage } from "node:async_hooks";
2672
3382
  import tls from "node:tls";
2673
- import util3 from "node:util";
3383
+ import util5 from "node:util";
2674
3384
  import v8 from "node:v8";
2675
3385
  import vm from "node:vm";
2676
3386
  import workerThreads from "node:worker_threads";
2677
3387
  import * as acorn from "acorn";
2678
3388
 
2679
3389
  // src/execute-realm/rejection-text.ts
2680
- import util2 from "node:util";
3390
+ import util4 from "node:util";
2681
3391
  var placeholder = "reason not shown";
2682
3392
  var nativeStackGetter = Object.getOwnPropertyDescriptor(new Error, "stack")?.get;
2683
3393
  function safeErrorMessage(value, maxLength = 300) {
@@ -2709,7 +3419,7 @@ function safeErrorStack(value) {
2709
3419
  }
2710
3420
  }
2711
3421
  function isSafeNativeError(value) {
2712
- return typeof value === "object" && value !== null && !util2.types.isProxy(value) && util2.types.isNativeError(value);
3422
+ return typeof value === "object" && value !== null && !util4.types.isProxy(value) && util4.types.isNativeError(value);
2713
3423
  }
2714
3424
  function isSafeHostError(value) {
2715
3425
  if (!isSafeNativeError(value))
@@ -2718,7 +3428,7 @@ function isSafeHostError(value) {
2718
3428
  for (let depth = 0;prototype !== null && depth < 32; depth += 1) {
2719
3429
  if (prototype === Error.prototype)
2720
3430
  return true;
2721
- if (util2.types.isProxy(prototype))
3431
+ if (util4.types.isProxy(prototype))
2722
3432
  return false;
2723
3433
  prototype = Object.getPrototypeOf(prototype);
2724
3434
  }
@@ -2733,9 +3443,9 @@ function ownDataProperty(value, key) {
2733
3443
  var deniedHostValues = new Map([
2734
3444
  [process, "process"],
2735
3445
  [globalThis, "the relay's global object"],
2736
- [fs3, "fs"],
3446
+ [fs4, "fs"],
2737
3447
  [fsPromises2, "fs/promises"],
2738
- [fs3.promises, "fs/promises"],
3448
+ [fs4.promises, "fs/promises"],
2739
3449
  [childProcess, "child_process"],
2740
3450
  [cluster, "cluster"],
2741
3451
  [dgram, "dgram"],
@@ -2753,9 +3463,9 @@ var deniedHostValues = new Map([
2753
3463
  [workerThreads, "worker_threads"],
2754
3464
  [globalThis.fetch, "Node fetch"],
2755
3465
  [eval, "eval"],
2756
- [util3.inspect, "host object inspection"],
2757
- [util3.format, "host object formatting"],
2758
- [util3.formatWithOptions, "host object formatting"],
3466
+ [util5.inspect, "host object inspection"],
3467
+ [util5.format, "host object formatting"],
3468
+ [util5.formatWithOptions, "host object formatting"],
2759
3469
  [crypto4.setEngine, "loading native crypto engines"],
2760
3470
  [events2.setMaxListeners, "changing shared event-emitter defaults or prototypes"],
2761
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)`])
@@ -3253,7 +3963,7 @@ class ExecuteRealm {
3253
3963
  toSandbox(value, seen = new Map) {
3254
3964
  if (!isObjectLike(value))
3255
3965
  return value;
3256
- if (value === Buffer.allocUnsafe || value === Buffer.allocUnsafeSlow || value === buffer2.SlowBuffer)
3966
+ if (value === Buffer.allocUnsafe || value === Buffer.allocUnsafeSlow || value === buffer3.SlowBuffer)
3257
3967
  return this.toSandbox(Buffer.alloc);
3258
3968
  if (this.hostBySandboxProxy.has(value))
3259
3969
  return value;
@@ -3273,7 +3983,7 @@ class ExecuteRealm {
3273
3983
  throw this.sandboxError(`${denied} is not available in execute code. Set ${allowNodeEnvironmentVariable}=1 for full Node access.`);
3274
3984
  if (this.isSandboxNative(value))
3275
3985
  return value;
3276
- if (util4.types.isPromise(value))
3986
+ if (util6.types.isPromise(value))
3277
3987
  return this.toSandboxPromise(value);
3278
3988
  if (Buffer.isBuffer(value)) {
3279
3989
  const copy = Buffer.alloc(value.length);
@@ -3282,11 +3992,11 @@ class ExecuteRealm {
3282
3992
  this.sandboxProxyByHost.set(value, proxy);
3283
3993
  return proxy;
3284
3994
  }
3285
- if (util4.types.isArrayBuffer(value)) {
3995
+ if (util6.types.isArrayBuffer(value)) {
3286
3996
  const SandboxUint8Array = this.sandboxIntrinsics.Uint8Array;
3287
3997
  return new SandboxUint8Array(new Uint8Array(value)).buffer;
3288
3998
  }
3289
- if (util4.types.isTypedArray(value) && !Buffer.isBuffer(value)) {
3999
+ if (util6.types.isTypedArray(value) && !Buffer.isBuffer(value)) {
3290
4000
  const name = Object.prototype.toString.call(value).slice(8, -1);
3291
4001
  const Constructor = this.sandboxIntrinsics[name] ?? this.sandboxIntrinsics.Uint8Array;
3292
4002
  return new Constructor(value);
@@ -3296,7 +4006,7 @@ class ExecuteRealm {
3296
4006
  throw this.sandboxError(deniedClass);
3297
4007
  if (!this.forceProxy.has(value) && typeof value === "object") {
3298
4008
  const prototype = Reflect.getPrototypeOf(value);
3299
- if (Array.isArray(value) && prototype === Array.prototype || util4.types.isArgumentsObject(value)) {
4009
+ if (Array.isArray(value) && prototype === Array.prototype || util6.types.isArgumentsObject(value)) {
3300
4010
  const output = [];
3301
4011
  Reflect.setPrototypeOf(output, this.sandboxArrayPrototype);
3302
4012
  seen.set(value, output);
@@ -3305,7 +4015,7 @@ class ExecuteRealm {
3305
4015
  output[index] = this.toSandbox(array[index], seen);
3306
4016
  return output;
3307
4017
  }
3308
- if ((prototype === Object.prototype || prototype === null) && !Object.hasOwn(value, "constructor") && !util4.types.isProxy(value)) {
4018
+ if ((prototype === Object.prototype || prototype === null) && !Object.hasOwn(value, "constructor") && !util6.types.isProxy(value)) {
3309
4019
  const output = Object.create(prototype === null ? null : this.sandboxObjectPrototype);
3310
4020
  seen.set(value, output);
3311
4021
  for (const key of Object.keys(value)) {
@@ -3463,8 +4173,9 @@ class ExecuteRealm {
3463
4173
  apply(_shadow, thisArgument, args) {
3464
4174
  const hostThis = isObjectLike(thisArgument) && realm.hostBySandboxProxy.has(thisArgument) ? realm.hostBySandboxProxy.get(thisArgument) : realm.toHost(thisArgument);
3465
4175
  const hostArgs = args.map((arg) => realm.toHost(arg));
4176
+ let prepared;
3466
4177
  try {
3467
- checkHostCall(target, hostThis, hostArgs);
4178
+ prepared = prepareExecuteFileOutputs(checkHostCall(target, hostThis, hostArgs));
3468
4179
  } catch (error) {
3469
4180
  if (returnsPromise(target))
3470
4181
  return realm.SandboxPromise.reject(realm.toSandboxThrown(error));
@@ -3480,7 +4191,7 @@ class ExecuteRealm {
3480
4191
  throw realm.toSandboxThrown(error);
3481
4192
  }
3482
4193
  try {
3483
- return realm.toSandbox(result);
4194
+ return realm.toSandbox(completeExecuteFileOutputs(result, prepared));
3484
4195
  } catch (error) {
3485
4196
  throw realm.sanitizeThrown(error);
3486
4197
  }
@@ -3522,8 +4233,8 @@ class ExecuteRealm {
3522
4233
  if (!guarded) {
3523
4234
  guarded = new Proxy(host, {
3524
4235
  apply(target, receiver, args) {
3525
- checkHostCall(target, receiver, args);
3526
- return Reflect.apply(target, receiver, args);
4236
+ const prepared = prepareExecuteFileOutputs(checkHostCall(target, receiver, args));
4237
+ return completeExecuteFileOutputs(Reflect.apply(target, receiver, args), prepared);
3527
4238
  },
3528
4239
  construct(target, args, newTarget) {
3529
4240
  checkHostCall(target, undefined, args);
@@ -3557,16 +4268,16 @@ class ExecuteRealm {
3557
4268
  }
3558
4269
  }
3559
4270
  copyToHost(value, seen) {
3560
- if (util4.types.isPromise(value))
4271
+ if (util6.types.isPromise(value))
3561
4272
  return this.toHostPromise(value);
3562
- if (util4.types.isDate(value))
4273
+ if (util6.types.isDate(value))
3563
4274
  return new Date(Date.prototype.getTime.call(value));
3564
- if (util4.types.isRegExp(value)) {
4275
+ if (util6.types.isRegExp(value)) {
3565
4276
  const source = Reflect.get(value, "source");
3566
4277
  const flags = Reflect.get(value, "flags");
3567
4278
  return new RegExp(String(source), String(flags));
3568
4279
  }
3569
- if (util4.types.isNativeError(value) || value instanceof this.SandboxError) {
4280
+ if (util6.types.isNativeError(value) || value instanceof this.SandboxError) {
3570
4281
  const name = String(Reflect.get(value, "name") ?? "Error");
3571
4282
  const output = new Error(String(Reflect.get(value, "message") ?? ""));
3572
4283
  seen.set(value, output);
@@ -3584,26 +4295,26 @@ class ExecuteRealm {
3584
4295
  Object.defineProperty(output, "cause", { value: this.toHost(cause, seen), configurable: true, writable: true });
3585
4296
  return output;
3586
4297
  }
3587
- if (util4.types.isMap(value)) {
4298
+ if (util6.types.isMap(value)) {
3588
4299
  const output = new Map;
3589
4300
  seen.set(value, output);
3590
4301
  Map.prototype.forEach.call(value, (item, key) => output.set(this.toHost(key, seen), this.toHost(item, seen)));
3591
4302
  return output;
3592
4303
  }
3593
- if (util4.types.isSet(value)) {
4304
+ if (util6.types.isSet(value)) {
3594
4305
  const output = new Set;
3595
4306
  seen.set(value, output);
3596
4307
  Set.prototype.forEach.call(value, (item) => output.add(this.toHost(item, seen)));
3597
4308
  return output;
3598
4309
  }
3599
- if (util4.types.isArrayBuffer(value))
4310
+ if (util6.types.isArrayBuffer(value))
3600
4311
  return new Uint8Array(new Uint8Array(value)).buffer;
3601
- if (util4.types.isTypedArray(value)) {
4312
+ if (util6.types.isTypedArray(value)) {
3602
4313
  const name = Object.prototype.toString.call(value).slice(8, -1);
3603
4314
  const Constructor = globalThis[name] ?? Uint8Array;
3604
4315
  return new Constructor(value);
3605
4316
  }
3606
- if (Array.isArray(value) || util4.types.isArgumentsObject(value)) {
4317
+ if (Array.isArray(value) || util6.types.isArgumentsObject(value)) {
3607
4318
  const output = [];
3608
4319
  seen.set(value, output);
3609
4320
  const array = value;
@@ -3728,7 +4439,7 @@ class ExecuteRealm {
3728
4439
  }
3729
4440
 
3730
4441
  // src/execute/code-runner.ts
3731
- import fs4 from "node:fs";
4442
+ import fs5 from "node:fs";
3732
4443
  import http3 from "node:http";
3733
4444
  import https2 from "node:https";
3734
4445
  import os4 from "node:os";
@@ -3833,7 +4544,7 @@ function describe(arg) {
3833
4544
  }
3834
4545
 
3835
4546
  // src/execute/log-capture.ts
3836
- import util5 from "node:util";
4547
+ import util7 from "node:util";
3837
4548
  var maxCapturedPageLogs = 50;
3838
4549
  var maxCapturedScriptLogs = 100;
3839
4550
  function createExecuteLogCapture(limits = {}) {
@@ -4022,7 +4733,7 @@ function formatLogValue(value) {
4022
4733
  if (isString(value)) {
4023
4734
  return value;
4024
4735
  }
4025
- return util5.inspect(value, { depth: 4, colors: false, maxArrayLength: 100, maxStringLength: 1000 });
4736
+ return util7.inspect(value, { depth: 4, colors: false, maxArrayLength: 100, maxStringLength: 1000 });
4026
4737
  }
4027
4738
 
4028
4739
  // src/execute/target-selection.ts
@@ -4140,6 +4851,8 @@ var defaultHandoffTimeoutMs = 10 * 60 * 1000;
4140
4851
  var defaultHandoffMessage = "Complete the requested task, then use the in-page continue control.";
4141
4852
  var timedOut = Symbol("timed-out");
4142
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.";
4143
4856
  var defaultPageRecoveredWarning = "The session default page was unresponsive; created a new page. References to the old page in state are stale.";
4144
4857
  var defaultPageCrashedWarning = "The session default page target crashed; checking it before the next execute.";
4145
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.";
@@ -4187,7 +4900,7 @@ var runPlaywrightOperation = fn("Execute.playwrightOperation")((options) => tryP
4187
4900
  catch: (cause) => operationFailure(options.label, cause)
4188
4901
  }).pipe(timeoutOrElse({
4189
4902
  duration: options.timeoutMs,
4190
- orElse: () => fail5(new PlaywrightOperationError({
4903
+ orElse: () => fail6(new PlaywrightOperationError({
4191
4904
  message: `${options.label} timed out after ${options.timeoutMs}ms`,
4192
4905
  operation: options.label,
4193
4906
  reason: "timeout"
@@ -4410,7 +5123,7 @@ function installClosedPageReplacementGuard(page, clearRecreatedFromClosedUrl) {
4410
5123
  }
4411
5124
 
4412
5125
  // src/execute/code-runner.ts
4413
- var nodeModules = { ...sandboxModules, fs: fs4, os: os4, http: http3, https: https2 };
5126
+ var nodeModules = { ...sandboxModules, fs: fs5, os: os4, http: http3, https: https2 };
4414
5127
 
4415
5128
  class ExecuteCodeError extends Error {
4416
5129
  originalError;
@@ -4769,6 +5482,7 @@ class DefaultPageHost {
4769
5482
  pendingTargetRebind;
4770
5483
  lastKnownNonBlankUrl;
4771
5484
  recreatedFromClosedUrl;
5485
+ pageReleasedByDebuggingBar = false;
4772
5486
  explicitMediaFeatures = new Map;
4773
5487
  explicitMedia;
4774
5488
  pendingWarnings = [];
@@ -4812,15 +5526,18 @@ class DefaultPageHost {
4812
5526
  this.pageProtectedUi = protectedUi;
4813
5527
  return true;
4814
5528
  }
4815
- markTargetDetached(targetId) {
5529
+ markTargetDetached(targetId, options = {}) {
4816
5530
  if (this.defaultPageTargetId !== targetId) {
4817
5531
  return false;
4818
5532
  }
4819
- if (this.lastKnownNonBlankUrl) {
5533
+ const releasedByUser = options.releasedByUser === true;
5534
+ if (releasedByUser)
5535
+ this.recreatedFromClosedUrl = undefined;
5536
+ else if (this.lastKnownNonBlankUrl)
4820
5537
  this.recreatedFromClosedUrl = this.lastKnownNonBlankUrl;
4821
- }
5538
+ this.pageReleasedByDebuggingBar = releasedByUser;
4822
5539
  this.unbindDefaultPage(undefined);
4823
- this.addWarningOnce(defaultPageClosedWarning);
5540
+ this.addWarningOnce(releasedByUser ? debuggingBarDismissedWarning : defaultPageClosedWarning);
4824
5541
  return true;
4825
5542
  }
4826
5543
  markTargetReplaced(previousTargetId, targetId) {
@@ -4857,6 +5574,7 @@ class DefaultPageHost {
4857
5574
  this.defaultPageTargetId = targetId;
4858
5575
  this.ownsPage = ownsPage;
4859
5576
  this.pendingTargetRebind = undefined;
5577
+ this.pageReleasedByDebuggingBar = false;
4860
5578
  this.recordNonBlankUrl(safePageUrl(page));
4861
5579
  const close = () => {
4862
5580
  if (this.page !== page)
@@ -4965,6 +5683,10 @@ class DefaultPageHost {
4965
5683
  });
4966
5684
  this.pendingWarnings.push(defaultPageClosedWarning);
4967
5685
  }
5686
+ if (this.pageReleasedByDebuggingBar) {
5687
+ this.pageReleasedByDebuggingBar = false;
5688
+ this.addWarningOnce(debuggingBarDismissedWarning);
5689
+ }
4968
5690
  const page = await context.newPage();
4969
5691
  const targetId = await resolvePageTargetId(page);
4970
5692
  this.bindDefaultPage(page, targetId, true, true);
@@ -5011,7 +5733,7 @@ class DefaultPageHost {
5011
5733
  }
5012
5734
 
5013
5735
  // src/execute/result-formatting.ts
5014
- import util6 from "node:util";
5736
+ import util8 from "node:util";
5015
5737
  var maxExecuteResultChars = 1e5;
5016
5738
  function boundExecuteResult(text, value, hasValue) {
5017
5739
  const valueChars = hasValue && value !== null && typeof value === "object" ? safeJsonStringify(value)?.length ?? 0 : typeof value === "string" ? value.length : 0;
@@ -5033,7 +5755,7 @@ function stringifyResult(result) {
5033
5755
  if (result === undefined) {
5034
5756
  return "undefined";
5035
5757
  }
5036
- return util6.inspect(result, { depth: 3, colors: false, maxArrayLength: 50, maxStringLength: 4000 });
5758
+ return util8.inspect(result, { depth: 3, colors: false, maxArrayLength: 50, maxStringLength: 4000 });
5037
5759
  }
5038
5760
  var maxJsonSafeDepth = 8;
5039
5761
  var maxJsonSafeBytes = 32 * 1024;
@@ -6663,7 +7385,7 @@ class GhostCursorTabs {
6663
7385
  command = fnUntraced(function* (tabId, params) {
6664
7386
  const operation = params?.op;
6665
7387
  if (!isString(operation) || !ghostCursorOperations.has(operation)) {
6666
- return yield* fail5(new Error(`Unknown ghost cursor operation: ${String(operation)}`));
7388
+ return yield* fail6(new Error(`Unknown ghost cursor operation: ${String(operation)}`));
6667
7389
  }
6668
7390
  const payload = params?.payload ?? null;
6669
7391
  const state = this.state(tabId);
@@ -6773,8 +7495,8 @@ function parseButton(value2) {
6773
7495
  }
6774
7496
 
6775
7497
  // src/snapshot/screenshot-diff.ts
6776
- import fs5 from "node:fs/promises";
6777
- import path3 from "node:path";
7498
+ import fs6 from "node:fs/promises";
7499
+ import path4 from "node:path";
6778
7500
  import pixelmatch from "pixelmatch";
6779
7501
  import { PNG } from "pngjs";
6780
7502
  var maxImageBytes = 32 * 1024 * 1024;
@@ -6783,7 +7505,7 @@ var pngSignature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
6783
7505
  function createScreenshotDiff(page) {
6784
7506
  return async (options) => {
6785
7507
  const threshold = validateThreshold(options.threshold ?? 0.1);
6786
- 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")) {
6787
7509
  throw new Error("screenshotDiff output path must be an absolute .png path");
6788
7510
  }
6789
7511
  const baseline = isString(options.baseline) ? await readBaseline(options.baseline) : options.baseline;
@@ -6801,7 +7523,7 @@ function createScreenshotDiff(page) {
6801
7523
  const image = PNG.sync.write(diff);
6802
7524
  const totalPixels = before.width * before.height;
6803
7525
  if (options.path)
6804
- await fs5.writeFile(options.path, image, { flag: "wx", mode: 384 });
7526
+ await fs6.writeFile(options.path, image, { flag: "wx", mode: 384 });
6805
7527
  return {
6806
7528
  matches: changedPixels === 0,
6807
7529
  width: before.width,
@@ -6815,9 +7537,9 @@ function createScreenshotDiff(page) {
6815
7537
  };
6816
7538
  }
6817
7539
  async function readBaseline(filename) {
6818
- if (!path3.isAbsolute(filename))
7540
+ if (!path4.isAbsolute(filename))
6819
7541
  throw new Error("screenshotDiff baseline path must be absolute");
6820
- const file = await fs5.open(filename, "r");
7542
+ const file = await fs6.open(filename, "r");
6821
7543
  try {
6822
7544
  const stat = await file.stat();
6823
7545
  if (!stat.isFile() || stat.size > maxImageBytes)
@@ -8081,14 +8803,14 @@ async function fillInputs(page, fields) {
8081
8803
  }
8082
8804
  }
8083
8805
  // src/snapshot/screenshot-labels.ts
8084
- import fs6 from "node:fs/promises";
8085
- import path4 from "node:path";
8806
+ import fs7 from "node:fs/promises";
8807
+ import path5 from "node:path";
8086
8808
  import { PNG as PNG2 } from "pngjs";
8087
8809
  async function screenshotWithLabels(options = {}) {
8088
8810
  if (!options.page) {
8089
8811
  throw new Error("screenshotWithLabels requires a page");
8090
8812
  }
8091
- if (options.path !== undefined && !path4.isAbsolute(options.path)) {
8813
+ if (options.path !== undefined && !path5.isAbsolute(options.path)) {
8092
8814
  throw new Error("screenshotWithLabels requires an absolute path");
8093
8815
  }
8094
8816
  const page = options.page;
@@ -8118,7 +8840,7 @@ async function screenshotWithLabels(options = {}) {
8118
8840
  try {
8119
8841
  const screenshot = offPage ? drawScreenshotLabels(await page.screenshot(), labels, viewportWidth) : await page.screenshot(options.path ? { path: options.path } : {});
8120
8842
  if (offPage && options.path)
8121
- await fs6.writeFile(options.path, screenshot);
8843
+ await fs7.writeFile(options.path, screenshot);
8122
8844
  return {
8123
8845
  ...options.path ? { path: options.path } : { image: screenshot },
8124
8846
  size: screenshot.byteLength,
@@ -8781,6 +9503,10 @@ function collectWebMcpToolsInPage() {
8781
9503
  }));
8782
9504
  }
8783
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
+ }
8784
9510
  const context = document.modelContext ?? navigator.modelContext;
8785
9511
  if (!context?.getTools)
8786
9512
  throw new Error("WebMCP is not available on this page");
@@ -8788,9 +9514,21 @@ function callWebMcpToolInPage(options) {
8788
9514
  const tool = tools.filter((candidate) => !("window" in candidate) || candidate.window === window).find((candidate) => candidate.name === options.name);
8789
9515
  if (!tool)
8790
9516
  throw new Error(`WebMCP tool ${JSON.stringify(options.name)} is not registered in this frame`);
8791
- 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 {
8792
9530
  throw new Error("WebMCP tool execution is not available on this page");
8793
- })();
9531
+ }
8794
9532
  if (typeof result !== "string")
8795
9533
  return result ?? null;
8796
9534
  try {
@@ -9125,10 +9863,10 @@ class ExecuteSecretsBridge {
9125
9863
  }
9126
9864
 
9127
9865
  // src/network-capture.ts
9128
- import path6 from "node:path";
9866
+ import path7 from "node:path";
9129
9867
 
9130
9868
  // src/network-capture/har-redaction.ts
9131
- import path5 from "node:path";
9869
+ import path6 from "node:path";
9132
9870
 
9133
9871
  // src/network-capture/types.ts
9134
9872
  var defaultNetworkCaptureMaxDurationMs = 30 * 60000;
@@ -9460,7 +10198,7 @@ function toHarEntry(entry) {
9460
10198
  }
9461
10199
  function writeArtifact(outputPath, value) {
9462
10200
  return tryPromise({
9463
- try: () => writeJsonFileAtomically(path5.resolve(outputPath), value),
10201
+ try: () => writeJsonFileAtomically(path6.resolve(outputPath), value),
9464
10202
  catch: (cause) => new NetworkCaptureError({ message: `Could not write network capture: ${outputPath}`, operation: "write", reason: "persistence-failed", cause })
9465
10203
  });
9466
10204
  }
@@ -9567,7 +10305,7 @@ class Recorder {
9567
10305
  }
9568
10306
  start(page, options = {}) {
9569
10307
  const capture = this;
9570
- return this.transition.withPermit(try_({
10308
+ return this.transition.withPermit(try_2({
9571
10309
  try: () => {
9572
10310
  validateOptions(options);
9573
10311
  if (capture.active) {
@@ -9699,7 +10437,7 @@ class Recorder {
9699
10437
  truncatedBodyCount: finalStatus.truncatedBodyCount + finished.redactionOmissionCount,
9700
10438
  active: false,
9701
10439
  stoppedAt: new Date().toISOString(),
9702
- ...options.outputPath ? { outputPath: path6.resolve(options.outputPath) } : {},
10440
+ ...options.outputPath ? { outputPath: path7.resolve(options.outputPath) } : {},
9703
10441
  ...finished.authProfile ? { authProfile: finished.authProfile } : {},
9704
10442
  updatedSecretRefs: finished.updatedSecretRefs,
9705
10443
  observedSecretRefs: finished.observedSecretRefs,
@@ -9931,25 +10669,25 @@ class Recorder {
9931
10669
  }
9932
10670
 
9933
10671
  // src/relay/log.ts
9934
- import fs7 from "node:fs";
10672
+ import fs8 from "node:fs";
9935
10673
  import os5 from "node:os";
9936
- import path7 from "node:path";
10674
+ import path8 from "node:path";
9937
10675
  var maxLogBytes = 1e6;
9938
10676
  var maxEntryCharacters = 64000;
9939
10677
  function managedRelayLogPath(home = os5.homedir()) {
9940
- return path7.join(stateRoot(home), "logs", "relay.log");
10678
+ return path8.join(stateRoot(home), "logs", "relay.log");
9941
10679
  }
9942
10680
  function appendManagedRelayProcessLog(message, home = os5.homedir()) {
9943
10681
  try {
9944
10682
  const logPath = managedRelayLogPath(home);
9945
- ensurePrivateDirectorySync(path7.dirname(logPath));
10683
+ ensurePrivateDirectorySync(path8.dirname(logPath));
9946
10684
  const entry = `${new Date().toISOString()} ${message.slice(0, maxEntryCharacters)}
9947
10685
  `;
9948
- const stat = fs7.statSync(logPath, { throwIfNoEntry: false });
10686
+ const stat = fs8.statSync(logPath, { throwIfNoEntry: false });
9949
10687
  if (stat && stat.size + Buffer.byteLength(entry) > maxLogBytes)
9950
- fs7.renameSync(logPath, `${logPath}.1`);
9951
- fs7.appendFileSync(logPath, entry, { encoding: "utf8", mode: 384 });
9952
- fs7.chmodSync(logPath, 384);
10688
+ fs8.renameSync(logPath, `${logPath}.1`);
10689
+ fs8.appendFileSync(logPath, entry, { encoding: "utf8", mode: 384 });
10690
+ fs8.chmodSync(logPath, 384);
9953
10691
  } catch {}
9954
10692
  }
9955
10693
  function relayLog(event, fields = {}) {
@@ -10419,15 +11157,15 @@ class ExecuteSandbox extends DefaultPageHost {
10419
11157
  }
10420
11158
 
10421
11159
  // src/recording-relay/flight-recorder.ts
10422
- import fs9 from "node:fs/promises";
10423
- import path9 from "node:path";
11160
+ import fs10 from "node:fs/promises";
11161
+ import path10 from "node:path";
10424
11162
  import { performance as performance3 } from "node:perf_hooks";
10425
11163
 
10426
11164
  // src/recording-relay/ffmpeg-encoder.ts
10427
11165
  import { execFile, spawn } from "node:child_process";
10428
11166
  import crypto6 from "node:crypto";
10429
11167
  import { once } from "node:events";
10430
- import fs8 from "node:fs/promises";
11168
+ import fs9 from "node:fs/promises";
10431
11169
 
10432
11170
  // src/recording-relay/mjpeg-matroska.ts
10433
11171
  var ebml = Buffer.from("1A45DFA3", "hex");
@@ -10544,7 +11282,7 @@ function mjpegMatroskaFrame(timestampMs, durationMs, frameLength) {
10544
11282
  import { performance as performance2 } from "node:perf_hooks";
10545
11283
 
10546
11284
  // src/recording-relay/types.ts
10547
- import path8 from "node:path";
11285
+ import path9 from "node:path";
10548
11286
  var defaultMaxDurationMs = 15 * 60 * 1000;
10549
11287
  var defaultCdpFrameRate = 60;
10550
11288
  var maxRecordingFrameRate = 60;
@@ -10640,7 +11378,7 @@ function findByRecordingTarget(map, target, ambiguousMessage) {
10640
11378
  return map.values().next().value;
10641
11379
  }
10642
11380
  function cdpArtifactType(outputPath) {
10643
- const extension = path8.extname(outputPath).toLowerCase();
11381
+ const extension = path9.extname(outputPath).toLowerCase();
10644
11382
  if (extension === ".webm")
10645
11383
  return "webm";
10646
11384
  if (extension === ".mp4")
@@ -10835,7 +11573,7 @@ async function createFfmpegVideoEncoder(options) {
10835
11573
  await writeStreamChunk(child.stdin, mjpegMatroskaHeader(options.width, options.height));
10836
11574
  } catch (error) {
10837
11575
  await exit;
10838
- await fs8.rm(temporaryOutputPath, { force: true });
11576
+ await fs9.rm(temporaryOutputPath, { force: true });
10839
11577
  throw error;
10840
11578
  }
10841
11579
  let completed = false;
@@ -10875,10 +11613,10 @@ async function createFfmpegVideoEncoder(options) {
10875
11613
  const error = await exit;
10876
11614
  if (error)
10877
11615
  throw error;
10878
- await fs8.rename(temporaryOutputPath, options.outputPath);
11616
+ await fs9.rename(temporaryOutputPath, options.outputPath);
10879
11617
  completed = true;
10880
11618
  })().catch(async (error) => {
10881
- await fs8.rm(temporaryOutputPath, { force: true });
11619
+ await fs9.rm(temporaryOutputPath, { force: true });
10882
11620
  throw error;
10883
11621
  });
10884
11622
  return finishingPromise;
@@ -10890,7 +11628,7 @@ async function createFfmpegVideoEncoder(options) {
10890
11628
  return cancelPromise;
10891
11629
  cancelPromise = (async () => {
10892
11630
  await terminate();
10893
- await fs8.rm(temporaryOutputPath, { force: true });
11631
+ await fs9.rm(temporaryOutputPath, { force: true });
10894
11632
  })();
10895
11633
  return cancelPromise;
10896
11634
  }
@@ -11054,7 +11792,7 @@ class FlightRecorderRelay {
11054
11792
  const startAt = frames[0].receivedAt;
11055
11793
  const endAt = frames.at(-1).receivedAt;
11056
11794
  const durationMs = Math.max(1, endAt - startAt);
11057
- await fs9.mkdir(path9.dirname(target.outputPath), { recursive: true });
11795
+ await fs10.mkdir(path10.dirname(target.outputPath), { recursive: true });
11058
11796
  let encoder;
11059
11797
  try {
11060
11798
  encoder = await (this.options.startVideoEncoder ?? startFfmpegVideoEncoder)({
@@ -11078,7 +11816,7 @@ class FlightRecorderRelay {
11078
11816
  sourceFrameCount: recorder.sourceFrameCount,
11079
11817
  droppedFrameCount: recorder.droppedFrameCount
11080
11818
  };
11081
- 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)}
11082
11820
  `, "utf8");
11083
11821
  return receipt;
11084
11822
  } catch (error) {
@@ -11179,7 +11917,7 @@ class FlightRecorderRelay {
11179
11917
  }
11180
11918
  async function assertOutputAvailable(filePath) {
11181
11919
  try {
11182
- await fs9.stat(filePath);
11920
+ await fs10.stat(filePath);
11183
11921
  } catch (error) {
11184
11922
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
11185
11923
  return;
@@ -11372,8 +12110,8 @@ function resolveExactHandoffTarget(options) {
11372
12110
  }
11373
12111
 
11374
12112
  // src/relay/lifecycle-log.ts
11375
- import fs10 from "node:fs";
11376
- import path10 from "node:path";
12113
+ import fs11 from "node:fs";
12114
+ import path11 from "node:path";
11377
12115
  var requestFields = {
11378
12116
  instanceId: RelayShutdownRequest.fields.instanceId,
11379
12117
  requestId: RelayShutdownRequest.fields.requestId,
@@ -11391,30 +12129,30 @@ var RelayLifecycleEvent = TaggedUnion({
11391
12129
  }
11392
12130
  });
11393
12131
  function appendRelayLifecycleEvent(filePath, event) {
11394
- const directory = path10.dirname(filePath);
12132
+ const directory = path11.dirname(filePath);
11395
12133
  ensurePrivateDirectorySync(directory);
11396
12134
  const entry = `${JSON.stringify({ ...encodeSync(RelayLifecycleEvent)(event), timestamp: new Date().toISOString() })}
11397
12135
  `;
11398
- const file = fs10.openSync(filePath, "a+", 384);
12136
+ const file = fs11.openSync(filePath, "a+", 384);
11399
12137
  try {
11400
- fs10.fchmodSync(file, 384);
11401
- if (fs10.fstatSync(file).size + Buffer.byteLength(entry) > 256000)
11402
- fs10.ftruncateSync(file, 0);
11403
- fs10.writeFileSync(file, entry);
11404
- 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);
11405
12143
  } finally {
11406
- fs10.closeSync(file);
12144
+ fs11.closeSync(file);
11407
12145
  }
11408
- const parent = fs10.openSync(directory, "r");
12146
+ const parent = fs11.openSync(directory, "r");
11409
12147
  try {
11410
12148
  try {
11411
- fs10.fsyncSync(parent);
12149
+ fs11.fsyncSync(parent);
11412
12150
  } catch (error) {
11413
12151
  if (!isUnsupportedDirectorySyncError(error))
11414
12152
  throw error;
11415
12153
  }
11416
12154
  } finally {
11417
- fs10.closeSync(parent);
12155
+ fs11.closeSync(parent);
11418
12156
  }
11419
12157
  }
11420
12158
 
@@ -11431,7 +12169,7 @@ class RelayShutdown {
11431
12169
  options;
11432
12170
  state = State.Running();
11433
12171
  requests = 0;
11434
- idle = makeUnsafe5(true);
12172
+ idle = makeUnsafe2(true);
11435
12173
  constructor(options) {
11436
12174
  this.options = options;
11437
12175
  }
@@ -11449,7 +12187,7 @@ class RelayShutdown {
11449
12187
  yield* control.options.settle;
11450
12188
  }).pipe(timeoutOrElse({
11451
12189
  duration: control.options.timeoutMs ?? 1e4,
11452
- orElse: () => fail5(control.busyError("timeout"))
12190
+ orElse: () => fail6(control.busyError("timeout"))
11453
12191
  }));
11454
12192
  }
11455
12193
  close() {
@@ -11463,7 +12201,7 @@ class RelayShutdown {
11463
12201
  const control = this;
11464
12202
  return acquireUseRelease(suspend2(() => {
11465
12203
  if (!control.accepting)
11466
- return fail5(control.busyError());
12204
+ return fail6(control.busyError());
11467
12205
  return sync2(() => control.retain());
11468
12206
  }), () => effect, (release) => sync2(release));
11469
12207
  }
@@ -11614,7 +12352,7 @@ class SessionError extends TaggedError2()("OpenCodeBrowserSessions.SessionError"
11614
12352
  }) {
11615
12353
  }
11616
12354
  var sessionError = (reason, message, sessionId) => new SessionError({ message, reason, ...sessionId ? { sessionId } : {} });
11617
- 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)) });
11618
12356
  var adoptionTipForUrl = (url) => {
11619
12357
  const selector = targetUrlHintSelector(url);
11620
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.`;
@@ -11687,7 +12425,7 @@ class SessionAdmission {
11687
12425
  pendingWork = 0;
11688
12426
  pendingSessionWork = new Map;
11689
12427
  identityChanges = new Map;
11690
- idle = makeUnsafe5(true);
12428
+ idle = makeUnsafe2(true);
11691
12429
  constructor(sessions, hooks) {
11692
12430
  this.sessions = sessions;
11693
12431
  this.hooks = hooks;
@@ -11708,20 +12446,20 @@ class SessionAdmission {
11708
12446
  awaitStableIdentity(id) {
11709
12447
  return suspend2(() => {
11710
12448
  const pending = id === undefined ? undefined : this.identityChanges.get(id);
11711
- return pending ? _await(pending).pipe(andThen(this.awaitStableIdentity(id))) : void_3;
12449
+ return pending ? _await(pending).pipe(andThen2(this.awaitStableIdentity(id))) : void_3;
11712
12450
  });
11713
12451
  }
11714
12452
  withIdentityChange(id, effect) {
11715
12453
  return suspend2(() => {
11716
12454
  const pending = this.identityChanges.get(id);
11717
12455
  if (pending)
11718
- return _await(pending).pipe(andThen(this.withIdentityChange(id, effect)));
11719
- const settled = makeUnsafe3();
12456
+ return _await(pending).pipe(andThen2(this.withIdentityChange(id, effect)));
12457
+ const settled = makeUnsafe4();
11720
12458
  this.identityChanges.set(id, settled);
11721
12459
  return effect.pipe(onExit((exit) => suspend2(() => {
11722
12460
  if (this.identityChanges.get(id) === settled)
11723
12461
  this.identityChanges.delete(id);
11724
- return done(settled, asVoid(exit));
12462
+ return done2(settled, asVoid(exit));
11725
12463
  })));
11726
12464
  });
11727
12465
  }
@@ -11744,13 +12482,13 @@ class SessionAdmission {
11744
12482
  };
11745
12483
  }
11746
12484
  withAdmission(sessionId, effect) {
11747
- return acquireUseRelease(try_({
12485
+ return acquireUseRelease(try_2({
11748
12486
  try: () => {
11749
12487
  this.assertAdmission();
11750
12488
  return this.retainWork(sessionId);
11751
12489
  },
11752
12490
  catch: (cause) => cause instanceof Error ? cause : new Error("Admit session operation", { cause })
11753
- }), () => this.awaitStableIdentity(sessionId).pipe(andThen(effect)), (release) => sync2(release));
12491
+ }), () => this.awaitStableIdentity(sessionId).pipe(andThen2(effect)), (release) => sync2(release));
11754
12492
  }
11755
12493
  forkTracked(effect, sessionId) {
11756
12494
  return uninterruptibleMask2(() => suspend2(() => {
@@ -11794,7 +12532,7 @@ class SessionAdmission {
11794
12532
  yield* rollback();
11795
12533
  this.schedulePersistence();
11796
12534
  yield* this.flushPersistence().pipe(ignore);
11797
- return yield* fail5(error);
12535
+ return yield* fail6(error);
11798
12536
  })));
11799
12537
  }
11800
12538
  beginDrain() {
@@ -11830,7 +12568,7 @@ function adoptTargetForSession(context, options) {
11830
12568
  return context.admission.withAdmission(options.sessionId, uninterruptibleMask2((restore) => gen(function* () {
11831
12569
  const resolved = yield* context.resolveWorkSession(options.sessionId, options.createIfMissing);
11832
12570
  const session = resolved.session;
11833
- const result2 = yield* make5();
12571
+ const result2 = yield* make10();
11834
12572
  let state = "pending";
11835
12573
  let cancelled = false;
11836
12574
  let reservation;
@@ -11859,7 +12597,7 @@ function adoptTargetForSession(context, options) {
11859
12597
  if (options.tabId !== undefined && browser?.key && context.hooks.targetBrowserKey?.(options.tabId) !== browser.key) {
11860
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);
11861
12599
  }
11862
- reservation = yield* try_({
12600
+ reservation = yield* try_2({
11863
12601
  try: () => context.targetOwnership.reserveTargetOwnership(options.targetId, session.id),
11864
12602
  catch: (cause) => cause instanceof Error ? cause : new Error("Reserve target ownership", { cause })
11865
12603
  });
@@ -11883,7 +12621,7 @@ function adoptTargetForSession(context, options) {
11883
12621
  if (adoptionCancelled()) {
11884
12622
  return yield* timeoutError;
11885
12623
  }
11886
- yield* try_({
12624
+ yield* try_2({
11887
12625
  try: () => {
11888
12626
  context.notifyTargetOwnershipChange(context.targetOwnership.commitTargetOwnership({
11889
12627
  reservation: activeReservation,
@@ -11898,7 +12636,7 @@ function adoptTargetForSession(context, options) {
11898
12636
  yield* succeed4(result2, value);
11899
12637
  return value;
11900
12638
  });
11901
- const transaction = session.executeSemaphore.withPermit(operation.pipe(matchEffect({
12639
+ const transaction = session.executeSemaphore.withPermit(operation.pipe(matchEffect2({
11902
12640
  onFailure: (error) => gen(function* () {
11903
12641
  if (reservation && state !== "committed") {
11904
12642
  context.notifyTargetOwnershipChange(context.targetOwnership.rollbackTargetOwnership(reservation));
@@ -11906,11 +12644,11 @@ function adoptTargetForSession(context, options) {
11906
12644
  if (context.sessions.get(session.id) === session && (resolved.created || state !== "pending")) {
11907
12645
  const cleanup = yield* result(cleanupSettledAdoption(context, session, resolved.created, previousTarget, previousRelayClosed));
11908
12646
  if (isFailure(cleanup)) {
11909
- yield* fail4(result2, cleanup.failure);
12647
+ yield* fail5(result2, cleanup.failure);
11910
12648
  return;
11911
12649
  }
11912
12650
  }
11913
- yield* fail4(result2, error);
12651
+ yield* fail5(result2, error);
11914
12652
  }),
11915
12653
  onSuccess: () => void_3
11916
12654
  })));
@@ -11918,7 +12656,7 @@ function adoptTargetForSession(context, options) {
11918
12656
  yield* context.admission.forkTracked(worker, session.id);
11919
12657
  return yield* restore(_await(result2).pipe(timeoutOrElse({
11920
12658
  duration: timeoutMs,
11921
- orElse: () => cancel.pipe(andThen(fail5(timeoutError)))
12659
+ orElse: () => cancel.pipe(andThen2(fail6(timeoutError)))
11922
12660
  }), onInterrupt(() => cancel)));
11923
12661
  })));
11924
12662
  }
@@ -11967,7 +12705,7 @@ function withLifecycleTimeout(hooks, effect, label) {
11967
12705
  const timeoutMs = hooks.lifecycleTimeoutMs ?? 1e4;
11968
12706
  return effect.pipe(timeoutOrElse({
11969
12707
  duration: timeoutMs,
11970
- orElse: () => fail5(sessionError("timeout", `${label} timed out after ${timeoutMs}ms`))
12708
+ orElse: () => fail6(sessionError("timeout", `${label} timed out after ${timeoutMs}ms`))
11971
12709
  }));
11972
12710
  }
11973
12711
  function closeSessionSettledWithTimeout(admission, hooks, session, closeSettled) {
@@ -11982,7 +12720,7 @@ function executeInSession(ctx, options) {
11982
12720
  }
11983
12721
  const resolved = yield* ctx.resolveWorkSession(options.sessionId, options.createIfMissing, options.browser);
11984
12722
  const session = resolved.session;
11985
- const response = yield* make5();
12723
+ const response = yield* make10();
11986
12724
  let started = false;
11987
12725
  let cancelled = false;
11988
12726
  const operation = gen(function* () {
@@ -11998,8 +12736,8 @@ function executeInSession(ctx, options) {
11998
12736
  started = true;
11999
12737
  session.updatedAt = new Date().toISOString();
12000
12738
  yield* ctx.setExecuting(session.id, true);
12001
- const stopSignal = makeUnsafe3();
12002
- const released = makeUnsafe3();
12739
+ const stopSignal = makeUnsafe4();
12740
+ const released = makeUnsafe4();
12003
12741
  const effectiveTimeoutMs = options.timeoutMs ?? ctx.hooks.executeTimeoutMs ?? defaultExecuteTimeoutMs;
12004
12742
  let deadline;
12005
12743
  const stopRunning = (message, diagnostic) => {
@@ -12063,9 +12801,9 @@ function executeInSession(ctx, options) {
12063
12801
  yield* ctx.admission.commitPersistence();
12064
12802
  return { result: resultWithHint, session: createdSummary(session, resolved.created) };
12065
12803
  });
12066
- const worker = session.executeSemaphore.withPermit(operation.pipe(matchEffect({
12067
- onFailure: (error) => (resolved.created ? ctx.cleanupCreatedSession(session) : void_3).pipe(andThen(fail4(response, error))),
12068
- 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)))
12069
12807
  })));
12070
12808
  const workerFiber = yield* ctx.admission.forkTracked(worker, session.id);
12071
12809
  return yield* restore(_await(response)).pipe(onInterrupt(() => suspend2(() => {
@@ -12074,7 +12812,7 @@ function executeInSession(ctx, options) {
12074
12812
  return void_3;
12075
12813
  }
12076
12814
  cancelled = true;
12077
- 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));
12078
12816
  })));
12079
12817
  })));
12080
12818
  }
@@ -12355,9 +13093,9 @@ class OpenCodeBrowserSessions {
12355
13093
  markTargetProtectedUi(targetId, protectedUi) {
12356
13094
  return this.collectSessionIds((session) => session.sandbox.markTargetProtectedUi(targetId, protectedUi));
12357
13095
  }
12358
- markTargetDetached(targetId) {
13096
+ markTargetDetached(targetId, options = {}) {
12359
13097
  return this.collectSessionIds((session) => {
12360
- const detached = session.sandbox.markTargetDetached(targetId);
13098
+ const detached = session.sandbox.markTargetDetached(targetId, options);
12361
13099
  if (session.target?.id === targetId && session.target.owner === "user") {
12362
13100
  this.notifyTargetOwnershipChange(this.targetOwnership.releaseTargetOwnership(targetId, session.id));
12363
13101
  }
@@ -12438,7 +13176,7 @@ class OpenCodeBrowserSessions {
12438
13176
  }
12439
13177
  networkStatus(id) {
12440
13178
  const session = this.sessions.get(id);
12441
- 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));
12442
13180
  }
12443
13181
  networkStop(id, options = {}) {
12444
13182
  return this.withSessionOperation(id, "network stop", (session) => session.sandbox.networkStop(options));
@@ -12454,8 +13192,8 @@ class OpenCodeBrowserSessions {
12454
13192
  return this.admission.withAdmission(id, suspend2(() => {
12455
13193
  const session = manager.sessions.get(id);
12456
13194
  if (!session)
12457
- return fail5(sessionError("not-found", `Session not found: ${id}`, id));
12458
- 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* () {
12459
13197
  if (manager.sessions.get(id) !== session) {
12460
13198
  return yield* sessionError("inactive", `Session is no longer active: ${id}`, id);
12461
13199
  }
@@ -12473,7 +13211,7 @@ class OpenCodeBrowserSessions {
12473
13211
  session.updatedAt = new Date().toISOString();
12474
13212
  yield* manager.admission.commitPersistence();
12475
13213
  return result;
12476
- }), (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);
12477
13215
  }
12478
13216
  execute(options) {
12479
13217
  return executeInSession(this.executionContext, options);
@@ -12578,7 +13316,7 @@ class OpenCodeBrowserSessions {
12578
13316
  catch: (cause) => cause
12579
13317
  }).pipe(timeoutOrElse({
12580
13318
  duration: this.hooks.journalTimeoutMs ?? 2000,
12581
- 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`))
12582
13320
  }), catch_((error) => sync2(() => {
12583
13321
  console.error("Session execute-record hook failed", error);
12584
13322
  })), asVoid2);
@@ -12662,7 +13400,7 @@ class OpenCodeBrowserSessions {
12662
13400
  const pending = Array.from(sessionRelayTargetIds(this.hooks, session)).filter((id) => !closed.has(id));
12663
13401
  if (pending.length === 0)
12664
13402
  return;
12665
- yield* forEach(pending, (targetId) => this.closeRelayTarget(targetId).pipe(ignore, andThen(sync2(() => {
13403
+ yield* forEach(pending, (targetId) => this.closeRelayTarget(targetId).pipe(ignore, andThen2(sync2(() => {
12666
13404
  closed.add(targetId);
12667
13405
  }))), { concurrency: 4, discard: true });
12668
13406
  }
@@ -12698,14 +13436,14 @@ class OpenCodeBrowserSessions {
12698
13436
  const timeout = sessionError("timeout", `Session ${operation} timed out waiting for active execute in ${session.id}`, session.id);
12699
13437
  return raceFirst(session.executeSemaphore.withPermit(suspend2(() => {
12700
13438
  if (state === "timed-out")
12701
- return fail5(timeout);
13439
+ return fail6(timeout);
12702
13440
  state = "started";
12703
13441
  return effect;
12704
13442
  }).pipe(uninterruptible)), sleep(this.hooks.lifecycleTimeoutMs ?? 1e4).pipe(flatMap3(() => {
12705
13443
  if (state === "started")
12706
13444
  return never;
12707
13445
  state = "timed-out";
12708
- return fail5(timeout);
13446
+ return fail6(timeout);
12709
13447
  })));
12710
13448
  });
12711
13449
  }
@@ -12807,7 +13545,7 @@ function relayHttpError(error) {
12807
13545
  return routeError(error instanceof Error ? error.message : String(error), 500, "internal");
12808
13546
  }
12809
13547
  function originPatterns(raw) {
12810
- return try_({
13548
+ return try_2({
12811
13549
  try: () => normalizeOriginPatterns(raw),
12812
13550
  catch: (cause) => cause instanceof OriginPatternError ? new Error(cause.message) : new Error("Invalid origin patterns", { cause })
12813
13551
  });
@@ -12819,8 +13557,8 @@ function sendNotFound(response) {
12819
13557
 
12820
13558
  // src/recording-relay.ts
12821
13559
  import crypto7 from "node:crypto";
12822
- import fs12 from "node:fs/promises";
12823
- import path12 from "node:path";
13560
+ import fs13 from "node:fs/promises";
13561
+ import path13 from "node:path";
12824
13562
  import { performance as performance4 } from "node:perf_hooks";
12825
13563
 
12826
13564
  // src/recording-relay/protocol.ts
@@ -12888,8 +13626,8 @@ function validateUint32(value, field, positive) {
12888
13626
  }
12889
13627
 
12890
13628
  // src/recording-relay/cdp-capture.ts
12891
- import fs11 from "node:fs/promises";
12892
- import path11 from "node:path";
13629
+ import fs12 from "node:fs/promises";
13630
+ import path12 from "node:path";
12893
13631
  function handleCdpScreencastFrame(context, recording, options) {
12894
13632
  const frame = parseScreencastFrame(options.params);
12895
13633
  acknowledgeScreencastFrame({
@@ -12954,7 +13692,7 @@ async function startCdpRecording(context, options, starting) {
12954
13692
  if (!artifactType) {
12955
13693
  return { success: false, error: "CDP recording output path must end in .webm or .mp4" };
12956
13694
  }
12957
- await fs11.mkdir(path11.dirname(options.outputPath), { recursive: true });
13695
+ await fs12.mkdir(path12.dirname(options.outputPath), { recursive: true });
12958
13696
  if (starting.cancelled)
12959
13697
  return cancelledResult();
12960
13698
  const frameRate = options.frameRate ?? defaultCdpFrameRate;
@@ -13093,7 +13831,7 @@ async function finishCdpRecording(context, recording) {
13093
13831
  await writeSourceFrame(recording, recording.lastFrame, endFrameNumber);
13094
13832
  recording.frameCount = endFrameNumber;
13095
13833
  await recording.encoder.finish();
13096
- const stat = await fs11.stat(recording.outputPath);
13834
+ const stat = await fs12.stat(recording.outputPath);
13097
13835
  const quality = recordingQuality(recording, durationMs);
13098
13836
  const metadata = {
13099
13837
  mode: "cdp",
@@ -13107,7 +13845,7 @@ async function finishCdpRecording(context, recording) {
13107
13845
  ...quality,
13108
13846
  mimeType: recording.artifactType === "mp4" ? "video/mp4" : "video/webm"
13109
13847
  };
13110
- await fs11.writeFile(`${recording.outputPath}.json`, `${JSON.stringify(metadata, null, 2)}
13848
+ await fs12.writeFile(`${recording.outputPath}.json`, `${JSON.stringify(metadata, null, 2)}
13111
13849
  `, "utf8");
13112
13850
  return {
13113
13851
  success: true,
@@ -13471,7 +14209,7 @@ class RecordingRelay {
13471
14209
  throw new Error("No tab capture data was received");
13472
14210
  await recording.file.sync();
13473
14211
  await recording.file.close();
13474
- await fs12.rename(recording.temporaryPath, recording.outputPath);
14212
+ await fs13.rename(recording.temporaryPath, recording.outputPath);
13475
14213
  recording.finalized = true;
13476
14214
  recording.resolveStop?.({
13477
14215
  success: true,
@@ -13517,7 +14255,7 @@ class RecordingRelay {
13517
14255
  await recording.writePromise.catch(() => {});
13518
14256
  await recording.file.close().catch(() => {});
13519
14257
  if (!recording.finalized)
13520
- await fs12.rm(recording.temporaryPath, { force: true }).catch(() => {});
14258
+ await fs13.rm(recording.temporaryPath, { force: true }).catch(() => {});
13521
14259
  if (this.activeRecordings.get(recording.tabId) === recording) {
13522
14260
  this.activeRecordings.delete(recording.tabId);
13523
14261
  this.recordingChanged(recording.tabId);
@@ -13541,11 +14279,11 @@ class RecordingRelay {
13541
14279
  if (cdpArtifactType(options.outputPath) !== "webm") {
13542
14280
  return { success: false, error: "tabCapture recording output path must end in .webm; use --mode cdp for MP4" };
13543
14281
  }
13544
- await fs12.mkdir(path12.dirname(options.outputPath), { recursive: true });
14282
+ await fs13.mkdir(path13.dirname(options.outputPath), { recursive: true });
13545
14283
  if (starting.cancelled)
13546
14284
  return { success: false, error: "Recording was cancelled while starting" };
13547
14285
  const temporaryPath = `${options.outputPath}.partial-${process.pid}-${crypto7.randomUUID()}`;
13548
- const file = await fs12.open(temporaryPath, "wx", 384);
14286
+ const file = await fs13.open(temporaryPath, "wx", 384);
13549
14287
  const recording = {
13550
14288
  tabId: options.tabId,
13551
14289
  ...options.sessionId ? { sessionId: options.sessionId } : {},
@@ -14791,6 +15529,52 @@ function replayTargetCreated(options) {
14791
15529
  }
14792
15530
  }
14793
15531
 
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)
15551
+ return;
15552
+ committedLoaders.add(loaderId);
15553
+ loaderCommitted(loaderId);
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
+ })));
15576
+ });
15577
+
14794
15578
  // src/relay/process-guard.ts
14795
15579
  import http4 from "node:http";
14796
15580
 
@@ -14992,7 +15776,15 @@ function createCdpDispatcher(options) {
14992
15776
  return;
14993
15777
  yield* ghostCursor.mouseEvent(mouseOptions.tabId, mouseOptions.message.params);
14994
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
+ }
14995
15786
  function captureScreenshotNudged(command) {
15787
+ const nudgeParams = captureScreenshotNudgeParams(command.params);
14996
15788
  const nudges = gen(function* () {
14997
15789
  for (const delayMs of [600, 1000, 1500, 2000, 3000, 5000, 8000]) {
14998
15790
  yield* sleep(delayMs);
@@ -15000,60 +15792,17 @@ function createCdpDispatcher(options) {
15000
15792
  yield* forkDetach(sendDebuggerCommand({
15001
15793
  tabId: command.tabId,
15002
15794
  method: "Page.captureScreenshot",
15003
- params: { format: "jpeg", quality: 1, clip: { x: 0, y: 0, width: 1, height: 1, scale: 1 } }
15795
+ params: nudgeParams
15004
15796
  }).pipe(ignore));
15005
15797
  }
15006
15798
  return yield* never;
15007
15799
  });
15008
15800
  return raceFirst(sendDebuggerCommand(command), nudges);
15009
15801
  }
15010
- const navigateTopFrameToDataUrl = fnUntraced(function* (tabId, params) {
15011
- const url = getString2(params, "url")?.trim();
15012
- if (!url || !/^data:/i.test(url))
15013
- return;
15014
- const frameId = mainFrameIdsByTab.get(tabId) ?? registry.tabTargets.get(tabId)?.targetInfo.targetId;
15015
- const requestedFrameId = getString2(params, "frameId");
15016
- if (!frameId || requestedFrameId !== undefined && requestedFrameId !== frameId || blankNavigationWaiters.has(tabId))
15017
- return;
15018
- const html = yield* tryPromise(() => dataUrlDocument2(url)).pipe(orElseSucceed(() => {
15019
- return;
15020
- }));
15021
- if (html === undefined)
15022
- return;
15023
- const committedLoaders = new Set;
15024
- let loaderCommitted = () => {};
15025
- blankNavigationWaiters.set(tabId, (frameUrl, loaderId) => {
15026
- if (frameUrl !== "about:blank" || loaderId === undefined)
15027
- return;
15028
- committedLoaders.add(loaderId);
15029
- loaderCommitted(loaderId);
15030
- });
15031
- return yield* gen(function* () {
15032
- const navigated = yield* sendDebuggerCommand({ tabId, method: "Page.navigate", params: { url: "about:blank", frameId } });
15033
- const loaderId = getString2(navigated, "loaderId");
15034
- if (getString2(navigated, "errorText") || loaderId === undefined)
15035
- return navigated;
15036
- if (!committedLoaders.has(loaderId)) {
15037
- const committed = yield* promise(() => new Promise((resolve) => {
15038
- loaderCommitted = (id) => {
15039
- if (id === loaderId)
15040
- resolve();
15041
- };
15042
- })).pipe(timeoutOption(1e4));
15043
- if (committed._tag === "None")
15044
- return navigated;
15045
- }
15046
- yield* sendDebuggerCommand({ tabId, method: "Page.setDocumentContent", params: { frameId, html } });
15047
- relayLog("navigate.data", { tabId, chars: html.length });
15048
- return { frameId: getString2(navigated, "frameId") ?? frameId, loaderId };
15049
- }).pipe(ensuring(sync2(() => {
15050
- blankNavigationWaiters.delete(tabId);
15051
- })));
15052
- });
15053
15802
  const routeCdpCommand = fn("Relay.routeCdpCommand")(function* (socket, message) {
15054
15803
  const clientOpenCodeBrowserSessionId = cdpClients.sessionId(socket);
15055
15804
  if (!shutdownControl.accepting && (!cdpClients.isSandbox(socket) || !clientOpenCodeBrowserSessionId || !sessions.hasPendingWork(clientOpenCodeBrowserSessionId))) {
15056
- 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"));
15057
15806
  }
15058
15807
  const guardMessage = guardCdpMethod({
15059
15808
  method: message.method,
@@ -15063,7 +15812,7 @@ function createCdpDispatcher(options) {
15063
15812
  pageUrls: () => cdpRouter.visibleRoots(socket).map((target) => target.targetInfo.url)
15064
15813
  });
15065
15814
  if (guardMessage) {
15066
- return yield* fail5(new Error(guardMessage));
15815
+ return yield* fail6(new Error(guardMessage));
15067
15816
  }
15068
15817
  if (message.method === "Page.navigate" || message.method === "Target.createTarget") {
15069
15818
  const tabSessionId = message.method === "Page.navigate" ? (() => {
@@ -15079,7 +15828,7 @@ function createCdpDispatcher(options) {
15079
15828
  sessionId: tabSessionId ?? clientOpenCodeBrowserSessionId
15080
15829
  }));
15081
15830
  if (refusal)
15082
- return yield* fail5(new Error(refusal));
15831
+ return yield* fail6(new Error(refusal));
15083
15832
  }
15084
15833
  if (message.method === "Browser.getVersion") {
15085
15834
  return {
@@ -15110,7 +15859,7 @@ function createCdpDispatcher(options) {
15110
15859
  if (message.method === "Target.setAutoAttach" && message.sessionId && registry.targets.has(message.sessionId)) {
15111
15860
  const target = cdpRouter.rootForSession(socket, message.sessionId);
15112
15861
  if (!target) {
15113
- return yield* fail5(new Error(`Target not found: ${message.sessionId}`));
15862
+ return yield* fail6(new Error(`Target not found: ${message.sessionId}`));
15114
15863
  }
15115
15864
  const result = yield* sendDebuggerCommand({ tabId: target.tabId, method: "Target.setAutoAttach", params: message.params ?? {} });
15116
15865
  replayChildTargetsForParent({ socket, parentSessionId: target.sessionId, registry, clients: cdpClients });
@@ -15136,7 +15885,7 @@ function createCdpDispatcher(options) {
15136
15885
  replayChildFrameNavigation({ socket, registry, target });
15137
15886
  return { sessionId: target.sessionId };
15138
15887
  }
15139
- return yield* fail5(new Error(`Target not found: ${targetId}`));
15888
+ return yield* fail6(new Error(`Target not found: ${targetId}`));
15140
15889
  }
15141
15890
  if (message.method === "Target.getTargetInfo") {
15142
15891
  const targetId = getString2(message.params, "targetId") ?? "";
@@ -15147,13 +15896,13 @@ function createCdpDispatcher(options) {
15147
15896
  if (!target) {
15148
15897
  if (!targetId && !message.sessionId)
15149
15898
  return {};
15150
- 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"}`));
15151
15900
  }
15152
15901
  return { targetInfo: target.targetInfo };
15153
15902
  }
15154
15903
  if (message.method === "Target.createTarget" || message.method === "Target.closeTarget") {
15155
15904
  if (message.method === "Target.createTarget") {
15156
- const url = getString2(message.params, "url") ?? "about:blank";
15905
+ const url = createTargetUrl2(message.params);
15157
15906
  const opencodeBrowserSessionId = cdpClients.sessionId(socket);
15158
15907
  const autoAttachParams = cdpClients.autoAttachParams(socket);
15159
15908
  const target = yield* createAndAttachTab({
@@ -15184,7 +15933,7 @@ function createCdpDispatcher(options) {
15184
15933
  return {};
15185
15934
  }
15186
15935
  const normalizedMessage = removeDefaultLightColorSchemeEmulation(message);
15187
- const route = yield* try_({
15936
+ const route = yield* try_2({
15188
15937
  try: () => cdpRouter.resolveCommandRoute(socket, message),
15189
15938
  catch: (error) => error instanceof Error ? error : new Error(String(error))
15190
15939
  });
@@ -15197,7 +15946,14 @@ function createCdpDispatcher(options) {
15197
15946
  if (message.method === ghostCursorCommandMethod)
15198
15947
  return yield* ghostCursor.command(tabId, message.params);
15199
15948
  if (message.method === "Page.navigate" && route.chromeSessionId === undefined) {
15200
- 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
+ });
15201
15957
  if (dataNavigation)
15202
15958
  return dataNavigation;
15203
15959
  }
@@ -15224,11 +15980,11 @@ function createCdpDispatcher(options) {
15224
15980
  return fnUntraced(function* (socket, raw) {
15225
15981
  const message = parseJsonObject(raw);
15226
15982
  if (!isCdpRequest(message)) {
15227
- return yield* fail5(new Error("Invalid CDP request"));
15983
+ return yield* fail6(new Error("Invalid CDP request"));
15228
15984
  }
15229
15985
  const frameTreeSent = message.method === "Page.getFrameTree" ? admitFrameTreeResponse(socket, message.sessionId) : undefined;
15230
15986
  debugLog?.(`cdp<- ${cdpClients.sessionId(socket) ?? "raw"} #${message.id} ${message.method} ${message.sessionId ?? ""}`);
15231
- yield* matchEffect(routeCdpCommand(socket, message), {
15987
+ yield* matchEffect2(routeCdpCommand(socket, message), {
15232
15988
  onFailure: (error) => {
15233
15989
  return sync2(() => {
15234
15990
  const runtimeEvaluation = isRuntimeEvaluationMethod(message.method);
@@ -15276,11 +16032,11 @@ function createExtensionCommands(options) {
15276
16032
  if (tabId !== undefined) {
15277
16033
  const owner = browsers.browserTab(tabId);
15278
16034
  if (!owner)
15279
- return fail5(new Error("browse extension is not connected"));
16035
+ return fail6(new Error("browse extension is not connected"));
15280
16036
  return sendToBrowser(owner.link, { ...command, params: { ...command.params, tabId: owner.tabId } });
15281
16037
  }
15282
16038
  const target = link ?? browsers.defaultLink();
15283
- 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"));
15284
16040
  };
15285
16041
  const sendExtensionBestEffort = (command, link) => {
15286
16042
  runPromise(ignore(sendToExtension(command, link))).catch(() => {});
@@ -15293,13 +16049,13 @@ function createExtensionCommands(options) {
15293
16049
  const sendToEach = (command) => gen(function* () {
15294
16050
  const links = browsers.list().filter((link) => link.rpc.connected);
15295
16051
  if (links.length === 0)
15296
- return yield* fail5(new Error("browse extension is not connected"));
16052
+ return yield* fail6(new Error("browse extension is not connected"));
15297
16053
  const results = yield* forEach(links, (link) => result(sendToBrowser(link, command)), { concurrency: "unbounded" });
15298
16054
  const succeeded = results.find(isSuccess);
15299
16055
  if (succeeded)
15300
16056
  return succeeded.success;
15301
16057
  const failed = results.find(isFailure);
15302
- 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"));
15303
16059
  });
15304
16060
  return { sendToExtension, sendExtensionBestEffort, sendToEveryBrowser, sendToEach };
15305
16061
  }
@@ -15335,6 +16091,7 @@ function createExtensionEventHandler(options) {
15335
16091
  refreshPageStatus,
15336
16092
  refreshTabGrouping,
15337
16093
  handleToolbarClick,
16094
+ handleDebuggingBarCancel,
15338
16095
  cancelTargetHandoffs,
15339
16096
  detachTargetState,
15340
16097
  detachChildTargetState,
@@ -15589,6 +16346,13 @@ function createExtensionEventHandler(options) {
15589
16346
  }
15590
16347
  return;
15591
16348
  }
16349
+ if (reason === "canceled_by_user") {
16350
+ if (eventTabId) {
16351
+ handleDebuggingBarCancel(eventTabId);
16352
+ detachTargetState(eventTabId, { releasedByUser: true });
16353
+ }
16354
+ return;
16355
+ }
15592
16356
  if (eventTabId)
15593
16357
  detachTargetState(eventTabId);
15594
16358
  return;
@@ -15823,7 +16587,7 @@ function createExtensionEventHandler(options) {
15823
16587
 
15824
16588
  // src/relay/extension-handshake.ts
15825
16589
  import crypto8 from "node:crypto";
15826
- import fs13 from "node:fs";
16590
+ import fs14 from "node:fs";
15827
16591
  import { WebSocket as WebSocket3 } from "ws";
15828
16592
  var maxPreAuthMessageBytes = 64 * 1024;
15829
16593
  var preAuthHandshakeTimeoutMs = 1e4;
@@ -15845,7 +16609,7 @@ class ExtensionHandshake {
15845
16609
  this.options = options;
15846
16610
  }
15847
16611
  rejectedProtocol() {
15848
- return this.mismatch ?? (fs13.existsSync(oldStoreMarker()) ? extensionProtocolCompatibility(2) : undefined);
16612
+ return this.mismatch ?? (fs14.existsSync(oldStoreMarker()) ? extensionProtocolCompatibility(2) : undefined);
15849
16613
  }
15850
16614
  mismatchAdvice(version) {
15851
16615
  return extensionProtocolAdvice(version, { install: installCommand() }, !this.mismatch || this.mismatch.origin === `chrome-extension://${this.options.storeId}` ? "store" : this.mismatch.origin === stableUnpackedExtensionOrigin2 ? "unpacked" : undefined);
@@ -16000,8 +16764,8 @@ class ExtensionHandshake {
16000
16764
  return;
16001
16765
  }
16002
16766
  this.mismatch = undefined;
16003
- if (fs13.existsSync(oldStoreMarker()))
16004
- fs13.rmSync(oldStoreMarker(), { force: true });
16767
+ if (fs14.existsSync(oldStoreMarker()))
16768
+ fs14.rmSync(oldStoreMarker(), { force: true });
16005
16769
  if (message.method === "protocol") {
16006
16770
  if (message.params?.unpaired === true) {
16007
16771
  this.lastUnpaired = Date.now();
@@ -16400,7 +17164,7 @@ function createRelayHousekeeping(options) {
16400
17164
  const target = registry.targetsByTargetId.get(targetId);
16401
17165
  return target ? isTabBusy(target.tabId) : false;
16402
17166
  }
16403
- }).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(() => {});
16404
17168
  }, 60000);
16405
17169
  idleReapTimer.unref();
16406
17170
  }
@@ -16437,7 +17201,7 @@ function createRelaySettingsSync(options) {
16437
17201
  const extensionSettings = (method, values) => gen(function* () {
16438
17202
  if (!browsers.connected) {
16439
17203
  const rejected = handshake.rejectedProtocol();
16440
- 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."));
16441
17205
  }
16442
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));
16443
17207
  return settingsFromExtension(result);
@@ -16479,7 +17243,7 @@ function createRelaySettingsSync(options) {
16479
17243
  const httpSettings = {
16480
17244
  get: () => extensionSettings("settings.get").pipe(map5((stored) => describeSettings(withRelaySettings(stored), userSettingOverrides()))),
16481
17245
  set: (input) => gen(function* () {
16482
- const requested = yield* try_({
17246
+ const requested = yield* try_2({
16483
17247
  try: () => parseSettingChanges(input),
16484
17248
  catch: (error) => error instanceof SettingsInputError ? new HttpRouteError2({ message: error.message, status: 400, code: "invalid-request" }) : new Error(String(error))
16485
17249
  });
@@ -16728,6 +17492,17 @@ function createTabPresentation(options) {
16728
17492
  console.error("Toolbar toggle failed", error);
16729
17493
  });
16730
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
+ }
16731
17506
  function presentAttachedTarget(committedTarget) {
16732
17507
  tabActivity.touch(committedTarget.tabId);
16733
17508
  const tabId = committedTarget.tabId;
@@ -16762,6 +17537,7 @@ function createTabPresentation(options) {
16762
17537
  requestHandoff,
16763
17538
  onSessionExecuteStateChange,
16764
17539
  handleToolbarClick,
17540
+ handleDebuggingBarCancel,
16765
17541
  presentAttachedTarget
16766
17542
  };
16767
17543
  }
@@ -16910,8 +17686,9 @@ function createRelayTransportServers(deps) {
16910
17686
 
16911
17687
  // src/cdp/root-target-lifecycle.ts
16912
17688
  var DEFAULT_INVENTORY_COMMAND_TIMEOUT_MS = 5000;
17689
+ var DEFAULT_ATTACH_COMMAND_TIMEOUT_MS = 1e4;
16913
17690
 
16914
- class InventoryTimeout extends TaggedError2()("RootTargetLifecycle.InventoryTimeout", {
17691
+ class RootTargetTimeout extends TaggedError2()("RootTargetLifecycle.CommandTimeout", {
16915
17692
  message: String3
16916
17693
  }) {
16917
17694
  }
@@ -16926,13 +17703,13 @@ class RootTargetLifecycle {
16926
17703
  scope;
16927
17704
  run;
16928
17705
  static make = fn("RootTargetLifecycle.make")(function* (options) {
16929
- const scope = yield* make6();
17706
+ const scope = yield* make11();
16930
17707
  const run = runForkWith(yield* context2());
16931
17708
  return yield* acquireRelease(sync2(() => new RootTargetLifecycle(options, scope, run)), (lifecycle) => lifecycle.close());
16932
17709
  });
16933
17710
  tabs = new Map;
16934
17711
  workers = new Map;
16935
- idle = makeUnsafe5(true);
17712
+ idle = makeUnsafe2(true);
16936
17713
  active = 0;
16937
17714
  closing = false;
16938
17715
  failedTabs = new Map;
@@ -16951,7 +17728,7 @@ class RootTargetLifecycle {
16951
17728
  work.revision += 1;
16952
17729
  this.failedTabs.delete(tabId);
16953
17730
  }
16954
- 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));
16955
17732
  reconcile = fn("RootTargetLifecycle.reconcile")((tabId, generation) => this.withPermit(tabId, generation, (transition) => this.reconcileUnlocked(transition)));
16956
17733
  queue(options) {
16957
17734
  if (this.closing)
@@ -16978,7 +17755,7 @@ class RootTargetLifecycle {
16978
17755
  work.users += 1;
16979
17756
  const worker = {
16980
17757
  generation,
16981
- done: makeUnsafe5(),
17758
+ done: makeUnsafe2(),
16982
17759
  attachIfMissing: options.attachIfMissing,
16983
17760
  renewed: options.renewed === true,
16984
17761
  pending: false,
@@ -17011,7 +17788,7 @@ class RootTargetLifecycle {
17011
17788
  }).pipe(tapError((error) => sync2(() => lifecycle.options.reportError(options.errorMessage, error))), retry({
17012
17789
  times: 2,
17013
17790
  schedule: spaced(0).pipe(modifyDelay(({ attempt }) => succeed6(100 * attempt))),
17014
- 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
17015
17792
  }));
17016
17793
  if (lifecycle.closing || generation !== lifecycle.options.extension.generation(options.tabId))
17017
17794
  return null;
@@ -17062,7 +17839,7 @@ class RootTargetLifecycle {
17062
17839
  const lifecycle = this;
17063
17840
  return suspend2(() => {
17064
17841
  if (lifecycle.closing)
17065
- return fail5(new Error("Relay is closing"));
17842
+ return fail6(new Error("Relay is closing"));
17066
17843
  const generation = expectedGeneration ?? lifecycle.options.extension.generation(tabId);
17067
17844
  const work = lifecycle.tabWork(tabId);
17068
17845
  const revision = work.revision;
@@ -17079,7 +17856,7 @@ class RootTargetLifecycle {
17079
17856
  root: lifecycle.options.registry.tabTargets.get(tabId),
17080
17857
  staged: lifecycle.options.registry.stagedRootTarget(tabId)
17081
17858
  };
17082
- return lifecycle.check(transition).pipe(andThen(() => use(transition)));
17859
+ return lifecycle.check(transition).pipe(andThen2(() => use(transition)));
17083
17860
  })).pipe(ensuring(sync2(() => {
17084
17861
  if (--work.users === 0 && !lifecycle.options.registry.routingRootTarget(tabId))
17085
17862
  lifecycle.tabs.delete(tabId);
@@ -17101,14 +17878,14 @@ class RootTargetLifecycle {
17101
17878
  return yield* new GenerationChanged({ message: "Root target generation changed during reconciliation" });
17102
17879
  });
17103
17880
  step(transition, effect) {
17104
- 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)));
17105
17882
  }
17106
17883
  command(transition, method, params = {}) {
17107
17884
  const send = this.options.extension.send({ method: "debugger.sendCommand", params: { tabId: transition.tabId, method, params } });
17108
17885
  const timeoutMs = transition.timeoutMs;
17109
17886
  return this.step(transition, timeoutMs === undefined ? send : send.pipe(timeoutOrElse({
17110
17887
  duration: timeoutMs,
17111
- 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}` }))
17112
17889
  })));
17113
17890
  }
17114
17891
  attachUnlocked = fnUntraced(function* (transition, options) {
@@ -17116,14 +17893,12 @@ class RootTargetLifecycle {
17116
17893
  if (!options.alreadyAttached)
17117
17894
  yield* this.step(transition, this.options.extension.send({ method: "debugger.attach", params: { tabId } }));
17118
17895
  yield* this.command(transition, "Page.enable");
17119
- yield* gen({ self: this }, function* () {
17120
- yield* this.command(transition, "Emulation.setFocusEmulationEnabled", { enabled: false });
17121
- }).pipe(ignore);
17896
+ yield* this.command(transition, "Emulation.setFocusEmulationEnabled", { enabled: false }).pipe(catchIf((error) => !(error instanceof RootTargetTimeout), () => void_3));
17122
17897
  yield* this.check(transition);
17123
17898
  const result = yield* this.command(transition, "Target.getTargetInfo");
17124
17899
  const reportedTargetInfo = getTargetInfo2(result.targetInfo);
17125
17900
  if (!reportedTargetInfo)
17126
- return yield* fail5(new Error("Target.getTargetInfo did not return targetInfo"));
17901
+ return yield* fail6(new Error("Target.getTargetInfo did not return targetInfo"));
17127
17902
  const targetInfo = options.openerTargetId && !reportedTargetInfo.openerId ? { ...reportedTargetInfo, openerId: options.openerTargetId } : reportedTargetInfo;
17128
17903
  const restored = options.opencodeBrowserSessionId ? undefined : this.options.sessions.persistedTargetOwner(targetInfo.targetId);
17129
17904
  const opencodeBrowserSessionId = options.opencodeBrowserSessionId ?? restored?.sessionId;
@@ -17147,7 +17922,7 @@ class RootTargetLifecycle {
17147
17922
  yield* this.check(transition);
17148
17923
  const targetInfo = getTargetInfo2(result.targetInfo);
17149
17924
  if (!targetInfo) {
17150
- 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"));
17151
17926
  }
17152
17927
  if (staged?.targetInfo.targetId === targetInfo.targetId) {
17153
17928
  yield* this.finish(transition, staged);
@@ -17170,11 +17945,11 @@ class RootTargetLifecycle {
17170
17945
  yield* this.command(transition, "Target.setAutoAttach", autoAttachParams ?? { autoAttach: true, waitForDebuggerOnStart: false, flatten: true });
17171
17946
  const result = yield* this.command(transition, "Target.getTargetInfo");
17172
17947
  if (getTargetInfo2(result.targetInfo)?.targetId !== target.targetInfo.targetId) {
17173
- 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}`));
17174
17949
  }
17175
17950
  const change = registry.commitStagedRootTarget(target.tabId, target.sessionId);
17176
17951
  if (!change)
17177
- 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}`));
17178
17953
  transition.root = change.target;
17179
17954
  transition.staged = undefined;
17180
17955
  if (change.kind === "replaced") {
@@ -17202,9 +17977,9 @@ class RootTargetLifecycle {
17202
17977
  }
17203
17978
 
17204
17979
  // src/session-manager/catalog.ts
17205
- import fs14 from "node:fs/promises";
17980
+ import fs15 from "node:fs/promises";
17206
17981
  import os6 from "node:os";
17207
- import path13 from "node:path";
17982
+ import path14 from "node:path";
17208
17983
  import crypto9 from "node:crypto";
17209
17984
  var PersistedSession = Struct({
17210
17985
  id: String3,
@@ -17225,7 +18000,7 @@ var Catalog = Struct({
17225
18000
  sessions: ArraySchema(PersistedSession)
17226
18001
  });
17227
18002
  function defaultSessionCatalogPath(port, home = os6.homedir()) {
17228
- return path13.join(dataRoot(home), "relays", String(port), "sessions.json");
18003
+ return path14.join(dataRoot(home), "relays", String(port), "sessions.json");
17229
18004
  }
17230
18005
 
17231
18006
  class SessionCatalog {
@@ -17236,7 +18011,7 @@ class SessionCatalog {
17236
18011
  async load() {
17237
18012
  let text;
17238
18013
  try {
17239
- text = await fs14.readFile(this.filePath, "utf8");
18014
+ text = await fs15.readFile(this.filePath, "utf8");
17240
18015
  } catch (error) {
17241
18016
  if (isNodeError(error) && error.code === "ENOENT")
17242
18017
  return [];
@@ -17252,7 +18027,7 @@ class SessionCatalog {
17252
18027
  const detail = error instanceof Error && error.message ? `: ${error.message}` : "";
17253
18028
  const corruptPath = `${this.filePath}.corrupt-${Date.now()}`;
17254
18029
  try {
17255
- await fs14.rename(this.filePath, corruptPath);
18030
+ await fs15.rename(this.filePath, corruptPath);
17256
18031
  console.error(`Browse session catalog at ${this.filePath} was unreadable${detail}; moved it to ${corruptPath} and started with no saved sessions`);
17257
18032
  } catch (moveError) {
17258
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`);
@@ -17261,21 +18036,21 @@ class SessionCatalog {
17261
18036
  }
17262
18037
  }
17263
18038
  async save(sessions) {
17264
- const directory = path13.dirname(this.filePath);
18039
+ const directory = path14.dirname(this.filePath);
17265
18040
  const temporaryPath = `${this.filePath}.${process.pid}.${crypto9.randomUUID()}.tmp`;
17266
18041
  const contents = `${JSON.stringify({ version: 1, sessions }, null, 2)}
17267
18042
  `;
17268
18043
  let temporaryFile;
17269
18044
  try {
17270
- await fs14.mkdir(directory, { recursive: true, mode: 448 });
17271
- await fs14.chmod(directory, 448);
17272
- 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);
17273
18048
  await temporaryFile.writeFile(contents, "utf8");
17274
18049
  await temporaryFile.sync();
17275
18050
  await temporaryFile.close();
17276
18051
  temporaryFile = undefined;
17277
- await fs14.rename(temporaryPath, this.filePath);
17278
- const directoryHandle = await fs14.open(directory, "r");
18052
+ await fs15.rename(temporaryPath, this.filePath);
18053
+ const directoryHandle = await fs15.open(directory, "r");
17279
18054
  try {
17280
18055
  try {
17281
18056
  await directoryHandle.sync();
@@ -17291,7 +18066,7 @@ class SessionCatalog {
17291
18066
  await temporaryFile?.close();
17292
18067
  } catch {}
17293
18068
  try {
17294
- await fs14.rm(temporaryPath, { force: true });
18069
+ await fs15.rm(temporaryPath, { force: true });
17295
18070
  } catch {}
17296
18071
  throw new Error(`Could not write browse session catalog at ${this.filePath}`, { cause: error });
17297
18072
  }
@@ -17314,6 +18089,7 @@ class SessionNavigationGuard {
17314
18089
  warnings = new Map;
17315
18090
  rulesCache = new Map;
17316
18091
  freshPopups = new Set;
18092
+ blanking = new Map;
17317
18093
  constructor(dependencies) {
17318
18094
  this.dependencies = dependencies;
17319
18095
  }
@@ -17343,7 +18119,7 @@ class SessionNavigationGuard {
17343
18119
  const rules = this.rules(options.sessionId);
17344
18120
  if (!rules)
17345
18121
  return;
17346
- 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");
17347
18123
  if (url === undefined)
17348
18124
  return;
17349
18125
  const decision = await checkNavigationUrl(url, rules);
@@ -17358,8 +18134,16 @@ class SessionNavigationGuard {
17358
18134
  this.freshPopups.add(target.tabId);
17359
18135
  this.observeCommittedUrl(target, target.targetInfo.url);
17360
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
+ }
17361
18144
  forgetTab(tabId) {
17362
18145
  this.freshPopups.delete(tabId);
18146
+ this.blanking.delete(tabId);
17363
18147
  }
17364
18148
  observeEvent(target, method, params) {
17365
18149
  if (method !== "Page.frameNavigated" && method !== "Page.frameRequestedNavigation" && method !== "Page.frameStartedNavigating" && method !== "Network.responseReceived")
@@ -17410,14 +18194,15 @@ class SessionNavigationGuard {
17410
18194
  observeCommittedUrl(target, url) {
17411
18195
  const rules = this.rules(target.opencodeBrowserSessionId);
17412
18196
  if (!rules)
17413
- return;
18197
+ return true;
17414
18198
  const decision = checkUrl(url, rules);
17415
18199
  if (decision.allowed) {
17416
18200
  if (!/^about:/.test(url))
17417
18201
  this.freshPopups.delete(target.tabId);
17418
- return;
18202
+ return true;
17419
18203
  }
17420
18204
  this.violation(target, url, decision.reason, "commit");
18205
+ return false;
17421
18206
  }
17422
18207
  violation(target, url, reason, _stage) {
17423
18208
  const sessionId = target.opencodeBrowserSessionId;
@@ -17433,7 +18218,14 @@ class SessionNavigationGuard {
17433
18218
  });
17434
18219
  return;
17435
18220
  }
17436
- 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
+ });
17437
18229
  }
17438
18230
  addWarning(sessionId, warning) {
17439
18231
  const pending = this.warnings.get(sessionId) ?? [];
@@ -17509,7 +18301,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17509
18301
  const sessionCatalog = options.sessionCatalogPath === null ? undefined : new SessionCatalog(options.sessionCatalogPath ?? defaultSessionCatalogPath(port));
17510
18302
  let catalogWritesEnabled = false;
17511
18303
  const registry = new TargetRegistry;
17512
- const authToken = yield* try_({
18304
+ const authToken = yield* try_2({
17513
18305
  try: () => {
17514
18306
  ensurePrivateDirectory();
17515
18307
  return relayToken();
@@ -17669,7 +18461,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17669
18461
  },
17670
18462
  checkBrowserResponsive: (key) => {
17671
18463
  const link = browsers.byKey(key);
17672
- 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."));
17673
18465
  },
17674
18466
  targetBrowserKey: (tabId) => browsers.ownerKey(tabId),
17675
18467
  getUserAttachedPageUrls: (session) => registry.listRootTargets().filter((target) => target.owner === "user" && browsers.ownerKey(target.tabId) === session.browser?.key).map((target) => target.targetInfo.url || "about:blank"),
@@ -17729,6 +18521,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17729
18521
  const known = ownersAcrossReconnect.get(targetId);
17730
18522
  return known?.sessionId !== undefined && sessions.sessions.has(known.sessionId) ? { sessionId: known.sessionId, owner: known.owner } : undefined;
17731
18523
  };
18524
+ const attachTimeoutMs = yield* Int("OPENCODE_BROWSER_ATTACH_TIMEOUT_MS").pipe(withDefault(1e4));
17732
18525
  const rootLifecycle = yield* RootTargetLifecycle.make({
17733
18526
  registry,
17734
18527
  sessions: {
@@ -17748,7 +18541,8 @@ var makeRelay = fnUntraced(function* (options = {}) {
17748
18541
  announceRoot: announceAttachedTarget,
17749
18542
  announceChild: announceAttachedChildTarget
17750
18543
  },
17751
- reportError: (message, error) => console.error(message, error)
18544
+ reportError: (message, error) => console.error(message, error),
18545
+ attachCommandTimeoutMs: attachTimeoutMs
17752
18546
  });
17753
18547
  const settingsSync = createRelaySettingsSync({
17754
18548
  browsers,
@@ -17763,8 +18557,8 @@ var makeRelay = fnUntraced(function* (options = {}) {
17763
18557
  const restartTimeoutMs = yield* Int("OPENCODE_BROWSER_RESTART_TIMEOUT_MS").pipe(withDefault(1e4));
17764
18558
  const clientGoneGraceMs = yield* Int("OPENCODE_BROWSER_CLIENT_GONE_GRACE_MS").pipe(withDefault(60000));
17765
18559
  const restartRequestId = yield* option(String2("OPENCODE_BROWSER_RESTART_REQUEST_ID"));
17766
- const lifecycleLogPath = path14.join(stateRoot(), "relays", String(port), "lifecycle.jsonl");
17767
- 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));
17768
18562
  function setProtectedUi(tabId, protectedUi) {
17769
18563
  const changed = registry.markRootTargetProtectedUi(tabId, protectedUi);
17770
18564
  if (!changed)
@@ -17813,25 +18607,50 @@ var makeRelay = fnUntraced(function* (options = {}) {
17813
18607
  const session = sessionId && sessions.sessions.get(sessionId);
17814
18608
  if (session) {
17815
18609
  const link = handshake.resolveSessionBrowser(undefined, session);
17816
- return "error" in link ? fail5(new Error(link.error)) : succeed6(link);
18610
+ return "error" in link ? fail6(new Error(link.error)) : succeed6(link);
17817
18611
  }
17818
18612
  const existing = sessionId ? registry.listRootTargets().find((target) => target.opencodeBrowserSessionId === sessionId && target.owner === "relay") : undefined;
17819
18613
  const link = (existing && browsers.browserTab(existing.tabId)?.link) ?? browsers.defaultLink();
17820
- 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"));
17821
18615
  });
17822
18616
  const createAndAttachTab = fnUntraced(function* (createOptions) {
17823
18617
  const link = yield* sessionBrowser(createOptions.opencodeBrowserSessionId);
17824
- 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);
17825
18619
  const tabId = getNumber2(result, "tabId");
17826
18620
  if (!tabId)
17827
- 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"));
17828
18622
  announceTab(tabId);
17829
- return yield* rootLifecycle.attach({
18623
+ const target = yield* rootLifecycle.attach({
17830
18624
  tabId,
17831
18625
  owner: "relay",
17832
18626
  ...createOptions.opencodeBrowserSessionId ? { opencodeBrowserSessionId: createOptions.opencodeBrowserSessionId } : {},
17833
18627
  ...createOptions.autoAttachParams ? { autoAttachParams: createOptions.autoAttachParams } : {}
17834
- });
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;
17835
18654
  });
17836
18655
  const closeTargetByTargetId = fnUntraced(function* (targetId) {
17837
18656
  const target = registry.targetsByTargetId.get(targetId);
@@ -17858,7 +18677,8 @@ var makeRelay = fnUntraced(function* (options = {}) {
17858
18677
  rootLifecycle.invalidate(tabId);
17859
18678
  if (detachOptions.updateExtension !== false) {
17860
18679
  sendExtensionBestEffort({ method: "pageStatus.clear", params: { tabId } });
17861
- presentation.scheduleTabGrouping(tabId, "tabs.ungroup");
18680
+ if (detachOptions.releasedByUser !== true || registry.tabTargets.get(tabId)?.owner !== "relay")
18681
+ presentation.scheduleTabGrouping(tabId, "tabs.ungroup");
17862
18682
  sendExtensionBestEffort({ method: "action.setAttached", params: { tabId, attached: false } });
17863
18683
  recordingRelay.abortRecordingForTab({ tabId, reason: "Tab detached" }).catch((error) => {
17864
18684
  console.error("Failed to abort recording for detached tab", error);
@@ -17871,7 +18691,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17871
18691
  if (detached) {
17872
18692
  presentation.cancelTargetHandoffs(detached.target, "target-detached");
17873
18693
  if (!detachOptions.preserveSessionTarget)
17874
- sessions.markTargetDetached(detached.target.targetInfo.targetId);
18694
+ sessions.markTargetDetached(detached.target.targetInfo.targetId, { releasedByUser: detachOptions.releasedByUser === true });
17875
18695
  contextDebugLog?.(`target-detached kind=root ${targetDiagnosticIdentity(registry, detached.target)}`);
17876
18696
  }
17877
18697
  cdpClients.detachTab(tabId, { destroyed: true });
@@ -17948,6 +18768,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
17948
18768
  refreshPageStatus: presentation.refreshPageStatus,
17949
18769
  refreshTabGrouping: presentation.refreshTabGrouping,
17950
18770
  handleToolbarClick: presentation.handleToolbarClick,
18771
+ handleDebuggingBarCancel: presentation.handleDebuggingBarCancel,
17951
18772
  cancelTargetHandoffs: presentation.cancelTargetHandoffs,
17952
18773
  detachTargetState,
17953
18774
  detachChildTargetState,
@@ -18041,7 +18862,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
18041
18862
  yield* catch_(listenHttpServer2({ server: httpServer, host: listenHost, port }), (error) => {
18042
18863
  return gen(function* () {
18043
18864
  yield* cleanup();
18044
- return yield* fail5(error);
18865
+ return yield* fail6(error);
18045
18866
  });
18046
18867
  });
18047
18868
  yield* sync2(() => pruneStaleExecuteFilesDirectories());
@@ -18061,7 +18882,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
18061
18882
  },
18062
18883
  catch: (cause) => cause instanceof Error ? cause : new Error("Load browse session catalog", { cause })
18063
18884
  });
18064
- yield* try_({
18885
+ yield* try_2({
18065
18886
  try: () => sessions.restore(restoredSessions),
18066
18887
  catch: (cause) => cause instanceof Error ? cause : new Error("Restore browse sessions", { cause })
18067
18888
  });
@@ -18099,7 +18920,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
18099
18920
  relayLog("relay.ready", { url: endpointUrl, version: opencodeBrowserVersion2, build: opencodeBrowserBuildId2, pid: process.pid, managed });
18100
18921
  }), (error) => gen(function* () {
18101
18922
  yield* cleanup();
18102
- return yield* fail5(error);
18923
+ return yield* fail6(error);
18103
18924
  }));
18104
18925
  return {
18105
18926
  url: endpointUrl,