@xbrowser/cli 1.33.0 → 1.35.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.
Files changed (53) hide show
  1. package/dist/{browser-3LBSVDSS.js → browser-KY7AIRAB.js} +3 -2
  2. package/dist/{browser-23BMBCH2.js → browser-MLKP72XP.js} +3 -3
  3. package/dist/{browser-D7RFPTD4.js → browser-RZ7DPBI3.js} +3 -3
  4. package/dist/cdp-driver-CCG3OJUQ.js +49 -0
  5. package/dist/{cdp-driver-B5KVVI4O.js → cdp-driver-HBMCD7NU.js} +2 -2
  6. package/dist/{cdp-driver-GE6Y6LPI.js → cdp-driver-MJD7YIQI.js} +2 -2
  7. package/dist/{cdp-driver-6G77XM4H.js → cdp-driver-YJU4GRSV.js} +203 -95
  8. package/dist/chunk-3SZTCI33.js +147 -0
  9. package/dist/{chunk-OVAUGFM6.js → chunk-43U5VDLB.js} +8 -2
  10. package/dist/chunk-53VZHESL.js +150 -0
  11. package/dist/{chunk-NAIHOVDZ.js → chunk-63526WET.js} +2 -8
  12. package/dist/{chunk-YX5KVWGX.js → chunk-6DS3T6UK.js} +203 -95
  13. package/dist/{chunk-DDHHVII7.js → chunk-BLCBCESM.js} +8 -2
  14. package/dist/{chunk-SH6OTPXN.js → chunk-C5ZPXPD7.js} +31 -7
  15. package/dist/chunk-EGOWDZXP.js +149 -0
  16. package/dist/chunk-GNLZWHSP.js +1380 -0
  17. package/dist/{chunk-5MYC6LVL.js → chunk-GYGVHWG3.js} +279 -1460
  18. package/dist/{chunk-2KPI5GKP.js → chunk-IYCB2KJL.js} +2 -8
  19. package/dist/chunk-JYYKMSFH.js +39 -0
  20. package/dist/{chunk-TBJUSUKF.js → chunk-NBT2CE3H.js} +140 -96
  21. package/dist/{chunk-ACPMC47K.js → chunk-QRFM4NOV.js} +1025 -202
  22. package/dist/chunk-RGL2YTWQ.js +64 -0
  23. package/dist/{chunk-BND5O5KC.js → chunk-SQLICOPZ.js} +177 -240
  24. package/dist/{chunk-O5PASNI7.js → chunk-UUW5EGES.js} +139 -237
  25. package/dist/{chunk-43TEMG4U.js → chunk-WGS3Y6ZV.js} +3 -1
  26. package/dist/{chunk-AKT3WLZM.js → chunk-Y2GRCINH.js} +1004 -183
  27. package/dist/{chunk-H25ECCYJ.js → chunk-ZCZELQCS.js} +203 -95
  28. package/dist/cli.js +2237 -278
  29. package/dist/{daemon-client-7D6EZNOE.js → daemon-client-OXKRGLPQ.js} +32 -8
  30. package/dist/{daemon-client-HEGAXWGK.js → daemon-client-Z3NKNZRL.js} +5 -1
  31. package/dist/daemon-main.js +2214 -159
  32. package/dist/human-interaction-BGAZC3JR.js +12 -0
  33. package/dist/human-interaction-TPKPEE7A.js +11 -0
  34. package/dist/human-interaction-ZSD3IX6Q.js +12 -0
  35. package/dist/index.d.ts +225 -94
  36. package/dist/index.js +2880 -267
  37. package/dist/{launcher-TOLF23ET.js → launcher-AUJK5QQM.js} +1 -1
  38. package/dist/{launcher-ZYB32LSZ.js → launcher-QBAZ6F5L.js} +1 -1
  39. package/dist/mistake-ledger-2B4N54CO.js +29 -0
  40. package/dist/{recovery-ORHJSBDN.js → recovery-5AGY7CV3.js} +4 -5
  41. package/dist/{recovery-JFGV3DBX.js → recovery-7NRRHLS4.js} +4 -4
  42. package/dist/{recovery-XDKN63O5.js → recovery-TIBRFGRP.js} +4 -4
  43. package/dist/run-routes-SJKVZ34L.js +26 -0
  44. package/dist/run-routes-TFNV5BBR.js +24 -0
  45. package/dist/{server-5JHB4TML.js → server-HUSX7EFE.js} +5 -4
  46. package/dist/{server-6CTC3RHV.js → server-KSP5H4HD.js} +5 -3
  47. package/dist/{session-replayer-IGRRA2QC.js → session-replayer-4TCLQI76.js} +1 -1
  48. package/dist/viewer-routes-YOS5GTCV.js +11 -0
  49. package/package.json +1 -1
  50. package/dist/chunk-QCV2PI7U.js +0 -184
  51. package/dist/human-interaction-ISMMOJOK.js +0 -8
  52. package/dist/human-interaction-STTZZZ5N.js +0 -8
  53. package/dist/human-interaction-UXFYV7DU.js +0 -8
@@ -0,0 +1,147 @@
1
+ // src/lib/mistake-ledger.ts
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from "fs";
3
+ import { homedir } from "os";
4
+ import { join, dirname } from "path";
5
+ var MISTAKE_THRESHOLD = 3;
6
+ var MISTAKE_LEDGER_PATH = join(
7
+ homedir(),
8
+ ".xbrowser",
9
+ "knowledge",
10
+ "mistakes.json"
11
+ );
12
+ function emptyLedger() {
13
+ return { version: 1, entries: {} };
14
+ }
15
+ function normalizeMistakeText(value) {
16
+ return value.replace(/\d{4}-\d{2}-\d{2}T[^'"\s]+/g, "<timestamp>").replace(/\d+(?:\.\d+)?\s*(?:ms|s)\b/gi, "<duration>").replace(/\b\d+\b/g, "<number>").replace(/\s+/g, " ").trim();
17
+ }
18
+ function mistakeFingerprint(category, message) {
19
+ return `${category}::${normalizeMistakeText(message)}`;
20
+ }
21
+ function readMistakeLedger(path = MISTAKE_LEDGER_PATH) {
22
+ try {
23
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
24
+ if (parsed.version !== 1 || typeof parsed.entries !== "object") {
25
+ return emptyLedger();
26
+ }
27
+ return parsed;
28
+ } catch {
29
+ return emptyLedger();
30
+ }
31
+ }
32
+ function writeMistakeLedger(ledger, path = MISTAKE_LEDGER_PATH) {
33
+ mkdirSync(join(path, ".."), { recursive: true });
34
+ writeFileSync(path, JSON.stringify(ledger, null, 2), "utf8");
35
+ }
36
+ function listMistakes(path = MISTAKE_LEDGER_PATH) {
37
+ return Object.values(readMistakeLedger(path).entries).sort((a, b) => b.lastSeen.localeCompare(a.lastSeen));
38
+ }
39
+ var MISTAKES_MD_HEADER = `# \u6301\u4E45\u5316\u9519\u9898\u672C\uFF08 graduated mistake ledger \uFF09
40
+
41
+ > \u8FD0\u884C\u65F6\u9519\u9898\u672C\uFF08~/.xbrowser/knowledge/mistakes.json\uFF0CJSON\uFF09\u53EA\u505A\u8BA1\u6570\uFF1B
42
+ > **\u540C\u4E00\u9519\u8BEF\u6307\u7EB9\u51FA\u73B0 \u2265${MISTAKE_THRESHOLD} \u6B21\u81EA\u52A8\u6C89\u6DC0\u5230\u672C\u6587\u4EF6**\uFF08\u6309\u65E5\u671F\u8BB0\u5F55\uFF09\u3002
43
+ > \u672C\u6587\u4EF6\u88AB AGENTS.md \u5F15\u7528\u2014\u2014\u6240\u6709 Agent \u5F00\u5DE5\u524D\u5FC5\u8BFB\uFF0C\u907F\u514D\u91CD\u8E48\u8986\u8F99\u3002
44
+ > \u4FEE\u590D\u540E\u5728\u5BF9\u5E94\u6761\u76EE\u8865\u300C\u6839\u56E0\u300D\u4E0E\u300C\u4FEE\u590D\u300D\u4E24\u884C\uFF1B\u65B0\u6761\u76EE\u7531 recordMistake \u81EA\u52A8\u8FFD\u52A0\uFF0C\u4EBA\u5DE5\u53EA\u8865\u4E0D\u5220\u3002
45
+
46
+ `;
47
+ function persistentMistakesPath() {
48
+ if (process.env.XBROWSER_MISTAKES_MD) return process.env.XBROWSER_MISTAKES_MD;
49
+ let dir = process.cwd();
50
+ for (let i = 0; i < 8; i++) {
51
+ const pkg = join(dir, "package.json");
52
+ if (existsSync(pkg)) {
53
+ try {
54
+ const name = JSON.parse(readFileSync(pkg, "utf8")).name;
55
+ if (name === "@xbrowser/cli") return join(dir, "docs", "mistakes.md");
56
+ } catch {
57
+ }
58
+ }
59
+ const parent = join(dir, "..");
60
+ if (parent === dir) break;
61
+ dir = parent;
62
+ }
63
+ return join(homedir(), ".xbrowser", "knowledge", "mistakes.md");
64
+ }
65
+ function graduateToMarkdown(entry) {
66
+ const mdPath = persistentMistakesPath();
67
+ try {
68
+ mkdirSync(dirname(mdPath), { recursive: true });
69
+ if (!existsSync(mdPath)) writeFileSync(mdPath, MISTAKES_MD_HEADER);
70
+ const day = entry.lastSeen.slice(0, 10);
71
+ const first = entry.occurrences[0];
72
+ const anchor = `<!-- fingerprint:${entry.fingerprint} -->`;
73
+ const existing = existsSync(mdPath) ? readFileSync(mdPath, "utf8") : "";
74
+ if (existing.includes(anchor)) return;
75
+ const block = [
76
+ `## ${day} \xB7 ${first.command} \xB7 ${first.message.split("\n")[0].slice(0, 80)}`,
77
+ anchor,
78
+ `- **\u7C7B\u522B**: ${entry.category}`,
79
+ `- **\u9996\u6B21/\u6700\u8FD1**: ${entry.firstSeen.slice(0, 19)} \u2192 ${entry.lastSeen.slice(0, 19)}\uFF08\u7D2F\u8BA1 ${entry.occurrences.length} \u6B21\uFF09`,
80
+ `- **\u5178\u578B\u9519\u8BEF**: ${first.message.split("\n")[0].slice(0, 160)}`,
81
+ `- **\u6839\u56E0**: \uFF08\u5F85\u8865\u2014\u2014\u4FEE\u590D\u65F6\u586B\u5199\uFF09`,
82
+ `- **\u4FEE\u590D**: \uFF08\u5F85\u8865\u2014\u2014\u586B PR \u53F7\u6216\u4FEE\u590D\u8BF4\u660E\uFF09`,
83
+ ""
84
+ ].join("\n");
85
+ appendFileSync(mdPath, block);
86
+ } catch {
87
+ }
88
+ }
89
+ function recordMistake(input, path = MISTAKE_LEDGER_PATH) {
90
+ if (!input.category) throw new Error("mistake category is required");
91
+ if (!input.command) throw new Error("mistake command is required");
92
+ if (!input.message) throw new Error("mistake message is required");
93
+ const ledger = readMistakeLedger(path);
94
+ const fingerprint = input.fingerprint || mistakeFingerprint(input.category, input.message);
95
+ const previous = ledger.entries[fingerprint];
96
+ const occurrence = {
97
+ timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
98
+ command: input.command,
99
+ message: input.message,
100
+ ...input.context ? { context: input.context } : {}
101
+ };
102
+ const entry = previous ? {
103
+ ...previous,
104
+ lastSeen: occurrence.timestamp,
105
+ occurrences: [...previous.occurrences, occurrence].slice(-100),
106
+ constrained: previous.constrained || previous.occurrences.length + 1 >= MISTAKE_THRESHOLD
107
+ } : {
108
+ fingerprint,
109
+ category: input.category,
110
+ firstSeen: occurrence.timestamp,
111
+ lastSeen: occurrence.timestamp,
112
+ occurrences: [occurrence],
113
+ constrained: false
114
+ };
115
+ ledger.entries[fingerprint] = entry;
116
+ writeMistakeLedger(ledger, path);
117
+ const newlyConstrained = Boolean(previous && !previous.constrained && entry.constrained);
118
+ if (newlyConstrained) graduateToMarkdown(entry);
119
+ return { entry, newlyConstrained };
120
+ }
121
+ function constrainedMistakes(path = MISTAKE_LEDGER_PATH) {
122
+ return listMistakes(path).filter((entry) => entry.constrained);
123
+ }
124
+ function isConstrainedMistake(category, message, path = MISTAKE_LEDGER_PATH) {
125
+ const entry = readMistakeLedger(path).entries[mistakeFingerprint(category, message)];
126
+ return Boolean(entry?.constrained);
127
+ }
128
+ function clearMistakes(path = MISTAKE_LEDGER_PATH) {
129
+ if (!existsSync(path)) return false;
130
+ writeMistakeLedger(emptyLedger(), path);
131
+ return true;
132
+ }
133
+
134
+ export {
135
+ MISTAKE_THRESHOLD,
136
+ MISTAKE_LEDGER_PATH,
137
+ normalizeMistakeText,
138
+ mistakeFingerprint,
139
+ readMistakeLedger,
140
+ writeMistakeLedger,
141
+ listMistakes,
142
+ persistentMistakesPath,
143
+ recordMistake,
144
+ constrainedMistakes,
145
+ isConstrainedMistake,
146
+ clearMistakes
147
+ };
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createRuleEngine,
3
3
  launch
4
- } from "./chunk-H25ECCYJ.js";
4
+ } from "./chunk-ZCZELQCS.js";
5
5
  import {
6
6
  errMsg
7
7
  } from "./chunk-GDKLH7ZY.js";
@@ -1225,7 +1225,10 @@ async function closeSessionByName(name) {
1225
1225
  for (const session of sessions) {
1226
1226
  if (session.name === name || session.id === name) {
1227
1227
  logSessionEvent2("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
1228
- if (session.isCDP) {
1228
+ if (session.bridge) {
1229
+ await session.page.close().catch(() => {
1230
+ });
1231
+ } else if (session.isCDP) {
1229
1232
  if (session.reusedExistingPage) {
1230
1233
  logSessionEvent2("close_session", `name="${session.name}" \u2014 reused existing tab, disconnecting only`);
1231
1234
  await session.browser.disconnect().catch(() => {
@@ -1353,9 +1356,12 @@ export {
1353
1356
  findTargetPage,
1354
1357
  resolveLaunchOpts,
1355
1358
  createBrowser,
1359
+ sessions,
1356
1360
  saveSessionDiskMeta,
1357
1361
  readSessionDiskMeta,
1358
1362
  deleteSessionDiskMeta,
1363
+ newSessionId,
1364
+ registerSession,
1359
1365
  resetIdleTimer,
1360
1366
  findOrRestoreSession2 as findOrRestoreSession,
1361
1367
  touchSession,
@@ -0,0 +1,150 @@
1
+ import {
2
+ outputEnvelope,
3
+ outputError
4
+ } from "./chunk-RGL2YTWQ.js";
5
+ import {
6
+ executeChain
7
+ } from "./chunk-Y2GRCINH.js";
8
+ import {
9
+ forwardManagedRun
10
+ } from "./chunk-C5ZPXPD7.js";
11
+ import {
12
+ errMsg
13
+ } from "./chunk-GDKLH7ZY.js";
14
+
15
+ // src/stdin.ts
16
+ import { readStdin, readCommandFile, splitFileLine } from "@dyyz1993/xcli-core";
17
+
18
+ // src/cli/run-routes.ts
19
+ import { readFileSync as readFileSync2 } from "fs";
20
+ import { z } from "zod/v4";
21
+
22
+ // src/browser/session-persistence.ts
23
+ import {
24
+ lstatSync,
25
+ existsSync,
26
+ mkdirSync,
27
+ readdirSync,
28
+ readFileSync,
29
+ renameSync,
30
+ unlinkSync,
31
+ writeFileSync
32
+ } from "fs";
33
+ import { homedir } from "os";
34
+ import { join } from "path";
35
+ import { randomUUID } from "crypto";
36
+ function sanitizeSessionName(name) {
37
+ if (!name || name === "." || name === "..") {
38
+ throw new Error(`Invalid session name "${name}": must be a non-empty file-safe name`);
39
+ }
40
+ if (name.length > 64) {
41
+ throw new Error(`Invalid session name: too long (max 64 chars, got ${name.length})`);
42
+ }
43
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)) {
44
+ throw new Error(
45
+ `Invalid session name "${name}": only [A-Za-z0-9._-] allowed and it must start with an alphanumeric character`
46
+ );
47
+ }
48
+ return name;
49
+ }
50
+
51
+ // src/cli/run-routes.ts
52
+ var manifest = z.object({
53
+ jobs: z.array(z.object({
54
+ session: z.string(),
55
+ chain: z.string().trim().min(1)
56
+ })).min(1).max(100)
57
+ });
58
+ async function runNamedJobs(jobs, limit, run = forwardManagedRun) {
59
+ if (!Number.isInteger(limit) || limit < 1 || limit > 8) throw new Error("--parallel must be an integer from 1 to 8");
60
+ const names = jobs.map((job) => sanitizeSessionName(job.session));
61
+ if (new Set(names).size !== names.length) throw new Error("Each job must use a different session name");
62
+ const results = [];
63
+ let next = 0;
64
+ await Promise.all(Array.from({ length: Math.min(limit, jobs.length) }, async () => {
65
+ while (next < jobs.length) {
66
+ const index = next++;
67
+ const { session, chain } = jobs[index];
68
+ try {
69
+ const result = await run(chain, session);
70
+ results[index] = { session, success: result.success, result };
71
+ } catch (error) {
72
+ results[index] = { session, success: false, error: errMsg(error) };
73
+ }
74
+ }
75
+ }));
76
+ return results;
77
+ }
78
+ async function handleManagedRunFile(filePath, options) {
79
+ try {
80
+ if (filePath.endsWith(".json")) {
81
+ const { jobs } = manifest.parse(JSON.parse(readFileSync2(filePath, "utf8")));
82
+ const results = await runNamedJobs(jobs, options.parallel === void 0 ? 2 : Number(options.parallel));
83
+ const success = results.every((job) => job.success);
84
+ const failures = results.filter((job) => !job.success);
85
+ const message2 = failures.length ? `Jobs failed: ${failures.map((job) => job.session).join(", ")}` : void 0;
86
+ outputEnvelope({ success, data: { jobs: results }, message: message2 }, { command: "run" }, options.mode);
87
+ if (!success) process.exitCode = 1;
88
+ return;
89
+ }
90
+ if (options.parallel !== void 0) throw new Error("--parallel requires a JSON job manifest");
91
+ const commands = readCommandFile(filePath);
92
+ if (commands.length === 0) throw new Error("No commands found in file");
93
+ const session = sanitizeSessionName(options.sessionName);
94
+ const result = await forwardManagedRun(commands.join(" ; "), session, true);
95
+ const failed = result.steps.find((step) => !step.success);
96
+ const message = result.success ? void 0 : result.stoppedReason ?? failed?.message ?? "Run failed";
97
+ outputEnvelope({ success: result.success, data: result, message }, { command: "run", session }, options.mode);
98
+ if (!result.success) process.exitCode = 1;
99
+ } catch (error) {
100
+ outputEnvelope({ success: false, data: null, message: errMsg(error) }, { command: "run" }, options.mode);
101
+ process.exitCode = 1;
102
+ }
103
+ }
104
+ async function handleRun(filePath, options) {
105
+ let commands;
106
+ try {
107
+ commands = readCommandFile(filePath);
108
+ } catch (e) {
109
+ outputError(`Failed to read file '${filePath}': ${errMsg(e)}`);
110
+ return;
111
+ }
112
+ if (commands.length === 0) {
113
+ outputError("No commands found in file");
114
+ return;
115
+ }
116
+ const chain = commands.join(" ; ");
117
+ const chainResult = await executeChain(chain, {
118
+ cdpEndpoint: options?.cdpEndpoint,
119
+ sessionName: options?.sessionName,
120
+ fileMode: true
121
+ });
122
+ for (const step of chainResult.steps) {
123
+ if (step.success) {
124
+ process.stdout.write(`[OK] ${step.raw}
125
+ `);
126
+ if (step.data && typeof step.data === "object") {
127
+ const d = step.data;
128
+ for (const [k, v] of Object.entries(d)) {
129
+ if (k !== "ok")
130
+ process.stdout.write(` ${k}: ${typeof v === "string" ? v : JSON.stringify(v)}
131
+ `);
132
+ }
133
+ }
134
+ } else {
135
+ outputError(`[FAIL] ${step.raw}: ${step.message}`);
136
+ }
137
+ }
138
+ if (chainResult.stoppedReason) {
139
+ outputError(`Stopped: ${chainResult.stoppedReason}`);
140
+ }
141
+ if (!chainResult.success) process.exit(1);
142
+ }
143
+
144
+ export {
145
+ readStdin,
146
+ readCommandFile,
147
+ runNamedJobs,
148
+ handleManagedRunFile,
149
+ handleRun
150
+ };
@@ -99,17 +99,11 @@ async function launchChrome(options = {}) {
99
99
  }
100
100
  const port = await findFreePort();
101
101
  const allArgs = [
102
+ ...DEFAULT_ARGS,
102
103
  `--remote-debugging-port=${port}`,
103
104
  "--remote-allow-origins=*",
104
- "--no-sandbox",
105
- "--no-first-run",
106
- "--no-default-browser-check",
107
105
  "--disable-session-crashed-bubble",
108
- "--disable-background-timer-throttling",
109
- "--disable-backgrounding-occluded-windows",
110
- "--disable-renderer-backgrounding",
111
- "--disable-features=Translate,PasswordLeakDetection",
112
- "--disable-popup-blocking"
106
+ "--disable-features=Translate,PasswordLeakDetection"
113
107
  ];
114
108
  if (headless) {
115
109
  allArgs.push("--headless", "--hide-scrollbars", "--mute-audio");