@opentiny/webmcp-cli 0.0.6 → 0.0.9

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.
package/dist/bin.cjs CHANGED
@@ -6,6 +6,13 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
9
16
  var __copyProps = (to, from, except, desc) => {
10
17
  if (from && typeof from === "object" || typeof from === "function") {
11
18
  for (let key of __getOwnPropNames(from))
@@ -23,210 +30,37 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
30
  mod
24
31
  ));
25
32
 
26
- // src/bin.ts
27
- var import_fs3 = __toESM(require("fs"), 1);
28
- var import_path3 = __toESM(require("path"), 1);
29
- var import_os3 = __toESM(require("os"), 1);
30
- var import_commander = require("commander");
31
- var import_picocolors2 = __toESM(require("picocolors"), 1);
32
- var import_fs4 = require("fs");
33
- var import_path4 = require("path");
34
-
35
- // src/expand-file-refs.ts
36
- var import_fs = require("fs");
37
- var import_path = require("path");
38
- var import_url = require("url");
39
- var JSON_STRING_LITERAL = /"(?:[^"\\]|\\.)*"/g;
40
- var UNQUOTED_FILE_REF = /(?<![\\"])@(base64)?file:([^\s"',}\]]+)/g;
41
- var FILE_REF_PREFIX = /^@(base64)?file:(.+)$/s;
42
- function resolveFilePath(filePath, baseDir = process.cwd()) {
43
- let normalizedPath = filePath.trim();
44
- if (normalizedPath.startsWith('"') && normalizedPath.endsWith('"') || normalizedPath.startsWith("'") && normalizedPath.endsWith("'")) {
45
- normalizedPath = normalizedPath.slice(1, -1).trim();
46
- }
47
- if (normalizedPath.startsWith("file://")) {
48
- normalizedPath = (0, import_url.fileURLToPath)(normalizedPath);
49
- }
50
- if ((0, import_path.isAbsolute)(normalizedPath)) {
51
- return (0, import_path.normalize)(normalizedPath);
52
- }
53
- return (0, import_path.resolve)(baseDir, normalizedPath);
54
- }
55
- function decodeFilePath(rawPath) {
56
- return rawPath.replace(/\\\\/g, "\\");
57
- }
58
- function readFileRefContent(filePath, baseDir, base64) {
59
- const absPath = resolveFilePath(filePath, baseDir);
60
- let content;
61
- try {
62
- content = (0, import_fs.readFileSync)(absPath, "utf-8");
63
- } catch (e) {
64
- throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6\u5F15\u7528 "${filePath}" (${absPath}): ${e.message}`);
65
- }
66
- return base64 ? Buffer.from(content, "utf-8").toString("base64") : content;
67
- }
68
- function expandFileRefValue(rawInner, baseDir) {
69
- const match = rawInner.match(FILE_REF_PREFIX);
70
- if (!match) {
71
- return null;
72
- }
73
- const [, base64Flag, rawPath] = match;
74
- const filePath = decodeFilePath(rawPath);
75
- const value = readFileRefContent(filePath, baseDir, Boolean(base64Flag));
76
- return JSON.stringify(value);
77
- }
78
- function expandQuotedFileRefs(argsJson, baseDir) {
79
- return argsJson.replace(JSON_STRING_LITERAL, (jsonStringLiteral) => {
80
- const rawInner = jsonStringLiteral.slice(1, -1);
81
- const replacement = expandFileRefValue(rawInner, baseDir);
82
- return replacement ?? jsonStringLiteral;
83
- });
84
- }
85
- function expandUnquotedFileRefs(argsJson, baseDir) {
86
- return argsJson.replace(UNQUOTED_FILE_REF, (match, base64Flag, filePath) => {
87
- const value = readFileRefContent(filePath, baseDir, Boolean(base64Flag));
88
- return JSON.stringify(value);
89
- });
90
- }
91
- function expandFileRefs(argsJson, baseDir = process.cwd()) {
92
- const withQuotedExpanded = expandQuotedFileRefs(argsJson, baseDir);
93
- return expandUnquotedFileRefs(withQuotedExpanded, baseDir);
94
- }
95
- function getFileBaseDir(fileOption) {
96
- if (!fileOption) {
97
- return process.cwd();
98
- }
99
- return (0, import_path.dirname)((0, import_path.resolve)(process.cwd(), fileOption));
100
- }
101
-
102
- // src/parse-run-args.ts
103
- var import_json5 = __toESM(require("json5"), 1);
104
- function cleanJsonString(str) {
105
- let cleaned = str.trim();
106
- if (cleaned.startsWith("'") && cleaned.endsWith("'")) {
107
- cleaned = cleaned.slice(1, -1).trim();
108
- }
109
- return cleaned;
110
- }
111
- function looksLikeObjectBody(raw) {
112
- return /^("?[\w-]+"?\s*:)/.test(raw);
113
- }
114
- function joinShellArgs(args) {
115
- const cleaned = args.map(cleanJsonString);
116
- const first = cleaned[0] ?? "";
117
- if (first.startsWith("{")) {
118
- return cleaned.join(" ");
119
- }
120
- if (looksLikeObjectBody(first)) {
121
- let joined = cleaned.join(" ");
122
- if (!joined.startsWith("{")) {
123
- joined = `{${joined}}`;
124
- }
125
- if (!joined.endsWith("}")) {
126
- joined = `${joined}}`;
127
- }
128
- return joined;
33
+ // src/browser.ts
34
+ function getCdpPort() {
35
+ const raw = process.env.WEBMCP_CDP_PORT;
36
+ if (raw) {
37
+ const port = Number.parseInt(raw, 10);
38
+ if (Number.isFinite(port) && port > 0) return port;
129
39
  }
130
- return cleaned.join(" ");
131
- }
132
- function insertMissingCommas(raw) {
133
- return raw.replace(/"(\s+)("?[\w-]+"?\s*:)/g, '",$2');
134
- }
135
- function quoteUnquotedStringValues(raw) {
136
- return raw.replace(
137
- /([{,]\s*(?:"([^"]+)"|([\w-]+))\s*:\s*)(?!"@(?:base64)?file:|"|true|false|null|-?\d|\{|\[)([^",}\]]+?)(?=\s*[,}])/g,
138
- (_match, prefix, _quotedKey, _unquotedKey, value) => {
139
- const trimmed = value.trim();
140
- if (/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(trimmed)) {
141
- return prefix + trimmed;
142
- }
143
- return prefix + JSON.stringify(trimmed);
144
- }
145
- );
40
+ return 9222;
146
41
  }
147
- function normalizeShellDamagedJson(raw) {
148
- let normalized = raw.trim();
149
- normalized = insertMissingCommas(normalized);
150
- normalized = quoteUnquotedStringValues(normalized);
151
- return normalized;
42
+ function getWorkspaceDir() {
43
+ return process.env.WEBMCP_WORKSPACE || import_path2.default.join(import_os.default.homedir(), ".webmcp_chrome_profile");
152
44
  }
153
- function buildArgsFromKeyValuePairs(args) {
154
- const obj = {};
155
- for (const pair of args) {
156
- const index = pair.indexOf("=");
157
- if (index === -1) {
158
- throw new Error(`\u65E0\u6548\u7684\u53C2\u6570\u683C\u5F0F "${pair}"\u3002\u8BF7\u4F7F\u7528 key=value\uFF0C\u6216 JSON / -f \u6587\u4EF6\u3002`);
159
- }
160
- const key = pair.substring(0, index).trim();
161
- let val = cleanJsonString(pair.substring(index + 1).trim());
162
- try {
163
- obj[key] = JSON.parse(val);
164
- } catch {
165
- obj[key] = val;
166
- }
167
- }
168
- return JSON.stringify(obj);
45
+ function shouldLaunchHeadless() {
46
+ if (process.env.WEBMCP_HEADLESS === "0") return false;
47
+ return process.env.WEBMCP_HEADLESS === "1" || process.env.CI === "true" || process.env.CI === "1";
169
48
  }
170
- function parseArgsJson(raw) {
171
- const trimmed = cleanJsonString(raw);
49
+ function readActivePortFromProfile(userDataDir) {
172
50
  try {
173
- return JSON.stringify(import_json5.default.parse(trimmed));
174
- } catch (firstError) {
175
- const repaired = normalizeShellDamagedJson(trimmed);
176
- try {
177
- return JSON.stringify(import_json5.default.parse(repaired));
178
- } catch {
179
- const hint = `\u63D0\u793A\uFF1Abash \u4E2D JSON \u5FC5\u987B\u7528\u5355\u5F15\u53F7\u5305\u88F9\uFF0C\u4F8B\u5982 '{"title":"\u6807\u9898","content":"@base64file:./article.md"}'\uFF1B\u6216\u4F7F\u7528 key=value\uFF1Atitle=\u6807\u9898 content=@base64file:./article.md\uFF1B\u6216\u4F7F\u7528 -f args.json\u3002`;
180
- const message = firstError instanceof Error ? firstError.message : String(firstError);
181
- throw new Error(`\u53C2\u6570\u4E0D\u662F\u6709\u6548\u7684 JSON \u6216 JS \u5BF9\u8C61: ${message}
182
- ${hint}`);
183
- }
184
- }
185
- }
186
- function prepareRunArgsJson(args, fileContent, baseDir) {
187
- if (fileContent !== void 0) {
188
- const trimmed = fileContent.trim();
189
- if (!trimmed) {
190
- throw new Error("\u901A\u8FC7 -f/--file \u6307\u5B9A\u7684\u53C2\u6570\u6587\u4EF6\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A");
191
- }
192
- const expanded2 = expandFileRefs(trimmed, baseDir);
193
- return parseArgsJson(expanded2);
194
- }
195
- if (args.length === 0) {
196
- return "{}";
197
- }
198
- const joined = joinShellArgs(args);
199
- let raw = "";
200
- if (joined.startsWith("{") || looksLikeObjectBody(joined)) {
201
- raw = joined;
202
- } else if (args.every((arg) => arg.includes("="))) {
203
- raw = buildArgsFromKeyValuePairs(args);
204
- } else {
205
- raw = joined;
206
- }
207
- if (!raw.trim()) {
208
- throw new Error("\u672A\u63D0\u4F9B\u6709\u6548\u53C2\u6570");
51
+ const content = import_fs2.default.readFileSync(import_path2.default.join(userDataDir, "DevToolsActivePort"), "utf-8");
52
+ const port = parseInt(content.split("\n")[0].trim(), 10);
53
+ return Number.isFinite(port) && port > 0 ? port : null;
54
+ } catch {
55
+ return null;
209
56
  }
210
- const expanded = expandFileRefs(raw, baseDir);
211
- return parseArgsJson(expanded);
212
57
  }
213
-
214
- // src/browser.ts
215
- var import_puppeteer_core = __toESM(require("puppeteer-core"), 1);
216
- var import_picocolors = __toESM(require("picocolors"), 1);
217
- var import_fs2 = __toESM(require("fs"), 1);
218
- var import_os = __toESM(require("os"), 1);
219
- var import_path2 = __toESM(require("path"), 1);
220
- var import_http = __toESM(require("http"), 1);
221
- var import_child_process = require("child_process");
222
- var import_url2 = require("url");
223
- var import_meta = {};
224
- var __filename = (0, import_url2.fileURLToPath)(import_meta.url);
225
- var __dirname = import_path2.default.dirname(__filename);
226
- var CDP_PORT = 9222;
227
- var CDP_URL = `http://localhost:${CDP_PORT}`;
228
- function getWorkspaceDir() {
229
- return process.env.WEBMCP_WORKSPACE || import_path2.default.join(import_os.default.homedir(), ".webmcp_chrome_profile");
58
+ function candidateCdpBaseUrls(port) {
59
+ return [
60
+ `http://127.0.0.1:${port}`,
61
+ `http://[::1]:${port}`,
62
+ `http://localhost:${port}`
63
+ ];
230
64
  }
231
65
  function getLastTabIdFilePath() {
232
66
  return import_path2.default.join(getWorkspaceDir(), ".last-tab-id");
@@ -321,6 +155,13 @@ async function connectPuppeteer(browserBaseUrl, attempt = 1, maxAttempts = 3) {
321
155
  }
322
156
  }
323
157
  function getDefaultBrowserPath() {
158
+ const envPath = process.env.CHROME_PATH || process.env.WEBMCP_CHROME_PATH || process.env.PUPPETEER_EXECUTABLE_PATH;
159
+ if (envPath && import_fs2.default.existsSync(envPath)) {
160
+ return { path: envPath, name: "Chrome" };
161
+ }
162
+ if (envPath) {
163
+ console.log(import_picocolors.default.yellow(`\u6307\u5B9A\u7684\u6D4F\u89C8\u5668\u8DEF\u5F84\u4E0D\u5B58\u5728\uFF0C\u5C06\u56DE\u9000\u5230\u81EA\u52A8\u68C0\u6D4B: ${envPath}`));
164
+ }
324
165
  const platform = import_os.default.platform();
325
166
  if (platform === "darwin") {
326
167
  const chromePath = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
@@ -364,16 +205,30 @@ async function startBrowserInBackground() {
364
205
  if (!browserInfo || !import_fs2.default.existsSync(browserInfo.path)) {
365
206
  throw new Error("\u65E0\u6CD5\u5728\u7CFB\u7EDF\u4E2D\u627E\u5230 Chrome \u6216 Edge \u6D4F\u89C8\u5668\u7684\u9ED8\u8BA4\u5B89\u88C5\u8DEF\u5F84\u3002");
366
207
  }
367
- console.log(import_picocolors.default.yellow(`\u6B63\u5728\u542F\u52A8\u540E\u53F0 ${browserInfo.name} \u5B9E\u4F8B (\u7AEF\u53E3: ${CDP_PORT})...`));
368
- const userDataDir = process.env.WEBMCP_WORKSPACE || import_path2.default.join(import_os.default.homedir(), ".webmcp_chrome_profile");
208
+ const cdpPort = getCdpPort();
209
+ console.log(import_picocolors.default.yellow(`\u6B63\u5728\u542F\u52A8\u540E\u53F0 ${browserInfo.name} \u5B9E\u4F8B (\u7AEF\u53E3: ${cdpPort})...`));
210
+ const userDataDir = getWorkspaceDir();
211
+ if (!import_fs2.default.existsSync(userDataDir)) {
212
+ import_fs2.default.mkdirSync(userDataDir, { recursive: true });
213
+ }
214
+ try {
215
+ import_fs2.default.unlinkSync(import_path2.default.join(userDataDir, "DevToolsActivePort"));
216
+ } catch {
217
+ }
369
218
  const launchArgs = [
370
- `--remote-debugging-port=${CDP_PORT}`,
219
+ `--remote-debugging-port=${cdpPort}`,
371
220
  `--user-data-dir=${userDataDir}`,
372
221
  "--no-first-run",
373
222
  "--no-default-browser-check"
374
223
  ];
375
- if (import_os.default.platform() === "win32") {
376
- launchArgs.push("--remote-debugging-address=127.0.0.1");
224
+ if (shouldLaunchHeadless()) {
225
+ launchArgs.push(
226
+ "--headless=new",
227
+ "--no-sandbox",
228
+ "--disable-setuid-sandbox",
229
+ "--disable-gpu",
230
+ "--disable-dev-shm-usage"
231
+ );
377
232
  }
378
233
  const child = (0, import_child_process.spawn)(
379
234
  browserInfo.path,
@@ -384,15 +239,22 @@ async function startBrowserInBackground() {
384
239
  }
385
240
  );
386
241
  child.unref();
387
- const pollUrls = [`http://127.0.0.1:${CDP_PORT}/json/version`, `http://localhost:${CDP_PORT}/json/version`];
388
- for (let i = 0; i < 30; i++) {
389
- for (const url of pollUrls) {
390
- try {
391
- await httpGet(url, 1e3);
392
- console.log(import_picocolors.default.green(`${browserInfo.name} \u542F\u52A8\u5E76\u5C31\u7EEA\u3002`));
393
- await new Promise((resolve3) => setTimeout(resolve3, 500));
394
- return;
395
- } catch {
242
+ for (let i = 0; i < 40; i++) {
243
+ const ports = /* @__PURE__ */ new Set([cdpPort]);
244
+ const activePort = readActivePortFromProfile(userDataDir);
245
+ if (activePort) ports.add(activePort);
246
+ for (const port of ports) {
247
+ for (const baseUrl of candidateCdpBaseUrls(port)) {
248
+ try {
249
+ await httpGet(`${baseUrl}/json/version`, 1e3);
250
+ if (port !== cdpPort) {
251
+ console.log(import_picocolors.default.yellow(`\u68C0\u6D4B\u5230\u7AEF\u53E3 ${cdpPort} \u5DF2\u88AB\u5176\u4ED6\u7A0B\u5E8F\u5360\u7528\uFF0C${browserInfo.name} \u5DF2\u81EA\u52A8\u5207\u6362\u5230\u7AEF\u53E3 ${port}\u3002`));
252
+ }
253
+ console.log(import_picocolors.default.green(`${browserInfo.name} \u542F\u52A8\u5E76\u5C31\u7EEA\uFF08${baseUrl}\uFF09\u3002`));
254
+ await new Promise((resolve3) => setTimeout(resolve3, 500));
255
+ return baseUrl;
256
+ } catch {
257
+ }
396
258
  }
397
259
  }
398
260
  await new Promise((resolve3) => setTimeout(resolve3, 500));
@@ -400,13 +262,16 @@ async function startBrowserInBackground() {
400
262
  throw new Error(`${browserInfo.name} \u542F\u52A8\u8D85\u65F6\uFF0C\u65E0\u6CD5\u8FDE\u63A5\u5230 CDP \u7AEF\u53E3\u3002`);
401
263
  }
402
264
  async function connectBrowser() {
265
+ const userDataDir = getWorkspaceDir();
266
+ const cdpPort = getCdpPort();
267
+ const recordedPort = readActivePortFromProfile(userDataDir);
403
268
  const versionAddresses = [
404
- `http://127.0.0.1:${CDP_PORT}/json/version`,
405
- `http://localhost:${CDP_PORT}/json/version`
269
+ ...recordedPort && recordedPort !== cdpPort ? candidateCdpBaseUrls(recordedPort).map((u) => `${u}/json/version`) : [],
270
+ ...candidateCdpBaseUrls(cdpPort).map((u) => `${u}/json/version`)
406
271
  ];
407
272
  const existingUrl = await findAvailableCdpUrl(versionAddresses, 2);
408
273
  if (existingUrl) {
409
- console.log(import_picocolors.default.yellow(`connectBrowser: \u68C0\u6D4B\u5230\u7AEF\u53E3 ${CDP_PORT} \u5DF2\u5C31\u7EEA\uFF0C\u6B63\u5728\u8FDE\u63A5 ${existingUrl}...`));
274
+ console.log(import_picocolors.default.yellow(`connectBrowser: \u68C0\u6D4B\u5230\u7AEF\u53E3 ${cdpPort} \u5DF2\u5C31\u7EEA\uFF0C\u6B63\u5728\u8FDE\u63A5 ${existingUrl}...`));
410
275
  try {
411
276
  const browser = await connectPuppeteer(existingUrl);
412
277
  console.log(import_picocolors.default.green(`connectBrowser: \u6210\u529F\u8FDE\u63A5 ${existingUrl}`));
@@ -418,25 +283,22 @@ async function connectBrowser() {
418
283
  );
419
284
  }
420
285
  }
421
- console.log(import_picocolors.default.yellow(`connectBrowser: \u7AEF\u53E3 ${CDP_PORT} \u65E0\u54CD\u5E94\uFF0C\u6B63\u5728\u542F\u52A8\u65B0\u7684\u6D4F\u89C8\u5668\u5B9E\u4F8B...`));
286
+ console.log(import_picocolors.default.yellow(`connectBrowser: \u7AEF\u53E3 ${cdpPort} \u65E0\u54CD\u5E94\uFF0C\u6B63\u5728\u542F\u52A8\u65B0\u7684\u6D4F\u89C8\u5668\u5B9E\u4F8B...`));
287
+ let launchedUrl;
422
288
  try {
423
- await startBrowserInBackground();
289
+ launchedUrl = await startBrowserInBackground();
424
290
  } catch (launchError) {
425
291
  const msg = launchError instanceof Error ? launchError.message : String(launchError);
426
292
  console.error(import_picocolors.default.red(`\u65E0\u6CD5\u542F\u52A8\u6D4F\u89C8\u5668: ${msg}`));
427
293
  throw new Error("Browser launch failed.");
428
294
  }
429
- const launchedUrl = await findAvailableCdpUrl(versionAddresses, 5);
430
- if (!launchedUrl) {
431
- throw new Error(`\u65E0\u6CD5\u8FDE\u63A5\u5230\u6D4F\u89C8\u5668\uFF08\u7AEF\u53E3 ${CDP_PORT}\uFF09\uFF0C\u8BF7\u68C0\u67E5 Chrome/Edge \u662F\u5426\u5DF2\u5B89\u88C5\u3002`);
432
- }
433
295
  try {
434
296
  console.log(import_picocolors.default.yellow(`connectBrowser: \u6D4F\u89C8\u5668\u5DF2\u542F\u52A8\uFF0C\u6B63\u5728\u8FDE\u63A5 ${launchedUrl}...`));
435
297
  const browser = await connectPuppeteer(launchedUrl);
436
298
  console.log(import_picocolors.default.green(`connectBrowser: \u6210\u529F\u8FDE\u63A5 ${launchedUrl}`));
437
299
  return browser;
438
300
  } catch {
439
- throw new Error(`\u65E0\u6CD5\u8FDE\u63A5\u5230\u6D4F\u89C8\u5668\uFF08\u7AEF\u53E3 ${CDP_PORT}\uFF09\uFF0C\u8BF7\u68C0\u67E5 Chrome/Edge \u662F\u5426\u5DF2\u5B89\u88C5\u3002`);
301
+ throw new Error(`\u65E0\u6CD5\u8FDE\u63A5\u5230\u6D4F\u89C8\u5668\uFF08${launchedUrl}\uFF09\uFF0C\u8BF7\u68C0\u67E5 Chrome/Edge \u662F\u5426\u5DF2\u5B89\u88C5\u3002`);
440
302
  }
441
303
  }
442
304
  async function getPageTargetId(page) {
@@ -516,10 +378,11 @@ async function getTargetPage(browser, tabid) {
516
378
  }
517
379
  if (!targetPage) {
518
380
  try {
519
- const urls = [
520
- `http://localhost:${CDP_PORT}/json/list`,
521
- `http://127.0.0.1:${CDP_PORT}/json/list`
522
- ];
381
+ const workspaceDir = getWorkspaceDir();
382
+ const cdpPort = getCdpPort();
383
+ const recordedPort = readActivePortFromProfile(workspaceDir);
384
+ const ports = recordedPort && recordedPort !== cdpPort ? [recordedPort, cdpPort] : [cdpPort];
385
+ const urls = ports.flatMap((port) => candidateCdpBaseUrls(port).map((u) => `${u}/json/list`));
523
386
  let activeTargetId = null;
524
387
  for (const url of urls) {
525
388
  try {
@@ -544,103 +407,2734 @@ async function getTargetPage(browser, tabid) {
544
407
  } catch {
545
408
  }
546
409
  }
547
- if (!targetPage) {
548
- const lastTarget = pageTargets[pageTargets.length - 1];
549
- targetPage = await lastTarget.page();
410
+ if (!targetPage) {
411
+ const lastTarget = pageTargets[pageTargets.length - 1];
412
+ targetPage = await lastTarget.page();
413
+ }
414
+ }
415
+ if (!targetPage) {
416
+ throw new Error("\u65E0\u6CD5\u83B7\u53D6\u76EE\u6807\u9875\u9762");
417
+ }
418
+ await injectWebMCPPolyfillAndTools(targetPage);
419
+ return targetPage;
420
+ }
421
+ async function injectIntoPage(page) {
422
+ await injectWebMCPPolyfillAndTools(page);
423
+ }
424
+ async function injectWebMCPPolyfillAndTools(page) {
425
+ const polyfillReady = await page.evaluate(() => {
426
+ return !!window.__webmcpcli_init;
427
+ }).catch(() => false);
428
+ if (!polyfillReady) {
429
+ console.log(import_picocolors.default.cyan("\u5F53\u524D\u9875\u9762\u5C1A\u672A\u6CE8\u5165 WebMCP \u73AF\u5883\uFF0C\u6B63\u5728\u6267\u884C\u81EA\u52A8\u6CE8\u5165..."));
430
+ const injectScriptPath = import_path2.default.resolve(__dirname, "inject-bundle.js");
431
+ if (!import_fs2.default.existsSync(injectScriptPath)) {
432
+ throw new Error(`Cannot find inject-bundle.js at ${injectScriptPath}. Please ensure you run 'pnpm build:inject' first.`);
433
+ }
434
+ const scriptContent = import_fs2.default.readFileSync(injectScriptPath, "utf-8");
435
+ try {
436
+ await page.evaluate(scriptContent);
437
+ } catch (err) {
438
+ const msg = err instanceof Error ? err.message : String(err);
439
+ throw new Error("\u81EA\u52A8\u6CE8\u5165\u811A\u672C\u6267\u884C\u5931\u8D25: " + msg);
440
+ }
441
+ await page.waitForFunction(() => {
442
+ const mcp = navigator.modelContext;
443
+ return mcp && typeof mcp.registerTool === "function";
444
+ }, { timeout: 1e4 }).catch(() => {
445
+ console.warn("\u7B49\u5F85 WebMCP registerTool \u63A5\u53E3\u5C31\u7EEA\u8D85\u65F6\uFF0C\u6B63\u5728\u7EE7\u7EED\u6CE8\u5165...");
446
+ });
447
+ }
448
+ await injectDomainTools(page);
449
+ }
450
+ function getToolsBundleName(hostname) {
451
+ const normalized = hostname.split(":")[0].toLowerCase();
452
+ const toolsDir = import_path2.default.resolve(__dirname, "webmcp-tools");
453
+ if (!import_fs2.default.existsSync(toolsDir)) {
454
+ return null;
455
+ }
456
+ let files = [];
457
+ try {
458
+ files = import_fs2.default.readdirSync(toolsDir);
459
+ } catch {
460
+ return null;
461
+ }
462
+ const supportedDomains = files.filter((f) => f.endsWith(".js")).map((f) => f.slice(0, -3));
463
+ if (supportedDomains.includes(normalized)) {
464
+ return `webmcp-tools/${normalized}.js`;
465
+ }
466
+ for (const domain of supportedDomains) {
467
+ if (normalized.endsWith("." + domain)) {
468
+ return `webmcp-tools/${domain}.js`;
469
+ }
470
+ }
471
+ return null;
472
+ }
473
+ async function injectDomainTools(page) {
474
+ let hostname;
475
+ try {
476
+ const url = new URL(page.url());
477
+ hostname = url.hostname;
478
+ } catch {
479
+ return;
480
+ }
481
+ const bundleName = getToolsBundleName(hostname);
482
+ if (!bundleName) {
483
+ return;
484
+ }
485
+ const toolBundlePath = import_path2.default.resolve(__dirname, bundleName);
486
+ if (!import_fs2.default.existsSync(toolBundlePath)) {
487
+ return;
488
+ }
489
+ const bundleKey = bundleName.replace(/^webmcp-tools\//, "").replace(/\.js$/, "");
490
+ const flagKey = `__webmcptools_${bundleKey.replace(/[^a-zA-Z0-9]/g, "")}`;
491
+ const alreadyInjected = await page.evaluate((key) => !!window[key], flagKey).catch(() => false);
492
+ if (alreadyInjected) {
493
+ return;
494
+ }
495
+ console.log(import_picocolors.default.cyan(`\u68C0\u6D4B\u5230\u57DF\u540D ${hostname} \u6709\u9884\u7F6E\u5DE5\u5177\uFF0C\u6B63\u5728\u6CE8\u5165...`));
496
+ const toolScript = import_fs2.default.readFileSync(toolBundlePath, "utf-8");
497
+ try {
498
+ await page.evaluate(toolScript);
499
+ console.log(import_picocolors.default.green(`\u5DF2\u4E3A ${hostname} \u6CE8\u5165\u9884\u7F6E\u5DE5\u5177`));
500
+ } catch (err) {
501
+ const msg = err instanceof Error ? err.message : String(err);
502
+ console.warn(import_picocolors.default.yellow(`\u57DF\u540D\u5DE5\u5177\u6CE8\u5165\u5931\u8D25 (${hostname}): ${msg}`));
503
+ }
504
+ }
505
+ var import_puppeteer_core, import_picocolors, import_fs2, import_os, import_path2, import_http, import_child_process, import_url2, import_meta, __filename, __dirname;
506
+ var init_browser = __esm({
507
+ "src/browser.ts"() {
508
+ "use strict";
509
+ import_puppeteer_core = __toESM(require("puppeteer-core"), 1);
510
+ import_picocolors = __toESM(require("picocolors"), 1);
511
+ import_fs2 = __toESM(require("fs"), 1);
512
+ import_os = __toESM(require("os"), 1);
513
+ import_path2 = __toESM(require("path"), 1);
514
+ import_http = __toESM(require("http"), 1);
515
+ import_child_process = require("child_process");
516
+ import_url2 = require("url");
517
+ import_meta = {};
518
+ __filename = (0, import_url2.fileURLToPath)(import_meta.url);
519
+ __dirname = import_path2.default.dirname(__filename);
520
+ }
521
+ });
522
+
523
+ // package.json
524
+ var package_default;
525
+ var init_package = __esm({
526
+ "package.json"() {
527
+ package_default = {
528
+ name: "@opentiny/webmcp-cli",
529
+ version: "0.0.9",
530
+ type: "module",
531
+ description: "WebMCP CLI for AI Agents to interact with browser via Puppeteer",
532
+ main: "dist/index.js",
533
+ types: "dist/index.d.ts",
534
+ bin: {
535
+ "webmcp-cli": "./dist/bin.js"
536
+ },
537
+ files: [
538
+ "dist",
539
+ "README.md"
540
+ ],
541
+ scripts: {
542
+ dev: "tsup --watch",
543
+ "build:inject": "node scripts/build-inject.mjs",
544
+ build: "tsup && pnpm run build:inject",
545
+ prepublishOnly: "pnpm run build",
546
+ "link:global": "npm install -g .",
547
+ start: "node dist/bin.js",
548
+ test: "vitest run",
549
+ "test:watch": "vitest",
550
+ "test:browser": "vitest run --config vitest.e2e.config.ts"
551
+ },
552
+ keywords: [
553
+ "chrome",
554
+ "puppeteer",
555
+ "cli"
556
+ ],
557
+ license: "MIT",
558
+ author: "OpenTiny Team",
559
+ engines: {
560
+ node: ">=16"
561
+ },
562
+ publishConfig: {
563
+ access: "public"
564
+ },
565
+ dependencies: {
566
+ "@mcp-b/webmcp-polyfill": "catalog:",
567
+ "@modelcontextprotocol/sdk": "catalog:",
568
+ "@opentiny/next-sdk": "workspace:^",
569
+ "@page-agent/page-controller": "catalog:",
570
+ clipboardy: "^5.3.1",
571
+ commander: "^11.1.0",
572
+ json5: "^2.2.3",
573
+ marked: "^15.0.7",
574
+ picocolors: "^1.0.0",
575
+ "puppeteer-core": "^22.0.0",
576
+ ws: "^8.18.0",
577
+ zod: "^3.23.0"
578
+ },
579
+ devDependencies: {
580
+ "@types/node": "^20.0.0",
581
+ "@types/ws": "^8.5.10",
582
+ esbuild: "^0.25.0",
583
+ tsup: "^8.0.2",
584
+ tsx: "^4.0.0",
585
+ typescript: "^5.3.3",
586
+ vitest: "^4.1.10"
587
+ }
588
+ };
589
+ }
590
+ });
591
+
592
+ // src/mcp/tools.ts
593
+ var import_zod, BrowserStateInput, BrowserToolCallInput, BrowserTabsOpenInput, BrowserTabsCloseInput, BrowserTabsSwitchInput, BrowserTabsNavInput, BrowserSubAgentRunInput, BrowserSkillsListInput, BrowserSkillsReadInput;
594
+ var init_tools = __esm({
595
+ "src/mcp/tools.ts"() {
596
+ "use strict";
597
+ import_zod = require("zod");
598
+ BrowserStateInput = import_zod.z.object({
599
+ tabId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]).optional().describe(
600
+ "\u76EE\u6807 tab ID\u3002CDP \u6A21\u5F0F\u4E3A target UUID \u5B57\u7B26\u4E32\uFF1BWXT \u6A21\u5F0F\u4E3A Chrome tab ID \u6570\u503C\u3002\u4E0D\u4F20\u65F6\u4F7F\u7528\u5F53\u524D\u6D3B\u8DC3 tab\u3002"
601
+ )
602
+ });
603
+ BrowserToolCallInput = import_zod.z.object({
604
+ toolName: import_zod.z.string().describe("\u9875\u9762 WebMCP \u5DE5\u5177\u540D\u79F0\uFF08\u53EF\u4ECE browser_state \u8FD4\u56DE\u7684 webmcpTools \u5217\u8868\u4E2D\u83B7\u53D6\uFF09"),
605
+ toolArgs: import_zod.z.record(import_zod.z.unknown()).optional().describe("\u5DE5\u5177\u53C2\u6570\uFF0C\u4E0E\u5DE5\u5177\u7684 inputSchema \u5BF9\u9F50"),
606
+ tabId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]).optional().describe("\u76EE\u6807 tab ID\uFF0C\u4E0D\u4F20\u65F6\u4F7F\u7528\u5F53\u524D\u6D3B\u8DC3 tab")
607
+ });
608
+ BrowserTabsOpenInput = import_zod.z.object({
609
+ url: import_zod.z.string().url().refine((val) => /^https?:\/\//i.test(val), { message: "\u53EA\u5141\u8BB8\u6253\u5F00 http \u6216 https \u534F\u8BAE\u7684 URL" }).describe("\u8981\u6253\u5F00\u7684 URL\uFF08\u4EC5\u652F\u6301 http/https \u534F\u8BAE\uFF09")
610
+ });
611
+ BrowserTabsCloseInput = import_zod.z.object({
612
+ tabId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]).optional().describe(
613
+ "\u8981\u5173\u95ED\u7684 tab ID\uFF0C\u4E0D\u4F20\u65F6\u5173\u95ED\u5F53\u524D\u6D3B\u8DC3 tab"
614
+ )
615
+ });
616
+ BrowserTabsSwitchInput = import_zod.z.object({
617
+ tabId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]).describe(
618
+ "\u8981\u5207\u6362\u5230\u7684 tab ID\uFF08\u53EF\u4ECE browser_state \u8FD4\u56DE\u7684 tabs \u5217\u8868\u4E2D\u83B7\u53D6\uFF09"
619
+ ),
620
+ activateVisible: import_zod.z.boolean().optional().describe("\u662F\u5426\u5728\u524D\u53F0\u663E\u5F0F\u5207\u6362 Chrome \u53EF\u89C1\u6D3B\u52A8\u6807\u7B7E\uFF08\u4EC5 WXT \u6A21\u5F0F\u6709\u6548\uFF0C\u9ED8\u8BA4 false\uFF09")
621
+ });
622
+ BrowserTabsNavInput = import_zod.z.object({
623
+ tabId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]).optional().describe("\u76EE\u6807 tab ID\uFF0C\u4E0D\u4F20\u65F6\u4F7F\u7528\u5F53\u524D\u6D3B\u8DC3 tab")
624
+ });
625
+ BrowserSubAgentRunInput = import_zod.z.object({
626
+ instruction: import_zod.z.string().describe("\u8981\u59D4\u6258\u7ED9 Tiny Robot \u5B50\u4EE3\u7406\u6267\u884C\u7684\u9AD8\u5C42\u81EA\u7136\u8BED\u8A00\u4EFB\u52A1\u6307\u4EE4"),
627
+ tabId: import_zod.z.number().optional().describe("\u76EE\u6807 tab ID\uFF0C\u4E0D\u4F20\u65F6\u4F7F\u7528\u5F53\u524D\u6D3B\u8DC3 tab"),
628
+ maxSteps: import_zod.z.number().min(1).max(20).optional().describe("\u6700\u5927\u81EA\u4E3B\u89C4\u5212\u6267\u884C\u6B65\u6570\uFF08\u9ED8\u8BA4 8\uFF0C\u6700\u5927 20\uFF09")
629
+ });
630
+ BrowserSkillsListInput = import_zod.z.object({}).describe("\u83B7\u53D6\u5F53\u524D\u6D4F\u89C8\u5668\u6269\u5C55\u4E2D\u5DF2\u6CE8\u518C\u7684\u6240\u6709 Skills \u6280\u80FD\u5143\u6570\u636E\u5217\u8868");
631
+ BrowserSkillsReadInput = import_zod.z.object({
632
+ name: import_zod.z.string().describe("\u8981\u8BFB\u53D6\u7684\u6280\u80FD\u540D\u79F0\uFF08\u53EF\u4ECE browser_skills_list \u8FD4\u56DE\u7684\u5217\u8868\u4E2D\u83B7\u53D6\uFF09")
633
+ });
634
+ }
635
+ });
636
+
637
+ // src/adapters/cdp-adapter.ts
638
+ var cdp_adapter_exports = {};
639
+ __export(cdp_adapter_exports, {
640
+ CdpBrowserAdapter: () => CdpBrowserAdapter
641
+ });
642
+ var CdpBrowserAdapter;
643
+ var init_cdp_adapter = __esm({
644
+ "src/adapters/cdp-adapter.ts"() {
645
+ "use strict";
646
+ init_browser();
647
+ CdpBrowserAdapter = class {
648
+ browser = null;
649
+ async getBrowser() {
650
+ if (!this.browser) {
651
+ this.browser = await connectBrowser();
652
+ }
653
+ return this.browser;
654
+ }
655
+ async getState(tabId) {
656
+ const browser = await this.getBrowser();
657
+ const tabIdStr = tabId != null ? String(tabId) : void 0;
658
+ const page = await getTargetPage(browser, tabIdStr);
659
+ await injectIntoPage(page);
660
+ const state = await page.evaluate(async () => {
661
+ const url = document.URL;
662
+ const title = document.title;
663
+ const mcp = document.modelContext || navigator.modelContext;
664
+ let webmcpTools = [];
665
+ if (mcp && typeof mcp.getTools === "function") {
666
+ try {
667
+ const toolsResult = await mcp.getTools();
668
+ const list = toolsResult?.tools || toolsResult || [];
669
+ webmcpTools = list.filter((t) => t && typeof t.name === "string").map((t) => ({
670
+ name: t.name,
671
+ description: typeof t.description === "string" ? t.description.slice(0, 200) : void 0
672
+ }));
673
+ } catch {
674
+ webmcpTools = [];
675
+ }
676
+ }
677
+ return { url, title, webmcpTools };
678
+ });
679
+ const activeTabId = await getPageTargetId(page).catch(() => null);
680
+ const pages = await browser.pages();
681
+ const tabs2 = await Promise.all(
682
+ pages.map(async (p) => {
683
+ const pUrl = p.url();
684
+ if (pUrl.startsWith("devtools://")) return null;
685
+ const pTitle = await Promise.race([
686
+ p.title().catch(() => "Unknown"),
687
+ new Promise((resolve3) => setTimeout(() => resolve3("Unknown"), 500))
688
+ ]);
689
+ return {
690
+ tabId: await getPageTargetId(p).catch(() => pUrl),
691
+ title: pTitle,
692
+ url: pUrl
693
+ };
694
+ })
695
+ );
696
+ return {
697
+ ...state,
698
+ activeTabId: activeTabId ?? void 0,
699
+ tabs: tabs2.filter(Boolean)
700
+ };
701
+ }
702
+ async callTool(toolName, args, tabId) {
703
+ const browser = await this.getBrowser();
704
+ const tabIdStr = tabId != null ? String(tabId) : void 0;
705
+ const page = await getTargetPage(browser, tabIdStr);
706
+ const urlBefore = page.url();
707
+ await injectIntoPage(page);
708
+ const argsJson = JSON.stringify(args);
709
+ try {
710
+ const result = await page.evaluate(
711
+ async (name, inputString) => {
712
+ const mcp = document.modelContext || navigator.modelContext;
713
+ if (!mcp || typeof mcp.executeTool !== "function") {
714
+ throw new Error("\u5F53\u524D\u9875\u9762\u6CA1\u6709\u6CE8\u5165 WebMCP \u73AF\u5883 (document.modelContext \u672A\u627E\u5230)");
715
+ }
716
+ const tools = await mcp.getTools();
717
+ const toolObj = tools.find((t) => t.name === name);
718
+ if (!toolObj) throw new Error(`Tool ${name} not found`);
719
+ let res = await mcp.executeTool(toolObj, inputString);
720
+ if (typeof res === "string") {
721
+ try {
722
+ res = JSON.parse(res);
723
+ } catch {
724
+ }
725
+ }
726
+ if (res === void 0 || res === null) {
727
+ throw new Error("\u5DE5\u5177 execute \u672A\u8FD4\u56DE\u7ED3\u679C");
728
+ }
729
+ if (typeof res === "object" && res.success === false) {
730
+ const failed = res;
731
+ throw new Error(failed.error || failed.message || "\u5DE5\u5177\u6267\u884C\u5931\u8D25");
732
+ }
733
+ return res;
734
+ },
735
+ toolName,
736
+ argsJson
737
+ );
738
+ return result;
739
+ } catch (evalError) {
740
+ const errMsg = evalError instanceof Error ? evalError.message : String(evalError);
741
+ const isContextDestroyed = errMsg.includes("context was destroyed") || errMsg.includes("Execution context was destroyed") || errMsg.includes("Cannot read properties of null") && errMsg.includes("context");
742
+ if (isContextDestroyed) {
743
+ await new Promise((resolve3) => setTimeout(resolve3, 800));
744
+ const newUrl = page.url();
745
+ if (newUrl && newUrl !== urlBefore) {
746
+ return { success: true, message: `\u5DE5\u5177 ${toolName} \u6267\u884C\u5B8C\u6210\uFF0C\u9875\u9762\u5DF2\u5BFC\u822A\u81F3 ${newUrl}`, navigatedTo: newUrl };
747
+ }
748
+ }
749
+ throw evalError;
750
+ }
751
+ }
752
+ async tabs(action, options) {
753
+ const browser = await this.getBrowser();
754
+ const tabIdStr = options.tabId != null ? String(options.tabId) : void 0;
755
+ switch (action) {
756
+ case "open": {
757
+ if (!options.url) throw new Error("tabs open \u9700\u8981 url \u53C2\u6570");
758
+ const page = await browser.newPage();
759
+ await page.goto(options.url);
760
+ await injectIntoPage(page);
761
+ const tabId = await getPageTargetId(page);
762
+ setLastActiveTabId(tabId);
763
+ return { success: true, tabId, url: options.url };
764
+ }
765
+ case "close": {
766
+ const page = await getTargetPage(browser, tabIdStr);
767
+ await page.close();
768
+ return { success: true };
769
+ }
770
+ case "switch": {
771
+ if (!tabIdStr) throw new Error("tabs switch \u9700\u8981 tabId \u53C2\u6570");
772
+ await activateTabById(browser, tabIdStr);
773
+ setLastActiveTabId(tabIdStr);
774
+ return { success: true, tabId: tabIdStr };
775
+ }
776
+ case "back": {
777
+ const page = await getTargetPage(browser, tabIdStr);
778
+ await page.goBack();
779
+ return { success: true };
780
+ }
781
+ case "forward": {
782
+ const page = await getTargetPage(browser, tabIdStr);
783
+ await page.goForward();
784
+ return { success: true };
785
+ }
786
+ }
787
+ }
788
+ async dispose() {
789
+ if (this.browser) {
790
+ await this.browser.disconnect().catch(() => {
791
+ });
792
+ this.browser = null;
793
+ }
794
+ }
795
+ };
796
+ }
797
+ });
798
+
799
+ // src/bridge/protocol.ts
800
+ var DEFAULT_WS_PORT, PROTOCOL_VERSION, WS_CLOSE_CODE, BRIDGE_ERROR_CODE, BRIDGE_METHODS;
801
+ var init_protocol = __esm({
802
+ "src/bridge/protocol.ts"() {
803
+ "use strict";
804
+ DEFAULT_WS_PORT = 18999;
805
+ PROTOCOL_VERSION = "1.1.0";
806
+ WS_CLOSE_CODE = {
807
+ /** 被新接入的扩展连接平滑替换(旧连接触发退避重连) */
808
+ REPLACED: 4e3,
809
+ /** 认证未通过(未提供 Token、Token 错误或 HMAC 签名校验失败) */
810
+ UNAUTHORIZED: 4001,
811
+ /** 协议主版本号不匹配 */
812
+ PROTOCOL_MISMATCH: 4002
813
+ };
814
+ BRIDGE_ERROR_CODE = {
815
+ /** 请求执行超时 */
816
+ REQUEST_TIMEOUT: -32e3,
817
+ /** 命令执行超时 */
818
+ EXECUTION_TIMEOUT: -32001,
819
+ /** 命令或系统操作执行失败 */
820
+ EXECUTION_FAILED: -32002,
821
+ /** 无效参数(如 command 为空) */
822
+ INVALID_PARAMS: -32602,
823
+ /** 不支持的方法 */
824
+ METHOD_NOT_FOUND: -32601,
825
+ /** 扩展尚未连接至桥接服务 */
826
+ EXTENSION_NOT_CONNECTED: -32051,
827
+ /** 侧边栏尚未就绪或已关闭 */
828
+ SIDEPANEL_NOT_READY: -32050
829
+ };
830
+ BRIDGE_METHODS = {
831
+ TOOL_CALL: "tool/call",
832
+ SUB_AGENT_RUN: "sub_agent/run",
833
+ BROWSER_TABS: "browser/tabs",
834
+ BROWSER_STATE: "browser/state",
835
+ SKILLS_LIST: "skills/list",
836
+ SKILLS_GET: "skills/get",
837
+ SKILLS_READ_RESOURCE: "skills/read_resource",
838
+ SYSTEM_BASH: "system/bash",
839
+ SYSTEM_PICK_DIRECTORY: "system/pick_directory"
840
+ };
841
+ }
842
+ });
843
+
844
+ // src/bridge/workspace-manager.ts
845
+ function resolveBaseWorkspace(params) {
846
+ if (params.workspacePath && typeof params.workspacePath === "string" && params.workspacePath.trim()) {
847
+ const trimmedWs = params.workspacePath.trim();
848
+ return import_node_path.default.isAbsolute(trimmedWs) ? trimmedWs : import_node_path.default.resolve(import_node_os.default.homedir(), trimmedWs);
849
+ }
850
+ if (params.conversationId && typeof params.conversationId === "string" && params.conversationId.trim()) {
851
+ const safeId = params.conversationId.trim().replace(/[/\\?%*:|"<>.]/g, "_");
852
+ const sessionDir = import_node_path.default.resolve(WORKSPACES_ROOT, safeId || "default");
853
+ const relative = import_node_path.default.relative(WORKSPACES_ROOT, sessionDir);
854
+ if (!relative || relative.startsWith("..") || import_node_path.default.isAbsolute(relative)) {
855
+ return import_node_path.default.join(WORKSPACES_ROOT, "default");
856
+ }
857
+ return sessionDir;
858
+ }
859
+ return import_node_path.default.join(WORKSPACES_ROOT, "default");
860
+ }
861
+ function resolveWorkspaceDir(params = {}) {
862
+ const baseDir = resolveBaseWorkspace(params);
863
+ if (!import_node_fs.default.existsSync(baseDir)) {
864
+ try {
865
+ import_node_fs.default.mkdirSync(baseDir, { recursive: true, mode: 493 });
866
+ } catch {
867
+ }
868
+ }
869
+ if (!params.cwd || typeof params.cwd !== "string" || !params.cwd.trim()) {
870
+ return baseDir;
871
+ }
872
+ const trimmedCwd = params.cwd.trim();
873
+ const targetDir = import_node_path.default.isAbsolute(trimmedCwd) ? import_node_path.default.resolve(trimmedCwd) : import_node_path.default.resolve(baseDir, trimmedCwd);
874
+ const relative = import_node_path.default.relative(baseDir, targetDir);
875
+ if (relative.startsWith("..") || import_node_path.default.isAbsolute(relative)) {
876
+ throw new BashInvalidParamsError(`\u76EE\u6807\u6267\u884C\u8DEF\u5F84\u8D85\u51FA\u5DF2\u6388\u6743\u5DE5\u4F5C\u7A7A\u95F4\u5B89\u5168\u8FB9\u754C: ${trimmedCwd}`);
877
+ }
878
+ return targetDir;
879
+ }
880
+ var import_node_path, import_node_os, import_node_fs, WORKSPACES_ROOT, BashInvalidParamsError;
881
+ var init_workspace_manager = __esm({
882
+ "src/bridge/workspace-manager.ts"() {
883
+ "use strict";
884
+ import_node_path = __toESM(require("path"), 1);
885
+ import_node_os = __toESM(require("os"), 1);
886
+ import_node_fs = __toESM(require("fs"), 1);
887
+ WORKSPACES_ROOT = import_node_path.default.join(import_node_os.default.homedir(), ".robot-wxt", "workspaces");
888
+ BashInvalidParamsError = class extends Error {
889
+ code = "INVALID_PARAMS";
890
+ constructor(message = "\u53C2\u6570\u9519\u8BEF") {
891
+ super(message);
892
+ this.name = "BashInvalidParamsError";
893
+ }
894
+ };
895
+ }
896
+ });
897
+
898
+ // src/bridge/bash-executor.ts
899
+ function findWindowsBash() {
900
+ const pathDirs = (process.env.PATH || "").split(import_node_path2.default.delimiter);
901
+ for (const dir of pathDirs) {
902
+ if (!dir) continue;
903
+ const candidate = import_node_path2.default.join(dir, "bash.exe");
904
+ try {
905
+ if (import_node_fs2.default.existsSync(candidate)) return candidate;
906
+ } catch {
907
+ }
908
+ }
909
+ const localAppData = process.env.LOCALAPPDATA || "";
910
+ const programFiles = process.env.ProgramFiles || "C:\\Program Files";
911
+ const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
912
+ const programW6432 = process.env.ProgramW6432 || programFiles;
913
+ const commonGitBashPaths = [
914
+ import_node_path2.default.join(programFiles, "Git", "bin", "bash.exe"),
915
+ import_node_path2.default.join(programFiles, "Git", "usr", "bin", "bash.exe"),
916
+ import_node_path2.default.join(programW6432, "Git", "bin", "bash.exe"),
917
+ import_node_path2.default.join(programFilesX86, "Git", "bin", "bash.exe"),
918
+ import_node_path2.default.join(localAppData, "Programs", "Git", "bin", "bash.exe"),
919
+ import_node_path2.default.join(localAppData, "Programs", "Git", "usr", "bin", "bash.exe"),
920
+ import_node_path2.default.join(process.env.SystemRoot || "C:\\Windows", "System32", "bash.exe")
921
+ ];
922
+ for (const candidate of commonGitBashPaths) {
923
+ try {
924
+ if (import_node_fs2.default.existsSync(candidate)) return candidate;
925
+ } catch {
926
+ }
927
+ }
928
+ return null;
929
+ }
930
+ function resolveShell(forcePlatform) {
931
+ const currentPlatform = forcePlatform || process.platform;
932
+ if (!forcePlatform && cachedShell) {
933
+ return cachedShell;
934
+ }
935
+ if (currentPlatform !== "win32") {
936
+ const posixShell = process.env.SHELL || "/bin/bash";
937
+ if (!forcePlatform) cachedShell = posixShell;
938
+ return posixShell;
939
+ }
940
+ const winBash = findWindowsBash();
941
+ if (winBash) {
942
+ if (!forcePlatform) cachedShell = winBash;
943
+ return winBash;
944
+ }
945
+ const fallback = "powershell.exe";
946
+ if (!forcePlatform) cachedShell = fallback;
947
+ return fallback;
948
+ }
949
+ function killProcessTree(child) {
950
+ if (process.platform === "win32" && child.pid) {
951
+ try {
952
+ (0, import_node_child_process.spawn)("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
953
+ windowsHide: true,
954
+ stdio: "ignore"
955
+ });
956
+ } catch {
957
+ child.kill("SIGKILL");
958
+ }
959
+ } else {
960
+ child.kill("SIGTERM");
961
+ setTimeout(() => {
962
+ try {
963
+ child.kill("SIGKILL");
964
+ } catch {
965
+ }
966
+ }, 2e3);
967
+ }
968
+ }
969
+ async function executeBash(params) {
970
+ const trimmedCommand = params.command?.trim();
971
+ if (!trimmedCommand) {
972
+ throw new BashInvalidParamsError("\u547D\u4EE4\u4E0D\u80FD\u4E3A\u7A7A");
973
+ }
974
+ if (/rm\s+(-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*\s+|--recursive\s+--force\s+)\s*(\/|~|\$HOME|\/\*)\s*$/i.test(
975
+ trimmedCommand
976
+ ) || /:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/i.test(trimmedCommand)) {
977
+ throw new BashInvalidParamsError("\u5B89\u5168\u62E6\u622A\uFF1A\u7981\u6B62\u5728\u5BBF\u4E3B\u673A\u6267\u884C\u9488\u5BF9\u7CFB\u7EDF\u5173\u952E\u6839\u8DEF\u5F84\u7684\u9AD8\u5371\u7834\u574F\u6027\u547D\u4EE4");
978
+ }
979
+ const cwd = resolveWorkspaceDir({
980
+ cwd: params.cwd,
981
+ workspacePath: params.workspacePath,
982
+ conversationId: params.conversationId
983
+ });
984
+ const normalizedTimeoutMs = typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs) && params.timeoutMs > 0 ? Math.min(params.timeoutMs, MAX_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS;
985
+ const { env = {}, maxBuffer = DEFAULT_MAX_BUFFER } = params;
986
+ const startTime = Date.now();
987
+ const shell = resolveShell();
988
+ return new Promise((resolve3, reject) => {
989
+ const stdoutChunks = [];
990
+ let stdoutBytes = 0;
991
+ const stderrChunks = [];
992
+ let stderrBytes = 0;
993
+ let truncated = false;
994
+ let isKilled = false;
995
+ const child = (0, import_node_child_process.spawn)(trimmedCommand, {
996
+ shell,
997
+ cwd,
998
+ env: { ...process.env, ...env },
999
+ windowsHide: true
1000
+ });
1001
+ const killTimeoutTimer = setTimeout(() => {
1002
+ isKilled = true;
1003
+ killProcessTree(child);
1004
+ reject(new BashTimeoutError(normalizedTimeoutMs));
1005
+ }, normalizedTimeoutMs);
1006
+ child.stdout.on("data", (chunk) => {
1007
+ if (stdoutBytes < maxBuffer) {
1008
+ const remaining = maxBuffer - stdoutBytes;
1009
+ if (chunk.length <= remaining) {
1010
+ stdoutChunks.push(chunk);
1011
+ stdoutBytes += chunk.length;
1012
+ } else {
1013
+ stdoutChunks.push(chunk.subarray(0, remaining));
1014
+ stdoutBytes += remaining;
1015
+ truncated = true;
1016
+ }
1017
+ } else {
1018
+ truncated = true;
1019
+ }
1020
+ });
1021
+ child.stderr.on("data", (chunk) => {
1022
+ if (stderrBytes < maxBuffer) {
1023
+ const remaining = maxBuffer - stderrBytes;
1024
+ if (chunk.length <= remaining) {
1025
+ stderrChunks.push(chunk);
1026
+ stderrBytes += chunk.length;
1027
+ } else {
1028
+ stderrChunks.push(chunk.subarray(0, remaining));
1029
+ stderrBytes += remaining;
1030
+ truncated = true;
1031
+ }
1032
+ } else {
1033
+ truncated = true;
1034
+ }
1035
+ });
1036
+ child.on("error", (err) => {
1037
+ clearTimeout(killTimeoutTimer);
1038
+ reject(err);
1039
+ });
1040
+ child.on("close", (exitCode, signal) => {
1041
+ clearTimeout(killTimeoutTimer);
1042
+ if (isKilled) return;
1043
+ const stdout = Buffer.concat(stdoutChunks).toString("utf8").trim();
1044
+ const stderr = Buffer.concat(stderrChunks).toString("utf8").trim();
1045
+ resolve3({
1046
+ stdout,
1047
+ stderr,
1048
+ exitCode,
1049
+ signal,
1050
+ durationMs: Date.now() - startTime,
1051
+ ...truncated ? { truncated: true } : {}
1052
+ });
1053
+ });
1054
+ });
1055
+ }
1056
+ var import_node_fs2, import_node_path2, import_node_child_process, BashTimeoutError, DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, DEFAULT_MAX_BUFFER, cachedShell;
1057
+ var init_bash_executor = __esm({
1058
+ "src/bridge/bash-executor.ts"() {
1059
+ "use strict";
1060
+ import_node_fs2 = __toESM(require("fs"), 1);
1061
+ import_node_path2 = __toESM(require("path"), 1);
1062
+ import_node_child_process = require("child_process");
1063
+ init_workspace_manager();
1064
+ BashTimeoutError = class extends Error {
1065
+ code = "TIMEOUT";
1066
+ timeoutMs;
1067
+ constructor(timeoutMs) {
1068
+ super(`\u547D\u4EE4\u6267\u884C\u8D85\u65F6 (${timeoutMs / 1e3}s)`);
1069
+ this.name = "BashTimeoutError";
1070
+ this.timeoutMs = timeoutMs;
1071
+ }
1072
+ };
1073
+ DEFAULT_TIMEOUT_MS = 3e4;
1074
+ MAX_TIMEOUT_MS = 6e5;
1075
+ DEFAULT_MAX_BUFFER = 512 * 1024;
1076
+ cachedShell = null;
1077
+ }
1078
+ });
1079
+
1080
+ // src/bridge/directory-picker.ts
1081
+ async function pickDirectory(optionsOrTitle) {
1082
+ const options = typeof optionsOrTitle === "string" ? { title: optionsOrTitle } : optionsOrTitle || {};
1083
+ const title = options.title || "\u8BF7\u9009\u62E9\u5DE5\u4F5C\u7A7A\u95F4\u6587\u4EF6\u5939";
1084
+ const defaultPath = options.defaultPath && typeof options.defaultPath === "string" ? options.defaultPath.trim() : void 0;
1085
+ const platform = process.platform;
1086
+ if (platform === "darwin") {
1087
+ return pickDirectoryMac(title, defaultPath);
1088
+ }
1089
+ if (platform === "win32") {
1090
+ return pickDirectoryWindows(title, defaultPath);
1091
+ }
1092
+ return pickDirectoryLinux(title, defaultPath);
1093
+ }
1094
+ function pickDirectoryMac(title, defaultPath) {
1095
+ const safeTitle = title.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
1096
+ const defaultClause = defaultPath ? ` default location POSIX file "${defaultPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` : "";
1097
+ const appleScript = `POSIX path of (choose folder with prompt "${safeTitle}"${defaultClause})`;
1098
+ return new Promise((resolve3, reject) => {
1099
+ const child = (0, import_node_child_process2.spawn)("osascript", ["-e", appleScript], {
1100
+ stdio: ["ignore", "pipe", "pipe"]
1101
+ });
1102
+ let stdout = "";
1103
+ let stderr = "";
1104
+ child.stdout?.on("data", (d) => {
1105
+ stdout += d.toString();
1106
+ });
1107
+ child.stderr?.on("data", (d) => {
1108
+ stderr += d.toString();
1109
+ });
1110
+ child.on("close", (code) => {
1111
+ if (code === 0) {
1112
+ const selected = stdout.trim();
1113
+ resolve3(selected || null);
1114
+ return;
1115
+ }
1116
+ if (code === 1 && (stderr.includes("User canceled") || stderr.includes("-128") || !stderr.trim())) {
1117
+ resolve3(null);
1118
+ return;
1119
+ }
1120
+ reject(new Error(`\u5524\u8D77\u7CFB\u7EDF\u6587\u4EF6\u5939\u9009\u62E9\u5668\u5931\u8D25: ${stderr.trim() || `\u9000\u51FA\u7801 ${code}`}`));
1121
+ });
1122
+ child.on("error", (err) => {
1123
+ reject(new Error(`\u5524\u8D77\u7CFB\u7EDF\u6587\u4EF6\u5939\u9009\u62E9\u5668\u5931\u8D25: ${err.message}`));
1124
+ });
1125
+ });
1126
+ }
1127
+ function escapePowerShellString(str) {
1128
+ return str.replace(/`/g, "``").replace(/"/g, '`"').replace(/\$/g, "`$");
1129
+ }
1130
+ function pickDirectoryWindows(title, defaultPath) {
1131
+ const safeTitle = escapePowerShellString(title);
1132
+ const safeDefaultPath = escapePowerShellString(defaultPath ?? "");
1133
+ const psScript = `
1134
+ $code = @'
1135
+ using System;
1136
+ using System.Runtime.InteropServices;
1137
+
1138
+ [ComImport, Guid("D57C7288-D4AD-4768-BE02-9D969532D960"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
1139
+ interface IFileOpenDialog {
1140
+ [PreserveSig] int Show(IntPtr hwnd);
1141
+ void SetFileTypes(uint cFileTypes, IntPtr rgFilterSpec);
1142
+ void SetFileTypeIndex(uint iFileType);
1143
+ void GetFileTypeIndex(out uint piFileType);
1144
+ void Advise(IntPtr pfde, out uint pdwCookie);
1145
+ void Unadvise(uint dwCookie);
1146
+ void SetOptions(uint fos);
1147
+ void GetOptions(out uint pfos);
1148
+ void SetDefaultFolder(IntPtr psi);
1149
+ void SetFolder(IntPtr psi);
1150
+ void GetFolder(out IntPtr ppsi);
1151
+ void GetCurrentSelection(out IntPtr ppsi);
1152
+ void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string pszName);
1153
+ void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
1154
+ void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
1155
+ void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string pszText);
1156
+ void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
1157
+ void GetResult(out IntPtr ppsi);
1158
+ void AddPlace(IntPtr psi, int fdap);
1159
+ void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
1160
+ void Close(int hr);
1161
+ void SetClientGuid([In] ref Guid guid);
1162
+ void ClearClientData();
1163
+ void SetFilter(IntPtr pFilter);
1164
+ void GetResults(out IntPtr ppenum);
1165
+ void GetSelectedItems(out IntPtr ppsai);
1166
+ }
1167
+
1168
+ [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
1169
+ interface IShellItem {
1170
+ void BindToHandler(IntPtr pbc, [In] ref Guid bhid, [In] ref Guid riid, out IntPtr ppv);
1171
+ void GetParent(out IShellItem ppsi);
1172
+ void GetDisplayName(uint sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
1173
+ void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);
1174
+ void Compare(IShellItem psi, uint hint, out int piOrder);
1175
+ }
1176
+
1177
+ public static class FolderPicker {
1178
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
1179
+ static extern int SHCreateItemFromParsingName(string pszPath, IntPtr pbc, [In] ref Guid riid, out IntPtr ppv);
1180
+
1181
+ // FOS_PICKFOLDERS = 0x20, FOS_FORCEFILESYSTEM = 0x40
1182
+ const uint FOS_PICKFOLDERS = 0x00000020;
1183
+ const uint FOS_FORCEFILESYSTEM = 0x00000040;
1184
+
1185
+ public static string Pick(string title, string defaultPath) {
1186
+ var clsid = new Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7");
1187
+ var riid = new Guid("D57C7288-D4AD-4768-BE02-9D969532D960");
1188
+ var obj = Activator.CreateInstance(Type.GetTypeFromCLSID(clsid));
1189
+ var dialog = (IFileOpenDialog)obj;
1190
+ dialog.SetOptions(FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM);
1191
+ dialog.SetTitle(title);
1192
+ if (!string.IsNullOrEmpty(defaultPath)) {
1193
+ var riidShellItem = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE");
1194
+ IntPtr psi;
1195
+ if (SHCreateItemFromParsingName(defaultPath, IntPtr.Zero, ref riidShellItem, out psi) == 0) {
1196
+ dialog.SetFolder(psi);
1197
+ Marshal.Release(psi);
1198
+ }
1199
+ }
1200
+ int hr = dialog.Show(IntPtr.Zero);
1201
+ if (hr != 0) return null; // \u7528\u6237\u53D6\u6D88 (HRESULT_FROM_WIN32(ERROR_CANCELLED) = 0x800704C7)
1202
+ IntPtr ppsi;
1203
+ dialog.GetResult(out ppsi);
1204
+ var shellItem = (IShellItem)Marshal.GetTypedObjectForIUnknown(ppsi, typeof(IShellItem));
1205
+ string path;
1206
+ shellItem.GetDisplayName(0x80058000, out path); // SIGDN_FILESYSPATH
1207
+ Marshal.Release(ppsi);
1208
+ return path;
1209
+ }
1210
+ }
1211
+ '@
1212
+ Add-Type -TypeDefinition $code
1213
+ $result = [FolderPicker]::Pick("${safeTitle}", "${safeDefaultPath}")
1214
+ if ($result) { Write-Output $result }
1215
+ `;
1216
+ return new Promise((resolve3, reject) => {
1217
+ const child = (0, import_node_child_process2.spawn)("powershell", ["-STA", "-NoProfile", "-WindowStyle", "Hidden", "-Command", psScript], {
1218
+ stdio: ["ignore", "pipe", "pipe"],
1219
+ windowsHide: true
1220
+ });
1221
+ let stdout = "";
1222
+ let stderr = "";
1223
+ child.stdout?.on("data", (d) => {
1224
+ stdout += d.toString();
1225
+ });
1226
+ child.stderr?.on("data", (d) => {
1227
+ stderr += d.toString();
1228
+ });
1229
+ child.on("close", (code) => {
1230
+ if (code === 0) {
1231
+ const selected = stdout.trim();
1232
+ resolve3(selected || null);
1233
+ return;
1234
+ }
1235
+ reject(new Error(`PowerShell \u6587\u4EF6\u5939\u9009\u62E9\u5668\u6267\u884C\u5931\u8D25: ${stderr.trim() || `\u9000\u51FA\u7801 ${code}`}`));
1236
+ });
1237
+ child.on("error", (err) => {
1238
+ reject(new Error(`\u5524\u8D77 PowerShell \u6587\u4EF6\u5939\u9009\u62E9\u5668\u5931\u8D25: ${err.message}`));
1239
+ });
1240
+ });
1241
+ }
1242
+ function pickDirectoryLinux(title, defaultPath) {
1243
+ const args = ["--file-selection", "--directory", `--title=${title}`];
1244
+ if (defaultPath) {
1245
+ args.push(`--filename=${defaultPath}`);
1246
+ }
1247
+ return new Promise((resolve3, reject) => {
1248
+ const child = (0, import_node_child_process2.spawn)("zenity", args, {
1249
+ stdio: ["ignore", "pipe", "pipe"]
1250
+ });
1251
+ let stdout = "";
1252
+ let stderr = "";
1253
+ child.stdout?.on("data", (d) => {
1254
+ stdout += d.toString();
1255
+ });
1256
+ child.stderr?.on("data", (d) => {
1257
+ stderr += d.toString();
1258
+ });
1259
+ child.on("close", (code) => {
1260
+ if (code === 0) {
1261
+ const selected = stdout.trim();
1262
+ resolve3(selected || null);
1263
+ return;
1264
+ }
1265
+ if (code === 1) {
1266
+ resolve3(null);
1267
+ return;
1268
+ }
1269
+ reject(new Error(`zenity \u76EE\u5F55\u9009\u62E9\u5668\u5F02\u5E38\u9000\u51FA (\u9000\u51FA\u7801 ${code}): ${stderr.trim()}`));
1270
+ });
1271
+ child.on("error", (err) => {
1272
+ if (err?.code === "ENOENT") {
1273
+ reject(new Error("\u672A\u68C0\u6D4B\u5230 zenity \u76EE\u5F55\u9009\u62E9\u5668\uFF0C\u8BF7\u5148\u5728\u7CFB\u7EDF\u4E2D\u5B89\u88C5 zenity (\u4F8B\u5982: sudo apt install zenity)"));
1274
+ return;
1275
+ }
1276
+ reject(new Error(`\u5524\u8D77 zenity \u76EE\u5F55\u9009\u62E9\u5668\u5931\u8D25: ${err.message}`));
1277
+ });
1278
+ });
1279
+ }
1280
+ var import_node_child_process2;
1281
+ var init_directory_picker = __esm({
1282
+ "src/bridge/directory-picker.ts"() {
1283
+ "use strict";
1284
+ import_node_child_process2 = require("child_process");
1285
+ }
1286
+ });
1287
+
1288
+ // src/bridge/bridge-client.ts
1289
+ var bridge_client_exports = {};
1290
+ __export(bridge_client_exports, {
1291
+ BRIDGE_ERROR_CODE: () => BRIDGE_ERROR_CODE,
1292
+ ExtensionBridgeClient: () => ExtensionBridgeClient,
1293
+ PROTOCOL_VERSION: () => PROTOCOL_VERSION,
1294
+ computeHmac: () => computeHmac,
1295
+ deriveSharedSecret: () => deriveSharedSecret,
1296
+ getKillPortHint: () => getKillPortHint,
1297
+ resolveOrCreateAuthToken: () => resolveOrCreateAuthToken,
1298
+ verifyHmacConstantTime: () => verifyHmacConstantTime
1299
+ });
1300
+ function resolveOrCreateAuthToken(explicitToken) {
1301
+ if (explicitToken && explicitToken.trim()) {
1302
+ const token = explicitToken.trim();
1303
+ try {
1304
+ if (!import_node_fs3.default.existsSync(TOKEN_FILE_DIR)) {
1305
+ import_node_fs3.default.mkdirSync(TOKEN_FILE_DIR, { mode: 448, recursive: true });
1306
+ }
1307
+ import_node_fs3.default.writeFileSync(TOKEN_FILE_PATH, token, { mode: 384, encoding: "utf8" });
1308
+ } catch {
1309
+ }
1310
+ return token;
1311
+ }
1312
+ if (process.env.ROBOT_WXT_BRIDGE_TOKEN) {
1313
+ return process.env.ROBOT_WXT_BRIDGE_TOKEN.trim();
1314
+ }
1315
+ try {
1316
+ if (import_node_fs3.default.existsSync(TOKEN_FILE_PATH)) {
1317
+ const existing = import_node_fs3.default.readFileSync(TOKEN_FILE_PATH, "utf8").trim();
1318
+ if (existing) return existing;
1319
+ }
1320
+ } catch {
1321
+ }
1322
+ const newToken = (0, import_node_crypto.randomBytes)(32).toString("hex");
1323
+ try {
1324
+ if (!import_node_fs3.default.existsSync(TOKEN_FILE_DIR)) {
1325
+ import_node_fs3.default.mkdirSync(TOKEN_FILE_DIR, { mode: 448, recursive: true });
1326
+ }
1327
+ import_node_fs3.default.writeFileSync(TOKEN_FILE_PATH, newToken, { mode: 384, encoding: "utf8" });
1328
+ } catch {
1329
+ }
1330
+ return newToken;
1331
+ }
1332
+ function parseMajorVersion(v) {
1333
+ return parseInt(v.split(".")[0] ?? "0", 10);
1334
+ }
1335
+ function deriveSharedSecret(tokenOrExtensionId, hmacSalt) {
1336
+ return (0, import_node_crypto.createHash)("sha256").update(`${tokenOrExtensionId}:${hmacSalt}`).digest();
1337
+ }
1338
+ function computeHmac(secret, challenge) {
1339
+ return (0, import_node_crypto.createHmac)("sha256", secret).update(challenge).digest("hex");
1340
+ }
1341
+ function verifyHmacConstantTime(actualHex, expectedHex) {
1342
+ if (!actualHex || typeof actualHex !== "string") return false;
1343
+ try {
1344
+ const actualBuf = Buffer.from(actualHex, "hex");
1345
+ const expectedBuf = Buffer.from(expectedHex, "hex");
1346
+ if (actualBuf.length !== expectedBuf.length) return false;
1347
+ return (0, import_node_crypto.timingSafeEqual)(actualBuf, expectedBuf);
1348
+ } catch {
1349
+ return false;
1350
+ }
1351
+ }
1352
+ function getKillPortHint(port) {
1353
+ if (process.platform === "win32") {
1354
+ return `netstat -ano | findstr :${port} \uFF08\u627E\u5230 PID \u540E\u6267\u884C: taskkill /pid <PID> /T /F\uFF09`;
1355
+ }
1356
+ return `lsof -ti:${port} | xargs kill -9`;
1357
+ }
1358
+ var import_ws, import_node_events, import_node_crypto, import_node_fs3, import_node_path3, import_node_os2, WS_PORT, REQUEST_TIMEOUT_MS, HANDSHAKE_TIMEOUT_MS, WS_OPEN, TOKEN_FILE_DIR, TOKEN_FILE_PATH, ExtensionBridgeClient;
1359
+ var init_bridge_client = __esm({
1360
+ "src/bridge/bridge-client.ts"() {
1361
+ "use strict";
1362
+ import_ws = require("ws");
1363
+ import_node_events = require("events");
1364
+ import_node_crypto = require("crypto");
1365
+ import_node_fs3 = __toESM(require("fs"), 1);
1366
+ import_node_path3 = __toESM(require("path"), 1);
1367
+ import_node_os2 = __toESM(require("os"), 1);
1368
+ init_protocol();
1369
+ init_bash_executor();
1370
+ init_directory_picker();
1371
+ WS_PORT = DEFAULT_WS_PORT;
1372
+ REQUEST_TIMEOUT_MS = 3e4;
1373
+ HANDSHAKE_TIMEOUT_MS = 5e3;
1374
+ WS_OPEN = 1;
1375
+ TOKEN_FILE_DIR = import_node_path3.default.join(import_node_os2.default.homedir(), ".robot-wxt");
1376
+ TOKEN_FILE_PATH = import_node_path3.default.join(TOKEN_FILE_DIR, "bridge-token");
1377
+ ExtensionBridgeClient = class _ExtensionBridgeClient extends import_node_events.EventEmitter {
1378
+ constructor(port = WS_PORT, authToken) {
1379
+ super();
1380
+ this.port = port;
1381
+ this.explicitAuthToken = authToken;
1382
+ this.authToken = authToken ?? resolveOrCreateAuthToken();
1383
+ }
1384
+ port;
1385
+ wss = null;
1386
+ extensionSocket = null;
1387
+ clientSocket = null;
1388
+ forwardedRequests = /* @__PURE__ */ new Map();
1389
+ pending = /* @__PURE__ */ new Map();
1390
+ socketAuthStates = /* @__PURE__ */ new Map();
1391
+ destroyed = false;
1392
+ idCounter = 0;
1393
+ isClientMode = false;
1394
+ explicitAuthToken;
1395
+ authToken;
1396
+ /** 获取当前服务端使用的认证 Token */
1397
+ get currentAuthToken() {
1398
+ return this.authToken;
1399
+ }
1400
+ /** 获取当前激活的 Socket */
1401
+ _getActiveSocket() {
1402
+ if (this.isClientMode && this.clientSocket) {
1403
+ return this.clientSocket.readyState === WS_OPEN ? this.clientSocket : null;
1404
+ }
1405
+ if (this.extensionSocket && this.extensionSocket.readyState === WS_OPEN) {
1406
+ return this.extensionSocket;
1407
+ }
1408
+ return null;
1409
+ }
1410
+ /** 是否已有就绪的扩展连接(或作为 Client 已连接到 Server) */
1411
+ get isConnected() {
1412
+ return this._getActiveSocket() != null;
1413
+ }
1414
+ /** 等待扩展连接或作为客户端连入服务就绪 */
1415
+ async waitForReady(timeoutMs = 5e3) {
1416
+ if (this.isConnected) return true;
1417
+ return new Promise((resolve3) => {
1418
+ const timer = setTimeout(() => {
1419
+ cleanup();
1420
+ resolve3(this.isConnected);
1421
+ }, timeoutMs);
1422
+ const cleanup = () => {
1423
+ clearTimeout(timer);
1424
+ this.off("connected", onConnected);
1425
+ };
1426
+ const onConnected = () => {
1427
+ cleanup();
1428
+ resolve3(true);
1429
+ };
1430
+ this.on("connected", onConnected);
1431
+ });
1432
+ }
1433
+ /**
1434
+ * 静态探测目标端口的桥接服务状态
1435
+ */
1436
+ static async probe(port = WS_PORT, authToken, timeoutMs = 800) {
1437
+ const client = new _ExtensionBridgeClient(port, authToken);
1438
+ try {
1439
+ const res = await client._probeExistingServer(timeoutMs);
1440
+ if (client.clientSocket) {
1441
+ try {
1442
+ client.clientSocket.close(1e3, "Probe finished");
1443
+ } catch {
1444
+ }
1445
+ }
1446
+ if (res.success) {
1447
+ return { running: true, authed: true };
1448
+ }
1449
+ if (res.error) {
1450
+ const isAuthError = res.error.message.includes("HMAC") || res.error.message.includes("\u8BA4\u8BC1\u5931\u8D25") || res.error.message.includes("Unauthorized");
1451
+ if (isAuthError) {
1452
+ return { running: true, authed: false, error: res.error.message };
1453
+ }
1454
+ return { running: false, authed: false, error: res.error.message };
1455
+ }
1456
+ return { running: false, authed: false };
1457
+ } finally {
1458
+ client.destroy();
1459
+ }
1460
+ }
1461
+ /**
1462
+ * 自动探测模式:
1463
+ * 优先尝试连接已存在的 18999 服务;连接不上时退回启动本机的 WebSocketServer。
1464
+ */
1465
+ async startAuto(probeTimeoutMs = 800) {
1466
+ if (this.destroyed) return;
1467
+ const probe = await this._probeExistingServer(probeTimeoutMs);
1468
+ if (probe.success) {
1469
+ return;
1470
+ }
1471
+ if (probe.error) {
1472
+ throw probe.error;
1473
+ }
1474
+ this.connect();
1475
+ }
1476
+ async _probeExistingServer(timeoutMs) {
1477
+ return new Promise((resolve3) => {
1478
+ let settled = false;
1479
+ let connectionEstablished = false;
1480
+ let authFailedReason = null;
1481
+ const ws = new import_ws.WebSocket(`ws://127.0.0.1:${this.port}`);
1482
+ const timer = setTimeout(() => {
1483
+ if (!settled) {
1484
+ settled = true;
1485
+ try {
1486
+ ws.terminate();
1487
+ } catch {
1488
+ }
1489
+ if (authFailedReason) {
1490
+ resolve3({
1491
+ success: false,
1492
+ error: new Error(
1493
+ `\u672C\u5730\u6865\u63A5\u670D\u52A1\uFF08127.0.0.1:${this.port}\uFF09\u6B63\u5728\u8FD0\u884C\uFF0C\u4F46 HMAC \u8BA4\u8BC1\u5931\u8D25\uFF1A${authFailedReason}\u3002
1494
+ \u8BF7\u786E\u8BA4\u5F53\u524D CLI \u4F7F\u7528\u7684 Token \u4E0E\u8BE5\u670D\u52A1\u4E00\u81F4\uFF0C\u6216\u7EC8\u6B62\u5360\u7528\u8FDB\u7A0B\uFF08\u53EF\u6267\u884C: ${getKillPortHint(this.port)}\uFF09\u3002`
1495
+ )
1496
+ });
1497
+ } else if (connectionEstablished) {
1498
+ resolve3({
1499
+ success: false,
1500
+ error: new Error(
1501
+ `\u672C\u5730 127.0.0.1:${this.port} \u5DF2\u88AB\u5360\u7528\u4E14\u65E0\u54CD\u5E94\uFF08\u53EF\u80FD\u4E0D\u662F\u6709\u6548\u6865\u63A5\u670D\u52A1\uFF09\uFF0C\u8BF7\u5148\u7EC8\u6B62\u5360\u7528\u8FDB\u7A0B\uFF08\u53EF\u6267\u884C: ${getKillPortHint(this.port)}\uFF09\u3002`
1502
+ )
1503
+ });
1504
+ } else {
1505
+ resolve3({ success: false });
1506
+ }
1507
+ }
1508
+ }, timeoutMs);
1509
+ ws.on("open", () => {
1510
+ connectionEstablished = true;
1511
+ });
1512
+ ws.on("close", (code, reason) => {
1513
+ const reasonStr = reason ? reason.toString() : "";
1514
+ if (code === WS_CLOSE_CODE.UNAUTHORIZED || reasonStr.includes("Unauthorized") || reasonStr.includes("HMAC")) {
1515
+ authFailedReason = reasonStr || "Token \u8BA4\u8BC1\u88AB\u62D2\u7EDD (HMAC verification failed)";
1516
+ }
1517
+ if (!settled && authFailedReason) {
1518
+ settled = true;
1519
+ clearTimeout(timer);
1520
+ resolve3({
1521
+ success: false,
1522
+ error: new Error(
1523
+ `\u672C\u5730\u6865\u63A5\u670D\u52A1\uFF08127.0.0.1:${this.port}\uFF09\u6B63\u5728\u8FD0\u884C\uFF0C\u4F46 HMAC \u8BA4\u8BC1\u5931\u8D25\uFF1A${authFailedReason}\u3002
1524
+ \u8BF7\u786E\u8BA4\u5F53\u524D CLI \u4F7F\u7528\u7684 Token \u4E0E\u8BE5\u670D\u52A1\u4E00\u81F4\uFF0C\u6216\u7EC8\u6B62\u5360\u7528\u8FDB\u7A0B\uFF08\u53EF\u6267\u884C: ${getKillPortHint(this.port)}\uFF09\u3002`
1525
+ )
1526
+ });
1527
+ }
1528
+ });
1529
+ ws.on("message", (data) => {
1530
+ try {
1531
+ const msg = JSON.parse(data.toString());
1532
+ if (msg.type === "BRIDGE_CHALLENGE" && msg.challenge && msg.hmacSalt) {
1533
+ connectionEstablished = true;
1534
+ const secret = deriveSharedSecret(this.authToken, msg.hmacSalt);
1535
+ const hmac = computeHmac(secret, msg.challenge);
1536
+ ws.send(
1537
+ JSON.stringify({
1538
+ type: "BRIDGE_AUTH",
1539
+ clientType: "cli-client",
1540
+ challenge: msg.challenge,
1541
+ hmac
1542
+ })
1543
+ );
1544
+ return;
1545
+ }
1546
+ if (msg.type === "BRIDGE_AUTH_OK" && !settled) {
1547
+ settled = true;
1548
+ clearTimeout(timer);
1549
+ this.isClientMode = true;
1550
+ this.clientSocket = ws;
1551
+ this._bindClientSocket(ws);
1552
+ this.emit("connected");
1553
+ resolve3({ success: true });
1554
+ }
1555
+ } catch {
1556
+ }
1557
+ });
1558
+ ws.once("error", (err) => {
1559
+ if (!settled) {
1560
+ settled = true;
1561
+ clearTimeout(timer);
1562
+ try {
1563
+ ws.terminate();
1564
+ } catch {
1565
+ }
1566
+ if (err?.code === "ECONNREFUSED" || err?.message?.includes("ECONNREFUSED")) {
1567
+ resolve3({ success: false });
1568
+ } else {
1569
+ resolve3({
1570
+ success: false,
1571
+ error: new Error(`\u8FDE\u63A5\u672C\u5730 127.0.0.1:${this.port} \u5931\u8D25: ${err?.message || err}`)
1572
+ });
1573
+ }
1574
+ }
1575
+ });
1576
+ });
1577
+ }
1578
+ _bindClientSocket(ws) {
1579
+ ws.on("message", (data) => {
1580
+ let msg;
1581
+ try {
1582
+ msg = JSON.parse(data.toString());
1583
+ } catch {
1584
+ return;
1585
+ }
1586
+ if (msg.type === "BRIDGE_CHALLENGE" || msg.type === "BRIDGE_AUTH_OK") {
1587
+ return;
1588
+ }
1589
+ if (msg.method === "notification/sub_agent_progress") {
1590
+ this.emit("progress", msg.params);
1591
+ return;
1592
+ }
1593
+ const pending = this.pending.get(String(msg.id));
1594
+ if (!pending) return;
1595
+ this.pending.delete(String(msg.id));
1596
+ clearTimeout(pending.timer);
1597
+ if (msg.error) {
1598
+ pending.reject(new Error(`[${msg.error.code}] ${msg.error.message}`));
1599
+ } else {
1600
+ pending.resolve(msg.result);
1601
+ }
1602
+ });
1603
+ ws.on("close", () => {
1604
+ this.clientSocket = null;
1605
+ this.emit("disconnected");
1606
+ this._rejectAllPending("\u4E0E\u670D\u52A1\u7684\u8FDE\u63A5\u5DF2\u65AD\u5F00");
1607
+ });
1608
+ }
1609
+ /** 启动 WebSocket 服务端,等待 Chrome 扩展(Offscreen Document)连入 */
1610
+ connect() {
1611
+ if (this.destroyed) return;
1612
+ if (this.wss) return;
1613
+ try {
1614
+ this.wss = new import_ws.WebSocketServer({
1615
+ port: this.port,
1616
+ host: "127.0.0.1",
1617
+ verifyClient: (info, callback) => {
1618
+ const origin = info.origin || info.req.headers.origin;
1619
+ if (origin) {
1620
+ const isAllowedExtension = origin.startsWith("chrome-extension://") || origin.startsWith("moz-extension://") || origin.startsWith("extension://");
1621
+ if (!isAllowedExtension) {
1622
+ callback(false, 403, "Forbidden origin: only browser extensions are allowed");
1623
+ return;
1624
+ }
1625
+ }
1626
+ callback(true);
1627
+ }
1628
+ });
1629
+ } catch (err) {
1630
+ this.emit("error", err);
1631
+ return;
1632
+ }
1633
+ this.wss.on("listening", () => {
1634
+ this.emit("listening");
1635
+ });
1636
+ this.wss.on("error", (err) => {
1637
+ if (err?.code === "EADDRINUSE") {
1638
+ process.stderr.write(
1639
+ `[webmcp-cli] \u26A0\uFE0F \u7AEF\u53E3 ${this.port} \u5DF2\u88AB\u5360\u7528\uFF0C\u8BF7\u5148\u7EC8\u6B62\u5360\u7528\u8BE5\u7AEF\u53E3\u7684\u65E7\u8FDB\u7A0B\uFF08\u53EF\u6267\u884C: ${getKillPortHint(this.port)}\uFF09
1640
+ `
1641
+ );
1642
+ }
1643
+ this.emit("error", err);
1644
+ });
1645
+ this.wss.on("connection", (socket) => {
1646
+ const challenge = (0, import_node_crypto.randomUUID)();
1647
+ const hmacSalt = (0, import_node_crypto.randomBytes)(16).toString("hex");
1648
+ const authState = {
1649
+ authenticated: false,
1650
+ challenge,
1651
+ hmacSalt,
1652
+ timer: setTimeout(() => {
1653
+ if (!authState.authenticated) {
1654
+ try {
1655
+ socket.close(WS_CLOSE_CODE.UNAUTHORIZED, "Handshake timeout");
1656
+ } catch {
1657
+ }
1658
+ }
1659
+ }, HANDSHAKE_TIMEOUT_MS)
1660
+ };
1661
+ this.socketAuthStates.set(socket, authState);
1662
+ try {
1663
+ socket.send(
1664
+ JSON.stringify({
1665
+ type: "BRIDGE_CHALLENGE",
1666
+ challenge,
1667
+ hmacSalt,
1668
+ protocolVersion: PROTOCOL_VERSION
1669
+ })
1670
+ );
1671
+ } catch {
1672
+ }
1673
+ socket.on("message", async (data) => {
1674
+ await this.handleSocketMessage(socket, data);
1675
+ });
1676
+ socket.on("close", () => {
1677
+ const auth = this.socketAuthStates.get(socket);
1678
+ if (auth?.timer) clearTimeout(auth.timer);
1679
+ this.socketAuthStates.delete(socket);
1680
+ for (const [reqId, fwdInfo] of this.forwardedRequests.entries()) {
1681
+ if (fwdInfo.socket === socket) {
1682
+ if (fwdInfo.timer) clearTimeout(fwdInfo.timer);
1683
+ this.forwardedRequests.delete(reqId);
1684
+ }
1685
+ }
1686
+ if (socket === this.extensionSocket) {
1687
+ this.extensionSocket = null;
1688
+ this.emit("disconnected");
1689
+ for (const [reqId, fwdInfo] of this.forwardedRequests.entries()) {
1690
+ if (fwdInfo.timer) clearTimeout(fwdInfo.timer);
1691
+ try {
1692
+ if (fwdInfo.socket.readyState === WS_OPEN) {
1693
+ fwdInfo.socket.send(
1694
+ JSON.stringify({
1695
+ jsonrpc: "2.0",
1696
+ id: fwdInfo.originalId,
1697
+ error: {
1698
+ code: BRIDGE_ERROR_CODE.EXTENSION_NOT_CONNECTED,
1699
+ message: "Chrome \u6269\u5C55\u8FDE\u63A5\u5DF2\u65AD\u5F00"
1700
+ }
1701
+ })
1702
+ );
1703
+ }
1704
+ } catch {
1705
+ }
1706
+ this.forwardedRequests.delete(reqId);
1707
+ }
1708
+ this._rejectAllPending("WebSocket \u8FDE\u63A5\u5DF2\u65AD\u5F00");
1709
+ }
1710
+ });
1711
+ socket.on("error", () => {
1712
+ });
1713
+ });
1714
+ this.wss.on("error", (err) => {
1715
+ this.emit("error", err);
1716
+ });
1717
+ }
1718
+ async handleSocketMessage(socket, data) {
1719
+ let msg;
1720
+ try {
1721
+ msg = JSON.parse(data.toString());
1722
+ } catch {
1723
+ return;
1724
+ }
1725
+ const currentAuth = this.socketAuthStates.get(socket);
1726
+ if (!currentAuth || !currentAuth.authenticated) {
1727
+ await this.handleHandshake(socket, currentAuth, msg);
1728
+ return;
1729
+ }
1730
+ if (msg.type === "KEEP_ALIVE" || msg.type === "WS_BRIDGE_KEEP_ALIVE") {
1731
+ return;
1732
+ }
1733
+ if (msg.method && msg.id) {
1734
+ if (socket === this.extensionSocket) {
1735
+ await this.handleExtensionSystemRpc(socket, msg);
1736
+ return;
1737
+ }
1738
+ await this.handleForwardRpc(socket, msg);
1739
+ return;
1740
+ }
1741
+ if (msg.method && !msg.id) {
1742
+ this.handleProgressNotification(msg);
1743
+ return;
1744
+ }
1745
+ if (msg.id) {
1746
+ this.handleIncomingResponse(msg);
1747
+ }
1748
+ }
1749
+ verifyHandshakeHmac(currentAuth, hmac) {
1750
+ if (!currentAuth.hmacSalt || !hmac) return false;
1751
+ const secret = deriveSharedSecret(this.authToken, currentAuth.hmacSalt);
1752
+ const expectedHmac = computeHmac(secret, currentAuth.challenge);
1753
+ if (verifyHmacConstantTime(hmac, expectedHmac)) {
1754
+ return true;
1755
+ }
1756
+ if (!this.explicitAuthToken) {
1757
+ const diskToken = resolveOrCreateAuthToken();
1758
+ if (diskToken && diskToken !== this.authToken) {
1759
+ const diskSecret = deriveSharedSecret(diskToken, currentAuth.hmacSalt);
1760
+ const diskExpectedHmac = computeHmac(diskSecret, currentAuth.challenge);
1761
+ if (verifyHmacConstantTime(hmac, diskExpectedHmac)) {
1762
+ this.authToken = diskToken;
1763
+ return true;
1764
+ }
1765
+ }
1766
+ }
1767
+ return false;
1768
+ }
1769
+ async handleHandshake(socket, currentAuth, msg) {
1770
+ if (!currentAuth || msg.type !== "BRIDGE_AUTH" || msg.challenge !== currentAuth.challenge) {
1771
+ try {
1772
+ socket.close(WS_CLOSE_CODE.UNAUTHORIZED, "Unauthorized: Handshake failed");
1773
+ } catch {
1774
+ }
1775
+ return;
1776
+ }
1777
+ const clientVersion = typeof msg.protocolVersion === "string" ? msg.protocolVersion : PROTOCOL_VERSION;
1778
+ if (parseMajorVersion(clientVersion) !== parseMajorVersion(PROTOCOL_VERSION)) {
1779
+ try {
1780
+ socket.close(
1781
+ WS_CLOSE_CODE.PROTOCOL_MISMATCH,
1782
+ `Protocol version mismatch: server=${PROTOCOL_VERSION}, client=${clientVersion}`
1783
+ );
1784
+ } catch {
1785
+ }
1786
+ return;
1787
+ }
1788
+ const verified = this.verifyHandshakeHmac(currentAuth, msg.hmac);
1789
+ if (!verified) {
1790
+ const tokenFingerprint = this.authToken ? `${this.authToken.slice(0, 6)}...` : "none";
1791
+ process.stderr.write(
1792
+ `[webmcp-cli] HMAC \u9A8C\u8BC1\u5931\u8D25\uFF0C\u62D2\u7EDD\u8FDE\u63A5. client extensionId=${msg.extensionId}, server authTokenFingerprint=${tokenFingerprint}
1793
+ `
1794
+ );
1795
+ try {
1796
+ socket.close(WS_CLOSE_CODE.UNAUTHORIZED, "Unauthorized: HMAC verification failed");
1797
+ } catch {
1798
+ }
1799
+ return;
1800
+ }
1801
+ clearTimeout(currentAuth.timer);
1802
+ currentAuth.authenticated = true;
1803
+ currentAuth.clientType = msg.clientType;
1804
+ if (msg.clientType === "extension") {
1805
+ if (this.extensionSocket && this.extensionSocket !== socket) {
1806
+ try {
1807
+ this.extensionSocket.close(WS_CLOSE_CODE.REPLACED, "Replaced by new connection");
1808
+ } catch {
1809
+ }
1810
+ }
1811
+ this.extensionSocket = socket;
1812
+ this.emit("connected");
1813
+ }
1814
+ try {
1815
+ socket.send(
1816
+ JSON.stringify({
1817
+ type: "BRIDGE_AUTH_OK",
1818
+ clientType: msg.clientType
1819
+ })
1820
+ );
1821
+ } catch {
1822
+ }
1823
+ }
1824
+ async handleForwardRpc(socket, msg) {
1825
+ let targetSocket = this._getActiveSocket();
1826
+ if (!targetSocket) {
1827
+ await new Promise((resolve3) => {
1828
+ const timer2 = setTimeout(resolve3, 6e3);
1829
+ this.once("connected", () => {
1830
+ clearTimeout(timer2);
1831
+ resolve3();
1832
+ });
1833
+ });
1834
+ targetSocket = this._getActiveSocket();
1835
+ }
1836
+ if (!targetSocket) {
1837
+ socket.send(
1838
+ JSON.stringify({
1839
+ jsonrpc: "2.0",
1840
+ id: msg.id,
1841
+ error: {
1842
+ code: BRIDGE_ERROR_CODE.EXTENSION_NOT_CONNECTED,
1843
+ message: "Chrome \u6269\u5C55\u5C1A\u672A\u8FDE\u63A5\u5230\u672C\u5730\u6865\u63A5\u670D\u52A1\u3002\u8BF7\u786E\u4FDD\u6D4F\u89C8\u5668\u5DF2\u542F\u52A8\uFF0C\u4E14\u5728\u4FA7\u8FB9\u680F\u4E2D\u5F00\u542F\u4E86\u300C\u672C\u5730 WebSocket \u6865\u63A5\u300D\u5F00\u5173\u3002"
1844
+ }
1845
+ })
1846
+ );
1847
+ return;
1848
+ }
1849
+ const internalId = `fwd_${++this.idCounter}_${Date.now()}`;
1850
+ const timeoutMs = msg.method === "sub_agent/run" ? 18e4 : REQUEST_TIMEOUT_MS;
1851
+ const timer = setTimeout(() => {
1852
+ const fwd = this.forwardedRequests.get(internalId);
1853
+ if (!fwd) return;
1854
+ this.forwardedRequests.delete(internalId);
1855
+ try {
1856
+ if (fwd.socket.readyState === WS_OPEN) {
1857
+ fwd.socket.send(
1858
+ JSON.stringify({
1859
+ jsonrpc: "2.0",
1860
+ id: fwd.originalId,
1861
+ error: {
1862
+ code: BRIDGE_ERROR_CODE.REQUEST_TIMEOUT,
1863
+ message: `\u8BF7\u6C42\u8F6C\u53D1\u81F3 Chrome \u6269\u5C55\u8D85\u65F6 (${timeoutMs / 1e3}s)`
1864
+ }
1865
+ })
1866
+ );
1867
+ }
1868
+ } catch {
1869
+ }
1870
+ }, timeoutMs);
1871
+ this.forwardedRequests.set(internalId, {
1872
+ socket,
1873
+ originalId: msg.id,
1874
+ progressToken: msg.params?.progressToken,
1875
+ timer
1876
+ });
1877
+ const outgoingMsg = { ...msg, id: internalId };
1878
+ targetSocket.send(JSON.stringify(outgoingMsg));
1879
+ }
1880
+ sendJsonRpcResponse(socket, response) {
1881
+ if (socket.readyState === WS_OPEN) {
1882
+ socket.send(JSON.stringify({ jsonrpc: "2.0", ...response }));
1883
+ }
1884
+ }
1885
+ formatSystemRpcError(err) {
1886
+ if (err instanceof BashInvalidParamsError || err?.code === "INVALID_PARAMS" || err?.message === "\u547D\u4EE4\u4E0D\u80FD\u4E3A\u7A7A") {
1887
+ return { code: BRIDGE_ERROR_CODE.INVALID_PARAMS, message: err?.message || "\u53C2\u6570\u9519\u8BEF" };
1888
+ }
1889
+ if (err instanceof BashTimeoutError || err?.code === "TIMEOUT" || typeof err?.message === "string" && err.message.includes("\u8D85\u65F6")) {
1890
+ return { code: BRIDGE_ERROR_CODE.EXECUTION_TIMEOUT, message: err?.message || "\u547D\u4EE4\u6267\u884C\u8D85\u65F6" };
1891
+ }
1892
+ return { code: BRIDGE_ERROR_CODE.EXECUTION_FAILED, message: err?.message || "\u6267\u884C\u5931\u8D25" };
1893
+ }
1894
+ systemRpcHandlers = Object.assign(
1895
+ /* @__PURE__ */ Object.create(null),
1896
+ {
1897
+ [BRIDGE_METHODS.SYSTEM_BASH]: async (params) => {
1898
+ return executeBash(params || {});
1899
+ },
1900
+ [BRIDGE_METHODS.SYSTEM_PICK_DIRECTORY]: async (params) => {
1901
+ const selectedPath = await pickDirectory({
1902
+ title: params?.title || void 0,
1903
+ defaultPath: params?.defaultPath || void 0
1904
+ });
1905
+ return {
1906
+ path: selectedPath,
1907
+ selectedPath,
1908
+ canceled: selectedPath === null
1909
+ };
1910
+ }
1911
+ }
1912
+ );
1913
+ async handleExtensionSystemRpc(socket, msg) {
1914
+ const { id, method, params } = msg;
1915
+ const handler = typeof method === "string" && Object.prototype.hasOwnProperty.call(this.systemRpcHandlers, method) ? this.systemRpcHandlers[method] : void 0;
1916
+ if (!handler || typeof handler !== "function") {
1917
+ this.sendJsonRpcResponse(socket, {
1918
+ id,
1919
+ error: {
1920
+ code: BRIDGE_ERROR_CODE.METHOD_NOT_FOUND,
1921
+ message: `\u4E0D\u652F\u6301\u7684\u65B9\u6CD5: ${method}`
1922
+ }
1923
+ });
1924
+ return;
1925
+ }
1926
+ try {
1927
+ const result = await handler(params);
1928
+ this.sendJsonRpcResponse(socket, { id, result });
1929
+ } catch (err) {
1930
+ this.sendJsonRpcResponse(socket, { id, error: this.formatSystemRpcError(err) });
1931
+ }
1932
+ }
1933
+ handleProgressNotification(msg) {
1934
+ const token = msg.params?.progressToken;
1935
+ if (token != null) {
1936
+ for (const [, reqInfo] of this.forwardedRequests) {
1937
+ if (reqInfo.progressToken === token) {
1938
+ try {
1939
+ if (reqInfo.socket.readyState === WS_OPEN) {
1940
+ reqInfo.socket.send(JSON.stringify(msg));
1941
+ }
1942
+ } catch {
1943
+ }
1944
+ }
1945
+ }
1946
+ }
1947
+ this.emit("progress", msg.params);
1948
+ }
1949
+ handleIncomingResponse(msg) {
1950
+ const fwdInfo = this.forwardedRequests.get(String(msg.id));
1951
+ if (fwdInfo) {
1952
+ if (fwdInfo.timer) clearTimeout(fwdInfo.timer);
1953
+ this.forwardedRequests.delete(String(msg.id));
1954
+ try {
1955
+ if (fwdInfo.socket.readyState === WS_OPEN) {
1956
+ fwdInfo.socket.send(
1957
+ JSON.stringify({
1958
+ ...msg,
1959
+ id: fwdInfo.originalId
1960
+ })
1961
+ );
1962
+ }
1963
+ } catch {
1964
+ }
1965
+ return;
1966
+ }
1967
+ const pending = this.pending.get(String(msg.id));
1968
+ if (!pending) return;
1969
+ this.pending.delete(String(msg.id));
1970
+ clearTimeout(pending.timer);
1971
+ if (msg.error) {
1972
+ pending.reject(new Error(`[${msg.error.code}] ${msg.error.message}`));
1973
+ } else {
1974
+ pending.resolve(msg.result);
1975
+ }
1976
+ }
1977
+ /** 发送 JSON-RPC 2.0 请求,返回 result */
1978
+ async call(method, params = {}, timeoutMs, progressToken, autoWaitMs = 0) {
1979
+ if (autoWaitMs > 0 && !this.isConnected) {
1980
+ await this.waitForReady(autoWaitMs);
1981
+ }
1982
+ const targetSocket = this._getActiveSocket();
1983
+ if (!targetSocket) {
1984
+ throw new Error(
1985
+ "\u4E0E Chrome \u6269\u5C55\u7684\u8FDE\u63A5\u5C1A\u672A\u5C31\u7EEA\uFF0C\u8BF7\u786E\u4FDD\uFF1A\n 1. Chrome \u6D4F\u89C8\u5668\u5DF2\u542F\u52A8\n 2. Tiny Robot \u6269\u5C55\u5DF2\u5B89\u88C5\u5E76\u5F00\u542F\n 3. \u6269\u5C55\u4FA7\u8FB9\u680F\u5DF2\u6253\u5F00"
1986
+ );
1987
+ }
1988
+ const effectiveTimeoutMs = timeoutMs ?? (method === "sub_agent/run" ? 18e4 : REQUEST_TIMEOUT_MS);
1989
+ const id = String(++this.idCounter);
1990
+ const requestParams = { ...params };
1991
+ if (progressToken != null) {
1992
+ requestParams.progressToken = progressToken;
1993
+ }
1994
+ const request = { jsonrpc: "2.0", id, method, params: requestParams };
1995
+ return new Promise((resolve3, reject) => {
1996
+ const timer = setTimeout(() => {
1997
+ this.pending.delete(id);
1998
+ reject(new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${effectiveTimeoutMs / 1e3}s\uFF09\uFF1A${method}`));
1999
+ }, effectiveTimeoutMs);
2000
+ this.pending.set(id, { resolve: resolve3, reject, timer });
2001
+ try {
2002
+ targetSocket.send(JSON.stringify(request));
2003
+ } catch (err) {
2004
+ this.pending.delete(id);
2005
+ clearTimeout(timer);
2006
+ reject(err instanceof Error ? err : new Error(String(err)));
2007
+ }
2008
+ });
2009
+ }
2010
+ /** 销毁服务,断开所有连接 */
2011
+ destroy() {
2012
+ this.destroyed = true;
2013
+ this._rejectAllPending("ExtensionBridgeClient \u5DF2\u9500\u6BC1");
2014
+ this.forwardedRequests.clear();
2015
+ if (this.clientSocket) {
2016
+ try {
2017
+ this.clientSocket.close();
2018
+ } catch {
2019
+ }
2020
+ this.clientSocket = null;
2021
+ }
2022
+ if (this.extensionSocket) {
2023
+ try {
2024
+ this.extensionSocket.close();
2025
+ } catch {
2026
+ }
2027
+ this.extensionSocket = null;
2028
+ }
2029
+ if (this.wss) {
2030
+ try {
2031
+ this.wss.close();
2032
+ } catch {
2033
+ }
2034
+ this.wss = null;
2035
+ }
2036
+ }
2037
+ _rejectAllPending(reason) {
2038
+ for (const [, pending] of this.pending) {
2039
+ clearTimeout(pending.timer);
2040
+ pending.reject(new Error(reason));
2041
+ }
2042
+ this.pending.clear();
2043
+ for (const [, fwdInfo] of this.forwardedRequests) {
2044
+ if (fwdInfo.timer) clearTimeout(fwdInfo.timer);
2045
+ }
2046
+ this.forwardedRequests.clear();
2047
+ }
2048
+ };
2049
+ }
2050
+ });
2051
+
2052
+ // src/adapters/wxt-adapter.ts
2053
+ var wxt_adapter_exports = {};
2054
+ __export(wxt_adapter_exports, {
2055
+ WxtBrowserAdapter: () => WxtBrowserAdapter
2056
+ });
2057
+ var AUTO_WAIT_MS, WxtBrowserAdapter;
2058
+ var init_wxt_adapter = __esm({
2059
+ "src/adapters/wxt-adapter.ts"() {
2060
+ "use strict";
2061
+ init_bridge_client();
2062
+ init_protocol();
2063
+ AUTO_WAIT_MS = 6e3;
2064
+ WxtBrowserAdapter = class {
2065
+ client;
2066
+ constructor(token, port) {
2067
+ this.client = new ExtensionBridgeClient(port, token);
2068
+ this.client.on("error", () => {
2069
+ });
2070
+ }
2071
+ /** 确保 WS 桥接服务已启动并连接 */
2072
+ async ensureConnected() {
2073
+ await this.client.startAuto();
2074
+ }
2075
+ async getState(tabId) {
2076
+ const numTabId = typeof tabId === "string" ? parseInt(tabId, 10) || void 0 : tabId;
2077
+ const result = await this.client.call(
2078
+ BRIDGE_METHODS.BROWSER_STATE,
2079
+ { tabId: numTabId },
2080
+ void 0,
2081
+ void 0,
2082
+ AUTO_WAIT_MS
2083
+ );
2084
+ return result;
2085
+ }
2086
+ async callTool(toolName, args, tabId) {
2087
+ const numTabId = typeof tabId === "string" ? parseInt(tabId, 10) || void 0 : tabId;
2088
+ return this.client.call(
2089
+ BRIDGE_METHODS.TOOL_CALL,
2090
+ { toolName, toolArgs: args, tabId: numTabId },
2091
+ void 0,
2092
+ void 0,
2093
+ AUTO_WAIT_MS
2094
+ );
2095
+ }
2096
+ async tabs(action, options) {
2097
+ const numTabId = typeof options.tabId === "string" ? parseInt(options.tabId, 10) || void 0 : options.tabId;
2098
+ return this.client.call(
2099
+ BRIDGE_METHODS.BROWSER_TABS,
2100
+ { tabAction: action, ...options, tabId: numTabId },
2101
+ void 0,
2102
+ void 0,
2103
+ AUTO_WAIT_MS
2104
+ );
2105
+ }
2106
+ /** 委托扩展内 Tiny Robot 子代理闭环执行高层任务 */
2107
+ async runSubAgent(instruction, options = {}, timeoutMs) {
2108
+ const params = { instruction, tabId: options.tabId, maxSteps: options.maxSteps };
2109
+ return this.client.call(
2110
+ BRIDGE_METHODS.SUB_AGENT_RUN,
2111
+ params,
2112
+ timeoutMs,
2113
+ options.progressToken,
2114
+ AUTO_WAIT_MS
2115
+ );
2116
+ }
2117
+ /** 获取已注册的 Skills 列表(L1 索引) */
2118
+ async listSkills() {
2119
+ return this.client.call(BRIDGE_METHODS.SKILLS_LIST, {}, void 0, void 0, AUTO_WAIT_MS);
2120
+ }
2121
+ /** 读取指定 Skill 的详细指令(L2 详情) */
2122
+ async getSkill(name) {
2123
+ return this.client.call(BRIDGE_METHODS.SKILLS_GET, { name }, void 0, void 0, AUTO_WAIT_MS);
2124
+ }
2125
+ /** 读取 Skill 关联资源(L3 资源) */
2126
+ async readSkillResource(name, resourcePath) {
2127
+ return this.client.call(
2128
+ BRIDGE_METHODS.SKILLS_READ_RESOURCE,
2129
+ { name, resourcePath },
2130
+ void 0,
2131
+ void 0,
2132
+ AUTO_WAIT_MS
2133
+ );
2134
+ }
2135
+ /** 获取底层 ExtensionBridgeClient(供 MCP Server 绑定事件) */
2136
+ get bridgeClient() {
2137
+ return this.client;
2138
+ }
2139
+ async dispose() {
2140
+ this.client.destroy();
2141
+ }
2142
+ };
2143
+ }
2144
+ });
2145
+
2146
+ // src/bridge/daemon.ts
2147
+ var daemon_exports = {};
2148
+ __export(daemon_exports, {
2149
+ PID_FILE: () => PID_FILE,
2150
+ ensureBridgeDaemon: () => ensureBridgeDaemon,
2151
+ findPidByPort: () => findPidByPort,
2152
+ getDaemonPidFile: () => getDaemonPidFile,
2153
+ isBridgeDaemonProcess: () => isBridgeDaemonProcess,
2154
+ isDaemonProcessAlive: () => isDaemonProcessAlive,
2155
+ isProcessAlive: () => isProcessAlive,
2156
+ killProcessOnPort: () => killProcessOnPort,
2157
+ killProcessTree: () => killProcessTree2,
2158
+ probeServerReady: () => probeServerReady,
2159
+ runDaemonProcess: () => runDaemonProcess,
2160
+ stopBridgeDaemon: () => stopBridgeDaemon
2161
+ });
2162
+ function getDaemonPidFile(port = WS_PORT2) {
2163
+ if (port === WS_PORT2) {
2164
+ return import_node_path4.default.join(DAEMON_DIR, "daemon.pid");
2165
+ }
2166
+ return import_node_path4.default.join(DAEMON_DIR, `daemon-${port}.pid`);
2167
+ }
2168
+ function isProcessAlive(pid) {
2169
+ if (!pid || pid <= 0) return false;
2170
+ try {
2171
+ process.kill(pid, 0);
2172
+ return true;
2173
+ } catch {
2174
+ return false;
2175
+ }
2176
+ }
2177
+ async function findPidByPort(port, excludePid) {
2178
+ if (process.platform === "win32") {
2179
+ try {
2180
+ const { stdout } = await execAsync("netstat -ano -p tcp");
2181
+ const lines = stdout.split(/\r?\n/);
2182
+ for (const rawLine of lines) {
2183
+ const line = rawLine.trim();
2184
+ if (!line.toUpperCase().startsWith("TCP")) continue;
2185
+ const parts = line.split(/\s+/);
2186
+ if (parts.length < 5) continue;
2187
+ const localAddr = parts[1];
2188
+ const state = parts[3]?.toUpperCase() || "";
2189
+ const pid = parseInt(parts[parts.length - 1], 10);
2190
+ if (!pid || isNaN(pid) || excludePid && pid === excludePid) continue;
2191
+ if (localAddr.endsWith(`:${port}`)) {
2192
+ if (state.includes("LISTEN") || state.includes("\u4FA6\u542C")) {
2193
+ return pid;
2194
+ }
2195
+ }
2196
+ }
2197
+ return null;
2198
+ } catch {
2199
+ return null;
2200
+ }
2201
+ }
2202
+ try {
2203
+ const { stdout } = await execAsync(`lsof -nP -iTCP:${port} -sTCP:LISTEN -t`);
2204
+ const pids = stdout.trim().split("\n").map((p) => parseInt(p.trim(), 10)).filter((p) => Boolean(p && !isNaN(p) && (!excludePid || p !== excludePid)));
2205
+ return pids[0] ?? null;
2206
+ } catch {
2207
+ return null;
2208
+ }
2209
+ }
2210
+ async function killProcessTree2(pid) {
2211
+ if (!pid || pid <= 0 || pid === process.pid) return false;
2212
+ if (process.platform === "win32") {
2213
+ try {
2214
+ await execAsync(`taskkill /pid ${pid} /T /F`);
2215
+ } catch {
2216
+ try {
2217
+ process.kill(pid, "SIGKILL");
2218
+ } catch {
2219
+ }
2220
+ }
2221
+ for (let i = 0; i < 15; i++) {
2222
+ await new Promise((r) => setTimeout(r, 100));
2223
+ if (!isProcessAlive(pid)) return true;
2224
+ }
2225
+ return !isProcessAlive(pid);
2226
+ }
2227
+ try {
2228
+ process.kill(pid, "SIGTERM");
2229
+ } catch {
2230
+ }
2231
+ for (let i = 0; i < 10; i++) {
2232
+ await new Promise((r) => setTimeout(r, 100));
2233
+ if (!isProcessAlive(pid)) return true;
2234
+ }
2235
+ try {
2236
+ process.kill(pid, "SIGKILL");
2237
+ } catch {
2238
+ }
2239
+ for (let i = 0; i < 5; i++) {
2240
+ await new Promise((r) => setTimeout(r, 100));
2241
+ if (!isProcessAlive(pid)) return true;
2242
+ }
2243
+ return !isProcessAlive(pid);
2244
+ }
2245
+ async function killProcessOnPort(port) {
2246
+ const pid = await findPidByPort(port, process.pid);
2247
+ if (pid) {
2248
+ await killProcessTree2(pid);
2249
+ for (let i = 0; i < 20; i++) {
2250
+ await new Promise((r) => setTimeout(r, 100));
2251
+ const remainingPid = await findPidByPort(port, process.pid);
2252
+ if (!remainingPid) return true;
2253
+ }
2254
+ }
2255
+ return false;
2256
+ }
2257
+ async function probeServerReady(port = WS_PORT2, token, timeoutMs = 1e3) {
2258
+ return ExtensionBridgeClient.probe(port, token ?? resolveOrCreateAuthToken(), timeoutMs);
2259
+ }
2260
+ function isDaemonProcessAlive(port = WS_PORT2) {
2261
+ const pidFile = getDaemonPidFile(port);
2262
+ if (!import_node_fs4.default.existsSync(pidFile)) return false;
2263
+ try {
2264
+ const pid = parseInt(import_node_fs4.default.readFileSync(pidFile, "utf8").trim(), 10);
2265
+ return Boolean(pid && isProcessAlive(pid));
2266
+ } catch {
2267
+ return false;
2268
+ }
2269
+ }
2270
+ async function ensureBridgeDaemon(options = {}) {
2271
+ const port = options.port ?? WS_PORT2;
2272
+ const token = options.token ?? resolveOrCreateAuthToken();
2273
+ const timeoutMs = options.timeoutMs ?? 6e3;
2274
+ const probe = await probeServerReady(port, token, 800);
2275
+ if (probe.running && probe.authed) {
2276
+ return { newlyStarted: false };
2277
+ }
2278
+ if (probe.running && !probe.authed) {
2279
+ if (!options.silent) {
2280
+ console.log(
2281
+ `\x1B[33m[webmcp-cli]\x1B[0m \u{1F504} \u68C0\u6D4B\u5230\u540E\u53F0\u6865\u63A5\u670D\u52A1 Token \u4E0D\u5339\u914D\uFF0C\u6B63\u5728\u9A8C\u8BC1\u65E7\u5B88\u62A4\u8FDB\u7A0B\u5F52\u5C5E\u5E76\u5C1D\u8BD5\u81EA\u52A8\u91CD\u542F...`
2282
+ );
2283
+ }
2284
+ const stopped = await stopBridgeDaemon(port, { onlyVerified: true });
2285
+ if (!stopped) {
2286
+ const killTip = getKillPortHint(port);
2287
+ throw new Error(
2288
+ `\u672C\u5730 127.0.0.1:${port} \u6B63\u5728\u8FD0\u884C\u670D\u52A1\uFF0C\u4F46\u8BA4\u8BC1\u672A\u901A\u8FC7\uFF08${probe.error || "Token \u4E0D\u5339\u914D"}\uFF09\u3002
2289
+ \u672A\u80FD\u786E\u8BA4\u8BE5\u8FDB\u7A0B\u5F52\u5C5E\u4E8E\u53D7\u7BA1\u7684\u6865\u63A5\u5B88\u62A4\u8FDB\u7A0B\uFF0C\u4E3A\u5B89\u5168\u8D77\u89C1\u5DF2\u963B\u6B62\u81EA\u52A8\u5F3A\u6740\u3002\u8BF7\u68C0\u67E5\u7AEF\u53E3 ${port} \u662F\u5426\u88AB\u5176\u4ED6\u5E94\u7528\u5360\u7528\uFF0C\u6216\u624B\u52A8\u7EC8\u6B62\uFF08\u53EF\u6267\u884C: ${killTip}\uFF09\u3002`
2290
+ );
2291
+ }
2292
+ await new Promise((r) => setTimeout(r, 400));
2293
+ }
2294
+ if (!options.silent) {
2295
+ console.log(`\x1B[36m[webmcp-cli]\x1B[0m \u{1F680} \u672C\u5730\u6865\u63A5\u670D\u52A1\u672A\u8FD0\u884C\uFF0C\u6B63\u5728\u81EA\u52A8\u62C9\u8D77\u5E38\u9A7B\u670D\u52A1 (127.0.0.1:${port})...`);
2296
+ }
2297
+ startDaemonProcessBackground(token, port);
2298
+ const startTime = Date.now();
2299
+ while (Date.now() - startTime < timeoutMs) {
2300
+ await new Promise((r) => setTimeout(r, 200));
2301
+ const check = await probeServerReady(port, token, 400);
2302
+ if (check.running && check.authed) {
2303
+ if (!options.silent) {
2304
+ console.log(`\x1B[32m[webmcp-cli]\x1B[0m \u2705 \u6865\u63A5\u670D\u52A1\u5DF2\u542F\u52A8\uFF0C\u6B63\u5728\u7B49\u5F85 Chrome \u6269\u5C55\u8FDE\u63A5...`);
2305
+ }
2306
+ return { newlyStarted: true };
2307
+ }
2308
+ }
2309
+ throw new Error(`\u542F\u52A8\u540E\u53F0 WebSocket \u6865\u63A5\u670D\u52A1\u8D85\u65F6\uFF08${timeoutMs}ms\uFF09\uFF0C\u8BF7\u68C0\u67E5\u7AEF\u53E3 ${port} \u662F\u5426\u53EF\u7528\u3002`);
2310
+ }
2311
+ function resolveCliEntry() {
2312
+ const currentDir = import_node_path4.default.dirname((0, import_node_url.fileURLToPath)(import_meta2.url));
2313
+ const distCandidate = import_node_path4.default.join(currentDir, "bin.js");
2314
+ if (import_node_fs4.default.existsSync(distCandidate)) return distCandidate;
2315
+ const projectDistCandidate = import_node_path4.default.resolve(currentDir, "../dist/bin.js");
2316
+ if (import_node_fs4.default.existsSync(projectDistCandidate)) return projectDistCandidate;
2317
+ return distCandidate;
2318
+ }
2319
+ function startDaemonProcessBackground(token, port) {
2320
+ const cliEntry = resolveCliEntry();
2321
+ if (!import_node_fs4.default.existsSync(DAEMON_DIR)) {
2322
+ import_node_fs4.default.mkdirSync(DAEMON_DIR, { mode: 448, recursive: true });
2323
+ }
2324
+ const child = (0, import_node_child_process3.spawn)(process.execPath, [cliEntry, "--mode", "wxt", "daemon", "--port", String(port)], {
2325
+ detached: true,
2326
+ stdio: "ignore",
2327
+ windowsHide: true,
2328
+ env: {
2329
+ ...process.env,
2330
+ ROBOT_WXT_BRIDGE_TOKEN: token
2331
+ }
2332
+ });
2333
+ child.unref();
2334
+ }
2335
+ async function runDaemonProcess(args) {
2336
+ let port = WS_PORT2;
2337
+ let token;
2338
+ const portIdx = args.indexOf("--port");
2339
+ if (portIdx !== -1 && args[portIdx + 1]) {
2340
+ port = parseInt(args[portIdx + 1], 10);
2341
+ }
2342
+ const tokenIdx = args.indexOf("--token");
2343
+ if (tokenIdx !== -1 && args[tokenIdx + 1]) {
2344
+ token = args[tokenIdx + 1];
2345
+ } else if (process.env.ROBOT_WXT_BRIDGE_TOKEN) {
2346
+ token = process.env.ROBOT_WXT_BRIDGE_TOKEN;
2347
+ }
2348
+ const client = new ExtensionBridgeClient(port, token);
2349
+ client.on("error", (err) => {
2350
+ if (err && (err.code === "EADDRINUSE" || err.message?.includes("EADDRINUSE"))) {
2351
+ process.exit(1);
2352
+ }
2353
+ });
2354
+ const pidFile = getDaemonPidFile(port);
2355
+ client.on("listening", () => {
2356
+ try {
2357
+ if (!import_node_fs4.default.existsSync(DAEMON_DIR)) {
2358
+ import_node_fs4.default.mkdirSync(DAEMON_DIR, { mode: 448, recursive: true });
2359
+ }
2360
+ import_node_fs4.default.writeFileSync(pidFile, String(process.pid), { mode: 384, encoding: "utf8" });
2361
+ } catch {
2362
+ }
2363
+ });
2364
+ client.connect();
2365
+ const shutdown = () => {
2366
+ try {
2367
+ if (import_node_fs4.default.existsSync(pidFile)) {
2368
+ const recordedPid = import_node_fs4.default.readFileSync(pidFile, "utf8").trim();
2369
+ if (recordedPid === String(process.pid)) {
2370
+ import_node_fs4.default.unlinkSync(pidFile);
2371
+ }
2372
+ }
2373
+ } catch {
2374
+ }
2375
+ client.destroy();
2376
+ process.exit(0);
2377
+ };
2378
+ process.on("SIGINT", shutdown);
2379
+ process.on("SIGTERM", shutdown);
2380
+ process.on("exit", shutdown);
2381
+ setInterval(() => {
2382
+ }, 6e4);
2383
+ }
2384
+ async function isBridgeDaemonProcess(pid) {
2385
+ if (!pid || pid <= 0 || !isProcessAlive(pid)) return false;
2386
+ try {
2387
+ let cmd = "";
2388
+ if (process.platform === "win32") {
2389
+ const { stdout } = await execAsync(
2390
+ `powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter \\"ProcessId = ${pid}\\").CommandLine"`
2391
+ );
2392
+ cmd = stdout.trim();
2393
+ } else {
2394
+ const { stdout } = await execAsync(`ps -p ${pid} -o command=`);
2395
+ cmd = stdout.trim();
2396
+ }
2397
+ if (!cmd) return false;
2398
+ return (cmd.includes("webmcp-cli") || cmd.includes("bin.js") || cmd.includes("daemon.js")) && cmd.includes("daemon");
2399
+ } catch {
2400
+ return false;
2401
+ }
2402
+ }
2403
+ async function stopBridgeDaemon(port = WS_PORT2, options = {}) {
2404
+ const onlyVerified = options.onlyVerified ?? false;
2405
+ let killedAny = false;
2406
+ const pidFile = getDaemonPidFile(port);
2407
+ let daemonPid = null;
2408
+ if (import_node_fs4.default.existsSync(pidFile)) {
2409
+ try {
2410
+ const pidStr = import_node_fs4.default.readFileSync(pidFile, "utf8").trim();
2411
+ const p = parseInt(pidStr, 10);
2412
+ if (p && isProcessAlive(p)) {
2413
+ daemonPid = p;
2414
+ }
2415
+ } catch {
2416
+ }
2417
+ }
2418
+ if (onlyVerified) {
2419
+ if (!daemonPid) {
2420
+ return false;
2421
+ }
2422
+ const isVerified = await isBridgeDaemonProcess(daemonPid);
2423
+ if (!isVerified) {
2424
+ return false;
2425
+ }
2426
+ const portPid = await findPidByPort(port, process.pid);
2427
+ if (portPid && portPid !== daemonPid) {
2428
+ return false;
2429
+ }
2430
+ const killed = await killProcessTree2(daemonPid);
2431
+ if (killed) {
2432
+ killedAny = true;
2433
+ try {
2434
+ if (import_node_fs4.default.existsSync(pidFile)) import_node_fs4.default.unlinkSync(pidFile);
2435
+ } catch {
2436
+ }
2437
+ }
2438
+ } else {
2439
+ if (daemonPid) {
2440
+ try {
2441
+ const killed = await killProcessTree2(daemonPid);
2442
+ if (killed) {
2443
+ killedAny = true;
2444
+ try {
2445
+ if (import_node_fs4.default.existsSync(pidFile)) import_node_fs4.default.unlinkSync(pidFile);
2446
+ } catch {
2447
+ }
2448
+ }
2449
+ } catch {
2450
+ }
2451
+ }
2452
+ const portPid = await findPidByPort(port, process.pid);
2453
+ if (portPid) {
2454
+ const killedByPort = await killProcessOnPort(port);
2455
+ if (killedByPort) {
2456
+ killedAny = true;
2457
+ }
2458
+ }
2459
+ }
2460
+ let portReleased = false;
2461
+ for (let i = 0; i < 10; i++) {
2462
+ const remainingPid = await findPidByPort(port, process.pid);
2463
+ if (!remainingPid) {
2464
+ portReleased = true;
2465
+ break;
2466
+ }
2467
+ await new Promise((r) => setTimeout(r, 200));
2468
+ }
2469
+ if (!portReleased) {
2470
+ return false;
2471
+ }
2472
+ return killedAny;
2473
+ }
2474
+ var import_node_child_process3, import_node_util, import_node_fs4, import_node_path4, import_node_os3, import_node_url, import_meta2, execAsync, WS_PORT2, DAEMON_DIR, PID_FILE;
2475
+ var init_daemon = __esm({
2476
+ "src/bridge/daemon.ts"() {
2477
+ "use strict";
2478
+ import_node_child_process3 = require("child_process");
2479
+ import_node_util = require("util");
2480
+ import_node_fs4 = __toESM(require("fs"), 1);
2481
+ import_node_path4 = __toESM(require("path"), 1);
2482
+ import_node_os3 = __toESM(require("os"), 1);
2483
+ import_node_url = require("url");
2484
+ init_bridge_client();
2485
+ import_meta2 = {};
2486
+ execAsync = (0, import_node_util.promisify)(import_node_child_process3.exec);
2487
+ WS_PORT2 = 18999;
2488
+ DAEMON_DIR = import_node_path4.default.join(import_node_os3.default.homedir(), ".robot-wxt");
2489
+ PID_FILE = getDaemonPidFile(WS_PORT2);
2490
+ }
2491
+ });
2492
+
2493
+ // src/mcp/server.ts
2494
+ var server_exports = {};
2495
+ __export(server_exports, {
2496
+ startMcpServer: () => startMcpServer
2497
+ });
2498
+ async function startMcpServer(options = {}) {
2499
+ const mode = options.mode ?? "cdp";
2500
+ const agentMode = options.agentMode ?? "tools";
2501
+ const isAgentMode = agentMode === "agent";
2502
+ const server = new import_mcp.McpServer({ name: SERVER_NAME, version: SERVER_VERSION });
2503
+ if (mode === "cdp") {
2504
+ if (isAgentMode) {
2505
+ throw new Error("--agent \u5B50\u4EE3\u7406\u59D4\u6258\u6A21\u5F0F\u4EC5\u5728 WXT \u6A21\u5F0F\u53EF\u7528\uFF0C\u8BF7\u4F7F\u7528: webmcp-cli --mode wxt mcp --agent");
2506
+ }
2507
+ await startCdpMcpServer(server, isAgentMode);
2508
+ } else {
2509
+ await startWxtMcpServer(server, isAgentMode, options);
2510
+ }
2511
+ const transport = new import_stdio.StdioServerTransport();
2512
+ await server.connect(transport);
2513
+ process.stderr.write(
2514
+ `[webmcp-cli] MCP Server \u5DF2\u542F\u52A8\uFF08${SERVER_NAME} v${SERVER_VERSION}\uFF0C\u6A21\u5F0F: ${mode}${isAgentMode ? "/agent" : "/tools"}\uFF09
2515
+ `
2516
+ );
2517
+ }
2518
+ async function startCdpMcpServer(server, isAgentMode) {
2519
+ const { CdpBrowserAdapter: CdpBrowserAdapter2 } = await Promise.resolve().then(() => (init_cdp_adapter(), cdp_adapter_exports));
2520
+ const adapter = new CdpBrowserAdapter2();
2521
+ registerCommonTools(server, adapter, isAgentMode);
2522
+ process.on("SIGINT", async () => {
2523
+ await adapter.dispose();
2524
+ process.exit(0);
2525
+ });
2526
+ process.on("SIGTERM", async () => {
2527
+ await adapter.dispose();
2528
+ process.exit(0);
2529
+ });
2530
+ }
2531
+ async function startWxtMcpServer(server, isAgentMode, options) {
2532
+ const { WxtBrowserAdapter: WxtBrowserAdapter2 } = await Promise.resolve().then(() => (init_wxt_adapter(), wxt_adapter_exports));
2533
+ const { ensureBridgeDaemon: ensureBridgeDaemon2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
2534
+ const daemonResult = await ensureBridgeDaemon2({
2535
+ token: options.token,
2536
+ port: options.wsPort,
2537
+ silent: true
2538
+ });
2539
+ const adapter = new WxtBrowserAdapter2(options.token, options.wsPort);
2540
+ await adapter.ensureConnected();
2541
+ if (daemonResult.newlyStarted) {
2542
+ process.stderr.write("[webmcp-cli] \u{1F680} \u672C\u5730\u6865\u63A5\u670D\u52A1\u5DF2\u542F\u52A8\uFF0C\u6B63\u5728\u7B49\u5F85 Chrome \u6269\u5C55\u8FDE\u63A5...\n");
2543
+ }
2544
+ const client = adapter.bridgeClient;
2545
+ registerCommonTools(server, adapter, isAgentMode);
2546
+ registerWxtTools(server, adapter, isAgentMode, server);
2547
+ registerSkillsResources(server, adapter);
2548
+ client.on("connected", () => {
2549
+ process.stderr.write("[webmcp-cli] \u5DF2\u8FDE\u63A5\u5230 Chrome \u6269\u5C55\n");
2550
+ try {
2551
+ server.server.notification({ method: "notifications/resources/list_changed" });
2552
+ } catch {
2553
+ }
2554
+ });
2555
+ client.on("disconnected", () => {
2556
+ process.stderr.write("[webmcp-cli] \u4E0E Chrome \u6269\u5C55\u7684\u8FDE\u63A5\u5DF2\u65AD\u5F00\n");
2557
+ });
2558
+ process.on("SIGINT", async () => {
2559
+ await adapter.dispose();
2560
+ process.exit(0);
2561
+ });
2562
+ process.on("SIGTERM", async () => {
2563
+ await adapter.dispose();
2564
+ process.exit(0);
2565
+ });
2566
+ const tokenFingerprint = options.token ? `${options.token.slice(0, 6)}...` : "(auto)";
2567
+ process.stderr.write(`[webmcp-cli] \u{1F511} Token \u6307\u7EB9: ${tokenFingerprint} (\u5B8C\u6574\u51ED\u636E\u89C1 ~/.robot-wxt/bridge-token)
2568
+ `);
2569
+ }
2570
+ function registerCommonTools(server, adapter, isAgentMode) {
2571
+ server.registerTool(
2572
+ "browser_state",
2573
+ {
2574
+ description: "\u83B7\u53D6\u5F53\u524D\u6D4F\u89C8\u5668\u72B6\u6001\uFF0C\u5305\u62EC\uFF1A\u5F53\u524D tab \u7684 URL / \u6807\u9898\u3001\u6240\u6709\u5DF2\u6253\u5F00\u7684 tab \u5217\u8868\u3001\u5F53\u524D\u9875\u9762\u6CE8\u518C\u7684 WebMCP \u5DE5\u5177\u5217\u8868\u3002\u5728\u6267\u884C\u64CD\u4F5C\u524D\uFF0C\u5EFA\u8BAE\u5148\u8C03\u7528\u6B64\u5DE5\u5177\u4E86\u89E3\u5F53\u524D\u6D4F\u89C8\u5668\u4E0A\u4E0B\u6587\u3002",
2575
+ inputSchema: BrowserStateInput.shape
2576
+ },
2577
+ async (args) => {
2578
+ const result = await adapter.getState(args.tabId);
2579
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
2580
+ }
2581
+ );
2582
+ if (!isAgentMode) {
2583
+ server.registerTool(
2584
+ "browser_tool_call",
2585
+ {
2586
+ description: "\u6267\u884C\u5F53\u524D\u9875\u9762\u6CE8\u518C\u7684 WebMCP \u5DE5\u5177\uFF08\u5982 click\u3001input\u3001scroll \u7B49\uFF09\u3002\u5DE5\u5177\u540D\u79F0\u548C\u53C2\u6570 schema \u901A\u8FC7 browser_state \u8FD4\u56DE\u7684 webmcpTools \u5B57\u6BB5\u83B7\u53D6\u3002",
2587
+ inputSchema: BrowserToolCallInput.shape
2588
+ },
2589
+ async (args) => {
2590
+ const result = await adapter.callTool(args.toolName, args.toolArgs ?? {}, args.tabId);
2591
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
2592
+ }
2593
+ );
2594
+ server.registerTool(
2595
+ "browser_tabs_open",
2596
+ { description: "\u5728\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u4E00\u4E2A\u65B0\u6807\u7B7E\u9875\u5E76\u5BFC\u822A\u5230\u6307\u5B9A URL\u3002", inputSchema: BrowserTabsOpenInput.shape },
2597
+ async (args) => {
2598
+ const result = await adapter.tabs("open", { url: args.url });
2599
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
2600
+ }
2601
+ );
2602
+ server.registerTool(
2603
+ "browser_tabs_close",
2604
+ { description: "\u5173\u95ED\u6307\u5B9A\u6807\u7B7E\u9875\uFF08\u4E0D\u6307\u5B9A tabId \u65F6\u5173\u95ED\u5F53\u524D\u6D3B\u8DC3\u6807\u7B7E\u9875\uFF09\u3002", inputSchema: BrowserTabsCloseInput.shape },
2605
+ async (args) => {
2606
+ const result = await adapter.tabs("close", { tabId: args.tabId });
2607
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
2608
+ }
2609
+ );
2610
+ server.registerTool(
2611
+ "browser_tabs_switch",
2612
+ {
2613
+ description: "\u5C06\u7126\u70B9\u5207\u6362\u5230\u6307\u5B9A\u6807\u7B7E\u9875\uFF08tabId \u901A\u8FC7 browser_state \u8FD4\u56DE\u7684 tabs \u5217\u8868\u83B7\u53D6\uFF09\u3002",
2614
+ inputSchema: BrowserTabsSwitchInput.shape
2615
+ },
2616
+ async (args) => {
2617
+ const result = await adapter.tabs("switch", { tabId: args.tabId, activateVisible: args.activateVisible });
2618
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
2619
+ }
2620
+ );
2621
+ server.registerTool(
2622
+ "browser_tabs_back",
2623
+ { description: "\u5728\u6307\u5B9A\u6807\u7B7E\u9875\uFF08\u6216\u5F53\u524D\u6D3B\u8DC3\u6807\u7B7E\u9875\uFF09\u4E2D\u6267\u884C\u6D4F\u89C8\u5668\u540E\u9000\u64CD\u4F5C\u3002", inputSchema: BrowserTabsNavInput.shape },
2624
+ async (args) => {
2625
+ const result = await adapter.tabs("back", { tabId: args.tabId });
2626
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
2627
+ }
2628
+ );
2629
+ server.registerTool(
2630
+ "browser_tabs_forward",
2631
+ { description: "\u5728\u6307\u5B9A\u6807\u7B7E\u9875\uFF08\u6216\u5F53\u524D\u6D3B\u8DC3\u6807\u7B7E\u9875\uFF09\u4E2D\u6267\u884C\u6D4F\u89C8\u5668\u524D\u8FDB\u64CD\u4F5C\u3002", inputSchema: BrowserTabsNavInput.shape },
2632
+ async (args) => {
2633
+ const result = await adapter.tabs("forward", { tabId: args.tabId });
2634
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
2635
+ }
2636
+ );
2637
+ }
2638
+ }
2639
+ function registerWxtTools(server, adapter, isAgentMode, mcpServer) {
2640
+ server.registerTool(
2641
+ "browser_sub_agent_run",
2642
+ {
2643
+ description: isAgentMode ? "\u300ATiny Robot \u7AEF\u4FA7\u81EA\u4E3B\u5B50\u4EE3\u7406\u300B\u5C06\u590D\u6742\u6216\u957F\u6D41\u7A0B\u7684\u6D4F\u89C8\u5668\u64CD\u4F5C\u4EFB\u52A1\u59D4\u6258\u7ED9\u6269\u5C55\u7AEF\u4FA7\u7684 Tiny Robot \u5B50\u4EE3\u7406\u95ED\u73AF\u6267\u884C\u3002\u5B50\u4EE3\u7406\u5C06\u5728\u7AEF\u4FA7\u81EA\u4E3B\u89C2\u5BDF\u9875\u9762\u3001\u89C4\u5212\u6B65\u9AA4\u5E76\u6267\u884C\u539F\u5B50\u64CD\u4F5C\uFF0C\u6267\u884C\u5B8C\u6BD5\u540E\u8FD4\u56DE\u6700\u7EC8\u7ED3\u679C\uFF0C\u6781\u5927\u5730\u8282\u7701\u4E3B Agent \u4E0A\u4E0B\u6587 Token\u3002" : "\u300A\u9AD8\u5C42\u4EFB\u52A1\u59D4\u6258\u300B\u5C06\u590D\u6742\u3001\u957F\u6D41\u7A0B\u6216\u9700\u53CD\u590D\u8BD5\u9519\u7684\u6D4F\u89C8\u5668\u64CD\u4F5C\u4EFB\u52A1\u59D4\u6258\u7ED9 Chrome \u6269\u5C55\u5185\u90E8\u7684 Tiny Robot \u5B50\u4EE3\u7406\uFF08Sub-Agent\uFF09\u81EA\u4E3B\u95ED\u73AF\u6267\u884C\u3002\u5B50\u4EE3\u7406\u5C06\u5728\u7AEF\u4FA7\u81EA\u4E3B\u8FDB\u884C\u9875\u9762\u63A2\u7D22\u3001\u89C4\u5212\u548C\u539F\u5B50\u64CD\u4F5C\uFF0C\u6267\u884C\u5B8C\u6BD5\u540E\u8FD4\u56DE\u6700\u7EC8\u7ED3\u679C\uFF0C\u6781\u5927\u5730\u8282\u7701\u5916\u90E8\u4E3B Agent \u7684\u4E0A\u4E0B\u6587 Token\u3002",
2644
+ inputSchema: BrowserSubAgentRunInput.shape
2645
+ },
2646
+ async (args, extra) => {
2647
+ const progressToken = extra?._meta?.progressToken;
2648
+ const onProgress = progressToken != null ? (params) => {
2649
+ if (params?.progressToken && params.progressToken !== progressToken) return;
2650
+ try {
2651
+ mcpServer.server.notification({
2652
+ method: "notifications/progress",
2653
+ params: { progressToken, progress: params?.step ?? 0, total: params?.total ?? args.maxSteps ?? 8, message: params?.message ?? "" }
2654
+ });
2655
+ } catch {
2656
+ }
2657
+ } : void 0;
2658
+ if (onProgress) adapter.bridgeClient.on("progress", onProgress);
2659
+ try {
2660
+ const result = await adapter.runSubAgent(args.instruction, {
2661
+ tabId: args.tabId,
2662
+ maxSteps: args.maxSteps,
2663
+ progressToken
2664
+ });
2665
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
2666
+ } finally {
2667
+ if (onProgress) adapter.bridgeClient.off("progress", onProgress);
2668
+ }
2669
+ }
2670
+ );
2671
+ if (!isAgentMode) {
2672
+ server.registerTool(
2673
+ "browser_skills_list",
2674
+ {
2675
+ description: "\u3010\u6280\u80FD\u6E10\u8FDB\u5F0F\u62AB\u9732 - L1 \u7D22\u5F15\u5C42\u3011\u83B7\u53D6\u5F53\u524D\u6D4F\u89C8\u5668\u6269\u5C55\u4E2D\u5DF2\u7EF4\u62A4\u7684\u6240\u6709 Skills \u6280\u80FD\u7B80\u77ED\u6E05\u5355\uFF08\u4EC5\u8FD4\u56DE\u540D\u79F0\u3001\u7B80\u4ECB\uFF0C\u6D88\u8017\u6781\u5C11 Token\uFF09\u3002\u5728\u81EA\u4E3B\u6267\u884C\u590D\u6742\u6216\u5782\u76F4\u9886\u57DF\u4EFB\u52A1\u524D\uFF0C\u53EF\u5148\u8C03\u7528\u6B64\u5DE5\u5177\u5339\u914D\u6700\u9002\u7528\u7684\u6280\u80FD\u3002",
2676
+ inputSchema: BrowserSkillsListInput.shape
2677
+ },
2678
+ async () => {
2679
+ const result = await adapter.listSkills();
2680
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
2681
+ }
2682
+ );
2683
+ server.registerTool(
2684
+ "browser_skills_read",
2685
+ {
2686
+ description: "\u3010\u6280\u80FD\u6E10\u8FDB\u5F0F\u62AB\u9732 - L2 \u5951\u7EA6\u5C42\u3011\u6839\u636E\u6280\u80FD\u540D\u79F0\u6309\u9700\u8BFB\u53D6\u8BE5\u6280\u80FD\u7684\u5B8C\u6574\u8BE6\u7EC6\u6267\u884C\u6307\u4EE4 (instructions)\u3001\u5DE5\u4F5C\u6D41\u89C4\u8303\u4E0E\u8F93\u5165\u8F93\u51FA\u5951\u7EA6\u3002",
2687
+ inputSchema: BrowserSkillsReadInput.shape
2688
+ },
2689
+ async (args) => {
2690
+ const result = await adapter.getSkill(args.name);
2691
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
2692
+ }
2693
+ );
2694
+ }
2695
+ }
2696
+ function registerSkillsResources(server, adapter) {
2697
+ server.registerResource(
2698
+ "skills_index",
2699
+ "skills://index",
2700
+ { description: "Skills L1\uFF1A\u6269\u5C55\u5DF2\u6CE8\u518C\u7684\u6240\u6709\u6280\u80FD\u5217\u8868\uFF08\u4EC5\u5143\u6570\u636E\uFF0C\u6D88\u8017\u6781\u5C11 Token\uFF09", mimeType: "application/json" },
2701
+ async () => {
2702
+ try {
2703
+ const skills = await adapter.listSkills();
2704
+ return { contents: [{ uri: "skills://index", text: JSON.stringify(skills, null, 2), mimeType: "application/json" }] };
2705
+ } catch (err) {
2706
+ return { contents: [{ uri: "skills://index", text: JSON.stringify({ error: err instanceof Error ? err.message : String(err) }), mimeType: "application/json" }] };
2707
+ }
2708
+ }
2709
+ );
2710
+ const skillDetailTemplate = new import_mcp.ResourceTemplate("skills://{skillName}/detail", { list: void 0 });
2711
+ server.registerResource(
2712
+ "skill_detail",
2713
+ skillDetailTemplate,
2714
+ { description: "Skills L2\uFF1A\u6309\u6280\u80FD\u540D\u5B9E\u65F6\u62C9\u53D6\u5B8C\u6574 SOP \u6267\u884C\u6307\u4EE4\u4E0E\u8F93\u5165\u8F93\u51FA\u5951\u7EA6", mimeType: "application/json" },
2715
+ async (uri, params) => {
2716
+ const { skillName } = params;
2717
+ try {
2718
+ const detail = await adapter.getSkill(skillName);
2719
+ return { contents: [{ uri: uri.href, text: JSON.stringify(detail, null, 2), mimeType: "application/json" }] };
2720
+ } catch (err) {
2721
+ return { contents: [{ uri: uri.href, text: JSON.stringify({ error: err instanceof Error ? err.message : String(err) }), mimeType: "application/json" }] };
2722
+ }
2723
+ }
2724
+ );
2725
+ const skillResourceTemplate = new import_mcp.ResourceTemplate("skills://{skillName}/{resourcePath}", { list: void 0 });
2726
+ server.registerResource(
2727
+ "skill_resource",
2728
+ skillResourceTemplate,
2729
+ { description: "Skills L3\uFF1A\u8BFB\u53D6\u6280\u80FD\u5173\u8054\u7684\u6DF1\u5165\u53C2\u8003\u8D44\u6599\u6216\u914D\u7F6E\u6587\u4EF6\uFF08\u6309\u9700\u52A0\u8F7D\uFF09", mimeType: "text/plain" },
2730
+ async (uri, params) => {
2731
+ const { skillName, resourcePath } = params;
2732
+ try {
2733
+ const text = await adapter.readSkillResource(skillName, resourcePath);
2734
+ return { contents: [{ uri: uri.href, text: String(text), mimeType: "text/plain" }] };
2735
+ } catch (err) {
2736
+ return { contents: [{ uri: uri.href, text: `\u8BFB\u53D6\u8D44\u6E90\u5931\u8D25: ${err instanceof Error ? err.message : String(err)}`, mimeType: "text/plain" }] };
2737
+ }
2738
+ }
2739
+ );
2740
+ }
2741
+ var import_mcp, import_stdio, SERVER_NAME, SERVER_VERSION;
2742
+ var init_server = __esm({
2743
+ "src/mcp/server.ts"() {
2744
+ "use strict";
2745
+ import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
2746
+ import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
2747
+ init_package();
2748
+ init_tools();
2749
+ SERVER_NAME = "webmcp-cli";
2750
+ SERVER_VERSION = package_default.version || "0.0.9";
2751
+ }
2752
+ });
2753
+
2754
+ // src/commands/agent.ts
2755
+ var agent_exports = {};
2756
+ __export(agent_exports, {
2757
+ handleAgentCommand: () => handleAgentCommand
2758
+ });
2759
+ async function handleAgentCommand(adapter, args) {
2760
+ const subCommand = args[0];
2761
+ const restArgs = args.slice(1);
2762
+ if (!subCommand || subCommand === "--help" || subCommand === "-h") {
2763
+ printAgentHelp();
2764
+ return;
2765
+ }
2766
+ if (subCommand === "run") {
2767
+ await handleAgentRun(adapter, restArgs);
2768
+ return;
2769
+ }
2770
+ console.error(`[\u9519\u8BEF] \u672A\u77E5\u5B50\u547D\u4EE4: agent ${subCommand}`);
2771
+ console.error("\u8FD0\u884C webmcp-cli --mode wxt agent --help \u67E5\u770B\u652F\u6301\u7684\u547D\u4EE4");
2772
+ process.exit(1);
2773
+ }
2774
+ async function handleAgentRun(adapter, args) {
2775
+ let instruction = "";
2776
+ let maxSteps;
2777
+ let tabId;
2778
+ const isJson = args.includes("--json");
2779
+ for (let i = 0; i < args.length; i++) {
2780
+ const arg = args[i];
2781
+ if (arg === "--max-steps" && args[i + 1]) {
2782
+ maxSteps = parseInt(args[++i], 10);
2783
+ } else if (arg === "--tab" && args[i + 1]) {
2784
+ tabId = parseInt(args[++i], 10);
2785
+ } else if (!arg.startsWith("-")) {
2786
+ instruction = arg;
2787
+ }
2788
+ }
2789
+ if (!instruction) {
2790
+ console.error('[\u9519\u8BEF] \u8BF7\u63D0\u4F9B\u4EFB\u52A1\u6307\u4EE4\u3002\u793A\u4F8B\uFF1Awebmcp-cli --mode wxt agent run "\u5E2E\u6211\u641C\u7D22\u6700\u65B0\u65B0\u95FB"');
2791
+ process.exit(1);
2792
+ }
2793
+ if (!isJson) {
2794
+ console.log(`\u{1F916} \u6B63\u5728\u59D4\u6258 Tiny Robot \u5B50\u4EE3\u7406\u6267\u884C\u4EFB\u52A1\uFF1A\u300C${instruction}\u300D`);
2795
+ if (maxSteps) console.log(` \u6700\u5927\u6B65\u6570\uFF1A${maxSteps}`);
2796
+ }
2797
+ try {
2798
+ const result = await adapter.runSubAgent(instruction, { tabId, maxSteps });
2799
+ if (isJson) {
2800
+ console.log(JSON.stringify(result, null, 2));
2801
+ } else {
2802
+ console.log("\n\u2705 \u5B50\u4EE3\u7406\u6267\u884C\u5B8C\u6210\uFF1A");
2803
+ console.log(JSON.stringify(result, null, 2));
2804
+ }
2805
+ } catch (err) {
2806
+ const msg = err instanceof Error ? err.message : String(err);
2807
+ if (isJson) {
2808
+ console.log(JSON.stringify({ success: false, error: msg }));
2809
+ } else {
2810
+ console.error(`\u274C \u6267\u884C\u5931\u8D25\uFF1A${msg}`);
2811
+ }
2812
+ process.exit(1);
2813
+ }
2814
+ }
2815
+ function printAgentHelp() {
2816
+ console.log(`
2817
+ webmcp-cli --mode wxt agent - \u59D4\u6258 Chrome \u6269\u5C55\u5185 Tiny Robot \u5B50\u4EE3\u7406\u6267\u884C\u9AD8\u5C42\u4EFB\u52A1
2818
+
2819
+ \u7528\u6CD5\uFF1A
2820
+ webmcp-cli --mode wxt agent run "<\u6307\u4EE4>" \u59D4\u6258\u5B50\u4EE3\u7406\u81EA\u4E3B\u6267\u884C\u81EA\u7136\u8BED\u8A00\u4EFB\u52A1
2821
+
2822
+ \u9009\u9879\uFF1A
2823
+ --max-steps <n> \u6700\u5927\u6267\u884C\u6B65\u6570\uFF08\u9ED8\u8BA4 8\uFF0C\u6700\u5927 20\uFF09
2824
+ --tab <tabId> \u6307\u5B9A\u76EE\u6807\u6807\u7B7E\u9875 ID
2825
+ --json \u8F93\u51FA JSON \u683C\u5F0F\u7ED3\u679C
2826
+
2827
+ \u793A\u4F8B\uFF1A
2828
+ webmcp-cli --mode wxt agent run "\u5E2E\u6211\u628A\u5F53\u524D\u5546\u54C1\u52A0\u5165\u8D2D\u7269\u8F66"
2829
+ webmcp-cli --mode wxt agent run "\u641C\u7D22\u5E76\u6536\u85CF\u524D3\u7BC7\u6587\u7AE0" --max-steps 10
2830
+ `.trim());
2831
+ }
2832
+ var init_agent = __esm({
2833
+ "src/commands/agent.ts"() {
2834
+ "use strict";
2835
+ }
2836
+ });
2837
+
2838
+ // src/commands/skills.ts
2839
+ var skills_exports = {};
2840
+ __export(skills_exports, {
2841
+ handleSkillsCommand: () => handleSkillsCommand
2842
+ });
2843
+ async function handleSkillsCommand(adapter, args) {
2844
+ const subCommand = args[0];
2845
+ const restArgs = args.slice(1);
2846
+ const isJson = args.includes("--json");
2847
+ if (!subCommand || subCommand === "--help" || subCommand === "-h") {
2848
+ printSkillsHelp();
2849
+ return;
2850
+ }
2851
+ if (subCommand === "list") {
2852
+ await handleSkillsList(adapter, isJson);
2853
+ return;
2854
+ }
2855
+ if (subCommand === "get") {
2856
+ const skillName = restArgs.find((a) => !a.startsWith("-"));
2857
+ if (!skillName) {
2858
+ console.error("[\u9519\u8BEF] \u8BF7\u63D0\u4F9B\u6280\u80FD\u540D\u79F0\u3002\u793A\u4F8B\uFF1Awebmcp-cli --mode wxt skills get <skillName>");
2859
+ process.exit(1);
2860
+ }
2861
+ await handleSkillsGet(adapter, skillName, isJson);
2862
+ return;
2863
+ }
2864
+ console.error(`[\u9519\u8BEF] \u672A\u77E5\u5B50\u547D\u4EE4: skills ${subCommand}`);
2865
+ printSkillsHelp();
2866
+ process.exit(1);
2867
+ }
2868
+ async function handleSkillsList(adapter, isJson) {
2869
+ try {
2870
+ const result = await adapter.listSkills();
2871
+ if (isJson) {
2872
+ console.log(JSON.stringify(result, null, 2));
2873
+ } else {
2874
+ const skills = result;
2875
+ if (!skills || skills.length === 0) {
2876
+ console.log("\uFF08\u5F53\u524D\u6269\u5C55\u672A\u6CE8\u518C\u4EFB\u4F55\u6280\u80FD\uFF09");
2877
+ return;
2878
+ }
2879
+ console.log(`
2880
+ \u{1F4DA} \u5DF2\u6CE8\u518C Skills\uFF08\u5171 ${skills.length} \u4E2A\uFF09\uFF1A
2881
+ `);
2882
+ for (const skill of skills) {
2883
+ console.log(` \u2022 ${skill.name}`);
2884
+ if (skill.description) {
2885
+ console.log(` ${skill.description.slice(0, 100)}${skill.description.length > 100 ? "..." : ""}`);
2886
+ }
2887
+ }
2888
+ console.log(`
2889
+ \u63D0\u793A\uFF1A\u4F7F\u7528 "webmcp-cli --mode wxt skills get <name>" \u67E5\u770B\u6280\u80FD\u8BE6\u60C5`);
2890
+ }
2891
+ } catch (err) {
2892
+ const msg = err instanceof Error ? err.message : String(err);
2893
+ if (isJson) {
2894
+ console.log(JSON.stringify({ error: msg }));
2895
+ } else {
2896
+ console.error(`\u274C \u83B7\u53D6\u6280\u80FD\u5217\u8868\u5931\u8D25\uFF1A${msg}`);
2897
+ }
2898
+ process.exit(1);
2899
+ }
2900
+ }
2901
+ async function handleSkillsGet(adapter, name, isJson) {
2902
+ try {
2903
+ const result = await adapter.getSkill(name);
2904
+ if (isJson) {
2905
+ console.log(JSON.stringify(result, null, 2));
2906
+ } else {
2907
+ const skill = result;
2908
+ console.log(`
2909
+ \u{1F4D6} \u6280\u80FD\uFF1A${skill.name}`);
2910
+ if (skill.description) console.log(`\u63CF\u8FF0\uFF1A${skill.description}`);
2911
+ if (skill.instructions) {
2912
+ console.log("\n--- \u6307\u4EE4 ---");
2913
+ console.log(skill.instructions);
2914
+ }
2915
+ }
2916
+ } catch (err) {
2917
+ const msg = err instanceof Error ? err.message : String(err);
2918
+ if (isJson) {
2919
+ console.log(JSON.stringify({ error: msg }));
2920
+ } else {
2921
+ console.error(`\u274C \u83B7\u53D6\u6280\u80FD\u8BE6\u60C5\u5931\u8D25\uFF1A${msg}`);
2922
+ }
2923
+ process.exit(1);
2924
+ }
2925
+ }
2926
+ function printSkillsHelp() {
2927
+ console.log(`
2928
+ webmcp-cli --mode wxt skills - \u67E5\u8BE2\u4E0E\u8BFB\u53D6\u6D4F\u89C8\u5668\u6269\u5C55\u4E2D\u6CE8\u518C\u7684 Skills \u6280\u80FD
2929
+
2930
+ \u7528\u6CD5\uFF1A
2931
+ webmcp-cli --mode wxt skills list \u5217\u51FA\u6240\u6709\u5DF2\u6CE8\u518C\u7684\u6280\u80FD
2932
+ webmcp-cli --mode wxt skills get <name> \u8BFB\u53D6\u6307\u5B9A\u6280\u80FD\u7684\u8BE6\u7EC6\u6267\u884C\u6307\u4EE4
2933
+
2934
+ \u9009\u9879\uFF1A
2935
+ --json \u8F93\u51FA JSON \u683C\u5F0F\u7ED3\u679C
2936
+
2937
+ \u793A\u4F8B\uFF1A
2938
+ webmcp-cli --mode wxt skills list
2939
+ webmcp-cli --mode wxt skills get order-management
2940
+ `.trim());
2941
+ }
2942
+ var init_skills = __esm({
2943
+ "src/commands/skills.ts"() {
2944
+ "use strict";
2945
+ }
2946
+ });
2947
+
2948
+ // src/bin.ts
2949
+ var import_fs3 = __toESM(require("fs"), 1);
2950
+ var import_path3 = __toESM(require("path"), 1);
2951
+ var import_os2 = __toESM(require("os"), 1);
2952
+ var import_commander = require("commander");
2953
+ var import_picocolors2 = __toESM(require("picocolors"), 1);
2954
+ var import_fs4 = require("fs");
2955
+ var import_path4 = require("path");
2956
+
2957
+ // src/expand-file-refs.ts
2958
+ var import_fs = require("fs");
2959
+ var import_path = require("path");
2960
+ var import_url = require("url");
2961
+ var JSON_STRING_LITERAL = /"(?:[^"\\]|\\.)*"/g;
2962
+ var UNQUOTED_FILE_REF = /(?<![\\"])@(base64)?file:([^\s"',}\]]+)/g;
2963
+ var FILE_REF_PREFIX = /^@(base64)?file:(.+)$/s;
2964
+ function resolveFilePath(filePath, baseDir = process.cwd()) {
2965
+ let normalizedPath = filePath.trim();
2966
+ if (normalizedPath.startsWith('"') && normalizedPath.endsWith('"') || normalizedPath.startsWith("'") && normalizedPath.endsWith("'")) {
2967
+ normalizedPath = normalizedPath.slice(1, -1).trim();
2968
+ }
2969
+ if (normalizedPath.startsWith("file://")) {
2970
+ normalizedPath = (0, import_url.fileURLToPath)(normalizedPath);
2971
+ }
2972
+ if ((0, import_path.isAbsolute)(normalizedPath)) {
2973
+ return (0, import_path.normalize)(normalizedPath);
2974
+ }
2975
+ return (0, import_path.resolve)(baseDir, normalizedPath);
2976
+ }
2977
+ function decodeFilePath(rawPath) {
2978
+ return rawPath.replace(/\\\\/g, "\\");
2979
+ }
2980
+ function readFileRefContent(filePath, baseDir, base64) {
2981
+ const absPath = resolveFilePath(filePath, baseDir);
2982
+ let content;
2983
+ try {
2984
+ content = (0, import_fs.readFileSync)(absPath, "utf-8");
2985
+ } catch (e) {
2986
+ throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6\u5F15\u7528 "${filePath}" (${absPath}): ${e.message}`);
2987
+ }
2988
+ return base64 ? Buffer.from(content, "utf-8").toString("base64") : content;
2989
+ }
2990
+ function expandFileRefValue(rawInner, baseDir) {
2991
+ const match = rawInner.match(FILE_REF_PREFIX);
2992
+ if (!match) {
2993
+ return null;
2994
+ }
2995
+ const [, base64Flag, rawPath] = match;
2996
+ const filePath = decodeFilePath(rawPath);
2997
+ const value = readFileRefContent(filePath, baseDir, Boolean(base64Flag));
2998
+ return JSON.stringify(value);
2999
+ }
3000
+ function expandQuotedFileRefs(argsJson, baseDir) {
3001
+ return argsJson.replace(JSON_STRING_LITERAL, (jsonStringLiteral) => {
3002
+ const rawInner = jsonStringLiteral.slice(1, -1);
3003
+ const replacement = expandFileRefValue(rawInner, baseDir);
3004
+ return replacement ?? jsonStringLiteral;
3005
+ });
3006
+ }
3007
+ function expandUnquotedFileRefs(argsJson, baseDir) {
3008
+ return argsJson.replace(UNQUOTED_FILE_REF, (match, base64Flag, filePath) => {
3009
+ const value = readFileRefContent(filePath, baseDir, Boolean(base64Flag));
3010
+ return JSON.stringify(value);
3011
+ });
3012
+ }
3013
+ function expandFileRefs(argsJson, baseDir = process.cwd()) {
3014
+ const withQuotedExpanded = expandQuotedFileRefs(argsJson, baseDir);
3015
+ return expandUnquotedFileRefs(withQuotedExpanded, baseDir);
3016
+ }
3017
+ function getFileBaseDir(fileOption) {
3018
+ if (!fileOption) {
3019
+ return process.cwd();
3020
+ }
3021
+ return (0, import_path.dirname)((0, import_path.resolve)(process.cwd(), fileOption));
3022
+ }
3023
+
3024
+ // src/parse-run-args.ts
3025
+ var import_json5 = __toESM(require("json5"), 1);
3026
+ function cleanJsonString(str) {
3027
+ let cleaned = str.trim();
3028
+ if (cleaned.startsWith("'") && cleaned.endsWith("'")) {
3029
+ cleaned = cleaned.slice(1, -1).trim();
3030
+ }
3031
+ return cleaned;
3032
+ }
3033
+ function looksLikeObjectBody(raw) {
3034
+ return /^("?[\w-]+"?\s*:)/.test(raw);
3035
+ }
3036
+ function joinShellArgs(args) {
3037
+ const cleaned = args.map(cleanJsonString);
3038
+ const first = cleaned[0] ?? "";
3039
+ if (first.startsWith("{")) {
3040
+ return cleaned.join(" ");
3041
+ }
3042
+ if (looksLikeObjectBody(first)) {
3043
+ let joined = cleaned.join(" ");
3044
+ if (!joined.startsWith("{")) {
3045
+ joined = `{${joined}}`;
3046
+ }
3047
+ if (!joined.endsWith("}")) {
3048
+ joined = `${joined}}`;
550
3049
  }
3050
+ return joined;
551
3051
  }
552
- if (!targetPage) {
553
- throw new Error("\u65E0\u6CD5\u83B7\u53D6\u76EE\u6807\u9875\u9762");
554
- }
555
- await injectWebMCPPolyfillAndTools(targetPage);
556
- return targetPage;
3052
+ return cleaned.join(" ");
557
3053
  }
558
- async function injectIntoPage(page) {
559
- await injectWebMCPPolyfillAndTools(page, true);
3054
+ function insertMissingCommas(raw) {
3055
+ return raw.replace(/"(\s+)("?[\w-]+"?\s*:)/g, '",$2');
560
3056
  }
561
- async function injectWebMCPPolyfillAndTools(page, force = false) {
562
- const polyfillReady = !force && await page.evaluate(() => {
563
- return !!window.__webmcpcli_init;
564
- }).catch(() => false);
565
- if (!polyfillReady) {
566
- console.log(import_picocolors.default.cyan("\u5F53\u524D\u9875\u9762\u5C1A\u672A\u6CE8\u5165 WebMCP \u73AF\u5883\uFF0C\u6B63\u5728\u6267\u884C\u81EA\u52A8\u6CE8\u5165..."));
567
- const injectScriptPath = import_path2.default.resolve(__dirname, "inject-bundle.js");
568
- if (!import_fs2.default.existsSync(injectScriptPath)) {
569
- throw new Error(`Cannot find inject-bundle.js at ${injectScriptPath}. Please ensure you run 'pnpm build:inject' first.`);
3057
+ function quoteUnquotedStringValues(raw) {
3058
+ return raw.replace(
3059
+ /([{,]\s*(?:"([^"]+)"|([\w-]+))\s*:\s*)(?!"@(?:base64)?file:|"|true|false|null|-?\d|\{|\[)([^",}\]]+?)(?=\s*[,}])/g,
3060
+ (_match, prefix, _quotedKey, _unquotedKey, value) => {
3061
+ const trimmed = value.trim();
3062
+ if (/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(trimmed)) {
3063
+ return prefix + trimmed;
3064
+ }
3065
+ return prefix + JSON.stringify(trimmed);
570
3066
  }
571
- const scriptContent = import_fs2.default.readFileSync(injectScriptPath, "utf-8");
3067
+ );
3068
+ }
3069
+ function normalizeShellDamagedJson(raw) {
3070
+ let normalized = raw.trim();
3071
+ normalized = insertMissingCommas(normalized);
3072
+ normalized = quoteUnquotedStringValues(normalized);
3073
+ return normalized;
3074
+ }
3075
+ function buildArgsFromKeyValuePairs(args) {
3076
+ const obj = {};
3077
+ for (const pair of args) {
3078
+ const index = pair.indexOf("=");
3079
+ if (index === -1) {
3080
+ throw new Error(`\u65E0\u6548\u7684\u53C2\u6570\u683C\u5F0F "${pair}"\u3002\u8BF7\u4F7F\u7528 key=value\uFF0C\u6216 JSON / -f \u6587\u4EF6\u3002`);
3081
+ }
3082
+ const key = pair.substring(0, index).trim();
3083
+ let val = cleanJsonString(pair.substring(index + 1).trim());
572
3084
  try {
573
- await page.evaluate(scriptContent);
574
- } catch (err) {
575
- const msg = err instanceof Error ? err.message : String(err);
576
- throw new Error("\u81EA\u52A8\u6CE8\u5165\u811A\u672C\u6267\u884C\u5931\u8D25: " + msg);
3085
+ obj[key] = JSON.parse(val);
3086
+ } catch {
3087
+ obj[key] = val;
577
3088
  }
578
- await page.waitForFunction(() => {
579
- const mcp = navigator.modelContext;
580
- return mcp && typeof mcp.registerTool === "function";
581
- }, { timeout: 1e4 }).catch(() => {
582
- console.warn("\u7B49\u5F85 WebMCP registerTool \u63A5\u53E3\u5C31\u7EEA\u8D85\u65F6\uFF0C\u6B63\u5728\u7EE7\u7EED\u6CE8\u5165...");
583
- });
584
3089
  }
585
- await injectDomainTools(page);
3090
+ return JSON.stringify(obj);
586
3091
  }
587
- function getToolsBundleName(hostname) {
588
- const normalized = hostname.split(":")[0].toLowerCase();
589
- const toolsDir = import_path2.default.resolve(__dirname, "webmcp-tools");
590
- if (!import_fs2.default.existsSync(toolsDir)) {
591
- return null;
592
- }
593
- let files = [];
3092
+ function parseArgsJson(raw) {
3093
+ const trimmed = cleanJsonString(raw);
594
3094
  try {
595
- files = import_fs2.default.readdirSync(toolsDir);
596
- } catch {
597
- return null;
598
- }
599
- const supportedDomains = files.filter((f) => f.endsWith(".js")).map((f) => f.slice(0, -3));
600
- if (supportedDomains.includes(normalized)) {
601
- return `webmcp-tools/${normalized}.js`;
602
- }
603
- for (const domain of supportedDomains) {
604
- if (normalized.endsWith("." + domain)) {
605
- return `webmcp-tools/${domain}.js`;
3095
+ return JSON.stringify(import_json5.default.parse(trimmed));
3096
+ } catch (firstError) {
3097
+ const repaired = normalizeShellDamagedJson(trimmed);
3098
+ try {
3099
+ return JSON.stringify(import_json5.default.parse(repaired));
3100
+ } catch {
3101
+ const hint = `\u63D0\u793A\uFF1Abash \u4E2D JSON \u5FC5\u987B\u7528\u5355\u5F15\u53F7\u5305\u88F9\uFF0C\u4F8B\u5982 '{"title":"\u6807\u9898","content":"@base64file:./article.md"}'\uFF1B\u6216\u4F7F\u7528 key=value\uFF1Atitle=\u6807\u9898 content=@base64file:./article.md\uFF1B\u6216\u4F7F\u7528 -f args.json\u3002`;
3102
+ const message = firstError instanceof Error ? firstError.message : String(firstError);
3103
+ throw new Error(`\u53C2\u6570\u4E0D\u662F\u6709\u6548\u7684 JSON \u6216 JS \u5BF9\u8C61: ${message}
3104
+ ${hint}`);
606
3105
  }
607
3106
  }
608
- return null;
609
3107
  }
610
- async function injectDomainTools(page) {
611
- let hostname;
612
- try {
613
- const url = new URL(page.url());
614
- hostname = url.hostname;
615
- } catch {
616
- return;
617
- }
618
- const bundleName = getToolsBundleName(hostname);
619
- if (!bundleName) {
620
- return;
3108
+ function prepareRunArgsJson(args, fileContent, baseDir) {
3109
+ if (fileContent !== void 0) {
3110
+ const trimmed = fileContent.trim();
3111
+ if (!trimmed) {
3112
+ throw new Error("\u901A\u8FC7 -f/--file \u6307\u5B9A\u7684\u53C2\u6570\u6587\u4EF6\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A");
3113
+ }
3114
+ const expanded2 = expandFileRefs(trimmed, baseDir);
3115
+ return parseArgsJson(expanded2);
621
3116
  }
622
- const toolBundlePath = import_path2.default.resolve(__dirname, bundleName);
623
- if (!import_fs2.default.existsSync(toolBundlePath)) {
624
- return;
3117
+ if (args.length === 0) {
3118
+ return "{}";
625
3119
  }
626
- const bundleKey = bundleName.replace(/^webmcp-tools\//, "").replace(/\.js$/, "");
627
- const flagKey = `__webmcptools_${bundleKey.replace(/[^a-zA-Z0-9]/g, "")}`;
628
- const alreadyInjected = await page.evaluate((key) => !!window[key], flagKey).catch(() => false);
629
- if (alreadyInjected) {
630
- return;
3120
+ const joined = joinShellArgs(args);
3121
+ let raw = "";
3122
+ if (joined.startsWith("{") || looksLikeObjectBody(joined)) {
3123
+ raw = joined;
3124
+ } else if (args.every((arg) => arg.includes("="))) {
3125
+ raw = buildArgsFromKeyValuePairs(args);
3126
+ } else {
3127
+ raw = joined;
631
3128
  }
632
- console.log(import_picocolors.default.cyan(`\u68C0\u6D4B\u5230\u57DF\u540D ${hostname} \u6709\u9884\u7F6E\u5DE5\u5177\uFF0C\u6B63\u5728\u6CE8\u5165...`));
633
- const toolScript = import_fs2.default.readFileSync(toolBundlePath, "utf-8");
634
- try {
635
- await page.evaluate(toolScript);
636
- console.log(import_picocolors.default.green(`\u5DF2\u4E3A ${hostname} \u6CE8\u5165\u9884\u7F6E\u5DE5\u5177`));
637
- } catch (err) {
638
- const msg = err instanceof Error ? err.message : String(err);
639
- console.warn(import_picocolors.default.yellow(`\u57DF\u540D\u5DE5\u5177\u6CE8\u5165\u5931\u8D25 (${hostname}): ${msg}`));
3129
+ if (!raw.trim()) {
3130
+ throw new Error("\u672A\u63D0\u4F9B\u6709\u6548\u53C2\u6570");
640
3131
  }
3132
+ const expanded = expandFileRefs(raw, baseDir);
3133
+ return parseArgsJson(expanded);
641
3134
  }
642
3135
 
643
3136
  // src/commands/state.ts
3137
+ init_browser();
644
3138
  async function stateCommand({ tabid }) {
645
3139
  const browser = await connectBrowser();
646
3140
  try {
@@ -649,11 +3143,19 @@ async function stateCommand({ tabid }) {
649
3143
  const state = await page.evaluate(async () => {
650
3144
  const url = document.URL;
651
3145
  const title = document.title;
652
- const mcp = document.modelContext;
3146
+ const mcp = document.modelContext || navigator.modelContext;
653
3147
  let webmcpTools = [];
654
- if (mcp && typeof mcp.listTools === "function") {
655
- const toolsResult = await mcp.getTools();
656
- webmcpTools = toolsResult?.tools || toolsResult || [];
3148
+ if (mcp && typeof mcp.getTools === "function") {
3149
+ try {
3150
+ const toolsResult = await mcp.getTools();
3151
+ const list = toolsResult?.tools || toolsResult || [];
3152
+ webmcpTools = list.filter((t) => t && typeof t.name === "string").map((t) => ({
3153
+ name: t.name,
3154
+ description: typeof t.description === "string" ? t.description.slice(0, 200) : void 0
3155
+ }));
3156
+ } catch {
3157
+ webmcpTools = [];
3158
+ }
657
3159
  }
658
3160
  return { url, title, webmcpTools };
659
3161
  });
@@ -685,156 +3187,8 @@ async function stateCommand({ tabid }) {
685
3187
  }
686
3188
  }
687
3189
 
688
- // src/zhihu/create-article.ts
689
- var import_os2 = __toESM(require("os"), 1);
690
-
691
- // src/zhihu/markdown.ts
692
- var import_marked = require("marked");
693
- function stripLeadingH1(markdown) {
694
- return markdown.replace(/^#\s+[^\n]*\n+/, "");
695
- }
696
- function markdownToHtml(markdown) {
697
- const marked = new import_marked.Marked({
698
- gfm: true,
699
- breaks: false,
700
- renderer: {
701
- code({ text, lang }) {
702
- const langClass = lang ? ` class="language-${lang}"` : "";
703
- const escaped = text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
704
- return `<pre><code${langClass}>${escaped}</code></pre>`;
705
- },
706
- codespan({ text }) {
707
- const escaped = text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
708
- return `<code>${escaped}</code>`;
709
- }
710
- }
711
- });
712
- return marked.parse(markdown);
713
- }
714
- function decodeBase64Content(content) {
715
- return Buffer.from(content, "base64").toString("utf-8");
716
- }
717
- var ZHIHU_WRITE_PAGE_RE = /^https:\/\/zhuanlan\.zhihu\.com\/(write|p\/\d+\/edit)/;
718
- function isZhihuWriteUrl(url) {
719
- return ZHIHU_WRITE_PAGE_RE.test(url);
720
- }
721
-
722
- // src/zhihu/create-article.ts
723
- function delay(ms) {
724
- return new Promise((resolve3) => setTimeout(resolve3, ms));
725
- }
726
- function getPasteModifier() {
727
- return import_os2.default.platform() === "darwin" ? "Meta" : "Control";
728
- }
729
- async function fillTitle(page, title) {
730
- await page.evaluate((titleText) => {
731
- const input = document.querySelector('textarea[placeholder*="\u6807\u9898"]') || document.querySelector(".WriteIndex-titleInput textarea") || document.querySelector(".WriteIndex-titleInput input");
732
- if (!input) throw new Error("\u672A\u627E\u5230\u6807\u9898\u8F93\u5165\u6846\uFF0C\u8BF7\u786E\u8BA4\u7F16\u8F91\u5668\u9875\u9762\u5DF2\u5B8C\u5168\u52A0\u8F7D");
733
- const setter = Object.getOwnPropertyDescriptor(
734
- input instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype,
735
- "value"
736
- )?.set;
737
- if (setter) {
738
- setter.call(input, titleText);
739
- } else {
740
- input.value = titleText;
741
- }
742
- input.dispatchEvent(new InputEvent("input", { bubbles: true, cancelable: true, data: titleText }));
743
- input.dispatchEvent(new Event("change", { bubbles: true }));
744
- if (input.value.trim() !== titleText.trim()) {
745
- throw new Error("\u6807\u9898\u586B\u5199\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u9875\u9762\u540E\u91CD\u8BD5");
746
- }
747
- }, title);
748
- }
749
- async function pasteHtmlToEditor(page, html) {
750
- const browser = page.browser();
751
- const tempPage = await browser.newPage();
752
- const modifier = getPasteModifier();
753
- try {
754
- const fullHtml = `<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>${html}</body></html>`;
755
- await tempPage.setContent(fullHtml, { waitUntil: "domcontentloaded" });
756
- await delay(300);
757
- await tempPage.click("body");
758
- await tempPage.keyboard.down(modifier);
759
- await tempPage.keyboard.press("KeyA");
760
- await tempPage.keyboard.up(modifier);
761
- await delay(100);
762
- await tempPage.keyboard.down(modifier);
763
- await tempPage.keyboard.press("KeyC");
764
- await tempPage.keyboard.up(modifier);
765
- await delay(300);
766
- } finally {
767
- await tempPage.close();
768
- }
769
- await page.bringToFront();
770
- await page.waitForSelector(".public-DraftEditor-content", { timeout: 1e4 });
771
- await page.click(".public-DraftEditor-content");
772
- await delay(200);
773
- await page.keyboard.down(modifier);
774
- await page.keyboard.press("KeyA");
775
- await page.keyboard.up(modifier);
776
- await delay(100);
777
- await page.keyboard.press("Backspace");
778
- await delay(200);
779
- await page.keyboard.down(modifier);
780
- await page.keyboard.press("KeyV");
781
- await page.keyboard.up(modifier);
782
- await delay(1500);
783
- const probe = html.replace(/<[^>]+>/g, "").trim().slice(0, 15);
784
- const verifyResult = await page.evaluate((probeText) => {
785
- const editor = document.querySelector(".public-DraftEditor-content");
786
- if (!editor) return { ok: false, reason: "no editor" };
787
- const text = (editor.innerText || "").trim();
788
- if (!text) return { ok: false, reason: "empty" };
789
- const inner = editor.innerHTML;
790
- const hasRichFormat = inner.includes("data-text") || /font-weight:\s*bold|font-style:\s*italic|code-block|blockquote/i.test(inner);
791
- const normalizedText = text.replace(/\s+/g, "");
792
- const normalizedProbe = probeText.replace(/\s+/g, "");
793
- const hasProbe = normalizedText.includes(normalizedProbe);
794
- return {
795
- ok: text.length > 20 && hasProbe && (hasRichFormat || text.length > 50),
796
- reason: !hasProbe ? "probe mismatch" : !hasRichFormat && text.length <= 50 ? "no rich format" : void 0
797
- };
798
- }, probe);
799
- if (!verifyResult.ok) {
800
- throw new Error(
801
- `\u6B63\u6587\u586B\u5199\u5931\u8D25\uFF08Markdown \u8F6C HTML \u7C98\u8D34\u672A\u751F\u6548\uFF09${verifyResult.reason ? `: ${verifyResult.reason}` : ""}`
802
- );
803
- }
804
- }
805
- async function zhihuCreateArticle(page, args) {
806
- const { title, content } = args;
807
- if (!title?.trim()) throw new Error("\u53C2\u6570 title \u4E0D\u80FD\u4E3A\u7A7A");
808
- if (!content?.trim()) throw new Error("\u53C2\u6570 content \u4E0D\u80FD\u4E3A\u7A7A");
809
- const url = page.url();
810
- if (!isZhihuWriteUrl(url)) {
811
- throw new Error("\u5F53\u524D\u9875\u9762\u4E0D\u662F\u77E5\u4E4E\u4E13\u680F\u7F16\u8F91\u5668\uFF0C\u8BF7\u5148\u6253\u5F00 https://zhuanlan.zhihu.com/write");
812
- }
813
- let markdown;
814
- try {
815
- markdown = stripLeadingH1(decodeBase64Content(content));
816
- } catch {
817
- throw new Error("content \u4E0D\u662F\u6709\u6548\u7684 Base64 \u7F16\u7801\uFF0C\u8BF7\u68C0\u67E5\u53C2\u6570\u6216\u4F7F\u7528 @base64file: \u5F15\u7528\u6587\u4EF6");
818
- }
819
- if (!markdown.trim()) {
820
- throw new Error("\u6B63\u6587\u5185\u5BB9\u4E3A\u7A7A\uFF0C\u8BF7\u68C0\u67E5 Markdown \u6587\u4EF6");
821
- }
822
- const html = markdownToHtml(markdown);
823
- await fillTitle(page, title.trim());
824
- await delay(500);
825
- await pasteHtmlToEditor(page, html);
826
- const result = {
827
- success: true,
828
- message: "\u6587\u7AE0\u6807\u9898\u548C\u6B63\u6587\u5DF2\u6210\u529F\u586B\u5199\u5230\u77E5\u4E4E\u4E13\u680F\u7F16\u8F91\u5668\uFF08Markdown \u5DF2\u8F6C\u4E3A\u5BCC\u6587\u672C\uFF09\uFF0C\u8349\u7A3F\u5C06\u81EA\u52A8\u4FDD\u5B58",
829
- title: title.trim(),
830
- contentLength: markdown.length
831
- };
832
- return {
833
- content: [{ type: "text", text: JSON.stringify(result) }]
834
- };
835
- }
836
-
837
3190
  // src/commands/run.ts
3191
+ init_browser();
838
3192
  async function runCommand({
839
3193
  toolName,
840
3194
  argsJson,
@@ -844,18 +3198,8 @@ async function runCommand({
844
3198
  try {
845
3199
  const page = await getTargetPage(browser, tabid);
846
3200
  const urlBefore = page.url();
3201
+ await injectIntoPage(page);
847
3202
  const cleanedArgs = argsJson.trim();
848
- if (toolName === "create_article") {
849
- let parsedArgs;
850
- try {
851
- parsedArgs = JSON.parse(cleanedArgs);
852
- } catch {
853
- throw new Error("\u53C2\u6570\u4E0D\u662F\u6709\u6548\u7684 JSON");
854
- }
855
- if (isZhihuWriteUrl(page.url())) {
856
- return await zhihuCreateArticle(page, parsedArgs);
857
- }
858
- }
859
3203
  let result;
860
3204
  try {
861
3205
  result = await page.evaluate(async (name, inputString) => {
@@ -919,6 +3263,7 @@ async function setClipboard(content) {
919
3263
  }
920
3264
 
921
3265
  // src/commands/tabs.ts
3266
+ init_browser();
922
3267
  function normalizeUrl(url) {
923
3268
  if (!url.startsWith("http://") && !url.startsWith("https://")) {
924
3269
  return "https://" + url;
@@ -1040,68 +3385,55 @@ async function tabsForwardCommand(tabid) {
1040
3385
  }
1041
3386
  }
1042
3387
 
1043
- // package.json
1044
- var package_default = {
1045
- name: "@opentiny/webmcp-cli",
1046
- version: "0.0.6",
1047
- type: "module",
1048
- description: "WebMCP CLI for AI Agents to interact with browser via Puppeteer",
1049
- main: "dist/index.js",
1050
- types: "dist/index.d.ts",
1051
- bin: {
1052
- "webmcp-cli": "./dist/bin.js"
1053
- },
1054
- files: [
1055
- "dist",
1056
- "README.md"
1057
- ],
1058
- scripts: {
1059
- dev: "tsup --watch",
1060
- "build:inject": "node scripts/build-inject.mjs",
1061
- build: "tsup && pnpm run build:inject",
1062
- prepublishOnly: "pnpm run build",
1063
- "link:global": "npm install -g .",
1064
- start: "node dist/bin.js"
1065
- },
1066
- keywords: [
1067
- "chrome",
1068
- "puppeteer",
1069
- "cli"
1070
- ],
1071
- license: "MIT",
1072
- author: "OpenTiny Team",
1073
- engines: {
1074
- node: ">=16"
1075
- },
1076
- publishConfig: {
1077
- access: "public"
1078
- },
1079
- dependencies: {
1080
- "@mcp-b/webmcp-polyfill": "catalog:",
1081
- "@opentiny/next-sdk": "workspace:^",
1082
- "@page-agent/page-controller": "catalog:",
1083
- clipboardy: "^5.3.1",
1084
- commander: "^11.1.0",
1085
- json5: "^2.2.3",
1086
- marked: "^15.0.7",
1087
- picocolors: "^1.0.0",
1088
- "puppeteer-core": "^22.0.0"
1089
- },
1090
- devDependencies: {
1091
- "@types/node": "^20.0.0",
1092
- esbuild: "^0.25.0",
1093
- tsup: "^8.0.2",
1094
- tsx: "^4.0.0",
1095
- typescript: "^5.3.3"
1096
- }
1097
- };
1098
-
1099
3388
  // src/bin.ts
3389
+ init_package();
3390
+ function extractMode(argv) {
3391
+ let mode = process.env.WEBMCP_MODE === "wxt" ? "wxt" : "cdp";
3392
+ const filteredArgv = [];
3393
+ for (let i = 0; i < argv.length; i++) {
3394
+ if (argv[i] === "--mode" && argv[i + 1]) {
3395
+ const val = argv[i + 1].toLowerCase();
3396
+ if (val === "wxt" || val === "cdp") mode = val;
3397
+ i++;
3398
+ } else if (argv[i].startsWith("--mode=")) {
3399
+ const val = argv[i].split("=")[1]?.toLowerCase();
3400
+ if (val === "wxt" || val === "cdp") mode = val;
3401
+ } else {
3402
+ filteredArgv.push(argv[i]);
3403
+ }
3404
+ }
3405
+ return { mode, filteredArgv };
3406
+ }
3407
+ var { mode: CLI_MODE, filteredArgv: FILTERED_ARGV } = extractMode(process.argv);
1100
3408
  var program = new import_commander.Command();
1101
3409
  function parseTabId(id) {
1102
3410
  if (!id) return void 0;
1103
3411
  return id;
1104
3412
  }
3413
+ function tryParseBrowserStateText(text) {
3414
+ const tryParse = (jsonStr) => {
3415
+ try {
3416
+ const parsed = JSON.parse(jsonStr);
3417
+ if (parsed && typeof parsed.content === "string") {
3418
+ return parsed;
3419
+ }
3420
+ } catch {
3421
+ }
3422
+ return null;
3423
+ };
3424
+ const direct = tryParse(text);
3425
+ if (direct) return direct;
3426
+ if (text.startsWith("\u6D4F\u89C8\u5668\u72B6\u6001: ")) {
3427
+ let jsonStr = text.substring("\u6D4F\u89C8\u5668\u72B6\u6001: ".length);
3428
+ const firstNewline = jsonStr.indexOf("\n");
3429
+ if (firstNewline !== -1) {
3430
+ const maybeJson = jsonStr.substring(0, firstNewline);
3431
+ if (tryParse(maybeJson)) jsonStr = maybeJson;
3432
+ }
3433
+ return tryParse(jsonStr);
3434
+ }
3435
+ return null;
3436
+ }
1105
3437
  function cleanOldLogs(baseDir, logDir) {
1106
3438
  try {
1107
3439
  const oldLogFile = import_path3.default.join(baseDir, "webmcp-cli.log");
@@ -1157,23 +3489,11 @@ function formatLogResult(result) {
1157
3489
  let searchResultStr = "";
1158
3490
  if (clone && Array.isArray(clone.content) && clone.content.length > 0 && clone.content[0] && typeof clone.content[0].text === "string") {
1159
3491
  const text = clone.content[0].text;
1160
- if (text.startsWith("\u6D4F\u89C8\u5668\u72B6\u6001: ")) {
1161
- let jsonStr = text.substring("\u6D4F\u89C8\u5668\u72B6\u6001: ".length);
1162
- let extraAlerts = "";
1163
- const firstNewline = jsonStr.indexOf("\n");
1164
- if (firstNewline !== -1) {
1165
- extraAlerts = jsonStr.substring(firstNewline);
1166
- jsonStr = jsonStr.substring(0, firstNewline);
1167
- }
1168
- try {
1169
- const parsed = JSON.parse(jsonStr);
1170
- if (parsed && typeof parsed.content === "string") {
1171
- a11yTreeStr = parsed.content;
1172
- parsed.content = "[Formatted A11y Tree - See details below]";
1173
- clone.content[0].text = `\u6D4F\u89C8\u5668\u72B6\u6001: ${JSON.stringify(parsed, null, 2)}${extraAlerts}`;
1174
- }
1175
- } catch {
1176
- }
3492
+ const browserState = tryParseBrowserStateText(text);
3493
+ if (browserState) {
3494
+ a11yTreeStr = browserState.content;
3495
+ browserState.content = "[Formatted A11y Tree - See details below]";
3496
+ clone.content[0].text = JSON.stringify(browserState, null, 2);
1177
3497
  } else if (text.includes("A11y Tree \u641C\u7D22\u7ED3\u679C") || text.includes("\u65E0\u969C\u788D\u6811\u641C\u7D22\u7ED3\u679C") || text.includes("\u65E0\u969C\u788D\u6811\u641C\u7D22") || text.includes("\u547D\u4E2D\u884C") || text.includes("context:")) {
1178
3498
  searchResultStr = text;
1179
3499
  clone.content[0].text = "[Search A11y Tree Result - See details below]";
@@ -1203,7 +3523,7 @@ ${searchResultStr}`;
1203
3523
  }
1204
3524
  function writeLog(commandName, args, result, error) {
1205
3525
  try {
1206
- const baseDir = process.env.WEBMCP_WORKSPACE || import_path3.default.join(import_os3.default.homedir(), ".webmcp_chrome_profile");
3526
+ const baseDir = process.env.WEBMCP_WORKSPACE || import_path3.default.join(import_os2.default.homedir(), ".webmcp_chrome_profile");
1207
3527
  const logDir = import_path3.default.join(baseDir, "logs");
1208
3528
  if (!import_fs3.default.existsSync(logDir)) {
1209
3529
  import_fs3.default.mkdirSync(logDir, { recursive: true });
@@ -1246,7 +3566,9 @@ function handleCommandError(error, commandName, args) {
1246
3566
  console.error(import_picocolors2.default.red(`Error executing ${commandName} command: ${msg}`));
1247
3567
  process.exit(1);
1248
3568
  }
1249
- program.name("webmcp-cli").description("WebMCP CLI for interacting with browser via CDP").version(package_default.version).option("-w, --workspace <path>", "\u6307\u5B9A\u81EA\u5B9A\u4E49\u7684\u6D4F\u89C8\u5668\u5DE5\u4F5C\u7A7A\u95F4\uFF08\u7528\u6237\u914D\u7F6E\u76EE\u5F55\uFF09\u8DEF\u5F84").hook("preAction", (thisCommand) => {
3569
+ program.name("webmcp-cli").description(
3570
+ "WebMCP CLI \u2014 \u652F\u6301\u4E24\u79CD\u6D4F\u89C8\u5668\u8FDE\u63A5\u6A21\u5F0F\uFF1A\n --mode cdp\uFF08\u9ED8\u8BA4\uFF09: \u57FA\u4E8E Puppeteer + CDP \u76F4\u8FDE\u6D4F\u89C8\u5668\uFF08\u72EC\u7ACB profile\uFF09\n --mode wxt : \u57FA\u4E8E WebSocket + Chrome \u6269\u5C55\u6865\u63A5\uFF08\u590D\u7528\u7528\u6237\u6570\u636E\uFF09"
3571
+ ).version(package_default.version).option("-w, --workspace <path>", "\u6307\u5B9A\u81EA\u5B9A\u4E49\u7684\u6D4F\u89C8\u5668\u5DE5\u4F5C\u7A7A\u95F4\uFF08\u7528\u6237\u914D\u7F6E\u76EE\u5F55\uFF09\u8DEF\u5F84\uFF0C\u4EC5 CDP \u6A21\u5F0F\u6709\u6548").hook("preAction", (thisCommand) => {
1250
3572
  const opts = thisCommand.opts();
1251
3573
  if (opts.workspace) {
1252
3574
  process.env.WEBMCP_WORKSPACE = opts.workspace;
@@ -1358,5 +3680,174 @@ tabs.command("forward [tabid]").description("\u5C06\u5F53\u524D\u6216\u6307\u5B9
1358
3680
  handleCommandError(error, "tabs forward", args);
1359
3681
  }
1360
3682
  });
1361
- program.parse(process.argv);
3683
+ program.command("mcp").description("\u4EE5\u6807\u51C6 MCP Server \u6A21\u5F0F\u542F\u52A8\uFF08stdio \u4F20\u8F93\uFF0CCDP \u5E95\u5C42\uFF09\u3002\n\u4F7F\u7528 --mode wxt mcp \u5207\u6362\u5230 WXT \u6865\u63A5\u5E95\u5C42\u3002").option("--agent", "\u4EE5\u5B50\u4EE3\u7406\u6A21\u5F0F\u542F\u52A8\uFF08\u6536\u655B\u5DE5\u5177\u4E3A\u9AD8\u5C42\u59D4\u6258\u63A5\u53E3\uFF09").action(async (opts) => {
3684
+ try {
3685
+ const { startMcpServer: startMcpServer2 } = await Promise.resolve().then(() => (init_server(), server_exports));
3686
+ await startMcpServer2({ mode: "cdp", agentMode: opts.agent ? "agent" : "tools" });
3687
+ } catch (error) {
3688
+ handleCommandError(error, "mcp", {});
3689
+ }
3690
+ });
3691
+ if (CLI_MODE === "wxt") {
3692
+ void handleWxtMode(FILTERED_ARGV.slice(2)).catch((error) => {
3693
+ handleCommandError(error, `wxt:${FILTERED_ARGV[2] ?? "help"}`, {});
3694
+ });
3695
+ } else {
3696
+ program.parse(FILTERED_ARGV);
3697
+ }
3698
+ async function handleWxtMode(args) {
3699
+ const command = args[0];
3700
+ if (command === "daemon" || command === "server") {
3701
+ const { runDaemonProcess: runDaemonProcess2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
3702
+ await runDaemonProcess2(args.slice(1));
3703
+ return;
3704
+ }
3705
+ if (command === "stop") {
3706
+ const { stopBridgeDaemon: stopBridgeDaemon2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
3707
+ const stopped = await stopBridgeDaemon2();
3708
+ console.log(stopped ? "\u2705 \u5DF2\u505C\u6B62\u540E\u53F0 WebSocket \u6865\u63A5\u670D\u52A1" : "\u2139\uFE0F \u5F53\u524D\u6CA1\u6709\u8FD0\u884C\u4E2D\u7684\u540E\u53F0\u6865\u63A5\u670D\u52A1");
3709
+ return;
3710
+ }
3711
+ if (command === "token") {
3712
+ const subArgs = args.slice(1);
3713
+ let wsPort2;
3714
+ const cleanArgs = [];
3715
+ for (let i = 0; i < subArgs.length; i++) {
3716
+ if ((subArgs[i] === "--ws-port" || subArgs[i] === "--port") && subArgs[i + 1]) {
3717
+ wsPort2 = parseInt(subArgs[++i], 10) || void 0;
3718
+ } else {
3719
+ cleanArgs.push(subArgs[i]);
3720
+ }
3721
+ }
3722
+ const action = cleanArgs[0];
3723
+ let tokenToSet;
3724
+ if (action === "set" && cleanArgs[1]) {
3725
+ tokenToSet = cleanArgs[1].trim();
3726
+ } else if (action && action !== "get" && !action.startsWith("-")) {
3727
+ tokenToSet = action.trim();
3728
+ }
3729
+ const { resolveOrCreateAuthToken: resolveOrCreateAuthToken2 } = await Promise.resolve().then(() => (init_bridge_client(), bridge_client_exports));
3730
+ if (tokenToSet) {
3731
+ resolveOrCreateAuthToken2(tokenToSet);
3732
+ console.log("\u2705 Token \u5DF2\u6210\u529F\u4FDD\u5B58\u81F3 ~/.robot-wxt/bridge-token");
3733
+ const { stopBridgeDaemon: stopBridgeDaemon2, ensureBridgeDaemon: ensureBridgeDaemon3 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
3734
+ await stopBridgeDaemon2(wsPort2);
3735
+ await ensureBridgeDaemon3({ token: tokenToSet, port: wsPort2 });
3736
+ console.log("\u{1F4A1} \u540E\u7EED\u6240\u6709 CLI \u547D\u4EE4\u4E0E MCP \u5DE5\u5177\u5747\u5C06\u81EA\u52A8\u4F7F\u7528\u6B64\u51ED\u636E\uFF0C\u65E0\u9700\u91CD\u590D\u8F93\u5165\u3002");
3737
+ return;
3738
+ }
3739
+ console.log(resolveOrCreateAuthToken2());
3740
+ return;
3741
+ }
3742
+ if (command === "mcp") {
3743
+ const { startMcpServer: startMcpServer2 } = await Promise.resolve().then(() => (init_server(), server_exports));
3744
+ const isAgent = args.includes("--agent") || args.includes("--mode=agent");
3745
+ const tokenIdx = args.indexOf("--token");
3746
+ const token2 = tokenIdx !== -1 ? args[tokenIdx + 1] : void 0;
3747
+ const wsPortIdx = args.indexOf("--ws-port");
3748
+ const wsPort2 = wsPortIdx !== -1 ? parseInt(args[wsPortIdx + 1], 10) || void 0 : void 0;
3749
+ await startMcpServer2({ mode: "wxt", agentMode: isAgent ? "agent" : "tools", token: token2, wsPort: wsPort2 });
3750
+ return;
3751
+ }
3752
+ if (!command || command === "--help" || command === "-h") {
3753
+ printWxtHelp();
3754
+ return;
3755
+ }
3756
+ let token;
3757
+ let wsPort;
3758
+ const commandArgs = [];
3759
+ for (let i = 1; i < args.length; i++) {
3760
+ if (args[i] === "--token" && args[i + 1]) {
3761
+ token = args[++i];
3762
+ } else if (args[i] === "--ws-port" && args[i + 1]) {
3763
+ wsPort = parseInt(args[++i], 10) || void 0;
3764
+ } else {
3765
+ commandArgs.push(args[i]);
3766
+ }
3767
+ }
3768
+ const { ensureBridgeDaemon: ensureBridgeDaemon2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
3769
+ const isJson = commandArgs.includes("--json");
3770
+ await ensureBridgeDaemon2({ token, port: wsPort, silent: isJson });
3771
+ const { WxtBrowserAdapter: WxtBrowserAdapter2 } = await Promise.resolve().then(() => (init_wxt_adapter(), wxt_adapter_exports));
3772
+ const adapter = new WxtBrowserAdapter2(token, wsPort);
3773
+ await adapter.ensureConnected();
3774
+ try {
3775
+ switch (command) {
3776
+ case "state": {
3777
+ const tabIdx = commandArgs.indexOf("--tab");
3778
+ const tabId = tabIdx !== -1 ? commandArgs[tabIdx + 1] : void 0;
3779
+ const result = await adapter.getState(tabId ? parseInt(tabId, 10) : void 0);
3780
+ console.log(JSON.stringify(result, null, 2));
3781
+ break;
3782
+ }
3783
+ case "run": {
3784
+ const toolName = commandArgs.find((a) => !a.startsWith("-"));
3785
+ const argsStr = commandArgs.slice(commandArgs.indexOf(toolName) + 1).find((a) => !a.startsWith("-"));
3786
+ if (!toolName) {
3787
+ console.error("[\u9519\u8BEF] \u8BF7\u63D0\u4F9B\u5DE5\u5177\u540D\u79F0");
3788
+ process.exit(1);
3789
+ }
3790
+ const toolArgs = argsStr ? JSON.parse(argsStr) : {};
3791
+ const result = await adapter.callTool(toolName, toolArgs);
3792
+ console.log(JSON.stringify(result, null, 2));
3793
+ break;
3794
+ }
3795
+ case "tabs": {
3796
+ const tabAction = commandArgs[0];
3797
+ const tabArgs = commandArgs.slice(1);
3798
+ const url = tabArgs.find((a) => a.startsWith("http"));
3799
+ const tabIdVal = tabArgs.find((a) => !a.startsWith("-") && !a.startsWith("http"));
3800
+ const result = await adapter.tabs(tabAction, {
3801
+ url,
3802
+ tabId: tabIdVal ? parseInt(tabIdVal, 10) : void 0
3803
+ });
3804
+ console.log(JSON.stringify(result, null, 2));
3805
+ break;
3806
+ }
3807
+ case "agent": {
3808
+ const { handleAgentCommand: handleAgentCommand2 } = await Promise.resolve().then(() => (init_agent(), agent_exports));
3809
+ await handleAgentCommand2(adapter, commandArgs);
3810
+ break;
3811
+ }
3812
+ case "skills":
3813
+ case "skill": {
3814
+ const { handleSkillsCommand: handleSkillsCommand2 } = await Promise.resolve().then(() => (init_skills(), skills_exports));
3815
+ await handleSkillsCommand2(adapter, commandArgs);
3816
+ break;
3817
+ }
3818
+ default:
3819
+ console.error(`[\u9519\u8BEF] WXT \u6A21\u5F0F\u4E0B\u672A\u77E5\u547D\u4EE4: ${command}`);
3820
+ printWxtHelp();
3821
+ process.exit(1);
3822
+ }
3823
+ } finally {
3824
+ await adapter.dispose();
3825
+ }
3826
+ }
3827
+ function printWxtHelp() {
3828
+ console.log(`
3829
+ webmcp-cli --mode wxt \u2014 WXT \u6865\u63A5\u6A21\u5F0F\uFF08\u901A\u8FC7 Chrome \u6269\u5C55\u8FDE\u63A5\uFF0C\u590D\u7528\u7528\u6237\u6570\u636E\uFF09
3830
+
3831
+ \u547D\u4EE4\uFF1A
3832
+ state \u83B7\u53D6\u5F53\u524D\u6D3B\u8DC3 tab \u4FE1\u606F\u4E0E\u9875\u9762\u5DE5\u5177\u5217\u8868
3833
+ run <tool> [args] \u8C03\u7528\u9875\u9762 WebMCP \u5DE5\u5177
3834
+ tabs <action> [...] \u7BA1\u7406\u6807\u7B7E\u9875\uFF08open/close/switch/back/forward\uFF09
3835
+ agent run "<\u6307\u4EE4>" \u59D4\u6258 Tiny Robot \u5B50\u4EE3\u7406\u81EA\u4E3B\u6267\u884C\u9AD8\u5C42\u4EFB\u52A1
3836
+ skills list \u5217\u51FA\u5DF2\u6CE8\u518C\u7684 Skills \u6280\u80FD
3837
+ skills get <name> \u8BFB\u53D6\u6307\u5B9A\u6280\u80FD\u7684\u8BE6\u7EC6\u6307\u4EE4
3838
+ token [get|set <t>] \u67E5\u770B\u6216\u4FDD\u5B58\u8BA4\u8BC1 Token
3839
+ stop \u505C\u6B62\u540E\u53F0 WebSocket \u6865\u63A5\u670D\u52A1
3840
+ mcp \u4EE5 MCP Server \u6A21\u5F0F\u542F\u52A8
3841
+
3842
+ \u9009\u9879\uFF1A
3843
+ --token <token> \u8BA4\u8BC1 Token\uFF08\u4F18\u5148\u4E8E ~/.robot-wxt/bridge-token\uFF09
3844
+ --ws-port <port> WS \u6865\u63A5\u7AEF\u53E3\uFF08\u9ED8\u8BA4 18999\uFF09
3845
+ --json \u8F93\u51FA JSON \u683C\u5F0F
3846
+
3847
+ \u793A\u4F8B\uFF1A
3848
+ webmcp-cli --mode wxt state
3849
+ webmcp-cli --mode wxt agent run "\u5E2E\u6211\u628A\u5546\u54C1\u52A0\u5165\u8D2D\u7269\u8F66"
3850
+ webmcp-cli --mode wxt mcp --agent
3851
+ `.trim());
3852
+ }
1362
3853
  //# sourceMappingURL=bin.cjs.map