@xbrowser/cli 1.34.0 → 1.36.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 (63) hide show
  1. package/README.md +137 -80
  2. package/dist/{browser-ZWEJ663M.js → browser-IEZOLTHA.js} +3 -3
  3. package/dist/{browser-GXL6V2JW.js → browser-NHQDQRXB.js} +3 -2
  4. package/dist/{browser-X7LO42UI.js → browser-XELRNYBL.js} +3 -3
  5. package/dist/cdp-driver-CCG3OJUQ.js +49 -0
  6. package/dist/{cdp-driver-GCFEMRFJ.js → cdp-driver-HBMCD7NU.js} +2 -2
  7. package/dist/{cdp-driver-QOUSRPR2.js → cdp-driver-MJD7YIQI.js} +2 -2
  8. package/dist/{cdp-driver-4MNHDU2J.js → cdp-driver-YJU4GRSV.js} +196 -95
  9. package/dist/chunk-2IOFJ6A3.js +149 -0
  10. package/dist/chunk-3SZTCI33.js +147 -0
  11. package/dist/{chunk-VYTQLZAX.js → chunk-5UXRFNXG.js} +28 -2
  12. package/dist/{chunk-NAIHOVDZ.js → chunk-63526WET.js} +2 -8
  13. package/dist/{chunk-YIL44YDX.js → chunk-6DS3T6UK.js} +196 -95
  14. package/dist/{chunk-J4NOL5XX.js → chunk-7KVH6MQG.js} +1099 -204
  15. package/dist/{chunk-N7DFS4V7.js → chunk-ENTENDF5.js} +9 -3
  16. package/dist/{chunk-R57Z5KZX.js → chunk-GVJ2UY65.js} +1078 -185
  17. package/dist/{chunk-3E6VVMK2.js → chunk-GYGVHWG3.js} +272 -1460
  18. package/dist/{chunk-2KPI5GKP.js → chunk-IYCB2KJL.js} +2 -8
  19. package/dist/chunk-KSB4PMCY.js +1380 -0
  20. package/dist/{chunk-RMYKVZIZ.js → chunk-L6QJUB33.js} +28 -2
  21. package/dist/{chunk-TBJUSUKF.js → chunk-NBT2CE3H.js} +140 -96
  22. package/dist/{chunk-DZ6XEPAH.js → chunk-PGEZJ6V3.js} +9 -3
  23. package/dist/chunk-RGL2YTWQ.js +64 -0
  24. package/dist/chunk-RL5FFY2Q.js +150 -0
  25. package/dist/{chunk-43TEMG4U.js → chunk-SBMVECDS.js} +3 -1
  26. package/dist/{chunk-BND5O5KC.js → chunk-SQLICOPZ.js} +177 -240
  27. package/dist/{chunk-O5PASNI7.js → chunk-UUW5EGES.js} +139 -237
  28. package/dist/{chunk-SH6OTPXN.js → chunk-WGWPWNIA.js} +78 -17
  29. package/dist/chunk-YW4BIJQL.js +489 -0
  30. package/dist/{chunk-R7AG7ONI.js → chunk-ZCZELQCS.js} +196 -95
  31. package/dist/chunk-ZR4NHTUV.js +39 -0
  32. package/dist/cli.js +2284 -307
  33. package/dist/convert-JNOM6H6A.js +490 -0
  34. package/dist/{convert-R3XXYKC6.js → convert-K6TLQEPX.js} +5 -3
  35. package/dist/{daemon-client-7D6EZNOE.js → daemon-client-AKQK5IIB.js} +79 -18
  36. package/dist/{daemon-client-HEGAXWGK.js → daemon-client-BBPQWLUX.js} +7 -1
  37. package/dist/daemon-main.js +2305 -164
  38. package/dist/human-interaction-BGAZC3JR.js +12 -0
  39. package/dist/human-interaction-TPKPEE7A.js +11 -0
  40. package/dist/human-interaction-ZSD3IX6Q.js +12 -0
  41. package/dist/index.d.ts +251 -97
  42. package/dist/index.js +2929 -298
  43. package/dist/{launcher-TOLF23ET.js → launcher-AUJK5QQM.js} +1 -1
  44. package/dist/{launcher-ZYB32LSZ.js → launcher-QBAZ6F5L.js} +1 -1
  45. package/dist/mistake-ledger-2B4N54CO.js +29 -0
  46. package/dist/{recovery-ORHJSBDN.js → recovery-5AGY7CV3.js} +4 -5
  47. package/dist/{recovery-XDKN63O5.js → recovery-7NRRHLS4.js} +2 -2
  48. package/dist/{recovery-JFGV3DBX.js → recovery-TIBRFGRP.js} +2 -2
  49. package/dist/run-routes-64IBBVOX.js +24 -0
  50. package/dist/run-routes-FG4LIACU.js +26 -0
  51. package/dist/{server-5U56MQD2.js → server-K22LJBO2.js} +5 -4
  52. package/dist/{server-R4OYD7ZC.js → server-ZHZDJJMG.js} +5 -3
  53. package/dist/{session-recorder-RUNQOJ7T.js → session-recorder-CNTY5KXF.js} +1 -1
  54. package/dist/{session-recorder-N7VEKJVW.js → session-recorder-KMKSQWEP.js} +1 -1
  55. package/dist/{session-replayer-GHEFFNGV.js → session-replayer-4TCLQI76.js} +1 -1
  56. package/dist/viewer-routes-CEO7HWCB.js +11 -0
  57. package/package.json +3 -2
  58. package/dist/chunk-ETCO4SNK.js +0 -206
  59. package/dist/chunk-QCV2PI7U.js +0 -184
  60. package/dist/convert-LB3GJTLR.js +0 -207
  61. package/dist/human-interaction-ISMMOJOK.js +0 -8
  62. package/dist/human-interaction-STTZZZ5N.js +0 -8
  63. package/dist/human-interaction-UXFYV7DU.js +0 -8
package/dist/cli.js CHANGED
@@ -1,7 +1,12 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ handleRun,
4
+ readStdin
5
+ } from "./chunk-2IOFJ6A3.js";
2
6
  import {
3
7
  PluginMetadataParser,
4
8
  XBrowserPluginLoader,
9
+ asZodSchema,
5
10
  attachDetectAntiBot,
6
11
  checkPluginLoginRequired,
7
12
  createStubContext,
@@ -15,10 +20,42 @@ import {
15
20
  getPluginStorage,
16
21
  isChainInput,
17
22
  loadHooks,
23
+ normalizeKebabParams,
18
24
  parsePluginParams,
19
- readJsonFile
20
- } from "./chunk-J4NOL5XX.js";
25
+ readJsonFile,
26
+ splitOutsideQuotes
27
+ } from "./chunk-7KVH6MQG.js";
28
+ import {
29
+ closeAllSessions,
30
+ closeSessionByName,
31
+ createSession,
32
+ findOrRestoreSession,
33
+ findSession,
34
+ getAllSessions,
35
+ saveSessionDiskMeta
36
+ } from "./chunk-KSB4PMCY.js";
21
37
  import "./chunk-JKVUFP3G.js";
38
+ import "./chunk-3SZTCI33.js";
39
+ import {
40
+ buildViewerUrl
41
+ } from "./chunk-3OD76SUE.js";
42
+ import {
43
+ NPM_REGISTRY_URL,
44
+ NPM_SCOPE,
45
+ getConfigValue,
46
+ getMarketplaceUrl,
47
+ loadConfig,
48
+ resolveNpmPackageWithFallback,
49
+ setConfigValue
50
+ } from "./chunk-ZTHE5RBZ.js";
51
+ import {
52
+ handleViewer
53
+ } from "./chunk-ZR4NHTUV.js";
54
+ import {
55
+ outputEnvelope,
56
+ outputError,
57
+ outputResult
58
+ } from "./chunk-RGL2YTWQ.js";
22
59
  import {
23
60
  daemonPing,
24
61
  forwardCommandLog,
@@ -42,32 +79,24 @@ import {
42
79
  forwardReplay,
43
80
  forwardSessionClose,
44
81
  forwardSessionList,
45
- forwardViewerCheckSelector,
46
82
  version
47
- } from "./chunk-SH6OTPXN.js";
48
- import {
49
- buildViewerUrl
50
- } from "./chunk-3OD76SUE.js";
51
- import {
52
- NPM_REGISTRY_URL,
53
- NPM_SCOPE,
54
- getConfigValue,
55
- getMarketplaceUrl,
56
- loadConfig,
57
- resolveNpmPackageWithFallback,
58
- setConfigValue
59
- } from "./chunk-ZTHE5RBZ.js";
83
+ } from "./chunk-WGWPWNIA.js";
60
84
  import {
61
- getDaemonConfig,
62
85
  getDaemonProcessStatus,
63
86
  killAllDaemonProcesses,
64
87
  startDaemonProcess,
65
88
  stopDaemonProcess
66
89
  } from "./chunk-Q2DFJQGS.js";
90
+ import "./chunk-GYGVHWG3.js";
91
+ import "./chunk-SMYSNO4M.js";
92
+ import "./chunk-IYCB2KJL.js";
93
+ import {
94
+ errMsg
95
+ } from "./chunk-GDKLH7ZY.js";
67
96
  import {
68
97
  SessionRecorder,
69
98
  readMarkdownSummary
70
- } from "./chunk-RMYKVZIZ.js";
99
+ } from "./chunk-L6QJUB33.js";
71
100
  import {
72
101
  addKnownIssue,
73
102
  getKnowledgePath,
@@ -76,83 +105,10 @@ import {
76
105
  readSiteKnowledge,
77
106
  readSiteKnowledgeMarkdown
78
107
  } from "./chunk-OZKD3W4X.js";
79
- import {
80
- closeAllSessions,
81
- closeSessionByName,
82
- createSession,
83
- findOrRestoreSession,
84
- findSession,
85
- getAllSessions,
86
- saveSessionDiskMeta
87
- } from "./chunk-3E6VVMK2.js";
88
- import "./chunk-SMYSNO4M.js";
89
- import "./chunk-2KPI5GKP.js";
90
- import {
91
- errMsg
92
- } from "./chunk-GDKLH7ZY.js";
93
108
  import "./chunk-KFQGP6VL.js";
94
109
 
95
110
  // src/router.ts
96
- import { parseArgs } from "@dyyz1993/xcli-core";
97
-
98
- // src/cli/output.ts
99
- import { outputFormatter, OutputFormatter } from "@dyyz1993/xcli-core";
100
- var formatter = new OutputFormatter();
101
- function outputResult(result, mode = "text") {
102
- if (mode !== "json" && mode !== "yaml" && typeof result === "object" && result !== null) {
103
- const r = result;
104
- if (r.success === false) {
105
- outputError(r.message ? String(r.message) : "Unknown error");
106
- }
107
- if (r.ok === false) {
108
- outputError(r.error ? String(r.error) : "Unknown error");
109
- }
110
- }
111
- const output = outputFormatter.format(result, {
112
- mode,
113
- color: mode === "text",
114
- emoji: false
115
- });
116
- console.log(output);
117
- }
118
- function outputError(message) {
119
- const formatted = formatter.formatError(message, { color: true, emoji: false });
120
- console.error(formatted);
121
- process.exitCode = 1;
122
- }
123
- function outputEnvelope(result, meta, mode) {
124
- if (mode !== "json" && mode !== "yaml") {
125
- if (!result.success) {
126
- outputError(result.message || "Unknown error");
127
- return;
128
- }
129
- outputResult(result.data, mode);
130
- return;
131
- }
132
- const { command, ...extraMeta } = meta;
133
- const commandResult = {
134
- success: result.success,
135
- data: result.data,
136
- message: result.message,
137
- tips: [],
138
- meta: {
139
- duration: result.duration ?? 0,
140
- ...extraMeta
141
- }
142
- };
143
- const formatted = outputFormatter.formatEnvelope(commandResult, {
144
- command,
145
- extraMeta,
146
- mode
147
- });
148
- console.log(formatted);
149
- if (result.tips?.length) {
150
- for (const tip of result.tips) {
151
- const text = typeof tip === "string" ? tip : tip.message;
152
- if (text) console.error(` \u{1F4A1} ${text}`);
153
- }
154
- }
155
- }
111
+ import { parseArgs, splitCommand, unquote } from "@dyyz1993/xcli-core";
156
112
 
157
113
  // src/utils/selector.ts
158
114
  var HTML_TAGS = /* @__PURE__ */ new Set([
@@ -240,11 +196,6 @@ function normalizeSelector(input) {
240
196
  return "#" + input;
241
197
  }
242
198
 
243
- // src/utils/zod-internal.ts
244
- function asZodSchema(value) {
245
- return value;
246
- }
247
-
248
199
  // src/cli/browser-routes.ts
249
200
  import { helpGenerator } from "@dyyz1993/xcli-core";
250
201
  function autoCompleteParams(cmdName, params, options) {
@@ -254,6 +205,7 @@ function autoCompleteParams(cmdName, params, options) {
254
205
  const schema = asZodSchema(cmd.parameters);
255
206
  const shape = schema?.shape ?? schema?._def?.shape;
256
207
  if (!shape) return params;
208
+ options = normalizeKebabParams(cmd.parameters, options);
257
209
  for (const key of Object.keys(shape)) {
258
210
  if (params[key] !== void 0) continue;
259
211
  const v = options[key];
@@ -728,7 +680,9 @@ async function handleBrowserCommand(command, args, options, sessionName, mode, c
728
680
  } else if (typeof options.frame === "string") {
729
681
  params = { ...params, _frame: options.frame };
730
682
  }
731
- const result = cdpEndpoint ? await executeCommand(cmdName, params, sessionName, { cdpEndpoint }) : await executeCommand(cmdName, params, sessionName);
683
+ const bridgeFlag = options.bridge === true || String(options.bridge) === "true" || process.env.XBROWSER_BRIDGE === "1";
684
+ const extra = bridgeFlag ? { cdpEndpoint, bridge: true } : cdpEndpoint ? { cdpEndpoint } : void 0;
685
+ const result = extra ? await executeCommand(cmdName, params, sessionName, extra) : await executeCommand(cmdName, params, sessionName);
732
686
  if (mode === "json" || mode === "yaml") {
733
687
  outputEnvelope(result, { command: cmdName }, mode);
734
688
  } else if (!result.success) {
@@ -750,11 +704,11 @@ async function handleBrowserCommand(command, args, options, sessionName, mode, c
750
704
  const dataObj = result.data;
751
705
  const handlerAlreadyWrote = !!dataObj && typeof dataObj.output === "string";
752
706
  if (outputFile && result.success && result.data && !handlerAlreadyWrote) {
753
- const { writeFileSync: writeFileSync7, mkdirSync: mkdirSync6 } = await import("fs");
754
- const { dirname: dirname4 } = await import("path");
707
+ const { writeFileSync: writeFileSync7, mkdirSync: mkdirSync7 } = await import("fs");
708
+ const { dirname: dirname5 } = await import("path");
755
709
  const content = typeof result.data === "string" ? result.data : dataObj.content || dataObj.text || JSON.stringify(result.data, null, 2);
756
710
  try {
757
- mkdirSync6(dirname4(outputFile), { recursive: true });
711
+ mkdirSync7(dirname5(outputFile), { recursive: true });
758
712
  writeFileSync7(outputFile, content, "utf-8");
759
713
  process.stdout.write(`
760
714
  \u{1F4C4} Written to ${outputFile}
@@ -781,6 +735,10 @@ function handleSessionHelp() {
781
735
  "Commands:",
782
736
  " close [--name <name>] Close session",
783
737
  " list, ls List active sessions",
738
+ " handoff <name> Print the Viewer link for a named session",
739
+ " save <name> Save login state from a local session",
740
+ " restore <name> Restore saved login state in a fresh session",
741
+ " errors List recurring command errors",
784
742
  " kill [--name <name>] Kill session forcefully",
785
743
  " kill-all Kill all sessions and daemon",
786
744
  "",
@@ -1150,14 +1108,14 @@ function isValidGitUrl(url) {
1150
1108
  return GIT_URL_RE.test(url) || GIT_SCP_RE.test(url);
1151
1109
  }
1152
1110
  function execGit(args) {
1153
- return new Promise((resolve8, reject) => {
1111
+ return new Promise((resolve10, reject) => {
1154
1112
  execFile("git", args, (err, _stdout, stderr) => {
1155
1113
  if (err) {
1156
1114
  const stderrText = typeof stderr === "string" ? stderr : stderr?.toString("utf-8") ?? "";
1157
1115
  const detail = stderrText.trim() || err.message;
1158
1116
  reject(new Error(`git clone failed: ${detail}`));
1159
1117
  } else {
1160
- resolve8();
1118
+ resolve10();
1161
1119
  }
1162
1120
  });
1163
1121
  });
@@ -1530,16 +1488,30 @@ var PluginInstaller = class {
1530
1488
  *
1531
1489
  * Some marketplace/npm packages import from `../shared/` (e.g. ssr-detect.js,
1532
1490
  * ai-chat-base.ts) but the `shared/` directory is not included in the package.
1533
- * This method scans the installed plugin's index.ts for such imports and
1534
- * copies the missing files from the local repository's `.xcli/plugins/shared/`
1535
- * directory (if available).
1491
+ * This method scans every .ts/.js source file in the installed plugin (not just
1492
+ * index.ts — media plugins like gemini import shared modules from generate.ts,
1493
+ * history.ts, music.ts, etc.) for such imports and copies the missing files
1494
+ * from the local repository's `.xcli/plugins/shared/` directory (if available).
1536
1495
  */
1537
1496
  async fixSharedDeps(pluginDir) {
1538
- const indexPath = resolve6(pluginDir, "index.ts");
1539
- if (!existsSync6(indexPath)) return;
1497
+ const sourceFiles = [];
1498
+ const collectSourceFiles = (dir) => {
1499
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1500
+ if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
1501
+ const full = resolve6(dir, entry.name);
1502
+ if (entry.isDirectory()) {
1503
+ collectSourceFiles(full);
1504
+ } else if (/\.(ts|js)$/.test(entry.name)) {
1505
+ sourceFiles.push(full);
1506
+ }
1507
+ }
1508
+ };
1509
+ if (!existsSync6(pluginDir)) return;
1510
+ collectSourceFiles(pluginDir);
1511
+ if (sourceFiles.length === 0) return;
1540
1512
  let content;
1541
1513
  try {
1542
- content = readFileSync5(indexPath, "utf8");
1514
+ content = sourceFiles.map((f) => readFileSync5(f, "utf8")).join("\n");
1543
1515
  } catch {
1544
1516
  return;
1545
1517
  }
@@ -1553,8 +1525,7 @@ var PluginInstaller = class {
1553
1525
  const sharedDir = resolve6(pluginDir, "..", "shared");
1554
1526
  const toCopy = [];
1555
1527
  for (const file of missingFiles) {
1556
- const targetPath = resolve6(sharedDir, file);
1557
- if (!existsSync6(targetPath)) {
1528
+ if (!existsSync6(resolve6(sharedDir, file)) && !toCopy.includes(file)) {
1558
1529
  toCopy.push(file);
1559
1530
  }
1560
1531
  }
@@ -1576,16 +1547,23 @@ var PluginInstaller = class {
1576
1547
  let allDownloaded = true;
1577
1548
  for (const file of toCopy) {
1578
1549
  try {
1579
- const url = `${GITHUB_RAW}/${file}`;
1580
- const resp = await fetch(url, { signal: AbortSignal.timeout(1e4) });
1581
- if (resp.ok) {
1582
- const content2 = await resp.text();
1583
- const dst = resolve6(sharedDir, file);
1584
- const dstDir = dirname2(dst);
1585
- if (!existsSync6(dstDir)) mkdirSync4(dstDir, { recursive: true });
1586
- writeFileSync5(dst, content2, "utf-8");
1587
- console.log(`\u2705 Downloaded shared/${file} from GitHub`);
1588
- } else {
1550
+ const candidates = file.endsWith(".js") ? [file, file.replace(/\.js$/, ".ts")] : [file];
1551
+ let downloaded = false;
1552
+ for (const candidate of candidates) {
1553
+ const url = `${GITHUB_RAW}/${candidate}`;
1554
+ const resp = await fetch(url, { signal: AbortSignal.timeout(1e4) });
1555
+ if (resp.ok) {
1556
+ const fileContent = await resp.text();
1557
+ const dst = resolve6(sharedDir, candidate);
1558
+ const dstDir = dirname2(dst);
1559
+ if (!existsSync6(dstDir)) mkdirSync4(dstDir, { recursive: true });
1560
+ writeFileSync5(dst, fileContent, "utf-8");
1561
+ console.log(`\u2705 Downloaded shared/${candidate} from GitHub`);
1562
+ downloaded = true;
1563
+ break;
1564
+ }
1565
+ }
1566
+ if (!downloaded) {
1589
1567
  allDownloaded = false;
1590
1568
  break;
1591
1569
  }
@@ -1602,16 +1580,21 @@ var PluginInstaller = class {
1602
1580
  }
1603
1581
  mkdirSync4(sharedDir, { recursive: true });
1604
1582
  for (const file of toCopy) {
1605
- const src = resolve6(sourceSharedDir, file);
1606
- const dst = resolve6(sharedDir, file);
1607
- if (existsSync6(src)) {
1583
+ const candidates = file.endsWith(".js") ? [file, file.replace(/\.js$/, ".ts")] : [file];
1584
+ const src = candidates.map((c) => resolve6(sourceSharedDir, c)).find((p) => existsSync6(p));
1585
+ if (!src) {
1586
+ console.warn(`\u26A0\uFE0F Could not copy shared/${file}: not found in ${sourceSharedDir}`);
1587
+ continue;
1588
+ }
1589
+ const dst = resolve6(sharedDir, basename2(src));
1590
+ {
1608
1591
  try {
1609
1592
  cpSync6(dirname2(src), dirname2(dst), { recursive: true });
1610
- console.log(`\u2705 Copied shared/${file} for plugin "${basename2(pluginDir)}"`);
1593
+ console.log(`\u2705 Copied shared/${basename2(src)} for plugin "${basename2(pluginDir)}"`);
1611
1594
  } catch {
1612
1595
  try {
1613
1596
  copyFileSync(src, dst);
1614
- console.log(`\u2705 Copied shared/${file} for plugin "${basename2(pluginDir)}"`);
1597
+ console.log(`\u2705 Copied shared/${basename2(src)} for plugin "${basename2(pluginDir)}"`);
1615
1598
  } catch {
1616
1599
  console.warn(`\u26A0\uFE0F Could not copy shared/${file}`);
1617
1600
  }
@@ -2798,6 +2781,35 @@ function cleanSessionFiles() {
2798
2781
  async function handleSession(args, options, mode, _cdpEndpoint) {
2799
2782
  const sub = args[0];
2800
2783
  switch (sub) {
2784
+ case "handoff": {
2785
+ const { handleViewer: handleViewer2 } = await import("./viewer-routes-CEO7HWCB.js");
2786
+ await handleViewer2([], { ...options, session: args[1] ?? options.session }, mode, _cdpEndpoint);
2787
+ break;
2788
+ }
2789
+ case "save":
2790
+ case "restore": {
2791
+ const name = args[1] || options.session || process.env.XBROWSER_SESSION || "default";
2792
+ try {
2793
+ const { forwardSessionState } = await import("./daemon-client-BBPQWLUX.js");
2794
+ const data = await forwardSessionState(sub, name);
2795
+ outputEnvelope({ success: true, data }, { command: `session ${sub}` }, mode);
2796
+ } catch (error) {
2797
+ outputEnvelope({ success: false, data: null, message: error instanceof Error ? error.message : String(error) }, { command: `session ${sub}` }, mode);
2798
+ process.exitCode = 1;
2799
+ }
2800
+ break;
2801
+ }
2802
+ case "errors": {
2803
+ const { listMistakes } = await import("./mistake-ledger-2B4N54CO.js");
2804
+ const errors = listMistakes().map(({ category, occurrences, constrained }) => ({
2805
+ category,
2806
+ command: occurrences.at(-1)?.command,
2807
+ count: occurrences.length,
2808
+ constrained
2809
+ }));
2810
+ outputEnvelope({ success: true, data: { errors } }, { command: "session errors" }, mode);
2811
+ break;
2812
+ }
2801
2813
  case "close": {
2802
2814
  if (options.all) {
2803
2815
  let count = 0;
@@ -2826,9 +2838,18 @@ async function handleSession(args, options, mode, _cdpEndpoint) {
2826
2838
  }
2827
2839
  case "list":
2828
2840
  case "ls": {
2841
+ let daemon;
2842
+ try {
2843
+ const ping = await daemonPing();
2844
+ if (ping && ping.ok && "version" in ping) {
2845
+ const info = ping;
2846
+ daemon = { version: info.version, buildId: info.buildId, startedAt: info.startedAt, pid: info.pid };
2847
+ }
2848
+ } catch {
2849
+ }
2829
2850
  try {
2830
2851
  const sessions = await forwardSessionList();
2831
- outputEnvelope({ success: true, data: { sessions } }, { command: "session list" }, mode);
2852
+ outputEnvelope({ success: true, data: daemon ? { sessions, daemon } : { sessions } }, { command: "session list" }, mode);
2832
2853
  } catch {
2833
2854
  const sessions = await listSessions();
2834
2855
  outputEnvelope({ success: true, data: { sessions } }, { command: "session list" }, mode);
@@ -2965,6 +2986,51 @@ async function infoFromMarketplacePlugin(slug, loader) {
2965
2986
  }
2966
2987
  return null;
2967
2988
  }
2989
+ async function searchFromMarketplaceAPI(options) {
2990
+ const baseUrl = getMarketplaceUrl();
2991
+ const params = new URLSearchParams();
2992
+ if (options.query) params.set("search", options.query);
2993
+ if (options.tag) params.set("tag", options.tag);
2994
+ if (options.site) params.set("site", options.site);
2995
+ if (options.limit) params.set("limit", String(options.limit));
2996
+ const url = `${baseUrl}/api/plugins?${params.toString()}`;
2997
+ const resp = await fetch(url, { signal: AbortSignal.timeout(5e3) });
2998
+ if (!resp.ok) return [];
2999
+ const body = await resp.json();
3000
+ const items = body.data?.items ?? [];
3001
+ return items.map((item) => ({
3002
+ name: item.slug || item.name,
3003
+ slug: item.slug,
3004
+ description: item.description,
3005
+ version: item.version,
3006
+ downloads: item.downloadCount,
3007
+ tags: item.tags,
3008
+ sites: item.siteUrls,
3009
+ commands: item.commands,
3010
+ source: "marketplace"
3011
+ }));
3012
+ }
3013
+ async function infoFromMarketplaceAPI(slug) {
3014
+ const baseUrl = getMarketplaceUrl();
3015
+ const url = `${baseUrl}/api/plugins/${encodeURIComponent(slug)}`;
3016
+ const resp = await fetch(url, { signal: AbortSignal.timeout(5e3) });
3017
+ if (!resp.ok) return null;
3018
+ const body = await resp.json();
3019
+ if (!body.success || !body.data) return null;
3020
+ const p = body.data;
3021
+ return {
3022
+ name: p.name || slug,
3023
+ slug: p.slug || slug,
3024
+ description: p.description,
3025
+ version: p.version,
3026
+ author: p.authorName,
3027
+ downloads: p.downloadCount ?? 0,
3028
+ tags: p.tags ?? [],
3029
+ sites: p.siteUrls ?? [],
3030
+ commands: p.commands ?? [],
3031
+ source: "marketplace"
3032
+ };
3033
+ }
2968
3034
  function normalizePluginName(name) {
2969
3035
  return name.replace(/^@[^/]+\//, "").replace(/^xbrowser-plugin-/, "").toLowerCase();
2970
3036
  }
@@ -3021,6 +3087,13 @@ async function handleSearch(args, options, mode) {
3021
3087
  const loader = await getPluginLoader();
3022
3088
  const pluginResults = await searchFromMarketplacePlugin2(searchOpts, loader);
3023
3089
  results.push(...pluginResults);
3090
+ if (pluginResults.length === 0) {
3091
+ try {
3092
+ const apiResults = await searchFromMarketplaceAPI(searchOpts);
3093
+ results.push(...apiResults);
3094
+ } catch {
3095
+ }
3096
+ }
3024
3097
  if (pluginResults.length === 0) {
3025
3098
  try {
3026
3099
  const npmResults = await NPMSearcher.search(searchOpts);
@@ -3092,6 +3165,36 @@ async function handlePluginInfo(args, options, mode) {
3092
3165
  process.stdout.write(`\u6807\u7B7E: ${(d.tags || []).join(", ")}
3093
3166
  `);
3094
3167
  process.stdout.write(`\u7F51\u7AD9: ${(d.sites || []).join(", ")}
3168
+ `);
3169
+ return;
3170
+ }
3171
+ } catch {
3172
+ }
3173
+ try {
3174
+ const apiInfo = await infoFromMarketplaceAPI(slug);
3175
+ if (apiInfo) {
3176
+ const d = apiInfo;
3177
+ if (mode === "json") {
3178
+ outputEnvelope({ success: true, data: { source: "marketplace", ...d } }, { command: "plugin info" }, mode);
3179
+ return;
3180
+ }
3181
+ process.stdout.write(`\u540D\u79F0: ${d.name || ""}
3182
+ `);
3183
+ process.stdout.write(`\u7248\u672C: ${d.version || ""}
3184
+ `);
3185
+ process.stdout.write(`\u63CF\u8FF0: ${d.description || ""}
3186
+ `);
3187
+ process.stdout.write(`\u4F5C\u8005: ${d.author || ""}
3188
+ `);
3189
+ process.stdout.write(`\u547D\u4EE4: ${(d.commands || []).join(", ")}
3190
+ `);
3191
+ process.stdout.write(`\u4E0B\u8F7D\u91CF: ${d.downloads || 0}
3192
+ `);
3193
+ process.stdout.write(`\u6807\u7B7E: ${(d.tags || []).join(", ")}
3194
+ `);
3195
+ process.stdout.write(`\u7F51\u7AD9: ${(d.sites || []).join(", ")}
3196
+ `);
3197
+ process.stdout.write(`\u6765\u6E90: marketplace
3095
3198
  `);
3096
3199
  return;
3097
3200
  }
@@ -3217,7 +3320,7 @@ async function handlePlugin(args, options, mode) {
3217
3320
  } catch {
3218
3321
  }
3219
3322
  try {
3220
- const { daemonPing: daemonPing2 } = await import("./daemon-client-HEGAXWGK.js");
3323
+ const { daemonPing: daemonPing2 } = await import("./daemon-client-BBPQWLUX.js");
3221
3324
  if (await daemonPing2()) {
3222
3325
  await fetch("http://localhost:9224/rpc", {
3223
3326
  method: "POST",
@@ -3406,9 +3509,9 @@ async function handleRecord(args, options, mode) {
3406
3509
  const defaultRecording = SessionRecorder.getRecordingsDir(sessionName) + "/recording.json";
3407
3510
  if (existsSync9(defaultRecording)) {
3408
3511
  try {
3409
- const { mkdirSync: mkdirSync6, copyFileSync: copyFileSync2 } = await import("fs");
3512
+ const { mkdirSync: mkdirSync7, copyFileSync: copyFileSync2 } = await import("fs");
3410
3513
  const { dirname: pathDirname } = await import("path");
3411
- mkdirSync6(pathDirname(output), { recursive: true });
3514
+ mkdirSync7(pathDirname(output), { recursive: true });
3412
3515
  if (output.endsWith(".yaml") || output.endsWith(".yml")) {
3413
3516
  const { default: yaml } = await import("yaml");
3414
3517
  const data = SessionRecorder.readData(sessionName);
@@ -3742,7 +3845,7 @@ async function handleConvert(args, _mode) {
3742
3845
  const fs2 = await import("fs");
3743
3846
  const path2 = await import("path");
3744
3847
  const { default: yaml } = await import("yaml");
3745
- const { generateJSScript, generatePythonScript, generateBashScript } = await import("./convert-LB3GJTLR.js");
3848
+ const { generateJSScript, generatePythonScript, generateBashScript } = await import("./convert-JNOM6H6A.js");
3746
3849
  let recording;
3747
3850
  try {
3748
3851
  const content = fs2.readFileSync(filePath, "utf-8");
@@ -3755,24 +3858,6 @@ async function handleConvert(args, _mode) {
3755
3858
  outputError(`Error: "${filePath}" does not contain a valid recording (expected a YAML/JSON object with events or actions).`);
3756
3859
  process.exit(1);
3757
3860
  }
3758
- const rawActions = recording.actions;
3759
- if (Array.isArray(rawActions) && !Array.isArray(recording.events)) {
3760
- recording.events = rawActions.map((a) => {
3761
- const action = a;
3762
- const element = action.element ?? {};
3763
- return {
3764
- type: action.type,
3765
- selector: element.selector ?? action.selector,
3766
- data: {
3767
- ...action.data,
3768
- value: action.value ?? action.data?.value,
3769
- key: action.key ?? action.data?.key,
3770
- x: action.scrollX ?? action.data?.x,
3771
- y: action.scrollY ?? action.data?.y
3772
- }
3773
- };
3774
- });
3775
- }
3776
3861
  const ext = path2.extname(outputPath).toLowerCase();
3777
3862
  const recordingTyped = recording;
3778
3863
  let script;
@@ -3785,12 +3870,13 @@ async function handleConvert(args, _mode) {
3785
3870
  }
3786
3871
  fs2.writeFileSync(outputPath, script);
3787
3872
  fs2.chmodSync(outputPath, 493);
3788
- const eventCount = (recordingTyped.events || []).length;
3873
+ const eventCount = [recordingTyped.events, recordingTyped.actions].find(Array.isArray)?.length ?? 0;
3874
+ const runner = ext === ".py" ? "python" : ext === ".sh" ? "bash" : "node";
3789
3875
  process.stdout.write(`Converted ${filePath} -> ${outputPath}
3790
3876
  `);
3791
3877
  process.stdout.write(` Events: ${eventCount}, Start URL: ${recordingTyped.startUrl}
3792
3878
  `);
3793
- process.stdout.write(` Run: ${ext === ".py" ? "python" : ext === ".sh" ? "./" : "node"} ${outputPath}
3879
+ process.stdout.write(` Run: ${runner} ${outputPath}
3794
3880
  `);
3795
3881
  }
3796
3882
  async function handleExtract(args, _mode) {
@@ -3837,10 +3923,10 @@ async function handleFilter(args, _mode, options) {
3837
3923
  }
3838
3924
  }
3839
3925
  async function handleGeneratePlugin(sessionName, pluginName, outputDir) {
3840
- const { SessionRecorder: SessionRecorder2 } = await import("./session-recorder-RUNQOJ7T.js");
3926
+ const { SessionRecorder: SessionRecorder2 } = await import("./session-recorder-CNTY5KXF.js");
3841
3927
  const { readSiteKnowledge: readSiteKnowledge2, toMarkdown } = await import("./site-knowledge-SYC6VCDB.js");
3842
- const { mkdirSync: mkdirSync6, writeFileSync: writeFileSync7 } = await import("fs");
3843
- const { join: join8 } = await import("path");
3928
+ const { mkdirSync: mkdirSync7, writeFileSync: writeFileSync7 } = await import("fs");
3929
+ const { join: join9 } = await import("path");
3844
3930
  const data = SessionRecorder2.readData(sessionName);
3845
3931
  if (!data) {
3846
3932
  outputError(`No recording found for session "${sessionName}". Run \`xbrowser record stop --session ${sessionName}\` first.`);
@@ -3852,14 +3938,14 @@ async function handleGeneratePlugin(sessionName, pluginName, outputDir) {
3852
3938
  } catch {
3853
3939
  }
3854
3940
  const finalPluginName = pluginName || domain.split(".")[0] || "my-site";
3855
- const finalOutputDir = outputDir || join8(process.cwd(), ".xcli", "plugins", finalPluginName);
3941
+ const finalOutputDir = outputDir || join9(process.cwd(), ".xcli", "plugins", finalPluginName);
3856
3942
  const knowledge = readSiteKnowledge2(domain);
3857
3943
  const knowledgeMd = knowledge ? toMarkdown(knowledge) : "";
3858
3944
  const pluginCode = generatePluginCode(finalPluginName, domain, data, knowledgeMd);
3859
- mkdirSync6(join8(finalOutputDir), { recursive: true });
3860
- writeFileSync7(join8(finalOutputDir, "index.ts"), pluginCode, "utf-8");
3945
+ mkdirSync7(join9(finalOutputDir), { recursive: true });
3946
+ writeFileSync7(join9(finalOutputDir, "index.ts"), pluginCode, "utf-8");
3861
3947
  if (knowledgeMd) {
3862
- writeFileSync7(join8(finalOutputDir, "SITE_KNOWLEDGE.md"), knowledgeMd, "utf-8");
3948
+ writeFileSync7(join9(finalOutputDir, "SITE_KNOWLEDGE.md"), knowledgeMd, "utf-8");
3863
3949
  }
3864
3950
  process.stdout.write("\n");
3865
3951
  process.stdout.write("=== Plugin Generated ===\n");
@@ -4039,114 +4125,1944 @@ ${commands.join("\n\n")}
4039
4125
  `;
4040
4126
  }
4041
4127
 
4042
- // src/stdin.ts
4043
- import { readStdin, readCommandFile, splitFileLine } from "@dyyz1993/xcli-core";
4128
+ // src/site-memory/cli.ts
4129
+ import { open as openFile, readFile, stat } from "fs/promises";
4130
+ import { isAbsolute as isAbsolute2, resolve as resolve8 } from "path";
4044
4131
 
4045
- // src/cli/run-routes.ts
4046
- async function handleRun(filePath, options) {
4047
- let commands;
4132
+ // src/site-memory/runner.ts
4133
+ import { createHash, randomUUID } from "crypto";
4134
+ var SiteMemorySpecError = class extends Error {
4135
+ constructor(message) {
4136
+ super(message);
4137
+ this.name = "SiteMemorySpecError";
4138
+ }
4139
+ };
4140
+ async function runWorkflow(raw, store, openPage, options) {
4141
+ const parsed = parseSpec(raw);
4142
+ const definitionKey = computeDefinitionKey(parsed);
4143
+ const hints = options?.cold ? /* @__PURE__ */ new Map() : readHints(store, parsed, definitionKey);
4144
+ const attempts = [];
4145
+ const run = {
4146
+ runId: randomUUID(),
4147
+ origin: parsed.origin,
4148
+ flow: parsed.flow,
4149
+ definitionKey,
4150
+ startedAt: Date.now(),
4151
+ endedAt: 0,
4152
+ outcome: "failed",
4153
+ verified: false,
4154
+ attempts
4155
+ };
4156
+ let handle;
4157
+ let allPassed = false;
4048
4158
  try {
4049
- commands = readCommandFile(filePath);
4050
- } catch (e) {
4051
- outputError(`Failed to read file '${filePath}': ${errMsg(e)}`);
4052
- return;
4159
+ let page;
4160
+ try {
4161
+ handle = await openPage();
4162
+ page = handle.page;
4163
+ } catch {
4164
+ recordLaunchFailure(parsed, attempts);
4165
+ }
4166
+ if (page) {
4167
+ allPassed = await executeSteps(parsed, page, hints, attempts);
4168
+ }
4169
+ } finally {
4170
+ if (handle) {
4171
+ try {
4172
+ await handle.close();
4173
+ } catch (closeError) {
4174
+ void closeError;
4175
+ }
4176
+ }
4177
+ }
4178
+ run.endedAt = Date.now();
4179
+ run.outcome = allPassed ? "passed" : "failed";
4180
+ run.verified = allPassed;
4181
+ store.putRun(run);
4182
+ return run;
4183
+ }
4184
+ var LIMITS = {
4185
+ SPEC_VERSION: 1,
4186
+ MAX_STEPS: 32,
4187
+ MAX_SELECTORS_PER_CLICK: 8,
4188
+ MAX_ID_LEN: 64,
4189
+ MAX_SELECTOR_LEN: 200,
4190
+ MAX_PATH_LEN: 512,
4191
+ MAX_EQUALS_LEN: 256,
4192
+ GOTO_TIMEOUT_MS: 15e3,
4193
+ PROBE_TIMEOUT_MS: 3e3,
4194
+ CLICK_TIMEOUT_MS: 5e3,
4195
+ TEXT_WAIT_MS: 8e3,
4196
+ POLL_INTERVAL_MS: 100
4197
+ };
4198
+ var ID_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
4199
+ var ORDINAL_ID_PATTERN = /^(?:step|s|op|id)-?\d+$/;
4200
+ var CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
4201
+ var SELECTOR_CHARSET = /^[A-Za-z0-9#._[\]()="':~,+*>^$| -]+$/;
4202
+ var NON_CSS_PREFIX = /^(?:xpath|text|role|css)=/i;
4203
+ function specError(message) {
4204
+ throw new SiteMemorySpecError("site-memory: " + message);
4205
+ }
4206
+ function isPlainObject(value) {
4207
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4208
+ }
4209
+ function parseStepId(raw, index) {
4210
+ if (typeof raw !== "string" || raw.length === 0 || raw.length > LIMITS.MAX_ID_LEN || !ID_PATTERN.test(raw) || ORDINAL_ID_PATTERN.test(raw)) {
4211
+ specError(`steps[${index}].id must be a unique semantic kebab-case id`);
4053
4212
  }
4054
- if (commands.length === 0) {
4055
- outputError("No commands found in file");
4056
- return;
4213
+ return raw;
4214
+ }
4215
+ function isPlausibleCssSelector(selector) {
4216
+ if (selector.length === 0 || selector.length > LIMITS.MAX_SELECTOR_LEN || !SELECTOR_CHARSET.test(selector) || selector.includes(">>") || NON_CSS_PREFIX.test(selector)) {
4217
+ return false;
4057
4218
  }
4058
- const chain = commands.join(" ; ");
4059
- const chainResult = await executeChain(chain, {
4060
- cdpEndpoint: options?.cdpEndpoint,
4061
- sessionName: options?.sessionName,
4062
- fileMode: true
4063
- });
4064
- for (const step of chainResult.steps) {
4065
- if (step.success) {
4066
- process.stdout.write(`[OK] ${step.raw}
4067
- `);
4068
- if (step.data && typeof step.data === "object") {
4069
- const d = step.data;
4070
- for (const [k, v] of Object.entries(d)) {
4071
- if (k !== "ok")
4072
- process.stdout.write(` ${k}: ${typeof v === "string" ? v : JSON.stringify(v)}
4073
- `);
4074
- }
4075
- }
4076
- } else {
4077
- outputError(`[FAIL] ${step.raw}: ${step.message}`);
4219
+ let brackets = 0;
4220
+ let parens = 0;
4221
+ let quote = null;
4222
+ for (const ch of selector) {
4223
+ if (quote) {
4224
+ if (ch === quote) quote = null;
4225
+ continue;
4226
+ }
4227
+ if (ch === '"' || ch === "'") {
4228
+ quote = ch;
4229
+ continue;
4078
4230
  }
4231
+ if (ch === "[") brackets++;
4232
+ else if (ch === "]") brackets--;
4233
+ else if (ch === "(") parens++;
4234
+ else if (ch === ")") parens--;
4235
+ if (brackets < 0 || parens < 0) return false;
4079
4236
  }
4080
- if (chainResult.stoppedReason) {
4081
- outputError(`Stopped: ${chainResult.stoppedReason}`);
4237
+ return brackets === 0 && parens === 0 && quote === null;
4238
+ }
4239
+ function parseOrigin(raw) {
4240
+ if (typeof raw !== "string" || raw.length === 0 || raw.length > 2048) {
4241
+ specError("origin must be an http(s) URL string");
4242
+ }
4243
+ let parsed;
4244
+ try {
4245
+ parsed = new URL(raw);
4246
+ } catch {
4247
+ specError("origin must be a valid http(s) URL");
4248
+ }
4249
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
4250
+ specError("origin scheme must be http or https");
4251
+ }
4252
+ if (parsed.username !== "" || parsed.password !== "") {
4253
+ specError("origin must not contain credentials");
4254
+ }
4255
+ if (parsed.pathname !== "" && parsed.pathname !== "/" || parsed.search !== "" || parsed.hash !== "") {
4256
+ specError("origin must be a bare origin without path, query or fragment");
4257
+ }
4258
+ const origin = parsed.origin;
4259
+ if (!origin || origin === "null") {
4260
+ specError("origin must be an http(s) origin");
4082
4261
  }
4083
- if (!chainResult.success) process.exit(1);
4262
+ return origin;
4084
4263
  }
4085
-
4086
- // src/cli/viewer-routes.ts
4087
- async function handleViewer(_args, options, mode, _cdpEndpoint) {
4088
- const name = options.session || process.env.XBROWSER_SESSION || "default";
4089
- const selector = options.selector;
4090
- const userPort = options.port ? Number(options.port) : void 0;
4091
- let status = getDaemonProcessStatus();
4092
- if (!status.running) {
4093
- await startDaemonProcess(userPort || 9224);
4094
- status = getDaemonProcessStatus();
4095
- }
4096
- const port = userPort || status.port || getDaemonConfig().basePort;
4097
- let url = `http://localhost:${port}/preview/${name}`;
4098
- if (selector) {
4099
- try {
4100
- const resp = await forwardViewerCheckSelector(name, selector);
4101
- if (resp.found) {
4102
- url += `#focus=${encodeURIComponent(selector)}`;
4264
+ function hasExactKeys(value, keys) {
4265
+ const actual = Object.keys(value);
4266
+ if (actual.length !== keys.length) return false;
4267
+ return keys.every((k) => k in value);
4268
+ }
4269
+ function parseSpec(raw) {
4270
+ if (!isPlainObject(raw)) {
4271
+ specError("spec must be a plain JSON object");
4272
+ }
4273
+ if (!hasExactKeys(raw, ["origin", "flow", "steps"])) {
4274
+ specError("spec must have exactly the keys: origin, flow, steps");
4275
+ }
4276
+ const origin = parseOrigin(raw.origin);
4277
+ const flow = raw.flow;
4278
+ if (typeof flow !== "string" || flow.length === 0 || flow.length > LIMITS.MAX_ID_LEN || !ID_PATTERN.test(flow)) {
4279
+ specError("flow must be 1-64 chars, lowercase kebab-case, starting with a letter");
4280
+ }
4281
+ const rawSteps = raw.steps;
4282
+ if (!Array.isArray(rawSteps) || rawSteps.length === 0) {
4283
+ specError("steps must be a non-empty array");
4284
+ }
4285
+ if (rawSteps.length > LIMITS.MAX_STEPS) {
4286
+ specError(`steps must not exceed ${LIMITS.MAX_STEPS} entries`);
4287
+ }
4288
+ const seenIds = /* @__PURE__ */ new Set();
4289
+ const steps = rawSteps.map((value, index) => {
4290
+ if (!isPlainObject(value)) {
4291
+ specError(`steps[${index}] must be a plain object`);
4292
+ }
4293
+ if (typeof value.op !== "string") {
4294
+ specError(`steps[${index}].op must be a string`);
4295
+ }
4296
+ const id = parseStepId(value.id, index);
4297
+ if (seenIds.has(id)) {
4298
+ specError(`steps[${index}].id must be unique across steps`);
4299
+ }
4300
+ seenIds.add(id);
4301
+ if (value.op === "goto") {
4302
+ if (!hasExactKeys(value, ["id", "op", "path"])) {
4303
+ specError(`steps[${index}] (goto) must have exactly id, op, path`);
4103
4304
  }
4104
- } catch {
4305
+ return parseGotoStep(value, id, index, origin);
4306
+ }
4307
+ if (value.op === "click") {
4308
+ if (!hasExactKeys(value, ["id", "op", "selectors"])) {
4309
+ specError(`steps[${index}] (click) must have exactly id, op, selectors`);
4310
+ }
4311
+ return parseClickStep(value, id, index);
4312
+ }
4313
+ if (value.op === "expect-text") {
4314
+ if (!hasExactKeys(value, ["id", "op", "selector", "equals"])) {
4315
+ specError(
4316
+ `steps[${index}] (expect-text) must have exactly id, op, selector, equals`
4317
+ );
4318
+ }
4319
+ return parseExpectTextStep(value, id, index);
4105
4320
  }
4321
+ specError(`steps[${index}].op must be one of goto, click, expect-text`);
4322
+ });
4323
+ if (steps[0].op !== "goto") {
4324
+ specError("the first step must be a goto (anchors the origin)");
4106
4325
  }
4107
- outputResult({ url, name, focused: !!selector && url.includes("#focus=") }, mode);
4326
+ if (steps[steps.length - 1].op !== "expect-text") {
4327
+ specError("the last step must be an expect-text (verification proof)");
4328
+ }
4329
+ return { origin, flow, steps };
4108
4330
  }
4109
-
4110
- // src/cli/net-routes.ts
4111
- async function handleNetCommand(args, options, mode, sessionName) {
4112
- const subCommand = args[0] || "list";
4113
- const netSession = sessionName;
4331
+ function parseGotoStep(value, id, index, origin) {
4332
+ const path2 = value.path;
4333
+ if (typeof path2 !== "string" || path2.length === 0 || path2.length > LIMITS.MAX_PATH_LEN || !path2.startsWith("/") || path2.startsWith("//") || CONTROL_CHARS.test(path2)) {
4334
+ specError(`steps[${index}].path must be a root-relative same-origin path`);
4335
+ }
4114
4336
  try {
4115
- switch (subCommand) {
4116
- case "list": {
4117
- const filter = options.filter;
4118
- const method = options.method;
4119
- const limit = options.limit ? Number(options.limit) : 50;
4120
- const result = await forwardNetworkList(netSession, { filter, method, limit });
4121
- if (mode === "json") {
4122
- outputResult(result, mode);
4123
- } else {
4124
- process.stdout.write(`
4125
- Network captures (session: ${netSession})`);
4126
- process.stdout.write(` Total: ${result.total}, Showing: ${result.captures.length}
4127
- `);
4128
- for (const c of result.captures) {
4129
- const statusColor = c.status < 300 ? "\x1B[32m" : c.status < 400 ? "\x1B[33m" : "\x1B[31m";
4130
- const reset = "\x1B[0m";
4131
- process.stdout.write(` #${c.id} ${c.method.padEnd(6)} ${statusColor}${c.status}${reset} ${c.resourceType.padEnd(10)} ${c.path}
4132
- `);
4133
- if (c.size > 0) {
4134
- const sizeStr = c.size > 1024 ? `${(c.size / 1024).toFixed(1)}KB` : `${c.size}B`;
4135
- process.stdout.write(` ${c.contentType.split(";")[0]} ${sizeStr}
4136
- `);
4137
- }
4138
- }
4139
- process.stdout.write("\n");
4140
- }
4141
- break;
4337
+ const resolved = new URL(path2, origin);
4338
+ if (resolved.origin !== origin) {
4339
+ specError(`steps[${index}].path resolves to a different origin`);
4340
+ }
4341
+ } catch {
4342
+ specError(`steps[${index}].path is not a resolvable path`);
4343
+ }
4344
+ return { id, op: "goto", path: path2 };
4345
+ }
4346
+ function parseClickStep(value, id, index) {
4347
+ const selectors = value.selectors;
4348
+ if (!Array.isArray(selectors) || selectors.length === 0 || selectors.length > LIMITS.MAX_SELECTORS_PER_CLICK) {
4349
+ specError(
4350
+ `steps[${index}].selectors must contain 1..${LIMITS.MAX_SELECTORS_PER_CLICK} CSS selectors`
4351
+ );
4352
+ }
4353
+ const seen = /* @__PURE__ */ new Set();
4354
+ for (const selector of selectors) {
4355
+ if (typeof selector !== "string" || !isPlausibleCssSelector(selector)) {
4356
+ specError(`steps[${index}].selectors must be plain CSS selector strings`);
4357
+ }
4358
+ if (seen.has(selector)) {
4359
+ specError(`steps[${index}].selectors must not contain duplicates`);
4360
+ }
4361
+ seen.add(selector);
4362
+ }
4363
+ return { id, op: "click", selectors };
4364
+ }
4365
+ function parseExpectTextStep(value, id, index) {
4366
+ const selector = value.selector;
4367
+ if (typeof selector !== "string" || !isPlausibleCssSelector(selector)) {
4368
+ specError(`steps[${index}].selector must be a plain CSS selector string`);
4369
+ }
4370
+ const equals = value.equals;
4371
+ if (typeof equals !== "string" || equals.trim().length === 0 || equals.length > LIMITS.MAX_EQUALS_LEN) {
4372
+ specError(`steps[${index}].equals must be 1..${LIMITS.MAX_EQUALS_LEN} chars of text`);
4373
+ }
4374
+ return { id, op: "expect-text", selector, equals };
4375
+ }
4376
+ function computeDefinitionKey(parsed) {
4377
+ const normalized = {
4378
+ v: LIMITS.SPEC_VERSION,
4379
+ origin: parsed.origin,
4380
+ flow: parsed.flow,
4381
+ steps: parsed.steps.map((step) => {
4382
+ if (step.op === "goto") {
4383
+ return { id: step.id, op: step.op, path: step.path };
4142
4384
  }
4143
- case "clear": {
4144
- await forwardNetworkClear(netSession);
4145
- process.stdout.write(`Network captures cleared for session: ${netSession}
4146
- `);
4147
- break;
4385
+ if (step.op === "click") {
4386
+ return { id: step.id, op: step.op, selectors: [...step.selectors] };
4148
4387
  }
4149
- case "top": {
4388
+ return { id: step.id, op: step.op, selector: step.selector, equals: step.equals };
4389
+ })
4390
+ };
4391
+ return createHash("sha256").update(`site-memory/spec/v${LIMITS.SPEC_VERSION}
4392
+ `).update(JSON.stringify(normalized)).digest("hex");
4393
+ }
4394
+ function readHints(store, parsed, definitionKey) {
4395
+ try {
4396
+ const brief = store.getBrief(parsed.origin, parsed.flow, definitionKey);
4397
+ const hints = /* @__PURE__ */ new Map();
4398
+ if (!brief || !Array.isArray(brief.hints)) {
4399
+ return hints;
4400
+ }
4401
+ for (const hint of brief.hints) {
4402
+ if (hint && typeof hint.stepId === "string" && Number.isInteger(hint.candidate) && hint.candidate >= 0) {
4403
+ hints.set(hint.stepId, hint);
4404
+ }
4405
+ }
4406
+ return hints;
4407
+ } catch {
4408
+ return /* @__PURE__ */ new Map();
4409
+ }
4410
+ }
4411
+ function probeOrder(step, hint) {
4412
+ const order = step.selectors.map((_, i) => i);
4413
+ if (hint && hint.candidate > 0 && hint.candidate < step.selectors.length) {
4414
+ return [hint.candidate, ...order.filter((i) => i !== hint.candidate)];
4415
+ }
4416
+ return order;
4417
+ }
4418
+ function sleep(ms, page) {
4419
+ if (page.waitForTimeout) return page.waitForTimeout(ms);
4420
+ return new Promise((resolve10) => setTimeout(resolve10, ms));
4421
+ }
4422
+ function originGuard(page, origin) {
4423
+ let rawUrl;
4424
+ try {
4425
+ rawUrl = page.url();
4426
+ } catch {
4427
+ return "browser-error";
4428
+ }
4429
+ try {
4430
+ return new URL(rawUrl).origin === origin ? null : "origin-changed";
4431
+ } catch {
4432
+ return "origin-changed";
4433
+ }
4434
+ }
4435
+ function recordLaunchFailure(parsed, attempts) {
4436
+ const first = parsed.steps[0];
4437
+ attempts.push({
4438
+ stepId: first.id,
4439
+ operation: first.op,
4440
+ attempt: 1,
4441
+ startedAt: Date.now(),
4442
+ durationMs: 0,
4443
+ outcome: "failed",
4444
+ errorCode: "browser-error"
4445
+ });
4446
+ }
4447
+ async function executeSteps(parsed, page, hints, attempts) {
4448
+ const counters = /* @__PURE__ */ new Map();
4449
+ const nextAttempt = (stepId) => {
4450
+ const n = (counters.get(stepId) ?? 0) + 1;
4451
+ counters.set(stepId, n);
4452
+ return n;
4453
+ };
4454
+ for (const step of parsed.steps) {
4455
+ if (step.op === "goto") {
4456
+ const passed2 = await runGotoStep(parsed.origin, step, page, nextAttempt, attempts);
4457
+ if (!passed2) return false;
4458
+ continue;
4459
+ }
4460
+ const guard = originGuard(page, parsed.origin);
4461
+ if (guard) {
4462
+ attempts.push({
4463
+ stepId: step.id,
4464
+ operation: step.op,
4465
+ attempt: nextAttempt(step.id),
4466
+ startedAt: Date.now(),
4467
+ durationMs: 0,
4468
+ outcome: "failed",
4469
+ errorCode: guard
4470
+ });
4471
+ return false;
4472
+ }
4473
+ const passed = step.op === "click" ? await runClickStep(step, page, hints.get(step.id), nextAttempt, attempts) : await runExpectTextStep(step, page, nextAttempt, attempts);
4474
+ if (!passed) return false;
4475
+ }
4476
+ return true;
4477
+ }
4478
+ async function runGotoStep(origin, step, page, nextAttempt, attempts) {
4479
+ const startedAt = Date.now();
4480
+ let errorCode;
4481
+ try {
4482
+ await page.goto(origin + step.path, { timeout: LIMITS.GOTO_TIMEOUT_MS });
4483
+ errorCode = originGuard(page, origin) ?? void 0;
4484
+ } catch {
4485
+ errorCode = "navigation-failed";
4486
+ }
4487
+ attempts.push({
4488
+ stepId: step.id,
4489
+ operation: "goto",
4490
+ attempt: nextAttempt(step.id),
4491
+ startedAt,
4492
+ durationMs: Date.now() - startedAt,
4493
+ outcome: errorCode ? "failed" : "passed",
4494
+ errorCode
4495
+ });
4496
+ return !errorCode;
4497
+ }
4498
+ async function runClickStep(step, page, hint, nextAttempt, attempts) {
4499
+ for (const candidate of probeOrder(step, hint)) {
4500
+ const startedAt = Date.now();
4501
+ const source = hint && candidate === hint.candidate ? "memory" : "definition";
4502
+ let locator;
4503
+ try {
4504
+ locator = page.locator(step.selectors[candidate]);
4505
+ } catch {
4506
+ attempts.push({
4507
+ stepId: step.id,
4508
+ operation: "click",
4509
+ attempt: nextAttempt(step.id),
4510
+ startedAt,
4511
+ durationMs: Date.now() - startedAt,
4512
+ outcome: "failed",
4513
+ errorCode: "browser-error",
4514
+ candidate,
4515
+ source
4516
+ });
4517
+ return false;
4518
+ }
4519
+ try {
4520
+ await locator.waitFor({ state: "visible", timeout: LIMITS.PROBE_TIMEOUT_MS });
4521
+ } catch {
4522
+ attempts.push({
4523
+ stepId: step.id,
4524
+ operation: "click",
4525
+ attempt: nextAttempt(step.id),
4526
+ startedAt,
4527
+ durationMs: Date.now() - startedAt,
4528
+ outcome: "failed",
4529
+ errorCode: "selector-not-ready",
4530
+ candidate,
4531
+ source
4532
+ });
4533
+ continue;
4534
+ }
4535
+ try {
4536
+ await locator.click({ timeout: LIMITS.CLICK_TIMEOUT_MS });
4537
+ } catch {
4538
+ attempts.push({
4539
+ stepId: step.id,
4540
+ operation: "click",
4541
+ attempt: nextAttempt(step.id),
4542
+ startedAt,
4543
+ durationMs: Date.now() - startedAt,
4544
+ outcome: "failed",
4545
+ errorCode: "click-failed",
4546
+ candidate,
4547
+ source
4548
+ });
4549
+ return false;
4550
+ }
4551
+ attempts.push({
4552
+ stepId: step.id,
4553
+ operation: "click",
4554
+ attempt: nextAttempt(step.id),
4555
+ startedAt,
4556
+ durationMs: Date.now() - startedAt,
4557
+ outcome: "passed",
4558
+ candidate,
4559
+ source
4560
+ });
4561
+ return true;
4562
+ }
4563
+ return false;
4564
+ }
4565
+ async function runExpectTextStep(step, page, nextAttempt, attempts) {
4566
+ const startedAt = Date.now();
4567
+ const fail3 = (errorCode) => {
4568
+ attempts.push({
4569
+ stepId: step.id,
4570
+ operation: "expect-text",
4571
+ attempt: nextAttempt(step.id),
4572
+ startedAt,
4573
+ durationMs: Date.now() - startedAt,
4574
+ outcome: "failed",
4575
+ errorCode
4576
+ });
4577
+ return false;
4578
+ };
4579
+ let locator;
4580
+ try {
4581
+ locator = page.locator(step.selector);
4582
+ } catch {
4583
+ return fail3("browser-error");
4584
+ }
4585
+ try {
4586
+ await locator.waitFor({ state: "visible", timeout: LIMITS.TEXT_WAIT_MS });
4587
+ } catch {
4588
+ return fail3("selector-not-ready");
4589
+ }
4590
+ const expected = step.equals.trim();
4591
+ const deadline = Date.now() + LIMITS.TEXT_WAIT_MS;
4592
+ for (; ; ) {
4593
+ let text;
4594
+ try {
4595
+ text = await locator.textContent();
4596
+ } catch {
4597
+ return fail3("browser-error");
4598
+ }
4599
+ if ((text ?? "").trim() === expected) {
4600
+ attempts.push({
4601
+ stepId: step.id,
4602
+ operation: "expect-text",
4603
+ attempt: nextAttempt(step.id),
4604
+ startedAt,
4605
+ durationMs: Date.now() - startedAt,
4606
+ outcome: "passed"
4607
+ });
4608
+ return true;
4609
+ }
4610
+ if (Date.now() >= deadline) {
4611
+ return fail3("assertion-failed");
4612
+ }
4613
+ await sleep(LIMITS.POLL_INTERVAL_MS, page);
4614
+ }
4615
+ }
4616
+
4617
+ // src/site-memory/store.ts
4618
+ import { mkdirSync as mkdirSync6, existsSync as existsSync10 } from "fs";
4619
+ import { createRequire } from "module";
4620
+ import { homedir as homedir3 } from "os";
4621
+ import { dirname as dirname4, join as join7, resolve as resolve7 } from "path";
4622
+ var databaseSyncCtor;
4623
+ function loadDatabaseSync() {
4624
+ if (!databaseSyncCtor) {
4625
+ const nodeRequire = createRequire(import.meta.url);
4626
+ const mod = nodeRequire("node:sqlite");
4627
+ databaseSyncCtor = mod.DatabaseSync;
4628
+ }
4629
+ return databaseSyncCtor;
4630
+ }
4631
+ var SCHEMA_VERSION = 1;
4632
+ var BUSY_TIMEOUT_MS = 5e3;
4633
+ var BRIEF_RECENCY_MS = 30 * 24 * 60 * 60 * 1e3;
4634
+ var MAX_RUNS_PER_SITE_FLOW = 200;
4635
+ var DEFAULT_RUN_LIMIT = 50;
4636
+ var MAX_RUN_LIMIT = 1e3;
4637
+ var MAX_ATTEMPTS_PER_RUN = 1e3;
4638
+ var MAX_RUN_ID_LENGTH = 128;
4639
+ var MAX_KEY_LENGTH = 512;
4640
+ var MAX_STEP_ID_LENGTH = 256;
4641
+ var OPERATIONS = ["goto", "click", "expect-text"];
4642
+ var OUTCOMES = ["passed", "failed"];
4643
+ var ERROR_CODES = [
4644
+ "browser-error",
4645
+ "navigation-failed",
4646
+ "origin-changed",
4647
+ "selector-not-ready",
4648
+ "click-failed",
4649
+ "assertion-failed"
4650
+ ];
4651
+ var SOURCES = ["definition", "memory"];
4652
+ var SCHEMA_SQL = `
4653
+ CREATE TABLE IF NOT EXISTS runs (
4654
+ run_id TEXT PRIMARY KEY,
4655
+ origin TEXT NOT NULL,
4656
+ flow TEXT NOT NULL,
4657
+ definition_key TEXT NOT NULL,
4658
+ started_at REAL NOT NULL,
4659
+ ended_at REAL NOT NULL,
4660
+ outcome TEXT NOT NULL,
4661
+ verified INTEGER NOT NULL
4662
+ );
4663
+ CREATE INDEX IF NOT EXISTS idx_runs_site_time ON runs (origin, flow, started_at DESC);
4664
+ CREATE INDEX IF NOT EXISTS idx_runs_definition ON runs (origin, flow, definition_key, ended_at DESC);
4665
+
4666
+ CREATE TABLE IF NOT EXISTS run_attempts (
4667
+ attempt_row_id INTEGER PRIMARY KEY AUTOINCREMENT,
4668
+ run_id TEXT NOT NULL REFERENCES runs (run_id) ON DELETE CASCADE,
4669
+ seq INTEGER NOT NULL,
4670
+ step_id TEXT NOT NULL,
4671
+ operation TEXT NOT NULL,
4672
+ attempt_no INTEGER NOT NULL,
4673
+ started_at REAL NOT NULL,
4674
+ duration_ms REAL NOT NULL,
4675
+ outcome TEXT NOT NULL,
4676
+ error_code TEXT,
4677
+ candidate INTEGER,
4678
+ source TEXT
4679
+ );
4680
+ CREATE INDEX IF NOT EXISTS idx_attempts_run ON run_attempts (run_id, seq);
4681
+ `;
4682
+ var SQL_INSERT_RUN = `
4683
+ INSERT INTO runs (run_id, origin, flow, definition_key, started_at, ended_at, outcome, verified)
4684
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
4685
+ ON CONFLICT (run_id) DO NOTHING
4686
+ `;
4687
+ var SQL_INSERT_ATTEMPT = `
4688
+ INSERT INTO run_attempts
4689
+ (run_id, seq, step_id, operation, attempt_no, started_at, duration_ms, outcome, error_code, candidate, source)
4690
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
4691
+ `;
4692
+ var SQL_PRUNE_RUNS = `
4693
+ DELETE FROM runs
4694
+ WHERE origin = ? AND flow = ?
4695
+ AND run_id NOT IN (
4696
+ SELECT run_id FROM runs WHERE origin = ? AND flow = ?
4697
+ ORDER BY started_at DESC, rowid DESC LIMIT ?
4698
+ )
4699
+ `;
4700
+ var SQL_GET_RUN = `
4701
+ SELECT run_id, origin, flow, definition_key, started_at, ended_at, outcome, verified
4702
+ FROM runs WHERE run_id = ?
4703
+ `;
4704
+ var SQL_GET_ATTEMPTS = `
4705
+ SELECT step_id, operation, attempt_no, started_at, duration_ms, outcome, error_code, candidate, source
4706
+ FROM run_attempts WHERE run_id = ?
4707
+ ORDER BY seq ASC, attempt_row_id ASC
4708
+ `;
4709
+ var SQL_LIST_RUNS_BY_ORIGIN = `
4710
+ SELECT run_id, origin, flow, definition_key, started_at, ended_at, outcome, verified
4711
+ FROM runs WHERE origin = ?
4712
+ ORDER BY started_at DESC, rowid DESC LIMIT ?
4713
+ `;
4714
+ var SQL_LIST_RUNS_BY_ORIGIN_FLOW = `
4715
+ SELECT run_id, origin, flow, definition_key, started_at, ended_at, outcome, verified
4716
+ FROM runs WHERE origin = ? AND flow = ?
4717
+ ORDER BY started_at DESC, rowid DESC LIMIT ?
4718
+ `;
4719
+ var SQL_LIST_SITES = `
4720
+ SELECT origin, flow, COUNT(*) AS runs,
4721
+ SUM(CASE WHEN outcome = 'passed' THEN 1 ELSE 0 END) AS passed,
4722
+ MAX(started_at) AS last_run_at
4723
+ FROM runs
4724
+ GROUP BY origin, flow
4725
+ ORDER BY origin ASC, flow ASC
4726
+ `;
4727
+ var SQL_STATS_ROWS = `
4728
+ SELECT r.run_id AS run_id, a.step_id AS step_id, a.operation AS operation,
4729
+ a.outcome AS outcome, a.error_code AS error_code
4730
+ FROM runs r JOIN run_attempts a ON a.run_id = r.run_id
4731
+ WHERE r.origin = ? AND r.flow = ?
4732
+ ORDER BY r.started_at ASC, r.rowid ASC, a.attempt_row_id ASC
4733
+ `;
4734
+ var SQL_HINT_ROWS = `
4735
+ SELECT a.step_id AS step_id, a.candidate AS candidate, r.ended_at AS ended_at
4736
+ FROM runs r JOIN run_attempts a ON a.run_id = r.run_id
4737
+ WHERE r.origin = ? AND r.flow = ? AND r.definition_key = ?
4738
+ AND r.outcome = 'passed' AND r.verified = 1
4739
+ AND a.outcome = 'passed' AND a.candidate IS NOT NULL
4740
+ ORDER BY r.ended_at DESC, a.attempt_row_id DESC
4741
+ `;
4742
+ var SQL_MAX_FAILED = `
4743
+ SELECT MAX(ended_at) AS max_failed
4744
+ FROM runs
4745
+ WHERE origin = ? AND flow = ? AND definition_key = ? AND outcome = 'failed'
4746
+ `;
4747
+ function isPlainObject2(value) {
4748
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4749
+ }
4750
+ function boundedString(value, maxLength) {
4751
+ if (typeof value !== "string" || value.length === 0 || value.length > maxLength) {
4752
+ return null;
4753
+ }
4754
+ return value;
4755
+ }
4756
+ function finiteNumber(value) {
4757
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
4758
+ }
4759
+ function oneOf(value, allow) {
4760
+ if (typeof value !== "string") return null;
4761
+ return allow.includes(value) ? value : null;
4762
+ }
4763
+ function parseAttempt(raw) {
4764
+ if (!isPlainObject2(raw)) return null;
4765
+ const stepId = boundedString(raw.stepId, MAX_STEP_ID_LENGTH);
4766
+ if (!stepId) return null;
4767
+ const operation = oneOf(raw.operation, OPERATIONS);
4768
+ if (!operation) return null;
4769
+ if (typeof raw.attempt !== "number" || !Number.isInteger(raw.attempt) || raw.attempt < 0) return null;
4770
+ const startedAt = finiteNumber(raw.startedAt);
4771
+ if (startedAt === null) return null;
4772
+ const durationMs = finiteNumber(raw.durationMs);
4773
+ if (durationMs === null || durationMs < 0) return null;
4774
+ const outcome = oneOf(raw.outcome, OUTCOMES);
4775
+ if (!outcome) return null;
4776
+ const attempt = { stepId, operation, attempt: raw.attempt, startedAt, durationMs, outcome };
4777
+ if (raw.errorCode !== void 0 && raw.errorCode !== null) {
4778
+ const errorCode = oneOf(raw.errorCode, ERROR_CODES);
4779
+ if (!errorCode) return null;
4780
+ attempt.errorCode = errorCode;
4781
+ }
4782
+ if (raw.candidate !== void 0 && raw.candidate !== null) {
4783
+ if (typeof raw.candidate !== "number" || !Number.isInteger(raw.candidate) || raw.candidate < 0) return null;
4784
+ attempt.candidate = raw.candidate;
4785
+ }
4786
+ if (raw.source !== void 0 && raw.source !== null) {
4787
+ const source = oneOf(raw.source, SOURCES);
4788
+ if (!source) return null;
4789
+ attempt.source = source;
4790
+ }
4791
+ return attempt;
4792
+ }
4793
+ function parseMemoryRun(input) {
4794
+ if (!isPlainObject2(input)) return null;
4795
+ const runId = boundedString(input.runId, MAX_RUN_ID_LENGTH);
4796
+ if (!runId) return null;
4797
+ const origin = boundedString(input.origin, MAX_KEY_LENGTH);
4798
+ if (!origin) return null;
4799
+ const flow = boundedString(input.flow, MAX_KEY_LENGTH);
4800
+ if (!flow) return null;
4801
+ const definitionKey = boundedString(input.definitionKey, MAX_KEY_LENGTH);
4802
+ if (!definitionKey) return null;
4803
+ const startedAt = finiteNumber(input.startedAt);
4804
+ if (startedAt === null) return null;
4805
+ const endedAt = finiteNumber(input.endedAt);
4806
+ if (endedAt === null || endedAt < startedAt) return null;
4807
+ const outcome = oneOf(input.outcome, OUTCOMES);
4808
+ if (!outcome) return null;
4809
+ if (typeof input.verified !== "boolean") return null;
4810
+ if (!Array.isArray(input.attempts) || input.attempts.length > MAX_ATTEMPTS_PER_RUN) return null;
4811
+ const attempts = [];
4812
+ for (const raw of input.attempts) {
4813
+ const attempt = parseAttempt(raw);
4814
+ if (!attempt) return null;
4815
+ attempts.push(attempt);
4816
+ }
4817
+ return { runId, origin, flow, definitionKey, startedAt, endedAt, outcome, verified: input.verified, attempts };
4818
+ }
4819
+ function toOperation(value) {
4820
+ return value === "goto" || value === "expect-text" ? value : "click";
4821
+ }
4822
+ function rowToRunSummary(row) {
4823
+ return {
4824
+ runId: String(row.run_id),
4825
+ origin: String(row.origin),
4826
+ flow: String(row.flow),
4827
+ definitionKey: String(row.definition_key),
4828
+ startedAt: Number(row.started_at),
4829
+ endedAt: Number(row.ended_at),
4830
+ outcome: row.outcome === "passed" ? "passed" : "failed",
4831
+ verified: Number(row.verified) === 1
4832
+ };
4833
+ }
4834
+ function rowToAttempt(row) {
4835
+ const attempt = {
4836
+ stepId: String(row.step_id),
4837
+ operation: toOperation(row.operation),
4838
+ attempt: Number(row.attempt_no),
4839
+ startedAt: Number(row.started_at),
4840
+ durationMs: Number(row.duration_ms),
4841
+ outcome: row.outcome === "passed" ? "passed" : "failed"
4842
+ };
4843
+ if (typeof row.error_code === "string") attempt.errorCode = row.error_code;
4844
+ if (row.candidate !== null && row.candidate !== void 0) attempt.candidate = Number(row.candidate);
4845
+ if (typeof row.source === "string") attempt.source = row.source;
4846
+ return attempt;
4847
+ }
4848
+ function normalizeLimit(limit) {
4849
+ if (typeof limit !== "number" || !Number.isFinite(limit) || limit < 1) return DEFAULT_RUN_LIMIT;
4850
+ return Math.min(Math.floor(limit), MAX_RUN_LIMIT);
4851
+ }
4852
+ function aggregateStats(rows) {
4853
+ const executions = /* @__PURE__ */ new Map();
4854
+ const steps = /* @__PURE__ */ new Map();
4855
+ let order = 0;
4856
+ for (const row of rows) {
4857
+ const runId = String(row.run_id);
4858
+ const stepId = String(row.step_id);
4859
+ const operation = toOperation(row.operation);
4860
+ let step = steps.get(stepId);
4861
+ if (!step) {
4862
+ step = { stepId, order: order++, operation, executions: 0, attempts: 0, failedAttempts: 0, passedExecutions: 0, errors: /* @__PURE__ */ new Map() };
4863
+ steps.set(stepId, step);
4864
+ }
4865
+ const execKey = `${runId}\0${stepId}`;
4866
+ let exec = executions.get(execKey);
4867
+ if (!exec) {
4868
+ exec = { stepId, hasPassed: false };
4869
+ executions.set(execKey, exec);
4870
+ step.executions += 1;
4871
+ }
4872
+ step.attempts += 1;
4873
+ step.operation = operation;
4874
+ if (row.outcome === "failed") {
4875
+ step.failedAttempts += 1;
4876
+ if (typeof row.error_code === "string") {
4877
+ const code = row.error_code;
4878
+ step.errors.set(code, (step.errors.get(code) ?? 0) + 1);
4879
+ }
4880
+ } else {
4881
+ exec.hasPassed = true;
4882
+ }
4883
+ }
4884
+ for (const exec of executions.values()) {
4885
+ const step = steps.get(exec.stepId);
4886
+ if (exec.hasPassed && step) step.passedExecutions += 1;
4887
+ }
4888
+ return [...steps.values()].sort((a, b) => a.order - b.order).map((step) => ({
4889
+ stepId: step.stepId,
4890
+ operation: step.operation,
4891
+ executions: step.executions,
4892
+ attempts: step.attempts,
4893
+ failedAttempts: step.failedAttempts,
4894
+ passedExecutions: step.passedExecutions,
4895
+ errors: Object.fromEntries(step.errors)
4896
+ }));
4897
+ }
4898
+ var SqliteSiteMemoryStore = class {
4899
+ db;
4900
+ statements = /* @__PURE__ */ new Map();
4901
+ readOnly;
4902
+ closed = false;
4903
+ constructor(db, readOnly) {
4904
+ this.db = db;
4905
+ this.readOnly = readOnly;
4906
+ }
4907
+ stmt(key, sql) {
4908
+ let statement = this.statements.get(key);
4909
+ if (!statement) {
4910
+ statement = this.db.prepare(sql);
4911
+ this.statements.set(key, statement);
4912
+ }
4913
+ return statement;
4914
+ }
4915
+ putRun(run) {
4916
+ if (this.readOnly) return;
4917
+ if (this.closed) {
4918
+ throw sanitizeError("putRun failed: store is closed");
4919
+ }
4920
+ const clean = parseMemoryRun(run);
4921
+ if (!clean) {
4922
+ const runIdHint = isPlainObject2(run) && typeof run.runId === "string" ? ` (runId "${run.runId.slice(0, MAX_RUN_ID_LENGTH)}")` : "";
4923
+ throw sanitizeError(`putRun rejected a run that does not match the sealed MemoryRun shape${runIdHint}`);
4924
+ }
4925
+ try {
4926
+ this.writeRun(clean);
4927
+ } catch (err) {
4928
+ throw sanitizeError("putRun failed to persist run", err);
4929
+ }
4930
+ }
4931
+ writeRun(run) {
4932
+ this.db.exec("BEGIN IMMEDIATE");
4933
+ try {
4934
+ const inserted = this.stmt("insert-run", SQL_INSERT_RUN).run(
4935
+ run.runId,
4936
+ run.origin,
4937
+ run.flow,
4938
+ run.definitionKey,
4939
+ run.startedAt,
4940
+ run.endedAt,
4941
+ run.outcome,
4942
+ run.verified ? 1 : 0
4943
+ );
4944
+ if (Number(inserted.changes) === 1) {
4945
+ const insertAttempt = this.stmt("insert-attempt", SQL_INSERT_ATTEMPT);
4946
+ for (let i = 0; i < run.attempts.length; i++) {
4947
+ const attempt = run.attempts[i];
4948
+ insertAttempt.run(
4949
+ run.runId,
4950
+ i,
4951
+ attempt.stepId,
4952
+ attempt.operation,
4953
+ attempt.attempt,
4954
+ attempt.startedAt,
4955
+ attempt.durationMs,
4956
+ attempt.outcome,
4957
+ attempt.errorCode ?? null,
4958
+ attempt.candidate ?? null,
4959
+ attempt.source ?? null
4960
+ );
4961
+ }
4962
+ this.stmt("prune-runs", SQL_PRUNE_RUNS).run(
4963
+ run.origin,
4964
+ run.flow,
4965
+ run.origin,
4966
+ run.flow,
4967
+ MAX_RUNS_PER_SITE_FLOW
4968
+ );
4969
+ }
4970
+ this.db.exec("COMMIT");
4971
+ } catch (err) {
4972
+ try {
4973
+ this.db.exec("ROLLBACK");
4974
+ } catch {
4975
+ }
4976
+ throw err;
4977
+ }
4978
+ }
4979
+ listSites() {
4980
+ if (this.closed) return [];
4981
+ try {
4982
+ const rows = this.stmt("list-sites", SQL_LIST_SITES).all();
4983
+ return rows.map((row) => {
4984
+ const r = row;
4985
+ return {
4986
+ origin: String(r.origin),
4987
+ flow: String(r.flow),
4988
+ runs: Number(r.runs),
4989
+ passed: Number(r.passed),
4990
+ lastRunAt: Number(r.last_run_at)
4991
+ };
4992
+ });
4993
+ } catch {
4994
+ return [];
4995
+ }
4996
+ }
4997
+ listRuns(origin, flow, limit) {
4998
+ if (this.closed) return [];
4999
+ try {
5000
+ const capped = normalizeLimit(limit);
5001
+ const rows = flow === void 0 ? this.stmt("list-runs-origin", SQL_LIST_RUNS_BY_ORIGIN).all(origin, capped) : this.stmt("list-runs-origin-flow", SQL_LIST_RUNS_BY_ORIGIN_FLOW).all(origin, flow, capped);
5002
+ return rows.map((row) => rowToRunSummary(row));
5003
+ } catch {
5004
+ return [];
5005
+ }
5006
+ }
5007
+ getRun(runId) {
5008
+ if (this.closed) return null;
5009
+ try {
5010
+ const row = this.stmt("get-run", SQL_GET_RUN).get(runId);
5011
+ if (!row) return null;
5012
+ const attempts = this.stmt("get-attempts", SQL_GET_ATTEMPTS).all(runId).map(
5013
+ (r) => rowToAttempt(r)
5014
+ );
5015
+ return { ...rowToRunSummary(row), attempts };
5016
+ } catch {
5017
+ return null;
5018
+ }
5019
+ }
5020
+ getStats(origin, flow) {
5021
+ if (this.closed) return [];
5022
+ try {
5023
+ const rows = this.stmt("stats-rows", SQL_STATS_ROWS).all(origin, flow).map(
5024
+ (row) => row
5025
+ );
5026
+ return aggregateStats(rows);
5027
+ } catch {
5028
+ return [];
5029
+ }
5030
+ }
5031
+ getBrief(origin, flow, definitionKey) {
5032
+ if (this.closed) return { origin, flow, hints: [] };
5033
+ try {
5034
+ const now = Date.now();
5035
+ const failedRow = this.stmt("max-failed", SQL_MAX_FAILED).get(origin, flow, definitionKey);
5036
+ const maxFailed = failedRow && failedRow.max_failed !== null && failedRow.max_failed !== void 0 ? Number(failedRow.max_failed) : null;
5037
+ const hintRows = this.stmt("hint-rows", SQL_HINT_ROWS).all(origin, flow, definitionKey).map(
5038
+ (row) => row
5039
+ );
5040
+ const hints = [];
5041
+ const seenSteps = /* @__PURE__ */ new Set();
5042
+ for (const row of hintRows) {
5043
+ const stepId = String(row.step_id);
5044
+ if (seenSteps.has(stepId)) continue;
5045
+ seenSteps.add(stepId);
5046
+ const verifiedAt = Number(row.ended_at);
5047
+ if (verifiedAt < now - BRIEF_RECENCY_MS) continue;
5048
+ if (maxFailed !== null && verifiedAt <= maxFailed) continue;
5049
+ hints.push({ stepId, candidate: Number(row.candidate), verifiedAt });
5050
+ }
5051
+ hints.sort((a, b) => a.stepId < b.stepId ? -1 : a.stepId > b.stepId ? 1 : 0);
5052
+ return { origin, flow, hints };
5053
+ } catch {
5054
+ return { origin, flow, hints: [] };
5055
+ }
5056
+ }
5057
+ close() {
5058
+ if (this.closed) return;
5059
+ this.closed = true;
5060
+ this.statements.clear();
5061
+ try {
5062
+ this.db.close();
5063
+ } catch {
5064
+ }
5065
+ }
5066
+ };
5067
+ function errorMessage(err) {
5068
+ return err instanceof Error ? err.message : String(err);
5069
+ }
5070
+ function sanitizeError(scope, err) {
5071
+ const raw = err === void 0 ? "" : errorMessage(err);
5072
+ const reason = raw.split("\n")[0].trim();
5073
+ return new Error(`site-memory: ${scope}${reason ? `: ${reason}` : ""}`);
5074
+ }
5075
+ function readVersion(db) {
5076
+ const row = db.prepare("PRAGMA user_version").get();
5077
+ return row ? Number(row.user_version) : 0;
5078
+ }
5079
+ function hasRunsTable(db) {
5080
+ return db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'runs'").get() != null;
5081
+ }
5082
+ function initSchema(db) {
5083
+ db.exec(SCHEMA_SQL);
5084
+ db.exec(`PRAGMA user_version = ${SCHEMA_VERSION};`);
5085
+ }
5086
+ function createEmptyVolatileStore(DatabaseSyncCtor) {
5087
+ const db = new DatabaseSyncCtor(":memory:");
5088
+ initSchema(db);
5089
+ return new SqliteSiteMemoryStore(db, true);
5090
+ }
5091
+ function openWritableStore(dbPath) {
5092
+ const DatabaseSyncCtor = loadDatabaseSync();
5093
+ const resolved = resolve7(dbPath);
5094
+ try {
5095
+ mkdirSync6(dirname4(resolved), { recursive: true });
5096
+ } catch (err) {
5097
+ throw sanitizeError(`cannot create directory for site-memory database at ${resolved}`, err);
5098
+ }
5099
+ let db;
5100
+ try {
5101
+ db = new DatabaseSyncCtor(resolved);
5102
+ } catch (err) {
5103
+ throw sanitizeError(`cannot open site-memory database at ${resolved}`, err);
5104
+ }
5105
+ try {
5106
+ db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS};`);
5107
+ db.exec("PRAGMA journal_mode = WAL;");
5108
+ db.exec("PRAGMA synchronous = NORMAL;");
5109
+ db.exec("PRAGMA foreign_keys = ON;");
5110
+ const version2 = readVersion(db);
5111
+ if (version2 === SCHEMA_VERSION) {
5112
+ return new SqliteSiteMemoryStore(db, false);
5113
+ }
5114
+ if (version2 === 0 && !hasRunsTable(db)) {
5115
+ initSchema(db);
5116
+ return new SqliteSiteMemoryStore(db, false);
5117
+ }
5118
+ if (version2 === 0) {
5119
+ throw new Error(`database at ${resolved} has tables but no schema version; refusing to touch it`);
5120
+ }
5121
+ throw new Error(`schema version ${version2} at ${resolved} is not supported (expected ${SCHEMA_VERSION})`);
5122
+ } catch (err) {
5123
+ try {
5124
+ db.close();
5125
+ } catch {
5126
+ }
5127
+ throw sanitizeError("cannot open writable site-memory database", err);
5128
+ }
5129
+ }
5130
+ function openReadonlyStore(dbPath) {
5131
+ const DatabaseSyncCtor = loadDatabaseSync();
5132
+ if (!existsSync10(dbPath)) {
5133
+ return createEmptyVolatileStore(DatabaseSyncCtor);
5134
+ }
5135
+ let db;
5136
+ try {
5137
+ db = new DatabaseSyncCtor(dbPath, { readOnly: true });
5138
+ db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS};`);
5139
+ const version2 = readVersion(db);
5140
+ if (version2 !== SCHEMA_VERSION) {
5141
+ throw new Error(`schema version ${version2} is not supported (expected ${SCHEMA_VERSION})`);
5142
+ }
5143
+ return new SqliteSiteMemoryStore(db, true);
5144
+ } catch (err) {
5145
+ if (db) {
5146
+ try {
5147
+ db.close();
5148
+ } catch {
5149
+ }
5150
+ }
5151
+ throw sanitizeError(`cannot open readonly site-memory database at ${dbPath}`, err);
5152
+ }
5153
+ }
5154
+ function defaultSiteMemoryPath() {
5155
+ return join7(homedir3(), ".xbrowser", "site-memory", "site-memory.sqlite");
5156
+ }
5157
+ function openSiteMemoryStore(dbPath, opts) {
5158
+ return opts?.readonly === true ? openReadonlyStore(dbPath) : openWritableStore(dbPath);
5159
+ }
5160
+
5161
+ // src/site-memory/view.ts
5162
+ var MAX_SITES = 200;
5163
+ var MAX_FLOWS_PER_SITE = 50;
5164
+ var MAX_RUNS_PER_FLOW = 25;
5165
+ var MAX_STATS_STEPS = 200;
5166
+ var MAX_RUN_DETAILS = 400;
5167
+ var MAX_ERROR_CODES_PER_STEP = 6;
5168
+ var MAX_ATTEMPTS_PER_RUN_LOG = 30;
5169
+ function escapeHtml(value) {
5170
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
5171
+ }
5172
+ function esc(value) {
5173
+ return escapeHtml(String(value));
5174
+ }
5175
+ function fmtTime(ms) {
5176
+ return Number.isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : "\u2014";
5177
+ }
5178
+ function fmtDuration(ms) {
5179
+ if (!Number.isFinite(ms) || ms < 0) return "\u2014";
5180
+ if (ms < 1e3) return `${Math.round(ms)}ms`;
5181
+ return `${(ms / 1e3).toFixed(1)}s`;
5182
+ }
5183
+ function fmtRate(numerator, denominator) {
5184
+ if (!Number.isFinite(numerator) || !Number.isFinite(denominator) || denominator <= 0) return "\u2014";
5185
+ return `${(numerator / denominator * 100).toFixed(1)}%`;
5186
+ }
5187
+ function plural(n, word) {
5188
+ return `${n} ${word}${n === 1 ? "" : "s"}`;
5189
+ }
5190
+ function groupFlows(sites) {
5191
+ const bySite = /* @__PURE__ */ new Map();
5192
+ for (const s of sites) {
5193
+ const list = bySite.get(s.origin) ?? [];
5194
+ list.push({
5195
+ origin: s.origin,
5196
+ flow: s.flow,
5197
+ runs: s.runs,
5198
+ passed: s.passed,
5199
+ lastRunAt: s.lastRunAt
5200
+ });
5201
+ bySite.set(s.origin, list);
5202
+ }
5203
+ return bySite;
5204
+ }
5205
+ function renderStatsTable(steps) {
5206
+ const bounded = steps.slice(0, MAX_STATS_STEPS);
5207
+ const truncated = steps.length > bounded.length;
5208
+ const rows = bounded.map((s) => {
5209
+ const errors = Object.entries(s.errors ?? {}).sort((a, b) => (b[1] ?? 0) - (a[1] ?? 0) || a[0].localeCompare(b[0])).slice(0, MAX_ERROR_CODES_PER_STEP).map(([code, n]) => `${esc(code)} \xD7${n}`).join(", ");
5210
+ return [
5211
+ ` <tr>`,
5212
+ ` <td class="step-id">${esc(s.stepId)}</td>`,
5213
+ ` <td>${esc(s.operation)}</td>`,
5214
+ ` <td class="num">${s.executions}</td>`,
5215
+ ` <td class="num">${s.attempts}</td>`,
5216
+ ` <td class="num">${s.failedAttempts}</td>`,
5217
+ ` <td class="num">${fmtRate(s.passedExecutions, s.executions)}</td>`,
5218
+ ` <td class="errors">${errors || "\u2014"}</td>`,
5219
+ ` </tr>`
5220
+ ].join("\n");
5221
+ }).join("\n");
5222
+ const note = truncated ? `
5223
+ <p class="note">Showing ${bounded.length} of ${steps.length} steps (bound).</p>` : "";
5224
+ return [
5225
+ ` <table class="stats">`,
5226
+ ` <thead>`,
5227
+ ` <tr><th>step</th><th>operation</th><th>executions</th><th>attempts</th><th>failed attempts</th><th>pass rate</th><th>top errors</th></tr>`,
5228
+ ` </thead>`,
5229
+ ` <tbody>`,
5230
+ rows,
5231
+ ` </tbody>`,
5232
+ ` </table>${note}`
5233
+ ].join("\n");
5234
+ }
5235
+ var EMPTY_RUN_DETAIL = { steps: null, attempts: null, failed: null, log: null, logCapped: false };
5236
+ function lookupRunDetail(store, runId, budget) {
5237
+ if (budget.left <= 0) return EMPTY_RUN_DETAIL;
5238
+ budget.left -= 1;
5239
+ const run = store.getRun(runId);
5240
+ if (!run) return EMPTY_RUN_DETAIL;
5241
+ const logCapped = run.attempts.length > MAX_ATTEMPTS_PER_RUN_LOG;
5242
+ return {
5243
+ steps: new Set(run.attempts.map((a) => a.stepId)).size,
5244
+ attempts: run.attempts.length,
5245
+ failed: run.attempts.filter((a) => a.outcome === "failed").length,
5246
+ log: logCapped ? run.attempts.slice(0, MAX_ATTEMPTS_PER_RUN_LOG) : run.attempts,
5247
+ logCapped
5248
+ };
5249
+ }
5250
+ function renderAttemptRow(a) {
5251
+ const errorText = a.errorCode ? ` \xB7 ${esc(a.errorCode)}` : "";
5252
+ const sourceText = a.source === "memory" ? "memory hit" : "definition";
5253
+ return [
5254
+ ` <li class="attempt ${esc(a.outcome)}">`,
5255
+ ` <span class="attempt-step">${esc(a.stepId)}</span>`,
5256
+ ` <span class="attempt-no">#${a.attempt}</span>`,
5257
+ ` <span class="attempt-op">${esc(a.operation)}</span>`,
5258
+ ` <span class="attempt-outcome">${esc(a.outcome)}${errorText}</span>`,
5259
+ ` <span class="attempt-source">${sourceText}</span>`,
5260
+ ` </li>`
5261
+ ].join("\n");
5262
+ }
5263
+ function renderAttemptLog(detail) {
5264
+ if (detail.log === null || detail.attempts === null) return "";
5265
+ const capNote = detail.logCapped ? `
5266
+ <p class="note">Showing first ${detail.log.length} of ${detail.attempts} attempts (bound).</p>` : "";
5267
+ return [
5268
+ ` <details class="run-attempts">`,
5269
+ ` <summary>attempts (${detail.attempts})</summary>`,
5270
+ ` <ul class="attempts">`,
5271
+ ...detail.log.map(renderAttemptRow),
5272
+ ` </ul>${capNote}`,
5273
+ ` </details>`
5274
+ ].join("\n");
5275
+ }
5276
+ function renderTimeline(runs, details) {
5277
+ const items = runs.map((r) => {
5278
+ const detail = details.get(r.runId) ?? EMPTY_RUN_DETAIL;
5279
+ const stepsText = detail.steps === null ? "n/a" : plural(detail.steps, "step");
5280
+ const attemptsText = detail.attempts === null ? "n/a" : plural(detail.attempts, "attempt");
5281
+ const failedText = detail.failed !== null && detail.failed > 0 ? ` <span class="run-failed">${detail.failed} failed</span>` : "";
5282
+ const verifiedText = r.verified ? '<span class="run-verified">verified</span>' : '<span class="run-unverified">unverified</span>';
5283
+ return [
5284
+ ` <li class="run ${r.outcome}">`,
5285
+ ` <div class="run-line">`,
5286
+ ` <span class="run-id">${esc(r.runId)}</span>`,
5287
+ ` <span class="run-when">${fmtTime(r.startedAt)} \u2192 ${fmtTime(r.endedAt)}</span>`,
5288
+ ` <span class="run-duration">${fmtDuration(r.endedAt - r.startedAt)}</span>`,
5289
+ ` <span class="run-steps">${stepsText}</span>`,
5290
+ ` <span class="run-attempts">${attemptsText}</span>${failedText}`,
5291
+ ` ${verifiedText}`,
5292
+ ` </div>`,
5293
+ renderAttemptLog(detail),
5294
+ ` </li>`
5295
+ ].join("\n");
5296
+ }).join("\n");
5297
+ return [` <ol class="timeline">`, items, ` </ol>`].join("\n");
5298
+ }
5299
+ function renderFlow(store, group, budget) {
5300
+ const runs = [...store.listRuns(group.origin, group.flow, MAX_RUNS_PER_FLOW)].sort(
5301
+ (a, b) => b.startedAt - a.startedAt || a.runId.localeCompare(b.runId)
5302
+ );
5303
+ const steps = [...store.getStats(group.origin, group.flow)].sort((a, b) => b.executions - a.executions || a.stepId.localeCompare(b.stepId));
5304
+ const details = /* @__PURE__ */ new Map();
5305
+ for (const r of runs) details.set(r.runId, lookupRunDetail(store, r.runId, budget));
5306
+ const runsNote = group.runs > runs.length ? `
5307
+ <p class="note">Showing latest ${runs.length} of ${group.runs} runs (bound).</p>` : "";
5308
+ return [
5309
+ ` <section class="flow">`,
5310
+ ` <h3>${esc(group.flow)}</h3>`,
5311
+ ` <p class="flow-meta">runs ${group.runs} \xB7 passed ${group.passed} \xB7 pass rate ${fmtRate(group.passed, group.runs)} \xB7 last run ${fmtTime(group.lastRunAt)}</p>`,
5312
+ ` <h4>Step stats</h4>`,
5313
+ steps.length > 0 ? renderStatsTable(steps) : ` <p class="note">No step stats recorded.</p>`,
5314
+ ` <h4>Recent runs</h4>${runsNote}`,
5315
+ runs.length > 0 ? renderTimeline(runs, details) : ` <p class="note">No runs recorded.</p>`,
5316
+ ` </section>`
5317
+ ].join("\n");
5318
+ }
5319
+ function renderSite(store, origin, flows, budget) {
5320
+ const ordered = [...flows].sort((a, b) => b.lastRunAt - a.lastRunAt || a.flow.localeCompare(b.flow));
5321
+ const bounded = ordered.slice(0, MAX_FLOWS_PER_SITE);
5322
+ const note = ordered.length > bounded.length ? `
5323
+ <p class="note">Showing ${bounded.length} of ${ordered.length} flows for this site (bound).</p>` : "";
5324
+ const body = bounded.map((f) => renderFlow(store, f, budget)).join("\n");
5325
+ return [`<section class="site">`, ` <h2>${esc(origin)}</h2>${note}`, body, `</section>`].join("\n");
5326
+ }
5327
+ var CSS = `:root{color-scheme:light dark}
5328
+ *{box-sizing:border-box}
5329
+ body{margin:0 auto;max-width:960px;padding:1.5rem 1rem 3rem;font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
5330
+ header h1{font-size:1.4rem;margin:0 0 .25rem}
5331
+ .meta,.note,.flow-meta{color:color-mix(in srgb,currentColor 62%,transparent);font-size:.85rem}
5332
+ .meta{margin:0 0 1.5rem}
5333
+ .site{margin:0 0 2.5rem;padding-top:.5rem;border-top:1px solid color-mix(in srgb,currentColor 18%,transparent)}
5334
+ .site h2{font-size:1.1rem;margin:.75rem 0 .25rem;word-break:break-all}
5335
+ .flow{margin:1rem 0 1.75rem;padding:.75rem 1rem;border:1px solid color-mix(in srgb,currentColor 15%,transparent);border-radius:8px}
5336
+ .flow h3{font-size:1rem;margin:0 0 .25rem;word-break:break-all}
5337
+ .flow h4{font-size:.85rem;margin:1rem 0 .4rem;text-transform:uppercase;letter-spacing:.04em}
5338
+ table.stats{border-collapse:collapse;width:100%;font-size:.85rem}
5339
+ table.stats th,table.stats td{text-align:left;padding:.3rem .5rem;border-bottom:1px solid color-mix(in srgb,currentColor 12%,transparent)}
5340
+ table.stats td.num,table.stats th:nth-child(n+3){text-align:right;font-variant-numeric:tabular-nums}
5341
+ table.stats td.step-id,table.stats td.errors{word-break:break-all}
5342
+ ol.timeline{list-style:none;margin:0;padding:0}
5343
+ ol.timeline li{padding:.3rem 0;border-bottom:1px dashed color-mix(in srgb,currentColor 12%,transparent)}
5344
+ .run-line{display:flex;flex-wrap:wrap;gap:.35rem .9rem;align-items:baseline}
5345
+ details.run-attempts{margin:.2rem 0 .1rem;font-size:.8rem}
5346
+ details.run-attempts summary{cursor:pointer;user-select:none;color:color-mix(in srgb,currentColor 55%,transparent)}
5347
+ ul.attempts{list-style:none;margin:.25rem 0 0;padding:0}
5348
+ ul.attempts li{display:flex;flex-wrap:wrap;gap:.15rem .7rem;padding:.15rem 0;border-bottom:1px dotted color-mix(in srgb,currentColor 10%,transparent)}
5349
+ .attempt-step,.attempt-no{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;word-break:break-all}
5350
+ li.attempt.failed .attempt-outcome{color:#c0392b}
5351
+ .attempt-source{color:color-mix(in srgb,currentColor 55%,transparent)}
5352
+ li.run.failed .run-id{color:#c0392b}
5353
+ li.run.passed .run-id{color:#1e7e34}
5354
+ .run-id{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;word-break:break-all}
5355
+ .run-failed{color:#c0392b}
5356
+ .run-unverified{color:#b58900}
5357
+ .run-verified{color:#1e7e34}
5358
+ .meta,.note,.flow-meta,.run-when,.run-duration{font-family:inherit}
5359
+ .empty{padding:2rem 0;text-align:center;color:color-mix(in srgb,currentColor 55%,transparent)}
5360
+ footer{margin-top:3rem;font-size:.75rem;color:color-mix(in srgb,currentColor 50%,transparent)}`;
5361
+ function renderSiteMemoryDashboard(store) {
5362
+ const allSites = [...store.listSites()];
5363
+ const totals = allSites.reduce(
5364
+ (acc, s) => {
5365
+ acc.runs += s.runs;
5366
+ acc.passed += s.passed;
5367
+ acc.flows += 1;
5368
+ return acc;
5369
+ },
5370
+ { runs: 0, passed: 0, flows: 0 }
5371
+ );
5372
+ const bySite = groupFlows(allSites);
5373
+ const siteEntries = [...bySite.entries()].map(([origin, flows]) => ({
5374
+ origin,
5375
+ flows,
5376
+ lastRunAt: flows.reduce((m, f) => Math.max(m, f.lastRunAt), 0)
5377
+ })).sort((a, b) => b.lastRunAt - a.lastRunAt || a.origin.localeCompare(b.origin));
5378
+ const boundedSites = siteEntries.slice(0, MAX_SITES);
5379
+ const sitesTruncated = siteEntries.length > boundedSites.length;
5380
+ const budget = { left: MAX_RUN_DETAILS };
5381
+ const body = boundedSites.length === 0 ? ` <p class="empty">No site-memory data recorded yet.</p>` : boundedSites.map((s) => renderSite(store, s.origin, s.flows, budget)).join("\n");
5382
+ const sitesNote = sitesTruncated ? `
5383
+ <p class="note">Showing ${boundedSites.length} of ${siteEntries.length} sites (bound).</p>` : "";
5384
+ const generatedAt = (/* @__PURE__ */ new Date()).toISOString();
5385
+ return `<!doctype html>
5386
+ <html lang="en">
5387
+ <head>
5388
+ <meta charset="utf-8">
5389
+ <meta name="viewport" content="width=device-width, initial-scale=1">
5390
+ <title>xbrowser \xB7 site-memory dashboard</title>
5391
+ <style>${CSS}</style>
5392
+ </head>
5393
+ <body>
5394
+ <header>
5395
+ <h1>Site Memory Dashboard</h1>
5396
+ <p class="meta">${boundedSites.length} sites \xB7 ${totals.flows} flows \xB7 ${totals.runs} runs \xB7 pass rate ${fmtRate(totals.passed, totals.runs)} \xB7 generated ${generatedAt}</p>
5397
+ </header>
5398
+ <main>
5399
+ ${body}${sitesNote}
5400
+ </main>
5401
+ <footer>Static snapshot \xB7 self-contained (no external assets, no scripts, no telemetry) \xB7 rendered by xbrowser site-memory</footer>
5402
+ </body>
5403
+ </html>`;
5404
+ }
5405
+
5406
+ // src/site-memory/mcp.ts
5407
+ var MAX_STRING_LEN = 512;
5408
+ var DEFAULT_RUNS_LIMIT = 50;
5409
+ var MAX_RUNS_LIMIT = 200;
5410
+ var MAX_SITE_SUMMARIES = 1e3;
5411
+ var MAX_ATTEMPTS = 1e3;
5412
+ var MAX_STATS_STEPS2 = 500;
5413
+ var SUPPORTED_PROTOCOL_VERSIONS = /* @__PURE__ */ new Set(["2024-11-05", "2025-03-26", "2025-06-18"]);
5414
+ var DEFAULT_PROTOCOL_VERSION = "2025-06-18";
5415
+ var DASHBOARD_URI = "xbrowser-site-memory://dashboard";
5416
+ function readOnlyAnnotations(title) {
5417
+ return { title, readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
5418
+ }
5419
+ var RUN_SUMMARY_ITEM_SCHEMA = {
5420
+ type: "object",
5421
+ properties: {
5422
+ runId: { type: "string" },
5423
+ origin: { type: "string" },
5424
+ flow: { type: "string" },
5425
+ definitionKey: { type: "string" },
5426
+ startedAt: { type: "number" },
5427
+ endedAt: { type: "number" },
5428
+ outcome: { type: "string", enum: ["passed", "failed"] },
5429
+ verified: { type: "boolean" }
5430
+ },
5431
+ required: ["runId", "origin", "flow", "definitionKey", "startedAt", "endedAt", "outcome", "verified"]
5432
+ };
5433
+ var STEP_STATS_ITEM_SCHEMA = {
5434
+ type: "object",
5435
+ properties: {
5436
+ stepId: { type: "string" },
5437
+ operation: { type: "string", enum: ["goto", "click", "expect-text"] },
5438
+ executions: { type: "number" },
5439
+ attempts: { type: "number" },
5440
+ failedAttempts: { type: "number" },
5441
+ passedExecutions: { type: "number" },
5442
+ errors: { type: "object", additionalProperties: { type: "number" } }
5443
+ },
5444
+ required: ["stepId", "operation", "executions", "attempts", "failedAttempts", "passedExecutions", "errors"]
5445
+ };
5446
+ var TOOLS = [
5447
+ {
5448
+ name: "site_memory_sites",
5449
+ description: "List recorded site summaries (origin + flow granularity, cross-host) with run counts, passed counts and last-run timestamps. Read-only query over the site-memory store.",
5450
+ annotations: readOnlyAnnotations("Site memory: sites"),
5451
+ inputSchema: { type: "object", properties: {} },
5452
+ outputSchema: {
5453
+ type: "object",
5454
+ properties: {
5455
+ sites: {
5456
+ type: "array",
5457
+ items: {
5458
+ type: "object",
5459
+ properties: {
5460
+ origin: { type: "string" },
5461
+ flow: { type: "string" },
5462
+ runs: { type: "number" },
5463
+ passed: { type: "number" },
5464
+ lastRunAt: { type: "number" }
5465
+ },
5466
+ required: ["origin", "flow", "runs", "passed", "lastRunAt"]
5467
+ }
5468
+ },
5469
+ truncated: { type: "boolean" }
5470
+ },
5471
+ required: ["sites"]
5472
+ }
5473
+ },
5474
+ {
5475
+ name: "site_memory_runs",
5476
+ description: `List run summaries for one origin, optionally filtered to a flow, newest first. Read-only. limit: integer 1..${MAX_RUNS_LIMIT} (default ${DEFAULT_RUNS_LIMIT}, clamped to max).`,
5477
+ annotations: readOnlyAnnotations("Site memory: runs"),
5478
+ inputSchema: {
5479
+ type: "object",
5480
+ properties: {
5481
+ origin: { type: "string", description: "Site origin, e.g. https://example.com" },
5482
+ flow: { type: "string", description: "Optional flow name filter" },
5483
+ limit: { type: "number", description: `Max runs to return (1..${MAX_RUNS_LIMIT}, default ${DEFAULT_RUNS_LIMIT})` }
5484
+ },
5485
+ required: ["origin"]
5486
+ },
5487
+ outputSchema: {
5488
+ type: "object",
5489
+ properties: {
5490
+ origin: { type: "string" },
5491
+ flow: { type: ["string", "null"] },
5492
+ limit: { type: "number" },
5493
+ count: { type: "number" },
5494
+ runs: { type: "array", items: RUN_SUMMARY_ITEM_SCHEMA }
5495
+ },
5496
+ required: ["origin", "flow", "limit", "count", "runs"]
5497
+ }
5498
+ },
5499
+ {
5500
+ name: "site_memory_run",
5501
+ description: `Get a single run (summary + step attempts) by runId. Read-only. Attempts payload bounded to ${MAX_ATTEMPTS}.`,
5502
+ annotations: readOnlyAnnotations("Site memory: run detail"),
5503
+ inputSchema: {
5504
+ type: "object",
5505
+ properties: {
5506
+ runId: { type: "string", description: "Run identifier" }
5507
+ },
5508
+ required: ["runId"]
5509
+ },
5510
+ outputSchema: {
5511
+ type: "object",
5512
+ properties: {
5513
+ run: {
5514
+ type: "object",
5515
+ properties: {
5516
+ runId: { type: "string" },
5517
+ origin: { type: "string" },
5518
+ flow: { type: "string" },
5519
+ definitionKey: { type: "string" },
5520
+ startedAt: { type: "number" },
5521
+ endedAt: { type: "number" },
5522
+ outcome: { type: "string", enum: ["passed", "failed"] },
5523
+ verified: { type: "boolean" },
5524
+ attempts: { type: "array" },
5525
+ attemptsTruncated: { type: "boolean" },
5526
+ totalAttempts: { type: "number" }
5527
+ },
5528
+ required: ["runId", "origin", "flow", "definitionKey", "startedAt", "endedAt", "outcome", "verified", "attempts"]
5529
+ }
5530
+ },
5531
+ required: ["run"]
5532
+ }
5533
+ },
5534
+ {
5535
+ name: "site_memory_stats",
5536
+ description: `Per-step stats (executions / attempts / failed attempts / error-code counts) for one origin + flow. Read-only. Step payload bounded to ${MAX_STATS_STEPS2}. Unknown origin/flow yields empty steps.`,
5537
+ annotations: readOnlyAnnotations("Site memory: step stats"),
5538
+ inputSchema: {
5539
+ type: "object",
5540
+ properties: {
5541
+ origin: { type: "string", description: "Site origin, e.g. https://example.com" },
5542
+ flow: { type: "string", description: "Flow name" }
5543
+ },
5544
+ required: ["origin", "flow"]
5545
+ },
5546
+ outputSchema: {
5547
+ type: "object",
5548
+ properties: {
5549
+ steps: { type: "array", items: STEP_STATS_ITEM_SCHEMA },
5550
+ truncated: { type: "boolean" }
5551
+ },
5552
+ required: ["steps"]
5553
+ }
5554
+ }
5555
+ ];
5556
+ function requireString(args, key) {
5557
+ const raw = args[key];
5558
+ if (typeof raw !== "string") throw new Error(`parameter "${key}" must be a string`);
5559
+ const value = raw.trim();
5560
+ if (value.length === 0) throw new Error(`parameter "${key}" must not be empty`);
5561
+ if (value.length > MAX_STRING_LEN) throw new Error(`parameter "${key}" exceeds ${MAX_STRING_LEN} characters`);
5562
+ return value;
5563
+ }
5564
+ function optionalString(args, key) {
5565
+ if (args[key] === void 0) return void 0;
5566
+ return requireString(args, key);
5567
+ }
5568
+ function resolveLimit(raw) {
5569
+ if (raw === void 0) return DEFAULT_RUNS_LIMIT;
5570
+ if (typeof raw !== "number" || !Number.isInteger(raw)) throw new Error('parameter "limit" must be an integer');
5571
+ if (raw < 1) throw new Error('parameter "limit" must be >= 1');
5572
+ return Math.min(raw, MAX_RUNS_LIMIT);
5573
+ }
5574
+ function structured(payload) {
5575
+ return {
5576
+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
5577
+ structuredContent: payload
5578
+ };
5579
+ }
5580
+ async function runSiteMemoryTool(store, name, args) {
5581
+ switch (name) {
5582
+ case "site_memory_sites": {
5583
+ const all = [...store.listSites()].sort(
5584
+ (a, b) => a.origin.localeCompare(b.origin) || a.flow.localeCompare(b.flow)
5585
+ );
5586
+ const truncated = all.length > MAX_SITE_SUMMARIES;
5587
+ const sites = truncated ? all.slice(0, MAX_SITE_SUMMARIES) : all;
5588
+ return structured({ sites, truncated });
5589
+ }
5590
+ case "site_memory_runs": {
5591
+ const origin = requireString(args, "origin");
5592
+ const flow = optionalString(args, "flow");
5593
+ const limit = resolveLimit(args.limit);
5594
+ const runs = store.listRuns(origin, flow, limit);
5595
+ return structured({ origin, flow: flow ?? null, limit, count: runs.length, runs });
5596
+ }
5597
+ case "site_memory_run": {
5598
+ const runId = requireString(args, "runId");
5599
+ const run = store.getRun(runId);
5600
+ if (!run) throw new Error(`run not found: ${runId}`);
5601
+ const { attempts, ...summary } = run;
5602
+ const truncated = attempts.length > MAX_ATTEMPTS;
5603
+ return structured({
5604
+ run: {
5605
+ ...summary,
5606
+ attempts: truncated ? attempts.slice(0, MAX_ATTEMPTS) : attempts,
5607
+ ...truncated ? { attemptsTruncated: true, totalAttempts: attempts.length } : {}
5608
+ }
5609
+ });
5610
+ }
5611
+ case "site_memory_stats": {
5612
+ const origin = requireString(args, "origin");
5613
+ const flow = requireString(args, "flow");
5614
+ const steps = store.getStats(origin, flow);
5615
+ const truncated = steps.length > MAX_STATS_STEPS2;
5616
+ return structured({
5617
+ steps: truncated ? steps.slice(0, MAX_STATS_STEPS2) : steps,
5618
+ truncated
5619
+ });
5620
+ }
5621
+ default:
5622
+ throw new Error(`unknown tool: ${name}`);
5623
+ }
5624
+ }
5625
+ function ok(id, result) {
5626
+ return { jsonrpc: "2.0", id, result };
5627
+ }
5628
+ function fail(id, code, message) {
5629
+ return { jsonrpc: "2.0", id, error: { code, message } };
5630
+ }
5631
+ async function dispatchSiteMemoryRpc(store, raw) {
5632
+ if (typeof raw !== "object" || raw === null) return null;
5633
+ const req = raw;
5634
+ if (typeof req.method !== "string" || req.method.length === 0) return null;
5635
+ if (req.id === void 0) return null;
5636
+ const id = typeof req.id === "number" || typeof req.id === "string" ? req.id : null;
5637
+ const params = typeof req.params === "object" && req.params !== null ? req.params : {};
5638
+ switch (req.method) {
5639
+ case "initialize": {
5640
+ const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : "";
5641
+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.has(requested) ? requested : DEFAULT_PROTOCOL_VERSION;
5642
+ return ok(id, {
5643
+ protocolVersion,
5644
+ capabilities: { tools: {}, resources: {} },
5645
+ serverInfo: { name: "xbrowser-site-memory", version: process.env.npm_package_version || "1.34.0" }
5646
+ });
5647
+ }
5648
+ case "notifications/initialized":
5649
+ return null;
5650
+ case "ping":
5651
+ return ok(id, {});
5652
+ case "tools/list":
5653
+ return ok(id, { tools: TOOLS });
5654
+ case "tools/call": {
5655
+ const name = typeof params.name === "string" ? params.name : "";
5656
+ const args = typeof params.arguments === "object" && params.arguments !== null ? params.arguments : {};
5657
+ try {
5658
+ const result = await runSiteMemoryTool(store, name, args);
5659
+ return ok(id, result);
5660
+ } catch (err) {
5661
+ return ok(id, {
5662
+ content: [{ type: "text", text: `Error: ${err.message}` }],
5663
+ isError: true
5664
+ });
5665
+ }
5666
+ }
5667
+ case "resources/list":
5668
+ return ok(id, {
5669
+ resources: [
5670
+ {
5671
+ uri: DASHBOARD_URI,
5672
+ name: "site-memory-dashboard",
5673
+ description: "Static self-contained HTML dashboard of recorded flows, runs, step stats and errors.",
5674
+ mimeType: "text/html"
5675
+ }
5676
+ ]
5677
+ });
5678
+ case "resources/read": {
5679
+ const uri = typeof params.uri === "string" && params.uri.length > 0 ? params.uri : DASHBOARD_URI;
5680
+ if (uri !== DASHBOARD_URI) return fail(id, -32002, `unknown resource: ${uri}`);
5681
+ return ok(id, {
5682
+ contents: [{ uri: DASHBOARD_URI, mimeType: "text/html", text: renderSiteMemoryDashboard(store) }]
5683
+ });
5684
+ }
5685
+ default:
5686
+ return fail(id, -32601, `method not found: ${req.method}`);
5687
+ }
5688
+ }
5689
+ function runSiteMemoryStdioLoop(store, input, output, onFinished) {
5690
+ let buffer = "";
5691
+ let inflight = 0;
5692
+ let inputEnded = false;
5693
+ let finished = false;
5694
+ const finish = () => {
5695
+ if (finished) return;
5696
+ finished = true;
5697
+ try {
5698
+ store.close();
5699
+ } catch {
5700
+ }
5701
+ if (onFinished) onFinished();
5702
+ else process.exit(0);
5703
+ };
5704
+ input.setEncoding("utf8");
5705
+ input.on("data", (chunk) => {
5706
+ buffer += chunk;
5707
+ let idx;
5708
+ while ((idx = buffer.indexOf("\n")) >= 0) {
5709
+ const line = buffer.slice(0, idx).trim();
5710
+ buffer = buffer.slice(idx + 1);
5711
+ if (!line) continue;
5712
+ let req;
5713
+ try {
5714
+ req = JSON.parse(line);
5715
+ } catch {
5716
+ continue;
5717
+ }
5718
+ inflight += 1;
5719
+ dispatchSiteMemoryRpc(store, req).then((res) => {
5720
+ if (res !== null) output.write(JSON.stringify(res) + "\n");
5721
+ }).catch(() => {
5722
+ }).finally(() => {
5723
+ inflight -= 1;
5724
+ if (inputEnded && inflight === 0) finish();
5725
+ });
5726
+ }
5727
+ });
5728
+ input.on("end", () => {
5729
+ inputEnded = true;
5730
+ if (inflight === 0) finish();
5731
+ });
5732
+ }
5733
+ function startSiteMemoryMcp(store) {
5734
+ runSiteMemoryStdioLoop(store, process.stdin, process.stdout);
5735
+ }
5736
+
5737
+ // src/site-memory/cli.ts
5738
+ var MAX_WORKFLOW_BYTES = 256 * 1024;
5739
+ var USAGE = `Usage: xbrowser site-memory <subcommand>
5740
+
5741
+ Subcommands:
5742
+ run <workflow.json> [--cold] Run a declared workflow in a fresh headless browser
5743
+ and record the sanitized run in the local store
5744
+ report --output <path> Write a self-contained HTML dashboard
5745
+ (exclusive create: fails if the path already exists)
5746
+ mcp Start the read-only stdio MCP server over the store
5747
+
5748
+ Environment:
5749
+ XBROWSER_SITE_MEMORY_DB=/abs/path Override the store location (must be absolute;
5750
+ shared by every host that launches the MCP)
5751
+
5752
+ Notes:
5753
+ - Only workflows explicitly declared in the JSON file are executed.
5754
+ - No daemon, session routing, or user-browser involvement; each run launches
5755
+ its own throwaway headless profile.
5756
+ - Reports are local files and are never launched or opened automatically.`;
5757
+ function fail2(message, command, mode) {
5758
+ outputEnvelope({ success: false, data: null, message }, { command }, mode);
5759
+ process.exitCode = 1;
5760
+ }
5761
+ function resolveStorePath() {
5762
+ const override = process.env.XBROWSER_SITE_MEMORY_DB;
5763
+ if (override !== void 0 && override !== "") {
5764
+ if (!isAbsolute2(override)) {
5765
+ throw new Error(
5766
+ `XBROWSER_SITE_MEMORY_DB must be an absolute path, got: ${override}`
5767
+ );
5768
+ }
5769
+ return override;
5770
+ }
5771
+ return defaultSiteMemoryPath();
5772
+ }
5773
+ function openReadOnlyStore(storePath) {
5774
+ try {
5775
+ return openSiteMemoryStore(storePath, { readonly: true });
5776
+ } catch (e) {
5777
+ const detail = e instanceof Error ? e.message : String(e);
5778
+ throw new Error(
5779
+ `cannot open read-only site-memory store at ${storePath} (${detail})`
5780
+ );
5781
+ }
5782
+ }
5783
+ function createLazyReadOnlyStore(storePath) {
5784
+ const query = (fn) => {
5785
+ const store = openSiteMemoryStore(storePath, { readonly: true });
5786
+ try {
5787
+ return fn(store);
5788
+ } finally {
5789
+ store.close();
5790
+ }
5791
+ };
5792
+ return {
5793
+ putRun() {
5794
+ throw new Error("site-memory MCP store is read-only");
5795
+ },
5796
+ listSites: () => query((s) => s.listSites()),
5797
+ listRuns: (origin, flow, limit) => query((s) => s.listRuns(origin, flow, limit)),
5798
+ getRun: (runId) => query((s) => s.getRun(runId)),
5799
+ getStats: (origin, flow) => query((s) => s.getStats(origin, flow)),
5800
+ getBrief: (origin, flow, definitionKey) => query((s) => s.getBrief(origin, flow, definitionKey)),
5801
+ close() {
5802
+ }
5803
+ };
5804
+ }
5805
+ var openHeadlessPage = async () => {
5806
+ const { launch } = await import("./cdp-driver-CCG3OJUQ.js");
5807
+ const { browser } = await launch({ headless: true });
5808
+ let context;
5809
+ try {
5810
+ context = await browser.newContext();
5811
+ const page = await context.newPage();
5812
+ const ownedContext = context;
5813
+ return {
5814
+ page,
5815
+ close: async () => {
5816
+ try {
5817
+ await ownedContext.close();
5818
+ } catch {
5819
+ }
5820
+ await browser.close();
5821
+ }
5822
+ };
5823
+ } catch (e) {
5824
+ await browser.close().catch(() => {
5825
+ });
5826
+ throw e;
5827
+ }
5828
+ };
5829
+ function warnIgnoredGlobalFlags(options) {
5830
+ if (options.cdp !== void 0 || options.session !== void 0) {
5831
+ console.error(
5832
+ "[site-memory] --cdp/--session are ignored: site-memory never uses the daemon, sessions, or the user browser."
5833
+ );
5834
+ }
5835
+ }
5836
+ async function handleRun2(rest, options, mode) {
5837
+ const command = "site-memory run";
5838
+ warnIgnoredGlobalFlags(options);
5839
+ const cold = options.cold !== void 0 && options.cold !== false;
5840
+ const fileArg = rest[0] ?? (typeof options.cold === "string" && options.cold !== "" ? options.cold : void 0);
5841
+ if (!fileArg) {
5842
+ fail2(`missing workflow file. Usage: xbrowser site-memory run <workflow.json> [--cold]`, command, mode);
5843
+ return;
5844
+ }
5845
+ const workflowPath = resolve8(fileArg);
5846
+ let size;
5847
+ try {
5848
+ size = (await stat(workflowPath)).size;
5849
+ } catch {
5850
+ fail2(`workflow file not found: ${workflowPath}`, command, mode);
5851
+ return;
5852
+ }
5853
+ if (size > MAX_WORKFLOW_BYTES) {
5854
+ fail2(
5855
+ `workflow file too large: ${workflowPath} (${size} bytes > ${MAX_WORKFLOW_BYTES} limit)`,
5856
+ command,
5857
+ mode
5858
+ );
5859
+ return;
5860
+ }
5861
+ let text;
5862
+ try {
5863
+ text = await readFile(workflowPath, "utf8");
5864
+ } catch (e) {
5865
+ fail2(`cannot read workflow file ${workflowPath}: ${e instanceof Error ? e.message : String(e)}`, command, mode);
5866
+ return;
5867
+ }
5868
+ let raw;
5869
+ try {
5870
+ raw = JSON.parse(text);
5871
+ } catch {
5872
+ fail2(`invalid workflow JSON in ${workflowPath}`, command, mode);
5873
+ return;
5874
+ }
5875
+ let storePath;
5876
+ try {
5877
+ storePath = resolveStorePath();
5878
+ } catch (e) {
5879
+ fail2(e instanceof Error ? e.message : String(e), command, mode);
5880
+ return;
5881
+ }
5882
+ let store;
5883
+ try {
5884
+ store = openSiteMemoryStore(storePath);
5885
+ } catch (e) {
5886
+ fail2(
5887
+ `cannot open site-memory store at ${storePath}: ${e instanceof Error ? e.message : String(e)}`,
5888
+ command,
5889
+ mode
5890
+ );
5891
+ return;
5892
+ }
5893
+ let run;
5894
+ try {
5895
+ run = await runWorkflow(raw, store, openHeadlessPage, { cold });
5896
+ } catch (e) {
5897
+ fail2(
5898
+ `workflow run failed: ${e instanceof Error ? e.message : String(e)}`,
5899
+ command,
5900
+ mode
5901
+ );
5902
+ return;
5903
+ } finally {
5904
+ store.close();
5905
+ }
5906
+ outputEnvelope(
5907
+ {
5908
+ success: true,
5909
+ data: run,
5910
+ duration: run.endedAt - run.startedAt
5911
+ },
5912
+ {
5913
+ command,
5914
+ store: storePath,
5915
+ cold,
5916
+ attempts: run.attempts.length,
5917
+ steps: new Set(run.attempts.map((a) => a.stepId)).size
5918
+ },
5919
+ mode
5920
+ );
5921
+ if (run.outcome !== "passed" || run.verified !== true) {
5922
+ process.exitCode = 1;
5923
+ }
5924
+ }
5925
+ async function handleReport(options, mode) {
5926
+ const command = "site-memory report";
5927
+ const outputArg = options.output;
5928
+ if (outputArg === void 0 || outputArg === "") {
5929
+ fail2(`missing --output <path>. Usage: xbrowser site-memory report --output <path>`, command, mode);
5930
+ return;
5931
+ }
5932
+ const reportPath = resolve8(outputArg);
5933
+ let storePath;
5934
+ try {
5935
+ storePath = resolveStorePath();
5936
+ } catch (e) {
5937
+ fail2(e instanceof Error ? e.message : String(e), command, mode);
5938
+ return;
5939
+ }
5940
+ let html;
5941
+ try {
5942
+ const store = openReadOnlyStore(storePath);
5943
+ try {
5944
+ html = renderSiteMemoryDashboard(store);
5945
+ } finally {
5946
+ store.close();
5947
+ }
5948
+ } catch (e) {
5949
+ fail2(e instanceof Error ? e.message : String(e), command, mode);
5950
+ return;
5951
+ }
5952
+ try {
5953
+ const fh = await openFile(reportPath, "wx", 384);
5954
+ try {
5955
+ await fh.writeFile(html, "utf8");
5956
+ } finally {
5957
+ await fh.close();
5958
+ }
5959
+ } catch (e) {
5960
+ const err = e;
5961
+ if (err.code === "EEXIST") {
5962
+ fail2(`refusing to overwrite existing report: ${reportPath}`, command, mode);
5963
+ } else {
5964
+ fail2(
5965
+ `cannot write report to ${reportPath}: ${err.message ?? String(e)}`,
5966
+ command,
5967
+ mode
5968
+ );
5969
+ }
5970
+ return;
5971
+ }
5972
+ outputEnvelope(
5973
+ {
5974
+ success: true,
5975
+ data: {
5976
+ path: reportPath,
5977
+ bytes: Buffer.byteLength(html, "utf8"),
5978
+ store: storePath
5979
+ }
5980
+ },
5981
+ { command },
5982
+ mode
5983
+ );
5984
+ }
5985
+ async function handleMcp(mode) {
5986
+ const command = "site-memory mcp";
5987
+ let storePath;
5988
+ try {
5989
+ storePath = resolveStorePath();
5990
+ } catch (e) {
5991
+ fail2(e instanceof Error ? e.message : String(e), command, mode);
5992
+ return;
5993
+ }
5994
+ const store = createLazyReadOnlyStore(storePath);
5995
+ try {
5996
+ await startSiteMemoryMcp(store);
5997
+ } catch (e) {
5998
+ store.close();
5999
+ fail2(
6000
+ `site-memory MCP failed to start: ${e instanceof Error ? e.message : String(e)}`,
6001
+ command,
6002
+ mode
6003
+ );
6004
+ }
6005
+ }
6006
+ async function handleSiteMemory(args, options, mode) {
6007
+ const sub = args[0];
6008
+ const rest = args.slice(1);
6009
+ switch (sub) {
6010
+ case "run":
6011
+ await handleRun2(rest, options, mode);
6012
+ return;
6013
+ case "report":
6014
+ await handleReport(options, mode);
6015
+ return;
6016
+ case "mcp":
6017
+ await handleMcp(mode);
6018
+ return;
6019
+ default:
6020
+ process.stdout.write(USAGE + "\n");
6021
+ if (sub !== void 0) process.exitCode = 1;
6022
+ return;
6023
+ }
6024
+ }
6025
+
6026
+ // src/cli/net-routes.ts
6027
+ async function handleNetCommand(args, options, mode, sessionName) {
6028
+ const subCommand = args[0] || "list";
6029
+ const netSession = sessionName;
6030
+ try {
6031
+ switch (subCommand) {
6032
+ case "list": {
6033
+ const filter = options.filter;
6034
+ const method = options.method;
6035
+ const limit = options.limit ? Number(options.limit) : 50;
6036
+ const result = await forwardNetworkList(netSession, { filter, method, limit });
6037
+ if (mode === "json") {
6038
+ outputResult(result, mode);
6039
+ } else {
6040
+ process.stdout.write(`
6041
+ Network captures (session: ${netSession})`);
6042
+ process.stdout.write(` Total: ${result.total}, Showing: ${result.captures.length}
6043
+ `);
6044
+ for (const c of result.captures) {
6045
+ const statusColor = c.status < 300 ? "\x1B[32m" : c.status < 400 ? "\x1B[33m" : "\x1B[31m";
6046
+ const reset = "\x1B[0m";
6047
+ process.stdout.write(` #${c.id} ${c.method.padEnd(6)} ${statusColor}${c.status}${reset} ${c.resourceType.padEnd(10)} ${c.path}
6048
+ `);
6049
+ if (c.size > 0) {
6050
+ const sizeStr = c.size > 1024 ? `${(c.size / 1024).toFixed(1)}KB` : `${c.size}B`;
6051
+ process.stdout.write(` ${c.contentType.split(";")[0]} ${sizeStr}
6052
+ `);
6053
+ }
6054
+ }
6055
+ process.stdout.write("\n");
6056
+ }
6057
+ break;
6058
+ }
6059
+ case "clear": {
6060
+ await forwardNetworkClear(netSession);
6061
+ process.stdout.write(`Network captures cleared for session: ${netSession}
6062
+ `);
6063
+ break;
6064
+ }
6065
+ case "top": {
4150
6066
  const minScore = options["min-score"] ? Number(options["min-score"]) : 0;
4151
6067
  const limit = options.limit ? Number(options.limit) : 20;
4152
6068
  const result = await forwardNetworkTop(netSession, { minScore, limit });
@@ -4442,7 +6358,7 @@ async function handleNetCommand(args, options, mode, sessionName) {
4442
6358
  // src/cli/test-routes.ts
4443
6359
  import { execFile as execFile2 } from "child_process";
4444
6360
  import { readFileSync as readFileSync6 } from "fs";
4445
- import { resolve as resolve7 } from "path";
6361
+ import { resolve as resolve9 } from "path";
4446
6362
  function execCli(args) {
4447
6363
  return new Promise((resolvePromise) => {
4448
6364
  execFile2(
@@ -4461,8 +6377,8 @@ function execCli(args) {
4461
6377
  }
4462
6378
  function findPluginPath(plugin) {
4463
6379
  const candidates = [
4464
- resolve7(process.cwd(), ".xcli/plugins", plugin, "index.ts"),
4465
- resolve7(process.cwd(), "node_modules/@xbrowser/cli/.xcli/plugins", plugin, "index.ts")
6380
+ resolve9(process.cwd(), ".xcli/plugins", plugin, "index.ts"),
6381
+ resolve9(process.cwd(), "node_modules/@xbrowser/cli/.xcli/plugins", plugin, "index.ts")
4466
6382
  ];
4467
6383
  for (const p of candidates) {
4468
6384
  try {
@@ -4471,7 +6387,7 @@ function findPluginPath(plugin) {
4471
6387
  } catch {
4472
6388
  }
4473
6389
  }
4474
- return resolve7(process.cwd(), ".xcli/plugins", plugin, "index.ts");
6390
+ return resolve9(process.cwd(), ".xcli/plugins", plugin, "index.ts");
4475
6391
  }
4476
6392
  function extractSchema(plugin, command) {
4477
6393
  const pluginPath = findPluginPath(plugin);
@@ -4698,12 +6614,12 @@ import { createServer } from "http";
4698
6614
 
4699
6615
  // src/console/facade.ts
4700
6616
  import { readFileSync as readFileSync7 } from "fs";
4701
- import { homedir as homedir3 } from "os";
4702
- import { join as join7 } from "path";
6617
+ import { homedir as homedir4 } from "os";
6618
+ import { join as join8 } from "path";
4703
6619
  var DAEMON_PREVIEW_URL = "http://127.0.0.1:9224";
4704
6620
  var CHROME_BRIDGE_STATUS_URL = "http://127.0.0.1:9347/status";
4705
6621
  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");
6622
+ var CHROME_BRIDGE_META_PATH = join8(homedir4(), ".xbrowser", "chrome-bridge-ext.json");
4707
6623
  async function fetchJson(url, timeoutMs = 1200) {
4708
6624
  try {
4709
6625
  const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
@@ -4840,33 +6756,33 @@ function badge(status) {
4840
6756
  }
4841
6757
  return '<span class="badge bad">unavailable</span>';
4842
6758
  }
4843
- function escapeHtml(value) {
6759
+ function escapeHtml2(value) {
4844
6760
  return String(value ?? "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
4845
6761
  }
4846
6762
  function renderOverviewHtml(overview) {
4847
6763
  const environmentRows = (overview.environments ?? []).map((environment) => `
4848
6764
  <tr>
4849
- <td>${escapeHtml(environment.label)}</td>
4850
- <td>${escapeHtml(environment.kind)}</td>
6765
+ <td>${escapeHtml2(environment.label)}</td>
6766
+ <td>${escapeHtml2(environment.kind)}</td>
4851
6767
  <td>${badge(environment.status)}</td>
4852
- <td>${escapeHtml(environment.detail)}</td>
6768
+ <td>${escapeHtml2(environment.detail)}</td>
4853
6769
  </tr>`).join("");
4854
6770
  const sessionRows = (overview.sessions ?? []).map((session) => `
4855
6771
  <tr>
4856
- <td>${escapeHtml(session.name)}</td>
4857
- <td>${escapeHtml(session.url ?? "-")}</td>
6772
+ <td>${escapeHtml2(session.name)}</td>
6773
+ <td>${escapeHtml2(session.url ?? "-")}</td>
4858
6774
  <td>${badge(session.status)}</td>
4859
- <td><a href="${escapeHtml(session.previewUrl)}" target="_blank" rel="noreferrer">preview</a></td>
6775
+ <td><a href="${escapeHtml2(session.previewUrl)}" target="_blank" rel="noreferrer">preview</a></td>
4860
6776
  </tr>`).join("");
4861
6777
  const pluginRows = (overview.plugins ?? []).map((plugin) => `
4862
6778
  <tr>
4863
- <td>${escapeHtml(plugin.displayName)}</td>
4864
- <td>${escapeHtml(plugin.version)}</td>
4865
- <td>${escapeHtml(plugin.source)}</td>
6779
+ <td>${escapeHtml2(plugin.displayName)}</td>
6780
+ <td>${escapeHtml2(plugin.version)}</td>
6781
+ <td>${escapeHtml2(plugin.source)}</td>
4866
6782
  <td>${badge(plugin.status)}</td>
4867
- <td>${escapeHtml(plugin.commands.slice(0, 8).join(", ") || "-")}</td>
6783
+ <td>${escapeHtml2(plugin.commands.slice(0, 8).join(", ") || "-")}</td>
4868
6784
  </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>';
6785
+ const evidence = overview.evidence ? `<pre>${escapeHtml2(JSON.stringify(overview.evidence, null, 2))}</pre>` : '<p class="muted">No session selected for evidence.</p>';
4870
6786
  return `<!doctype html>
4871
6787
  <html lang="zh-CN">
4872
6788
  <head>
@@ -4901,7 +6817,7 @@ function renderOverviewHtml(overview) {
4901
6817
  <main>
4902
6818
  <h1>xBrowser Console</h1>
4903
6819
  <span class="readonly">Read-only prototype</span>
4904
- <p>Generated at ${escapeHtml(overview.generatedAt)} \xB7 \u9636\u6BB5 0 / Console Facade \u603B\u89C8</p>
6820
+ <p>Generated at ${escapeHtml2(overview.generatedAt)} \xB7 \u9636\u6BB5 0 / Console Facade \u603B\u89C8</p>
4905
6821
  <section class="cards">
4906
6822
  <div class="card"><span>\u8FD0\u884C\u4F1A\u8BDD</span><strong>${overview.stats.runningSessions}</strong></div>
4907
6823
  <div class="card"><span>\u53EF\u7528\u73AF\u5883</span><strong>${overview.stats.availableEnvironments}</strong></div>
@@ -5101,9 +7017,13 @@ Commands:
5101
7017
  create <name> --template <type> Create plugin
5102
7018
  serve [--port <p>] [--host <h>] [--token <t>] [--cors-origins <csv>] Start HTTP server (loopback by default)
5103
7019
  remote <url> [command] [--token <t>] Execute on remote server
5104
- run <file> Execute commands from file
7020
+ run <file> [--headless] Execute commands from a text file
7021
+ run <jobs.json> [--parallel N] Run named headless jobs concurrently
5105
7022
  viewer [--name <n>] Generate viewer URL
5106
7023
  console-panel [--port <n>] Readonly Console Facade overview
7024
+ site-memory run <workflow.json> [--cold] Run declared workflow in a fresh headless browser
7025
+ site-memory report --output <path> Write HTML run dashboard (never overwrites)
7026
+ site-memory mcp Readonly stdio MCP over run history
5107
7027
  help Show this help
5108
7028
  --version Show version
5109
7029
  Plugin Commands:
@@ -5242,6 +7162,10 @@ async function handleStdinMode(stdinCommands, argv) {
5242
7162
  async function handleEvalMode(argv) {
5243
7163
  const evalCommands = parseEvalFlags(argv);
5244
7164
  if (evalCommands.length === 0) return;
7165
+ if (evalCommands.includes("--help") || evalCommands.includes("-h")) {
7166
+ showMainHelp();
7167
+ return;
7168
+ }
5245
7169
  const knownCommands = new Set(getCommandNames());
5246
7170
  const chainParts = evalCommands.map((value) => {
5247
7171
  const firstWord = value.trim().split(/\s+/)[0] || "";
@@ -5362,7 +7286,7 @@ async function handleChainInput(input, argv) {
5362
7286
  import { helpGenerator as helpGenerator3 } from "@dyyz1993/xcli-core";
5363
7287
 
5364
7288
  // src/router/help.ts
5365
- import { helpGenerator as helpGenerator2, outputFormatter as outputFormatter2 } from "@dyyz1993/xcli-core";
7289
+ import { helpGenerator as helpGenerator2, outputFormatter } from "@dyyz1993/xcli-core";
5366
7290
  function showCommandHelp(siteName, cmd, siteConfig, mode) {
5367
7291
  const c = cmd;
5368
7292
  if (mode === "json") {
@@ -5409,7 +7333,7 @@ function showCommandHelp(siteName, cmd, siteConfig, mode) {
5409
7333
  }
5410
7334
  function outputLoginRequired(result, mode) {
5411
7335
  if (mode === "json" || mode === "yaml") {
5412
- console.log(outputFormatter2.format(result, { mode, color: false, emoji: false }));
7336
+ console.log(outputFormatter.format(result, { mode, color: false, emoji: false }));
5413
7337
  return;
5414
7338
  }
5415
7339
  const message = result.message || "Login required";
@@ -5515,6 +7439,7 @@ async function handleCommandHelp(command, positional, mode) {
5515
7439
  return true;
5516
7440
  }
5517
7441
  function showBuiltinHelp(builtinCmd, mode) {
7442
+ builtinCmd = hideInternalParams(builtinCmd);
5518
7443
  if (mode === "json") {
5519
7444
  const paramsList = [];
5520
7445
  const schema = asZodSchema(builtinCmd.parameters);
@@ -5549,6 +7474,22 @@ function showBuiltinHelp(builtinCmd, mode) {
5549
7474
  }
5550
7475
  console.log(helpGenerator3.generate(builtinCmd, { color: true, emoji: false }));
5551
7476
  }
7477
+ function hideInternalParams(builtinCmd) {
7478
+ const schema = builtinCmd.parameters;
7479
+ if (!schema || typeof schema.omit !== "function") return builtinCmd;
7480
+ const internal = asZodSchema(builtinCmd.parameters);
7481
+ const shapeOrFn = internal.shape ?? internal._def?.shape;
7482
+ const shape = typeof shapeOrFn === "function" ? shapeOrFn() : shapeOrFn;
7483
+ if (!shape) return builtinCmd;
7484
+ const mask = {};
7485
+ for (const [key, field] of Object.entries(shape)) {
7486
+ const fieldSchema = asZodSchema(field);
7487
+ const description = fieldSchema.description || fieldSchema._def?.description || "";
7488
+ if (description.startsWith("Internal:")) mask[key] = true;
7489
+ }
7490
+ if (Object.keys(mask).length === 0) return builtinCmd;
7491
+ return { ...builtinCmd, parameters: schema.omit(mask) };
7492
+ }
5552
7493
  var SUBCOMMAND_HELP = {
5553
7494
  session: "session open|close|kill|list [--session <name>] [--cdp <endpoint>]",
5554
7495
  plugin: "plugin install|uninstall|list|reload|schema|search|info <name>",
@@ -5556,17 +7497,18 @@ var SUBCOMMAND_HELP = {
5556
7497
  daemon: "daemon status [--port <port>]",
5557
7498
  replay: "replay <file> [--slow-mo <ms>] [--stop-on-error]",
5558
7499
  create: "create <name> [--template static|dynamic|login|api]",
5559
- run: "run <file>",
7500
+ run: "run <file> [--headless] | run <jobs.json> [--parallel N]",
5560
7501
  serve: "serve [--port <port>] [--host <host>] [--token <token>] [--cors-origins <csv>]",
5561
7502
  remote: "remote <url> [command] [--token <token>]",
5562
7503
  convert: "convert <file> [--to js|py|sh]",
5563
7504
  extract: "extract <file> [--format json|yaml]",
5564
- filter: "filter <file> [--include <type>] [--exclude <type>]",
7505
+ filter: "filter <in.yaml> <out.yaml> [--include <type>] [--exclude <type>]",
5565
7506
  test: "test <name> [--cdp <endpoint>]",
5566
7507
  viewer: "viewer [--session <name>]",
5567
7508
  "console-panel": "console-panel [--port <port>]",
5568
7509
  kill: "kill [--all]",
5569
- net: "net [--cdp <endpoint>]"
7510
+ net: "net [--cdp <endpoint>]",
7511
+ "site-memory": "site-memory run <workflow.json> [--cold] | report --output <path> | mcp"
5570
7512
  };
5571
7513
 
5572
7514
  // src/server/http-server.ts
@@ -5895,19 +7837,19 @@ function headersToObject(headers) {
5895
7837
  return result;
5896
7838
  }
5897
7839
  function readBody(req) {
5898
- return new Promise((resolve8, reject) => {
7840
+ return new Promise((resolve10, reject) => {
5899
7841
  const chunks = [];
5900
7842
  req.on("data", (chunk) => chunks.push(chunk));
5901
7843
  req.on("end", () => {
5902
7844
  const raw = Buffer.concat(chunks).toString("utf-8");
5903
7845
  if (!raw) {
5904
- resolve8(null);
7846
+ resolve10(null);
5905
7847
  return;
5906
7848
  }
5907
7849
  try {
5908
- resolve8(JSON.parse(raw));
7850
+ resolve10(JSON.parse(raw));
5909
7851
  } catch {
5910
- resolve8(null);
7852
+ resolve10(null);
5911
7853
  }
5912
7854
  });
5913
7855
  req.on("error", reject);
@@ -5961,7 +7903,7 @@ var HTTPServer = class {
5961
7903
  res.end(JSON.stringify({ error: "INTERNAL_ERROR", message, statusCode: 500 }));
5962
7904
  });
5963
7905
  });
5964
- return new Promise((resolve8, reject) => {
7906
+ return new Promise((resolve10, reject) => {
5965
7907
  const server = this.server;
5966
7908
  server.on("error", (err) => {
5967
7909
  this.server = null;
@@ -5976,7 +7918,7 @@ var HTTPServer = class {
5976
7918
  this.port = addr.port;
5977
7919
  }
5978
7920
  console.log(`HTTP server listening on http://${this.host}:${this.port}`);
5979
- resolve8({ port: this.port, host: this.host });
7921
+ resolve10({ port: this.port, host: this.host });
5980
7922
  });
5981
7923
  });
5982
7924
  }
@@ -5987,13 +7929,13 @@ var HTTPServer = class {
5987
7929
  */
5988
7930
  async stop() {
5989
7931
  if (!this.server) return;
5990
- return new Promise((resolve8, reject) => {
7932
+ return new Promise((resolve10, reject) => {
5991
7933
  this.server.close((err) => {
5992
7934
  if (err) {
5993
7935
  reject(err);
5994
7936
  } else {
5995
7937
  this.server = null;
5996
- resolve8();
7938
+ resolve10();
5997
7939
  }
5998
7940
  });
5999
7941
  });
@@ -6137,7 +8079,7 @@ async function handleRemote(args, options, mode) {
6137
8079
  }
6138
8080
  }
6139
8081
  async function startMcpServer() {
6140
- const { startMcpStdio } = await import("./server-R4OYD7ZC.js");
8082
+ const { startMcpStdio } = await import("./server-ZHZDJJMG.js");
6141
8083
  startMcpStdio();
6142
8084
  }
6143
8085
 
@@ -6181,8 +8123,18 @@ async function dispatchSubcommand(request) {
6181
8123
  await handleFilter(cmdArgs, mode, options);
6182
8124
  return true;
6183
8125
  case "run":
6184
- if (!cmdArgs[0]) outputError("Usage: xbrowser run <file>");
6185
- await handleRun(cmdArgs[0], { cdpEndpoint, sessionName });
8126
+ if (!cmdArgs[0]) {
8127
+ outputError("Usage: xbrowser run <file>");
8128
+ } else if (options.headless === true || options.parallel !== void 0 || cmdArgs[0].endsWith(".json")) {
8129
+ if (cdpEndpoint || options.bridge) {
8130
+ outputError("Managed runs use a self-launched headless browser");
8131
+ } else {
8132
+ const { handleManagedRunFile } = await import("./run-routes-64IBBVOX.js");
8133
+ await handleManagedRunFile(cmdArgs[0], { sessionName, parallel: options.parallel, mode });
8134
+ }
8135
+ } else {
8136
+ await handleRun(cmdArgs[0], { cdpEndpoint, sessionName });
8137
+ }
6186
8138
  return true;
6187
8139
  case "serve":
6188
8140
  await handleServe(cmdArgs, options, mode);
@@ -6212,6 +8164,9 @@ async function dispatchSubcommand(request) {
6212
8164
  case "net":
6213
8165
  await handleNetCommand(cmdArgs, options, mode, sessionName);
6214
8166
  return true;
8167
+ case "site-memory":
8168
+ await handleSiteMemory(cmdArgs, options, mode);
8169
+ return true;
6215
8170
  case "console-panel":
6216
8171
  await handleConsoleServe(cmdArgs, options, mode);
6217
8172
  return true;
@@ -6229,7 +8184,7 @@ import {
6229
8184
  isCommandResult,
6230
8185
  tip as makeTipSafe,
6231
8186
  normalizeTips,
6232
- outputFormatter as outputFormatter3,
8187
+ outputFormatter as outputFormatter2,
6233
8188
  TipCollector
6234
8189
  } from "@dyyz1993/xcli-core";
6235
8190
  var KNOWN_GLOBAL_OPTIONS = /* @__PURE__ */ new Set([
@@ -6249,6 +8204,16 @@ var KNOWN_GLOBAL_OPTIONS = /* @__PURE__ */ new Set([
6249
8204
  "headless",
6250
8205
  "tab"
6251
8206
  ]);
8207
+ var GLOBAL_VALUE_FLAGS = /* @__PURE__ */ new Set([
8208
+ "--session",
8209
+ "--cdp",
8210
+ "--output",
8211
+ "-o",
8212
+ "--timeout",
8213
+ "--frame",
8214
+ "--target",
8215
+ "--tab"
8216
+ ]);
6252
8217
  async function handlePluginOrChainRoute(request) {
6253
8218
  const { command, cmdArgs, argv, options, mode, cdpEndpoint, sessionName, chainTokenStart, chainTokenEnd } = request;
6254
8219
  const loader = await getPluginLoader();
@@ -6270,7 +8235,7 @@ async function handlePluginOrChainRoute(request) {
6270
8235
  continue;
6271
8236
  }
6272
8237
  if (globalFlagSet.has(argv[i])) continue;
6273
- if (i > 0 && globalFlagSet.has(argv[i - 1]) && !argv[i].startsWith("-")) continue;
8238
+ if (i > 0 && GLOBAL_VALUE_FLAGS.has(argv[i - 1]) && !argv[i].startsWith("-")) continue;
6274
8239
  if (argv[i].startsWith("--session=") || argv[i].startsWith("--cdp=")) continue;
6275
8240
  cleanParts.push(argv[i]);
6276
8241
  }
@@ -6415,7 +8380,7 @@ Run "xbrowser ${command} ${subCommand} --help" to see available parameters.`
6415
8380
  }
6416
8381
  const needsBrowser = cmdEntry.scope === "page" || cmdEntry.scope === "browser";
6417
8382
  if (needsBrowser && !process.env.XBROWSER_DAEMON_WORKER) {
6418
- const { forwardPluginExec } = await import("./daemon-client-HEGAXWGK.js");
8383
+ const { forwardPluginExec } = await import("./daemon-client-BBPQWLUX.js");
6419
8384
  const userTimeout = typeof params.timeout === "number" && params.timeout > 0 ? params.timeout * 1e3 + 3e4 : void 0;
6420
8385
  const result = await forwardPluginExec(`${command}.${subCommand}`, params, sessionName, cdpEndpoint, userTimeout);
6421
8386
  const resultData = result && typeof result === "object" && "data" in result ? result.data : void 0;
@@ -6427,14 +8392,20 @@ Run "xbrowser ${command} ${subCommand} --help" to see available parameters.`
6427
8392
  if (result && result.success !== false) {
6428
8393
  if (isCommandResult(result)) {
6429
8394
  if (mode === "json" || mode === "yaml") {
6430
- console.log(outputFormatter3.format(result.data, { mode, color: false, emoji: false }));
8395
+ console.log(outputFormatter2.format(result.data, { mode, color: false, emoji: false }));
6431
8396
  if (result.tips?.length) {
6432
- for (const tip of result.tips) console.error(`\u{1F4A1} ${tip}`);
8397
+ for (const tip of result.tips) {
8398
+ const text = typeof tip === "string" ? tip : tip.message;
8399
+ if (text) console.error(`\u{1F4A1} ${text}`);
8400
+ }
6433
8401
  }
6434
8402
  } else {
6435
- console.log(outputFormatter3.format(result.data, { mode: "text", color: true, emoji: true }));
8403
+ console.log(outputFormatter2.format(result.data, { mode: "text", color: true, emoji: true }));
6436
8404
  if (result.tips?.length) {
6437
- for (const tip of result.tips) console.log(` \u{1F4A1} ${tip}`);
8405
+ for (const tip of result.tips) {
8406
+ const text = typeof tip === "string" ? tip : tip.message;
8407
+ if (text) console.log(` \u{1F4A1} ${text}`);
8408
+ }
6438
8409
  }
6439
8410
  }
6440
8411
  }
@@ -6455,7 +8426,7 @@ Run "xbrowser ${command} ${subCommand} --help" to see available parameters.`
6455
8426
  const targetPage = pages[cmdTabIndex];
6456
8427
  await targetPage.bringToFront().catch(() => {
6457
8428
  });
6458
- const { setActivePage } = await import("./browser-GXL6V2JW.js");
8429
+ const { setActivePage } = await import("./browser-NHQDQRXB.js");
6459
8430
  setActivePage(session, targetPage);
6460
8431
  }
6461
8432
  }
@@ -6551,7 +8522,7 @@ Run "xbrowser ${command} ${subCommand} --help" to see available parameters.`
6551
8522
  mode
6552
8523
  );
6553
8524
  } else {
6554
- console.log(outputFormatter3.format(outputData, { mode: "text", color: true, emoji: true }));
8525
+ console.log(outputFormatter2.format(outputData, { mode: "text", color: true, emoji: true }));
6555
8526
  if (tips?.length) {
6556
8527
  for (const tip of tips) console.log(` \u{1F4A1} ${typeof tip === "string" ? tip : tip.message}`);
6557
8528
  }
@@ -6582,8 +8553,10 @@ async function routeCommand(argvIn, stdinCommands) {
6582
8553
  return;
6583
8554
  }
6584
8555
  const evalStart = findEvalStart(argv);
6585
- if (evalStart >= 0 && argv.length > evalStart + 1) {
6586
- await handleEvalScript(argv.slice(evalStart + 1), argv);
8556
+ const evalParts = evalStart >= 0 ? argv.slice(evalStart + 1) : [];
8557
+ const evalHelpRequested = evalParts.includes("--help") || evalParts.includes("-h");
8558
+ if (evalStart >= 0 && evalParts.length > 0 && !evalHelpRequested) {
8559
+ await handleEvalScript(evalParts, argv);
6587
8560
  return;
6588
8561
  }
6589
8562
  if (parseEvalFlags(argv).length > 0) {
@@ -6602,12 +8575,12 @@ async function routeCommand(argvIn, stdinCommands) {
6602
8575
  if (argv[0] === "--json" || argv[0] === "--yaml") {
6603
8576
  argv = argv.slice(1);
6604
8577
  }
6605
- const globalFlags = /* @__PURE__ */ new Set(["--session", "--cdp", "--json", "--yaml", "--output", "--timeout", "--help", "-h", "--version", "--frame", "--target", "--tab"]);
8578
+ const globalFlags = /* @__PURE__ */ new Set([...GLOBAL_VALUE_FLAGS, "--json", "--yaml", "--help", "-h", "--version", "--bridge"]);
6606
8579
  let chainArgIdx = -1;
6607
8580
  let seenCommandWord = false;
6608
8581
  for (let i = 0; i < argv.length; i++) {
6609
8582
  if (globalFlags.has(argv[i])) continue;
6610
- if (globalFlags.has(argv[i]) || i > 0 && globalFlags.has(argv[i - 1]) && !argv[i].startsWith("-")) continue;
8583
+ if (globalFlags.has(argv[i]) || i > 0 && GLOBAL_VALUE_FLAGS.has(argv[i - 1]) && !argv[i].startsWith("-")) continue;
6611
8584
  if (!seenCommandWord) {
6612
8585
  if (argv[i].includes(" ") && /^[a-zA-Z]/.test(argv[i])) {
6613
8586
  chainArgIdx = i;
@@ -6618,12 +8591,15 @@ async function routeCommand(argvIn, stdinCommands) {
6618
8591
  }
6619
8592
  if (chainArgIdx >= 0) {
6620
8593
  const chainArg = argv[chainArgIdx];
8594
+ if (isChainInput(chainArg)) {
8595
+ await handleChainInput(chainArg, argvIn);
8596
+ return;
8597
+ }
6621
8598
  const spaceIdx = chainArg.indexOf(" ");
6622
8599
  const possibleCmd = chainArg.substring(0, spaceIdx);
6623
8600
  if (/^[a-zA-Z][\w-]*$/.test(possibleCmd)) {
6624
8601
  const remainder = chainArg.substring(spaceIdx + 1);
6625
- let remainderParts = remainder.split(/\s+/).filter(Boolean);
6626
- remainderParts = remainderParts.flatMap((part) => part.split(";").filter(Boolean));
8602
+ const remainderParts = splitOutsideQuotes(remainder, ";").flatMap((part) => splitCommand(part)).map(unquote);
6627
8603
  chainTokenStart = chainArgIdx;
6628
8604
  chainTokenEnd = chainArgIdx + remainderParts.length;
6629
8605
  argv = [...argv.slice(0, chainArgIdx), possibleCmd, ...remainderParts, ...argv.slice(chainArgIdx + 1)];
@@ -6636,7 +8612,7 @@ async function routeCommand(argvIn, stdinCommands) {
6636
8612
  const hasJsonFlag = argv.some((a) => a === "--json" || a.startsWith("--json="));
6637
8613
  const hasYamlFlag = argv.some((a) => a === "--yaml" || a.startsWith("--yaml="));
6638
8614
  const cleanArgv = argv.filter((a) => a !== "--json" && a !== "--yaml");
6639
- const parsed = parseArgs(cleanArgv, { booleanFlags: ["json", "yaml"] });
8615
+ const parsed = parseArgs(cleanArgv, { booleanFlags: ["json", "yaml", "bridge", "headless"] });
6640
8616
  const { positional, options } = parsed;
6641
8617
  if (hasJsonFlag) options.json = true;
6642
8618
  if (hasYamlFlag) options.yaml = true;
@@ -6703,7 +8679,7 @@ async function main() {
6703
8679
  let exitCode = 0;
6704
8680
  try {
6705
8681
  await ensureProxyFetch();
6706
- const isMcp = process.argv[2] === "mcp";
8682
+ const isMcp = process.argv[2] === "mcp" || process.argv[2] === "site-memory" && process.argv[3] === "mcp";
6707
8683
  const stdinCommands = isMcp ? [] : await readStdin();
6708
8684
  await routeCommand(process.argv.slice(2), stdinCommands);
6709
8685
  } catch (err) {
@@ -6711,9 +8687,10 @@ async function main() {
6711
8687
  exitCode = 1;
6712
8688
  } finally {
6713
8689
  const command = process.argv[2];
6714
- const isLongRunning = command === "preview" || command === "serve" || command === "mcp" || command === "console-panel";
8690
+ const commandSub = process.argv[3];
8691
+ const isLongRunning = command === "preview" || command === "serve" || command === "mcp" || command === "console-panel" || command === "site-memory" && commandSub === "mcp";
6715
8692
  if (!isLongRunning) {
6716
- const { ensureProcessCanExit } = await import("./browser-GXL6V2JW.js");
8693
+ const { ensureProcessCanExit } = await import("./browser-NHQDQRXB.js");
6717
8694
  await ensureProcessCanExit().catch(() => {
6718
8695
  });
6719
8696
  process.exit(process.exitCode || exitCode);