@xbrowser/cli 1.34.0 → 1.35.0

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