glidercli 0.4.37 → 0.4.40

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/README.md CHANGED
@@ -131,7 +131,7 @@ glider loop hn-scrape.yaml
131
131
 
132
132
  | Output | Path |
133
133
  |--------|------|
134
- | LaunchAgent daemon log | AGLOGS namespace `glider/relay` |
134
+ | LaunchAgent daemon log | stderr, or optional sink via `GLIDER_AGLOGS_NAMESPACE` + `GLIDER_AGLOG_BIN` |
135
135
  | domain index | `~/.glider/config/domains.json` |
136
136
  | per-host intel | `~/.glider/warch/HOST/glider.json` |
137
137
  | explore cache | `~/.glider/bexplore/HOST/` |
@@ -266,7 +266,7 @@ CLI 0.4.18 expects an extension with `listTabs` plus `incognito` on tabs/windows
266
266
  | `glider type` | type |
267
267
  | `glider screenshot` | PNG |
268
268
  | `glider frozen` | detect frozen tab (detect only; unknown flags/args fail closed) |
269
- | `glider thaw` | unfreeze tab (`--verify` / `--all`). Not a subcommand of `frozen` |
269
+ | `glider thaw` | unfreeze tab (`--verify` or `--all`). Not a subcommand of `frozen` |
270
270
  | `glider explore` | crawl + HAR |
271
271
  | `glider resolve` | host warch |
272
272
  | `glider run` | YAML task |
@@ -276,13 +276,14 @@ CLI 0.4.18 expects an extension with `listTabs` plus `incognito` on tabs/windows
276
276
 
277
277
  ## Verification
278
278
 
279
+ Scoreboard: [`tests/contract.json`](tests/contract.json) — missing test OK (deferred); wrong/broken test forbidden.
280
+
279
281
  ```bash
280
- node --check bin/glider.js && node --check lib/bserve.js
281
- node --test tests/*.test.js
282
- node tests/live-browser.smoke.js # isolated live-browser fixture
282
+ npm test # unit / mock / in-process relay (no CRX)
283
+ npm run test:live # real Chromium + Glider extension (tests/live-browser.smoke.js)
283
284
  ```
284
285
 
285
- Live smoke creates + closes its own browser window.
286
+ Live smoke creates + closes its own browser window. Required rows in `contract.json` are the live checks that must pass; deferred rows are scaffolding only.
286
287
 
287
288
  Incomplete event-stream features fail closed: `wait --network-idle`, console streaming, response fulfillment. No success-shaped fallback.
288
289
 
package/bin/glider.js CHANGED
@@ -32,6 +32,11 @@ const YAML = require('yaml');
32
32
 
33
33
  // Config
34
34
  const { relayPort } = require('../lib/relay-config.js');
35
+ const {
36
+ ensureSessionRunnable,
37
+ waitForTargetSession,
38
+ isLifecycleMethod,
39
+ } = require('../lib/session-runnable.js');
35
40
  const DEBUG_PORT = process.env.GLIDER_DEBUG_PORT || 9222;
36
41
  const DEBUG_URL = `http://127.0.0.1:${DEBUG_PORT}`;
37
42
  const LIB_DIR = path.join(__dirname, '..', 'lib');
@@ -893,12 +898,32 @@ async function pickLiveSessionId() {
893
898
  return null;
894
899
  }
895
900
 
901
+ // Product gate: every non-lifecycle /cdp call re-asserts runnable state.
902
+ // No memo — freeze/background can happen between verbs; Chromium stays healed.
903
+ async function autoEnsureSessionRunnable(sessionId) {
904
+ try {
905
+ await ensureSessionRunnable({
906
+ sessionId: sessionId || null,
907
+ send: (call) => httpPostRaw('/cdp', call),
908
+ });
909
+ } catch {
910
+ // Best-effort; verb still runs. Explicit glider thaw remains available.
911
+ }
912
+ }
913
+
896
914
  async function httpPost(urlPath, body) {
897
915
  const payload = { ...body };
898
916
  const pinned = activeSessionId;
899
917
  if (urlPath === '/cdp' && pinned && payload.sessionId == null) {
900
918
  payload.sessionId = pinned;
901
919
  }
920
+ if (
921
+ urlPath === '/cdp'
922
+ && payload.method
923
+ && !isLifecycleMethod(payload.method)
924
+ ) {
925
+ await autoEnsureSessionRunnable(payload.sessionId || pinned || null);
926
+ }
902
927
  try {
903
928
  return await httpPostRaw(urlPath, payload);
904
929
  } catch (error) {
@@ -910,6 +935,7 @@ async function httpPost(urlPath, body) {
910
935
  ) {
911
936
  const live = await pickLiveSessionId();
912
937
  if (live) {
938
+ await autoEnsureSessionRunnable(live);
913
939
  const retry = { ...body, sessionId: live };
914
940
  return httpPostRaw(urlPath, retry);
915
941
  }
@@ -1953,7 +1979,11 @@ async function cmdInstallDaemon() {
1953
1979
  if (jsonOutput) emitJson(true, { running: true, port: PORT, pid: record.pid, childPid: record.childPid, alreadyRunning });
1954
1980
  log.ok(alreadyRunning ? 'Daemon already running' : 'Daemon started');
1955
1981
  log.info('Relay will auto-restart on crash');
1956
- log.info('Logs: AGLOGS glider/relay');
1982
+ log.info(
1983
+ process.env.GLIDER_AGLOGS_NAMESPACE
1984
+ ? `Logs: log adapter namespace ${process.env.GLIDER_AGLOGS_NAMESPACE}`
1985
+ : 'Logs: daemon stderr (optional GLIDER_AGLOGS_NAMESPACE + GLIDER_AGLOG_BIN)',
1986
+ );
1957
1987
  log.info(`PID: ${record.pid}`);
1958
1988
  return;
1959
1989
  }
@@ -2678,7 +2708,7 @@ async function cmdWindow(args) {
2678
2708
  } catch (err) {
2679
2709
  log.fail(err.message);
2680
2710
  } finally {
2681
- wm.close();
2711
+ await wm.close();
2682
2712
  }
2683
2713
  }
2684
2714
 
@@ -3202,12 +3232,11 @@ async function cmdThaw(opts = []) {
3202
3232
 
3203
3233
  const results = [];
3204
3234
  for (const sid of sessions) {
3205
- const p1 = { method: 'Emulation.setFocusEmulationEnabled', params: { enabled: true } };
3206
- const p2 = { method: 'Page.setWebLifecycleState', params: { state: 'active' } };
3207
- if (sid) { p1.sessionId = sid; p2.sessionId = sid; }
3208
3235
  try {
3209
- await httpPost('/cdp', p1);
3210
- await httpPost('/cdp', p2);
3236
+ await ensureSessionRunnable({
3237
+ sessionId: sid || null,
3238
+ send: (call) => httpPostRaw('/cdp', call),
3239
+ });
3211
3240
  const entry = { sessionId: sid || activeSessionId || '(pinned)', thawed: true };
3212
3241
  if (verify) {
3213
3242
  const vp = { method: 'Runtime.evaluate', params: { expression: `document.visibilityState`, returnByValue: true } };
@@ -4001,18 +4030,27 @@ async function cmdExplore(url, opts = []) {
4001
4030
  if (freshTab) {
4002
4031
  const { WindowManager } = require(path.join(LIB_DIR, 'bwindow.js'));
4003
4032
  const wm = new WindowManager();
4004
- await wm.connect();
4005
- await wm.init();
4006
- log.info(`[explore] Opening fresh tab for capture...`);
4007
- const result = await wm.createTab(url);
4008
- freshTargetId = result.targetId;
4009
- await new Promise(r => setTimeout(r, 2500));
4010
4033
  try {
4011
- const targetsRes = await httpGet('/targets');
4012
- const targets = (targetsRes && targetsRes.targets) || targetsRes || [];
4013
- const t = (Array.isArray(targets) ? targets : []).find(x => x.targetId === freshTargetId);
4014
- if (t && t.sessionId) sessionId = t.sessionId;
4015
- } catch {}
4034
+ await wm.connect();
4035
+ await wm.init();
4036
+ log.info(`[explore] Opening fresh tab for capture...`);
4037
+ const result = await wm.createTab(url);
4038
+ freshTargetId = result.targetId;
4039
+ if (result.sessionId) sessionId = result.sessionId;
4040
+ } finally {
4041
+ await wm.close();
4042
+ }
4043
+ if (!sessionId && freshTargetId) {
4044
+ sessionId = await waitForTargetSession({
4045
+ targetId: freshTargetId,
4046
+ listTargets: async () => {
4047
+ const targetsRes = await httpGet('/targets');
4048
+ return (targetsRes && targetsRes.targets) || targetsRes || [];
4049
+ },
4050
+ timeoutMs: 10000,
4051
+ intervalMs: 100,
4052
+ });
4053
+ }
4016
4054
  if (!sessionId) log.info('[explore] fresh-tab created but sessionId not resolved (bexplore will auto-pin)');
4017
4055
  else log.ok(`[explore] fresh-tab session: ${sessionId}`);
4018
4056
  }
@@ -4041,10 +4079,14 @@ async function cmdExplore(url, opts = []) {
4041
4079
  try {
4042
4080
  const { WindowManager } = require(path.join(LIB_DIR, 'bwindow.js'));
4043
4081
  const wm = new WindowManager();
4044
- await wm.connect();
4045
- await wm.init();
4046
- await wm.closeTarget(freshTargetId);
4047
- log.ok(`[explore] fresh-tab closed: ${freshTargetId}`);
4082
+ try {
4083
+ await wm.connect();
4084
+ await wm.init();
4085
+ await wm.closeTarget(freshTargetId);
4086
+ log.ok(`[explore] fresh-tab closed: ${freshTargetId}`);
4087
+ } finally {
4088
+ await wm.close();
4089
+ }
4048
4090
  } catch (e) {
4049
4091
  log.info(`[explore] fresh-tab close failed: ${e.message}`);
4050
4092
  }
package/docs/setup.json CHANGED
@@ -43,7 +43,7 @@
43
43
  "registry_base": "$GLIDER",
44
44
  "resolve": "glider resolve <url> --json",
45
45
  "browser": "$GLIDER/config/browser.json",
46
- "daemon_log": "AGLOGS namespace glider/relay when GLIDER_AGLOGS_NAMESPACE is set",
46
+ "daemon_log": "daemon stderr; optional structured sink when GLIDER_AGLOGS_NAMESPACE + GLIDER_AGLOG_BIN are set",
47
47
  "cookies_jar": "$GLIDER/cookies/<host>/header.txt",
48
48
  "cookies_index": "$GLIDER/cookies/domains.json",
49
49
  "cookie_jar_verb": "glider cookie-jar sync|read|list|add|rm|rebuild",
package/lib/bexplore.js CHANGED
@@ -13,8 +13,9 @@ const path = require('path');
13
13
  const http = require('http');
14
14
  const { relayHttpUrl, relayWebSocketUrl } = require('./relay-config.js');
15
15
  const { capturesDir } = require('./paths.js');
16
+ const { ensureSessionRunnable } = require('./session-runnable.js');
16
17
 
17
- const RELAY_URL = relayWebSocketUrl();
18
+ const RELAY_URL = relayWebSocketUrl(process.env, `explore-${process.pid}`);
18
19
  const RELAY_HTTP = relayHttpUrl();
19
20
 
20
21
  const PATH_TEMPLATE_CAP = 16;
@@ -424,6 +425,14 @@ class SiteExplorer {
424
425
  }
425
426
 
426
427
  async enableSession(sid) {
428
+ await ensureSessionRunnable({
429
+ sessionId: sid,
430
+ send: async (call) => this.sendWithRetry(call.method, call.params, {
431
+ sessionId: call.sessionId,
432
+ retries: 2,
433
+ }),
434
+ });
435
+ console.error(`[explore] Session thawed for background capture: ${sid}`);
427
436
  const domainEnables = [
428
437
  ['Runtime.enable', {}],
429
438
  ['Page.enable', {}],
package/lib/bwindow.js CHANGED
@@ -18,11 +18,15 @@
18
18
  const WebSocket = require('ws');
19
19
  const { relayWebSocketUrl } = require('./relay-config.js');
20
20
 
21
- const RELAY_URL = relayWebSocketUrl();
21
+ let windowClientSequence = 0;
22
22
 
23
23
  class WindowManager {
24
- constructor() {
24
+ constructor(options = {}) {
25
25
  this.ws = null;
26
+ this.relayUrl = relayWebSocketUrl(
27
+ process.env,
28
+ options.clientId || `window-${process.pid}-${++windowClientSequence}`,
29
+ );
26
30
  this.messageId = 0;
27
31
  this.pending = new Map();
28
32
  this.targets = new Map(); // targetId -> { sessionId, url, windowId, createdByGlider }
@@ -30,7 +34,7 @@ class WindowManager {
30
34
 
31
35
  async connect() {
32
36
  return new Promise((resolve, reject) => {
33
- this.ws = new WebSocket(RELAY_URL);
37
+ this.ws = new WebSocket(this.relayUrl);
34
38
  this.ws.on('open', resolve);
35
39
  this.ws.on('error', reject);
36
40
  this.ws.on('message', (data) => this._handleMessage(JSON.parse(data.toString())));
@@ -237,8 +241,18 @@ class WindowManager {
237
241
  return Array.from(this.targets.values());
238
242
  }
239
243
 
240
- close() {
241
- if (this.ws) this.ws.close();
244
+ async close() {
245
+ const ws = this.ws;
246
+ this.ws = null;
247
+ if (!ws || ws.readyState === WebSocket.CLOSED) return;
248
+ await new Promise((resolve) => {
249
+ const timer = setTimeout(resolve, 1000);
250
+ ws.once('close', () => {
251
+ clearTimeout(timer);
252
+ resolve();
253
+ });
254
+ ws.close();
255
+ });
242
256
  }
243
257
  }
244
258
 
@@ -331,7 +345,7 @@ Examples:
331
345
  console.error(`Error: ${err.message}`);
332
346
  process.exit(1);
333
347
  } finally {
334
- wm.close();
348
+ await wm.close();
335
349
  }
336
350
  }
337
351
 
@@ -7,8 +7,9 @@ DAEMON_PATH="$SCRIPT_DIR/glider-daemon.sh"
7
7
  BSERVE="$SCRIPT_DIR/bserve.js"
8
8
  LOG_DIR="${GLIDER:-$HOME/.glider}"
9
9
  PORT="${GLIDER_PORT:-${RELAY_PORT:-19988}}"
10
+ # Optional structured log sink. Both env vars required; no hardcoded host paths.
10
11
  AGLOG_NAMESPACE="${GLIDER_AGLOGS_NAMESPACE:-}"
11
- AGLOG_BIN="${GLIDER_AGLOG_BIN:-${AG:-$HOME/.agents}/tools/lib/aglog.sh}"
12
+ AGLOG_BIN="${GLIDER_AGLOG_BIN:-}"
12
13
 
13
14
  case "$PORT" in
14
15
  ''|*[!0-9]*|0|0*) echo "glider-daemon: invalid relay port: $PORT" >&2; exit 2 ;;
@@ -45,8 +46,12 @@ management_lock_owned=0
45
46
 
46
47
  mkdir -p "$LOG_DIR"
47
48
 
49
+ if [ -n "$AGLOG_NAMESPACE" ] && [ -z "$AGLOG_BIN" ]; then
50
+ echo "glider-daemon: GLIDER_AGLOGS_NAMESPACE set but GLIDER_AGLOG_BIN is empty" >&2
51
+ exit 78
52
+ fi
48
53
  if [ -n "$AGLOG_NAMESPACE" ] && [ ! -x "$AGLOG_BIN" ]; then
49
- echo "glider-daemon: AGLOGS adapter is unavailable: $AGLOG_BIN" >&2
54
+ echo "glider-daemon: log adapter is unavailable: $AGLOG_BIN" >&2
50
55
  exit 78
51
56
  fi
52
57
 
@@ -470,7 +475,7 @@ write_pid_record
470
475
  initial_handoff=1
471
476
  while true; do
472
477
  emit_log_line "[$(date)] Starting relay on port $PORT..." || {
473
- echo "glider-daemon: AGLOGS start event failed" >&2
478
+ echo "glider-daemon: log adapter start event failed" >&2
474
479
  exit 74
475
480
  }
476
481
 
@@ -533,7 +538,7 @@ while true; do
533
538
  write_pid_record
534
539
 
535
540
  emit_log_line "[$(date)] Relay exited with code $EXIT_CODE, restarting in 2s..." || {
536
- echo "glider-daemon: AGLOGS restart event failed" >&2
541
+ echo "glider-daemon: log adapter restart event failed" >&2
537
542
  exit 74
538
543
  }
539
544
  sleep 2
@@ -13,8 +13,10 @@ function relayHttpUrl(env = process.env) {
13
13
  return env.RELAY_HTTP || `http://127.0.0.1:${relayPort(env)}`;
14
14
  }
15
15
 
16
- function relayWebSocketUrl(env = process.env) {
17
- return env.RELAY_URL || `ws://127.0.0.1:${relayPort(env)}/cdp`;
16
+ function relayWebSocketUrl(env = process.env, clientId = '') {
17
+ const base = env.RELAY_URL || `ws://127.0.0.1:${relayPort(env)}/cdp`;
18
+ if (!clientId) return base;
19
+ return `${base.replace(/\/+$/, '')}/${encodeURIComponent(clientId)}`;
18
20
  }
19
21
 
20
22
  module.exports = {
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Session runnable gate — product auto-heal for Chromium background throttle.
5
+ * One primitive for CLI thaw, explore, and every /cdp verb path.
6
+ */
7
+
8
+ const THAW_STEPS = [
9
+ { method: 'Emulation.setFocusEmulationEnabled', params: { enabled: true } },
10
+ { method: 'Page.setWebLifecycleState', params: { state: 'active' } },
11
+ ];
12
+
13
+ const LIFECYCLE_METHODS = new Set(THAW_STEPS.map((step) => step.method));
14
+
15
+ function thawCdpCalls(sessionId) {
16
+ return THAW_STEPS.map(({ method, params }) => {
17
+ const call = { method, params: { ...params } };
18
+ if (sessionId) call.sessionId = sessionId;
19
+ return call;
20
+ });
21
+ }
22
+
23
+ function isLifecycleMethod(method) {
24
+ return LIFECYCLE_METHODS.has(method);
25
+ }
26
+
27
+ /**
28
+ * @param {{ sessionId?: string|null, send: (call: {method:string, params:object, sessionId?:string}) => Promise<any> }} opts
29
+ */
30
+ async function ensureSessionRunnable({ sessionId = null, send }) {
31
+ if (typeof send !== 'function') throw new TypeError('ensureSessionRunnable requires send()');
32
+ for (const call of thawCdpCalls(sessionId || null)) {
33
+ await send(call);
34
+ }
35
+ return { sessionId: sessionId || null, thawed: true };
36
+ }
37
+
38
+ /**
39
+ * Poll /targets (or any listTargets) until targetId has a sessionId.
40
+ * Replaces fixed sleeps on --fresh-tab.
41
+ */
42
+ async function waitForTargetSession({
43
+ targetId,
44
+ listTargets,
45
+ timeoutMs = 10000,
46
+ intervalMs = 100,
47
+ now = () => Date.now(),
48
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
49
+ }) {
50
+ if (!targetId) throw new TypeError('waitForTargetSession requires targetId');
51
+ if (typeof listTargets !== 'function') throw new TypeError('waitForTargetSession requires listTargets()');
52
+ const deadline = now() + timeoutMs;
53
+ while (now() <= deadline) {
54
+ const raw = await listTargets();
55
+ const list = Array.isArray(raw) ? raw : (raw && raw.targets) || [];
56
+ const hit = list.find((row) => row && row.targetId === targetId && row.sessionId);
57
+ if (hit) return hit.sessionId;
58
+ if (now() >= deadline) break;
59
+ await sleep(intervalMs);
60
+ }
61
+ return null;
62
+ }
63
+
64
+ module.exports = {
65
+ thawCdpCalls,
66
+ ensureSessionRunnable,
67
+ waitForTargetSession,
68
+ isLifecycleMethod,
69
+ LIFECYCLE_METHODS,
70
+ };
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "glidercli",
3
- "version": "0.4.37",
3
+ "version": "0.4.40",
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"
7
7
  },
8
8
  "scripts": {
9
9
  "test": "node --test tests/*.test.js",
10
- "test:syntax": "node --check bin/glider.js && node --check lib/bserve.js && node --check lib/bexplore.js && node --check lib/tab-catalog.js && node --check lib/tab-tui.js && node --check lib/tab-map.js && node --check lib/pin-machine.js && node --check lib/relay-heal.js && node --check lib/status-model.js && node --check lib/target-registry.js && node --check lib/pkg-update.js && node --check lib/cookie-jar.js && node --check lib/headless-runtime.js",
10
+ "test:syntax": "node --check bin/glider.js && node --check lib/bserve.js && node --check lib/bexplore.js && node --check lib/bwindow.js && node --check lib/relay-config.js && node --check lib/session-runnable.js && node --check lib/tab-catalog.js && node --check lib/tab-tui.js && node --check lib/tab-map.js && node --check lib/pin-machine.js && node --check lib/relay-heal.js && node --check lib/status-model.js && node --check lib/target-registry.js && node --check lib/pkg-update.js && node --check lib/cookie-jar.js && node --check lib/headless-runtime.js",
11
11
  "test:regression": "node --test tests/browser-config.test.js tests/core.test.js tests/cli-regression.test.js tests/relay-integration.test.js tests/target-registry.test.js tests/tab-tui-color-regression.test.js tests/tab-map.test.js tests/tab-catalog.test.js",
12
12
  "test:integration": "node --test tests/relay-integration.test.js tests/daemon-lifecycle.test.js",
13
13
  "test:pack": "node --test tests/npm-tarball.test.js",