glidercli 0.4.16 → 0.4.18

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
@@ -123,6 +123,7 @@ glider config browser chrome
123
123
  glider install
124
124
  glider connect
125
125
  glider goto "https://news.ycombinator.com"
126
+ glider tabs
126
127
  glider loop hn-scrape.yaml
127
128
  ```
128
129
 
@@ -141,6 +142,25 @@ Copy `config/domains.template.json` into `~/.glider/config/domains.json` to seed
141
142
 
142
143
  ---
143
144
 
145
+ ## Tabs
146
+
147
+ `glider tabs` is the visible Helium rail, not the debugger map.
148
+
149
+ 1. current window `chrome.tabs` (live title/url, including `chrome://newtab`)
150
+ 2. other windows
151
+ 3. attached: CDP session not in `chrome.tabs`
152
+ 4. stale: `tabId` gone from `chrome.tabs`; dropped from the relay map
153
+
154
+ Incognito is Chromium `windows.Window.incognito` and `tabs.Tab.incognito` only. TUI: `window N (current, incognito)`. Enable Allow in Incognito on the extension. CDP `browserContextId` is not that flag.
155
+
156
+ `glider targets` stays the raw CDP session list.
157
+
158
+ Old relay without GET `/catalog` is recycled by `glider start`, `glider heal`, and the daemon (SIGTERM the child; supervisor respawns current `bserve.js`). `listTabs` fail reloads the extension and attach-all.
159
+
160
+ CLI 0.4.18 expects an extension with `listTabs` plus `incognito` on tabs/windows (github [`vdutts7/glider`](https://github.com/vdutts7/glider) 1.0.10, or Chrome Web Store after that upload). Store 1.0.9 lacks `listTabs`; windows stay empty and live CDP rows sit under attached.
161
+
162
+ ---
163
+
144
164
  ## Gotchas
145
165
 
146
166
  | problem | fix | stability | why |
@@ -148,6 +168,9 @@ Copy `config/domains.template.json` into `~/.glider/config/domains.json` to seed
148
168
  | extension not connected | install/enable [`Glider` on Chrome Web Store](https://chromewebstore.google.com/detail/glider/njbidokkffhgpofcejgcfcgcinmeoalj) in selected browser profile; click Glider icon, then run `glider connect` | per browser launch | relay waits on extension WS |
149
169
  | extension socket up but worker dead | click Glider icon or `glider reload` | MV3 worker | status refuses healthy until pong |
150
170
  | daemon / `glider start` refuses after a killed supervisor | run `glider start` or `glider install` again (0.4.15+ reaps dead claim tombstones when nothing listens) | session-stable | crash/SIGKILL left `daemon-*.claim` without a live owner |
171
+ | `glider tabs` dumps old CDP pages | `glider start` or `glider heal` (0.4.17 recycles a relay that does not advertise `/catalog`) | session | node does not hot-load `bserve.js` |
172
+ | `glider tabs` has empty windows | load Glider 1.0.10 from [`vdutts7/glider`](https://github.com/vdutts7/glider) or CWS after upload (needs `listTabs`) | until CWS 1.0.10 | Chrome Web Store 1.0.9 lacks that RPC |
173
+ | incognito window has no `(incognito)` tag | Allow in Incognito on the extension, then reload; CLI 0.4.18 | per profile | Chromium hides those windows until that toggle |
151
174
  | custom relay port has no extension | stay on `19988` with Chrome Web Store build | install-stable | published extension connects to `ws://localhost:19988/extension` |
152
175
  | wrong tab targeted | `glider targets` → `glider use-session session-6` | session-stable | multi-tab needs explicit session |
153
176
  | explore HAR empty bodies | replay in-tab with auth hook on XHR/fetch | site-specific | some SPAs never expose bearer in storage |
@@ -165,7 +188,8 @@ Copy `config/domains.template.json` into `~/.glider/config/domains.json` to seed
165
188
  | `glider connect` | attach relay to browser |
166
189
  | `glider status` | server + extension + tabs |
167
190
  | `glider doctor` | relay + SW + targets |
168
- | `glider heal` | wake SW, reattach |
191
+ | `glider tabs` | chrome.tabs by window (incognito tag), then attached, then stale |
192
+ | `glider heal` | recycle stale relay, wake SW, reattach |
169
193
  | `glider reload` | pin extension |
170
194
  | `glider goto` | navigate |
171
195
  | `glider eval` | run JS |
@@ -199,7 +223,7 @@ Incomplete event-stream features fail closed: `wait --network-idle`, console str
199
223
 
200
224
  | status | item |
201
225
  |--------|------|
202
- | done | CDP relay, YAML tasks, loop, daemon, multi-tab, `resolve` |
226
+ | done | CDP relay, YAML tasks, loop, daemon, multi-tab, `resolve`, `glider tabs` catalog |
203
227
  | planned | Linux and Windows browser launch |
204
228
  | | headless cloud mode |
205
229
  | | task chaining |
package/bin/glider.js CHANGED
@@ -78,6 +78,8 @@ if (fs.existsSync(REGISTRY_FILE)) {
78
78
  const { DirectCDP, checkChrome } = require(path.join(LIB_DIR, 'cdp-direct.js'));
79
79
  const { resolveDomain } = require(path.join(LIB_DIR, 'domain-resolve.js'));
80
80
  const pinMachine = require(path.join(LIB_DIR, 'pin-machine.js'));
81
+ const relayHeal = require(path.join(LIB_DIR, 'relay-heal.js'));
82
+ const { npmIsNewer } = require(path.join(LIB_DIR, 'pkg-update.js'));
81
83
 
82
84
  // Domain extensions - load from ~/.glider/config/domains.json
83
85
  const DOMAIN_CONFIG_PATHS = configPath('domains.json');
@@ -500,7 +502,8 @@ function httpGet(urlPath) {
500
502
  const started = Date.now();
501
503
  return new Promise((resolve, reject) => {
502
504
  const url = new URL(urlPath, SERVER_URL);
503
- const req = http.get(url, { timeout: 2000 }, (res) => {
505
+ const timeoutMs = urlPath === '/catalog' ? 8000 : 2000;
506
+ const req = http.get(url, { timeout: timeoutMs }, (res) => {
504
507
  let data = '';
505
508
  res.on('data', chunk => data += chunk);
506
509
  res.on('end', () => {
@@ -807,6 +810,98 @@ async function getTargets() {
807
810
  }
808
811
  }
809
812
 
813
+ async function fetchCatalogQuiet() {
814
+ try {
815
+ const catalog = await httpGet('/catalog');
816
+ return relayHeal.catalogLooksLive(catalog) ? catalog : null;
817
+ } catch {
818
+ return null;
819
+ }
820
+ }
821
+
822
+ function relayProcessIsOurs(status) {
823
+ if (!Number.isInteger(status?.pid) || status.pid <= 0) return false;
824
+ const identity = getProcessIdentity(status.pid);
825
+ return Boolean(identity && commandIncludesPath(identity.command, RELAY_ENTRY));
826
+ }
827
+
828
+ async function recycleLiveRelay() {
829
+ const ownership = inspectDaemonOwnership();
830
+ if (ownership.state === 'owned' && daemonChildMatches(ownership.record)) {
831
+ const childPid = ownership.record.childPid;
832
+ try { process.kill(childPid, 'SIGTERM'); } catch (error) {
833
+ if (error.code !== 'ESRCH') throw error;
834
+ }
835
+ await waitForProcessExit(childPid, 8000);
836
+ await waitUntil(async () => Boolean(await fetchCatalogQuiet()), {
837
+ timeoutMs: 20000,
838
+ intervalMs: 200,
839
+ label: 'catalog after daemon child recycle',
840
+ });
841
+ return { recycled: true, via: 'daemon_child' };
842
+ }
843
+ if (ownership.state === 'owned' || ownership.state === 'unverified') {
844
+ throw new Error(`cannot recycle unverified daemon-owned relay on port ${PORT}`);
845
+ }
846
+ await cmdStop({ render: false });
847
+ await new Promise((r) => setTimeout(r, 300));
848
+ await cmdStart({ render: false });
849
+ await waitUntil(async () => Boolean(await fetchCatalogQuiet()), {
850
+ timeoutMs: 15000,
851
+ intervalMs: 200,
852
+ label: 'catalog after standalone restart',
853
+ });
854
+ return { recycled: true, via: 'standalone_restart' };
855
+ }
856
+
857
+ async function autoHealRelay() {
858
+ const actions = [];
859
+ let status = null;
860
+ try { status = await getRelayStatus(); } catch { status = null; }
861
+ if (!status) return { actions, catalog: null, status: null };
862
+
863
+ const identity = Number.isInteger(status.pid) ? getProcessIdentity(status.pid) : null;
864
+ const decision = relayHeal.shouldRecycleRelay({
865
+ catalogOk: Boolean(await fetchCatalogQuiet()),
866
+ catalogAdvertised: status.catalog === true,
867
+ entryMtimeMs: relayHeal.entryMtimeMs(RELAY_ENTRY),
868
+ processStartMs: relayHeal.lstartToMs(identity?.started),
869
+ });
870
+ if (decision.recycle && relayProcessIsOurs(status)) {
871
+ try {
872
+ const recycled = await recycleLiveRelay();
873
+ actions.push({ step: 'recycle_relay', ok: true, reason: decision.reason, ...recycled });
874
+ } catch (error) {
875
+ actions.push({ step: 'recycle_relay', ok: false, reason: decision.reason, error: error.message });
876
+ }
877
+ try { status = await getRelayStatus(); } catch { status = null; }
878
+ }
879
+
880
+ let catalog = await fetchCatalogQuiet();
881
+ const ext = relayHeal.shouldHealExtension({
882
+ extensionConnected: status?.extension === true,
883
+ workerAlive: extensionReady(status),
884
+ listTabsOk: catalog ? catalog.listTabsOk === true : null,
885
+ });
886
+ if (ext.heal && ext.step === 'reload' && extensionReady(status)) {
887
+ try {
888
+ await postExtension({ method: 'reloadSelf', params: {} });
889
+ actions.push({ step: 'reload_extension', ok: true });
890
+ const beforeGen = status.extensionGeneration;
891
+ await waitUntil(async () => {
892
+ const now = await getRelayStatus();
893
+ return now?.extension === true && now.extensionGeneration !== beforeGen;
894
+ }, { timeoutMs: 15000, intervalMs: 200, label: 'extension reconnect' });
895
+ await postExtension({ method: 'attachAllTabs', params: {} });
896
+ actions.push({ step: 'attach_all', ok: true });
897
+ } catch (error) {
898
+ actions.push({ step: 'reload_extension', ok: false, error: error.message });
899
+ }
900
+ catalog = await fetchCatalogQuiet();
901
+ }
902
+ return { actions, catalog, status };
903
+ }
904
+
810
905
  function appleScriptString(value) {
811
906
  return String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
812
907
  }
@@ -1072,18 +1167,61 @@ async function cmdStart({ render = true } = {}) {
1072
1167
  throw new Error(`Daemon PID ${ownership.record.pid} does not own the active relay on port ${PORT}`);
1073
1168
  }
1074
1169
  if (ownership.state === 'unverified') assertStandaloneRelayAllowed(ownership);
1075
- const result = {
1076
- running: true,
1077
- port: PORT,
1078
- pid: status.pid,
1079
- alreadyRunning: true,
1080
- managedBy: ownership.state === 'owned' ? 'daemon' : 'standalone',
1081
- };
1082
- if (render) {
1083
- if (jsonOutput) emitJson(true, result);
1084
- else log.ok('Server already running');
1170
+ const identity = getProcessIdentity(status.pid);
1171
+ const decision = relayHeal.shouldRecycleRelay({
1172
+ catalogOk: Boolean(await fetchCatalogQuiet()),
1173
+ catalogAdvertised: status.catalog === true,
1174
+ entryMtimeMs: relayHeal.entryMtimeMs(RELAY_ENTRY),
1175
+ processStartMs: relayHeal.lstartToMs(identity?.started),
1176
+ });
1177
+ const ours = relayProcessIsOurs(status);
1178
+ if (ours && decision.recycle && ownership.state === 'owned') {
1179
+ const childPid = ownership.record.childPid;
1180
+ try { process.kill(childPid, 'SIGTERM'); } catch (error) {
1181
+ if (error.code !== 'ESRCH') throw error;
1182
+ }
1183
+ await waitForProcessExit(childPid, 8000);
1184
+ await waitUntil(async () => Boolean(await fetchCatalogQuiet()), {
1185
+ timeoutMs: 20000,
1186
+ intervalMs: 200,
1187
+ label: 'catalog after daemon child recycle',
1188
+ });
1189
+ const live = await getRelayStatus();
1190
+ const result = {
1191
+ running: true,
1192
+ port: PORT,
1193
+ pid: live?.pid,
1194
+ alreadyRunning: false,
1195
+ recycled: true,
1196
+ managedBy: 'daemon',
1197
+ };
1198
+ if (render) {
1199
+ if (jsonOutput) emitJson(true, result);
1200
+ else log.ok('Server recycled onto current relay');
1201
+ }
1202
+ return result;
1203
+ }
1204
+ if (ours && decision.recycle) {
1205
+ try { process.kill(status.pid, 'SIGTERM'); } catch (error) {
1206
+ if (error.code !== 'ESRCH') throw error;
1207
+ }
1208
+ await waitForProcessExit(status.pid, 8000);
1209
+ try { removeRelayPidRecordIfOwned(status.pid, identity?.started); } catch {}
1210
+ status = null;
1211
+ } else {
1212
+ const result = {
1213
+ running: true,
1214
+ port: PORT,
1215
+ pid: status.pid,
1216
+ alreadyRunning: true,
1217
+ managedBy: ownership.state === 'owned' ? 'daemon' : 'standalone',
1218
+ };
1219
+ if (render) {
1220
+ if (jsonOutput) emitJson(true, result);
1221
+ else log.ok('Server already running');
1222
+ }
1223
+ return result;
1085
1224
  }
1086
- return result;
1087
1225
  }
1088
1226
 
1089
1227
  assertStandaloneRelayAllowed(ownership);
@@ -2132,6 +2270,12 @@ async function cmdHeal(args = []) {
2132
2270
  relay = null;
2133
2271
  }
2134
2272
 
2273
+ if (relay) {
2274
+ const healed = await autoHealRelay();
2275
+ actions.push(...healed.actions);
2276
+ try { relay = await getRelayStatus(); } catch { relay = null; }
2277
+ }
2278
+
2135
2279
  if (clearPin) {
2136
2280
  clearPersistedSession();
2137
2281
  actions.push({ step: 'clear_pin', ok: true });
@@ -2212,26 +2356,56 @@ async function cmdHeal(args = []) {
2212
2356
  }
2213
2357
 
2214
2358
  async function cmdTabs() {
2215
- const targets = await getTargets();
2216
- const part = pinMachine.partition(targets);
2217
- if (jsonOutput) {
2218
- emitJson(true, { pages: part.pages, iframes: part.iframes, other: part.other, activeSessionId });
2359
+ let catalog = await fetchCatalogQuiet();
2360
+ if (!catalog || (catalog.listTabsOk === false)) {
2361
+ await autoHealRelay();
2362
+ catalog = await fetchCatalogQuiet();
2363
+ }
2364
+ if (!catalog || catalog.error || !Array.isArray(catalog.windows)) {
2365
+ if (jsonOutput) {
2366
+ emitJson(false, null, 'catalog unavailable');
2367
+ process.exitCode = 1;
2368
+ return;
2369
+ }
2370
+ log.fail('catalog unavailable');
2371
+ process.exitCode = 1;
2219
2372
  return;
2220
2373
  }
2221
- if (part.pages.length === 0) {
2222
- log.warn('No page targets');
2374
+ if (jsonOutput) {
2375
+ emitJson(true, { ...catalog, activeSessionId });
2223
2376
  return;
2224
2377
  }
2225
- console.log(`${GREEN}${part.pages.length}${NC} page(s) connected:\n`);
2226
- part.pages.forEach((t, i) => {
2227
- const mark = t.sessionId === activeSessionId ? `${GREEN}*${NC} ` : ' ';
2228
- console.log(`${mark}${CYAN}[${i + 1}]${NC} ${t.title || t.url}`);
2229
- console.log(` ${DIM}${t.url}${NC}`);
2230
- const kids = part.iframes.filter((fr) => fr.parent_targetId === t.targetId);
2231
- for (const fr of kids) {
2232
- console.log(` ${DIM}iframe${NC} ${fr.url}`);
2233
- }
2234
- });
2378
+ const winCount = catalog.windows.reduce((n, w) => n + (w.tabs || []).length, 0);
2379
+ console.log(`${GREEN}${winCount}${NC} tab(s) in ${catalog.windows.length} window(s)\n`);
2380
+ let n = 0;
2381
+ for (const w of catalog.windows) {
2382
+ const tag = [w.current ? 'current' : 'other', w.incognito ? 'incognito' : null].filter(Boolean).join(', ');
2383
+ console.log(`${CYAN}window ${w.windowId}${NC} ${DIM}(${tag})${NC}`);
2384
+ for (const t of w.tabs || []) {
2385
+ n += 1;
2386
+ const mark = t.sessionId && t.sessionId === activeSessionId ? `${GREEN}*${NC} ` : ' ';
2387
+ const att = t.attached ? `${DIM} attached${NC}` : '';
2388
+ const disc = t.discarded ? `${DIM} discarded${NC}` : '';
2389
+ console.log(`${mark}${CYAN}[${n}]${NC} ${t.title || t.url}${att}${disc}`);
2390
+ console.log(` ${DIM}${t.url}${NC}`);
2391
+ }
2392
+ console.log();
2393
+ }
2394
+ if ((catalog.attached || []).length) {
2395
+ console.log(`${CYAN}attached${NC} ${DIM}(debugger, not in chrome.tabs)${NC}`);
2396
+ catalog.attached.forEach((t, i) => {
2397
+ console.log(` ${CYAN}[A${i + 1}]${NC} ${t.title || t.url}`);
2398
+ console.log(` ${DIM}${t.url}${NC}`);
2399
+ });
2400
+ console.log();
2401
+ }
2402
+ if ((catalog.stale || []).length) {
2403
+ console.log(`${YELLOW}stale${NC} ${DIM}(dropped from map)${NC}`);
2404
+ catalog.stale.forEach((t, i) => {
2405
+ console.log(` ${CYAN}[S${i + 1}]${NC} ${t.title || t.url}`);
2406
+ console.log(` ${DIM}${t.url}${NC}`);
2407
+ });
2408
+ }
2235
2409
  }
2236
2410
 
2237
2411
  async function cmdWindow(args) {
@@ -3697,7 +3871,7 @@ ${B5}SETUP${NC}
3697
3871
  ${B5}STATUS${NC}
3698
3872
  ${BW}status${NC} Check server, extension, tabs
3699
3873
  ${BW}doctor${NC} Relay + SW + targets
3700
- ${BW}heal${NC} Ensure relay, wake SW, reattach
3874
+ ${BW}heal${NC} Recycle stale relay, wake SW, reattach
3701
3875
  ${BW}reload${NC} Pin Glider extension
3702
3876
  ${BW}config browser chrome${NC} ${DIM}also: edge, brave, opera, vivaldi, helium, arc${NC}
3703
3877
  ${BW}test${NC} Run diagnostics
@@ -3717,7 +3891,7 @@ ${B5}PAGE INFO${NC}
3717
3891
  ${BW}html${NC} [selector] Get HTML
3718
3892
  ${BW}title${NC} Get page title
3719
3893
  ${BW}url${NC} Get current URL
3720
- ${BW}tabs${NC} List connected tabs
3894
+ ${BW}tabs${NC} chrome.tabs by window (incognito tag), then attached, then stale
3721
3895
 
3722
3896
  ${B5}MULTI-WINDOW${NC}
3723
3897
  ${BW}window new${NC} [url] Create new browser window ${DIM}(closeable)${NC}
@@ -3888,7 +4062,7 @@ async function checkForUpdates() {
3888
4062
  });
3889
4063
 
3890
4064
  const latest = data.version;
3891
- if (latest && latest !== current) {
4065
+ if (latest && npmIsNewer(current, latest)) {
3892
4066
  console.error(`${YELLOW}⬆${NC} Update available: ${DIM}${current}${NC} → ${GREEN}${latest}${NC} ${DIM}(run: glider update)${NC}`);
3893
4067
  }
3894
4068
  } catch {} // Silent fail - don't block CLI
@@ -3912,13 +4086,15 @@ async function cmdUpdate() {
3912
4086
  });
3913
4087
 
3914
4088
  const latest = data.version;
3915
- if (latest === current) {
3916
- log.ok(`Already on latest version (${current})`);
4089
+ if (!latest) throw new Error('npm latest version missing');
4090
+ if (!npmIsNewer(current, latest)) {
4091
+ if (latest === current) log.ok(`Already on latest version (${current})`);
4092
+ else log.ok(`Local ${current} is ahead of npm ${latest}; not downgrading`);
3917
4093
  return;
3918
4094
  }
3919
-
4095
+
3920
4096
  log.info(`Updating ${current} → ${latest}...`);
3921
- execSync('npm update -g glidercli', { stdio: 'inherit' });
4097
+ execSync(`npm install -g glidercli@${latest}`, { stdio: 'inherit' });
3922
4098
  log.ok(`Updated to ${latest}`);
3923
4099
  } catch (e) {
3924
4100
  log.fail(`Update failed: ${e.message}`);
package/docs/setup.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "project": "glidercli",
4
- "updated": "2026-09-17"
4
+ "updated": "2026-10-16"
5
5
  },
6
6
  "architecture": {
7
7
  "flow": "glidercli -> bserve (localhost relay) -> Chromium extension -> chrome.debugger -> tab",
@@ -25,8 +25,9 @@
25
25
  },
26
26
  "endpoints": {
27
27
  "http": {
28
- "/status": "GET - extension/targets/clients status",
29
- "/targets": "GET - connected tabs",
28
+ "/status": "GET - extension/targets/clients status; catalog true when GET /catalog exists",
29
+ "/targets": "GET - connected CDP sessions",
30
+ "/catalog": "GET - chrome.tabs by window (incognito from chrome.windows/tabs), attached debugger-only, stale reaped sessions",
30
31
  "/cdp": "POST - forward CDP command"
31
32
  },
32
33
  "websocket": {
package/lib/bserve.js CHANGED
@@ -6,8 +6,10 @@
6
6
  'use strict';
7
7
 
8
8
  const { WebSocketServer, WebSocket } = require('ws');
9
+ const fs = require('fs');
9
10
  const http = require('http');
10
11
  const { relayPort } = require('./relay-config.js');
12
+ const { buildCatalog, reapFromMap } = require('./tab-catalog.js');
11
13
 
12
14
  const PORT = relayPort();
13
15
  const HOST = '127.0.0.1';
@@ -50,9 +52,13 @@ function extensionWorkerAlive() {
50
52
  }
51
53
 
52
54
  function statusPayload() {
55
+ let entryMtimeMs = 0;
56
+ try { entryMtimeMs = fs.statSync(__filename).mtimeMs; } catch { /* ignore */ }
53
57
  return {
54
58
  pid: process.pid,
55
59
  port: PORT,
60
+ catalog: true,
61
+ entryMtimeMs,
56
62
  extension: extensionSocketOpen(),
57
63
  extensionWorkerAlive: extensionWorkerAlive(),
58
64
  extensionGeneration,
@@ -118,6 +124,35 @@ async function waitForExtensionSocket(timeoutMs) {
118
124
  throw new Error('Extension not connected');
119
125
  }
120
126
 
127
+ async function buildLiveCatalog() {
128
+ let chromeTabs = [];
129
+ let chromeWindows = [];
130
+ let focusedWindowId = 0;
131
+ let listTabsOk = false;
132
+ if (extensionSocketOpen()) {
133
+ try {
134
+ const listed = await sendToExtension({ method: 'listTabs', params: {}, timeout: 4000 });
135
+ const rows = listed && (listed.tabs || listed.result?.tabs);
136
+ chromeTabs = Array.isArray(rows) ? rows : [];
137
+ focusedWindowId = Number(listed?.focusedWindowId || listed?.result?.focusedWindowId) || 0;
138
+ const wins = listed && (listed.windows || listed.result?.windows);
139
+ chromeWindows = Array.isArray(wins) ? wins : [];
140
+ listTabsOk = true;
141
+ } catch {
142
+ listTabsOk = false;
143
+ }
144
+ }
145
+ const catalog = buildCatalog({
146
+ chromeTabs,
147
+ chromeWindows,
148
+ cdpPages: Array.from(connectedTargets.values()),
149
+ focusedWindowId,
150
+ listTabsOk,
151
+ });
152
+ if (listTabsOk) reapFromMap(connectedTargets, catalog.reapSessionIds);
153
+ return catalog;
154
+ }
155
+
121
156
  function removeTargetById(targetId) {
122
157
  for (const [sessionId, target] of connectedTargets.entries()) {
123
158
  if (target.targetId === targetId) {
@@ -138,6 +173,17 @@ const server = http.createServer((req, res) => {
138
173
  } else if (req.url === '/targets') {
139
174
  res.writeHead(200, { 'Content-Type': 'application/json' });
140
175
  res.end(JSON.stringify(Array.from(connectedTargets.values())));
176
+ } else if (req.url === '/catalog' && req.method === 'GET') {
177
+ (async () => {
178
+ try {
179
+ const catalog = await buildLiveCatalog();
180
+ res.writeHead(200, { 'Content-Type': 'application/json' });
181
+ res.end(JSON.stringify(catalog));
182
+ } catch (e) {
183
+ res.writeHead(500, { 'Content-Type': 'application/json' });
184
+ res.end(JSON.stringify({ error: e.message }));
185
+ }
186
+ })();
141
187
  } else if (req.url === '/attach' && req.method === 'POST') {
142
188
  (async () => {
143
189
  try {
@@ -204,12 +250,14 @@ function handleExtensionConnection(ws) {
204
250
  extensionWs = null;
205
251
  try { previous.close(4001, 'Replaced'); } catch { /* ignore */ }
206
252
  // Hard cut on replace (not a transient flap): drop clients + pending.
207
- // Targets stay until the new extension re-announces or grace paths clear them.
208
253
  rejectAllPending('Extension replaced');
209
254
  closeAllClients('Extension replaced');
210
255
  }
211
256
 
212
257
  clearDisconnectGrace();
258
+ // New generation: old sessionIds are dead. Keep the map only while disconnected
259
+ // (reconnect grace). Re-announce fills it again.
260
+ connectedTargets.clear();
213
261
  extensionWs = ws;
214
262
  extensionGeneration += 1;
215
263
  lastPongAt = Date.now();
@@ -267,9 +315,11 @@ function handleExtensionMessage(msg) {
267
315
  const { method, params, sessionId } = msg.params;
268
316
 
269
317
  if (method === 'Target.attachedToTarget') {
318
+ const tabId = Number(params.tabId || params.targetInfo?.tabId) || 0;
270
319
  connectedTargets.set(params.sessionId, {
271
320
  sessionId: params.sessionId,
272
321
  targetId: params.targetInfo.targetId,
322
+ tabId,
273
323
  targetInfo: params.targetInfo,
274
324
  });
275
325
  console.log(`[relay] Target attached: ${params.targetInfo.url}`);
@@ -473,6 +523,7 @@ if (require.main === module) {
473
523
  console.log(` - CDP: ws://${HOST}:${PORT}/cdp`);
474
524
  console.log(` - Status: http://${HOST}:${PORT}/status`);
475
525
  console.log(` - Targets: http://${HOST}:${PORT}/targets`);
526
+ console.log(` - Catalog: http://${HOST}:${PORT}/catalog`);
476
527
  });
477
528
 
478
529
  process.on('SIGINT', () => {
@@ -494,8 +494,30 @@ while true; do
494
494
  exit 1
495
495
  fi
496
496
 
497
+ poll_child_recycle() {
498
+ while kill -0 "$child_pid" 2>/dev/null; do
499
+ if "$NODE_BIN" -e '
500
+ const heal = require(process.argv[1]);
501
+ const port = process.argv[2];
502
+ const entry = process.argv[3];
503
+ const childPid = Number(process.argv[4]);
504
+ heal.childNeedsRecycle({ port, entryPath: entry, childPid }).then((d) => {
505
+ process.exit(d.recycle ? 0 : 1);
506
+ }).catch(() => process.exit(1));
507
+ ' "$SCRIPT_DIR/relay-heal.js" "$PORT" "$BSERVE" "$child_pid"; then
508
+ echo "glider-daemon: recycling stale relay child PID $child_pid" >&2
509
+ kill "$child_pid" 2>/dev/null || true
510
+ return 0
511
+ fi
512
+ sleep "${GLIDER_RELAY_HEAL_POLL_SEC:-2}"
513
+ done
514
+ }
515
+ poll_child_recycle &
516
+ watcher_pid=$!
497
517
  wait "$child_pid"
498
518
  EXIT_CODE=$?
519
+ kill "$watcher_pid" 2>/dev/null || true
520
+ wait "$watcher_pid" 2>/dev/null || true
499
521
  child_pid=""
500
522
  child_started=""
501
523
  relay_ready=0
@@ -31,6 +31,7 @@ function info(t) {
31
31
  title: ti.title || t.title || '',
32
32
  parentFrameId: ti.parentFrameId || t.parentFrameId || '',
33
33
  attached: ti.attached,
34
+ tabId: Number(t.tabId || ti.tabId) || 0,
34
35
  };
35
36
  }
36
37
 
@@ -0,0 +1,26 @@
1
+ 'use strict';
2
+
3
+ function parseVersion(raw) {
4
+ const core = String(raw || '').trim().split('-')[0].split('+')[0];
5
+ const parts = core.split('.').map((n) => Number.parseInt(n, 10));
6
+ if (parts.length < 1 || parts.some((n) => !Number.isInteger(n) || n < 0)) return null;
7
+ while (parts.length < 3) parts.push(0);
8
+ return parts.slice(0, 3);
9
+ }
10
+
11
+ function compareVersions(a, b) {
12
+ const left = parseVersion(a);
13
+ const right = parseVersion(b);
14
+ if (!left || !right) return null;
15
+ for (let i = 0; i < 3; i += 1) {
16
+ if (left[i] < right[i]) return -1;
17
+ if (left[i] > right[i]) return 1;
18
+ }
19
+ return 0;
20
+ }
21
+
22
+ function npmIsNewer(current, latest) {
23
+ return compareVersions(current, latest) === -1;
24
+ }
25
+
26
+ module.exports = { parseVersion, compareVersions, npmIsNewer };
@@ -0,0 +1,113 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const http = require('http');
5
+ const { execFileSync } = require('child_process');
6
+
7
+ function catalogLooksLive(body) {
8
+ return Boolean(body && Array.isArray(body.windows) && body.error == null);
9
+ }
10
+
11
+ function lstartToMs(started) {
12
+ if (!started) return NaN;
13
+ const t = Date.parse(started);
14
+ return Number.isFinite(t) ? t : NaN;
15
+ }
16
+
17
+ function entryMtimeMs(entryPath) {
18
+ try {
19
+ return fs.statSync(entryPath).mtimeMs;
20
+ } catch {
21
+ return NaN;
22
+ }
23
+ }
24
+
25
+ function relayBinaryStale({ entryMtimeMs: mtime, processStartMs, skewMs = 2000 } = {}) {
26
+ if (!Number.isFinite(mtime) || !Number.isFinite(processStartMs)) return false;
27
+ return mtime > processStartMs + skewMs;
28
+ }
29
+
30
+ function shouldRecycleRelay({
31
+ catalogOk,
32
+ catalogAdvertised,
33
+ entryMtimeMs: mtime,
34
+ processStartMs,
35
+ } = {}) {
36
+ if (catalogAdvertised === false) return { recycle: true, reason: 'catalog_unadvertised' };
37
+ if (catalogAdvertised === true) {
38
+ if (relayBinaryStale({ entryMtimeMs: mtime, processStartMs })) {
39
+ return { recycle: true, reason: 'binary_stale' };
40
+ }
41
+ return { recycle: false, reason: null };
42
+ }
43
+ if (catalogOk === false) return { recycle: true, reason: 'catalog_missing' };
44
+ if (relayBinaryStale({ entryMtimeMs: mtime, processStartMs })) {
45
+ return { recycle: true, reason: 'binary_stale' };
46
+ }
47
+ return { recycle: false, reason: null };
48
+ }
49
+
50
+ function shouldHealExtension({ workerAlive, listTabsOk, extensionConnected } = {}) {
51
+ if (extensionConnected === false) return { heal: true, step: 'wake' };
52
+ if (workerAlive === false) return { heal: true, step: 'wake' };
53
+ if (listTabsOk === false) return { heal: true, step: 'reload' };
54
+ return { heal: false, step: null };
55
+ }
56
+
57
+ function childStartMs(pid) {
58
+ try {
59
+ const started = execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], {
60
+ encoding: 'utf8',
61
+ env: { ...process.env, LC_ALL: 'C', LANG: 'C', TZ: 'UTC' },
62
+ }).trim();
63
+ return lstartToMs(started);
64
+ } catch {
65
+ return NaN;
66
+ }
67
+ }
68
+
69
+ function httpGetJson(port, urlPath, timeoutMs = 800) {
70
+ return new Promise((resolve) => {
71
+ const req = http.get(
72
+ { host: '127.0.0.1', port: Number(port), path: urlPath, timeout: timeoutMs },
73
+ (res) => {
74
+ let raw = '';
75
+ res.on('data', (chunk) => { raw += chunk; });
76
+ res.on('end', () => {
77
+ let body = null;
78
+ try { body = JSON.parse(raw); } catch { /* not json */ }
79
+ resolve({ status: res.statusCode, body });
80
+ });
81
+ },
82
+ );
83
+ req.on('error', () => resolve({ status: 0, body: null }));
84
+ req.on('timeout', () => {
85
+ req.destroy();
86
+ resolve({ status: 0, body: null });
87
+ });
88
+ });
89
+ }
90
+
91
+ async function childNeedsRecycle({ port, entryPath, childPid }) {
92
+ const cat = await httpGetJson(port, '/catalog', 800);
93
+ const st = await httpGetJson(port, '/status', 800);
94
+ const advertised = st.body ? st.body.catalog === true : false;
95
+ const decision = shouldRecycleRelay({
96
+ catalogOk: catalogLooksLive(cat.body) && cat.status >= 200 && cat.status < 300,
97
+ catalogAdvertised: advertised,
98
+ entryMtimeMs: entryMtimeMs(entryPath),
99
+ processStartMs: childStartMs(childPid),
100
+ });
101
+ return decision;
102
+ }
103
+
104
+ module.exports = {
105
+ catalogLooksLive,
106
+ lstartToMs,
107
+ entryMtimeMs,
108
+ relayBinaryStale,
109
+ shouldRecycleRelay,
110
+ shouldHealExtension,
111
+ childNeedsRecycle,
112
+ httpGetJson,
113
+ };
@@ -0,0 +1,149 @@
1
+ 'use strict';
2
+
3
+ const { partition } = require('./pin-machine.js');
4
+
5
+ function tabIdOf(row) {
6
+ const n = Number(row && (row.tabId ?? row.targetInfo?.tabId));
7
+ return Number.isInteger(n) && n > 0 ? n : 0;
8
+ }
9
+
10
+ function contextIdOf(page) {
11
+ return (page && (page.browserContextId || page.targetInfo?.browserContextId)) || '';
12
+ }
13
+
14
+ function windowIncognito(chromeWindows, wid, tabsInWindow) {
15
+ const meta = (chromeWindows || []).find((w) => (w.windowId ?? w.id) === wid);
16
+ if (meta && Object.prototype.hasOwnProperty.call(meta, 'incognito')) {
17
+ return { incognito: !!meta.incognito, incognitoSource: 'chrome.windows' };
18
+ }
19
+ if ((tabsInWindow || []).some((t) => t.incognito)) {
20
+ return { incognito: true, incognitoSource: 'chrome.tabs' };
21
+ }
22
+ return { incognito: false, incognitoSource: '' };
23
+ }
24
+
25
+ function chromeRow(tab, page, win) {
26
+ const fromTab = !!tab.incognito;
27
+ const incognito = win.incognito || fromTab;
28
+ const incognitoSource = win.incognito
29
+ ? win.incognitoSource
30
+ : (fromTab ? 'chrome.tabs' : '');
31
+ return {
32
+ tabId: tab.id,
33
+ windowId: tab.windowId,
34
+ index: tab.index,
35
+ title: tab.title || '',
36
+ url: tab.url || '',
37
+ active: !!tab.active,
38
+ discarded: !!tab.discarded,
39
+ highlighted: !!tab.highlighted,
40
+ incognito,
41
+ incognitoSource,
42
+ attached: Boolean(page && page.sessionId),
43
+ sessionId: page && page.sessionId ? page.sessionId : '',
44
+ targetId: page && page.targetId ? page.targetId : '',
45
+ browserContextId: contextIdOf(page),
46
+ };
47
+ }
48
+
49
+ function buildCatalog({ chromeTabs, chromeWindows, cdpPages, focusedWindowId, listTabsOk } = {}) {
50
+ const tabs = Array.isArray(chromeTabs) ? chromeTabs : [];
51
+ const rawPages = Array.isArray(cdpPages) ? cdpPages : [];
52
+ const part = partition(rawPages);
53
+ const bySession = new Map(rawPages.map((t) => [t.sessionId || '', t]));
54
+ const enriched = part.pages.map((p) => {
55
+ const raw = bySession.get(p.sessionId) || p;
56
+ return {
57
+ ...p,
58
+ tabId: tabIdOf(raw),
59
+ browserContextId: contextIdOf(raw),
60
+ targetInfo: raw.targetInfo,
61
+ };
62
+ });
63
+
64
+ const byTab = new Map();
65
+ for (const p of enriched) {
66
+ if (p.tabId) byTab.set(p.tabId, p);
67
+ }
68
+ const chromeIds = new Set(tabs.map((t) => t.id));
69
+
70
+ const windowMap = new Map();
71
+ const matched = new Set();
72
+ for (const tab of tabs) {
73
+ if (!tab || tab.id == null) continue;
74
+ const page = byTab.get(tab.id) || null;
75
+ if (page) matched.add(page.sessionId);
76
+ const wid = tab.windowId;
77
+ if (!windowMap.has(wid)) {
78
+ const win = windowIncognito(
79
+ chromeWindows,
80
+ wid,
81
+ tabs.filter((t) => t.windowId === wid),
82
+ );
83
+ windowMap.set(wid, {
84
+ windowId: wid,
85
+ current: focusedWindowId != null && wid === focusedWindowId,
86
+ incognito: win.incognito,
87
+ incognitoSource: win.incognitoSource,
88
+ tabs: [],
89
+ });
90
+ }
91
+ const bucket = windowMap.get(wid);
92
+ bucket.tabs.push(chromeRow(tab, page, {
93
+ incognito: bucket.incognito,
94
+ incognitoSource: bucket.incognitoSource,
95
+ }));
96
+ }
97
+ for (const w of windowMap.values()) {
98
+ w.tabs.sort((a, b) => a.index - b.index);
99
+ }
100
+ const windows = Array.from(windowMap.values()).sort((a, b) => {
101
+ if (a.current !== b.current) return a.current ? -1 : 1;
102
+ return a.windowId - b.windowId;
103
+ });
104
+
105
+ const attached = [];
106
+ const stale = [];
107
+ const ok = listTabsOk === true;
108
+ for (const p of enriched) {
109
+ if (matched.has(p.sessionId)) continue;
110
+ const row = {
111
+ tabId: p.tabId || 0,
112
+ sessionId: p.sessionId,
113
+ targetId: p.targetId,
114
+ title: p.title || '',
115
+ url: p.url || '',
116
+ type: p.type,
117
+ browserContextId: contextIdOf(p),
118
+ };
119
+ if (ok && p.tabId && !chromeIds.has(p.tabId)) {
120
+ stale.push({ ...row, reason: 'tab_gone' });
121
+ } else {
122
+ attached.push(row);
123
+ }
124
+ }
125
+
126
+ return {
127
+ focusedWindowId: focusedWindowId || 0,
128
+ listTabsOk: ok,
129
+ windows,
130
+ attached,
131
+ stale,
132
+ reapSessionIds: stale.map((s) => s.sessionId).filter(Boolean),
133
+ iframes: part.iframes,
134
+ pages: part.pages,
135
+ };
136
+ }
137
+
138
+ function reapFromMap(connectedTargets, sessionIds) {
139
+ const dropped = [];
140
+ for (const sid of sessionIds || []) {
141
+ if (connectedTargets.has(sid)) {
142
+ connectedTargets.delete(sid);
143
+ dropped.push(sid);
144
+ }
145
+ }
146
+ return dropped;
147
+ }
148
+
149
+ module.exports = { buildCatalog, reapFromMap, tabIdOf };
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "glidercli",
3
- "version": "0.4.16",
3
+ "version": "0.4.18",
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",
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/pin-machine.js && node --check lib/relay-heal.js && node --check lib/pkg-update.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",
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",