glidercli 0.3.20 → 0.3.21

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 (2) hide show
  1. package/bin/glider.js +428 -0
  2. package/package.json +1 -1
package/bin/glider.js CHANGED
@@ -1488,6 +1488,198 @@ async function cmdCorsFetch(url, opts = []) {
1488
1488
  }
1489
1489
  }
1490
1490
 
1491
+
1492
+ // Detect if the attached tab is under Chrome hidden-tab throttling.
1493
+ // Primitive: runtime_evaluate_sync_reads.
1494
+ // Recipe: eval document.visibilityState + '|' + document.hidden.
1495
+ // Semantics: 'hidden|true' → macrotasks (setTimeout/fetch/XHR/workers) will not fire.
1496
+ // Exit code: 0 if visible, 1 if hidden (chainable in scripts).
1497
+ async function cmdFrozen(opts = []) {
1498
+ let sessionId = null;
1499
+ for (let i = 0; i < opts.length; i++) {
1500
+ const a = opts[i];
1501
+ if (a === '--session' || a === '--sessionId') sessionId = opts[++i];
1502
+ else if (a === '--help') {
1503
+ console.log('Usage: glider frozen [--session <id>]');
1504
+ console.log(' Detect whether the attached tab is macrotask-frozen (hidden).');
1505
+ console.log(' Exit code: 0 = visible, 1 = hidden (frozen).');
1506
+ return;
1507
+ }
1508
+ }
1509
+ if (!await ensureConnected()) process.exit(1);
1510
+
1511
+ const js = `document.visibilityState + '|' + document.hidden + '|' + (document.wasDiscarded||false)`;
1512
+ try {
1513
+ const cdpParams = { method: 'Runtime.evaluate', params: { expression: js, returnByValue: true } };
1514
+ if (sessionId) cdpParams.sessionId = sessionId;
1515
+ const result = await httpPost('/cdp', cdpParams);
1516
+ if (result && result.error && !result.result) {
1517
+ const msg = `CDP error: ${typeof result.error === 'string' ? result.error : JSON.stringify(result.error)}`;
1518
+ if (jsonOutput) emitJson(false, null, msg);
1519
+ log.fail(msg);
1520
+ process.exit(2);
1521
+ }
1522
+ const value = result?.result?.value;
1523
+ if (!value) {
1524
+ if (jsonOutput) emitJson(false, null, 'no value');
1525
+ log.fail('No value returned');
1526
+ process.exit(2);
1527
+ }
1528
+ const [visibilityState, hidden, wasDiscarded] = String(value).split('|');
1529
+ const frozen = hidden === 'true';
1530
+ const out = { visibilityState, hidden: frozen, wasDiscarded: wasDiscarded === 'true', frozen };
1531
+ if (jsonOutput) {
1532
+ emitJson(true, out);
1533
+ } else {
1534
+ if (frozen) {
1535
+ log.warn(`FROZEN - visibilityState=${visibilityState} hidden=${hidden} wasDiscarded=${wasDiscarded}`);
1536
+ log.info('Macrotasks (setTimeout/fetch/XHR/workers) will not fire until user focuses tab.');
1537
+ } else {
1538
+ log.ok(`live - visibilityState=${visibilityState} hidden=${hidden} wasDiscarded=${wasDiscarded}`);
1539
+ }
1540
+ }
1541
+ process.exit(frozen ? 1 : 0);
1542
+ } catch (e) {
1543
+ if (jsonOutput) emitJson(false, null, e.message);
1544
+ log.fail(`frozen check failed: ${e.message}`);
1545
+ process.exit(2);
1546
+ }
1547
+ }
1548
+
1549
+ // List cookies for a URL (including HttpOnly) via extension chrome.cookies.getAll bridge.
1550
+ // Primitive: extension_ws_bridge (background.js exposes method:'getCookies').
1551
+ // Note: this reads via the CRX cookies API - HttpOnly cookies (ESTSAUTH, s.SessID etc.)
1552
+ // ARE returned because MV3 extensions with "cookies" permission bypass the JS wall.
1553
+ async function cmdCookies(opts = []) {
1554
+ let url = null;
1555
+ let host = null; // convenience: bare host → https://<host>/
1556
+ let name = null; // optional exact-name filter
1557
+ let showValue = false; // print full cookie value (default: mask)
1558
+ let asHeader = false; // emit as ready-to-paste "Cookie: k=v; k=v" line
1559
+
1560
+ const positional = [];
1561
+ for (let i = 0; i < opts.length; i++) {
1562
+ const a = opts[i];
1563
+ if (a === '--url' || a === '-u') url = opts[++i];
1564
+ else if (a === '--host' || a === '-h') host = opts[++i];
1565
+ else if (a === '--name' || a === '-n') name = opts[++i];
1566
+ else if (a === '--value' || a === '--secret' || a === '--full') showValue = true;
1567
+ else if (a === '--header' || a === '--as-header') asHeader = true;
1568
+ else if (a === '--help') {
1569
+ console.log('Usage: glider cookies <url> | --host <h> | --url <u> [--name <n>] [--value] [--header] [--json]');
1570
+ console.log(' Read cookies (INCLUDING HttpOnly) for a URL via the extension cookies API.');
1571
+ console.log(' --host <h> convenience: expands to https://<h>/');
1572
+ console.log(' --name <n> filter to a single cookie by exact name');
1573
+ console.log(' --value print full cookie value (default: masked)');
1574
+ console.log(' --header emit as "Cookie: k=v; k=v" header line');
1575
+ return;
1576
+ }
1577
+ else if (!a.startsWith('-')) positional.push(a);
1578
+ }
1579
+ if (!url && positional.length) url = positional[0];
1580
+ if (!url && host) url = /^https?:\/\//i.test(host) ? host : `https://${host}/`;
1581
+ if (!url) {
1582
+ log.fail('Usage: glider cookies <url> | --host <h> | --url <u>');
1583
+ process.exit(1);
1584
+ }
1585
+
1586
+ if (!await ensureConnected()) process.exit(1);
1587
+
1588
+ try {
1589
+ const payload = await httpPost('/extension', {
1590
+ method: 'getCookies',
1591
+ params: { url }
1592
+ });
1593
+
1594
+ if (!payload || payload.error) {
1595
+ const msg = payload?.error || 'no response from extension';
1596
+ if (jsonOutput) emitJson(false, null, msg);
1597
+ log.fail(`cookies fetch failed: ${msg}`);
1598
+ log.info('Requires glider CRX >= 0.3.21 (bg handler "getCookies"). Reload the extension if just updated.');
1599
+ process.exit(1);
1600
+ }
1601
+
1602
+ let cookies = payload.data || payload.result?.cookies || payload.cookies || [];
1603
+ if (!Array.isArray(cookies)) {
1604
+ if (jsonOutput) emitJson(false, null, 'unexpected response shape');
1605
+ log.fail('unexpected response shape from extension');
1606
+ console.error(JSON.stringify(payload).slice(0, 500));
1607
+ process.exit(1);
1608
+ }
1609
+ if (name) cookies = cookies.filter(c => c.name === name);
1610
+
1611
+ // Filter expired
1612
+ const nowSec = Math.floor(Date.now() / 1000);
1613
+ for (const c of cookies) {
1614
+ if (c.expirationDate) {
1615
+ c._expires_in_sec = Math.floor(c.expirationDate - nowSec);
1616
+ c._expired = c._expires_in_sec < 0;
1617
+ } else {
1618
+ c._expires_in_sec = null;
1619
+ c._expired = false; // session cookie
1620
+ }
1621
+ }
1622
+
1623
+ if (asHeader) {
1624
+ const line = cookies
1625
+ .filter(c => !c._expired)
1626
+ .map(c => `${c.name}=${c.value}`)
1627
+ .join('; ');
1628
+ if (jsonOutput) emitJson(true, { header: line, count: cookies.length });
1629
+ else console.log(line);
1630
+ return;
1631
+ }
1632
+
1633
+ if (jsonOutput) {
1634
+ const out = cookies.map(c => ({
1635
+ name: c.name,
1636
+ domain: c.domain,
1637
+ path: c.path,
1638
+ httpOnly: !!c.httpOnly,
1639
+ secure: !!c.secure,
1640
+ sameSite: c.sameSite,
1641
+ session: !!c.session,
1642
+ expirationDate: c.expirationDate || null,
1643
+ expires_in_sec: c._expires_in_sec,
1644
+ expired: c._expired,
1645
+ value: showValue ? c.value : maskCookieValue(c.value),
1646
+ }));
1647
+ emitJson(true, { url, count: out.length, cookies: out });
1648
+ return;
1649
+ }
1650
+
1651
+ if (cookies.length === 0) {
1652
+ log.warn(name ? `No cookie named "${name}" for ${url}` : `No cookies for ${url}`);
1653
+ return;
1654
+ }
1655
+ log.ok(`${cookies.length} cookie(s) for ${url}:`);
1656
+ for (const c of cookies) {
1657
+ const flags = [
1658
+ c.httpOnly ? 'HttpOnly' : null,
1659
+ c.secure ? 'Secure' : null,
1660
+ c.sameSite ? `SameSite=${c.sameSite}` : null,
1661
+ c.session ? 'Session' : null,
1662
+ ].filter(Boolean).join(' ');
1663
+ const exp = c._expires_in_sec == null
1664
+ ? '(session)'
1665
+ : (c._expired ? `EXPIRED ${-c._expires_in_sec}s ago` : `expires in ${Math.floor(c._expires_in_sec/60)}m ${c._expires_in_sec%60}s`);
1666
+ const val = showValue ? c.value : maskCookieValue(c.value);
1667
+ console.log(` ${c.name}=${val} [${c.domain}${c.path}] ${flags} ${exp}`);
1668
+ }
1669
+ } catch (e) {
1670
+ if (jsonOutput) emitJson(false, null, e.message);
1671
+ log.fail(`cookies fetch failed: ${e.message}`);
1672
+ process.exit(1);
1673
+ }
1674
+ }
1675
+
1676
+ function maskCookieValue(v) {
1677
+ if (v == null) return '(none)';
1678
+ const s = String(v);
1679
+ if (s.length < 20) return s.slice(0, 4) + '...' + s.slice(-2);
1680
+ return s.slice(0, 12) + '...(' + (s.length - 20) + ' chars)...' + s.slice(-6);
1681
+ }
1682
+
1491
1683
  // Spawn multiple tabs
1492
1684
  async function cmdSpawn(urls) {
1493
1685
  if (!urls || urls.length === 0) {
@@ -2196,6 +2388,30 @@ ${YELLOW}DOMAIN EXTENSIONS:${NC}
2196
2388
  }
2197
2389
  console.log('');
2198
2390
  }
2391
+
2392
+ // Plugins socket - hydrated from ~/.glider/plugins/*.plugin.{json,js}
2393
+ // (loadPlugins is called from main() before showHelp when invoked as `glider help`,
2394
+ // but a bare `glider --help` runs before main; safe-load here for that path.)
2395
+ if (GLIDER_PLUGIN_REGISTRY.size === 0) {
2396
+ try { loadPlugins(); } catch {}
2397
+ }
2398
+ const seen = new Set();
2399
+ const pluginVerbs = [];
2400
+ for (const [verb, def] of GLIDER_PLUGIN_REGISTRY) {
2401
+ if (def.verb !== verb) continue; // skip aliases
2402
+ if (seen.has(def._source)) continue;
2403
+ seen.add(def._source);
2404
+ pluginVerbs.push({ verb, def });
2405
+ }
2406
+ if (pluginVerbs.length > 0) {
2407
+ console.log(`${YELLOW}PLUGINS:${NC} (from ~/.glider/plugins/)`);
2408
+ for (const { verb, def } of pluginVerbs) {
2409
+ const desc = (Array.isArray(def.help) ? def.help.find(l => !/^Usage:/i.test(l)) : def.help) || '(no description)';
2410
+ const shortDesc = String(desc).replace(/^\s+/, '').slice(0, 60);
2411
+ console.log(` ${GREEN}${verb.padEnd(16)}${NC} ${DIM}${shortDesc}${NC}`);
2412
+ }
2413
+ console.log('');
2414
+ }
2199
2415
  }
2200
2416
 
2201
2417
  // Version check - non-blocking, runs in background
@@ -2253,10 +2469,211 @@ async function cmdUpdate() {
2253
2469
  }
2254
2470
  }
2255
2471
 
2472
+ // ────────────────────────────────────────────────────────────────
2473
+ // PLUGIN SOCKET (v0.3.21)
2474
+ // ────────────────────────────────────────────────────────────────
2475
+ // glidercli itself is verb-agnostic. Local plugins hydrate additional
2476
+ // verbs at runtime from `$HOME/.glider/plugins/*.plugin.{json,js}`.
2477
+ // This lets consumers (org-specific ontologies, private tentacles) ship
2478
+ // their own verbs without ever landing in the public npm package.
2479
+ //
2480
+ // Plugin discovery order:
2481
+ // 1. $GLIDER_PLUGIN_DIR (env override)
2482
+ // 2. $HOME/.glider/plugins/
2483
+ //
2484
+ // Two plugin formats:
2485
+ //
2486
+ // (a) JSON - declarative, for simple eval-based verbs:
2487
+ // {
2488
+ // "verb": "myverb",
2489
+ // "aliases": ["mv"],
2490
+ // "help": ["Usage: glider myverb [--flag]", " Describe it..."],
2491
+ // "primitive": "eval" | "extension" | "cdp",
2492
+ // "recipe": "<javascript expression>" (for primitive=eval)
2493
+ // "method": "<extension method name>" (for primitive=extension)
2494
+ // "args": { "--flag": {"type":"boolean|string|number"} }, optional
2495
+ // "output": { "format":"table|json|raw" } optional
2496
+ // }
2497
+ //
2498
+ // (b) JS - imperative, for complex verbs:
2499
+ // module.exports = {
2500
+ // verb: 'myverb',
2501
+ // aliases: ['mv'],
2502
+ // help: ['Usage: glider myverb ...'],
2503
+ // async run(argv, ctx) {
2504
+ // // ctx = { cdp, ext, log, jsonOutput, emitJson, ensureConnected, mask, httpPost, httpGet, os, fs, path }
2505
+ // const val = await ctx.cdp.eval('1+1', { sessionId: ctx.persistedSessionId });
2506
+ // ctx.log.ok(JSON.stringify(val));
2507
+ // }
2508
+ // };
2509
+ const GLIDER_PLUGIN_REGISTRY = new Map(); // verb → plugin def
2510
+
2511
+ function pluginDirs() {
2512
+ const dirs = [];
2513
+ if (process.env.GLIDER_PLUGIN_DIR) dirs.push(process.env.GLIDER_PLUGIN_DIR);
2514
+ dirs.push(path.join(os.homedir(), '.glider', 'plugins'));
2515
+ return dirs.filter(d => { try { return fs.statSync(d).isDirectory(); } catch { return false; } });
2516
+ }
2517
+
2518
+ function loadPlugins() {
2519
+ const dirs = pluginDirs();
2520
+ for (const dir of dirs) {
2521
+ let entries;
2522
+ try { entries = fs.readdirSync(dir); } catch { continue; }
2523
+ for (const name of entries) {
2524
+ if (!/\.plugin\.(json|js|cjs)$/i.test(name)) continue;
2525
+ const full = path.join(dir, name);
2526
+ try {
2527
+ let def;
2528
+ if (/\.json$/i.test(name)) {
2529
+ def = JSON.parse(fs.readFileSync(full, 'utf8'));
2530
+ def._source = full;
2531
+ def._type = 'json';
2532
+ } else {
2533
+ def = require(full);
2534
+ def._source = full;
2535
+ def._type = 'js';
2536
+ }
2537
+ if (!def.verb || typeof def.verb !== 'string') {
2538
+ log.warn(`Plugin ${name}: missing "verb", skipping`);
2539
+ continue;
2540
+ }
2541
+ GLIDER_PLUGIN_REGISTRY.set(def.verb, def);
2542
+ for (const a of (def.aliases || [])) GLIDER_PLUGIN_REGISTRY.set(a, def);
2543
+ } catch (e) {
2544
+ log.warn(`Plugin ${name}: load failed - ${e.message}`);
2545
+ }
2546
+ }
2547
+ }
2548
+ }
2549
+
2550
+ // Build the helper context passed to JS plugins
2551
+ function makePluginCtx() {
2552
+ return {
2553
+ // Primitives
2554
+ cdp: {
2555
+ async eval(js, opts = {}) {
2556
+ const params = { method: 'Runtime.evaluate', params: { expression: js, returnByValue: true, awaitPromise: !!opts.awaitPromise } };
2557
+ if (opts.sessionId) params.sessionId = opts.sessionId;
2558
+ const r = await httpPost('/cdp', params);
2559
+ if (r && r.error && !r.result) throw new Error(`CDP: ${typeof r.error === 'string' ? r.error : JSON.stringify(r.error)}`);
2560
+ return r?.result?.value;
2561
+ },
2562
+ async call(method, params, opts = {}) {
2563
+ const body = { method, params: params || {} };
2564
+ if (opts.sessionId) body.sessionId = opts.sessionId;
2565
+ return await httpPost('/cdp', body);
2566
+ },
2567
+ },
2568
+ ext: {
2569
+ async call(method, params) {
2570
+ return await httpPost('/extension', { method, params: params || {} });
2571
+ },
2572
+ },
2573
+ // Utilities
2574
+ log,
2575
+ get jsonOutput() { return jsonOutput; },
2576
+ emitJson,
2577
+ ensureConnected,
2578
+ httpPost, httpGet,
2579
+ // Common masks
2580
+ mask: {
2581
+ jwt(s) {
2582
+ if (!s || typeof s !== 'string') return String(s);
2583
+ if (s.length < 40) return s.slice(0,6) + '...' + s.slice(-4);
2584
+ return s.slice(0,20) + '...(' + (s.length - 30) + ' chars)...' + s.slice(-10);
2585
+ },
2586
+ cookie(s) {
2587
+ if (s == null) return '(none)';
2588
+ const t = String(s);
2589
+ if (t.length < 20) return t.slice(0,4) + '...' + t.slice(-2);
2590
+ return t.slice(0,12) + '...(' + (t.length - 20) + ' chars)...' + t.slice(-6);
2591
+ },
2592
+ },
2593
+ // Node built-ins (avoid plugins needing to require these themselves)
2594
+ os, fs, path,
2595
+ // Version marker for plugins to feature-detect
2596
+ apiVersion: 1,
2597
+ };
2598
+ }
2599
+
2600
+ async function runPlugin(def, argv) {
2601
+ const ctx = makePluginCtx();
2602
+
2603
+ // Help dispatch
2604
+ if (argv.includes('--help') || argv.includes('-h')) {
2605
+ if (Array.isArray(def.help)) def.help.forEach(l => console.log(l));
2606
+ else if (typeof def.help === 'string') console.log(def.help);
2607
+ else console.log(`Usage: glider ${def.verb} [args]`);
2608
+ return;
2609
+ }
2610
+
2611
+ // JS plugin - call run()
2612
+ if (def._type === 'js') {
2613
+ if (typeof def.run !== 'function') {
2614
+ log.fail(`Plugin ${def.verb}: JS plugin must export "run(argv, ctx)"`);
2615
+ process.exit(1);
2616
+ }
2617
+ if (!await ensureConnected()) process.exit(1);
2618
+ try {
2619
+ await def.run(argv, ctx);
2620
+ } catch (e) {
2621
+ if (jsonOutput) emitJson(false, null, e.message);
2622
+ log.fail(`Plugin ${def.verb} failed: ${e.message}`);
2623
+ if (process.env.GLIDER_PLUGIN_DEBUG) console.error(e.stack);
2624
+ process.exit(1);
2625
+ }
2626
+ return;
2627
+ }
2628
+
2629
+ // JSON plugin - declarative execution
2630
+ if (!await ensureConnected()) process.exit(1);
2631
+ const parsed = parseJsonPluginArgs(argv, def.args || {});
2632
+ try {
2633
+ let out;
2634
+ if (def.primitive === 'eval') {
2635
+ if (!def.recipe) throw new Error('JSON plugin with primitive=eval requires "recipe"');
2636
+ const sessionId = parsed['--session'] || parsed.sessionId;
2637
+ const val = await ctx.cdp.eval(def.recipe, { sessionId, awaitPromise: !!def.awaitPromise });
2638
+ out = val;
2639
+ } else if (def.primitive === 'extension') {
2640
+ if (!def.method) throw new Error('JSON plugin with primitive=extension requires "method"');
2641
+ const params = { ...parsed };
2642
+ delete params._;
2643
+ out = await ctx.ext.call(def.method, params);
2644
+ } else {
2645
+ throw new Error(`Unknown primitive "${def.primitive}" (expected: eval | extension)`);
2646
+ }
2647
+ if (jsonOutput || def.output?.format === 'json') {
2648
+ emitJson(true, out);
2649
+ } else {
2650
+ console.log(typeof out === 'string' ? out : JSON.stringify(out, null, 2));
2651
+ }
2652
+ } catch (e) {
2653
+ if (jsonOutput) emitJson(false, null, e.message);
2654
+ log.fail(`Plugin ${def.verb} failed: ${e.message}`);
2655
+ process.exit(1);
2656
+ }
2657
+ }
2658
+
2659
+ function parseJsonPluginArgs(argv, schema) {
2660
+ const out = { _: [] };
2661
+ for (let i = 0; i < argv.length; i++) {
2662
+ const a = argv[i];
2663
+ if (a.startsWith('--')) {
2664
+ const spec = schema[a] || { type: 'string' };
2665
+ if (spec.type === 'boolean') out[a] = true;
2666
+ else out[a] = argv[++i];
2667
+ } else out._.push(a);
2668
+ }
2669
+ return out;
2670
+ }
2671
+
2256
2672
  // Main
2257
2673
  async function main() {
2258
2674
  const args = parseGlobalFlags(process.argv.slice(2));
2259
2675
  loadPersistedSession();
2676
+ loadPlugins(); // hydrate ~/.glider/plugins/*.plugin.{json,js} - verb-agnostic core
2260
2677
  let cmd = args[0];
2261
2678
 
2262
2679
  // v0.3.15: reload-ext command aliases -
@@ -2413,6 +2830,12 @@ async function main() {
2413
2830
  case 'cfetch':
2414
2831
  await cmdCorsFetch(args[1], args.slice(2));
2415
2832
  break;
2833
+ case 'frozen':
2834
+ await cmdFrozen(args.slice(1));
2835
+ break;
2836
+ case 'cookies':
2837
+ await cmdCookies(args.slice(1));
2838
+ break;
2416
2839
  case 'spawn':
2417
2840
  await cmdSpawn(args.slice(1));
2418
2841
  break;
@@ -2452,6 +2875,11 @@ async function main() {
2452
2875
  await cmdLoop(taskArg, loopOpts);
2453
2876
  break;
2454
2877
  default:
2878
+ // Plugin registry check FIRST - locally-hydrated verbs win over "unknown"
2879
+ if (GLIDER_PLUGIN_REGISTRY.has(cmd)) {
2880
+ await runPlugin(GLIDER_PLUGIN_REGISTRY.get(cmd), args.slice(1));
2881
+ break;
2882
+ }
2455
2883
  // Check if it's a domain command from config
2456
2884
  if (DOMAINS[cmd]) {
2457
2885
  const domain = DOMAINS[cmd];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "glidercli",
3
- "version": "0.3.20",
3
+ "version": "0.3.21",
4
4
  "description": "Browser automation CLI. Control Chrome from terminal via CDP, run YAML task files, autonomous loops until completion.",
5
5
  "main": "index.js",
6
6
  "bin": {