@querying/sneaky 0.3.0 → 0.4.1

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.
@@ -24,102 +24,86 @@ export class ReplLocator {
24
24
  return new ReplLocator(this.page, { ...this.target, nth: index });
25
25
  }
26
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);
27
+ return this.page.session.act({ type: "click", target: this.target, button: options?.button, click_count: options?.clickCount }, { ...options, ...this.page.callScope() });
29
28
  }
30
29
  async dblclick(options) {
31
- await this.page.ensureActive();
32
- return this.page.session.act({ type: "dblclick", target: this.target }, options);
30
+ return this.page.session.act({ type: "dblclick", target: this.target }, { ...options, ...this.page.callScope() });
33
31
  }
34
32
  async hover(options) {
35
- await this.page.ensureActive();
36
- return this.page.session.act({ type: "hover", target: this.target }, options);
33
+ return this.page.session.act({ type: "hover", target: this.target }, { ...options, ...this.page.callScope() });
34
+ }
35
+ async dragTo(destination, options) {
36
+ const to = destination instanceof ReplLocator ? destination.target : parseTarget(destination);
37
+ return this.page.session.act({ type: "drag", target: this.target, to, button: options?.button }, { ...options, ...this.page.callScope() });
37
38
  }
38
39
  async fill(text, options) {
39
- await this.page.ensureActive();
40
- return this.page.session.fill(this.target, text, options);
40
+ return this.page.session.fill(this.target, text, { ...options, ...this.page.callScope() });
41
41
  }
42
42
  async fillSecret(accountId, field, options) {
43
- await this.page.ensureActive();
44
- return this.page.session.fillSecret(this.target, accountId, field, options);
43
+ return this.page.session.fillSecret(this.target, accountId, field, { ...options, ...this.page.callScope() });
45
44
  }
46
45
  async type(text, options) {
47
- await this.page.ensureActive();
48
- return this.page.session.act({ type: "type", target: this.target, text }, options);
46
+ return this.page.session.act({ type: "type", target: this.target, text }, { ...options, ...this.page.callScope() });
49
47
  }
50
48
  async press(key, options) {
51
- await this.page.ensureActive();
52
49
  return this.page.session.act([
53
50
  { type: "click", target: this.target, speed: "fast" },
54
51
  { type: "press", key },
55
- ], options);
52
+ ], { ...options, ...this.page.callScope() });
56
53
  }
57
54
  async selectOption(valueOrOpt, options) {
58
- await this.page.ensureActive();
59
55
  const spec = typeof valueOrOpt === "string" ? { value: valueOrOpt } : valueOrOpt;
60
- return this.page.session.act({ type: "select", target: this.target, value: spec.value, label: spec.label }, options);
56
+ return this.page.session.act({ type: "select", target: this.target, value: spec.value, label: spec.label }, { ...options, ...this.page.callScope() });
57
+ }
58
+ async setInputFiles(files, options) {
59
+ return this.page.session.upload(this.target, files, { ...options, ...this.page.callScope() });
61
60
  }
62
61
  async waitFor(options) {
63
- await this.page.ensureActive();
64
- return this.page.session.act({ type: "wait", target: this.target, timeout_ms: options?.timeout });
62
+ return this.page.session.act({ type: "wait", target: this.target, timeout_ms: options?.timeout }, this.page.callScope());
65
63
  }
66
64
  async textContent() {
67
- await this.page.ensureActive();
68
- return (await this.page.session.query(this.target, "textContent")).value;
65
+ return (await this.page.session.query(this.target, "textContent", undefined, this.page.callScope())).value;
69
66
  }
70
67
  async innerText() {
71
- await this.page.ensureActive();
72
- return (await this.page.session.query(this.target, "innerText")).value;
68
+ return (await this.page.session.query(this.target, "innerText", undefined, this.page.callScope())).value;
73
69
  }
74
70
  async innerHTML() {
75
- await this.page.ensureActive();
76
- return (await this.page.session.query(this.target, "innerHTML")).value;
71
+ return (await this.page.session.query(this.target, "innerHTML", undefined, this.page.callScope())).value;
77
72
  }
78
73
  async outerHTML() {
79
- await this.page.ensureActive();
80
- return (await this.page.session.query(this.target, "outerHTML")).value;
74
+ return (await this.page.session.query(this.target, "outerHTML", undefined, this.page.callScope())).value;
81
75
  }
82
76
  async inputValue() {
83
- await this.page.ensureActive();
84
- return (await this.page.session.query(this.target, "inputValue")).value;
77
+ return (await this.page.session.query(this.target, "inputValue", undefined, this.page.callScope())).value;
85
78
  }
86
79
  async getAttribute(name) {
87
- await this.page.ensureActive();
88
- return (await this.page.session.query(this.target, "getAttribute", name)).value;
80
+ return (await this.page.session.query(this.target, "getAttribute", name, this.page.callScope())).value;
89
81
  }
90
82
  async isVisible() {
91
- await this.page.ensureActive();
92
- return Boolean((await this.page.session.query(this.target, "isVisible")).value);
83
+ return Boolean((await this.page.session.query(this.target, "isVisible", undefined, this.page.callScope())).value);
93
84
  }
94
85
  async isEnabled() {
95
- await this.page.ensureActive();
96
- return Boolean((await this.page.session.query(this.target, "isEnabled")).value);
86
+ return Boolean((await this.page.session.query(this.target, "isEnabled", undefined, this.page.callScope())).value);
97
87
  }
98
88
  async isChecked() {
99
- await this.page.ensureActive();
100
- return Boolean((await this.page.session.query(this.target, "isChecked")).value);
89
+ return Boolean((await this.page.session.query(this.target, "isChecked", undefined, this.page.callScope())).value);
101
90
  }
102
91
  async count() {
103
- await this.page.ensureActive();
104
- return Number((await this.page.session.query(this.target, "count")).value ?? 0);
92
+ return Number((await this.page.session.query(this.target, "count", undefined, this.page.callScope())).value ?? 0);
105
93
  }
106
94
  async boundingBox() {
107
- await this.page.ensureActive();
108
- return (await this.page.session.query(this.target, "boundingBox")).value;
95
+ return (await this.page.session.query(this.target, "boundingBox", undefined, this.page.callScope())).value;
109
96
  }
110
97
  async allTextContents() {
111
- await this.page.ensureActive();
112
- const v = (await this.page.session.query(this.target, "allTextContents")).value;
98
+ const v = (await this.page.session.query(this.target, "allTextContents", undefined, this.page.callScope())).value;
113
99
  return Array.isArray(v) ? v : [];
114
100
  }
115
101
  async allInnerTexts() {
116
- await this.page.ensureActive();
117
- const v = (await this.page.session.query(this.target, "allInnerTexts")).value;
102
+ const v = (await this.page.session.query(this.target, "allInnerTexts", undefined, this.page.callScope())).value;
118
103
  return Array.isArray(v) ? v : [];
119
104
  }
120
105
  async screenshot(options = {}) {
121
- await this.page.ensureActive();
122
- const res = await this.page.session.screenshot({ ...options, target: this.target });
106
+ const res = await this.page.session.screenshot({ ...options, target: this.target, ...this.page.callScope() });
123
107
  const buf = Buffer.from(res.data, "base64");
124
108
  if (options.path) {
125
109
  fs.mkdirSync(path.dirname(path.resolve(options.path)), { recursive: true });
@@ -142,38 +126,39 @@ export class ReplPage {
142
126
  this.host = host;
143
127
  this.currentUrl = initialMeta?.url ?? "about:blank";
144
128
  this.currentTitle = initialMeta?.title ?? "";
129
+ this.spaceName = initialMeta?.space;
145
130
  this.keyboard = {
146
131
  press: async (key) => {
147
- await this.ensureActive();
148
- return this.session.press(key);
132
+ return this.session.press(key, this.callScope());
149
133
  },
150
134
  type: async (text, options) => {
151
- await this.ensureActive();
152
- return this.session.act({ type: "type", text }, options);
135
+ return this.session.act({ type: "type", text }, { ...options, ...this.callScope() });
153
136
  },
154
137
  };
155
138
  this.mouse = {
156
139
  click: async (x, y, options) => {
157
- await this.ensureActive();
158
140
  return this.session.act({
159
141
  type: "click",
160
142
  target: { x, y },
161
143
  button: options?.button,
162
144
  click_count: options?.clickCount,
163
145
  speed: options?.speed,
164
- });
146
+ }, this.callScope());
165
147
  },
166
148
  move: async (x, y, options) => {
167
- await this.ensureActive();
168
- return this.session.act({ type: "hover", target: { x, y } }, options);
149
+ return this.session.act({ type: "hover", target: { x, y } }, { ...options, ...this.callScope() });
169
150
  },
170
151
  wheel: async (dx, dy) => {
171
- await this.ensureActive();
172
- return this.session.act({ type: "scroll", dx, dy });
152
+ return this.session.act({ type: "scroll", dx, dy }, this.callScope());
173
153
  },
174
154
  };
175
155
  }
176
- /** Internal: activates this tab on the daemon if it is not already the front tab. */
156
+ spaceName;
157
+ /** Returns the daemon call scope pinning all actions directly to this page's CDP targetId without stealing foreground focus. */
158
+ callScope() {
159
+ return { targetId: this.targetId, space: this.spaceName };
160
+ }
161
+ /** Internal: activates this tab on the daemon only when explicitly requested (e.g. bringToFront). */
177
162
  async ensureActive() {
178
163
  await this.host.ensureTabActive(this.targetId);
179
164
  }
@@ -188,50 +173,48 @@ export class ReplPage {
188
173
  return this.currentUrl;
189
174
  }
190
175
  async title() {
191
- await this.ensureActive();
192
- const res = await this.session.eval("document.title || ''", { world: "isolated", awaitPromise: false });
176
+ const res = await this.session.eval("document.title || ''", {
177
+ world: "isolated",
178
+ awaitPromise: false,
179
+ ...this.callScope(),
180
+ });
193
181
  this.currentTitle = typeof res.value === "string" ? res.value : this.currentTitle;
194
182
  return this.currentTitle;
195
183
  }
196
184
  async goto(url, options = {}) {
197
- await this.ensureActive();
198
185
  const res = await this.session.goto(url, {
199
186
  waitUntil: options.waitUntil ?? "load",
200
187
  timeoutMs: options.timeout,
188
+ ...this.callScope(),
201
189
  });
202
190
  this._updateMeta(res.url, res.title);
203
191
  return res;
204
192
  }
205
193
  async reload(options = {}) {
206
- await this.ensureActive();
207
194
  const res = await this.session.act({
208
195
  type: "reload",
209
196
  wait_until: options.waitUntil,
210
197
  timeout_ms: options.timeout,
211
- });
198
+ }, this.callScope());
212
199
  this._updateMeta(res.page?.url, res.page?.title);
213
200
  return res;
214
201
  }
215
202
  async goBack() {
216
- await this.ensureActive();
217
- const res = await this.session.act({ type: "back" });
203
+ const res = await this.session.act({ type: "back" }, this.callScope());
218
204
  this._updateMeta(res.page?.url, res.page?.title);
219
205
  return res;
220
206
  }
221
207
  async goForward() {
222
- await this.ensureActive();
223
- const res = await this.session.act({ type: "forward" });
208
+ const res = await this.session.act({ type: "forward" }, this.callScope());
224
209
  this._updateMeta(res.page?.url, res.page?.title);
225
210
  return res;
226
211
  }
227
212
  async content() {
228
- await this.ensureActive();
229
- const res = await this.session.eval("document.documentElement ? document.documentElement.outerHTML : ''", { world: "isolated", awaitPromise: false });
213
+ const res = await this.session.eval("document.documentElement ? document.documentElement.outerHTML : ''", { world: "isolated", awaitPromise: false, ...this.callScope() });
230
214
  return typeof res.value === "string" ? res.value : "";
231
215
  }
232
216
  /** Evaluates a function or JS expression in the page's main world WITHOUT calling Runtime.enable. */
233
217
  async evaluate(fnOrExpr, arg) {
234
- await this.ensureActive();
235
218
  let expression;
236
219
  if (typeof fnOrExpr === "function") {
237
220
  const serializedArg = arg === undefined ? "" : JSON.stringify(arg);
@@ -240,16 +223,14 @@ export class ReplPage {
240
223
  else {
241
224
  expression = fnOrExpr;
242
225
  }
243
- const res = await this.session.eval(expression, { world: "main", awaitPromise: true });
226
+ const res = await this.session.eval(expression, { world: "main", awaitPromise: true, ...this.callScope() });
244
227
  return res.value;
245
228
  }
246
229
  async setViewportSize(size) {
247
- await this.ensureActive();
248
- return this.session.setViewport(size);
230
+ return this.session.setViewport({ ...size, ...this.callScope() });
249
231
  }
250
232
  async screenshot(options = {}) {
251
- await this.ensureActive();
252
- const res = await this.session.screenshot(options);
233
+ const res = await this.session.screenshot({ ...options, ...this.callScope() });
253
234
  const buf = Buffer.from(res.data, "base64");
254
235
  if (options.path) {
255
236
  fs.mkdirSync(path.dirname(path.resolve(options.path)), { recursive: true });
@@ -258,8 +239,7 @@ export class ReplPage {
258
239
  return buf;
259
240
  }
260
241
  async pdf(options = {}) {
261
- await this.ensureActive();
262
- const res = await this.session.pdf(options);
242
+ const res = await this.session.pdf({ ...options, ...this.callScope() });
263
243
  const buf = Buffer.from(res.data, "base64");
264
244
  if (options.path) {
265
245
  fs.mkdirSync(path.dirname(path.resolve(options.path)), { recursive: true });
@@ -268,11 +248,11 @@ export class ReplPage {
268
248
  return buf;
269
249
  }
270
250
  async extract(options = {}) {
271
- await this.ensureActive();
272
251
  return this.session.extract({
273
252
  kind: options.kind ?? "markdown",
274
253
  target: options.selector ? parseTarget(options.selector) : undefined,
275
254
  maxChars: options.maxChars,
255
+ ...this.callScope(),
276
256
  });
277
257
  }
278
258
  async snapshot(options) {
@@ -282,17 +262,62 @@ export class ReplPage {
282
262
  await new Promise((r) => setTimeout(r, Math.max(0, ms)));
283
263
  }
284
264
  async waitForSelector(selectorOrRef, options = {}) {
285
- await this.ensureActive();
286
- return this.session.act({ type: "wait", target: parseTarget(selectorOrRef), timeout_ms: options.timeout });
265
+ return this.session.act({ type: "wait", target: parseTarget(selectorOrRef), timeout_ms: options.timeout }, this.callScope());
287
266
  }
288
267
  async waitForURL(urlSubstring, options = {}) {
289
- await this.ensureActive();
290
- return this.session.act({ type: "wait", url_contains: urlSubstring, timeout_ms: options.timeout });
268
+ return this.session.act({ type: "wait", url_contains: urlSubstring, timeout_ms: options.timeout }, this.callScope());
291
269
  }
292
270
  async bringToFront() {
293
271
  await this.session.activateTab(this.targetId);
294
272
  await this.host.ensureTabActive(this.targetId);
295
273
  }
274
+ async hover(selectorOrTarget, options) {
275
+ return this.session.act({ type: "hover", target: parseTarget(selectorOrTarget) }, { ...options, ...this.callScope() });
276
+ }
277
+ async dragAndDrop(source, target, options) {
278
+ return this.session.act({ type: "drag", target: parseTarget(source), to: parseTarget(target), button: options?.button }, { ...options, ...this.callScope() });
279
+ }
280
+ async pendingDialog() {
281
+ return (await this.session.pendingDialog(this.callScope())).dialog ?? null;
282
+ }
283
+ async acceptDialog(promptText) {
284
+ return this.session.acceptDialog(promptText, this.callScope());
285
+ }
286
+ async dismissDialog() {
287
+ return this.session.dismissDialog(this.callScope());
288
+ }
289
+ async setInputFiles(selectorOrTarget, files, options) {
290
+ return this.session.upload(selectorOrTarget, files, { ...options, ...this.callScope() });
291
+ }
292
+ async downloads() {
293
+ return (await this.session.downloads()).downloads ?? [];
294
+ }
295
+ async waitForDownload(triggerOrOpts, maybeOpts) {
296
+ const trigger = typeof triggerOrOpts === "function" ? triggerOrOpts : undefined;
297
+ const opts = typeof triggerOrOpts === "function" ? maybeOpts : triggerOrOpts;
298
+ const current = await this.session.downloads();
299
+ const waitPromise = this.session.waitForDownload({
300
+ downloadDir: opts?.downloadDir,
301
+ sinceSeq: current.seq,
302
+ timeoutMs: opts?.timeout,
303
+ });
304
+ if (trigger) {
305
+ const [dl] = await Promise.all([waitPromise, trigger()]);
306
+ return dl;
307
+ }
308
+ return waitPromise;
309
+ }
310
+ async waitForPopup(triggerOrOpts, maybeOpts) {
311
+ const trigger = typeof triggerOrOpts === "function" ? triggerOrOpts : undefined;
312
+ const opts = typeof triggerOrOpts === "function" ? maybeOpts : triggerOrOpts;
313
+ const waitPromise = this.session.waitForPopup({
314
+ openerId: this.targetId,
315
+ timeoutMs: opts?.timeout,
316
+ ...this.callScope(),
317
+ });
318
+ const pop = trigger ? (await Promise.all([waitPromise, trigger()]))[0] : await waitPromise;
319
+ return this.host.attachPopupTab(pop, this.spaceName);
320
+ }
296
321
  async close() {
297
322
  await this.session.closeTab(this.targetId);
298
323
  this.host.onTabClosed(this.targetId);
@@ -316,6 +341,71 @@ export class ReplPage {
316
341
  return `ReplPage(${this.targetId}, ${this.currentUrl})`;
317
342
  }
318
343
  }
344
+ /**
345
+ * Isolated parallel Space handle (inspired by Ego Lite's TaskSpace).
346
+ * Safe to use concurrently inside `Promise.all(...)` within a single REPL script:
347
+ * tabs created through a `ReplSpace` stay pinned to that Space without mutating the
348
+ * shared global `page` binding or stealing foreground tab focus.
349
+ */
350
+ export class ReplSpace {
351
+ name;
352
+ profileId;
353
+ openScopedTab;
354
+ listSpaceTabs;
355
+ focusSpace;
356
+ handoffSpaceFn;
357
+ resumeSpaceFn;
358
+ waitResumeFn;
359
+ closeSpaceFn;
360
+ tabs = [];
361
+ page = null;
362
+ constructor(name, profileId, openScopedTab, listSpaceTabs, focusSpace, handoffSpaceFn, resumeSpaceFn, waitResumeFn, closeSpaceFn, initialPage) {
363
+ this.name = name;
364
+ this.profileId = profileId;
365
+ this.openScopedTab = openScopedTab;
366
+ this.listSpaceTabs = listSpaceTabs;
367
+ this.focusSpace = focusSpace;
368
+ this.handoffSpaceFn = handoffSpaceFn;
369
+ this.resumeSpaceFn = resumeSpaceFn;
370
+ this.waitResumeFn = waitResumeFn;
371
+ this.closeSpaceFn = closeSpaceFn;
372
+ if (initialPage) {
373
+ this.page = initialPage;
374
+ this.tabs.push(initialPage);
375
+ }
376
+ }
377
+ async openTab(url) {
378
+ const p = await this.openScopedTab(url);
379
+ this.page = p;
380
+ if (!this.tabs.some((t) => t.targetId === p.targetId)) {
381
+ this.tabs.push(p);
382
+ }
383
+ return p;
384
+ }
385
+ async listTabs() {
386
+ return this.listSpaceTabs();
387
+ }
388
+ async focus() {
389
+ return this.focusSpace();
390
+ }
391
+ async handoff(options) {
392
+ return this.handoffSpaceFn(options);
393
+ }
394
+ async resume() {
395
+ return this.resumeSpaceFn();
396
+ }
397
+ async waitForResume(timeoutMs) {
398
+ return this.waitResumeFn(timeoutMs);
399
+ }
400
+ async close() {
401
+ this.tabs.length = 0;
402
+ this.page = null;
403
+ return this.closeSpaceFn();
404
+ }
405
+ toString() {
406
+ return `ReplSpace(${this.profileId}/${this.name}, tabs=${this.tabs.length})`;
407
+ }
408
+ }
319
409
  function formatSnapshotDiff(diff) {
320
410
  if (!diff)
321
411
  return null;
@@ -378,13 +468,18 @@ export class SneakyReplSession {
378
468
  turnDisplayed = [];
379
469
  displaySeq = 0;
380
470
  artifactDir;
381
- constructor(client, session, profileId, host, ephemeral, artifactDir) {
471
+ currentSpace = null;
472
+ get spaceName() {
473
+ return this.currentSpace;
474
+ }
475
+ constructor(client, session, profileId, host, ephemeral, artifactDir, initialSpace) {
382
476
  this.client = client;
383
477
  this.session = session;
384
478
  this.profileId = profileId;
385
479
  this.host = host;
386
480
  this.ephemeral = ephemeral;
387
481
  this.artifactDir = artifactDir ?? path.join(sneakyHomeDir(), "artifacts");
482
+ this.currentSpace = initialSpace?.trim() || null;
388
483
  this.resetContext();
389
484
  }
390
485
  static async connect(options = {}) {
@@ -399,15 +494,34 @@ export class SneakyReplSession {
399
494
  });
400
495
  const incognito = Boolean(options.incognito) || host.type === "cloud";
401
496
  const profileId = incognito ? "incognito" : (options.profile?.trim() || defaultProfile || "default");
497
+ const space = options.space?.trim() || undefined;
402
498
  let session;
499
+ let initialSpaceTargetId;
500
+ let initialSpaceUrl;
501
+ let initialSpaceTitle;
502
+ const background = options.background ?? true;
403
503
  if (incognito) {
404
504
  const headless = options.headful ? false : (options.headless ?? true);
405
- session = await client.createSession({ mode: "browser", headless, stealth: true });
505
+ session = await client.createSession({ mode: "browser", headless, background, stealth: true });
506
+ }
507
+ else if (space) {
508
+ const sp = await client.ensureSpace(profileId, {
509
+ name: space,
510
+ client: options.clientName ?? "repl",
511
+ createTab: true,
512
+ headful: options.headful,
513
+ headless: options.headless,
514
+ });
515
+ session = client.attachSession(sp.session_id);
516
+ initialSpaceTargetId = sp.target_id || sp.space.active_target_id;
517
+ initialSpaceUrl = sp.space.active_url;
518
+ initialSpaceTitle = sp.space.active_title;
406
519
  }
407
520
  else {
408
521
  const ensured = await client.ensureProfileSession(profileId, {
409
522
  headful: options.headful,
410
523
  headless: options.headless,
524
+ background,
411
525
  });
412
526
  session = ensured.session;
413
527
  }
@@ -418,7 +532,17 @@ export class SneakyReplSession {
418
532
  catch {
419
533
  // HTTP fallback remains active automatically.
420
534
  }
421
- return new SneakyReplSession(client, session, profileId, host, incognito, options.artifactDir);
535
+ const repl = new SneakyReplSession(client, session, profileId, host, incognito, options.artifactDir, space);
536
+ if (initialSpaceTargetId) {
537
+ const p = repl.attachOrReuse({
538
+ id: initialSpaceTargetId,
539
+ url: initialSpaceUrl,
540
+ title: initialSpaceTitle,
541
+ space,
542
+ });
543
+ repl.context.page = p;
544
+ }
545
+ return repl;
422
546
  }
423
547
  hostCallbacks = {
424
548
  ensureTabActive: async (targetId) => {
@@ -442,6 +566,14 @@ export class SneakyReplSession {
442
566
  snapshotPage: async (targetPage, opts) => {
443
567
  return this.takeSnapshot(targetPage, opts);
444
568
  },
569
+ attachPopupTab: (popup, space) => {
570
+ return this.attachOrReuse({
571
+ id: popup.target_id,
572
+ url: popup.url,
573
+ title: popup.title,
574
+ space: space ?? this.currentSpace ?? undefined,
575
+ });
576
+ },
445
577
  };
446
578
  syncTabsGlobal() {
447
579
  if (!this.context)
@@ -451,7 +583,11 @@ export class SneakyReplSession {
451
583
  attachOrReuse(info) {
452
584
  let p = this.attachedTabs.get(info.id);
453
585
  if (!p) {
454
- p = new ReplPage(this.session, info.id, this.hostCallbacks, { url: info.url, title: info.title });
586
+ p = new ReplPage(this.session, info.id, this.hostCallbacks, {
587
+ url: info.url,
588
+ title: info.title,
589
+ space: info.space ?? this.currentSpace ?? undefined,
590
+ });
455
591
  this.attachedTabs.set(info.id, p);
456
592
  }
457
593
  else {
@@ -461,7 +597,6 @@ export class SneakyReplSession {
461
597
  return p;
462
598
  }
463
599
  async takeSnapshot(targetPage, opts = {}) {
464
- await targetPage.ensureActive();
465
600
  let mode = "interactive";
466
601
  if (opts.full)
467
602
  mode = "full";
@@ -481,6 +616,7 @@ export class SneakyReplSession {
481
616
  maxChars: opts.maxChars,
482
617
  diffFrom: wantDiff ? prevSnapId : undefined,
483
618
  includeTreeWithDiff: true,
619
+ ...targetPage.callScope(),
484
620
  });
485
621
  this.lastSnapshotByTab.set(targetPage.targetId, raw.snapshot_id);
486
622
  targetPage._updateMeta(raw.page?.url, raw.page?.title);
@@ -670,25 +806,29 @@ export class SneakyReplSession {
670
806
  }
671
807
  return tabs;
672
808
  };
673
- const attachBrowserTab = async (targetId) => {
809
+ const attachBrowserTab = async (targetId, opts) => {
674
810
  if (!targetId)
675
811
  throw new Error("attachBrowserTab(targetId) requires a targetId");
676
812
  const tabs = await listBrowserTabs();
677
813
  const found = tabs.find((t) => t.id === targetId);
678
- await this.session.activateTab(targetId);
679
- this.activeTargetId = targetId;
814
+ if (opts?.focus) {
815
+ await this.session.activateTab(targetId);
816
+ this.activeTargetId = targetId;
817
+ }
680
818
  const p = this.attachOrReuse(found ?? { id: targetId });
681
819
  this.context.page = p;
682
820
  return p;
683
821
  };
684
- const attachActiveBrowserTab = async () => {
822
+ const attachActiveBrowserTab = async (opts) => {
685
823
  const tabs = await listBrowserTabs();
686
824
  if (tabs.length === 0) {
687
825
  return openTab("about:blank");
688
826
  }
689
827
  const chosen = tabs.find((t) => t.active) ?? tabs[0];
690
- await this.session.activateTab(chosen.id);
691
- this.activeTargetId = chosen.id;
828
+ if (opts?.focus) {
829
+ await this.session.activateTab(chosen.id);
830
+ this.activeTargetId = chosen.id;
831
+ }
692
832
  const p = this.attachOrReuse(chosen);
693
833
  this.context.page = p;
694
834
  return p;
@@ -699,16 +839,111 @@ export class SneakyReplSession {
699
839
  return existing;
700
840
  return attachBrowserTab(targetId);
701
841
  };
702
- const openTab = async (url) => {
703
- const opened = await this.session.openTab("about:blank");
704
- this.activeTargetId = opened.target_id;
705
- const p = this.attachOrReuse({ id: opened.target_id, url: "about:blank", title: "" });
842
+ const openTab = async (url, opts) => {
843
+ const space = opts?.space ?? this.currentSpace ?? undefined;
844
+ const background = opts?.background ?? true;
845
+ const opened = await this.session.openTab("about:blank", { background, space });
846
+ if (!background) {
847
+ this.activeTargetId = opened.target_id;
848
+ }
849
+ const p = this.attachOrReuse({ id: opened.target_id, url: "about:blank", title: "", space });
706
850
  this.context.page = p;
707
851
  if (url && url !== "about:blank") {
708
852
  await p.goto(url, { waitUntil: "load" });
709
853
  }
710
854
  return p;
711
855
  };
856
+ const openSpace = async (name, opts) => {
857
+ if (this.ephemeral) {
858
+ throw new Error("openSpace() requires a persistent profile (not --incognito)");
859
+ }
860
+ const spaceName = name.trim();
861
+ if (!spaceName) {
862
+ throw new Error("openSpace(name) requires a non-empty space name");
863
+ }
864
+ const wantInitial = opts?.createTab ?? Boolean(opts?.url);
865
+ const sp = await this.client.ensureSpace(this.profileId, {
866
+ name: spaceName,
867
+ url: opts?.url,
868
+ client: "repl",
869
+ createTab: wantInitial,
870
+ });
871
+ let initialPage = null;
872
+ if (wantInitial && sp.target_id) {
873
+ initialPage = this.attachOrReuse({
874
+ id: sp.target_id,
875
+ url: sp.space.active_url || opts?.url || "about:blank",
876
+ title: sp.space.active_title || "",
877
+ space: sp.space.name,
878
+ });
879
+ }
880
+ const openScopedTab = async (url) => {
881
+ const opened = await this.session.openTab("about:blank", { background: true, space: sp.space.name });
882
+ const p = this.attachOrReuse({ id: opened.target_id, url: "about:blank", title: "", space: sp.space.name });
883
+ if (url && url !== "about:blank") {
884
+ await p.goto(url, { waitUntil: "load" });
885
+ }
886
+ return p;
887
+ };
888
+ const listSpaceTabs = async () => {
889
+ const all = await listBrowserTabs();
890
+ return all.filter((t) => t.space === sp.space.name);
891
+ };
892
+ const focusSpace = () => this.client.focusSpace(this.profileId, sp.space.name);
893
+ const handoffSpaceFn = (hOpts) => this.client.handoffSpace(this.profileId, sp.space.name, hOpts);
894
+ const resumeSpaceFn = () => this.client.resumeSpace(this.profileId, sp.space.name);
895
+ const waitResumeFn = (timeoutMs) => this.client.waitForSpaceResume(this.profileId, sp.space.name, { timeoutMs });
896
+ const closeSpaceFn = () => this.client.closeSpace(this.profileId, sp.space.name);
897
+ return new ReplSpace(sp.space.name, this.profileId, openScopedTab, listSpaceTabs, focusSpace, handoffSpaceFn, resumeSpaceFn, waitResumeFn, closeSpaceFn, initialPage);
898
+ };
899
+ const useSpace = async (name, url) => {
900
+ if (this.ephemeral) {
901
+ throw new Error("useSpace() requires a persistent profile (not --incognito)");
902
+ }
903
+ const sp = await this.client.ensureSpace(this.profileId, {
904
+ name,
905
+ url,
906
+ client: "repl",
907
+ createTab: true,
908
+ });
909
+ this.currentSpace = sp.space.name;
910
+ this.context.spaceName = this.currentSpace;
911
+ const p = this.attachOrReuse({
912
+ id: sp.target_id,
913
+ url: sp.space.active_url || url || "about:blank",
914
+ title: sp.space.active_title || "",
915
+ space: sp.space.name,
916
+ });
917
+ this.context.page = p;
918
+ return p;
919
+ };
920
+ const listSpaces = async () => {
921
+ if (this.ephemeral)
922
+ return [];
923
+ return (await this.client.spaces(this.profileId)).spaces;
924
+ };
925
+ const closeSpace = async (name) => {
926
+ if (this.ephemeral)
927
+ return { deleted: false, closed_tabs: 0 };
928
+ const target = name?.trim() || this.currentSpace;
929
+ if (!target)
930
+ throw new Error("closeSpace(name?) requires a space name");
931
+ const res = await this.client.closeSpace(this.profileId, target);
932
+ if (this.currentSpace === target) {
933
+ this.currentSpace = null;
934
+ this.context.spaceName = null;
935
+ }
936
+ return res;
937
+ };
938
+ const freezeInactiveTabs = async (minIdleSeconds = 0) => {
939
+ if (!this.ephemeral) {
940
+ return this.client.freezeProfileTabs(this.profileId, { minIdleSeconds });
941
+ }
942
+ return this.session.freezeTabs({ minIdleSeconds });
943
+ };
944
+ const trimMemory = async () => {
945
+ return this.session.trimMemory();
946
+ };
712
947
  const closeTab = async (tabOrId) => {
713
948
  const id = typeof tabOrId === "string" ? tabOrId : tabOrId?.targetId;
714
949
  if (!id)
@@ -754,12 +989,12 @@ export class SneakyReplSession {
754
989
  if (!targetPage) {
755
990
  throw new Error("no active page attached; call openTab(url) or attachActiveBrowserTab() first");
756
991
  }
757
- await targetPage.ensureActive();
758
992
  const res = await this.session.screenshot({
759
993
  format: opts?.format ?? "png",
760
994
  quality: opts?.quality,
761
995
  fullPage: opts?.fullPage,
762
996
  annotate: true,
997
+ ...targetPage.callScope(),
763
998
  });
764
999
  const buffer = Buffer.from(res.data, "base64");
765
1000
  if (opts?.path) {
@@ -775,6 +1010,94 @@ export class SneakyReplSession {
775
1010
  annotations: res.annotations ?? [],
776
1011
  };
777
1012
  };
1013
+ const siteNote = async (domainOrUrl) => {
1014
+ let target = domainOrUrl?.trim() ?? "";
1015
+ if (!target) {
1016
+ const p = this.context.page;
1017
+ if (!p) {
1018
+ throw new Error("siteNote(domainOrUrl?) requires a domain/URL or an active page");
1019
+ }
1020
+ target = await p.url();
1021
+ }
1022
+ const res = await this.client.matchSiteNotes(target);
1023
+ return res.notes ?? [];
1024
+ };
1025
+ const saveSiteNote = async (domainOrUrl, body, opts) => {
1026
+ const target = domainOrUrl?.trim();
1027
+ if (!target)
1028
+ throw new Error("saveSiteNote(domainOrUrl, body) requires a domain or URL");
1029
+ return this.client.saveSiteNote(target, {
1030
+ body,
1031
+ profileId: opts?.profileId ?? (this.ephemeral ? undefined : this.profileId),
1032
+ tags: opts?.tags,
1033
+ recipes: opts?.recipes,
1034
+ });
1035
+ };
1036
+ const appendSiteNote = async (domainOrUrl, entry, opts) => {
1037
+ const target = domainOrUrl?.trim();
1038
+ if (!target)
1039
+ throw new Error("appendSiteNote(domainOrUrl, entry) requires a domain or URL");
1040
+ return this.client.appendSiteNote(target, entry, {
1041
+ profileId: opts?.profileId ?? (this.ephemeral ? undefined : this.profileId),
1042
+ tags: opts?.tags,
1043
+ recipeId: opts?.recipeId,
1044
+ });
1045
+ };
1046
+ const listSiteNotes = async (query) => {
1047
+ return (await this.client.sites({ q: query })).notes ?? [];
1048
+ };
1049
+ const recordRecipe = async (id, fn, opts) => {
1050
+ if (!id?.trim())
1051
+ throw new Error("recordRecipe(id, fn, opts?) requires a recipe id");
1052
+ if (typeof fn !== "function")
1053
+ throw new Error("recordRecipe(id, fn, opts?) requires an async action function");
1054
+ await this.session.network.capture({
1055
+ enabled: true,
1056
+ resourceTypes: ["xhr", "fetch", "document"],
1057
+ captureBodies: false,
1058
+ });
1059
+ const before = await this.session.network.list({ limit: 500 });
1060
+ const sinceSeq = (before.requests ?? []).reduce((max, r) => (r.seq > max ? r.seq : max), 0);
1061
+ await fn();
1062
+ const settle = opts?.settleMs ?? 150;
1063
+ if (settle > 0) {
1064
+ await new Promise((r) => setTimeout(r, settle));
1065
+ }
1066
+ const p = this.context.page;
1067
+ const sourceUrl = p ? p.url() : "";
1068
+ return this.client.compileRecipeFromCapture({
1069
+ sessionId: this.session.id,
1070
+ profileId: this.ephemeral ? undefined : this.profileId,
1071
+ id: id.trim(),
1072
+ name: opts?.name,
1073
+ description: opts?.description,
1074
+ sourceUrl: sourceUrl || undefined,
1075
+ tags: opts?.tags,
1076
+ urlContains: opts?.urlContains,
1077
+ sinceSeq,
1078
+ autoParameterize: opts?.autoParameterize,
1079
+ escalateOnStatus: opts?.escalateOnStatus,
1080
+ save: opts?.save,
1081
+ linkSiteNote: opts?.linkSiteNote,
1082
+ });
1083
+ };
1084
+ const runRecipe = async (id, params, opts) => {
1085
+ if (!id?.trim())
1086
+ throw new Error("runRecipe(id, params?, opts?) requires a recipe id");
1087
+ return this.client.runRecipe(id.trim(), {
1088
+ profileId: opts?.profileId,
1089
+ params,
1090
+ escalate: opts?.escalate,
1091
+ timeoutMs: opts?.timeoutMs,
1092
+ ignoreCertErrors: opts?.ignoreCertErrors,
1093
+ });
1094
+ };
1095
+ const listRecipes = async (filter) => {
1096
+ return (await this.client.recipes(filter)).recipes ?? [];
1097
+ };
1098
+ const saveRecipe = async (recipe, opts) => {
1099
+ return this.client.saveRecipe(recipe, opts);
1100
+ };
778
1101
  const sandbox = {
779
1102
  // Browser globals (Aside-compatible neutral start).
780
1103
  page: null,
@@ -785,6 +1108,13 @@ export class SneakyReplSession {
785
1108
  getTabByTargetId,
786
1109
  openTab,
787
1110
  closeTab,
1111
+ spaceName: this.currentSpace,
1112
+ openSpace,
1113
+ useSpace,
1114
+ listSpaces,
1115
+ closeSpace,
1116
+ freezeInactiveTabs,
1117
+ trimMemory,
788
1118
  snapshot,
789
1119
  annotatedScreenshot,
790
1120
  display: (img, label) => this.recordDisplay(img, label),
@@ -798,12 +1128,18 @@ export class SneakyReplSession {
798
1128
  profileAccounts: async () => this.ephemeral ? [] : (await this.client.accounts({ profileId: this.profileId })).accounts,
799
1129
  fillSecret: async (target, accountId, field, opts) => {
800
1130
  const p = this.context.page;
801
- if (p)
802
- await p.ensureActive();
803
- return this.session.fillSecret(target, accountId, field, opts);
1131
+ return this.session.fillSecret(target, accountId, field, { ...opts, ...(p ? p.callScope() : {}) });
804
1132
  },
805
1133
  verifyIp: async (alignPersona = false) => this.ephemeral ? null : this.client.verifyProfileIp(this.profileId, { alignPersona }),
806
1134
  network: this.session.network,
1135
+ siteNote,
1136
+ saveSiteNote,
1137
+ appendSiteNote,
1138
+ listSiteNotes,
1139
+ recordRecipe,
1140
+ runRecipe,
1141
+ listRecipes,
1142
+ saveRecipe,
807
1143
  sneaky: this.client,
808
1144
  session: this.session,
809
1145
  // Standard Node & Web utilities.