@xbrowser/cli 1.34.0 → 1.36.0

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