glidercli 0.4.10 → 0.4.12

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.
package/bin/glider.js CHANGED
@@ -76,6 +76,7 @@ if (fs.existsSync(REGISTRY_FILE)) {
76
76
  // Direct CDP module
77
77
  const { DirectCDP, checkChrome } = require(path.join(LIB_DIR, 'cdp-direct.js'));
78
78
  const { resolveDomain } = require(path.join(LIB_DIR, 'domain-resolve.js'));
79
+ const pinMachine = require(path.join(LIB_DIR, 'pin-machine.js'));
79
80
 
80
81
  // Domain extensions - load from ~/.glider/config/domains.json
81
82
  const DOMAIN_CONFIG_PATHS = configPath('domains.json');
@@ -473,11 +474,18 @@ function httpGet(urlPath) {
473
474
 
474
475
  function loadPersistedSession() {
475
476
  if (activeSessionId) return;
476
- if (!fs.existsSync(SESSION_STORE)) return;
477
+ const pin = readPinStore();
478
+ if (pin.sessionId) activeSessionId = pin.sessionId;
479
+ }
480
+
481
+ function readPinStore() {
482
+ if (!fs.existsSync(SESSION_STORE)) return {};
477
483
  try {
478
484
  const data = JSON.parse(fs.readFileSync(SESSION_STORE, 'utf8'));
479
- if (data.sessionId) activeSessionId = data.sessionId;
480
- } catch { /* ignore */ }
485
+ return data && typeof data === 'object' ? data : {};
486
+ } catch {
487
+ return {};
488
+ }
481
489
  }
482
490
 
483
491
  function clearPersistedSession() {
@@ -485,10 +493,24 @@ function clearPersistedSession() {
485
493
  try { if (fs.existsSync(SESSION_STORE)) fs.unlinkSync(SESSION_STORE); } catch { /* ignore */ }
486
494
  }
487
495
 
488
- function persistSession(sessionId) {
496
+ function persistSession(sessionId, extra = {}) {
489
497
  activeSessionId = sessionId;
498
+ const prev = readPinStore();
499
+ const doc = {
500
+ sessionId,
501
+ targetId: extra.targetId || prev.targetId || '',
502
+ host: extra.host || prev.host || '',
503
+ url: extra.url || prev.url || '',
504
+ reason: extra.reason || prev.reason || '',
505
+ updated: new Date().toISOString(),
506
+ };
490
507
  fs.mkdirSync(path.dirname(SESSION_STORE), { recursive: true });
491
- fs.writeFileSync(SESSION_STORE, JSON.stringify({ sessionId, updated: new Date().toISOString() }, null, 2));
508
+ fs.writeFileSync(SESSION_STORE, JSON.stringify(doc, null, 2));
509
+ }
510
+
511
+ function persistPin(pin) {
512
+ if (!pin || !pin.sessionId) return;
513
+ persistSession(pin.sessionId, pin);
492
514
  }
493
515
 
494
516
  const lastHttpTiming = { relay_ms: 0, cdp_ms: 0 };
@@ -619,7 +641,15 @@ function httpPostRaw(urlPath, payload) {
619
641
 
620
642
  async function pickLiveSessionId() {
621
643
  const targets = await getTargets();
622
- return targets[0]?.sessionId || null;
644
+ const want = readPinStore();
645
+ const resolved = pinMachine.resolvePin({
646
+ targets,
647
+ host: want.host || '',
648
+ targetId: want.targetId || '',
649
+ sessionId: '',
650
+ });
651
+ if (resolved.pin) persistPin(resolved.pin);
652
+ return resolved.pin ? resolved.pin.sessionId : null;
623
653
  }
624
654
 
625
655
  async function httpPost(urlPath, body) {
@@ -638,12 +668,11 @@ async function httpPost(urlPath, body) {
638
668
  && isSessionNotFoundError(error)
639
669
  ) {
640
670
  const live = await pickLiveSessionId();
641
- clearPersistedSession();
642
671
  if (live) {
643
- persistSession(live);
644
672
  const retry = { ...body, sessionId: live };
645
673
  return httpPostRaw(urlPath, retry);
646
674
  }
675
+ clearPersistedSession();
647
676
  }
648
677
  throw error;
649
678
  }
@@ -2068,16 +2097,24 @@ async function cmdHeal(args = []) {
2068
2097
 
2069
2098
  async function cmdTabs() {
2070
2099
  const targets = await getTargets();
2071
- if (targets.length === 0) {
2072
- log.warn('No tabs connected');
2100
+ const part = pinMachine.partition(targets);
2101
+ if (jsonOutput) {
2102
+ emitJson(true, { pages: part.pages, iframes: part.iframes, other: part.other, activeSessionId });
2073
2103
  return;
2074
2104
  }
2075
- console.log(`${GREEN}${targets.length}${NC} tab(s) connected:\n`);
2076
- targets.forEach((t, i) => {
2077
- const url = t.targetInfo?.url || 'unknown';
2078
- const title = t.targetInfo?.title || '';
2079
- console.log(` ${CYAN}[${i + 1}]${NC} ${title}`);
2080
- console.log(` ${DIM}${url}${NC}`);
2105
+ if (part.pages.length === 0) {
2106
+ log.warn('No page targets');
2107
+ return;
2108
+ }
2109
+ console.log(`${GREEN}${part.pages.length}${NC} page(s) connected:\n`);
2110
+ part.pages.forEach((t, i) => {
2111
+ const mark = t.sessionId === activeSessionId ? `${GREEN}*${NC} ` : ' ';
2112
+ console.log(`${mark}${CYAN}[${i + 1}]${NC} ${t.title || t.url}`);
2113
+ console.log(` ${DIM}${t.url}${NC}`);
2114
+ const kids = part.iframes.filter((fr) => fr.parent_targetId === t.targetId);
2115
+ for (const fr of kids) {
2116
+ console.log(` ${DIM}iframe${NC} ${fr.url}`);
2117
+ }
2081
2118
  });
2082
2119
  }
2083
2120
 
@@ -2327,25 +2364,28 @@ async function cmdSnapshot(opts = []) {
2327
2364
 
2328
2365
  async function cmdTargets() {
2329
2366
  const raw = await httpGet('/targets');
2330
- const targets = (Array.isArray(raw) ? raw : []).map((t) => ({
2367
+ const part = pinMachine.partition(raw);
2368
+ const targets = part.rows.map((t) => ({
2331
2369
  sessionId: t.sessionId,
2332
2370
  targetId: t.targetId,
2333
- title: t.title || t.targetInfo?.title || '',
2334
- url: t.url || t.targetInfo?.url || '',
2371
+ type: t.type,
2372
+ title: t.title,
2373
+ url: t.url,
2374
+ parentFrameId: t.parentFrameId || '',
2335
2375
  }));
2336
2376
  if (jsonOutput) {
2337
- emitJson(true, { targets, activeSessionId });
2338
- } else {
2339
- if (!targets.length) {
2340
- log.warn('No targets');
2341
- return;
2342
- }
2343
- console.log(`${GREEN}${targets.length}${NC} target(s):\n`);
2344
- for (const t of targets) {
2345
- const mark = t.sessionId === activeSessionId ? `${GREEN}*${NC} ` : ' ';
2346
- console.log(`${mark}${CYAN}${t.sessionId}${NC} ${t.title}`);
2347
- console.log(` ${DIM}${t.url}${NC}`);
2348
- }
2377
+ emitJson(true, { targets, pages: part.pages, iframes: part.iframes, activeSessionId });
2378
+ return;
2379
+ }
2380
+ if (!targets.length) {
2381
+ log.warn('No targets');
2382
+ return;
2383
+ }
2384
+ console.log(`${GREEN}${part.pages.length}${NC} page(s), ${part.iframes.length} iframe(s):\n`);
2385
+ for (const t of targets) {
2386
+ const mark = t.sessionId === activeSessionId ? `${GREEN}*${NC} ` : ' ';
2387
+ console.log(`${mark}${CYAN}${t.sessionId}${NC} ${t.type} ${t.title}`);
2388
+ console.log(` ${DIM}${t.url}${NC}`);
2349
2389
  }
2350
2390
  }
2351
2391
 
@@ -2358,29 +2398,31 @@ async function cmdUseSession(arg, opts = []) {
2358
2398
  process.exit(1);
2359
2399
  }
2360
2400
  const raw = await httpGet('/targets');
2361
- const targets = Array.isArray(raw) ? raw : [];
2362
- const hit = parsed.url
2363
- ? targets.find((target) => (target.url || target.targetInfo?.url || '').includes(parsed.url))
2364
- : targets.find((target) => target.sessionId === requestedSession || target.targetId === requestedSession);
2365
- if (!hit) {
2401
+ const host = parsed.url ? (pinMachine.hostFromUrl(parsed.url.includes('://') ? parsed.url : `https://${parsed.url}`) || parsed.url) : '';
2402
+ const resolved = pinMachine.resolvePin({
2403
+ targets: Array.isArray(raw) ? raw : [],
2404
+ host,
2405
+ sessionId: requestedSession || '',
2406
+ });
2407
+ if (!resolved.pin) {
2366
2408
  const message = parsed.url
2367
- ? `no live target matching --url ${parsed.url}`
2368
- : `session is not live: ${requestedSession}`;
2369
- if (jsonOutput) emitJson(false, null, message);
2409
+ ? `no page pin for --url ${parsed.url} (${resolved.state})`
2410
+ : `no page pin for session ${requestedSession} (${resolved.state})`;
2411
+ if (jsonOutput) emitJson(false, { state: resolved.state }, message);
2370
2412
  log.fail(message);
2371
2413
  process.exit(1);
2372
2414
  }
2373
- const sessionId = hit.sessionId;
2374
- persistSession(sessionId);
2415
+ persistPin(resolved.pin);
2375
2416
  if (jsonOutput) {
2376
2417
  emitJson(true, {
2377
- sessionId,
2378
- targetId: hit.targetId,
2379
- url: hit.url || hit.targetInfo?.url || '',
2418
+ sessionId: resolved.pin.sessionId,
2419
+ targetId: resolved.pin.targetId,
2420
+ url: resolved.pin.url,
2421
+ reason: resolved.pin.reason,
2380
2422
  persisted: SESSION_STORE,
2381
2423
  });
2382
2424
  } else {
2383
- log.ok(`Active session: ${sessionId}`);
2425
+ log.ok(`Active session: ${resolved.pin.sessionId} (${resolved.pin.reason})`);
2384
2426
  console.log(SESSION_STORE);
2385
2427
  }
2386
2428
  }
@@ -3168,7 +3210,7 @@ async function cmdExplore(url, opts = []) {
3168
3210
  process.exit(1);
3169
3211
  }
3170
3212
 
3171
- let depth = 2;
3213
+ let depth = Infinity;
3172
3214
  let outputDir = '/tmp/glider-explore';
3173
3215
  let harFile = null;
3174
3216
  let sessionId = null;
@@ -3477,14 +3519,7 @@ async function cmdLoop(taskFileOrPrompt, options = {}) {
3477
3519
  }
3478
3520
 
3479
3521
  // Check for completion marker in task file (if it was modified)
3480
- if (fs.existsSync(taskFileOrPrompt)) {
3481
- const currentContent = fs.readFileSync(taskFileOrPrompt, 'utf8');
3482
- if (currentContent.includes(completionMarker) || currentContent.includes('DONE')) {
3483
- log.ok('Task file marked as complete');
3484
- state.status = 'completed';
3485
- break;
3486
- }
3487
- }
3522
+
3488
3523
 
3489
3524
  state.completed.push({ iteration: state.iteration, success: true });
3490
3525
 
package/lib/bexplore.js CHANGED
@@ -27,7 +27,8 @@ class SiteExplorer {
27
27
  // Exploration state
28
28
  this.visited = new Set();
29
29
  this.toVisit = [];
30
- this.depth = Number.isFinite(options.depth) ? options.depth : 3;
30
+ // 0 = passive (reload/HAR/screenshots, zero clicks). Any other value = full live-DOM flay.
31
+ this.depth = options.depth === 0 ? 0 : Infinity;
31
32
  this.outputDir = options.outputDir || '/tmp/explore';
32
33
  this.harFile = options.harFile;
33
34
  this.wantedSessionId = options.sessionId || null;
@@ -36,6 +37,8 @@ class SiteExplorer {
36
37
  // Captured data
37
38
  this.requests = [];
38
39
  this.responses = [];
40
+ this.bodies = {};
41
+ this._bodyJobs = [];
39
42
  this.scripts = [];
40
43
  this.stylesheets = [];
41
44
  this.websockets = [];
@@ -118,6 +121,11 @@ class SiteExplorer {
118
121
  timestamp: msg.params.timestamp
119
122
  });
120
123
  }
124
+
125
+ if (msg.method === 'Network.loadingFinished') {
126
+ const id = msg.params.requestId;
127
+ this._bodyJobs.push(this._pullBody(id));
128
+ }
121
129
 
122
130
  if (msg.method === 'Network.webSocketCreated') {
123
131
  this.websockets.push({
@@ -311,6 +319,7 @@ class SiteExplorer {
311
319
 
312
320
  const elements = await this.evaluate(`
313
321
  (() => {
322
+ try {
314
323
  const result = {
315
324
  tabs: [],
316
325
  buttons: [],
@@ -329,21 +338,21 @@ class SiteExplorer {
329
338
 
330
339
  // Helper: generate best selector for element
331
340
  const getSelector = (el) => {
332
- // Priority: data-qa > aria-label > id > unique class > nth-child path
341
+ try {
333
342
  const qa = el.getAttribute('data-qa');
334
- if (qa) return '[data-qa="' + qa + '"]';
343
+ if (qa) return '[data-qa="' + qa.replace(/"/g, '\\"') + '"]';
335
344
 
336
345
  const ariaLabel = el.getAttribute('aria-label');
337
346
  if (ariaLabel) return '[aria-label="' + ariaLabel.replace(/"/g, '\\"') + '"]';
338
347
 
339
- if (el.id) return '#' + el.id;
348
+ if (el.id) return '#' + CSS.escape(el.id);
340
349
 
341
- // Try unique class
342
350
  const classes = Array.from(el.classList).filter(c => !c.includes('--') && c.length > 2);
343
351
  for (const cls of classes) {
344
- if (document.querySelectorAll('.' + cls).length === 1) {
345
- return '.' + cls;
346
- }
352
+ try {
353
+ const sel = '.' + CSS.escape(cls);
354
+ if (document.querySelectorAll(sel).length === 1) return sel;
355
+ } catch (_) {}
347
356
  }
348
357
 
349
358
  // Build nth-child path (last resort)
@@ -360,6 +369,7 @@ class SiteExplorer {
360
369
  if (path.length > 4) break; // limit depth
361
370
  }
362
371
  return path.join(' > ') || null;
372
+ } catch (_) { return null; }
363
373
  };
364
374
 
365
375
  // Tabs (role=tab, .tab, [data-tab], nav items)
@@ -373,22 +383,23 @@ class SiteExplorer {
373
383
 
374
384
  // Buttons
375
385
  document.querySelectorAll('button, [role="button"], input[type="button"], input[type="submit"], .btn, [class*="button"]').forEach(el => {
376
- if (el.offsetParent !== null) { // visible
377
- result.buttons.push({
378
- text: el.textContent?.trim().slice(0, 50) || el.value || el.getAttribute('aria-label'),
379
- selector: getSelector(el),
380
- label: el.getAttribute('aria-label'),
381
- qa: el.getAttribute('data-qa'),
382
- type: el.type || 'button'
383
- });
384
- }
386
+ const r = el.getBoundingClientRect();
387
+ if (r.width === 0 && r.height === 0) return;
388
+ result.buttons.push({
389
+ text: el.textContent?.trim().slice(0, 50) || el.value || el.getAttribute('aria-label'),
390
+ selector: getSelector(el),
391
+ label: el.getAttribute('aria-label'),
392
+ qa: el.getAttribute('data-qa'),
393
+ type: el.type || 'button'
394
+ });
385
395
  });
386
396
 
387
397
  // Links (internal only)
388
398
  const baseUrl = window.location.origin;
389
399
  document.querySelectorAll('a[href]').forEach(el => {
390
400
  const href = el.href;
391
- if (href && href.startsWith(baseUrl) && el.offsetParent !== null) {
401
+ const r = el.getBoundingClientRect();
402
+ if (href && href.startsWith(baseUrl) && (r.width > 0 || r.height > 0)) {
392
403
  result.links.push({
393
404
  text: el.textContent?.trim().slice(0, 50),
394
405
  href: href,
@@ -480,6 +491,13 @@ class SiteExplorer {
480
491
  });
481
492
 
482
493
  return result;
494
+ } catch (e) {
495
+ return {
496
+ tabs: [], buttons: [], links: [], forms: [], tables: [], modals: [],
497
+ filters: [], pagination: null, infiniteScroll: false, sidePanels: [],
498
+ dropdowns: [], checkboxes: [], inputs: [], discoveryError: String(e && e.message || e)
499
+ };
500
+ }
483
501
  })()
484
502
  `);
485
503
 
@@ -573,7 +591,7 @@ class SiteExplorer {
573
591
  if (options.reload !== false) {
574
592
  console.error('[explore] Reloading page to capture all network traffic...');
575
593
  await this.send('Page.reload');
576
- await new Promise(r => setTimeout(r, 3000)); // Wait for page load
594
+ await new Promise(r => setTimeout(r, 6000));
577
595
  }
578
596
 
579
597
  this.siteMap.url = await this.evaluate('window.location.href');
@@ -588,6 +606,11 @@ class SiteExplorer {
588
606
  try {
589
607
  elements = await this.discoverElements();
590
608
  console.error(`[explore] Found: ${elements.tabs.length} tabs, ${elements.buttons.length} buttons, ${elements.links.length} links`);
609
+ if (elements.buttons.length + elements.links.length + elements.tabs.length === 0) {
610
+ await new Promise(r => setTimeout(r, 4000));
611
+ elements = await this.discoverElements();
612
+ console.error(`[explore] rediscover: ${elements.tabs.length} tabs, ${elements.buttons.length} buttons, ${elements.links.length} links`);
613
+ }
591
614
  } catch (e) {
592
615
  console.error(`[explore] DOM discovery failed (${e.message}); skipping discovery, preserving HAR`);
593
616
  elements = { tabs: [], buttons: [], links: [], forms: [], tables: [], dropdowns: [], checkboxes: [], modals: [], sidePanels: [] };
@@ -597,69 +620,64 @@ class SiteExplorer {
597
620
  if (depth === 0) {
598
621
  console.error('[explore] depth=0 passive - no clicks, scroll, or toggles');
599
622
  } else {
600
- // Click through tabs
601
- for (const tab of elements.tabs.slice(0, depth)) {
602
- if (tab.text) {
603
- console.error(`[explore] Clicking tab: ${tab.text}`);
604
- try {
605
- await this.clickByText(tab.text);
606
- this.clicksPerformed++;
607
- await new Promise(r => setTimeout(r, 1000));
608
- await this.screenshot(`tab-${tab.text.replace(/[^a-z0-9]/gi, '-').slice(0, 20)}`);
609
- await this.discoverElements(); // Re-discover after tab change
610
- } catch (e) {
611
- console.error(`[explore] Tab click failed: ${e.message}`);
612
- }
623
+ const visited = new Set();
624
+ const poison = /delete|remove|sign out|log out|logout|disconnect|unsubscribe/;
625
+ const flayKey = (kind, item) => {
626
+ const href = (item.href || '').split('?')[0].split('#')[0];
627
+ const text = (item.text || item.label || '').trim().slice(0, 80);
628
+ return `${kind}|${href}|${text}|${item.selector || ''}`;
629
+ };
630
+ const unsafe = (item) => poison.test((item.text || item.label || '').toLowerCase());
631
+ let stagnant = 0;
632
+ while (stagnant < 2) {
633
+ let els;
634
+ try {
635
+ els = await this.discoverElements();
636
+ } catch (e) {
637
+ console.error(`[explore] rediscover failed (${e.message})`);
638
+ els = { tabs: [], buttons: [], links: [], checkboxes: [] };
613
639
  }
614
- }
615
-
616
- // Click through buttons (non-destructive ones)
617
- const safeButtons = elements.buttons.filter(b => {
618
- const text = (b.text || '').toLowerCase();
619
- return !text.includes('delete') && !text.includes('remove') && !text.includes('submit') && !text.includes('save') && !text.includes('menu');
620
- });
621
-
622
- for (const btn of safeButtons.slice(0, depth)) {
623
- if (btn.text) {
624
- console.error(`[explore] Clicking button: ${btn.text}`);
625
- try {
626
- await this.clickByText(btn.text);
627
- this.clicksPerformed++;
628
- await new Promise(r => setTimeout(r, 500));
629
- } catch (e) {
630
- console.error(`[explore] Button click failed: ${e.message}`);
631
- }
640
+ const queue = [];
641
+ for (const tab of els.tabs || []) queue.push({ kind: 'tab', item: tab });
642
+ for (const btn of els.buttons || []) queue.push({ kind: 'button', item: btn });
643
+ for (const link of els.links || []) queue.push({ kind: 'link', item: link });
644
+ for (const cb of els.checkboxes || []) queue.push({ kind: 'checkbox', item: cb });
645
+ const next = queue.find(({ kind, item }) => !unsafe(item) && !visited.has(flayKey(kind, item)) && (item.text || item.label || item.href || item.selector));
646
+ if (!next) {
647
+ console.error('[explore] frontier empty; scrolling then one more discover');
648
+ await this.scrollToBottom();
649
+ stagnant += 1;
650
+ continue;
632
651
  }
633
- }
634
-
635
- // Expand dropdowns
636
- for (const dropdown of elements.dropdowns.slice(0, Math.min(depth, 5))) {
637
- console.error(`[explore] Opening dropdown`);
638
- // Click to open, then click away
639
- }
640
-
641
- // Scroll to trigger lazy loading
642
- console.error('[explore] Scrolling to trigger lazy loading...');
643
- await this.scrollToBottom();
644
- await this.screenshot('scrolled');
645
-
646
- // Check all checkboxes (to see what filters do)
647
- for (const cb of elements.checkboxes.slice(0, Math.min(depth, 5))) {
648
- if (cb.label) {
649
- console.error(`[explore] Toggling checkbox: ${cb.label}`);
650
- try {
652
+ stagnant = 0;
653
+ const key = flayKey(next.kind, next.item);
654
+ visited.add(key);
655
+ const label = next.item.text || next.item.label || next.item.href || key;
656
+ console.error(`[explore] flay ${next.kind}: ${String(label).slice(0, 80)} (visited=${visited.size})`);
657
+ try {
658
+ if (next.kind === 'link' && next.item.href) {
659
+ await this.evaluate(`location.assign(${JSON.stringify(next.item.href)})`);
660
+ } else if (next.kind === 'checkbox' && next.item.label) {
651
661
  await this.evaluate(`
652
- const cb = Array.from(document.querySelectorAll('input[type="checkbox"]'))
653
- .find(e => e.labels?.[0]?.textContent?.includes(${JSON.stringify(cb.label)}));
654
- if (cb) cb.click();
655
- `);
656
- this.clicksPerformed++;
657
- await new Promise(r => setTimeout(r, 500));
658
- } catch (e) {
659
- console.error(`[explore] Checkbox toggle failed: ${e.message}`);
662
+ const cb = Array.from(document.querySelectorAll('input[type="checkbox"]'))
663
+ .find(e => e.labels?.[0]?.textContent?.includes(${JSON.stringify(next.item.label)}));
664
+ if (cb) cb.click();
665
+ `);
666
+ } else if (next.item.selector) {
667
+ await this.clickElement(next.item.selector);
668
+ } else if (next.item.text) {
669
+ await this.clickByText(next.item.text);
670
+ }
671
+ this.clicksPerformed++;
672
+ await new Promise(r => setTimeout(r, 800));
673
+ if (this.clicksPerformed % 5 === 0) {
674
+ await this.screenshot(`flay-${this.clicksPerformed}`);
660
675
  }
676
+ } catch (e) {
677
+ console.error(`[explore] flay click failed: ${e.message}`);
661
678
  }
662
679
  }
680
+ await this.screenshot('scrolled');
663
681
  }
664
682
 
665
683
  // Final screenshot (best-effort)
@@ -669,7 +687,16 @@ class SiteExplorer {
669
687
  console.error(`[explore] Final screenshot failed (${e.message}); continuing`);
670
688
  }
671
689
 
672
- return this.generateReport();
690
+ const report = this.generateReport();
691
+ if (this.harFile) {
692
+ await this.saveHAR();
693
+ }
694
+ try {
695
+ this.generateTaskFile(report);
696
+ } catch (e) {
697
+ console.error('[explore] task.yaml skipped:', e.message);
698
+ }
699
+ return report;
673
700
  }
674
701
 
675
702
  generateReport() {
@@ -747,20 +774,17 @@ class SiteExplorer {
747
774
  const reportPath = path.join(this.outputDir, 'report.json');
748
775
  fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
749
776
  console.error(`[explore] Report saved: ${reportPath}`);
750
-
751
- // Generate YAML task file for ralph mode
752
- this.generateTaskFile(report);
753
-
754
- // Save HAR if requested
755
- if (this.harFile) {
756
- this.saveHAR();
757
- }
758
-
759
777
  return report;
760
778
  }
761
779
 
762
780
  generateTaskFile(report) {
763
- const yaml = require('yaml');
781
+ let yaml;
782
+ try {
783
+ yaml = require('yaml');
784
+ } catch (e) {
785
+ console.error('[explore] yaml module missing; skip task.yaml');
786
+ return;
787
+ }
764
788
 
765
789
  // Build task steps from discovered elements
766
790
  const steps = [];
@@ -772,8 +796,7 @@ class SiteExplorer {
772
796
  // Add clicks for key buttons (with selectors)
773
797
  if (this.depth > 0) {
774
798
  const actionButtons = (report.raw.buttons || [])
775
- .filter(b => b.selector && b.qa && !b.qa.includes('history') && !b.qa.includes('search'))
776
- .slice(0, this.depth);
799
+ .filter(b => b.selector && b.qa && !b.qa.includes('history') && !b.qa.includes('search'));
777
800
 
778
801
  for (const btn of actionButtons) {
779
802
  steps.push({ log: `Click: ${btn.text || btn.label}` });
@@ -784,7 +807,6 @@ class SiteExplorer {
784
807
 
785
808
  // Add screenshot at end
786
809
  steps.push({ screenshot: path.join(this.outputDir, 'task-result.png') });
787
- steps.push({ log: 'LOOP_COMPLETE' });
788
810
 
789
811
  const task = {
790
812
  name: `Explore ${new URL(report.url).hostname}`,
@@ -799,13 +821,49 @@ class SiteExplorer {
799
821
  console.error(`[explore] Run with: glider ralph ${taskPath}`);
800
822
  }
801
823
 
802
- saveHAR() {
824
+ _bodyable(mime) {
825
+ const m = (mime || '').toLowerCase();
826
+ if (!m) return true;
827
+ if (/image|font|video|audio|wasm|octet-stream|woff|zip|pdf/.test(m)) return false;
828
+ return /json|text|xml|javascript|graphql|urlencoded/.test(m) || m.startsWith('text/');
829
+ }
830
+
831
+ async _pullBody(id) {
832
+ if (this.bodies[id]) return;
833
+ const resp = this.responses.find(r => r.id === id);
834
+ if (resp && !this._bodyable(resp.mimeType)) return;
835
+ try {
836
+ const r = await this.send('Network.getResponseBody', { requestId: id }, { timeoutMs: 2500 });
837
+ if (r && r.body != null) {
838
+ this.bodies[id] = r.base64Encoded
839
+ ? Buffer.from(r.body, 'base64').toString('utf8')
840
+ : r.body;
841
+ }
842
+ } catch (_) { /* evicted/opaque */ }
843
+ }
844
+
845
+ async saveHAR() {
846
+ await Promise.allSettled(this._bodyJobs);
847
+ const bodies = { ...this.bodies };
848
+ for (const resp of this.responses) {
849
+ if (bodies[resp.id]) continue;
850
+ if (!this._bodyable(resp.mimeType)) continue;
851
+ try {
852
+ const r = await this.send('Network.getResponseBody', { requestId: resp.id }, { timeoutMs: 1500 });
853
+ if (r && r.body != null) {
854
+ bodies[resp.id] = r.base64Encoded
855
+ ? Buffer.from(r.body, 'base64').toString('utf8')
856
+ : r.body;
857
+ }
858
+ } catch (_) { /* cached/opaque/CORS - leave text empty */ }
859
+ }
803
860
  const har = {
804
861
  log: {
805
862
  version: '1.2',
806
863
  creator: { name: 'bexplore', version: '1.0.0' },
807
864
  entries: this.requests.map(req => {
808
865
  const resp = this.responses.find(r => r.id === req.id);
866
+ const text = bodies[req.id] || '';
809
867
  return {
810
868
  startedDateTime: new Date(req.timestamp * 1000).toISOString(),
811
869
  request: {
@@ -817,7 +875,7 @@ class SiteExplorer {
817
875
  response: resp ? {
818
876
  status: resp.status,
819
877
  headers: Object.entries(resp.headers || {}).map(([name, value]) => ({ name, value })),
820
- content: { mimeType: resp.mimeType }
878
+ content: { mimeType: resp.mimeType, text, size: text.length }
821
879
  } : { status: 0, headers: [], content: {} }
822
880
  };
823
881
  })
@@ -825,7 +883,8 @@ class SiteExplorer {
825
883
  };
826
884
 
827
885
  fs.writeFileSync(this.harFile, JSON.stringify(har, null, 2));
828
- console.error(`[explore] HAR saved: ${this.harFile}`);
886
+ const withBody = Object.keys(bodies).length;
887
+ console.error(`[explore] HAR saved: ${this.harFile} (${withBody} bodies)`);
829
888
  }
830
889
 
831
890
  async close() {
@@ -860,14 +919,14 @@ Usage:
860
919
  node bexplore.js [options]
861
920
 
862
921
  Options:
863
- --depth N Exploration depth (default: 3; 0 = passive, no clicks)
922
+ --depth 0 Passive only (reload, discover, screenshots, HAR). Omit for full live-DOM flay.
864
923
  --output DIR Output directory (default: /tmp/explore)
865
924
  --har FILE Save HAR file
866
925
  --session-id ID CDP session (e.g. session-6 from GET /targets)
867
926
  --help Show this help
868
927
 
869
928
  Depth 0 (passive): reload, discover DOM, screenshots, HAR - zero clicks.
870
- Depth N>0: up to N tab/button/checkbox interactions per category.
929
+ Any other / omitted: recursively click every new live-DOM control until the frontier is empty.
871
930
 
872
931
  The tool will:
873
932
  1. Discover all tabs, buttons, links, forms, tables
@@ -887,13 +946,16 @@ Examples:
887
946
  process.exit(0);
888
947
  }
889
948
 
890
- let depth = 3;
949
+ let depth = Infinity;
891
950
  let outputDir = '/tmp/explore';
892
951
  let harFile = null;
893
952
  let sessionId = null;
894
953
 
895
954
  for (let i = 0; i < args.length; i++) {
896
- if (args[i] === '--depth') depth = parseInt(args[++i], 10);
955
+ if (args[i] === '--depth') {
956
+ const n = parseInt(args[++i], 10);
957
+ depth = n === 0 ? 0 : Infinity;
958
+ }
897
959
  else if (args[i] === '--output') outputDir = args[++i];
898
960
  else if (args[i] === '--har') harFile = args[++i];
899
961
  else if (args[i] === '--session-id') sessionId = args[++i];
@@ -941,7 +1003,7 @@ Examples:
941
1003
  // Salvage: even on catastrophic failure, save whatever HAR + partial report we have
942
1004
  try {
943
1005
  if (harFile && explorer.requests && explorer.requests.length > 0) {
944
- explorer.saveHAR();
1006
+ await explorer.saveHAR();
945
1007
  console.error(`[explore] HAR salvaged despite error (${explorer.requests.length} requests captured)`);
946
1008
  }
947
1009
  if (explorer.outputDir && fs.existsSync(explorer.outputDir)) {
@@ -0,0 +1,121 @@
1
+ 'use strict';
2
+
3
+ /** CDP pin machine. SSOT: operator $CURREGISTRY/glider/cdp-target-shape.json */
4
+ const PAGE = 'page';
5
+ const IFRAME = 'iframe';
6
+ const NEVER = new Set([IFRAME, 'worker', 'service_worker', 'shared_worker', 'browser']);
7
+
8
+ function hostFromUrl(url) {
9
+ if (!url || typeof url !== 'string') return '';
10
+ try {
11
+ return new URL(url).hostname || '';
12
+ } catch {
13
+ return '';
14
+ }
15
+ }
16
+
17
+ function hostIn(url, host) {
18
+ if (!host || !url) return false;
19
+ const h = String(host).toLowerCase().replace(/^\./, '');
20
+ const u = String(url).toLowerCase();
21
+ return u.includes(h) || u.includes(h.replace(/^www\./, ''));
22
+ }
23
+
24
+ function info(t) {
25
+ const ti = t && typeof t.targetInfo === 'object' && t.targetInfo ? t.targetInfo : {};
26
+ return {
27
+ sessionId: t.sessionId || '',
28
+ targetId: t.targetId || ti.targetId || '',
29
+ type: String(ti.type || t.type || 'unknown').toLowerCase(),
30
+ url: ti.url || t.url || '',
31
+ title: ti.title || t.title || '',
32
+ parentFrameId: ti.parentFrameId || t.parentFrameId || '',
33
+ attached: ti.attached,
34
+ };
35
+ }
36
+
37
+ function partition(raw) {
38
+ const rows = (Array.isArray(raw) ? raw : []).filter((t) => t && typeof t === 'object').map(info);
39
+ const pages = rows.filter((r) => r.type === PAGE);
40
+ const iframes = rows.filter((r) => r.type === IFRAME).map((fr) => {
41
+ const parent = pages.find((p) => p.targetId && p.targetId === fr.parentFrameId) || null;
42
+ return {
43
+ ...fr,
44
+ parent_sessionId: parent ? parent.sessionId : '',
45
+ parent_targetId: fr.parentFrameId || '',
46
+ };
47
+ });
48
+ const other = rows.filter((r) => r.type !== PAGE && r.type !== IFRAME);
49
+ return { pages, iframes, other, rows };
50
+ }
51
+
52
+ function pinOf(page, reason) {
53
+ return {
54
+ sessionId: page.sessionId,
55
+ targetId: page.targetId,
56
+ type: PAGE,
57
+ url: page.url,
58
+ host: hostFromUrl(page.url),
59
+ reason,
60
+ };
61
+ }
62
+
63
+ function resolvePin({ targets, host, targetId, sessionId } = {}) {
64
+ const part = partition(targets);
65
+ if (!part.rows.length) {
66
+ return { state: 'S0_empty', pin: null, ...part };
67
+ }
68
+ const wantHost = host || '';
69
+ const wantTarget = targetId || '';
70
+ const wantSession = sessionId || '';
71
+
72
+ if (wantSession) {
73
+ const row = part.rows.find((r) => r.sessionId === wantSession || r.targetId === wantSession);
74
+ if (row && row.type === PAGE) {
75
+ return { state: 'S4_pin', pin: pinOf(row, 'explicit_session'), ...part };
76
+ }
77
+ if (row && row.type === IFRAME) {
78
+ const parent = part.pages.find((p) => p.targetId === row.parentFrameId);
79
+ if (parent) return { state: 'S4_pin', pin: pinOf(parent, 'parent_of_oopif'), ...part };
80
+ return { state: 'F_orphan_iframe', pin: null, ...part };
81
+ }
82
+ if (row && NEVER.has(row.type)) {
83
+ return { state: 'F_need_context', pin: null, ...part };
84
+ }
85
+ }
86
+
87
+ if (!wantHost && !wantTarget) {
88
+ return { state: 'F_need_context', pin: null, ...part };
89
+ }
90
+
91
+ if (wantTarget) {
92
+ const page = part.pages.find((p) => p.targetId === wantTarget);
93
+ if (page) return { state: 'S4_pin', pin: pinOf(page, 'same_tab_new_session'), ...part };
94
+ }
95
+
96
+ if (wantHost) {
97
+ const hits = part.pages.filter((p) => hostIn(p.url, wantHost));
98
+ if (hits.length > 1) return { state: 'F_ambiguous', pin: null, hits, ...part };
99
+ if (hits.length === 1) return { state: 'S4_pin', pin: pinOf(hits[0], 'page_url'), ...part };
100
+ const kids = part.iframes.filter((fr) => hostIn(fr.url, wantHost) && fr.parent_sessionId);
101
+ if (kids.length) {
102
+ const parent = part.pages.find((p) => p.sessionId === kids[0].parent_sessionId);
103
+ if (parent) return { state: 'S4_pin', pin: pinOf(parent, 'parent_of_oopif'), ...part };
104
+ return { state: 'F_orphan_iframe', pin: null, ...part };
105
+ }
106
+ if (part.pages.length) return { state: 'F_stale', pin: null, ...part };
107
+ return { state: 'F_no_page', pin: null, ...part };
108
+ }
109
+
110
+ return { state: 'F_stale', pin: null, ...part };
111
+ }
112
+
113
+ module.exports = {
114
+ PAGE,
115
+ NEVER,
116
+ hostFromUrl,
117
+ hostIn,
118
+ info,
119
+ partition,
120
+ resolvePin,
121
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "glidercli",
3
- "version": "0.4.10",
3
+ "version": "0.4.12",
4
4
  "description": "Browser automation CLI. Control a configured Chromium browser through an extension CDP relay, run YAML tasks, and execute bounded autonomous loops.",
5
5
  "bin": {
6
6
  "glider": "bin/glider.js"