dsh-browser-cdp 1.7.6 → 1.7.10

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/lib/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { f as stopLocalBrowser, l as launchLocalBrowser } from "./launcher-BadIUjAx.js";
1
+ import { f as stopLocalBrowser, l as launchLocalBrowser } from "./launcher-Vz8i9ylT.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { defineTool } from "@deepseek-ai/dsh-tools";
4
- import { constants, createReadStream, createWriteStream, existsSync, readdirSync } from "node:fs";
4
+ import { constants, createReadStream, createWriteStream, existsSync, readFileSync, readdirSync } from "node:fs";
5
5
  import { homedir, tmpdir } from "node:os";
6
+ import { basename, dirname, join, normalize, resolve, sep } from "node:path";
6
7
  import { fileURLToPath } from "node:url";
7
8
  import { access, chmod, copyFile, mkdir, open, readFile, readdir, rename, rm, symlink, writeFile } from "node:fs/promises";
8
9
  import { execFile, spawn } from "node:child_process";
9
10
  import { promisify } from "node:util";
10
- import { basename, dirname, join, normalize, resolve, sep } from "node:path";
11
11
  import { request } from "node:http";
12
12
  import { isIP } from "node:net";
13
13
  import z from "@deepseek-ai/schemastery";
@@ -858,7 +858,9 @@ const FULL = {
858
858
  /**
859
859
  * The capability projection per engine. `chrome` / `unknown` → full
860
860
  * capabilities (bit-for-bit today's behavior); `lightpanda` → the analysis
861
- * (docs/plans/2026-10-04-lightpanda-backend-analysis.md §7) projection.
861
+ * (docs/plans/2026-10-04-lightpanda-backend-analysis.md §7) projection;
862
+ * `tabbit` → CLI-protocol limitations (no download events, no overlay pick,
863
+ * no raw CDP screencast through the plugin's usual path).
862
864
  */
863
865
  function capabilitiesFor(engine) {
864
866
  if (engine === "lightpanda") return {
@@ -871,6 +873,16 @@ function capabilitiesFor(engine) {
871
873
  downloadEvents: false,
872
874
  browserClose: false
873
875
  };
876
+ if (engine === "tabbit") return {
877
+ engine: "tabbit",
878
+ screencast: true,
879
+ overlay: false,
880
+ bindingCalled: false,
881
+ imageFormat: "jpeg",
882
+ loadEvent: true,
883
+ downloadEvents: false,
884
+ browserClose: false
885
+ };
874
886
  return {
875
887
  ...FULL,
876
888
  engine
@@ -1221,6 +1233,13 @@ const EGO_CLI_KIND = "ego-cli";
1221
1233
  /** Default panel label for an ego-cli link (no endpoint to fall back to). */
1222
1234
  const EGO_CLI_LABEL = "本机 ego CLI";
1223
1235
  /**
1236
+ * Tabbit CLI backend (P0-3/P0-4, cdp-tabbit-bridge).
1237
+ * Same singleton + never-stop rules as ego-cli: Tabbit owns its browser lifecycle.
1238
+ */
1239
+ const TABBIT_CLI_KIND = "tabbit-cli";
1240
+ /** Default panel label for a tabbit-cli link. */
1241
+ const TABBIT_CLI_LABEL = "Tabbit 浏览器";
1242
+ /**
1224
1243
  * Lightpanda backend — the managed-serve link kind (headless quick-trial
1225
1244
  * engine; headed kinds are the manual-fallback backstop). Local-only
1226
1245
  * singleton, same rules as `ego-cli`.
@@ -1267,6 +1286,15 @@ function coerceLink(raw) {
1267
1286
  servePath
1268
1287
  };
1269
1288
  }
1289
+ if (rec.kind === TABBIT_CLI_KIND) {
1290
+ const cliPath = typeof rec.cliPath === "string" ? rec.cliPath.trim() : "";
1291
+ return {
1292
+ ...base,
1293
+ kind: TABBIT_CLI_KIND,
1294
+ label: label === "" ? TABBIT_CLI_LABEL : label,
1295
+ cliPath
1296
+ };
1297
+ }
1270
1298
  const endpoint = normalizeEndpoint(rec.endpoint);
1271
1299
  if (!endpoint.ok) return null;
1272
1300
  return {
@@ -1289,15 +1317,18 @@ function sanitizeLinks(raw, max = MAX_TARGETS) {
1289
1317
  links: [],
1290
1318
  droppedEgoCli: 0,
1291
1319
  droppedLightpanda: 0,
1320
+ droppedTabbitCli: 0,
1292
1321
  droppedInvalid: 0
1293
1322
  };
1294
1323
  const out = [];
1295
1324
  const seen = /* @__PURE__ */ new Set();
1296
1325
  let droppedEgoCli = 0;
1297
1326
  let droppedLightpanda = 0;
1327
+ let droppedTabbitCli = 0;
1298
1328
  let droppedInvalid = 0;
1299
1329
  let sawEgoCli = false;
1300
1330
  let sawLightpanda = false;
1331
+ let sawTabbitCli = false;
1301
1332
  for (const entry of raw) {
1302
1333
  const link = coerceLink(entry);
1303
1334
  if (!link) {
@@ -1318,6 +1349,13 @@ function sanitizeLinks(raw, max = MAX_TARGETS) {
1318
1349
  }
1319
1350
  sawLightpanda = true;
1320
1351
  }
1352
+ if (link.kind === TABBIT_CLI_KIND) {
1353
+ if (sawTabbitCli) {
1354
+ droppedTabbitCli += 1;
1355
+ continue;
1356
+ }
1357
+ sawTabbitCli = true;
1358
+ }
1321
1359
  if (seen.has(link.id)) link.id = newTargetId();
1322
1360
  seen.add(link.id);
1323
1361
  out.push(link);
@@ -1327,11 +1365,13 @@ function sanitizeLinks(raw, max = MAX_TARGETS) {
1327
1365
  links: out,
1328
1366
  droppedEgoCli,
1329
1367
  droppedLightpanda,
1368
+ droppedTabbitCli,
1330
1369
  droppedInvalid
1331
1370
  };
1332
1371
  }
1333
1372
  function findLink(links, id) {
1334
1373
  if (id === "") return null;
1374
+ if (!Array.isArray(links) || links.length === 0) return null;
1335
1375
  return links.find((link) => link.id === id) ?? null;
1336
1376
  }
1337
1377
  /**
@@ -1346,6 +1386,7 @@ function findLink(links, id) {
1346
1386
  */
1347
1387
  function resolveEffectiveLink(links, activeTargetId) {
1348
1388
  if (activeTargetId === "") return null;
1389
+ if (!Array.isArray(links) || links.length === 0) return null;
1349
1390
  const activated = findLink(links, activeTargetId);
1350
1391
  if (activated && activated.enabled) return {
1351
1392
  link: activated,
@@ -1711,6 +1752,16 @@ async function refreshAttach(input) {
1711
1752
  });
1712
1753
  if (target.kind === EGO_CLI_KIND) return refreshCliAttach(input, cache, suggested, target, now);
1713
1754
  if (target.kind === LP_KIND) return refreshLightpandaAttach(input, cache, suggested, target, now);
1755
+ if (target.kind === TABBIT_CLI_KIND) {
1756
+ cache.patch({
1757
+ ...suggested,
1758
+ targetId: target.id,
1759
+ status: "ready",
1760
+ code: "",
1761
+ message: "tabbit-cli ready"
1762
+ });
1763
+ return cache.get();
1764
+ }
1714
1765
  const sameTarget = previous.targetId === target.id && previous.endpoint === target.endpoint;
1715
1766
  const suggestedProbe = {
1716
1767
  ...suggested,
@@ -1796,11 +1847,31 @@ async function refreshAttach(input) {
1796
1847
  //#region src/cast-server.ts
1797
1848
  const WORKER_BIN = fileURLToPath(new URL("../bin/cdp-cast-worker.mjs", import.meta.url));
1798
1849
  let attachWsUrl = null;
1799
- /** Lightpanda backend — engine of the attached endpoint, published next to it. */
1850
+ /** Engine of the attached endpoint, published next to it. */
1800
1851
  let attachEngine = null;
1801
1852
  /** Logger captured in initCastServer so module-level helpers can report. */
1802
1853
  let castLogger;
1803
1854
  /**
1855
+ * The active ego-cli frame poller, published by initCastServer so the tool-side
1856
+ * doctor can report the current frame source without threading the instance
1857
+ * through every registration. Null when no cast server is wired (headless host).
1858
+ */
1859
+ let activeCliPoller = null;
1860
+ /** Frame-source status for bcdp_doctor: running + the newest frame's age. */
1861
+ function getCliPollStatus() {
1862
+ if (!activeCliPoller || !activeCliPoller.isRunning()) return {
1863
+ running: false,
1864
+ lastFrameAgeMs: null,
1865
+ frameSeq: 0
1866
+ };
1867
+ const f = activeCliPoller.getFrame();
1868
+ return {
1869
+ running: true,
1870
+ lastFrameAgeMs: f ? Math.max(0, Date.now() - f.updatedAt) : null,
1871
+ frameSeq: f ? f.seq : 0
1872
+ };
1873
+ }
1874
+ /**
1804
1875
  * Publish the currently resolved endpoint for the worker. Called by the host
1805
1876
  * half whenever the ACTIVATED target changes (new target, new endpoint, or
1806
1877
  * mode switching away from remote). Returns true when the value actually
@@ -1862,6 +1933,9 @@ const EGO_WATCH_STOP_ROUTE = "/api/bcdp/watch/stop";
1862
1933
  const EGO_WATCH_STATUS_ROUTE = "/api/bcdp/watch/status";
1863
1934
  const EGO_VIDEO_ROUTE = "/api/bcdp/video";
1864
1935
  const EGO_VIDEO_STATUS_ROUTE = "/api/bcdp/video/status";
1936
+ const EGO_CLI_FRAME_ROUTE = "/api/bcdp/cli-frame";
1937
+ /** Synthetic target id the panel shows for the single CLI fallback frame. */
1938
+ const CLI_FRAME_TARGET_ID = "__cli_frame__";
1865
1939
  let toolCallCount = 0;
1866
1940
  const sseClients = /* @__PURE__ */ new Set();
1867
1941
  /** Timestamp of the last bcdp_* tool call — the idle reaper's activity signal. */
@@ -1897,6 +1971,42 @@ function markEgoToolCall(sessionId) {
1897
1971
  sseClients.delete(res);
1898
1972
  }
1899
1973
  }
1974
+ /**
1975
+ * Push one CLI-captured frame into the live watch-panel stream. In the degraded
1976
+ * ego-cli mode there is no screencast worker to emit `spaces`/`frame` events, so
1977
+ * the poller is their only source: we broadcast a synthetic single-space `spaces`
1978
+ * event (tab bar + active page) followed by a `frame` event (the image) to every
1979
+ * connected client. The client's existing SSE handlers render both, so the panel
1980
+ * updates the instant a frame lands — no client polling, no chicken/egg.
1981
+ *
1982
+ * `fmt` names the image encoding: the client builds `data:image/<fmt>;base64,…`,
1983
+ * so a JPEG frame MUST say `jpeg` or the panel renders garbage. Default `png`
1984
+ * keeps the ego-cli poller (which captures PNG) unchanged.
1985
+ */
1986
+ function broadcastCliFrame(frame) {
1987
+ if (sseClients.size === 0) return;
1988
+ const synthetic = [{
1989
+ targetId: CLI_FRAME_TARGET_ID,
1990
+ url: frame.url,
1991
+ title: frame.title,
1992
+ active: true,
1993
+ lastActive: frame.updatedAt
1994
+ }];
1995
+ const spacesFrame = `event: spaces\ndata: ${JSON.stringify(synthetic)}\n\n`;
1996
+ const framePayload = {
1997
+ targetId: CLI_FRAME_TARGET_ID,
1998
+ data: frame.png.toString("base64"),
1999
+ fmt: frame.fmt ?? "png",
2000
+ ts: frame.updatedAt
2001
+ };
2002
+ const frameEvent = `event: frame\ndata: ${JSON.stringify(framePayload)}\n\n`;
2003
+ for (const res of sseClients) try {
2004
+ res.write(spacesFrame);
2005
+ res.write(frameEvent);
2006
+ } catch {
2007
+ sseClients.delete(res);
2008
+ }
2009
+ }
1900
2010
  function castStatePath() {
1901
2011
  const e = process.env;
1902
2012
  const isWin = process.platform === "win32";
@@ -2269,9 +2379,10 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
2269
2379
  }), loginImport = async () => ({
2270
2380
  ok: false,
2271
2381
  error: "login import not supported by this host build"
2272
- })) {
2382
+ }), cliPoller = null) {
2273
2383
  const ensureWorker = makeEnsureWorker(ctx, cfg, ffmpegManager);
2274
2384
  const pushConfig = makePushConfig(ensureWorker, ffmpegManager);
2385
+ activeCliPoller = cliPoller;
2275
2386
  const rawServer = ctx.get?.("webServer");
2276
2387
  if (!rawServer || typeof rawServer.register !== "function") return;
2277
2388
  const isTrustedRequest = (req) => /(?:^|;\s*)dsh-auth-[^=]+=/.test(String(req.headers.cookie ?? ""));
@@ -2306,12 +2417,28 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
2306
2417
  handler: async (_req, resRaw) => {
2307
2418
  const res = resRaw;
2308
2419
  const port = await ensureWorker();
2309
- if (port === null) return sendJson(res, 200, {
2310
- ok: false,
2311
- spaces: [],
2312
- toolCallCount,
2313
- reason: "no live agent browser"
2314
- });
2420
+ if (port === null) {
2421
+ const cliFrame = cliPoller && cliPoller.isRunning() ? cliPoller.getFrame() : null;
2422
+ if (cliFrame) return sendJson(res, 200, {
2423
+ ok: true,
2424
+ toolCallCount,
2425
+ cliFrameMode: true,
2426
+ cliFrameIntervalMs: 3e3,
2427
+ spaces: [{
2428
+ targetId: CLI_FRAME_TARGET_ID,
2429
+ url: cliFrame.url,
2430
+ title: cliFrame.title,
2431
+ active: true,
2432
+ lastActive: cliFrame.updatedAt
2433
+ }]
2434
+ });
2435
+ return sendJson(res, 200, {
2436
+ ok: false,
2437
+ spaces: [],
2438
+ toolCallCount,
2439
+ reason: "no live agent browser"
2440
+ });
2441
+ }
2315
2442
  const data = await proxyFrom(port, "/api/spaces");
2316
2443
  if (!data) return sendJson(res, 200, {
2317
2444
  ok: false,
@@ -2338,6 +2465,26 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
2338
2465
  proxyWorkerStream(port, res, "/api/stream");
2339
2466
  }
2340
2467
  });
2468
+ const disposeCliFrame = server.register({
2469
+ kind: "exact",
2470
+ path: EGO_CLI_FRAME_ROUTE,
2471
+ handler: async (_req, resRaw) => {
2472
+ const res = resRaw;
2473
+ const frame = cliPoller && cliPoller.isRunning() ? cliPoller.getFrame() : null;
2474
+ if (!frame) {
2475
+ res.statusCode = 204;
2476
+ res.end();
2477
+ return;
2478
+ }
2479
+ res.writeHead(200, {
2480
+ "content-type": "image/png",
2481
+ "content-length": frame.png.length,
2482
+ "cache-control": "no-store",
2483
+ "x-cli-frame-seq": String(frame.seq)
2484
+ });
2485
+ res.end(frame.png);
2486
+ }
2487
+ });
2341
2488
  const disposeInput = server.register({
2342
2489
  kind: "exact",
2343
2490
  path: EGO_INPUT_ROUTE,
@@ -2589,6 +2736,9 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
2589
2736
  try {
2590
2737
  disposeStream();
2591
2738
  } catch {}
2739
+ try {
2740
+ disposeCliFrame();
2741
+ } catch {}
2592
2742
  try {
2593
2743
  disposeInput();
2594
2744
  } catch {}
@@ -2631,6 +2781,135 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
2631
2781
  });
2632
2782
  }
2633
2783
 
2784
+ //#endregion
2785
+ //#region src/cast/cli-frame-poller.ts
2786
+ /**
2787
+ * src/cast/cli-frame-poller.ts — degraded observation frame source for the
2788
+ * `ego-cli` link kind.
2789
+ *
2790
+ * When the activated link is a local ego CLI, no CDP ws is injected, so the
2791
+ * screencast worker cannot attach and the watch panel would show nothing. This
2792
+ * poller is the fallback: every `intervalMs` it runs a short heredoc through
2793
+ * the SAME CLI channel real tools use (`ego-browser nodejs`), captures one
2794
+ * viewport PNG, and keeps the newest frame in memory for the host route to
2795
+ * serve. One frame in, one frame out — no streaming, no SSE image mirror.
2796
+ *
2797
+ * Design constraints (from the approved plan):
2798
+ * - It is a fire-and-forget short subprocess, NOT a long-lived process, so it
2799
+ * lives in the host half (cast-server), not inside cdp-cast-worker.
2800
+ * - It never contends with a real tool call: when `isBusy()` is true (a bcdp_*
2801
+ * call holds the plugin lock) the tick is skipped, and the previous frame
2802
+ * stays served. Frame freshness is subordinate to correctness of actions.
2803
+ * - Capture failures are silent by design: a wedged space / no active tab /
2804
+ * transient cold start must not blank the panel — the last good frame is the
2805
+ * honest degraded state, and the next tick retries.
2806
+ * - `capture` is injected (returns the CLI's merged stdout), so this module
2807
+ * imports nothing from index.ts and never touches ctx.subprocess directly.
2808
+ */
2809
+ /** Sentinel the frame heredoc prints; carries base64 PNG + url + title. */
2810
+ const FRAME_SENTINEL = "@@BCDP_FRAME@@";
2811
+ /**
2812
+ * Parse one capture's merged stdout for the frame sentinel line. Returns the
2813
+ * decoded frame, or null when the sentinel is absent or its payload malformed
2814
+ * (a CLI that errored before reaching the log line, a truncated base64, etc.).
2815
+ * Scans last-to-first so trailing log noise cannot displace the payload, and so
2816
+ * the behaviour matches the tool-side `parseSentinel` convention.
2817
+ * @internal exported for tests
2818
+ */
2819
+ function parseFrameSentinel(stdout, seq, at) {
2820
+ const lines = stdout.split("\n");
2821
+ for (let i = lines.length - 1; i >= 0; i--) {
2822
+ const line = lines[i];
2823
+ const idx = line.indexOf(FRAME_SENTINEL);
2824
+ if (idx === -1) continue;
2825
+ const payload = line.slice(idx + 14).trim();
2826
+ if (payload === "") continue;
2827
+ let parsed;
2828
+ try {
2829
+ parsed = JSON.parse(payload);
2830
+ } catch {
2831
+ return null;
2832
+ }
2833
+ if (typeof parsed.png !== "string" || parsed.png === "") return null;
2834
+ let png;
2835
+ try {
2836
+ png = Buffer.from(parsed.png, "base64");
2837
+ } catch {
2838
+ return null;
2839
+ }
2840
+ if (png.length === 0) return null;
2841
+ return {
2842
+ png,
2843
+ url: typeof parsed.url === "string" ? parsed.url : "",
2844
+ title: typeof parsed.title === "string" ? parsed.title : "",
2845
+ seq,
2846
+ updatedAt: at
2847
+ };
2848
+ }
2849
+ return null;
2850
+ }
2851
+ var CliFramePoller = class {
2852
+ opts;
2853
+ timer = null;
2854
+ latest = null;
2855
+ seq = 0;
2856
+ /** Guard against overlapping ticks (a capture slower than the interval). */
2857
+ inFlight = false;
2858
+ constructor(opts) {
2859
+ this.opts = opts;
2860
+ }
2861
+ /** Start polling. Idempotent: a second call while running is a no-op. */
2862
+ start() {
2863
+ if (this.timer !== null) return;
2864
+ this.timer = setInterval(() => {
2865
+ this.tick();
2866
+ }, this.opts.intervalMs);
2867
+ this.timer.unref?.();
2868
+ this.tick();
2869
+ }
2870
+ /** Stop polling and drop the cached frame (the panel reverts to its placeholder). */
2871
+ stop() {
2872
+ if (this.timer !== null) {
2873
+ clearInterval(this.timer);
2874
+ this.timer = null;
2875
+ }
2876
+ this.latest = null;
2877
+ }
2878
+ isRunning() {
2879
+ return this.timer !== null;
2880
+ }
2881
+ /** The newest captured frame, or null when there is none yet. */
2882
+ getFrame() {
2883
+ return this.latest;
2884
+ }
2885
+ async tick() {
2886
+ if (this.inFlight) return;
2887
+ if (this.opts.isBusy && this.opts.isBusy()) return;
2888
+ this.inFlight = true;
2889
+ try {
2890
+ const frame = parseFrameSentinel(await this.opts.capture(), ++this.seq, (this.opts.now ?? Date.now)());
2891
+ if (frame !== null) {
2892
+ this.latest = frame;
2893
+ if (this.opts.onFrame) try {
2894
+ this.opts.onFrame(frame);
2895
+ } catch {}
2896
+ }
2897
+ } catch {} finally {
2898
+ this.inFlight = false;
2899
+ }
2900
+ }
2901
+ };
2902
+ /**
2903
+ * The capture heredoc. Uses the runtime's own facades (taskSpaces + page) so it
2904
+ * rides the exact channel real tools use; deliberately does NOT call
2905
+ * ensureRealTab / switchTab — a passive observer must not move the active tab.
2906
+ * `page.screenshot()` in this runtime returns a saved PNG path, so we read the
2907
+ * file back into base64 and clean it up.
2908
+ */
2909
+ function buildFrameScript(spaceJson) {
2910
+ return `const task = await taskSpaces.useOrCreate(${spaceJson})\nlet __info = {}\ntry { __info = await page.info() } catch { __info = {} }\nconst __p = await page.screenshot({ fullPage: false })\nconst __fs = await import('node:fs/promises')\nconst __png = (await __fs.readFile(__p)).toString('base64')\ntry { await __fs.unlink(__p) } catch {}\nconsole.log(${JSON.stringify(FRAME_SENTINEL)} + JSON.stringify({ png: __png, url: __info.url || '', title: __info.title || '' }))\n`;
2911
+ }
2912
+
2634
2913
  //#endregion
2635
2914
  //#region src/config.ts
2636
2915
  const backend = z.union([
@@ -2700,6 +2979,7 @@ const Config$1 = z.object({
2700
2979
  probeEngine: z.union([
2701
2980
  "chrome",
2702
2981
  "lightpanda",
2982
+ "tabbit",
2703
2983
  "unknown"
2704
2984
  ])
2705
2985
  }),
@@ -2723,6 +3003,7 @@ const Config$1 = z.object({
2723
3003
  probeEngine: z.union([
2724
3004
  "chrome",
2725
3005
  "lightpanda",
3006
+ "tabbit",
2726
3007
  "unknown"
2727
3008
  ])
2728
3009
  }),
@@ -2745,6 +3026,7 @@ const Config$1 = z.object({
2745
3026
  probeEngine: z.union([
2746
3027
  "chrome",
2747
3028
  "lightpanda",
3029
+ "tabbit",
2748
3030
  "unknown"
2749
3031
  ])
2750
3032
  })
@@ -2765,6 +3047,7 @@ const Config$1 = z.object({
2765
3047
  localHeadless: z.boolean().description("Run the locally launched browser headless."),
2766
3048
  remoteEnabled: z.boolean().description("Master switch for REMOTE attach. Off = the configured target sequence is preserved but inert (nothing probes or connects remotely); flip back on any time. Does not affect cdpMode=local.").volatile(),
2767
3049
  allowProbeColdStart: z.boolean().description("Allow the ego-cli readiness probe to cold-start the backing browser. Off (default): the probe never launches the browser — when --status cannot prove the browser is already up, the heredoc round-trip is skipped and the browser starts on the first real bcdp_* call instead (no browser window at plugin startup). On: the probe verifies the SDK harness up front, which may launch the browser.").volatile(),
3050
+ cliFramePollEnabled: z.boolean().default(true).description("Degraded watch-panel frame source for the local ego-cli link: with no CDP screencast available, capture one viewport screenshot every 5s through the CLI channel and serve it to the panel. On (default): the poller runs while an ego-cli link owns routing. Off: the panel keeps its placeholder and no screenshot subprocess is spawned. Hot-applies without reloading the plugin.").volatile(),
2768
3051
  localUserDataDir: z.string().description("Profile dir for the locally launched browser. Empty = managed dir; never point at your daily Chrome profile."),
2769
3052
  lightpandaArgs: z.string().description("Extra args appended to a managed `lightpanda serve` argv. --host/--port are managed and cannot be overridden.").volatile(),
2770
3053
  castFpsCap: z.number().min(0).max(60).step(1),
@@ -3037,6 +3320,7 @@ function resolveConfig(config = {}) {
3037
3320
  lightpandaArgs: trimmed(config.lightpandaArgs),
3038
3321
  remoteEnabled: config.remoteEnabled === void 0 ? true : Boolean(config.remoteEnabled),
3039
3322
  allowProbeColdStart: config.allowProbeColdStart === true || config.allowProbeColdStart === "true",
3323
+ cliFramePollEnabled: config.cliFramePollEnabled !== false && config.cliFramePollEnabled !== "false",
3040
3324
  jevUrl: trimmed(config.jevUrl),
3041
3325
  jevKey: trimmed(config.jevKey),
3042
3326
  jevModel: trimmed(config.jevModel) === "" ? "jev" : trimmed(config.jevModel),
@@ -3066,7 +3350,7 @@ function normalizeProbeState(link) {
3066
3350
  probeError: typeof link.probeError === "string" ? link.probeError : "",
3067
3351
  probeCode: typeof link.probeCode === "string" ? link.probeCode : "",
3068
3352
  probeAt: typeof link.probeAt === "number" && Number.isFinite(link.probeAt) ? link.probeAt : 0,
3069
- probeEngine: link.probeEngine === "chrome" || link.probeEngine === "lightpanda" ? link.probeEngine : "unknown"
3353
+ probeEngine: link.probeEngine === "chrome" || link.probeEngine === "lightpanda" || link.probeEngine === "tabbit" ? link.probeEngine : "unknown"
3070
3354
  };
3071
3355
  }
3072
3356
 
@@ -4529,6 +4813,417 @@ function readAll(reader) {
4529
4813
  return reader.readFrom(0).text;
4530
4814
  }
4531
4815
 
4816
+ //#endregion
4817
+ //#region src/cdp/tabbit-cli-link.ts
4818
+ /**
4819
+ * Three-tier detection for tabbit-cli:
4820
+ * 1. Explicit cfg.cliPath (from link row)
4821
+ * 2. Windows LOCALAPPDATA standard install path
4822
+ * 3. POSIX ~/.local/bin or PATH
4823
+ */
4824
+ function resolveTabbitCli(cliPath) {
4825
+ if (cliPath && cliPath.trim() !== "") {
4826
+ const p = cliPath.trim();
4827
+ if (existsSync(p)) return {
4828
+ found: true,
4829
+ cliPath: p
4830
+ };
4831
+ return {
4832
+ found: false,
4833
+ cliPath: p,
4834
+ error: `explicit path not found: ${p}`
4835
+ };
4836
+ }
4837
+ const e = process.env;
4838
+ const isWin = process.platform === "win32";
4839
+ if (isWin) {
4840
+ const localAppData = e.LOCALAPPDATA || "";
4841
+ const candidates = [join(localAppData, "Tabbit", "LocalAgent", "bin", "tabbit-cli.exe"), join(localAppData, "Tabbit", "LocalAgent", "bin", "tabbit-cli")];
4842
+ for (const c of candidates) if (existsSync(c)) return {
4843
+ found: true,
4844
+ cliPath: c
4845
+ };
4846
+ } else {
4847
+ const posixCandidates = [join(e.HOME || e.USERPROFILE || "", ".local", "bin", "tabbit-cli"), "/usr/local/bin/tabbit-cli"];
4848
+ for (const c of posixCandidates) if (existsSync(c)) return {
4849
+ found: true,
4850
+ cliPath: c
4851
+ };
4852
+ }
4853
+ return {
4854
+ found: false,
4855
+ cliPath: "",
4856
+ error: isWin ? `tabbit-cli.exe not found at %LOCALAPPDATA%\\Tabbit\\LocalAgent\\bin\\` : "tabbit-cli not found in ~/.local/bin or /usr/local/bin"
4857
+ };
4858
+ }
4859
+ /**
4860
+ * Parse stdout from `tabbit-cli nodejs` — expects a single JSON object
4861
+ * matching the receipt schema from SKILL.md.
4862
+ * Pure JSON.parse, no sentinel needed.
4863
+ */
4864
+ function parseTabbitReceipt(stdout) {
4865
+ const trimmed$1 = stdout.trim();
4866
+ if (trimmed$1 === "") return {
4867
+ ok: false,
4868
+ status: "failed",
4869
+ error: {
4870
+ code: "EMPTY_OUTPUT",
4871
+ message: "tabbit-cli produced no stdout"
4872
+ }
4873
+ };
4874
+ let parsed;
4875
+ try {
4876
+ parsed = JSON.parse(trimmed$1);
4877
+ } catch {
4878
+ const lines = trimmed$1.split("\n");
4879
+ for (let i = lines.length - 1; i >= 0; i--) try {
4880
+ parsed = JSON.parse(lines[i]);
4881
+ break;
4882
+ } catch {}
4883
+ if (!parsed) return {
4884
+ ok: false,
4885
+ status: "failed",
4886
+ error: {
4887
+ code: "PARSE_ERROR",
4888
+ message: `cannot parse tabbit receipt: ${trimmed$1.slice(0, 200)}`
4889
+ }
4890
+ };
4891
+ }
4892
+ const obj = parsed;
4893
+ const status = String(obj.status ?? "failed");
4894
+ const requestId = typeof obj.requestId === "string" ? obj.requestId : typeof obj.result?.requestId === "string" ? obj.result.requestId : void 0;
4895
+ const acqTabs = obj.result?.acquisition?.tabIds;
4896
+ const tabIds = Array.isArray(acqTabs) ? acqTabs.filter((n) => typeof n === "number") : void 0;
4897
+ const tabField = tabIds && tabIds.length > 0 ? { tabIds } : {};
4898
+ if (status === "succeeded") {
4899
+ const result = obj.result;
4900
+ return {
4901
+ ok: true,
4902
+ status,
4903
+ data: result?.value ?? result ?? obj,
4904
+ requestId,
4905
+ ...tabField
4906
+ };
4907
+ }
4908
+ if (status === "queued" || status === "running") return {
4909
+ ok: false,
4910
+ status,
4911
+ requestId,
4912
+ ...tabField
4913
+ };
4914
+ const errMsg = typeof obj.error === "string" ? obj.error : typeof obj.result?.error === "string" ? obj.result.error : typeof obj.message === "string" ? obj.message : "unknown error";
4915
+ return {
4916
+ ok: false,
4917
+ status,
4918
+ error: {
4919
+ code: typeof obj.code === "string" ? obj.code : /timeout/i.test(errMsg) ? "TIMEOUT" : /not attached|not found|no element/i.test(errMsg) ? "ELEMENT_NOT_FOUND" : /ERR_|net::|navigation/i.test(errMsg) ? "NAVIGATION_FAILED" : "EXECUTION_FAILED",
4920
+ message: errMsg
4921
+ },
4922
+ requestId,
4923
+ ...tabField
4924
+ };
4925
+ }
4926
+ /**
4927
+ * `--timeout-ms` accepted range, straight from the CLI's own rejection message:
4928
+ *
4929
+ * "--timeout-ms must be from 60000 through 180000; the default is 60000, so
4930
+ * omit it unless the program needs longer"
4931
+ *
4932
+ * Anything shorter makes the CLI refuse the whole request with REQUEST_FAILED
4933
+ * and never run the snippet. This is a hard contract, so it is enforced here
4934
+ * once instead of at every call site — the 3 s frame poller used to pass 10 s /
4935
+ * 15 s and therefore NEVER captured a frame, which is invisible because the
4936
+ * rejection surfaces as an ordinary "failed" receipt rather than an exception.
4937
+ */
4938
+ const TABBIT_MIN_TIMEOUT_MS = 6e4;
4939
+ const TABBIT_MAX_TIMEOUT_MS = 18e4;
4940
+ /**
4941
+ * Execute a Playwright JS snippet via tabbit-cli nodejs.
4942
+ * Writes JS code to stdin, collects stdout JSON receipt.
4943
+ */
4944
+ async function runTabbitSnippet(subprocess, jsCode, opts) {
4945
+ const args = [
4946
+ "nodejs",
4947
+ "--task",
4948
+ opts.taskName,
4949
+ "--request-id",
4950
+ opts.requestId
4951
+ ];
4952
+ const timeout = opts.timeoutMs === void 0 ? void 0 : Math.min(TABBIT_MAX_TIMEOUT_MS, Math.max(TABBIT_MIN_TIMEOUT_MS, opts.timeoutMs));
4953
+ if (timeout !== void 0) args.push("--timeout-ms", String(timeout));
4954
+ if (opts.tabId !== void 0) args.push("--tab", String(opts.tabId));
4955
+ if (opts.groupId !== void 0) args.push("--group", String(opts.groupId));
4956
+ const handle = subprocess.spawn({
4957
+ argv: [opts.cliPath, ...args],
4958
+ cwd: process.cwd(),
4959
+ env: { ...process.env },
4960
+ stdio: {
4961
+ stdin: { data: jsCode },
4962
+ stdout: { maxBytes: 4 * 1024 * 1024 },
4963
+ stderr: { maxBytes: 64 * 1024 }
4964
+ },
4965
+ graceMs: (timeout ?? TABBIT_MIN_TIMEOUT_MS) + 15e3
4966
+ });
4967
+ const { exitCode } = await handle.done;
4968
+ return {
4969
+ receipt: parseTabbitReceipt(readAll(handle.collected.stdout)),
4970
+ exitCode: exitCode ?? 1
4971
+ };
4972
+ }
4973
+ /**
4974
+ * Poll a pending receipt (queued/running) up to maxWait ms.
4975
+ * Returns the final receipt or a timeout error.
4976
+ */
4977
+ async function pollTabbitPending(subprocess, opts) {
4978
+ const maxWait = opts.maxWaitMs ?? 6e4;
4979
+ const pollInterval = 5e3;
4980
+ const start = Date.now();
4981
+ while (Date.now() - start < maxWait) {
4982
+ const args = [
4983
+ "receipt",
4984
+ "--task",
4985
+ opts.taskName,
4986
+ "--request-id",
4987
+ opts.requestId,
4988
+ "--wait-ms",
4989
+ String(pollInterval)
4990
+ ];
4991
+ const handle = subprocess.spawn({
4992
+ argv: [opts.cliPath, ...args],
4993
+ cwd: process.cwd(),
4994
+ env: { ...process.env },
4995
+ stdio: {
4996
+ stdin: { data: "" },
4997
+ stdout: { maxBytes: 4 * 1024 * 1024 },
4998
+ stderr: { maxBytes: 64 * 1024 }
4999
+ },
5000
+ graceMs: pollInterval + 1e4
5001
+ });
5002
+ await handle.done;
5003
+ const receipt = parseTabbitReceipt(readAll(handle.collected.stdout));
5004
+ if (receipt.status !== "queued" && receipt.status !== "running") return receipt;
5005
+ }
5006
+ return {
5007
+ ok: false,
5008
+ status: "interrupted",
5009
+ error: {
5010
+ code: "POLL_TIMEOUT",
5011
+ message: `receipt still pending after ${maxWait}ms`
5012
+ }
5013
+ };
5014
+ }
5015
+ /** Create a task (档位 A: returns inventory without acquiring) */
5016
+ async function tabbitCreateTask(subprocess, cliPath, taskName) {
5017
+ const handle = subprocess.spawn({
5018
+ argv: [
5019
+ cliPath,
5020
+ "create",
5021
+ "--task",
5022
+ taskName
5023
+ ],
5024
+ cwd: process.cwd(),
5025
+ env: { ...process.env },
5026
+ stdio: {
5027
+ stdin: { data: "" },
5028
+ stdout: { maxBytes: 1024 * 1024 },
5029
+ stderr: { maxBytes: 64 * 1024 }
5030
+ },
5031
+ graceMs: 1e4
5032
+ });
5033
+ await handle.done;
5034
+ const stdout = readAll(handle.collected.stdout);
5035
+ try {
5036
+ const parsed = JSON.parse(stdout.trim());
5037
+ return {
5038
+ tabs: Array.isArray(parsed.tabs) ? parsed.tabs : [],
5039
+ currentTabId: typeof parsed.currentTabId === "number" ? parsed.currentTabId : null,
5040
+ total: typeof parsed.total === "number" ? parsed.total : 0,
5041
+ complete: parsed.complete === true
5042
+ };
5043
+ } catch {
5044
+ return {
5045
+ tabs: [],
5046
+ currentTabId: null,
5047
+ total: 0,
5048
+ complete: false
5049
+ };
5050
+ }
5051
+ }
5052
+ /** Finish a task (retain tabs by default) */
5053
+ async function tabbitFinishTask(subprocess, cliPath, taskName, discard = false) {
5054
+ const args = [
5055
+ "finish",
5056
+ "--task",
5057
+ taskName
5058
+ ];
5059
+ if (discard) args.push("--discard");
5060
+ await subprocess.spawn({
5061
+ argv: [cliPath, ...args],
5062
+ cwd: process.cwd(),
5063
+ env: { ...process.env },
5064
+ stdio: {
5065
+ stdin: { data: "" },
5066
+ stdout: { maxBytes: 64 * 1024 },
5067
+ stderr: { maxBytes: 64 * 1024 }
5068
+ },
5069
+ graceMs: 1e4
5070
+ }).done;
5071
+ return { released: true };
5072
+ }
5073
+ /** List tabs with optional state filter */
5074
+ async function tabbitListTabs(subprocess, cliPath, taskName, stateFilter) {
5075
+ const args = [
5076
+ "tabs",
5077
+ "--task",
5078
+ taskName
5079
+ ];
5080
+ if (stateFilter) args.push("--state", stateFilter);
5081
+ const handle = subprocess.spawn({
5082
+ argv: [cliPath, ...args],
5083
+ cwd: process.cwd(),
5084
+ env: { ...process.env },
5085
+ stdio: {
5086
+ stdin: { data: "" },
5087
+ stdout: { maxBytes: 1024 * 1024 },
5088
+ stderr: { maxBytes: 64 * 1024 }
5089
+ },
5090
+ graceMs: 1e4
5091
+ });
5092
+ await handle.done;
5093
+ const stdout = readAll(handle.collected.stdout);
5094
+ try {
5095
+ const parsed = JSON.parse(stdout.trim());
5096
+ return {
5097
+ tabs: Array.isArray(parsed.tabs) ? parsed.tabs : [],
5098
+ total: typeof parsed.total === "number" ? parsed.total : 0,
5099
+ complete: parsed.complete === true
5100
+ };
5101
+ } catch {
5102
+ return {
5103
+ tabs: [],
5104
+ total: 0,
5105
+ complete: false
5106
+ };
5107
+ }
5108
+ }
5109
+ /** Diagnose: check if tabbit-cli can reach the browser (short timeout, no launch). */
5110
+ async function tabbitDiagnose(subprocess, cliPath) {
5111
+ const handle = subprocess.spawn({
5112
+ argv: [cliPath, "diagnose"],
5113
+ cwd: process.cwd(),
5114
+ env: { ...process.env },
5115
+ stdio: {
5116
+ stdin: { data: "" },
5117
+ stdout: { maxBytes: 128 * 1024 },
5118
+ stderr: { maxBytes: 128 * 1024 }
5119
+ },
5120
+ graceMs: 2e4
5121
+ });
5122
+ const { exitCode } = await handle.done;
5123
+ const stdout = readAll(handle.collected.stdout);
5124
+ return {
5125
+ reachable: (exitCode ?? 1) === 0,
5126
+ raw: stdout
5127
+ };
5128
+ }
5129
+ function buildNavigateSnippet(url, waitUntil) {
5130
+ return `await page.goto(${JSON.stringify(url)}, {waitUntil: ${JSON.stringify(waitUntil)}}); return {url: page.url(), title: await page.title()};`;
5131
+ }
5132
+ function buildObserveSnippet(maxChars) {
5133
+ return `return await tabbit.observe({frames: "none", maxChars: ${maxChars}});`;
5134
+ }
5135
+ function buildClickSnippet(locatorExpr) {
5136
+ return `await ${locatorExpr}.click(); return {clicked: true};`;
5137
+ }
5138
+ function buildFillSnippet(locatorExpr, value) {
5139
+ return `await ${locatorExpr}.fill(${JSON.stringify(value)}); return {filled: true};`;
5140
+ }
5141
+ /**
5142
+ * In-snippet capture deadline (ms).
5143
+ *
5144
+ * `Page.captureScreenshot` is NOT reliably fast in this runtime: the same tab
5145
+ * that answers in 132 ms can also never answer at all, and an unanswered send
5146
+ * blocks the whole evaluation until the CLI's hard deadline, which takes the
5147
+ * executor down and kills every other call in that task. A short `Promise.race`
5148
+ * inside the snippet keeps a stuck capture from becoming a stuck task.
5149
+ */
5150
+ const TABBIT_CAPTURE_DEADLINE_MS = 8e3;
5151
+ /** The race-guarded capture expression shared by both snippet builders. */
5152
+ function captureWithDeadline(format, quality, deadlineMs) {
5153
+ return [
5154
+ `const c = await context.newCDPSession(page);`,
5155
+ `let r = null, capErr = null;`,
5156
+ `try {`,
5157
+ ` r = await Promise.race([`,
5158
+ ` c.send("Page.captureScreenshot", ${`{format: "${format}"${quality === void 0 ? "" : `, quality: ${quality}`}, fromSurface: true}`}),`,
5159
+ ` new Promise((_, reject) => setTimeout(() => reject(new Error("capture-deadline")), ${deadlineMs})),`,
5160
+ ` ]);`,
5161
+ `} catch (e) { capErr = String((e && e.message) || e); }`,
5162
+ `try { await c.detach(); } catch {}`,
5163
+ `if (capErr !== null || !r) return {skipped: "capture-timeout", error: capErr, url: page.url()};`
5164
+ ];
5165
+ }
5166
+ function buildScreenshotSnippet(outPath, deadlineMs = TABBIT_CAPTURE_DEADLINE_MS) {
5167
+ const p = JSON.stringify(outPath);
5168
+ return [
5169
+ ...captureWithDeadline("png", void 0, deadlineMs),
5170
+ `const buf = Buffer.from(r.data, "base64");`,
5171
+ `const fs = await import("node:fs");`,
5172
+ `fs.writeFileSync(${p}, buf);`,
5173
+ `return {path: ${p}, bytes: buf.length, url: page.url(), title: await page.title()};`
5174
+ ].join("\n");
5175
+ }
5176
+ /** JPEG quality for the live watch-panel frame stream. */
5177
+ const TABBIT_FRAME_JPEG_QUALITY = 50;
5178
+ /**
5179
+ * Build the live watch-panel frame-capture snippet.
5180
+ *
5181
+ * The bytes go to `outPath` INSIDE the CLI process and only the path travels
5182
+ * back in the receipt, for the same resource-demotion reason as
5183
+ * `buildScreenshotSnippet`. The old snippet returned the raw base64, which over
5184
+ * threshold became a `resource`; the poller then found no `receipt.data.base64`,
5185
+ * broadcast nothing, and — because the receipt still said `succeeded` — logged
5186
+ * nothing either. That is exactly how the panel stayed empty while every tool
5187
+ * call reported success.
5188
+ *
5189
+ * JPEG (not PNG) because the panel refreshes on a 3 s cadence: a PNG of a heavy
5190
+ * page takes ~2.6 s to encode, JPEG/q50 a fraction of that and ~3× smaller over
5191
+ * SSE.
5192
+ *
5193
+ * A blank page is skipped instead of captured: `about:blank` hangs the CLI until
5194
+ * its hard deadline (observed: 60 s EVALUATION_TIMEOUT), and a blank frame tells
5195
+ * the panel nothing anyway.
5196
+ */
5197
+ function buildFrameCaptureSnippet(outPath, quality = TABBIT_FRAME_JPEG_QUALITY, deadlineMs = TABBIT_CAPTURE_DEADLINE_MS) {
5198
+ const p = JSON.stringify(outPath);
5199
+ return [
5200
+ `const url = page.url();`,
5201
+ `if (!url || url === "about:blank") return {skipped: "blank", url: url || ""};`,
5202
+ ...captureWithDeadline("jpeg", quality, deadlineMs),
5203
+ `const buf = Buffer.from(r.data, "base64");`,
5204
+ `const fs = await import("node:fs");`,
5205
+ `fs.writeFileSync(${p}, buf);`,
5206
+ `return {path: ${p}, url, title: await page.title(), bytes: buf.length};`
5207
+ ].join("\n");
5208
+ }
5209
+ /**
5210
+ * Translate a bcdp_* locator/ref format into a Playwright locator expression.
5211
+ * - `loc=role:button[name="Save"]` → `page.getByRole("button", {name: "Save", exact: true})`
5212
+ * - `loc=css:.btn-submit` → `page.locator(".btn-submit")`
5213
+ * - `@N` → `page.locator('[data-ref="N"]')` (best-effort, may not work on Tabbit)
5214
+ */
5215
+ function translateLocator(selector) {
5216
+ if (!selector) return null;
5217
+ const roleMatch = selector.match(/^loc=role:(\w+)\[name="(.+?)"\]$/);
5218
+ if (roleMatch) return `page.getByRole(${JSON.stringify(roleMatch[1])}, {name: ${JSON.stringify(roleMatch[2])}, exact: true})`;
5219
+ const cssMatch = selector.match(/^loc=css:(.+)$/);
5220
+ if (cssMatch) return `page.locator(${JSON.stringify(cssMatch[1])})`;
5221
+ const hrefMatch = selector.match(/^loc=href:(.+)$/);
5222
+ if (hrefMatch) return `page.locator(${JSON.stringify(`a[href="${hrefMatch[1]}"]`)})`;
5223
+ if (!selector.startsWith("@") && !selector.startsWith("loc=")) return `page.locator(${JSON.stringify(selector)})`;
5224
+ return null;
5225
+ }
5226
+
4532
5227
  //#endregion
4533
5228
  //#region src/jev/wire.ts
4534
5229
  const noul = (instructions, criteria) => criteria === void 0 ? {
@@ -7269,10 +7964,21 @@ function createSessionSpaceTracker(defaultNameFor = () => DEFAULT_SPACE) {
7269
7964
  const slots = /* @__PURE__ */ new Map();
7270
7965
  let sessionKey = GLOBAL_SESSION_KEY;
7271
7966
  let session;
7967
+ let linkScope = "";
7968
+ let lastRealKey = null;
7969
+ /**
7970
+ * Compose the full slot key. When linkScope is '' (legacy / single-backend),
7971
+ * the key equals sessionKey so all pre-existing behaviour is preserved.
7972
+ */
7973
+ const composeKey = () => linkScope ? `${sessionKey}\x00${linkScope}` : sessionKey;
7974
+ const noteReal = () => {
7975
+ if (sessionKey !== GLOBAL_SESSION_KEY) lastRealKey = composeKey();
7976
+ };
7272
7977
  const slotOf = (key) => {
7273
7978
  let s = slots.get(key);
7274
7979
  if (!s) {
7275
- const def = defaultNameFor(key);
7980
+ const bareSession = key.split("\0")[0];
7981
+ const def = defaultNameFor(bareSession);
7276
7982
  s = {
7277
7983
  activeSpace: def,
7278
7984
  activeName: typeof def === "string" ? def : null
@@ -7282,26 +7988,33 @@ function createSessionSpaceTracker(defaultNameFor = () => DEFAULT_SPACE) {
7282
7988
  return s;
7283
7989
  };
7284
7990
  const withSlot = (fn) => {
7285
- fn(slotOf(sessionKey), defaultNameFor(sessionKey));
7991
+ fn(slotOf(composeKey()), defaultNameFor(sessionKey));
7286
7992
  };
7287
7993
  return {
7288
- setCurrentSession: (id) => {
7994
+ setCurrentSession: (id, newLinkScope) => {
7289
7995
  session = id;
7290
7996
  sessionKey = id ?? GLOBAL_SESSION_KEY;
7997
+ if (newLinkScope !== void 0) linkScope = newLinkScope;
7998
+ noteReal();
7291
7999
  },
7292
8000
  currentSession: () => session,
7293
- current: () => slotOf(sessionKey).activeSpace,
8001
+ current: () => slotOf(composeKey()).activeSpace,
8002
+ lastActiveSpace: () => lastRealKey === null ? null : slotOf(lastRealKey).activeSpace,
7294
8003
  opened: (args, result) => {
8004
+ noteReal();
7295
8005
  withSlot((s, def) => {
7296
8006
  s.activeName = result?.name ?? str(args?.name, def) ?? null;
7297
8007
  s.activeSpace = result?.id ?? s.activeName ?? def;
7298
8008
  });
7299
8009
  },
7300
8010
  selected: (space) => {
7301
- if (space !== void 0 && space !== "") withSlot((s) => {
7302
- s.activeSpace = space;
7303
- s.activeName = typeof space === "string" ? space : null;
7304
- });
8011
+ if (space !== void 0 && space !== "") {
8012
+ noteReal();
8013
+ withSlot((s) => {
8014
+ s.activeSpace = space;
8015
+ s.activeName = typeof space === "string" ? space : null;
8016
+ });
8017
+ }
7305
8018
  },
7306
8019
  closed: (space, done) => {
7307
8020
  withSlot((s, def) => {
@@ -7326,8 +8039,38 @@ function createSessionSpaceTracker(defaultNameFor = () => DEFAULT_SPACE) {
7326
8039
  * harness sessions sharing the same browser remain unsupported (host-level).
7327
8040
  */
7328
8041
  let egoLockChain = Promise.resolve();
8042
+ /**
8043
+ * How many bcdp_* executions are currently inside the lock body (0 = idle).
8044
+ * The CLI frame poller reads this via `egoLockBusy()` to skip a tick while a
8045
+ * real tool call owns the browser — a passive observer must never contend with
8046
+ * an action. Incremented the moment the queued `fn` starts, decremented when its
8047
+ * result settles, so a chained-but-not-yet-run call does not falsely read busy.
8048
+ */
8049
+ let egoLockDepth = 0;
8050
+ function egoLockBusy() {
8051
+ return egoLockDepth > 0;
8052
+ }
7329
8053
  function withEgoLock(fn) {
7330
- const run = egoLockChain.then(() => fn(), () => fn());
8054
+ const runBody = () => {
8055
+ egoLockDepth += 1;
8056
+ let r;
8057
+ try {
8058
+ r = fn();
8059
+ } catch (err) {
8060
+ egoLockDepth -= 1;
8061
+ throw err;
8062
+ }
8063
+ if (r && typeof r.then === "function") return r.then((v) => {
8064
+ egoLockDepth -= 1;
8065
+ return v;
8066
+ }, (e) => {
8067
+ egoLockDepth -= 1;
8068
+ throw e;
8069
+ });
8070
+ egoLockDepth -= 1;
8071
+ return r;
8072
+ };
8073
+ const run = egoLockChain.then(runBody, runBody);
7331
8074
  egoLockChain = run.then(() => void 0, () => void 0);
7332
8075
  return run;
7333
8076
  }
@@ -7804,6 +8547,12 @@ function buildEgoToolArgv(prefix, attach, runtimeArgs) {
7804
8547
  ];
7805
8548
  }
7806
8549
  async function runEgoScript(subprocess, script, exec, cfg, graceOverrideMs) {
8550
+ if (resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.kind === TABBIT_CLI_KIND) return {
8551
+ ok: false,
8552
+ error: "tabbit-cli is active: ego runtime launch blocked (no Chrome fallback)",
8553
+ stdout: "",
8554
+ stderr: ""
8555
+ };
7807
8556
  let handle;
7808
8557
  try {
7809
8558
  const { attach } = effectiveChannel(cfg);
@@ -7868,6 +8617,47 @@ async function runEgoScript(subprocess, script, exec, cfg, graceOverrideMs) {
7868
8617
  stderr
7869
8618
  };
7870
8619
  }
8620
+ /**
8621
+ * ego-cli degraded frame source: run the poller heredoc through the SAME CLI
8622
+ * channel real tools use and resolve the merged stdout (which carries the
8623
+ * `@@BCDP_FRAME@@` payload). Kept separate from `runEgoScript` because that one
8624
+ * parses `@@DSH_RESULT@@` and needs an exec/abort context a passive poller has
8625
+ * none of. A failed or non-zero run resolves '' — the poller treats '' as "no
8626
+ * new frame" and keeps the previous one, so a transient cold start never blanks
8627
+ * the panel.
8628
+ */
8629
+ const CLI_FRAME_MAX_BYTES = 12 * 1024 * 1024;
8630
+ async function spawnCliFrameCapture(subprocess, cfg, space) {
8631
+ if (space === null || space === void 0 || space === "") return "";
8632
+ const { attach } = effectiveChannel(cfg);
8633
+ const script = buildFrameScript(j(space));
8634
+ try {
8635
+ const handle = subprocess.spawn({
8636
+ argv: buildEgoToolArgv(cfg.egoArgvPrefix, attach, cfg.runtimeArgs ?? ""),
8637
+ cwd: process.cwd(),
8638
+ env: resolveEgoEnv(cfg),
8639
+ stdio: {
8640
+ stdin: { data: script },
8641
+ stdout: {
8642
+ maxBytes: CLI_FRAME_MAX_BYTES,
8643
+ spill: { maxBytes: CLI_FRAME_MAX_BYTES }
8644
+ },
8645
+ stderr: {
8646
+ maxBytes: CLI_FRAME_MAX_BYTES,
8647
+ spill: { maxBytes: CLI_FRAME_MAX_BYTES }
8648
+ }
8649
+ },
8650
+ graceMs: cfg.graceMs
8651
+ });
8652
+ if ((await handle.done).exitCode !== 0) return "";
8653
+ return mergeCliOutput({
8654
+ stdout: readAll(handle.collected.stdout),
8655
+ stderr: readAll(handle.collected.stderr)
8656
+ });
8657
+ } catch {
8658
+ return "";
8659
+ }
8660
+ }
7871
8661
  /** How much raw stdout a tool may hand back when a script emitted no JSON. */
7872
8662
  const TOOL_RAW_STDOUT_MAX = 4e3;
7873
8663
  /**
@@ -7941,6 +8731,291 @@ function callingSessionId(exec) {
7941
8731
  const id = (exec?.agent)?.session?.id;
7942
8732
  return typeof id === "string" && id !== "" ? id : void 0;
7943
8733
  }
8734
+ /**
8735
+ * Tabbit tab inventory cache (module-level, written by 3s poller, read by tool handlers).
8736
+ * @internal
8737
+ */
8738
+ const _tabbitTabCache = {
8739
+ tabs: [],
8740
+ total: 0,
8741
+ complete: false,
8742
+ updatedAt: 0
8743
+ };
8744
+ /**
8745
+ * The last tab ID the agent actively operated on (set by navigate/acquire).
8746
+ * The frame poller uses this to screenshot the correct page.
8747
+ * @internal
8748
+ */
8749
+ let _tabbitLastActiveTabId = null;
8750
+ /**
8751
+ * The task name used by the last tool call (frame poller must reuse it to access owned tabs).
8752
+ * @internal
8753
+ */
8754
+ let _tabbitLastTaskName = "";
8755
+ /**
8756
+ * Tabbit backend dispatcher: when the active link is tabbit-cli, route the tool
8757
+ * call through tabbit-cli nodejs instead of the ego SDK subprocess path.
8758
+ * Returns {ok, ...data} matching toolPayload contract, or null to fall through
8759
+ * to the ego path (e.g. non-tabbit links, unsupported tools).
8760
+ */
8761
+ async function tryTabbitExecute(ctx, cfg, toolName, args, taskName) {
8762
+ const { effective } = effectiveChannel(cfg);
8763
+ if (!effective || effective.link.kind !== TABBIT_CLI_KIND) return null;
8764
+ const cli = resolveTabbitCli(effective.link.cliPath);
8765
+ if (!cli.found) return {
8766
+ ok: false,
8767
+ text: `tabbit-cli not found: ${cli.error}`
8768
+ };
8769
+ const sub = ctx.subprocess;
8770
+ _tabbitLastTaskName = taskName;
8771
+ const reqId = `${toolName}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
8772
+ const trackRun = (receipt) => {
8773
+ const ids = receipt.tabIds;
8774
+ if (ids && ids.length > 0) _tabbitLastActiveTabId = ids[ids.length - 1];
8775
+ };
8776
+ switch (toolName) {
8777
+ case "bcdp_status": {
8778
+ const diag = await tabbitDiagnose(sub, cli.cliPath);
8779
+ return {
8780
+ ok: diag.reachable,
8781
+ available: diag.reachable,
8782
+ backend: "tabbit-cli",
8783
+ raw: diag.raw.slice(0, 500),
8784
+ path: cli.cliPath
8785
+ };
8786
+ }
8787
+ case "bcdp_help": return {
8788
+ ok: true,
8789
+ text: `Tabbit backend active (${cli.cliPath}).\nSupported tools: bcdp_space, bcdp_navigate, bcdp_snapshot, bcdp_click, bcdp_fill, bcdp_screenshot, bcdp_tab op=list.\nUnsupported tools will return errors (no ego fallback).`,
8790
+ backend: "tabbit-cli"
8791
+ };
8792
+ case "bcdp_doctor": {
8793
+ const diag = await tabbitDiagnose(sub, cli.cliPath);
8794
+ return {
8795
+ ok: true,
8796
+ text: `backend: tabbit-cli\ncliPath: ${cli.cliPath}\nreachable: ${diag.reachable}\nraw: ${diag.raw.slice(0, 300)}`,
8797
+ backend: "tabbit-cli"
8798
+ };
8799
+ }
8800
+ case "bcdp_space": {
8801
+ const op = str(args.op, "open");
8802
+ if (op === "open") return {
8803
+ ok: true,
8804
+ ...await tabbitCreateTask(sub, cli.cliPath, taskName),
8805
+ backend: "tabbit-cli"
8806
+ };
8807
+ if (op === "close") {
8808
+ await tabbitFinishTask(sub, cli.cliPath, taskName, Boolean(args.discard));
8809
+ return {
8810
+ ok: true,
8811
+ released: true,
8812
+ backend: "tabbit-cli"
8813
+ };
8814
+ }
8815
+ if (op === "list") {
8816
+ const diag = await tabbitDiagnose(sub, cli.cliPath);
8817
+ return {
8818
+ ok: diag.reachable,
8819
+ raw: diag.raw,
8820
+ backend: "tabbit-cli"
8821
+ };
8822
+ }
8823
+ return {
8824
+ ok: false,
8825
+ text: `bcdp_space: unsupported op=${op} on tabbit backend`
8826
+ };
8827
+ }
8828
+ case "bcdp_tab": {
8829
+ const op = str(args.op, "list");
8830
+ if (op === "list") {
8831
+ if (Date.now() - _tabbitTabCache.updatedAt < 5e3 && _tabbitTabCache.tabs.length > 0) return {
8832
+ ok: true,
8833
+ tabs: _tabbitTabCache.tabs,
8834
+ total: _tabbitTabCache.total,
8835
+ complete: _tabbitTabCache.complete,
8836
+ cached: true,
8837
+ backend: "tabbit-cli"
8838
+ };
8839
+ const stateArg = str(args.state, "");
8840
+ return {
8841
+ ok: true,
8842
+ ...await tabbitListTabs(sub, cli.cliPath, taskName, stateArg || void 0),
8843
+ backend: "tabbit-cli"
8844
+ };
8845
+ }
8846
+ return {
8847
+ ok: false,
8848
+ text: `bcdp_tab: op=${op} not yet supported on tabbit backend`
8849
+ };
8850
+ }
8851
+ case "bcdp_navigate": {
8852
+ const url = str(args.url, "");
8853
+ if (url === "") return {
8854
+ ok: false,
8855
+ text: "bcdp_navigate: url is required"
8856
+ };
8857
+ const js = buildNavigateSnippet(url, str(args.waitUntil, "domcontentloaded"));
8858
+ const navTabId = typeof args.tab === "number" ? args.tab : void 0;
8859
+ const { receipt } = await runTabbitSnippet(sub, js, {
8860
+ cliPath: cli.cliPath,
8861
+ taskName,
8862
+ requestId: reqId,
8863
+ timeoutMs: 12e4,
8864
+ tabId: navTabId
8865
+ });
8866
+ if (receipt.ok) {
8867
+ if (navTabId) _tabbitLastActiveTabId = navTabId;
8868
+ trackRun(receipt);
8869
+ return {
8870
+ ok: true,
8871
+ ...receipt.data,
8872
+ backend: "tabbit-playwright"
8873
+ };
8874
+ }
8875
+ if (receipt.status === "queued" || receipt.status === "running") {
8876
+ const final = await pollTabbitPending(sub, {
8877
+ cliPath: cli.cliPath,
8878
+ taskName,
8879
+ requestId: reqId
8880
+ });
8881
+ if (final.ok) {
8882
+ trackRun(final);
8883
+ return {
8884
+ ok: true,
8885
+ ...final.data,
8886
+ backend: "tabbit-playwright"
8887
+ };
8888
+ }
8889
+ return {
8890
+ ok: false,
8891
+ text: `navigate pending then ${final.status}: ${final.error?.message ?? ""}`
8892
+ };
8893
+ }
8894
+ return {
8895
+ ok: false,
8896
+ text: receipt.error?.message ?? "navigation failed"
8897
+ };
8898
+ }
8899
+ case "bcdp_snapshot": {
8900
+ const { receipt } = await runTabbitSnippet(sub, buildObserveSnippet(typeof args.maxChars === "number" ? args.maxChars : 8e3), {
8901
+ cliPath: cli.cliPath,
8902
+ taskName,
8903
+ requestId: reqId
8904
+ });
8905
+ if (receipt.ok) {
8906
+ trackRun(receipt);
8907
+ return {
8908
+ ok: true,
8909
+ text: String(receipt.data ?? ""),
8910
+ format: "plaintext",
8911
+ backend: "tabbit-playwright"
8912
+ };
8913
+ }
8914
+ return {
8915
+ ok: false,
8916
+ text: receipt.error?.message ?? "observe failed"
8917
+ };
8918
+ }
8919
+ case "bcdp_click": {
8920
+ const selector = str(args.selector, str(args.loc, ""));
8921
+ const locExpr = translateLocator(selector);
8922
+ if (!locExpr) return {
8923
+ ok: false,
8924
+ text: `bcdp_click: cannot translate selector "${selector}" for tabbit backend`
8925
+ };
8926
+ const { receipt } = await runTabbitSnippet(sub, buildClickSnippet(locExpr), {
8927
+ cliPath: cli.cliPath,
8928
+ taskName,
8929
+ requestId: reqId
8930
+ });
8931
+ if (receipt.ok) {
8932
+ trackRun(receipt);
8933
+ return {
8934
+ ok: true,
8935
+ ...receipt.data,
8936
+ backend: "tabbit-playwright"
8937
+ };
8938
+ }
8939
+ return {
8940
+ ok: false,
8941
+ text: receipt.error?.message ?? "click failed"
8942
+ };
8943
+ }
8944
+ case "bcdp_fill": {
8945
+ const selector = str(args.selector, str(args.loc, ""));
8946
+ const value = str(args.value, "");
8947
+ const locExpr = translateLocator(selector);
8948
+ if (!locExpr) return {
8949
+ ok: false,
8950
+ text: `bcdp_fill: cannot translate selector "${selector}" for tabbit backend`
8951
+ };
8952
+ const { receipt } = await runTabbitSnippet(sub, buildFillSnippet(locExpr, value), {
8953
+ cliPath: cli.cliPath,
8954
+ taskName,
8955
+ requestId: reqId
8956
+ });
8957
+ if (receipt.ok) {
8958
+ trackRun(receipt);
8959
+ return {
8960
+ ok: true,
8961
+ ...receipt.data,
8962
+ backend: "tabbit-playwright"
8963
+ };
8964
+ }
8965
+ return {
8966
+ ok: false,
8967
+ text: receipt.error?.message ?? "fill failed"
8968
+ };
8969
+ }
8970
+ case "bcdp_screenshot": {
8971
+ const requested = str(args.path, "");
8972
+ const { receipt } = await runTabbitSnippet(sub, buildScreenshotSnippet(requested !== "" ? requested : join(tmpdir(), `dsh-browser-cdp-shot-${Date.now()}.png`)), {
8973
+ cliPath: cli.cliPath,
8974
+ taskName,
8975
+ requestId: reqId,
8976
+ timeoutMs: 12e4
8977
+ });
8978
+ if (receipt.ok) {
8979
+ trackRun(receipt);
8980
+ const d = receipt.data;
8981
+ if (d?.skipped !== void 0) return {
8982
+ ok: false,
8983
+ text: `bcdp_screenshot: capture did not complete (${d.skipped}${d.error ? `: ${d.error}` : ""}) on ${d.url ?? "unknown page"}. The page may still be loading or the renderer is not producing frames.`
8984
+ };
8985
+ if (typeof d?.path !== "string") return {
8986
+ ok: false,
8987
+ text: `bcdp_screenshot: receipt carried no path (status=${receipt.status}, data=${JSON.stringify(d ?? null).slice(0, 160)})`
8988
+ };
8989
+ let base64 = "";
8990
+ try {
8991
+ base64 = readFileSync(d.path).toString("base64");
8992
+ } catch (err) {
8993
+ return {
8994
+ ok: false,
8995
+ text: `bcdp_screenshot: cannot read ${d.path}: ${String(err?.message ?? err)}`
8996
+ };
8997
+ }
8998
+ return {
8999
+ ok: true,
9000
+ path: d.path,
9001
+ base64,
9002
+ bytes: d.bytes,
9003
+ url: d.url,
9004
+ title: d.title,
9005
+ backend: "tabbit-playwright"
9006
+ };
9007
+ }
9008
+ return {
9009
+ ok: false,
9010
+ text: receipt.error?.message ?? "screenshot failed"
9011
+ };
9012
+ }
9013
+ default: return {
9014
+ ok: false,
9015
+ text: `bcdp tool "${toolName}" is not yet supported on tabbit-cli backend. Supported: space, navigate, snapshot, click, fill, screenshot, tab list.`
9016
+ };
9017
+ }
9018
+ }
7944
9019
  function defineEgoTool(ctx, cfg, opts) {
7945
9020
  return defineTool({
7946
9021
  name: opts.name,
@@ -7952,7 +9027,7 @@ function defineEgoTool(ctx, cfg, opts) {
7952
9027
  },
7953
9028
  timeoutMs: TOOL_TIMEOUT_MS,
7954
9029
  execute: async (args, exec) => withEgoLock(async () => {
7955
- cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
9030
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
7956
9031
  markEgoToolCall(callingSessionId(exec));
7957
9032
  if (typeof opts.gate === "function") {
7958
9033
  const blocked = opts.gate(args);
@@ -7961,6 +9036,13 @@ function defineEgoTool(ctx, cfg, opts) {
7961
9036
  text: blocked
7962
9037
  };
7963
9038
  }
9039
+ if (resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.kind === TABBIT_CLI_KIND) {
9040
+ const tabName = `dsh-${sessionSpaceToken(callingSessionId(exec) ?? "")}`;
9041
+ return await tryTabbitExecute(ctx, cfg, opts.name, args, tabName) ?? {
9042
+ ok: false,
9043
+ text: `tabbit-cli is the active backend but tool "${opts.name}" dispatch failed unexpectedly. Not falling back to ego.`
9044
+ };
9045
+ }
7964
9046
  if (opts.tabRevive) {
7965
9047
  const { result: result$1, recoveredFrom } = await runWithTabRevive(ctx, cfg, exec, () => opts.buildScript(args));
7966
9048
  if (!result$1.ok) throw new Error(recoveredFrom ? `${result$1.error}\n${recoveredFrom}` : result$1.error);
@@ -8170,6 +9252,9 @@ function apply(ctx, config = {}) {
8170
9252
  get allowProbeColdStart() {
8171
9253
  return resolveConfig(bridge.source()).allowProbeColdStart;
8172
9254
  },
9255
+ get cliFramePollEnabled() {
9256
+ return resolveConfig(bridge.source()).cliFramePollEnabled;
9257
+ },
8173
9258
  get jevUrl() {
8174
9259
  return judgeSettingsOf(resolveConfig(bridge.source())).jevUrl;
8175
9260
  },
@@ -8341,6 +9426,81 @@ function apply(ctx, config = {}) {
8341
9426
  })})`);
8342
9427
  }
8343
9428
  bridge.onChange(() => tiers.reapply());
9429
+ const cliPoller = new CliFramePoller({
9430
+ intervalMs: 3e3,
9431
+ capture: () => spawnCliFrameCapture(ctx.subprocess, cfg, cfg.spaceTracker.lastActiveSpace()),
9432
+ isBusy: egoLockBusy,
9433
+ onFrame: (frame) => broadcastCliFrame(frame)
9434
+ });
9435
+ ctx.effect?.(() => () => cliPoller.stop());
9436
+ const tabbitTabTimer = setInterval(async () => {
9437
+ const eff = resolveEffectiveLink(cfg.links, cfg.activeTargetId);
9438
+ if (eff?.link.kind !== TABBIT_CLI_KIND) return;
9439
+ const cli = resolveTabbitCli(eff.link.cliPath);
9440
+ if (!cli.found) return;
9441
+ try {
9442
+ const taskName = `dsh-${sessionSpaceToken("poll")}`;
9443
+ const result = await tabbitListTabs(ctx.subprocess, cli.cliPath, taskName);
9444
+ Object.assign(_tabbitTabCache, result, { updatedAt: Date.now() });
9445
+ } catch {}
9446
+ }, 3e3);
9447
+ ctx.effect?.(() => () => clearInterval(tabbitTabTimer));
9448
+ let tabbitFrameSeq = 0;
9449
+ let tabbitFrameInFlight = false;
9450
+ let tabbitFrameSkipLogged = "";
9451
+ const tabbitFramePath = join(tmpdir(), `dsh-browser-cdp-frame-${process.pid}.jpg`);
9452
+ const tabbitFrameTimer = setInterval(async () => {
9453
+ const eff = resolveEffectiveLink(cfg.links, cfg.activeTargetId);
9454
+ if (eff?.link.kind !== TABBIT_CLI_KIND) return;
9455
+ const cli = resolveTabbitCli(eff.link.cliPath);
9456
+ if (!cli.found) return;
9457
+ if (egoLockBusy()) return;
9458
+ if (!_tabbitLastTaskName) return;
9459
+ if (tabbitFrameInFlight) return;
9460
+ tabbitFrameInFlight = true;
9461
+ try {
9462
+ const reqId = `frame-${Date.now()}`;
9463
+ const js = buildFrameCaptureSnippet(tabbitFramePath);
9464
+ const target = _tabbitLastActiveTabId ?? _tabbitTabCache.tabs.find((t) => t.active === true)?.tabId;
9465
+ const { receipt } = await runTabbitSnippet(ctx.subprocess, js, {
9466
+ cliPath: cli.cliPath,
9467
+ taskName: _tabbitLastTaskName,
9468
+ requestId: reqId,
9469
+ ...typeof target === "number" ? { tabId: target } : {}
9470
+ });
9471
+ const data = receipt.data;
9472
+ if (receipt.ok && data?.skipped !== void 0) {
9473
+ const key = `${data.skipped}:${data.error ?? ""}`;
9474
+ if (tabbitFrameSkipLogged !== key) {
9475
+ tabbitFrameSkipLogged = key;
9476
+ ctx.logger?.info?.(`dsh-browser-cdp: tabbit frame skipped (${key}) url=${data.url ?? "?"}`);
9477
+ }
9478
+ return;
9479
+ }
9480
+ tabbitFrameSkipLogged = "";
9481
+ if (receipt.ok && typeof data?.path === "string") {
9482
+ const png = readFileSync(data.path);
9483
+ tabbitFrameSeq++;
9484
+ broadcastCliFrame({
9485
+ png,
9486
+ url: data.url ?? "",
9487
+ title: data.title ?? "",
9488
+ seq: tabbitFrameSeq,
9489
+ updatedAt: Date.now(),
9490
+ fmt: "jpeg"
9491
+ });
9492
+ return;
9493
+ }
9494
+ if (receipt.ok) ctx.logger?.warn?.(`dsh-browser-cdp: tabbit frame receipt carried no path (status=${receipt.status}, data=${JSON.stringify(data ?? null).slice(0, 120)})`);
9495
+ else if (receipt.status !== "queued" && receipt.status !== "running") ctx.logger?.warn?.(`dsh-browser-cdp: tabbit frame capture failed: ${receipt.error?.message ?? receipt.status}`);
9496
+ } catch (err) {
9497
+ ctx.logger?.warn?.(`dsh-browser-cdp: tabbit frame poller error: ${String(err?.message ?? err)}`);
9498
+ } finally {
9499
+ tabbitFrameInFlight = false;
9500
+ }
9501
+ }, 3e3);
9502
+ ctx.effect?.(() => () => clearInterval(tabbitFrameTimer));
9503
+ ctx.effect?.(() => () => clearInterval(tabbitFrameTimer));
8344
9504
  const triggerCdpRefresh = (() => {
8345
9505
  let inFlight = false;
8346
9506
  let pending = false;
@@ -8392,6 +9552,8 @@ function apply(ctx, config = {}) {
8392
9552
  changed = true;
8393
9553
  recycleWorker("cdp activation change").catch(() => null);
8394
9554
  }
9555
+ if (ws === null && attach.linkKind === EGO_CLI_KIND && attach.status === "ready" && resolved.cliFramePollEnabled === true) cliPoller.start();
9556
+ else cliPoller.stop();
8395
9557
  } catch {} finally {
8396
9558
  inFlight = false;
8397
9559
  if (pending) {
@@ -8411,7 +9573,7 @@ function apply(ctx, config = {}) {
8411
9573
  });
8412
9574
  ctx.inject?.(["webServer"], (wctx) => {
8413
9575
  try {
8414
- initCastServer(wctx, cfg, bridge, ffmpegManager, () => openAgentWindow(ctx, cfg), (opts) => importLoginCookies(opts, { subprocess: ctx.subprocess }));
9576
+ initCastServer(wctx, cfg, bridge, ffmpegManager, () => openAgentWindow(ctx, cfg), (opts) => importLoginCookies(opts, { subprocess: ctx.subprocess }), cliPoller);
8415
9577
  } catch (err) {
8416
9578
  ctx.logger?.warn?.(`dsh-browser-cdp: cast server init failed: ${err?.message ?? err}`);
8417
9579
  }
@@ -8449,13 +9611,14 @@ function apply(ctx, config = {}) {
8449
9611
  const last = getLastEgoActivity();
8450
9612
  if (!shouldReapBrowser(Date.now(), last, cfg.idleTimeoutMin)) return;
8451
9613
  if (last <= reapedFor) return;
8452
- if (effectiveChannel(cfg).effective?.link.kind === EGO_CLI_KIND) {
9614
+ const linkKind = effectiveChannel(cfg).effective?.link.kind;
9615
+ if (linkKind === EGO_CLI_KIND || linkKind === TABBIT_CLI_KIND) {
8453
9616
  reapedFor = last;
8454
- ctx.logger?.info?.("dsh-browser-cdp: idle reaper skipped: ego-cli owns the user's browser (never --stop it)");
9617
+ ctx.logger?.info?.(`dsh-browser-cdp: idle reaper skipped: ${linkKind} owns the user\'s browser (never --stop it)`);
8455
9618
  return;
8456
9619
  }
8457
9620
  try {
8458
- const { localBrowserInfo, stopLocalBrowser: stopLocalBrowser$1 } = await import("./launcher-h0Ca5NV1.js");
9621
+ const { localBrowserInfo, stopLocalBrowser: stopLocalBrowser$1 } = await import("./launcher-hmPXaWQa.js");
8459
9622
  if (localBrowserInfo()) {
8460
9623
  await stopLocalBrowser$1();
8461
9624
  ctx.logger?.info?.("dsh-browser-cdp: idle reaper stopped the locally launched browser");
@@ -8496,8 +9659,8 @@ function apply(ctx, config = {}) {
8496
9659
  }, "dsh-browser-cdp: idle reaper");
8497
9660
  ctx.effect?.(() => {
8498
9661
  try {
8499
- if (effectiveChannel(cfg).effective?.link.kind === EGO_CLI_KIND) {
8500
- ctx.logger?.info?.("dsh-browser-cdp: teardown skipped --stop: ego-cli owns the user's browser");
9662
+ if (effectiveChannel(cfg).effective?.link.kind === EGO_CLI_KIND || effectiveChannel(cfg).effective?.link.kind === TABBIT_CLI_KIND) {
9663
+ ctx.logger?.info?.("dsh-browser-cdp: teardown skipped --stop: user-owned browser (ego-cli/tabbit-cli)");
8501
9664
  return;
8502
9665
  }
8503
9666
  ctx.subprocess.spawn({
@@ -9349,7 +10512,12 @@ function registerActionTools(ctx, cfg, reg) {
9349
10512
  },
9350
10513
  space: spaceParam
9351
10514
  },
9352
- gate: () => defaultAttachCache.get().engine === "lightpanda" ? "engine-unsupported: the attached browser is Lightpanda, which has no Page download events �?bcdp_download cannot capture files on this engine. Trigger the download another way (e.g. fetch() the URL in-page and return the bytes)." : null,
10515
+ gate: () => {
10516
+ const eng = defaultAttachCache.get().engine;
10517
+ if (eng === "lightpanda") return "engine-unsupported: Lightpanda has no Page download events, bcdp_download cannot capture files. Use fetch() in-page instead.";
10518
+ if (eng === "tabbit") return "engine-unsupported: Tabbit CLI mode does not expose Playwright download events. Use page.fetch() in bcdp_script to download via browser network.";
10519
+ return null;
10520
+ },
9353
10521
  buildScript: (args) => {
9354
10522
  const sel = str(args.triggerSelector, "");
9355
10523
  const script = str(args.triggerScript, "");
@@ -9482,7 +10650,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9482
10650
  },
9483
10651
  timeoutMs: 15e3,
9484
10652
  execute: async (args, exec) => withEgoLock(async () => {
9485
- cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
10653
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
9486
10654
  markEgoToolCall(callingSessionId(exec));
9487
10655
  const result = await runWithStaleSpaceRetry(ctx, cfg, { signal: exec?.signal }, () => humanCheckScript(str(args.space, cfg.activeSpace)));
9488
10656
  if (!result.ok) return {
@@ -9608,6 +10776,14 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9608
10776
  lines.push(`channel: ${channel.effective ? `${channel.effective.link.label} [${channel.effective.link.id}] (${channel.effective.reason}${channel.effective.demotedId ? `, over ${channel.effective.demotedId}` : ""})` : "(none — activate a link or enable one)"}`);
9609
10777
  lines.push(`remote CDP: ${cfg.remoteEnabled === false ? "DISABLED by switch (sequence preserved)" : "enabled"}`);
9610
10778
  lines.push(`attach: ${attachNow.status}${attachNow.endpointSource ? ` (source: ${attachNow.endpointSource})` : ""}${attachNow.endpoint ? ` @ ${attachNow.endpoint}` : ""}`);
10779
+ const cliPoll = getCliPollStatus();
10780
+ const frameSource = getAttachEndpoint() ? "screencast (CDP)" : cliPoll.running ? `cli-poll (3s interval, seq ${cliPoll.frameSeq}${cliPoll.lastFrameAgeMs !== null ? `, last frame ${cliPoll.lastFrameAgeMs}ms ago` : ", no frame yet"})` : cfg.cliFramePollEnabled === false ? "none (cliFramePollEnabled off)" : "none";
10781
+ lines.push(`frame source: ${frameSource}`);
10782
+ {
10783
+ const sid = callingSessionId(exec);
10784
+ const pollSpace = cfg.spaceTracker.lastActiveSpace();
10785
+ lines.push(`session scope: id=${sid ?? "(none → global slot)"} thisCallSpace=${cfg.activeSpace} pollerObserves=${pollSpace ?? "(null: poller will skip / no default registered)"} defaultSpace=${cfg.defaultSpace} isolateSpaces=${cfg.isolateSpaces}`);
10786
+ }
9611
10787
  if (attachNow.engine !== void 0) lines.push(`engine: ${attachNow.engine}`);
9612
10788
  if (attachNow.engine === "lightpanda") lines.push("degraded on this engine: live view (no screencast) · panel pick (no Overlay/bindingCalled) · bcdp_download (no Page download events) · screenshots are PNG text-renders · auth_flush is a no-op");
9613
10789
  if (attachNow.engine === "lightpanda" || process.platform === "win32") lines.push(process.platform === "win32" ? "lightpanda on win32: no native build �?use WSL2: `wsl --install` (admin), then inside WSL: `curl -fsSL https://pkg.lightpanda.io/install.sh | bash` + `lightpanda serve --host 127.0.0.1 --port 9222`; WSL2 maps the port to Windows localhost, then add http://127.0.0.1:9222 as a CDP endpoint. Docker alternative: `docker run -d -p 127.0.0.1:9222:9222 lightpanda/browser:nightly`." : "lightpanda (linux/macOS): `curl -fsSL https://pkg.lightpanda.io/install.sh | bash` (installs to ~/.local/bin) then `lightpanda serve --host 127.0.0.1 --port 9222`.");
@@ -9732,7 +10908,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9732
10908
  },
9733
10909
  timeoutMs: TOOL_TIMEOUT_MS,
9734
10910
  execute: async (args, exec) => {
9735
- cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
10911
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
9736
10912
  markEgoToolCall(callingSessionId(exec));
9737
10913
  const timeoutMs = typeof args.timeoutMs === "number" && Number.isFinite(args.timeoutMs) && args.timeoutMs > 0 ? args.timeoutMs : void 0;
9738
10914
  const start = Date.now();
@@ -9866,7 +11042,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9866
11042
  },
9867
11043
  timeoutMs: 1e4,
9868
11044
  execute: async (_args, exec) => {
9869
- cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
11045
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
9870
11046
  markEgoToolCall(callingSessionId(exec));
9871
11047
  const judge = judgeCfg();
9872
11048
  const runtime = judgeRuntimeOf();
@@ -9966,7 +11142,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9966
11142
  },
9967
11143
  timeoutMs: 6e4,
9968
11144
  execute: async (args, exec) => {
9969
- cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
11145
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
9970
11146
  markEgoToolCall(callingSessionId(exec));
9971
11147
  const blocked = attachGate();
9972
11148
  if (blocked !== "") return {
@@ -10105,7 +11281,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
10105
11281
  },
10106
11282
  timeoutMs: 6e4,
10107
11283
  execute: async (args, exec) => {
10108
- cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
11284
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
10109
11285
  markEgoToolCall(callingSessionId(exec));
10110
11286
  const blocked = attachGate();
10111
11287
  if (blocked !== "") return {
@@ -10215,7 +11391,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
10215
11391
  },
10216
11392
  timeoutMs: TOOL_TIMEOUT_MS,
10217
11393
  execute: async (args, exec) => {
10218
- cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
11394
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
10219
11395
  markEgoToolCall(callingSessionId(exec));
10220
11396
  const blocked = attachGate();
10221
11397
  if (blocked !== "") return {
@@ -10313,7 +11489,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
10313
11489
  },
10314
11490
  timeoutMs: TOOL_TIMEOUT_MS,
10315
11491
  execute: async (args, exec) => {
10316
- cfg.spaceTracker.setCurrentSession(callingSessionId(exec));
11492
+ cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
10317
11493
  markEgoToolCall(callingSessionId(exec));
10318
11494
  const blocked = attachGate();
10319
11495
  if (blocked !== "") return {
@@ -10380,4 +11556,4 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
10380
11556
  }
10381
11557
 
10382
11558
  //#endregion
10383
- export { ATTACH_SESSION_HINT, CDP_CONNECT_FAIL_RE, Config, GLOBAL_SESSION_KEY, STATUS_FACADE_SCRIPT, STATUS_FACADE_SENTINEL, TAB_STUCK_RE, apply, attachSessionHint, buildEgoToolArgv, cdpAttachError, createActiveSpaceTracker, createSessionSpaceTracker, decideCdpAttach, deriveSlotDefaultName, effectiveChannel, findChromeBinary, findUpstreamPluginInstall, inject, isTabStuckFailure, name, parseSentinel, parseStatusFacades, resolveEgoEnv, runWithStaleSpaceRetry, runWithTabRevive, sessionSpaceToken, shouldReapBrowser };
11559
+ export { ATTACH_SESSION_HINT, CDP_CONNECT_FAIL_RE, Config, GLOBAL_SESSION_KEY, STATUS_FACADE_SCRIPT, STATUS_FACADE_SENTINEL, TAB_STUCK_RE, apply, attachSessionHint, buildEgoToolArgv, cdpAttachError, createActiveSpaceTracker, createSessionSpaceTracker, decideCdpAttach, deriveSlotDefaultName, effectiveChannel, egoLockBusy, findChromeBinary, findUpstreamPluginInstall, inject, isTabStuckFailure, name, parseSentinel, parseStatusFacades, resolveEgoEnv, runWithStaleSpaceRetry, runWithTabRevive, sessionSpaceToken, shouldReapBrowser };