@opentiny/webmcp-cli 0.1.0-alpha.1 → 0.1.1-alpha.1

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.js CHANGED
@@ -1,13 +1,192 @@
1
1
  #!/usr/bin/env node
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __esm = (fn, res) => function __init() {
5
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
- };
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
2
+
3
+ // src/bin.ts
4
+ import fs2 from "fs";
5
+ import path2 from "path";
6
+ import os2 from "os";
7
+ import { Command } from "commander";
8
+ import pc2 from "picocolors";
9
+ import { readFileSync as readFileSync2 } from "fs";
10
+ import { resolve as resolve2 } from "path";
11
+
12
+ // src/expand-file-refs.ts
13
+ import { readFileSync } from "fs";
14
+ import { dirname, isAbsolute, normalize, resolve } from "path";
15
+ import { fileURLToPath } from "url";
16
+ var JSON_STRING_LITERAL = /"(?:[^"\\]|\\.)*"/g;
17
+ var UNQUOTED_FILE_REF = /(?<![\\"])@(base64)?file:([^\s"',}\]]+)/g;
18
+ var FILE_REF_PREFIX = /^@(base64)?file:(.+)$/s;
19
+ function resolveFilePath(filePath, baseDir = process.cwd()) {
20
+ let normalizedPath = filePath.trim();
21
+ if (normalizedPath.startsWith('"') && normalizedPath.endsWith('"') || normalizedPath.startsWith("'") && normalizedPath.endsWith("'")) {
22
+ normalizedPath = normalizedPath.slice(1, -1).trim();
23
+ }
24
+ if (normalizedPath.startsWith("file://")) {
25
+ normalizedPath = fileURLToPath(normalizedPath);
26
+ }
27
+ if (isAbsolute(normalizedPath)) {
28
+ return normalize(normalizedPath);
29
+ }
30
+ return resolve(baseDir, normalizedPath);
31
+ }
32
+ function decodeFilePath(rawPath) {
33
+ return rawPath.replace(/\\\\/g, "\\");
34
+ }
35
+ function readFileRefContent(filePath, baseDir, base64) {
36
+ const absPath = resolveFilePath(filePath, baseDir);
37
+ let content;
38
+ try {
39
+ content = readFileSync(absPath, "utf-8");
40
+ } catch (e) {
41
+ throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6\u5F15\u7528 "${filePath}" (${absPath}): ${e.message}`);
42
+ }
43
+ return base64 ? Buffer.from(content, "utf-8").toString("base64") : content;
44
+ }
45
+ function expandFileRefValue(rawInner, baseDir) {
46
+ const match = rawInner.match(FILE_REF_PREFIX);
47
+ if (!match) {
48
+ return null;
49
+ }
50
+ const [, base64Flag, rawPath] = match;
51
+ const filePath = decodeFilePath(rawPath);
52
+ const value = readFileRefContent(filePath, baseDir, Boolean(base64Flag));
53
+ return JSON.stringify(value);
54
+ }
55
+ function expandQuotedFileRefs(argsJson, baseDir) {
56
+ return argsJson.replace(JSON_STRING_LITERAL, (jsonStringLiteral) => {
57
+ const rawInner = jsonStringLiteral.slice(1, -1);
58
+ const replacement = expandFileRefValue(rawInner, baseDir);
59
+ return replacement ?? jsonStringLiteral;
60
+ });
61
+ }
62
+ function expandUnquotedFileRefs(argsJson, baseDir) {
63
+ return argsJson.replace(UNQUOTED_FILE_REF, (match, base64Flag, filePath) => {
64
+ const value = readFileRefContent(filePath, baseDir, Boolean(base64Flag));
65
+ return JSON.stringify(value);
66
+ });
67
+ }
68
+ function expandFileRefs(argsJson, baseDir = process.cwd()) {
69
+ const withQuotedExpanded = expandQuotedFileRefs(argsJson, baseDir);
70
+ return expandUnquotedFileRefs(withQuotedExpanded, baseDir);
71
+ }
72
+ function getFileBaseDir(fileOption) {
73
+ if (!fileOption) {
74
+ return process.cwd();
75
+ }
76
+ return dirname(resolve(process.cwd(), fileOption));
77
+ }
78
+
79
+ // src/parse-run-args.ts
80
+ import JSON5 from "json5";
81
+ function cleanJsonString(str) {
82
+ let cleaned = str.trim();
83
+ if (cleaned.startsWith("'") && cleaned.endsWith("'")) {
84
+ cleaned = cleaned.slice(1, -1).trim();
85
+ }
86
+ return cleaned;
87
+ }
88
+ function looksLikeObjectBody(raw) {
89
+ return /^("?[\w-]+"?\s*:)/.test(raw);
90
+ }
91
+ function joinShellArgs(args) {
92
+ const cleaned = args.map(cleanJsonString);
93
+ const first = cleaned[0] ?? "";
94
+ if (first.startsWith("{")) {
95
+ return cleaned.join(" ");
96
+ }
97
+ if (looksLikeObjectBody(first)) {
98
+ let joined = cleaned.join(" ");
99
+ if (!joined.startsWith("{")) {
100
+ joined = `{${joined}}`;
101
+ }
102
+ if (!joined.endsWith("}")) {
103
+ joined = `${joined}}`;
104
+ }
105
+ return joined;
106
+ }
107
+ return cleaned.join(" ");
108
+ }
109
+ function insertMissingCommas(raw) {
110
+ return raw.replace(/"(\s+)("?[\w-]+"?\s*:)/g, '",$2');
111
+ }
112
+ function quoteUnquotedStringValues(raw) {
113
+ return raw.replace(
114
+ /([{,]\s*(?:"([^"]+)"|([\w-]+))\s*:\s*)(?!"@(?:base64)?file:|"|true|false|null|-?\d|\{|\[)([^",}\]]+?)(?=\s*[,}])/g,
115
+ (_match, prefix, _quotedKey, _unquotedKey, value) => {
116
+ const trimmed = value.trim();
117
+ if (/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(trimmed)) {
118
+ return prefix + trimmed;
119
+ }
120
+ return prefix + JSON.stringify(trimmed);
121
+ }
122
+ );
123
+ }
124
+ function normalizeShellDamagedJson(raw) {
125
+ let normalized = raw.trim();
126
+ normalized = insertMissingCommas(normalized);
127
+ normalized = quoteUnquotedStringValues(normalized);
128
+ return normalized;
129
+ }
130
+ function buildArgsFromKeyValuePairs(args) {
131
+ const obj = {};
132
+ for (const pair of args) {
133
+ const index = pair.indexOf("=");
134
+ if (index === -1) {
135
+ throw new Error(`\u65E0\u6548\u7684\u53C2\u6570\u683C\u5F0F "${pair}"\u3002\u8BF7\u4F7F\u7528 key=value\uFF0C\u6216 JSON / -f \u6587\u4EF6\u3002`);
136
+ }
137
+ const key = pair.substring(0, index).trim();
138
+ let val = cleanJsonString(pair.substring(index + 1).trim());
139
+ try {
140
+ obj[key] = JSON.parse(val);
141
+ } catch {
142
+ obj[key] = val;
143
+ }
144
+ }
145
+ return JSON.stringify(obj);
146
+ }
147
+ function parseArgsJson(raw) {
148
+ const trimmed = cleanJsonString(raw);
149
+ try {
150
+ return JSON.stringify(JSON5.parse(trimmed));
151
+ } catch (firstError) {
152
+ const repaired = normalizeShellDamagedJson(trimmed);
153
+ try {
154
+ return JSON.stringify(JSON5.parse(repaired));
155
+ } catch {
156
+ 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`;
157
+ const message = firstError instanceof Error ? firstError.message : String(firstError);
158
+ throw new Error(`\u53C2\u6570\u4E0D\u662F\u6709\u6548\u7684 JSON \u6216 JS \u5BF9\u8C61: ${message}
159
+ ${hint}`);
160
+ }
161
+ }
162
+ }
163
+ function prepareRunArgsJson(args, fileContent, baseDir) {
164
+ if (fileContent !== void 0) {
165
+ const trimmed = fileContent.trim();
166
+ if (!trimmed) {
167
+ throw new Error("\u901A\u8FC7 -f/--file \u6307\u5B9A\u7684\u53C2\u6570\u6587\u4EF6\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A");
168
+ }
169
+ const expanded2 = expandFileRefs(trimmed, baseDir);
170
+ return parseArgsJson(expanded2);
171
+ }
172
+ if (args.length === 0) {
173
+ return "{}";
174
+ }
175
+ const joined = joinShellArgs(args);
176
+ let raw = "";
177
+ if (joined.startsWith("{") || looksLikeObjectBody(joined)) {
178
+ raw = joined;
179
+ } else if (args.every((arg) => arg.includes("="))) {
180
+ raw = buildArgsFromKeyValuePairs(args);
181
+ } else {
182
+ raw = joined;
183
+ }
184
+ if (!raw.trim()) {
185
+ throw new Error("\u672A\u63D0\u4F9B\u6709\u6548\u53C2\u6570");
186
+ }
187
+ const expanded = expandFileRefs(raw, baseDir);
188
+ return parseArgsJson(expanded);
189
+ }
11
190
 
12
191
  // src/browser.ts
13
192
  import puppeteer from "puppeteer-core";
@@ -18,6 +197,8 @@ import path from "path";
18
197
  import http from "http";
19
198
  import { spawn } from "child_process";
20
199
  import { fileURLToPath as fileURLToPath2 } from "url";
200
+ var __filename = fileURLToPath2(import.meta.url);
201
+ var __dirname = path.dirname(__filename);
21
202
  function getCdpPort() {
22
203
  const raw = process.env.WEBMCP_CDP_PORT;
23
204
  if (raw) {
@@ -33,38 +214,6 @@ function shouldLaunchHeadless() {
33
214
  if (process.env.WEBMCP_HEADLESS === "0") return false;
34
215
  return process.env.WEBMCP_HEADLESS === "1" || process.env.CI === "true" || process.env.CI === "1";
35
216
  }
36
- function shouldIgnoreCertificateErrors() {
37
- return process.env.WEBMCP_IGNORE_CERTIFICATE_ERRORS === "1";
38
- }
39
- function buildChromeLaunchArgs(input) {
40
- const launchArgs = [
41
- `--remote-debugging-port=${input.cdpPort}`,
42
- `--user-data-dir=${input.userDataDir}`,
43
- "--no-first-run",
44
- "--no-default-browser-check"
45
- ];
46
- if (input.headless) {
47
- launchArgs.push(
48
- "--headless=new",
49
- "--no-sandbox",
50
- "--disable-setuid-sandbox",
51
- "--disable-gpu",
52
- "--disable-dev-shm-usage"
53
- );
54
- }
55
- const ignoreCertificateErrors = input.ignoreCertificateErrors ?? shouldIgnoreCertificateErrors();
56
- if (ignoreCertificateErrors) {
57
- launchArgs.push("--ignore-certificate-errors");
58
- }
59
- return launchArgs;
60
- }
61
- function buildPuppeteerConnectOptions(browserBaseUrl) {
62
- return {
63
- browserURL: browserBaseUrl,
64
- defaultViewport: null,
65
- ...shouldIgnoreCertificateErrors() ? { ignoreHTTPSErrors: true } : {}
66
- };
67
- }
68
217
  function readActivePortFromProfile(userDataDir) {
69
218
  try {
70
219
  const content = fs.readFileSync(path.join(userDataDir, "DevToolsActivePort"), "utf-8");
@@ -159,7 +308,7 @@ async function findAvailableCdpUrl(addresses, retries = 2) {
159
308
  async function connectPuppeteer(browserBaseUrl, attempt = 1, maxAttempts = 3) {
160
309
  try {
161
310
  return await promiseWithTimeout(
162
- puppeteer.connect(buildPuppeteerConnectOptions(browserBaseUrl)),
311
+ puppeteer.connect({ browserURL: browserBaseUrl, defaultViewport: null }),
163
312
  1e4,
164
313
  `puppeteer.connect to ${browserBaseUrl} timed out`
165
314
  );
@@ -234,11 +383,21 @@ async function startBrowserInBackground() {
234
383
  fs.unlinkSync(path.join(userDataDir, "DevToolsActivePort"));
235
384
  } catch {
236
385
  }
237
- const launchArgs = buildChromeLaunchArgs({
238
- cdpPort,
239
- userDataDir,
240
- headless: shouldLaunchHeadless()
241
- });
386
+ const launchArgs = [
387
+ `--remote-debugging-port=${cdpPort}`,
388
+ `--user-data-dir=${userDataDir}`,
389
+ "--no-first-run",
390
+ "--no-default-browser-check"
391
+ ];
392
+ if (shouldLaunchHeadless()) {
393
+ launchArgs.push(
394
+ "--headless=new",
395
+ "--no-sandbox",
396
+ "--disable-setuid-sandbox",
397
+ "--disable-gpu",
398
+ "--disable-dev-shm-usage"
399
+ );
400
+ }
242
401
  const child = spawn(
243
402
  browserInfo.path,
244
403
  launchArgs,
@@ -359,2780 +518,160 @@ async function activateTabById(browser, tabid) {
359
518
  try {
360
519
  await session.send("Target.activateTarget", { targetId: realTabId });
361
520
  } finally {
362
- await session.detach().catch(() => {
363
- });
364
- }
365
- }
366
- async function getTargetPage(browser, tabid) {
367
- const pageTargets = getPageTargets(browser);
368
- if (pageTargets.length === 0) {
369
- const newPage = await browser.newPage();
370
- await injectWebMCPPolyfillAndTools(newPage);
371
- return newPage;
372
- }
373
- let targetPage = null;
374
- if (tabid !== void 0) {
375
- const target = findPageTargetByTabId(browser, tabid);
376
- if (!target) {
377
- throw new Error(`Tab with targetId "${tabid}" not found.`);
378
- }
379
- targetPage = await target.page();
380
- } else {
381
- const lastTabId = getLastActiveTabId();
382
- if (lastTabId) {
383
- const lastTarget = findPageTargetByTabId(browser, lastTabId);
384
- if (lastTarget) {
385
- targetPage = await lastTarget.page();
386
- }
387
- }
388
- if (!targetPage) {
389
- try {
390
- const workspaceDir = getWorkspaceDir();
391
- const cdpPort = getCdpPort();
392
- const recordedPort = readActivePortFromProfile(workspaceDir);
393
- const ports = recordedPort && recordedPort !== cdpPort ? [recordedPort, cdpPort] : [cdpPort];
394
- const urls = ports.flatMap((port) => candidateCdpBaseUrls(port).map((u) => `${u}/json/list`));
395
- let activeTargetId = null;
396
- for (const url of urls) {
397
- try {
398
- const body = await httpGet(url, 1e3);
399
- const targetsData = JSON.parse(body);
400
- const active = targetsData.find((t) => t.type === "page" && !t.url.startsWith("devtools://"));
401
- if (active) {
402
- activeTargetId = active.id;
403
- break;
404
- }
405
- } catch {
406
- }
407
- }
408
- if (activeTargetId) {
409
- for (const target of pageTargets) {
410
- if (getTargetIdFromTarget(target) === activeTargetId) {
411
- targetPage = await target.page();
412
- break;
413
- }
414
- }
415
- }
416
- } catch {
417
- }
418
- }
419
- if (!targetPage) {
420
- const lastTarget = pageTargets[pageTargets.length - 1];
421
- targetPage = await lastTarget.page();
422
- }
423
- }
424
- if (!targetPage) {
425
- throw new Error("\u65E0\u6CD5\u83B7\u53D6\u76EE\u6807\u9875\u9762");
426
- }
427
- await injectWebMCPPolyfillAndTools(targetPage);
428
- return targetPage;
429
- }
430
- async function injectIntoPage(page) {
431
- await injectWebMCPPolyfillAndTools(page);
432
- }
433
- async function injectWebMCPPolyfillAndTools(page) {
434
- const polyfillReady = await page.evaluate(() => {
435
- return !!window.__webmcpcli_init;
436
- }).catch(() => false);
437
- if (!polyfillReady) {
438
- console.log(pc.cyan("\u5F53\u524D\u9875\u9762\u5C1A\u672A\u6CE8\u5165 WebMCP \u73AF\u5883\uFF0C\u6B63\u5728\u6267\u884C\u81EA\u52A8\u6CE8\u5165..."));
439
- const injectScriptPath = path.resolve(__dirname, "inject-bundle.js");
440
- if (!fs.existsSync(injectScriptPath)) {
441
- throw new Error(`Cannot find inject-bundle.js at ${injectScriptPath}. Please ensure you run 'pnpm build:inject' first.`);
442
- }
443
- const scriptContent = fs.readFileSync(injectScriptPath, "utf-8");
444
- try {
445
- await page.evaluate(scriptContent);
446
- } catch (err) {
447
- const msg = err instanceof Error ? err.message : String(err);
448
- throw new Error("\u81EA\u52A8\u6CE8\u5165\u811A\u672C\u6267\u884C\u5931\u8D25: " + msg);
449
- }
450
- await page.waitForFunction(() => {
451
- const mcp = navigator.modelContext;
452
- return mcp && typeof mcp.registerTool === "function";
453
- }, { timeout: 1e4 }).catch(() => {
454
- console.warn("\u7B49\u5F85 WebMCP registerTool \u63A5\u53E3\u5C31\u7EEA\u8D85\u65F6\uFF0C\u6B63\u5728\u7EE7\u7EED\u6CE8\u5165...");
455
- });
456
- }
457
- await injectDomainTools(page);
458
- }
459
- function getToolsBundleName(hostname) {
460
- const normalized = hostname.split(":")[0].toLowerCase();
461
- const toolsDir = path.resolve(__dirname, "webmcp-tools");
462
- if (!fs.existsSync(toolsDir)) {
463
- return null;
464
- }
465
- let files = [];
466
- try {
467
- files = fs.readdirSync(toolsDir);
468
- } catch {
469
- return null;
470
- }
471
- const supportedDomains = files.filter((f) => f.endsWith(".js")).map((f) => f.slice(0, -3));
472
- if (supportedDomains.includes(normalized)) {
473
- return `webmcp-tools/${normalized}.js`;
474
- }
475
- for (const domain of supportedDomains) {
476
- if (normalized.endsWith("." + domain)) {
477
- return `webmcp-tools/${domain}.js`;
478
- }
479
- }
480
- return null;
481
- }
482
- async function injectDomainTools(page) {
483
- let hostname;
484
- try {
485
- const url = new URL(page.url());
486
- hostname = url.hostname;
487
- } catch {
488
- return;
489
- }
490
- const bundleName = getToolsBundleName(hostname);
491
- if (!bundleName) {
492
- return;
493
- }
494
- const toolBundlePath = path.resolve(__dirname, bundleName);
495
- if (!fs.existsSync(toolBundlePath)) {
496
- return;
497
- }
498
- const bundleKey = bundleName.replace(/^webmcp-tools\//, "").replace(/\.js$/, "");
499
- const flagKey = `__webmcptools_${bundleKey.replace(/[^a-zA-Z0-9]/g, "")}`;
500
- const alreadyInjected = await page.evaluate((key) => !!window[key], flagKey).catch(() => false);
501
- if (alreadyInjected) {
502
- return;
503
- }
504
- console.log(pc.cyan(`\u68C0\u6D4B\u5230\u57DF\u540D ${hostname} \u6709\u9884\u7F6E\u5DE5\u5177\uFF0C\u6B63\u5728\u6CE8\u5165...`));
505
- const toolScript = fs.readFileSync(toolBundlePath, "utf-8");
506
- try {
507
- await page.evaluate(toolScript);
508
- console.log(pc.green(`\u5DF2\u4E3A ${hostname} \u6CE8\u5165\u9884\u7F6E\u5DE5\u5177`));
509
- } catch (err) {
510
- const msg = err instanceof Error ? err.message : String(err);
511
- console.warn(pc.yellow(`\u57DF\u540D\u5DE5\u5177\u6CE8\u5165\u5931\u8D25 (${hostname}): ${msg}`));
512
- }
513
- }
514
- var __filename, __dirname;
515
- var init_browser = __esm({
516
- "src/browser.ts"() {
517
- "use strict";
518
- __filename = fileURLToPath2(import.meta.url);
519
- __dirname = path.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.1.0-alpha.1",
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
- import { z } from "zod";
594
- var BrowserStateInput, BrowserToolCallInput, BrowserTabsOpenInput, BrowserTabsCloseInput, BrowserTabsSwitchInput, BrowserTabsNavInput, BrowserSubAgentRunInput, BrowserSkillsListInput, BrowserSkillsReadInput;
595
- var init_tools = __esm({
596
- "src/mcp/tools.ts"() {
597
- "use strict";
598
- BrowserStateInput = z.object({
599
- tabId: z.union([z.string(), 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 = z.object({
604
- toolName: 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: z.record(z.unknown()).optional().describe("\u5DE5\u5177\u53C2\u6570\uFF0C\u4E0E\u5DE5\u5177\u7684 inputSchema \u5BF9\u9F50"),
606
- tabId: z.union([z.string(), z.number()]).optional().describe("\u76EE\u6807 tab ID\uFF0C\u4E0D\u4F20\u65F6\u4F7F\u7528\u5F53\u524D\u6D3B\u8DC3 tab")
607
- });
608
- BrowserTabsOpenInput = z.object({
609
- url: 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 = z.object({
612
- tabId: z.union([z.string(), 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 = z.object({
617
- tabId: z.union([z.string(), 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: 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 = z.object({
623
- tabId: z.union([z.string(), z.number()]).optional().describe("\u76EE\u6807 tab ID\uFF0C\u4E0D\u4F20\u65F6\u4F7F\u7528\u5F53\u524D\u6D3B\u8DC3 tab")
624
- });
625
- BrowserSubAgentRunInput = z.object({
626
- instruction: 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: z.number().optional().describe("\u76EE\u6807 tab ID\uFF0C\u4E0D\u4F20\u65F6\u4F7F\u7528\u5F53\u524D\u6D3B\u8DC3 tab"),
628
- maxSteps: 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 = 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 = z.object({
632
- name: 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
- import path2 from "path";
846
- import os2 from "os";
847
- import fs2 from "fs";
848
- function resolveBaseWorkspace(params) {
849
- if (params.workspacePath && typeof params.workspacePath === "string" && params.workspacePath.trim()) {
850
- const trimmedWs = params.workspacePath.trim();
851
- return path2.isAbsolute(trimmedWs) ? trimmedWs : path2.resolve(os2.homedir(), trimmedWs);
852
- }
853
- if (params.conversationId && typeof params.conversationId === "string" && params.conversationId.trim()) {
854
- const safeId = params.conversationId.trim().replace(/[/\\?%*:|"<>.]/g, "_");
855
- const sessionDir = path2.resolve(WORKSPACES_ROOT, safeId || "default");
856
- const relative = path2.relative(WORKSPACES_ROOT, sessionDir);
857
- if (!relative || relative.startsWith("..") || path2.isAbsolute(relative)) {
858
- return path2.join(WORKSPACES_ROOT, "default");
859
- }
860
- return sessionDir;
861
- }
862
- return path2.join(WORKSPACES_ROOT, "default");
863
- }
864
- function resolveWorkspaceDir(params = {}) {
865
- const baseDir = resolveBaseWorkspace(params);
866
- if (!fs2.existsSync(baseDir)) {
867
- try {
868
- fs2.mkdirSync(baseDir, { recursive: true, mode: 493 });
869
- } catch {
870
- }
871
- }
872
- if (!params.cwd || typeof params.cwd !== "string" || !params.cwd.trim()) {
873
- return baseDir;
874
- }
875
- const trimmedCwd = params.cwd.trim();
876
- const targetDir = path2.isAbsolute(trimmedCwd) ? path2.resolve(trimmedCwd) : path2.resolve(baseDir, trimmedCwd);
877
- const relative = path2.relative(baseDir, targetDir);
878
- if (relative.startsWith("..") || path2.isAbsolute(relative)) {
879
- throw new BashInvalidParamsError(`\u76EE\u6807\u6267\u884C\u8DEF\u5F84\u8D85\u51FA\u5DF2\u6388\u6743\u5DE5\u4F5C\u7A7A\u95F4\u5B89\u5168\u8FB9\u754C: ${trimmedCwd}`);
880
- }
881
- return targetDir;
882
- }
883
- var WORKSPACES_ROOT, BashInvalidParamsError;
884
- var init_workspace_manager = __esm({
885
- "src/bridge/workspace-manager.ts"() {
886
- "use strict";
887
- WORKSPACES_ROOT = path2.join(os2.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
- import fs3 from "fs";
900
- import path3 from "path";
901
- import { spawn as spawn2 } from "child_process";
902
- function findWindowsBash() {
903
- const pathDirs = (process.env.PATH || "").split(path3.delimiter);
904
- for (const dir of pathDirs) {
905
- if (!dir) continue;
906
- const candidate = path3.join(dir, "bash.exe");
907
- try {
908
- if (fs3.existsSync(candidate)) return candidate;
909
- } catch {
910
- }
911
- }
912
- const localAppData = process.env.LOCALAPPDATA || "";
913
- const programFiles = process.env.ProgramFiles || "C:\\Program Files";
914
- const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
915
- const programW6432 = process.env.ProgramW6432 || programFiles;
916
- const commonGitBashPaths = [
917
- path3.join(programFiles, "Git", "bin", "bash.exe"),
918
- path3.join(programFiles, "Git", "usr", "bin", "bash.exe"),
919
- path3.join(programW6432, "Git", "bin", "bash.exe"),
920
- path3.join(programFilesX86, "Git", "bin", "bash.exe"),
921
- path3.join(localAppData, "Programs", "Git", "bin", "bash.exe"),
922
- path3.join(localAppData, "Programs", "Git", "usr", "bin", "bash.exe"),
923
- path3.join(process.env.SystemRoot || "C:\\Windows", "System32", "bash.exe")
924
- ];
925
- for (const candidate of commonGitBashPaths) {
926
- try {
927
- if (fs3.existsSync(candidate)) return candidate;
928
- } catch {
929
- }
930
- }
931
- return null;
932
- }
933
- function resolveShell(forcePlatform) {
934
- const currentPlatform = forcePlatform || process.platform;
935
- if (!forcePlatform && cachedShell) {
936
- return cachedShell;
937
- }
938
- if (currentPlatform !== "win32") {
939
- const posixShell = process.env.SHELL || "/bin/bash";
940
- if (!forcePlatform) cachedShell = posixShell;
941
- return posixShell;
942
- }
943
- const winBash = findWindowsBash();
944
- if (winBash) {
945
- if (!forcePlatform) cachedShell = winBash;
946
- return winBash;
947
- }
948
- const fallback = "powershell.exe";
949
- if (!forcePlatform) cachedShell = fallback;
950
- return fallback;
951
- }
952
- function killProcessTree(child) {
953
- if (process.platform === "win32" && child.pid) {
954
- try {
955
- spawn2("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
956
- windowsHide: true,
957
- stdio: "ignore"
958
- });
959
- } catch {
960
- child.kill("SIGKILL");
961
- }
962
- } else {
963
- child.kill("SIGTERM");
964
- setTimeout(() => {
965
- try {
966
- child.kill("SIGKILL");
967
- } catch {
968
- }
969
- }, 2e3);
970
- }
971
- }
972
- async function executeBash(params) {
973
- const trimmedCommand = params.command?.trim();
974
- if (!trimmedCommand) {
975
- throw new BashInvalidParamsError("\u547D\u4EE4\u4E0D\u80FD\u4E3A\u7A7A");
976
- }
977
- if (/rm\s+(-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*\s+|--recursive\s+--force\s+)\s*(\/|~|\$HOME|\/\*)\s*$/i.test(
978
- trimmedCommand
979
- ) || /:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/i.test(trimmedCommand)) {
980
- 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");
981
- }
982
- const cwd = resolveWorkspaceDir({
983
- cwd: params.cwd,
984
- workspacePath: params.workspacePath,
985
- conversationId: params.conversationId
986
- });
987
- const normalizedTimeoutMs = typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs) && params.timeoutMs > 0 ? Math.min(params.timeoutMs, MAX_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS;
988
- const { env = {}, maxBuffer = DEFAULT_MAX_BUFFER } = params;
989
- const startTime = Date.now();
990
- const shell = resolveShell();
991
- return new Promise((resolve3, reject) => {
992
- const stdoutChunks = [];
993
- let stdoutBytes = 0;
994
- const stderrChunks = [];
995
- let stderrBytes = 0;
996
- let truncated = false;
997
- let isKilled = false;
998
- const child = spawn2(trimmedCommand, {
999
- shell,
1000
- cwd,
1001
- env: { ...process.env, ...env },
1002
- windowsHide: true
1003
- });
1004
- const killTimeoutTimer = setTimeout(() => {
1005
- isKilled = true;
1006
- killProcessTree(child);
1007
- reject(new BashTimeoutError(normalizedTimeoutMs));
1008
- }, normalizedTimeoutMs);
1009
- child.stdout.on("data", (chunk) => {
1010
- if (stdoutBytes < maxBuffer) {
1011
- const remaining = maxBuffer - stdoutBytes;
1012
- if (chunk.length <= remaining) {
1013
- stdoutChunks.push(chunk);
1014
- stdoutBytes += chunk.length;
1015
- } else {
1016
- stdoutChunks.push(chunk.subarray(0, remaining));
1017
- stdoutBytes += remaining;
1018
- truncated = true;
1019
- }
1020
- } else {
1021
- truncated = true;
1022
- }
1023
- });
1024
- child.stderr.on("data", (chunk) => {
1025
- if (stderrBytes < maxBuffer) {
1026
- const remaining = maxBuffer - stderrBytes;
1027
- if (chunk.length <= remaining) {
1028
- stderrChunks.push(chunk);
1029
- stderrBytes += chunk.length;
1030
- } else {
1031
- stderrChunks.push(chunk.subarray(0, remaining));
1032
- stderrBytes += remaining;
1033
- truncated = true;
1034
- }
1035
- } else {
1036
- truncated = true;
1037
- }
1038
- });
1039
- child.on("error", (err) => {
1040
- clearTimeout(killTimeoutTimer);
1041
- reject(err);
1042
- });
1043
- child.on("close", (exitCode, signal) => {
1044
- clearTimeout(killTimeoutTimer);
1045
- if (isKilled) return;
1046
- const stdout = Buffer.concat(stdoutChunks).toString("utf8").trim();
1047
- const stderr = Buffer.concat(stderrChunks).toString("utf8").trim();
1048
- resolve3({
1049
- stdout,
1050
- stderr,
1051
- exitCode,
1052
- signal,
1053
- durationMs: Date.now() - startTime,
1054
- ...truncated ? { truncated: true } : {}
1055
- });
1056
- });
1057
- });
1058
- }
1059
- var BashTimeoutError, DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, DEFAULT_MAX_BUFFER, cachedShell;
1060
- var init_bash_executor = __esm({
1061
- "src/bridge/bash-executor.ts"() {
1062
- "use strict";
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
- import { spawn as spawn3 } from "child_process";
1082
- async function pickDirectory(optionsOrTitle) {
1083
- const options = typeof optionsOrTitle === "string" ? { title: optionsOrTitle } : optionsOrTitle || {};
1084
- const title = options.title || "\u8BF7\u9009\u62E9\u5DE5\u4F5C\u7A7A\u95F4\u6587\u4EF6\u5939";
1085
- const defaultPath = options.defaultPath && typeof options.defaultPath === "string" ? options.defaultPath.trim() : void 0;
1086
- const platform = process.platform;
1087
- if (platform === "darwin") {
1088
- return pickDirectoryMac(title, defaultPath);
1089
- }
1090
- if (platform === "win32") {
1091
- return pickDirectoryWindows(title, defaultPath);
1092
- }
1093
- return pickDirectoryLinux(title, defaultPath);
1094
- }
1095
- function pickDirectoryMac(title, defaultPath) {
1096
- const safeTitle = title.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
1097
- const defaultClause = defaultPath ? ` default location POSIX file "${defaultPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` : "";
1098
- const appleScript = `POSIX path of (choose folder with prompt "${safeTitle}"${defaultClause})`;
1099
- return new Promise((resolve3, reject) => {
1100
- const child = spawn3("osascript", ["-e", appleScript], {
1101
- stdio: ["ignore", "pipe", "pipe"]
1102
- });
1103
- let stdout = "";
1104
- let stderr = "";
1105
- child.stdout?.on("data", (d) => {
1106
- stdout += d.toString();
1107
- });
1108
- child.stderr?.on("data", (d) => {
1109
- stderr += d.toString();
1110
- });
1111
- child.on("close", (code) => {
1112
- if (code === 0) {
1113
- const selected = stdout.trim();
1114
- resolve3(selected || null);
1115
- return;
1116
- }
1117
- if (code === 1 && (stderr.includes("User canceled") || stderr.includes("-128") || !stderr.trim())) {
1118
- resolve3(null);
1119
- return;
1120
- }
1121
- reject(new Error(`\u5524\u8D77\u7CFB\u7EDF\u6587\u4EF6\u5939\u9009\u62E9\u5668\u5931\u8D25: ${stderr.trim() || `\u9000\u51FA\u7801 ${code}`}`));
1122
- });
1123
- child.on("error", (err) => {
1124
- reject(new Error(`\u5524\u8D77\u7CFB\u7EDF\u6587\u4EF6\u5939\u9009\u62E9\u5668\u5931\u8D25: ${err.message}`));
1125
- });
1126
- });
1127
- }
1128
- function escapePowerShellString(str) {
1129
- return str.replace(/`/g, "``").replace(/"/g, '`"').replace(/\$/g, "`$");
1130
- }
1131
- function pickDirectoryWindows(title, defaultPath) {
1132
- const safeTitle = escapePowerShellString(title);
1133
- const safeDefaultPath = escapePowerShellString(defaultPath ?? "");
1134
- const psScript = `
1135
- $code = @'
1136
- using System;
1137
- using System.Runtime.InteropServices;
1138
-
1139
- [ComImport, Guid("D57C7288-D4AD-4768-BE02-9D969532D960"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
1140
- interface IFileOpenDialog {
1141
- [PreserveSig] int Show(IntPtr hwnd);
1142
- void SetFileTypes(uint cFileTypes, IntPtr rgFilterSpec);
1143
- void SetFileTypeIndex(uint iFileType);
1144
- void GetFileTypeIndex(out uint piFileType);
1145
- void Advise(IntPtr pfde, out uint pdwCookie);
1146
- void Unadvise(uint dwCookie);
1147
- void SetOptions(uint fos);
1148
- void GetOptions(out uint pfos);
1149
- void SetDefaultFolder(IntPtr psi);
1150
- void SetFolder(IntPtr psi);
1151
- void GetFolder(out IntPtr ppsi);
1152
- void GetCurrentSelection(out IntPtr ppsi);
1153
- void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string pszName);
1154
- void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
1155
- void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
1156
- void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string pszText);
1157
- void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
1158
- void GetResult(out IntPtr ppsi);
1159
- void AddPlace(IntPtr psi, int fdap);
1160
- void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
1161
- void Close(int hr);
1162
- void SetClientGuid([In] ref Guid guid);
1163
- void ClearClientData();
1164
- void SetFilter(IntPtr pFilter);
1165
- void GetResults(out IntPtr ppenum);
1166
- void GetSelectedItems(out IntPtr ppsai);
1167
- }
1168
-
1169
- [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
1170
- interface IShellItem {
1171
- void BindToHandler(IntPtr pbc, [In] ref Guid bhid, [In] ref Guid riid, out IntPtr ppv);
1172
- void GetParent(out IShellItem ppsi);
1173
- void GetDisplayName(uint sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
1174
- void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);
1175
- void Compare(IShellItem psi, uint hint, out int piOrder);
1176
- }
1177
-
1178
- public static class FolderPicker {
1179
- [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
1180
- static extern int SHCreateItemFromParsingName(string pszPath, IntPtr pbc, [In] ref Guid riid, out IntPtr ppv);
1181
-
1182
- // FOS_PICKFOLDERS = 0x20, FOS_FORCEFILESYSTEM = 0x40
1183
- const uint FOS_PICKFOLDERS = 0x00000020;
1184
- const uint FOS_FORCEFILESYSTEM = 0x00000040;
1185
-
1186
- public static string Pick(string title, string defaultPath) {
1187
- var clsid = new Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7");
1188
- var riid = new Guid("D57C7288-D4AD-4768-BE02-9D969532D960");
1189
- var obj = Activator.CreateInstance(Type.GetTypeFromCLSID(clsid));
1190
- var dialog = (IFileOpenDialog)obj;
1191
- dialog.SetOptions(FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM);
1192
- dialog.SetTitle(title);
1193
- if (!string.IsNullOrEmpty(defaultPath)) {
1194
- var riidShellItem = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE");
1195
- IntPtr psi;
1196
- if (SHCreateItemFromParsingName(defaultPath, IntPtr.Zero, ref riidShellItem, out psi) == 0) {
1197
- dialog.SetFolder(psi);
1198
- Marshal.Release(psi);
1199
- }
1200
- }
1201
- int hr = dialog.Show(IntPtr.Zero);
1202
- if (hr != 0) return null; // \u7528\u6237\u53D6\u6D88 (HRESULT_FROM_WIN32(ERROR_CANCELLED) = 0x800704C7)
1203
- IntPtr ppsi;
1204
- dialog.GetResult(out ppsi);
1205
- var shellItem = (IShellItem)Marshal.GetTypedObjectForIUnknown(ppsi, typeof(IShellItem));
1206
- string path;
1207
- shellItem.GetDisplayName(0x80058000, out path); // SIGDN_FILESYSPATH
1208
- Marshal.Release(ppsi);
1209
- return path;
1210
- }
1211
- }
1212
- '@
1213
- Add-Type -TypeDefinition $code
1214
- $result = [FolderPicker]::Pick("${safeTitle}", "${safeDefaultPath}")
1215
- if ($result) { Write-Output $result }
1216
- `;
1217
- return new Promise((resolve3, reject) => {
1218
- const child = spawn3("powershell", ["-STA", "-NoProfile", "-WindowStyle", "Hidden", "-Command", psScript], {
1219
- stdio: ["ignore", "pipe", "pipe"],
1220
- windowsHide: true
1221
- });
1222
- let stdout = "";
1223
- let stderr = "";
1224
- child.stdout?.on("data", (d) => {
1225
- stdout += d.toString();
1226
- });
1227
- child.stderr?.on("data", (d) => {
1228
- stderr += d.toString();
1229
- });
1230
- child.on("close", (code) => {
1231
- if (code === 0) {
1232
- const selected = stdout.trim();
1233
- resolve3(selected || null);
1234
- return;
1235
- }
1236
- reject(new Error(`PowerShell \u6587\u4EF6\u5939\u9009\u62E9\u5668\u6267\u884C\u5931\u8D25: ${stderr.trim() || `\u9000\u51FA\u7801 ${code}`}`));
1237
- });
1238
- child.on("error", (err) => {
1239
- reject(new Error(`\u5524\u8D77 PowerShell \u6587\u4EF6\u5939\u9009\u62E9\u5668\u5931\u8D25: ${err.message}`));
1240
- });
1241
- });
1242
- }
1243
- function pickDirectoryLinux(title, defaultPath) {
1244
- const args = ["--file-selection", "--directory", `--title=${title}`];
1245
- if (defaultPath) {
1246
- args.push(`--filename=${defaultPath}`);
1247
- }
1248
- return new Promise((resolve3, reject) => {
1249
- const child = spawn3("zenity", args, {
1250
- stdio: ["ignore", "pipe", "pipe"]
1251
- });
1252
- let stdout = "";
1253
- let stderr = "";
1254
- child.stdout?.on("data", (d) => {
1255
- stdout += d.toString();
1256
- });
1257
- child.stderr?.on("data", (d) => {
1258
- stderr += d.toString();
1259
- });
1260
- child.on("close", (code) => {
1261
- if (code === 0) {
1262
- const selected = stdout.trim();
1263
- resolve3(selected || null);
1264
- return;
1265
- }
1266
- if (code === 1) {
1267
- resolve3(null);
1268
- return;
1269
- }
1270
- reject(new Error(`zenity \u76EE\u5F55\u9009\u62E9\u5668\u5F02\u5E38\u9000\u51FA (\u9000\u51FA\u7801 ${code}): ${stderr.trim()}`));
1271
- });
1272
- child.on("error", (err) => {
1273
- if (err?.code === "ENOENT") {
1274
- 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)"));
1275
- return;
1276
- }
1277
- reject(new Error(`\u5524\u8D77 zenity \u76EE\u5F55\u9009\u62E9\u5668\u5931\u8D25: ${err.message}`));
1278
- });
1279
- });
1280
- }
1281
- var init_directory_picker = __esm({
1282
- "src/bridge/directory-picker.ts"() {
1283
- "use strict";
1284
- }
1285
- });
1286
-
1287
- // src/bridge/bridge-client.ts
1288
- var bridge_client_exports = {};
1289
- __export(bridge_client_exports, {
1290
- BRIDGE_ERROR_CODE: () => BRIDGE_ERROR_CODE,
1291
- ExtensionBridgeClient: () => ExtensionBridgeClient,
1292
- PROTOCOL_VERSION: () => PROTOCOL_VERSION,
1293
- computeHmac: () => computeHmac,
1294
- deriveSharedSecret: () => deriveSharedSecret,
1295
- getKillPortHint: () => getKillPortHint,
1296
- resolveOrCreateAuthToken: () => resolveOrCreateAuthToken,
1297
- verifyHmacConstantTime: () => verifyHmacConstantTime
1298
- });
1299
- import { WebSocketServer, WebSocket as WsClient } from "ws";
1300
- import { EventEmitter } from "events";
1301
- import { randomUUID, randomBytes, createHmac, createHash, timingSafeEqual } from "crypto";
1302
- import fs4 from "fs";
1303
- import path4 from "path";
1304
- import os3 from "os";
1305
- function resolveOrCreateAuthToken(explicitToken) {
1306
- if (explicitToken && explicitToken.trim()) {
1307
- const token = explicitToken.trim();
1308
- try {
1309
- if (!fs4.existsSync(TOKEN_FILE_DIR)) {
1310
- fs4.mkdirSync(TOKEN_FILE_DIR, { mode: 448, recursive: true });
1311
- }
1312
- fs4.writeFileSync(TOKEN_FILE_PATH, token, { mode: 384, encoding: "utf8" });
1313
- } catch {
1314
- }
1315
- return token;
1316
- }
1317
- if (process.env.ROBOT_WXT_BRIDGE_TOKEN) {
1318
- return process.env.ROBOT_WXT_BRIDGE_TOKEN.trim();
1319
- }
1320
- try {
1321
- if (fs4.existsSync(TOKEN_FILE_PATH)) {
1322
- const existing = fs4.readFileSync(TOKEN_FILE_PATH, "utf8").trim();
1323
- if (existing) return existing;
1324
- }
1325
- } catch {
1326
- }
1327
- const newToken = randomBytes(32).toString("hex");
1328
- try {
1329
- if (!fs4.existsSync(TOKEN_FILE_DIR)) {
1330
- fs4.mkdirSync(TOKEN_FILE_DIR, { mode: 448, recursive: true });
1331
- }
1332
- fs4.writeFileSync(TOKEN_FILE_PATH, newToken, { mode: 384, encoding: "utf8" });
1333
- } catch {
1334
- }
1335
- return newToken;
1336
- }
1337
- function parseMajorVersion(v) {
1338
- return parseInt(v.split(".")[0] ?? "0", 10);
1339
- }
1340
- function deriveSharedSecret(tokenOrExtensionId, hmacSalt) {
1341
- return createHash("sha256").update(`${tokenOrExtensionId}:${hmacSalt}`).digest();
1342
- }
1343
- function computeHmac(secret, challenge) {
1344
- return createHmac("sha256", secret).update(challenge).digest("hex");
1345
- }
1346
- function verifyHmacConstantTime(actualHex, expectedHex) {
1347
- if (!actualHex || typeof actualHex !== "string") return false;
1348
- try {
1349
- const actualBuf = Buffer.from(actualHex, "hex");
1350
- const expectedBuf = Buffer.from(expectedHex, "hex");
1351
- if (actualBuf.length !== expectedBuf.length) return false;
1352
- return timingSafeEqual(actualBuf, expectedBuf);
1353
- } catch {
1354
- return false;
1355
- }
1356
- }
1357
- function getKillPortHint(port) {
1358
- if (process.platform === "win32") {
1359
- return `netstat -ano | findstr :${port} \uFF08\u627E\u5230 PID \u540E\u6267\u884C: taskkill /pid <PID> /T /F\uFF09`;
1360
- }
1361
- return `lsof -ti:${port} | xargs kill -9`;
1362
- }
1363
- var WS_PORT, REQUEST_TIMEOUT_MS, HANDSHAKE_TIMEOUT_MS, WS_OPEN, TOKEN_FILE_DIR, TOKEN_FILE_PATH, ExtensionBridgeClient;
1364
- var init_bridge_client = __esm({
1365
- "src/bridge/bridge-client.ts"() {
1366
- "use strict";
1367
- init_protocol();
1368
- init_bash_executor();
1369
- init_directory_picker();
1370
- WS_PORT = DEFAULT_WS_PORT;
1371
- REQUEST_TIMEOUT_MS = 3e4;
1372
- HANDSHAKE_TIMEOUT_MS = 5e3;
1373
- WS_OPEN = 1;
1374
- TOKEN_FILE_DIR = path4.join(os3.homedir(), ".robot-wxt");
1375
- TOKEN_FILE_PATH = path4.join(TOKEN_FILE_DIR, "bridge-token");
1376
- ExtensionBridgeClient = class _ExtensionBridgeClient extends EventEmitter {
1377
- constructor(port = WS_PORT, authToken) {
1378
- super();
1379
- this.port = port;
1380
- this.explicitAuthToken = authToken;
1381
- this.authToken = authToken ?? resolveOrCreateAuthToken();
1382
- }
1383
- port;
1384
- wss = null;
1385
- extensionSocket = null;
1386
- clientSocket = null;
1387
- forwardedRequests = /* @__PURE__ */ new Map();
1388
- pending = /* @__PURE__ */ new Map();
1389
- socketAuthStates = /* @__PURE__ */ new Map();
1390
- destroyed = false;
1391
- idCounter = 0;
1392
- isClientMode = false;
1393
- explicitAuthToken;
1394
- authToken;
1395
- /** 获取当前服务端使用的认证 Token */
1396
- get currentAuthToken() {
1397
- return this.authToken;
1398
- }
1399
- /** 获取当前激活的 Socket */
1400
- _getActiveSocket() {
1401
- if (this.isClientMode && this.clientSocket) {
1402
- return this.clientSocket.readyState === WS_OPEN ? this.clientSocket : null;
1403
- }
1404
- if (this.extensionSocket && this.extensionSocket.readyState === WS_OPEN) {
1405
- return this.extensionSocket;
1406
- }
1407
- return null;
1408
- }
1409
- /** 是否已有就绪的扩展连接(或作为 Client 已连接到 Server) */
1410
- get isConnected() {
1411
- return this._getActiveSocket() != null;
1412
- }
1413
- /** 等待扩展连接或作为客户端连入服务就绪 */
1414
- async waitForReady(timeoutMs = 5e3) {
1415
- if (this.isConnected) return true;
1416
- return new Promise((resolve3) => {
1417
- const timer = setTimeout(() => {
1418
- cleanup();
1419
- resolve3(this.isConnected);
1420
- }, timeoutMs);
1421
- const cleanup = () => {
1422
- clearTimeout(timer);
1423
- this.off("connected", onConnected);
1424
- };
1425
- const onConnected = () => {
1426
- cleanup();
1427
- resolve3(true);
1428
- };
1429
- this.on("connected", onConnected);
1430
- });
1431
- }
1432
- /**
1433
- * 静态探测目标端口的桥接服务状态
1434
- */
1435
- static async probe(port = WS_PORT, authToken, timeoutMs = 800) {
1436
- const client = new _ExtensionBridgeClient(port, authToken);
1437
- try {
1438
- const res = await client._probeExistingServer(timeoutMs);
1439
- if (client.clientSocket) {
1440
- try {
1441
- client.clientSocket.close(1e3, "Probe finished");
1442
- } catch {
1443
- }
1444
- }
1445
- if (res.success) {
1446
- return { running: true, authed: true };
1447
- }
1448
- if (res.error) {
1449
- const isAuthError = res.error.message.includes("HMAC") || res.error.message.includes("\u8BA4\u8BC1\u5931\u8D25") || res.error.message.includes("Unauthorized");
1450
- if (isAuthError) {
1451
- return { running: true, authed: false, error: res.error.message };
1452
- }
1453
- return { running: false, authed: false, error: res.error.message };
1454
- }
1455
- return { running: false, authed: false };
1456
- } finally {
1457
- client.destroy();
1458
- }
1459
- }
1460
- /**
1461
- * 自动探测模式:
1462
- * 优先尝试连接已存在的 18999 服务;连接不上时退回启动本机的 WebSocketServer。
1463
- */
1464
- async startAuto(probeTimeoutMs = 800) {
1465
- if (this.destroyed) return;
1466
- const probe = await this._probeExistingServer(probeTimeoutMs);
1467
- if (probe.success) {
1468
- return;
1469
- }
1470
- if (probe.error) {
1471
- throw probe.error;
1472
- }
1473
- this.connect();
1474
- }
1475
- async _probeExistingServer(timeoutMs) {
1476
- return new Promise((resolve3) => {
1477
- let settled = false;
1478
- let connectionEstablished = false;
1479
- let authFailedReason = null;
1480
- const ws = new WsClient(`ws://127.0.0.1:${this.port}`);
1481
- const timer = setTimeout(() => {
1482
- if (!settled) {
1483
- settled = true;
1484
- try {
1485
- ws.terminate();
1486
- } catch {
1487
- }
1488
- if (authFailedReason) {
1489
- resolve3({
1490
- success: false,
1491
- error: new Error(
1492
- `\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
1493
- \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`
1494
- )
1495
- });
1496
- } else if (connectionEstablished) {
1497
- resolve3({
1498
- success: false,
1499
- error: new Error(
1500
- `\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`
1501
- )
1502
- });
1503
- } else {
1504
- resolve3({ success: false });
1505
- }
1506
- }
1507
- }, timeoutMs);
1508
- ws.on("open", () => {
1509
- connectionEstablished = true;
1510
- });
1511
- ws.on("close", (code, reason) => {
1512
- const reasonStr = reason ? reason.toString() : "";
1513
- if (code === WS_CLOSE_CODE.UNAUTHORIZED || reasonStr.includes("Unauthorized") || reasonStr.includes("HMAC")) {
1514
- authFailedReason = reasonStr || "Token \u8BA4\u8BC1\u88AB\u62D2\u7EDD (HMAC verification failed)";
1515
- }
1516
- if (!settled && authFailedReason) {
1517
- settled = true;
1518
- clearTimeout(timer);
1519
- resolve3({
1520
- success: false,
1521
- error: new Error(
1522
- `\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
1523
- \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`
1524
- )
1525
- });
1526
- }
1527
- });
1528
- ws.on("message", (data) => {
1529
- try {
1530
- const msg = JSON.parse(data.toString());
1531
- if (msg.type === "BRIDGE_CHALLENGE" && msg.challenge && msg.hmacSalt) {
1532
- connectionEstablished = true;
1533
- const secret = deriveSharedSecret(this.authToken, msg.hmacSalt);
1534
- const hmac = computeHmac(secret, msg.challenge);
1535
- ws.send(
1536
- JSON.stringify({
1537
- type: "BRIDGE_AUTH",
1538
- clientType: "cli-client",
1539
- challenge: msg.challenge,
1540
- hmac
1541
- })
1542
- );
1543
- return;
1544
- }
1545
- if (msg.type === "BRIDGE_AUTH_OK" && !settled) {
1546
- settled = true;
1547
- clearTimeout(timer);
1548
- this.isClientMode = true;
1549
- this.clientSocket = ws;
1550
- this._bindClientSocket(ws);
1551
- this.emit("connected");
1552
- resolve3({ success: true });
1553
- }
1554
- } catch {
1555
- }
1556
- });
1557
- ws.once("error", (err) => {
1558
- if (!settled) {
1559
- settled = true;
1560
- clearTimeout(timer);
1561
- try {
1562
- ws.terminate();
1563
- } catch {
1564
- }
1565
- if (err?.code === "ECONNREFUSED" || err?.message?.includes("ECONNREFUSED")) {
1566
- resolve3({ success: false });
1567
- } else {
1568
- resolve3({
1569
- success: false,
1570
- error: new Error(`\u8FDE\u63A5\u672C\u5730 127.0.0.1:${this.port} \u5931\u8D25: ${err?.message || err}`)
1571
- });
1572
- }
1573
- }
1574
- });
1575
- });
1576
- }
1577
- _bindClientSocket(ws) {
1578
- ws.on("message", (data) => {
1579
- let msg;
1580
- try {
1581
- msg = JSON.parse(data.toString());
1582
- } catch {
1583
- return;
1584
- }
1585
- if (msg.type === "BRIDGE_CHALLENGE" || msg.type === "BRIDGE_AUTH_OK") {
1586
- return;
1587
- }
1588
- if (msg.method === "notification/sub_agent_progress") {
1589
- this.emit("progress", msg.params);
1590
- return;
1591
- }
1592
- const pending = this.pending.get(String(msg.id));
1593
- if (!pending) return;
1594
- this.pending.delete(String(msg.id));
1595
- clearTimeout(pending.timer);
1596
- if (msg.error) {
1597
- pending.reject(new Error(`[${msg.error.code}] ${msg.error.message}`));
1598
- } else {
1599
- pending.resolve(msg.result);
1600
- }
1601
- });
1602
- ws.on("close", () => {
1603
- this.clientSocket = null;
1604
- this.emit("disconnected");
1605
- this._rejectAllPending("\u4E0E\u670D\u52A1\u7684\u8FDE\u63A5\u5DF2\u65AD\u5F00");
1606
- });
1607
- }
1608
- /** 启动 WebSocket 服务端,等待 Chrome 扩展(Offscreen Document)连入 */
1609
- connect() {
1610
- if (this.destroyed) return;
1611
- if (this.wss) return;
1612
- try {
1613
- this.wss = new WebSocketServer({
1614
- port: this.port,
1615
- host: "127.0.0.1",
1616
- verifyClient: (info, callback) => {
1617
- const origin = info.origin || info.req.headers.origin;
1618
- if (origin) {
1619
- const isAllowedExtension = origin.startsWith("chrome-extension://") || origin.startsWith("moz-extension://") || origin.startsWith("extension://");
1620
- if (!isAllowedExtension) {
1621
- callback(false, 403, "Forbidden origin: only browser extensions are allowed");
1622
- return;
1623
- }
1624
- }
1625
- callback(true);
1626
- }
1627
- });
1628
- } catch (err) {
1629
- this.emit("error", err);
1630
- return;
1631
- }
1632
- this.wss.on("listening", () => {
1633
- this.emit("listening");
1634
- });
1635
- this.wss.on("error", (err) => {
1636
- if (err?.code === "EADDRINUSE") {
1637
- process.stderr.write(
1638
- `[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
1639
- `
1640
- );
1641
- }
1642
- this.emit("error", err);
1643
- });
1644
- this.wss.on("connection", (socket) => {
1645
- const challenge = randomUUID();
1646
- const hmacSalt = randomBytes(16).toString("hex");
1647
- const authState = {
1648
- authenticated: false,
1649
- challenge,
1650
- hmacSalt,
1651
- timer: setTimeout(() => {
1652
- if (!authState.authenticated) {
1653
- try {
1654
- socket.close(WS_CLOSE_CODE.UNAUTHORIZED, "Handshake timeout");
1655
- } catch {
1656
- }
1657
- }
1658
- }, HANDSHAKE_TIMEOUT_MS)
1659
- };
1660
- this.socketAuthStates.set(socket, authState);
1661
- try {
1662
- socket.send(
1663
- JSON.stringify({
1664
- type: "BRIDGE_CHALLENGE",
1665
- challenge,
1666
- hmacSalt,
1667
- protocolVersion: PROTOCOL_VERSION
1668
- })
1669
- );
1670
- } catch {
1671
- }
1672
- socket.on("message", async (data) => {
1673
- await this.handleSocketMessage(socket, data);
1674
- });
1675
- socket.on("close", () => {
1676
- const auth = this.socketAuthStates.get(socket);
1677
- if (auth?.timer) clearTimeout(auth.timer);
1678
- this.socketAuthStates.delete(socket);
1679
- for (const [reqId, fwdInfo] of this.forwardedRequests.entries()) {
1680
- if (fwdInfo.socket === socket) {
1681
- if (fwdInfo.timer) clearTimeout(fwdInfo.timer);
1682
- this.forwardedRequests.delete(reqId);
1683
- }
1684
- }
1685
- if (socket === this.extensionSocket) {
1686
- this.extensionSocket = null;
1687
- this.emit("disconnected");
1688
- for (const [reqId, fwdInfo] of this.forwardedRequests.entries()) {
1689
- if (fwdInfo.timer) clearTimeout(fwdInfo.timer);
1690
- try {
1691
- if (fwdInfo.socket.readyState === WS_OPEN) {
1692
- fwdInfo.socket.send(
1693
- JSON.stringify({
1694
- jsonrpc: "2.0",
1695
- id: fwdInfo.originalId,
1696
- error: {
1697
- code: BRIDGE_ERROR_CODE.EXTENSION_NOT_CONNECTED,
1698
- message: "Chrome \u6269\u5C55\u8FDE\u63A5\u5DF2\u65AD\u5F00"
1699
- }
1700
- })
1701
- );
1702
- }
1703
- } catch {
1704
- }
1705
- this.forwardedRequests.delete(reqId);
1706
- }
1707
- this._rejectAllPending("WebSocket \u8FDE\u63A5\u5DF2\u65AD\u5F00");
1708
- }
1709
- });
1710
- socket.on("error", () => {
1711
- });
1712
- });
1713
- this.wss.on("error", (err) => {
1714
- this.emit("error", err);
1715
- });
1716
- }
1717
- async handleSocketMessage(socket, data) {
1718
- let msg;
1719
- try {
1720
- msg = JSON.parse(data.toString());
1721
- } catch {
1722
- return;
1723
- }
1724
- const currentAuth = this.socketAuthStates.get(socket);
1725
- if (!currentAuth || !currentAuth.authenticated) {
1726
- await this.handleHandshake(socket, currentAuth, msg);
1727
- return;
1728
- }
1729
- if (msg.type === "KEEP_ALIVE" || msg.type === "WS_BRIDGE_KEEP_ALIVE") {
1730
- return;
1731
- }
1732
- if (msg.method && msg.id) {
1733
- if (socket === this.extensionSocket) {
1734
- await this.handleExtensionSystemRpc(socket, msg);
1735
- return;
1736
- }
1737
- await this.handleForwardRpc(socket, msg);
1738
- return;
1739
- }
1740
- if (msg.method && !msg.id) {
1741
- this.handleProgressNotification(msg);
1742
- return;
1743
- }
1744
- if (msg.id) {
1745
- this.handleIncomingResponse(msg);
1746
- }
1747
- }
1748
- verifyHandshakeHmac(currentAuth, hmac) {
1749
- if (!currentAuth.hmacSalt || !hmac) return false;
1750
- const secret = deriveSharedSecret(this.authToken, currentAuth.hmacSalt);
1751
- const expectedHmac = computeHmac(secret, currentAuth.challenge);
1752
- if (verifyHmacConstantTime(hmac, expectedHmac)) {
1753
- return true;
1754
- }
1755
- if (!this.explicitAuthToken) {
1756
- const diskToken = resolveOrCreateAuthToken();
1757
- if (diskToken && diskToken !== this.authToken) {
1758
- const diskSecret = deriveSharedSecret(diskToken, currentAuth.hmacSalt);
1759
- const diskExpectedHmac = computeHmac(diskSecret, currentAuth.challenge);
1760
- if (verifyHmacConstantTime(hmac, diskExpectedHmac)) {
1761
- this.authToken = diskToken;
1762
- return true;
1763
- }
1764
- }
1765
- }
1766
- return false;
1767
- }
1768
- async handleHandshake(socket, currentAuth, msg) {
1769
- if (!currentAuth || msg.type !== "BRIDGE_AUTH" || msg.challenge !== currentAuth.challenge) {
1770
- try {
1771
- socket.close(WS_CLOSE_CODE.UNAUTHORIZED, "Unauthorized: Handshake failed");
1772
- } catch {
1773
- }
1774
- return;
1775
- }
1776
- const clientVersion = typeof msg.protocolVersion === "string" ? msg.protocolVersion : PROTOCOL_VERSION;
1777
- if (parseMajorVersion(clientVersion) !== parseMajorVersion(PROTOCOL_VERSION)) {
1778
- try {
1779
- socket.close(
1780
- WS_CLOSE_CODE.PROTOCOL_MISMATCH,
1781
- `Protocol version mismatch: server=${PROTOCOL_VERSION}, client=${clientVersion}`
1782
- );
1783
- } catch {
1784
- }
1785
- return;
1786
- }
1787
- const verified = this.verifyHandshakeHmac(currentAuth, msg.hmac);
1788
- if (!verified) {
1789
- const tokenFingerprint = this.authToken ? `${this.authToken.slice(0, 6)}...` : "none";
1790
- process.stderr.write(
1791
- `[webmcp-cli] HMAC \u9A8C\u8BC1\u5931\u8D25\uFF0C\u62D2\u7EDD\u8FDE\u63A5. client extensionId=${msg.extensionId}, server authTokenFingerprint=${tokenFingerprint}
1792
- `
1793
- );
1794
- try {
1795
- socket.close(WS_CLOSE_CODE.UNAUTHORIZED, "Unauthorized: HMAC verification failed");
1796
- } catch {
1797
- }
1798
- return;
1799
- }
1800
- clearTimeout(currentAuth.timer);
1801
- currentAuth.authenticated = true;
1802
- currentAuth.clientType = msg.clientType;
1803
- if (msg.clientType === "extension") {
1804
- if (this.extensionSocket && this.extensionSocket !== socket) {
1805
- try {
1806
- this.extensionSocket.close(WS_CLOSE_CODE.REPLACED, "Replaced by new connection");
1807
- } catch {
1808
- }
1809
- }
1810
- this.extensionSocket = socket;
1811
- this.emit("connected");
1812
- }
1813
- try {
1814
- socket.send(
1815
- JSON.stringify({
1816
- type: "BRIDGE_AUTH_OK",
1817
- clientType: msg.clientType
1818
- })
1819
- );
1820
- } catch {
1821
- }
1822
- }
1823
- async handleForwardRpc(socket, msg) {
1824
- let targetSocket = this._getActiveSocket();
1825
- if (!targetSocket) {
1826
- await new Promise((resolve3) => {
1827
- const timer2 = setTimeout(resolve3, 6e3);
1828
- this.once("connected", () => {
1829
- clearTimeout(timer2);
1830
- resolve3();
1831
- });
1832
- });
1833
- targetSocket = this._getActiveSocket();
1834
- }
1835
- if (!targetSocket) {
1836
- socket.send(
1837
- JSON.stringify({
1838
- jsonrpc: "2.0",
1839
- id: msg.id,
1840
- error: {
1841
- code: BRIDGE_ERROR_CODE.EXTENSION_NOT_CONNECTED,
1842
- 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"
1843
- }
1844
- })
1845
- );
1846
- return;
1847
- }
1848
- const internalId = `fwd_${++this.idCounter}_${Date.now()}`;
1849
- const timeoutMs = msg.method === "sub_agent/run" ? 18e4 : REQUEST_TIMEOUT_MS;
1850
- const timer = setTimeout(() => {
1851
- const fwd = this.forwardedRequests.get(internalId);
1852
- if (!fwd) return;
1853
- this.forwardedRequests.delete(internalId);
1854
- try {
1855
- if (fwd.socket.readyState === WS_OPEN) {
1856
- fwd.socket.send(
1857
- JSON.stringify({
1858
- jsonrpc: "2.0",
1859
- id: fwd.originalId,
1860
- error: {
1861
- code: BRIDGE_ERROR_CODE.REQUEST_TIMEOUT,
1862
- message: `\u8BF7\u6C42\u8F6C\u53D1\u81F3 Chrome \u6269\u5C55\u8D85\u65F6 (${timeoutMs / 1e3}s)`
1863
- }
1864
- })
1865
- );
1866
- }
1867
- } catch {
1868
- }
1869
- }, timeoutMs);
1870
- this.forwardedRequests.set(internalId, {
1871
- socket,
1872
- originalId: msg.id,
1873
- progressToken: msg.params?.progressToken,
1874
- timer
1875
- });
1876
- const outgoingMsg = { ...msg, id: internalId };
1877
- targetSocket.send(JSON.stringify(outgoingMsg));
1878
- }
1879
- sendJsonRpcResponse(socket, response) {
1880
- if (socket.readyState === WS_OPEN) {
1881
- socket.send(JSON.stringify({ jsonrpc: "2.0", ...response }));
1882
- }
1883
- }
1884
- formatSystemRpcError(err) {
1885
- if (err instanceof BashInvalidParamsError || err?.code === "INVALID_PARAMS" || err?.message === "\u547D\u4EE4\u4E0D\u80FD\u4E3A\u7A7A") {
1886
- return { code: BRIDGE_ERROR_CODE.INVALID_PARAMS, message: err?.message || "\u53C2\u6570\u9519\u8BEF" };
1887
- }
1888
- if (err instanceof BashTimeoutError || err?.code === "TIMEOUT" || typeof err?.message === "string" && err.message.includes("\u8D85\u65F6")) {
1889
- return { code: BRIDGE_ERROR_CODE.EXECUTION_TIMEOUT, message: err?.message || "\u547D\u4EE4\u6267\u884C\u8D85\u65F6" };
1890
- }
1891
- return { code: BRIDGE_ERROR_CODE.EXECUTION_FAILED, message: err?.message || "\u6267\u884C\u5931\u8D25" };
1892
- }
1893
- systemRpcHandlers = Object.assign(
1894
- /* @__PURE__ */ Object.create(null),
1895
- {
1896
- [BRIDGE_METHODS.SYSTEM_BASH]: async (params) => {
1897
- return executeBash(params || {});
1898
- },
1899
- [BRIDGE_METHODS.SYSTEM_PICK_DIRECTORY]: async (params) => {
1900
- const selectedPath = await pickDirectory({
1901
- title: params?.title || void 0,
1902
- defaultPath: params?.defaultPath || void 0
1903
- });
1904
- return {
1905
- path: selectedPath,
1906
- selectedPath,
1907
- canceled: selectedPath === null
1908
- };
1909
- }
1910
- }
1911
- );
1912
- async handleExtensionSystemRpc(socket, msg) {
1913
- const { id, method, params } = msg;
1914
- const handler = typeof method === "string" && Object.prototype.hasOwnProperty.call(this.systemRpcHandlers, method) ? this.systemRpcHandlers[method] : void 0;
1915
- if (!handler || typeof handler !== "function") {
1916
- this.sendJsonRpcResponse(socket, {
1917
- id,
1918
- error: {
1919
- code: BRIDGE_ERROR_CODE.METHOD_NOT_FOUND,
1920
- message: `\u4E0D\u652F\u6301\u7684\u65B9\u6CD5: ${method}`
1921
- }
1922
- });
1923
- return;
1924
- }
1925
- try {
1926
- const result = await handler(params);
1927
- this.sendJsonRpcResponse(socket, { id, result });
1928
- } catch (err) {
1929
- this.sendJsonRpcResponse(socket, { id, error: this.formatSystemRpcError(err) });
1930
- }
1931
- }
1932
- handleProgressNotification(msg) {
1933
- const token = msg.params?.progressToken;
1934
- if (token != null) {
1935
- for (const [, reqInfo] of this.forwardedRequests) {
1936
- if (reqInfo.progressToken === token) {
1937
- try {
1938
- if (reqInfo.socket.readyState === WS_OPEN) {
1939
- reqInfo.socket.send(JSON.stringify(msg));
1940
- }
1941
- } catch {
1942
- }
1943
- }
1944
- }
1945
- }
1946
- this.emit("progress", msg.params);
1947
- }
1948
- handleIncomingResponse(msg) {
1949
- const fwdInfo = this.forwardedRequests.get(String(msg.id));
1950
- if (fwdInfo) {
1951
- if (fwdInfo.timer) clearTimeout(fwdInfo.timer);
1952
- this.forwardedRequests.delete(String(msg.id));
1953
- try {
1954
- if (fwdInfo.socket.readyState === WS_OPEN) {
1955
- fwdInfo.socket.send(
1956
- JSON.stringify({
1957
- ...msg,
1958
- id: fwdInfo.originalId
1959
- })
1960
- );
1961
- }
1962
- } catch {
1963
- }
1964
- return;
1965
- }
1966
- const pending = this.pending.get(String(msg.id));
1967
- if (!pending) return;
1968
- this.pending.delete(String(msg.id));
1969
- clearTimeout(pending.timer);
1970
- if (msg.error) {
1971
- pending.reject(new Error(`[${msg.error.code}] ${msg.error.message}`));
1972
- } else {
1973
- pending.resolve(msg.result);
1974
- }
1975
- }
1976
- /** 发送 JSON-RPC 2.0 请求,返回 result */
1977
- async call(method, params = {}, timeoutMs, progressToken, autoWaitMs = 0) {
1978
- if (autoWaitMs > 0 && !this.isConnected) {
1979
- await this.waitForReady(autoWaitMs);
1980
- }
1981
- const targetSocket = this._getActiveSocket();
1982
- if (!targetSocket) {
1983
- throw new Error(
1984
- "\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"
1985
- );
1986
- }
1987
- const effectiveTimeoutMs = timeoutMs ?? (method === "sub_agent/run" ? 18e4 : REQUEST_TIMEOUT_MS);
1988
- const id = String(++this.idCounter);
1989
- const requestParams = { ...params };
1990
- if (progressToken != null) {
1991
- requestParams.progressToken = progressToken;
1992
- }
1993
- const request = { jsonrpc: "2.0", id, method, params: requestParams };
1994
- return new Promise((resolve3, reject) => {
1995
- const timer = setTimeout(() => {
1996
- this.pending.delete(id);
1997
- reject(new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${effectiveTimeoutMs / 1e3}s\uFF09\uFF1A${method}`));
1998
- }, effectiveTimeoutMs);
1999
- this.pending.set(id, { resolve: resolve3, reject, timer });
2000
- try {
2001
- targetSocket.send(JSON.stringify(request));
2002
- } catch (err) {
2003
- this.pending.delete(id);
2004
- clearTimeout(timer);
2005
- reject(err instanceof Error ? err : new Error(String(err)));
2006
- }
2007
- });
2008
- }
2009
- /** 销毁服务,断开所有连接 */
2010
- destroy() {
2011
- this.destroyed = true;
2012
- this._rejectAllPending("ExtensionBridgeClient \u5DF2\u9500\u6BC1");
2013
- this.forwardedRequests.clear();
2014
- if (this.clientSocket) {
2015
- try {
2016
- this.clientSocket.close();
2017
- } catch {
2018
- }
2019
- this.clientSocket = null;
2020
- }
2021
- if (this.extensionSocket) {
2022
- try {
2023
- this.extensionSocket.close();
2024
- } catch {
2025
- }
2026
- this.extensionSocket = null;
2027
- }
2028
- if (this.wss) {
2029
- try {
2030
- this.wss.close();
2031
- } catch {
2032
- }
2033
- this.wss = null;
2034
- }
2035
- }
2036
- _rejectAllPending(reason) {
2037
- for (const [, pending] of this.pending) {
2038
- clearTimeout(pending.timer);
2039
- pending.reject(new Error(reason));
2040
- }
2041
- this.pending.clear();
2042
- for (const [, fwdInfo] of this.forwardedRequests) {
2043
- if (fwdInfo.timer) clearTimeout(fwdInfo.timer);
2044
- }
2045
- this.forwardedRequests.clear();
2046
- }
2047
- };
2048
- }
2049
- });
2050
-
2051
- // src/adapters/wxt-adapter.ts
2052
- var wxt_adapter_exports = {};
2053
- __export(wxt_adapter_exports, {
2054
- WxtBrowserAdapter: () => WxtBrowserAdapter
2055
- });
2056
- var AUTO_WAIT_MS, WxtBrowserAdapter;
2057
- var init_wxt_adapter = __esm({
2058
- "src/adapters/wxt-adapter.ts"() {
2059
- "use strict";
2060
- init_bridge_client();
2061
- init_protocol();
2062
- AUTO_WAIT_MS = 6e3;
2063
- WxtBrowserAdapter = class {
2064
- client;
2065
- constructor(token, port) {
2066
- this.client = new ExtensionBridgeClient(port, token);
2067
- this.client.on("error", () => {
2068
- });
2069
- }
2070
- /** 确保 WS 桥接服务已启动并连接 */
2071
- async ensureConnected() {
2072
- await this.client.startAuto();
2073
- }
2074
- async getState(tabId) {
2075
- const numTabId = typeof tabId === "string" ? parseInt(tabId, 10) || void 0 : tabId;
2076
- const result = await this.client.call(
2077
- BRIDGE_METHODS.BROWSER_STATE,
2078
- { tabId: numTabId },
2079
- void 0,
2080
- void 0,
2081
- AUTO_WAIT_MS
2082
- );
2083
- return result;
2084
- }
2085
- async callTool(toolName, args, tabId) {
2086
- const numTabId = typeof tabId === "string" ? parseInt(tabId, 10) || void 0 : tabId;
2087
- return this.client.call(
2088
- BRIDGE_METHODS.TOOL_CALL,
2089
- { toolName, toolArgs: args, tabId: numTabId },
2090
- void 0,
2091
- void 0,
2092
- AUTO_WAIT_MS
2093
- );
2094
- }
2095
- async tabs(action, options) {
2096
- const numTabId = typeof options.tabId === "string" ? parseInt(options.tabId, 10) || void 0 : options.tabId;
2097
- return this.client.call(
2098
- BRIDGE_METHODS.BROWSER_TABS,
2099
- { tabAction: action, ...options, tabId: numTabId },
2100
- void 0,
2101
- void 0,
2102
- AUTO_WAIT_MS
2103
- );
2104
- }
2105
- /** 委托扩展内 Tiny Robot 子代理闭环执行高层任务 */
2106
- async runSubAgent(instruction, options = {}, timeoutMs) {
2107
- const params = { instruction, tabId: options.tabId, maxSteps: options.maxSteps };
2108
- return this.client.call(
2109
- BRIDGE_METHODS.SUB_AGENT_RUN,
2110
- params,
2111
- timeoutMs,
2112
- options.progressToken,
2113
- AUTO_WAIT_MS
2114
- );
2115
- }
2116
- /** 获取已注册的 Skills 列表(L1 索引) */
2117
- async listSkills() {
2118
- return this.client.call(BRIDGE_METHODS.SKILLS_LIST, {}, void 0, void 0, AUTO_WAIT_MS);
2119
- }
2120
- /** 读取指定 Skill 的详细指令(L2 详情) */
2121
- async getSkill(name) {
2122
- return this.client.call(BRIDGE_METHODS.SKILLS_GET, { name }, void 0, void 0, AUTO_WAIT_MS);
2123
- }
2124
- /** 读取 Skill 关联资源(L3 资源) */
2125
- async readSkillResource(name, resourcePath) {
2126
- return this.client.call(
2127
- BRIDGE_METHODS.SKILLS_READ_RESOURCE,
2128
- { name, resourcePath },
2129
- void 0,
2130
- void 0,
2131
- AUTO_WAIT_MS
2132
- );
2133
- }
2134
- /** 获取底层 ExtensionBridgeClient(供 MCP Server 绑定事件) */
2135
- get bridgeClient() {
2136
- return this.client;
2137
- }
2138
- async dispose() {
2139
- this.client.destroy();
2140
- }
2141
- };
2142
- }
2143
- });
2144
-
2145
- // src/bridge/daemon.ts
2146
- var daemon_exports = {};
2147
- __export(daemon_exports, {
2148
- PID_FILE: () => PID_FILE,
2149
- ensureBridgeDaemon: () => ensureBridgeDaemon,
2150
- findPidByPort: () => findPidByPort,
2151
- getDaemonPidFile: () => getDaemonPidFile,
2152
- isBridgeDaemonProcess: () => isBridgeDaemonProcess,
2153
- isDaemonProcessAlive: () => isDaemonProcessAlive,
2154
- isProcessAlive: () => isProcessAlive,
2155
- killProcessOnPort: () => killProcessOnPort,
2156
- killProcessTree: () => killProcessTree2,
2157
- probeServerReady: () => probeServerReady,
2158
- runDaemonProcess: () => runDaemonProcess,
2159
- stopBridgeDaemon: () => stopBridgeDaemon
2160
- });
2161
- import { spawn as spawn4, exec } from "child_process";
2162
- import { promisify } from "util";
2163
- import fs5 from "fs";
2164
- import path5 from "path";
2165
- import os4 from "os";
2166
- import { fileURLToPath as fileURLToPath3 } from "url";
2167
- function getDaemonPidFile(port = WS_PORT2) {
2168
- if (port === WS_PORT2) {
2169
- return path5.join(DAEMON_DIR, "daemon.pid");
2170
- }
2171
- return path5.join(DAEMON_DIR, `daemon-${port}.pid`);
2172
- }
2173
- function isProcessAlive(pid) {
2174
- if (!pid || pid <= 0) return false;
2175
- try {
2176
- process.kill(pid, 0);
2177
- return true;
2178
- } catch {
2179
- return false;
2180
- }
2181
- }
2182
- async function findPidByPort(port, excludePid) {
2183
- if (process.platform === "win32") {
2184
- try {
2185
- const { stdout } = await execAsync("netstat -ano -p tcp");
2186
- const lines = stdout.split(/\r?\n/);
2187
- for (const rawLine of lines) {
2188
- const line = rawLine.trim();
2189
- if (!line.toUpperCase().startsWith("TCP")) continue;
2190
- const parts = line.split(/\s+/);
2191
- if (parts.length < 5) continue;
2192
- const localAddr = parts[1];
2193
- const state = parts[3]?.toUpperCase() || "";
2194
- const pid = parseInt(parts[parts.length - 1], 10);
2195
- if (!pid || isNaN(pid) || excludePid && pid === excludePid) continue;
2196
- if (localAddr.endsWith(`:${port}`)) {
2197
- if (state.includes("LISTEN") || state.includes("\u4FA6\u542C")) {
2198
- return pid;
2199
- }
2200
- }
2201
- }
2202
- return null;
2203
- } catch {
2204
- return null;
2205
- }
2206
- }
2207
- try {
2208
- const { stdout } = await execAsync(`lsof -nP -iTCP:${port} -sTCP:LISTEN -t`);
2209
- const pids = stdout.trim().split("\n").map((p) => parseInt(p.trim(), 10)).filter((p) => Boolean(p && !isNaN(p) && (!excludePid || p !== excludePid)));
2210
- return pids[0] ?? null;
2211
- } catch {
2212
- return null;
2213
- }
2214
- }
2215
- async function killProcessTree2(pid) {
2216
- if (!pid || pid <= 0 || pid === process.pid) return false;
2217
- if (process.platform === "win32") {
2218
- try {
2219
- await execAsync(`taskkill /pid ${pid} /T /F`);
2220
- } catch {
2221
- try {
2222
- process.kill(pid, "SIGKILL");
2223
- } catch {
2224
- }
2225
- }
2226
- for (let i = 0; i < 15; i++) {
2227
- await new Promise((r) => setTimeout(r, 100));
2228
- if (!isProcessAlive(pid)) return true;
2229
- }
2230
- return !isProcessAlive(pid);
2231
- }
2232
- try {
2233
- process.kill(pid, "SIGTERM");
2234
- } catch {
2235
- }
2236
- for (let i = 0; i < 10; i++) {
2237
- await new Promise((r) => setTimeout(r, 100));
2238
- if (!isProcessAlive(pid)) return true;
2239
- }
2240
- try {
2241
- process.kill(pid, "SIGKILL");
2242
- } catch {
2243
- }
2244
- for (let i = 0; i < 5; i++) {
2245
- await new Promise((r) => setTimeout(r, 100));
2246
- if (!isProcessAlive(pid)) return true;
2247
- }
2248
- return !isProcessAlive(pid);
2249
- }
2250
- async function killProcessOnPort(port) {
2251
- const pid = await findPidByPort(port, process.pid);
2252
- if (pid) {
2253
- await killProcessTree2(pid);
2254
- for (let i = 0; i < 20; i++) {
2255
- await new Promise((r) => setTimeout(r, 100));
2256
- const remainingPid = await findPidByPort(port, process.pid);
2257
- if (!remainingPid) return true;
2258
- }
2259
- }
2260
- return false;
2261
- }
2262
- async function probeServerReady(port = WS_PORT2, token, timeoutMs = 1e3) {
2263
- return ExtensionBridgeClient.probe(port, token ?? resolveOrCreateAuthToken(), timeoutMs);
2264
- }
2265
- function isDaemonProcessAlive(port = WS_PORT2) {
2266
- const pidFile = getDaemonPidFile(port);
2267
- if (!fs5.existsSync(pidFile)) return false;
2268
- try {
2269
- const pid = parseInt(fs5.readFileSync(pidFile, "utf8").trim(), 10);
2270
- return Boolean(pid && isProcessAlive(pid));
2271
- } catch {
2272
- return false;
2273
- }
2274
- }
2275
- async function ensureBridgeDaemon(options = {}) {
2276
- const port = options.port ?? WS_PORT2;
2277
- const token = options.token ?? resolveOrCreateAuthToken();
2278
- const timeoutMs = options.timeoutMs ?? 6e3;
2279
- const probe = await probeServerReady(port, token, 800);
2280
- if (probe.running && probe.authed) {
2281
- return { newlyStarted: false };
2282
- }
2283
- if (probe.running && !probe.authed) {
2284
- if (!options.silent) {
2285
- console.log(
2286
- `\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...`
2287
- );
2288
- }
2289
- const stopped = await stopBridgeDaemon(port, { onlyVerified: true });
2290
- if (!stopped) {
2291
- const killTip = getKillPortHint(port);
2292
- throw new Error(
2293
- `\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
2294
- \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`
2295
- );
2296
- }
2297
- await new Promise((r) => setTimeout(r, 400));
2298
- }
2299
- if (!options.silent) {
2300
- 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})...`);
2301
- }
2302
- startDaemonProcessBackground(token, port);
2303
- const startTime = Date.now();
2304
- while (Date.now() - startTime < timeoutMs) {
2305
- await new Promise((r) => setTimeout(r, 200));
2306
- const check = await probeServerReady(port, token, 400);
2307
- if (check.running && check.authed) {
2308
- if (!options.silent) {
2309
- 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...`);
2310
- }
2311
- return { newlyStarted: true };
2312
- }
2313
- }
2314
- 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`);
2315
- }
2316
- function resolveCliEntry() {
2317
- const currentDir = path5.dirname(fileURLToPath3(import.meta.url));
2318
- const distCandidate = path5.join(currentDir, "bin.js");
2319
- if (fs5.existsSync(distCandidate)) return distCandidate;
2320
- const projectDistCandidate = path5.resolve(currentDir, "../dist/bin.js");
2321
- if (fs5.existsSync(projectDistCandidate)) return projectDistCandidate;
2322
- return distCandidate;
2323
- }
2324
- function startDaemonProcessBackground(token, port) {
2325
- const cliEntry = resolveCliEntry();
2326
- if (!fs5.existsSync(DAEMON_DIR)) {
2327
- fs5.mkdirSync(DAEMON_DIR, { mode: 448, recursive: true });
2328
- }
2329
- const child = spawn4(process.execPath, [cliEntry, "--mode", "wxt", "daemon", "--port", String(port)], {
2330
- detached: true,
2331
- stdio: "ignore",
2332
- windowsHide: true,
2333
- env: {
2334
- ...process.env,
2335
- ROBOT_WXT_BRIDGE_TOKEN: token
2336
- }
2337
- });
2338
- child.unref();
2339
- }
2340
- async function runDaemonProcess(args) {
2341
- let port = WS_PORT2;
2342
- let token;
2343
- const portIdx = args.indexOf("--port");
2344
- if (portIdx !== -1 && args[portIdx + 1]) {
2345
- port = parseInt(args[portIdx + 1], 10);
2346
- }
2347
- const tokenIdx = args.indexOf("--token");
2348
- if (tokenIdx !== -1 && args[tokenIdx + 1]) {
2349
- token = args[tokenIdx + 1];
2350
- } else if (process.env.ROBOT_WXT_BRIDGE_TOKEN) {
2351
- token = process.env.ROBOT_WXT_BRIDGE_TOKEN;
2352
- }
2353
- const client = new ExtensionBridgeClient(port, token);
2354
- client.on("error", (err) => {
2355
- if (err && (err.code === "EADDRINUSE" || err.message?.includes("EADDRINUSE"))) {
2356
- process.exit(1);
2357
- }
2358
- });
2359
- const pidFile = getDaemonPidFile(port);
2360
- client.on("listening", () => {
2361
- try {
2362
- if (!fs5.existsSync(DAEMON_DIR)) {
2363
- fs5.mkdirSync(DAEMON_DIR, { mode: 448, recursive: true });
2364
- }
2365
- fs5.writeFileSync(pidFile, String(process.pid), { mode: 384, encoding: "utf8" });
2366
- } catch {
2367
- }
2368
- });
2369
- client.connect();
2370
- const shutdown = () => {
2371
- try {
2372
- if (fs5.existsSync(pidFile)) {
2373
- const recordedPid = fs5.readFileSync(pidFile, "utf8").trim();
2374
- if (recordedPid === String(process.pid)) {
2375
- fs5.unlinkSync(pidFile);
2376
- }
2377
- }
2378
- } catch {
2379
- }
2380
- client.destroy();
2381
- process.exit(0);
2382
- };
2383
- process.on("SIGINT", shutdown);
2384
- process.on("SIGTERM", shutdown);
2385
- process.on("exit", shutdown);
2386
- setInterval(() => {
2387
- }, 6e4);
2388
- }
2389
- async function isBridgeDaemonProcess(pid) {
2390
- if (!pid || pid <= 0 || !isProcessAlive(pid)) return false;
2391
- try {
2392
- let cmd = "";
2393
- if (process.platform === "win32") {
2394
- const { stdout } = await execAsync(
2395
- `powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter \\"ProcessId = ${pid}\\").CommandLine"`
2396
- );
2397
- cmd = stdout.trim();
2398
- } else {
2399
- const { stdout } = await execAsync(`ps -p ${pid} -o command=`);
2400
- cmd = stdout.trim();
2401
- }
2402
- if (!cmd) return false;
2403
- return (cmd.includes("webmcp-cli") || cmd.includes("bin.js") || cmd.includes("daemon.js")) && cmd.includes("daemon");
2404
- } catch {
2405
- return false;
2406
- }
2407
- }
2408
- async function stopBridgeDaemon(port = WS_PORT2, options = {}) {
2409
- const onlyVerified = options.onlyVerified ?? false;
2410
- let killedAny = false;
2411
- const pidFile = getDaemonPidFile(port);
2412
- let daemonPid = null;
2413
- if (fs5.existsSync(pidFile)) {
2414
- try {
2415
- const pidStr = fs5.readFileSync(pidFile, "utf8").trim();
2416
- const p = parseInt(pidStr, 10);
2417
- if (p && isProcessAlive(p)) {
2418
- daemonPid = p;
2419
- }
2420
- } catch {
2421
- }
2422
- }
2423
- if (onlyVerified) {
2424
- if (!daemonPid) {
2425
- return false;
2426
- }
2427
- const isVerified = await isBridgeDaemonProcess(daemonPid);
2428
- if (!isVerified) {
2429
- return false;
2430
- }
2431
- const portPid = await findPidByPort(port, process.pid);
2432
- if (portPid && portPid !== daemonPid) {
2433
- return false;
2434
- }
2435
- const killed = await killProcessTree2(daemonPid);
2436
- if (killed) {
2437
- killedAny = true;
2438
- try {
2439
- if (fs5.existsSync(pidFile)) fs5.unlinkSync(pidFile);
2440
- } catch {
2441
- }
2442
- }
2443
- } else {
2444
- if (daemonPid) {
2445
- try {
2446
- const killed = await killProcessTree2(daemonPid);
2447
- if (killed) {
2448
- killedAny = true;
2449
- try {
2450
- if (fs5.existsSync(pidFile)) fs5.unlinkSync(pidFile);
2451
- } catch {
2452
- }
2453
- }
2454
- } catch {
2455
- }
2456
- }
2457
- const portPid = await findPidByPort(port, process.pid);
2458
- if (portPid) {
2459
- const killedByPort = await killProcessOnPort(port);
2460
- if (killedByPort) {
2461
- killedAny = true;
2462
- }
2463
- }
2464
- }
2465
- let portReleased = false;
2466
- for (let i = 0; i < 10; i++) {
2467
- const remainingPid = await findPidByPort(port, process.pid);
2468
- if (!remainingPid) {
2469
- portReleased = true;
2470
- break;
2471
- }
2472
- await new Promise((r) => setTimeout(r, 200));
2473
- }
2474
- if (!portReleased) {
2475
- return false;
2476
- }
2477
- return killedAny;
2478
- }
2479
- var execAsync, WS_PORT2, DAEMON_DIR, PID_FILE;
2480
- var init_daemon = __esm({
2481
- "src/bridge/daemon.ts"() {
2482
- "use strict";
2483
- init_bridge_client();
2484
- execAsync = promisify(exec);
2485
- WS_PORT2 = 18999;
2486
- DAEMON_DIR = path5.join(os4.homedir(), ".robot-wxt");
2487
- PID_FILE = getDaemonPidFile(WS_PORT2);
2488
- }
2489
- });
2490
-
2491
- // src/mcp/server.ts
2492
- var server_exports = {};
2493
- __export(server_exports, {
2494
- startMcpServer: () => startMcpServer
2495
- });
2496
- import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
2497
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
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 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 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 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 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 SERVER_NAME, SERVER_VERSION;
2742
- var init_server = __esm({
2743
- "src/mcp/server.ts"() {
2744
- "use strict";
2745
- init_package();
2746
- init_tools();
2747
- SERVER_NAME = "webmcp-cli";
2748
- SERVER_VERSION = package_default.version || "0.0.9";
2749
- }
2750
- });
2751
-
2752
- // src/commands/agent.ts
2753
- var agent_exports = {};
2754
- __export(agent_exports, {
2755
- handleAgentCommand: () => handleAgentCommand
2756
- });
2757
- async function handleAgentCommand(adapter, args) {
2758
- const subCommand = args[0];
2759
- const restArgs = args.slice(1);
2760
- if (!subCommand || subCommand === "--help" || subCommand === "-h") {
2761
- printAgentHelp();
2762
- return;
2763
- }
2764
- if (subCommand === "run") {
2765
- await handleAgentRun(adapter, restArgs);
2766
- return;
2767
- }
2768
- console.error(`[\u9519\u8BEF] \u672A\u77E5\u5B50\u547D\u4EE4: agent ${subCommand}`);
2769
- console.error("\u8FD0\u884C webmcp-cli --mode wxt agent --help \u67E5\u770B\u652F\u6301\u7684\u547D\u4EE4");
2770
- process.exit(1);
2771
- }
2772
- async function handleAgentRun(adapter, args) {
2773
- let instruction = "";
2774
- let maxSteps;
2775
- let tabId;
2776
- const isJson = args.includes("--json");
2777
- for (let i = 0; i < args.length; i++) {
2778
- const arg = args[i];
2779
- if (arg === "--max-steps" && args[i + 1]) {
2780
- maxSteps = parseInt(args[++i], 10);
2781
- } else if (arg === "--tab" && args[i + 1]) {
2782
- tabId = parseInt(args[++i], 10);
2783
- } else if (!arg.startsWith("-")) {
2784
- instruction = arg;
2785
- }
2786
- }
2787
- if (!instruction) {
2788
- 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"');
2789
- process.exit(1);
2790
- }
2791
- if (!isJson) {
2792
- console.log(`\u{1F916} \u6B63\u5728\u59D4\u6258 Tiny Robot \u5B50\u4EE3\u7406\u6267\u884C\u4EFB\u52A1\uFF1A\u300C${instruction}\u300D`);
2793
- if (maxSteps) console.log(` \u6700\u5927\u6B65\u6570\uFF1A${maxSteps}`);
2794
- }
2795
- try {
2796
- const result = await adapter.runSubAgent(instruction, { tabId, maxSteps });
2797
- if (isJson) {
2798
- console.log(JSON.stringify(result, null, 2));
2799
- } else {
2800
- console.log("\n\u2705 \u5B50\u4EE3\u7406\u6267\u884C\u5B8C\u6210\uFF1A");
2801
- console.log(JSON.stringify(result, null, 2));
2802
- }
2803
- } catch (err) {
2804
- const msg = err instanceof Error ? err.message : String(err);
2805
- if (isJson) {
2806
- console.log(JSON.stringify({ success: false, error: msg }));
2807
- } else {
2808
- console.error(`\u274C \u6267\u884C\u5931\u8D25\uFF1A${msg}`);
2809
- }
2810
- process.exit(1);
2811
- }
2812
- }
2813
- function printAgentHelp() {
2814
- console.log(`
2815
- webmcp-cli --mode wxt agent - \u59D4\u6258 Chrome \u6269\u5C55\u5185 Tiny Robot \u5B50\u4EE3\u7406\u6267\u884C\u9AD8\u5C42\u4EFB\u52A1
2816
-
2817
- \u7528\u6CD5\uFF1A
2818
- webmcp-cli --mode wxt agent run "<\u6307\u4EE4>" \u59D4\u6258\u5B50\u4EE3\u7406\u81EA\u4E3B\u6267\u884C\u81EA\u7136\u8BED\u8A00\u4EFB\u52A1
2819
-
2820
- \u9009\u9879\uFF1A
2821
- --max-steps <n> \u6700\u5927\u6267\u884C\u6B65\u6570\uFF08\u9ED8\u8BA4 8\uFF0C\u6700\u5927 20\uFF09
2822
- --tab <tabId> \u6307\u5B9A\u76EE\u6807\u6807\u7B7E\u9875 ID
2823
- --json \u8F93\u51FA JSON \u683C\u5F0F\u7ED3\u679C
2824
-
2825
- \u793A\u4F8B\uFF1A
2826
- webmcp-cli --mode wxt agent run "\u5E2E\u6211\u628A\u5F53\u524D\u5546\u54C1\u52A0\u5165\u8D2D\u7269\u8F66"
2827
- webmcp-cli --mode wxt agent run "\u641C\u7D22\u5E76\u6536\u85CF\u524D3\u7BC7\u6587\u7AE0" --max-steps 10
2828
- `.trim());
2829
- }
2830
- var init_agent = __esm({
2831
- "src/commands/agent.ts"() {
2832
- "use strict";
2833
- }
2834
- });
2835
-
2836
- // src/commands/skills.ts
2837
- var skills_exports = {};
2838
- __export(skills_exports, {
2839
- handleSkillsCommand: () => handleSkillsCommand
2840
- });
2841
- async function handleSkillsCommand(adapter, args) {
2842
- const subCommand = args[0];
2843
- const restArgs = args.slice(1);
2844
- const isJson = args.includes("--json");
2845
- if (!subCommand || subCommand === "--help" || subCommand === "-h") {
2846
- printSkillsHelp();
2847
- return;
2848
- }
2849
- if (subCommand === "list") {
2850
- await handleSkillsList(adapter, isJson);
2851
- return;
2852
- }
2853
- if (subCommand === "get") {
2854
- const skillName = restArgs.find((a) => !a.startsWith("-"));
2855
- if (!skillName) {
2856
- console.error("[\u9519\u8BEF] \u8BF7\u63D0\u4F9B\u6280\u80FD\u540D\u79F0\u3002\u793A\u4F8B\uFF1Awebmcp-cli --mode wxt skills get <skillName>");
2857
- process.exit(1);
2858
- }
2859
- await handleSkillsGet(adapter, skillName, isJson);
2860
- return;
2861
- }
2862
- console.error(`[\u9519\u8BEF] \u672A\u77E5\u5B50\u547D\u4EE4: skills ${subCommand}`);
2863
- printSkillsHelp();
2864
- process.exit(1);
2865
- }
2866
- async function handleSkillsList(adapter, isJson) {
2867
- try {
2868
- const result = await adapter.listSkills();
2869
- if (isJson) {
2870
- console.log(JSON.stringify(result, null, 2));
2871
- } else {
2872
- const skills = result;
2873
- if (!skills || skills.length === 0) {
2874
- console.log("\uFF08\u5F53\u524D\u6269\u5C55\u672A\u6CE8\u518C\u4EFB\u4F55\u6280\u80FD\uFF09");
2875
- return;
2876
- }
2877
- console.log(`
2878
- \u{1F4DA} \u5DF2\u6CE8\u518C Skills\uFF08\u5171 ${skills.length} \u4E2A\uFF09\uFF1A
2879
- `);
2880
- for (const skill of skills) {
2881
- console.log(` \u2022 ${skill.name}`);
2882
- if (skill.description) {
2883
- console.log(` ${skill.description.slice(0, 100)}${skill.description.length > 100 ? "..." : ""}`);
2884
- }
2885
- }
2886
- console.log(`
2887
- \u63D0\u793A\uFF1A\u4F7F\u7528 "webmcp-cli --mode wxt skills get <name>" \u67E5\u770B\u6280\u80FD\u8BE6\u60C5`);
2888
- }
2889
- } catch (err) {
2890
- const msg = err instanceof Error ? err.message : String(err);
2891
- if (isJson) {
2892
- console.log(JSON.stringify({ error: msg }));
2893
- } else {
2894
- console.error(`\u274C \u83B7\u53D6\u6280\u80FD\u5217\u8868\u5931\u8D25\uFF1A${msg}`);
2895
- }
2896
- process.exit(1);
2897
- }
2898
- }
2899
- async function handleSkillsGet(adapter, name, isJson) {
2900
- try {
2901
- const result = await adapter.getSkill(name);
2902
- if (isJson) {
2903
- console.log(JSON.stringify(result, null, 2));
2904
- } else {
2905
- const skill = result;
2906
- console.log(`
2907
- \u{1F4D6} \u6280\u80FD\uFF1A${skill.name}`);
2908
- if (skill.description) console.log(`\u63CF\u8FF0\uFF1A${skill.description}`);
2909
- if (skill.instructions) {
2910
- console.log("\n--- \u6307\u4EE4 ---");
2911
- console.log(skill.instructions);
2912
- }
2913
- }
2914
- } catch (err) {
2915
- const msg = err instanceof Error ? err.message : String(err);
2916
- if (isJson) {
2917
- console.log(JSON.stringify({ error: msg }));
2918
- } else {
2919
- console.error(`\u274C \u83B7\u53D6\u6280\u80FD\u8BE6\u60C5\u5931\u8D25\uFF1A${msg}`);
2920
- }
2921
- process.exit(1);
2922
- }
2923
- }
2924
- function printSkillsHelp() {
2925
- console.log(`
2926
- webmcp-cli --mode wxt skills - \u67E5\u8BE2\u4E0E\u8BFB\u53D6\u6D4F\u89C8\u5668\u6269\u5C55\u4E2D\u6CE8\u518C\u7684 Skills \u6280\u80FD
2927
-
2928
- \u7528\u6CD5\uFF1A
2929
- webmcp-cli --mode wxt skills list \u5217\u51FA\u6240\u6709\u5DF2\u6CE8\u518C\u7684\u6280\u80FD
2930
- webmcp-cli --mode wxt skills get <name> \u8BFB\u53D6\u6307\u5B9A\u6280\u80FD\u7684\u8BE6\u7EC6\u6267\u884C\u6307\u4EE4
2931
-
2932
- \u9009\u9879\uFF1A
2933
- --json \u8F93\u51FA JSON \u683C\u5F0F\u7ED3\u679C
2934
-
2935
- \u793A\u4F8B\uFF1A
2936
- webmcp-cli --mode wxt skills list
2937
- webmcp-cli --mode wxt skills get order-management
2938
- `.trim());
2939
- }
2940
- var init_skills = __esm({
2941
- "src/commands/skills.ts"() {
2942
- "use strict";
2943
- }
2944
- });
2945
-
2946
- // src/bin.ts
2947
- import fs6 from "fs";
2948
- import path6 from "path";
2949
- import os5 from "os";
2950
- import { Command } from "commander";
2951
- import pc2 from "picocolors";
2952
- import { readFileSync as readFileSync2 } from "fs";
2953
- import { resolve as resolve2 } from "path";
2954
-
2955
- // src/expand-file-refs.ts
2956
- import { readFileSync } from "fs";
2957
- import { dirname, isAbsolute, normalize, resolve } from "path";
2958
- import { fileURLToPath } from "url";
2959
- var JSON_STRING_LITERAL = /"(?:[^"\\]|\\.)*"/g;
2960
- var UNQUOTED_FILE_REF = /(?<![\\"])@(base64)?file:([^\s"',}\]]+)/g;
2961
- var FILE_REF_PREFIX = /^@(base64)?file:(.+)$/s;
2962
- function resolveFilePath(filePath, baseDir = process.cwd()) {
2963
- let normalizedPath = filePath.trim();
2964
- if (normalizedPath.startsWith('"') && normalizedPath.endsWith('"') || normalizedPath.startsWith("'") && normalizedPath.endsWith("'")) {
2965
- normalizedPath = normalizedPath.slice(1, -1).trim();
2966
- }
2967
- if (normalizedPath.startsWith("file://")) {
2968
- normalizedPath = fileURLToPath(normalizedPath);
2969
- }
2970
- if (isAbsolute(normalizedPath)) {
2971
- return normalize(normalizedPath);
2972
- }
2973
- return resolve(baseDir, normalizedPath);
2974
- }
2975
- function decodeFilePath(rawPath) {
2976
- return rawPath.replace(/\\\\/g, "\\");
2977
- }
2978
- function readFileRefContent(filePath, baseDir, base64) {
2979
- const absPath = resolveFilePath(filePath, baseDir);
2980
- let content;
2981
- try {
2982
- content = readFileSync(absPath, "utf-8");
2983
- } catch (e) {
2984
- throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6\u5F15\u7528 "${filePath}" (${absPath}): ${e.message}`);
2985
- }
2986
- return base64 ? Buffer.from(content, "utf-8").toString("base64") : content;
2987
- }
2988
- function expandFileRefValue(rawInner, baseDir) {
2989
- const match = rawInner.match(FILE_REF_PREFIX);
2990
- if (!match) {
2991
- return null;
2992
- }
2993
- const [, base64Flag, rawPath] = match;
2994
- const filePath = decodeFilePath(rawPath);
2995
- const value = readFileRefContent(filePath, baseDir, Boolean(base64Flag));
2996
- return JSON.stringify(value);
2997
- }
2998
- function expandQuotedFileRefs(argsJson, baseDir) {
2999
- return argsJson.replace(JSON_STRING_LITERAL, (jsonStringLiteral) => {
3000
- const rawInner = jsonStringLiteral.slice(1, -1);
3001
- const replacement = expandFileRefValue(rawInner, baseDir);
3002
- return replacement ?? jsonStringLiteral;
3003
- });
3004
- }
3005
- function expandUnquotedFileRefs(argsJson, baseDir) {
3006
- return argsJson.replace(UNQUOTED_FILE_REF, (match, base64Flag, filePath) => {
3007
- const value = readFileRefContent(filePath, baseDir, Boolean(base64Flag));
3008
- return JSON.stringify(value);
3009
- });
3010
- }
3011
- function expandFileRefs(argsJson, baseDir = process.cwd()) {
3012
- const withQuotedExpanded = expandQuotedFileRefs(argsJson, baseDir);
3013
- return expandUnquotedFileRefs(withQuotedExpanded, baseDir);
3014
- }
3015
- function getFileBaseDir(fileOption) {
3016
- if (!fileOption) {
3017
- return process.cwd();
3018
- }
3019
- return dirname(resolve(process.cwd(), fileOption));
3020
- }
3021
-
3022
- // src/parse-run-args.ts
3023
- import JSON5 from "json5";
3024
- function cleanJsonString(str) {
3025
- let cleaned = str.trim();
3026
- if (cleaned.startsWith("'") && cleaned.endsWith("'")) {
3027
- cleaned = cleaned.slice(1, -1).trim();
3028
- }
3029
- return cleaned;
3030
- }
3031
- function looksLikeObjectBody(raw) {
3032
- return /^("?[\w-]+"?\s*:)/.test(raw);
521
+ await session.detach().catch(() => {
522
+ });
523
+ }
3033
524
  }
3034
- function joinShellArgs(args) {
3035
- const cleaned = args.map(cleanJsonString);
3036
- const first = cleaned[0] ?? "";
3037
- if (first.startsWith("{")) {
3038
- return cleaned.join(" ");
525
+ async function getTargetPage(browser, tabid) {
526
+ const pageTargets = getPageTargets(browser);
527
+ if (pageTargets.length === 0) {
528
+ const newPage = await browser.newPage();
529
+ await injectWebMCPPolyfillAndTools(newPage);
530
+ return newPage;
3039
531
  }
3040
- if (looksLikeObjectBody(first)) {
3041
- let joined = cleaned.join(" ");
3042
- if (!joined.startsWith("{")) {
3043
- joined = `{${joined}}`;
532
+ let targetPage = null;
533
+ if (tabid !== void 0) {
534
+ const target = findPageTargetByTabId(browser, tabid);
535
+ if (!target) {
536
+ throw new Error(`Tab with targetId "${tabid}" not found.`);
3044
537
  }
3045
- if (!joined.endsWith("}")) {
3046
- joined = `${joined}}`;
538
+ targetPage = await target.page();
539
+ } else {
540
+ const lastTabId = getLastActiveTabId();
541
+ if (lastTabId) {
542
+ const lastTarget = findPageTargetByTabId(browser, lastTabId);
543
+ if (lastTarget) {
544
+ targetPage = await lastTarget.page();
545
+ }
3047
546
  }
3048
- return joined;
3049
- }
3050
- return cleaned.join(" ");
3051
- }
3052
- function insertMissingCommas(raw) {
3053
- return raw.replace(/"(\s+)("?[\w-]+"?\s*:)/g, '",$2');
3054
- }
3055
- function quoteUnquotedStringValues(raw) {
3056
- return raw.replace(
3057
- /([{,]\s*(?:"([^"]+)"|([\w-]+))\s*:\s*)(?!"@(?:base64)?file:|"|true|false|null|-?\d|\{|\[)([^",}\]]+?)(?=\s*[,}])/g,
3058
- (_match, prefix, _quotedKey, _unquotedKey, value) => {
3059
- const trimmed = value.trim();
3060
- if (/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(trimmed)) {
3061
- return prefix + trimmed;
547
+ if (!targetPage) {
548
+ try {
549
+ const workspaceDir = getWorkspaceDir();
550
+ const cdpPort = getCdpPort();
551
+ const recordedPort = readActivePortFromProfile(workspaceDir);
552
+ const ports = recordedPort && recordedPort !== cdpPort ? [recordedPort, cdpPort] : [cdpPort];
553
+ const urls = ports.flatMap((port) => candidateCdpBaseUrls(port).map((u) => `${u}/json/list`));
554
+ let activeTargetId = null;
555
+ for (const url of urls) {
556
+ try {
557
+ const body = await httpGet(url, 1e3);
558
+ const targetsData = JSON.parse(body);
559
+ const active = targetsData.find((t) => t.type === "page" && !t.url.startsWith("devtools://"));
560
+ if (active) {
561
+ activeTargetId = active.id;
562
+ break;
563
+ }
564
+ } catch {
565
+ }
566
+ }
567
+ if (activeTargetId) {
568
+ for (const target of pageTargets) {
569
+ if (getTargetIdFromTarget(target) === activeTargetId) {
570
+ targetPage = await target.page();
571
+ break;
572
+ }
573
+ }
574
+ }
575
+ } catch {
3062
576
  }
3063
- return prefix + JSON.stringify(trimmed);
3064
577
  }
3065
- );
578
+ if (!targetPage) {
579
+ const lastTarget = pageTargets[pageTargets.length - 1];
580
+ targetPage = await lastTarget.page();
581
+ }
582
+ }
583
+ if (!targetPage) {
584
+ throw new Error("\u65E0\u6CD5\u83B7\u53D6\u76EE\u6807\u9875\u9762");
585
+ }
586
+ await injectWebMCPPolyfillAndTools(targetPage);
587
+ return targetPage;
3066
588
  }
3067
- function normalizeShellDamagedJson(raw) {
3068
- let normalized = raw.trim();
3069
- normalized = insertMissingCommas(normalized);
3070
- normalized = quoteUnquotedStringValues(normalized);
3071
- return normalized;
589
+ async function injectIntoPage(page) {
590
+ await injectWebMCPPolyfillAndTools(page);
3072
591
  }
3073
- function buildArgsFromKeyValuePairs(args) {
3074
- const obj = {};
3075
- for (const pair of args) {
3076
- const index = pair.indexOf("=");
3077
- if (index === -1) {
3078
- throw new Error(`\u65E0\u6548\u7684\u53C2\u6570\u683C\u5F0F "${pair}"\u3002\u8BF7\u4F7F\u7528 key=value\uFF0C\u6216 JSON / -f \u6587\u4EF6\u3002`);
592
+ async function injectWebMCPPolyfillAndTools(page) {
593
+ const polyfillReady = await page.evaluate(() => {
594
+ return !!window.__webmcpcli_init;
595
+ }).catch(() => false);
596
+ if (!polyfillReady) {
597
+ console.log(pc.cyan("\u5F53\u524D\u9875\u9762\u5C1A\u672A\u6CE8\u5165 WebMCP \u73AF\u5883\uFF0C\u6B63\u5728\u6267\u884C\u81EA\u52A8\u6CE8\u5165..."));
598
+ const injectScriptPath = path.resolve(__dirname, "inject-bundle.js");
599
+ if (!fs.existsSync(injectScriptPath)) {
600
+ throw new Error(`Cannot find inject-bundle.js at ${injectScriptPath}. Please ensure you run 'pnpm build:inject' first.`);
3079
601
  }
3080
- const key = pair.substring(0, index).trim();
3081
- let val = cleanJsonString(pair.substring(index + 1).trim());
602
+ const scriptContent = fs.readFileSync(injectScriptPath, "utf-8");
3082
603
  try {
3083
- obj[key] = JSON.parse(val);
3084
- } catch {
3085
- obj[key] = val;
604
+ await page.evaluate(scriptContent);
605
+ } catch (err) {
606
+ const msg = err instanceof Error ? err.message : String(err);
607
+ throw new Error("\u81EA\u52A8\u6CE8\u5165\u811A\u672C\u6267\u884C\u5931\u8D25: " + msg);
3086
608
  }
609
+ await page.waitForFunction(() => {
610
+ const mcp = navigator.modelContext;
611
+ return mcp && typeof mcp.registerTool === "function";
612
+ }, { timeout: 1e4 }).catch(() => {
613
+ console.warn("\u7B49\u5F85 WebMCP registerTool \u63A5\u53E3\u5C31\u7EEA\u8D85\u65F6\uFF0C\u6B63\u5728\u7EE7\u7EED\u6CE8\u5165...");
614
+ });
3087
615
  }
3088
- return JSON.stringify(obj);
616
+ await injectDomainTools(page);
3089
617
  }
3090
- function parseArgsJson(raw) {
3091
- const trimmed = cleanJsonString(raw);
618
+ function getToolsBundleName(hostname) {
619
+ const normalized = hostname.split(":")[0].toLowerCase();
620
+ const toolsDir = path.resolve(__dirname, "webmcp-tools");
621
+ if (!fs.existsSync(toolsDir)) {
622
+ return null;
623
+ }
624
+ let files = [];
3092
625
  try {
3093
- return JSON.stringify(JSON5.parse(trimmed));
3094
- } catch (firstError) {
3095
- const repaired = normalizeShellDamagedJson(trimmed);
3096
- try {
3097
- return JSON.stringify(JSON5.parse(repaired));
3098
- } catch {
3099
- 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`;
3100
- const message = firstError instanceof Error ? firstError.message : String(firstError);
3101
- throw new Error(`\u53C2\u6570\u4E0D\u662F\u6709\u6548\u7684 JSON \u6216 JS \u5BF9\u8C61: ${message}
3102
- ${hint}`);
626
+ files = fs.readdirSync(toolsDir);
627
+ } catch {
628
+ return null;
629
+ }
630
+ const supportedDomains = files.filter((f) => f.endsWith(".js")).map((f) => f.slice(0, -3));
631
+ if (supportedDomains.includes(normalized)) {
632
+ return `webmcp-tools/${normalized}.js`;
633
+ }
634
+ for (const domain of supportedDomains) {
635
+ if (normalized.endsWith("." + domain)) {
636
+ return `webmcp-tools/${domain}.js`;
3103
637
  }
3104
638
  }
639
+ return null;
3105
640
  }
3106
- function prepareRunArgsJson(args, fileContent, baseDir) {
3107
- if (fileContent !== void 0) {
3108
- const trimmed = fileContent.trim();
3109
- if (!trimmed) {
3110
- throw new Error("\u901A\u8FC7 -f/--file \u6307\u5B9A\u7684\u53C2\u6570\u6587\u4EF6\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A");
3111
- }
3112
- const expanded2 = expandFileRefs(trimmed, baseDir);
3113
- return parseArgsJson(expanded2);
641
+ async function injectDomainTools(page) {
642
+ let hostname;
643
+ try {
644
+ const url = new URL(page.url());
645
+ hostname = url.hostname;
646
+ } catch {
647
+ return;
3114
648
  }
3115
- if (args.length === 0) {
3116
- return "{}";
649
+ const bundleName = getToolsBundleName(hostname);
650
+ if (!bundleName) {
651
+ return;
3117
652
  }
3118
- const joined = joinShellArgs(args);
3119
- let raw = "";
3120
- if (joined.startsWith("{") || looksLikeObjectBody(joined)) {
3121
- raw = joined;
3122
- } else if (args.every((arg) => arg.includes("="))) {
3123
- raw = buildArgsFromKeyValuePairs(args);
3124
- } else {
3125
- raw = joined;
653
+ const toolBundlePath = path.resolve(__dirname, bundleName);
654
+ if (!fs.existsSync(toolBundlePath)) {
655
+ return;
3126
656
  }
3127
- if (!raw.trim()) {
3128
- throw new Error("\u672A\u63D0\u4F9B\u6709\u6548\u53C2\u6570");
657
+ const bundleKey = bundleName.replace(/^webmcp-tools\//, "").replace(/\.js$/, "");
658
+ const flagKey = `__webmcptools_${bundleKey.replace(/[^a-zA-Z0-9]/g, "")}`;
659
+ const alreadyInjected = await page.evaluate((key) => !!window[key], flagKey).catch(() => false);
660
+ if (alreadyInjected) {
661
+ return;
662
+ }
663
+ console.log(pc.cyan(`\u68C0\u6D4B\u5230\u57DF\u540D ${hostname} \u6709\u9884\u7F6E\u5DE5\u5177\uFF0C\u6B63\u5728\u6CE8\u5165...`));
664
+ const toolScript = fs.readFileSync(toolBundlePath, "utf-8");
665
+ try {
666
+ await page.evaluate(toolScript);
667
+ console.log(pc.green(`\u5DF2\u4E3A ${hostname} \u6CE8\u5165\u9884\u7F6E\u5DE5\u5177`));
668
+ } catch (err) {
669
+ const msg = err instanceof Error ? err.message : String(err);
670
+ console.warn(pc.yellow(`\u57DF\u540D\u5DE5\u5177\u6CE8\u5165\u5931\u8D25 (${hostname}): ${msg}`));
3129
671
  }
3130
- const expanded = expandFileRefs(raw, baseDir);
3131
- return parseArgsJson(expanded);
3132
672
  }
3133
673
 
3134
674
  // src/commands/state.ts
3135
- init_browser();
3136
675
  async function stateCommand({ tabid }) {
3137
676
  const browser = await connectBrowser();
3138
677
  try {
@@ -3186,7 +725,6 @@ async function stateCommand({ tabid }) {
3186
725
  }
3187
726
 
3188
727
  // src/commands/run.ts
3189
- init_browser();
3190
728
  async function runCommand({
3191
729
  toolName,
3192
730
  argsJson,
@@ -3261,7 +799,6 @@ async function setClipboard(content) {
3261
799
  }
3262
800
 
3263
801
  // src/commands/tabs.ts
3264
- init_browser();
3265
802
  function normalizeUrl(url) {
3266
803
  if (!url.startsWith("http://") && !url.startsWith("https://")) {
3267
804
  return "https://" + url;
@@ -3383,26 +920,75 @@ async function tabsForwardCommand(tabid) {
3383
920
  }
3384
921
  }
3385
922
 
3386
- // src/bin.ts
3387
- init_package();
3388
- function extractMode(argv) {
3389
- let mode = process.env.WEBMCP_MODE === "wxt" ? "wxt" : "cdp";
3390
- const filteredArgv = [];
3391
- for (let i = 0; i < argv.length; i++) {
3392
- if (argv[i] === "--mode" && argv[i + 1]) {
3393
- const val = argv[i + 1].toLowerCase();
3394
- if (val === "wxt" || val === "cdp") mode = val;
3395
- i++;
3396
- } else if (argv[i].startsWith("--mode=")) {
3397
- const val = argv[i].split("=")[1]?.toLowerCase();
3398
- if (val === "wxt" || val === "cdp") mode = val;
3399
- } else {
3400
- filteredArgv.push(argv[i]);
3401
- }
923
+ // package.json
924
+ var package_default = {
925
+ name: "@opentiny/webmcp-cli",
926
+ version: "0.1.1-alpha.1",
927
+ type: "module",
928
+ description: "WebMCP CLI for AI Agents to interact with browser via Puppeteer",
929
+ repository: {
930
+ type: "git",
931
+ url: "git+https://github.com/opentiny/webmcp-sdk.git",
932
+ directory: "packages/webmcp-cli"
933
+ },
934
+ bugs: {
935
+ url: "https://github.com/opentiny/webmcp-sdk/issues"
936
+ },
937
+ main: "dist/index.js",
938
+ types: "dist/index.d.ts",
939
+ bin: {
940
+ "webmcp-cli": "./dist/bin.js"
941
+ },
942
+ files: [
943
+ "dist",
944
+ "README.md"
945
+ ],
946
+ scripts: {
947
+ dev: "tsup --watch",
948
+ "build:inject": "node scripts/build-inject.mjs",
949
+ build: "tsup && pnpm run build:inject",
950
+ prepublishOnly: "pnpm run build",
951
+ "link:global": "npm install -g .",
952
+ start: "node dist/bin.js",
953
+ test: "vitest run",
954
+ "test:watch": "vitest",
955
+ "test:browser": "vitest run --config vitest.e2e.config.ts"
956
+ },
957
+ keywords: [
958
+ "chrome",
959
+ "puppeteer",
960
+ "cli"
961
+ ],
962
+ license: "MIT",
963
+ author: "OpenTiny Team",
964
+ engines: {
965
+ node: ">=16"
966
+ },
967
+ publishConfig: {
968
+ access: "public"
969
+ },
970
+ dependencies: {
971
+ "@mcp-b/webmcp-polyfill": "catalog:",
972
+ "@opentiny/next-sdk": "workspace:^",
973
+ "@page-agent/page-controller": "catalog:",
974
+ clipboardy: "^5.3.1",
975
+ commander: "^11.1.0",
976
+ json5: "^2.2.3",
977
+ marked: "^15.0.7",
978
+ picocolors: "^1.0.0",
979
+ "puppeteer-core": "^22.0.0"
980
+ },
981
+ devDependencies: {
982
+ "@types/node": "^20.0.0",
983
+ esbuild: "^0.25.0",
984
+ tsup: "^8.0.2",
985
+ tsx: "^4.0.0",
986
+ typescript: "^5.3.3",
987
+ vitest: "^4.1.10"
3402
988
  }
3403
- return { mode, filteredArgv };
3404
- }
3405
- var { mode: CLI_MODE, filteredArgv: FILTERED_ARGV } = extractMode(process.argv);
989
+ };
990
+
991
+ // src/bin.ts
3406
992
  var program = new Command();
3407
993
  function parseTabId(id) {
3408
994
  if (!id) return void 0;
@@ -3434,26 +1020,26 @@ function tryParseBrowserStateText(text) {
3434
1020
  }
3435
1021
  function cleanOldLogs(baseDir, logDir) {
3436
1022
  try {
3437
- const oldLogFile = path6.join(baseDir, "webmcp-cli.log");
3438
- if (fs6.existsSync(oldLogFile)) {
1023
+ const oldLogFile = path2.join(baseDir, "webmcp-cli.log");
1024
+ if (fs2.existsSync(oldLogFile)) {
3439
1025
  try {
3440
- fs6.unlinkSync(oldLogFile);
1026
+ fs2.unlinkSync(oldLogFile);
3441
1027
  } catch {
3442
1028
  }
3443
1029
  }
3444
- if (fs6.existsSync(baseDir)) {
3445
- const baseFiles = fs6.readdirSync(baseDir);
1030
+ if (fs2.existsSync(baseDir)) {
1031
+ const baseFiles = fs2.readdirSync(baseDir);
3446
1032
  for (const file of baseFiles) {
3447
1033
  if (/^webmcp-cli-\d{4}-\d{2}-\d{2}\.log$/.test(file)) {
3448
1034
  try {
3449
- fs6.unlinkSync(path6.join(baseDir, file));
1035
+ fs2.unlinkSync(path2.join(baseDir, file));
3450
1036
  } catch {
3451
1037
  }
3452
1038
  }
3453
1039
  }
3454
1040
  }
3455
- if (!fs6.existsSync(logDir)) return;
3456
- const files = fs6.readdirSync(logDir);
1041
+ if (!fs2.existsSync(logDir)) return;
1042
+ const files = fs2.readdirSync(logDir);
3457
1043
  const logFilePattern = /^webmcp-cli-(\d{4}-\d{2}-\d{2})\.log$/;
3458
1044
  const now = Date.now();
3459
1045
  const maxAgeMs = 7 * 24 * 60 * 60 * 1e3;
@@ -3465,7 +1051,7 @@ function cleanOldLogs(baseDir, logDir) {
3465
1051
  if (isNaN(fileDate)) continue;
3466
1052
  if (now - fileDate > maxAgeMs) {
3467
1053
  try {
3468
- fs6.unlinkSync(path6.join(logDir, file));
1054
+ fs2.unlinkSync(path2.join(logDir, file));
3469
1055
  } catch {
3470
1056
  }
3471
1057
  }
@@ -3521,13 +1107,13 @@ ${searchResultStr}`;
3521
1107
  }
3522
1108
  function writeLog(commandName, args, result, error) {
3523
1109
  try {
3524
- const baseDir = process.env.WEBMCP_WORKSPACE || path6.join(os5.homedir(), ".webmcp_chrome_profile");
3525
- const logDir = path6.join(baseDir, "logs");
3526
- if (!fs6.existsSync(logDir)) {
3527
- fs6.mkdirSync(logDir, { recursive: true });
1110
+ const baseDir = process.env.WEBMCP_WORKSPACE || path2.join(os2.homedir(), ".webmcp_chrome_profile");
1111
+ const logDir = path2.join(baseDir, "logs");
1112
+ if (!fs2.existsSync(logDir)) {
1113
+ fs2.mkdirSync(logDir, { recursive: true });
3528
1114
  }
3529
1115
  const todayStr = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
3530
- const logFile = path6.join(logDir, `webmcp-cli-${todayStr}.log`);
1116
+ const logFile = path2.join(logDir, `webmcp-cli-${todayStr}.log`);
3531
1117
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
3532
1118
  let logText = `========================================
3533
1119
  `;
@@ -3553,7 +1139,7 @@ ${error instanceof Error ? error.stack : String(error)}
3553
1139
  logText += `========================================
3554
1140
 
3555
1141
  `;
3556
- fs6.appendFileSync(logFile, logText, "utf-8");
1142
+ fs2.appendFileSync(logFile, logText, "utf-8");
3557
1143
  cleanOldLogs(baseDir, logDir);
3558
1144
  } catch (e) {
3559
1145
  }
@@ -3564,22 +1150,11 @@ function handleCommandError(error, commandName, args) {
3564
1150
  console.error(pc2.red(`Error executing ${commandName} command: ${msg}`));
3565
1151
  process.exit(1);
3566
1152
  }
3567
- program.name("webmcp-cli").description(
3568
- "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"
3569
- ).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").option(
3570
- "--ignore-certificate-errors",
3571
- "\u5173\u95ED\u53D7\u63A7\u6D4F\u89C8\u5668\u7684 HTTPS \u8BC1\u4E66\u6821\u9A8C\uFF08\u81EA\u7B7E\u540D\u3001\u8FC7\u671F\u6216\u4E3B\u673A\u540D\u4E0D\u5339\u914D\uFF09\u3002\u4E5F\u53EF\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF WEBMCP_IGNORE_CERTIFICATE_ERRORS=1\u3002\u9ED8\u8BA4\u4ECD\u6821\u9A8C\u3002\u4EC5 CDP \u6A21\u5F0F\u6709\u6548"
3572
- ).hook("preAction", (thisCommand) => {
1153
+ 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) => {
3573
1154
  const opts = thisCommand.opts();
3574
1155
  if (opts.workspace) {
3575
1156
  process.env.WEBMCP_WORKSPACE = opts.workspace;
3576
1157
  }
3577
- if (opts.ignoreCertificateErrors) {
3578
- process.env.WEBMCP_IGNORE_CERTIFICATE_ERRORS = "1";
3579
- }
3580
- if (process.env.WEBMCP_IGNORE_CERTIFICATE_ERRORS === "1") {
3581
- console.error(pc2.yellow("\u5F53\u524D\u53D7\u63A7\u6D4F\u89C8\u5668\u5DF2\u5173\u95ED TLS \u8BC1\u4E66\u6821\u9A8C\u3002"));
3582
- }
3583
1158
  });
3584
1159
  program.command("state").description("\u83B7\u53D6\u6D4F\u89C8\u5668\u5F53\u524D\u9875\u7B7E\u6216\u6307\u5B9A\u9875\u7B7E\u7684\u5BFC\u822A\u5143\u6570\u636E\uFF08url\u3001title\u3001webmcpTools\u3001\u6240\u6709\u9875\u7B7E\u5217\u8868\uFF09").option("-t, --tabid <id>", "\u6307\u5B9A\u9875\u7B7E\u7684 ID").action(async (options) => {
3585
1160
  const args = { tabid: parseTabId(options.tabid) };
@@ -3687,174 +1262,5 @@ tabs.command("forward [tabid]").description("\u5C06\u5F53\u524D\u6216\u6307\u5B9
3687
1262
  handleCommandError(error, "tabs forward", args);
3688
1263
  }
3689
1264
  });
3690
- 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) => {
3691
- try {
3692
- const { startMcpServer: startMcpServer2 } = await Promise.resolve().then(() => (init_server(), server_exports));
3693
- await startMcpServer2({ mode: "cdp", agentMode: opts.agent ? "agent" : "tools" });
3694
- } catch (error) {
3695
- handleCommandError(error, "mcp", {});
3696
- }
3697
- });
3698
- if (CLI_MODE === "wxt") {
3699
- void handleWxtMode(FILTERED_ARGV.slice(2)).catch((error) => {
3700
- handleCommandError(error, `wxt:${FILTERED_ARGV[2] ?? "help"}`, {});
3701
- });
3702
- } else {
3703
- program.parse(FILTERED_ARGV);
3704
- }
3705
- async function handleWxtMode(args) {
3706
- const command = args[0];
3707
- if (command === "daemon" || command === "server") {
3708
- const { runDaemonProcess: runDaemonProcess2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
3709
- await runDaemonProcess2(args.slice(1));
3710
- return;
3711
- }
3712
- if (command === "stop") {
3713
- const { stopBridgeDaemon: stopBridgeDaemon2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
3714
- const stopped = await stopBridgeDaemon2();
3715
- 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");
3716
- return;
3717
- }
3718
- if (command === "token") {
3719
- const subArgs = args.slice(1);
3720
- let wsPort2;
3721
- const cleanArgs = [];
3722
- for (let i = 0; i < subArgs.length; i++) {
3723
- if ((subArgs[i] === "--ws-port" || subArgs[i] === "--port") && subArgs[i + 1]) {
3724
- wsPort2 = parseInt(subArgs[++i], 10) || void 0;
3725
- } else {
3726
- cleanArgs.push(subArgs[i]);
3727
- }
3728
- }
3729
- const action = cleanArgs[0];
3730
- let tokenToSet;
3731
- if (action === "set" && cleanArgs[1]) {
3732
- tokenToSet = cleanArgs[1].trim();
3733
- } else if (action && action !== "get" && !action.startsWith("-")) {
3734
- tokenToSet = action.trim();
3735
- }
3736
- const { resolveOrCreateAuthToken: resolveOrCreateAuthToken2 } = await Promise.resolve().then(() => (init_bridge_client(), bridge_client_exports));
3737
- if (tokenToSet) {
3738
- resolveOrCreateAuthToken2(tokenToSet);
3739
- console.log("\u2705 Token \u5DF2\u6210\u529F\u4FDD\u5B58\u81F3 ~/.robot-wxt/bridge-token");
3740
- const { stopBridgeDaemon: stopBridgeDaemon2, ensureBridgeDaemon: ensureBridgeDaemon3 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
3741
- await stopBridgeDaemon2(wsPort2);
3742
- await ensureBridgeDaemon3({ token: tokenToSet, port: wsPort2 });
3743
- 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");
3744
- return;
3745
- }
3746
- console.log(resolveOrCreateAuthToken2());
3747
- return;
3748
- }
3749
- if (command === "mcp") {
3750
- const { startMcpServer: startMcpServer2 } = await Promise.resolve().then(() => (init_server(), server_exports));
3751
- const isAgent = args.includes("--agent") || args.includes("--mode=agent");
3752
- const tokenIdx = args.indexOf("--token");
3753
- const token2 = tokenIdx !== -1 ? args[tokenIdx + 1] : void 0;
3754
- const wsPortIdx = args.indexOf("--ws-port");
3755
- const wsPort2 = wsPortIdx !== -1 ? parseInt(args[wsPortIdx + 1], 10) || void 0 : void 0;
3756
- await startMcpServer2({ mode: "wxt", agentMode: isAgent ? "agent" : "tools", token: token2, wsPort: wsPort2 });
3757
- return;
3758
- }
3759
- if (!command || command === "--help" || command === "-h") {
3760
- printWxtHelp();
3761
- return;
3762
- }
3763
- let token;
3764
- let wsPort;
3765
- const commandArgs = [];
3766
- for (let i = 1; i < args.length; i++) {
3767
- if (args[i] === "--token" && args[i + 1]) {
3768
- token = args[++i];
3769
- } else if (args[i] === "--ws-port" && args[i + 1]) {
3770
- wsPort = parseInt(args[++i], 10) || void 0;
3771
- } else {
3772
- commandArgs.push(args[i]);
3773
- }
3774
- }
3775
- const { ensureBridgeDaemon: ensureBridgeDaemon2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
3776
- const isJson = commandArgs.includes("--json");
3777
- await ensureBridgeDaemon2({ token, port: wsPort, silent: isJson });
3778
- const { WxtBrowserAdapter: WxtBrowserAdapter2 } = await Promise.resolve().then(() => (init_wxt_adapter(), wxt_adapter_exports));
3779
- const adapter = new WxtBrowserAdapter2(token, wsPort);
3780
- await adapter.ensureConnected();
3781
- try {
3782
- switch (command) {
3783
- case "state": {
3784
- const tabIdx = commandArgs.indexOf("--tab");
3785
- const tabId = tabIdx !== -1 ? commandArgs[tabIdx + 1] : void 0;
3786
- const result = await adapter.getState(tabId ? parseInt(tabId, 10) : void 0);
3787
- console.log(JSON.stringify(result, null, 2));
3788
- break;
3789
- }
3790
- case "run": {
3791
- const toolName = commandArgs.find((a) => !a.startsWith("-"));
3792
- const argsStr = commandArgs.slice(commandArgs.indexOf(toolName) + 1).find((a) => !a.startsWith("-"));
3793
- if (!toolName) {
3794
- console.error("[\u9519\u8BEF] \u8BF7\u63D0\u4F9B\u5DE5\u5177\u540D\u79F0");
3795
- process.exit(1);
3796
- }
3797
- const toolArgs = argsStr ? JSON.parse(argsStr) : {};
3798
- const result = await adapter.callTool(toolName, toolArgs);
3799
- console.log(JSON.stringify(result, null, 2));
3800
- break;
3801
- }
3802
- case "tabs": {
3803
- const tabAction = commandArgs[0];
3804
- const tabArgs = commandArgs.slice(1);
3805
- const url = tabArgs.find((a) => a.startsWith("http"));
3806
- const tabIdVal = tabArgs.find((a) => !a.startsWith("-") && !a.startsWith("http"));
3807
- const result = await adapter.tabs(tabAction, {
3808
- url,
3809
- tabId: tabIdVal ? parseInt(tabIdVal, 10) : void 0
3810
- });
3811
- console.log(JSON.stringify(result, null, 2));
3812
- break;
3813
- }
3814
- case "agent": {
3815
- const { handleAgentCommand: handleAgentCommand2 } = await Promise.resolve().then(() => (init_agent(), agent_exports));
3816
- await handleAgentCommand2(adapter, commandArgs);
3817
- break;
3818
- }
3819
- case "skills":
3820
- case "skill": {
3821
- const { handleSkillsCommand: handleSkillsCommand2 } = await Promise.resolve().then(() => (init_skills(), skills_exports));
3822
- await handleSkillsCommand2(adapter, commandArgs);
3823
- break;
3824
- }
3825
- default:
3826
- console.error(`[\u9519\u8BEF] WXT \u6A21\u5F0F\u4E0B\u672A\u77E5\u547D\u4EE4: ${command}`);
3827
- printWxtHelp();
3828
- process.exit(1);
3829
- }
3830
- } finally {
3831
- await adapter.dispose();
3832
- }
3833
- }
3834
- function printWxtHelp() {
3835
- console.log(`
3836
- 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
3837
-
3838
- \u547D\u4EE4\uFF1A
3839
- state \u83B7\u53D6\u5F53\u524D\u6D3B\u8DC3 tab \u4FE1\u606F\u4E0E\u9875\u9762\u5DE5\u5177\u5217\u8868
3840
- run <tool> [args] \u8C03\u7528\u9875\u9762 WebMCP \u5DE5\u5177
3841
- tabs <action> [...] \u7BA1\u7406\u6807\u7B7E\u9875\uFF08open/close/switch/back/forward\uFF09
3842
- agent run "<\u6307\u4EE4>" \u59D4\u6258 Tiny Robot \u5B50\u4EE3\u7406\u81EA\u4E3B\u6267\u884C\u9AD8\u5C42\u4EFB\u52A1
3843
- skills list \u5217\u51FA\u5DF2\u6CE8\u518C\u7684 Skills \u6280\u80FD
3844
- skills get <name> \u8BFB\u53D6\u6307\u5B9A\u6280\u80FD\u7684\u8BE6\u7EC6\u6307\u4EE4
3845
- token [get|set <t>] \u67E5\u770B\u6216\u4FDD\u5B58\u8BA4\u8BC1 Token
3846
- stop \u505C\u6B62\u540E\u53F0 WebSocket \u6865\u63A5\u670D\u52A1
3847
- mcp \u4EE5 MCP Server \u6A21\u5F0F\u542F\u52A8
3848
-
3849
- \u9009\u9879\uFF1A
3850
- --token <token> \u8BA4\u8BC1 Token\uFF08\u4F18\u5148\u4E8E ~/.robot-wxt/bridge-token\uFF09
3851
- --ws-port <port> WS \u6865\u63A5\u7AEF\u53E3\uFF08\u9ED8\u8BA4 18999\uFF09
3852
- --json \u8F93\u51FA JSON \u683C\u5F0F
3853
-
3854
- \u793A\u4F8B\uFF1A
3855
- webmcp-cli --mode wxt state
3856
- webmcp-cli --mode wxt agent run "\u5E2E\u6211\u628A\u5546\u54C1\u52A0\u5165\u8D2D\u7269\u8F66"
3857
- webmcp-cli --mode wxt mcp --agent
3858
- `.trim());
3859
- }
1265
+ program.parse(process.argv);
3860
1266
  //# sourceMappingURL=bin.js.map