@xbrowser/cli 1.33.0 → 1.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/{browser-3LBSVDSS.js → browser-KY7AIRAB.js} +3 -2
  2. package/dist/{browser-23BMBCH2.js → browser-MLKP72XP.js} +3 -3
  3. package/dist/{browser-D7RFPTD4.js → browser-RZ7DPBI3.js} +3 -3
  4. package/dist/cdp-driver-CCG3OJUQ.js +49 -0
  5. package/dist/{cdp-driver-B5KVVI4O.js → cdp-driver-HBMCD7NU.js} +2 -2
  6. package/dist/{cdp-driver-GE6Y6LPI.js → cdp-driver-MJD7YIQI.js} +2 -2
  7. package/dist/{cdp-driver-6G77XM4H.js → cdp-driver-YJU4GRSV.js} +203 -95
  8. package/dist/chunk-3SZTCI33.js +147 -0
  9. package/dist/{chunk-OVAUGFM6.js → chunk-43U5VDLB.js} +8 -2
  10. package/dist/chunk-53VZHESL.js +150 -0
  11. package/dist/{chunk-NAIHOVDZ.js → chunk-63526WET.js} +2 -8
  12. package/dist/{chunk-YX5KVWGX.js → chunk-6DS3T6UK.js} +203 -95
  13. package/dist/{chunk-DDHHVII7.js → chunk-BLCBCESM.js} +8 -2
  14. package/dist/{chunk-SH6OTPXN.js → chunk-C5ZPXPD7.js} +31 -7
  15. package/dist/chunk-EGOWDZXP.js +149 -0
  16. package/dist/chunk-GNLZWHSP.js +1380 -0
  17. package/dist/{chunk-5MYC6LVL.js → chunk-GYGVHWG3.js} +279 -1460
  18. package/dist/{chunk-2KPI5GKP.js → chunk-IYCB2KJL.js} +2 -8
  19. package/dist/chunk-JYYKMSFH.js +39 -0
  20. package/dist/{chunk-TBJUSUKF.js → chunk-NBT2CE3H.js} +140 -96
  21. package/dist/{chunk-ACPMC47K.js → chunk-QRFM4NOV.js} +1025 -202
  22. package/dist/chunk-RGL2YTWQ.js +64 -0
  23. package/dist/{chunk-BND5O5KC.js → chunk-SQLICOPZ.js} +177 -240
  24. package/dist/{chunk-O5PASNI7.js → chunk-UUW5EGES.js} +139 -237
  25. package/dist/{chunk-43TEMG4U.js → chunk-WGS3Y6ZV.js} +3 -1
  26. package/dist/{chunk-AKT3WLZM.js → chunk-Y2GRCINH.js} +1004 -183
  27. package/dist/{chunk-H25ECCYJ.js → chunk-ZCZELQCS.js} +203 -95
  28. package/dist/cli.js +2237 -278
  29. package/dist/{daemon-client-7D6EZNOE.js → daemon-client-OXKRGLPQ.js} +32 -8
  30. package/dist/{daemon-client-HEGAXWGK.js → daemon-client-Z3NKNZRL.js} +5 -1
  31. package/dist/daemon-main.js +2214 -159
  32. package/dist/human-interaction-BGAZC3JR.js +12 -0
  33. package/dist/human-interaction-TPKPEE7A.js +11 -0
  34. package/dist/human-interaction-ZSD3IX6Q.js +12 -0
  35. package/dist/index.d.ts +225 -94
  36. package/dist/index.js +2880 -267
  37. package/dist/{launcher-TOLF23ET.js → launcher-AUJK5QQM.js} +1 -1
  38. package/dist/{launcher-ZYB32LSZ.js → launcher-QBAZ6F5L.js} +1 -1
  39. package/dist/mistake-ledger-2B4N54CO.js +29 -0
  40. package/dist/{recovery-ORHJSBDN.js → recovery-5AGY7CV3.js} +4 -5
  41. package/dist/{recovery-JFGV3DBX.js → recovery-7NRRHLS4.js} +4 -4
  42. package/dist/{recovery-XDKN63O5.js → recovery-TIBRFGRP.js} +4 -4
  43. package/dist/run-routes-SJKVZ34L.js +26 -0
  44. package/dist/run-routes-TFNV5BBR.js +24 -0
  45. package/dist/{server-5JHB4TML.js → server-HUSX7EFE.js} +5 -4
  46. package/dist/{server-6CTC3RHV.js → server-KSP5H4HD.js} +5 -3
  47. package/dist/{session-replayer-IGRRA2QC.js → session-replayer-4TCLQI76.js} +1 -1
  48. package/dist/viewer-routes-YOS5GTCV.js +11 -0
  49. package/package.json +1 -1
  50. package/dist/chunk-QCV2PI7U.js +0 -184
  51. package/dist/human-interaction-ISMMOJOK.js +0 -8
  52. package/dist/human-interaction-STTZZZ5N.js +0 -8
  53. package/dist/human-interaction-UXFYV7DU.js +0 -8
package/dist/index.js CHANGED
@@ -1,3 +1,11 @@
1
+ import {
2
+ handleViewer
3
+ } from "./chunk-JYYKMSFH.js";
4
+ import {
5
+ generateBashScript,
6
+ generateJSScript,
7
+ generatePythonScript
8
+ } from "./chunk-ETCO4SNK.js";
1
9
  import {
2
10
  extractAndSave,
3
11
  extractRecording,
@@ -7,6 +15,16 @@ import {
7
15
  filterRecording,
8
16
  parseExcludeTypes
9
17
  } from "./chunk-ANVL2ID2.js";
18
+ import {
19
+ handleRun,
20
+ readCommandFile,
21
+ readStdin
22
+ } from "./chunk-53VZHESL.js";
23
+ import {
24
+ outputEnvelope,
25
+ outputError,
26
+ outputResult
27
+ } from "./chunk-RGL2YTWQ.js";
10
28
  import {
11
29
  ALL_ENGINE_KEYS,
12
30
  PluginMetadataParser,
@@ -48,7 +66,7 @@ import {
48
66
  splitCommand,
49
67
  waitForAIResponse,
50
68
  waitForPage
51
- } from "./chunk-AKT3WLZM.js";
69
+ } from "./chunk-Y2GRCINH.js";
52
70
  import {
53
71
  SessionRecorder,
54
72
  readMarkdownSummary
@@ -64,8 +82,9 @@ import {
64
82
  getBrowser,
65
83
  resetForTesting,
66
84
  saveSessionDiskMeta
67
- } from "./chunk-DDHHVII7.js";
85
+ } from "./chunk-BLCBCESM.js";
68
86
  import "./chunk-JKVUFP3G.js";
87
+ import "./chunk-3SZTCI33.js";
69
88
  import {
70
89
  daemonPing,
71
90
  forwardCommandLog,
@@ -89,18 +108,16 @@ import {
89
108
  forwardReplay,
90
109
  forwardSessionClose,
91
110
  forwardSessionList,
92
- forwardViewerCheckSelector,
93
111
  version
94
- } from "./chunk-SH6OTPXN.js";
112
+ } from "./chunk-C5ZPXPD7.js";
95
113
  import {
96
114
  buildViewerUrl
97
115
  } from "./chunk-3OD76SUE.js";
98
116
  import {
99
117
  CaptchaDetector,
100
118
  HumanInteractionManager,
101
- ScreencastCapturer,
102
119
  WebhookNotifier
103
- } from "./chunk-O5PASNI7.js";
120
+ } from "./chunk-UUW5EGES.js";
104
121
  import {
105
122
  NPM_REGISTRY_URL,
106
123
  NPM_SCOPE,
@@ -112,20 +129,14 @@ import {
112
129
  setConfigValue
113
130
  } from "./chunk-ZTHE5RBZ.js";
114
131
  import {
115
- getDaemonConfig,
116
132
  getDaemonProcessStatus,
117
133
  killAllDaemonProcesses,
118
134
  startDaemonProcess,
119
135
  stopDaemonProcess
120
136
  } from "./chunk-Q2DFJQGS.js";
121
- import {
122
- generateBashScript,
123
- generateJSScript,
124
- generatePythonScript
125
- } from "./chunk-ETCO4SNK.js";
126
- import "./chunk-YX5KVWGX.js";
137
+ import "./chunk-6DS3T6UK.js";
127
138
  import "./chunk-SMYSNO4M.js";
128
- import "./chunk-2KPI5GKP.js";
139
+ import "./chunk-IYCB2KJL.js";
129
140
  import {
130
141
  errMsg
131
142
  } from "./chunk-GDKLH7ZY.js";
@@ -172,65 +183,6 @@ var BROWSER_SCOPE = {
172
183
  // src/router.ts
173
184
  import { parseArgs } from "@dyyz1993/xcli-core";
174
185
 
175
- // src/cli/output.ts
176
- import { outputFormatter, OutputFormatter } from "@dyyz1993/xcli-core";
177
- var formatter = new OutputFormatter();
178
- function outputResult(result, mode = "text") {
179
- if (mode !== "json" && mode !== "yaml" && typeof result === "object" && result !== null) {
180
- const r = result;
181
- if (r.success === false) {
182
- outputError(r.message ? String(r.message) : "Unknown error");
183
- }
184
- if (r.ok === false) {
185
- outputError(r.error ? String(r.error) : "Unknown error");
186
- }
187
- }
188
- const output = outputFormatter.format(result, {
189
- mode,
190
- color: mode === "text",
191
- emoji: false
192
- });
193
- console.log(output);
194
- }
195
- function outputError(message) {
196
- const formatted = formatter.formatError(message, { color: true, emoji: false });
197
- console.error(formatted);
198
- process.exitCode = 1;
199
- }
200
- function outputEnvelope(result, meta, mode) {
201
- if (mode !== "json" && mode !== "yaml") {
202
- if (!result.success) {
203
- outputError(result.message || "Unknown error");
204
- return;
205
- }
206
- outputResult(result.data, mode);
207
- return;
208
- }
209
- const { command, ...extraMeta } = meta;
210
- const commandResult = {
211
- success: result.success,
212
- data: result.data,
213
- message: result.message,
214
- tips: [],
215
- meta: {
216
- duration: result.duration ?? 0,
217
- ...extraMeta
218
- }
219
- };
220
- const formatted = outputFormatter.formatEnvelope(commandResult, {
221
- command,
222
- extraMeta,
223
- mode
224
- });
225
- console.log(formatted);
226
- if (result.tips?.length) {
227
- for (const tip of result.tips) {
228
- const text = typeof tip === "string" ? tip : tip.message;
229
- if (text) console.error(` \u{1F4A1} ${text}`);
230
- }
231
- }
232
- }
233
-
234
186
  // src/utils/selector.ts
235
187
  var HTML_TAGS = /* @__PURE__ */ new Set([
236
188
  "html",
@@ -805,7 +757,9 @@ async function handleBrowserCommand(command, args, options, sessionName, mode, c
805
757
  } else if (typeof options.frame === "string") {
806
758
  params = { ...params, _frame: options.frame };
807
759
  }
808
- const result = cdpEndpoint ? await executeCommand(cmdName, params, sessionName, { cdpEndpoint }) : await executeCommand(cmdName, params, sessionName);
760
+ const bridgeFlag = options.bridge === true || String(options.bridge) === "true" || process.env.XBROWSER_BRIDGE === "1";
761
+ const extra = bridgeFlag ? { cdpEndpoint, bridge: true } : cdpEndpoint ? { cdpEndpoint } : void 0;
762
+ const result = extra ? await executeCommand(cmdName, params, sessionName, extra) : await executeCommand(cmdName, params, sessionName);
809
763
  if (mode === "json" || mode === "yaml") {
810
764
  outputEnvelope(result, { command: cmdName }, mode);
811
765
  } else if (!result.success) {
@@ -827,11 +781,11 @@ async function handleBrowserCommand(command, args, options, sessionName, mode, c
827
781
  const dataObj = result.data;
828
782
  const handlerAlreadyWrote = !!dataObj && typeof dataObj.output === "string";
829
783
  if (outputFile && result.success && result.data && !handlerAlreadyWrote) {
830
- const { writeFileSync: writeFileSync8, mkdirSync: mkdirSync7 } = await import("fs");
831
- const { dirname: dirname5 } = await import("path");
784
+ const { writeFileSync: writeFileSync8, mkdirSync: mkdirSync8 } = await import("fs");
785
+ const { dirname: dirname6 } = await import("path");
832
786
  const content = typeof result.data === "string" ? result.data : dataObj.content || dataObj.text || JSON.stringify(result.data, null, 2);
833
787
  try {
834
- mkdirSync7(dirname5(outputFile), { recursive: true });
788
+ mkdirSync8(dirname6(outputFile), { recursive: true });
835
789
  writeFileSync8(outputFile, content, "utf-8");
836
790
  process.stdout.write(`
837
791
  \u{1F4C4} Written to ${outputFile}
@@ -871,6 +825,10 @@ function handleSessionHelp() {
871
825
  "Commands:",
872
826
  " close [--name <name>] Close session",
873
827
  " list, ls List active sessions",
828
+ " handoff <name> Print the Viewer link for a named session",
829
+ " save <name> Save login state from a local session",
830
+ " restore <name> Restore saved login state in a fresh session",
831
+ " errors List recurring command errors",
874
832
  " kill [--name <name>] Kill session forcefully",
875
833
  " kill-all Kill all sessions and daemon",
876
834
  "",
@@ -1240,14 +1198,14 @@ function isValidGitUrl(url) {
1240
1198
  return GIT_URL_RE.test(url) || GIT_SCP_RE.test(url);
1241
1199
  }
1242
1200
  function execGit(args) {
1243
- return new Promise((resolve8, reject) => {
1201
+ return new Promise((resolve10, reject) => {
1244
1202
  execFile("git", args, (err, _stdout, stderr) => {
1245
1203
  if (err) {
1246
1204
  const stderrText = typeof stderr === "string" ? stderr : stderr?.toString("utf-8") ?? "";
1247
1205
  const detail = stderrText.trim() || err.message;
1248
1206
  reject(new Error(`git clone failed: ${detail}`));
1249
1207
  } else {
1250
- resolve8();
1208
+ resolve10();
1251
1209
  }
1252
1210
  });
1253
1211
  });
@@ -1620,16 +1578,30 @@ var PluginInstaller = class {
1620
1578
  *
1621
1579
  * Some marketplace/npm packages import from `../shared/` (e.g. ssr-detect.js,
1622
1580
  * ai-chat-base.ts) but the `shared/` directory is not included in the package.
1623
- * This method scans the installed plugin's index.ts for such imports and
1624
- * copies the missing files from the local repository's `.xcli/plugins/shared/`
1625
- * directory (if available).
1581
+ * This method scans every .ts/.js source file in the installed plugin (not just
1582
+ * index.ts — media plugins like gemini import shared modules from generate.ts,
1583
+ * history.ts, music.ts, etc.) for such imports and copies the missing files
1584
+ * from the local repository's `.xcli/plugins/shared/` directory (if available).
1626
1585
  */
1627
1586
  async fixSharedDeps(pluginDir) {
1628
- const indexPath = resolve6(pluginDir, "index.ts");
1629
- if (!existsSync6(indexPath)) return;
1587
+ const sourceFiles = [];
1588
+ const collectSourceFiles = (dir) => {
1589
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1590
+ if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
1591
+ const full = resolve6(dir, entry.name);
1592
+ if (entry.isDirectory()) {
1593
+ collectSourceFiles(full);
1594
+ } else if (/\.(ts|js)$/.test(entry.name)) {
1595
+ sourceFiles.push(full);
1596
+ }
1597
+ }
1598
+ };
1599
+ if (!existsSync6(pluginDir)) return;
1600
+ collectSourceFiles(pluginDir);
1601
+ if (sourceFiles.length === 0) return;
1630
1602
  let content;
1631
1603
  try {
1632
- content = readFileSync5(indexPath, "utf8");
1604
+ content = sourceFiles.map((f) => readFileSync5(f, "utf8")).join("\n");
1633
1605
  } catch {
1634
1606
  return;
1635
1607
  }
@@ -1643,8 +1615,7 @@ var PluginInstaller = class {
1643
1615
  const sharedDir = resolve6(pluginDir, "..", "shared");
1644
1616
  const toCopy = [];
1645
1617
  for (const file of missingFiles) {
1646
- const targetPath = resolve6(sharedDir, file);
1647
- if (!existsSync6(targetPath)) {
1618
+ if (!existsSync6(resolve6(sharedDir, file)) && !toCopy.includes(file)) {
1648
1619
  toCopy.push(file);
1649
1620
  }
1650
1621
  }
@@ -1666,16 +1637,23 @@ var PluginInstaller = class {
1666
1637
  let allDownloaded = true;
1667
1638
  for (const file of toCopy) {
1668
1639
  try {
1669
- const url = `${GITHUB_RAW}/${file}`;
1670
- const resp = await fetch(url, { signal: AbortSignal.timeout(1e4) });
1671
- if (resp.ok) {
1672
- const content2 = await resp.text();
1673
- const dst = resolve6(sharedDir, file);
1674
- const dstDir = dirname2(dst);
1675
- if (!existsSync6(dstDir)) mkdirSync4(dstDir, { recursive: true });
1676
- writeFileSync5(dst, content2, "utf-8");
1677
- console.log(`\u2705 Downloaded shared/${file} from GitHub`);
1678
- } else {
1640
+ const candidates = file.endsWith(".js") ? [file, file.replace(/\.js$/, ".ts")] : [file];
1641
+ let downloaded = false;
1642
+ for (const candidate of candidates) {
1643
+ const url = `${GITHUB_RAW}/${candidate}`;
1644
+ const resp = await fetch(url, { signal: AbortSignal.timeout(1e4) });
1645
+ if (resp.ok) {
1646
+ const fileContent = await resp.text();
1647
+ const dst = resolve6(sharedDir, candidate);
1648
+ const dstDir = dirname2(dst);
1649
+ if (!existsSync6(dstDir)) mkdirSync4(dstDir, { recursive: true });
1650
+ writeFileSync5(dst, fileContent, "utf-8");
1651
+ console.log(`\u2705 Downloaded shared/${candidate} from GitHub`);
1652
+ downloaded = true;
1653
+ break;
1654
+ }
1655
+ }
1656
+ if (!downloaded) {
1679
1657
  allDownloaded = false;
1680
1658
  break;
1681
1659
  }
@@ -1692,16 +1670,21 @@ var PluginInstaller = class {
1692
1670
  }
1693
1671
  mkdirSync4(sharedDir, { recursive: true });
1694
1672
  for (const file of toCopy) {
1695
- const src = resolve6(sourceSharedDir, file);
1696
- const dst = resolve6(sharedDir, file);
1697
- if (existsSync6(src)) {
1673
+ const candidates = file.endsWith(".js") ? [file, file.replace(/\.js$/, ".ts")] : [file];
1674
+ const src = candidates.map((c) => resolve6(sourceSharedDir, c)).find((p) => existsSync6(p));
1675
+ if (!src) {
1676
+ console.warn(`\u26A0\uFE0F Could not copy shared/${file}: not found in ${sourceSharedDir}`);
1677
+ continue;
1678
+ }
1679
+ const dst = resolve6(sharedDir, basename2(src));
1680
+ {
1698
1681
  try {
1699
1682
  cpSync6(dirname2(src), dirname2(dst), { recursive: true });
1700
- console.log(`\u2705 Copied shared/${file} for plugin "${basename2(pluginDir)}"`);
1683
+ console.log(`\u2705 Copied shared/${basename2(src)} for plugin "${basename2(pluginDir)}"`);
1701
1684
  } catch {
1702
1685
  try {
1703
1686
  copyFileSync(src, dst);
1704
- console.log(`\u2705 Copied shared/${file} for plugin "${basename2(pluginDir)}"`);
1687
+ console.log(`\u2705 Copied shared/${basename2(src)} for plugin "${basename2(pluginDir)}"`);
1705
1688
  } catch {
1706
1689
  console.warn(`\u26A0\uFE0F Could not copy shared/${file}`);
1707
1690
  }
@@ -2893,6 +2876,35 @@ function cleanSessionFiles() {
2893
2876
  async function handleSession(args, options, mode, _cdpEndpoint) {
2894
2877
  const sub = args[0];
2895
2878
  switch (sub) {
2879
+ case "handoff": {
2880
+ const { handleViewer: handleViewer2 } = await import("./viewer-routes-YOS5GTCV.js");
2881
+ await handleViewer2([], { ...options, session: args[1] ?? options.session }, mode, _cdpEndpoint);
2882
+ break;
2883
+ }
2884
+ case "save":
2885
+ case "restore": {
2886
+ const name = args[1] || options.session || process.env.XBROWSER_SESSION || "default";
2887
+ try {
2888
+ const { forwardSessionState } = await import("./daemon-client-Z3NKNZRL.js");
2889
+ const data = await forwardSessionState(sub, name);
2890
+ outputEnvelope({ success: true, data }, { command: `session ${sub}` }, mode);
2891
+ } catch (error) {
2892
+ outputEnvelope({ success: false, data: null, message: error instanceof Error ? error.message : String(error) }, { command: `session ${sub}` }, mode);
2893
+ process.exitCode = 1;
2894
+ }
2895
+ break;
2896
+ }
2897
+ case "errors": {
2898
+ const { listMistakes } = await import("./mistake-ledger-2B4N54CO.js");
2899
+ const errors = listMistakes().map(({ category, occurrences, constrained }) => ({
2900
+ category,
2901
+ command: occurrences.at(-1)?.command,
2902
+ count: occurrences.length,
2903
+ constrained
2904
+ }));
2905
+ outputEnvelope({ success: true, data: { errors } }, { command: "session errors" }, mode);
2906
+ break;
2907
+ }
2896
2908
  case "close": {
2897
2909
  if (options.all) {
2898
2910
  let count = 0;
@@ -2921,9 +2933,18 @@ async function handleSession(args, options, mode, _cdpEndpoint) {
2921
2933
  }
2922
2934
  case "list":
2923
2935
  case "ls": {
2936
+ let daemon;
2937
+ try {
2938
+ const ping = await daemonPing();
2939
+ if (ping && ping.ok && "version" in ping) {
2940
+ const info = ping;
2941
+ daemon = { version: info.version, buildId: info.buildId, startedAt: info.startedAt, pid: info.pid };
2942
+ }
2943
+ } catch {
2944
+ }
2924
2945
  try {
2925
2946
  const sessions = await forwardSessionList();
2926
- outputEnvelope({ success: true, data: { sessions } }, { command: "session list" }, mode);
2947
+ outputEnvelope({ success: true, data: daemon ? { sessions, daemon } : { sessions } }, { command: "session list" }, mode);
2927
2948
  } catch {
2928
2949
  const sessions = await listSessions();
2929
2950
  outputEnvelope({ success: true, data: { sessions } }, { command: "session list" }, mode);
@@ -3060,6 +3081,51 @@ async function infoFromMarketplacePlugin(slug, loader) {
3060
3081
  }
3061
3082
  return null;
3062
3083
  }
3084
+ async function searchFromMarketplaceAPI(options) {
3085
+ const baseUrl = getMarketplaceUrl();
3086
+ const params = new URLSearchParams();
3087
+ if (options.query) params.set("search", options.query);
3088
+ if (options.tag) params.set("tag", options.tag);
3089
+ if (options.site) params.set("site", options.site);
3090
+ if (options.limit) params.set("limit", String(options.limit));
3091
+ const url = `${baseUrl}/api/plugins?${params.toString()}`;
3092
+ const resp = await fetch(url, { signal: AbortSignal.timeout(5e3) });
3093
+ if (!resp.ok) return [];
3094
+ const body = await resp.json();
3095
+ const items = body.data?.items ?? [];
3096
+ return items.map((item) => ({
3097
+ name: item.slug || item.name,
3098
+ slug: item.slug,
3099
+ description: item.description,
3100
+ version: item.version,
3101
+ downloads: item.downloadCount,
3102
+ tags: item.tags,
3103
+ sites: item.siteUrls,
3104
+ commands: item.commands,
3105
+ source: "marketplace"
3106
+ }));
3107
+ }
3108
+ async function infoFromMarketplaceAPI(slug) {
3109
+ const baseUrl = getMarketplaceUrl();
3110
+ const url = `${baseUrl}/api/plugins/${encodeURIComponent(slug)}`;
3111
+ const resp = await fetch(url, { signal: AbortSignal.timeout(5e3) });
3112
+ if (!resp.ok) return null;
3113
+ const body = await resp.json();
3114
+ if (!body.success || !body.data) return null;
3115
+ const p = body.data;
3116
+ return {
3117
+ name: p.name || slug,
3118
+ slug: p.slug || slug,
3119
+ description: p.description,
3120
+ version: p.version,
3121
+ author: p.authorName,
3122
+ downloads: p.downloadCount ?? 0,
3123
+ tags: p.tags ?? [],
3124
+ sites: p.siteUrls ?? [],
3125
+ commands: p.commands ?? [],
3126
+ source: "marketplace"
3127
+ };
3128
+ }
3063
3129
  function normalizePluginName(name) {
3064
3130
  return name.replace(/^@[^/]+\//, "").replace(/^xbrowser-plugin-/, "").toLowerCase();
3065
3131
  }
@@ -3116,6 +3182,13 @@ async function handleSearch(args, options, mode) {
3116
3182
  const loader = await getPluginLoader();
3117
3183
  const pluginResults = await searchFromMarketplacePlugin2(searchOpts, loader);
3118
3184
  results.push(...pluginResults);
3185
+ if (pluginResults.length === 0) {
3186
+ try {
3187
+ const apiResults = await searchFromMarketplaceAPI(searchOpts);
3188
+ results.push(...apiResults);
3189
+ } catch {
3190
+ }
3191
+ }
3119
3192
  if (pluginResults.length === 0) {
3120
3193
  try {
3121
3194
  const npmResults = await NPMSearcher.search(searchOpts);
@@ -3187,6 +3260,36 @@ async function handlePluginInfo(args, options, mode) {
3187
3260
  process.stdout.write(`\u6807\u7B7E: ${(d.tags || []).join(", ")}
3188
3261
  `);
3189
3262
  process.stdout.write(`\u7F51\u7AD9: ${(d.sites || []).join(", ")}
3263
+ `);
3264
+ return;
3265
+ }
3266
+ } catch {
3267
+ }
3268
+ try {
3269
+ const apiInfo = await infoFromMarketplaceAPI(slug);
3270
+ if (apiInfo) {
3271
+ const d = apiInfo;
3272
+ if (mode === "json") {
3273
+ outputEnvelope({ success: true, data: { source: "marketplace", ...d } }, { command: "plugin info" }, mode);
3274
+ return;
3275
+ }
3276
+ process.stdout.write(`\u540D\u79F0: ${d.name || ""}
3277
+ `);
3278
+ process.stdout.write(`\u7248\u672C: ${d.version || ""}
3279
+ `);
3280
+ process.stdout.write(`\u63CF\u8FF0: ${d.description || ""}
3281
+ `);
3282
+ process.stdout.write(`\u4F5C\u8005: ${d.author || ""}
3283
+ `);
3284
+ process.stdout.write(`\u547D\u4EE4: ${(d.commands || []).join(", ")}
3285
+ `);
3286
+ process.stdout.write(`\u4E0B\u8F7D\u91CF: ${d.downloads || 0}
3287
+ `);
3288
+ process.stdout.write(`\u6807\u7B7E: ${(d.tags || []).join(", ")}
3289
+ `);
3290
+ process.stdout.write(`\u7F51\u7AD9: ${(d.sites || []).join(", ")}
3291
+ `);
3292
+ process.stdout.write(`\u6765\u6E90: marketplace
3190
3293
  `);
3191
3294
  return;
3192
3295
  }
@@ -3312,7 +3415,7 @@ async function handlePlugin(args, options, mode) {
3312
3415
  } catch {
3313
3416
  }
3314
3417
  try {
3315
- const { daemonPing: daemonPing2 } = await import("./daemon-client-HEGAXWGK.js");
3418
+ const { daemonPing: daemonPing2 } = await import("./daemon-client-Z3NKNZRL.js");
3316
3419
  if (await daemonPing2()) {
3317
3420
  await fetch("http://localhost:9224/rpc", {
3318
3421
  method: "POST",
@@ -3501,9 +3604,9 @@ async function handleRecord(args, options, mode) {
3501
3604
  const defaultRecording = SessionRecorder.getRecordingsDir(sessionName) + "/recording.json";
3502
3605
  if (existsSync9(defaultRecording)) {
3503
3606
  try {
3504
- const { mkdirSync: mkdirSync7, copyFileSync: copyFileSync2 } = await import("fs");
3607
+ const { mkdirSync: mkdirSync8, copyFileSync: copyFileSync2 } = await import("fs");
3505
3608
  const { dirname: pathDirname } = await import("path");
3506
- mkdirSync7(pathDirname(output), { recursive: true });
3609
+ mkdirSync8(pathDirname(output), { recursive: true });
3507
3610
  if (output.endsWith(".yaml") || output.endsWith(".yml")) {
3508
3611
  const { default: yaml3 } = await import("yaml");
3509
3612
  const data = SessionRecorder.readData(sessionName);
@@ -3934,8 +4037,8 @@ async function handleFilter(args, _mode, options) {
3934
4037
  async function handleGeneratePlugin(sessionName, pluginName, outputDir) {
3935
4038
  const { SessionRecorder: SessionRecorder2 } = await import("./session-recorder-RUNQOJ7T.js");
3936
4039
  const { readSiteKnowledge: readSiteKnowledge2, toMarkdown } = await import("./site-knowledge-SYC6VCDB.js");
3937
- const { mkdirSync: mkdirSync7, writeFileSync: writeFileSync8 } = await import("fs");
3938
- const { join: join9 } = await import("path");
4040
+ const { mkdirSync: mkdirSync8, writeFileSync: writeFileSync8 } = await import("fs");
4041
+ const { join: join10 } = await import("path");
3939
4042
  const data = SessionRecorder2.readData(sessionName);
3940
4043
  if (!data) {
3941
4044
  outputError(`No recording found for session "${sessionName}". Run \`xbrowser record stop --session ${sessionName}\` first.`);
@@ -3947,14 +4050,14 @@ async function handleGeneratePlugin(sessionName, pluginName, outputDir) {
3947
4050
  } catch {
3948
4051
  }
3949
4052
  const finalPluginName = pluginName || domain.split(".")[0] || "my-site";
3950
- const finalOutputDir = outputDir || join9(process.cwd(), ".xcli", "plugins", finalPluginName);
4053
+ const finalOutputDir = outputDir || join10(process.cwd(), ".xcli", "plugins", finalPluginName);
3951
4054
  const knowledge = readSiteKnowledge2(domain);
3952
4055
  const knowledgeMd = knowledge ? toMarkdown(knowledge) : "";
3953
4056
  const pluginCode = generatePluginCode(finalPluginName, domain, data, knowledgeMd);
3954
- mkdirSync7(join9(finalOutputDir), { recursive: true });
3955
- writeFileSync8(join9(finalOutputDir, "index.ts"), pluginCode, "utf-8");
4057
+ mkdirSync8(join10(finalOutputDir), { recursive: true });
4058
+ writeFileSync8(join10(finalOutputDir, "index.ts"), pluginCode, "utf-8");
3956
4059
  if (knowledgeMd) {
3957
- writeFileSync8(join9(finalOutputDir, "SITE_KNOWLEDGE.md"), knowledgeMd, "utf-8");
4060
+ writeFileSync8(join10(finalOutputDir, "SITE_KNOWLEDGE.md"), knowledgeMd, "utf-8");
3958
4061
  }
3959
4062
  process.stdout.write("\n");
3960
4063
  process.stdout.write("=== Plugin Generated ===\n");
@@ -4133,73 +4236,1903 @@ ${commands.join("\n\n")}
4133
4236
  });
4134
4237
  `;
4135
4238
  }
4136
-
4137
- // src/stdin.ts
4138
- import { readStdin, readCommandFile, splitFileLine } from "@dyyz1993/xcli-core";
4139
-
4140
- // src/cli/run-routes.ts
4141
- async function handleRun(filePath, options) {
4142
- let commands;
4239
+
4240
+ // src/site-memory/cli.ts
4241
+ import { open as openFile, readFile, stat } from "fs/promises";
4242
+ import { isAbsolute as isAbsolute2, resolve as resolve8 } from "path";
4243
+
4244
+ // src/site-memory/runner.ts
4245
+ import { createHash, randomUUID } from "crypto";
4246
+ var SiteMemorySpecError = class extends Error {
4247
+ constructor(message) {
4248
+ super(message);
4249
+ this.name = "SiteMemorySpecError";
4250
+ }
4251
+ };
4252
+ async function runWorkflow(raw, store, openPage, options) {
4253
+ const parsed = parseSpec(raw);
4254
+ const definitionKey = computeDefinitionKey(parsed);
4255
+ const hints = options?.cold ? /* @__PURE__ */ new Map() : readHints(store, parsed, definitionKey);
4256
+ const attempts = [];
4257
+ const run = {
4258
+ runId: randomUUID(),
4259
+ origin: parsed.origin,
4260
+ flow: parsed.flow,
4261
+ definitionKey,
4262
+ startedAt: Date.now(),
4263
+ endedAt: 0,
4264
+ outcome: "failed",
4265
+ verified: false,
4266
+ attempts
4267
+ };
4268
+ let handle;
4269
+ let allPassed = false;
4270
+ try {
4271
+ let page;
4272
+ try {
4273
+ handle = await openPage();
4274
+ page = handle.page;
4275
+ } catch {
4276
+ recordLaunchFailure(parsed, attempts);
4277
+ }
4278
+ if (page) {
4279
+ allPassed = await executeSteps(parsed, page, hints, attempts);
4280
+ }
4281
+ } finally {
4282
+ if (handle) {
4283
+ try {
4284
+ await handle.close();
4285
+ } catch (closeError) {
4286
+ void closeError;
4287
+ }
4288
+ }
4289
+ }
4290
+ run.endedAt = Date.now();
4291
+ run.outcome = allPassed ? "passed" : "failed";
4292
+ run.verified = allPassed;
4293
+ store.putRun(run);
4294
+ return run;
4295
+ }
4296
+ var LIMITS = {
4297
+ SPEC_VERSION: 1,
4298
+ MAX_STEPS: 32,
4299
+ MAX_SELECTORS_PER_CLICK: 8,
4300
+ MAX_ID_LEN: 64,
4301
+ MAX_SELECTOR_LEN: 200,
4302
+ MAX_PATH_LEN: 512,
4303
+ MAX_EQUALS_LEN: 256,
4304
+ GOTO_TIMEOUT_MS: 15e3,
4305
+ PROBE_TIMEOUT_MS: 3e3,
4306
+ CLICK_TIMEOUT_MS: 5e3,
4307
+ TEXT_WAIT_MS: 8e3,
4308
+ POLL_INTERVAL_MS: 100
4309
+ };
4310
+ var ID_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
4311
+ var ORDINAL_ID_PATTERN = /^(?:step|s|op|id)-?\d+$/;
4312
+ var CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
4313
+ var SELECTOR_CHARSET = /^[A-Za-z0-9#._[\]()="':~,+*>^$| -]+$/;
4314
+ var NON_CSS_PREFIX = /^(?:xpath|text|role|css)=/i;
4315
+ function specError(message) {
4316
+ throw new SiteMemorySpecError("site-memory: " + message);
4317
+ }
4318
+ function isPlainObject(value) {
4319
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4320
+ }
4321
+ function parseStepId(raw, index) {
4322
+ if (typeof raw !== "string" || raw.length === 0 || raw.length > LIMITS.MAX_ID_LEN || !ID_PATTERN.test(raw) || ORDINAL_ID_PATTERN.test(raw)) {
4323
+ specError(`steps[${index}].id must be a unique semantic kebab-case id`);
4324
+ }
4325
+ return raw;
4326
+ }
4327
+ function isPlausibleCssSelector(selector) {
4328
+ if (selector.length === 0 || selector.length > LIMITS.MAX_SELECTOR_LEN || !SELECTOR_CHARSET.test(selector) || selector.includes(">>") || NON_CSS_PREFIX.test(selector)) {
4329
+ return false;
4330
+ }
4331
+ let brackets = 0;
4332
+ let parens = 0;
4333
+ let quote = null;
4334
+ for (const ch of selector) {
4335
+ if (quote) {
4336
+ if (ch === quote) quote = null;
4337
+ continue;
4338
+ }
4339
+ if (ch === '"' || ch === "'") {
4340
+ quote = ch;
4341
+ continue;
4342
+ }
4343
+ if (ch === "[") brackets++;
4344
+ else if (ch === "]") brackets--;
4345
+ else if (ch === "(") parens++;
4346
+ else if (ch === ")") parens--;
4347
+ if (brackets < 0 || parens < 0) return false;
4348
+ }
4349
+ return brackets === 0 && parens === 0 && quote === null;
4350
+ }
4351
+ function parseOrigin(raw) {
4352
+ if (typeof raw !== "string" || raw.length === 0 || raw.length > 2048) {
4353
+ specError("origin must be an http(s) URL string");
4354
+ }
4355
+ let parsed;
4356
+ try {
4357
+ parsed = new URL(raw);
4358
+ } catch {
4359
+ specError("origin must be a valid http(s) URL");
4360
+ }
4361
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
4362
+ specError("origin scheme must be http or https");
4363
+ }
4364
+ if (parsed.username !== "" || parsed.password !== "") {
4365
+ specError("origin must not contain credentials");
4366
+ }
4367
+ if (parsed.pathname !== "" && parsed.pathname !== "/" || parsed.search !== "" || parsed.hash !== "") {
4368
+ specError("origin must be a bare origin without path, query or fragment");
4369
+ }
4370
+ const origin = parsed.origin;
4371
+ if (!origin || origin === "null") {
4372
+ specError("origin must be an http(s) origin");
4373
+ }
4374
+ return origin;
4375
+ }
4376
+ function hasExactKeys(value, keys) {
4377
+ const actual = Object.keys(value);
4378
+ if (actual.length !== keys.length) return false;
4379
+ return keys.every((k) => k in value);
4380
+ }
4381
+ function parseSpec(raw) {
4382
+ if (!isPlainObject(raw)) {
4383
+ specError("spec must be a plain JSON object");
4384
+ }
4385
+ if (!hasExactKeys(raw, ["origin", "flow", "steps"])) {
4386
+ specError("spec must have exactly the keys: origin, flow, steps");
4387
+ }
4388
+ const origin = parseOrigin(raw.origin);
4389
+ const flow = raw.flow;
4390
+ if (typeof flow !== "string" || flow.length === 0 || flow.length > LIMITS.MAX_ID_LEN || !ID_PATTERN.test(flow)) {
4391
+ specError("flow must be 1-64 chars, lowercase kebab-case, starting with a letter");
4392
+ }
4393
+ const rawSteps = raw.steps;
4394
+ if (!Array.isArray(rawSteps) || rawSteps.length === 0) {
4395
+ specError("steps must be a non-empty array");
4396
+ }
4397
+ if (rawSteps.length > LIMITS.MAX_STEPS) {
4398
+ specError(`steps must not exceed ${LIMITS.MAX_STEPS} entries`);
4399
+ }
4400
+ const seenIds = /* @__PURE__ */ new Set();
4401
+ const steps = rawSteps.map((value, index) => {
4402
+ if (!isPlainObject(value)) {
4403
+ specError(`steps[${index}] must be a plain object`);
4404
+ }
4405
+ if (typeof value.op !== "string") {
4406
+ specError(`steps[${index}].op must be a string`);
4407
+ }
4408
+ const id = parseStepId(value.id, index);
4409
+ if (seenIds.has(id)) {
4410
+ specError(`steps[${index}].id must be unique across steps`);
4411
+ }
4412
+ seenIds.add(id);
4413
+ if (value.op === "goto") {
4414
+ if (!hasExactKeys(value, ["id", "op", "path"])) {
4415
+ specError(`steps[${index}] (goto) must have exactly id, op, path`);
4416
+ }
4417
+ return parseGotoStep(value, id, index, origin);
4418
+ }
4419
+ if (value.op === "click") {
4420
+ if (!hasExactKeys(value, ["id", "op", "selectors"])) {
4421
+ specError(`steps[${index}] (click) must have exactly id, op, selectors`);
4422
+ }
4423
+ return parseClickStep(value, id, index);
4424
+ }
4425
+ if (value.op === "expect-text") {
4426
+ if (!hasExactKeys(value, ["id", "op", "selector", "equals"])) {
4427
+ specError(
4428
+ `steps[${index}] (expect-text) must have exactly id, op, selector, equals`
4429
+ );
4430
+ }
4431
+ return parseExpectTextStep(value, id, index);
4432
+ }
4433
+ specError(`steps[${index}].op must be one of goto, click, expect-text`);
4434
+ });
4435
+ if (steps[0].op !== "goto") {
4436
+ specError("the first step must be a goto (anchors the origin)");
4437
+ }
4438
+ if (steps[steps.length - 1].op !== "expect-text") {
4439
+ specError("the last step must be an expect-text (verification proof)");
4440
+ }
4441
+ return { origin, flow, steps };
4442
+ }
4443
+ function parseGotoStep(value, id, index, origin) {
4444
+ const path4 = value.path;
4445
+ if (typeof path4 !== "string" || path4.length === 0 || path4.length > LIMITS.MAX_PATH_LEN || !path4.startsWith("/") || path4.startsWith("//") || CONTROL_CHARS.test(path4)) {
4446
+ specError(`steps[${index}].path must be a root-relative same-origin path`);
4447
+ }
4448
+ try {
4449
+ const resolved = new URL(path4, origin);
4450
+ if (resolved.origin !== origin) {
4451
+ specError(`steps[${index}].path resolves to a different origin`);
4452
+ }
4453
+ } catch {
4454
+ specError(`steps[${index}].path is not a resolvable path`);
4455
+ }
4456
+ return { id, op: "goto", path: path4 };
4457
+ }
4458
+ function parseClickStep(value, id, index) {
4459
+ const selectors = value.selectors;
4460
+ if (!Array.isArray(selectors) || selectors.length === 0 || selectors.length > LIMITS.MAX_SELECTORS_PER_CLICK) {
4461
+ specError(
4462
+ `steps[${index}].selectors must contain 1..${LIMITS.MAX_SELECTORS_PER_CLICK} CSS selectors`
4463
+ );
4464
+ }
4465
+ const seen = /* @__PURE__ */ new Set();
4466
+ for (const selector of selectors) {
4467
+ if (typeof selector !== "string" || !isPlausibleCssSelector(selector)) {
4468
+ specError(`steps[${index}].selectors must be plain CSS selector strings`);
4469
+ }
4470
+ if (seen.has(selector)) {
4471
+ specError(`steps[${index}].selectors must not contain duplicates`);
4472
+ }
4473
+ seen.add(selector);
4474
+ }
4475
+ return { id, op: "click", selectors };
4476
+ }
4477
+ function parseExpectTextStep(value, id, index) {
4478
+ const selector = value.selector;
4479
+ if (typeof selector !== "string" || !isPlausibleCssSelector(selector)) {
4480
+ specError(`steps[${index}].selector must be a plain CSS selector string`);
4481
+ }
4482
+ const equals = value.equals;
4483
+ if (typeof equals !== "string" || equals.trim().length === 0 || equals.length > LIMITS.MAX_EQUALS_LEN) {
4484
+ specError(`steps[${index}].equals must be 1..${LIMITS.MAX_EQUALS_LEN} chars of text`);
4485
+ }
4486
+ return { id, op: "expect-text", selector, equals };
4487
+ }
4488
+ function computeDefinitionKey(parsed) {
4489
+ const normalized = {
4490
+ v: LIMITS.SPEC_VERSION,
4491
+ origin: parsed.origin,
4492
+ flow: parsed.flow,
4493
+ steps: parsed.steps.map((step) => {
4494
+ if (step.op === "goto") {
4495
+ return { id: step.id, op: step.op, path: step.path };
4496
+ }
4497
+ if (step.op === "click") {
4498
+ return { id: step.id, op: step.op, selectors: [...step.selectors] };
4499
+ }
4500
+ return { id: step.id, op: step.op, selector: step.selector, equals: step.equals };
4501
+ })
4502
+ };
4503
+ return createHash("sha256").update(`site-memory/spec/v${LIMITS.SPEC_VERSION}
4504
+ `).update(JSON.stringify(normalized)).digest("hex");
4505
+ }
4506
+ function readHints(store, parsed, definitionKey) {
4507
+ try {
4508
+ const brief = store.getBrief(parsed.origin, parsed.flow, definitionKey);
4509
+ const hints = /* @__PURE__ */ new Map();
4510
+ if (!brief || !Array.isArray(brief.hints)) {
4511
+ return hints;
4512
+ }
4513
+ for (const hint of brief.hints) {
4514
+ if (hint && typeof hint.stepId === "string" && Number.isInteger(hint.candidate) && hint.candidate >= 0) {
4515
+ hints.set(hint.stepId, hint);
4516
+ }
4517
+ }
4518
+ return hints;
4519
+ } catch {
4520
+ return /* @__PURE__ */ new Map();
4521
+ }
4522
+ }
4523
+ function probeOrder(step, hint) {
4524
+ const order = step.selectors.map((_, i) => i);
4525
+ if (hint && hint.candidate > 0 && hint.candidate < step.selectors.length) {
4526
+ return [hint.candidate, ...order.filter((i) => i !== hint.candidate)];
4527
+ }
4528
+ return order;
4529
+ }
4530
+ function sleep(ms, page) {
4531
+ if (page.waitForTimeout) return page.waitForTimeout(ms);
4532
+ return new Promise((resolve10) => setTimeout(resolve10, ms));
4533
+ }
4534
+ function originGuard(page, origin) {
4535
+ let rawUrl;
4536
+ try {
4537
+ rawUrl = page.url();
4538
+ } catch {
4539
+ return "browser-error";
4540
+ }
4541
+ try {
4542
+ return new URL(rawUrl).origin === origin ? null : "origin-changed";
4543
+ } catch {
4544
+ return "origin-changed";
4545
+ }
4546
+ }
4547
+ function recordLaunchFailure(parsed, attempts) {
4548
+ const first = parsed.steps[0];
4549
+ attempts.push({
4550
+ stepId: first.id,
4551
+ operation: first.op,
4552
+ attempt: 1,
4553
+ startedAt: Date.now(),
4554
+ durationMs: 0,
4555
+ outcome: "failed",
4556
+ errorCode: "browser-error"
4557
+ });
4558
+ }
4559
+ async function executeSteps(parsed, page, hints, attempts) {
4560
+ const counters = /* @__PURE__ */ new Map();
4561
+ const nextAttempt = (stepId) => {
4562
+ const n = (counters.get(stepId) ?? 0) + 1;
4563
+ counters.set(stepId, n);
4564
+ return n;
4565
+ };
4566
+ for (const step of parsed.steps) {
4567
+ if (step.op === "goto") {
4568
+ const passed2 = await runGotoStep(parsed.origin, step, page, nextAttempt, attempts);
4569
+ if (!passed2) return false;
4570
+ continue;
4571
+ }
4572
+ const guard = originGuard(page, parsed.origin);
4573
+ if (guard) {
4574
+ attempts.push({
4575
+ stepId: step.id,
4576
+ operation: step.op,
4577
+ attempt: nextAttempt(step.id),
4578
+ startedAt: Date.now(),
4579
+ durationMs: 0,
4580
+ outcome: "failed",
4581
+ errorCode: guard
4582
+ });
4583
+ return false;
4584
+ }
4585
+ const passed = step.op === "click" ? await runClickStep(step, page, hints.get(step.id), nextAttempt, attempts) : await runExpectTextStep(step, page, nextAttempt, attempts);
4586
+ if (!passed) return false;
4587
+ }
4588
+ return true;
4589
+ }
4590
+ async function runGotoStep(origin, step, page, nextAttempt, attempts) {
4591
+ const startedAt = Date.now();
4592
+ let errorCode;
4593
+ try {
4594
+ await page.goto(origin + step.path, { timeout: LIMITS.GOTO_TIMEOUT_MS });
4595
+ errorCode = originGuard(page, origin) ?? void 0;
4596
+ } catch {
4597
+ errorCode = "navigation-failed";
4598
+ }
4599
+ attempts.push({
4600
+ stepId: step.id,
4601
+ operation: "goto",
4602
+ attempt: nextAttempt(step.id),
4603
+ startedAt,
4604
+ durationMs: Date.now() - startedAt,
4605
+ outcome: errorCode ? "failed" : "passed",
4606
+ errorCode
4607
+ });
4608
+ return !errorCode;
4609
+ }
4610
+ async function runClickStep(step, page, hint, nextAttempt, attempts) {
4611
+ for (const candidate of probeOrder(step, hint)) {
4612
+ const startedAt = Date.now();
4613
+ const source = hint && candidate === hint.candidate ? "memory" : "definition";
4614
+ let locator;
4615
+ try {
4616
+ locator = page.locator(step.selectors[candidate]);
4617
+ } catch {
4618
+ attempts.push({
4619
+ stepId: step.id,
4620
+ operation: "click",
4621
+ attempt: nextAttempt(step.id),
4622
+ startedAt,
4623
+ durationMs: Date.now() - startedAt,
4624
+ outcome: "failed",
4625
+ errorCode: "browser-error",
4626
+ candidate,
4627
+ source
4628
+ });
4629
+ return false;
4630
+ }
4631
+ try {
4632
+ await locator.waitFor({ state: "visible", timeout: LIMITS.PROBE_TIMEOUT_MS });
4633
+ } catch {
4634
+ attempts.push({
4635
+ stepId: step.id,
4636
+ operation: "click",
4637
+ attempt: nextAttempt(step.id),
4638
+ startedAt,
4639
+ durationMs: Date.now() - startedAt,
4640
+ outcome: "failed",
4641
+ errorCode: "selector-not-ready",
4642
+ candidate,
4643
+ source
4644
+ });
4645
+ continue;
4646
+ }
4647
+ try {
4648
+ await locator.click({ timeout: LIMITS.CLICK_TIMEOUT_MS });
4649
+ } catch {
4650
+ attempts.push({
4651
+ stepId: step.id,
4652
+ operation: "click",
4653
+ attempt: nextAttempt(step.id),
4654
+ startedAt,
4655
+ durationMs: Date.now() - startedAt,
4656
+ outcome: "failed",
4657
+ errorCode: "click-failed",
4658
+ candidate,
4659
+ source
4660
+ });
4661
+ return false;
4662
+ }
4663
+ attempts.push({
4664
+ stepId: step.id,
4665
+ operation: "click",
4666
+ attempt: nextAttempt(step.id),
4667
+ startedAt,
4668
+ durationMs: Date.now() - startedAt,
4669
+ outcome: "passed",
4670
+ candidate,
4671
+ source
4672
+ });
4673
+ return true;
4674
+ }
4675
+ return false;
4676
+ }
4677
+ async function runExpectTextStep(step, page, nextAttempt, attempts) {
4678
+ const startedAt = Date.now();
4679
+ const fail3 = (errorCode) => {
4680
+ attempts.push({
4681
+ stepId: step.id,
4682
+ operation: "expect-text",
4683
+ attempt: nextAttempt(step.id),
4684
+ startedAt,
4685
+ durationMs: Date.now() - startedAt,
4686
+ outcome: "failed",
4687
+ errorCode
4688
+ });
4689
+ return false;
4690
+ };
4691
+ let locator;
4692
+ try {
4693
+ locator = page.locator(step.selector);
4694
+ } catch {
4695
+ return fail3("browser-error");
4696
+ }
4697
+ try {
4698
+ await locator.waitFor({ state: "visible", timeout: LIMITS.TEXT_WAIT_MS });
4699
+ } catch {
4700
+ return fail3("selector-not-ready");
4701
+ }
4702
+ const expected = step.equals.trim();
4703
+ const deadline = Date.now() + LIMITS.TEXT_WAIT_MS;
4704
+ for (; ; ) {
4705
+ let text;
4706
+ try {
4707
+ text = await locator.textContent();
4708
+ } catch {
4709
+ return fail3("browser-error");
4710
+ }
4711
+ if ((text ?? "").trim() === expected) {
4712
+ attempts.push({
4713
+ stepId: step.id,
4714
+ operation: "expect-text",
4715
+ attempt: nextAttempt(step.id),
4716
+ startedAt,
4717
+ durationMs: Date.now() - startedAt,
4718
+ outcome: "passed"
4719
+ });
4720
+ return true;
4721
+ }
4722
+ if (Date.now() >= deadline) {
4723
+ return fail3("assertion-failed");
4724
+ }
4725
+ await sleep(LIMITS.POLL_INTERVAL_MS, page);
4726
+ }
4727
+ }
4728
+
4729
+ // src/site-memory/store.ts
4730
+ import { mkdirSync as mkdirSync6, existsSync as existsSync10 } from "fs";
4731
+ import { createRequire } from "module";
4732
+ import { homedir as homedir3 } from "os";
4733
+ import { dirname as dirname4, join as join7, resolve as resolve7 } from "path";
4734
+ var databaseSyncCtor;
4735
+ function loadDatabaseSync() {
4736
+ if (!databaseSyncCtor) {
4737
+ const nodeRequire = createRequire(import.meta.url);
4738
+ const mod = nodeRequire("node:sqlite");
4739
+ databaseSyncCtor = mod.DatabaseSync;
4740
+ }
4741
+ return databaseSyncCtor;
4742
+ }
4743
+ var SCHEMA_VERSION = 1;
4744
+ var BUSY_TIMEOUT_MS = 5e3;
4745
+ var BRIEF_RECENCY_MS = 30 * 24 * 60 * 60 * 1e3;
4746
+ var MAX_RUNS_PER_SITE_FLOW = 200;
4747
+ var DEFAULT_RUN_LIMIT = 50;
4748
+ var MAX_RUN_LIMIT = 1e3;
4749
+ var MAX_ATTEMPTS_PER_RUN = 1e3;
4750
+ var MAX_RUN_ID_LENGTH = 128;
4751
+ var MAX_KEY_LENGTH = 512;
4752
+ var MAX_STEP_ID_LENGTH = 256;
4753
+ var OPERATIONS = ["goto", "click", "expect-text"];
4754
+ var OUTCOMES = ["passed", "failed"];
4755
+ var ERROR_CODES = [
4756
+ "browser-error",
4757
+ "navigation-failed",
4758
+ "origin-changed",
4759
+ "selector-not-ready",
4760
+ "click-failed",
4761
+ "assertion-failed"
4762
+ ];
4763
+ var SOURCES = ["definition", "memory"];
4764
+ var SCHEMA_SQL = `
4765
+ CREATE TABLE IF NOT EXISTS runs (
4766
+ run_id TEXT PRIMARY KEY,
4767
+ origin TEXT NOT NULL,
4768
+ flow TEXT NOT NULL,
4769
+ definition_key TEXT NOT NULL,
4770
+ started_at REAL NOT NULL,
4771
+ ended_at REAL NOT NULL,
4772
+ outcome TEXT NOT NULL,
4773
+ verified INTEGER NOT NULL
4774
+ );
4775
+ CREATE INDEX IF NOT EXISTS idx_runs_site_time ON runs (origin, flow, started_at DESC);
4776
+ CREATE INDEX IF NOT EXISTS idx_runs_definition ON runs (origin, flow, definition_key, ended_at DESC);
4777
+
4778
+ CREATE TABLE IF NOT EXISTS run_attempts (
4779
+ attempt_row_id INTEGER PRIMARY KEY AUTOINCREMENT,
4780
+ run_id TEXT NOT NULL REFERENCES runs (run_id) ON DELETE CASCADE,
4781
+ seq INTEGER NOT NULL,
4782
+ step_id TEXT NOT NULL,
4783
+ operation TEXT NOT NULL,
4784
+ attempt_no INTEGER NOT NULL,
4785
+ started_at REAL NOT NULL,
4786
+ duration_ms REAL NOT NULL,
4787
+ outcome TEXT NOT NULL,
4788
+ error_code TEXT,
4789
+ candidate INTEGER,
4790
+ source TEXT
4791
+ );
4792
+ CREATE INDEX IF NOT EXISTS idx_attempts_run ON run_attempts (run_id, seq);
4793
+ `;
4794
+ var SQL_INSERT_RUN = `
4795
+ INSERT INTO runs (run_id, origin, flow, definition_key, started_at, ended_at, outcome, verified)
4796
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
4797
+ ON CONFLICT (run_id) DO NOTHING
4798
+ `;
4799
+ var SQL_INSERT_ATTEMPT = `
4800
+ INSERT INTO run_attempts
4801
+ (run_id, seq, step_id, operation, attempt_no, started_at, duration_ms, outcome, error_code, candidate, source)
4802
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
4803
+ `;
4804
+ var SQL_PRUNE_RUNS = `
4805
+ DELETE FROM runs
4806
+ WHERE origin = ? AND flow = ?
4807
+ AND run_id NOT IN (
4808
+ SELECT run_id FROM runs WHERE origin = ? AND flow = ?
4809
+ ORDER BY started_at DESC, rowid DESC LIMIT ?
4810
+ )
4811
+ `;
4812
+ var SQL_GET_RUN = `
4813
+ SELECT run_id, origin, flow, definition_key, started_at, ended_at, outcome, verified
4814
+ FROM runs WHERE run_id = ?
4815
+ `;
4816
+ var SQL_GET_ATTEMPTS = `
4817
+ SELECT step_id, operation, attempt_no, started_at, duration_ms, outcome, error_code, candidate, source
4818
+ FROM run_attempts WHERE run_id = ?
4819
+ ORDER BY seq ASC, attempt_row_id ASC
4820
+ `;
4821
+ var SQL_LIST_RUNS_BY_ORIGIN = `
4822
+ SELECT run_id, origin, flow, definition_key, started_at, ended_at, outcome, verified
4823
+ FROM runs WHERE origin = ?
4824
+ ORDER BY started_at DESC, rowid DESC LIMIT ?
4825
+ `;
4826
+ var SQL_LIST_RUNS_BY_ORIGIN_FLOW = `
4827
+ SELECT run_id, origin, flow, definition_key, started_at, ended_at, outcome, verified
4828
+ FROM runs WHERE origin = ? AND flow = ?
4829
+ ORDER BY started_at DESC, rowid DESC LIMIT ?
4830
+ `;
4831
+ var SQL_LIST_SITES = `
4832
+ SELECT origin, flow, COUNT(*) AS runs,
4833
+ SUM(CASE WHEN outcome = 'passed' THEN 1 ELSE 0 END) AS passed,
4834
+ MAX(started_at) AS last_run_at
4835
+ FROM runs
4836
+ GROUP BY origin, flow
4837
+ ORDER BY origin ASC, flow ASC
4838
+ `;
4839
+ var SQL_STATS_ROWS = `
4840
+ SELECT r.run_id AS run_id, a.step_id AS step_id, a.operation AS operation,
4841
+ a.outcome AS outcome, a.error_code AS error_code
4842
+ FROM runs r JOIN run_attempts a ON a.run_id = r.run_id
4843
+ WHERE r.origin = ? AND r.flow = ?
4844
+ ORDER BY r.started_at ASC, r.rowid ASC, a.attempt_row_id ASC
4845
+ `;
4846
+ var SQL_HINT_ROWS = `
4847
+ SELECT a.step_id AS step_id, a.candidate AS candidate, r.ended_at AS ended_at
4848
+ FROM runs r JOIN run_attempts a ON a.run_id = r.run_id
4849
+ WHERE r.origin = ? AND r.flow = ? AND r.definition_key = ?
4850
+ AND r.outcome = 'passed' AND r.verified = 1
4851
+ AND a.outcome = 'passed' AND a.candidate IS NOT NULL
4852
+ ORDER BY r.ended_at DESC, a.attempt_row_id DESC
4853
+ `;
4854
+ var SQL_MAX_FAILED = `
4855
+ SELECT MAX(ended_at) AS max_failed
4856
+ FROM runs
4857
+ WHERE origin = ? AND flow = ? AND definition_key = ? AND outcome = 'failed'
4858
+ `;
4859
+ function isPlainObject2(value) {
4860
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4861
+ }
4862
+ function boundedString(value, maxLength) {
4863
+ if (typeof value !== "string" || value.length === 0 || value.length > maxLength) {
4864
+ return null;
4865
+ }
4866
+ return value;
4867
+ }
4868
+ function finiteNumber(value) {
4869
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
4870
+ }
4871
+ function oneOf(value, allow) {
4872
+ if (typeof value !== "string") return null;
4873
+ return allow.includes(value) ? value : null;
4874
+ }
4875
+ function parseAttempt(raw) {
4876
+ if (!isPlainObject2(raw)) return null;
4877
+ const stepId = boundedString(raw.stepId, MAX_STEP_ID_LENGTH);
4878
+ if (!stepId) return null;
4879
+ const operation = oneOf(raw.operation, OPERATIONS);
4880
+ if (!operation) return null;
4881
+ if (typeof raw.attempt !== "number" || !Number.isInteger(raw.attempt) || raw.attempt < 0) return null;
4882
+ const startedAt = finiteNumber(raw.startedAt);
4883
+ if (startedAt === null) return null;
4884
+ const durationMs = finiteNumber(raw.durationMs);
4885
+ if (durationMs === null || durationMs < 0) return null;
4886
+ const outcome = oneOf(raw.outcome, OUTCOMES);
4887
+ if (!outcome) return null;
4888
+ const attempt = { stepId, operation, attempt: raw.attempt, startedAt, durationMs, outcome };
4889
+ if (raw.errorCode !== void 0 && raw.errorCode !== null) {
4890
+ const errorCode = oneOf(raw.errorCode, ERROR_CODES);
4891
+ if (!errorCode) return null;
4892
+ attempt.errorCode = errorCode;
4893
+ }
4894
+ if (raw.candidate !== void 0 && raw.candidate !== null) {
4895
+ if (typeof raw.candidate !== "number" || !Number.isInteger(raw.candidate) || raw.candidate < 0) return null;
4896
+ attempt.candidate = raw.candidate;
4897
+ }
4898
+ if (raw.source !== void 0 && raw.source !== null) {
4899
+ const source = oneOf(raw.source, SOURCES);
4900
+ if (!source) return null;
4901
+ attempt.source = source;
4902
+ }
4903
+ return attempt;
4904
+ }
4905
+ function parseMemoryRun(input) {
4906
+ if (!isPlainObject2(input)) return null;
4907
+ const runId = boundedString(input.runId, MAX_RUN_ID_LENGTH);
4908
+ if (!runId) return null;
4909
+ const origin = boundedString(input.origin, MAX_KEY_LENGTH);
4910
+ if (!origin) return null;
4911
+ const flow = boundedString(input.flow, MAX_KEY_LENGTH);
4912
+ if (!flow) return null;
4913
+ const definitionKey = boundedString(input.definitionKey, MAX_KEY_LENGTH);
4914
+ if (!definitionKey) return null;
4915
+ const startedAt = finiteNumber(input.startedAt);
4916
+ if (startedAt === null) return null;
4917
+ const endedAt = finiteNumber(input.endedAt);
4918
+ if (endedAt === null || endedAt < startedAt) return null;
4919
+ const outcome = oneOf(input.outcome, OUTCOMES);
4920
+ if (!outcome) return null;
4921
+ if (typeof input.verified !== "boolean") return null;
4922
+ if (!Array.isArray(input.attempts) || input.attempts.length > MAX_ATTEMPTS_PER_RUN) return null;
4923
+ const attempts = [];
4924
+ for (const raw of input.attempts) {
4925
+ const attempt = parseAttempt(raw);
4926
+ if (!attempt) return null;
4927
+ attempts.push(attempt);
4928
+ }
4929
+ return { runId, origin, flow, definitionKey, startedAt, endedAt, outcome, verified: input.verified, attempts };
4930
+ }
4931
+ function toOperation(value) {
4932
+ return value === "goto" || value === "expect-text" ? value : "click";
4933
+ }
4934
+ function rowToRunSummary(row) {
4935
+ return {
4936
+ runId: String(row.run_id),
4937
+ origin: String(row.origin),
4938
+ flow: String(row.flow),
4939
+ definitionKey: String(row.definition_key),
4940
+ startedAt: Number(row.started_at),
4941
+ endedAt: Number(row.ended_at),
4942
+ outcome: row.outcome === "passed" ? "passed" : "failed",
4943
+ verified: Number(row.verified) === 1
4944
+ };
4945
+ }
4946
+ function rowToAttempt(row) {
4947
+ const attempt = {
4948
+ stepId: String(row.step_id),
4949
+ operation: toOperation(row.operation),
4950
+ attempt: Number(row.attempt_no),
4951
+ startedAt: Number(row.started_at),
4952
+ durationMs: Number(row.duration_ms),
4953
+ outcome: row.outcome === "passed" ? "passed" : "failed"
4954
+ };
4955
+ if (typeof row.error_code === "string") attempt.errorCode = row.error_code;
4956
+ if (row.candidate !== null && row.candidate !== void 0) attempt.candidate = Number(row.candidate);
4957
+ if (typeof row.source === "string") attempt.source = row.source;
4958
+ return attempt;
4959
+ }
4960
+ function normalizeLimit(limit) {
4961
+ if (typeof limit !== "number" || !Number.isFinite(limit) || limit < 1) return DEFAULT_RUN_LIMIT;
4962
+ return Math.min(Math.floor(limit), MAX_RUN_LIMIT);
4963
+ }
4964
+ function aggregateStats(rows) {
4965
+ const executions = /* @__PURE__ */ new Map();
4966
+ const steps = /* @__PURE__ */ new Map();
4967
+ let order = 0;
4968
+ for (const row of rows) {
4969
+ const runId = String(row.run_id);
4970
+ const stepId = String(row.step_id);
4971
+ const operation = toOperation(row.operation);
4972
+ let step = steps.get(stepId);
4973
+ if (!step) {
4974
+ step = { stepId, order: order++, operation, executions: 0, attempts: 0, failedAttempts: 0, passedExecutions: 0, errors: /* @__PURE__ */ new Map() };
4975
+ steps.set(stepId, step);
4976
+ }
4977
+ const execKey = `${runId}\0${stepId}`;
4978
+ let exec = executions.get(execKey);
4979
+ if (!exec) {
4980
+ exec = { stepId, hasPassed: false };
4981
+ executions.set(execKey, exec);
4982
+ step.executions += 1;
4983
+ }
4984
+ step.attempts += 1;
4985
+ step.operation = operation;
4986
+ if (row.outcome === "failed") {
4987
+ step.failedAttempts += 1;
4988
+ if (typeof row.error_code === "string") {
4989
+ const code = row.error_code;
4990
+ step.errors.set(code, (step.errors.get(code) ?? 0) + 1);
4991
+ }
4992
+ } else {
4993
+ exec.hasPassed = true;
4994
+ }
4995
+ }
4996
+ for (const exec of executions.values()) {
4997
+ const step = steps.get(exec.stepId);
4998
+ if (exec.hasPassed && step) step.passedExecutions += 1;
4999
+ }
5000
+ return [...steps.values()].sort((a, b) => a.order - b.order).map((step) => ({
5001
+ stepId: step.stepId,
5002
+ operation: step.operation,
5003
+ executions: step.executions,
5004
+ attempts: step.attempts,
5005
+ failedAttempts: step.failedAttempts,
5006
+ passedExecutions: step.passedExecutions,
5007
+ errors: Object.fromEntries(step.errors)
5008
+ }));
5009
+ }
5010
+ var SqliteSiteMemoryStore = class {
5011
+ db;
5012
+ statements = /* @__PURE__ */ new Map();
5013
+ readOnly;
5014
+ closed = false;
5015
+ constructor(db, readOnly) {
5016
+ this.db = db;
5017
+ this.readOnly = readOnly;
5018
+ }
5019
+ stmt(key, sql) {
5020
+ let statement = this.statements.get(key);
5021
+ if (!statement) {
5022
+ statement = this.db.prepare(sql);
5023
+ this.statements.set(key, statement);
5024
+ }
5025
+ return statement;
5026
+ }
5027
+ putRun(run) {
5028
+ if (this.readOnly) return;
5029
+ if (this.closed) {
5030
+ throw sanitizeError("putRun failed: store is closed");
5031
+ }
5032
+ const clean = parseMemoryRun(run);
5033
+ if (!clean) {
5034
+ const runIdHint = isPlainObject2(run) && typeof run.runId === "string" ? ` (runId "${run.runId.slice(0, MAX_RUN_ID_LENGTH)}")` : "";
5035
+ throw sanitizeError(`putRun rejected a run that does not match the sealed MemoryRun shape${runIdHint}`);
5036
+ }
5037
+ try {
5038
+ this.writeRun(clean);
5039
+ } catch (err) {
5040
+ throw sanitizeError("putRun failed to persist run", err);
5041
+ }
5042
+ }
5043
+ writeRun(run) {
5044
+ this.db.exec("BEGIN IMMEDIATE");
5045
+ try {
5046
+ const inserted = this.stmt("insert-run", SQL_INSERT_RUN).run(
5047
+ run.runId,
5048
+ run.origin,
5049
+ run.flow,
5050
+ run.definitionKey,
5051
+ run.startedAt,
5052
+ run.endedAt,
5053
+ run.outcome,
5054
+ run.verified ? 1 : 0
5055
+ );
5056
+ if (Number(inserted.changes) === 1) {
5057
+ const insertAttempt = this.stmt("insert-attempt", SQL_INSERT_ATTEMPT);
5058
+ for (let i = 0; i < run.attempts.length; i++) {
5059
+ const attempt = run.attempts[i];
5060
+ insertAttempt.run(
5061
+ run.runId,
5062
+ i,
5063
+ attempt.stepId,
5064
+ attempt.operation,
5065
+ attempt.attempt,
5066
+ attempt.startedAt,
5067
+ attempt.durationMs,
5068
+ attempt.outcome,
5069
+ attempt.errorCode ?? null,
5070
+ attempt.candidate ?? null,
5071
+ attempt.source ?? null
5072
+ );
5073
+ }
5074
+ this.stmt("prune-runs", SQL_PRUNE_RUNS).run(
5075
+ run.origin,
5076
+ run.flow,
5077
+ run.origin,
5078
+ run.flow,
5079
+ MAX_RUNS_PER_SITE_FLOW
5080
+ );
5081
+ }
5082
+ this.db.exec("COMMIT");
5083
+ } catch (err) {
5084
+ try {
5085
+ this.db.exec("ROLLBACK");
5086
+ } catch {
5087
+ }
5088
+ throw err;
5089
+ }
5090
+ }
5091
+ listSites() {
5092
+ if (this.closed) return [];
5093
+ try {
5094
+ const rows = this.stmt("list-sites", SQL_LIST_SITES).all();
5095
+ return rows.map((row) => {
5096
+ const r = row;
5097
+ return {
5098
+ origin: String(r.origin),
5099
+ flow: String(r.flow),
5100
+ runs: Number(r.runs),
5101
+ passed: Number(r.passed),
5102
+ lastRunAt: Number(r.last_run_at)
5103
+ };
5104
+ });
5105
+ } catch {
5106
+ return [];
5107
+ }
5108
+ }
5109
+ listRuns(origin, flow, limit) {
5110
+ if (this.closed) return [];
5111
+ try {
5112
+ const capped = normalizeLimit(limit);
5113
+ 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);
5114
+ return rows.map((row) => rowToRunSummary(row));
5115
+ } catch {
5116
+ return [];
5117
+ }
5118
+ }
5119
+ getRun(runId) {
5120
+ if (this.closed) return null;
5121
+ try {
5122
+ const row = this.stmt("get-run", SQL_GET_RUN).get(runId);
5123
+ if (!row) return null;
5124
+ const attempts = this.stmt("get-attempts", SQL_GET_ATTEMPTS).all(runId).map(
5125
+ (r) => rowToAttempt(r)
5126
+ );
5127
+ return { ...rowToRunSummary(row), attempts };
5128
+ } catch {
5129
+ return null;
5130
+ }
5131
+ }
5132
+ getStats(origin, flow) {
5133
+ if (this.closed) return [];
5134
+ try {
5135
+ const rows = this.stmt("stats-rows", SQL_STATS_ROWS).all(origin, flow).map(
5136
+ (row) => row
5137
+ );
5138
+ return aggregateStats(rows);
5139
+ } catch {
5140
+ return [];
5141
+ }
5142
+ }
5143
+ getBrief(origin, flow, definitionKey) {
5144
+ if (this.closed) return { origin, flow, hints: [] };
5145
+ try {
5146
+ const now = Date.now();
5147
+ const failedRow = this.stmt("max-failed", SQL_MAX_FAILED).get(origin, flow, definitionKey);
5148
+ const maxFailed = failedRow && failedRow.max_failed !== null && failedRow.max_failed !== void 0 ? Number(failedRow.max_failed) : null;
5149
+ const hintRows = this.stmt("hint-rows", SQL_HINT_ROWS).all(origin, flow, definitionKey).map(
5150
+ (row) => row
5151
+ );
5152
+ const hints = [];
5153
+ const seenSteps = /* @__PURE__ */ new Set();
5154
+ for (const row of hintRows) {
5155
+ const stepId = String(row.step_id);
5156
+ if (seenSteps.has(stepId)) continue;
5157
+ seenSteps.add(stepId);
5158
+ const verifiedAt = Number(row.ended_at);
5159
+ if (verifiedAt < now - BRIEF_RECENCY_MS) continue;
5160
+ if (maxFailed !== null && verifiedAt <= maxFailed) continue;
5161
+ hints.push({ stepId, candidate: Number(row.candidate), verifiedAt });
5162
+ }
5163
+ hints.sort((a, b) => a.stepId < b.stepId ? -1 : a.stepId > b.stepId ? 1 : 0);
5164
+ return { origin, flow, hints };
5165
+ } catch {
5166
+ return { origin, flow, hints: [] };
5167
+ }
5168
+ }
5169
+ close() {
5170
+ if (this.closed) return;
5171
+ this.closed = true;
5172
+ this.statements.clear();
5173
+ try {
5174
+ this.db.close();
5175
+ } catch {
5176
+ }
5177
+ }
5178
+ };
5179
+ function errorMessage(err) {
5180
+ return err instanceof Error ? err.message : String(err);
5181
+ }
5182
+ function sanitizeError(scope, err) {
5183
+ const raw = err === void 0 ? "" : errorMessage(err);
5184
+ const reason = raw.split("\n")[0].trim();
5185
+ return new Error(`site-memory: ${scope}${reason ? `: ${reason}` : ""}`);
5186
+ }
5187
+ function readVersion(db) {
5188
+ const row = db.prepare("PRAGMA user_version").get();
5189
+ return row ? Number(row.user_version) : 0;
5190
+ }
5191
+ function hasRunsTable(db) {
5192
+ return db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'runs'").get() != null;
5193
+ }
5194
+ function initSchema(db) {
5195
+ db.exec(SCHEMA_SQL);
5196
+ db.exec(`PRAGMA user_version = ${SCHEMA_VERSION};`);
5197
+ }
5198
+ function createEmptyVolatileStore(DatabaseSyncCtor) {
5199
+ const db = new DatabaseSyncCtor(":memory:");
5200
+ initSchema(db);
5201
+ return new SqliteSiteMemoryStore(db, true);
5202
+ }
5203
+ function openWritableStore(dbPath) {
5204
+ const DatabaseSyncCtor = loadDatabaseSync();
5205
+ const resolved = resolve7(dbPath);
5206
+ try {
5207
+ mkdirSync6(dirname4(resolved), { recursive: true });
5208
+ } catch (err) {
5209
+ throw sanitizeError(`cannot create directory for site-memory database at ${resolved}`, err);
5210
+ }
5211
+ let db;
5212
+ try {
5213
+ db = new DatabaseSyncCtor(resolved);
5214
+ } catch (err) {
5215
+ throw sanitizeError(`cannot open site-memory database at ${resolved}`, err);
5216
+ }
5217
+ try {
5218
+ db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS};`);
5219
+ db.exec("PRAGMA journal_mode = WAL;");
5220
+ db.exec("PRAGMA synchronous = NORMAL;");
5221
+ db.exec("PRAGMA foreign_keys = ON;");
5222
+ const version2 = readVersion(db);
5223
+ if (version2 === SCHEMA_VERSION) {
5224
+ return new SqliteSiteMemoryStore(db, false);
5225
+ }
5226
+ if (version2 === 0 && !hasRunsTable(db)) {
5227
+ initSchema(db);
5228
+ return new SqliteSiteMemoryStore(db, false);
5229
+ }
5230
+ if (version2 === 0) {
5231
+ throw new Error(`database at ${resolved} has tables but no schema version; refusing to touch it`);
5232
+ }
5233
+ throw new Error(`schema version ${version2} at ${resolved} is not supported (expected ${SCHEMA_VERSION})`);
5234
+ } catch (err) {
5235
+ try {
5236
+ db.close();
5237
+ } catch {
5238
+ }
5239
+ throw sanitizeError("cannot open writable site-memory database", err);
5240
+ }
5241
+ }
5242
+ function openReadonlyStore(dbPath) {
5243
+ const DatabaseSyncCtor = loadDatabaseSync();
5244
+ if (!existsSync10(dbPath)) {
5245
+ return createEmptyVolatileStore(DatabaseSyncCtor);
5246
+ }
5247
+ let db;
5248
+ try {
5249
+ db = new DatabaseSyncCtor(dbPath, { readOnly: true });
5250
+ db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS};`);
5251
+ const version2 = readVersion(db);
5252
+ if (version2 !== SCHEMA_VERSION) {
5253
+ throw new Error(`schema version ${version2} is not supported (expected ${SCHEMA_VERSION})`);
5254
+ }
5255
+ return new SqliteSiteMemoryStore(db, true);
5256
+ } catch (err) {
5257
+ if (db) {
5258
+ try {
5259
+ db.close();
5260
+ } catch {
5261
+ }
5262
+ }
5263
+ throw sanitizeError(`cannot open readonly site-memory database at ${dbPath}`, err);
5264
+ }
5265
+ }
5266
+ function defaultSiteMemoryPath() {
5267
+ return join7(homedir3(), ".xbrowser", "site-memory", "site-memory.sqlite");
5268
+ }
5269
+ function openSiteMemoryStore(dbPath, opts) {
5270
+ return opts?.readonly === true ? openReadonlyStore(dbPath) : openWritableStore(dbPath);
5271
+ }
5272
+
5273
+ // src/site-memory/view.ts
5274
+ var MAX_SITES = 200;
5275
+ var MAX_FLOWS_PER_SITE = 50;
5276
+ var MAX_RUNS_PER_FLOW = 25;
5277
+ var MAX_STATS_STEPS = 200;
5278
+ var MAX_RUN_DETAILS = 400;
5279
+ var MAX_ERROR_CODES_PER_STEP = 6;
5280
+ var MAX_ATTEMPTS_PER_RUN_LOG = 30;
5281
+ function escapeHtml(value) {
5282
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
5283
+ }
5284
+ function esc(value) {
5285
+ return escapeHtml(String(value));
5286
+ }
5287
+ function fmtTime(ms) {
5288
+ return Number.isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : "\u2014";
5289
+ }
5290
+ function fmtDuration(ms) {
5291
+ if (!Number.isFinite(ms) || ms < 0) return "\u2014";
5292
+ if (ms < 1e3) return `${Math.round(ms)}ms`;
5293
+ return `${(ms / 1e3).toFixed(1)}s`;
5294
+ }
5295
+ function fmtRate(numerator, denominator) {
5296
+ if (!Number.isFinite(numerator) || !Number.isFinite(denominator) || denominator <= 0) return "\u2014";
5297
+ return `${(numerator / denominator * 100).toFixed(1)}%`;
5298
+ }
5299
+ function plural(n, word) {
5300
+ return `${n} ${word}${n === 1 ? "" : "s"}`;
5301
+ }
5302
+ function groupFlows(sites) {
5303
+ const bySite = /* @__PURE__ */ new Map();
5304
+ for (const s of sites) {
5305
+ const list = bySite.get(s.origin) ?? [];
5306
+ list.push({
5307
+ origin: s.origin,
5308
+ flow: s.flow,
5309
+ runs: s.runs,
5310
+ passed: s.passed,
5311
+ lastRunAt: s.lastRunAt
5312
+ });
5313
+ bySite.set(s.origin, list);
5314
+ }
5315
+ return bySite;
5316
+ }
5317
+ function renderStatsTable(steps) {
5318
+ const bounded = steps.slice(0, MAX_STATS_STEPS);
5319
+ const truncated = steps.length > bounded.length;
5320
+ const rows = bounded.map((s) => {
5321
+ 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(", ");
5322
+ return [
5323
+ ` <tr>`,
5324
+ ` <td class="step-id">${esc(s.stepId)}</td>`,
5325
+ ` <td>${esc(s.operation)}</td>`,
5326
+ ` <td class="num">${s.executions}</td>`,
5327
+ ` <td class="num">${s.attempts}</td>`,
5328
+ ` <td class="num">${s.failedAttempts}</td>`,
5329
+ ` <td class="num">${fmtRate(s.passedExecutions, s.executions)}</td>`,
5330
+ ` <td class="errors">${errors || "\u2014"}</td>`,
5331
+ ` </tr>`
5332
+ ].join("\n");
5333
+ }).join("\n");
5334
+ const note = truncated ? `
5335
+ <p class="note">Showing ${bounded.length} of ${steps.length} steps (bound).</p>` : "";
5336
+ return [
5337
+ ` <table class="stats">`,
5338
+ ` <thead>`,
5339
+ ` <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>`,
5340
+ ` </thead>`,
5341
+ ` <tbody>`,
5342
+ rows,
5343
+ ` </tbody>`,
5344
+ ` </table>${note}`
5345
+ ].join("\n");
5346
+ }
5347
+ var EMPTY_RUN_DETAIL = { steps: null, attempts: null, failed: null, log: null, logCapped: false };
5348
+ function lookupRunDetail(store, runId, budget) {
5349
+ if (budget.left <= 0) return EMPTY_RUN_DETAIL;
5350
+ budget.left -= 1;
5351
+ const run = store.getRun(runId);
5352
+ if (!run) return EMPTY_RUN_DETAIL;
5353
+ const logCapped = run.attempts.length > MAX_ATTEMPTS_PER_RUN_LOG;
5354
+ return {
5355
+ steps: new Set(run.attempts.map((a) => a.stepId)).size,
5356
+ attempts: run.attempts.length,
5357
+ failed: run.attempts.filter((a) => a.outcome === "failed").length,
5358
+ log: logCapped ? run.attempts.slice(0, MAX_ATTEMPTS_PER_RUN_LOG) : run.attempts,
5359
+ logCapped
5360
+ };
5361
+ }
5362
+ function renderAttemptRow(a) {
5363
+ const errorText = a.errorCode ? ` \xB7 ${esc(a.errorCode)}` : "";
5364
+ const sourceText = a.source === "memory" ? "memory hit" : "definition";
5365
+ return [
5366
+ ` <li class="attempt ${esc(a.outcome)}">`,
5367
+ ` <span class="attempt-step">${esc(a.stepId)}</span>`,
5368
+ ` <span class="attempt-no">#${a.attempt}</span>`,
5369
+ ` <span class="attempt-op">${esc(a.operation)}</span>`,
5370
+ ` <span class="attempt-outcome">${esc(a.outcome)}${errorText}</span>`,
5371
+ ` <span class="attempt-source">${sourceText}</span>`,
5372
+ ` </li>`
5373
+ ].join("\n");
5374
+ }
5375
+ function renderAttemptLog(detail) {
5376
+ if (detail.log === null || detail.attempts === null) return "";
5377
+ const capNote = detail.logCapped ? `
5378
+ <p class="note">Showing first ${detail.log.length} of ${detail.attempts} attempts (bound).</p>` : "";
5379
+ return [
5380
+ ` <details class="run-attempts">`,
5381
+ ` <summary>attempts (${detail.attempts})</summary>`,
5382
+ ` <ul class="attempts">`,
5383
+ ...detail.log.map(renderAttemptRow),
5384
+ ` </ul>${capNote}`,
5385
+ ` </details>`
5386
+ ].join("\n");
5387
+ }
5388
+ function renderTimeline(runs, details) {
5389
+ const items = runs.map((r) => {
5390
+ const detail = details.get(r.runId) ?? EMPTY_RUN_DETAIL;
5391
+ const stepsText = detail.steps === null ? "n/a" : plural(detail.steps, "step");
5392
+ const attemptsText = detail.attempts === null ? "n/a" : plural(detail.attempts, "attempt");
5393
+ const failedText = detail.failed !== null && detail.failed > 0 ? ` <span class="run-failed">${detail.failed} failed</span>` : "";
5394
+ const verifiedText = r.verified ? '<span class="run-verified">verified</span>' : '<span class="run-unverified">unverified</span>';
5395
+ return [
5396
+ ` <li class="run ${r.outcome}">`,
5397
+ ` <div class="run-line">`,
5398
+ ` <span class="run-id">${esc(r.runId)}</span>`,
5399
+ ` <span class="run-when">${fmtTime(r.startedAt)} \u2192 ${fmtTime(r.endedAt)}</span>`,
5400
+ ` <span class="run-duration">${fmtDuration(r.endedAt - r.startedAt)}</span>`,
5401
+ ` <span class="run-steps">${stepsText}</span>`,
5402
+ ` <span class="run-attempts">${attemptsText}</span>${failedText}`,
5403
+ ` ${verifiedText}`,
5404
+ ` </div>`,
5405
+ renderAttemptLog(detail),
5406
+ ` </li>`
5407
+ ].join("\n");
5408
+ }).join("\n");
5409
+ return [` <ol class="timeline">`, items, ` </ol>`].join("\n");
5410
+ }
5411
+ function renderFlow(store, group, budget) {
5412
+ const runs = [...store.listRuns(group.origin, group.flow, MAX_RUNS_PER_FLOW)].sort(
5413
+ (a, b) => b.startedAt - a.startedAt || a.runId.localeCompare(b.runId)
5414
+ );
5415
+ const steps = [...store.getStats(group.origin, group.flow)].sort((a, b) => b.executions - a.executions || a.stepId.localeCompare(b.stepId));
5416
+ const details = /* @__PURE__ */ new Map();
5417
+ for (const r of runs) details.set(r.runId, lookupRunDetail(store, r.runId, budget));
5418
+ const runsNote = group.runs > runs.length ? `
5419
+ <p class="note">Showing latest ${runs.length} of ${group.runs} runs (bound).</p>` : "";
5420
+ return [
5421
+ ` <section class="flow">`,
5422
+ ` <h3>${esc(group.flow)}</h3>`,
5423
+ ` <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>`,
5424
+ ` <h4>Step stats</h4>`,
5425
+ steps.length > 0 ? renderStatsTable(steps) : ` <p class="note">No step stats recorded.</p>`,
5426
+ ` <h4>Recent runs</h4>${runsNote}`,
5427
+ runs.length > 0 ? renderTimeline(runs, details) : ` <p class="note">No runs recorded.</p>`,
5428
+ ` </section>`
5429
+ ].join("\n");
5430
+ }
5431
+ function renderSite(store, origin, flows, budget) {
5432
+ const ordered = [...flows].sort((a, b) => b.lastRunAt - a.lastRunAt || a.flow.localeCompare(b.flow));
5433
+ const bounded = ordered.slice(0, MAX_FLOWS_PER_SITE);
5434
+ const note = ordered.length > bounded.length ? `
5435
+ <p class="note">Showing ${bounded.length} of ${ordered.length} flows for this site (bound).</p>` : "";
5436
+ const body = bounded.map((f) => renderFlow(store, f, budget)).join("\n");
5437
+ return [`<section class="site">`, ` <h2>${esc(origin)}</h2>${note}`, body, `</section>`].join("\n");
5438
+ }
5439
+ var CSS = `:root{color-scheme:light dark}
5440
+ *{box-sizing:border-box}
5441
+ 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}
5442
+ header h1{font-size:1.4rem;margin:0 0 .25rem}
5443
+ .meta,.note,.flow-meta{color:color-mix(in srgb,currentColor 62%,transparent);font-size:.85rem}
5444
+ .meta{margin:0 0 1.5rem}
5445
+ .site{margin:0 0 2.5rem;padding-top:.5rem;border-top:1px solid color-mix(in srgb,currentColor 18%,transparent)}
5446
+ .site h2{font-size:1.1rem;margin:.75rem 0 .25rem;word-break:break-all}
5447
+ .flow{margin:1rem 0 1.75rem;padding:.75rem 1rem;border:1px solid color-mix(in srgb,currentColor 15%,transparent);border-radius:8px}
5448
+ .flow h3{font-size:1rem;margin:0 0 .25rem;word-break:break-all}
5449
+ .flow h4{font-size:.85rem;margin:1rem 0 .4rem;text-transform:uppercase;letter-spacing:.04em}
5450
+ table.stats{border-collapse:collapse;width:100%;font-size:.85rem}
5451
+ table.stats th,table.stats td{text-align:left;padding:.3rem .5rem;border-bottom:1px solid color-mix(in srgb,currentColor 12%,transparent)}
5452
+ table.stats td.num,table.stats th:nth-child(n+3){text-align:right;font-variant-numeric:tabular-nums}
5453
+ table.stats td.step-id,table.stats td.errors{word-break:break-all}
5454
+ ol.timeline{list-style:none;margin:0;padding:0}
5455
+ ol.timeline li{padding:.3rem 0;border-bottom:1px dashed color-mix(in srgb,currentColor 12%,transparent)}
5456
+ .run-line{display:flex;flex-wrap:wrap;gap:.35rem .9rem;align-items:baseline}
5457
+ details.run-attempts{margin:.2rem 0 .1rem;font-size:.8rem}
5458
+ details.run-attempts summary{cursor:pointer;user-select:none;color:color-mix(in srgb,currentColor 55%,transparent)}
5459
+ ul.attempts{list-style:none;margin:.25rem 0 0;padding:0}
5460
+ 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)}
5461
+ .attempt-step,.attempt-no{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;word-break:break-all}
5462
+ li.attempt.failed .attempt-outcome{color:#c0392b}
5463
+ .attempt-source{color:color-mix(in srgb,currentColor 55%,transparent)}
5464
+ li.run.failed .run-id{color:#c0392b}
5465
+ li.run.passed .run-id{color:#1e7e34}
5466
+ .run-id{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;word-break:break-all}
5467
+ .run-failed{color:#c0392b}
5468
+ .run-unverified{color:#b58900}
5469
+ .run-verified{color:#1e7e34}
5470
+ .meta,.note,.flow-meta,.run-when,.run-duration{font-family:inherit}
5471
+ .empty{padding:2rem 0;text-align:center;color:color-mix(in srgb,currentColor 55%,transparent)}
5472
+ footer{margin-top:3rem;font-size:.75rem;color:color-mix(in srgb,currentColor 50%,transparent)}`;
5473
+ function renderSiteMemoryDashboard(store) {
5474
+ const allSites = [...store.listSites()];
5475
+ const totals = allSites.reduce(
5476
+ (acc, s) => {
5477
+ acc.runs += s.runs;
5478
+ acc.passed += s.passed;
5479
+ acc.flows += 1;
5480
+ return acc;
5481
+ },
5482
+ { runs: 0, passed: 0, flows: 0 }
5483
+ );
5484
+ const bySite = groupFlows(allSites);
5485
+ const siteEntries = [...bySite.entries()].map(([origin, flows]) => ({
5486
+ origin,
5487
+ flows,
5488
+ lastRunAt: flows.reduce((m, f) => Math.max(m, f.lastRunAt), 0)
5489
+ })).sort((a, b) => b.lastRunAt - a.lastRunAt || a.origin.localeCompare(b.origin));
5490
+ const boundedSites = siteEntries.slice(0, MAX_SITES);
5491
+ const sitesTruncated = siteEntries.length > boundedSites.length;
5492
+ const budget = { left: MAX_RUN_DETAILS };
5493
+ 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");
5494
+ const sitesNote = sitesTruncated ? `
5495
+ <p class="note">Showing ${boundedSites.length} of ${siteEntries.length} sites (bound).</p>` : "";
5496
+ const generatedAt = (/* @__PURE__ */ new Date()).toISOString();
5497
+ return `<!doctype html>
5498
+ <html lang="en">
5499
+ <head>
5500
+ <meta charset="utf-8">
5501
+ <meta name="viewport" content="width=device-width, initial-scale=1">
5502
+ <title>xbrowser \xB7 site-memory dashboard</title>
5503
+ <style>${CSS}</style>
5504
+ </head>
5505
+ <body>
5506
+ <header>
5507
+ <h1>Site Memory Dashboard</h1>
5508
+ <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>
5509
+ </header>
5510
+ <main>
5511
+ ${body}${sitesNote}
5512
+ </main>
5513
+ <footer>Static snapshot \xB7 self-contained (no external assets, no scripts, no telemetry) \xB7 rendered by xbrowser site-memory</footer>
5514
+ </body>
5515
+ </html>`;
5516
+ }
5517
+
5518
+ // src/site-memory/mcp.ts
5519
+ var MAX_STRING_LEN = 512;
5520
+ var DEFAULT_RUNS_LIMIT = 50;
5521
+ var MAX_RUNS_LIMIT = 200;
5522
+ var MAX_SITE_SUMMARIES = 1e3;
5523
+ var MAX_ATTEMPTS = 1e3;
5524
+ var MAX_STATS_STEPS2 = 500;
5525
+ var SUPPORTED_PROTOCOL_VERSIONS = /* @__PURE__ */ new Set(["2024-11-05", "2025-03-26", "2025-06-18"]);
5526
+ var DEFAULT_PROTOCOL_VERSION = "2025-06-18";
5527
+ var DASHBOARD_URI = "xbrowser-site-memory://dashboard";
5528
+ function readOnlyAnnotations(title) {
5529
+ return { title, readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
5530
+ }
5531
+ var RUN_SUMMARY_ITEM_SCHEMA = {
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
+ },
5543
+ required: ["runId", "origin", "flow", "definitionKey", "startedAt", "endedAt", "outcome", "verified"]
5544
+ };
5545
+ var STEP_STATS_ITEM_SCHEMA = {
5546
+ type: "object",
5547
+ properties: {
5548
+ stepId: { type: "string" },
5549
+ operation: { type: "string", enum: ["goto", "click", "expect-text"] },
5550
+ executions: { type: "number" },
5551
+ attempts: { type: "number" },
5552
+ failedAttempts: { type: "number" },
5553
+ passedExecutions: { type: "number" },
5554
+ errors: { type: "object", additionalProperties: { type: "number" } }
5555
+ },
5556
+ required: ["stepId", "operation", "executions", "attempts", "failedAttempts", "passedExecutions", "errors"]
5557
+ };
5558
+ var TOOLS = [
5559
+ {
5560
+ name: "site_memory_sites",
5561
+ 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.",
5562
+ annotations: readOnlyAnnotations("Site memory: sites"),
5563
+ inputSchema: { type: "object", properties: {} },
5564
+ outputSchema: {
5565
+ type: "object",
5566
+ properties: {
5567
+ sites: {
5568
+ type: "array",
5569
+ items: {
5570
+ type: "object",
5571
+ properties: {
5572
+ origin: { type: "string" },
5573
+ flow: { type: "string" },
5574
+ runs: { type: "number" },
5575
+ passed: { type: "number" },
5576
+ lastRunAt: { type: "number" }
5577
+ },
5578
+ required: ["origin", "flow", "runs", "passed", "lastRunAt"]
5579
+ }
5580
+ },
5581
+ truncated: { type: "boolean" }
5582
+ },
5583
+ required: ["sites"]
5584
+ }
5585
+ },
5586
+ {
5587
+ name: "site_memory_runs",
5588
+ 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).`,
5589
+ annotations: readOnlyAnnotations("Site memory: runs"),
5590
+ inputSchema: {
5591
+ type: "object",
5592
+ properties: {
5593
+ origin: { type: "string", description: "Site origin, e.g. https://example.com" },
5594
+ flow: { type: "string", description: "Optional flow name filter" },
5595
+ limit: { type: "number", description: `Max runs to return (1..${MAX_RUNS_LIMIT}, default ${DEFAULT_RUNS_LIMIT})` }
5596
+ },
5597
+ required: ["origin"]
5598
+ },
5599
+ outputSchema: {
5600
+ type: "object",
5601
+ properties: {
5602
+ origin: { type: "string" },
5603
+ flow: { type: ["string", "null"] },
5604
+ limit: { type: "number" },
5605
+ count: { type: "number" },
5606
+ runs: { type: "array", items: RUN_SUMMARY_ITEM_SCHEMA }
5607
+ },
5608
+ required: ["origin", "flow", "limit", "count", "runs"]
5609
+ }
5610
+ },
5611
+ {
5612
+ name: "site_memory_run",
5613
+ description: `Get a single run (summary + step attempts) by runId. Read-only. Attempts payload bounded to ${MAX_ATTEMPTS}.`,
5614
+ annotations: readOnlyAnnotations("Site memory: run detail"),
5615
+ inputSchema: {
5616
+ type: "object",
5617
+ properties: {
5618
+ runId: { type: "string", description: "Run identifier" }
5619
+ },
5620
+ required: ["runId"]
5621
+ },
5622
+ outputSchema: {
5623
+ type: "object",
5624
+ properties: {
5625
+ run: {
5626
+ type: "object",
5627
+ properties: {
5628
+ runId: { type: "string" },
5629
+ origin: { type: "string" },
5630
+ flow: { type: "string" },
5631
+ definitionKey: { type: "string" },
5632
+ startedAt: { type: "number" },
5633
+ endedAt: { type: "number" },
5634
+ outcome: { type: "string", enum: ["passed", "failed"] },
5635
+ verified: { type: "boolean" },
5636
+ attempts: { type: "array" },
5637
+ attemptsTruncated: { type: "boolean" },
5638
+ totalAttempts: { type: "number" }
5639
+ },
5640
+ required: ["runId", "origin", "flow", "definitionKey", "startedAt", "endedAt", "outcome", "verified", "attempts"]
5641
+ }
5642
+ },
5643
+ required: ["run"]
5644
+ }
5645
+ },
5646
+ {
5647
+ name: "site_memory_stats",
5648
+ 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.`,
5649
+ annotations: readOnlyAnnotations("Site memory: step stats"),
5650
+ inputSchema: {
5651
+ type: "object",
5652
+ properties: {
5653
+ origin: { type: "string", description: "Site origin, e.g. https://example.com" },
5654
+ flow: { type: "string", description: "Flow name" }
5655
+ },
5656
+ required: ["origin", "flow"]
5657
+ },
5658
+ outputSchema: {
5659
+ type: "object",
5660
+ properties: {
5661
+ steps: { type: "array", items: STEP_STATS_ITEM_SCHEMA },
5662
+ truncated: { type: "boolean" }
5663
+ },
5664
+ required: ["steps"]
5665
+ }
5666
+ }
5667
+ ];
5668
+ function requireString(args, key) {
5669
+ const raw = args[key];
5670
+ if (typeof raw !== "string") throw new Error(`parameter "${key}" must be a string`);
5671
+ const value = raw.trim();
5672
+ if (value.length === 0) throw new Error(`parameter "${key}" must not be empty`);
5673
+ if (value.length > MAX_STRING_LEN) throw new Error(`parameter "${key}" exceeds ${MAX_STRING_LEN} characters`);
5674
+ return value;
5675
+ }
5676
+ function optionalString(args, key) {
5677
+ if (args[key] === void 0) return void 0;
5678
+ return requireString(args, key);
5679
+ }
5680
+ function resolveLimit(raw) {
5681
+ if (raw === void 0) return DEFAULT_RUNS_LIMIT;
5682
+ if (typeof raw !== "number" || !Number.isInteger(raw)) throw new Error('parameter "limit" must be an integer');
5683
+ if (raw < 1) throw new Error('parameter "limit" must be >= 1');
5684
+ return Math.min(raw, MAX_RUNS_LIMIT);
5685
+ }
5686
+ function structured(payload) {
5687
+ return {
5688
+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
5689
+ structuredContent: payload
5690
+ };
5691
+ }
5692
+ async function runSiteMemoryTool(store, name, args) {
5693
+ switch (name) {
5694
+ case "site_memory_sites": {
5695
+ const all = [...store.listSites()].sort(
5696
+ (a, b) => a.origin.localeCompare(b.origin) || a.flow.localeCompare(b.flow)
5697
+ );
5698
+ const truncated = all.length > MAX_SITE_SUMMARIES;
5699
+ const sites = truncated ? all.slice(0, MAX_SITE_SUMMARIES) : all;
5700
+ return structured({ sites, truncated });
5701
+ }
5702
+ case "site_memory_runs": {
5703
+ const origin = requireString(args, "origin");
5704
+ const flow = optionalString(args, "flow");
5705
+ const limit = resolveLimit(args.limit);
5706
+ const runs = store.listRuns(origin, flow, limit);
5707
+ return structured({ origin, flow: flow ?? null, limit, count: runs.length, runs });
5708
+ }
5709
+ case "site_memory_run": {
5710
+ const runId = requireString(args, "runId");
5711
+ const run = store.getRun(runId);
5712
+ if (!run) throw new Error(`run not found: ${runId}`);
5713
+ const { attempts, ...summary } = run;
5714
+ const truncated = attempts.length > MAX_ATTEMPTS;
5715
+ return structured({
5716
+ run: {
5717
+ ...summary,
5718
+ attempts: truncated ? attempts.slice(0, MAX_ATTEMPTS) : attempts,
5719
+ ...truncated ? { attemptsTruncated: true, totalAttempts: attempts.length } : {}
5720
+ }
5721
+ });
5722
+ }
5723
+ case "site_memory_stats": {
5724
+ const origin = requireString(args, "origin");
5725
+ const flow = requireString(args, "flow");
5726
+ const steps = store.getStats(origin, flow);
5727
+ const truncated = steps.length > MAX_STATS_STEPS2;
5728
+ return structured({
5729
+ steps: truncated ? steps.slice(0, MAX_STATS_STEPS2) : steps,
5730
+ truncated
5731
+ });
5732
+ }
5733
+ default:
5734
+ throw new Error(`unknown tool: ${name}`);
5735
+ }
5736
+ }
5737
+ function ok(id, result) {
5738
+ return { jsonrpc: "2.0", id, result };
5739
+ }
5740
+ function fail(id, code, message) {
5741
+ return { jsonrpc: "2.0", id, error: { code, message } };
5742
+ }
5743
+ async function dispatchSiteMemoryRpc(store, raw) {
5744
+ if (typeof raw !== "object" || raw === null) return null;
5745
+ const req = raw;
5746
+ if (typeof req.method !== "string" || req.method.length === 0) return null;
5747
+ if (req.id === void 0) return null;
5748
+ const id = typeof req.id === "number" || typeof req.id === "string" ? req.id : null;
5749
+ const params = typeof req.params === "object" && req.params !== null ? req.params : {};
5750
+ switch (req.method) {
5751
+ case "initialize": {
5752
+ const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : "";
5753
+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.has(requested) ? requested : DEFAULT_PROTOCOL_VERSION;
5754
+ return ok(id, {
5755
+ protocolVersion,
5756
+ capabilities: { tools: {}, resources: {} },
5757
+ serverInfo: { name: "xbrowser-site-memory", version: process.env.npm_package_version || "1.34.0" }
5758
+ });
5759
+ }
5760
+ case "notifications/initialized":
5761
+ return null;
5762
+ case "ping":
5763
+ return ok(id, {});
5764
+ case "tools/list":
5765
+ return ok(id, { tools: TOOLS });
5766
+ case "tools/call": {
5767
+ const name = typeof params.name === "string" ? params.name : "";
5768
+ const args = typeof params.arguments === "object" && params.arguments !== null ? params.arguments : {};
5769
+ try {
5770
+ const result = await runSiteMemoryTool(store, name, args);
5771
+ return ok(id, result);
5772
+ } catch (err) {
5773
+ return ok(id, {
5774
+ content: [{ type: "text", text: `Error: ${err.message}` }],
5775
+ isError: true
5776
+ });
5777
+ }
5778
+ }
5779
+ case "resources/list":
5780
+ return ok(id, {
5781
+ resources: [
5782
+ {
5783
+ uri: DASHBOARD_URI,
5784
+ name: "site-memory-dashboard",
5785
+ description: "Static self-contained HTML dashboard of recorded flows, runs, step stats and errors.",
5786
+ mimeType: "text/html"
5787
+ }
5788
+ ]
5789
+ });
5790
+ case "resources/read": {
5791
+ const uri = typeof params.uri === "string" && params.uri.length > 0 ? params.uri : DASHBOARD_URI;
5792
+ if (uri !== DASHBOARD_URI) return fail(id, -32002, `unknown resource: ${uri}`);
5793
+ return ok(id, {
5794
+ contents: [{ uri: DASHBOARD_URI, mimeType: "text/html", text: renderSiteMemoryDashboard(store) }]
5795
+ });
5796
+ }
5797
+ default:
5798
+ return fail(id, -32601, `method not found: ${req.method}`);
5799
+ }
5800
+ }
5801
+ function runSiteMemoryStdioLoop(store, input, output, onFinished) {
5802
+ let buffer = "";
5803
+ let inflight = 0;
5804
+ let inputEnded = false;
5805
+ let finished = false;
5806
+ const finish = () => {
5807
+ if (finished) return;
5808
+ finished = true;
5809
+ try {
5810
+ store.close();
5811
+ } catch {
5812
+ }
5813
+ if (onFinished) onFinished();
5814
+ else process.exit(0);
5815
+ };
5816
+ input.setEncoding("utf8");
5817
+ input.on("data", (chunk) => {
5818
+ buffer += chunk;
5819
+ let idx;
5820
+ while ((idx = buffer.indexOf("\n")) >= 0) {
5821
+ const line = buffer.slice(0, idx).trim();
5822
+ buffer = buffer.slice(idx + 1);
5823
+ if (!line) continue;
5824
+ let req;
5825
+ try {
5826
+ req = JSON.parse(line);
5827
+ } catch {
5828
+ continue;
5829
+ }
5830
+ inflight += 1;
5831
+ dispatchSiteMemoryRpc(store, req).then((res) => {
5832
+ if (res !== null) output.write(JSON.stringify(res) + "\n");
5833
+ }).catch(() => {
5834
+ }).finally(() => {
5835
+ inflight -= 1;
5836
+ if (inputEnded && inflight === 0) finish();
5837
+ });
5838
+ }
5839
+ });
5840
+ input.on("end", () => {
5841
+ inputEnded = true;
5842
+ if (inflight === 0) finish();
5843
+ });
5844
+ }
5845
+ function startSiteMemoryMcp(store) {
5846
+ runSiteMemoryStdioLoop(store, process.stdin, process.stdout);
5847
+ }
5848
+
5849
+ // src/site-memory/cli.ts
5850
+ var MAX_WORKFLOW_BYTES = 256 * 1024;
5851
+ var USAGE = `Usage: xbrowser site-memory <subcommand>
5852
+
5853
+ Subcommands:
5854
+ run <workflow.json> [--cold] Run a declared workflow in a fresh headless browser
5855
+ and record the sanitized run in the local store
5856
+ report --output <path> Write a self-contained HTML dashboard
5857
+ (exclusive create: fails if the path already exists)
5858
+ mcp Start the read-only stdio MCP server over the store
5859
+
5860
+ Environment:
5861
+ XBROWSER_SITE_MEMORY_DB=/abs/path Override the store location (must be absolute;
5862
+ shared by every host that launches the MCP)
5863
+
5864
+ Notes:
5865
+ - Only workflows explicitly declared in the JSON file are executed.
5866
+ - No daemon, session routing, or user-browser involvement; each run launches
5867
+ its own throwaway headless profile.
5868
+ - Reports are local files and are never launched or opened automatically.`;
5869
+ function fail2(message, command, mode) {
5870
+ outputEnvelope({ success: false, data: null, message }, { command }, mode);
5871
+ process.exitCode = 1;
5872
+ }
5873
+ function resolveStorePath() {
5874
+ const override = process.env.XBROWSER_SITE_MEMORY_DB;
5875
+ if (override !== void 0 && override !== "") {
5876
+ if (!isAbsolute2(override)) {
5877
+ throw new Error(
5878
+ `XBROWSER_SITE_MEMORY_DB must be an absolute path, got: ${override}`
5879
+ );
5880
+ }
5881
+ return override;
5882
+ }
5883
+ return defaultSiteMemoryPath();
5884
+ }
5885
+ function openReadOnlyStore(storePath) {
5886
+ try {
5887
+ return openSiteMemoryStore(storePath, { readonly: true });
5888
+ } catch (e) {
5889
+ const detail = e instanceof Error ? e.message : String(e);
5890
+ throw new Error(
5891
+ `cannot open read-only site-memory store at ${storePath} (${detail})`
5892
+ );
5893
+ }
5894
+ }
5895
+ function createLazyReadOnlyStore(storePath) {
5896
+ const query = (fn) => {
5897
+ const store = openSiteMemoryStore(storePath, { readonly: true });
5898
+ try {
5899
+ return fn(store);
5900
+ } finally {
5901
+ store.close();
5902
+ }
5903
+ };
5904
+ return {
5905
+ putRun() {
5906
+ throw new Error("site-memory MCP store is read-only");
5907
+ },
5908
+ listSites: () => query((s) => s.listSites()),
5909
+ listRuns: (origin, flow, limit) => query((s) => s.listRuns(origin, flow, limit)),
5910
+ getRun: (runId) => query((s) => s.getRun(runId)),
5911
+ getStats: (origin, flow) => query((s) => s.getStats(origin, flow)),
5912
+ getBrief: (origin, flow, definitionKey) => query((s) => s.getBrief(origin, flow, definitionKey)),
5913
+ close() {
5914
+ }
5915
+ };
5916
+ }
5917
+ var openHeadlessPage = async () => {
5918
+ const { launch } = await import("./cdp-driver-MJD7YIQI.js");
5919
+ const { browser } = await launch({ headless: true });
5920
+ let context;
5921
+ try {
5922
+ context = await browser.newContext();
5923
+ const page = await context.newPage();
5924
+ const ownedContext = context;
5925
+ return {
5926
+ page,
5927
+ close: async () => {
5928
+ try {
5929
+ await ownedContext.close();
5930
+ } catch {
5931
+ }
5932
+ await browser.close();
5933
+ }
5934
+ };
5935
+ } catch (e) {
5936
+ await browser.close().catch(() => {
5937
+ });
5938
+ throw e;
5939
+ }
5940
+ };
5941
+ function warnIgnoredGlobalFlags(options) {
5942
+ if (options.cdp !== void 0 || options.session !== void 0) {
5943
+ console.error(
5944
+ "[site-memory] --cdp/--session are ignored: site-memory never uses the daemon, sessions, or the user browser."
5945
+ );
5946
+ }
5947
+ }
5948
+ async function handleRun2(rest, options, mode) {
5949
+ const command = "site-memory run";
5950
+ warnIgnoredGlobalFlags(options);
5951
+ const cold = options.cold !== void 0 && options.cold !== false;
5952
+ const fileArg = rest[0] ?? (typeof options.cold === "string" && options.cold !== "" ? options.cold : void 0);
5953
+ if (!fileArg) {
5954
+ fail2(`missing workflow file. Usage: xbrowser site-memory run <workflow.json> [--cold]`, command, mode);
5955
+ return;
5956
+ }
5957
+ const workflowPath = resolve8(fileArg);
5958
+ let size;
5959
+ try {
5960
+ size = (await stat(workflowPath)).size;
5961
+ } catch {
5962
+ fail2(`workflow file not found: ${workflowPath}`, command, mode);
5963
+ return;
5964
+ }
5965
+ if (size > MAX_WORKFLOW_BYTES) {
5966
+ fail2(
5967
+ `workflow file too large: ${workflowPath} (${size} bytes > ${MAX_WORKFLOW_BYTES} limit)`,
5968
+ command,
5969
+ mode
5970
+ );
5971
+ return;
5972
+ }
5973
+ let text;
5974
+ try {
5975
+ text = await readFile(workflowPath, "utf8");
5976
+ } catch (e) {
5977
+ fail2(`cannot read workflow file ${workflowPath}: ${e instanceof Error ? e.message : String(e)}`, command, mode);
5978
+ return;
5979
+ }
5980
+ let raw;
5981
+ try {
5982
+ raw = JSON.parse(text);
5983
+ } catch {
5984
+ fail2(`invalid workflow JSON in ${workflowPath}`, command, mode);
5985
+ return;
5986
+ }
5987
+ let storePath;
5988
+ try {
5989
+ storePath = resolveStorePath();
5990
+ } catch (e) {
5991
+ fail2(e instanceof Error ? e.message : String(e), command, mode);
5992
+ return;
5993
+ }
5994
+ let store;
5995
+ try {
5996
+ store = openSiteMemoryStore(storePath);
5997
+ } catch (e) {
5998
+ fail2(
5999
+ `cannot open site-memory store at ${storePath}: ${e instanceof Error ? e.message : String(e)}`,
6000
+ command,
6001
+ mode
6002
+ );
6003
+ return;
6004
+ }
6005
+ let run;
6006
+ try {
6007
+ run = await runWorkflow(raw, store, openHeadlessPage, { cold });
6008
+ } catch (e) {
6009
+ fail2(
6010
+ `workflow run failed: ${e instanceof Error ? e.message : String(e)}`,
6011
+ command,
6012
+ mode
6013
+ );
6014
+ return;
6015
+ } finally {
6016
+ store.close();
6017
+ }
6018
+ outputEnvelope(
6019
+ {
6020
+ success: true,
6021
+ data: run,
6022
+ duration: run.endedAt - run.startedAt
6023
+ },
6024
+ {
6025
+ command,
6026
+ store: storePath,
6027
+ cold,
6028
+ attempts: run.attempts.length,
6029
+ steps: new Set(run.attempts.map((a) => a.stepId)).size
6030
+ },
6031
+ mode
6032
+ );
6033
+ if (run.outcome !== "passed" || run.verified !== true) {
6034
+ process.exitCode = 1;
6035
+ }
6036
+ }
6037
+ async function handleReport(options, mode) {
6038
+ const command = "site-memory report";
6039
+ const outputArg = options.output;
6040
+ if (outputArg === void 0 || outputArg === "") {
6041
+ fail2(`missing --output <path>. Usage: xbrowser site-memory report --output <path>`, command, mode);
6042
+ return;
6043
+ }
6044
+ const reportPath = resolve8(outputArg);
6045
+ let storePath;
6046
+ try {
6047
+ storePath = resolveStorePath();
6048
+ } catch (e) {
6049
+ fail2(e instanceof Error ? e.message : String(e), command, mode);
6050
+ return;
6051
+ }
6052
+ let html;
6053
+ try {
6054
+ const store = openReadOnlyStore(storePath);
6055
+ try {
6056
+ html = renderSiteMemoryDashboard(store);
6057
+ } finally {
6058
+ store.close();
6059
+ }
6060
+ } catch (e) {
6061
+ fail2(e instanceof Error ? e.message : String(e), command, mode);
6062
+ return;
6063
+ }
6064
+ try {
6065
+ const fh = await openFile(reportPath, "wx", 384);
6066
+ try {
6067
+ await fh.writeFile(html, "utf8");
6068
+ } finally {
6069
+ await fh.close();
6070
+ }
6071
+ } catch (e) {
6072
+ const err = e;
6073
+ if (err.code === "EEXIST") {
6074
+ fail2(`refusing to overwrite existing report: ${reportPath}`, command, mode);
6075
+ } else {
6076
+ fail2(
6077
+ `cannot write report to ${reportPath}: ${err.message ?? String(e)}`,
6078
+ command,
6079
+ mode
6080
+ );
6081
+ }
6082
+ return;
6083
+ }
6084
+ outputEnvelope(
6085
+ {
6086
+ success: true,
6087
+ data: {
6088
+ path: reportPath,
6089
+ bytes: Buffer.byteLength(html, "utf8"),
6090
+ store: storePath
6091
+ }
6092
+ },
6093
+ { command },
6094
+ mode
6095
+ );
6096
+ }
6097
+ async function handleMcp(mode) {
6098
+ const command = "site-memory mcp";
6099
+ let storePath;
4143
6100
  try {
4144
- commands = readCommandFile(filePath);
6101
+ storePath = resolveStorePath();
4145
6102
  } catch (e) {
4146
- outputError(`Failed to read file '${filePath}': ${errMsg(e)}`);
4147
- return;
4148
- }
4149
- if (commands.length === 0) {
4150
- outputError("No commands found in file");
6103
+ fail2(e instanceof Error ? e.message : String(e), command, mode);
4151
6104
  return;
4152
6105
  }
4153
- const chain = commands.join(" ; ");
4154
- const chainResult = await executeChain(chain, {
4155
- cdpEndpoint: options?.cdpEndpoint,
4156
- sessionName: options?.sessionName,
4157
- fileMode: true
4158
- });
4159
- for (const step of chainResult.steps) {
4160
- if (step.success) {
4161
- process.stdout.write(`[OK] ${step.raw}
4162
- `);
4163
- if (step.data && typeof step.data === "object") {
4164
- const d = step.data;
4165
- for (const [k, v] of Object.entries(d)) {
4166
- if (k !== "ok")
4167
- process.stdout.write(` ${k}: ${typeof v === "string" ? v : JSON.stringify(v)}
4168
- `);
4169
- }
4170
- }
4171
- } else {
4172
- outputError(`[FAIL] ${step.raw}: ${step.message}`);
4173
- }
4174
- }
4175
- if (chainResult.stoppedReason) {
4176
- outputError(`Stopped: ${chainResult.stoppedReason}`);
6106
+ const store = createLazyReadOnlyStore(storePath);
6107
+ try {
6108
+ await startSiteMemoryMcp(store);
6109
+ } catch (e) {
6110
+ store.close();
6111
+ fail2(
6112
+ `site-memory MCP failed to start: ${e instanceof Error ? e.message : String(e)}`,
6113
+ command,
6114
+ mode
6115
+ );
4177
6116
  }
4178
- if (!chainResult.success) process.exit(1);
4179
6117
  }
4180
-
4181
- // src/cli/viewer-routes.ts
4182
- async function handleViewer(_args, options, mode, _cdpEndpoint) {
4183
- const name = options.session || process.env.XBROWSER_SESSION || "default";
4184
- const selector = options.selector;
4185
- const userPort = options.port ? Number(options.port) : void 0;
4186
- let status = getDaemonProcessStatus();
4187
- if (!status.running) {
4188
- await startDaemonProcess(userPort || 9224);
4189
- status = getDaemonProcessStatus();
4190
- }
4191
- const port = userPort || status.port || getDaemonConfig().basePort;
4192
- let url = `http://localhost:${port}/preview/${name}`;
4193
- if (selector) {
4194
- try {
4195
- const resp = await forwardViewerCheckSelector(name, selector);
4196
- if (resp.found) {
4197
- url += `#focus=${encodeURIComponent(selector)}`;
4198
- }
4199
- } catch {
4200
- }
6118
+ async function handleSiteMemory(args, options, mode) {
6119
+ const sub = args[0];
6120
+ const rest = args.slice(1);
6121
+ switch (sub) {
6122
+ case "run":
6123
+ await handleRun2(rest, options, mode);
6124
+ return;
6125
+ case "report":
6126
+ await handleReport(options, mode);
6127
+ return;
6128
+ case "mcp":
6129
+ await handleMcp(mode);
6130
+ return;
6131
+ default:
6132
+ process.stdout.write(USAGE + "\n");
6133
+ if (sub !== void 0) process.exitCode = 1;
6134
+ return;
4201
6135
  }
4202
- outputResult({ url, name, focused: !!selector && url.includes("#focus=") }, mode);
4203
6136
  }
4204
6137
 
4205
6138
  // src/cli/net-routes.ts
@@ -4537,7 +6470,7 @@ async function handleNetCommand(args, options, mode, sessionName) {
4537
6470
  // src/cli/test-routes.ts
4538
6471
  import { execFile as execFile2 } from "child_process";
4539
6472
  import { readFileSync as readFileSync6 } from "fs";
4540
- import { resolve as resolve7 } from "path";
6473
+ import { resolve as resolve9 } from "path";
4541
6474
  function execCli(args) {
4542
6475
  return new Promise((resolvePromise) => {
4543
6476
  execFile2(
@@ -4556,8 +6489,8 @@ function execCli(args) {
4556
6489
  }
4557
6490
  function findPluginPath(plugin) {
4558
6491
  const candidates = [
4559
- resolve7(process.cwd(), ".xcli/plugins", plugin, "index.ts"),
4560
- resolve7(process.cwd(), "node_modules/@xbrowser/cli/.xcli/plugins", plugin, "index.ts")
6492
+ resolve9(process.cwd(), ".xcli/plugins", plugin, "index.ts"),
6493
+ resolve9(process.cwd(), "node_modules/@xbrowser/cli/.xcli/plugins", plugin, "index.ts")
4561
6494
  ];
4562
6495
  for (const p of candidates) {
4563
6496
  try {
@@ -4566,7 +6499,7 @@ function findPluginPath(plugin) {
4566
6499
  } catch {
4567
6500
  }
4568
6501
  }
4569
- return resolve7(process.cwd(), ".xcli/plugins", plugin, "index.ts");
6502
+ return resolve9(process.cwd(), ".xcli/plugins", plugin, "index.ts");
4570
6503
  }
4571
6504
  function extractSchema(plugin, command) {
4572
6505
  const pluginPath = findPluginPath(plugin);
@@ -4793,12 +6726,12 @@ import { createServer } from "http";
4793
6726
 
4794
6727
  // src/console/facade.ts
4795
6728
  import { readFileSync as readFileSync7 } from "fs";
4796
- import { homedir as homedir3 } from "os";
4797
- import { join as join7 } from "path";
6729
+ import { homedir as homedir4 } from "os";
6730
+ import { join as join8 } from "path";
4798
6731
  var DAEMON_PREVIEW_URL = "http://127.0.0.1:9224";
4799
6732
  var CHROME_BRIDGE_STATUS_URL = "http://127.0.0.1:9347/status";
4800
6733
  var LOGIN_BRIDGE_STATUS_URL = "http://127.0.0.1:9355/cookies";
4801
- var CHROME_BRIDGE_META_PATH = join7(homedir3(), ".xbrowser", "chrome-bridge-ext.json");
6734
+ var CHROME_BRIDGE_META_PATH = join8(homedir4(), ".xbrowser", "chrome-bridge-ext.json");
4802
6735
  async function fetchJson(url, timeoutMs = 1200) {
4803
6736
  try {
4804
6737
  const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
@@ -4935,33 +6868,33 @@ function badge(status) {
4935
6868
  }
4936
6869
  return '<span class="badge bad">unavailable</span>';
4937
6870
  }
4938
- function escapeHtml(value) {
6871
+ function escapeHtml2(value) {
4939
6872
  return String(value ?? "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
4940
6873
  }
4941
6874
  function renderOverviewHtml(overview) {
4942
6875
  const environmentRows = (overview.environments ?? []).map((environment) => `
4943
6876
  <tr>
4944
- <td>${escapeHtml(environment.label)}</td>
4945
- <td>${escapeHtml(environment.kind)}</td>
6877
+ <td>${escapeHtml2(environment.label)}</td>
6878
+ <td>${escapeHtml2(environment.kind)}</td>
4946
6879
  <td>${badge(environment.status)}</td>
4947
- <td>${escapeHtml(environment.detail)}</td>
6880
+ <td>${escapeHtml2(environment.detail)}</td>
4948
6881
  </tr>`).join("");
4949
6882
  const sessionRows = (overview.sessions ?? []).map((session) => `
4950
6883
  <tr>
4951
- <td>${escapeHtml(session.name)}</td>
4952
- <td>${escapeHtml(session.url ?? "-")}</td>
6884
+ <td>${escapeHtml2(session.name)}</td>
6885
+ <td>${escapeHtml2(session.url ?? "-")}</td>
4953
6886
  <td>${badge(session.status)}</td>
4954
- <td><a href="${escapeHtml(session.previewUrl)}" target="_blank" rel="noreferrer">preview</a></td>
6887
+ <td><a href="${escapeHtml2(session.previewUrl)}" target="_blank" rel="noreferrer">preview</a></td>
4955
6888
  </tr>`).join("");
4956
6889
  const pluginRows = (overview.plugins ?? []).map((plugin) => `
4957
6890
  <tr>
4958
- <td>${escapeHtml(plugin.displayName)}</td>
4959
- <td>${escapeHtml(plugin.version)}</td>
4960
- <td>${escapeHtml(plugin.source)}</td>
6891
+ <td>${escapeHtml2(plugin.displayName)}</td>
6892
+ <td>${escapeHtml2(plugin.version)}</td>
6893
+ <td>${escapeHtml2(plugin.source)}</td>
4961
6894
  <td>${badge(plugin.status)}</td>
4962
- <td>${escapeHtml(plugin.commands.slice(0, 8).join(", ") || "-")}</td>
6895
+ <td>${escapeHtml2(plugin.commands.slice(0, 8).join(", ") || "-")}</td>
4963
6896
  </tr>`).join("");
4964
- const evidence = overview.evidence ? `<pre>${escapeHtml(JSON.stringify(overview.evidence, null, 2))}</pre>` : '<p class="muted">No session selected for evidence.</p>';
6897
+ const evidence = overview.evidence ? `<pre>${escapeHtml2(JSON.stringify(overview.evidence, null, 2))}</pre>` : '<p class="muted">No session selected for evidence.</p>';
4965
6898
  return `<!doctype html>
4966
6899
  <html lang="zh-CN">
4967
6900
  <head>
@@ -4996,7 +6929,7 @@ function renderOverviewHtml(overview) {
4996
6929
  <main>
4997
6930
  <h1>xBrowser Console</h1>
4998
6931
  <span class="readonly">Read-only prototype</span>
4999
- <p>Generated at ${escapeHtml(overview.generatedAt)} \xB7 \u9636\u6BB5 0 / Console Facade \u603B\u89C8</p>
6932
+ <p>Generated at ${escapeHtml2(overview.generatedAt)} \xB7 \u9636\u6BB5 0 / Console Facade \u603B\u89C8</p>
5000
6933
  <section class="cards">
5001
6934
  <div class="card"><span>\u8FD0\u884C\u4F1A\u8BDD</span><strong>${overview.stats.runningSessions}</strong></div>
5002
6935
  <div class="card"><span>\u53EF\u7528\u73AF\u5883</span><strong>${overview.stats.availableEnvironments}</strong></div>
@@ -5196,9 +7129,13 @@ Commands:
5196
7129
  create <name> --template <type> Create plugin
5197
7130
  serve [--port <p>] [--host <h>] [--token <t>] [--cors-origins <csv>] Start HTTP server (loopback by default)
5198
7131
  remote <url> [command] [--token <t>] Execute on remote server
5199
- run <file> Execute commands from file
7132
+ run <file> [--headless] Execute commands from a text file
7133
+ run <jobs.json> [--parallel N] Run named headless jobs concurrently
5200
7134
  viewer [--name <n>] Generate viewer URL
5201
7135
  console-panel [--port <n>] Readonly Console Facade overview
7136
+ site-memory run <workflow.json> [--cold] Run declared workflow in a fresh headless browser
7137
+ site-memory report --output <path> Write HTML run dashboard (never overwrites)
7138
+ site-memory mcp Readonly stdio MCP over run history
5202
7139
  help Show this help
5203
7140
  --version Show version
5204
7141
  Plugin Commands:
@@ -5457,7 +7394,7 @@ async function handleChainInput(input, argv) {
5457
7394
  import { helpGenerator as helpGenerator3 } from "@dyyz1993/xcli-core";
5458
7395
 
5459
7396
  // src/router/help.ts
5460
- import { helpGenerator as helpGenerator2, outputFormatter as outputFormatter2 } from "@dyyz1993/xcli-core";
7397
+ import { helpGenerator as helpGenerator2, outputFormatter } from "@dyyz1993/xcli-core";
5461
7398
  function showCommandHelp(siteName, cmd, siteConfig, mode) {
5462
7399
  const c = cmd;
5463
7400
  if (mode === "json") {
@@ -5504,7 +7441,7 @@ function showCommandHelp(siteName, cmd, siteConfig, mode) {
5504
7441
  }
5505
7442
  function outputLoginRequired(result, mode) {
5506
7443
  if (mode === "json" || mode === "yaml") {
5507
- console.log(outputFormatter2.format(result, { mode, color: false, emoji: false }));
7444
+ console.log(outputFormatter.format(result, { mode, color: false, emoji: false }));
5508
7445
  return;
5509
7446
  }
5510
7447
  const message = result.message || "Login required";
@@ -5651,7 +7588,7 @@ var SUBCOMMAND_HELP = {
5651
7588
  daemon: "daemon status [--port <port>]",
5652
7589
  replay: "replay <file> [--slow-mo <ms>] [--stop-on-error]",
5653
7590
  create: "create <name> [--template static|dynamic|login|api]",
5654
- run: "run <file>",
7591
+ run: "run <file> [--headless] | run <jobs.json> [--parallel N]",
5655
7592
  serve: "serve [--port <port>] [--host <host>] [--token <token>] [--cors-origins <csv>]",
5656
7593
  remote: "remote <url> [command] [--token <token>]",
5657
7594
  convert: "convert <file> [--to js|py|sh]",
@@ -5661,7 +7598,8 @@ var SUBCOMMAND_HELP = {
5661
7598
  viewer: "viewer [--session <name>]",
5662
7599
  "console-panel": "console-panel [--port <port>]",
5663
7600
  kill: "kill [--all]",
5664
- net: "net [--cdp <endpoint>]"
7601
+ net: "net [--cdp <endpoint>]",
7602
+ "site-memory": "site-memory run <workflow.json> [--cold] | report --output <path> | mcp"
5665
7603
  };
5666
7604
 
5667
7605
  // src/server/http-server.ts
@@ -5990,19 +7928,19 @@ function headersToObject(headers) {
5990
7928
  return result;
5991
7929
  }
5992
7930
  function readBody(req) {
5993
- return new Promise((resolve8, reject) => {
7931
+ return new Promise((resolve10, reject) => {
5994
7932
  const chunks = [];
5995
7933
  req.on("data", (chunk) => chunks.push(chunk));
5996
7934
  req.on("end", () => {
5997
7935
  const raw = Buffer.concat(chunks).toString("utf-8");
5998
7936
  if (!raw) {
5999
- resolve8(null);
7937
+ resolve10(null);
6000
7938
  return;
6001
7939
  }
6002
7940
  try {
6003
- resolve8(JSON.parse(raw));
7941
+ resolve10(JSON.parse(raw));
6004
7942
  } catch {
6005
- resolve8(null);
7943
+ resolve10(null);
6006
7944
  }
6007
7945
  });
6008
7946
  req.on("error", reject);
@@ -6056,7 +7994,7 @@ var HTTPServer = class {
6056
7994
  res.end(JSON.stringify({ error: "INTERNAL_ERROR", message, statusCode: 500 }));
6057
7995
  });
6058
7996
  });
6059
- return new Promise((resolve8, reject) => {
7997
+ return new Promise((resolve10, reject) => {
6060
7998
  const server = this.server;
6061
7999
  server.on("error", (err) => {
6062
8000
  this.server = null;
@@ -6071,7 +8009,7 @@ var HTTPServer = class {
6071
8009
  this.port = addr.port;
6072
8010
  }
6073
8011
  console.log(`HTTP server listening on http://${this.host}:${this.port}`);
6074
- resolve8({ port: this.port, host: this.host });
8012
+ resolve10({ port: this.port, host: this.host });
6075
8013
  });
6076
8014
  });
6077
8015
  }
@@ -6082,13 +8020,13 @@ var HTTPServer = class {
6082
8020
  */
6083
8021
  async stop() {
6084
8022
  if (!this.server) return;
6085
- return new Promise((resolve8, reject) => {
8023
+ return new Promise((resolve10, reject) => {
6086
8024
  this.server.close((err) => {
6087
8025
  if (err) {
6088
8026
  reject(err);
6089
8027
  } else {
6090
8028
  this.server = null;
6091
- resolve8();
8029
+ resolve10();
6092
8030
  }
6093
8031
  });
6094
8032
  });
@@ -6232,7 +8170,7 @@ async function handleRemote(args, options, mode) {
6232
8170
  }
6233
8171
  }
6234
8172
  async function startMcpServer() {
6235
- const { startMcpStdio } = await import("./server-5JHB4TML.js");
8173
+ const { startMcpStdio } = await import("./server-HUSX7EFE.js");
6236
8174
  startMcpStdio();
6237
8175
  }
6238
8176
 
@@ -6276,8 +8214,18 @@ async function dispatchSubcommand(request) {
6276
8214
  await handleFilter(cmdArgs, mode, options);
6277
8215
  return true;
6278
8216
  case "run":
6279
- if (!cmdArgs[0]) outputError("Usage: xbrowser run <file>");
6280
- await handleRun(cmdArgs[0], { cdpEndpoint, sessionName });
8217
+ if (!cmdArgs[0]) {
8218
+ outputError("Usage: xbrowser run <file>");
8219
+ } else if (options.headless === true || options.parallel !== void 0 || cmdArgs[0].endsWith(".json")) {
8220
+ if (cdpEndpoint || options.bridge) {
8221
+ outputError("Managed runs use a self-launched headless browser");
8222
+ } else {
8223
+ const { handleManagedRunFile } = await import("./run-routes-SJKVZ34L.js");
8224
+ await handleManagedRunFile(cmdArgs[0], { sessionName, parallel: options.parallel, mode });
8225
+ }
8226
+ } else {
8227
+ await handleRun(cmdArgs[0], { cdpEndpoint, sessionName });
8228
+ }
6281
8229
  return true;
6282
8230
  case "serve":
6283
8231
  await handleServe(cmdArgs, options, mode);
@@ -6307,6 +8255,9 @@ async function dispatchSubcommand(request) {
6307
8255
  case "net":
6308
8256
  await handleNetCommand(cmdArgs, options, mode, sessionName);
6309
8257
  return true;
8258
+ case "site-memory":
8259
+ await handleSiteMemory(cmdArgs, options, mode);
8260
+ return true;
6310
8261
  case "console-panel":
6311
8262
  await handleConsoleServe(cmdArgs, options, mode);
6312
8263
  return true;
@@ -6324,7 +8275,7 @@ import {
6324
8275
  isCommandResult,
6325
8276
  tip as makeTipSafe,
6326
8277
  normalizeTips,
6327
- outputFormatter as outputFormatter3,
8278
+ outputFormatter as outputFormatter2,
6328
8279
  TipCollector
6329
8280
  } from "@dyyz1993/xcli-core";
6330
8281
  var KNOWN_GLOBAL_OPTIONS = /* @__PURE__ */ new Set([
@@ -6510,7 +8461,7 @@ Run "xbrowser ${command} ${subCommand} --help" to see available parameters.`
6510
8461
  }
6511
8462
  const needsBrowser = cmdEntry.scope === "page" || cmdEntry.scope === "browser";
6512
8463
  if (needsBrowser && !process.env.XBROWSER_DAEMON_WORKER) {
6513
- const { forwardPluginExec } = await import("./daemon-client-HEGAXWGK.js");
8464
+ const { forwardPluginExec } = await import("./daemon-client-Z3NKNZRL.js");
6514
8465
  const userTimeout = typeof params.timeout === "number" && params.timeout > 0 ? params.timeout * 1e3 + 3e4 : void 0;
6515
8466
  const result = await forwardPluginExec(`${command}.${subCommand}`, params, sessionName, cdpEndpoint, userTimeout);
6516
8467
  const resultData = result && typeof result === "object" && "data" in result ? result.data : void 0;
@@ -6522,14 +8473,20 @@ Run "xbrowser ${command} ${subCommand} --help" to see available parameters.`
6522
8473
  if (result && result.success !== false) {
6523
8474
  if (isCommandResult(result)) {
6524
8475
  if (mode === "json" || mode === "yaml") {
6525
- console.log(outputFormatter3.format(result.data, { mode, color: false, emoji: false }));
8476
+ console.log(outputFormatter2.format(result.data, { mode, color: false, emoji: false }));
6526
8477
  if (result.tips?.length) {
6527
- for (const tip of result.tips) console.error(`\u{1F4A1} ${tip}`);
8478
+ for (const tip of result.tips) {
8479
+ const text = typeof tip === "string" ? tip : tip.message;
8480
+ if (text) console.error(`\u{1F4A1} ${text}`);
8481
+ }
6528
8482
  }
6529
8483
  } else {
6530
- console.log(outputFormatter3.format(result.data, { mode: "text", color: true, emoji: true }));
8484
+ console.log(outputFormatter2.format(result.data, { mode: "text", color: true, emoji: true }));
6531
8485
  if (result.tips?.length) {
6532
- for (const tip of result.tips) console.log(` \u{1F4A1} ${tip}`);
8486
+ for (const tip of result.tips) {
8487
+ const text = typeof tip === "string" ? tip : tip.message;
8488
+ if (text) console.log(` \u{1F4A1} ${text}`);
8489
+ }
6533
8490
  }
6534
8491
  }
6535
8492
  }
@@ -6550,7 +8507,7 @@ Run "xbrowser ${command} ${subCommand} --help" to see available parameters.`
6550
8507
  const targetPage = pages[cmdTabIndex];
6551
8508
  await targetPage.bringToFront().catch(() => {
6552
8509
  });
6553
- const { setActivePage } = await import("./browser-D7RFPTD4.js");
8510
+ const { setActivePage } = await import("./browser-RZ7DPBI3.js");
6554
8511
  setActivePage(session, targetPage);
6555
8512
  }
6556
8513
  }
@@ -6646,7 +8603,7 @@ Run "xbrowser ${command} ${subCommand} --help" to see available parameters.`
6646
8603
  mode
6647
8604
  );
6648
8605
  } else {
6649
- console.log(outputFormatter3.format(outputData, { mode: "text", color: true, emoji: true }));
8606
+ console.log(outputFormatter2.format(outputData, { mode: "text", color: true, emoji: true }));
6650
8607
  if (tips?.length) {
6651
8608
  for (const tip of tips) console.log(` \u{1F4A1} ${typeof tip === "string" ? tip : tip.message}`);
6652
8609
  }
@@ -6697,7 +8654,7 @@ async function routeCommand(argvIn, stdinCommands) {
6697
8654
  if (argv[0] === "--json" || argv[0] === "--yaml") {
6698
8655
  argv = argv.slice(1);
6699
8656
  }
6700
- const globalFlags = /* @__PURE__ */ new Set(["--session", "--cdp", "--json", "--yaml", "--output", "--timeout", "--help", "-h", "--version", "--frame", "--target", "--tab"]);
8657
+ const globalFlags = /* @__PURE__ */ new Set(["--session", "--cdp", "--json", "--yaml", "--output", "--timeout", "--help", "-h", "--version", "--frame", "--target", "--tab", "--bridge"]);
6701
8658
  let chainArgIdx = -1;
6702
8659
  let seenCommandWord = false;
6703
8660
  for (let i = 0; i < argv.length; i++) {
@@ -6731,7 +8688,7 @@ async function routeCommand(argvIn, stdinCommands) {
6731
8688
  const hasJsonFlag = argv.some((a) => a === "--json" || a.startsWith("--json="));
6732
8689
  const hasYamlFlag = argv.some((a) => a === "--yaml" || a.startsWith("--yaml="));
6733
8690
  const cleanArgv = argv.filter((a) => a !== "--json" && a !== "--yaml");
6734
- const parsed = parseArgs(cleanArgv, { booleanFlags: ["json", "yaml"] });
8691
+ const parsed = parseArgs(cleanArgv, { booleanFlags: ["json", "yaml", "bridge", "headless"] });
6735
8692
  const { positional, options } = parsed;
6736
8693
  if (hasJsonFlag) options.json = true;
6737
8694
  if (hasYamlFlag) options.yaml = true;
@@ -7351,19 +9308,24 @@ var StreamCoordinator = class {
7351
9308
  });
7352
9309
  }
7353
9310
  sink;
7354
- lastFrameData = null;
7355
- lastFrameViewport = null;
7356
- lastUncroppedFrameData = null;
7357
- lastUncroppedFrameViewport = null;
7358
9311
  stateManager = new StreamStateManager();
7359
9312
  frameRateController = new FrameRateController();
7360
9313
  frameProcessor = new FrameProcessor();
7361
9314
  sessionCrops = /* @__PURE__ */ new Map();
9315
+ sessionFrames = /* @__PURE__ */ new Map();
9316
+ frameCacheSeq = 0;
7362
9317
  // -----------------------------------------------------------------------
7363
9318
  // Public accessors
7364
9319
  // -----------------------------------------------------------------------
7365
- getLastFrameViewport() {
7366
- return this.lastFrameViewport;
9320
+ /**
9321
+ * Cached viewport for a session's last frame. When `sessionId` is omitted
9322
+ * (legacy callers), falls back to the most recently updated session's
9323
+ * viewport so old call sites keep behaving like the former global cache.
9324
+ */
9325
+ getLastFrameViewport(sessionId) {
9326
+ const entry = sessionId !== void 0 ? this.sessionFrames.get(sessionId) : this.latestFrameCache();
9327
+ if (!entry) return null;
9328
+ return entry.uncroppedViewport ?? entry.viewport ?? null;
7367
9329
  }
7368
9330
  getCrop(sessionId) {
7369
9331
  return this.sessionCrops.get(sessionId);
@@ -7382,12 +9344,26 @@ var StreamCoordinator = class {
7382
9344
  resetFrameRate() {
7383
9345
  this.frameRateController.reset();
7384
9346
  }
7385
- /** Clear cached last-frame data. */
7386
- clearLastFrame() {
7387
- this.lastFrameData = null;
7388
- this.lastFrameViewport = null;
7389
- this.lastUncroppedFrameData = null;
7390
- this.lastUncroppedFrameViewport = null;
9347
+ /**
9348
+ * Clear cached last-frame data. With `sessionId`, only that session's cache
9349
+ * is dropped (other concurrent sessions keep theirs). Without it (legacy
9350
+ * callers), every session's cache is cleared — same as the old global clear.
9351
+ */
9352
+ clearLastFrame(sessionId) {
9353
+ if (sessionId === void 0) {
9354
+ this.sessionFrames.clear();
9355
+ return;
9356
+ }
9357
+ this.sessionFrames.delete(sessionId);
9358
+ }
9359
+ /**
9360
+ * Full teardown of per-session stream state (last-frame cache + crop).
9361
+ * Must be called when a session unregisters so a later session reusing the
9362
+ * same id can never replay the previous occupant's stale frame.
9363
+ */
9364
+ releaseSession(sessionId) {
9365
+ this.sessionFrames.delete(sessionId);
9366
+ this.sessionCrops.delete(sessionId);
7391
9367
  }
7392
9368
  // -----------------------------------------------------------------------
7393
9369
  // Frame capture callbacks (used by SessionManager)
@@ -7402,8 +9378,10 @@ var StreamCoordinator = class {
7402
9378
  resetStaticSnapshotTimer();
7403
9379
  (async () => {
7404
9380
  const data = frame.data.toString("base64");
7405
- this.lastUncroppedFrameData = data;
7406
- this.lastUncroppedFrameViewport = frame.viewport;
9381
+ const cache = this.getOrCreateFrameCache(sessionId);
9382
+ cache.uncroppedData = data;
9383
+ cache.uncroppedViewport = frame.viewport;
9384
+ this.touchFrameCache(cache);
7407
9385
  this.stateManager.onFrameReceived();
7408
9386
  const config = this.stateManager.getConfig();
7409
9387
  if (!this.frameRateController.shouldSendFrame(config.maxFps)) {
@@ -7439,8 +9417,10 @@ var StreamCoordinator = class {
7439
9417
  }
7440
9418
  const screenshot = await page.screenshot({ type: "jpeg", quality: 100 });
7441
9419
  const data = screenshot.toString("base64");
7442
- this.lastUncroppedFrameData = data;
7443
- this.lastUncroppedFrameViewport = viewport;
9420
+ const cache = this.getOrCreateFrameCache(sessionId);
9421
+ cache.uncroppedData = data;
9422
+ cache.uncroppedViewport = viewport;
9423
+ this.touchFrameCache(cache);
7444
9424
  await this.processAndBroadcast(
7445
9425
  data,
7446
9426
  viewport,
@@ -7452,12 +9432,16 @@ var StreamCoordinator = class {
7452
9432
  );
7453
9433
  }
7454
9434
  /**
7455
- * Process and broadcast the current last frame for a session (used for
7456
- * replay and crop changes).
9435
+ * Process and broadcast the cached last frame for a session (used for
9436
+ * replay and crop changes). Strictly per-session: a session with no cached
9437
+ * frame of its own replays nothing — it must never fall back to another
9438
+ * session's frame.
7457
9439
  */
7458
9440
  async replayLastFrame(sessionId) {
7459
- const data = this.lastUncroppedFrameData ?? this.lastFrameData;
7460
- const viewport = this.lastUncroppedFrameViewport ?? this.lastFrameViewport;
9441
+ const entry = this.sessionFrames.get(sessionId);
9442
+ if (!entry) return;
9443
+ const data = entry.uncroppedData ?? entry.data;
9444
+ const viewport = entry.uncroppedViewport ?? entry.viewport;
7461
9445
  if (!data || !viewport) return;
7462
9446
  await this.processAndBroadcast(
7463
9447
  data,
@@ -7476,7 +9460,7 @@ var StreamCoordinator = class {
7476
9460
  // Private helpers
7477
9461
  // -----------------------------------------------------------------------
7478
9462
  async handleStateChange(_newState) {
7479
- if (!this.lastFrameData || !this.lastFrameViewport) return;
9463
+ if (this.sessionFrames.size === 0) return;
7480
9464
  }
7481
9465
  async processAndBroadcast(frameData, frameViewport, sessionId, frameSessionId, frameId, frameTimestamp, frameUrl) {
7482
9466
  const config = this.stateManager.getConfig();
@@ -7518,15 +9502,181 @@ var StreamCoordinator = class {
7518
9502
  const headerLen = Buffer.alloc(4);
7519
9503
  headerLen.writeUInt32BE(header.length, 0);
7520
9504
  const payload = Buffer.concat([headerLen, header, processedBuffer]);
7521
- this.lastFrameData = frameData;
7522
- this.lastFrameViewport = frameViewport;
9505
+ const cache = this.getOrCreateFrameCache(sessionId);
9506
+ cache.data = frameData;
9507
+ cache.viewport = frameViewport;
9508
+ this.touchFrameCache(cache);
7523
9509
  this.sink.broadcastBinaryToSession(sessionId, payload);
7524
9510
  }
9511
+ // -----------------------------------------------------------------------
9512
+ // Per-session frame-cache helpers
9513
+ // -----------------------------------------------------------------------
9514
+ getOrCreateFrameCache(sessionId) {
9515
+ let entry = this.sessionFrames.get(sessionId);
9516
+ if (!entry) {
9517
+ entry = { uncroppedData: null, uncroppedViewport: null, data: null, viewport: null, seq: 0 };
9518
+ this.sessionFrames.set(sessionId, entry);
9519
+ }
9520
+ return entry;
9521
+ }
9522
+ touchFrameCache(entry) {
9523
+ entry.seq = ++this.frameCacheSeq;
9524
+ }
9525
+ /** Most recently updated entry — only used by the legacy no-arg fallback. */
9526
+ latestFrameCache() {
9527
+ let latest;
9528
+ for (const entry of this.sessionFrames.values()) {
9529
+ if (!latest || entry.seq > latest.seq) latest = entry;
9530
+ }
9531
+ return latest;
9532
+ }
7525
9533
  };
7526
9534
 
7527
9535
  // src/ws/session-manager.ts
7528
9536
  import { EventEmitter } from "events";
7529
9537
 
9538
+ // src/screencast.ts
9539
+ var ScreencastCapturer = class {
9540
+ interval;
9541
+ quality;
9542
+ type;
9543
+ maxWidth;
9544
+ maxHeight;
9545
+ isCapturing = false;
9546
+ frameCallback = null;
9547
+ // CDP Cast state
9548
+ cdpSession = null;
9549
+ sessionId = "";
9550
+ // Fallback polling state
9551
+ fallbackTimer = null;
9552
+ constructor(options = {}) {
9553
+ this.interval = options.interval || 100;
9554
+ this.quality = options.quality || 60;
9555
+ this.type = options.type || "jpeg";
9556
+ this.maxWidth = options.width || 1920;
9557
+ this.maxHeight = options.height || 1080;
9558
+ }
9559
+ /**
9560
+ * Start screencast capture using CDP Page.startScreencast.
9561
+ *
9562
+ * If CDP session creation fails (non-Chromium, restricted access),
9563
+ * automatically falls back to `page.screenshot()` polling.
9564
+ */
9565
+ async startCapture(page, sessionId, onFrame) {
9566
+ if (this.isCapturing) {
9567
+ throw new Error("Screencast is already capturing");
9568
+ }
9569
+ this.isCapturing = true;
9570
+ this.frameCallback = onFrame;
9571
+ this.sessionId = sessionId;
9572
+ try {
9573
+ const cdp = await page.context().newCDPSession(page);
9574
+ this.cdpSession = cdp;
9575
+ cdp.on("Page.screencastFrame", async (params) => {
9576
+ const cb = this.frameCallback;
9577
+ if (!cb) return;
9578
+ cdp.send("Page.screencastFrameAck", { sessionId: params.sessionId }).catch(() => {
9579
+ });
9580
+ const logicalViewport = page.viewportSize();
9581
+ const viewport = logicalViewport ?? {
9582
+ width: params.metadata?.deviceWidth || this.maxWidth,
9583
+ height: params.metadata?.deviceHeight || this.maxHeight
9584
+ };
9585
+ cb({
9586
+ id: crypto.randomUUID(),
9587
+ sessionId: this.sessionId,
9588
+ timestamp: Date.now(),
9589
+ data: Buffer.from(params.data, "base64"),
9590
+ url: page.url(),
9591
+ viewport
9592
+ });
9593
+ });
9594
+ await cdp.send("Page.startScreencast", {
9595
+ format: this.type === "png" ? "png" : "jpeg",
9596
+ quality: this.type === "jpeg" ? this.quality : void 0,
9597
+ maxWidth: this.maxWidth,
9598
+ maxHeight: this.maxHeight
9599
+ });
9600
+ } catch {
9601
+ this.cdpSession = null;
9602
+ this.startFallbackPolling(page, sessionId);
9603
+ }
9604
+ }
9605
+ /**
9606
+ * Fallback: periodic page.screenshot() polling when CDP Cast is unavailable.
9607
+ */
9608
+ startFallbackPolling(page, sessionId) {
9609
+ const captureLoop = async () => {
9610
+ if (!this.frameCallback) return;
9611
+ try {
9612
+ const frame = await this.captureFrame(page, sessionId);
9613
+ this.frameCallback(frame);
9614
+ } catch {
9615
+ }
9616
+ };
9617
+ captureLoop();
9618
+ this.fallbackTimer = setInterval(captureLoop, this.interval);
9619
+ }
9620
+ /**
9621
+ * Capture a single screenshot frame from the page (fallback mode).
9622
+ */
9623
+ async captureFrame(page, sessionId) {
9624
+ let viewport = page.viewportSize();
9625
+ if (!viewport) {
9626
+ try {
9627
+ viewport = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
9628
+ } catch {
9629
+ viewport = { width: 1920, height: 1080 };
9630
+ }
9631
+ }
9632
+ const screenshot = await page.screenshot({
9633
+ type: this.type,
9634
+ quality: this.type === "jpeg" ? this.quality : void 0
9635
+ });
9636
+ return {
9637
+ id: crypto.randomUUID(),
9638
+ sessionId,
9639
+ timestamp: Date.now(),
9640
+ data: screenshot,
9641
+ url: page.url(),
9642
+ viewport: viewport || { width: 0, height: 0 }
9643
+ };
9644
+ }
9645
+ /**
9646
+ * Stop the current screencast capture.
9647
+ */
9648
+ async stopCapture() {
9649
+ if (this.cdpSession) {
9650
+ try {
9651
+ this.cdpSession.off("Page.screencastFrame", () => {
9652
+ });
9653
+ await this.cdpSession.send("Page.stopScreencast");
9654
+ } catch {
9655
+ }
9656
+ try {
9657
+ await this.cdpSession.detach();
9658
+ } catch {
9659
+ }
9660
+ this.cdpSession = null;
9661
+ }
9662
+ if (this.fallbackTimer) {
9663
+ clearInterval(this.fallbackTimer);
9664
+ this.fallbackTimer = null;
9665
+ }
9666
+ this.isCapturing = false;
9667
+ this.frameCallback = null;
9668
+ }
9669
+ isActive() {
9670
+ return this.isCapturing;
9671
+ }
9672
+ setInterval(interval) {
9673
+ this.interval = interval;
9674
+ }
9675
+ setQuality(quality) {
9676
+ this.quality = quality;
9677
+ }
9678
+ };
9679
+
7530
9680
  // src/ws/element-monitor.ts
7531
9681
  var ElementMonitor = class {
7532
9682
  constructor(page, onFocusChange, onViewsUpdate, getClientCount) {
@@ -7858,6 +10008,7 @@ var SessionManager = class extends EventEmitter {
7858
10008
  });
7859
10009
  }
7860
10010
  unregisterSession(sessionId) {
10011
+ this.streamCoordinator?.releaseSession(sessionId);
7861
10012
  const sc = this.screencasts.get(sessionId);
7862
10013
  if (!sc) return;
7863
10014
  if (sc.capturer.isActive()) {
@@ -8216,13 +10367,13 @@ var FileListHandler = class {
8216
10367
  const msg = ctx.message;
8217
10368
  try {
8218
10369
  const { readdirSync: readdirSync3, statSync } = await import("fs");
8219
- const { join: join9, resolve: resolve8 } = await import("path");
8220
- const targetPath = resolve8(msg.path);
10370
+ const { join: join10, resolve: resolve10 } = await import("path");
10371
+ const targetPath = resolve10(msg.path);
8221
10372
  const entries = readdirSync3(targetPath);
8222
10373
  const files = entries.map((name) => {
8223
10374
  try {
8224
- const stat = statSync(join9(targetPath, name));
8225
- return { name, isDir: stat.isDirectory(), size: stat.size, modified: stat.mtime.toISOString() };
10375
+ const stat2 = statSync(join10(targetPath, name));
10376
+ return { name, isDir: stat2.isDirectory(), size: stat2.size, modified: stat2.mtime.toISOString() };
8226
10377
  } catch {
8227
10378
  return { name, isDir: false, size: 0, modified: "" };
8228
10379
  }
@@ -8239,8 +10390,8 @@ var FileDownloadHandler = class {
8239
10390
  const msg = ctx.message;
8240
10391
  try {
8241
10392
  const { readFileSync: readFileSync9 } = await import("fs");
8242
- const { resolve: resolve8, basename: basename3 } = await import("path");
8243
- const targetPath = resolve8(msg.path);
10393
+ const { resolve: resolve10, basename: basename3 } = await import("path");
10394
+ const targetPath = resolve10(msg.path);
8244
10395
  const data = readFileSync9(targetPath);
8245
10396
  const base64 = data.toString("base64");
8246
10397
  const ext = targetPath.split(".").pop()?.toLowerCase() || "";
@@ -8304,7 +10455,7 @@ var FocusClearHandler = class {
8304
10455
  async handle(ctx) {
8305
10456
  if (!ctx.sessionId) return;
8306
10457
  this.sc.deleteCrop(ctx.sessionId);
8307
- const vp = this.sc.getLastFrameViewport();
10458
+ const vp = this.sc.getLastFrameViewport(ctx.sessionId);
8308
10459
  if (vp) {
8309
10460
  ctx.broadcastToSession(ctx.sessionId, { type: "status", data: { status: "connected", viewport: vp } });
8310
10461
  }
@@ -8322,7 +10473,7 @@ var SelectViewHandler = class {
8322
10473
  if (!ctx.sessionId) return;
8323
10474
  if (!msg.rect) {
8324
10475
  this.sc.deleteCrop(ctx.sessionId);
8325
- const vp = this.sc.getLastFrameViewport();
10476
+ const vp = this.sc.getLastFrameViewport(ctx.sessionId);
8326
10477
  if (vp) {
8327
10478
  ctx.broadcastToSession(ctx.sessionId, { type: "status", data: { status: "connected", viewport: vp } });
8328
10479
  }
@@ -8384,7 +10535,418 @@ var MessageDispatcher = class {
8384
10535
  }
8385
10536
  };
8386
10537
 
10538
+ // src/ws/workspace-controller.ts
10539
+ import { randomUUID as randomUUID2 } from "crypto";
10540
+ var LOOPBACK_ADDRESSES = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
10541
+ var LOOPBACK_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
10542
+ function checkWorkspaceTrust(peer, viewerPort) {
10543
+ if (!peer) return { ok: true };
10544
+ const { remoteAddress, origin } = peer;
10545
+ if (remoteAddress !== void 0 && remoteAddress !== "" && !LOOPBACK_ADDRESSES.has(remoteAddress)) {
10546
+ return { ok: false, reason: `Workspace controls are restricted to local viewers (peer ${remoteAddress} is not loopback).` };
10547
+ }
10548
+ if (origin !== void 0 && origin !== "") {
10549
+ let parsed;
10550
+ try {
10551
+ parsed = new URL(origin);
10552
+ } catch {
10553
+ return { ok: false, reason: `Invalid Origin for workspace controls: ${origin}` };
10554
+ }
10555
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
10556
+ return { ok: false, reason: `Unsupported Origin protocol for workspace controls: ${parsed.protocol}` };
10557
+ }
10558
+ if (!LOOPBACK_HOSTNAMES.has(parsed.hostname)) {
10559
+ return { ok: false, reason: `Workspace controls are restricted to the local Viewer origin (got ${origin}).` };
10560
+ }
10561
+ const originPort = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
10562
+ if (viewerPort > 0 && originPort !== String(viewerPort)) {
10563
+ return { ok: false, reason: `Workspace controls accept the local Viewer origin only (origin port ${originPort} != viewer port ${viewerPort}).` };
10564
+ }
10565
+ }
10566
+ return { ok: true };
10567
+ }
10568
+ var WorkspaceError = class extends Error {
10569
+ };
10570
+ var NAVIGATE_TIMEOUT_MS = 15e3;
10571
+ var HISTORY_TIMEOUT_MS = 15e3;
10572
+ function assertSafeNavigationUrl(raw) {
10573
+ const trimmed = (raw ?? "").trim();
10574
+ if (!trimmed) throw new WorkspaceError("Navigation URL is empty");
10575
+ let parsed;
10576
+ try {
10577
+ parsed = new URL(trimmed);
10578
+ } catch {
10579
+ throw new WorkspaceError(`Invalid URL: ${trimmed}`);
10580
+ }
10581
+ if (parsed.protocol === "about:") {
10582
+ if (parsed.href === "about:blank") return "about:blank";
10583
+ throw new WorkspaceError(`Unsupported URL scheme: ${parsed.protocol} (only about:blank is allowed)`);
10584
+ }
10585
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
10586
+ throw new WorkspaceError(`Unsupported URL scheme: ${parsed.protocol} (only http/https/about:blank are allowed)`);
10587
+ }
10588
+ return parsed.href;
10589
+ }
10590
+ var WorkspaceController = class {
10591
+ constructor(sessionManager) {
10592
+ this.sessionManager = sessionManager;
10593
+ }
10594
+ sessionManager;
10595
+ resolver;
10596
+ handoffProbe;
10597
+ /**
10598
+ * Stable opaque IDs per tab. Keyed by the XBPage instance — the CDP
10599
+ * driver's `context.pages()` returns the same wrapper objects on every
10600
+ * call, so identity holds across snapshots. IDs die with the page (WeakMap)
10601
+ * and with the controller (daemon restart) — clients holding a stale ID
10602
+ * get a "tab no longer exists" error and re-pull state.
10603
+ */
10604
+ tabIds = /* @__PURE__ */ new WeakMap();
10605
+ tabIdFor(page) {
10606
+ let id = this.tabIds.get(page);
10607
+ if (!id) {
10608
+ id = "tab-" + randomUUID2().slice(0, 8);
10609
+ this.tabIds.set(page, id);
10610
+ }
10611
+ return id;
10612
+ }
10613
+ /**
10614
+ * Per-session mutation serialization. Overlapping viewers (or a racing
10615
+ * navigate + tab close) must not interleave: two concurrent closes on a
10616
+ * two-tab session could both pass the last-tab guard and leave the session
10617
+ * pageless, and a stale select index could rebind onto a just-closed page.
10618
+ * Every mutation re-snapshots `context.pages()` at its turn, so running
10619
+ * them one-at-a-time per session keeps the last-tab invariant and index
10620
+ * freshness. Reads (`workspace_request`) stay unserialized.
10621
+ */
10622
+ mutationQueues = /* @__PURE__ */ new Map();
10623
+ /** Host (daemon) injects session ownership lookup. */
10624
+ setResolver(resolver) {
10625
+ this.resolver = resolver;
10626
+ }
10627
+ /** Host (daemon) injects the waitForHuman handoff-waiting probe. */
10628
+ setHandoffProbe(probe) {
10629
+ this.handoffProbe = probe;
10630
+ }
10631
+ /** Runs mutations one at a time per session; rejections propagate to caller. */
10632
+ enqueueMutation(sessionId, task) {
10633
+ const prev = this.mutationQueues.get(sessionId) ?? Promise.resolve();
10634
+ const run = prev.catch(() => {
10635
+ }).then(task);
10636
+ const tail = run.then(() => void 0, () => void 0);
10637
+ this.mutationQueues.set(sessionId, tail);
10638
+ tail.finally(() => {
10639
+ if (this.mutationQueues.get(sessionId) === tail) this.mutationQueues.delete(sessionId);
10640
+ }).catch(() => {
10641
+ });
10642
+ return run;
10643
+ }
10644
+ // -----------------------------------------------------------------------
10645
+ // Dispatch
10646
+ // -----------------------------------------------------------------------
10647
+ async dispatch(ctx) {
10648
+ try {
10649
+ switch (ctx.message.type) {
10650
+ case "workspace_request":
10651
+ await this.onRequest(ctx);
10652
+ return;
10653
+ case "workspace_navigate":
10654
+ await this.onNavigate(ctx);
10655
+ return;
10656
+ case "workspace_history":
10657
+ await this.onHistory(ctx);
10658
+ return;
10659
+ case "workspace_tab":
10660
+ await this.onTab(ctx);
10661
+ return;
10662
+ default:
10663
+ this.replyError(ctx, `Unknown workspace message type: ${ctx.message.type}`);
10664
+ }
10665
+ } catch (err) {
10666
+ if (err instanceof WorkspaceError) {
10667
+ this.replyError(ctx, err.message);
10668
+ return;
10669
+ }
10670
+ this.replyError(ctx, err instanceof Error ? err.message : String(err));
10671
+ }
10672
+ }
10673
+ // -----------------------------------------------------------------------
10674
+ // Handlers
10675
+ // -----------------------------------------------------------------------
10676
+ async onRequest(ctx) {
10677
+ const resolved = this.resolveSession(ctx);
10678
+ const state = await this.buildState(resolved);
10679
+ ctx.sendToClient(ctx.clientId, state);
10680
+ }
10681
+ async onNavigate(ctx) {
10682
+ if (!ctx.sessionId) {
10683
+ throw new WorkspaceError('Not bound to a session. Connect via /preview/<sessionId> or send {"type":"bind"} first.');
10684
+ }
10685
+ await this.enqueueMutation(ctx.sessionId, async () => {
10686
+ const msg = ctx.message;
10687
+ const resolved = this.resolveSession(ctx);
10688
+ this.requireManaged(resolved);
10689
+ const url = assertSafeNavigationUrl(typeof msg.url === "string" ? msg.url : "");
10690
+ await resolved.handle.page.goto(url, { waitUntil: "domcontentloaded", timeout: NAVIGATE_TIMEOUT_MS });
10691
+ ctx.sendToTrustedSessionClients(resolved.sessionId, await this.buildState(resolved));
10692
+ });
10693
+ }
10694
+ async onHistory(ctx) {
10695
+ if (!ctx.sessionId) {
10696
+ throw new WorkspaceError('Not bound to a session. Connect via /preview/<sessionId> or send {"type":"bind"} first.');
10697
+ }
10698
+ await this.enqueueMutation(ctx.sessionId, async () => {
10699
+ const msg = ctx.message;
10700
+ const resolved = this.resolveSession(ctx);
10701
+ this.requireManaged(resolved);
10702
+ const action = msg.action;
10703
+ const page = resolved.handle.page;
10704
+ if (action === "back") {
10705
+ await page.goBack({ timeout: HISTORY_TIMEOUT_MS });
10706
+ } else if (action === "forward") {
10707
+ await page.goForward({ timeout: HISTORY_TIMEOUT_MS });
10708
+ } else if (action === "reload") {
10709
+ await page.reload({ timeout: HISTORY_TIMEOUT_MS });
10710
+ } else {
10711
+ throw new WorkspaceError(`Invalid history action: ${String(action)} (expected back | forward | reload)`);
10712
+ }
10713
+ ctx.sendToTrustedSessionClients(resolved.sessionId, await this.buildState(resolved));
10714
+ });
10715
+ }
10716
+ async onTab(ctx) {
10717
+ if (!ctx.sessionId) {
10718
+ throw new WorkspaceError('Not bound to a session. Connect via /preview/<sessionId> or send {"type":"bind"} first.');
10719
+ }
10720
+ await this.enqueueMutation(ctx.sessionId, async () => {
10721
+ const msg = ctx.message;
10722
+ const resolved = this.resolveSession(ctx);
10723
+ this.requireManaged(resolved);
10724
+ const context = resolved.handle.context;
10725
+ if (!context) {
10726
+ throw new WorkspaceError("Session has no owned browser context; workspace tab controls are unavailable");
10727
+ }
10728
+ switch (msg.action) {
10729
+ case "new":
10730
+ await this.tabNew(ctx, resolved, context);
10731
+ return;
10732
+ case "select":
10733
+ await this.tabSelect(ctx, resolved, context, msg);
10734
+ return;
10735
+ case "close":
10736
+ await this.tabClose(ctx, resolved, context, msg);
10737
+ return;
10738
+ default:
10739
+ throw new WorkspaceError(`Invalid tab action: ${String(msg.action)} (expected new | select | close)`);
10740
+ }
10741
+ });
10742
+ }
10743
+ // -----------------------------------------------------------------------
10744
+ // Tab operations (mirror src/commands/tab.ts semantics)
10745
+ // -----------------------------------------------------------------------
10746
+ async tabNew(ctx, resolved, context) {
10747
+ const newPage = await context.newPage();
10748
+ this.rebindActivePage(resolved, newPage);
10749
+ ctx.sendToTrustedSessionClients(resolved.sessionId, await this.buildState(resolved));
10750
+ }
10751
+ /**
10752
+ * Resolves the target page for select/close.
10753
+ *
10754
+ * `tabId` (stable opaque ID from workspace_state) is the preferred path:
10755
+ * it names the exact tab regardless of index shifts caused by earlier
10756
+ * queued closes, and a stale ID (tab already closed) is rejected instead
10757
+ * of silently acting on whatever now sits at that position. `index` is
10758
+ * the legacy fallback resolved against the CURRENT snapshot (kept for
10759
+ * mock/test clients). If both are supplied, tabId wins.
10760
+ */
10761
+ resolveTabTarget(pages, activePage, action, msg) {
10762
+ const tabId = typeof msg.tabId === "string" ? msg.tabId.trim() : "";
10763
+ if (tabId) {
10764
+ const target = pages.find((pg) => this.tabIds.get(pg) === tabId);
10765
+ if (!target) {
10766
+ throw new WorkspaceError(
10767
+ `Tab ${tabId} no longer exists (it may have been closed). Send workspace_request to refresh the tab list.`
10768
+ );
10769
+ }
10770
+ return target;
10771
+ }
10772
+ if (typeof msg.index === "number") {
10773
+ if (!Number.isInteger(msg.index) || msg.index < 0 || msg.index >= pages.length) {
10774
+ throw new WorkspaceError(`Invalid tab index: ${String(msg.index)}. Valid range: 0-${Math.max(0, pages.length - 1)}`);
10775
+ }
10776
+ return pages[msg.index];
10777
+ }
10778
+ if (action === "close") return activePage;
10779
+ throw new WorkspaceError("workspace_tab select requires a tabId (preferred) or an integer index");
10780
+ }
10781
+ async tabSelect(ctx, resolved, context, msg) {
10782
+ const pages = context.pages();
10783
+ const targetPage = this.resolveTabTarget(pages, resolved.handle.page, "select", msg);
10784
+ await targetPage.bringToFront().catch(() => {
10785
+ });
10786
+ for (let i = 0; i < 5; i++) {
10787
+ const okProbe = await targetPage.evaluate("1").then(() => true, () => false);
10788
+ if (okProbe) break;
10789
+ await new Promise((r) => setTimeout(r, 300));
10790
+ }
10791
+ try {
10792
+ const mouse = targetPage.mouse;
10793
+ if (mouse) await mouse.move(1, 1).catch(() => {
10794
+ });
10795
+ } catch {
10796
+ }
10797
+ this.rebindActivePage(resolved, targetPage);
10798
+ ctx.sendToTrustedSessionClients(resolved.sessionId, await this.buildState(resolved));
10799
+ }
10800
+ async tabClose(ctx, resolved, context, msg) {
10801
+ const pages = context.pages();
10802
+ const activePage = resolved.handle.page;
10803
+ const pageToClose = this.resolveTabTarget(pages, activePage, "close", msg);
10804
+ if (pages.length <= 1) {
10805
+ throw new WorkspaceError("Cannot close the last remaining tab");
10806
+ }
10807
+ const isActivePage = pageToClose === activePage;
10808
+ await pageToClose.close();
10809
+ const remainingPages = context.pages();
10810
+ if (remainingPages.length === 0) {
10811
+ throw new WorkspaceError("All tabs closed; the session needs a page");
10812
+ }
10813
+ if (isActivePage) {
10814
+ const closeIndex = pages.indexOf(pageToClose);
10815
+ const switchIndex = closeIndex >= 0 && closeIndex < remainingPages.length ? closeIndex : remainingPages.length - 1;
10816
+ this.rebindActivePage(resolved, remainingPages[switchIndex]);
10817
+ }
10818
+ ctx.sendToTrustedSessionClients(resolved.sessionId, await this.buildState(resolved));
10819
+ }
10820
+ // -----------------------------------------------------------------------
10821
+ // State building
10822
+ // -----------------------------------------------------------------------
10823
+ /**
10824
+ * Builds the `workspace_state` payload for a session.
10825
+ *
10826
+ * - Managed sessions enumerate the full context tab list.
10827
+ * - Externally-owned sessions (or standalone mode without a resolver) get
10828
+ * a read-only single-page state describing only the bound page — the
10829
+ * user's other tabs are never enumerated.
10830
+ */
10831
+ async buildState(resolved) {
10832
+ const { sessionId, handle } = resolved;
10833
+ const context = handle.context;
10834
+ const handoffWaiting = this.handoffProbe?.(sessionId) === true ? { handoffWaiting: true } : {};
10835
+ if (!handle.managed || !context) {
10836
+ const page = handle.page;
10837
+ if (!page) {
10838
+ return { type: "workspace_state", sessionId, tabs: [], activeIndex: -1, readOnly: true, ...handoffWaiting };
10839
+ }
10840
+ const title = await page.title().catch(() => "");
10841
+ return {
10842
+ type: "workspace_state",
10843
+ sessionId,
10844
+ tabs: [{ id: this.tabIdFor(page), index: 0, url: page.url(), ...title ? { title } : {} }],
10845
+ activeIndex: 0,
10846
+ readOnly: true,
10847
+ ...handoffWaiting
10848
+ };
10849
+ }
10850
+ const pages = context.pages();
10851
+ const activePage = handle.page;
10852
+ let activeIndex = pages.findIndex((pg) => pg === activePage);
10853
+ const tabs = [];
10854
+ for (let i = 0; i < pages.length; i++) {
10855
+ const url = pages[i].url();
10856
+ const title = await pages[i].title().catch(() => "");
10857
+ if (pages[i] === activePage) activeIndex = i;
10858
+ tabs.push({ id: this.tabIdFor(pages[i]), index: i, url, ...title ? { title } : {} });
10859
+ }
10860
+ if (activeIndex < 0 && tabs.length > 0) {
10861
+ activeIndex = 0;
10862
+ }
10863
+ return { type: "workspace_state", sessionId, tabs, activeIndex, ...handoffWaiting };
10864
+ }
10865
+ // -----------------------------------------------------------------------
10866
+ // Session resolution / guards
10867
+ // -----------------------------------------------------------------------
10868
+ /**
10869
+ * Resolves the client's bound session. Bound session ownership: the client
10870
+ * must be bound to a registered session; operations never touch sessions
10871
+ * other than the one this client is bound to.
10872
+ */
10873
+ resolveSession(ctx) {
10874
+ if (!ctx.sessionId) {
10875
+ throw new WorkspaceError('Not bound to a session. Connect via /preview/<sessionId> or send {"type":"bind"} first.');
10876
+ }
10877
+ const resolved = this.resolveBySessionId(ctx.sessionId);
10878
+ if (!resolved) {
10879
+ throw new WorkspaceError(`Session "${ctx.sessionId}" not found`);
10880
+ }
10881
+ return resolved;
10882
+ }
10883
+ /**
10884
+ * SessionId → handle. Prefers the host resolver (daemon, authoritative
10885
+ * ManagedSession); falls back to the WS-registered page as a read-only
10886
+ * single-page session (standalone viewer without a resolver).
10887
+ */
10888
+ resolveBySessionId(sessionId) {
10889
+ const handle = this.resolver?.(sessionId);
10890
+ if (handle?.page) {
10891
+ return { sessionId, handle };
10892
+ }
10893
+ const wsPage = this.sessionManager.getPageForSession(sessionId);
10894
+ if (wsPage) {
10895
+ return { sessionId, handle: { page: wsPage, context: null, managed: false } };
10896
+ }
10897
+ return void 0;
10898
+ }
10899
+ /**
10900
+ * Pushes a fresh `workspace_state` to the session's viewers via the
10901
+ * supplied trusted-targeting send (never the legacy broadcast — tab
10902
+ * metadata must not reach untrusted clients). Used by WSServer on
10903
+ * `page-switched` so panels stay in sync when the active tab changes
10904
+ * out-of-band (e.g. a CLI `tab switch` command).
10905
+ */
10906
+ async pushState(sessionId, send) {
10907
+ const resolved = this.resolveBySessionId(sessionId);
10908
+ if (!resolved) return;
10909
+ send(sessionId, await this.buildState(resolved));
10910
+ }
10911
+ requireManaged(resolved) {
10912
+ if (!resolved.handle.managed || !resolved.handle.context) {
10913
+ throw new WorkspaceError(
10914
+ `Session "${resolved.sessionId}" is attached to an external browser; workspace navigation and tab controls are read-only. Reopen the session as a managed (self-launched) session to control it.`
10915
+ );
10916
+ }
10917
+ }
10918
+ // -----------------------------------------------------------------------
10919
+ // Active page coherence
10920
+ // -----------------------------------------------------------------------
10921
+ /**
10922
+ * Rebinds the session's active page after a tab switch/new/close using the
10923
+ * existing lifecycle helpers:
10924
+ * 1. host-side `setActivePage` (browser.ts) updates the ManagedSession,
10925
+ * 2. SessionManager re-registration moves the screencast + element monitor
10926
+ * to the new page and emits `page-switched` (viewer follows the tab).
10927
+ */
10928
+ rebindActivePage(resolved, page) {
10929
+ resolved.handle.setActivePage?.(page);
10930
+ resolved.handle.page = page;
10931
+ this.sessionManager.registerSession(resolved.sessionId, page, void 0);
10932
+ }
10933
+ // -----------------------------------------------------------------------
10934
+ // Replies
10935
+ // -----------------------------------------------------------------------
10936
+ replyError(ctx, message) {
10937
+ ctx.sendToClient(ctx.clientId, { type: "workspace_error", message });
10938
+ }
10939
+ };
10940
+
8387
10941
  // src/websocket-server.ts
10942
+ function extractPeerInfo(req) {
10943
+ const r = req;
10944
+ if (!r) return void 0;
10945
+ const remoteAddress = typeof r.socket?.remoteAddress === "string" ? r.socket.remoteAddress : void 0;
10946
+ const origin = typeof r.headers?.origin === "string" ? r.headers.origin : void 0;
10947
+ if (remoteAddress === void 0 && origin === void 0) return void 0;
10948
+ return { ...remoteAddress !== void 0 ? { remoteAddress } : {}, ...origin !== void 0 ? { origin } : {} };
10949
+ }
8388
10950
  var WSServer = class extends EventEmitter2 {
8389
10951
  port;
8390
10952
  host;
@@ -8394,6 +10956,7 @@ var WSServer = class extends EventEmitter2 {
8394
10956
  streamCoordinator;
8395
10957
  sessionManager;
8396
10958
  messageDispatcher;
10959
+ workspaceController;
8397
10960
  constructor(config = {}) {
8398
10961
  super();
8399
10962
  this.port = config.port ?? 9223;
@@ -8402,8 +10965,24 @@ var WSServer = class extends EventEmitter2 {
8402
10965
  this.sessionManager = new SessionManager();
8403
10966
  this.sessionManager.setStreamCoordinator(this.streamCoordinator);
8404
10967
  this.messageDispatcher = new MessageDispatcher(this.streamCoordinator, this.sessionManager);
10968
+ this.workspaceController = new WorkspaceController(this.sessionManager);
8405
10969
  this.setupSessionManagerEvents();
8406
10970
  }
10971
+ /**
10972
+ * Injects the session ownership lookup used by workspace controls
10973
+ * (navigate / history / tab). The daemon maps WS sessionIds to
10974
+ * ManagedSessions; without a resolver the workspace is read-only.
10975
+ */
10976
+ setWorkspaceSessionResolver(resolver) {
10977
+ this.workspaceController.setResolver(resolver);
10978
+ }
10979
+ /**
10980
+ * Injects the waitForHuman handoff probe so workspace state can flag
10981
+ * `handoffWaiting` for late-connecting/reconnecting viewers.
10982
+ */
10983
+ setWorkspaceHandoffProbe(probe) {
10984
+ this.workspaceController.setHandoffProbe(probe);
10985
+ }
8407
10986
  // -----------------------------------------------------------------------
8408
10987
  // SessionManager event wiring
8409
10988
  // -----------------------------------------------------------------------
@@ -8425,8 +11004,10 @@ var WSServer = class extends EventEmitter2 {
8425
11004
  this.emit("screencast-stopped", sessionId);
8426
11005
  });
8427
11006
  this.sessionManager.on("page-switched", (sessionId, page) => {
8428
- this.streamCoordinator.clearLastFrame();
11007
+ this.streamCoordinator.clearLastFrame(sessionId);
8429
11008
  this.broadcastToSession(sessionId, { type: "navigation", url: page.url(), title: "" });
11009
+ this.workspaceController.pushState(sessionId, (sid, message) => this.sendWorkspaceToSessionClients(sid, message)).catch(() => {
11010
+ });
8430
11011
  });
8431
11012
  }
8432
11013
  // -----------------------------------------------------------------------
@@ -8466,7 +11047,7 @@ var WSServer = class extends EventEmitter2 {
8466
11047
  });
8467
11048
  }
8468
11049
  this.sessionManager.incrementClientCount(sessionId);
8469
- if (this.streamCoordinator.getLastFrameViewport()) {
11050
+ if (this.streamCoordinator.getLastFrameViewport(sessionId)) {
8470
11051
  this.streamCoordinator.replayLastFrame(sessionId).catch(() => {
8471
11052
  });
8472
11053
  }
@@ -8497,7 +11078,7 @@ var WSServer = class extends EventEmitter2 {
8497
11078
  if (sc?.page) {
8498
11079
  (async () => {
8499
11080
  try {
8500
- const vp = this.streamCoordinator.getLastFrameViewport() || sc.page.viewportSize() || await sc.page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
11081
+ const vp = this.streamCoordinator.getLastFrameViewport(sessionId) || sc.page.viewportSize() || await sc.page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
8501
11082
  this.sendToClient(clientId, {
8502
11083
  type: "status",
8503
11084
  data: { status: "connected", sessionId, viewport: vp ?? void 0 }
@@ -8557,7 +11138,7 @@ var WSServer = class extends EventEmitter2 {
8557
11138
  this.isRunning = false;
8558
11139
  return;
8559
11140
  }
8560
- return new Promise((resolve8, reject) => {
11141
+ return new Promise((resolve10, reject) => {
8561
11142
  this.wsServer.close((err) => {
8562
11143
  if (err) {
8563
11144
  reject(err);
@@ -8565,7 +11146,7 @@ var WSServer = class extends EventEmitter2 {
8565
11146
  this.wsServer = null;
8566
11147
  this.isRunning = false;
8567
11148
  this.emit("stopped");
8568
- resolve8();
11149
+ resolve10();
8569
11150
  }
8570
11151
  });
8571
11152
  });
@@ -8574,10 +11155,11 @@ var WSServer = class extends EventEmitter2 {
8574
11155
  // Connection handler
8575
11156
  // -----------------------------------------------------------------------
8576
11157
  setupConnectionHandler(wsServer) {
8577
- wsServer.on("connection", (ws, _req, sessionIdFromUrl) => {
11158
+ wsServer.on("connection", (ws, req, sessionIdFromUrl) => {
8578
11159
  const wsLike = ws;
8579
11160
  const clientId = crypto.randomUUID();
8580
- const client = { id: clientId, ws: wsLike };
11161
+ const peer = extractPeerInfo(req);
11162
+ const client = { id: clientId, ws: wsLike, ...peer ? { peer } : {} };
8581
11163
  this.sessionManager.addClient(client);
8582
11164
  if (sessionIdFromUrl) {
8583
11165
  client.requestedSessionId = sessionIdFromUrl;
@@ -8627,7 +11209,7 @@ var WSServer = class extends EventEmitter2 {
8627
11209
  if (initPage) {
8628
11210
  (async () => {
8629
11211
  try {
8630
- const vp = this.streamCoordinator.getLastFrameViewport() || initPage.viewportSize() || await initPage.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
11212
+ const vp = this.streamCoordinator.getLastFrameViewport(initSessionId) || initPage.viewportSize() || await initPage.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
8631
11213
  this.sendToClient(clientId, {
8632
11214
  type: "status",
8633
11215
  data: { status: "connected", sessionId: initSessionId || void 0, viewport: vp ?? void 0 }
@@ -8680,6 +11262,22 @@ var WSServer = class extends EventEmitter2 {
8680
11262
  });
8681
11263
  return;
8682
11264
  }
11265
+ if (msg.type === "workspace_request" || msg.type === "workspace_navigate" || msg.type === "workspace_history" || msg.type === "workspace_tab") {
11266
+ const trust = checkWorkspaceTrust(this.sessionManager.getClient(clientId)?.peer, this.port);
11267
+ if (!trust.ok) {
11268
+ this.sendToClient(clientId, { type: "workspace_error", message: trust.reason });
11269
+ return;
11270
+ }
11271
+ await this.workspaceController.dispatch({
11272
+ clientId,
11273
+ sessionId,
11274
+ message: msg,
11275
+ sendToClient: (id, message) => this.sendToClient(id, message),
11276
+ sendToTrustedSessionClients: (sid, message) => this.sendWorkspaceToSessionClients(sid, message),
11277
+ broadcastToSession: (sid, message) => this.broadcastToSession(sid, message)
11278
+ });
11279
+ return;
11280
+ }
8683
11281
  const ctx = {
8684
11282
  clientId,
8685
11283
  sessionId,
@@ -8721,6 +11319,21 @@ var WSServer = class extends EventEmitter2 {
8721
11319
  this.sendToClient(clientId, message);
8722
11320
  }
8723
11321
  }
11322
+ /**
11323
+ * Sends a workspace message ONLY to the session's trusted clients
11324
+ * (loopback peer / loopback Viewer origin, per checkWorkspaceTrust).
11325
+ * `workspace_state` carries tab titles/URLs of managed sessions and must
11326
+ * never be broadcast to legacy LAN clients bound to the same session.
11327
+ */
11328
+ sendWorkspaceToSessionClients(sessionId, message) {
11329
+ const clients = this.sessionManager.getSessionClients(sessionId);
11330
+ if (!clients) return;
11331
+ for (const clientId of clients) {
11332
+ const peer = this.sessionManager.getClient(clientId)?.peer;
11333
+ if (!checkWorkspaceTrust(peer, this.port).ok) continue;
11334
+ this.sendToClient(clientId, message);
11335
+ }
11336
+ }
8724
11337
  broadcast(message) {
8725
11338
  for (const clientId of this.sessionManager.getAllClientIds()) {
8726
11339
  this.sendToClient(clientId, message);
@@ -8949,7 +11562,7 @@ function getCompanyType(domain) {
8949
11562
  // src/data-collector/storage.ts
8950
11563
  import fs4 from "fs/promises";
8951
11564
  import path3 from "path";
8952
- import { createHash } from "crypto";
11565
+ import { createHash as createHash2 } from "crypto";
8953
11566
  var DataStorage = class {
8954
11567
  config;
8955
11568
  basePath;
@@ -8974,7 +11587,7 @@ var DataStorage = class {
8974
11587
  );
8975
11588
  }
8976
11589
  generateId(query, engine) {
8977
- const hash = createHash("sha256").update(`${engine}:${query}:${Date.now()}`).digest("hex");
11590
+ const hash = createHash2("sha256").update(`${engine}:${query}:${Date.now()}`).digest("hex");
8978
11591
  return hash.slice(0, 16);
8979
11592
  }
8980
11593
  async initialize() {
@@ -9072,8 +11685,8 @@ var DataStorage = class {
9072
11685
  const engines = await fs4.readdir(enginesDir);
9073
11686
  for (const engine of engines) {
9074
11687
  const enginePath = path3.join(enginesDir, engine);
9075
- const stat = await fs4.stat(enginePath);
9076
- if (stat.isDirectory()) {
11688
+ const stat2 = await fs4.stat(enginePath);
11689
+ if (stat2.isDirectory()) {
9077
11690
  const engineResults = await this.loadEngineHistory(engine, limit);
9078
11691
  allResults.push(...engineResults);
9079
11692
  }
@@ -9207,8 +11820,8 @@ var DataStorage = class {
9207
11820
  const engines = await fs4.readdir(enginesDir);
9208
11821
  for (const engine of engines) {
9209
11822
  const enginePath = path3.join(enginesDir, engine);
9210
- const stat = await fs4.stat(enginePath);
9211
- if (stat.isDirectory()) {
11823
+ const stat2 = await fs4.stat(enginePath);
11824
+ if (stat2.isDirectory()) {
9212
11825
  const files = await fs4.readdir(enginePath);
9213
11826
  for (const file of files) {
9214
11827
  const filePath = path3.join(enginePath, file);
@@ -9726,8 +12339,8 @@ var DataCollector = class {
9726
12339
  }
9727
12340
  } catch (error) {
9728
12341
  const duration = Date.now() - startTime;
9729
- const errorMessage = error instanceof Error ? error.message : String(error);
9730
- errors.push(errorMessage);
12342
+ const errorMessage2 = error instanceof Error ? error.message : String(error);
12343
+ errors.push(errorMessage2);
9731
12344
  return {
9732
12345
  success: false,
9733
12346
  engine,
@@ -9824,7 +12437,7 @@ var DataCollector = class {
9824
12437
  return results;
9825
12438
  }
9826
12439
  async createBrowserContext() {
9827
- const { launch } = await import("./cdp-driver-GE6Y6LPI.js");
12440
+ const { launch } = await import("./cdp-driver-MJD7YIQI.js");
9828
12441
  const { browser } = await launch({
9829
12442
  headless: true,
9830
12443
  args: ["--no-sandbox", "--disable-setuid-sandbox"]
@@ -9837,7 +12450,7 @@ var DataCollector = class {
9837
12450
  return context;
9838
12451
  }
9839
12452
  sleep(ms) {
9840
- return new Promise((resolve8) => setTimeout(resolve8, ms));
12453
+ return new Promise((resolve10) => setTimeout(resolve10, ms));
9841
12454
  }
9842
12455
  async exportResults(outputPath, format = "json") {
9843
12456
  switch (format) {