@querying/sneaky 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +171 -2
  3. package/bin/sneaky-mcp.mjs +5 -0
  4. package/bin/sneaky.mjs +51 -0
  5. package/dist/agent/index.d.ts +277 -0
  6. package/dist/agent/index.js +319 -0
  7. package/dist/agent/index.js.map +1 -0
  8. package/dist/browser/index.d.ts +69 -0
  9. package/dist/browser/index.js +326 -0
  10. package/dist/browser/index.js.map +1 -0
  11. package/dist/cli/index.d.ts +51 -0
  12. package/dist/cli/index.js +189 -0
  13. package/dist/cli/index.js.map +1 -0
  14. package/dist/driver/cdp.d.ts +36 -0
  15. package/dist/driver/cdp.js +240 -0
  16. package/dist/driver/cdp.js.map +1 -0
  17. package/dist/driver/frame.d.ts +229 -0
  18. package/dist/driver/frame.js +794 -0
  19. package/dist/driver/frame.js.map +1 -0
  20. package/dist/driver/index.d.ts +13 -0
  21. package/dist/driver/index.js +6 -0
  22. package/dist/driver/index.js.map +1 -0
  23. package/dist/driver/keys.d.ts +9 -0
  24. package/dist/driver/keys.js +65 -0
  25. package/dist/driver/keys.js.map +1 -0
  26. package/dist/driver/launcher.d.ts +49 -0
  27. package/dist/driver/launcher.js +251 -0
  28. package/dist/driver/launcher.js.map +1 -0
  29. package/dist/driver/page.d.ts +391 -0
  30. package/dist/driver/page.js +1594 -0
  31. package/dist/driver/page.js.map +1 -0
  32. package/dist/index.d.ts +501 -0
  33. package/dist/index.js +688 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/mcp/server.d.ts +35 -0
  36. package/dist/mcp/server.js +548 -0
  37. package/dist/mcp/server.js.map +1 -0
  38. package/dist/repl/cli.d.ts +1 -0
  39. package/dist/repl/cli.js +246 -0
  40. package/dist/repl/cli.js.map +1 -0
  41. package/dist/repl/host.d.ts +46 -0
  42. package/dist/repl/host.js +167 -0
  43. package/dist/repl/host.js.map +1 -0
  44. package/dist/repl/index.d.ts +246 -0
  45. package/dist/repl/index.js +923 -0
  46. package/dist/repl/index.js.map +1 -0
  47. package/dist/repl/transform.d.ts +19 -0
  48. package/dist/repl/transform.js +590 -0
  49. package/dist/repl/transform.js.map +1 -0
  50. package/dist/request/index.d.ts +265 -0
  51. package/dist/request/index.js +898 -0
  52. package/dist/request/index.js.map +1 -0
  53. package/package.json +83 -4
@@ -0,0 +1,923 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import util from "node:util";
4
+ import vm from "node:vm";
5
+ import { parseTarget, } from "../index.js";
6
+ import { connectSneakyClient, sneakyHomeDir } from "./host.js";
7
+ import { transformReplCode } from "./transform.js";
8
+ export { connectSneakyClient, loadSneakyConfig, resolveHostConfig, sneakyHomeDir } from "./host.js";
9
+ export { transformReplCode } from "./transform.js";
10
+ export class ReplLocator {
11
+ page;
12
+ target;
13
+ constructor(page, target) {
14
+ this.page = page;
15
+ this.target = target;
16
+ }
17
+ first() {
18
+ return new ReplLocator(this.page, { ...this.target, nth: 0 });
19
+ }
20
+ last() {
21
+ return new ReplLocator(this.page, { ...this.target, nth: -1 });
22
+ }
23
+ nth(index) {
24
+ return new ReplLocator(this.page, { ...this.target, nth: index });
25
+ }
26
+ async click(options) {
27
+ await this.page.ensureActive();
28
+ return this.page.session.act({ type: "click", target: this.target, button: options?.button, click_count: options?.clickCount }, options);
29
+ }
30
+ async dblclick(options) {
31
+ await this.page.ensureActive();
32
+ return this.page.session.act({ type: "dblclick", target: this.target }, options);
33
+ }
34
+ async hover(options) {
35
+ await this.page.ensureActive();
36
+ return this.page.session.act({ type: "hover", target: this.target }, options);
37
+ }
38
+ async fill(text, options) {
39
+ await this.page.ensureActive();
40
+ return this.page.session.fill(this.target, text, options);
41
+ }
42
+ async type(text, options) {
43
+ await this.page.ensureActive();
44
+ return this.page.session.act({ type: "type", target: this.target, text }, options);
45
+ }
46
+ async press(key, options) {
47
+ await this.page.ensureActive();
48
+ return this.page.session.act([
49
+ { type: "click", target: this.target, speed: "fast" },
50
+ { type: "press", key },
51
+ ], options);
52
+ }
53
+ async selectOption(valueOrOpt, options) {
54
+ await this.page.ensureActive();
55
+ const spec = typeof valueOrOpt === "string" ? { value: valueOrOpt } : valueOrOpt;
56
+ return this.page.session.act({ type: "select", target: this.target, value: spec.value, label: spec.label }, options);
57
+ }
58
+ async waitFor(options) {
59
+ await this.page.ensureActive();
60
+ return this.page.session.act({ type: "wait", target: this.target, timeout_ms: options?.timeout });
61
+ }
62
+ async textContent() {
63
+ await this.page.ensureActive();
64
+ return (await this.page.session.query(this.target, "textContent")).value;
65
+ }
66
+ async innerText() {
67
+ await this.page.ensureActive();
68
+ return (await this.page.session.query(this.target, "innerText")).value;
69
+ }
70
+ async innerHTML() {
71
+ await this.page.ensureActive();
72
+ return (await this.page.session.query(this.target, "innerHTML")).value;
73
+ }
74
+ async outerHTML() {
75
+ await this.page.ensureActive();
76
+ return (await this.page.session.query(this.target, "outerHTML")).value;
77
+ }
78
+ async inputValue() {
79
+ await this.page.ensureActive();
80
+ return (await this.page.session.query(this.target, "inputValue")).value;
81
+ }
82
+ async getAttribute(name) {
83
+ await this.page.ensureActive();
84
+ return (await this.page.session.query(this.target, "getAttribute", name)).value;
85
+ }
86
+ async isVisible() {
87
+ await this.page.ensureActive();
88
+ return Boolean((await this.page.session.query(this.target, "isVisible")).value);
89
+ }
90
+ async isEnabled() {
91
+ await this.page.ensureActive();
92
+ return Boolean((await this.page.session.query(this.target, "isEnabled")).value);
93
+ }
94
+ async isChecked() {
95
+ await this.page.ensureActive();
96
+ return Boolean((await this.page.session.query(this.target, "isChecked")).value);
97
+ }
98
+ async count() {
99
+ await this.page.ensureActive();
100
+ return Number((await this.page.session.query(this.target, "count")).value ?? 0);
101
+ }
102
+ async boundingBox() {
103
+ await this.page.ensureActive();
104
+ return (await this.page.session.query(this.target, "boundingBox")).value;
105
+ }
106
+ async allTextContents() {
107
+ await this.page.ensureActive();
108
+ const v = (await this.page.session.query(this.target, "allTextContents")).value;
109
+ return Array.isArray(v) ? v : [];
110
+ }
111
+ async allInnerTexts() {
112
+ await this.page.ensureActive();
113
+ const v = (await this.page.session.query(this.target, "allInnerTexts")).value;
114
+ return Array.isArray(v) ? v : [];
115
+ }
116
+ async screenshot(options = {}) {
117
+ await this.page.ensureActive();
118
+ const res = await this.page.session.screenshot({ ...options, target: this.target });
119
+ const buf = Buffer.from(res.data, "base64");
120
+ if (options.path) {
121
+ fs.mkdirSync(path.dirname(path.resolve(options.path)), { recursive: true });
122
+ fs.writeFileSync(options.path, buf);
123
+ }
124
+ return buf;
125
+ }
126
+ }
127
+ export class ReplPage {
128
+ session;
129
+ targetId;
130
+ host;
131
+ currentUrl;
132
+ currentTitle;
133
+ keyboard;
134
+ mouse;
135
+ constructor(session, targetId, host, initialMeta) {
136
+ this.session = session;
137
+ this.targetId = targetId;
138
+ this.host = host;
139
+ this.currentUrl = initialMeta?.url ?? "about:blank";
140
+ this.currentTitle = initialMeta?.title ?? "";
141
+ this.keyboard = {
142
+ press: async (key) => {
143
+ await this.ensureActive();
144
+ return this.session.press(key);
145
+ },
146
+ type: async (text, options) => {
147
+ await this.ensureActive();
148
+ return this.session.act({ type: "type", text }, options);
149
+ },
150
+ };
151
+ this.mouse = {
152
+ click: async (x, y, options) => {
153
+ await this.ensureActive();
154
+ return this.session.act({
155
+ type: "click",
156
+ target: { x, y },
157
+ button: options?.button,
158
+ click_count: options?.clickCount,
159
+ speed: options?.speed,
160
+ });
161
+ },
162
+ move: async (x, y, options) => {
163
+ await this.ensureActive();
164
+ return this.session.act({ type: "hover", target: { x, y } }, options);
165
+ },
166
+ wheel: async (dx, dy) => {
167
+ await this.ensureActive();
168
+ return this.session.act({ type: "scroll", dx, dy });
169
+ },
170
+ };
171
+ }
172
+ /** Internal: activates this tab on the daemon if it is not already the front tab. */
173
+ async ensureActive() {
174
+ await this.host.ensureTabActive(this.targetId);
175
+ }
176
+ /** Internal: updates cached URL/title from daemon responses. */
177
+ _updateMeta(url, title) {
178
+ if (typeof url === "string" && url.length > 0)
179
+ this.currentUrl = url;
180
+ if (typeof title === "string")
181
+ this.currentTitle = title;
182
+ }
183
+ url() {
184
+ return this.currentUrl;
185
+ }
186
+ async title() {
187
+ await this.ensureActive();
188
+ const res = await this.session.eval("document.title || ''", { world: "isolated", awaitPromise: false });
189
+ this.currentTitle = typeof res.value === "string" ? res.value : this.currentTitle;
190
+ return this.currentTitle;
191
+ }
192
+ async goto(url, options = {}) {
193
+ await this.ensureActive();
194
+ const res = await this.session.goto(url, {
195
+ waitUntil: options.waitUntil ?? "load",
196
+ timeoutMs: options.timeout,
197
+ });
198
+ this._updateMeta(res.url, res.title);
199
+ return res;
200
+ }
201
+ async reload(options = {}) {
202
+ await this.ensureActive();
203
+ const res = await this.session.act({
204
+ type: "reload",
205
+ wait_until: options.waitUntil,
206
+ timeout_ms: options.timeout,
207
+ });
208
+ this._updateMeta(res.page?.url, res.page?.title);
209
+ return res;
210
+ }
211
+ async goBack() {
212
+ await this.ensureActive();
213
+ const res = await this.session.act({ type: "back" });
214
+ this._updateMeta(res.page?.url, res.page?.title);
215
+ return res;
216
+ }
217
+ async goForward() {
218
+ await this.ensureActive();
219
+ const res = await this.session.act({ type: "forward" });
220
+ this._updateMeta(res.page?.url, res.page?.title);
221
+ return res;
222
+ }
223
+ async content() {
224
+ await this.ensureActive();
225
+ const res = await this.session.eval("document.documentElement ? document.documentElement.outerHTML : ''", { world: "isolated", awaitPromise: false });
226
+ return typeof res.value === "string" ? res.value : "";
227
+ }
228
+ /** Evaluates a function or JS expression in the page's main world WITHOUT calling Runtime.enable. */
229
+ async evaluate(fnOrExpr, arg) {
230
+ await this.ensureActive();
231
+ let expression;
232
+ if (typeof fnOrExpr === "function") {
233
+ const serializedArg = arg === undefined ? "" : JSON.stringify(arg);
234
+ expression = `(${fnOrExpr.toString()})(${serializedArg})`;
235
+ }
236
+ else {
237
+ expression = fnOrExpr;
238
+ }
239
+ const res = await this.session.eval(expression, { world: "main", awaitPromise: true });
240
+ return res.value;
241
+ }
242
+ async setViewportSize(size) {
243
+ await this.ensureActive();
244
+ return this.session.setViewport(size);
245
+ }
246
+ async screenshot(options = {}) {
247
+ await this.ensureActive();
248
+ const res = await this.session.screenshot(options);
249
+ const buf = Buffer.from(res.data, "base64");
250
+ if (options.path) {
251
+ fs.mkdirSync(path.dirname(path.resolve(options.path)), { recursive: true });
252
+ fs.writeFileSync(options.path, buf);
253
+ }
254
+ return buf;
255
+ }
256
+ async pdf(options = {}) {
257
+ await this.ensureActive();
258
+ const res = await this.session.pdf(options);
259
+ const buf = Buffer.from(res.data, "base64");
260
+ if (options.path) {
261
+ fs.mkdirSync(path.dirname(path.resolve(options.path)), { recursive: true });
262
+ fs.writeFileSync(options.path, buf);
263
+ }
264
+ return buf;
265
+ }
266
+ async extract(options = {}) {
267
+ await this.ensureActive();
268
+ return this.session.extract({
269
+ kind: options.kind ?? "markdown",
270
+ target: options.selector ? parseTarget(options.selector) : undefined,
271
+ maxChars: options.maxChars,
272
+ });
273
+ }
274
+ async snapshot(options) {
275
+ return this.host.snapshotPage(this, options);
276
+ }
277
+ async waitForTimeout(ms) {
278
+ await new Promise((r) => setTimeout(r, Math.max(0, ms)));
279
+ }
280
+ async waitForSelector(selectorOrRef, options = {}) {
281
+ await this.ensureActive();
282
+ return this.session.act({ type: "wait", target: parseTarget(selectorOrRef), timeout_ms: options.timeout });
283
+ }
284
+ async waitForURL(urlSubstring, options = {}) {
285
+ await this.ensureActive();
286
+ return this.session.act({ type: "wait", url_contains: urlSubstring, timeout_ms: options.timeout });
287
+ }
288
+ async bringToFront() {
289
+ await this.session.activateTab(this.targetId);
290
+ await this.host.ensureTabActive(this.targetId);
291
+ }
292
+ async close() {
293
+ await this.session.closeTab(this.targetId);
294
+ this.host.onTabClosed(this.targetId);
295
+ }
296
+ locator(selectorOrRef) {
297
+ return new ReplLocator(this, parseTarget(selectorOrRef));
298
+ }
299
+ getByRole(role, options = {}) {
300
+ return new ReplLocator(this, { role, name: options.name, exact: options.exact });
301
+ }
302
+ getByText(text, options = {}) {
303
+ return new ReplLocator(this, { text, exact: options.exact });
304
+ }
305
+ getByLabel(label, options = {}) {
306
+ return new ReplLocator(this, { label, exact: options.exact });
307
+ }
308
+ getByPlaceholder(placeholder, options = {}) {
309
+ return new ReplLocator(this, { placeholder, exact: options.exact });
310
+ }
311
+ toString() {
312
+ return `ReplPage(${this.targetId}, ${this.currentUrl})`;
313
+ }
314
+ }
315
+ function formatSnapshotDiff(diff) {
316
+ if (!diff)
317
+ return null;
318
+ const parts = [];
319
+ for (const line of diff.removed ?? []) {
320
+ parts.push(`- ${line}`);
321
+ }
322
+ for (const line of diff.added ?? []) {
323
+ parts.push(`+ ${line}`);
324
+ }
325
+ if (parts.length === 0) {
326
+ return `(no changes; ${diff.unchanged_count} unchanged lines since ${diff.base_snapshot_id})`;
327
+ }
328
+ return parts.join("\n");
329
+ }
330
+ function cookieMatchesUrl(c, target) {
331
+ if (c.secure && target.protocol !== "https:")
332
+ return false;
333
+ const host = target.hostname.toLowerCase();
334
+ if (c.domain) {
335
+ const dom = c.domain.toLowerCase().replace(/^\./, "");
336
+ if (host !== dom && !host.endsWith(`.${dom}`))
337
+ return false;
338
+ }
339
+ if (c.path && !target.pathname.startsWith(c.path))
340
+ return false;
341
+ return true;
342
+ }
343
+ function normalizeFetchHeaders(headers) {
344
+ const out = [];
345
+ if (!headers)
346
+ return out;
347
+ if (headers instanceof Headers) {
348
+ headers.forEach((v, k) => out.push([k, v]));
349
+ }
350
+ else if (Array.isArray(headers)) {
351
+ for (const [k, v] of headers)
352
+ out.push([String(k), String(v)]);
353
+ }
354
+ else {
355
+ for (const [k, v] of Object.entries(headers)) {
356
+ if (v !== undefined)
357
+ out.push([k, String(v)]);
358
+ }
359
+ }
360
+ return out;
361
+ }
362
+ export class SneakyReplSession {
363
+ client;
364
+ session;
365
+ profileId;
366
+ host;
367
+ ephemeral;
368
+ context;
369
+ activeTargetId = null;
370
+ attachedTabs = new Map();
371
+ lastSnapshotByTab = new Map();
372
+ turnStdout = [];
373
+ turnStderr = [];
374
+ turnDisplayed = [];
375
+ displaySeq = 0;
376
+ artifactDir;
377
+ constructor(client, session, profileId, host, ephemeral, artifactDir) {
378
+ this.client = client;
379
+ this.session = session;
380
+ this.profileId = profileId;
381
+ this.host = host;
382
+ this.ephemeral = ephemeral;
383
+ this.artifactDir = artifactDir ?? path.join(sneakyHomeDir(), "artifacts");
384
+ this.resetContext();
385
+ }
386
+ static async connect(options = {}) {
387
+ const { client, host, defaultProfile } = await connectSneakyClient({
388
+ host: options.host,
389
+ baseUrl: options.baseUrl,
390
+ authToken: options.authToken,
391
+ apiKey: options.apiKey,
392
+ remote: options.remote,
393
+ autoStartLocal: options.autoStartLocal,
394
+ homeDir: options.homeDir,
395
+ });
396
+ const incognito = Boolean(options.incognito) || host.type === "cloud";
397
+ const profileId = incognito ? "incognito" : (options.profile?.trim() || defaultProfile || "default");
398
+ let session;
399
+ if (incognito) {
400
+ const headless = options.headful ? false : (options.headless ?? true);
401
+ session = await client.createSession({ mode: "browser", headless, stealth: true });
402
+ }
403
+ else {
404
+ const ensured = await client.ensureProfileSession(profileId, {
405
+ headful: options.headful,
406
+ headless: options.headless,
407
+ });
408
+ session = ensured.session;
409
+ }
410
+ // Upgrade to multiplexed WS RPC for low-latency REPL operations (falls back transparently to HTTP if unavailable).
411
+ try {
412
+ await session.connectRPC();
413
+ }
414
+ catch {
415
+ // HTTP fallback remains active automatically.
416
+ }
417
+ return new SneakyReplSession(client, session, profileId, host, incognito, options.artifactDir);
418
+ }
419
+ hostCallbacks = {
420
+ ensureTabActive: async (targetId) => {
421
+ if (this.activeTargetId === targetId)
422
+ return;
423
+ await this.session.activateTab(targetId);
424
+ this.activeTargetId = targetId;
425
+ },
426
+ onTabClosed: (targetId) => {
427
+ const closedPage = this.attachedTabs.get(targetId);
428
+ this.attachedTabs.delete(targetId);
429
+ this.lastSnapshotByTab.delete(targetId);
430
+ if (this.activeTargetId === targetId) {
431
+ this.activeTargetId = null;
432
+ }
433
+ this.syncTabsGlobal();
434
+ if (closedPage && this.context.page === closedPage) {
435
+ this.context.page = this.attachedTabs.values().next().value ?? null;
436
+ }
437
+ },
438
+ snapshotPage: async (targetPage, opts) => {
439
+ return this.takeSnapshot(targetPage, opts);
440
+ },
441
+ };
442
+ syncTabsGlobal() {
443
+ if (!this.context)
444
+ return;
445
+ this.context.tabs = [...this.attachedTabs.values()];
446
+ }
447
+ attachOrReuse(info) {
448
+ let p = this.attachedTabs.get(info.id);
449
+ if (!p) {
450
+ p = new ReplPage(this.session, info.id, this.hostCallbacks, { url: info.url, title: info.title });
451
+ this.attachedTabs.set(info.id, p);
452
+ }
453
+ else {
454
+ p._updateMeta(info.url, info.title);
455
+ }
456
+ this.syncTabsGlobal();
457
+ return p;
458
+ }
459
+ async takeSnapshot(targetPage, opts = {}) {
460
+ await targetPage.ensureActive();
461
+ let mode = "interactive";
462
+ if (opts.full)
463
+ mode = "full";
464
+ else if (opts.compact)
465
+ mode = "compact";
466
+ else if (opts.interactive === false)
467
+ mode = "full";
468
+ const prevSnapId = this.lastSnapshotByTab.get(targetPage.targetId);
469
+ const wantDiff = opts.diff !== false && Boolean(prevSnapId) && !opts.ref && !opts.selector;
470
+ const raw = await this.session.snapshot({
471
+ mode,
472
+ source: opts.source,
473
+ showHidden: opts.showHidden,
474
+ ref: opts.ref,
475
+ selector: opts.selector,
476
+ maxNodes: opts.maxNodes,
477
+ maxChars: opts.maxChars,
478
+ diffFrom: wantDiff ? prevSnapId : undefined,
479
+ includeTreeWithDiff: true,
480
+ });
481
+ this.lastSnapshotByTab.set(targetPage.targetId, raw.snapshot_id);
482
+ targetPage._updateMeta(raw.page?.url, raw.page?.title);
483
+ return {
484
+ tree: raw.tree ?? "",
485
+ diff: formatSnapshotDiff(raw.diff),
486
+ rawDiff: raw.diff,
487
+ snapshotId: raw.snapshot_id,
488
+ refCount: raw.ref_count,
489
+ refs: raw.refs,
490
+ page: raw.page,
491
+ truncated: raw.truncated,
492
+ };
493
+ }
494
+ async replFetch(input, init) {
495
+ const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
496
+ const method = (init?.method ?? (typeof input !== "string" && !(input instanceof URL) ? input.method : "GET")).toUpperCase();
497
+ const headers = normalizeFetchHeaders(init?.headers ?? (typeof input !== "string" && !(input instanceof URL) ? input.headers : undefined));
498
+ let body;
499
+ if (init?.body !== undefined && init?.body !== null) {
500
+ if (typeof init.body === "string") {
501
+ body = init.body;
502
+ }
503
+ else if (init.body instanceof Uint8Array) {
504
+ body = init.body;
505
+ }
506
+ else if (init.body instanceof ArrayBuffer) {
507
+ body = new Uint8Array(init.body);
508
+ }
509
+ else {
510
+ body = String(init.body);
511
+ }
512
+ }
513
+ // Primary path: real Chromium //net (tfrd) sharing live browser cookies!
514
+ if (!this.client.isCloud) {
515
+ try {
516
+ await this.session.syncBrowserToHttp([urlStr]);
517
+ }
518
+ catch {
519
+ // Best-effort sync; proceed even if browser hasn't visited domain yet.
520
+ }
521
+ try {
522
+ const res = await this.session.fetch(urlStr, { method, headers, body });
523
+ const respHeaders = new Headers();
524
+ for (const [k, v] of res.headers ?? []) {
525
+ try {
526
+ respHeaders.append(k, v);
527
+ }
528
+ catch {
529
+ // Skip invalid/pseudo headers such as :status.
530
+ }
531
+ }
532
+ respHeaders.set("x-sneaky-transport", "tfrd");
533
+ const rawBody = res.body_is_binary && res.body_base64
534
+ ? Buffer.from(res.body_base64, "base64")
535
+ : (res.body ?? "");
536
+ const status = res.status === 204 || res.status === 304 ? res.status : (res.status || 200);
537
+ const webResp = new Response(status === 204 || status === 304 ? null : rawBody, {
538
+ status,
539
+ statusText: res.status_text || "",
540
+ headers: respHeaders,
541
+ });
542
+ Object.defineProperty(webResp, "url", { value: res.url || urlStr, configurable: true });
543
+ return webResp;
544
+ }
545
+ catch (err) {
546
+ const msg = err instanceof Error ? err.message : String(err);
547
+ // Only fall back when tfrd binary itself is absent; propagate genuine network/HTTP errors?
548
+ // Actually if tfrd is unavailable on this machine (e.g. macOS dev box), fall back transparently with browser cookies!
549
+ const isTfrdMissing = msg.includes("tfrd") || msg.includes("not found") || msg.includes("executable") || msg.includes("HTTP 404");
550
+ if (!isTfrdMissing) {
551
+ throw err;
552
+ }
553
+ }
554
+ }
555
+ // Fallback path: native Node fetch with live browser cookies attached automatically.
556
+ const targetURL = new URL(urlStr);
557
+ const hasExplicitCookie = headers.some(([k]) => k.toLowerCase() === "cookie");
558
+ const fallbackHeaders = new Headers();
559
+ for (const [k, v] of headers)
560
+ fallbackHeaders.append(k, v);
561
+ if (!hasExplicitCookie) {
562
+ try {
563
+ const browserCookies = await this.session.cookies("browser", [urlStr]);
564
+ const matched = browserCookies.filter((c) => cookieMatchesUrl(c, targetURL));
565
+ if (matched.length > 0) {
566
+ fallbackHeaders.set("cookie", matched.map((c) => `${c.name}=${c.value}`).join("; "));
567
+ }
568
+ }
569
+ catch {
570
+ // Proceed without cookies if browser cannot report cookies yet.
571
+ }
572
+ }
573
+ const nativeResp = await globalThis.fetch(urlStr, {
574
+ ...init,
575
+ method,
576
+ headers: fallbackHeaders,
577
+ });
578
+ const clonedHeaders = new Headers(nativeResp.headers);
579
+ clonedHeaders.set("x-sneaky-transport", "browser-cookie-fetch");
580
+ const bytes = new Uint8Array(await nativeResp.arrayBuffer());
581
+ const wrapped = new Response(nativeResp.status === 204 || nativeResp.status === 304 ? null : bytes, {
582
+ status: nativeResp.status,
583
+ statusText: nativeResp.statusText,
584
+ headers: clonedHeaders,
585
+ });
586
+ Object.defineProperty(wrapped, "url", { value: nativeResp.url || urlStr, configurable: true });
587
+ return wrapped;
588
+ }
589
+ recordDisplay(input, label) {
590
+ let buf;
591
+ let mimeType = "image/png";
592
+ if (Buffer.isBuffer(input)) {
593
+ buf = input;
594
+ }
595
+ else if (input instanceof Uint8Array) {
596
+ buf = Buffer.from(input);
597
+ }
598
+ else if (typeof input === "string") {
599
+ if (fs.existsSync(input)) {
600
+ buf = fs.readFileSync(input);
601
+ if (input.toLowerCase().endsWith(".jpg") || input.toLowerCase().endsWith(".jpeg"))
602
+ mimeType = "image/jpeg";
603
+ else if (input.toLowerCase().endsWith(".webp"))
604
+ mimeType = "image/webp";
605
+ }
606
+ else {
607
+ buf = Buffer.from(input, "base64");
608
+ }
609
+ }
610
+ else if (input && typeof input === "object") {
611
+ if (input.mimeType)
612
+ mimeType = input.mimeType;
613
+ else if (input.format === "jpeg" || input.format === "jpg")
614
+ mimeType = "image/jpeg";
615
+ else if (input.format === "webp")
616
+ mimeType = "image/webp";
617
+ if (input.buffer)
618
+ buf = Buffer.isBuffer(input.buffer) ? input.buffer : Buffer.from(input.buffer);
619
+ else if (input.base64)
620
+ buf = Buffer.from(input.base64, "base64");
621
+ else
622
+ throw new Error("display() requires a Buffer, image file path, or { buffer | base64 } object");
623
+ }
624
+ else {
625
+ throw new Error("display() requires a Buffer, image file path, or { buffer | base64 } object");
626
+ }
627
+ const ext = mimeType === "image/jpeg" ? "jpg" : mimeType === "image/webp" ? "webp" : "png";
628
+ fs.mkdirSync(this.artifactDir, { recursive: true });
629
+ this.displaySeq++;
630
+ const safeLabel = label ? `-${label.replace(/[^a-zA-Z0-9_-]+/g, "_").slice(0, 32)}` : "";
631
+ const filePath = path.join(this.artifactDir, `display-${Date.now()}-${this.displaySeq}${safeLabel}.${ext}`);
632
+ fs.writeFileSync(filePath, buf);
633
+ const entry = {
634
+ path: filePath,
635
+ mimeType,
636
+ base64: buf.toString("base64"),
637
+ bytes: buf.length,
638
+ label,
639
+ };
640
+ this.turnDisplayed.push(entry);
641
+ this.turnStdout.push(`[display] saved ${filePath} (${buf.length} bytes, ${mimeType})`);
642
+ return entry;
643
+ }
644
+ /** Reinitializes the JS vm.Context cleanly (starts neutral with page = null and empty tabs). */
645
+ resetContext() {
646
+ this.attachedTabs.clear();
647
+ this.lastSnapshotByTab.clear();
648
+ this.activeTargetId = null;
649
+ const replConsole = {
650
+ log: (...args) => this.turnStdout.push(util.format(...args)),
651
+ info: (...args) => this.turnStdout.push(util.format(...args)),
652
+ debug: (...args) => this.turnStdout.push(util.format(...args)),
653
+ dir: (obj, opts) => this.turnStdout.push(util.inspect(obj, { depth: 4, colors: false, ...opts })),
654
+ warn: (...args) => this.turnStderr.push(util.format(...args)),
655
+ error: (...args) => this.turnStderr.push(util.format(...args)),
656
+ };
657
+ const listBrowserTabs = async () => {
658
+ const res = await this.session.tabs();
659
+ const tabs = res.tabs ?? [];
660
+ for (const t of tabs) {
661
+ const existing = this.attachedTabs.get(t.id);
662
+ if (existing)
663
+ existing._updateMeta(t.url, t.title);
664
+ if (t.active)
665
+ this.activeTargetId = t.id;
666
+ }
667
+ return tabs;
668
+ };
669
+ const attachBrowserTab = async (targetId) => {
670
+ if (!targetId)
671
+ throw new Error("attachBrowserTab(targetId) requires a targetId");
672
+ const tabs = await listBrowserTabs();
673
+ const found = tabs.find((t) => t.id === targetId);
674
+ await this.session.activateTab(targetId);
675
+ this.activeTargetId = targetId;
676
+ const p = this.attachOrReuse(found ?? { id: targetId });
677
+ this.context.page = p;
678
+ return p;
679
+ };
680
+ const attachActiveBrowserTab = async () => {
681
+ const tabs = await listBrowserTabs();
682
+ if (tabs.length === 0) {
683
+ return openTab("about:blank");
684
+ }
685
+ const chosen = tabs.find((t) => t.active) ?? tabs[0];
686
+ await this.session.activateTab(chosen.id);
687
+ this.activeTargetId = chosen.id;
688
+ const p = this.attachOrReuse(chosen);
689
+ this.context.page = p;
690
+ return p;
691
+ };
692
+ const getTabByTargetId = async (targetId) => {
693
+ const existing = this.attachedTabs.get(targetId);
694
+ if (existing)
695
+ return existing;
696
+ return attachBrowserTab(targetId);
697
+ };
698
+ const openTab = async (url) => {
699
+ const opened = await this.session.openTab("about:blank");
700
+ this.activeTargetId = opened.target_id;
701
+ const p = this.attachOrReuse({ id: opened.target_id, url: "about:blank", title: "" });
702
+ this.context.page = p;
703
+ if (url && url !== "about:blank") {
704
+ await p.goto(url, { waitUntil: "load" });
705
+ }
706
+ return p;
707
+ };
708
+ const closeTab = async (tabOrId) => {
709
+ const id = typeof tabOrId === "string" ? tabOrId : tabOrId?.targetId;
710
+ if (!id)
711
+ throw new Error("closeTab(tab) requires a ReplPage or targetId");
712
+ await this.session.closeTab(id);
713
+ this.hostCallbacks.onTabClosed(id);
714
+ };
715
+ const snapshot = async (targetPageOrOpts, maybeOpts) => {
716
+ let targetPage;
717
+ let opts;
718
+ if (targetPageOrOpts instanceof ReplPage) {
719
+ targetPage = targetPageOrOpts;
720
+ opts = maybeOpts;
721
+ }
722
+ else if (targetPageOrOpts && typeof targetPageOrOpts === "object") {
723
+ targetPage = this.context.page ?? null;
724
+ opts = targetPageOrOpts;
725
+ }
726
+ else {
727
+ targetPage = this.context.page ?? null;
728
+ opts = maybeOpts;
729
+ }
730
+ if (!targetPage) {
731
+ throw new Error("no active page attached; call openTab(url) or attachActiveBrowserTab() first");
732
+ }
733
+ return this.takeSnapshot(targetPage, opts);
734
+ };
735
+ const annotatedScreenshot = async (targetPageOrOpts, maybeOpts) => {
736
+ let targetPage;
737
+ let opts;
738
+ if (targetPageOrOpts instanceof ReplPage) {
739
+ targetPage = targetPageOrOpts;
740
+ opts = maybeOpts;
741
+ }
742
+ else if (targetPageOrOpts && typeof targetPageOrOpts === "object") {
743
+ targetPage = this.context.page ?? null;
744
+ opts = targetPageOrOpts;
745
+ }
746
+ else {
747
+ targetPage = this.context.page ?? null;
748
+ opts = maybeOpts;
749
+ }
750
+ if (!targetPage) {
751
+ throw new Error("no active page attached; call openTab(url) or attachActiveBrowserTab() first");
752
+ }
753
+ await targetPage.ensureActive();
754
+ const res = await this.session.screenshot({
755
+ format: opts?.format ?? "png",
756
+ quality: opts?.quality,
757
+ fullPage: opts?.fullPage,
758
+ annotate: true,
759
+ });
760
+ const buffer = Buffer.from(res.data, "base64");
761
+ if (opts?.path) {
762
+ fs.mkdirSync(path.dirname(path.resolve(opts.path)), { recursive: true });
763
+ fs.writeFileSync(opts.path, buffer);
764
+ }
765
+ return {
766
+ buffer,
767
+ base64: res.data,
768
+ mimeType: res.mime_type,
769
+ format: res.format,
770
+ annotationCount: res.annotation_count ?? 0,
771
+ annotations: res.annotations ?? [],
772
+ };
773
+ };
774
+ const sandbox = {
775
+ // Browser globals (Aside-compatible neutral start).
776
+ page: null,
777
+ tabs: [],
778
+ listBrowserTabs,
779
+ attachBrowserTab,
780
+ attachActiveBrowserTab,
781
+ getTabByTargetId,
782
+ openTab,
783
+ closeTab,
784
+ snapshot,
785
+ annotatedScreenshot,
786
+ display: (img, label) => this.recordDisplay(img, label),
787
+ // Sneaky superpower: cookie-bearing HTTP via tfrd (with browser-cookie fallback).
788
+ fetch: (input, init) => this.replFetch(input, init),
789
+ cookies: (urls) => this.session.cookies("all", urls),
790
+ setCookies: (list, target = "both") => this.session.setCookies(list, target),
791
+ syncCookies: (direction = "both", urls) => this.session.syncCookies(direction, urls),
792
+ network: this.session.network,
793
+ sneaky: this.client,
794
+ session: this.session,
795
+ // Standard Node & Web utilities.
796
+ console: replConsole,
797
+ fs,
798
+ path,
799
+ Buffer,
800
+ URL,
801
+ URLSearchParams,
802
+ Headers,
803
+ Request,
804
+ Response,
805
+ TextEncoder,
806
+ TextDecoder,
807
+ AbortController,
808
+ AbortSignal,
809
+ setTimeout,
810
+ clearTimeout,
811
+ setInterval,
812
+ clearInterval,
813
+ sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms))),
814
+ pwd: process.cwd(),
815
+ };
816
+ this.context = vm.createContext(sandbox);
817
+ }
818
+ /** Executes JS code in the persistent vm.Context, returning stdout/stderr, return value, and displayed images. */
819
+ async run(code, options = {}) {
820
+ const started = Date.now();
821
+ this.turnStdout = [];
822
+ this.turnStderr = [];
823
+ this.turnDisplayed = [];
824
+ const trimmed = code.trim();
825
+ if (!trimmed) {
826
+ return { ok: true, stdout: "", stderr: "", displayed: [], durationMs: 0 };
827
+ }
828
+ const timeoutMs = Math.max(100, options.timeoutMs ?? 60_000);
829
+ let script;
830
+ try {
831
+ const { wrapped } = transformReplCode(trimmed, { captureLastExpr: true });
832
+ script = new vm.Script(wrapped, { filename: "sneaky-repl.js" });
833
+ }
834
+ catch (err) {
835
+ if (err instanceof SyntaxError) {
836
+ try {
837
+ const { wrapped } = transformReplCode(trimmed, { captureLastExpr: false });
838
+ script = new vm.Script(wrapped, { filename: "sneaky-repl.js" });
839
+ }
840
+ catch (err2) {
841
+ return {
842
+ ok: false,
843
+ stdout: "",
844
+ stderr: "",
845
+ displayed: [],
846
+ error: err2 instanceof Error ? err2.message : String(err2),
847
+ durationMs: Date.now() - started,
848
+ };
849
+ }
850
+ }
851
+ else {
852
+ return {
853
+ ok: false,
854
+ stdout: "",
855
+ stderr: "",
856
+ displayed: [],
857
+ error: err instanceof Error ? err.message : String(err),
858
+ durationMs: Date.now() - started,
859
+ };
860
+ }
861
+ }
862
+ let timer;
863
+ try {
864
+ const execPromise = Promise.resolve(script.runInContext(this.context, { timeout: timeoutMs }));
865
+ const timeoutPromise = new Promise((_, reject) => {
866
+ timer = setTimeout(() => reject(new Error(`REPL execution timed out after ${timeoutMs}ms`)), timeoutMs);
867
+ });
868
+ const result = await Promise.race([execPromise, timeoutPromise]);
869
+ const resultFormatted = result === undefined
870
+ ? undefined
871
+ : typeof result === "string"
872
+ ? result
873
+ : util.inspect(result, { depth: 4, colors: false, maxArrayLength: 100 });
874
+ return {
875
+ ok: true,
876
+ stdout: this.turnStdout.join("\n"),
877
+ stderr: this.turnStderr.join("\n"),
878
+ result,
879
+ resultFormatted,
880
+ displayed: [...this.turnDisplayed],
881
+ durationMs: Date.now() - started,
882
+ };
883
+ }
884
+ catch (err) {
885
+ return {
886
+ ok: false,
887
+ stdout: this.turnStdout.join("\n"),
888
+ stderr: this.turnStderr.join("\n"),
889
+ displayed: [...this.turnDisplayed],
890
+ error: err instanceof Error ? (err.stack || err.message) : String(err),
891
+ durationMs: Date.now() - started,
892
+ };
893
+ }
894
+ finally {
895
+ if (timer)
896
+ clearTimeout(timer);
897
+ }
898
+ }
899
+ /** Closes WS RPC; if this session is ephemeral (--incognito or cloud), also closes the browser session. */
900
+ async close() {
901
+ if (this.ephemeral) {
902
+ try {
903
+ await this.session.close();
904
+ }
905
+ catch {
906
+ // Ignore close errors during shutdown.
907
+ }
908
+ return;
909
+ }
910
+ // Keep persistent profile browser running in daemon, just release WS if open.
911
+ const anySess = this.session;
912
+ if (anySess.rpcWs) {
913
+ try {
914
+ anySess.rpcWs.close();
915
+ }
916
+ catch {
917
+ // Ignore WS close errors.
918
+ }
919
+ anySess.rpcWs = undefined;
920
+ }
921
+ }
922
+ }
923
+ //# sourceMappingURL=index.js.map