@xbrowser/cli 1.32.0 → 1.33.0

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.
@@ -21,8 +21,8 @@ import {
21
21
  saveSessionDiskMeta,
22
22
  setActivePage,
23
23
  touchSession
24
- } from "./chunk-JO6WHY3D.js";
25
- import "./chunk-NDBOLP5Z.js";
24
+ } from "./chunk-OVAUGFM6.js";
25
+ import "./chunk-H25ECCYJ.js";
26
26
  import "./chunk-A7NEA4PA.js";
27
27
  import "./chunk-SMYSNO4M.js";
28
28
  import "./chunk-2KPI5GKP.js";
@@ -21,7 +21,7 @@ import {
21
21
  saveSessionDiskMeta,
22
22
  setActivePage,
23
23
  touchSession
24
- } from "./chunk-NBW3GGZB.js";
24
+ } from "./chunk-5MYC6LVL.js";
25
25
  import "./chunk-SMYSNO4M.js";
26
26
  import "./chunk-2KPI5GKP.js";
27
27
  import "./chunk-GDKLH7ZY.js";
@@ -21,8 +21,8 @@ import {
21
21
  saveSessionDiskMeta,
22
22
  setActivePage,
23
23
  touchSession
24
- } from "./chunk-BM6DDHA2.js";
25
- import "./chunk-VYGK4X33.js";
24
+ } from "./chunk-DDHHVII7.js";
25
+ import "./chunk-YX5KVWGX.js";
26
26
  import "./chunk-SMYSNO4M.js";
27
27
  import "./chunk-2KPI5GKP.js";
28
28
  import "./chunk-GDKLH7ZY.js";
@@ -5484,9 +5484,9 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
5484
5484
  * evaluate 可排队 >30s——Runtime.evaluate 单独放宽到 90s)
5485
5485
  * @returns the `result` field from the CDP response
5486
5486
  */
5487
- async send(method, params, sessionId, timeoutMs) {
5487
+ async send(method, params, sessionId, timeoutMs, skipSequence) {
5488
5488
  const effectiveTimeout = timeoutMs ?? (method === "Runtime.evaluate" ? 9e4 : 3e4);
5489
- if (this.guard) {
5489
+ if (this.guard && !skipSequence) {
5490
5490
  const decision = this.guard.evaluate({
5491
5491
  method,
5492
5492
  params: params ?? {},
@@ -5499,9 +5499,14 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
5499
5499
  if (decision && decision.action === "transform" && Array.isArray(decision.transformedParams?.__sequence)) {
5500
5500
  const sequence = decision.transformedParams.__sequence;
5501
5501
  let last;
5502
- for (const step of sequence) {
5502
+ for (let i = 0; i < sequence.length; i++) {
5503
+ const step = sequence[i];
5503
5504
  if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
5504
- last = await this.send(step.method, step.params, sessionId, effectiveTimeout);
5505
+ if (i < sequence.length - 1) {
5506
+ void this.send(step.method, step.params, sessionId, effectiveTimeout, true).catch(() => void 0);
5507
+ } else {
5508
+ last = await this.send(step.method, step.params, sessionId, effectiveTimeout, true);
5509
+ }
5505
5510
  }
5506
5511
  return last;
5507
5512
  }
@@ -14,7 +14,7 @@ import {
14
14
  scrollIntoView,
15
15
  waitForActionable,
16
16
  waitForNetworkIdle
17
- } from "./chunk-NDBOLP5Z.js";
17
+ } from "./chunk-H25ECCYJ.js";
18
18
  import "./chunk-A7NEA4PA.js";
19
19
  import "./chunk-SMYSNO4M.js";
20
20
  import {
@@ -14,7 +14,7 @@ import {
14
14
  scrollIntoView,
15
15
  waitForActionable,
16
16
  waitForNetworkIdle
17
- } from "./chunk-VYGK4X33.js";
17
+ } from "./chunk-YX5KVWGX.js";
18
18
  import "./chunk-SMYSNO4M.js";
19
19
  import {
20
20
  connectToCDP,
@@ -5557,9 +5557,9 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
5557
5557
  * evaluate 可排队 >30s——Runtime.evaluate 单独放宽到 90s)
5558
5558
  * @returns the `result` field from the CDP response
5559
5559
  */
5560
- async send(method, params, sessionId, timeoutMs) {
5560
+ async send(method, params, sessionId, timeoutMs, skipSequence) {
5561
5561
  const effectiveTimeout = timeoutMs ?? (method === "Runtime.evaluate" ? 9e4 : 3e4);
5562
- if (this.guard) {
5562
+ if (this.guard && !skipSequence) {
5563
5563
  const decision = this.guard.evaluate({
5564
5564
  method,
5565
5565
  params: params ?? {},
@@ -5572,9 +5572,14 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
5572
5572
  if (decision && decision.action === "transform" && Array.isArray(decision.transformedParams?.__sequence)) {
5573
5573
  const sequence = decision.transformedParams.__sequence;
5574
5574
  let last;
5575
- for (const step of sequence) {
5575
+ for (let i = 0; i < sequence.length; i++) {
5576
+ const step = sequence[i];
5576
5577
  if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
5577
- last = await this.send(step.method, step.params, sessionId, effectiveTimeout);
5578
+ if (i < sequence.length - 1) {
5579
+ void this.send(step.method, step.params, sessionId, effectiveTimeout, true).catch(() => void 0);
5580
+ } else {
5581
+ last = await this.send(step.method, step.params, sessionId, effectiveTimeout, true);
5582
+ }
5578
5583
  }
5579
5584
  return last;
5580
5585
  }
@@ -20,7 +20,7 @@ import {
20
20
  resolveLaunchOpts,
21
21
  saveSessionDiskMeta,
22
22
  setActivePage
23
- } from "./chunk-NBW3GGZB.js";
23
+ } from "./chunk-5MYC6LVL.js";
24
24
  import {
25
25
  rand,
26
26
  sleep,
@@ -9178,7 +9178,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9178
9178
  }
9179
9179
  let targetPageOverride = null;
9180
9180
  if (_target && extraOpts?.cdpEndpoint) {
9181
- const { findTargetPage } = await import("./browser-CE4GTZRO.js");
9181
+ const { findTargetPage } = await import("./browser-3LBSVDSS.js");
9182
9182
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
9183
9183
  if (!targetPageOverride) {
9184
9184
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -9,7 +9,7 @@ import {
9
9
  resolveLaunchOpts,
10
10
  saveSessionDiskMeta,
11
11
  setActivePage
12
- } from "./chunk-BM6DDHA2.js";
12
+ } from "./chunk-DDHHVII7.js";
13
13
  import {
14
14
  detectAntiBot,
15
15
  formatDetectionMessage
@@ -9495,7 +9495,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
9495
9495
  }
9496
9496
  let targetPageOverride = null;
9497
9497
  if (_target && extraOpts?.cdpEndpoint) {
9498
- const { findTargetPage } = await import("./browser-JPTQ5JA2.js");
9498
+ const { findTargetPage } = await import("./browser-D7RFPTD4.js");
9499
9499
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
9500
9500
  if (!targetPageOverride) {
9501
9501
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  launch
3
- } from "./chunk-VYGK4X33.js";
3
+ } from "./chunk-YX5KVWGX.js";
4
4
  import {
5
5
  errMsg
6
6
  } from "./chunk-GDKLH7ZY.js";
@@ -5385,9 +5385,9 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
5385
5385
  * evaluate 可排队 >30s——Runtime.evaluate 单独放宽到 90s)
5386
5386
  * @returns the `result` field from the CDP response
5387
5387
  */
5388
- async send(method, params, sessionId, timeoutMs) {
5388
+ async send(method, params, sessionId, timeoutMs, skipSequence) {
5389
5389
  const effectiveTimeout = timeoutMs ?? (method === "Runtime.evaluate" ? 9e4 : 3e4);
5390
- if (this.guard) {
5390
+ if (this.guard && !skipSequence) {
5391
5391
  const decision = this.guard.evaluate({
5392
5392
  method,
5393
5393
  params: params ?? {},
@@ -5400,9 +5400,14 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
5400
5400
  if (decision && decision.action === "transform" && Array.isArray(decision.transformedParams?.__sequence)) {
5401
5401
  const sequence = decision.transformedParams.__sequence;
5402
5402
  let last;
5403
- for (const step of sequence) {
5403
+ for (let i = 0; i < sequence.length; i++) {
5404
+ const step = sequence[i];
5404
5405
  if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
5405
- last = await this.send(step.method, step.params, sessionId, effectiveTimeout);
5406
+ if (i < sequence.length - 1) {
5407
+ void this.send(step.method, step.params, sessionId, effectiveTimeout, true).catch(() => void 0);
5408
+ } else {
5409
+ last = await this.send(step.method, step.params, sessionId, effectiveTimeout, true);
5410
+ }
5406
5411
  }
5407
5412
  return last;
5408
5413
  }
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createRuleEngine,
3
3
  launch
4
- } from "./chunk-NDBOLP5Z.js";
4
+ } from "./chunk-H25ECCYJ.js";
5
5
  import {
6
6
  errMsg
7
7
  } from "./chunk-GDKLH7ZY.js";
@@ -4388,9 +4388,9 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
4388
4388
  * evaluate 可排队 >30s——Runtime.evaluate 单独放宽到 90s)
4389
4389
  * @returns the `result` field from the CDP response
4390
4390
  */
4391
- async send(method, params, sessionId, timeoutMs) {
4391
+ async send(method, params, sessionId, timeoutMs, skipSequence) {
4392
4392
  const effectiveTimeout = timeoutMs ?? (method === "Runtime.evaluate" ? 9e4 : 3e4);
4393
- if (this.guard) {
4393
+ if (this.guard && !skipSequence) {
4394
4394
  const decision = this.guard.evaluate({
4395
4395
  method,
4396
4396
  params: params ?? {},
@@ -4403,9 +4403,14 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
4403
4403
  if (decision && decision.action === "transform" && Array.isArray(decision.transformedParams?.__sequence)) {
4404
4404
  const sequence = decision.transformedParams.__sequence;
4405
4405
  let last;
4406
- for (const step of sequence) {
4406
+ for (let i = 0; i < sequence.length; i++) {
4407
+ const step = sequence[i];
4407
4408
  if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
4408
- last = await this.send(step.method, step.params, sessionId, effectiveTimeout);
4409
+ if (i < sequence.length - 1) {
4410
+ void this.send(step.method, step.params, sessionId, effectiveTimeout, true).catch(() => void 0);
4411
+ } else {
4412
+ last = await this.send(step.method, step.params, sessionId, effectiveTimeout, true);
4413
+ }
4409
4414
  }
4410
4415
  return last;
4411
4416
  }
package/dist/cli.js CHANGED
@@ -17,9 +17,10 @@ import {
17
17
  loadHooks,
18
18
  parsePluginParams,
19
19
  readJsonFile
20
- } from "./chunk-G47VJ5OR.js";
20
+ } from "./chunk-ACPMC47K.js";
21
21
  import "./chunk-JKVUFP3G.js";
22
22
  import {
23
+ daemonPing,
23
24
  forwardCommandLog,
24
25
  forwardExec,
25
26
  forwardNetworkAnalyze,
@@ -83,7 +84,7 @@ import {
83
84
  findSession,
84
85
  getAllSessions,
85
86
  saveSessionDiskMeta
86
- } from "./chunk-NBW3GGZB.js";
87
+ } from "./chunk-5MYC6LVL.js";
87
88
  import "./chunk-SMYSNO4M.js";
88
89
  import "./chunk-2KPI5GKP.js";
89
90
  import {
@@ -3216,8 +3217,8 @@ async function handlePlugin(args, options, mode) {
3216
3217
  } catch {
3217
3218
  }
3218
3219
  try {
3219
- const { daemonPing } = await import("./daemon-client-HEGAXWGK.js");
3220
- if (await daemonPing()) {
3220
+ const { daemonPing: daemonPing2 } = await import("./daemon-client-HEGAXWGK.js");
3221
+ if (await daemonPing2()) {
3221
3222
  await fetch("http://localhost:9224/rpc", {
3222
3223
  method: "POST",
3223
3224
  headers: { "Content-Type": "application/json" },
@@ -3839,7 +3840,7 @@ async function handleGeneratePlugin(sessionName, pluginName, outputDir) {
3839
3840
  const { SessionRecorder: SessionRecorder2 } = await import("./session-recorder-RUNQOJ7T.js");
3840
3841
  const { readSiteKnowledge: readSiteKnowledge2, toMarkdown } = await import("./site-knowledge-SYC6VCDB.js");
3841
3842
  const { mkdirSync: mkdirSync6, writeFileSync: writeFileSync7 } = await import("fs");
3842
- const { join: join7 } = await import("path");
3843
+ const { join: join8 } = await import("path");
3843
3844
  const data = SessionRecorder2.readData(sessionName);
3844
3845
  if (!data) {
3845
3846
  outputError(`No recording found for session "${sessionName}". Run \`xbrowser record stop --session ${sessionName}\` first.`);
@@ -3851,14 +3852,14 @@ async function handleGeneratePlugin(sessionName, pluginName, outputDir) {
3851
3852
  } catch {
3852
3853
  }
3853
3854
  const finalPluginName = pluginName || domain.split(".")[0] || "my-site";
3854
- const finalOutputDir = outputDir || join7(process.cwd(), ".xcli", "plugins", finalPluginName);
3855
+ const finalOutputDir = outputDir || join8(process.cwd(), ".xcli", "plugins", finalPluginName);
3855
3856
  const knowledge = readSiteKnowledge2(domain);
3856
3857
  const knowledgeMd = knowledge ? toMarkdown(knowledge) : "";
3857
3858
  const pluginCode = generatePluginCode(finalPluginName, domain, data, knowledgeMd);
3858
- mkdirSync6(join7(finalOutputDir), { recursive: true });
3859
- writeFileSync7(join7(finalOutputDir, "index.ts"), pluginCode, "utf-8");
3859
+ mkdirSync6(join8(finalOutputDir), { recursive: true });
3860
+ writeFileSync7(join8(finalOutputDir, "index.ts"), pluginCode, "utf-8");
3860
3861
  if (knowledgeMd) {
3861
- writeFileSync7(join7(finalOutputDir, "SITE_KNOWLEDGE.md"), knowledgeMd, "utf-8");
3862
+ writeFileSync7(join8(finalOutputDir, "SITE_KNOWLEDGE.md"), knowledgeMd, "utf-8");
3862
3863
  }
3863
3864
  process.stdout.write("\n");
3864
3865
  process.stdout.write("=== Plugin Generated ===\n");
@@ -4692,6 +4693,317 @@ ${icon} ${plugin}.${command}
4692
4693
  }
4693
4694
  }
4694
4695
 
4696
+ // src/console/serve.ts
4697
+ import { createServer } from "http";
4698
+
4699
+ // src/console/facade.ts
4700
+ import { readFileSync as readFileSync7 } from "fs";
4701
+ import { homedir as homedir3 } from "os";
4702
+ import { join as join7 } from "path";
4703
+ var DAEMON_PREVIEW_URL = "http://127.0.0.1:9224";
4704
+ var CHROME_BRIDGE_STATUS_URL = "http://127.0.0.1:9347/status";
4705
+ var LOGIN_BRIDGE_STATUS_URL = "http://127.0.0.1:9355/cookies";
4706
+ var CHROME_BRIDGE_META_PATH = join7(homedir3(), ".xbrowser", "chrome-bridge-ext.json");
4707
+ async function fetchJson(url, timeoutMs = 1200) {
4708
+ try {
4709
+ const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
4710
+ if (!response.ok) return null;
4711
+ return await response.json();
4712
+ } catch {
4713
+ return null;
4714
+ }
4715
+ }
4716
+ function asRecord(value) {
4717
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
4718
+ }
4719
+ async function buildEnvironments() {
4720
+ const daemonStatus = getDaemonProcessStatus();
4721
+ const daemonPingResult = await daemonPing().catch(() => null);
4722
+ const environments = [{
4723
+ id: "daemon",
4724
+ kind: "daemon",
4725
+ label: "Local daemon",
4726
+ status: daemonStatus.running && daemonPingResult?.ok ? "available" : "unavailable",
4727
+ detail: daemonStatus.running ? `PID ${daemonStatus.pid}, port ${daemonStatus.port}` : "daemon is not running",
4728
+ evidence: { ...daemonStatus, ping: daemonPingResult }
4729
+ }];
4730
+ const bridgeStatus = asRecord(await fetchJson(CHROME_BRIDGE_STATUS_URL));
4731
+ const bridgeRunning = bridgeStatus.running === true;
4732
+ const bridgeClients = Array.isArray(bridgeStatus.clients) ? bridgeStatus.clients.length : 0;
4733
+ let bridgeExtId = null;
4734
+ try {
4735
+ bridgeExtId = asRecord(JSON.parse(readFileSync7(CHROME_BRIDGE_META_PATH, "utf8"))).extId || null;
4736
+ } catch {
4737
+ }
4738
+ environments.push({
4739
+ id: "chrome-bridge",
4740
+ kind: "chrome_bridge",
4741
+ label: "Daily Chrome (extension bridge)",
4742
+ status: bridgeRunning ? bridgeClients > 0 ? "available" : "degraded" : "unavailable",
4743
+ detail: bridgeRunning ? `${bridgeClients} extension connection(s)` : "bridge server unavailable",
4744
+ evidence: { ...bridgeStatus, extId: bridgeExtId }
4745
+ });
4746
+ const loginStatus = await fetchJson(LOGIN_BRIDGE_STATUS_URL, 800);
4747
+ const loginCookies = Array.isArray(asRecord(loginStatus).cookies) ? asRecord(loginStatus).cookies.length : 0;
4748
+ environments.push({
4749
+ id: "login-bridge",
4750
+ kind: "login_bridge",
4751
+ label: "Login state archive",
4752
+ status: loginStatus === null ? "unavailable" : loginCookies > 0 ? "available" : "degraded",
4753
+ detail: loginStatus === null ? "bridge unavailable" : `${loginCookies} archived cookie(s)`,
4754
+ evidence: { cookieCount: loginCookies }
4755
+ });
4756
+ return environments;
4757
+ }
4758
+ function toConsoleSessions(raw) {
4759
+ return raw.map((session) => ({
4760
+ id: session.id,
4761
+ name: session.name,
4762
+ url: session.url,
4763
+ environmentId: "daemon",
4764
+ status: session.url ? "running" : "ready",
4765
+ previewUrl: `${DAEMON_PREVIEW_URL}/preview/${encodeURIComponent(session.name)}`
4766
+ }));
4767
+ }
4768
+ async function buildPlugins() {
4769
+ const [installed, loaderResult] = await Promise.all([
4770
+ new PluginInstaller().list().catch(() => []),
4771
+ getPluginLoader().then((loader) => loader.getCore().loader.getSites()).catch(() => [])
4772
+ ]);
4773
+ const loadedNames = /* @__PURE__ */ new Set();
4774
+ const loadedCommands = /* @__PURE__ */ new Map();
4775
+ for (const site of loaderResult) {
4776
+ const config = asRecord(site.config);
4777
+ const name = String(config.name ?? "");
4778
+ if (!name) continue;
4779
+ loadedNames.add(name);
4780
+ const commands = site.getAllCommands?.() ?? [];
4781
+ loadedCommands.set(name, commands.map((command) => String(command.name ?? "")).filter(Boolean));
4782
+ }
4783
+ const plugins = installed.map((installedPlugin) => {
4784
+ const metadata = installedPlugin.metadata;
4785
+ const shortName = String(metadata?.name ?? installedPlugin.name);
4786
+ return {
4787
+ id: installedPlugin.id,
4788
+ name: installedPlugin.name,
4789
+ displayName: String(metadata?.name ?? installedPlugin.name),
4790
+ source: installedPlugin.source,
4791
+ version: String(metadata?.version ?? "unknown"),
4792
+ description: String(metadata?.description ?? ""),
4793
+ tags: metadata?.tags ?? [],
4794
+ commands: loadedCommands.get(shortName) ?? metadata?.commands ?? [],
4795
+ sites: metadata?.sites ?? [],
4796
+ status: loadedNames.has(shortName) ? "loaded" : "installed"
4797
+ };
4798
+ });
4799
+ return plugins.sort((left, right) => left.displayName.localeCompare(right.displayName));
4800
+ }
4801
+ async function buildRecentEvidence(sessionName) {
4802
+ const [commandLog, network] = await Promise.all([
4803
+ forwardCommandLog(sessionName, 5).catch(() => null),
4804
+ forwardNetworkList(sessionName, { limit: 5 }).catch(() => null)
4805
+ ]);
4806
+ return { session: sessionName, commandLog, network };
4807
+ }
4808
+ async function buildConsoleOverview(options) {
4809
+ const [environments, rawSessions, plugins] = await Promise.all([
4810
+ buildEnvironments(),
4811
+ forwardSessionList().catch(() => []),
4812
+ buildPlugins()
4813
+ ]);
4814
+ const sessions = toConsoleSessions(rawSessions);
4815
+ const evidenceSession = options?.recentSession ?? sessions[0]?.name;
4816
+ const evidence = options?.includeEvidence !== false && evidenceSession ? await buildRecentEvidence(evidenceSession) : null;
4817
+ return {
4818
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
4819
+ readonly: true,
4820
+ environments,
4821
+ sessions,
4822
+ plugins,
4823
+ stats: {
4824
+ runningSessions: sessions.filter((session) => session.status === "running").length,
4825
+ availableEnvironments: environments.filter((environment) => environment.status === "available").length,
4826
+ installedPlugins: plugins.length,
4827
+ loadedPlugins: plugins.filter((plugin) => plugin.status === "loaded").length
4828
+ },
4829
+ ...evidence ? { evidence } : {}
4830
+ };
4831
+ }
4832
+
4833
+ // src/console/overview-template.ts
4834
+ function badge(status) {
4835
+ if (status === "available" || status === "running" || status === "loaded") {
4836
+ return '<span class="badge ok">available</span>';
4837
+ }
4838
+ if (status === "degraded" || status === "ready" || status === "installed") {
4839
+ return '<span class="badge warn">limited</span>';
4840
+ }
4841
+ return '<span class="badge bad">unavailable</span>';
4842
+ }
4843
+ function escapeHtml(value) {
4844
+ return String(value ?? "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
4845
+ }
4846
+ function renderOverviewHtml(overview) {
4847
+ const environmentRows = (overview.environments ?? []).map((environment) => `
4848
+ <tr>
4849
+ <td>${escapeHtml(environment.label)}</td>
4850
+ <td>${escapeHtml(environment.kind)}</td>
4851
+ <td>${badge(environment.status)}</td>
4852
+ <td>${escapeHtml(environment.detail)}</td>
4853
+ </tr>`).join("");
4854
+ const sessionRows = (overview.sessions ?? []).map((session) => `
4855
+ <tr>
4856
+ <td>${escapeHtml(session.name)}</td>
4857
+ <td>${escapeHtml(session.url ?? "-")}</td>
4858
+ <td>${badge(session.status)}</td>
4859
+ <td><a href="${escapeHtml(session.previewUrl)}" target="_blank" rel="noreferrer">preview</a></td>
4860
+ </tr>`).join("");
4861
+ const pluginRows = (overview.plugins ?? []).map((plugin) => `
4862
+ <tr>
4863
+ <td>${escapeHtml(plugin.displayName)}</td>
4864
+ <td>${escapeHtml(plugin.version)}</td>
4865
+ <td>${escapeHtml(plugin.source)}</td>
4866
+ <td>${badge(plugin.status)}</td>
4867
+ <td>${escapeHtml(plugin.commands.slice(0, 8).join(", ") || "-")}</td>
4868
+ </tr>`).join("");
4869
+ const evidence = overview.evidence ? `<pre>${escapeHtml(JSON.stringify(overview.evidence, null, 2))}</pre>` : '<p class="muted">No session selected for evidence.</p>';
4870
+ return `<!doctype html>
4871
+ <html lang="zh-CN">
4872
+ <head>
4873
+ <meta charset="utf-8">
4874
+ <meta name="viewport" content="width=device-width, initial-scale=1">
4875
+ <title>xBrowser Console - readonly overview</title>
4876
+ <style>
4877
+ :root { color-scheme: light; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, sans-serif; }
4878
+ body { margin: 0; background: #f6f8fb; color: #16202b; }
4879
+ main { max-width: 1180px; margin: 0 auto; padding: 32px 24px 56px; }
4880
+ h1 { font-size: 26px; margin: 0; }
4881
+ h2 { margin: 30px 0 12px; font-size: 17px; }
4882
+ p { line-height: 1.5; }
4883
+ .readonly { display: inline-block; margin-top: 8px; padding: 3px 8px; border: 1px solid #7da2c7; color: #21527d; border-radius: 999px; font-size: 12px; }
4884
+ .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 10px; margin-top: 20px; }
4885
+ .card { background: white; border: 1px solid #dbe2e9; border-radius: 12px; padding: 16px; }
4886
+ .card strong { display: block; font-size: 25px; margin-top: 5px; }
4887
+ table { width: 100%; border-collapse: collapse; background: white; border: 1px solid #dbe2e9; border-radius: 10px; overflow: hidden; }
4888
+ th, td { text-align: left; padding: 10px 12px; border-bottom: 1px solid #e7ecf1; font-size: 13px; }
4889
+ th { background: #22436b; color: white; font-weight: 600; }
4890
+ tr:last-child td { border-bottom: 0; }
4891
+ a { color: #21527d; }
4892
+ .badge { font-size: 11px; padding: 2px 7px; border-radius: 999px; }
4893
+ .ok { background: #e5f6ec; color: #176538; }
4894
+ .warn { background: #fff4dc; color: #84590c; }
4895
+ .bad { background: #fdeaea; color: #8b2020; }
4896
+ pre { background: #10202f; color: #dceaf5; padding: 14px; border-radius: 10px; overflow: auto; font-size: 12px; }
4897
+ .muted { color: #596877; }
4898
+ </style>
4899
+ </head>
4900
+ <body>
4901
+ <main>
4902
+ <h1>xBrowser Console</h1>
4903
+ <span class="readonly">Read-only prototype</span>
4904
+ <p>Generated at ${escapeHtml(overview.generatedAt)} \xB7 \u9636\u6BB5 0 / Console Facade \u603B\u89C8</p>
4905
+ <section class="cards">
4906
+ <div class="card"><span>\u8FD0\u884C\u4F1A\u8BDD</span><strong>${overview.stats.runningSessions}</strong></div>
4907
+ <div class="card"><span>\u53EF\u7528\u73AF\u5883</span><strong>${overview.stats.availableEnvironments}</strong></div>
4908
+ <div class="card"><span>\u5DF2\u5B89\u88C5\u63D2\u4EF6</span><strong>${overview.stats.installedPlugins}</strong></div>
4909
+ <div class="card"><span>\u5DF2\u52A0\u8F7D\u63D2\u4EF6</span><strong>${overview.stats.loadedPlugins}</strong></div>
4910
+ </section>
4911
+ <h2>\u7EDF\u4E00\u73AF\u5883\u72B6\u6001</h2>
4912
+ <table><thead><tr><th>\u73AF\u5883</th><th>\u7C7B\u578B</th><th>\u72B6\u6001</th><th>\u8BE6\u60C5</th></tr></thead><tbody>${environmentRows}</tbody></table>
4913
+ <h2>\u4F1A\u8BDD</h2>
4914
+ <table><thead><tr><th>\u540D\u79F0</th><th>\u5F53\u524D URL</th><th>\u72B6\u6001</th><th>\u753B\u9762</th></tr></thead><tbody>${sessionRows || '<tr><td colspan="4" class="muted">\u6682\u65E0\u8FD0\u884C\u4F1A\u8BDD</td></tr>'}</tbody></table>
4915
+ <h2>\u63D2\u4EF6</h2>
4916
+ <table><thead><tr><th>\u540D\u79F0</th><th>\u7248\u672C</th><th>\u6765\u6E90</th><th>\u72B6\u6001</th><th>\u547D\u4EE4</th></tr></thead><tbody>${pluginRows || '<tr><td colspan="5" class="muted">\u6682\u65E0\u5DF2\u5B89\u88C5\u63D2\u4EF6</td></tr>'}</tbody></table>
4917
+ <h2>\u6700\u8FD1\u8BC1\u636E</h2>
4918
+ ${evidence}
4919
+ </main>
4920
+ </body>
4921
+ </html>`;
4922
+ }
4923
+
4924
+ // src/console/serve.ts
4925
+ var DEFAULT_PORT = 9225;
4926
+ function parsePort(value) {
4927
+ const parsed = Number(value);
4928
+ return Number.isInteger(parsed) && parsed > 0 && parsed < 65536 ? parsed : DEFAULT_PORT;
4929
+ }
4930
+ function sendJson(response, statusCode, body) {
4931
+ response.writeHead(statusCode, { "Content-Type": "application/json; charset=utf-8" });
4932
+ response.end(JSON.stringify(body, null, 2));
4933
+ }
4934
+ function sendHtml(response, body) {
4935
+ response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
4936
+ response.end(body);
4937
+ }
4938
+ async function readJson(request) {
4939
+ const chunks = [];
4940
+ for await (const chunk of request) chunks.push(chunk);
4941
+ try {
4942
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
4943
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
4944
+ } catch {
4945
+ return {};
4946
+ }
4947
+ }
4948
+ async function handleConsoleServe(args, options, mode) {
4949
+ const port = parsePort(options.port ?? args[0]);
4950
+ const server = createServer(async (request, response) => {
4951
+ const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
4952
+ try {
4953
+ if (pathname === "/health") {
4954
+ sendJson(response, 200, { ok: true, readonly: true });
4955
+ return;
4956
+ }
4957
+ if (pathname !== "/" && pathname !== "/overview" && pathname !== "/api/overview") {
4958
+ sendJson(response, 404, { error: "NOT_FOUND", readonly: true });
4959
+ return;
4960
+ }
4961
+ const body = request.method === "POST" ? await readJson(request) : {};
4962
+ const overview = await buildConsoleOverview({
4963
+ recentSession: typeof body.recentSession === "string" ? body.recentSession : void 0,
4964
+ includeEvidence: body.includeEvidence !== false
4965
+ });
4966
+ if (pathname === "/api/overview" || request.headers.accept?.includes("application/json")) {
4967
+ sendJson(response, 200, overview);
4968
+ } else {
4969
+ sendHtml(response, renderOverviewHtml(overview));
4970
+ }
4971
+ } catch (error) {
4972
+ sendJson(response, 500, {
4973
+ error: "CONSOLE_FACADE_ERROR",
4974
+ message: error instanceof Error ? error.message : String(error),
4975
+ readonly: true
4976
+ });
4977
+ }
4978
+ });
4979
+ const stop = () => server.close(() => process.exit(0));
4980
+ process.once("SIGINT", stop);
4981
+ process.once("SIGTERM", stop);
4982
+ server.listen(port, "127.0.0.1", () => {
4983
+ const output = {
4984
+ ok: true,
4985
+ readonly: true,
4986
+ url: `http://127.0.0.1:${port}`,
4987
+ endpoints: ["GET /", "GET /overview", "GET|POST /api/overview", "GET /health"]
4988
+ };
4989
+ if (mode === "json") outputResult(output, mode);
4990
+ else {
4991
+ console.log(`
4992
+ Console Facade (readonly): ${output.url}`);
4993
+ console.log(" Endpoints: /overview, /api/overview, /health");
4994
+ console.log(" Press Ctrl+C to stop\n");
4995
+ }
4996
+ });
4997
+ if (process.env.NODE_ENV === "test") {
4998
+ handleConsoleServe.__serverForTests = server;
4999
+ }
5000
+ server.on("error", (error) => {
5001
+ if (error.code === "EADDRINUSE") outputError(`Console port ${port} is already in use`);
5002
+ else outputError(error.message);
5003
+ process.exit(1);
5004
+ });
5005
+ }
5006
+
4695
5007
  // src/cli/help.ts
4696
5008
  function showMainHelp() {
4697
5009
  console.log(`
@@ -4791,6 +5103,7 @@ Commands:
4791
5103
  remote <url> [command] [--token <t>] Execute on remote server
4792
5104
  run <file> Execute commands from file
4793
5105
  viewer [--name <n>] Generate viewer URL
5106
+ console-panel [--port <n>] Readonly Console Facade overview
4794
5107
  help Show this help
4795
5108
  --version Show version
4796
5109
  Plugin Commands:
@@ -5251,12 +5564,13 @@ var SUBCOMMAND_HELP = {
5251
5564
  filter: "filter <file> [--include <type>] [--exclude <type>]",
5252
5565
  test: "test <name> [--cdp <endpoint>]",
5253
5566
  viewer: "viewer [--session <name>]",
5567
+ "console-panel": "console-panel [--port <port>]",
5254
5568
  kill: "kill [--all]",
5255
5569
  net: "net [--cdp <endpoint>]"
5256
5570
  };
5257
5571
 
5258
5572
  // src/server/http-server.ts
5259
- import { createServer } from "http";
5573
+ import { createServer as createServer2 } from "http";
5260
5574
 
5261
5575
  // src/server/auth.ts
5262
5576
  function resolveTokens(configTokens) {
@@ -5637,7 +5951,7 @@ var HTTPServer = class {
5637
5951
  const authRequired = isAuthRequired(this.validTokens);
5638
5952
  const tokens = this.validTokens;
5639
5953
  const corsOrigins = this.corsOrigins;
5640
- this.server = createServer((req, res) => {
5954
+ this.server = createServer2((req, res) => {
5641
5955
  const authFn = authRequired ? (authHeader) => validateAuth(authHeader, tokens) : void 0;
5642
5956
  handleRequest(req, res, authFn, corsOrigins).catch((err) => {
5643
5957
  const message = err instanceof Error ? err.message : String(err);
@@ -5823,7 +6137,7 @@ async function handleRemote(args, options, mode) {
5823
6137
  }
5824
6138
  }
5825
6139
  async function startMcpServer() {
5826
- const { startMcpStdio } = await import("./server-QI3UIB4Y.js");
6140
+ const { startMcpStdio } = await import("./server-6CTC3RHV.js");
5827
6141
  startMcpStdio();
5828
6142
  }
5829
6143
 
@@ -5898,6 +6212,9 @@ async function dispatchSubcommand(request) {
5898
6212
  case "net":
5899
6213
  await handleNetCommand(cmdArgs, options, mode, sessionName);
5900
6214
  return true;
6215
+ case "console-panel":
6216
+ await handleConsoleServe(cmdArgs, options, mode);
6217
+ return true;
5901
6218
  default:
5902
6219
  return false;
5903
6220
  }
@@ -6138,7 +6455,7 @@ Run "xbrowser ${command} ${subCommand} --help" to see available parameters.`
6138
6455
  const targetPage = pages[cmdTabIndex];
6139
6456
  await targetPage.bringToFront().catch(() => {
6140
6457
  });
6141
- const { setActivePage } = await import("./browser-CE4GTZRO.js");
6458
+ const { setActivePage } = await import("./browser-3LBSVDSS.js");
6142
6459
  setActivePage(session, targetPage);
6143
6460
  }
6144
6461
  }
@@ -6394,9 +6711,9 @@ async function main() {
6394
6711
  exitCode = 1;
6395
6712
  } finally {
6396
6713
  const command = process.argv[2];
6397
- const isLongRunning = command === "preview" || command === "serve" || command === "mcp";
6714
+ const isLongRunning = command === "preview" || command === "serve" || command === "mcp" || command === "console-panel";
6398
6715
  if (!isLongRunning) {
6399
- const { ensureProcessCanExit } = await import("./browser-CE4GTZRO.js");
6716
+ const { ensureProcessCanExit } = await import("./browser-3LBSVDSS.js");
6400
6717
  await ensureProcessCanExit().catch(() => {
6401
6718
  });
6402
6719
  process.exit(process.exitCode || exitCode);
@@ -39,10 +39,10 @@ import {
39
39
  resolveLaunchOpts,
40
40
  saveSessionDiskMeta,
41
41
  setActivePage
42
- } from "./chunk-JO6WHY3D.js";
42
+ } from "./chunk-OVAUGFM6.js";
43
43
  import {
44
44
  createRuleEngine
45
- } from "./chunk-NDBOLP5Z.js";
45
+ } from "./chunk-H25ECCYJ.js";
46
46
  import {
47
47
  queryJS
48
48
  } from "./chunk-A7NEA4PA.js";
@@ -8610,7 +8610,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8610
8610
  }
8611
8611
  let targetPageOverride = null;
8612
8612
  if (_target && extraOpts?.cdpEndpoint) {
8613
- const { findTargetPage } = await import("./browser-F4X2ND5E.js");
8613
+ const { findTargetPage } = await import("./browser-23BMBCH2.js");
8614
8614
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
8615
8615
  if (!targetPageOverride) {
8616
8616
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -10197,7 +10197,7 @@ function createRPCHandler() {
10197
10197
  if (isNewFormat) {
10198
10198
  try {
10199
10199
  const replayErrors = [];
10200
- const { SessionReplayer } = await import("./session-replayer-SUWCEU5L.js");
10200
+ const { SessionReplayer } = await import("./session-replayer-IGRRA2QC.js");
10201
10201
  const replayer = new SessionReplayer({
10202
10202
  page: session.page,
10203
10203
  stepDelay: slowMo * 500,
package/dist/index.js CHANGED
@@ -48,7 +48,7 @@ import {
48
48
  splitCommand,
49
49
  waitForAIResponse,
50
50
  waitForPage
51
- } from "./chunk-Z6NMBZK3.js";
51
+ } from "./chunk-AKT3WLZM.js";
52
52
  import {
53
53
  SessionRecorder,
54
54
  readMarkdownSummary
@@ -64,9 +64,10 @@ import {
64
64
  getBrowser,
65
65
  resetForTesting,
66
66
  saveSessionDiskMeta
67
- } from "./chunk-BM6DDHA2.js";
67
+ } from "./chunk-DDHHVII7.js";
68
68
  import "./chunk-JKVUFP3G.js";
69
69
  import {
70
+ daemonPing,
70
71
  forwardCommandLog,
71
72
  forwardExec,
72
73
  forwardNetworkAnalyze,
@@ -122,7 +123,7 @@ import {
122
123
  generateJSScript,
123
124
  generatePythonScript
124
125
  } from "./chunk-ETCO4SNK.js";
125
- import "./chunk-VYGK4X33.js";
126
+ import "./chunk-YX5KVWGX.js";
126
127
  import "./chunk-SMYSNO4M.js";
127
128
  import "./chunk-2KPI5GKP.js";
128
129
  import {
@@ -3311,8 +3312,8 @@ async function handlePlugin(args, options, mode) {
3311
3312
  } catch {
3312
3313
  }
3313
3314
  try {
3314
- const { daemonPing } = await import("./daemon-client-HEGAXWGK.js");
3315
- if (await daemonPing()) {
3315
+ const { daemonPing: daemonPing2 } = await import("./daemon-client-HEGAXWGK.js");
3316
+ if (await daemonPing2()) {
3316
3317
  await fetch("http://localhost:9224/rpc", {
3317
3318
  method: "POST",
3318
3319
  headers: { "Content-Type": "application/json" },
@@ -3934,7 +3935,7 @@ async function handleGeneratePlugin(sessionName, pluginName, outputDir) {
3934
3935
  const { SessionRecorder: SessionRecorder2 } = await import("./session-recorder-RUNQOJ7T.js");
3935
3936
  const { readSiteKnowledge: readSiteKnowledge2, toMarkdown } = await import("./site-knowledge-SYC6VCDB.js");
3936
3937
  const { mkdirSync: mkdirSync7, writeFileSync: writeFileSync8 } = await import("fs");
3937
- const { join: join8 } = await import("path");
3938
+ const { join: join9 } = await import("path");
3938
3939
  const data = SessionRecorder2.readData(sessionName);
3939
3940
  if (!data) {
3940
3941
  outputError(`No recording found for session "${sessionName}". Run \`xbrowser record stop --session ${sessionName}\` first.`);
@@ -3946,14 +3947,14 @@ async function handleGeneratePlugin(sessionName, pluginName, outputDir) {
3946
3947
  } catch {
3947
3948
  }
3948
3949
  const finalPluginName = pluginName || domain.split(".")[0] || "my-site";
3949
- const finalOutputDir = outputDir || join8(process.cwd(), ".xcli", "plugins", finalPluginName);
3950
+ const finalOutputDir = outputDir || join9(process.cwd(), ".xcli", "plugins", finalPluginName);
3950
3951
  const knowledge = readSiteKnowledge2(domain);
3951
3952
  const knowledgeMd = knowledge ? toMarkdown(knowledge) : "";
3952
3953
  const pluginCode = generatePluginCode(finalPluginName, domain, data, knowledgeMd);
3953
- mkdirSync7(join8(finalOutputDir), { recursive: true });
3954
- writeFileSync8(join8(finalOutputDir, "index.ts"), pluginCode, "utf-8");
3954
+ mkdirSync7(join9(finalOutputDir), { recursive: true });
3955
+ writeFileSync8(join9(finalOutputDir, "index.ts"), pluginCode, "utf-8");
3955
3956
  if (knowledgeMd) {
3956
- writeFileSync8(join8(finalOutputDir, "SITE_KNOWLEDGE.md"), knowledgeMd, "utf-8");
3957
+ writeFileSync8(join9(finalOutputDir, "SITE_KNOWLEDGE.md"), knowledgeMd, "utf-8");
3957
3958
  }
3958
3959
  process.stdout.write("\n");
3959
3960
  process.stdout.write("=== Plugin Generated ===\n");
@@ -4787,6 +4788,317 @@ ${icon} ${plugin}.${command}
4787
4788
  }
4788
4789
  }
4789
4790
 
4791
+ // src/console/serve.ts
4792
+ import { createServer } from "http";
4793
+
4794
+ // src/console/facade.ts
4795
+ import { readFileSync as readFileSync7 } from "fs";
4796
+ import { homedir as homedir3 } from "os";
4797
+ import { join as join7 } from "path";
4798
+ var DAEMON_PREVIEW_URL = "http://127.0.0.1:9224";
4799
+ var CHROME_BRIDGE_STATUS_URL = "http://127.0.0.1:9347/status";
4800
+ var LOGIN_BRIDGE_STATUS_URL = "http://127.0.0.1:9355/cookies";
4801
+ var CHROME_BRIDGE_META_PATH = join7(homedir3(), ".xbrowser", "chrome-bridge-ext.json");
4802
+ async function fetchJson(url, timeoutMs = 1200) {
4803
+ try {
4804
+ const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
4805
+ if (!response.ok) return null;
4806
+ return await response.json();
4807
+ } catch {
4808
+ return null;
4809
+ }
4810
+ }
4811
+ function asRecord(value) {
4812
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
4813
+ }
4814
+ async function buildEnvironments() {
4815
+ const daemonStatus = getDaemonProcessStatus();
4816
+ const daemonPingResult = await daemonPing().catch(() => null);
4817
+ const environments = [{
4818
+ id: "daemon",
4819
+ kind: "daemon",
4820
+ label: "Local daemon",
4821
+ status: daemonStatus.running && daemonPingResult?.ok ? "available" : "unavailable",
4822
+ detail: daemonStatus.running ? `PID ${daemonStatus.pid}, port ${daemonStatus.port}` : "daemon is not running",
4823
+ evidence: { ...daemonStatus, ping: daemonPingResult }
4824
+ }];
4825
+ const bridgeStatus = asRecord(await fetchJson(CHROME_BRIDGE_STATUS_URL));
4826
+ const bridgeRunning = bridgeStatus.running === true;
4827
+ const bridgeClients = Array.isArray(bridgeStatus.clients) ? bridgeStatus.clients.length : 0;
4828
+ let bridgeExtId = null;
4829
+ try {
4830
+ bridgeExtId = asRecord(JSON.parse(readFileSync7(CHROME_BRIDGE_META_PATH, "utf8"))).extId || null;
4831
+ } catch {
4832
+ }
4833
+ environments.push({
4834
+ id: "chrome-bridge",
4835
+ kind: "chrome_bridge",
4836
+ label: "Daily Chrome (extension bridge)",
4837
+ status: bridgeRunning ? bridgeClients > 0 ? "available" : "degraded" : "unavailable",
4838
+ detail: bridgeRunning ? `${bridgeClients} extension connection(s)` : "bridge server unavailable",
4839
+ evidence: { ...bridgeStatus, extId: bridgeExtId }
4840
+ });
4841
+ const loginStatus = await fetchJson(LOGIN_BRIDGE_STATUS_URL, 800);
4842
+ const loginCookies = Array.isArray(asRecord(loginStatus).cookies) ? asRecord(loginStatus).cookies.length : 0;
4843
+ environments.push({
4844
+ id: "login-bridge",
4845
+ kind: "login_bridge",
4846
+ label: "Login state archive",
4847
+ status: loginStatus === null ? "unavailable" : loginCookies > 0 ? "available" : "degraded",
4848
+ detail: loginStatus === null ? "bridge unavailable" : `${loginCookies} archived cookie(s)`,
4849
+ evidence: { cookieCount: loginCookies }
4850
+ });
4851
+ return environments;
4852
+ }
4853
+ function toConsoleSessions(raw) {
4854
+ return raw.map((session) => ({
4855
+ id: session.id,
4856
+ name: session.name,
4857
+ url: session.url,
4858
+ environmentId: "daemon",
4859
+ status: session.url ? "running" : "ready",
4860
+ previewUrl: `${DAEMON_PREVIEW_URL}/preview/${encodeURIComponent(session.name)}`
4861
+ }));
4862
+ }
4863
+ async function buildPlugins() {
4864
+ const [installed, loaderResult] = await Promise.all([
4865
+ new PluginInstaller().list().catch(() => []),
4866
+ getPluginLoader().then((loader) => loader.getCore().loader.getSites()).catch(() => [])
4867
+ ]);
4868
+ const loadedNames = /* @__PURE__ */ new Set();
4869
+ const loadedCommands = /* @__PURE__ */ new Map();
4870
+ for (const site of loaderResult) {
4871
+ const config = asRecord(site.config);
4872
+ const name = String(config.name ?? "");
4873
+ if (!name) continue;
4874
+ loadedNames.add(name);
4875
+ const commands = site.getAllCommands?.() ?? [];
4876
+ loadedCommands.set(name, commands.map((command) => String(command.name ?? "")).filter(Boolean));
4877
+ }
4878
+ const plugins = installed.map((installedPlugin) => {
4879
+ const metadata = installedPlugin.metadata;
4880
+ const shortName = String(metadata?.name ?? installedPlugin.name);
4881
+ return {
4882
+ id: installedPlugin.id,
4883
+ name: installedPlugin.name,
4884
+ displayName: String(metadata?.name ?? installedPlugin.name),
4885
+ source: installedPlugin.source,
4886
+ version: String(metadata?.version ?? "unknown"),
4887
+ description: String(metadata?.description ?? ""),
4888
+ tags: metadata?.tags ?? [],
4889
+ commands: loadedCommands.get(shortName) ?? metadata?.commands ?? [],
4890
+ sites: metadata?.sites ?? [],
4891
+ status: loadedNames.has(shortName) ? "loaded" : "installed"
4892
+ };
4893
+ });
4894
+ return plugins.sort((left, right) => left.displayName.localeCompare(right.displayName));
4895
+ }
4896
+ async function buildRecentEvidence(sessionName) {
4897
+ const [commandLog, network] = await Promise.all([
4898
+ forwardCommandLog(sessionName, 5).catch(() => null),
4899
+ forwardNetworkList(sessionName, { limit: 5 }).catch(() => null)
4900
+ ]);
4901
+ return { session: sessionName, commandLog, network };
4902
+ }
4903
+ async function buildConsoleOverview(options) {
4904
+ const [environments, rawSessions, plugins] = await Promise.all([
4905
+ buildEnvironments(),
4906
+ forwardSessionList().catch(() => []),
4907
+ buildPlugins()
4908
+ ]);
4909
+ const sessions = toConsoleSessions(rawSessions);
4910
+ const evidenceSession = options?.recentSession ?? sessions[0]?.name;
4911
+ const evidence = options?.includeEvidence !== false && evidenceSession ? await buildRecentEvidence(evidenceSession) : null;
4912
+ return {
4913
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
4914
+ readonly: true,
4915
+ environments,
4916
+ sessions,
4917
+ plugins,
4918
+ stats: {
4919
+ runningSessions: sessions.filter((session) => session.status === "running").length,
4920
+ availableEnvironments: environments.filter((environment) => environment.status === "available").length,
4921
+ installedPlugins: plugins.length,
4922
+ loadedPlugins: plugins.filter((plugin) => plugin.status === "loaded").length
4923
+ },
4924
+ ...evidence ? { evidence } : {}
4925
+ };
4926
+ }
4927
+
4928
+ // src/console/overview-template.ts
4929
+ function badge(status) {
4930
+ if (status === "available" || status === "running" || status === "loaded") {
4931
+ return '<span class="badge ok">available</span>';
4932
+ }
4933
+ if (status === "degraded" || status === "ready" || status === "installed") {
4934
+ return '<span class="badge warn">limited</span>';
4935
+ }
4936
+ return '<span class="badge bad">unavailable</span>';
4937
+ }
4938
+ function escapeHtml(value) {
4939
+ return String(value ?? "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
4940
+ }
4941
+ function renderOverviewHtml(overview) {
4942
+ const environmentRows = (overview.environments ?? []).map((environment) => `
4943
+ <tr>
4944
+ <td>${escapeHtml(environment.label)}</td>
4945
+ <td>${escapeHtml(environment.kind)}</td>
4946
+ <td>${badge(environment.status)}</td>
4947
+ <td>${escapeHtml(environment.detail)}</td>
4948
+ </tr>`).join("");
4949
+ const sessionRows = (overview.sessions ?? []).map((session) => `
4950
+ <tr>
4951
+ <td>${escapeHtml(session.name)}</td>
4952
+ <td>${escapeHtml(session.url ?? "-")}</td>
4953
+ <td>${badge(session.status)}</td>
4954
+ <td><a href="${escapeHtml(session.previewUrl)}" target="_blank" rel="noreferrer">preview</a></td>
4955
+ </tr>`).join("");
4956
+ const pluginRows = (overview.plugins ?? []).map((plugin) => `
4957
+ <tr>
4958
+ <td>${escapeHtml(plugin.displayName)}</td>
4959
+ <td>${escapeHtml(plugin.version)}</td>
4960
+ <td>${escapeHtml(plugin.source)}</td>
4961
+ <td>${badge(plugin.status)}</td>
4962
+ <td>${escapeHtml(plugin.commands.slice(0, 8).join(", ") || "-")}</td>
4963
+ </tr>`).join("");
4964
+ const evidence = overview.evidence ? `<pre>${escapeHtml(JSON.stringify(overview.evidence, null, 2))}</pre>` : '<p class="muted">No session selected for evidence.</p>';
4965
+ return `<!doctype html>
4966
+ <html lang="zh-CN">
4967
+ <head>
4968
+ <meta charset="utf-8">
4969
+ <meta name="viewport" content="width=device-width, initial-scale=1">
4970
+ <title>xBrowser Console - readonly overview</title>
4971
+ <style>
4972
+ :root { color-scheme: light; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, sans-serif; }
4973
+ body { margin: 0; background: #f6f8fb; color: #16202b; }
4974
+ main { max-width: 1180px; margin: 0 auto; padding: 32px 24px 56px; }
4975
+ h1 { font-size: 26px; margin: 0; }
4976
+ h2 { margin: 30px 0 12px; font-size: 17px; }
4977
+ p { line-height: 1.5; }
4978
+ .readonly { display: inline-block; margin-top: 8px; padding: 3px 8px; border: 1px solid #7da2c7; color: #21527d; border-radius: 999px; font-size: 12px; }
4979
+ .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 10px; margin-top: 20px; }
4980
+ .card { background: white; border: 1px solid #dbe2e9; border-radius: 12px; padding: 16px; }
4981
+ .card strong { display: block; font-size: 25px; margin-top: 5px; }
4982
+ table { width: 100%; border-collapse: collapse; background: white; border: 1px solid #dbe2e9; border-radius: 10px; overflow: hidden; }
4983
+ th, td { text-align: left; padding: 10px 12px; border-bottom: 1px solid #e7ecf1; font-size: 13px; }
4984
+ th { background: #22436b; color: white; font-weight: 600; }
4985
+ tr:last-child td { border-bottom: 0; }
4986
+ a { color: #21527d; }
4987
+ .badge { font-size: 11px; padding: 2px 7px; border-radius: 999px; }
4988
+ .ok { background: #e5f6ec; color: #176538; }
4989
+ .warn { background: #fff4dc; color: #84590c; }
4990
+ .bad { background: #fdeaea; color: #8b2020; }
4991
+ pre { background: #10202f; color: #dceaf5; padding: 14px; border-radius: 10px; overflow: auto; font-size: 12px; }
4992
+ .muted { color: #596877; }
4993
+ </style>
4994
+ </head>
4995
+ <body>
4996
+ <main>
4997
+ <h1>xBrowser Console</h1>
4998
+ <span class="readonly">Read-only prototype</span>
4999
+ <p>Generated at ${escapeHtml(overview.generatedAt)} \xB7 \u9636\u6BB5 0 / Console Facade \u603B\u89C8</p>
5000
+ <section class="cards">
5001
+ <div class="card"><span>\u8FD0\u884C\u4F1A\u8BDD</span><strong>${overview.stats.runningSessions}</strong></div>
5002
+ <div class="card"><span>\u53EF\u7528\u73AF\u5883</span><strong>${overview.stats.availableEnvironments}</strong></div>
5003
+ <div class="card"><span>\u5DF2\u5B89\u88C5\u63D2\u4EF6</span><strong>${overview.stats.installedPlugins}</strong></div>
5004
+ <div class="card"><span>\u5DF2\u52A0\u8F7D\u63D2\u4EF6</span><strong>${overview.stats.loadedPlugins}</strong></div>
5005
+ </section>
5006
+ <h2>\u7EDF\u4E00\u73AF\u5883\u72B6\u6001</h2>
5007
+ <table><thead><tr><th>\u73AF\u5883</th><th>\u7C7B\u578B</th><th>\u72B6\u6001</th><th>\u8BE6\u60C5</th></tr></thead><tbody>${environmentRows}</tbody></table>
5008
+ <h2>\u4F1A\u8BDD</h2>
5009
+ <table><thead><tr><th>\u540D\u79F0</th><th>\u5F53\u524D URL</th><th>\u72B6\u6001</th><th>\u753B\u9762</th></tr></thead><tbody>${sessionRows || '<tr><td colspan="4" class="muted">\u6682\u65E0\u8FD0\u884C\u4F1A\u8BDD</td></tr>'}</tbody></table>
5010
+ <h2>\u63D2\u4EF6</h2>
5011
+ <table><thead><tr><th>\u540D\u79F0</th><th>\u7248\u672C</th><th>\u6765\u6E90</th><th>\u72B6\u6001</th><th>\u547D\u4EE4</th></tr></thead><tbody>${pluginRows || '<tr><td colspan="5" class="muted">\u6682\u65E0\u5DF2\u5B89\u88C5\u63D2\u4EF6</td></tr>'}</tbody></table>
5012
+ <h2>\u6700\u8FD1\u8BC1\u636E</h2>
5013
+ ${evidence}
5014
+ </main>
5015
+ </body>
5016
+ </html>`;
5017
+ }
5018
+
5019
+ // src/console/serve.ts
5020
+ var DEFAULT_PORT = 9225;
5021
+ function parsePort(value) {
5022
+ const parsed = Number(value);
5023
+ return Number.isInteger(parsed) && parsed > 0 && parsed < 65536 ? parsed : DEFAULT_PORT;
5024
+ }
5025
+ function sendJson(response, statusCode, body) {
5026
+ response.writeHead(statusCode, { "Content-Type": "application/json; charset=utf-8" });
5027
+ response.end(JSON.stringify(body, null, 2));
5028
+ }
5029
+ function sendHtml(response, body) {
5030
+ response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
5031
+ response.end(body);
5032
+ }
5033
+ async function readJson(request) {
5034
+ const chunks = [];
5035
+ for await (const chunk of request) chunks.push(chunk);
5036
+ try {
5037
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
5038
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
5039
+ } catch {
5040
+ return {};
5041
+ }
5042
+ }
5043
+ async function handleConsoleServe(args, options, mode) {
5044
+ const port = parsePort(options.port ?? args[0]);
5045
+ const server = createServer(async (request, response) => {
5046
+ const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
5047
+ try {
5048
+ if (pathname === "/health") {
5049
+ sendJson(response, 200, { ok: true, readonly: true });
5050
+ return;
5051
+ }
5052
+ if (pathname !== "/" && pathname !== "/overview" && pathname !== "/api/overview") {
5053
+ sendJson(response, 404, { error: "NOT_FOUND", readonly: true });
5054
+ return;
5055
+ }
5056
+ const body = request.method === "POST" ? await readJson(request) : {};
5057
+ const overview = await buildConsoleOverview({
5058
+ recentSession: typeof body.recentSession === "string" ? body.recentSession : void 0,
5059
+ includeEvidence: body.includeEvidence !== false
5060
+ });
5061
+ if (pathname === "/api/overview" || request.headers.accept?.includes("application/json")) {
5062
+ sendJson(response, 200, overview);
5063
+ } else {
5064
+ sendHtml(response, renderOverviewHtml(overview));
5065
+ }
5066
+ } catch (error) {
5067
+ sendJson(response, 500, {
5068
+ error: "CONSOLE_FACADE_ERROR",
5069
+ message: error instanceof Error ? error.message : String(error),
5070
+ readonly: true
5071
+ });
5072
+ }
5073
+ });
5074
+ const stop = () => server.close(() => process.exit(0));
5075
+ process.once("SIGINT", stop);
5076
+ process.once("SIGTERM", stop);
5077
+ server.listen(port, "127.0.0.1", () => {
5078
+ const output = {
5079
+ ok: true,
5080
+ readonly: true,
5081
+ url: `http://127.0.0.1:${port}`,
5082
+ endpoints: ["GET /", "GET /overview", "GET|POST /api/overview", "GET /health"]
5083
+ };
5084
+ if (mode === "json") outputResult(output, mode);
5085
+ else {
5086
+ console.log(`
5087
+ Console Facade (readonly): ${output.url}`);
5088
+ console.log(" Endpoints: /overview, /api/overview, /health");
5089
+ console.log(" Press Ctrl+C to stop\n");
5090
+ }
5091
+ });
5092
+ if (process.env.NODE_ENV === "test") {
5093
+ handleConsoleServe.__serverForTests = server;
5094
+ }
5095
+ server.on("error", (error) => {
5096
+ if (error.code === "EADDRINUSE") outputError(`Console port ${port} is already in use`);
5097
+ else outputError(error.message);
5098
+ process.exit(1);
5099
+ });
5100
+ }
5101
+
4790
5102
  // src/cli/help.ts
4791
5103
  function showMainHelp() {
4792
5104
  console.log(`
@@ -4886,6 +5198,7 @@ Commands:
4886
5198
  remote <url> [command] [--token <t>] Execute on remote server
4887
5199
  run <file> Execute commands from file
4888
5200
  viewer [--name <n>] Generate viewer URL
5201
+ console-panel [--port <n>] Readonly Console Facade overview
4889
5202
  help Show this help
4890
5203
  --version Show version
4891
5204
  Plugin Commands:
@@ -5346,12 +5659,13 @@ var SUBCOMMAND_HELP = {
5346
5659
  filter: "filter <file> [--include <type>] [--exclude <type>]",
5347
5660
  test: "test <name> [--cdp <endpoint>]",
5348
5661
  viewer: "viewer [--session <name>]",
5662
+ "console-panel": "console-panel [--port <port>]",
5349
5663
  kill: "kill [--all]",
5350
5664
  net: "net [--cdp <endpoint>]"
5351
5665
  };
5352
5666
 
5353
5667
  // src/server/http-server.ts
5354
- import { createServer } from "http";
5668
+ import { createServer as createServer2 } from "http";
5355
5669
 
5356
5670
  // src/server/auth.ts
5357
5671
  function resolveTokens(configTokens) {
@@ -5732,7 +6046,7 @@ var HTTPServer = class {
5732
6046
  const authRequired = isAuthRequired(this.validTokens);
5733
6047
  const tokens = this.validTokens;
5734
6048
  const corsOrigins = this.corsOrigins;
5735
- this.server = createServer((req, res) => {
6049
+ this.server = createServer2((req, res) => {
5736
6050
  const authFn = authRequired ? (authHeader) => validateAuth(authHeader, tokens) : void 0;
5737
6051
  handleRequest(req, res, authFn, corsOrigins).catch((err) => {
5738
6052
  const message = err instanceof Error ? err.message : String(err);
@@ -5918,7 +6232,7 @@ async function handleRemote(args, options, mode) {
5918
6232
  }
5919
6233
  }
5920
6234
  async function startMcpServer() {
5921
- const { startMcpStdio } = await import("./server-OZZ7NTCX.js");
6235
+ const { startMcpStdio } = await import("./server-5JHB4TML.js");
5922
6236
  startMcpStdio();
5923
6237
  }
5924
6238
 
@@ -5993,6 +6307,9 @@ async function dispatchSubcommand(request) {
5993
6307
  case "net":
5994
6308
  await handleNetCommand(cmdArgs, options, mode, sessionName);
5995
6309
  return true;
6310
+ case "console-panel":
6311
+ await handleConsoleServe(cmdArgs, options, mode);
6312
+ return true;
5996
6313
  default:
5997
6314
  return false;
5998
6315
  }
@@ -6233,7 +6550,7 @@ Run "xbrowser ${command} ${subCommand} --help" to see available parameters.`
6233
6550
  const targetPage = pages[cmdTabIndex];
6234
6551
  await targetPage.bringToFront().catch(() => {
6235
6552
  });
6236
- const { setActivePage } = await import("./browser-JPTQ5JA2.js");
6553
+ const { setActivePage } = await import("./browser-D7RFPTD4.js");
6237
6554
  setActivePage(session, targetPage);
6238
6555
  }
6239
6556
  }
@@ -7899,12 +8216,12 @@ var FileListHandler = class {
7899
8216
  const msg = ctx.message;
7900
8217
  try {
7901
8218
  const { readdirSync: readdirSync3, statSync } = await import("fs");
7902
- const { join: join8, resolve: resolve8 } = await import("path");
8219
+ const { join: join9, resolve: resolve8 } = await import("path");
7903
8220
  const targetPath = resolve8(msg.path);
7904
8221
  const entries = readdirSync3(targetPath);
7905
8222
  const files = entries.map((name) => {
7906
8223
  try {
7907
- const stat = statSync(join8(targetPath, name));
8224
+ const stat = statSync(join9(targetPath, name));
7908
8225
  return { name, isDir: stat.isDirectory(), size: stat.size, modified: stat.mtime.toISOString() };
7909
8226
  } catch {
7910
8227
  return { name, isDir: false, size: 0, modified: "" };
@@ -7921,10 +8238,10 @@ var FileDownloadHandler = class {
7921
8238
  async handle(ctx) {
7922
8239
  const msg = ctx.message;
7923
8240
  try {
7924
- const { readFileSync: readFileSync8 } = await import("fs");
8241
+ const { readFileSync: readFileSync9 } = await import("fs");
7925
8242
  const { resolve: resolve8, basename: basename3 } = await import("path");
7926
8243
  const targetPath = resolve8(msg.path);
7927
- const data = readFileSync8(targetPath);
8244
+ const data = readFileSync9(targetPath);
7928
8245
  const base64 = data.toString("base64");
7929
8246
  const ext = targetPath.split(".").pop()?.toLowerCase() || "";
7930
8247
  const mimeMap = {
@@ -9507,7 +9824,7 @@ var DataCollector = class {
9507
9824
  return results;
9508
9825
  }
9509
9826
  async createBrowserContext() {
9510
- const { launch } = await import("./cdp-driver-NGTMK5ID.js");
9827
+ const { launch } = await import("./cdp-driver-GE6Y6LPI.js");
9511
9828
  const { browser } = await launch({
9512
9829
  headless: true,
9513
9830
  args: ["--no-sandbox", "--disable-setuid-sandbox"]
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  executeChain,
3
3
  executeCommand
4
- } from "./chunk-Z6NMBZK3.js";
5
- import "./chunk-BM6DDHA2.js";
4
+ } from "./chunk-AKT3WLZM.js";
5
+ import "./chunk-DDHHVII7.js";
6
6
  import "./chunk-JKVUFP3G.js";
7
7
  import "./chunk-3OD76SUE.js";
8
8
  import "./chunk-ZTHE5RBZ.js";
9
9
  import "./chunk-Q2DFJQGS.js";
10
- import "./chunk-VYGK4X33.js";
10
+ import "./chunk-YX5KVWGX.js";
11
11
  import "./chunk-SMYSNO4M.js";
12
12
  import "./chunk-2KPI5GKP.js";
13
13
  import "./chunk-GDKLH7ZY.js";
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  executeChain,
3
3
  executeCommand
4
- } from "./chunk-G47VJ5OR.js";
4
+ } from "./chunk-ACPMC47K.js";
5
5
  import "./chunk-JKVUFP3G.js";
6
6
  import "./chunk-3OD76SUE.js";
7
7
  import "./chunk-ZTHE5RBZ.js";
8
8
  import "./chunk-Q2DFJQGS.js";
9
- import "./chunk-NBW3GGZB.js";
9
+ import "./chunk-5MYC6LVL.js";
10
10
  import "./chunk-SMYSNO4M.js";
11
11
  import "./chunk-2KPI5GKP.js";
12
12
  import "./chunk-GDKLH7ZY.js";
@@ -142,7 +142,7 @@ var SessionReplayer = class {
142
142
  if (this.opts.page) {
143
143
  this.page = this.opts.page;
144
144
  } else if (this.opts.cdpUrl) {
145
- const { launch } = await import("./cdp-driver-OA67L3ON.js");
145
+ const { launch } = await import("./cdp-driver-B5KVVI4O.js");
146
146
  const { browser } = await launch({ cdpEndpoint: this.opts.cdpUrl });
147
147
  let contexts = browser.contexts();
148
148
  for (let i = 0; i < 10 && contexts.length === 0; i++) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xbrowser/cli",
3
- "version": "1.32.0",
3
+ "version": "1.33.0",
4
4
  "description": "Browser automation CLI for web scraping, headless browsing, SEO analysis, and AI agent workflows. A command-line alternative to Playwright, Puppeteer, and Selenium.",
5
5
  "type": "module",
6
6
  "bin": {