@bigduu/bamboo-agent 0.0.0-stage → 2026.11.50

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.
@@ -0,0 +1,4334 @@
1
+ #!/usr/bin/env node
2
+ // BAMBOO_BROWSER_STORAGE_INSPECTION_V1
3
+ // BAMBOO_BROWSER_LAUNCH_ADMISSION_V1
4
+ // BAMBOO_BROWSER_EPHEMERAL_CLEAN_V1
5
+ // One host owns the account browser; chats own pages and optional clean contexts.
6
+ // Bamboo is the only client: newline-delimited JSON over stdio never exposes a CDP port.
7
+ // Load Playwright only inside main, after installing native child tracking.
8
+ const { createHash, randomBytes } = require('node:crypto');
9
+ const { constants: fsConstants } = require('node:fs');
10
+ const fs = require('node:fs/promises');
11
+ const os = require('node:os');
12
+ const path = require('node:path');
13
+ const readline = require('node:readline');
14
+ const assert = require('node:assert/strict');
15
+ const nativeFs = require('node:fs');
16
+ const { isDeepStrictEqual } = require('node:util');
17
+ const { execFileSync } = require('node:child_process');
18
+
19
+ // Shared by the production host and the read-only inspection CLI. No method
20
+ // here creates, mounts, detaches or deletes a backing image.
21
+ const IMAGE_BYTES = 536_870_912;
22
+ const QUOTA_BYTES = 402_653_184;
23
+ const ACCOUNT_KEY = createHash('sha256')
24
+ .update('bamboo-browser-shared-account-v1\0').digest('hex');
25
+
26
+ function absolute(value) {
27
+ assert.ok(typeof value === 'string' && value.length > 1 && !value.includes('\0') &&
28
+ path.posix.isAbsolute(value) && path.posix.normalize(value) === value && !value.endsWith('/'),
29
+ 'Expected a canonical absolute path');
30
+ return value;
31
+ }
32
+
33
+ function macSharedStoragePlan(dataRoot) {
34
+ absolute(dataRoot);
35
+ const root = path.posix.join(dataRoot, 'browser-storage-v1');
36
+ const image = path.posix.join(root, 'account.dmg');
37
+ const mount = path.posix.join(root, 'mounted');
38
+ const volumeName = `BambooBrowser_${createHash('sha256').update(dataRoot).digest('hex').slice(0, 12)}`;
39
+ const paths = {
40
+ profile: path.posix.join(mount, 'profiles', ACCOUNT_KEY),
41
+ home: path.posix.join(mount, 'home'),
42
+ cache: path.posix.join(mount, 'cache'),
43
+ config: path.posix.join(mount, 'config'),
44
+ data: path.posix.join(mount, 'data'),
45
+ temporary: path.posix.join(mount, 'tmp'),
46
+ downloads: path.posix.join(mount, 'downloads'),
47
+ };
48
+ return {
49
+ kind: 'mac_shared_browser_storage_plan_v1', dataRoot, root, image, mount,
50
+ imageBytes: IMAGE_BYTES, quotaBytes: QUOTA_BYTES, accountKey: ACCOUNT_KEY, paths,
51
+ // Preview only. Creation/mounting requires a separate concrete grant and
52
+ // an adapter that checks exclusive ownership and actual OS readback.
53
+ proposedCommands: [
54
+ { executable: '/usr/bin/hdiutil', arguments: ['create', '-size', '512m',
55
+ '-type', 'UDIF', '-fs', 'APFS', '-fsargs', `-q ${QUOTA_BYTES}`,
56
+ '-volname', volumeName, image] },
57
+ { executable: '/usr/bin/hdiutil', arguments: ['attach', '-plist', '-nobrowse',
58
+ '-mountpoint', mount, image] },
59
+ ],
60
+ launchPaths: {
61
+ userDataDir: paths.profile, downloadsPath: paths.downloads,
62
+ environment: { HOME: paths.home, XDG_CACHE_HOME: paths.cache,
63
+ XDG_CONFIG_HOME: paths.config, XDG_DATA_HOME: paths.data,
64
+ TMPDIR: paths.temporary, TEMP: paths.temporary, TMP: paths.temporary,
65
+ BAMBOO_BROWSER_PROFILE_DIR: paths.profile,
66
+ BAMBOO_BROWSER_DOWNLOAD_ROOT: paths.downloads },
67
+ },
68
+ };
69
+ }
70
+
71
+ function keys(value, expected) {
72
+ assert.ok(value && typeof value === 'object' && !Array.isArray(value));
73
+ assert.deepEqual(Object.keys(value).sort(), [...expected].sort());
74
+ }
75
+
76
+ function privateDirectory(value, expectedPath, device, owner) {
77
+ keys(value, ['path', 'realPath', 'directory', 'symlink', 'device', 'uid', 'mode']);
78
+ assert.equal(value.path, expectedPath);
79
+ assert.equal(value.realPath, expectedPath);
80
+ assert.equal(value.directory, true);
81
+ assert.equal(value.symlink, false);
82
+ assert.equal(value.device, device);
83
+ assert.equal(value.uid, owner);
84
+ assert.ok(Number.isSafeInteger(value.mode) && value.mode >= 0 && value.mode <= 0xffff &&
85
+ (value.mode & 0o777) === 0o700, 'Storage directories must be private');
86
+ }
87
+
88
+ // An OS adapter must collect these observations itself, with its stable lease
89
+ // held, binding hdiutil backing identity to diskutil volume/quota and opened
90
+ // path descriptors. Caller JSON, an old receipt or a mount path alone is not
91
+ // evidence. Passing this structural check never authorizes launch or detach.
92
+ function validateMacStorageObservation(plan, value) {
93
+ return validateMacStorageIdentity(plan, value, false);
94
+ }
95
+
96
+ // Reset may reclaim a full volume, but uses every other backing/path check.
97
+ // This separate entry point cannot weaken the launch admission predicate.
98
+ function validateMacStorageResetObservation(plan, value) {
99
+ return validateMacStorageIdentity(plan, value, true);
100
+ }
101
+
102
+ // A freshly formatted volume has not yet acquired its private role folders.
103
+ // This read-only result permits native preparation checks, never launch.
104
+ function validateMacStoragePreparationObservation(plan, value) {
105
+ return validateMacStorageIdentity(plan, value, false, true);
106
+ }
107
+
108
+ function validateMacStorageIdentity(plan, value, resetting, preparing = false) {
109
+ assert.ok(isDeepStrictEqual(plan, macSharedStoragePlan(plan.dataRoot)), 'Storage plan changed');
110
+ keys(value, ['ownerUid', 'image', 'attachment', 'volume', 'mount', 'paths']);
111
+ assert.ok(Number.isSafeInteger(value.ownerUid) && value.ownerUid >= 0);
112
+ const image = value.image;
113
+ keys(image, ['path', 'realPath', 'regular', 'symlink', 'uid', 'mode', 'device',
114
+ 'sizeBytes', 'virtualBytes', 'format', 'segments']);
115
+ assert.equal(image.path, plan.image);
116
+ assert.equal(image.realPath, plan.image);
117
+ assert.equal(image.regular, true);
118
+ assert.equal(image.symlink, false);
119
+ assert.equal(image.uid, value.ownerUid);
120
+ assert.ok(Number.isSafeInteger(image.mode) && image.mode >= 0 && image.mode <= 0xffff);
121
+ assert.equal(image.mode & 0o777, 0o600);
122
+ assert.equal(image.sizeBytes, IMAGE_BYTES);
123
+ assert.equal(image.virtualBytes, IMAGE_BYTES);
124
+ assert.equal(image.format, 'UDRW');
125
+ assert.deepEqual(image.segments, [plan.image]);
126
+ const volume = value.volume;
127
+ keys(volume, ['uuid', 'deviceIdentifier', 'quotaBytes', 'usedBytes', 'filesystem', 'writable']);
128
+ assert.match(volume.uuid, /^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/i);
129
+ assert.match(volume.deviceIdentifier, /^disk[0-9]+s[0-9]+$/);
130
+ assert.equal(volume.quotaBytes, QUOTA_BYTES);
131
+ assert.ok(Number.isSafeInteger(volume.usedBytes) && volume.usedBytes >= 0 &&
132
+ (resetting || preparing ? volume.usedBytes <= IMAGE_BYTES : volume.usedBytes < QUOTA_BYTES),
133
+ 'Full or unconfirmed storage refuses admission');
134
+ assert.equal(volume.filesystem, 'apfs');
135
+ assert.equal(volume.writable, true);
136
+ keys(value.attachment, ['imagePath', 'volumeDevice', 'volumeUuid', 'mountPoint']);
137
+ assert.equal(value.attachment.imagePath, plan.image);
138
+ assert.equal(value.attachment.volumeDevice, volume.deviceIdentifier);
139
+ assert.equal(value.attachment.volumeUuid, volume.uuid);
140
+ assert.equal(value.attachment.mountPoint, plan.mount);
141
+ const mount = value.mount;
142
+ assert.ok(Number.isSafeInteger(mount.device) && mount.device > 0);
143
+ assert.ok(Number.isSafeInteger(image.device) && image.device > 0);
144
+ assert.notEqual(mount.device, image.device, 'An ordinary folder is not a mounted image');
145
+ if (preparing) {
146
+ keys(mount, ['path', 'realPath', 'directory', 'symlink', 'device', 'uid', 'mode']);
147
+ assert.equal(mount.path, plan.mount); assert.equal(mount.realPath, plan.mount);
148
+ assert.equal(mount.directory, true); assert.equal(mount.symlink, false);
149
+ assert.equal(mount.uid, value.ownerUid);
150
+ assert.ok(Number.isSafeInteger(mount.mode) && mount.mode >= 0 && mount.mode <= 0xffff &&
151
+ [0o700, 0o755].includes(mount.mode & 0o777));
152
+ } else privateDirectory(mount, plan.mount, mount.device, value.ownerUid);
153
+ keys(value.paths, Object.keys(plan.paths));
154
+ for (const [role, target] of Object.entries(plan.paths)) {
155
+ if (!(preparing && value.paths[role] === null)) {
156
+ privateDirectory(value.paths[role], target, mount.device, value.ownerUid);
157
+ }
158
+ }
159
+ return { kind: preparing ? 'validated_mac_storage_preparation_observation_v1' :
160
+ resetting ? 'validated_mac_storage_reset_observation_v1' :
161
+ 'validated_mac_storage_observation_v1', image: plan.image,
162
+ volumeUuid: volume.uuid, imageBytes: IMAGE_BYTES, quotaBytes: QUOTA_BYTES,
163
+ launchAuthorized: false, writerExitProven: false, detachAuthorized: false };
164
+ }
165
+
166
+ // These are the only OS subprocesses used by inspection. Creation, attachment,
167
+ // detachment, quota mutation and privilege escalation are intentionally absent.
168
+ function readMacPlist(executable, arguments_) {
169
+ const environment = { PATH: '/usr/bin:/bin:/usr/sbin:/sbin', LC_ALL: 'C' };
170
+ const bytes = execFileSync(executable, arguments_, { timeout: 10_000,
171
+ maxBuffer: 4 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'], env: environment });
172
+ const json = execFileSync('/usr/bin/plutil', ['-convert', 'json', '-o', '-', '-'], {
173
+ input: bytes, encoding: 'utf8', timeout: 10_000, maxBuffer: 4 * 1024 * 1024,
174
+ stdio: ['pipe', 'pipe', 'pipe'], env: environment,
175
+ });
176
+ return JSON.parse(json);
177
+ }
178
+
179
+ function inspectMacSharedStorage(plan, readers = {}) {
180
+ return inspectMacStorageIdentity(plan, readers, false);
181
+ }
182
+
183
+ function inspectMacStorageForReset(plan, readers = {}) {
184
+ return inspectMacStorageIdentity(plan, readers, true);
185
+ }
186
+
187
+ function inspectMacStorageForPreparation(plan, readers = {}) {
188
+ return inspectMacStorageIdentity(plan, readers, false, true);
189
+ }
190
+
191
+ // Before a reattach, bind the registered inode to one non-sparse backing and
192
+ // reject an attachment anywhere else. No create/attach or quota mutation here.
193
+ function inspectMacStorageBacking(plan, readers = {}) {
194
+ assert.ok(isDeepStrictEqual(plan, macSharedStoragePlan(plan.dataRoot)), 'Storage plan changed');
195
+ const filesystem = readers.filesystem || nativeFs;
196
+ const read = readers.readPlist || readMacPlist;
197
+ const uid = readers.uid ?? process.getuid?.();
198
+ const stat = filesystem.lstatSync(plan.image);
199
+ assert.equal(filesystem.realpathSync(plan.dataRoot), plan.dataRoot);
200
+ assert.equal(filesystem.realpathSync(plan.image), plan.image);
201
+ assert.ok(stat.isFile() && !stat.isSymbolicLink());
202
+ assert.equal(stat.uid, uid); assert.equal(stat.mode & 0o777, 0o600);
203
+ assert.equal(stat.size, IMAGE_BYTES); assert.equal(stat.nlink, 1);
204
+ assert.ok(Number.isSafeInteger(stat.ino) && stat.ino > 0);
205
+ const info = read('/usr/bin/hdiutil', ['imageinfo', '-plist', plan.image]);
206
+ assert.equal(info.Format, 'UDRW'); assert.deepEqual(info.Segments, [plan.image]);
207
+ assert.equal(info['Size Information']?.['Total Bytes'], IMAGE_BYTES);
208
+ const images = read('/usr/bin/hdiutil', ['info', '-plist']).images;
209
+ assert.ok(Array.isArray(images));
210
+ const matching = images.filter(item => item['image-path'] === plan.image);
211
+ assert.ok(matching.length <= 1, 'Duplicate image attachments');
212
+ if (matching.length) {
213
+ const mounted = matching[0]['system-entities']?.filter(item => item['mount-point']);
214
+ assert.equal(mounted?.length, 1, 'Image has no unique mounted volume');
215
+ assert.equal(mounted[0]['mount-point'], plan.mount);
216
+ assert.match(mounted[0]['dev-entry'], /^\/dev\/disk[0-9]+s[0-9]+$/);
217
+ }
218
+ return { kind: 'validated_mac_storage_backing_observation_v1', imageBytes: IMAGE_BYTES,
219
+ imageInode: stat.ino, imageDevice: stat.dev, attached: matching.length === 1 };
220
+ }
221
+
222
+ function inspectMacStorageIdentity(plan, readers, resetting, preparing = false) {
223
+ assert.ok(isDeepStrictEqual(plan, macSharedStoragePlan(plan.dataRoot)), 'Storage plan changed');
224
+ const filesystem = readers.filesystem || nativeFs;
225
+ const read = readers.readPlist || readMacPlist;
226
+ const uid = readers.uid ?? process.getuid?.();
227
+ assert.ok(Number.isSafeInteger(uid) && uid >= 0, 'Native owner identity unavailable');
228
+ assert.equal(filesystem.realpathSync(plan.dataRoot), plan.dataRoot);
229
+ const stat = filesystem.lstatSync(plan.image);
230
+ const image = { path: plan.image, realPath: filesystem.realpathSync(plan.image),
231
+ regular: stat.isFile(), symlink: stat.isSymbolicLink(), uid: stat.uid,
232
+ mode: stat.mode, device: stat.dev, sizeBytes: stat.size };
233
+ // Fail before subprocesses when the known owned backing is absent or unsafe.
234
+ assert.equal(image.realPath, plan.image);
235
+ assert.equal(image.regular, true);
236
+ assert.equal(image.symlink, false);
237
+ assert.equal(image.uid, uid);
238
+ assert.equal(image.sizeBytes, IMAGE_BYTES);
239
+ function directory(target) {
240
+ const metadata = filesystem.lstatSync(target);
241
+ return { path: target, realPath: filesystem.realpathSync(target),
242
+ directory: metadata.isDirectory(), symlink: metadata.isSymbolicLink(),
243
+ device: metadata.dev, uid: metadata.uid, mode: metadata.mode };
244
+ }
245
+ const mount = directory(plan.mount);
246
+ const paths = Object.fromEntries(Object.entries(plan.paths).map(([role, target]) => {
247
+ try { return [role, directory(target)]; }
248
+ catch (error) {
249
+ if (preparing && error.code === 'ENOENT') return [role, null];
250
+ throw error;
251
+ }
252
+ }));
253
+ const imageInfo = read('/usr/bin/hdiutil', ['imageinfo', '-plist', plan.image]);
254
+ image.virtualBytes = imageInfo['Size Information']?.['Total Bytes'];
255
+ image.format = imageInfo.Format;
256
+ image.segments = imageInfo.Segments;
257
+ const info = read('/usr/sbin/diskutil', ['info', '-plist', plan.mount]);
258
+ assert.equal(info.MountPoint, plan.mount);
259
+ assert.equal(info.APFSSnapshot, false);
260
+ const apfs = read('/usr/sbin/diskutil', ['apfs', 'list', '-plist']);
261
+ const containers = apfs.Containers?.filter(item =>
262
+ item.ContainerReference === info.APFSContainerReference);
263
+ assert.equal(containers?.length, 1, 'Ambiguous or missing APFS container');
264
+ const volumes = containers[0].Volumes?.filter(item => item.DeviceIdentifier === info.DeviceIdentifier);
265
+ assert.equal(containers[0].Volumes?.length, 1, 'Expected one bounded APFS volume');
266
+ assert.equal(volumes?.length, 1, 'Ambiguous or missing APFS volume');
267
+ const nativeVolume = volumes[0];
268
+ assert.equal(nativeVolume.APFSVolumeUUID, info.VolumeUUID);
269
+ const images = read('/usr/bin/hdiutil', ['info', '-plist']).images
270
+ ?.filter(item => item['image-path'] === plan.image);
271
+ assert.equal(images?.length, 1, 'Backing image not attached exactly once');
272
+ const entities = images[0]['system-entities']?.filter(item =>
273
+ item['dev-entry'] === `/dev/${info.DeviceIdentifier}` && item['mount-point'] === plan.mount);
274
+ assert.equal(entities?.length, 1, 'Mount is not owned by the expected backing image');
275
+ const observation = { ownerUid: uid, image, mount, paths,
276
+ volume: { uuid: nativeVolume.APFSVolumeUUID, deviceIdentifier: nativeVolume.DeviceIdentifier,
277
+ quotaBytes: nativeVolume.CapacityQuota, usedBytes: nativeVolume.CapacityInUse,
278
+ filesystem: info.FilesystemType, writable: info.WritableVolume },
279
+ attachment: { imagePath: images[0]['image-path'], volumeDevice: info.DeviceIdentifier,
280
+ volumeUuid: info.VolumeUUID, mountPoint: info.MountPoint },
281
+ };
282
+ return { observation, validation: preparing ? validateMacStoragePreparationObservation(plan, observation) :
283
+ resetting ? validateMacStorageResetObservation(plan, observation) :
284
+ validateMacStorageObservation(plan, observation) };
285
+ }
286
+
287
+
288
+ function storageUnavailable(reason, cause) {
289
+ const error = new Error(reason.replaceAll('_', ' '), { cause });
290
+ error.code = 'browser_storage_unavailable';
291
+ error.reason = reason;
292
+ return error;
293
+ }
294
+
295
+ // Error domains remain distinct. A DOM origin quota is not the native image
296
+ // quota, and Chromium's observed DataError/IOError is not QuotaExceededError.
297
+ // Page-controlled text never becomes evidence of native ENOSPC.
298
+ function storageOperationError(cause, origin) {
299
+ let reason = 'browser_storage_outcome_unconfirmed';
300
+ if (origin === 'native_fs') {
301
+ if (cause?.code === 'ENOSPC' || cause?.code === 'EDQUOT') reason = 'browser_storage_full';
302
+ else if (cause?.code === 'EIO') reason = 'browser_storage_io_unconfirmed';
303
+ } else if (origin === 'chromium_storage') {
304
+ if (cause?.name === 'QuotaExceededError') reason = 'browser_origin_quota_exceeded';
305
+ else if (cause?.name === 'DataError' && cause?.message === 'Failed to write blobs (IOError)') {
306
+ reason = 'browser_storage_io_unconfirmed';
307
+ }
308
+ }
309
+ return storageUnavailable(reason, cause);
310
+ }
311
+
312
+ function ephemeralCleanSettings(environment, readers = {}) {
313
+ const platform = readers.platform || process.platform;
314
+ if (!['linux', 'win32'].includes(platform)) {
315
+ throw storageUnavailable('browser_ephemeral_clean_provider_unsupported');
316
+ }
317
+ try {
318
+ assert.equal(environment.BAMBOO_BROWSER_HOST_PROTOCOL, '2');
319
+ assert.equal(environment.BAMBOO_BROWSER_EPHEMERAL_CLEAN, '1');
320
+ // This is a separate temporary provider, never an escape from a failed
321
+ // account/quota admission or a way to import persistent storage.
322
+ for (const name of Object.keys(environment)) {
323
+ if (name.startsWith('BAMBOO_BROWSER_PROFILE_') || name.startsWith('BAMBOO_BROWSER_STORAGE_') ||
324
+ name === 'BAMBOO_BROWSER_LAUNCH_ATTEMPT') assert.equal(environment[name], undefined);
325
+ }
326
+ const scratch = environment.BAMBOO_BROWSER_DOWNLOAD_ROOT;
327
+ const paths = platform === 'win32' ? path.win32 : path.posix;
328
+ assert.ok(typeof scratch === 'string' && !scratch.includes('\0') &&
329
+ paths.isAbsolute(scratch) && paths.normalize(scratch) === scratch);
330
+ for (const name of ['TMPDIR', 'TEMP', 'TMP']) assert.equal(environment[name], scratch);
331
+ const stat = (readers.filesystem || nativeFs).lstatSync(scratch);
332
+ assert.ok(stat.isDirectory() && !stat.isSymbolicLink());
333
+ if (platform !== 'win32') {
334
+ assert.equal(stat.uid, readers.uid ?? process.getuid?.());
335
+ assert.equal(stat.mode & 0o777, 0o700);
336
+ }
337
+ return { cleanOnly: true, scratch, profile: null };
338
+ } catch (cause) {
339
+ throw storageUnavailable('browser_ephemeral_clean_configuration_invalid', cause);
340
+ }
341
+ }
342
+
343
+ function productionStorageSettings(environment = process.env, readers = {}, prelaunch = false) {
344
+ if (environment.BAMBOO_BROWSER_EPHEMERAL_CLEAN !== undefined) {
345
+ return ephemeralCleanSettings(environment, readers);
346
+ }
347
+ if (environment.BAMBOO_BROWSER_HOST_PROTOCOL !== '2' &&
348
+ !environment.BAMBOO_BROWSER_STORAGE_DATA_ROOT) return null;
349
+ if ((readers.platform || process.platform) !== 'darwin') {
350
+ throw storageUnavailable('browser_storage_provider_unsupported');
351
+ }
352
+ try {
353
+ const plan = macSharedStoragePlan(environment.BAMBOO_BROWSER_STORAGE_DATA_ROOT);
354
+ const filesystem = readers.filesystem || nativeFs;
355
+ const owner = readers.uid ?? process.getuid?.();
356
+ const control = environment.BAMBOO_BROWSER_PROFILE_CONTROL_DIR;
357
+ absolute(control);
358
+ assert.equal(path.basename(control), ACCOUNT_KEY);
359
+ assert.equal(path.dirname(path.dirname(control)), plan.dataRoot);
360
+ assert.notEqual(path.dirname(control), plan.root);
361
+ function privatePath(target, device) {
362
+ absolute(target);
363
+ const stat = filesystem.lstatSync(target);
364
+ assert.equal(filesystem.realpathSync(target), target);
365
+ assert.ok(stat.isDirectory() && !stat.isSymbolicLink());
366
+ assert.equal(stat.uid, owner);
367
+ assert.equal(stat.mode & 0o777, 0o700);
368
+ if (device !== undefined) assert.equal(stat.dev, device);
369
+ return stat;
370
+ }
371
+ const controlStat = privatePath(control);
372
+ // Only metadata names are inspected. Never copy, parse or remove an old
373
+ // cookie/database; its presence requires a separately approved migration.
374
+ const entries = filesystem.readdirSync(control);
375
+ if (entries.some(name => name !== '.bamboo-profile.lock' &&
376
+ (prelaunch || name !== '.bamboo-profile-launch-active-v1'))) {
377
+ throw storageUnavailable('browser_storage_migration_required');
378
+ }
379
+ // Correlate this owned launch with the native durable fence. This UUID is
380
+ // not authentication or proof of all-writer exit. A fresh owner must never
381
+ // adopt a previous launch simply because its process-local locks vanished.
382
+ if (!prelaunch) {
383
+ let descriptor;
384
+ try {
385
+ const generation = environment.BAMBOO_BROWSER_STORAGE_GENERATION;
386
+ assert.match(generation, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
387
+ descriptor = filesystem.openSync(path.join(control, '.bamboo-profile-launch-active-v1'),
388
+ fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
389
+ const metadata = filesystem.fstatSync(descriptor);
390
+ assert.ok(metadata.isFile() && metadata.uid === owner &&
391
+ (metadata.mode & 0o777) === 0o600 && metadata.size <= 128);
392
+ const bytes = Buffer.alloc(129);
393
+ const length = filesystem.readSync(descriptor, bytes, 0, bytes.length, 0);
394
+ assert.equal(bytes.subarray(0, length).toString('utf8'), `BAMBOO_BROWSER_LAUNCH_V1\n${generation}\n`);
395
+ } catch (error) {
396
+ throw storageUnavailable('browser_storage_launch_fence_invalid', error);
397
+ } finally {
398
+ if (descriptor !== undefined) filesystem.closeSync(descriptor);
399
+ }
400
+ }
401
+ assert.equal(environment.BAMBOO_BROWSER_PROFILE_DIR, plan.paths.profile);
402
+ for (const [name, role] of Object.entries({ HOME: 'home', XDG_CACHE_HOME: 'cache',
403
+ XDG_CONFIG_HOME: 'config', XDG_DATA_HOME: 'data' })) {
404
+ assert.equal(environment[name], plan.paths[role]);
405
+ }
406
+ const scratch = environment.TMPDIR;
407
+ absolute(scratch);
408
+ assert.equal(path.dirname(scratch), plan.paths.temporary);
409
+ for (const name of ['TEMP', 'TMP', 'BAMBOO_BROWSER_DOWNLOAD_ROOT']) {
410
+ assert.equal(environment[name], scratch);
411
+ }
412
+ const inspected = (readers.inspect || inspectMacSharedStorage)(plan, readers);
413
+ if (environment.BAMBOO_BROWSER_STORAGE_VOLUME_UUID !== undefined) {
414
+ assert.equal(inspected.observation.volume.uuid.toLowerCase(),
415
+ environment.BAMBOO_BROWSER_STORAGE_VOLUME_UUID.toLowerCase());
416
+ }
417
+ const device = inspected.observation.mount.device;
418
+ assert.notEqual(controlStat.dev, device, 'Control fences must remain outside full storage');
419
+ privatePath(scratch, device);
420
+ return { plan, profile: plan.paths.profile, scratch, control };
421
+ } catch (error) {
422
+ if (error.code === 'browser_storage_unavailable') throw error;
423
+ throw storageUnavailable('browser_storage_observation_failed', error);
424
+ }
425
+ }
426
+
427
+ // This is a lifecycle permit from the owned native parent, not an HTTP/model
428
+ // authorization proof. Preflight is read-only; no native roots or profile
429
+ // writers may be constructed before the parent's durable-fence grant.
430
+ async function prepareNativeLaunch(environment = process.env, input = process.stdin, output = process.stdout) {
431
+ if (environment.BAMBOO_BROWSER_EPHEMERAL_CLEAN !== undefined) {
432
+ productionStorageSettings(environment, {}, true);
433
+ return null;
434
+ }
435
+ if (environment.BAMBOO_BROWSER_HOST_PROTOCOL !== '2' &&
436
+ !environment.BAMBOO_BROWSER_STORAGE_DATA_ROOT) return null;
437
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
438
+ const attempt = environment.BAMBOO_BROWSER_LAUNCH_ATTEMPT;
439
+ if (environment.BAMBOO_BROWSER_HOST_PROTOCOL !== '2' || !uuid.test(attempt || '')) {
440
+ throw Object.assign(new Error('browser launch admission required'), { code: 'browser_launch_admission_required' });
441
+ }
442
+ productionStorageSettings(environment, {}, true);
443
+ const prefix = 'BAMBOO_BROWSER_LAUNCH_V1 ';
444
+ const lines = readline.createInterface({ input, crlfDelay: Infinity });
445
+ // Keep this SAME iterator through normal RPC, including a first request
446
+ // delivered in the same pipe chunk as the grant. Never discard prefetched data.
447
+ const requests = lines[Symbol.asyncIterator]();
448
+ let rejectOversize;
449
+ const oversized = new Promise((_, reject) => { rejectOversize = reject; });
450
+ let frameBytes = 0; let firstLineSeen = false;
451
+ const limit = chunk => {
452
+ if (firstLineSeen) return;
453
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
454
+ const end = bytes.indexOf(10);
455
+ frameBytes += end < 0 ? bytes.length : end + 1;
456
+ firstLineSeen = end >= 0;
457
+ if (frameBytes > 16_384) {
458
+ lines.close(); input.pause();
459
+ rejectOversize(new Error('browser launch frame too large'));
460
+ }
461
+ };
462
+ input.on('data', limit);
463
+ try {
464
+ output.write(prefix + JSON.stringify({ kind: 'bamboo_browser_launch_ready', version: 1,
465
+ attempt_id: attempt }) + '\n');
466
+ const first = await Promise.race([requests.next(), oversized]);
467
+ assert.ok(!first.done && Buffer.byteLength(first.value) <= 16_384);
468
+ assert.ok(first.value.startsWith(prefix));
469
+ const grant = JSON.parse(first.value.slice(prefix.length));
470
+ assert.equal(first.value, prefix + JSON.stringify(grant), 'Noncanonical/duplicate grant fields');
471
+ assert.deepEqual(Object.keys(grant).sort(), ['attempt_id', 'kind', 'launch_generation', 'version']);
472
+ assert.equal(grant.kind, 'bamboo_browser_launch_grant');
473
+ assert.equal(grant.version, 1);
474
+ assert.equal(grant.attempt_id, attempt);
475
+ assert.match(grant.launch_generation, uuid);
476
+ return { lines, requests,
477
+ environment: { ...environment, BAMBOO_BROWSER_STORAGE_GENERATION: grant.launch_generation } };
478
+ } catch (cause) {
479
+ lines.close(); input.pause();
480
+ throw Object.assign(new Error('browser launch admission invalid', { cause }), {
481
+ code: 'browser_launch_admission_invalid',
482
+ });
483
+ } finally {
484
+ input.removeListener('data', limit);
485
+ }
486
+ }
487
+
488
+ // Capture actual ChildProcess handles before pinned Playwright loads its spawn
489
+ // module. A JS Browser.close() promise or Node exit does not wait those handles.
490
+ // This proves only the captured roots; arbitrary detached descendants remain a
491
+ // separate native containment requirement, never inferred from a PID or PGID.
492
+ function verifyOwnedHostGroup(read = execFileSync, currentPid = process.pid) {
493
+ try {
494
+ assert.ok(Number.isSafeInteger(currentPid) && currentPid > 0);
495
+ const group = read('/bin/ps', ['-o', 'pgid=', '-p', String(currentPid)], {
496
+ encoding: 'utf8', timeout: 1000, maxBuffer: 1024,
497
+ stdio: ['ignore', 'pipe', 'pipe'], env: { PATH: '/usr/bin:/bin', LC_ALL: 'C' },
498
+ });
499
+ assert.equal(String(group).trim(), String(currentPid));
500
+ return true;
501
+ } catch (cause) {
502
+ const error = new Error('browser native owner process group unavailable', { cause });
503
+ error.code = 'browser_writer_exit_unconfirmed';
504
+ throw error;
505
+ }
506
+ }
507
+
508
+ function createNativeRootTracker(spawns, expectedProfile, policy = {}) {
509
+ const original = spawns.spawn;
510
+ const roots = [];
511
+ let launched = false;
512
+ function unconfirmed(cause) {
513
+ const error = new Error('browser native writer exit unconfirmed', { cause });
514
+ error.code = 'browser_writer_exit_unconfirmed';
515
+ return error;
516
+ }
517
+ return {
518
+ async launch(operation) {
519
+ if (launched) throw unconfirmed();
520
+ launched = true;
521
+ const capture = function(executable, args, options) {
522
+ const profiles = Array.isArray(args) ? args.filter(arg =>
523
+ typeof arg === 'string' && arg.startsWith('--user-data-dir=')) : [];
524
+ if (!profiles.length) return Reflect.apply(original, spawns, [executable, args, options]);
525
+ const actual = profiles[0].slice('--user-data-dir='.length);
526
+ if (profiles.length !== 1 || roots.length || !path.isAbsolute(actual) ||
527
+ expectedProfile && actual !== expectedProfile) throw unconfirmed();
528
+ // Pinned Playwright normally detaches Chromium into a second group.
529
+ // The production owner has first checked its own dedicated group;
530
+ // inherit it so native deadline cancellation includes this root.
531
+ const nativeOptions = policy.managedGroup ? { ...options, detached: false } : options;
532
+ const child = Reflect.apply(original, spawns, [executable, args, nativeOptions]);
533
+ if (!Number.isSafeInteger(child.pid) || child.pid < 1 || typeof child.once !== 'function') {
534
+ throw unconfirmed();
535
+ }
536
+ const record = { pid: child.pid, child, result: null, stopRequested: false };
537
+ record.closed = new Promise(resolve => {
538
+ child.once('close', (code, signal) => { record.result = { code, signal }; resolve(); });
539
+ });
540
+ roots.push(record);
541
+ return child;
542
+ };
543
+ spawns.spawn = capture;
544
+ let result;
545
+ try { result = await operation(); }
546
+ finally {
547
+ if (spawns.spawn === capture) spawns.spawn = original;
548
+ }
549
+ if (spawns.spawn !== original || roots.length !== 1) throw unconfirmed();
550
+ return result;
551
+ },
552
+ snapshot() {
553
+ return { roots: roots.map(root => ({ pid: root.pid, ...root.result })),
554
+ allDescendantsProven: false };
555
+ },
556
+ stopCapturedRoots() {
557
+ let rootSignalsAttempted = 0;
558
+ for (const root of roots) {
559
+ if (root.result || root.stopRequested) continue;
560
+ root.stopRequested = true;
561
+ rootSignalsAttempted++;
562
+ // Use the owned ChildProcess handle, never process.kill(numericPid).
563
+ // This requests a root stop only; its descendants remain unconfirmed.
564
+ try { root.child.kill('SIGKILL'); } catch { /* retain unknown outcome */ }
565
+ }
566
+ return { rootSignalsAttempted, allDescendantsProven: false };
567
+ },
568
+ async waitClosed() {
569
+ if (roots.length !== 1) throw unconfirmed();
570
+ let timer;
571
+ try {
572
+ await Promise.race([
573
+ Promise.all(roots.map(root => root.closed)),
574
+ new Promise((resolve, reject) => { timer = setTimeout(() => reject(unconfirmed()), 2000); }),
575
+ ]);
576
+ } finally { clearTimeout(timer); }
577
+ if (roots.some(root => !root.result || root.result.code !== 0 || root.result.signal !== null)) {
578
+ throw unconfirmed();
579
+ }
580
+ return this.snapshot();
581
+ },
582
+ };
583
+ }
584
+
585
+ const MAX_SNAPSHOT_CHARS = 80_000;
586
+ const MAX_HTML_CHARS = 100_000;
587
+ const MAX_TABS = 8;
588
+ // Rust retires this host after 30 seconds. Leave time for state() and stdio.
589
+ const POINTER_ACTION_BUDGET_MS = 22_000;
590
+ // Bound returned bytes, not OS disk usage: Chromium may buffer a chunk before
591
+ // its next progress event lets us cancel an oversized transfer.
592
+ const MAX_DOWNLOAD_BYTES = 256 * 1024;
593
+ const DOWNLOAD_ACTION_BUDGET_MS = process.env.NODE_ENV === 'test'
594
+ ? Math.min(20_000, Math.max(100, Number(process.env.BAMBOO_BROWSER_TEST_DOWNLOAD_BUDGET_MS) || 20_000))
595
+ : 20_000;
596
+ const TEST_DOWNLOAD_CLEANUP_DELAY_MS = process.env.NODE_ENV === 'test'
597
+ ? Math.min(5_000, Math.max(0, Number(process.env.BAMBOO_BROWSER_TEST_DOWNLOAD_CLEANUP_DELAY_MS) || 0))
598
+ : 0;
599
+ const TEST_DOWNLOAD_CLICK_DELAY_MS = process.env.NODE_ENV === 'test'
600
+ ? Math.min(1_000, Math.max(0, Number(process.env.BAMBOO_BROWSER_TEST_DOWNLOAD_CLICK_DELAY_MS) || 0))
601
+ : 0;
602
+ const TEST_PRIVATE_PAGE_FAILURE = process.env.NODE_ENV === 'test'
603
+ ? process.env.BAMBOO_BROWSER_TEST_PRIVATE_PAGE_FAILURE : '';
604
+ const TEST_RETIRE_CLOSE_DELAY_MS = process.env.NODE_ENV === 'test'
605
+ ? Math.min(1_000, Math.max(0, Number(process.env.BAMBOO_BROWSER_TEST_RETIRE_CLOSE_DELAY_MS) || 0))
606
+ : 0;
607
+ // The packaged host does not inherit NODE_ENV. Direct host tests can pause
608
+ // observer setup to force a navigation between the first and final epoch checks.
609
+ const TEST_OBSERVER_SETUP_DELAY_MS = process.env.NODE_ENV === 'test'
610
+ ? Math.min(2_000, Math.max(0, Number(process.env.BAMBOO_BROWSER_TEST_OBSERVER_DELAY_MS) || 0))
611
+ : 0;
612
+ const TEST_DIALOG_STATE_DELAY_MS = process.env.NODE_ENV === 'test'
613
+ ? Math.min(2_000, Math.max(0, Number(process.env.BAMBOO_BROWSER_TEST_DIALOG_STATE_DELAY_MS) || 0))
614
+ : 0;
615
+ const TEST_DIALOG_READ_DELAY_MS = process.env.NODE_ENV === 'test'
616
+ ? Math.min(2_000, Math.max(0, Number(process.env.BAMBOO_BROWSER_TEST_DIALOG_READ_DELAY_MS) || 0))
617
+ : 0;
618
+ const TEST_SUPPRESS_SCREENCAST_FRAMES = process.env.NODE_ENV === 'test' &&
619
+ process.env.BAMBOO_BROWSER_TEST_SUPPRESS_SCREENCAST_FRAMES === '1';
620
+ const TEST_STALL_SCREENCAST_STOP = process.env.NODE_ENV === 'test' &&
621
+ process.env.BAMBOO_BROWSER_TEST_STALL_SCREENCAST_STOP === '1';
622
+ const CAPTURE_FIRST_FRAME_WAIT_MS = 750;
623
+ const CAPTURE_RESTART_LIMIT = 3;
624
+ const CAPTURE_FALLBACK_INTERVAL_MS = 1_500;
625
+ const CAPTURE_STILL_TIMEOUT_MS = 3_000;
626
+ const MAX_DIALOG_CHARS = 4_096;
627
+ const DIALOG_TIMEOUT_MS = Number.isInteger(Number(process.env.BAMBOO_BROWSER_DIALOG_TIMEOUT_MS))
628
+ ? Math.max(100, Math.min(300_000, Number(process.env.BAMBOO_BROWSER_DIALOG_TIMEOUT_MS)))
629
+ : 300_000;
630
+ const MAX_EVAL_CODE_BYTES = 8 * 1024;
631
+ const MAX_EVAL_JSON_BYTES = 64 * 1024;
632
+ const EVAL_HELPER_KEY = `__bamboo_eval_${randomBytes(16).toString('hex')}`;
633
+ const SCRIPT_BLOB_KEY = `__bamboo_blob_${randomBytes(16).toString('hex')}`;
634
+ const SCRIPT_BLOB_SECRET = randomBytes(24).toString('hex');
635
+ const DOWNLOAD_LINK_KEY = `__bamboo_link_${randomBytes(16).toString('hex')}`;
636
+ const DOWNLOAD_LINK_SECRET = randomBytes(24).toString('hex');
637
+
638
+ let browser;
639
+ let context; // The account's default persistent context only.
640
+ let closing = false;
641
+ let shuttingDown = false;
642
+ let browserClosed = false;
643
+ let hostClose;
644
+ let hostRuntime;
645
+ let retireAfterReply = false;
646
+ let downloadCdp;
647
+ let downloadContextId;
648
+ let downloadDir;
649
+ let profileDirectory;
650
+ let profileKey;
651
+ let profileCookieState;
652
+ let profileCheckpoint = Promise.resolve();
653
+ let profileFailure;
654
+ let profileTimer;
655
+ let profileInterval;
656
+ let nativeRoots;
657
+ let hostStorageSettings;
658
+
659
+ function profileError() {
660
+ const error = new Error('browser profile persistence unavailable');
661
+ error.code = 'browser_profile_unavailable';
662
+ return error;
663
+ }
664
+
665
+ async function readProfile() {
666
+ const directory = process.env.BAMBOO_BROWSER_PROFILE_DIR;
667
+ if (!directory) return;
668
+ try {
669
+ if (!path.isAbsolute(directory) || !/^[a-f0-9]{64}$/.test(path.basename(directory))) throw profileError();
670
+ const metadata = await fs.lstat(directory);
671
+ if (!metadata.isDirectory() || metadata.isSymbolicLink() ||
672
+ await fs.realpath(directory) !== path.normalize(directory)) throw profileError();
673
+ if (process.platform !== 'win32' &&
674
+ ((metadata.mode & 0o077) !== 0 || metadata.uid !== process.getuid())) throw profileError();
675
+ profileDirectory = directory;
676
+ profileKey = path.basename(directory);
677
+ const file = path.join(directory, '.bamboo-session-cookies-v1.json');
678
+ let bytes;
679
+ try {
680
+ const stat = await fs.lstat(file);
681
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 32 * 1024 * 1024 ||
682
+ (process.platform !== 'win32' && ((stat.mode & 0o077) !== 0 || stat.uid !== process.getuid()))) throw profileError();
683
+ bytes = await fs.readFile(file, 'utf8');
684
+ } catch (error) {
685
+ if (error.code === 'ENOENT') return [];
686
+ throw error;
687
+ }
688
+ const state = JSON.parse(bytes);
689
+ if (!state || Object.keys(state).join(',') !== 'schemaVersion,profileKey,cookies' ||
690
+ state.schemaVersion !== 1 || state.profileKey !== profileKey || !Array.isArray(state.cookies)) throw profileError();
691
+ for (const cookie of state.cookies) {
692
+ if (!cookie || cookie.expires !== -1 ||
693
+ !['name', 'value', 'domain', 'path'].every(key => typeof cookie[key] === 'string') ||
694
+ typeof cookie.httpOnly !== 'boolean' || typeof cookie.secure !== 'boolean' ||
695
+ !['Strict', 'Lax', 'None'].includes(cookie.sameSite)) throw profileError();
696
+ }
697
+ profileCookieState = bytes;
698
+ return state.cookies;
699
+ } catch (error) {
700
+ if (['ENOSPC', 'EDQUOT', 'EIO'].includes(error?.code)) {
701
+ throw storageOperationError(error, 'native_fs');
702
+ }
703
+ throw profileError();
704
+ }
705
+ }
706
+
707
+ // Chromium owns cookies/localStorage/IndexedDB in the private profile. Its
708
+ // headless shell drops session-only cookies on restart, even for a persistent
709
+ // context. Keep only those cookies with the same account profile: recycling
710
+ // the shared runtime must not end its login. Clean contexts never enter this checkpoint.
711
+ function checkpointProfile() {
712
+ clearTimeout(profileTimer);
713
+ profileTimer = undefined;
714
+ if (!profileDirectory || !context || browserClosed) return Promise.resolve();
715
+ if (profileFailure) return Promise.reject(profileFailure);
716
+ profileCheckpoint = profileCheckpoint.then(async () => {
717
+ const cookies = (await context.cookies()).filter(cookie => cookie.expires === -1)
718
+ .sort((a, b) => JSON.stringify([a.domain, a.path, a.name, a.partitionKey || ''])
719
+ .localeCompare(JSON.stringify([b.domain, b.path, b.name, b.partitionKey || ''])));
720
+ const bytes = JSON.stringify({ schemaVersion: 1, profileKey, cookies }) + '\n';
721
+ if (Buffer.byteLength(bytes) > 32 * 1024 * 1024) throw profileError();
722
+ if (bytes === profileCookieState) return;
723
+ const target = path.join(profileDirectory, '.bamboo-session-cookies-v1.json');
724
+ const temporary = `${target}.${randomBytes(12).toString('hex')}.tmp`;
725
+ try {
726
+ const file = await fs.open(temporary, 'wx', 0o600);
727
+ try { await file.writeFile(bytes); await file.sync(); } finally { await file.close(); }
728
+ await fs.rename(temporary, target);
729
+ if (process.platform !== 'win32') {
730
+ // The renamed cookie checkpoint must survive alongside its directory
731
+ // entry before a successful logout reply or in-memory cache advance.
732
+ const directory = await fs.open(profileDirectory,
733
+ fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW);
734
+ try { await directory.sync(); } finally { await directory.close(); }
735
+ }
736
+ profileCookieState = bytes;
737
+ } finally {
738
+ await fs.rm(temporary, { force: true }).catch(() => {});
739
+ }
740
+ }).catch(error => {
741
+ profileFailure = ['ENOSPC', 'EDQUOT', 'EIO'].includes(error?.code)
742
+ ? storageOperationError(error, 'native_fs') : profileError();
743
+ retireAfterReply = true;
744
+ throw profileFailure;
745
+ });
746
+ return profileCheckpoint;
747
+ }
748
+
749
+ function scheduleProfileCheckpoint() {
750
+ if (!profileDirectory || shuttingDown || browserClosed || profileTimer || profileFailure) return;
751
+ profileTimer = setTimeout(() => {
752
+ profileTimer = undefined;
753
+ void checkpointProfile().catch(() => {});
754
+ }, 100);
755
+ profileTimer.unref();
756
+ }
757
+
758
+ function checkUrl(raw) {
759
+ const value = new URL(raw);
760
+ if (value.protocol !== 'http:' && value.protocol !== 'https:') {
761
+ const error = new Error('only http and https pages are supported');
762
+ error.code = 'invalid_url';
763
+ throw error;
764
+ }
765
+ if (value.username || value.password) {
766
+ const error = new Error('URLs with embedded credentials are not supported');
767
+ error.code = 'invalid_url';
768
+ throw error;
769
+ }
770
+ return value.href;
771
+ }
772
+
773
+ function checkPageUrl(raw) {
774
+ return raw === 'about:blank' ? raw : checkUrl(raw);
775
+ }
776
+
777
+ function installEvalHelper(key) {
778
+ const root = globalThis;
779
+ const nativeEval = root.eval;
780
+ const nativeError = Error;
781
+ const arrayCtor = Array;
782
+ const weakSetCtor = WeakSet;
783
+ const isArray = Array.isArray;
784
+ const isFiniteNumber = Number.isFinite;
785
+ const isSafeInteger = Number.isSafeInteger;
786
+ const getPrototypeOf = Object.getPrototypeOf;
787
+ const objectKeys = Object.keys;
788
+ const getDescriptor = Object.getOwnPropertyDescriptor;
789
+ const create = Object.create;
790
+ const define = Object.defineProperty;
791
+ const setPrototypeOf = Object.setPrototypeOf;
792
+ const hasOwn = Object.hasOwn;
793
+ const stringify = JSON.stringify;
794
+ const apply = Reflect.apply;
795
+ const charCodeAt = String.prototype.charCodeAt;
796
+ const seenHas = WeakSet.prototype.has;
797
+ const seenAdd = WeakSet.prototype.add;
798
+ const seenDelete = WeakSet.prototype.delete;
799
+ const plainPrototype = Object.prototype;
800
+ const withinUtf8Bytes = (text, limit) => {
801
+ let bytes = 0;
802
+ for (let index = 0; index < text.length; index++) {
803
+ const unit = apply(charCodeAt, text, [index]);
804
+ if (unit <= 0x7f) bytes++;
805
+ else if (unit <= 0x7ff) bytes += 2;
806
+ else if (unit >= 0xd800 && unit <= 0xdbff && index + 1 < text.length) {
807
+ const next = apply(charCodeAt, text, [index + 1]);
808
+ if (next >= 0xdc00 && next <= 0xdfff) { bytes += 4; index++; }
809
+ else bytes += 3;
810
+ } else bytes += 3;
811
+ if (bytes > limit) return false;
812
+ }
813
+ return true;
814
+ };
815
+
816
+ const execute = async source => {
817
+ const value = await (0, nativeEval)(source);
818
+ const seen = new weakSetCtor();
819
+ let entries = 0;
820
+ let stringUnits = 0;
821
+ const safe = (item, depth) => {
822
+ if (++entries > 256 || depth > 8) throw new nativeError('browser_eval result exceeds depth or entry limit');
823
+ if (item === null || typeof item === 'boolean') return item;
824
+ if (typeof item === 'number' && isFiniteNumber(item)) return item;
825
+ if (typeof item === 'string') {
826
+ stringUnits += item.length;
827
+ if (stringUnits > 65536) throw new nativeError('browser_eval result exceeds string limit');
828
+ return item;
829
+ }
830
+ if (typeof item !== 'object' || apply(seenHas, seen, [item])) {
831
+ throw new nativeError('browser_eval result is not JSON-safe');
832
+ }
833
+ apply(seenAdd, seen, [item]);
834
+ let result;
835
+ if (isArray(item)) {
836
+ const length = item.length;
837
+ if (!isSafeInteger(length) || length < 0 || length > 64) {
838
+ throw new nativeError('browser_eval result exceeds array limit');
839
+ }
840
+ result = new arrayCtor(length);
841
+ for (let index = 0; index < length; index++) {
842
+ const descriptor = getDescriptor(item, index);
843
+ if (!descriptor || !hasOwn(descriptor, 'value')) {
844
+ throw new nativeError('browser_eval result contains an accessor or hole');
845
+ }
846
+ define(result, index, {
847
+ value: safe(descriptor.value, depth + 1),
848
+ enumerable: true, configurable: true, writable: true,
849
+ });
850
+ }
851
+ // A hostile page may add Array.prototype.toJSON after eval. Keep the
852
+ // transfer value free of inherited serialization hooks.
853
+ setPrototypeOf(result, null);
854
+ } else {
855
+ const prototype = getPrototypeOf(item);
856
+ if (prototype !== plainPrototype && prototype !== null) {
857
+ throw new nativeError('browser_eval result must contain only plain objects');
858
+ }
859
+ const keys = objectKeys(item);
860
+ if (keys.length > 64) throw new nativeError('browser_eval result exceeds object entry limit');
861
+ result = create(null);
862
+ for (let index = 0; index < keys.length; index++) {
863
+ const property = keys[index];
864
+ if (property.length > 256) throw new nativeError('browser_eval result key is too long');
865
+ const descriptor = getDescriptor(item, property);
866
+ if (!descriptor || !hasOwn(descriptor, 'value')) {
867
+ throw new nativeError('browser_eval result contains an accessor');
868
+ }
869
+ define(result, property, {
870
+ value: safe(descriptor.value, depth + 1),
871
+ enumerable: true, configurable: true, writable: true,
872
+ });
873
+ }
874
+ }
875
+ apply(seenDelete, seen, [item]);
876
+ return result;
877
+ };
878
+ const safeValue = safe(value, 0);
879
+ const valueJson = stringify(safeValue);
880
+ if (!withinUtf8Bytes(valueJson, 65536)) throw new nativeError('browser_eval result exceeds 64 KiB');
881
+ const response = create(null);
882
+ define(response, 'ok', { value: true, enumerable: true });
883
+ define(response, 'value', { value: safeValue, enumerable: true });
884
+ define(response, 'observed_url', { value: root.location.href, enumerable: true });
885
+ // Playwright's object transfer can use mutable page intrinsics. Return a
886
+ // bounded primitive and parse it with trusted Node intrinsics instead.
887
+ const serialized = stringify(response);
888
+ if (!withinUtf8Bytes(serialized, 75000)) throw new nativeError('browser_eval transfer exceeds limit');
889
+ return serialized;
890
+ };
891
+ const run = async source => {
892
+ try {
893
+ return await execute(source);
894
+ } catch {
895
+ // Never inspect or stringify a thrown page value. Error.message and
896
+ // toString can be hostile getters, and Playwright would transfer an
897
+ // unbounded rejection if this helper let it escape.
898
+ return '{"ok":false}';
899
+ }
900
+ };
901
+ define(root, key, { value: run, enumerable: false, configurable: false, writable: false });
902
+ }
903
+
904
+ // Installed before site scripts to save pristine intrinsics. Only the bounded
905
+ // attempt wraps page methods; a site-installed hook makes the attempt fail.
906
+ // Captured values live in this private closure, behind a host-only secret.
907
+ function installScriptBlobCapture({ key, secret }) {
908
+ const root = globalThis;
909
+ const apply = Reflect.apply;
910
+ const define = Object.defineProperty;
911
+ const getDescriptor = Object.getOwnPropertyDescriptor;
912
+ const createObject = Object.create;
913
+ const json = JSON;
914
+ const stringify = json.stringify;
915
+ const urlClass = URL;
916
+ const anchorClass = HTMLAnchorElement;
917
+ const eventTargetClass = EventTarget;
918
+ const htmlElementClass = HTMLElement;
919
+ const weakMapClass = WeakMap;
920
+ const stringClass = String;
921
+ const byteArrayClass = Uint8Array;
922
+ const isSafeInteger = Number.isSafeInteger;
923
+ const nativeCreate = urlClass.createObjectURL;
924
+ const nativeAnchorClick = anchorClass.prototype.click;
925
+ const nativeBlobSize = getDescriptor(Blob.prototype, 'size').get;
926
+ const nativeBlobArrayBuffer = Blob.prototype.arrayBuffer;
927
+ const nativeEventTarget = getDescriptor(Event.prototype, 'target').get;
928
+ const nativeCurrentEvent = getDescriptor(root, 'event').get;
929
+ const nativePreventDefault = Event.prototype.preventDefault;
930
+ const nativeStopImmediatePropagation = Event.prototype.stopImmediatePropagation;
931
+ const nativeContains = Node.prototype.contains;
932
+ const nativeQuerySelectorAll = root.document.querySelectorAll;
933
+ const nativeClosest = Element.prototype.closest;
934
+ const nativeNodeListLength = getDescriptor(NodeList.prototype, 'length').get;
935
+ const nativeNodeListItem = NodeList.prototype.item;
936
+ const nativeHref = getDescriptor(anchorClass.prototype, 'href').get;
937
+ const nativeGetAttribute = Element.prototype.getAttribute;
938
+ const nativeBtoa = root.btoa;
939
+ const nativeFromCharCode = stringClass.fromCharCode;
940
+ const nativeCodePointAt = stringClass.prototype.codePointAt;
941
+ const typedArrayPrototype = Object.getPrototypeOf(byteArrayClass.prototype);
942
+ const nativeTypedArrayLength = getDescriptor(typedArrayPrototype, 'length').get;
943
+ const nativeTypedArrayByteLength = getDescriptor(typedArrayPrototype, 'byteLength').get;
944
+ const nativeAdd = eventTargetClass.prototype.addEventListener;
945
+ const nativeRemove = eventTargetClass.prototype.removeEventListener;
946
+ const nativeOnclick = getDescriptor(htmlElementClass.prototype, 'onclick');
947
+ const nativeEval = root.eval;
948
+ const nativeDelete = Reflect.deleteProperty;
949
+ const weakGet = WeakMap.prototype.get;
950
+ const weakSet = WeakMap.prototype.set;
951
+ const listeners = new weakMapClass();
952
+ const maxBytes = 256 * 1024;
953
+ let armed = false;
954
+ let selectedElement = null;
955
+ let selectedEvent = null;
956
+ let trustedClicks = 0;
957
+ let created = null;
958
+ let creations = 0;
959
+ let clicked = null;
960
+ let clicks = 0;
961
+ let ambiguous = false;
962
+ let handlerDepth = 0;
963
+ let matched = false;
964
+ let onclickCapture = null;
965
+ const reset = () => {
966
+ armed = false;
967
+ selectedElement = null;
968
+ selectedEvent = null;
969
+ trustedClicks = 0;
970
+ created = null;
971
+ creations = 0;
972
+ clicked = null;
973
+ clicks = 0;
974
+ ambiguous = false;
975
+ handlerDepth = 0;
976
+ matched = false;
977
+ };
978
+ const inSelectedDispatch = () => armed && selectedEvent !== null &&
979
+ apply(nativeCurrentEvent, root, []) === selectedEvent;
980
+ const inSelectedHandler = () => inSelectedDispatch() && handlerDepth > 0;
981
+ // A microtask can run while window.event, eventPhase and currentTarget still
982
+ // identify the trusted click. Only a directly invoked selected-element
983
+ // handler may produce the returned Blob, and any other creation is ambiguous.
984
+ const wrappedAdd = function(type, listener, options) {
985
+ if (type !== 'click' || listener === null ||
986
+ (typeof listener !== 'function' && typeof listener !== 'object') ||
987
+ (typeof this !== 'object' && typeof this !== 'function') || this === null) {
988
+ return apply(nativeAdd, this, [type, listener, options]);
989
+ }
990
+ let byListener = apply(weakGet, listeners, [this]);
991
+ if (!byListener) {
992
+ byListener = new weakMapClass();
993
+ apply(weakSet, listeners, [this, byListener]);
994
+ }
995
+ let wrapper = apply(weakGet, byListener, [listener]);
996
+ if (!wrapper) {
997
+ wrapper = function(event) {
998
+ const direct = armed && this === selectedElement && event === selectedEvent;
999
+ if (direct) handlerDepth++;
1000
+ try {
1001
+ if (typeof listener === 'function') return apply(listener, this, [event]);
1002
+ return apply(listener.handleEvent, listener, [event]);
1003
+ } finally {
1004
+ if (direct) handlerDepth--;
1005
+ }
1006
+ };
1007
+ apply(weakSet, byListener, [listener, wrapper]);
1008
+ }
1009
+ return apply(nativeAdd, this, [type, wrapper, options]);
1010
+ };
1011
+ const wrappedRemove = function(type, listener, options) {
1012
+ const byListener = this !== null && (typeof this === 'object' || typeof this === 'function')
1013
+ ? apply(weakGet, listeners, [this]) : null;
1014
+ const wrapper = byListener && listener !== null &&
1015
+ (typeof listener === 'function' || typeof listener === 'object')
1016
+ ? apply(weakGet, byListener, [listener]) : null;
1017
+ if (type === 'click' && wrapper) apply(nativeRemove, this, [type, wrapper, options]);
1018
+ return apply(nativeRemove, this, [type, listener, options]);
1019
+ };
1020
+ define(eventTargetClass.prototype, 'addEventListener', {
1021
+ value: wrappedAdd, writable: true, configurable: true,
1022
+ });
1023
+ define(eventTargetClass.prototype, 'removeEventListener', {
1024
+ value: wrappedRemove, writable: true, configurable: true,
1025
+ });
1026
+ apply(nativeAdd, root, ['click', event => {
1027
+ if (!armed) return;
1028
+ try {
1029
+ if (!apply(getDescriptor(event, 'isTrusted').get, event, [])) return;
1030
+ const target = apply(nativeEventTarget, event, []);
1031
+ if (target !== selectedElement && !apply(nativeContains, selectedElement, [target])) {
1032
+ ambiguous = true;
1033
+ apply(nativePreventDefault, event, []);
1034
+ apply(nativeStopImmediatePropagation, event, []);
1035
+ return;
1036
+ }
1037
+ trustedClicks++;
1038
+ if (trustedClicks === 1) selectedEvent = event;
1039
+ else ambiguous = true;
1040
+ } catch { ambiguous = true; }
1041
+ }, true]);
1042
+ const captureCreate = function(blob) {
1043
+ const url = apply(nativeCreate, this, [blob]);
1044
+ if (inSelectedDispatch()) {
1045
+ if (!inSelectedHandler()) { ambiguous = true; return url; }
1046
+ creations++;
1047
+ if (creations === 1) {
1048
+ try {
1049
+ created = { blob, url, size: apply(nativeBlobSize, blob, []) };
1050
+ } catch { ambiguous = true; }
1051
+ } else ambiguous = true;
1052
+ }
1053
+ return url;
1054
+ };
1055
+ const captureClick = function(...args) {
1056
+ if (!inSelectedDispatch()) return apply(nativeAnchorClick, this, args);
1057
+ if (!inSelectedHandler()) { ambiguous = true; return undefined; }
1058
+ clicks++;
1059
+ try {
1060
+ const url = apply(nativeHref, this, []);
1061
+ const filename = apply(nativeGetAttribute, this, ['download']);
1062
+ if (clicks === 1 && created && url === created.url && safeFilename(filename)) {
1063
+ clicked = { url, filename };
1064
+ }
1065
+ else ambiguous = true;
1066
+ } catch { ambiguous = true; }
1067
+ // Never let a script click start a native download while it is being
1068
+ // attributed. Unmatched/multiple activations fail closed at finish().
1069
+ return undefined;
1070
+ };
1071
+ const safeFilename = filename => {
1072
+ if (typeof filename !== 'string' || !filename || filename.length > 180 ||
1073
+ filename === '.' || filename === '..') return false;
1074
+ for (let index = 0; index < filename.length; index++) {
1075
+ const codePoint = apply(nativeCodePointAt, filename, [index]);
1076
+ if (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ||
1077
+ codePoint === 0x2f || codePoint === 0x3a || codePoint === 0x5c ||
1078
+ (codePoint >= 0xd800 && codePoint <= 0xdfff)) return false;
1079
+ if (codePoint > 0xffff) index++;
1080
+ }
1081
+ return true;
1082
+ };
1083
+ const captureOnclick = target => {
1084
+ if (getDescriptor(target, 'onclick')) return false;
1085
+ const original = apply(nativeOnclick.get, target, []);
1086
+ if (original === null) return true;
1087
+ if (typeof original !== 'function') return false;
1088
+ const info = { target, original, changed: false, value: original };
1089
+ info.getter = function() {
1090
+ if (this === target) return info.value;
1091
+ return apply(nativeOnclick.get, this, []);
1092
+ };
1093
+ info.setter = function(value) {
1094
+ if (this !== target) return apply(nativeOnclick.set, this, [value]);
1095
+ info.changed = true;
1096
+ info.value = value;
1097
+ ambiguous = true;
1098
+ return apply(nativeOnclick.set, target, [value]);
1099
+ };
1100
+ info.listener = function(event) {
1101
+ if (info.changed || apply(nativeOnclick.get, target, []) !== null) {
1102
+ ambiguous = true;
1103
+ return undefined;
1104
+ }
1105
+ const direct = armed && this === target && event === selectedEvent;
1106
+ if (direct) handlerDepth++;
1107
+ try {
1108
+ const result = apply(original, this, [event]);
1109
+ if (result === false) apply(nativePreventDefault, event, []);
1110
+ return result;
1111
+ } finally {
1112
+ if (direct) handlerDepth--;
1113
+ }
1114
+ };
1115
+ onclickCapture = info;
1116
+ apply(nativeOnclick.set, target, [null]);
1117
+ apply(nativeAdd, target, ['click', info.listener, false]);
1118
+ define(target, 'onclick', {
1119
+ get: info.getter, set: info.setter, enumerable: true, configurable: true,
1120
+ });
1121
+ return true;
1122
+ };
1123
+ const onclickIntact = () => !onclickCapture ||
1124
+ (getDescriptor(onclickCapture.target, 'onclick')?.get === onclickCapture.getter &&
1125
+ getDescriptor(onclickCapture.target, 'onclick')?.set === onclickCapture.setter &&
1126
+ apply(nativeOnclick.get, onclickCapture.target, []) === null &&
1127
+ !onclickCapture.changed);
1128
+ const evalIntact = () => getDescriptor(root, 'eval')?.value === nativeEval;
1129
+ const nativeMethodsIntact = () => root.URL === urlClass && root.HTMLAnchorElement === anchorClass &&
1130
+ root.EventTarget === eventTargetClass && root.HTMLElement === htmlElementClass &&
1131
+ root.WeakMap === weakMapClass &&
1132
+ urlClass.createObjectURL === nativeCreate && anchorClass.prototype.click === nativeAnchorClick &&
1133
+ eventTargetClass.prototype.addEventListener === wrappedAdd &&
1134
+ eventTargetClass.prototype.removeEventListener === wrappedRemove &&
1135
+ getDescriptor(htmlElementClass.prototype, 'onclick')?.get === nativeOnclick.get &&
1136
+ getDescriptor(htmlElementClass.prototype, 'onclick')?.set === nativeOnclick.set && evalIntact();
1137
+ const wrappersIntact = () => root.URL === urlClass && root.HTMLAnchorElement === anchorClass &&
1138
+ root.EventTarget === eventTargetClass && root.HTMLElement === htmlElementClass &&
1139
+ root.WeakMap === weakMapClass &&
1140
+ urlClass.createObjectURL === captureCreate && anchorClass.prototype.click === captureClick &&
1141
+ eventTargetClass.prototype.addEventListener === wrappedAdd &&
1142
+ eventTargetClass.prototype.removeEventListener === wrappedRemove && onclickIntact();
1143
+ const restore = () => {
1144
+ let restored = true;
1145
+ try {
1146
+ if (onclickCapture) {
1147
+ const info = onclickCapture;
1148
+ apply(nativeRemove, info.target, ['click', info.listener, false]);
1149
+ const descriptor = getDescriptor(info.target, 'onclick');
1150
+ if (descriptor?.get === info.getter && descriptor?.set === info.setter) {
1151
+ if (!apply(nativeDelete, Reflect, [info.target, 'onclick'])) restored = false;
1152
+ } else restored = false;
1153
+ const current = apply(nativeOnclick.get, info.target, []);
1154
+ if (!info.changed && current === null && restored) {
1155
+ apply(nativeOnclick.set, info.target, [info.original]);
1156
+ }
1157
+ onclickCapture = null;
1158
+ }
1159
+ if (urlClass.createObjectURL === captureCreate) {
1160
+ define(urlClass, 'createObjectURL', {
1161
+ value: nativeCreate, writable: true, configurable: true,
1162
+ });
1163
+ } else if (urlClass.createObjectURL !== nativeCreate) restored = false;
1164
+ if (anchorClass.prototype.click === captureClick) {
1165
+ define(anchorClass.prototype, 'click', {
1166
+ value: nativeAnchorClick, writable: true, configurable: true,
1167
+ });
1168
+ } else if (anchorClass.prototype.click !== nativeAnchorClick) restored = false;
1169
+ } catch { restored = false; }
1170
+ return restored;
1171
+ };
1172
+ const run = async (operation, suppliedSecret, selector) => {
1173
+ if (suppliedSecret !== secret) return '{"status":"unverifiable"}';
1174
+ if (operation === 'matches') {
1175
+ if (armed && evalIntact() && wrappersIntact() && selector === selectedElement) {
1176
+ matched = true;
1177
+ return '{"status":"matched"}';
1178
+ }
1179
+ ambiguous = true;
1180
+ return '{"status":"unverifiable"}';
1181
+ }
1182
+ if (operation === 'status') {
1183
+ return armed && matched && !ambiguous && evalIntact() && wrappersIntact()
1184
+ ? '{"status":"matched"}' : '{"status":"unverifiable"}';
1185
+ }
1186
+ if (operation === 'cancel') {
1187
+ const hadAttempt = armed;
1188
+ armed = false;
1189
+ const restored = !hadAttempt || restore();
1190
+ reset();
1191
+ return restored ? '{"status":"unverifiable"}' : '{"status":"cleanup_failed"}';
1192
+ }
1193
+ if (operation === 'arm') {
1194
+ const restored = !(armed || onclickCapture) || restore();
1195
+ reset();
1196
+ if (!restored) return '{"status":"cleanup_failed"}';
1197
+ if (!nativeMethodsIntact() || typeof selector !== 'string' || !selector ||
1198
+ selector.length > 512) {
1199
+ return '{"status":"unverifiable"}';
1200
+ }
1201
+ let target;
1202
+ try {
1203
+ const matches = apply(nativeQuerySelectorAll, root.document, [selector]);
1204
+ if (apply(nativeNodeListLength, matches, []) !== 1) return '{"status":"unverifiable"}';
1205
+ target = apply(nativeNodeListItem, matches, [0]);
1206
+ if (!target || !apply(nativeContains, root.document, [target])) {
1207
+ return '{"status":"unverifiable"}';
1208
+ }
1209
+ // A link with href is handled by the script-free private-page flow.
1210
+ // A bare <a onclick> without href can be a synchronous Blob producer.
1211
+ const anchor = apply(nativeClosest, target, ['a']);
1212
+ if (anchor && (anchor !== target || apply(nativeGetAttribute, target, ['href']) !== null)) {
1213
+ return '{"status":"unverifiable"}';
1214
+ }
1215
+ } catch { return '{"status":"unverifiable"}'; }
1216
+ try {
1217
+ if (!captureOnclick(target)) return '{"status":"unverifiable"}';
1218
+ define(urlClass, 'createObjectURL', {
1219
+ value: captureCreate, writable: true, configurable: true,
1220
+ });
1221
+ define(anchorClass.prototype, 'click', {
1222
+ value: captureClick, writable: true, configurable: true,
1223
+ });
1224
+ } catch {
1225
+ return restore() ? '{"status":"unverifiable"}' : '{"status":"cleanup_failed"}';
1226
+ }
1227
+ selectedElement = target;
1228
+ armed = true;
1229
+ return '{"status":"armed"}';
1230
+ }
1231
+ if (operation !== 'finish') return '{"status":"unverifiable"}';
1232
+ const valid = armed && evalIntact() && wrappersIntact() && !ambiguous && trustedClicks === 1 &&
1233
+ creations === 1 && clicks === 1 && clicked && created &&
1234
+ clicked.url === created.url;
1235
+ const captured = valid ? { blob: created.blob, size: created.size,
1236
+ filename: clicked.filename } : null;
1237
+ const hadAttempt = armed;
1238
+ armed = false;
1239
+ const restored = !hadAttempt || restore();
1240
+ reset();
1241
+ if (!restored) return '{"status":"cleanup_failed"}';
1242
+ if (!captured) return '{"status":"unverifiable"}';
1243
+ if (!isSafeInteger(captured.size) || captured.size > maxBytes) {
1244
+ return '{"status":"too_large"}';
1245
+ }
1246
+ try {
1247
+ const data = await apply(nativeBlobArrayBuffer, captured.blob, []);
1248
+ const bytes = new byteArrayClass(data);
1249
+ const byteLength = apply(nativeTypedArrayByteLength, bytes, []);
1250
+ const length = apply(nativeTypedArrayLength, bytes, []);
1251
+ if (byteLength !== captured.size || byteLength > maxBytes || length !== byteLength) {
1252
+ return '{"status":"unverifiable"}';
1253
+ }
1254
+ let binary = '';
1255
+ for (let index = 0; index < length; index++) {
1256
+ binary += apply(nativeFromCharCode, stringClass, [bytes[index]]);
1257
+ }
1258
+ // A page may replace Object.prototype.toJSON after init. A null-prototype
1259
+ // envelope keeps the captured native serializer from calling page code.
1260
+ const result = apply(createObject, Object, [null]);
1261
+ result.status = 'ok';
1262
+ result.filename = captured.filename;
1263
+ result.byte_count = length;
1264
+ result.data_base64 = apply(nativeBtoa, root, [binary]);
1265
+ return apply(stringify, json, [result]);
1266
+ } catch {
1267
+ return '{"status":"unverifiable"}';
1268
+ }
1269
+ };
1270
+ define(root, key, { value: run, enumerable: false, configurable: false, writable: false });
1271
+ }
1272
+
1273
+ // Resolve the approved CSS link with pristine DOM methods. Playwright's
1274
+ // ElementHandle.evaluate can be intercepted by a site's window.eval, even
1275
+ // after CDP disables page scripts, so it cannot authorize a download URL.
1276
+ function installDownloadLinkInspector({ key, secret }) {
1277
+ const root = globalThis;
1278
+ const document = root.document;
1279
+ const apply = Reflect.apply;
1280
+ const define = Object.defineProperty;
1281
+ const create = Object.create;
1282
+ const stringify = JSON.stringify;
1283
+ const getDescriptor = Object.getOwnPropertyDescriptor;
1284
+ const getPrototypeOf = Object.getPrototypeOf;
1285
+ const hasOwn = Object.hasOwn;
1286
+ const evalDescriptor = getDescriptor(root, 'eval');
1287
+ const nativeEval = evalDescriptor?.value;
1288
+ const queryPath = [];
1289
+ let queryOwner = document;
1290
+ while (queryOwner && !getDescriptor(queryOwner, 'querySelectorAll')) {
1291
+ queryPath.push(queryOwner);
1292
+ queryOwner = getPrototypeOf(queryOwner);
1293
+ }
1294
+ const querySelectorAll = queryOwner && getDescriptor(queryOwner, 'querySelectorAll')?.value;
1295
+ const nodeListLength = getDescriptor(NodeList.prototype, 'length').get;
1296
+ const nodeListItem = NodeList.prototype.item;
1297
+ const getAttribute = Element.prototype.getAttribute;
1298
+ const anchorHref = getDescriptor(HTMLAnchorElement.prototype, 'href').get;
1299
+ const contains = Node.prototype.contains;
1300
+ const unverifiable = '{"status":"unverifiable"}';
1301
+ let observed;
1302
+ const pristineMethods = () => {
1303
+ const currentEval = getDescriptor(root, 'eval');
1304
+ if (!currentEval || !hasOwn(currentEval, 'value') || currentEval.value !== nativeEval ||
1305
+ typeof nativeEval !== 'function') return false;
1306
+ let owner = document;
1307
+ for (const expected of queryPath) {
1308
+ if (owner !== expected || getDescriptor(owner, 'querySelectorAll')) return false;
1309
+ owner = getPrototypeOf(owner);
1310
+ }
1311
+ const currentQuery = owner && getDescriptor(owner, 'querySelectorAll');
1312
+ return owner === queryOwner && currentQuery && hasOwn(currentQuery, 'value') &&
1313
+ currentQuery.value === querySelectorAll && typeof querySelectorAll === 'function';
1314
+ };
1315
+ const inspect = (operation, suppliedSecret, selector) => {
1316
+ if (suppliedSecret !== secret || !pristineMethods()) {
1317
+ return unverifiable;
1318
+ }
1319
+ if (operation === 'matches') {
1320
+ return observed && selector === observed.element &&
1321
+ apply(contains, document, [selector]) ? '{"status":"matched"}' : unverifiable;
1322
+ }
1323
+ if ((operation !== 'inspect' && operation !== 'confirm') ||
1324
+ typeof selector !== 'string' || !selector || selector.length > 512) {
1325
+ return unverifiable;
1326
+ }
1327
+ if (operation === 'inspect') observed = undefined;
1328
+ try {
1329
+ const matches = apply(querySelectorAll, document, [selector]);
1330
+ if (apply(nodeListLength, matches, []) !== 1) return unverifiable;
1331
+ const element = apply(nodeListItem, matches, [0]);
1332
+ if (!element || !apply(contains, document, [element])) return unverifiable;
1333
+ const rawHref = apply(getAttribute, element, ['href']);
1334
+ const download = apply(getAttribute, element, ['download']);
1335
+ const href = apply(anchorHref, element, []);
1336
+ if (typeof rawHref !== 'string' || !rawHref.trim() || rawHref.length > 2_048 ||
1337
+ typeof href !== 'string' || href.length > 2_048 ||
1338
+ (download !== null && (typeof download !== 'string' || download.length > 180))) {
1339
+ return unverifiable;
1340
+ }
1341
+ if (operation === 'confirm') {
1342
+ if (!observed || observed.selector !== selector || observed.element !== element ||
1343
+ observed.rawHref !== rawHref || observed.href !== href ||
1344
+ observed.download !== download) return unverifiable;
1345
+ } else {
1346
+ observed = { selector, element, rawHref, href, download };
1347
+ }
1348
+ const result = apply(create, Object, [null]);
1349
+ result.status = 'ok';
1350
+ result.href = href;
1351
+ result.download = download;
1352
+ return apply(stringify, JSON, [result]);
1353
+ } catch { return unverifiable; }
1354
+ };
1355
+ define(root, key, { value: inspect, enumerable: false, configurable: false, writable: false });
1356
+
1357
+ }
1358
+
1359
+
1360
+ // Browser state is runtime-owned; all active-page/action/event state below is
1361
+ // chat-owned. Shared storage is intentional account reuse, not chat isolation.
1362
+ function createChatScope({ id, generation, profileMode, context, downloadDir,
1363
+ downloadContextId, runtime }) {
1364
+ const browser = runtime.browser;
1365
+ const downloadCdp = runtime.downloadCdp;
1366
+ let epoch = randomBytes(6).readUIntBE(0, 6);
1367
+ let tabs = [];
1368
+ const tabByPage = new WeakMap();
1369
+ let activeTabId;
1370
+ let activeCapture;
1371
+ let desiredCapture;
1372
+ let captureGeneration = 0;
1373
+ let captureTask = Promise.resolve();
1374
+ let captureTimer;
1375
+ let frameSeq = 0;
1376
+ let lastFrameAt = 0;
1377
+ let closing = false;
1378
+ let shuttingDown = false;
1379
+ let pendingDialog;
1380
+ let inFlightAction;
1381
+ const dialogWaiters = new Set();
1382
+ let activeDownloadAttempt;
1383
+ let transientPageCreation;
1384
+ const transientPages = new WeakSet();
1385
+ const orphanDownloads = new Set();
1386
+ let downloadSweep = Promise.resolve();
1387
+ let scopeClose;
1388
+ let commandTail = Promise.resolve();
1389
+ let queuedCommands = 0;
1390
+ const ownedPages = new Set();
1391
+ const emit = message => {
1392
+ if (!closing) runtime.emitScope(api, message);
1393
+ };
1394
+
1395
+ function bounded(value, maximum) {
1396
+ return value.length > maximum ? value.slice(0, maximum) : value;
1397
+ }
1398
+
1399
+ function boundedDialogText(value) {
1400
+ let text = '';
1401
+ let consumed = 0;
1402
+ for (const character of value) {
1403
+ if (consumed + character.length > MAX_DIALOG_CHARS) break;
1404
+ const codePoint = character.codePointAt(0);
1405
+ text += codePoint >= 0xD800 && codePoint <= 0xDFFF ? '\uFFFD' : character;
1406
+ consumed += character.length;
1407
+ }
1408
+ return { text, truncated: consumed < value.length };
1409
+ }
1410
+
1411
+ function staleEpochError() {
1412
+ const error = new Error('browser page changed; refresh state and retry');
1413
+ error.code = 'stale_epoch';
1414
+ return error;
1415
+ }
1416
+
1417
+ function activeTab() {
1418
+ return tabs.find(tab => tab.id === activeTabId);
1419
+ }
1420
+
1421
+ function requireActiveTab() {
1422
+ const tab = activeTab();
1423
+ if (!tab || tab.page.isClosed()) throw staleEpochError();
1424
+ return tab;
1425
+ }
1426
+
1427
+ function tabSummary(tab) {
1428
+ return {
1429
+ tab_id: tab.id,
1430
+ url: tab.page.url(),
1431
+ title: tab.title,
1432
+ active: tab.id === activeTabId,
1433
+ };
1434
+ }
1435
+
1436
+ function dialogError(code, message) {
1437
+ const error = new Error(message);
1438
+ error.code = code;
1439
+ return error;
1440
+ }
1441
+
1442
+ function dialogState() {
1443
+ const tab = requireActiveTab();
1444
+ const pending = pendingDialog;
1445
+ const message = pending && boundedDialogText(pending.message);
1446
+ const defaultValue = pending && boundedDialogText(pending.defaultValue);
1447
+ return {
1448
+ page_epoch: epoch,
1449
+ active_tab_id: tab.id,
1450
+ url: tab.page.url(),
1451
+ title: tab.title,
1452
+ frame_seq: frameSeq,
1453
+ viewport: tab.page.viewportSize(),
1454
+ can_go_back: false,
1455
+ can_go_forward: false,
1456
+ tabs: tabs.map(tabSummary),
1457
+ pending_dialog: pending ? {
1458
+ dialog_id: pending.id,
1459
+ tab_id: pending.tabId,
1460
+ page_epoch: pending.pageEpoch,
1461
+ url: pending.url,
1462
+ type: pending.type,
1463
+ message: message.text,
1464
+ message_truncated: message.truncated,
1465
+ default_value: defaultValue.text,
1466
+ default_value_truncated: defaultValue.truncated,
1467
+ expires_at_ms: pending.expiresAt,
1468
+ status: pending.expired ? 'expired' : 'pending',
1469
+ } : null,
1470
+ };
1471
+ }
1472
+
1473
+ async function stableRead(read) {
1474
+ for (let attempt = 0; attempt < 3; attempt++) {
1475
+ const tab = requireActiveTab();
1476
+ const readEpoch = epoch;
1477
+ const readUrl = tab.page.url();
1478
+ checkPageUrl(readUrl);
1479
+ try {
1480
+ const value = await read(tab);
1481
+ if (epoch === readEpoch && activeTabId === tab.id &&
1482
+ !tab.page.isClosed() && tab.page.url() === readUrl) {
1483
+ return { page_epoch: readEpoch, active_tab_id: tab.id, url: readUrl, ...value };
1484
+ }
1485
+ } catch (error) {
1486
+ if (epoch === readEpoch && activeTabId === tab.id &&
1487
+ !tab.page.isClosed() && tab.page.url() === readUrl) throw error;
1488
+ }
1489
+ }
1490
+ throw staleEpochError();
1491
+ }
1492
+
1493
+ async function state() {
1494
+ // Browser title/history CDP calls can block while a JavaScript dialog is
1495
+ // open. The synchronous page metadata still identifies the authoritative
1496
+ // tab and pending dialog without wedging the host command loop.
1497
+ if (pendingDialog && activeTab()) return dialogState();
1498
+ if (!activeTab()) {
1499
+ return {
1500
+ page_epoch: epoch,
1501
+ active_tab_id: null,
1502
+ url: '',
1503
+ title: '',
1504
+ frame_seq: frameSeq,
1505
+ viewport: { width: 1000, height: 720 },
1506
+ can_go_back: false,
1507
+ can_go_forward: false,
1508
+ tabs: [],
1509
+ pending_dialog: null,
1510
+ };
1511
+ }
1512
+ return stableRead(async tab => {
1513
+ const viewport = tab.page.viewportSize();
1514
+ const title = await tab.page.title();
1515
+ tab.title = title;
1516
+ let canGoBack = false;
1517
+ let canGoForward = false;
1518
+ try {
1519
+ const cdp = await tab.cdp;
1520
+ const history = await cdp.send('Page.getNavigationHistory');
1521
+ canGoBack = history.currentIndex > 0;
1522
+ canGoForward = history.currentIndex < history.entries.length - 1;
1523
+ } catch {
1524
+ // Navigation history is a hint and may be briefly unavailable.
1525
+ }
1526
+ return {
1527
+ frame_seq: frameSeq, title, viewport,
1528
+ can_go_back: canGoBack, can_go_forward: canGoForward,
1529
+ tabs: tabs.map(tabSummary),
1530
+ };
1531
+ });
1532
+ }
1533
+
1534
+ function checkEpoch(args) {
1535
+ if (args.expected_epoch !== epoch) {
1536
+ throw staleEpochError();
1537
+ }
1538
+ }
1539
+
1540
+ function checkEvalArgs(args) {
1541
+ if (typeof args.code !== 'string' || !args.code.trim() ||
1542
+ Buffer.byteLength(args.code, 'utf8') > MAX_EVAL_CODE_BYTES) {
1543
+ const error = new Error('browser_eval code must be nonempty and at most 8 KiB');
1544
+ error.code = 'invalid_request';
1545
+ throw error;
1546
+ }
1547
+ if (!Number.isSafeInteger(args.expected_epoch) || args.expected_epoch < 0) {
1548
+ const error = new Error('browser_eval requires a safe expected_epoch');
1549
+ error.code = 'invalid_request';
1550
+ throw error;
1551
+ }
1552
+ if (typeof args.expected_url !== 'string' ||
1553
+ Buffer.byteLength(args.expected_url, 'utf8') > 8192) {
1554
+ const error = new Error('browser_eval requires a bounded expected_url');
1555
+ error.code = 'invalid_request';
1556
+ throw error;
1557
+ }
1558
+ checkPageUrl(args.expected_url);
1559
+ checkEpoch(args);
1560
+ }
1561
+
1562
+ // Playwright installs this before document scripts in every page and frame.
1563
+ // The non-writable function keeps pristine intrinsics in its closure, so page
1564
+ // scripts cannot replace the bounded serializer before or during model eval.
1565
+ function validateEvalResult(value) {
1566
+ // The pre-document helper transfers a bounded JSON primitive. Validate its
1567
+ // parsed value again with trusted Node intrinsics before returning it.
1568
+ const stack = [[value, 0]];
1569
+ let entries = 0;
1570
+ let stringUnits = 0;
1571
+ while (stack.length) {
1572
+ const [item, depth] = stack.pop();
1573
+ if (++entries > 256 || depth > 8) {
1574
+ const error = new Error('browser_eval result exceeds depth or entry limit');
1575
+ error.code = 'browser_eval_error';
1576
+ throw error;
1577
+ }
1578
+ if (item === null || typeof item === 'boolean') continue;
1579
+ if (typeof item === 'number' && Number.isFinite(item)) continue;
1580
+ if (typeof item === 'string') {
1581
+ stringUnits += item.length;
1582
+ if (stringUnits <= 65536) continue;
1583
+ } else if (Array.isArray(item)) {
1584
+ if (item.length <= 64) {
1585
+ let valid = true;
1586
+ for (let index = 0; index < item.length; index++) {
1587
+ const descriptor = Object.getOwnPropertyDescriptor(item, String(index));
1588
+ if (!descriptor || !Object.hasOwn(descriptor, 'value')) {
1589
+ valid = false;
1590
+ break;
1591
+ }
1592
+ stack.push([descriptor.value, depth + 1]);
1593
+ }
1594
+ if (valid) continue;
1595
+ }
1596
+ } else if (typeof item === 'object') {
1597
+ const keys = Object.keys(item);
1598
+ const prototype = Object.getPrototypeOf(item);
1599
+ if ((prototype === Object.prototype || prototype === null) &&
1600
+ keys.length <= 64 && keys.every(key => key.length <= 256)) {
1601
+ let valid = true;
1602
+ for (const key of keys) {
1603
+ const descriptor = Object.getOwnPropertyDescriptor(item, key);
1604
+ if (!descriptor || !Object.hasOwn(descriptor, 'value')) {
1605
+ valid = false;
1606
+ break;
1607
+ }
1608
+ stack.push([descriptor.value, depth + 1]);
1609
+ }
1610
+ if (valid) continue;
1611
+ }
1612
+ }
1613
+ const error = new Error('browser_eval result is not JSON-safe or exceeds limits');
1614
+ error.code = 'browser_eval_error';
1615
+ throw error;
1616
+ }
1617
+ return value;
1618
+ }
1619
+
1620
+ async function evalInActivePage(args) {
1621
+ checkEvalArgs(args);
1622
+ const tab = requireActiveTab();
1623
+ const page = tab.page;
1624
+ let popupStarted = false;
1625
+ let cdp;
1626
+ const onWindowOpen = () => { popupStarted = true; };
1627
+ const onPopup = () => { popupStarted = true; };
1628
+ const unchanged = () => epoch === args.expected_epoch && activeTabId === tab.id &&
1629
+ !page.isClosed() && page.url() === args.expected_url &&
1630
+ // Playwright can adopt a popup after window.open returns if its destination
1631
+ // response is slow. CDP reports the intent before the new tab is visible.
1632
+ !popupStarted &&
1633
+ // A same-URL reload can keep the old URL/epoch until its slow response
1634
+ // commits. Never return a value from the document being replaced.
1635
+ tab.pendingNavigations.size === 0;
1636
+ if (!unchanged()) throw staleEpochError();
1637
+ let transferred;
1638
+ try {
1639
+ // Playwright's page.evaluate compiles its callback through the page's
1640
+ // mutable window.eval. CDP compiles this fixed call independently while
1641
+ // the protected helper still evaluates the model source in the page realm.
1642
+ cdp = await tab.cdp;
1643
+ if (!cdp) throw new Error('browser_eval page session unavailable');
1644
+ page.on('popup', onPopup);
1645
+ cdp.on('Page.windowOpen', onWindowOpen);
1646
+ await cdp.send('Page.enable');
1647
+ if (!unchanged()) throw staleEpochError();
1648
+ const expression = `window[${JSON.stringify(EVAL_HELPER_KEY)}](${JSON.stringify(args.code)})`;
1649
+ const reply = await cdp.send('Runtime.evaluate', {
1650
+ expression, awaitPromise: true, returnByValue: true,
1651
+ });
1652
+ if (reply.exceptionDetails) throw new Error('browser_eval page helper unavailable');
1653
+ const serialized = reply.result?.value;
1654
+ if (typeof serialized !== 'string' || Buffer.byteLength(serialized, 'utf8') > 75000) {
1655
+ throw new Error('browser_eval transfer exceeds limit');
1656
+ }
1657
+ const evaluated = JSON.parse(serialized);
1658
+ if (evaluated?.ok !== true) throw new Error('browser_eval JavaScript failed');
1659
+ if (evaluated.observed_url !== args.expected_url) throw staleEpochError();
1660
+ // A synchronous location assignment may schedule navigation after eval
1661
+ // resolves. Give Chromium a turn to commit it, then recheck from the host.
1662
+ // A second page.evaluate here would expose its Promise/timeout result to
1663
+ // page-controlled globals before any transfer limit is enforced.
1664
+ await new Promise(resolve => setTimeout(resolve, 25));
1665
+ if (!unchanged()) throw staleEpochError();
1666
+ transferred = evaluated.value;
1667
+ } catch (error) {
1668
+ // Chromium may destroy the execution context before Playwright's frame
1669
+ // navigation event advances our epoch. Never surface that result as a
1670
+ // script exception from the old document.
1671
+ if (error?.code === 'stale_epoch' || !unchanged() ||
1672
+ String(error?.message || error).includes('Execution context was destroyed')) {
1673
+ throw staleEpochError();
1674
+ }
1675
+ const boundedError = new Error(bounded(String(error?.message || error), 2048));
1676
+ boundedError.code = 'browser_eval_error';
1677
+ throw boundedError;
1678
+ } finally {
1679
+ page.off('popup', onPopup);
1680
+ cdp?.off('Page.windowOpen', onWindowOpen);
1681
+ }
1682
+ if (!unchanged()) throw staleEpochError();
1683
+ const value = validateEvalResult(transferred);
1684
+ if (Buffer.byteLength(JSON.stringify(value), 'utf8') > MAX_EVAL_JSON_BYTES) {
1685
+ const error = new Error('browser_eval result exceeds 64 KiB');
1686
+ error.code = 'browser_eval_error';
1687
+ throw error;
1688
+ }
1689
+ if (!unchanged()) throw staleEpochError();
1690
+ return {
1691
+ page_epoch: epoch,
1692
+ active_tab_id: tab.id,
1693
+ url: page.url(),
1694
+ value,
1695
+ };
1696
+ }
1697
+
1698
+ function requireTabId(raw) {
1699
+ if (typeof raw !== 'string' || !/^[0-9a-f]{24}$/.test(raw)) {
1700
+ const error = new Error('invalid browser tab ID');
1701
+ error.code = 'invalid_request';
1702
+ throw error;
1703
+ }
1704
+ return raw;
1705
+ }
1706
+
1707
+ function captureIsCurrent(capture) {
1708
+ return captureGeneration === capture.generation && desiredCapture === capture &&
1709
+ activeTabId === capture.tabId && epoch === capture.epoch &&
1710
+ !capture.page.isClosed() && !shuttingDown && !closing;
1711
+ }
1712
+
1713
+ function clearCaptureTimer() {
1714
+ if (captureTimer) clearTimeout(captureTimer);
1715
+ captureTimer = undefined;
1716
+ }
1717
+
1718
+ function emitCaptureFrame(capture, data, viewportWidth, viewportHeight) {
1719
+ if (!captureIsCurrent(capture)) return false;
1720
+ const now = Date.now();
1721
+ if (now - lastFrameAt < 100) return false;
1722
+ lastFrameAt = now;
1723
+ emit({
1724
+ event: 'frame', active_tab_id: capture.tabId, page_epoch: capture.epoch,
1725
+ frame_seq: ++frameSeq, viewport_width: viewportWidth,
1726
+ viewport_height: viewportHeight, data: data.toString('base64'),
1727
+ });
1728
+ return true;
1729
+ }
1730
+
1731
+ function armCaptureRecovery(capture, delay = CAPTURE_FIRST_FRAME_WAIT_MS) {
1732
+ if (!captureIsCurrent(capture) || capture.screencastSeen) return;
1733
+ clearCaptureTimer();
1734
+ captureTimer = setTimeout(() => {
1735
+ captureTimer = undefined;
1736
+ void recoverCapture(capture);
1737
+ }, delay);
1738
+ }
1739
+
1740
+ async function recoverCapture(capture) {
1741
+ if (!captureIsCurrent(capture) || capture.screencastSeen) return;
1742
+ if (!capture.reportedStall) {
1743
+ capture.reportedStall = true;
1744
+ console.warn('browser screencast produced no current frame; recovering');
1745
+ }
1746
+ // A direct Chromium screenshot keeps the shared picture stream usable while
1747
+ // Playwright's asynchronous screencast stop/start recovers. Its result may
1748
+ // complete after a navigation or tab switch, so fence it on both sides.
1749
+ try {
1750
+ const viewport = capture.page.viewportSize();
1751
+ const url = capture.page.url();
1752
+ const data = await capture.page.screenshot({
1753
+ type: 'jpeg', quality: 75, scale: 'css', timeout: CAPTURE_STILL_TIMEOUT_MS,
1754
+ });
1755
+ const currentViewport = capture.page.viewportSize();
1756
+ if (!capture.screencastSeen && viewport && currentViewport &&
1757
+ url === capture.url && url === capture.page.url() &&
1758
+ viewport.width === currentViewport.width && viewport.height === currentViewport.height) {
1759
+ emitCaptureFrame(capture, data, viewport.width, viewport.height);
1760
+ }
1761
+ } catch {
1762
+ if (captureIsCurrent(capture)) console.warn('browser recovery screenshot failed');
1763
+ }
1764
+ if (!captureIsCurrent(capture) || capture.screencastSeen) return;
1765
+ if (!capture.startSettled) {
1766
+ // A channel start can remain pending while direct screenshots still work.
1767
+ // Keep the fallback alive without queuing a second start behind it.
1768
+ armCaptureRecovery(capture, CAPTURE_FALLBACK_INTERVAL_MS);
1769
+ } else if (capture.restart < CAPTURE_RESTART_LIMIT) {
1770
+ scheduleCapture(capture.restart + 1);
1771
+ } else {
1772
+ // At most one 3-second screenshot every 1.5 seconds for the active tab;
1773
+ // normal screencast frames immediately cancel this fallback timer.
1774
+ armCaptureRecovery(capture, CAPTURE_FALLBACK_INTERVAL_MS);
1775
+ }
1776
+ }
1777
+
1778
+ function scheduleCapture(restart = 0) {
1779
+ const generation = ++captureGeneration;
1780
+ clearCaptureTimer();
1781
+ const tab = activeTab();
1782
+ const capture = tab && !tab.page.isClosed() ? {
1783
+ page: tab.page, tabId: tab.id, url: tab.page.url(), epoch, generation, restart,
1784
+ screencastSeen: false, reportedStall: restart > 0, startSettled: false,
1785
+ } : undefined;
1786
+ desiredCapture = capture;
1787
+ // The previous Playwright stop may itself remain pending. A fenced direct
1788
+ // screenshot can still seed the new epoch while the serialized restart waits.
1789
+ if (capture) armCaptureRecovery(capture);
1790
+ captureTask = captureTask.catch(() => {}).then(async () => {
1791
+ if (generation !== captureGeneration || shuttingDown || closing) return;
1792
+ if (activeCapture) {
1793
+ const previous = activeCapture;
1794
+ activeCapture = undefined;
1795
+ // Playwright marks a screencast started before its channel call returns.
1796
+ // Even a failed start must be stopped before another start is attempted.
1797
+ // Exercise a permanently pending stop in the real Chromium host test.
1798
+ if (TEST_STALL_SCREENCAST_STOP) await new Promise(() => {});
1799
+ await previous.page.screencast.stop().catch(() => {
1800
+ if (!previous.page.isClosed() && !shuttingDown && !closing) {
1801
+ console.warn('browser screencast stop failed; retrying capture');
1802
+ }
1803
+ });
1804
+ }
1805
+ if (generation !== captureGeneration || shuttingDown || closing) return;
1806
+ if (!capture || tab.page.isClosed()) return;
1807
+ activeCapture = capture;
1808
+ try {
1809
+ await tab.page.screencast.start({
1810
+ quality: 75,
1811
+ size: { width: 1200, height: 1000 },
1812
+ onFrame: ({ data, viewportWidth, viewportHeight }) => {
1813
+ if (!captureIsCurrent(capture) || TEST_SUPPRESS_SCREENCAST_FRAMES) return;
1814
+ if (emitCaptureFrame(capture, data, viewportWidth, viewportHeight)) {
1815
+ capture.screencastSeen = true;
1816
+ clearCaptureTimer();
1817
+ }
1818
+ },
1819
+ });
1820
+ } catch {
1821
+ if (captureIsCurrent(capture)) console.warn('browser screencast start failed; recovering');
1822
+ } finally {
1823
+ capture.startSettled = true;
1824
+ }
1825
+ });
1826
+ }
1827
+
1828
+ function advanceEpoch() {
1829
+ epoch++;
1830
+ if (pendingDialog && pendingDialog.pageEpoch !== epoch) {
1831
+ expireDialog(pendingDialog);
1832
+ }
1833
+ lastFrameAt = 0;
1834
+ // Reset the server's cached JPEG before replying with the new active state.
1835
+ emit({ event: 'frame_reset', active_tab_id: activeTabId || null, page_epoch: epoch });
1836
+ // Restarting screencast yields a first current-epoch JPEG even if a hidden
1837
+ // iframe changes without repainting the visible page.
1838
+ void scheduleCapture();
1839
+ }
1840
+
1841
+ function expireDialog(pending) {
1842
+ if (pendingDialog !== pending || pending.expired) return;
1843
+ pending.expired = true;
1844
+ clearTimeout(pending.timer);
1845
+ void pending.dialog.dismiss().catch(() => {}).finally(() => {
1846
+ if (pendingDialog === pending && (!pending.owner || pending.owner.settled)) {
1847
+ pendingDialog = undefined;
1848
+ }
1849
+ });
1850
+ }
1851
+
1852
+ function captureDialog(tab, dialog) {
1853
+ if (shuttingDown || closing || pendingDialog ||
1854
+ !['alert', 'confirm', 'prompt'].includes(dialog.type())) {
1855
+ void dialog.dismiss().catch(() => {});
1856
+ return;
1857
+ }
1858
+ const owner = inFlightAction;
1859
+ if (owner) owner.hadDialog = true;
1860
+ const pending = {
1861
+ id: randomBytes(12).toString('hex'),
1862
+ tabId: tab.id,
1863
+ pageEpoch: epoch,
1864
+ url: tab.page.url(),
1865
+ type: dialog.type(),
1866
+ message: dialog.message(),
1867
+ defaultValue: dialog.defaultValue(),
1868
+ dialog,
1869
+ owner,
1870
+ expired: false,
1871
+ expiresAt: Date.now() + DIALOG_TIMEOUT_MS,
1872
+ };
1873
+ pending.timer = setTimeout(() => expireDialog(pending), DIALOG_TIMEOUT_MS);
1874
+ pending.timer.unref();
1875
+ pendingDialog = pending;
1876
+ owner?.notify?.();
1877
+ for (const notify of dialogWaiters) notify();
1878
+ }
1879
+
1880
+ function targetError(code, message) {
1881
+ const error = new Error(message);
1882
+ error.code = code;
1883
+ return error;
1884
+ }
1885
+
1886
+ function pointerTimeout(deadlineAt) {
1887
+ if (deadlineAt === undefined) return 10_000;
1888
+ const remaining = deadlineAt - Date.now();
1889
+ if (remaining <= 0) {
1890
+ throw targetError('navigation_timeout', 'browser pointer action timed out');
1891
+ }
1892
+ return Math.min(10_000, remaining);
1893
+ }
1894
+
1895
+ function semanticString(target, name, maximum, required = false) {
1896
+ const value = target[name];
1897
+ if (value === undefined && !required) return undefined;
1898
+ if (typeof value !== 'string' || !value.trim() || value.length > maximum) {
1899
+ throw targetError('invalid_target', `invalid browser target ${name}`);
1900
+ }
1901
+ return value;
1902
+ }
1903
+
1904
+ function selectOptionArgs(args) {
1905
+ if (typeof args.selector !== 'string' || !args.selector.trim() ||
1906
+ args.selector.length > 512) {
1907
+ throw targetError('invalid_target', 'browser select requires a bounded CSS selector');
1908
+ }
1909
+ if (!Array.isArray(args.values) || args.values.length < 1 || args.values.length > 16 ||
1910
+ args.values.some(value => typeof value !== 'string' || Buffer.byteLength(value, 'utf8') > 512)) {
1911
+ throw targetError('invalid_target', 'browser select requires 1..16 option values of at most 512 bytes each');
1912
+ }
1913
+ return args.values;
1914
+ }
1915
+
1916
+ function downloadError(code, message) {
1917
+ return targetError(code, message);
1918
+ }
1919
+
1920
+ function downloadDeadline(promise, deadlineAt) {
1921
+ const remaining = deadlineAt - Date.now();
1922
+ if (remaining <= 0) {
1923
+ return Promise.reject(downloadError('download_timeout', 'browser download timed out'));
1924
+ }
1925
+ return new Promise((resolve, reject) => {
1926
+ const timer = setTimeout(() => reject(downloadError('download_timeout', 'browser download timed out')), remaining);
1927
+ Promise.resolve(promise).then(
1928
+ value => { clearTimeout(timer); resolve(value); },
1929
+ error => { clearTimeout(timer); reject(error); },
1930
+ );
1931
+ });
1932
+ }
1933
+
1934
+ async function inspectDownloadLink(cdp, selector, operation, deadlineAt) {
1935
+ const expression = `window[${JSON.stringify(DOWNLOAD_LINK_KEY)}](` +
1936
+ `${JSON.stringify(operation)},${JSON.stringify(DOWNLOAD_LINK_SECRET)},` +
1937
+ `${JSON.stringify(selector)})`;
1938
+ let answer;
1939
+ try {
1940
+ answer = await downloadDeadline(cdp.send('Runtime.evaluate', {
1941
+ expression, awaitPromise: true, returnByValue: true,
1942
+ }), deadlineAt);
1943
+ } catch (error) {
1944
+ if (error?.code === 'download_timeout') throw error;
1945
+ throw downloadError('download_unverifiable', 'browser download cannot verify the selected link');
1946
+ }
1947
+ if (answer.exceptionDetails || answer.result?.type !== 'string' ||
1948
+ typeof answer.result.value !== 'string' || answer.result.value.length > 4_096) {
1949
+ throw downloadError('download_unverifiable', 'browser download cannot verify the selected link');
1950
+ }
1951
+ let link;
1952
+ try { link = JSON.parse(answer.result.value); } catch { /* Fail closed below. */ }
1953
+ if (link?.status !== 'ok' || typeof link.href !== 'string' || link.href.length > 2_048 ||
1954
+ (link.download !== null && (typeof link.download !== 'string' || link.download.length > 180))) {
1955
+ throw downloadError('download_unverifiable', 'browser download cannot verify the selected link');
1956
+ }
1957
+ return link;
1958
+ }
1959
+
1960
+ async function scriptBlobCommand(cdp, operation, selector, deadlineAt) {
1961
+ const expression = `window[${JSON.stringify(SCRIPT_BLOB_KEY)}](` +
1962
+ `${JSON.stringify(operation)},${JSON.stringify(SCRIPT_BLOB_SECRET)},` +
1963
+ `${JSON.stringify(selector)})`;
1964
+ let answer;
1965
+ try {
1966
+ answer = await downloadDeadline(cdp.send('Runtime.evaluate', {
1967
+ expression, awaitPromise: true, returnByValue: true,
1968
+ }), deadlineAt);
1969
+ } catch (error) {
1970
+ if (error?.code === 'download_timeout') throw error;
1971
+ throw downloadError('download_unverifiable', 'browser download cannot verify the selected script');
1972
+ }
1973
+ if (answer.exceptionDetails || answer.result?.type !== 'string' ||
1974
+ typeof answer.result.value !== 'string' || answer.result.value.length > 360_000) {
1975
+ throw downloadError('download_unverifiable', 'browser download cannot verify the selected script');
1976
+ }
1977
+ let result;
1978
+ try { result = JSON.parse(answer.result.value); } catch { /* Fail closed below. */ }
1979
+ if (!result || typeof result !== 'object' || Array.isArray(result) ||
1980
+ !['armed', 'matched', 'ok', 'too_large', 'unverifiable', 'cleanup_failed'].includes(result.status)) {
1981
+ throw downloadError('download_unverifiable', 'browser download cannot verify the selected script');
1982
+ }
1983
+ return result;
1984
+ }
1985
+
1986
+ function verifiedDownloadUrl(value, previousUrl) {
1987
+ if (typeof value !== 'string' || !value || value.length > 2_048 || /[\x00-\x1f\x7f]/.test(value)) return null;
1988
+ try {
1989
+ const url = new URL(value, previousUrl);
1990
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password ||
1991
+ (previousUrl?.startsWith('https://') && url.protocol !== 'https:')) return null;
1992
+ url.hash = '';
1993
+ return url.href.length <= 2_048 ? url.href : null;
1994
+ } catch { return null; }
1995
+ }
1996
+
1997
+ function downloadResponseHeader(event, name) {
1998
+ if (!Array.isArray(event.responseHeaders)) return null;
1999
+ const values = event.responseHeaders.filter(header =>
2000
+ header && typeof header.name === 'string' && header.name.toLowerCase() === name);
2001
+ return values.length === 1 && typeof values[0].value === 'string' ? values[0].value : null;
2002
+ }
2003
+
2004
+ async function observeDownloadRedirects(attempt, cdp, initialUrl, nativeDownloadAttribute, deadlineAt) {
2005
+ let current;
2006
+ let hops = 0;
2007
+ let failed = false;
2008
+ let enabled = true;
2009
+ let disablePromise;
2010
+ const pending = new Set();
2011
+ const reject = () => {
2012
+ failed = true;
2013
+ attempt.verifiedFinalUrl = null;
2014
+ attempt.resolveUnverifiable();
2015
+ };
2016
+ const disable = until => {
2017
+ if (!enabled) return Promise.resolve();
2018
+ if (!disablePromise) {
2019
+ cdp.off('Fetch.requestPaused', onPaused);
2020
+ disablePromise = cdp.send('Fetch.disable').then(() => { enabled = false; });
2021
+ }
2022
+ return downloadDeadline(disablePromise, until);
2023
+ };
2024
+ const onPaused = event => {
2025
+ const requestUrl = verifiedDownloadUrl(event.request?.url);
2026
+ const responseStage = Number.isInteger(event.responseStatusCode);
2027
+ let finalResponse = false;
2028
+ if (failed || !attempt.accepting || event.frameId !== attempt.frameId ||
2029
+ event.resourceType !== 'Document' || event.request?.method !== 'GET' || !requestUrl) {
2030
+ reject();
2031
+ } else if (!responseStage) {
2032
+ if (!current) {
2033
+ if (event.redirectedRequestId || requestUrl !== initialUrl) reject();
2034
+ } else if (!current.redirectUrl || event.redirectedRequestId !== current.id ||
2035
+ requestUrl !== current.redirectUrl) {
2036
+ reject();
2037
+ }
2038
+ if (!failed) current = { id: event.requestId, url: requestUrl, responseSeen: false };
2039
+ } else if (!current || current.id !== event.requestId || current.url !== requestUrl ||
2040
+ current.responseSeen) {
2041
+ reject();
2042
+ } else {
2043
+ current.responseSeen = true;
2044
+ const status = event.responseStatusCode;
2045
+ if ([301, 302, 303, 307, 308].includes(status)) {
2046
+ const next = verifiedDownloadUrl(downloadResponseHeader(event, 'location'), current.url);
2047
+ if (!next || ++hops > 5) reject();
2048
+ else current.redirectUrl = next;
2049
+ } else {
2050
+ const type = downloadResponseHeader(event, 'content-type');
2051
+ const disposition = downloadResponseHeader(event, 'content-disposition');
2052
+ const refresh = Array.isArray(event.responseHeaders) && event.responseHeaders.some(header =>
2053
+ typeof header?.name === 'string' && header.name.toLowerCase() === 'refresh');
2054
+ // Keep all terminal documents paused until their headers prove they
2055
+ // cannot render HTML or load resources in the private page. Redirects
2056
+ // receive no exception to the direct-download policy.
2057
+ const nativeDownload = /^\s*attachment\s*(?:;|$)/i.test(disposition || '') ||
2058
+ (nativeDownloadAttribute && new URL(current.url).origin === new URL(initialUrl).origin) ||
2059
+ /^\s*application\/octet-stream\s*(?:;|$)/i.test(type || '');
2060
+ if (![200, 206].includes(status) || refresh || !type ||
2061
+ /^\s*(?:text\/html|application\/xhtml\+xml)\s*(?:;|$)/i.test(type) ||
2062
+ !nativeDownload || attempt.verifiedFinalUrl) {
2063
+ reject();
2064
+ } else {
2065
+ attempt.verifiedFinalUrl = current.url;
2066
+ finalResponse = true;
2067
+ }
2068
+ }
2069
+ }
2070
+ const method = failed ? 'Fetch.failRequest' :
2071
+ responseStage ? 'Fetch.continueResponse' : 'Fetch.continueRequest';
2072
+ const params = method === 'Fetch.failRequest'
2073
+ ? { requestId: event.requestId, errorReason: 'BlockedByClient' }
2074
+ : { requestId: event.requestId };
2075
+ const continuation = downloadDeadline(cdp.send(method, params), deadlineAt)
2076
+ .then(async () => {
2077
+ if (finalResponse && !failed) {
2078
+ await disable(deadlineAt);
2079
+ attempt.resolveVerified();
2080
+ }
2081
+ })
2082
+ .catch(reject).finally(() => pending.delete(continuation));
2083
+ pending.add(continuation);
2084
+ };
2085
+ cdp.on('Fetch.requestPaused', onPaused);
2086
+ try {
2087
+ await downloadDeadline(cdp.send('Fetch.enable', { patterns: [
2088
+ { urlPattern: '*', requestStage: 'Request' },
2089
+ { urlPattern: '*', requestStage: 'Response' },
2090
+ ] }), deadlineAt);
2091
+ } catch (error) {
2092
+ cdp.off('Fetch.requestPaused', onPaused);
2093
+ throw error;
2094
+ }
2095
+ return async cleanupDeadlineAt => {
2096
+ cdp.off('Fetch.requestPaused', onPaused);
2097
+ // Closing the private target tears down its Fetch domain. Sending
2098
+ // Fetch.disable afterward fails because the CDP session is detached.
2099
+ if (attempt.page?.isClosed()) return;
2100
+ await disable(cleanupDeadlineAt);
2101
+ await downloadDeadline(Promise.all(pending), cleanupDeadlineAt);
2102
+ };
2103
+ }
2104
+
2105
+ async function createTransientDownloadPage(deadlineAt) {
2106
+ // Hold page events until the private newPage identity is known.
2107
+ const creation = { observed: [], page: null };
2108
+ transientPageCreation = creation;
2109
+ const pending = Promise.resolve().then(async () => {
2110
+ const page = await runtime.createPage(api, true);
2111
+ if (TEST_PRIVATE_PAGE_FAILURE === 'reject') throw new Error('private page setup failed');
2112
+ if (TEST_PRIVATE_PAGE_FAILURE === 'timeout') await new Promise(resolve => setTimeout(resolve, 6_000));
2113
+ return page;
2114
+ });
2115
+ let failed = false;
2116
+ try {
2117
+ creation.page = await downloadDeadline(pending, deadlineAt);
2118
+ transientPages.add(creation.page);
2119
+ return creation.page;
2120
+ } catch (error) {
2121
+ // An emitted page without proven identity must never enter shared tabs.
2122
+ failed = true;
2123
+ shuttingDown = true;
2124
+ retireAfterReply = true;
2125
+ void pending.then(page => page.close().catch(() => {})).catch(() => {});
2126
+ throw error;
2127
+ } finally {
2128
+ transientPageCreation = undefined;
2129
+ for (const page of creation.observed) {
2130
+ if (failed) void page.close().catch(() => {});
2131
+ else if (page !== creation.page) adoptPage(page);
2132
+ }
2133
+ }
2134
+ }
2135
+
2136
+ function escapeHtmlAttribute(value) {
2137
+ return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
2138
+ }
2139
+
2140
+ function cleanDownloadFilename(value) {
2141
+ const basename = path.posix.basename(String(value || '').slice(0, 1024).replace(/\\/g, '/'))
2142
+ .replace(/[\x00-\x1f\x7f]/g, '')
2143
+ .trim();
2144
+ if (!basename || basename === '.' || basename === '..') return 'download.bin';
2145
+ let cleaned = '';
2146
+ for (const character of basename) {
2147
+ if (Buffer.byteLength(cleaned + character, 'utf8') > 180) break;
2148
+ cleaned += character;
2149
+ }
2150
+ return cleaned || 'download.bin';
2151
+ }
2152
+
2153
+ function cancelDownloadGuid(guid) {
2154
+ return downloadCdp?.send('Browser.cancelDownload', {
2155
+ guid, ...(downloadContextId ? { browserContextId: downloadContextId } : {}),
2156
+ }).catch(() => {});
2157
+ }
2158
+
2159
+ async function removeDownloadArtifacts(guid) {
2160
+ // allowAndName uses the CDP guid for both the final file and its partial
2161
+ // .crdownload file. Never use a browser-supplied path or suggested filename.
2162
+ if (!downloadDir || !/^[a-zA-Z0-9_-]{1,128}$/.test(guid)) return;
2163
+ await Promise.all([
2164
+ fs.rm(path.join(downloadDir, guid), { force: true }),
2165
+ fs.rm(path.join(downloadDir, `${guid}.crdownload`), { force: true }),
2166
+ ]);
2167
+ }
2168
+
2169
+ async function clearDownloadDirectory() {
2170
+ if (!downloadDir) return;
2171
+ const entries = await fs.readdir(downloadDir).catch(error => {
2172
+ if (error.code === 'ENOENT') return [];
2173
+ throw error;
2174
+ });
2175
+ await Promise.all(entries.map(name => fs.rm(path.join(downloadDir, name), { recursive: true, force: true })));
2176
+ }
2177
+
2178
+ async function settleDownloadDirectory(deadlineAt) {
2179
+ // Chromium can recreate a .crdownload shortly after reporting cancellation.
2180
+ // Do not return a reusable host until its private directory stays empty.
2181
+ let emptySince = 0;
2182
+ while (true) {
2183
+ const entries = await downloadDeadline(fs.readdir(downloadDir), deadlineAt);
2184
+ if (entries.length) {
2185
+ await downloadDeadline(clearDownloadDirectory(), deadlineAt);
2186
+ emptySince = 0;
2187
+ } else if (emptySince && Date.now() - emptySince >= 100) {
2188
+ return;
2189
+ } else if (!emptySince) {
2190
+ emptySince = Date.now();
2191
+ }
2192
+ await downloadDeadline(new Promise(resolve => setTimeout(resolve, 25)), deadlineAt);
2193
+ }
2194
+ }
2195
+
2196
+ function sweepOrphanDownloads() {
2197
+ const sweep = downloadSweep.then(async () => {
2198
+ if (!activeDownloadAttempt) await clearDownloadDirectory();
2199
+ });
2200
+ downloadSweep = sweep.catch(() => {});
2201
+ return sweep;
2202
+ }
2203
+
2204
+ function onDownloadWillBegin(event) {
2205
+ const attempt = activeDownloadAttempt;
2206
+ if (attempt?.mode === 'script_blob') {
2207
+ attempt.nativeDownloadObserved = true;
2208
+ cancelDownloadGuid(event.guid);
2209
+ return;
2210
+ }
2211
+ if (attempt?.accepting && event.frameId === attempt.frameId &&
2212
+ event.url !== attempt.verifiedFinalUrl) {
2213
+ attempt.resolveUnverifiable();
2214
+ }
2215
+ if (!attempt?.accepting || attempt.guid || event.frameId !== attempt.frameId ||
2216
+ event.url !== attempt.verifiedFinalUrl) {
2217
+ cancelDownloadGuid(event.guid);
2218
+ return;
2219
+ }
2220
+ attempt.guid = event.guid;
2221
+ attempt.resolveGuid(event.guid);
2222
+ }
2223
+
2224
+ function onDownloadProgress(event) {
2225
+ const attempt = activeDownloadAttempt;
2226
+ if (attempt?.mode === 'script_blob') {
2227
+ attempt.nativeDownloadObserved = true;
2228
+ if (event.state === 'inProgress') cancelDownloadGuid(event.guid);
2229
+ else void removeDownloadArtifacts(event.guid).catch(() => {});
2230
+ return;
2231
+ }
2232
+ if (!attempt || event.guid !== attempt.guid) {
2233
+ if (event.state === 'inProgress') cancelDownloadGuid(event.guid);
2234
+ else void removeDownloadArtifacts(event.guid).catch(() => {});
2235
+ return;
2236
+ }
2237
+ if (event.state !== 'inProgress') {
2238
+ attempt.terminal = true;
2239
+ attempt.terminalState = event.state;
2240
+ attempt.resolveTerminal();
2241
+ }
2242
+ if (event.receivedBytes > MAX_DOWNLOAD_BYTES) {
2243
+ attempt.oversized = true;
2244
+ cancelDownloadGuid(event.guid);
2245
+ if (attempt.download) void attempt.download.cancel().catch(() => {});
2246
+ }
2247
+ }
2248
+
2249
+ function onPageDownload(page, download) {
2250
+ const attempt = activeDownloadAttempt;
2251
+ if (attempt?.mode === 'script_blob') attempt.nativeDownloadObserved = true;
2252
+ if (attempt?.accepting && attempt.page === page && download.url() !== attempt.verifiedFinalUrl) {
2253
+ attempt.resolveUnverifiable();
2254
+ }
2255
+ if (!attempt?.accepting || attempt.page !== page || attempt.download ||
2256
+ download.url() !== attempt.verifiedFinalUrl) {
2257
+ const cleanup = download.cancel().catch(() => {})
2258
+ .then(() => download.delete().catch(() => {}));
2259
+ orphanDownloads.add(cleanup);
2260
+ void cleanup.finally(() => {
2261
+ orphanDownloads.delete(cleanup);
2262
+ void sweepOrphanDownloads().catch(() => {
2263
+ // This directory contains only this host's browser downloads. A
2264
+ // failed sweep must not leave unapproved bytes in a reusable session.
2265
+ shuttingDown = true;
2266
+ void closeHost().finally(() => process.exit(1));
2267
+ });
2268
+ });
2269
+ return;
2270
+ }
2271
+ attempt.download = download;
2272
+ attempt.resolveDownload(download);
2273
+ if (attempt.oversized) void download.cancel().catch(() => {});
2274
+ }
2275
+
2276
+ async function boundedDownload(args, deadlineAt = Date.now() + DOWNLOAD_ACTION_BUDGET_MS) {
2277
+ // The 20-second action budget includes cancellation and artifact removal.
2278
+ // Reserve its last slice for cleanup even when the transfer never settles.
2279
+ const cleanupBudget = Math.min(2_000, Math.floor(DOWNLOAD_ACTION_BUDGET_MS / 4));
2280
+ const workDeadlineAt = deadlineAt - cleanupBudget;
2281
+ const cancelDeadlineAt = deadlineAt - Math.ceil(cleanupBudget / 2);
2282
+ const terminalDeadlineAt = deadlineAt - Math.ceil(cleanupBudget / 4);
2283
+ checkEpoch(args);
2284
+ if (typeof args.selector !== 'string' || !args.selector.trim() || args.selector.length > 512) {
2285
+ throw downloadError('invalid_target', 'browser download requires a bounded CSS selector');
2286
+ }
2287
+ await downloadDeadline(downloadSweep, workDeadlineAt);
2288
+ const tab = requireActiveTab();
2289
+ const cdp = await downloadDeadline(tab.cdp, workDeadlineAt);
2290
+ if (!cdp || !downloadCdp) {
2291
+ throw downloadError('download_failed', 'browser download observer unavailable');
2292
+ }
2293
+ checkEpoch(args);
2294
+ let resolveDownload;
2295
+ let resolveGuid;
2296
+ let resolveTerminal;
2297
+ let resolveUnverifiable;
2298
+ let resolveVerified;
2299
+ let scriptsDisabled = false;
2300
+ let transientPage;
2301
+ let closeGuard;
2302
+ const attempt = {
2303
+ page: null,
2304
+ frameId: null,
2305
+ accepting: false,
2306
+ download: null,
2307
+ guid: null,
2308
+ verifiedFinalUrl: null,
2309
+ oversized: false,
2310
+ terminal: false,
2311
+ downloadPromise: new Promise(resolve => { resolveDownload = resolve; }),
2312
+ guidPromise: new Promise(resolve => { resolveGuid = resolve; }),
2313
+ terminalPromise: new Promise(resolve => { resolveTerminal = resolve; }),
2314
+ unverifiablePromise: new Promise(resolve => { resolveUnverifiable = resolve; }),
2315
+ verifiedPromise: new Promise(resolve => { resolveVerified = resolve; }),
2316
+ resolveDownload: download => resolveDownload(download),
2317
+ resolveGuid: guid => resolveGuid(guid),
2318
+ resolveTerminal: () => resolveTerminal(),
2319
+ resolveUnverifiable: () => resolveUnverifiable(),
2320
+ resolveVerified: () => resolveVerified(),
2321
+ };
2322
+ activeDownloadAttempt = attempt;
2323
+ try {
2324
+ // Freeze page timers and handlers before resolving the selected link.
2325
+ // Otherwise a getter invoked during target inspection could schedule a
2326
+ // same-URL download in the gap before the native click.
2327
+ scriptsDisabled = true;
2328
+ await downloadDeadline(cdp.send('Emulation.setScriptExecutionDisabled', { value: true }),
2329
+ workDeadlineAt);
2330
+ await downloadDeadline(new Promise(resolve => setTimeout(resolve, 25)), workDeadlineAt);
2331
+ let link;
2332
+ try {
2333
+ link = await inspectDownloadLink(cdp, args.selector, 'inspect', workDeadlineAt);
2334
+ } catch (error) {
2335
+ // Only a failed initial inspection can enter the script-Blob path.
2336
+ // Later failures may follow a private click/request; retrying the same
2337
+ // selector could act on a different DOM node in the shared page.
2338
+ if (error?.code === 'download_unverifiable') error.scriptFallbackEligible = true;
2339
+ throw error;
2340
+ }
2341
+ await downloadDeadline(withPinnedTarget(args, async handle => {
2342
+ checkEpoch(args);
2343
+ if (await handle.ownerFrame() !== tab.page.mainFrame()) {
2344
+ throw downloadError('download_unverifiable',
2345
+ 'browser download requires a link in the main page');
2346
+ }
2347
+ // The pinned ElementHandle must be the inspector's exact DOM node. Its
2348
+ // evaluate result is used only for identity, after the helper checked
2349
+ // that page eval is pristine; href bytes still come solely from CDP.
2350
+ let pinnedMatch;
2351
+ try {
2352
+ pinnedMatch = await downloadDeadline(handle.evaluate((element, identity) =>
2353
+ window[identity.key]('matches', identity.secret, element), {
2354
+ key: DOWNLOAD_LINK_KEY, secret: DOWNLOAD_LINK_SECRET,
2355
+ }), workDeadlineAt);
2356
+ } catch (error) {
2357
+ if (error?.code === 'download_timeout') throw error;
2358
+ }
2359
+ if (pinnedMatch !== '{"status":"matched"}') {
2360
+ throw downloadError('download_unverifiable',
2361
+ 'browser download target changed before trial click');
2362
+ }
2363
+ try {
2364
+ // Verify the selected element could receive a native click, without
2365
+ // running its handlers or starting the download in the shared page.
2366
+ await handle.click({ trial: true,
2367
+ timeout: Math.min(1_500, pointerTimeout(workDeadlineAt)) });
2368
+ } catch {
2369
+ throw downloadError('download_unverifiable',
2370
+ 'browser download requires an actionable link');
2371
+ }
2372
+ checkEpoch(args);
2373
+ // The helper pins the unique DOM element and compares it after the
2374
+ // trial click, so a replaced selector cannot authorize another href.
2375
+ const confirmed = await inspectDownloadLink(cdp, args.selector, 'confirm', workDeadlineAt);
2376
+ if (confirmed.href !== link.href || confirmed.download !== link.download) {
2377
+ throw downloadError('download_unverifiable', 'browser download selected link changed');
2378
+ }
2379
+ let href;
2380
+ try {
2381
+ const resolved = new URL(link.href);
2382
+ // Fragments never reach the HTTP request or Chromium's download URL.
2383
+ resolved.hash = '';
2384
+ href = resolved.href;
2385
+ } catch {
2386
+ throw downloadError('download_unverifiable',
2387
+ 'browser download requires a direct HTTP(S) link');
2388
+ }
2389
+ if (typeof href !== 'string' || href.length > 2_048 ||
2390
+ !(href.startsWith('http://') || href.startsWith('https://'))) {
2391
+ throw downloadError('download_unverifiable',
2392
+ 'browser download requires a direct HTTP(S) link');
2393
+ }
2394
+ try {
2395
+ checkUrl(href);
2396
+ } catch {
2397
+ throw downloadError('download_unverifiable',
2398
+ 'browser download requires a direct HTTP(S) link');
2399
+ }
2400
+ // Download requests lack reliable Network events; use a private frame ID.
2401
+ const sharedUrl = tab.page.url();
2402
+ if (sharedUrl === 'about:blank') throw downloadError('download_unverifiable',
2403
+ 'browser download requires an HTTP(S) page');
2404
+ let documentUrl;
2405
+ try {
2406
+ documentUrl = new URL(checkUrl(sharedUrl));
2407
+ documentUrl.hash = '';
2408
+ } catch {
2409
+ throw downloadError('download_unverifiable',
2410
+ 'browser download requires an HTTP(S) page');
2411
+ }
2412
+ const sourceResponse = tab.mainDocumentResponse;
2413
+ if (!sourceResponse || tab.mainDocumentUrl !== documentUrl.href) throw downloadError(
2414
+ 'download_unverifiable', 'browser download cannot verify the source page policy');
2415
+ const sourceHeaders = await downloadDeadline(sourceResponse.headersArray(), workDeadlineAt).catch(() => null);
2416
+ if (!sourceHeaders || sourceHeaders.some(header =>
2417
+ header.name.toLowerCase() === 'content-security-policy' &&
2418
+ header.value.split(/[;,]/).some(policyDirective =>
2419
+ policyDirective.trim().split(/\s+/, 1)[0].toLowerCase() === 'sandbox'))) {
2420
+ throw downloadError('download_unverifiable', 'browser download cannot verify the source page policy');
2421
+ }
2422
+ transientPage = await createTransientDownloadPage(workDeadlineAt);
2423
+ transientPage.on('download', download => onPageDownload(transientPage, download));
2424
+ transientPage.on('framenavigated', frame => {
2425
+ if (attempt.accepting && frame === transientPage.mainFrame()) {
2426
+ attempt.resolveUnverifiable();
2427
+ }
2428
+ });
2429
+ const privateCdp = await downloadDeadline(context.newCDPSession(transientPage), workDeadlineAt);
2430
+ await downloadDeadline(privateCdp.send('Emulation.setScriptExecutionDisabled', { value: true }),
2431
+ workDeadlineAt);
2432
+ const downloadAttribute = link.download === null ? '' : ` download="${escapeHtmlAttribute(link.download)}"`;
2433
+ const html = `<a id="bamboo-download" href="${escapeHtmlAttribute(href)}"${downloadAttribute}>Download</a>`;
2434
+ await downloadDeadline(transientPage.route(url => url.href === documentUrl.href,
2435
+ route => route.fulfill({
2436
+ status: 200, contentType: 'text/html',
2437
+ headers: { 'content-security-policy': "default-src 'none'; script-src 'none'; object-src 'none'",
2438
+ 'referrer-policy': 'no-referrer' },
2439
+ body: html,
2440
+ }), { times: 1 }), workDeadlineAt);
2441
+ await downloadDeadline(transientPage.goto(documentUrl.href, {
2442
+ waitUntil: 'domcontentloaded', timeout: pointerTimeout(workDeadlineAt),
2443
+ }), workDeadlineAt);
2444
+ await downloadDeadline(transientPage.route('**/*', route => {
2445
+ const request = route.request();
2446
+ let mainNavigation = false;
2447
+ try {
2448
+ mainNavigation = request.isNavigationRequest() &&
2449
+ request.frame() === transientPage.mainFrame();
2450
+ } catch { /* Unknown provenance is blocked. */ }
2451
+ if (mainNavigation) {
2452
+ return route.continue();
2453
+ }
2454
+ return route.abort('blockedbyclient');
2455
+ }), workDeadlineAt);
2456
+ const frameTree = await downloadDeadline(privateCdp.send('Page.getFrameTree'), workDeadlineAt);
2457
+ attempt.page = transientPage;
2458
+ attempt.frameId = frameTree.frameTree.frame.id;
2459
+ if (verifiedDownloadUrl(href) !== href) {
2460
+ throw downloadError('download_unverifiable', 'browser download requires a safe HTTP(S) link');
2461
+ }
2462
+ closeGuard = await observeDownloadRedirects(attempt, privateCdp, href,
2463
+ link.download !== null && documentUrl.origin === new URL(href).origin, workDeadlineAt);
2464
+ checkEpoch(args);
2465
+ if (activeTabId !== tab.id || tab.page.url() !== sharedUrl) throw staleEpochError();
2466
+ if (TEST_DOWNLOAD_CLICK_DELAY_MS) {
2467
+ await downloadDeadline(new Promise(resolve => setTimeout(resolve, TEST_DOWNLOAD_CLICK_DELAY_MS)),
2468
+ workDeadlineAt);
2469
+ }
2470
+ attempt.accepting = true;
2471
+ await transientPage.locator('#bamboo-download').click({
2472
+ timeout: pointerTimeout(workDeadlineAt), noWaitAfter: true,
2473
+ });
2474
+ }, workDeadlineAt), workDeadlineAt);
2475
+ const accepted = await downloadDeadline(Promise.race([
2476
+ Promise.all([attempt.downloadPromise, attempt.guidPromise, attempt.verifiedPromise])
2477
+ .then(([download]) => ({ download })),
2478
+ attempt.unverifiablePromise.then(() => ({ unverifiable: true })),
2479
+ ]), workDeadlineAt);
2480
+ if (accepted.unverifiable) {
2481
+ throw downloadError('download_unverifiable',
2482
+ 'browser download redirect cannot be verified');
2483
+ }
2484
+ const { download } = accepted;
2485
+ if (attempt.oversized) {
2486
+ throw downloadError('download_too_large', 'browser download exceeds 256 KiB');
2487
+ }
2488
+ let artifact;
2489
+ try {
2490
+ // Playwright's Artifact path is launch-wide, whereas the native CDP
2491
+ // download path is now owned by this chat. Await native completion and
2492
+ // read only the verified GUID in the scope directory; never trust a
2493
+ // suggested filename or another chat's launch-wide Artifact path.
2494
+ await downloadDeadline(attempt.terminalPromise, workDeadlineAt);
2495
+ if (attempt.terminalState !== 'completed' || await downloadDeadline(download.failure(), workDeadlineAt)) {
2496
+ throw downloadError('download_failed', 'browser download failed');
2497
+ }
2498
+ if (!/^[a-zA-Z0-9_-]{1,128}$/.test(attempt.guid)) throw downloadError('download_failed', 'browser download identity unavailable');
2499
+ artifact = path.join(downloadDir, attempt.guid);
2500
+ } catch (error) {
2501
+ if (attempt.oversized) {
2502
+ throw downloadError('download_too_large', 'browser download exceeds 256 KiB');
2503
+ }
2504
+ if (error?.code === 'download_timeout') throw error;
2505
+ throw downloadError('download_failed', 'browser download failed');
2506
+ }
2507
+ const size = await downloadDeadline(fs.lstat(artifact), workDeadlineAt);
2508
+ if (!size.isFile() || size.isSymbolicLink()) throw downloadError('download_failed', 'browser download artifact unavailable');
2509
+ if (size.size > MAX_DOWNLOAD_BYTES || attempt.oversized) {
2510
+ throw downloadError('download_too_large', 'browser download exceeds 256 KiB');
2511
+ }
2512
+ const bytes = await downloadDeadline(fs.readFile(artifact), workDeadlineAt);
2513
+ if (bytes.length > MAX_DOWNLOAD_BYTES || attempt.oversized) {
2514
+ throw downloadError('download_too_large', 'browser download exceeds 256 KiB');
2515
+ }
2516
+ checkEpoch(args);
2517
+ if (activeTabId !== tab.id || tab.page.isClosed()) throw staleEpochError();
2518
+ const current = await downloadDeadline(state(), workDeadlineAt);
2519
+ checkEpoch(args);
2520
+ if (current.active_tab_id !== tab.id) throw staleEpochError();
2521
+ return {
2522
+ page_epoch: current.page_epoch,
2523
+ active_tab_id: current.active_tab_id,
2524
+ url: current.url,
2525
+ filename: cleanDownloadFilename(download.suggestedFilename()),
2526
+ byte_count: bytes.length,
2527
+ sha256: createHash('sha256').update(bytes).digest('hex'),
2528
+ data_base64: bytes.toString('base64'),
2529
+ };
2530
+ } catch (error) {
2531
+ if (['stale_epoch', 'invalid_target', 'target_not_found', 'ambiguous_target',
2532
+ 'download_timeout', 'download_too_large', 'download_failed',
2533
+ 'download_unverifiable'].includes(error?.code)) {
2534
+ throw error;
2535
+ }
2536
+ // Playwright errors can quote a selected URL or filename. Never forward
2537
+ // them through the host's generic error envelope.
2538
+ throw downloadError('download_failed', 'browser download failed');
2539
+ } finally {
2540
+ attempt.accepting = false;
2541
+ let cleanupError;
2542
+ if (scriptsDisabled) {
2543
+ try {
2544
+ await downloadDeadline(cdp.send('Emulation.setScriptExecutionDisabled', { value: false }),
2545
+ cancelDeadlineAt);
2546
+ } catch (error) {
2547
+ cleanupError = error;
2548
+ }
2549
+ }
2550
+ const cancellation = [];
2551
+ if (attempt.guid && !attempt.terminal) cancellation.push(cancelDownloadGuid(attempt.guid));
2552
+ if (attempt.download && !attempt.terminal) cancellation.push(attempt.download.cancel().catch(() => {}));
2553
+ try {
2554
+ if (TEST_DOWNLOAD_CLEANUP_DELAY_MS && attempt.guid) {
2555
+ await downloadDeadline(new Promise(resolve => setTimeout(resolve, TEST_DOWNLOAD_CLEANUP_DELAY_MS)),
2556
+ cancelDeadlineAt);
2557
+ }
2558
+ await downloadDeadline(Promise.all(cancellation), cancelDeadlineAt);
2559
+ if (attempt.guid && !attempt.terminal) {
2560
+ await downloadDeadline(attempt.terminalPromise, terminalDeadlineAt);
2561
+ }
2562
+ } catch (error) {
2563
+ cleanupError = error;
2564
+ }
2565
+ if (attempt.download) {
2566
+ try {
2567
+ await downloadDeadline(attempt.download.delete().catch(() => {}), deadlineAt);
2568
+ } catch (error) {
2569
+ cleanupError ||= error;
2570
+ }
2571
+ }
2572
+ if (attempt.guid) {
2573
+ try {
2574
+ await downloadDeadline(removeDownloadArtifacts(attempt.guid), deadlineAt);
2575
+ } catch (error) {
2576
+ cleanupError ||= error;
2577
+ }
2578
+ }
2579
+ if (transientPage) {
2580
+ try {
2581
+ await downloadDeadline(transientPage.close(), deadlineAt);
2582
+ } catch (error) {
2583
+ cleanupError ||= error;
2584
+ }
2585
+ }
2586
+ if (closeGuard) {
2587
+ try {
2588
+ await closeGuard(deadlineAt);
2589
+ } catch (error) {
2590
+ cleanupError ||= error;
2591
+ }
2592
+ }
2593
+ if (activeDownloadAttempt === attempt) activeDownloadAttempt = undefined;
2594
+ try {
2595
+ await downloadDeadline(Promise.all([...orphanDownloads]), deadlineAt);
2596
+ await downloadDeadline(clearDownloadDirectory(), deadlineAt);
2597
+ await settleDownloadDirectory(deadlineAt);
2598
+ } catch (error) {
2599
+ cleanupError ||= error;
2600
+ }
2601
+ if (cleanupError) {
2602
+ // A nonterminal transfer can recreate a partial file after cleanup.
2603
+ // Retire the host; Rust owns and removes its per-session TMPDIR on exit.
2604
+ shuttingDown = true;
2605
+ retireAfterReply = true;
2606
+ throw downloadError(cleanupError.code === 'download_timeout' ? 'download_timeout' : 'download_failed',
2607
+ 'browser download cleanup failed');
2608
+ }
2609
+ }
2610
+ }
2611
+
2612
+ async function boundedScriptBlobDownload(args, deadlineAt) {
2613
+ const cleanupBudget = Math.min(2_000, Math.floor(DOWNLOAD_ACTION_BUDGET_MS / 4));
2614
+ const workDeadlineAt = deadlineAt - cleanupBudget;
2615
+ checkEpoch(args);
2616
+ if (typeof args.selector !== 'string' || !args.selector.trim() || args.selector.length > 512) {
2617
+ throw downloadError('invalid_target', 'browser download requires a bounded CSS selector');
2618
+ }
2619
+ await downloadDeadline(downloadSweep, workDeadlineAt);
2620
+ const tab = requireActiveTab();
2621
+ const cdp = await downloadDeadline(tab.cdp, workDeadlineAt);
2622
+ if (!cdp || !downloadCdp) throw downloadError('download_failed', 'browser download observer unavailable');
2623
+ const sharedUrl = tab.page.url();
2624
+ let documentUrl;
2625
+ try {
2626
+ documentUrl = new URL(checkUrl(sharedUrl));
2627
+ documentUrl.hash = '';
2628
+ } catch {
2629
+ throw downloadError('download_unverifiable', 'browser download requires an HTTP(S) page');
2630
+ }
2631
+ if (!tab.mainDocumentResponse || tab.mainDocumentUrl !== documentUrl.href) {
2632
+ throw downloadError('download_unverifiable', 'browser download cannot verify the source page policy');
2633
+ }
2634
+ const sourceHeaders = await downloadDeadline(tab.mainDocumentResponse.headersArray(), workDeadlineAt)
2635
+ .catch(() => null);
2636
+ if (!sourceHeaders || sourceHeaders.some(header =>
2637
+ header.name.toLowerCase() === 'content-security-policy' &&
2638
+ header.value.split(/[;,]/).some(directive =>
2639
+ directive.trim().split(/\s+/, 1)[0].toLowerCase() === 'sandbox'))) {
2640
+ throw downloadError('download_unverifiable', 'browser download cannot verify the source page policy');
2641
+ }
2642
+ checkEpoch(args);
2643
+ const attempt = { mode: 'script_blob', accepting: false, nativeDownloadObserved: false };
2644
+ activeDownloadAttempt = attempt;
2645
+ let helperArmed = false;
2646
+ let cleanupError;
2647
+ let response;
2648
+ try {
2649
+ const captured = await downloadDeadline(withPinnedTarget(args, async handle => {
2650
+ checkEpoch(args);
2651
+ let owner;
2652
+ try { owner = await handle.ownerFrame(); } catch { /* Tampered page eval can spoof a Node. */ }
2653
+ if (owner !== tab.page.mainFrame()) {
2654
+ throw downloadError('download_unverifiable',
2655
+ 'browser script download requires a target in the main page');
2656
+ }
2657
+ try {
2658
+ await handle.click({ trial: true,
2659
+ timeout: Math.min(1_500, pointerTimeout(workDeadlineAt)) });
2660
+ } catch {
2661
+ throw downloadError('download_unverifiable',
2662
+ 'browser script download requires an actionable target');
2663
+ }
2664
+ checkEpoch(args);
2665
+ const armed = await scriptBlobCommand(cdp, 'arm', args.selector, workDeadlineAt);
2666
+ if (armed.status === 'cleanup_failed') {
2667
+ cleanupError = downloadError('download_failed', 'browser script download cleanup failed');
2668
+ throw cleanupError;
2669
+ }
2670
+ if (armed.status !== 'armed') {
2671
+ throw downloadError('download_unverifiable',
2672
+ 'browser download cannot verify the selected script');
2673
+ }
2674
+ helperArmed = true;
2675
+ try {
2676
+ // Playwright evaluates against the pinned ElementHandle, but page eval
2677
+ // may be tampered with. Trust only the helper's separate CDP status:
2678
+ // a forged evaluate return cannot set its private matched bit.
2679
+ await downloadDeadline(handle.evaluate((element, identity) =>
2680
+ window[identity.key]('matches', identity.secret, element), {
2681
+ key: SCRIPT_BLOB_KEY, secret: SCRIPT_BLOB_SECRET,
2682
+ }), workDeadlineAt).catch(error => {
2683
+ if (error?.code === 'download_timeout') throw error;
2684
+ });
2685
+ const identity = await scriptBlobCommand(cdp, 'status', null, workDeadlineAt);
2686
+ if (identity.status !== 'matched' || attempt.nativeDownloadObserved) {
2687
+ throw downloadError('download_unverifiable',
2688
+ 'browser download target changed before click');
2689
+ }
2690
+ if (TEST_DOWNLOAD_CLICK_DELAY_MS) {
2691
+ await downloadDeadline(new Promise(resolve => setTimeout(resolve, TEST_DOWNLOAD_CLICK_DELAY_MS)),
2692
+ workDeadlineAt);
2693
+ }
2694
+ if (attempt.nativeDownloadObserved) {
2695
+ throw downloadError('download_unverifiable', 'browser download attribution is ambiguous');
2696
+ }
2697
+ checkEpoch(args);
2698
+ if (activeTabId !== tab.id || tab.page.url() !== sharedUrl ||
2699
+ tab.pendingNavigations.size) throw staleEpochError();
2700
+ await downloadDeadline(handle.click({
2701
+ noWaitAfter: true, timeout: pointerTimeout(workDeadlineAt),
2702
+ }), workDeadlineAt);
2703
+ checkEpoch(args);
2704
+ if (activeTabId !== tab.id || tab.page.url() !== sharedUrl ||
2705
+ tab.pendingNavigations.size) throw staleEpochError();
2706
+ const result = await scriptBlobCommand(cdp, 'finish', null, workDeadlineAt);
2707
+ helperArmed = result.status === 'cleanup_failed';
2708
+ if (result.status === 'cleanup_failed') {
2709
+ cleanupError = downloadError('download_failed', 'browser script download cleanup failed');
2710
+ throw cleanupError;
2711
+ }
2712
+ return result;
2713
+ } finally {
2714
+ if (helperArmed) {
2715
+ try {
2716
+ const cancelled = await scriptBlobCommand(cdp, 'cancel', null, deadlineAt);
2717
+ if (cancelled.status === 'cleanup_failed') {
2718
+ cleanupError = downloadError('download_failed', 'browser script download cleanup failed');
2719
+ }
2720
+ } catch (error) { cleanupError = error; }
2721
+ helperArmed = false;
2722
+ }
2723
+ }
2724
+ }, workDeadlineAt), workDeadlineAt);
2725
+ if (attempt.nativeDownloadObserved) {
2726
+ throw downloadError('download_unverifiable', 'browser download attribution is ambiguous');
2727
+ }
2728
+ if (captured.status === 'too_large') {
2729
+ throw downloadError('download_too_large', 'browser download exceeds 256 KiB');
2730
+ }
2731
+ if (captured.status !== 'ok' || typeof captured.filename !== 'string' ||
2732
+ cleanDownloadFilename(captured.filename) !== captured.filename ||
2733
+ Buffer.byteLength(captured.filename, 'utf8') > 180 ||
2734
+ typeof captured.data_base64 !== 'string' ||
2735
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(captured.data_base64)) {
2736
+ throw downloadError('download_unverifiable', 'browser download cannot verify the selected script');
2737
+ }
2738
+ const bytes = Buffer.from(captured.data_base64, 'base64');
2739
+ if (bytes.length > MAX_DOWNLOAD_BYTES) {
2740
+ throw downloadError('download_too_large', 'browser download exceeds 256 KiB');
2741
+ }
2742
+ if (bytes.length !== captured.byte_count ||
2743
+ bytes.toString('base64') !== captured.data_base64) {
2744
+ throw downloadError('download_unverifiable', 'browser download bytes could not be verified');
2745
+ }
2746
+ const current = await downloadDeadline(state(), workDeadlineAt);
2747
+ checkEpoch(args);
2748
+ if (current.active_tab_id !== tab.id || current.url !== sharedUrl ||
2749
+ tab.pendingNavigations.size) throw staleEpochError();
2750
+ response = {
2751
+ page_epoch: current.page_epoch,
2752
+ active_tab_id: current.active_tab_id,
2753
+ url: current.url,
2754
+ filename: captured.filename,
2755
+ byte_count: bytes.length,
2756
+ sha256: createHash('sha256').update(bytes).digest('hex'),
2757
+ data_base64: captured.data_base64,
2758
+ };
2759
+ } catch (error) {
2760
+ const pageChanged = epoch !== args.expected_epoch || activeTabId !== tab.id ||
2761
+ tab.page.isClosed() || tab.page.url() !== sharedUrl || tab.pendingNavigations.size > 0;
2762
+ if (pageChanged || error?.code === 'stale_epoch' || error?.code === 'download_timeout' ||
2763
+ attempt.nativeDownloadObserved) {
2764
+ shuttingDown = true;
2765
+ retireAfterReply = true;
2766
+ }
2767
+ if (['stale_epoch', 'invalid_target', 'target_not_found', 'ambiguous_target',
2768
+ 'download_timeout', 'download_too_large', 'download_failed',
2769
+ 'download_unverifiable'].includes(error?.code)) throw error;
2770
+ throw downloadError('download_failed', 'browser script download failed');
2771
+ } finally {
2772
+ try {
2773
+ await downloadDeadline(Promise.all([...orphanDownloads]), deadlineAt);
2774
+ await downloadDeadline(clearDownloadDirectory(), deadlineAt);
2775
+ await settleDownloadDirectory(deadlineAt);
2776
+ } catch (error) { cleanupError ||= error; }
2777
+ if (activeDownloadAttempt === attempt) activeDownloadAttempt = undefined;
2778
+ if (cleanupError || attempt.nativeDownloadObserved) {
2779
+ shuttingDown = true;
2780
+ retireAfterReply = true;
2781
+ if (cleanupError) {
2782
+ throw downloadError(cleanupError.code === 'download_timeout' ? 'download_timeout' : 'download_failed',
2783
+ 'browser script download cleanup failed');
2784
+ }
2785
+ throw downloadError('download_unverifiable', 'browser download attribution is ambiguous');
2786
+ }
2787
+ }
2788
+ return response;
2789
+ }
2790
+
2791
+ function fileInputArgs(args) {
2792
+ const invalid = () => targetError('invalid_request', 'invalid browser in-memory file input');
2793
+ if (!args || typeof args !== 'object' || Array.isArray(args) ||
2794
+ Object.keys(args).some(key => !['selector', 'filename', 'mime_type', 'data_base64', 'expected_epoch'].includes(key))) {
2795
+ throw invalid();
2796
+ }
2797
+ const { selector, filename, mime_type: mimeType, data_base64: dataBase64 } = args;
2798
+ if (typeof selector !== 'string' || !selector.trim() || selector.length > 512 ||
2799
+ typeof filename !== 'string' || !filename.trim() || filename.length > 128 ||
2800
+ filename === '.' || filename === '..' || /[\p{Cc}/\\:]/u.test(filename) ||
2801
+ typeof mimeType !== 'string' || mimeType.length > 128 ||
2802
+ !/^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+$/.test(mimeType) ||
2803
+ typeof dataBase64 !== 'string' || dataBase64.length > 1398104 ||
2804
+ dataBase64.length % 4 !== 0 ||
2805
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(dataBase64)) {
2806
+ throw invalid();
2807
+ }
2808
+ const buffer = Buffer.from(dataBase64, 'base64');
2809
+ if (buffer.length > 1024 * 1024 || buffer.toString('base64') !== dataBase64) throw invalid();
2810
+ return { name: filename, mimeType, buffer };
2811
+ }
2812
+
2813
+ async function waitForTarget(locator, missingMessage, deadlineAt) {
2814
+ try {
2815
+ await locator.first().waitFor({ state: 'attached', timeout: pointerTimeout(deadlineAt) });
2816
+ } catch (error) {
2817
+ if (error.name !== 'TimeoutError') throw error;
2818
+ if (deadlineAt !== undefined && Date.now() >= deadlineAt) pointerTimeout(deadlineAt);
2819
+ throw targetError('target_not_found', missingMessage);
2820
+ }
2821
+ }
2822
+
2823
+ async function targetLocator(args, page, deadlineAt) {
2824
+ let locator;
2825
+ if (args.target === undefined) {
2826
+ if (typeof args.selector !== 'string' || !args.selector.trim()) {
2827
+ throw targetError('invalid_target', 'browser action requires a selector or target');
2828
+ }
2829
+ locator = page.locator(args.selector);
2830
+ } else {
2831
+ if (args.selector !== undefined && args.selector !== null) {
2832
+ throw targetError('invalid_target', 'selector and target are mutually exclusive');
2833
+ }
2834
+ const target = args.target;
2835
+ if (!target || typeof target !== 'object' || Array.isArray(target)) {
2836
+ throw targetError('invalid_target', 'invalid browser semantic target');
2837
+ }
2838
+ const kind = target.kind;
2839
+ const allowed = kind === 'role'
2840
+ ? ['kind', 'role', 'name', 'exact', 'frame_selector']
2841
+ : kind === 'label' || kind === 'text'
2842
+ ? ['kind', 'value', 'exact', 'frame_selector']
2843
+ : null;
2844
+ if (!allowed || Object.keys(target).some(key => !allowed.includes(key)) ||
2845
+ (target.exact !== undefined && typeof target.exact !== 'boolean')) {
2846
+ throw targetError('invalid_target', 'invalid browser semantic target');
2847
+ }
2848
+ const frameSelector = semanticString(target, 'frame_selector', 512);
2849
+ let scope = page;
2850
+ if (frameSelector) {
2851
+ const owner = page.frameLocator(frameSelector).owner();
2852
+ await waitForTarget(owner, 'browser target iframe not found', deadlineAt);
2853
+ const count = await owner.count();
2854
+ if (count === 0) throw targetError('target_not_found', 'browser target iframe not found');
2855
+ if (count !== 1) {
2856
+ throw targetError('ambiguous_target', `browser target iframe matched ${count} elements`);
2857
+ }
2858
+ scope = page.frameLocator(frameSelector);
2859
+ }
2860
+ const exact = target.exact ?? true;
2861
+ if (kind === 'role') {
2862
+ const role = semanticString(target, 'role', 64, true);
2863
+ if (!/^[a-z-]+$/.test(role)) {
2864
+ throw targetError('invalid_target', 'invalid browser target role');
2865
+ }
2866
+ const name = semanticString(target, 'name', 256);
2867
+ locator = scope.getByRole(role, name === undefined ? {} : { name, exact });
2868
+ } else {
2869
+ const value = semanticString(target, 'value', 256, true);
2870
+ locator = kind === 'label'
2871
+ ? scope.getByLabel(value, { exact })
2872
+ : scope.getByText(value, { exact });
2873
+ }
2874
+ }
2875
+ await waitForTarget(locator, 'browser target not found', deadlineAt);
2876
+ const count = await locator.count();
2877
+ if (count === 0) throw targetError('target_not_found', 'browser target not found');
2878
+ if (count !== 1) {
2879
+ throw targetError('ambiguous_target', `browser target matched ${count} elements`);
2880
+ }
2881
+ return locator;
2882
+ }
2883
+
2884
+ async function withPinnedTarget(args, act, deadlineAt) {
2885
+ const page = requireActiveTab().page;
2886
+ const locator = await targetLocator(args, page, deadlineAt);
2887
+ checkEpoch(args);
2888
+ // A Locator may re-resolve after navigation while waiting for an old
2889
+ // disabled element. An ElementHandle stays bound to its document.
2890
+ const handle = await locator.elementHandle({ timeout: pointerTimeout(deadlineAt) });
2891
+ if (!handle) throw targetError('target_not_found', 'browser target not found');
2892
+ try {
2893
+ const count = await locator.count();
2894
+ if (count !== 1) {
2895
+ throw targetError(
2896
+ count === 0 ? 'target_not_found' : 'ambiguous_target',
2897
+ `browser target matched ${count} elements`,
2898
+ );
2899
+ }
2900
+ checkEpoch(args);
2901
+ return await act(handle);
2902
+ } finally {
2903
+ await handle.dispose().catch(() => {});
2904
+ }
2905
+ }
2906
+
2907
+ function pointerPoint(args, xName, yName, page) {
2908
+ const viewport = page.viewportSize();
2909
+ const x = args[xName];
2910
+ const y = args[yName];
2911
+ if (!Number.isFinite(x) || !Number.isFinite(y) ||
2912
+ x < 0 || y < 0 || x >= viewport.width || y >= viewport.height) {
2913
+ throw targetError('invalid_request', 'browser pointer coordinate is outside the viewport');
2914
+ }
2915
+ return { x, y };
2916
+ }
2917
+
2918
+ function pointerSelector(value) {
2919
+ if (typeof value !== 'string' || !value.trim() || value.length > 512) {
2920
+ throw targetError('invalid_request', 'invalid browser pointer selector');
2921
+ }
2922
+ return value;
2923
+ }
2924
+
2925
+ function pointerButton(value) {
2926
+ const button = value ?? 'left';
2927
+ if (!['left', 'right', 'middle'].includes(button)) {
2928
+ throw targetError('invalid_request', 'invalid browser pointer button');
2929
+ }
2930
+ return button;
2931
+ }
2932
+
2933
+ async function assertDragPoint(handle, point, deadlineAt, trial) {
2934
+ const hitsTarget = () => handle.evaluate((element, { x, y }) => {
2935
+ let hit = element.ownerDocument.elementFromPoint(x, y);
2936
+ while (hit?.shadowRoot) {
2937
+ const inner = hit.shadowRoot.elementFromPoint(x, y);
2938
+ if (!inner || inner === hit) break;
2939
+ hit = inner;
2940
+ }
2941
+ for (let node = hit; node; node = node.parentNode ?? node.getRootNode()?.host) {
2942
+ if (node === element) return true;
2943
+ }
2944
+ return false;
2945
+ }, point);
2946
+ pointerTimeout(deadlineAt);
2947
+ try {
2948
+ if (!await hitsTarget()) throw new Error('pointer intercepted');
2949
+ // Trial performs Playwright's receives-events checks before mouse-down.
2950
+ // During an active drag, use the exact hit test without altering mouse state.
2951
+ if (trial) await handle.click({ trial: true, scroll: 'none', timeout: pointerTimeout(deadlineAt) });
2952
+ if (!await hitsTarget()) throw new Error('pointer intercepted');
2953
+ } catch {
2954
+ throw targetError('target_not_actionable', 'browser drag target is obscured or detached');
2955
+ }
2956
+ }
2957
+
2958
+ function navigationResponseKind(response) {
2959
+ const status = response.status();
2960
+ if ([301, 302, 303, 307, 308].includes(status)) return 'redirect';
2961
+ if (status === 204 || status === 205 ||
2962
+ /^\s*attachment(?:\s*;|\s*$)/i.test(response.headers()['content-disposition'] ?? '')) {
2963
+ return 'no_document';
2964
+ }
2965
+ return null;
2966
+ }
2967
+
2968
+ async function observeActionNavigation(page, deadlineAt) {
2969
+ let started = false;
2970
+ let committed = false;
2971
+ let failed = false;
2972
+ const pendingRequests = new Map();
2973
+ let revision = 0;
2974
+ let observedPage = page;
2975
+ let blankPopupExpected = false;
2976
+ let pendingPopupOpens = 0;
2977
+ const listeners = [];
2978
+ let cdp;
2979
+ const onWindowOpen = event => {
2980
+ // Playwright's popup/page events can be delayed until a slow destination
2981
+ // response starts. CDP reports window.open at the triggering gesture.
2982
+ started = true;
2983
+ committed = false;
2984
+ failed = false;
2985
+ pendingRequests.clear();
2986
+ blankPopupExpected = !event.url || event.url === 'about:blank';
2987
+ pendingPopupOpens++;
2988
+ revision++;
2989
+ };
2990
+ const watch = (target, popup = false) => {
2991
+ if (listeners.some(item => item.page === target)) return;
2992
+ if (popup) {
2993
+ // adoptPage activates popups before their navigation commits. An initial
2994
+ // about:blank page is not the destination of window.open(url).
2995
+ observedPage = target;
2996
+ started = true;
2997
+ committed = target.url() !== 'about:blank' || blankPopupExpected;
2998
+ failed = false;
2999
+ pendingRequests.clear();
3000
+ revision++;
3001
+ }
3002
+ const onRequest = request => {
3003
+ if (target !== observedPage || (target === page && pendingPopupOpens) ||
3004
+ !request.isNavigationRequest()) return;
3005
+ started = true;
3006
+ committed = false;
3007
+ failed = false;
3008
+ let frame = null;
3009
+ try { frame = request.frame(); } catch { /* A new frame may not exist yet. */ }
3010
+ const redirectedFrom = request.redirectedFrom();
3011
+ if (redirectedFrom) pendingRequests.delete(redirectedFrom);
3012
+ pendingRequests.set(request, frame);
3013
+ revision++;
3014
+ };
3015
+ const onFailed = request => {
3016
+ if (target !== observedPage || (target === page && pendingPopupOpens) ||
3017
+ !pendingRequests.has(request)) return;
3018
+ const frame = pendingRequests.get(request);
3019
+ pendingRequests.delete(request);
3020
+ // A newer request for the same frame supersedes this failure.
3021
+ if (![...pendingRequests.values()].includes(frame)) failed = true;
3022
+ revision++;
3023
+ };
3024
+ const onFinished = request => {
3025
+ if (target !== observedPage || (target === page && pendingPopupOpens) ||
3026
+ !pendingRequests.has(request)) return;
3027
+ // A redirect remains pending until its successor request arrives. A
3028
+ // 204/205/download has no document commit, so it completes here.
3029
+ const kind = tabByPage.get(target)?.navigationResponses.get(request);
3030
+ if (kind === 'redirect' || (pendingRequests.get(request) !== null && kind !== 'no_document')) return;
3031
+ pendingRequests.delete(request);
3032
+ committed = pendingRequests.size === 0;
3033
+ revision++;
3034
+ };
3035
+ const onFrame = frame => {
3036
+ if (target !== observedPage) return;
3037
+ if (target === page && pendingPopupOpens) return;
3038
+ if (target !== page && frame === target.mainFrame() &&
3039
+ frame.url() === 'about:blank' && !blankPopupExpected) return;
3040
+ for (const [request, requestedFrame] of pendingRequests) {
3041
+ if (requestedFrame === frame) pendingRequests.delete(request);
3042
+ }
3043
+ started = true;
3044
+ committed = pendingRequests.size === 0;
3045
+ revision++;
3046
+ };
3047
+ const onClose = () => {
3048
+ if (target !== observedPage || (target === page && pendingPopupOpens)) return;
3049
+ failed = true;
3050
+ revision++;
3051
+ };
3052
+ target.on('request', onRequest);
3053
+ target.on('requestfailed', onFailed);
3054
+ target.on('requestfinished', onFinished);
3055
+ target.on('framenavigated', onFrame);
3056
+ target.on('close', onClose);
3057
+ listeners.push({ page: target, onRequest, onFailed, onFinished, onFrame, onClose });
3058
+ // Adopted pages track navigation requests from their creation. A slow
3059
+ // request may already be in flight before this action subscribes.
3060
+ const inFlight = tabByPage.get(target)?.pendingNavigations;
3061
+ if (inFlight?.size) {
3062
+ for (const [request, frame] of inFlight) pendingRequests.set(request, frame);
3063
+ started = true;
3064
+ committed = false;
3065
+ revision++;
3066
+ }
3067
+ };
3068
+ const onPopup = target => {
3069
+ if (pendingPopupOpens) pendingPopupOpens--;
3070
+ watch(target, true);
3071
+ };
3072
+ const dispose = () => {
3073
+ cdp?.off('Page.windowOpen', onWindowOpen);
3074
+ page.off('popup', onPopup);
3075
+ for (const { page: target, onRequest, onFailed, onFinished, onFrame, onClose } of listeners) {
3076
+ target.off('request', onRequest);
3077
+ target.off('requestfailed', onFailed);
3078
+ target.off('requestfinished', onFinished);
3079
+ target.off('framenavigated', onFrame);
3080
+ target.off('close', onClose);
3081
+ }
3082
+ };
3083
+ // A navigation request can start before CDP setup finishes while the old
3084
+ // document still owns the epoch. Observe Playwright events first so a
3085
+ // pointer action cannot run into that in-flight navigation.
3086
+ watch(page);
3087
+ page.on('popup', onPopup);
3088
+ try {
3089
+ cdp = await tabByPage.get(page)?.cdp;
3090
+ if (!cdp) throw targetError('browser_error', 'browser page navigation observer unavailable');
3091
+ cdp.on('Page.windowOpen', onWindowOpen);
3092
+ await cdp.send('Page.enable');
3093
+ if (TEST_OBSERVER_SETUP_DELAY_MS) {
3094
+ emit({ event: 'test_observer_setup_waiting' });
3095
+ await new Promise(resolve => setTimeout(resolve, TEST_OBSERVER_SETUP_DELAY_MS));
3096
+ }
3097
+ } catch (error) {
3098
+ dispose();
3099
+ throw error;
3100
+ }
3101
+ return {
3102
+ get started() { return started; },
3103
+ async finish() {
3104
+ // A newly committed document can immediately request another navigation.
3105
+ // Each request invalidates the prior commit; return only after the latest
3106
+ // request commits and navigation events have settled for one short turn.
3107
+ const deadline = Math.min(deadlineAt ?? Infinity, Date.now() + 20_000);
3108
+ if (Date.now() >= deadline) {
3109
+ throw targetError('navigation_timeout', 'browser pointer action timed out');
3110
+ }
3111
+ let observedRevision = revision;
3112
+ while (Date.now() < deadline) {
3113
+ await new Promise(resolve => setTimeout(resolve, 50));
3114
+ if (observedRevision !== revision) {
3115
+ observedRevision = revision;
3116
+ continue;
3117
+ }
3118
+ if (failed) break;
3119
+ if (!pendingPopupOpens && (!started || committed)) return;
3120
+ }
3121
+ if (deadlineAt !== undefined && Date.now() >= deadlineAt) pointerTimeout(deadlineAt);
3122
+ if (!failed && (pendingPopupOpens || (started && !committed))) {
3123
+ throw targetError('navigation_timeout', 'browser navigation did not complete');
3124
+ }
3125
+ if (failed) throw targetError('navigation_failed', 'browser navigation failed');
3126
+ },
3127
+ dispose,
3128
+ };
3129
+ }
3130
+
3131
+ async function hoverWithNavigation(page, expectedEpoch, hover, deadlineAt) {
3132
+ pointerTimeout(deadlineAt);
3133
+ const navigation = await observeActionNavigation(page, deadlineAt);
3134
+ try {
3135
+ if (expectedEpoch !== epoch) throw staleEpochError();
3136
+ if (!navigation.started) {
3137
+ try { await hover(navigation); } catch (error) {
3138
+ if (!navigation.started && expectedEpoch === epoch) throw error;
3139
+ }
3140
+ }
3141
+ await navigation.finish();
3142
+ } finally {
3143
+ navigation.dispose();
3144
+ }
3145
+ }
3146
+
3147
+ async function dragBetween(page, source, destination, expectedEpoch, button = 'left', deadlineAt, existingNavigation, validateTarget) {
3148
+ if (expectedEpoch !== epoch) throw staleEpochError();
3149
+ pointerTimeout(deadlineAt);
3150
+ const navigation = existingNavigation ?? await observeActionNavigation(page, deadlineAt);
3151
+ const ownsNavigation = !existingNavigation;
3152
+ const interrupted = () => expectedEpoch !== epoch || navigation.started;
3153
+ let downAttempted = false;
3154
+ let safeDrop = false;
3155
+ let failure;
3156
+ try {
3157
+ if (expectedEpoch !== epoch) throw staleEpochError();
3158
+ if (!navigation.started) {
3159
+ try {
3160
+ if (validateTarget) await validateTarget('source', source);
3161
+ pointerTimeout(deadlineAt);
3162
+ await page.mouse.move(source.x, source.y);
3163
+ if (!interrupted()) {
3164
+ if (validateTarget) await validateTarget('source', source);
3165
+ pointerTimeout(deadlineAt);
3166
+ downAttempted = true;
3167
+ await page.mouse.down({ button });
3168
+ let current = source;
3169
+ if (!interrupted() && typeof destination === 'function') {
3170
+ const viewport = page.viewportSize();
3171
+ current = {
3172
+ x: source.x + (source.x + 8 < viewport.width ? 8 : -8),
3173
+ y: source.y + (source.y + 8 < viewport.height ? 8 : -8),
3174
+ };
3175
+ pointerTimeout(deadlineAt);
3176
+ await page.mouse.move(current.x, current.y);
3177
+ if (!interrupted()) destination = await destination();
3178
+ }
3179
+ if (!interrupted()) {
3180
+ if (validateTarget) await validateTarget('destination', destination);
3181
+ for (let step = 1; step <= 12; step++) {
3182
+ if (interrupted()) break;
3183
+ pointerTimeout(deadlineAt);
3184
+ await page.mouse.move(
3185
+ current.x + (destination.x - current.x) * step / 12,
3186
+ current.y + (destination.y - current.y) * step / 12,
3187
+ );
3188
+ }
3189
+ if (!interrupted()) {
3190
+ if (validateTarget) await validateTarget('destination', destination);
3191
+ safeDrop = true;
3192
+ }
3193
+ }
3194
+ }
3195
+ } catch (error) {
3196
+ if (!interrupted()) failure = error;
3197
+ } finally {
3198
+ if (downAttempted) {
3199
+ // Clear button state without finishing a rejected gesture over an
3200
+ // unrelated overlay or on a new page.
3201
+ if (interrupted() || !safeDrop) await page.mouse.move(-1, -1).catch(() => {});
3202
+ await page.mouse.up({ button }).catch(() => {});
3203
+ }
3204
+ }
3205
+ }
3206
+ if (ownsNavigation) await navigation.finish();
3207
+ if (failure) throw failure;
3208
+ } finally {
3209
+ if (ownsNavigation) navigation.dispose();
3210
+ }
3211
+ }
3212
+
3213
+ function activateTab(tab) {
3214
+ if (activeTabId === tab.id) return;
3215
+ activeTabId = tab.id;
3216
+ advanceEpoch();
3217
+ }
3218
+
3219
+ function adoptPage(target) {
3220
+ if (shuttingDown) {
3221
+ void target.close().catch(() => {});
3222
+ return null;
3223
+ }
3224
+ const existing = tabByPage.get(target);
3225
+ if (existing) return existing;
3226
+ if (tabs.length >= MAX_TABS) {
3227
+ void target.close().catch(() => {});
3228
+ return null;
3229
+ }
3230
+ const tab = {
3231
+ id: randomBytes(12).toString('hex'),
3232
+ page: target,
3233
+ cdp: context.newCDPSession(target).catch(() => null),
3234
+ title: '',
3235
+ pendingNavigations: new Map(),
3236
+ navigationResponses: new WeakMap(),
3237
+ pendingDocumentResponse: null,
3238
+ mainDocumentResponse: null,
3239
+ mainDocumentUrl: null,
3240
+ };
3241
+ tabs.push(tab);
3242
+ tabByPage.set(target, tab);
3243
+ runtime.recordPage(api, target, false);
3244
+ target.setDefaultTimeout(10_000);
3245
+ target.on('domcontentloaded', () => {
3246
+ void target.title().then(title => { tab.title = title; }).catch(() => {});
3247
+ });
3248
+ target.on('request', request => {
3249
+ if (!request.isNavigationRequest()) return;
3250
+ let frame = null;
3251
+ try { frame = request.frame(); } catch { /* A new frame may not exist yet. */ }
3252
+ const redirectedFrom = request.redirectedFrom();
3253
+ if (redirectedFrom) tab.pendingNavigations.delete(redirectedFrom);
3254
+ tab.pendingNavigations.set(request, frame);
3255
+ });
3256
+ target.on('response', response => {
3257
+ const kind = navigationResponseKind(response);
3258
+ if (kind) tab.navigationResponses.set(response.request(), kind);
3259
+ try {
3260
+ if (response.request().isNavigationRequest() && response.frame() === target.mainFrame()) {
3261
+ tab.pendingDocumentResponse = response;
3262
+ }
3263
+ } catch { /* A response without a committed main frame is not authoritative. */ }
3264
+ });
3265
+ target.on('requestfailed', request => tab.pendingNavigations.delete(request));
3266
+ target.on('download', download => onPageDownload(target, download));
3267
+ target.on('requestfinished', request => {
3268
+ if (!tab.pendingNavigations.has(request)) return;
3269
+ const kind = tab.navigationResponses.get(request);
3270
+ if (kind !== 'redirect' && (tab.pendingNavigations.get(request) === null || kind === 'no_document')) {
3271
+ tab.pendingNavigations.delete(request);
3272
+ }
3273
+ });
3274
+ target.on('dialog', dialog => captureDialog(tab, dialog));
3275
+ target.on('framenavigated', frame => {
3276
+ const mainFrame = target.mainFrame();
3277
+ const pendingMainRequest = frame === mainFrame && [...tab.pendingNavigations]
3278
+ .reverse().find(([, requestedFrame]) => requestedFrame === frame || requestedFrame === null)?.[0];
3279
+ const hadDocumentRequest = Boolean(pendingMainRequest);
3280
+ for (const [request, requestedFrame] of tab.pendingNavigations) {
3281
+ if (requestedFrame === frame) tab.pendingNavigations.delete(request);
3282
+ }
3283
+ if (frame === mainFrame) {
3284
+ const url = frame.url();
3285
+ const committedUrl = url.split('#', 1)[0];
3286
+ const response = hadDocumentRequest &&
3287
+ tab.pendingDocumentResponse?.request() === pendingMainRequest &&
3288
+ tab.pendingDocumentResponse.url() === committedUrl
3289
+ ? tab.pendingDocumentResponse : null;
3290
+ if (response) {
3291
+ tab.mainDocumentResponse = response;
3292
+ tab.mainDocumentUrl = committedUrl;
3293
+ } else if (!hadDocumentRequest && tab.mainDocumentResponse &&
3294
+ tab.mainDocumentUrl && committedUrl.startsWith('http')) {
3295
+ // Hash/history API transitions keep the same document and enforcing
3296
+ // response policy. A new document request without a matching response
3297
+ // still loses provenance and fails closed at download time.
3298
+ try {
3299
+ if (new URL(committedUrl).origin === new URL(tab.mainDocumentUrl).origin) {
3300
+ tab.mainDocumentUrl = committedUrl;
3301
+ } else {
3302
+ tab.mainDocumentResponse = null;
3303
+ tab.mainDocumentUrl = null;
3304
+ }
3305
+ } catch {
3306
+ tab.mainDocumentResponse = null;
3307
+ tab.mainDocumentUrl = null;
3308
+ }
3309
+ } else {
3310
+ tab.mainDocumentResponse = null;
3311
+ tab.mainDocumentUrl = null;
3312
+ }
3313
+ tab.pendingDocumentResponse = null;
3314
+ if (url !== 'about:blank') {
3315
+ try { checkUrl(url); } catch { void target.goto('about:blank').catch(() => {}); }
3316
+ }
3317
+ }
3318
+ // Every frame navigation invalidates coordinates and semantic targets in
3319
+ // the active view, including iframe content.
3320
+ if (activeTabId === tab.id) advanceEpoch();
3321
+ });
3322
+ target.on('close', () => {
3323
+ if (pendingDialog?.tabId === tab.id) expireDialog(pendingDialog);
3324
+ const closedIndex = tabs.indexOf(tab);
3325
+ tabs = tabs.filter(candidate => candidate !== tab);
3326
+ if (activeTabId !== tab.id) return;
3327
+ activeTabId = tabs[Math.min(closedIndex, tabs.length - 1)]?.id;
3328
+ if (!shuttingDown) {
3329
+ advanceEpoch();
3330
+ }
3331
+ });
3332
+ // A popup becomes the visible workbench tab. Explicit new tabs use this same
3333
+ // path, so a page cannot exist without an opaque ID and navigation guard.
3334
+ activateTab(tab);
3335
+ return tab;
3336
+ }
3337
+
3338
+ async function answerDialog(args = {}) {
3339
+ const pending = pendingDialog;
3340
+ if (!pending || pending.expired || args.dialog_id !== pending.id) {
3341
+ throw dialogError('stale_dialog', 'browser dialog is no longer pending');
3342
+ }
3343
+ if (args.expected_epoch !== pending.pageEpoch || epoch !== pending.pageEpoch ||
3344
+ !tabs.some(tab => tab.id === pending.tabId && !tab.page.isClosed())) {
3345
+ throw staleEpochError();
3346
+ }
3347
+ // Rust serializes an omitted Option<String> as null. Both null and an
3348
+ // absent field mean "use the page's prompt default" or no alert text.
3349
+ const text = args.text == null ? undefined : args.text;
3350
+ if (typeof args.accept !== 'boolean' ||
3351
+ (text !== undefined && (pending.type !== 'prompt' || !args.accept ||
3352
+ typeof text !== 'string' || text.length > MAX_DIALOG_CHARS))) {
3353
+ throw dialogError('invalid_request', 'invalid browser dialog response');
3354
+ }
3355
+ clearTimeout(pending.timer);
3356
+ pendingDialog = undefined;
3357
+ const owner = pending.owner;
3358
+ let nextDialog;
3359
+ if (owner && !owner.settled) {
3360
+ nextDialog = new Promise(resolve => { owner.notify = resolve; });
3361
+ }
3362
+ try {
3363
+ if (args.accept) {
3364
+ await pending.dialog.accept(pending.type === 'prompt' ? (text ?? pending.defaultValue) : undefined);
3365
+ } else {
3366
+ await pending.dialog.dismiss();
3367
+ }
3368
+ } catch {
3369
+ throw dialogError('browser_error', 'browser dialog response failed');
3370
+ }
3371
+ if (owner && !owner.settled) {
3372
+ const outcome = await Promise.race([
3373
+ owner.done,
3374
+ nextDialog.then(() => ({ kind: 'dialog' })),
3375
+ ]);
3376
+ owner.notify = undefined;
3377
+ if (pendingDialog) return dialogState();
3378
+ if (outcome.kind === 'error') {
3379
+ throw dialogError('browser_error', 'browser action failed after dialog response');
3380
+ }
3381
+ }
3382
+ return stateAfterDialog();
3383
+ }
3384
+
3385
+ async function stateAfterDialog() {
3386
+ if (pendingDialog) return dialogState();
3387
+ let notify;
3388
+ const nextDialog = new Promise(resolve => {
3389
+ notify = resolve;
3390
+ dialogWaiters.add(resolve);
3391
+ });
3392
+ try {
3393
+ const outcome = await Promise.race([
3394
+ (async () => {
3395
+ if (TEST_DIALOG_STATE_DELAY_MS) {
3396
+ await new Promise(resolve => setTimeout(resolve, TEST_DIALOG_STATE_DELAY_MS));
3397
+ }
3398
+ return state();
3399
+ })().then(result => ({ result }), error => ({ error })),
3400
+ nextDialog.then(() => ({ dialog: true })),
3401
+ ]);
3402
+ if (pendingDialog || outcome.dialog) return dialogState();
3403
+ if (outcome.error) throw outcome.error;
3404
+ return outcome.result;
3405
+ } finally {
3406
+ dialogWaiters.delete(notify);
3407
+ }
3408
+ }
3409
+
3410
+ async function dispatch(action, args = {}) {
3411
+ if (action === 'dialog_respond') return answerDialog(args);
3412
+ if (action === 'close') {
3413
+ if (pendingDialog) expireDialog(pendingDialog);
3414
+ return command(action, args);
3415
+ }
3416
+ if (pendingDialog || inFlightAction) {
3417
+ if (action === 'state' || action === 'tab_list') return dialogState();
3418
+ throw dialogError('dialog_pending', 'answer the pending browser dialog first');
3419
+ }
3420
+ // These reads bypass commandTail, so they must not acquire mutation
3421
+ // ownership. Keep dialog-aware, epoch-stable reads without rejecting a
3422
+ // concurrent write merely because its metadata read is still in flight.
3423
+ if (action === 'state' || action === 'tab_list') return stateAfterDialog();
3424
+ const owner = { settled: false, hadDialog: false };
3425
+ const nextDialog = new Promise(resolve => { owner.notify = resolve; });
3426
+ inFlightAction = owner;
3427
+ owner.done = Promise.resolve().then(() => command(action, args)).then(
3428
+ result => ({ kind: 'done', result }),
3429
+ error => ({ kind: 'error', error }),
3430
+ );
3431
+ void owner.done.then(() => {
3432
+ owner.settled = true;
3433
+ if (inFlightAction === owner) inFlightAction = undefined;
3434
+ if (pendingDialog?.owner === owner && pendingDialog.expired) pendingDialog = undefined;
3435
+ });
3436
+ const outcome = await Promise.race([
3437
+ owner.done,
3438
+ nextDialog.then(() => ({ kind: 'dialog' })),
3439
+ ]);
3440
+ owner.notify = undefined;
3441
+ if (pendingDialog) {
3442
+ if (action === 'dom' || action === 'screenshot') {
3443
+ throw dialogError('dialog_pending', 'answer the pending browser dialog first');
3444
+ }
3445
+ return dialogState();
3446
+ }
3447
+ if (outcome.kind === 'error') {
3448
+ if (owner.hadDialog) {
3449
+ throw dialogError('browser_error', 'browser action failed after dialog');
3450
+ }
3451
+ throw outcome.error;
3452
+ }
3453
+ return outcome.result;
3454
+ }
3455
+
3456
+ async function command(action, args = {}) {
3457
+ switch (action) {
3458
+ case 'state':
3459
+ case 'tab_list':
3460
+ return state();
3461
+ case 'tab_create':
3462
+ checkEpoch(args);
3463
+ if (tabs.length >= MAX_TABS) {
3464
+ const error = new Error('browser tab limit reached');
3465
+ error.code = 'invalid_request';
3466
+ throw error;
3467
+ }
3468
+ var targetUrl = args.url === undefined ? null : checkUrl(args.url);
3469
+ var previousActiveTabId = activeTabId;
3470
+ var createdPage = await runtime.createPage(api, false);
3471
+ adoptPage(createdPage);
3472
+ if (targetUrl) {
3473
+ try {
3474
+ await createdPage.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 20_000 });
3475
+ } catch (error) {
3476
+ await createdPage.close().catch(() => {});
3477
+ const previousTab = tabs.find(tab => tab.id === previousActiveTabId);
3478
+ if (previousTab) activateTab(previousTab);
3479
+ throw error;
3480
+ }
3481
+ }
3482
+ return state();
3483
+ case 'tab_activate': {
3484
+ checkEpoch(args);
3485
+ const tabId = requireTabId(args.tab_id);
3486
+ const tab = tabs.find(tab => tab.id === tabId);
3487
+ if (!tab) {
3488
+ const error = new Error('browser tab not found');
3489
+ error.code = 'invalid_request';
3490
+ throw error;
3491
+ }
3492
+ activateTab(tab);
3493
+ return state();
3494
+ }
3495
+ case 'tab_close': {
3496
+ checkEpoch(args);
3497
+ const tabId = requireTabId(args.tab_id);
3498
+ const tab = tabs.find(tab => tab.id === tabId);
3499
+ if (!tab) {
3500
+ const error = new Error('browser tab not found');
3501
+ error.code = 'invalid_request';
3502
+ throw error;
3503
+ }
3504
+ await tab.page.close();
3505
+ return state();
3506
+ }
3507
+ case 'navigate':
3508
+ checkEpoch(args);
3509
+ var url = checkUrl(args.url);
3510
+ var createdFirstPage = !activeTab();
3511
+ var page = createdFirstPage ? await runtime.createPage(api, false) : requireActiveTab().page;
3512
+ if (createdFirstPage) adoptPage(page);
3513
+ try {
3514
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 20_000 });
3515
+ } catch (error) {
3516
+ if (createdFirstPage) await page.close().catch(() => {});
3517
+ throw error;
3518
+ }
3519
+ return state();
3520
+ case 'history':
3521
+ checkEpoch(args);
3522
+ page = requireActiveTab().page;
3523
+ if (args.direction === 'back') await page.goBack({ waitUntil: 'domcontentloaded', timeout: 20_000 });
3524
+ else if (args.direction === 'forward') await page.goForward({ waitUntil: 'domcontentloaded', timeout: 20_000 });
3525
+ else if (args.direction === 'reload') await page.reload({ waitUntil: 'domcontentloaded', timeout: 20_000 });
3526
+ else throw new Error('invalid history direction');
3527
+ return state();
3528
+ case 'viewport':
3529
+ checkEpoch(args);
3530
+ page = requireActiveTab().page;
3531
+ if (!Number.isInteger(args.width) || !Number.isInteger(args.height) ||
3532
+ args.width < 320 || args.width > 1200 || args.height < 240 || args.height > 1000) {
3533
+ throw new Error('viewport must be within 320..1200 by 240..1000 CSS pixels');
3534
+ }
3535
+ if (page.viewportSize().width !== args.width || page.viewportSize().height !== args.height) {
3536
+ await page.setViewportSize({ width: args.width, height: args.height });
3537
+ // Frame coordinates from the prior viewport must not be applied to
3538
+ // the resized page, even if its URL has not changed.
3539
+ advanceEpoch();
3540
+ }
3541
+ return state();
3542
+ case 'input':
3543
+ checkEpoch(args);
3544
+ page = requireActiveTab().page;
3545
+ if (args.kind === 'click') {
3546
+ await page.mouse.click(args.x, args.y, { button: args.button || 'left' });
3547
+ } else if (args.kind === 'scroll') {
3548
+ await page.mouse.move(args.x, args.y);
3549
+ await page.mouse.wheel(args.delta_x, args.delta_y);
3550
+ } else if (args.kind === 'type') {
3551
+ await page.keyboard.insertText(args.text);
3552
+ } else if (args.kind === 'key') {
3553
+ await page.keyboard.press(args.key);
3554
+ } else {
3555
+ throw new Error('invalid input kind');
3556
+ }
3557
+ return state();
3558
+ case 'dom': {
3559
+ if (TEST_DIALOG_READ_DELAY_MS) {
3560
+ await new Promise(resolve => setTimeout(resolve, TEST_DIALOG_READ_DELAY_MS));
3561
+ }
3562
+ return stableRead(async tab => {
3563
+ const page = tab.page;
3564
+ const snapshot = await page.ariaSnapshot({ mode: 'ai', depth: 12, timeout: 10_000 });
3565
+ const html = await page.content();
3566
+ return {
3567
+ title: await page.title(),
3568
+ snapshot: bounded(snapshot, MAX_SNAPSHOT_CHARS),
3569
+ html: bounded(html, MAX_HTML_CHARS),
3570
+ snapshot_truncated: snapshot.length > MAX_SNAPSHOT_CHARS,
3571
+ html_truncated: html.length > MAX_HTML_CHARS,
3572
+ };
3573
+ });
3574
+ }
3575
+ case 'click_selector':
3576
+ checkEpoch(args);
3577
+ await withPinnedTarget(args, handle => handle.click({ timeout: 10_000 }));
3578
+ return state();
3579
+ case 'fill_selector':
3580
+ checkEpoch(args);
3581
+ await withPinnedTarget(args, handle => handle.fill(args.text, { timeout: 10_000 }));
3582
+ return state();
3583
+ case 'press_selector':
3584
+ checkEpoch(args);
3585
+ if (args.selector || args.target !== undefined) {
3586
+ await withPinnedTarget(args, handle => handle.press(args.key, { timeout: 10_000 }));
3587
+ } else {
3588
+ await requireActiveTab().page.keyboard.press(args.key);
3589
+ }
3590
+ return state();
3591
+ case 'select_option': {
3592
+ checkEpoch(args);
3593
+ const values = selectOptionArgs(args);
3594
+ try {
3595
+ const selectedValues = await withPinnedTarget(args, async handle => {
3596
+ const identity = await handle.evaluate(element => ({
3597
+ tag_name: element.tagName,
3598
+ multiple: element.multiple,
3599
+ }));
3600
+ if (identity.tag_name !== 'SELECT') {
3601
+ throw targetError('invalid_target', 'browser select target must be a native select element');
3602
+ }
3603
+ if (!identity.multiple && values.length > 1) {
3604
+ throw targetError('invalid_target', 'single-select target accepts exactly one value');
3605
+ }
3606
+ return handle.selectOption(values, { timeout: 10_000 });
3607
+ });
3608
+ return { ...await state(), selected_values: selectedValues };
3609
+ } catch (error) {
3610
+ if (['invalid_target', 'target_not_found', 'ambiguous_target', 'stale_epoch'].includes(error?.code)) {
3611
+ throw error;
3612
+ }
3613
+ // Playwright's call log can quote option values. Keep the failure
3614
+ // actionable without copying page data into the tool error.
3615
+ throw targetError('selection_failed', 'browser select option failed; refresh the page and retry');
3616
+ }
3617
+ }
3618
+ case 'download': {
3619
+ const deadlineAt = Date.now() + DOWNLOAD_ACTION_BUDGET_MS;
3620
+ try {
3621
+ return await boundedDownload(args, deadlineAt);
3622
+ } catch (error) {
3623
+ if (error?.code !== 'download_unverifiable' ||
3624
+ error.scriptFallbackEligible !== true || retireAfterReply) throw error;
3625
+ // Initial inspection failed before any private navigation or download
3626
+ // request. The Blob helper independently requires a unique non-link
3627
+ // target; a direct attempt that progressed past inspection never
3628
+ // authorizes a second click after a same-epoch DOM replacement.
3629
+ return boundedScriptBlobDownload(args, deadlineAt);
3630
+ }
3631
+ }
3632
+ case 'set_file_input': {
3633
+ checkEpoch(args);
3634
+ const file = fileInputArgs(args);
3635
+ try {
3636
+ await withPinnedTarget(args, async handle => {
3637
+ const isFileInput = await handle.evaluate(element =>
3638
+ element instanceof HTMLInputElement && element.type === 'file');
3639
+ if (!isFileInput) {
3640
+ throw targetError('invalid_target', 'browser target must be a file input');
3641
+ }
3642
+ await handle.setInputFiles(file, { timeout: 10_000 });
3643
+ });
3644
+ return state();
3645
+ } catch (error) {
3646
+ if (['invalid_request', 'invalid_target', 'stale_epoch'].includes(error?.code)) throw error;
3647
+ // Playwright errors may quote the filename or page content.
3648
+ throw targetError('file_input_failed', 'browser file input failed; refresh the page and retry');
3649
+ }
3650
+ }
3651
+ case 'hover_selector': {
3652
+ const deadlineAt = Date.now() + POINTER_ACTION_BUDGET_MS;
3653
+ checkEpoch(args);
3654
+ page = requireActiveTab().page;
3655
+ await hoverWithNavigation(page, args.expected_epoch,
3656
+ navigation => withPinnedTarget(args, async handle => {
3657
+ if (navigation.started) return;
3658
+ await handle.scrollIntoViewIfNeeded({ timeout: pointerTimeout(deadlineAt) });
3659
+ // The scroll handler may start a navigation while the old document
3660
+ // still owns the epoch. Never let hover's own scrolling hide that gap.
3661
+ await new Promise(resolve => setTimeout(resolve, 50));
3662
+ if (navigation.started) return;
3663
+ if (args.expected_epoch !== epoch) throw staleEpochError();
3664
+ await handle.hover({ scroll: 'none', timeout: pointerTimeout(deadlineAt) });
3665
+ }, deadlineAt), deadlineAt);
3666
+ return state();
3667
+ }
3668
+ case 'hover_at': {
3669
+ const deadlineAt = Date.now() + POINTER_ACTION_BUDGET_MS;
3670
+ checkEpoch(args);
3671
+ page = requireActiveTab().page;
3672
+ const hoverPoint = pointerPoint(args, 'x', 'y', page);
3673
+ checkEpoch(args);
3674
+ await hoverWithNavigation(page, args.expected_epoch,
3675
+ () => page.mouse.move(hoverPoint.x, hoverPoint.y), deadlineAt);
3676
+ return state();
3677
+ }
3678
+ case 'drag_selector': {
3679
+ const deadlineAt = Date.now() + POINTER_ACTION_BUDGET_MS;
3680
+ checkEpoch(args);
3681
+ page = requireActiveTab().page;
3682
+ const sourceSelector = pointerSelector(args.source_selector);
3683
+ const targetSelector = pointerSelector(args.target_selector);
3684
+ const navigation = await observeActionNavigation(page, deadlineAt);
3685
+ try {
3686
+ checkEpoch(args);
3687
+ try {
3688
+ await withPinnedTarget({ selector: sourceSelector, expected_epoch: args.expected_epoch }, async source => {
3689
+ await withPinnedTarget({ selector: targetSelector, expected_epoch: args.expected_epoch }, async destination => {
3690
+ await source.scrollIntoViewIfNeeded({ timeout: pointerTimeout(deadlineAt) });
3691
+ // A page scroll handler can start navigation before the first
3692
+ // mouse event, while the old document still owns the epoch.
3693
+ await new Promise(resolve => setTimeout(resolve, 50));
3694
+ if (navigation.started || args.expected_epoch !== epoch) return;
3695
+ const from = await source.boundingBox();
3696
+ const to = await destination.boundingBox();
3697
+ if (!from || !to) throw targetError('target_not_found', 'browser drag target is detached');
3698
+ const start = pointerPoint({ x: from.x + from.width / 2, y: from.y + from.height / 2 }, 'x', 'y', page);
3699
+ const viewport = page.viewportSize();
3700
+ const targetX = to.x + to.width / 2;
3701
+ const targetY = to.y + to.height / 2;
3702
+ const targetVisible = targetX >= 0 && targetY >= 0 &&
3703
+ targetX < viewport.width && targetY < viewport.height;
3704
+ const end = targetVisible
3705
+ ? pointerPoint({ x: targetX, y: targetY }, 'x', 'y', page)
3706
+ : async () => {
3707
+ // Begin the drag on the visible source before scrolling a distant
3708
+ // destination into view; both elements need not fit together.
3709
+ await destination.scrollIntoViewIfNeeded({ timeout: pointerTimeout(deadlineAt) });
3710
+ const box = await destination.boundingBox();
3711
+ if (!box) throw targetError('target_not_found', 'browser drag target is detached');
3712
+ return pointerPoint({ x: box.x + box.width / 2, y: box.y + box.height / 2 }, 'x', 'y', page);
3713
+ };
3714
+ checkEpoch(args);
3715
+ await dragBetween(page, start, end, args.expected_epoch, 'left', deadlineAt, navigation,
3716
+ (kind, point) => assertDragPoint(kind === 'source' ? source : destination, point, deadlineAt,
3717
+ kind === 'source'));
3718
+ }, deadlineAt);
3719
+ }, deadlineAt);
3720
+ } catch (error) {
3721
+ if (!navigation.started && args.expected_epoch === epoch) throw error;
3722
+ }
3723
+ await navigation.finish();
3724
+ return state();
3725
+ } finally {
3726
+ navigation.dispose();
3727
+ }
3728
+ }
3729
+ case 'drag_at': {
3730
+ const deadlineAt = Date.now() + POINTER_ACTION_BUDGET_MS;
3731
+ checkEpoch(args);
3732
+ page = requireActiveTab().page;
3733
+ const from = pointerPoint(args, 'x', 'y', page);
3734
+ const to = pointerPoint(args, 'to_x', 'to_y', page);
3735
+ const button = pointerButton(args.button);
3736
+ checkEpoch(args);
3737
+ await dragBetween(page, from, to, args.expected_epoch, button, deadlineAt);
3738
+ return state();
3739
+ }
3740
+ case 'screenshot': {
3741
+ if (TEST_DIALOG_READ_DELAY_MS) {
3742
+ await new Promise(resolve => setTimeout(resolve, TEST_DIALOG_READ_DELAY_MS));
3743
+ }
3744
+ return stableRead(async tab => {
3745
+ const page = tab.page;
3746
+ const viewport = page.viewportSize();
3747
+ const data = await page.screenshot({ type: 'jpeg', quality: 80, scale: 'css', timeout: 10_000 });
3748
+ return { viewport, mime_type: 'image/jpeg', data: data.toString('base64') };
3749
+ });
3750
+ }
3751
+ case 'eval':
3752
+ return evalInActivePage(args);
3753
+ case 'close':
3754
+ await closeScope();
3755
+ return { closed: true };
3756
+ default:
3757
+ throw new Error(`unknown browser action: ${action}`);
3758
+ }
3759
+ }
3760
+
3761
+
3762
+ function closeScope() {
3763
+ if (scopeClose) return scopeClose;
3764
+ // Revoke events/queued work before awaiting page close. The shared context
3765
+ // and account data are not owned by this chat and must remain alive.
3766
+ shuttingDown = true;
3767
+ closing = true;
3768
+ clearCaptureTimer();
3769
+ captureGeneration++;
3770
+ desiredCapture = undefined;
3771
+ activeCapture = undefined;
3772
+ if (pendingDialog) expireDialog(pendingDialog);
3773
+ activeDownloadAttempt?.download?.cancel().catch(() => {});
3774
+ scopeClose = (async () => {
3775
+ const results = await Promise.allSettled([...ownedPages].map(page => page.close()));
3776
+ const failure = results.find(result => result.status === 'rejected');
3777
+ if (profileMode === 'clean') await context.close();
3778
+ if (failure) throw failure.reason;
3779
+ await sweepOrphanDownloads();
3780
+ // Keep scratch until the whole browser's close is confirmed. Page close
3781
+ // and a cancellation reply alone do not prove every native file writer
3782
+ // has stopped; another chat still legitimately owns this browser.
3783
+ })();
3784
+ return scopeClose;
3785
+ }
3786
+
3787
+ async function invoke(action, args) {
3788
+ runtime.assertRunning();
3789
+ if (shuttingDown) throw runtime.error('browser_scope_closed', 'browser scope closed');
3790
+ const run = async () => {
3791
+ runtime.assertRunning();
3792
+ if (shuttingDown) throw runtime.error('browser_scope_closed', 'browser scope closed');
3793
+ const result = action === 'download'
3794
+ ? await runtime.withDownload(api, () => dispatch(action, args))
3795
+ : await dispatch(action, args);
3796
+ return { ...result, profile_mode: profileMode, storage_shared: profileMode === 'shared' };
3797
+ };
3798
+ // Dialog responses/state must reach a pending action instead of queuing
3799
+ // behind it. Mutations remain serialized within this chat only.
3800
+ if (['state', 'tab_list', 'dialog_respond'].includes(action)) return run();
3801
+ if (queuedCommands >= 8) throw runtime.error('browser_scope_busy', 'browser scope queue full');
3802
+ queuedCommands++;
3803
+ const result = commandTail.then(run);
3804
+ commandTail = result.catch(() => {});
3805
+ try { return await result; } finally { queuedCommands--; }
3806
+ }
3807
+
3808
+ const api = { id, generation, profileMode, context, downloadDir, downloadContextId,
3809
+ ownedPages, invoke, close: closeScope, adoptPage, onDownloadWillBegin, onDownloadProgress,
3810
+ isClosed: () => shuttingDown, markTransient: page => transientPages.add(page) };
3811
+ return api;
3812
+ }
3813
+
3814
+ // The private stdio v2 protocol multiplexes chat owners; it is not a public
3815
+ // authentication channel. Rust binds opaque scope handles to canonical chats.
3816
+ function createHostRuntime({ browser, sharedContext, downloadCdp, contextOptions, cleanOnly = false }) {
3817
+ const hostGeneration = randomBytes(12).toString('hex');
3818
+ const instanceId = randomBytes(12).toString('hex');
3819
+ const entries = new Map();
3820
+ const spentGenerations = new Set();
3821
+ const pageOwners = new WeakMap();
3822
+ const allPages = new Set();
3823
+ const pendingCreations = new Map();
3824
+ const downloadOwners = new Map();
3825
+ let pageCreation = Promise.resolve();
3826
+ let contextCreation = Promise.resolve();
3827
+ let activeDownloadScope;
3828
+ let stopping = false;
3829
+ const error = (code, message) => Object.assign(new Error(message), { code });
3830
+ const validHandle = value => typeof value === 'string' && /^[a-f0-9]{24}$/.test(value);
3831
+ const scopeKey = request => `${request.scope_id}:${request.scope_generation}`;
3832
+ const scopeMatches = (scope, request) => scope.id === request.scope_id && scope.generation === request.scope_generation;
3833
+ const closed = () => error('browser_scope_closed', 'browser scope closed or generation retired');
3834
+ function assertRunning() {
3835
+ if (stopping) throw error('browser_unavailable', 'browser runtime stopping');
3836
+ }
3837
+ function emitScope(scope, message) {
3838
+ const entry = entries.get(scope.id);
3839
+ if (stopping || entry?.scope !== scope || entry.closing || scope.isClosed()) return;
3840
+ emit({ ...message, version: 2, host_generation: hostGeneration,
3841
+ scope_id: scope.id, scope_generation: scope.generation });
3842
+ }
3843
+ function recordPage(scope, page, privatePage) {
3844
+ const known = pageOwners.get(page);
3845
+ if (known) {
3846
+ if (known.scope !== scope || known.privatePage !== privatePage) throw error('browser_page_owner_conflict', 'page owner conflict');
3847
+ return;
3848
+ }
3849
+ if (scope.isClosed() || stopping || allPages.size >= 32) {
3850
+ void page.close().catch(() => {});
3851
+ throw error('browser_scope_busy', 'browser page capacity unavailable');
3852
+ }
3853
+ pageOwners.set(page, { scope, privatePage });
3854
+ allPages.add(page); scope.ownedPages.add(page);
3855
+ if (privatePage) scope.markTransient(page);
3856
+ page.once('close', () => { allPages.delete(page); scope.ownedPages.delete(page); pageOwners.delete(page); });
3857
+ }
3858
+ async function routePopup(page) {
3859
+ try {
3860
+ if (pageOwners.has(page)) return;
3861
+ const opener = await page.opener();
3862
+ const owner = opener && pageOwners.get(opener);
3863
+ if (!owner || owner.privatePage || owner.scope.isClosed() || stopping) {
3864
+ await page.close(); return;
3865
+ }
3866
+ owner.scope.adoptPage(page);
3867
+ } catch { await page.close().catch(() => {}); }
3868
+ }
3869
+ function watchContext(ownedContext) {
3870
+ ownedContext.on('page', page => {
3871
+ if (pageOwners.has(page)) return;
3872
+ const pending = pendingCreations.get(ownedContext);
3873
+ if (pending) { pending.observed.add(page); return; }
3874
+ void routePopup(page);
3875
+ });
3876
+ }
3877
+ watchContext(sharedContext);
3878
+ function createPage(scope, privatePage) {
3879
+ const result = pageCreation.then(async () => {
3880
+ if (scope.isClosed() || stopping) throw closed();
3881
+ if (allPages.size >= 32) throw error('browser_scope_busy', 'browser page capacity unavailable');
3882
+ const pending = { observed: new Set() };
3883
+ pendingCreations.set(scope.context, pending);
3884
+ let created;
3885
+ try {
3886
+ created = await scope.context.newPage();
3887
+ if (scope.isClosed() || stopping) { await created.close(); throw closed(); }
3888
+ recordPage(scope, created, privatePage);
3889
+ return created;
3890
+ } finally {
3891
+ pendingCreations.delete(scope.context);
3892
+ // A concurrent popup must inherit its actual opener, never the chat
3893
+ // whose newPage promise happened to be in flight.
3894
+ for (const page of pending.observed) if (page !== created) void routePopup(page);
3895
+ }
3896
+ });
3897
+ pageCreation = result.catch(() => {});
3898
+ return result;
3899
+ }
3900
+ async function withDownload(scope, operation) {
3901
+ // Browser.setDownloadBehavior is context-wide. Only this bounded operation
3902
+ // is globally arbitrated; other chat page commands remain independent.
3903
+ if (activeDownloadScope) throw error('browser_download_busy', 'another download is active');
3904
+ if (scope.isClosed() || stopping) throw closed();
3905
+ activeDownloadScope = scope;
3906
+ try {
3907
+ await downloadCdp.send('Browser.setDownloadBehavior', {
3908
+ behavior: 'allowAndName', downloadPath: scope.downloadDir, eventsEnabled: true,
3909
+ ...(scope.downloadContextId ? { browserContextId: scope.downloadContextId } : {}),
3910
+ });
3911
+ return await operation();
3912
+ } finally {
3913
+ try {
3914
+ await downloadCdp.send('Browser.setDownloadBehavior', { behavior: 'deny', eventsEnabled: true,
3915
+ ...(scope.downloadContextId ? { browserContextId: scope.downloadContextId } : {}) });
3916
+ } catch {
3917
+ // A rejected policy restore leaves this context's write destination
3918
+ // unknown. Do not reuse the browser behind a released busy flag.
3919
+ stopping = true;
3920
+ retireAfterReply = true;
3921
+ throw error('browser_unavailable', 'browser download policy restoration unconfirmed');
3922
+ } finally { activeDownloadScope = undefined; }
3923
+ }
3924
+ }
3925
+ downloadCdp.on('Browser.downloadWillBegin', event => {
3926
+ if (!activeDownloadScope) {
3927
+ void downloadCdp.send('Browser.cancelDownload', { guid: event.guid }).catch(() => {});
3928
+ return;
3929
+ }
3930
+ downloadOwners.set(event.guid, activeDownloadScope);
3931
+ activeDownloadScope.onDownloadWillBegin(event);
3932
+ });
3933
+ downloadCdp.on('Browser.downloadProgress', event => {
3934
+ const owner = downloadOwners.get(event.guid);
3935
+ if (owner) owner.onDownloadProgress(event);
3936
+ if (event.state !== 'inProgress') downloadOwners.delete(event.guid);
3937
+ });
3938
+ async function makeScope(request, profileMode) {
3939
+ let ownedContext = sharedContext;
3940
+ let contextId = downloadContextId;
3941
+ if (profileMode === 'clean') {
3942
+ const makeContext = contextCreation.then(async () => {
3943
+ const before = new Set((await downloadCdp.send('Target.getBrowserContexts')).browserContextIds);
3944
+ const clean = await browser.newContext(contextOptions);
3945
+ try {
3946
+ await configureContext(clean);
3947
+ const added = (await downloadCdp.send('Target.getBrowserContexts')).browserContextIds.filter(id => !before.has(id));
3948
+ if (added.length !== 1) throw error('browser_context_unavailable', 'clean context identity unavailable');
3949
+ watchContext(clean);
3950
+ await downloadCdp.send('Browser.setDownloadBehavior', { behavior: 'deny', eventsEnabled: true, browserContextId: added[0] });
3951
+ return { clean, contextId: added[0] };
3952
+ } catch (failure) { await clean.close().catch(() => {}); throw failure; }
3953
+ });
3954
+ contextCreation = makeContext.catch(() => {});
3955
+ const created = await makeContext;
3956
+ ownedContext = created.clean; contextId = created.contextId;
3957
+ }
3958
+ let scratch;
3959
+ try {
3960
+ scratch = await fs.mkdtemp(path.join(downloadDir, 'chat-'));
3961
+ return createChatScope({ id: request.scope_id, generation: request.scope_generation,
3962
+ profileMode, context: ownedContext, downloadContextId: contextId, downloadDir: scratch, runtime });
3963
+ } catch (failure) {
3964
+ if (profileMode === 'clean') await ownedContext.close().catch(() => {});
3965
+ if (scratch) await fs.rm(scratch, { recursive: true, force: true });
3966
+ throw failure;
3967
+ }
3968
+ }
3969
+ async function open(request) {
3970
+ const args = request.args || {};
3971
+ if (typeof args !== 'object' || Array.isArray(args) || Object.keys(args).some(key => key !== 'profile_mode') ||
3972
+ args.profile_mode !== undefined && !['shared', 'clean'].includes(args.profile_mode)) {
3973
+ throw error('invalid_request', 'profile_mode must be shared or clean');
3974
+ }
3975
+ let entry = entries.get(request.scope_id);
3976
+ if (entry) {
3977
+ if (entry.generation !== request.scope_generation || entry.closing) throw closed();
3978
+ if (args.profile_mode !== undefined && entry.profileMode !== args.profile_mode) {
3979
+ throw error('browser_profile_mode_conflict', 'close this chat browser before changing profile mode');
3980
+ }
3981
+ return entry.promise;
3982
+ }
3983
+ if (cleanOnly && args.profile_mode !== 'clean') {
3984
+ throw storageUnavailable('browser_shared_profile_unsupported');
3985
+ }
3986
+ if (spentGenerations.has(scopeKey(request))) throw closed();
3987
+ if (entries.size >= 16 || spentGenerations.size >= 1024) throw error('browser_scope_busy', 'browser scope capacity unavailable');
3988
+ entry = { generation: request.scope_generation, profileMode: args.profile_mode || 'shared', closing: false };
3989
+ entries.set(request.scope_id, entry);
3990
+ entry.promise = makeScope(request, entry.profileMode).then(async scope => {
3991
+ entry.scope = scope;
3992
+ if (entry.closing || stopping) { await scope.close(); throw closed(); }
3993
+ return scope;
3994
+ }).catch(failure => {
3995
+ if (entries.get(request.scope_id) === entry) entries.delete(request.scope_id);
3996
+ spentGenerations.add(scopeKey(request));
3997
+ throw failure;
3998
+ });
3999
+ return entry.promise;
4000
+ }
4001
+ async function closeEntry(request) {
4002
+ const entry = entries.get(request.scope_id);
4003
+ if (!entry || entry.generation !== request.scope_generation) throw closed();
4004
+ if (entry.close) return entry.close;
4005
+ entry.closing = true;
4006
+ spentGenerations.add(scopeKey(request));
4007
+ entry.close = (async () => {
4008
+ let scope;
4009
+ try { scope = await entry.promise; }
4010
+ catch (failure) { if (failure.code === 'browser_scope_closed') return { closed: true }; throw failure; }
4011
+ await scope.close();
4012
+ if (entries.get(request.scope_id) === entry) entries.delete(request.scope_id);
4013
+ return { closed: true };
4014
+ })().catch(failure => { retireAfterReply = true; throw failure; });
4015
+ return entry.close;
4016
+ }
4017
+ async function handle(request) {
4018
+ if (request.action === 'runtime_state') return { protocol_version: 2, host_generation: hostGeneration,
4019
+ browser_instance_id: instanceId, scope_count: entries.size, profile_modes: cleanOnly ? ['clean'] : ['shared', 'clean'],
4020
+ storage_boundary: cleanOnly ? { provider: 'ephemeral_clean_v1', persistent: false } :
4021
+ hostStorageSettings ? { provider: 'mac_apfs_fixed_v1', image_bytes: IMAGE_BYTES,
4022
+ quota_bytes: QUOTA_BYTES, native_root_tracking: 1, native_group: 'host_inherited_v1' } : null };
4023
+ if (stopping) throw error('browser_unavailable', 'browser runtime stopping');
4024
+ if (request.version !== 2 || request.host_generation !== hostGeneration ||
4025
+ !validHandle(request.scope_id) || !validHandle(request.scope_generation)) {
4026
+ throw error('browser_scope_closed', 'invalid or stale browser owner');
4027
+ }
4028
+ if (request.action === 'scope_close' || request.action === 'close') return closeEntry(request);
4029
+ if (request.action === 'scope_open') return (await open(request)).invoke('state', {});
4030
+ const entry = entries.get(request.scope_id);
4031
+ if (!entry || entry.closing || !scopeMatches({ id: request.scope_id, generation: entry.generation }, request)) throw closed();
4032
+ const scope = await entry.promise;
4033
+ return scope.invoke(request.action, request.args || {});
4034
+ }
4035
+ async function closeScopes() {
4036
+ stopping = true;
4037
+ const results = await Promise.allSettled([...entries].map(async ([id, entry]) => {
4038
+ if (entry.close) return entry.close;
4039
+ entry.closing = true;
4040
+ spentGenerations.add(`${id}:${entry.generation}`);
4041
+ const scope = await entry.promise;
4042
+ return scope.close();
4043
+ }));
4044
+ const failure = results.find(result => result.status === 'rejected' && result.reason?.code !== 'browser_scope_closed');
4045
+ if (failure) throw failure.reason;
4046
+ }
4047
+ const runtime = { browser, downloadCdp, handle, closeScopes, error, createPage, recordPage,
4048
+ withDownload, emitScope, assertRunning, generation: hostGeneration };
4049
+ return runtime;
4050
+ }
4051
+
4052
+ async function configureContext(ownedContext) {
4053
+ await ownedContext.addInitScript(installEvalHelper, EVAL_HELPER_KEY);
4054
+ await ownedContext.addInitScript(installScriptBlobCapture, { key: SCRIPT_BLOB_KEY, secret: SCRIPT_BLOB_SECRET });
4055
+ await ownedContext.addInitScript(installDownloadLinkInspector, { key: DOWNLOAD_LINK_KEY, secret: DOWNLOAD_LINK_SECRET });
4056
+ await ownedContext.route('**/*', route => {
4057
+ if (route.request().isNavigationRequest()) {
4058
+ try { checkUrl(route.request().url()); } catch { return route.abort('blockedbyclient'); }
4059
+ }
4060
+ return route.continue();
4061
+ });
4062
+ }
4063
+
4064
+ function emit(message) {
4065
+ if (!closing) process.stdout.write(`${JSON.stringify(message)}\n`);
4066
+ }
4067
+
4068
+ function replyEnvelope(request, payload, v2, hostGeneration) {
4069
+ // Keep internal capacity subtypes while emitting the canonical v2 busy code
4070
+ // already mapped by the native client to HTTP 503 browser_busy.
4071
+ const response = v2 && payload.ok === false &&
4072
+ ['browser_download_busy', 'browser_scope_busy'].includes(payload.code)
4073
+ ? { ...payload, code: 'browser_busy' } : payload;
4074
+ return { id: Number.isSafeInteger(request?.id) ? request.id : null, ...response,
4075
+ ...(v2 ? { version: 2, host_generation: hostGeneration,
4076
+ scope_id: request?.scope_id, scope_generation: request?.scope_generation } : {}) };
4077
+ }
4078
+
4079
+ function isScopeCleanup(request, hostGeneration) {
4080
+ return request?.action === 'scope_close' && request.host_generation === hostGeneration &&
4081
+ typeof request.scope_id === 'string' && /^[0-9a-f]{24}$/.test(request.scope_id) &&
4082
+ typeof request.scope_generation === 'string' && /^[0-9a-f]{24}$/.test(request.scope_generation);
4083
+ }
4084
+
4085
+ function createRequestBudget() {
4086
+ let total = 0; let ordinary = 0;
4087
+ return {
4088
+ acquire(cleanup) {
4089
+ // Reserve one cleanup slot per admitted chat. Cancelled read waiters can
4090
+ // leave native work pending, so this bound also lives in the actual host.
4091
+ if (total >= 64 || !cleanup && ordinary >= 48) {
4092
+ throw Object.assign(new Error('browser request capacity unavailable'), { code: 'browser_busy' });
4093
+ }
4094
+ total++; if (!cleanup) ordinary++;
4095
+ let released = false;
4096
+ return () => {
4097
+ if (released) return;
4098
+ released = true; total--; if (!cleanup) ordinary--;
4099
+ };
4100
+ },
4101
+ };
4102
+ }
4103
+
4104
+ function closeHost() {
4105
+ if (hostClose) return hostClose;
4106
+ shuttingDown = true;
4107
+ hostClose = finishCloseHost();
4108
+ return hostClose;
4109
+ }
4110
+
4111
+ async function finishCloseHost() {
4112
+ clearTimeout(profileTimer);
4113
+ clearInterval(profileInterval);
4114
+ let checkpointError;
4115
+ // Stop document timers/network writers before taking the final snapshot.
4116
+ // Do not run beforeunload handlers or enqueue a close behind a hung action.
4117
+ try {
4118
+ if (hostRuntime) await hostRuntime.closeScopes();
4119
+ if (context) await Promise.all(context.pages().map(page => page.close()));
4120
+ } catch (error) { checkpointError = error; }
4121
+ try { await checkpointProfile(); } catch (error) { checkpointError = error; }
4122
+ let writerCloseError;
4123
+ try { await context?.close(); } catch (error) { writerCloseError = error; }
4124
+ try { await browser?.close(); } catch (error) { writerCloseError ||= error; }
4125
+ try { await nativeRoots?.waitClosed(); } catch (error) { writerCloseError ||= error; }
4126
+ // A rejected close is not evidence that the writer stopped. Preserve the
4127
+ // scratch and do not publish browserClosed; the native owner must retain its
4128
+ // resources until the independent writer domain is actually confirmed.
4129
+ if (writerCloseError) {
4130
+ nativeRoots?.stopCapturedRoots?.();
4131
+ throw writerCloseError;
4132
+ }
4133
+ browserClosed = true;
4134
+ downloadCdp = undefined;
4135
+ downloadContextId = undefined;
4136
+ if (retireAfterReply && TEST_RETIRE_CLOSE_DELAY_MS) {
4137
+ await new Promise(resolve => setTimeout(resolve, TEST_RETIRE_CLOSE_DELAY_MS));
4138
+ }
4139
+ if (downloadDir && !retireAfterReply) {
4140
+ await fs.rm(downloadDir, { recursive: true, force: true }).catch(() => {});
4141
+ downloadDir = undefined;
4142
+ }
4143
+ if (checkpointError) throw checkpointError;
4144
+ }
4145
+
4146
+ function recordClosedLaunch(control, generation) {
4147
+ const marker = path.join(control, '.bamboo-profile-launch-active-v1');
4148
+ const launch = `BAMBOO_BROWSER_LAUNCH_V1\n${generation}\n`;
4149
+ const closed = Buffer.from(`BAMBOO_BROWSER_CLOSED_V1\n${process.pid}\n`);
4150
+ const descriptor = nativeFs.openSync(marker, fsConstants.O_RDWR |
4151
+ fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
4152
+ try {
4153
+ const stat = nativeFs.fstatSync(descriptor);
4154
+ assert.ok(stat.isFile() && stat.uid === process.getuid() && stat.nlink === 1 &&
4155
+ (stat.mode & 0o777) === 0o600 && stat.size === launch.length);
4156
+ const bytes = Buffer.alloc(launch.length);
4157
+ assert.equal(nativeFs.readSync(descriptor, bytes, 0, bytes.length, 0), bytes.length);
4158
+ assert.equal(bytes.toString('utf8'), launch);
4159
+ assert.equal(nativeFs.writeSync(descriptor, closed, 0, closed.length, bytes.length), closed.length);
4160
+ nativeFs.fsyncSync(descriptor);
4161
+ } finally {
4162
+ nativeFs.closeSync(descriptor);
4163
+ }
4164
+ }
4165
+
4166
+ async function main() {
4167
+ const admission = await prepareNativeLaunch();
4168
+ hostStorageSettings = productionStorageSettings(admission?.environment || process.env);
4169
+ if (hostStorageSettings) process.chdir(hostStorageSettings.scratch);
4170
+ const downloadRoot = process.env.BAMBOO_BROWSER_DOWNLOAD_ROOT || os.tmpdir();
4171
+ downloadDir = await fs.mkdtemp(path.join(downloadRoot, 'bamboo-browser-download-'));
4172
+ const sessionCookies = await readProfile();
4173
+ const launchOptions = { headless: true, downloadsPath: downloadDir,
4174
+ ...(process.env.BAMBOO_BROWSER_EXECUTABLE ? { executablePath: process.env.BAMBOO_BROWSER_EXECUTABLE } : {}) };
4175
+ const contextOptions = { viewport: { width: 1000, height: 720 }, deviceScaleFactor: 1,
4176
+ acceptDownloads: true, serviceWorkers: 'block' };
4177
+ const managedGroup = hostStorageSettings && !hostStorageSettings.cleanOnly ? verifyOwnedHostGroup() : false;
4178
+ nativeRoots = createNativeRootTracker(require('node:child_process'), profileDirectory, { managedGroup });
4179
+ if (profileDirectory) {
4180
+ context = await nativeRoots.launch(() => {
4181
+ const { chromium } = require('playwright-core');
4182
+ return chromium.launchPersistentContext(profileDirectory, { ...launchOptions, ...contextOptions });
4183
+ });
4184
+ browser = context.browser();
4185
+ if (!browser) throw profileError();
4186
+ if (sessionCookies.length) await context.addCookies(sessionCookies);
4187
+ for (const page of context.pages()) await page.close();
4188
+ await checkpointProfile();
4189
+ context.on('response', scheduleProfileCheckpoint);
4190
+ profileInterval = setInterval(scheduleProfileCheckpoint, 5000); profileInterval.unref();
4191
+ } else {
4192
+ // Standalone hosts and the explicit Linux/Windows clean-only provider use
4193
+ // Playwright's temporary profile. They never import the account context.
4194
+ browser = await nativeRoots.launch(() => {
4195
+ const { chromium } = require('playwright-core');
4196
+ return chromium.launch(launchOptions);
4197
+ });
4198
+ context = await browser.newContext(contextOptions);
4199
+ }
4200
+ await configureContext(context);
4201
+ downloadCdp = await browser.newBrowserCDPSession();
4202
+ const ids = (await downloadCdp.send('Target.getBrowserContexts')).browserContextIds;
4203
+ downloadContextId = profileDirectory ? undefined : ids[0];
4204
+ if (!profileDirectory && ids.length !== 1) throw profileError();
4205
+ await downloadCdp.send('Browser.setDownloadBehavior', { behavior: 'deny', eventsEnabled: true,
4206
+ ...(downloadContextId ? { browserContextId: downloadContextId } : {}) });
4207
+ hostRuntime = createHostRuntime({ browser, sharedContext: context, downloadCdp, contextOptions,
4208
+ cleanOnly: hostStorageSettings?.cleanOnly === true });
4209
+ const v2 = process.env.BAMBOO_BROWSER_HOST_PROTOCOL === '2';
4210
+ const legacy = { scope_id: '0'.repeat(24), scope_generation: '0'.repeat(24), host_generation: hostRuntime.generation, version: 2 };
4211
+ if (!v2) await hostRuntime.handle({ ...legacy, action: 'scope_open', args: {} });
4212
+ const lines = admission?.lines || readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
4213
+ const requests = admission?.requests || lines[Symbol.asyncIterator]();
4214
+ const pending = new Set();
4215
+ const budget = createRequestBudget();
4216
+ let lastRequestId = 0;
4217
+ const disconnected = () => {
4218
+ lines.close(); process.stdin.pause(); closing = true;
4219
+ void closeHost().catch(() => { process.exitCode = 1; });
4220
+ };
4221
+ process.stdin.once('end', disconnected);
4222
+ process.stdout.on('error', error => { if (error.code !== 'EPIPE') process.exitCode = 1; disconnected(); });
4223
+ async function answer(request) {
4224
+ try {
4225
+ if (profileFailure) throw profileFailure;
4226
+ const owned = v2 ? request : { ...request, ...legacy };
4227
+ const result = await hostRuntime.handle(owned);
4228
+ if (!v2 || result.profile_mode === 'shared') await checkpointProfile();
4229
+ emit(replyEnvelope(request, { ok: true, result }, v2, hostRuntime.generation));
4230
+ } catch (error) {
4231
+ emit(replyEnvelope(request, { ok: false, code: error.code || 'browser_error',
4232
+ error: String(error.message || error) }, v2, hostRuntime.generation));
4233
+ }
4234
+ }
4235
+ for await (const line of requests) {
4236
+ if (shuttingDown) break;
4237
+ let request;
4238
+ let envelopeValid = false;
4239
+ let release;
4240
+ try {
4241
+ if (Buffer.byteLength(line) > 2 * 1024 * 1024) throw new Error('browser request too large');
4242
+ request = JSON.parse(line);
4243
+ if (!Number.isSafeInteger(request.id) || request.id <= lastRequestId ||
4244
+ typeof request.action !== 'string' || v2 && request.version !== 2) throw new Error('invalid browser request envelope');
4245
+ lastRequestId = request.id;
4246
+ envelopeValid = true;
4247
+ release = budget.acquire(v2 && isScopeCleanup(request, hostRuntime.generation));
4248
+ } catch (error) {
4249
+ emit(replyEnvelope(request, { ok: false, code: error.code || 'invalid_request', error: error.message }, v2, hostRuntime.generation));
4250
+ if (v2 && !envelopeValid) {
4251
+ // An unbindable/replayed internal frame is a protocol failure, not a
4252
+ // request that can safely be left waiting behind an anonymous error.
4253
+ retireAfterReply = true;
4254
+ process.exitCode = 1;
4255
+ disconnected();
4256
+ break;
4257
+ }
4258
+ continue;
4259
+ }
4260
+ const work = answer(request); pending.add(work);
4261
+ void work.finally(() => {
4262
+ pending.delete(work);
4263
+ release();
4264
+ if (retireAfterReply) { process.exitCode = 1; disconnected(); }
4265
+ });
4266
+ if (!v2) {
4267
+ await work;
4268
+ if (request.action === 'close') break;
4269
+ }
4270
+ if (retireAfterReply) break;
4271
+ }
4272
+ closing = true;
4273
+ shuttingDown = true;
4274
+ lines.close(); process.stdin.pause();
4275
+ if (retireAfterReply) {
4276
+ // Never keep a timed-out Chromium transfer alive for the next request.
4277
+ // Native forced retirement must quarantine the unconfirmed writer domain.
4278
+ await Promise.race([closeHost(), new Promise(resolve => setTimeout(resolve, 250))]);
4279
+ process.exit(1);
4280
+ }
4281
+ await closeHost();
4282
+ await Promise.allSettled([...pending]);
4283
+ if (managedGroup && !retireAfterReply && !process.exitCode &&
4284
+ process.env.BAMBOO_BROWSER_PERSIST_CLOSE_V1 === '1') {
4285
+ // Bamboo can die before it waits for this host. Record the completed close
4286
+ // in the same launch fence, so the next owner can finish the group check.
4287
+ recordClosedLaunch(hostStorageSettings.control, admission.environment.BAMBOO_BROWSER_STORAGE_GENERATION);
4288
+ }
4289
+ }
4290
+
4291
+ if (require.main === module) {
4292
+ const arguments_ = process.argv.slice(2);
4293
+ if (arguments_.length) {
4294
+ // Native reset uses this read-only helper under its exclusive stable gate.
4295
+ // It neither imports Playwright nor creates/mounts/erases storage. Its JSON
4296
+ // is not an erasure grant; the native owner still holds and verifies paths.
4297
+ try {
4298
+ assert.equal(arguments_.length, 2);
4299
+ assert.ok(['--storage-inspect-v1', '--storage-reset-inspect-v1', '--storage-prepare-inspect-v1',
4300
+ '--storage-backing-inspect-v1'].includes(arguments_[0]));
4301
+ assert.equal(process.platform, 'darwin');
4302
+ const plan = macSharedStoragePlan(arguments_[1]);
4303
+ if (arguments_[0] === '--storage-backing-inspect-v1') {
4304
+ process.stdout.write(JSON.stringify(inspectMacStorageBacking(plan)) + '\n');
4305
+ } else {
4306
+ const result = arguments_[0] === '--storage-prepare-inspect-v1' ? inspectMacStorageForPreparation(plan) :
4307
+ arguments_[0] === '--storage-reset-inspect-v1' ?
4308
+ inspectMacStorageForReset(plan) : inspectMacSharedStorage(plan);
4309
+ const receipt = { kind: result.validation.kind,
4310
+ volumeUuid: result.validation.volumeUuid, imageBytes: IMAGE_BYTES, quotaBytes: QUOTA_BYTES,
4311
+ mountDevice: result.observation.mount.device, imageDevice: result.observation.image.device };
4312
+ if (arguments_[0] === '--storage-prepare-inspect-v1') {
4313
+ receipt.mountMode = result.observation.mount.mode & 0o777;
4314
+ receipt.pathsComplete = Object.values(result.observation.paths).every(value => value !== null);
4315
+ receipt.pathsAbsent = Object.values(result.observation.paths).every(value => value === null);
4316
+ }
4317
+ process.stdout.write(JSON.stringify(receipt) + '\n');
4318
+ }
4319
+ } catch {
4320
+ process.stderr.write('browser storage inspection unavailable\n');
4321
+ process.exitCode = 2;
4322
+ }
4323
+ } else main().catch(async error => {
4324
+ process.stderr.write(`browser host failed: ${error.message || error}\n`);
4325
+ process.exitCode = 1;
4326
+ await closeHost().catch(() => {});
4327
+ });
4328
+ } else {
4329
+ module.exports = { installScriptBlobCapture, installDownloadLinkInspector,
4330
+ IMAGE_BYTES, QUOTA_BYTES, ACCOUNT_KEY, macSharedStoragePlan,
4331
+ validateMacStorageObservation, inspectMacSharedStorage,
4332
+ validateMacStorageResetObservation, inspectMacStorageForReset,
4333
+ validateMacStoragePreparationObservation, inspectMacStorageForPreparation, inspectMacStorageBacking };
4334
+ }