@opentiny/webmcp-cli 0.1.1-alpha.1 → 0.1.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,192 +1,13 @@
1
1
  #!/usr/bin/env node
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
- }
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
+ };
190
11
 
191
12
  // src/browser.ts
192
13
  import puppeteer from "puppeteer-core";
@@ -197,8 +18,6 @@ import path from "path";
197
18
  import http from "http";
198
19
  import { spawn } from "child_process";
199
20
  import { fileURLToPath as fileURLToPath2 } from "url";
200
- var __filename = fileURLToPath2(import.meta.url);
201
- var __dirname = path.dirname(__filename);
202
21
  function getCdpPort() {
203
22
  const raw = process.env.WEBMCP_CDP_PORT;
204
23
  if (raw) {
@@ -214,6 +33,38 @@ function shouldLaunchHeadless() {
214
33
  if (process.env.WEBMCP_HEADLESS === "0") return false;
215
34
  return process.env.WEBMCP_HEADLESS === "1" || process.env.CI === "true" || process.env.CI === "1";
216
35
  }
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
+ }
217
68
  function readActivePortFromProfile(userDataDir) {
218
69
  try {
219
70
  const content = fs.readFileSync(path.join(userDataDir, "DevToolsActivePort"), "utf-8");
@@ -308,7 +159,7 @@ async function findAvailableCdpUrl(addresses, retries = 2) {
308
159
  async function connectPuppeteer(browserBaseUrl, attempt = 1, maxAttempts = 3) {
309
160
  try {
310
161
  return await promiseWithTimeout(
311
- puppeteer.connect({ browserURL: browserBaseUrl, defaultViewport: null }),
162
+ puppeteer.connect(buildPuppeteerConnectOptions(browserBaseUrl)),
312
163
  1e4,
313
164
  `puppeteer.connect to ${browserBaseUrl} timed out`
314
165
  );
@@ -383,21 +234,11 @@ async function startBrowserInBackground() {
383
234
  fs.unlinkSync(path.join(userDataDir, "DevToolsActivePort"));
384
235
  } catch {
385
236
  }
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
- }
237
+ const launchArgs = buildChromeLaunchArgs({
238
+ cdpPort,
239
+ userDataDir,
240
+ headless: shouldLaunchHeadless()
241
+ });
401
242
  const child = spawn(
402
243
  browserInfo.path,
403
244
  launchArgs,
@@ -522,156 +363,3446 @@ async function activateTabById(browser, tabid) {
522
363
  });
523
364
  }
524
365
  }
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;
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.1",
530
+ type: "module",
531
+ description: "WebMCP CLI for AI Agents to interact with browser via Puppeteer",
532
+ repository: {
533
+ type: "git",
534
+ url: "git+https://github.com/opentiny/webmcp-sdk.git",
535
+ directory: "packages/webmcp-cli"
536
+ },
537
+ bugs: {
538
+ url: "https://github.com/opentiny/webmcp-sdk/issues"
539
+ },
540
+ main: "dist/index.js",
541
+ types: "dist/index.d.ts",
542
+ bin: {
543
+ "webmcp-cli": "./dist/bin.js"
544
+ },
545
+ files: [
546
+ "dist",
547
+ "README.md",
548
+ "scripts/ensure-pty-helper.mjs"
549
+ ],
550
+ scripts: {
551
+ dev: "tsup --watch",
552
+ "build:inject": "node scripts/build-inject.mjs",
553
+ build: "tsup && pnpm run build:inject",
554
+ prepublishOnly: "pnpm run build",
555
+ "link:global": "npm install -g .",
556
+ start: "node dist/bin.js",
557
+ postinstall: "node scripts/ensure-pty-helper.mjs",
558
+ test: "vitest run",
559
+ "test:watch": "vitest",
560
+ "test:browser": "vitest run --config vitest.e2e.config.ts"
561
+ },
562
+ keywords: [
563
+ "chrome",
564
+ "puppeteer",
565
+ "cli"
566
+ ],
567
+ license: "MIT",
568
+ author: "OpenTiny Team",
569
+ engines: {
570
+ node: ">=18.19.0"
571
+ },
572
+ publishConfig: {
573
+ access: "public"
574
+ },
575
+ dependencies: {
576
+ "@mcp-b/webmcp-polyfill": "catalog:",
577
+ "@modelcontextprotocol/sdk": "catalog:",
578
+ "@opentiny/next-sdk": "workspace:^",
579
+ "@page-agent/page-controller": "catalog:",
580
+ clipboardy: "^5.3.1",
581
+ commander: "^11.1.0",
582
+ execa: "^9.6.1",
583
+ json5: "^2.2.3",
584
+ marked: "^15.0.7",
585
+ picocolors: "^1.0.0",
586
+ "puppeteer-core": "^22.0.0",
587
+ ws: "^8.18.0",
588
+ zod: "^3.23.0"
589
+ },
590
+ optionalDependencies: {
591
+ "node-pty": "^1.1.0"
592
+ },
593
+ devDependencies: {
594
+ "@types/node": "^20.0.0",
595
+ "@types/ws": "^8.5.10",
596
+ esbuild: "^0.25.0",
597
+ tsup: "^8.0.2",
598
+ tsx: "^4.0.0",
599
+ typescript: "^5.3.3",
600
+ vitest: "^4.1.10"
601
+ }
602
+ };
603
+ }
604
+ });
605
+
606
+ // src/mcp/tools.ts
607
+ import { z } from "zod";
608
+ var BrowserStateInput, BrowserToolCallInput, BrowserTabsOpenInput, BrowserTabsCloseInput, BrowserTabsSwitchInput, BrowserTabsNavInput, BrowserSubAgentRunInput, BrowserSkillsListInput, BrowserSkillsReadInput;
609
+ var init_tools = __esm({
610
+ "src/mcp/tools.ts"() {
611
+ "use strict";
612
+ BrowserStateInput = z.object({
613
+ tabId: z.union([z.string(), z.number()]).optional().describe(
614
+ "\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"
615
+ )
616
+ });
617
+ BrowserToolCallInput = z.object({
618
+ 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"),
619
+ toolArgs: z.record(z.unknown()).optional().describe("\u5DE5\u5177\u53C2\u6570\uFF0C\u4E0E\u5DE5\u5177\u7684 inputSchema \u5BF9\u9F50"),
620
+ tabId: z.union([z.string(), z.number()]).optional().describe("\u76EE\u6807 tab ID\uFF0C\u4E0D\u4F20\u65F6\u4F7F\u7528\u5F53\u524D\u6D3B\u8DC3 tab")
621
+ });
622
+ BrowserTabsOpenInput = z.object({
623
+ 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")
624
+ });
625
+ BrowserTabsCloseInput = z.object({
626
+ tabId: z.union([z.string(), z.number()]).optional().describe(
627
+ "\u8981\u5173\u95ED\u7684 tab ID\uFF0C\u4E0D\u4F20\u65F6\u5173\u95ED\u5F53\u524D\u6D3B\u8DC3 tab"
628
+ )
629
+ });
630
+ BrowserTabsSwitchInput = z.object({
631
+ tabId: z.union([z.string(), z.number()]).describe(
632
+ "\u8981\u5207\u6362\u5230\u7684 tab ID\uFF08\u53EF\u4ECE browser_state \u8FD4\u56DE\u7684 tabs \u5217\u8868\u4E2D\u83B7\u53D6\uFF09"
633
+ ),
634
+ 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")
635
+ });
636
+ BrowserTabsNavInput = z.object({
637
+ tabId: z.union([z.string(), z.number()]).optional().describe("\u76EE\u6807 tab ID\uFF0C\u4E0D\u4F20\u65F6\u4F7F\u7528\u5F53\u524D\u6D3B\u8DC3 tab")
638
+ });
639
+ BrowserSubAgentRunInput = z.object({
640
+ 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"),
641
+ tabId: z.number().optional().describe("\u76EE\u6807 tab ID\uFF0C\u4E0D\u4F20\u65F6\u4F7F\u7528\u5F53\u524D\u6D3B\u8DC3 tab"),
642
+ 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")
643
+ });
644
+ 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");
645
+ BrowserSkillsReadInput = z.object({
646
+ 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")
647
+ });
648
+ }
649
+ });
650
+
651
+ // src/adapters/cdp-adapter.ts
652
+ var cdp_adapter_exports = {};
653
+ __export(cdp_adapter_exports, {
654
+ CdpBrowserAdapter: () => CdpBrowserAdapter
655
+ });
656
+ var CdpBrowserAdapter;
657
+ var init_cdp_adapter = __esm({
658
+ "src/adapters/cdp-adapter.ts"() {
659
+ "use strict";
660
+ init_browser();
661
+ CdpBrowserAdapter = class {
662
+ browser = null;
663
+ async getBrowser() {
664
+ if (!this.browser) {
665
+ this.browser = await connectBrowser();
666
+ }
667
+ return this.browser;
668
+ }
669
+ async getState(tabId) {
670
+ const browser = await this.getBrowser();
671
+ const tabIdStr = tabId != null ? String(tabId) : void 0;
672
+ const page = await getTargetPage(browser, tabIdStr);
673
+ await injectIntoPage(page);
674
+ const state = await page.evaluate(async () => {
675
+ const url = document.URL;
676
+ const title = document.title;
677
+ const mcp = document.modelContext || navigator.modelContext;
678
+ let webmcpTools = [];
679
+ if (mcp && typeof mcp.getTools === "function") {
680
+ try {
681
+ const toolsResult = await mcp.getTools();
682
+ const list = toolsResult?.tools || toolsResult || [];
683
+ webmcpTools = list.filter((t) => t && typeof t.name === "string").map((t) => ({
684
+ name: t.name,
685
+ description: typeof t.description === "string" ? t.description.slice(0, 200) : void 0
686
+ }));
687
+ } catch {
688
+ webmcpTools = [];
689
+ }
690
+ }
691
+ return { url, title, webmcpTools };
692
+ });
693
+ const activeTabId = await getPageTargetId(page).catch(() => null);
694
+ const pages = await browser.pages();
695
+ const tabs2 = await Promise.all(
696
+ pages.map(async (p) => {
697
+ const pUrl = p.url();
698
+ if (pUrl.startsWith("devtools://")) return null;
699
+ const pTitle = await Promise.race([
700
+ p.title().catch(() => "Unknown"),
701
+ new Promise((resolve3) => setTimeout(() => resolve3("Unknown"), 500))
702
+ ]);
703
+ return {
704
+ tabId: await getPageTargetId(p).catch(() => pUrl),
705
+ title: pTitle,
706
+ url: pUrl
707
+ };
708
+ })
709
+ );
710
+ return {
711
+ ...state,
712
+ activeTabId: activeTabId ?? void 0,
713
+ tabs: tabs2.filter(Boolean)
714
+ };
715
+ }
716
+ async callTool(toolName, args, tabId) {
717
+ const browser = await this.getBrowser();
718
+ const tabIdStr = tabId != null ? String(tabId) : void 0;
719
+ const page = await getTargetPage(browser, tabIdStr);
720
+ const urlBefore = page.url();
721
+ await injectIntoPage(page);
722
+ const argsJson = JSON.stringify(args);
723
+ try {
724
+ const result = await page.evaluate(
725
+ async (name, inputString) => {
726
+ const mcp = document.modelContext || navigator.modelContext;
727
+ if (!mcp || typeof mcp.executeTool !== "function") {
728
+ throw new Error("\u5F53\u524D\u9875\u9762\u6CA1\u6709\u6CE8\u5165 WebMCP \u73AF\u5883 (document.modelContext \u672A\u627E\u5230)");
729
+ }
730
+ const tools = await mcp.getTools();
731
+ const toolObj = tools.find((t) => t.name === name);
732
+ if (!toolObj) throw new Error(`Tool ${name} not found`);
733
+ let res = await mcp.executeTool(toolObj, inputString);
734
+ if (typeof res === "string") {
735
+ try {
736
+ res = JSON.parse(res);
737
+ } catch {
738
+ }
739
+ }
740
+ if (res === void 0 || res === null) {
741
+ throw new Error("\u5DE5\u5177 execute \u672A\u8FD4\u56DE\u7ED3\u679C");
742
+ }
743
+ if (typeof res === "object" && res.success === false) {
744
+ const failed = res;
745
+ throw new Error(failed.error || failed.message || "\u5DE5\u5177\u6267\u884C\u5931\u8D25");
746
+ }
747
+ return res;
748
+ },
749
+ toolName,
750
+ argsJson
751
+ );
752
+ return result;
753
+ } catch (evalError) {
754
+ const errMsg = evalError instanceof Error ? evalError.message : String(evalError);
755
+ const isContextDestroyed = errMsg.includes("context was destroyed") || errMsg.includes("Execution context was destroyed") || errMsg.includes("Cannot read properties of null") && errMsg.includes("context");
756
+ if (isContextDestroyed) {
757
+ await new Promise((resolve3) => setTimeout(resolve3, 800));
758
+ const newUrl = page.url();
759
+ if (newUrl && newUrl !== urlBefore) {
760
+ return { success: true, message: `\u5DE5\u5177 ${toolName} \u6267\u884C\u5B8C\u6210\uFF0C\u9875\u9762\u5DF2\u5BFC\u822A\u81F3 ${newUrl}`, navigatedTo: newUrl };
761
+ }
762
+ }
763
+ throw evalError;
764
+ }
765
+ }
766
+ async tabs(action, options) {
767
+ const browser = await this.getBrowser();
768
+ const tabIdStr = options.tabId != null ? String(options.tabId) : void 0;
769
+ switch (action) {
770
+ case "open": {
771
+ if (!options.url) throw new Error("tabs open \u9700\u8981 url \u53C2\u6570");
772
+ const page = await browser.newPage();
773
+ await page.goto(options.url);
774
+ await injectIntoPage(page);
775
+ const tabId = await getPageTargetId(page);
776
+ setLastActiveTabId(tabId);
777
+ return { success: true, tabId, url: options.url };
778
+ }
779
+ case "close": {
780
+ const page = await getTargetPage(browser, tabIdStr);
781
+ await page.close();
782
+ return { success: true };
783
+ }
784
+ case "switch": {
785
+ if (!tabIdStr) throw new Error("tabs switch \u9700\u8981 tabId \u53C2\u6570");
786
+ await activateTabById(browser, tabIdStr);
787
+ setLastActiveTabId(tabIdStr);
788
+ return { success: true, tabId: tabIdStr };
789
+ }
790
+ case "back": {
791
+ const page = await getTargetPage(browser, tabIdStr);
792
+ await page.goBack();
793
+ return { success: true };
794
+ }
795
+ case "forward": {
796
+ const page = await getTargetPage(browser, tabIdStr);
797
+ await page.goForward();
798
+ return { success: true };
799
+ }
800
+ }
801
+ }
802
+ async dispose() {
803
+ if (this.browser) {
804
+ await this.browser.disconnect().catch(() => {
805
+ });
806
+ this.browser = null;
807
+ }
808
+ }
809
+ };
810
+ }
811
+ });
812
+
813
+ // src/bridge/protocol.ts
814
+ function isTerminalMethod(method) {
815
+ return TERMINAL_METHOD_SET.has(method);
816
+ }
817
+ var DEFAULT_WS_PORT, PROTOCOL_VERSION, WS_CLOSE_CODE, BRIDGE_ERROR_CODE, BRIDGE_METHODS, TERMINAL_EVENTS, BASH_EVENTS, TERMINAL_METHOD_SET;
818
+ var init_protocol = __esm({
819
+ "src/bridge/protocol.ts"() {
820
+ "use strict";
821
+ DEFAULT_WS_PORT = 18999;
822
+ PROTOCOL_VERSION = "1.2.0";
823
+ WS_CLOSE_CODE = {
824
+ /** 被新接入的扩展连接平滑替换(旧连接触发退避重连) */
825
+ REPLACED: 4e3,
826
+ /** 认证未通过(未提供 Token、Token 错误或 HMAC 签名校验失败) */
827
+ UNAUTHORIZED: 4001,
828
+ /** 协议主版本号不匹配 */
829
+ PROTOCOL_MISMATCH: 4002
830
+ };
831
+ BRIDGE_ERROR_CODE = {
832
+ /** 请求执行超时 */
833
+ REQUEST_TIMEOUT: -32e3,
834
+ /** 命令执行超时 */
835
+ EXECUTION_TIMEOUT: -32001,
836
+ /** 命令或系统操作执行失败 */
837
+ EXECUTION_FAILED: -32002,
838
+ /** 无效参数(如 command 为空) */
839
+ INVALID_PARAMS: -32602,
840
+ /** 不支持的方法 */
841
+ METHOD_NOT_FOUND: -32601,
842
+ /** 扩展尚未连接至桥接服务 */
843
+ EXTENSION_NOT_CONNECTED: -32051,
844
+ /** 侧边栏尚未就绪或已关闭 */
845
+ SIDEPANEL_NOT_READY: -32050
846
+ };
847
+ BRIDGE_METHODS = {
848
+ TOOL_CALL: "tool/call",
849
+ SUB_AGENT_RUN: "sub_agent/run",
850
+ BROWSER_TABS: "browser/tabs",
851
+ BROWSER_STATE: "browser/state",
852
+ SKILLS_LIST: "skills/list",
853
+ SKILLS_GET: "skills/get",
854
+ SKILLS_READ_RESOURCE: "skills/read_resource",
855
+ SYSTEM_BASH: "system/bash",
856
+ SYSTEM_PICK_DIRECTORY: "system/pick_directory",
857
+ TERMINAL_OPEN: "terminal/open",
858
+ TERMINAL_INPUT: "terminal/input",
859
+ TERMINAL_RESIZE: "terminal/resize",
860
+ TERMINAL_CLOSE: "terminal/close"
861
+ };
862
+ TERMINAL_EVENTS = {
863
+ OUTPUT: "notification/terminal_output",
864
+ EXIT: "notification/terminal_exit"
865
+ };
866
+ BASH_EVENTS = {
867
+ OUTPUT: "notification/bash_output"
868
+ };
869
+ TERMINAL_METHOD_SET = /* @__PURE__ */ new Set([
870
+ BRIDGE_METHODS.TERMINAL_OPEN,
871
+ BRIDGE_METHODS.TERMINAL_INPUT,
872
+ BRIDGE_METHODS.TERMINAL_RESIZE,
873
+ BRIDGE_METHODS.TERMINAL_CLOSE
874
+ ]);
875
+ }
876
+ });
877
+
878
+ // src/bridge/workspace-manager.ts
879
+ import path2 from "path";
880
+ import os2 from "os";
881
+ import fs2 from "fs";
882
+ function resolveBaseWorkspace(params) {
883
+ if (params.workspacePath && typeof params.workspacePath === "string" && params.workspacePath.trim()) {
884
+ const trimmedWs = params.workspacePath.trim();
885
+ return path2.isAbsolute(trimmedWs) ? trimmedWs : path2.resolve(os2.homedir(), trimmedWs);
886
+ }
887
+ if (params.conversationId && typeof params.conversationId === "string" && params.conversationId.trim()) {
888
+ const safeId = params.conversationId.trim().replace(/[/\\?%*:|"<>.]/g, "_");
889
+ const sessionDir = path2.resolve(WORKSPACES_ROOT, safeId || "default");
890
+ const relative = path2.relative(WORKSPACES_ROOT, sessionDir);
891
+ if (!relative || relative.startsWith("..") || path2.isAbsolute(relative)) {
892
+ return path2.join(WORKSPACES_ROOT, "default");
893
+ }
894
+ return sessionDir;
895
+ }
896
+ return path2.join(WORKSPACES_ROOT, "default");
897
+ }
898
+ function resolveWorkspaceDir(params = {}) {
899
+ const baseDir = resolveBaseWorkspace(params);
900
+ if (!fs2.existsSync(baseDir)) {
901
+ try {
902
+ fs2.mkdirSync(baseDir, { recursive: true, mode: 493 });
903
+ } catch {
904
+ }
905
+ }
906
+ if (!params.cwd || typeof params.cwd !== "string" || !params.cwd.trim()) {
907
+ return baseDir;
908
+ }
909
+ const trimmedCwd = params.cwd.trim();
910
+ const targetDir = path2.isAbsolute(trimmedCwd) ? path2.resolve(trimmedCwd) : path2.resolve(baseDir, trimmedCwd);
911
+ const relative = path2.relative(baseDir, targetDir);
912
+ if (relative.startsWith("..") || path2.isAbsolute(relative)) {
913
+ throw new BashInvalidParamsError(`\u76EE\u6807\u6267\u884C\u8DEF\u5F84\u8D85\u51FA\u5DF2\u6388\u6743\u5DE5\u4F5C\u7A7A\u95F4\u5B89\u5168\u8FB9\u754C: ${trimmedCwd}`);
914
+ }
915
+ return targetDir;
916
+ }
917
+ var WORKSPACES_ROOT, BashInvalidParamsError;
918
+ var init_workspace_manager = __esm({
919
+ "src/bridge/workspace-manager.ts"() {
920
+ "use strict";
921
+ WORKSPACES_ROOT = path2.join(os2.homedir(), ".robot-wxt", "workspaces");
922
+ BashInvalidParamsError = class extends Error {
923
+ code = "INVALID_PARAMS";
924
+ constructor(message = "\u53C2\u6570\u9519\u8BEF") {
925
+ super(message);
926
+ this.name = "BashInvalidParamsError";
927
+ }
928
+ };
929
+ }
930
+ });
931
+
932
+ // src/bridge/bash-executor.ts
933
+ import { spawnSync } from "child_process";
934
+ import fs3 from "fs";
935
+ import path3 from "path";
936
+ import { StringDecoder } from "string_decoder";
937
+ import { execa } from "execa";
938
+ function findWindowsBash() {
939
+ const pathDirs = (process.env.PATH || "").split(path3.delimiter);
940
+ for (const dir of pathDirs) {
941
+ if (!dir) continue;
942
+ const candidate = path3.join(dir, "bash.exe");
943
+ try {
944
+ if (fs3.existsSync(candidate)) return candidate;
945
+ } catch {
946
+ }
947
+ }
948
+ const localAppData = process.env.LOCALAPPDATA || "";
949
+ const programFiles = process.env.ProgramFiles || "C:\\Program Files";
950
+ const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
951
+ const programW6432 = process.env.ProgramW6432 || programFiles;
952
+ const commonGitBashPaths = [
953
+ path3.join(programFiles, "Git", "bin", "bash.exe"),
954
+ path3.join(programFiles, "Git", "usr", "bin", "bash.exe"),
955
+ path3.join(programW6432, "Git", "bin", "bash.exe"),
956
+ path3.join(programFilesX86, "Git", "bin", "bash.exe"),
957
+ path3.join(localAppData, "Programs", "Git", "bin", "bash.exe"),
958
+ path3.join(localAppData, "Programs", "Git", "usr", "bin", "bash.exe"),
959
+ path3.join(process.env.SystemRoot || "C:\\Windows", "System32", "bash.exe")
960
+ ];
961
+ for (const candidate of commonGitBashPaths) {
962
+ try {
963
+ if (fs3.existsSync(candidate)) return candidate;
964
+ } catch {
965
+ }
966
+ }
967
+ return null;
968
+ }
969
+ function resolveShell(forcePlatform) {
970
+ const currentPlatform = forcePlatform || process.platform;
971
+ if (!forcePlatform && cachedShell) {
972
+ return cachedShell;
973
+ }
974
+ if (currentPlatform !== "win32") {
975
+ const posixShell = process.env.SHELL || "/bin/bash";
976
+ if (!forcePlatform) cachedShell = posixShell;
977
+ return posixShell;
978
+ }
979
+ const winBash = findWindowsBash();
980
+ if (winBash) {
981
+ if (!forcePlatform) cachedShell = winBash;
982
+ return winBash;
983
+ }
984
+ const fallback = "powershell.exe";
985
+ if (!forcePlatform) cachedShell = fallback;
986
+ return fallback;
987
+ }
988
+ function stripAnsi(text) {
989
+ return text.replace(ANSI_PATTERN, "");
990
+ }
991
+ function createAnsiStripper() {
992
+ let pending = "";
993
+ const take = (final) => {
994
+ let out = "";
995
+ let index = 0;
996
+ while (index < pending.length) {
997
+ if (pending[index] !== "\x1B") {
998
+ out += pending[index];
999
+ index += 1;
1000
+ continue;
1001
+ }
1002
+ const rest = pending.slice(index);
1003
+ ANSI_PATTERN.lastIndex = 0;
1004
+ const match = ANSI_PATTERN.exec(rest);
1005
+ if (match && match.index === 0) {
1006
+ index += match[0].length;
1007
+ continue;
1008
+ }
1009
+ if (!final && rest.length < 128 && isOpenAnsi(rest)) {
1010
+ pending = rest;
1011
+ return out;
1012
+ }
1013
+ out += pending[index];
1014
+ index += 1;
1015
+ }
1016
+ pending = "";
1017
+ return out;
1018
+ };
1019
+ return {
1020
+ push(text) {
1021
+ pending += text;
1022
+ return take(false);
1023
+ },
1024
+ end() {
1025
+ return take(true);
1026
+ }
1027
+ };
1028
+ }
1029
+ function isOpenAnsi(text) {
1030
+ if (!text.startsWith("\x1B")) return false;
1031
+ if (text.length === 1) return true;
1032
+ if (text[1] === "[") {
1033
+ let index = 2;
1034
+ while (index < text.length && /[0-?]/.test(text[index])) index += 1;
1035
+ while (index < text.length && /[ -/]/.test(text[index])) index += 1;
1036
+ return index >= text.length;
1037
+ }
1038
+ if (text[1] === "]") return !text.includes("\x07") && !text.includes("\x1B\\");
1039
+ return false;
1040
+ }
1041
+ function withoutCarriageReturn(buf) {
1042
+ if (!buf.includes(13)) return buf;
1043
+ const out = Buffer.allocUnsafe(buf.length);
1044
+ let size = 0;
1045
+ for (let index = 0; index < buf.length; index += 1) {
1046
+ const byte = buf[index];
1047
+ if (byte === 13) continue;
1048
+ out[size] = byte;
1049
+ size += 1;
1050
+ }
1051
+ return out.subarray(0, size);
1052
+ }
1053
+ function collectLimited(stream, maxBuffer, onText, stripCarriageReturn = false, ansi) {
1054
+ const state = { chunks: [], truncated: false };
1055
+ if (!stream) return state;
1056
+ const decoder = new StringDecoder("utf8");
1057
+ let bytes = 0;
1058
+ const emitText = (text) => {
1059
+ const cleaned = ansi ? ansi.push(text) : text;
1060
+ if (cleaned) onText?.(cleaned);
1061
+ };
1062
+ const emit = (buf) => {
1063
+ emitText(decoder.write(buf));
1064
+ };
1065
+ stream.on("data", (chunk) => {
1066
+ const raw = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1067
+ const buf = stripCarriageReturn ? withoutCarriageReturn(raw) : raw;
1068
+ if (buf.length === 0) return;
1069
+ emit(buf);
1070
+ if (bytes >= maxBuffer) {
1071
+ state.truncated = true;
1072
+ return;
1073
+ }
1074
+ const remaining = maxBuffer - bytes;
1075
+ if (buf.length <= remaining) {
1076
+ state.chunks.push(buf);
1077
+ bytes += buf.length;
1078
+ return;
1079
+ }
1080
+ state.chunks.push(buf.subarray(0, remaining));
1081
+ bytes += remaining;
1082
+ state.truncated = true;
1083
+ });
1084
+ stream.on("end", () => {
1085
+ const rest = ansi ? `${ansi.push(decoder.end())}${ansi.end()}` : decoder.end();
1086
+ if (rest) onText?.(rest);
1087
+ });
1088
+ return state;
1089
+ }
1090
+ function decodeLimited(state, removeAnsi = false) {
1091
+ const decoder = new StringDecoder("utf8");
1092
+ const text = decoder.write(Buffer.concat(state.chunks));
1093
+ const flushed = state.truncated ? "" : decoder.end();
1094
+ const decoded = text + flushed;
1095
+ return (removeAnsi ? stripAnsi(decoded) : decoded).trim();
1096
+ }
1097
+ function signalProcessTree(pid, signal) {
1098
+ if (!pid || pid <= 0) return;
1099
+ if (process.platform === "win32") {
1100
+ try {
1101
+ spawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], { windowsHide: true, timeout: 5e3 });
1102
+ } catch {
1103
+ }
1104
+ return;
1105
+ }
1106
+ try {
1107
+ process.kill(-pid, signal);
1108
+ } catch {
1109
+ try {
1110
+ process.kill(pid, signal);
1111
+ } catch {
1112
+ }
1113
+ }
1114
+ }
1115
+ function ignoreStreamError(stream) {
1116
+ stream?.on("error", () => {
1117
+ });
1118
+ }
1119
+ async function executeBash(params) {
1120
+ const trimmedCommand = params.command?.trim();
1121
+ if (!trimmedCommand) {
1122
+ throw new BashInvalidParamsError("\u547D\u4EE4\u4E0D\u80FD\u4E3A\u7A7A");
1123
+ }
1124
+ if (/rm\s+(-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*\s+|--recursive\s+--force\s+)\s*(\/|~|\$HOME|\/\*)\s*$/i.test(
1125
+ trimmedCommand
1126
+ ) || /:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/i.test(trimmedCommand)) {
1127
+ 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");
1128
+ }
1129
+ const cwd = resolveWorkspaceDir({
1130
+ cwd: params.cwd,
1131
+ workspacePath: params.workspacePath,
1132
+ conversationId: params.conversationId
1133
+ });
1134
+ const normalizedTimeoutMs = typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs) && params.timeoutMs > 0 ? Math.min(params.timeoutMs, MAX_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS;
1135
+ const { env = {}, maxBuffer = DEFAULT_MAX_BUFFER } = params;
1136
+ const shell = resolveShell();
1137
+ const useTty = params.tty === true && process.platform !== "win32";
1138
+ const detached = process.platform !== "win32";
1139
+ const subprocess = useTty ? execa("python3", ["-u", "-c", TTY_HELPER], {
1140
+ cwd,
1141
+ env: {
1142
+ ...env,
1143
+ PAGER: "cat",
1144
+ GIT_PAGER: "cat",
1145
+ BASH_TTY_COMMAND: trimmedCommand,
1146
+ BASH_TTY_SHELL: shell
1147
+ },
1148
+ stdin: "ignore",
1149
+ buffer: false,
1150
+ encoding: "buffer",
1151
+ reject: false,
1152
+ windowsHide: true,
1153
+ stripFinalNewline: false,
1154
+ detached
1155
+ }) : execa(trimmedCommand, {
1156
+ shell,
1157
+ cwd,
1158
+ env,
1159
+ stdin: "ignore",
1160
+ buffer: false,
1161
+ encoding: "buffer",
1162
+ reject: false,
1163
+ windowsHide: true,
1164
+ stripFinalNewline: false,
1165
+ detached
1166
+ });
1167
+ ignoreStreamError(subprocess.stdout);
1168
+ ignoreStreamError(subprocess.stderr);
1169
+ let timedOut = false;
1170
+ let forceTimer;
1171
+ const timer = setTimeout(() => {
1172
+ timedOut = true;
1173
+ signalProcessTree(subprocess.pid, "SIGTERM");
1174
+ forceTimer = setTimeout(() => {
1175
+ signalProcessTree(subprocess.pid, "SIGKILL");
1176
+ subprocess.stdout?.destroy();
1177
+ subprocess.stderr?.destroy();
1178
+ }, FORCE_KILL_AFTER_DELAY_MS);
1179
+ }, normalizedTimeoutMs);
1180
+ const emit = (stream) => (text) => {
1181
+ params.onOutput?.({ stream, text });
1182
+ };
1183
+ const ansi = useTty ? createAnsiStripper() : void 0;
1184
+ const stdoutState = collectLimited(subprocess.stdout, maxBuffer, emit("stdout"), useTty, ansi);
1185
+ const stderrState = collectLimited(subprocess.stderr, maxBuffer, emit("stderr"));
1186
+ let result;
1187
+ try {
1188
+ result = await subprocess;
1189
+ } catch (err) {
1190
+ if (timedOut) throw new BashTimeoutError(normalizedTimeoutMs);
1191
+ throw err;
1192
+ } finally {
1193
+ clearTimeout(timer);
1194
+ if (forceTimer) clearTimeout(forceTimer);
1195
+ }
1196
+ if (timedOut) {
1197
+ throw new BashTimeoutError(normalizedTimeoutMs);
1198
+ }
1199
+ if (result.failed && result.exitCode == null && result.signal == null && !result.isTerminated) {
1200
+ throw new Error(result.shortMessage || result.message || "\u547D\u4EE4\u542F\u52A8\u5931\u8D25");
1201
+ }
1202
+ const truncated = stdoutState.truncated || stderrState.truncated;
1203
+ return {
1204
+ stdout: decodeLimited(stdoutState, useTty),
1205
+ stderr: decodeLimited(stderrState),
1206
+ exitCode: result.exitCode ?? null,
1207
+ signal: result.signal ?? null,
1208
+ durationMs: result.durationMs ?? 0,
1209
+ ...truncated ? { truncated: true } : {}
1210
+ };
1211
+ }
1212
+ var BashTimeoutError, DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, DEFAULT_MAX_BUFFER, cachedShell, FORCE_KILL_AFTER_DELAY_MS, TTY_HELPER, ANSI_PATTERN;
1213
+ var init_bash_executor = __esm({
1214
+ "src/bridge/bash-executor.ts"() {
1215
+ "use strict";
1216
+ init_workspace_manager();
1217
+ BashTimeoutError = class extends Error {
1218
+ code = "TIMEOUT";
1219
+ timeoutMs;
1220
+ constructor(timeoutMs) {
1221
+ super(`\u547D\u4EE4\u6267\u884C\u8D85\u65F6 (${timeoutMs / 1e3}s)`);
1222
+ this.name = "BashTimeoutError";
1223
+ this.timeoutMs = timeoutMs;
1224
+ }
1225
+ };
1226
+ DEFAULT_TIMEOUT_MS = 3e4;
1227
+ MAX_TIMEOUT_MS = 6e5;
1228
+ DEFAULT_MAX_BUFFER = 512 * 1024;
1229
+ cachedShell = null;
1230
+ FORCE_KILL_AFTER_DELAY_MS = 2e3;
1231
+ TTY_HELPER = `
1232
+ import errno, os, sys
1233
+ cmd = os.environ.get("BASH_TTY_COMMAND") or ""
1234
+ shell = os.environ.get("BASH_TTY_SHELL") or "/bin/bash"
1235
+ if not cmd:
1236
+ sys.exit(127)
1237
+ import pty
1238
+ pid, fd = pty.fork()
1239
+ if pid == 0:
1240
+ os.environ.pop("BASH_TTY_COMMAND", None)
1241
+ os.environ.pop("BASH_TTY_SHELL", None)
1242
+ os.environ["TERM"] = "xterm-256color"
1243
+ try:
1244
+ # stdout/stderr \u4ECD\u662F\u7EC8\u7AEF\uFF1Bstdin \u6362\u6210 /dev/null\uFF0C\u8BFB\u53D6\u8F93\u5165\u7684\u547D\u4EE4\u4F1A\u7ACB\u523B\u9047\u5230 EOF
1245
+ null_fd = os.open(os.devnull, os.O_RDONLY)
1246
+ os.dup2(null_fd, 0)
1247
+ os.close(null_fd)
1248
+ os.execvp(shell, [shell, "-c", cmd])
1249
+ except OSError:
1250
+ os._exit(127)
1251
+ while True:
1252
+ try:
1253
+ data = os.read(fd, 65536)
1254
+ except OSError as exc:
1255
+ if exc.errno == errno.EINTR:
1256
+ continue
1257
+ break
1258
+ if not data:
1259
+ break
1260
+ try:
1261
+ os.write(1, data)
1262
+ except OSError:
1263
+ break
1264
+ try:
1265
+ _, status = os.waitpid(pid, 0)
1266
+ except OSError:
1267
+ sys.exit(1)
1268
+ if os.WIFEXITED(status):
1269
+ sys.exit(os.WEXITSTATUS(status))
1270
+ if os.WIFSIGNALED(status):
1271
+ sys.exit(128 + os.WTERMSIG(status))
1272
+ sys.exit(1)
1273
+ `;
1274
+ ANSI_PATTERN = /\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007]*(?:\u0007|\u001B\\)|[@-Z\\-_])/g;
1275
+ }
1276
+ });
1277
+
1278
+ // src/bridge/directory-picker.ts
1279
+ import { spawn as spawn2 } from "child_process";
1280
+ async function pickDirectory(optionsOrTitle) {
1281
+ const options = typeof optionsOrTitle === "string" ? { title: optionsOrTitle } : optionsOrTitle || {};
1282
+ const title = options.title || "\u8BF7\u9009\u62E9\u5DE5\u4F5C\u7A7A\u95F4\u6587\u4EF6\u5939";
1283
+ const defaultPath = options.defaultPath && typeof options.defaultPath === "string" ? options.defaultPath.trim() : void 0;
1284
+ const platform = process.platform;
1285
+ if (platform === "darwin") {
1286
+ return pickDirectoryMac(title, defaultPath);
1287
+ }
1288
+ if (platform === "win32") {
1289
+ return pickDirectoryWindows(title, defaultPath);
1290
+ }
1291
+ return pickDirectoryLinux(title, defaultPath);
1292
+ }
1293
+ function pickDirectoryMac(title, defaultPath) {
1294
+ const safeTitle = title.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
1295
+ const defaultClause = defaultPath ? ` default location POSIX file "${defaultPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` : "";
1296
+ const appleScript = `POSIX path of (choose folder with prompt "${safeTitle}"${defaultClause})`;
1297
+ return new Promise((resolve3, reject) => {
1298
+ const child = spawn2("osascript", ["-e", appleScript], {
1299
+ stdio: ["ignore", "pipe", "pipe"]
1300
+ });
1301
+ let stdout = "";
1302
+ let stderr = "";
1303
+ child.stdout?.on("data", (d) => {
1304
+ stdout += d.toString();
1305
+ });
1306
+ child.stderr?.on("data", (d) => {
1307
+ stderr += d.toString();
1308
+ });
1309
+ child.on("close", (code) => {
1310
+ if (code === 0) {
1311
+ const selected = stdout.trim();
1312
+ resolve3(selected || null);
1313
+ return;
1314
+ }
1315
+ if (code === 1 && (stderr.includes("User canceled") || stderr.includes("-128") || !stderr.trim())) {
1316
+ resolve3(null);
1317
+ return;
1318
+ }
1319
+ reject(new Error(`\u5524\u8D77\u7CFB\u7EDF\u6587\u4EF6\u5939\u9009\u62E9\u5668\u5931\u8D25: ${stderr.trim() || `\u9000\u51FA\u7801 ${code}`}`));
1320
+ });
1321
+ child.on("error", (err) => {
1322
+ reject(new Error(`\u5524\u8D77\u7CFB\u7EDF\u6587\u4EF6\u5939\u9009\u62E9\u5668\u5931\u8D25: ${err.message}`));
1323
+ });
1324
+ });
1325
+ }
1326
+ function escapePowerShellString(str) {
1327
+ return str.replace(/`/g, "``").replace(/"/g, '`"').replace(/\$/g, "`$");
1328
+ }
1329
+ function pickDirectoryWindows(title, defaultPath) {
1330
+ const safeTitle = escapePowerShellString(title);
1331
+ const safeDefaultPath = escapePowerShellString(defaultPath ?? "");
1332
+ const psScript = `
1333
+ $code = @'
1334
+ using System;
1335
+ using System.Runtime.InteropServices;
1336
+
1337
+ [ComImport, Guid("D57C7288-D4AD-4768-BE02-9D969532D960"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
1338
+ interface IFileOpenDialog {
1339
+ [PreserveSig] int Show(IntPtr hwnd);
1340
+ void SetFileTypes(uint cFileTypes, IntPtr rgFilterSpec);
1341
+ void SetFileTypeIndex(uint iFileType);
1342
+ void GetFileTypeIndex(out uint piFileType);
1343
+ void Advise(IntPtr pfde, out uint pdwCookie);
1344
+ void Unadvise(uint dwCookie);
1345
+ void SetOptions(uint fos);
1346
+ void GetOptions(out uint pfos);
1347
+ void SetDefaultFolder(IntPtr psi);
1348
+ void SetFolder(IntPtr psi);
1349
+ void GetFolder(out IntPtr ppsi);
1350
+ void GetCurrentSelection(out IntPtr ppsi);
1351
+ void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string pszName);
1352
+ void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
1353
+ void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
1354
+ void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string pszText);
1355
+ void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
1356
+ void GetResult(out IntPtr ppsi);
1357
+ void AddPlace(IntPtr psi, int fdap);
1358
+ void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
1359
+ void Close(int hr);
1360
+ void SetClientGuid([In] ref Guid guid);
1361
+ void ClearClientData();
1362
+ void SetFilter(IntPtr pFilter);
1363
+ void GetResults(out IntPtr ppenum);
1364
+ void GetSelectedItems(out IntPtr ppsai);
1365
+ }
1366
+
1367
+ [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
1368
+ interface IShellItem {
1369
+ void BindToHandler(IntPtr pbc, [In] ref Guid bhid, [In] ref Guid riid, out IntPtr ppv);
1370
+ void GetParent(out IShellItem ppsi);
1371
+ void GetDisplayName(uint sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
1372
+ void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);
1373
+ void Compare(IShellItem psi, uint hint, out int piOrder);
1374
+ }
1375
+
1376
+ public static class FolderPicker {
1377
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
1378
+ static extern int SHCreateItemFromParsingName(string pszPath, IntPtr pbc, [In] ref Guid riid, out IntPtr ppv);
1379
+
1380
+ // FOS_PICKFOLDERS = 0x20, FOS_FORCEFILESYSTEM = 0x40
1381
+ const uint FOS_PICKFOLDERS = 0x00000020;
1382
+ const uint FOS_FORCEFILESYSTEM = 0x00000040;
1383
+
1384
+ public static string Pick(string title, string defaultPath) {
1385
+ var clsid = new Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7");
1386
+ var riid = new Guid("D57C7288-D4AD-4768-BE02-9D969532D960");
1387
+ var obj = Activator.CreateInstance(Type.GetTypeFromCLSID(clsid));
1388
+ var dialog = (IFileOpenDialog)obj;
1389
+ dialog.SetOptions(FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM);
1390
+ dialog.SetTitle(title);
1391
+ if (!string.IsNullOrEmpty(defaultPath)) {
1392
+ var riidShellItem = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE");
1393
+ IntPtr psi;
1394
+ if (SHCreateItemFromParsingName(defaultPath, IntPtr.Zero, ref riidShellItem, out psi) == 0) {
1395
+ dialog.SetFolder(psi);
1396
+ Marshal.Release(psi);
1397
+ }
1398
+ }
1399
+ int hr = dialog.Show(IntPtr.Zero);
1400
+ if (hr != 0) return null; // \u7528\u6237\u53D6\u6D88 (HRESULT_FROM_WIN32(ERROR_CANCELLED) = 0x800704C7)
1401
+ IntPtr ppsi;
1402
+ dialog.GetResult(out ppsi);
1403
+ var shellItem = (IShellItem)Marshal.GetTypedObjectForIUnknown(ppsi, typeof(IShellItem));
1404
+ string path;
1405
+ shellItem.GetDisplayName(0x80058000, out path); // SIGDN_FILESYSPATH
1406
+ Marshal.Release(ppsi);
1407
+ return path;
1408
+ }
1409
+ }
1410
+ '@
1411
+ Add-Type -TypeDefinition $code
1412
+ $result = [FolderPicker]::Pick("${safeTitle}", "${safeDefaultPath}")
1413
+ if ($result) { Write-Output $result }
1414
+ `;
1415
+ return new Promise((resolve3, reject) => {
1416
+ const child = spawn2("powershell", ["-STA", "-NoProfile", "-WindowStyle", "Hidden", "-Command", psScript], {
1417
+ stdio: ["ignore", "pipe", "pipe"],
1418
+ windowsHide: true
1419
+ });
1420
+ let stdout = "";
1421
+ let stderr = "";
1422
+ child.stdout?.on("data", (d) => {
1423
+ stdout += d.toString();
1424
+ });
1425
+ child.stderr?.on("data", (d) => {
1426
+ stderr += d.toString();
1427
+ });
1428
+ child.on("close", (code) => {
1429
+ if (code === 0) {
1430
+ const selected = stdout.trim();
1431
+ resolve3(selected || null);
1432
+ return;
1433
+ }
1434
+ reject(new Error(`PowerShell \u6587\u4EF6\u5939\u9009\u62E9\u5668\u6267\u884C\u5931\u8D25: ${stderr.trim() || `\u9000\u51FA\u7801 ${code}`}`));
1435
+ });
1436
+ child.on("error", (err) => {
1437
+ reject(new Error(`\u5524\u8D77 PowerShell \u6587\u4EF6\u5939\u9009\u62E9\u5668\u5931\u8D25: ${err.message}`));
1438
+ });
1439
+ });
1440
+ }
1441
+ function pickDirectoryLinux(title, defaultPath) {
1442
+ const args = ["--file-selection", "--directory", `--title=${title}`];
1443
+ if (defaultPath) {
1444
+ args.push(`--filename=${defaultPath}`);
1445
+ }
1446
+ return new Promise((resolve3, reject) => {
1447
+ const child = spawn2("zenity", args, {
1448
+ stdio: ["ignore", "pipe", "pipe"]
1449
+ });
1450
+ let stdout = "";
1451
+ let stderr = "";
1452
+ child.stdout?.on("data", (d) => {
1453
+ stdout += d.toString();
1454
+ });
1455
+ child.stderr?.on("data", (d) => {
1456
+ stderr += d.toString();
1457
+ });
1458
+ child.on("close", (code) => {
1459
+ if (code === 0) {
1460
+ const selected = stdout.trim();
1461
+ resolve3(selected || null);
1462
+ return;
1463
+ }
1464
+ if (code === 1) {
1465
+ resolve3(null);
1466
+ return;
1467
+ }
1468
+ reject(new Error(`zenity \u76EE\u5F55\u9009\u62E9\u5668\u5F02\u5E38\u9000\u51FA (\u9000\u51FA\u7801 ${code}): ${stderr.trim()}`));
1469
+ });
1470
+ child.on("error", (err) => {
1471
+ if (err?.code === "ENOENT") {
1472
+ 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)"));
1473
+ return;
1474
+ }
1475
+ reject(new Error(`\u5524\u8D77 zenity \u76EE\u5F55\u9009\u62E9\u5668\u5931\u8D25: ${err.message}`));
1476
+ });
1477
+ });
1478
+ }
1479
+ var init_directory_picker = __esm({
1480
+ "src/bridge/directory-picker.ts"() {
1481
+ "use strict";
1482
+ }
1483
+ });
1484
+
1485
+ // src/bridge/pty-backend.ts
1486
+ import { spawnSync as spawnSync2 } from "child_process";
1487
+ import { chmodSync, existsSync } from "fs";
1488
+ import { createRequire } from "module";
1489
+ import path4 from "path";
1490
+ import { constants } from "os";
1491
+ function interactiveArgs(shell) {
1492
+ if (process.platform !== "win32") return ["-i"];
1493
+ const base = path4.basename(shell).toLowerCase();
1494
+ if (base === "powershell.exe" || base === "pwsh.exe") return ["-NoLogo"];
1495
+ if (base === "cmd.exe") return [];
1496
+ return ["-i"];
1497
+ }
1498
+ function ptyEnvironment() {
1499
+ const env = {};
1500
+ for (const [key, value] of Object.entries(process.env)) {
1501
+ if (value !== void 0) env[key] = value;
1502
+ }
1503
+ env.TERM = "xterm-256color";
1504
+ return env;
1505
+ }
1506
+ function resolveSpawnFile(shell, pathEnv = process.env.PATH || "") {
1507
+ if (!shell || path4.isAbsolute(shell)) return shell;
1508
+ const names = process.platform === "win32" && !shell.toLowerCase().endsWith(".exe") ? [shell, `${shell}.exe`] : [shell];
1509
+ for (const dir of pathEnv.split(path4.delimiter)) {
1510
+ if (!dir) continue;
1511
+ for (const name of names) {
1512
+ const candidate = path4.join(dir, name);
1513
+ try {
1514
+ if (existsSync(candidate)) return candidate;
1515
+ } catch {
1516
+ }
1517
+ }
1518
+ }
1519
+ if (process.platform === "win32") {
1520
+ const systemRoot = process.env.SystemRoot || "C:\\Windows";
1521
+ const fallbacks = [
1522
+ path4.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
1523
+ path4.join(systemRoot, "Sysnative", "WindowsPowerShell", "v1.0", "powershell.exe")
1524
+ ];
1525
+ for (const candidate of fallbacks) {
1526
+ try {
1527
+ if (existsSync(candidate)) return candidate;
1528
+ } catch {
1529
+ }
1530
+ }
1531
+ }
1532
+ return shell;
1533
+ }
1534
+ function describeSpawnHelperChmodError(helper, code) {
1535
+ if (code !== "EPERM" && code !== "EACCES") return null;
1536
+ return `spawn-helper \u65E0\u6CD5\u8BBE\u7F6E\u4E3A\u53EF\u6267\u884C\uFF08${helper}\uFF09\u3002\u5F53\u524D\u7528\u6237\u6CA1\u6709\u6743\u9650\u4FEE\u6539\u8BE5\u6587\u4EF6\u3002\u8BF7\u7528\u5B89\u88C5\u65F6\u7684\u7528\u6237\u91CD\u65B0\u5B89\u88C5 @opentiny/webmcp-cli\uFF0C\u6216\u5BF9\u8BE5\u6587\u4EF6\u6267\u884C chmod 755\u3002`;
1537
+ }
1538
+ function loadNodePty() {
1539
+ try {
1540
+ return createRequire(import.meta.url)("node-pty");
1541
+ } catch (err) {
1542
+ const detail = err instanceof Error ? err.message : String(err);
1543
+ throw new Error(`\u4EA4\u4E92\u7EC8\u7AEF\u4E0D\u53EF\u7528\uFF1A\u672A\u80FD\u52A0\u8F7D node-pty\uFF08${detail}\uFF09\u3002\u5176\u4F59\u6865\u63A5\u547D\u4EE4\u4ECD\u53EF\u4F7F\u7528\u3002`);
1544
+ }
1545
+ }
1546
+ function spawnHelperPath() {
1547
+ try {
1548
+ const pkgJson = createRequire(import.meta.url).resolve("node-pty/package.json");
1549
+ return path4.join(path4.dirname(pkgJson), "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper");
1550
+ } catch {
1551
+ return null;
1552
+ }
1553
+ }
1554
+ function ensureSpawnHelper() {
1555
+ if (process.platform === "win32") return null;
1556
+ const helper = spawnHelperPath();
1557
+ if (!helper || !existsSync(helper)) return null;
1558
+ try {
1559
+ chmodSync(helper, 493);
1560
+ return null;
1561
+ } catch (err) {
1562
+ const code = err && typeof err === "object" && "code" in err ? String(err.code) : void 0;
1563
+ return describeSpawnHelperChmodError(helper, code);
1564
+ }
1565
+ }
1566
+ function signalName(code) {
1567
+ if (!code) return null;
1568
+ for (const [name, value] of Object.entries(constants.signals)) {
1569
+ if (value === code) return name;
1570
+ }
1571
+ return String(code);
1572
+ }
1573
+ function descendantPids(rootPid) {
1574
+ const result = spawnSync2("ps", ["-ax", "-o", "pid=,ppid="], { encoding: "utf8", timeout: 3e3 });
1575
+ if (result.status !== 0 || !result.stdout) return [];
1576
+ const children = /* @__PURE__ */ new Map();
1577
+ for (const line of result.stdout.split("\n")) {
1578
+ const [pidText, ppidText] = line.trim().split(/\s+/);
1579
+ const pid = Number(pidText);
1580
+ const ppid = Number(ppidText);
1581
+ if (!pid || !ppid) continue;
1582
+ const list = children.get(ppid);
1583
+ if (list) list.push(pid);
1584
+ else children.set(ppid, [pid]);
1585
+ }
1586
+ const out = [];
1587
+ const walk = (pid) => {
1588
+ for (const child of children.get(pid) || []) {
1589
+ walk(child);
1590
+ out.push(child);
1591
+ }
1592
+ };
1593
+ walk(rootPid);
1594
+ return out;
1595
+ }
1596
+ function killPtySession(term) {
1597
+ const pid = term.pid;
1598
+ if (pid && pid > 0) {
1599
+ if (process.platform === "win32") {
1600
+ try {
1601
+ spawnSync2("taskkill", ["/pid", String(pid), "/T", "/F"], { windowsHide: true, timeout: 3e3 });
1602
+ } catch {
1603
+ }
1604
+ } else {
1605
+ for (const victim of [...descendantPids(pid), pid]) {
1606
+ try {
1607
+ process.kill(victim, "SIGKILL");
1608
+ } catch {
1609
+ }
1610
+ }
1611
+ }
1612
+ }
1613
+ try {
1614
+ term.kill("SIGHUP");
1615
+ } catch {
1616
+ }
1617
+ }
1618
+ function spawnHostPty(options) {
1619
+ const pty = loadNodePty();
1620
+ const helperError = ensureSpawnHelper();
1621
+ const shell = resolveSpawnFile(options.shell || resolveShell());
1622
+ const pending = [];
1623
+ let dataCb = null;
1624
+ let exitCb = null;
1625
+ let pendingExit = null;
1626
+ let settled = false;
1627
+ let term = null;
1628
+ const emitData = (data) => {
1629
+ if (!data) return;
1630
+ if (dataCb) dataCb(data);
1631
+ else pending.push(data);
1632
+ };
1633
+ const finish = (info) => {
1634
+ if (settled) return;
1635
+ settled = true;
1636
+ if (exitCb) exitCb(info);
1637
+ else pendingExit = info;
1638
+ };
1639
+ try {
1640
+ term = pty.spawn(shell, interactiveArgs(shell), {
1641
+ name: "xterm-256color",
1642
+ cols: options.cols,
1643
+ rows: options.rows,
1644
+ cwd: options.cwd,
1645
+ env: ptyEnvironment()
1646
+ });
1647
+ term.onData((data) => emitData(data));
1648
+ term.onExit((event) => {
1649
+ finish({ exitCode: event.exitCode, signal: signalName(event.signal) });
1650
+ });
1651
+ } catch (err) {
1652
+ const message = err instanceof Error ? err.message : String(err);
1653
+ const detail = helperError ? `${helperError} ${message}` : message;
1654
+ setImmediate(() => {
1655
+ emitData(`\r
1656
+ [\u7EC8\u7AEF\u542F\u52A8\u5931\u8D25] ${detail}\r
1657
+ `);
1658
+ finish({ exitCode: null, signal: null });
1659
+ });
1660
+ }
1661
+ return {
1662
+ write(data) {
1663
+ try {
1664
+ term?.write(data);
1665
+ } catch {
1666
+ }
1667
+ },
1668
+ resize(cols, rows) {
1669
+ try {
1670
+ term?.resize(cols, rows);
1671
+ } catch {
1672
+ }
1673
+ },
1674
+ kill() {
1675
+ if (term) killPtySession(term);
1676
+ },
1677
+ pause() {
1678
+ try {
1679
+ term?.pause();
1680
+ } catch {
1681
+ }
1682
+ },
1683
+ resume() {
1684
+ try {
1685
+ term?.resume();
1686
+ } catch {
1687
+ }
1688
+ },
1689
+ onData(cb) {
1690
+ dataCb = cb;
1691
+ for (const chunk of pending) cb(chunk);
1692
+ pending.length = 0;
1693
+ },
1694
+ onExit(cb) {
1695
+ exitCb = cb;
1696
+ if (pendingExit) cb(pendingExit);
1697
+ }
1698
+ };
1699
+ }
1700
+ var init_pty_backend = __esm({
1701
+ "src/bridge/pty-backend.ts"() {
1702
+ "use strict";
1703
+ init_bash_executor();
1704
+ }
1705
+ });
1706
+
1707
+ // src/bridge/terminal-session.ts
1708
+ import { randomUUID } from "crypto";
1709
+ function applyTerminalBackpressure(bufferedAmount, flow) {
1710
+ if (bufferedAmount > TERMINAL_OUTPUT_HIGH_WATER) flow.pauseOutput();
1711
+ else if (bufferedAmount <= TERMINAL_OUTPUT_HIGH_WATER / 2) flow.resumeOutput();
1712
+ }
1713
+ function clampDimension(value, fallback) {
1714
+ const parsed = typeof value === "number" ? value : Number(value);
1715
+ if (!Number.isFinite(parsed)) return fallback;
1716
+ return Math.max(2, Math.min(500, Math.floor(parsed)));
1717
+ }
1718
+ var OUTPUT_CHUNK, MAX_INPUT, DEFAULT_COALESCE_MS, TERMINAL_OUTPUT_HIGH_WATER, TerminalSessionManager;
1719
+ var init_terminal_session = __esm({
1720
+ "src/bridge/terminal-session.ts"() {
1721
+ "use strict";
1722
+ init_workspace_manager();
1723
+ init_pty_backend();
1724
+ init_protocol();
1725
+ OUTPUT_CHUNK = 32 * 1024;
1726
+ MAX_INPUT = 64 * 1024;
1727
+ DEFAULT_COALESCE_MS = 16;
1728
+ TERMINAL_OUTPUT_HIGH_WATER = 1024 * 1024;
1729
+ TerminalSessionManager = class {
1730
+ session = null;
1731
+ buffer = "";
1732
+ timer = null;
1733
+ send;
1734
+ spawnPty;
1735
+ coalesceMs;
1736
+ constructor(options) {
1737
+ this.send = options.send;
1738
+ this.spawnPty = options.spawnPty ?? ((opts) => spawnHostPty(opts));
1739
+ this.coalesceMs = options.coalesceMs ?? DEFAULT_COALESCE_MS;
1740
+ }
1741
+ open(params = {}) {
1742
+ const cwd = resolveWorkspaceDir(params);
1743
+ const cols = clampDimension(params.cols, 80);
1744
+ const rows = clampDimension(params.rows, 24);
1745
+ this.closeActive();
1746
+ const id = randomUUID();
1747
+ const pty = this.spawnPty({ cwd, cols, rows });
1748
+ this.session = { id, pty, cwd };
1749
+ pty.onData((data) => this.pushOutput(id, data));
1750
+ pty.onExit((info) => {
1751
+ if (this.session?.id !== id) return;
1752
+ this.flush(id);
1753
+ this.session = null;
1754
+ this.send({
1755
+ jsonrpc: "2.0",
1756
+ method: TERMINAL_EVENTS.EXIT,
1757
+ params: {
1758
+ sessionId: id,
1759
+ exitCode: info.exitCode,
1760
+ signal: info.signal
1761
+ }
1762
+ });
1763
+ });
1764
+ return { sessionId: id, cwd };
1765
+ }
1766
+ input(params) {
1767
+ const session = this.requireSession(params.sessionId);
1768
+ if (typeof params.data !== "string") {
1769
+ throw new BashInvalidParamsError("data \u5FC5\u987B\u662F\u5B57\u7B26\u4E32");
1770
+ }
1771
+ if (params.data.length > MAX_INPUT) {
1772
+ throw new BashInvalidParamsError("\u5355\u6B21\u8F93\u5165\u8FC7\u957F");
1773
+ }
1774
+ session.pty.write(params.data);
1775
+ return { ok: true };
1776
+ }
1777
+ resize(params) {
1778
+ const session = this.requireSession(params.sessionId);
1779
+ session.pty.resize(clampDimension(params.cols, 80), clampDimension(params.rows, 24));
1780
+ return { ok: true };
1781
+ }
1782
+ close(params = {}) {
1783
+ if (!this.session || params.sessionId && params.sessionId !== this.session.id) {
1784
+ return { ok: true };
1785
+ }
1786
+ this.closeActive();
1787
+ return { ok: true };
1788
+ }
1789
+ disposeAll() {
1790
+ this.closeActive();
1791
+ }
1792
+ pauseOutput() {
1793
+ try {
1794
+ this.session?.pty.pause();
1795
+ } catch {
1796
+ }
1797
+ }
1798
+ resumeOutput() {
1799
+ try {
1800
+ this.session?.pty.resume();
1801
+ } catch {
1802
+ }
1803
+ }
1804
+ requireSession(sessionId) {
1805
+ if (!this.session || !sessionId || sessionId !== this.session.id) {
1806
+ throw new Error("\u7EC8\u7AEF\u4F1A\u8BDD\u4E0D\u5B58\u5728");
1807
+ }
1808
+ return this.session;
1809
+ }
1810
+ closeActive() {
1811
+ const current = this.session;
1812
+ this.session = null;
1813
+ this.buffer = "";
1814
+ if (this.timer) {
1815
+ clearTimeout(this.timer);
1816
+ this.timer = null;
1817
+ }
1818
+ current?.pty.kill();
1819
+ }
1820
+ pushOutput(sessionId, chunk) {
1821
+ if (this.session?.id !== sessionId || !chunk) return;
1822
+ this.buffer += chunk;
1823
+ this.flushFullChunks(sessionId);
1824
+ if (!this.buffer) return;
1825
+ if (this.coalesceMs <= 0) {
1826
+ this.flush(sessionId);
1827
+ return;
1828
+ }
1829
+ if (!this.timer) {
1830
+ this.timer = setTimeout(() => this.flush(sessionId), this.coalesceMs);
1831
+ }
1832
+ }
1833
+ flushFullChunks(sessionId) {
1834
+ while (this.buffer.length >= OUTPUT_CHUNK) {
1835
+ const data = this.buffer.slice(0, OUTPUT_CHUNK);
1836
+ this.buffer = this.buffer.slice(OUTPUT_CHUNK);
1837
+ this.emitOutput(sessionId, data);
1838
+ }
1839
+ }
1840
+ flush(sessionId) {
1841
+ if (this.timer) {
1842
+ clearTimeout(this.timer);
1843
+ this.timer = null;
1844
+ }
1845
+ if (!this.buffer || this.session?.id !== sessionId) {
1846
+ this.buffer = "";
1847
+ return;
1848
+ }
1849
+ const data = this.buffer;
1850
+ this.buffer = "";
1851
+ this.emitOutput(sessionId, data);
1852
+ }
1853
+ emitOutput(sessionId, data) {
1854
+ this.send({
1855
+ jsonrpc: "2.0",
1856
+ method: TERMINAL_EVENTS.OUTPUT,
1857
+ params: { sessionId, data }
1858
+ });
1859
+ }
1860
+ };
1861
+ }
1862
+ });
1863
+
1864
+ // src/bridge/bridge-client.ts
1865
+ var bridge_client_exports = {};
1866
+ __export(bridge_client_exports, {
1867
+ BRIDGE_ERROR_CODE: () => BRIDGE_ERROR_CODE,
1868
+ ExtensionBridgeClient: () => ExtensionBridgeClient,
1869
+ PROTOCOL_VERSION: () => PROTOCOL_VERSION,
1870
+ computeHmac: () => computeHmac,
1871
+ deriveSharedSecret: () => deriveSharedSecret,
1872
+ getKillPortHint: () => getKillPortHint,
1873
+ resolveOrCreateAuthToken: () => resolveOrCreateAuthToken,
1874
+ verifyHmacConstantTime: () => verifyHmacConstantTime
1875
+ });
1876
+ import { WebSocketServer, WebSocket as WsClient } from "ws";
1877
+ import { EventEmitter } from "events";
1878
+ import { randomUUID as randomUUID2, randomBytes, createHmac, createHash, timingSafeEqual } from "crypto";
1879
+ import fs4 from "fs";
1880
+ import path5 from "path";
1881
+ import os3 from "os";
1882
+ function isJsonRpcId(id) {
1883
+ if (id === null || typeof id === "string") return true;
1884
+ return typeof id === "number" && Number.isFinite(id);
1885
+ }
1886
+ function resolveOrCreateAuthToken(explicitToken) {
1887
+ if (explicitToken && explicitToken.trim()) {
1888
+ const token = explicitToken.trim();
1889
+ try {
1890
+ if (!fs4.existsSync(TOKEN_FILE_DIR)) {
1891
+ fs4.mkdirSync(TOKEN_FILE_DIR, { mode: 448, recursive: true });
1892
+ }
1893
+ fs4.writeFileSync(TOKEN_FILE_PATH, token, { mode: 384, encoding: "utf8" });
1894
+ } catch {
1895
+ }
1896
+ return token;
1897
+ }
1898
+ if (process.env.ROBOT_WXT_BRIDGE_TOKEN) {
1899
+ return process.env.ROBOT_WXT_BRIDGE_TOKEN.trim();
1900
+ }
1901
+ try {
1902
+ if (fs4.existsSync(TOKEN_FILE_PATH)) {
1903
+ const existing = fs4.readFileSync(TOKEN_FILE_PATH, "utf8").trim();
1904
+ if (existing) return existing;
1905
+ }
1906
+ } catch {
1907
+ }
1908
+ const newToken = randomBytes(32).toString("hex");
1909
+ try {
1910
+ if (!fs4.existsSync(TOKEN_FILE_DIR)) {
1911
+ fs4.mkdirSync(TOKEN_FILE_DIR, { mode: 448, recursive: true });
1912
+ }
1913
+ fs4.writeFileSync(TOKEN_FILE_PATH, newToken, { mode: 384, encoding: "utf8" });
1914
+ } catch {
1915
+ }
1916
+ return newToken;
1917
+ }
1918
+ function parseMajorVersion(v) {
1919
+ return parseInt(v.split(".")[0] ?? "0", 10);
1920
+ }
1921
+ function deriveSharedSecret(tokenOrExtensionId, hmacSalt) {
1922
+ return createHash("sha256").update(`${tokenOrExtensionId}:${hmacSalt}`).digest();
1923
+ }
1924
+ function computeHmac(secret, challenge) {
1925
+ return createHmac("sha256", secret).update(challenge).digest("hex");
1926
+ }
1927
+ function verifyHmacConstantTime(actualHex, expectedHex) {
1928
+ if (!actualHex || typeof actualHex !== "string") return false;
1929
+ try {
1930
+ const actualBuf = Buffer.from(actualHex, "hex");
1931
+ const expectedBuf = Buffer.from(expectedHex, "hex");
1932
+ if (actualBuf.length !== expectedBuf.length) return false;
1933
+ return timingSafeEqual(actualBuf, expectedBuf);
1934
+ } catch {
1935
+ return false;
1936
+ }
1937
+ }
1938
+ function getKillPortHint(port) {
1939
+ if (process.platform === "win32") {
1940
+ return `netstat -ano | findstr :${port} \uFF08\u627E\u5230 PID \u540E\u6267\u884C: taskkill /pid <PID> /T /F\uFF09`;
1941
+ }
1942
+ return `lsof -ti:${port} | xargs kill -9`;
1943
+ }
1944
+ var WS_PORT, REQUEST_TIMEOUT_MS, HANDSHAKE_TIMEOUT_MS, WS_OPEN, TOKEN_FILE_DIR, TOKEN_FILE_PATH, ExtensionBridgeClient;
1945
+ var init_bridge_client = __esm({
1946
+ "src/bridge/bridge-client.ts"() {
1947
+ "use strict";
1948
+ init_protocol();
1949
+ init_bash_executor();
1950
+ init_directory_picker();
1951
+ init_terminal_session();
1952
+ WS_PORT = DEFAULT_WS_PORT;
1953
+ REQUEST_TIMEOUT_MS = 3e4;
1954
+ HANDSHAKE_TIMEOUT_MS = 5e3;
1955
+ WS_OPEN = 1;
1956
+ TOKEN_FILE_DIR = path5.join(os3.homedir(), ".robot-wxt");
1957
+ TOKEN_FILE_PATH = path5.join(TOKEN_FILE_DIR, "bridge-token");
1958
+ ExtensionBridgeClient = class _ExtensionBridgeClient extends EventEmitter {
1959
+ constructor(port = WS_PORT, authToken) {
1960
+ super();
1961
+ this.port = port;
1962
+ this.explicitAuthToken = authToken;
1963
+ this.authToken = authToken ?? resolveOrCreateAuthToken();
1964
+ }
1965
+ port;
1966
+ wss = null;
1967
+ extensionSocket = null;
1968
+ clientSocket = null;
1969
+ forwardedRequests = /* @__PURE__ */ new Map();
1970
+ pending = /* @__PURE__ */ new Map();
1971
+ socketAuthStates = /* @__PURE__ */ new Map();
1972
+ destroyed = false;
1973
+ terminalSessions = null;
1974
+ idCounter = 0;
1975
+ isClientMode = false;
1976
+ explicitAuthToken;
1977
+ authToken;
1978
+ /** 获取当前服务端使用的认证 Token */
1979
+ get currentAuthToken() {
1980
+ return this.authToken;
1981
+ }
1982
+ /** 获取当前激活的 Socket */
1983
+ _getActiveSocket() {
1984
+ if (this.isClientMode && this.clientSocket) {
1985
+ return this.clientSocket.readyState === WS_OPEN ? this.clientSocket : null;
1986
+ }
1987
+ if (this.extensionSocket && this.extensionSocket.readyState === WS_OPEN) {
1988
+ return this.extensionSocket;
1989
+ }
1990
+ return null;
1991
+ }
1992
+ /** 是否已有就绪的扩展连接(或作为 Client 已连接到 Server) */
1993
+ get isConnected() {
1994
+ return this._getActiveSocket() != null;
1995
+ }
1996
+ /** 等待扩展连接或作为客户端连入服务就绪 */
1997
+ async waitForReady(timeoutMs = 5e3) {
1998
+ if (this.isConnected) return true;
1999
+ return new Promise((resolve3) => {
2000
+ const timer = setTimeout(() => {
2001
+ cleanup();
2002
+ resolve3(this.isConnected);
2003
+ }, timeoutMs);
2004
+ const cleanup = () => {
2005
+ clearTimeout(timer);
2006
+ this.off("connected", onConnected);
2007
+ };
2008
+ const onConnected = () => {
2009
+ cleanup();
2010
+ resolve3(true);
2011
+ };
2012
+ this.on("connected", onConnected);
2013
+ });
2014
+ }
2015
+ /**
2016
+ * 静态探测目标端口的桥接服务状态
2017
+ */
2018
+ static async probe(port = WS_PORT, authToken, timeoutMs = 800) {
2019
+ const client = new _ExtensionBridgeClient(port, authToken);
2020
+ try {
2021
+ const res = await client._probeExistingServer(timeoutMs);
2022
+ if (client.clientSocket) {
2023
+ try {
2024
+ client.clientSocket.close(1e3, "Probe finished");
2025
+ } catch {
2026
+ }
2027
+ }
2028
+ if (res.success) {
2029
+ return { running: true, authed: true };
2030
+ }
2031
+ if (res.error) {
2032
+ const isAuthError = res.error.message.includes("HMAC") || res.error.message.includes("\u8BA4\u8BC1\u5931\u8D25") || res.error.message.includes("Unauthorized");
2033
+ if (isAuthError) {
2034
+ return { running: true, authed: false, error: res.error.message };
2035
+ }
2036
+ return { running: false, authed: false, error: res.error.message };
2037
+ }
2038
+ return { running: false, authed: false };
2039
+ } finally {
2040
+ client.destroy();
2041
+ }
2042
+ }
2043
+ /**
2044
+ * 自动探测模式:
2045
+ * 优先尝试连接已存在的 18999 服务;连接不上时退回启动本机的 WebSocketServer。
2046
+ */
2047
+ async startAuto(probeTimeoutMs = 800) {
2048
+ if (this.destroyed) return;
2049
+ const probe = await this._probeExistingServer(probeTimeoutMs);
2050
+ if (probe.success) {
2051
+ return;
2052
+ }
2053
+ if (probe.error) {
2054
+ throw probe.error;
2055
+ }
2056
+ this.connect();
2057
+ }
2058
+ async _probeExistingServer(timeoutMs) {
2059
+ return new Promise((resolve3) => {
2060
+ let settled = false;
2061
+ let connectionEstablished = false;
2062
+ let authFailedReason = null;
2063
+ const ws = new WsClient(`ws://127.0.0.1:${this.port}`);
2064
+ const timer = setTimeout(() => {
2065
+ if (!settled) {
2066
+ settled = true;
2067
+ try {
2068
+ ws.terminate();
2069
+ } catch {
2070
+ }
2071
+ if (authFailedReason) {
2072
+ resolve3({
2073
+ success: false,
2074
+ error: new Error(
2075
+ `\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
2076
+ \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`
2077
+ )
2078
+ });
2079
+ } else if (connectionEstablished) {
2080
+ resolve3({
2081
+ success: false,
2082
+ error: new Error(
2083
+ `\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`
2084
+ )
2085
+ });
2086
+ } else {
2087
+ resolve3({ success: false });
2088
+ }
2089
+ }
2090
+ }, timeoutMs);
2091
+ ws.on("open", () => {
2092
+ connectionEstablished = true;
2093
+ });
2094
+ ws.on("close", (code, reason) => {
2095
+ const reasonStr = reason ? reason.toString() : "";
2096
+ if (code === WS_CLOSE_CODE.UNAUTHORIZED || reasonStr.includes("Unauthorized") || reasonStr.includes("HMAC")) {
2097
+ authFailedReason = reasonStr || "Token \u8BA4\u8BC1\u88AB\u62D2\u7EDD (HMAC verification failed)";
2098
+ }
2099
+ if (!settled && authFailedReason) {
2100
+ settled = true;
2101
+ clearTimeout(timer);
2102
+ resolve3({
2103
+ success: false,
2104
+ error: new Error(
2105
+ `\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
2106
+ \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`
2107
+ )
2108
+ });
2109
+ }
2110
+ });
2111
+ ws.on("message", (data) => {
2112
+ try {
2113
+ const msg = JSON.parse(data.toString());
2114
+ if (msg.type === "BRIDGE_CHALLENGE" && msg.challenge && msg.hmacSalt) {
2115
+ connectionEstablished = true;
2116
+ const secret = deriveSharedSecret(this.authToken, msg.hmacSalt);
2117
+ const hmac = computeHmac(secret, msg.challenge);
2118
+ ws.send(
2119
+ JSON.stringify({
2120
+ type: "BRIDGE_AUTH",
2121
+ clientType: "cli-client",
2122
+ challenge: msg.challenge,
2123
+ hmac
2124
+ })
2125
+ );
2126
+ return;
2127
+ }
2128
+ if (msg.type === "BRIDGE_AUTH_OK" && !settled) {
2129
+ settled = true;
2130
+ clearTimeout(timer);
2131
+ this.isClientMode = true;
2132
+ this.clientSocket = ws;
2133
+ this._bindClientSocket(ws);
2134
+ this.emit("connected");
2135
+ resolve3({ success: true });
2136
+ }
2137
+ } catch {
2138
+ }
2139
+ });
2140
+ ws.once("error", (err) => {
2141
+ if (!settled) {
2142
+ settled = true;
2143
+ clearTimeout(timer);
2144
+ try {
2145
+ ws.terminate();
2146
+ } catch {
2147
+ }
2148
+ if (err?.code === "ECONNREFUSED" || err?.message?.includes("ECONNREFUSED")) {
2149
+ resolve3({ success: false });
2150
+ } else {
2151
+ resolve3({
2152
+ success: false,
2153
+ error: new Error(`\u8FDE\u63A5\u672C\u5730 127.0.0.1:${this.port} \u5931\u8D25: ${err?.message || err}`)
2154
+ });
2155
+ }
2156
+ }
2157
+ });
2158
+ });
2159
+ }
2160
+ _bindClientSocket(ws) {
2161
+ ws.on("message", (data) => {
2162
+ let msg;
2163
+ try {
2164
+ msg = JSON.parse(data.toString());
2165
+ } catch {
2166
+ return;
2167
+ }
2168
+ if (msg.type === "BRIDGE_CHALLENGE" || msg.type === "BRIDGE_AUTH_OK") {
2169
+ return;
2170
+ }
2171
+ if (msg.method === "notification/sub_agent_progress") {
2172
+ this.emit("progress", msg.params);
2173
+ return;
2174
+ }
2175
+ const pending = this.pending.get(String(msg.id));
2176
+ if (!pending) return;
2177
+ this.pending.delete(String(msg.id));
2178
+ clearTimeout(pending.timer);
2179
+ if (msg.error) {
2180
+ pending.reject(new Error(`[${msg.error.code}] ${msg.error.message}`));
2181
+ } else {
2182
+ pending.resolve(msg.result);
2183
+ }
2184
+ });
2185
+ ws.on("close", () => {
2186
+ this.clientSocket = null;
2187
+ this.emit("disconnected");
2188
+ this._rejectAllPending("\u4E0E\u670D\u52A1\u7684\u8FDE\u63A5\u5DF2\u65AD\u5F00");
2189
+ });
2190
+ }
2191
+ /** 启动 WebSocket 服务端,等待 Chrome 扩展(Offscreen Document)连入 */
2192
+ connect() {
2193
+ if (this.destroyed) return;
2194
+ if (this.wss) return;
2195
+ try {
2196
+ this.wss = new WebSocketServer({
2197
+ port: this.port,
2198
+ host: "127.0.0.1",
2199
+ verifyClient: (info, callback) => {
2200
+ const origin = info.origin || info.req.headers.origin;
2201
+ if (origin) {
2202
+ const isAllowedExtension = origin.startsWith("chrome-extension://") || origin.startsWith("moz-extension://") || origin.startsWith("extension://");
2203
+ if (!isAllowedExtension) {
2204
+ callback(false, 403, "Forbidden origin: only browser extensions are allowed");
2205
+ return;
2206
+ }
2207
+ }
2208
+ callback(true);
2209
+ }
2210
+ });
2211
+ } catch (err) {
2212
+ this.emit("error", err);
2213
+ return;
2214
+ }
2215
+ this.wss.on("listening", () => {
2216
+ this.emit("listening");
2217
+ });
2218
+ this.wss.on("error", (err) => {
2219
+ if (err?.code === "EADDRINUSE") {
2220
+ process.stderr.write(
2221
+ `[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
2222
+ `
2223
+ );
2224
+ }
2225
+ this.emit("error", err);
2226
+ });
2227
+ this.wss.on("connection", (socket) => {
2228
+ const challenge = randomUUID2();
2229
+ const hmacSalt = randomBytes(16).toString("hex");
2230
+ const authState = {
2231
+ authenticated: false,
2232
+ challenge,
2233
+ hmacSalt,
2234
+ timer: setTimeout(() => {
2235
+ if (!authState.authenticated) {
2236
+ try {
2237
+ socket.close(WS_CLOSE_CODE.UNAUTHORIZED, "Handshake timeout");
2238
+ } catch {
2239
+ }
2240
+ }
2241
+ }, HANDSHAKE_TIMEOUT_MS)
2242
+ };
2243
+ this.socketAuthStates.set(socket, authState);
2244
+ try {
2245
+ socket.send(
2246
+ JSON.stringify({
2247
+ type: "BRIDGE_CHALLENGE",
2248
+ challenge,
2249
+ hmacSalt,
2250
+ protocolVersion: PROTOCOL_VERSION
2251
+ })
2252
+ );
2253
+ } catch {
2254
+ }
2255
+ socket.on("message", async (data) => {
2256
+ await this.handleSocketMessage(socket, data);
2257
+ });
2258
+ socket.on("close", () => {
2259
+ const auth = this.socketAuthStates.get(socket);
2260
+ if (auth?.timer) clearTimeout(auth.timer);
2261
+ this.socketAuthStates.delete(socket);
2262
+ for (const [reqId, fwdInfo] of this.forwardedRequests.entries()) {
2263
+ if (fwdInfo.socket === socket) {
2264
+ if (fwdInfo.timer) clearTimeout(fwdInfo.timer);
2265
+ this.forwardedRequests.delete(reqId);
2266
+ }
2267
+ }
2268
+ if (socket === this.extensionSocket) {
2269
+ this.extensionSocket = null;
2270
+ this.terminalSessions?.disposeAll();
2271
+ this.emit("disconnected");
2272
+ for (const [reqId, fwdInfo] of this.forwardedRequests.entries()) {
2273
+ if (fwdInfo.timer) clearTimeout(fwdInfo.timer);
2274
+ try {
2275
+ if (fwdInfo.socket.readyState === WS_OPEN) {
2276
+ fwdInfo.socket.send(
2277
+ JSON.stringify({
2278
+ jsonrpc: "2.0",
2279
+ id: fwdInfo.originalId,
2280
+ error: {
2281
+ code: BRIDGE_ERROR_CODE.EXTENSION_NOT_CONNECTED,
2282
+ message: "Chrome \u6269\u5C55\u8FDE\u63A5\u5DF2\u65AD\u5F00"
2283
+ }
2284
+ })
2285
+ );
2286
+ }
2287
+ } catch {
2288
+ }
2289
+ this.forwardedRequests.delete(reqId);
2290
+ }
2291
+ this._rejectAllPending("WebSocket \u8FDE\u63A5\u5DF2\u65AD\u5F00");
2292
+ }
2293
+ });
2294
+ socket.on("error", () => {
2295
+ });
2296
+ });
2297
+ this.wss.on("error", (err) => {
2298
+ this.emit("error", err);
2299
+ });
2300
+ }
2301
+ async handleSocketMessage(socket, data) {
2302
+ let msg;
2303
+ try {
2304
+ msg = JSON.parse(data.toString());
2305
+ } catch {
2306
+ return;
2307
+ }
2308
+ const currentAuth = this.socketAuthStates.get(socket);
2309
+ if (!currentAuth || !currentAuth.authenticated) {
2310
+ await this.handleHandshake(socket, currentAuth, msg);
2311
+ return;
2312
+ }
2313
+ if (msg.type === "KEEP_ALIVE" || msg.type === "WS_BRIDGE_KEEP_ALIVE") {
2314
+ return;
2315
+ }
2316
+ if (msg.method && msg.id) {
2317
+ if (typeof msg.method === "string" && isTerminalMethod(msg.method) && socket !== this.extensionSocket) {
2318
+ this.sendJsonRpcResponse(socket, {
2319
+ id: msg.id,
2320
+ error: {
2321
+ code: BRIDGE_ERROR_CODE.METHOD_NOT_FOUND,
2322
+ message: "\u7EC8\u7AEF\u4F1A\u8BDD\u4EC5\u5141\u8BB8\u5DF2\u8BA4\u8BC1\u7684\u6269\u5C55\u8FDE\u63A5"
2323
+ }
2324
+ });
2325
+ return;
2326
+ }
2327
+ if (socket === this.extensionSocket) {
2328
+ await this.handleExtensionSystemRpc(socket, msg);
2329
+ return;
2330
+ }
2331
+ await this.handleForwardRpc(socket, msg);
2332
+ return;
2333
+ }
2334
+ if (msg.method && !msg.id) {
2335
+ this.handleProgressNotification(msg);
2336
+ return;
2337
+ }
2338
+ if (msg.id) {
2339
+ this.handleIncomingResponse(msg);
2340
+ }
2341
+ }
2342
+ verifyHandshakeHmac(currentAuth, hmac) {
2343
+ if (!currentAuth.hmacSalt || !hmac) return false;
2344
+ const secret = deriveSharedSecret(this.authToken, currentAuth.hmacSalt);
2345
+ const expectedHmac = computeHmac(secret, currentAuth.challenge);
2346
+ if (verifyHmacConstantTime(hmac, expectedHmac)) {
2347
+ return true;
2348
+ }
2349
+ if (!this.explicitAuthToken) {
2350
+ const diskToken = resolveOrCreateAuthToken();
2351
+ if (diskToken && diskToken !== this.authToken) {
2352
+ const diskSecret = deriveSharedSecret(diskToken, currentAuth.hmacSalt);
2353
+ const diskExpectedHmac = computeHmac(diskSecret, currentAuth.challenge);
2354
+ if (verifyHmacConstantTime(hmac, diskExpectedHmac)) {
2355
+ this.authToken = diskToken;
2356
+ return true;
2357
+ }
2358
+ }
2359
+ }
2360
+ return false;
2361
+ }
2362
+ async handleHandshake(socket, currentAuth, msg) {
2363
+ if (!currentAuth || msg.type !== "BRIDGE_AUTH" || msg.challenge !== currentAuth.challenge) {
2364
+ try {
2365
+ socket.close(WS_CLOSE_CODE.UNAUTHORIZED, "Unauthorized: Handshake failed");
2366
+ } catch {
2367
+ }
2368
+ return;
2369
+ }
2370
+ const clientVersion = typeof msg.protocolVersion === "string" ? msg.protocolVersion : PROTOCOL_VERSION;
2371
+ if (parseMajorVersion(clientVersion) !== parseMajorVersion(PROTOCOL_VERSION)) {
2372
+ try {
2373
+ socket.close(
2374
+ WS_CLOSE_CODE.PROTOCOL_MISMATCH,
2375
+ `Protocol version mismatch: server=${PROTOCOL_VERSION}, client=${clientVersion}`
2376
+ );
2377
+ } catch {
2378
+ }
2379
+ return;
2380
+ }
2381
+ const verified = this.verifyHandshakeHmac(currentAuth, msg.hmac);
2382
+ if (!verified) {
2383
+ const tokenFingerprint = this.authToken ? `${this.authToken.slice(0, 6)}...` : "none";
2384
+ process.stderr.write(
2385
+ `[webmcp-cli] HMAC \u9A8C\u8BC1\u5931\u8D25\uFF0C\u62D2\u7EDD\u8FDE\u63A5. client extensionId=${msg.extensionId}, server authTokenFingerprint=${tokenFingerprint}
2386
+ `
2387
+ );
2388
+ try {
2389
+ socket.close(WS_CLOSE_CODE.UNAUTHORIZED, "Unauthorized: HMAC verification failed");
2390
+ } catch {
2391
+ }
2392
+ return;
2393
+ }
2394
+ clearTimeout(currentAuth.timer);
2395
+ currentAuth.authenticated = true;
2396
+ currentAuth.clientType = msg.clientType;
2397
+ if (msg.clientType === "extension") {
2398
+ if (this.extensionSocket && this.extensionSocket !== socket) {
2399
+ this.terminalSessions?.disposeAll();
2400
+ try {
2401
+ this.extensionSocket.close(WS_CLOSE_CODE.REPLACED, "Replaced by new connection");
2402
+ } catch {
2403
+ }
2404
+ }
2405
+ this.extensionSocket = socket;
2406
+ this.emit("connected");
2407
+ }
2408
+ try {
2409
+ socket.send(
2410
+ JSON.stringify({
2411
+ type: "BRIDGE_AUTH_OK",
2412
+ clientType: msg.clientType
2413
+ })
2414
+ );
2415
+ } catch {
2416
+ }
2417
+ }
2418
+ async handleForwardRpc(socket, msg) {
2419
+ let targetSocket = this._getActiveSocket();
2420
+ if (!targetSocket) {
2421
+ await new Promise((resolve3) => {
2422
+ const timer2 = setTimeout(resolve3, 6e3);
2423
+ this.once("connected", () => {
2424
+ clearTimeout(timer2);
2425
+ resolve3();
2426
+ });
2427
+ });
2428
+ targetSocket = this._getActiveSocket();
2429
+ }
2430
+ if (!targetSocket) {
2431
+ socket.send(
2432
+ JSON.stringify({
2433
+ jsonrpc: "2.0",
2434
+ id: msg.id,
2435
+ error: {
2436
+ code: BRIDGE_ERROR_CODE.EXTENSION_NOT_CONNECTED,
2437
+ 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"
2438
+ }
2439
+ })
2440
+ );
2441
+ return;
2442
+ }
2443
+ const internalId = `fwd_${++this.idCounter}_${Date.now()}`;
2444
+ const timeoutMs = msg.method === "sub_agent/run" ? 18e4 : REQUEST_TIMEOUT_MS;
2445
+ const timer = setTimeout(() => {
2446
+ const fwd = this.forwardedRequests.get(internalId);
2447
+ if (!fwd) return;
2448
+ this.forwardedRequests.delete(internalId);
2449
+ try {
2450
+ if (fwd.socket.readyState === WS_OPEN) {
2451
+ fwd.socket.send(
2452
+ JSON.stringify({
2453
+ jsonrpc: "2.0",
2454
+ id: fwd.originalId,
2455
+ error: {
2456
+ code: BRIDGE_ERROR_CODE.REQUEST_TIMEOUT,
2457
+ message: `\u8BF7\u6C42\u8F6C\u53D1\u81F3 Chrome \u6269\u5C55\u8D85\u65F6 (${timeoutMs / 1e3}s)`
2458
+ }
2459
+ })
2460
+ );
2461
+ }
2462
+ } catch {
2463
+ }
2464
+ }, timeoutMs);
2465
+ this.forwardedRequests.set(internalId, {
2466
+ socket,
2467
+ originalId: msg.id,
2468
+ progressToken: msg.params?.progressToken,
2469
+ timer
2470
+ });
2471
+ const outgoingMsg = { ...msg, id: internalId };
2472
+ targetSocket.send(JSON.stringify(outgoingMsg));
2473
+ }
2474
+ sendJsonRpcResponse(socket, response) {
2475
+ if (socket.readyState === WS_OPEN) {
2476
+ socket.send(JSON.stringify({ jsonrpc: "2.0", ...response }));
2477
+ }
2478
+ }
2479
+ formatSystemRpcError(err) {
2480
+ if (err instanceof BashInvalidParamsError || err?.code === "INVALID_PARAMS" || err?.message === "\u547D\u4EE4\u4E0D\u80FD\u4E3A\u7A7A") {
2481
+ return { code: BRIDGE_ERROR_CODE.INVALID_PARAMS, message: err?.message || "\u53C2\u6570\u9519\u8BEF" };
2482
+ }
2483
+ if (err instanceof BashTimeoutError || err?.code === "TIMEOUT" || typeof err?.message === "string" && err.message.includes("\u8D85\u65F6")) {
2484
+ return { code: BRIDGE_ERROR_CODE.EXECUTION_TIMEOUT, message: err?.message || "\u547D\u4EE4\u6267\u884C\u8D85\u65F6" };
2485
+ }
2486
+ return { code: BRIDGE_ERROR_CODE.EXECUTION_FAILED, message: err?.message || "\u6267\u884C\u5931\u8D25" };
2487
+ }
2488
+ systemRpcHandlers = Object.assign(
2489
+ /* @__PURE__ */ Object.create(null),
2490
+ {
2491
+ [BRIDGE_METHODS.SYSTEM_PICK_DIRECTORY]: async (params) => {
2492
+ const selectedPath = await pickDirectory({
2493
+ title: params?.title || void 0,
2494
+ defaultPath: params?.defaultPath || void 0
2495
+ });
2496
+ return {
2497
+ path: selectedPath,
2498
+ selectedPath,
2499
+ canceled: selectedPath === null
2500
+ };
2501
+ },
2502
+ [BRIDGE_METHODS.TERMINAL_OPEN]: async (params) => this.getTerminalSessions().open(params || {}),
2503
+ [BRIDGE_METHODS.TERMINAL_INPUT]: async (params) => this.getTerminalSessions().input(params || {}),
2504
+ [BRIDGE_METHODS.TERMINAL_RESIZE]: async (params) => this.getTerminalSessions().resize(params || {}),
2505
+ [BRIDGE_METHODS.TERMINAL_CLOSE]: async (params) => this.getTerminalSessions().close(params || {})
2506
+ }
2507
+ );
2508
+ sendJsonRpcNotification(socket, method, params) {
2509
+ if (socket.readyState !== WS_OPEN) return;
2510
+ let payload;
2511
+ try {
2512
+ payload = JSON.stringify({ jsonrpc: "2.0", method, params });
2513
+ } catch {
2514
+ return;
2515
+ }
2516
+ try {
2517
+ socket.send(payload);
2518
+ } catch {
2519
+ }
2520
+ }
2521
+ async executeHostBash(socket, id, params) {
2522
+ try {
2523
+ const requestParams = params && typeof params === "object" ? params : {};
2524
+ const result = await executeBash({
2525
+ ...requestParams,
2526
+ onOutput: (chunk) => {
2527
+ if (!chunk.text) return;
2528
+ this.sendJsonRpcNotification(socket, BASH_EVENTS.OUTPUT, {
2529
+ id,
2530
+ stream: chunk.stream,
2531
+ text: chunk.text
2532
+ });
2533
+ }
2534
+ });
2535
+ this.sendJsonRpcResponse(socket, { id, result });
2536
+ } catch (err) {
2537
+ this.sendJsonRpcResponse(socket, { id, error: this.formatSystemRpcError(err) });
2538
+ }
2539
+ }
2540
+ async handleExtensionSystemRpc(socket, msg) {
2541
+ const { id, method, params } = msg;
2542
+ if (!isJsonRpcId(id)) {
2543
+ this.sendJsonRpcResponse(socket, {
2544
+ id: null,
2545
+ error: {
2546
+ code: BRIDGE_ERROR_CODE.INVALID_PARAMS,
2547
+ message: "\u65E0\u6548\u7684\u8BF7\u6C42 id"
2548
+ }
2549
+ });
2550
+ return;
2551
+ }
2552
+ if (method === BRIDGE_METHODS.SYSTEM_BASH) {
2553
+ await this.executeHostBash(socket, id, params);
2554
+ return;
2555
+ }
2556
+ const handler = typeof method === "string" && Object.prototype.hasOwnProperty.call(this.systemRpcHandlers, method) ? this.systemRpcHandlers[method] : void 0;
2557
+ if (!handler || typeof handler !== "function") {
2558
+ this.sendJsonRpcResponse(socket, {
2559
+ id,
2560
+ error: {
2561
+ code: BRIDGE_ERROR_CODE.METHOD_NOT_FOUND,
2562
+ message: `\u4E0D\u652F\u6301\u7684\u65B9\u6CD5: ${method}`
2563
+ }
2564
+ });
2565
+ return;
2566
+ }
2567
+ try {
2568
+ const result = await handler(params);
2569
+ this.sendJsonRpcResponse(socket, { id, result });
2570
+ } catch (err) {
2571
+ this.sendJsonRpcResponse(socket, { id, error: this.formatSystemRpcError(err) });
2572
+ }
2573
+ }
2574
+ handleProgressNotification(msg) {
2575
+ const token = msg.params?.progressToken;
2576
+ if (token != null) {
2577
+ for (const [, reqInfo] of this.forwardedRequests) {
2578
+ if (reqInfo.progressToken === token) {
2579
+ try {
2580
+ if (reqInfo.socket.readyState === WS_OPEN) {
2581
+ reqInfo.socket.send(JSON.stringify(msg));
2582
+ }
2583
+ } catch {
2584
+ }
2585
+ }
2586
+ }
2587
+ }
2588
+ this.emit("progress", msg.params);
2589
+ }
2590
+ handleIncomingResponse(msg) {
2591
+ const fwdInfo = this.forwardedRequests.get(String(msg.id));
2592
+ if (fwdInfo) {
2593
+ if (fwdInfo.timer) clearTimeout(fwdInfo.timer);
2594
+ this.forwardedRequests.delete(String(msg.id));
2595
+ try {
2596
+ if (fwdInfo.socket.readyState === WS_OPEN) {
2597
+ fwdInfo.socket.send(
2598
+ JSON.stringify({
2599
+ ...msg,
2600
+ id: fwdInfo.originalId
2601
+ })
2602
+ );
2603
+ }
2604
+ } catch {
2605
+ }
2606
+ return;
2607
+ }
2608
+ const pending = this.pending.get(String(msg.id));
2609
+ if (!pending) return;
2610
+ this.pending.delete(String(msg.id));
2611
+ clearTimeout(pending.timer);
2612
+ if (msg.error) {
2613
+ pending.reject(new Error(`[${msg.error.code}] ${msg.error.message}`));
2614
+ } else {
2615
+ pending.resolve(msg.result);
2616
+ }
2617
+ }
2618
+ /** 发送 JSON-RPC 2.0 请求,返回 result */
2619
+ async call(method, params = {}, timeoutMs, progressToken, autoWaitMs = 0) {
2620
+ if (autoWaitMs > 0 && !this.isConnected) {
2621
+ await this.waitForReady(autoWaitMs);
2622
+ }
2623
+ const targetSocket = this._getActiveSocket();
2624
+ if (!targetSocket) {
2625
+ throw new Error(
2626
+ "\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"
2627
+ );
2628
+ }
2629
+ const effectiveTimeoutMs = timeoutMs ?? (method === "sub_agent/run" ? 18e4 : REQUEST_TIMEOUT_MS);
2630
+ const id = String(++this.idCounter);
2631
+ const requestParams = { ...params };
2632
+ if (progressToken != null) {
2633
+ requestParams.progressToken = progressToken;
2634
+ }
2635
+ const request = { jsonrpc: "2.0", id, method, params: requestParams };
2636
+ return new Promise((resolve3, reject) => {
2637
+ const timer = setTimeout(() => {
2638
+ this.pending.delete(id);
2639
+ reject(new Error(`\u8BF7\u6C42\u8D85\u65F6\uFF08${effectiveTimeoutMs / 1e3}s\uFF09\uFF1A${method}`));
2640
+ }, effectiveTimeoutMs);
2641
+ this.pending.set(id, { resolve: resolve3, reject, timer });
2642
+ try {
2643
+ targetSocket.send(JSON.stringify(request));
2644
+ } catch (err) {
2645
+ this.pending.delete(id);
2646
+ clearTimeout(timer);
2647
+ reject(err instanceof Error ? err : new Error(String(err)));
2648
+ }
2649
+ });
2650
+ }
2651
+ getTerminalSessions() {
2652
+ if (!this.terminalSessions) {
2653
+ this.terminalSessions = new TerminalSessionManager({
2654
+ send: (frame) => {
2655
+ const socket = this.extensionSocket;
2656
+ if (!socket || socket.readyState !== WS_OPEN) return;
2657
+ const sessions = this.terminalSessions;
2658
+ if (sessions) applyTerminalBackpressure(socket.bufferedAmount ?? 0, sessions);
2659
+ let payload;
2660
+ try {
2661
+ payload = JSON.stringify(frame);
2662
+ } catch {
2663
+ return;
2664
+ }
2665
+ try {
2666
+ socket.send(payload, () => {
2667
+ if (this.terminalSessions && socket.readyState === WS_OPEN) {
2668
+ applyTerminalBackpressure(socket.bufferedAmount ?? 0, this.terminalSessions);
2669
+ }
2670
+ });
2671
+ } catch {
2672
+ }
2673
+ }
2674
+ });
2675
+ }
2676
+ return this.terminalSessions;
2677
+ }
2678
+ /** 销毁服务,断开所有连接 */
2679
+ destroy() {
2680
+ this.destroyed = true;
2681
+ this.terminalSessions?.disposeAll();
2682
+ this._rejectAllPending("ExtensionBridgeClient \u5DF2\u9500\u6BC1");
2683
+ this.forwardedRequests.clear();
2684
+ if (this.clientSocket) {
2685
+ try {
2686
+ this.clientSocket.close();
2687
+ } catch {
2688
+ }
2689
+ this.clientSocket = null;
2690
+ }
2691
+ if (this.extensionSocket) {
2692
+ try {
2693
+ this.extensionSocket.close();
2694
+ } catch {
2695
+ }
2696
+ this.extensionSocket = null;
2697
+ }
2698
+ if (this.wss) {
2699
+ try {
2700
+ this.wss.close();
2701
+ } catch {
2702
+ }
2703
+ this.wss = null;
2704
+ }
2705
+ }
2706
+ _rejectAllPending(reason) {
2707
+ for (const [, pending] of this.pending) {
2708
+ clearTimeout(pending.timer);
2709
+ pending.reject(new Error(reason));
2710
+ }
2711
+ this.pending.clear();
2712
+ for (const [, fwdInfo] of this.forwardedRequests) {
2713
+ if (fwdInfo.timer) clearTimeout(fwdInfo.timer);
2714
+ }
2715
+ this.forwardedRequests.clear();
2716
+ }
2717
+ };
2718
+ }
2719
+ });
2720
+
2721
+ // src/adapters/wxt-adapter.ts
2722
+ var wxt_adapter_exports = {};
2723
+ __export(wxt_adapter_exports, {
2724
+ WxtBrowserAdapter: () => WxtBrowserAdapter
2725
+ });
2726
+ var AUTO_WAIT_MS, WxtBrowserAdapter;
2727
+ var init_wxt_adapter = __esm({
2728
+ "src/adapters/wxt-adapter.ts"() {
2729
+ "use strict";
2730
+ init_bridge_client();
2731
+ init_protocol();
2732
+ AUTO_WAIT_MS = 6e3;
2733
+ WxtBrowserAdapter = class {
2734
+ client;
2735
+ constructor(token, port) {
2736
+ this.client = new ExtensionBridgeClient(port, token);
2737
+ this.client.on("error", () => {
2738
+ });
2739
+ }
2740
+ /** 确保 WS 桥接服务已启动并连接 */
2741
+ async ensureConnected() {
2742
+ await this.client.startAuto();
2743
+ }
2744
+ async getState(tabId) {
2745
+ const numTabId = typeof tabId === "string" ? parseInt(tabId, 10) || void 0 : tabId;
2746
+ const result = await this.client.call(
2747
+ BRIDGE_METHODS.BROWSER_STATE,
2748
+ { tabId: numTabId },
2749
+ void 0,
2750
+ void 0,
2751
+ AUTO_WAIT_MS
2752
+ );
2753
+ return result;
2754
+ }
2755
+ async callTool(toolName, args, tabId) {
2756
+ const numTabId = typeof tabId === "string" ? parseInt(tabId, 10) || void 0 : tabId;
2757
+ return this.client.call(
2758
+ BRIDGE_METHODS.TOOL_CALL,
2759
+ { toolName, toolArgs: args, tabId: numTabId },
2760
+ void 0,
2761
+ void 0,
2762
+ AUTO_WAIT_MS
2763
+ );
2764
+ }
2765
+ async tabs(action, options) {
2766
+ const numTabId = typeof options.tabId === "string" ? parseInt(options.tabId, 10) || void 0 : options.tabId;
2767
+ return this.client.call(
2768
+ BRIDGE_METHODS.BROWSER_TABS,
2769
+ { tabAction: action, ...options, tabId: numTabId },
2770
+ void 0,
2771
+ void 0,
2772
+ AUTO_WAIT_MS
2773
+ );
2774
+ }
2775
+ /** 委托扩展内 Tiny Robot 子代理闭环执行高层任务 */
2776
+ async runSubAgent(instruction, options = {}, timeoutMs) {
2777
+ const params = { instruction, tabId: options.tabId, maxSteps: options.maxSteps };
2778
+ return this.client.call(
2779
+ BRIDGE_METHODS.SUB_AGENT_RUN,
2780
+ params,
2781
+ timeoutMs,
2782
+ options.progressToken,
2783
+ AUTO_WAIT_MS
2784
+ );
2785
+ }
2786
+ /** 获取已注册的 Skills 列表(L1 索引) */
2787
+ async listSkills() {
2788
+ return this.client.call(BRIDGE_METHODS.SKILLS_LIST, {}, void 0, void 0, AUTO_WAIT_MS);
2789
+ }
2790
+ /** 读取指定 Skill 的详细指令(L2 详情) */
2791
+ async getSkill(name) {
2792
+ return this.client.call(BRIDGE_METHODS.SKILLS_GET, { name }, void 0, void 0, AUTO_WAIT_MS);
2793
+ }
2794
+ /** 读取 Skill 关联资源(L3 资源) */
2795
+ async readSkillResource(name, resourcePath) {
2796
+ return this.client.call(
2797
+ BRIDGE_METHODS.SKILLS_READ_RESOURCE,
2798
+ { name, resourcePath },
2799
+ void 0,
2800
+ void 0,
2801
+ AUTO_WAIT_MS
2802
+ );
2803
+ }
2804
+ /** 获取底层 ExtensionBridgeClient(供 MCP Server 绑定事件) */
2805
+ get bridgeClient() {
2806
+ return this.client;
2807
+ }
2808
+ async dispose() {
2809
+ this.client.destroy();
2810
+ }
2811
+ };
2812
+ }
2813
+ });
2814
+
2815
+ // src/bridge/daemon.ts
2816
+ var daemon_exports = {};
2817
+ __export(daemon_exports, {
2818
+ PID_FILE: () => PID_FILE,
2819
+ ensureBridgeDaemon: () => ensureBridgeDaemon,
2820
+ findPidByPort: () => findPidByPort,
2821
+ getDaemonPidFile: () => getDaemonPidFile,
2822
+ isBridgeDaemonProcess: () => isBridgeDaemonProcess,
2823
+ isDaemonProcessAlive: () => isDaemonProcessAlive,
2824
+ isProcessAlive: () => isProcessAlive,
2825
+ killProcessOnPort: () => killProcessOnPort,
2826
+ killProcessTree: () => killProcessTree,
2827
+ probeServerReady: () => probeServerReady,
2828
+ runDaemonProcess: () => runDaemonProcess,
2829
+ stopBridgeDaemon: () => stopBridgeDaemon
2830
+ });
2831
+ import { spawn as spawn3, exec } from "child_process";
2832
+ import { promisify } from "util";
2833
+ import fs5 from "fs";
2834
+ import path6 from "path";
2835
+ import os4 from "os";
2836
+ import { fileURLToPath as fileURLToPath3 } from "url";
2837
+ function getDaemonPidFile(port = WS_PORT2) {
2838
+ if (port === WS_PORT2) {
2839
+ return path6.join(DAEMON_DIR, "daemon.pid");
2840
+ }
2841
+ return path6.join(DAEMON_DIR, `daemon-${port}.pid`);
2842
+ }
2843
+ function isProcessAlive(pid) {
2844
+ if (!pid || pid <= 0) return false;
2845
+ try {
2846
+ process.kill(pid, 0);
2847
+ return true;
2848
+ } catch {
2849
+ return false;
2850
+ }
2851
+ }
2852
+ async function findPidByPort(port, excludePid) {
2853
+ if (process.platform === "win32") {
2854
+ try {
2855
+ const { stdout } = await execAsync("netstat -ano -p tcp");
2856
+ const lines = stdout.split(/\r?\n/);
2857
+ for (const rawLine of lines) {
2858
+ const line = rawLine.trim();
2859
+ if (!line.toUpperCase().startsWith("TCP")) continue;
2860
+ const parts = line.split(/\s+/);
2861
+ if (parts.length < 5) continue;
2862
+ const localAddr = parts[1];
2863
+ const state = parts[3]?.toUpperCase() || "";
2864
+ const pid = parseInt(parts[parts.length - 1], 10);
2865
+ if (!pid || isNaN(pid) || excludePid && pid === excludePid) continue;
2866
+ if (localAddr.endsWith(`:${port}`)) {
2867
+ if (state.includes("LISTEN") || state.includes("\u4FA6\u542C")) {
2868
+ return pid;
2869
+ }
2870
+ }
2871
+ }
2872
+ return null;
2873
+ } catch {
2874
+ return null;
2875
+ }
2876
+ }
2877
+ try {
2878
+ const { stdout } = await execAsync(`lsof -nP -iTCP:${port} -sTCP:LISTEN -t`);
2879
+ const pids = stdout.trim().split("\n").map((p) => parseInt(p.trim(), 10)).filter((p) => Boolean(p && !isNaN(p) && (!excludePid || p !== excludePid)));
2880
+ return pids[0] ?? null;
2881
+ } catch {
2882
+ return null;
2883
+ }
2884
+ }
2885
+ async function killProcessTree(pid) {
2886
+ if (!pid || pid <= 0 || pid === process.pid) return false;
2887
+ if (process.platform === "win32") {
2888
+ try {
2889
+ await execAsync(`taskkill /pid ${pid} /T /F`);
2890
+ } catch {
2891
+ try {
2892
+ process.kill(pid, "SIGKILL");
2893
+ } catch {
2894
+ }
2895
+ }
2896
+ for (let i = 0; i < 15; i++) {
2897
+ await new Promise((r) => setTimeout(r, 100));
2898
+ if (!isProcessAlive(pid)) return true;
2899
+ }
2900
+ return !isProcessAlive(pid);
2901
+ }
2902
+ try {
2903
+ process.kill(pid, "SIGTERM");
2904
+ } catch {
2905
+ }
2906
+ for (let i = 0; i < 10; i++) {
2907
+ await new Promise((r) => setTimeout(r, 100));
2908
+ if (!isProcessAlive(pid)) return true;
2909
+ }
2910
+ try {
2911
+ process.kill(pid, "SIGKILL");
2912
+ } catch {
2913
+ }
2914
+ for (let i = 0; i < 5; i++) {
2915
+ await new Promise((r) => setTimeout(r, 100));
2916
+ if (!isProcessAlive(pid)) return true;
2917
+ }
2918
+ return !isProcessAlive(pid);
2919
+ }
2920
+ async function killProcessOnPort(port) {
2921
+ const pid = await findPidByPort(port, process.pid);
2922
+ if (pid) {
2923
+ await killProcessTree(pid);
2924
+ for (let i = 0; i < 20; i++) {
2925
+ await new Promise((r) => setTimeout(r, 100));
2926
+ const remainingPid = await findPidByPort(port, process.pid);
2927
+ if (!remainingPid) return true;
2928
+ }
2929
+ }
2930
+ return false;
2931
+ }
2932
+ async function probeServerReady(port = WS_PORT2, token, timeoutMs = 1e3) {
2933
+ return ExtensionBridgeClient.probe(port, token ?? resolveOrCreateAuthToken(), timeoutMs);
2934
+ }
2935
+ function isDaemonProcessAlive(port = WS_PORT2) {
2936
+ const pidFile = getDaemonPidFile(port);
2937
+ if (!fs5.existsSync(pidFile)) return false;
2938
+ try {
2939
+ const pid = parseInt(fs5.readFileSync(pidFile, "utf8").trim(), 10);
2940
+ return Boolean(pid && isProcessAlive(pid));
2941
+ } catch {
2942
+ return false;
2943
+ }
2944
+ }
2945
+ async function ensureBridgeDaemon(options = {}) {
2946
+ const port = options.port ?? WS_PORT2;
2947
+ const token = options.token ?? resolveOrCreateAuthToken();
2948
+ const timeoutMs = options.timeoutMs ?? 6e3;
2949
+ const probe = await probeServerReady(port, token, 800);
2950
+ if (probe.running && probe.authed) {
2951
+ return { newlyStarted: false };
2952
+ }
2953
+ if (probe.running && !probe.authed) {
2954
+ if (!options.silent) {
2955
+ console.log(
2956
+ `\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...`
2957
+ );
2958
+ }
2959
+ const stopped = await stopBridgeDaemon(port, { onlyVerified: true });
2960
+ if (!stopped) {
2961
+ const killTip = getKillPortHint(port);
2962
+ throw new Error(
2963
+ `\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
2964
+ \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`
2965
+ );
2966
+ }
2967
+ await new Promise((r) => setTimeout(r, 400));
2968
+ }
2969
+ if (!options.silent) {
2970
+ 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})...`);
2971
+ }
2972
+ startDaemonProcessBackground(token, port);
2973
+ const startTime = Date.now();
2974
+ while (Date.now() - startTime < timeoutMs) {
2975
+ await new Promise((r) => setTimeout(r, 200));
2976
+ const check = await probeServerReady(port, token, 400);
2977
+ if (check.running && check.authed) {
2978
+ if (!options.silent) {
2979
+ 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...`);
2980
+ }
2981
+ return { newlyStarted: true };
2982
+ }
2983
+ }
2984
+ 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`);
2985
+ }
2986
+ function resolveCliEntry() {
2987
+ const currentDir = path6.dirname(fileURLToPath3(import.meta.url));
2988
+ const distCandidate = path6.join(currentDir, "bin.js");
2989
+ if (fs5.existsSync(distCandidate)) return distCandidate;
2990
+ const projectDistCandidate = path6.resolve(currentDir, "../dist/bin.js");
2991
+ if (fs5.existsSync(projectDistCandidate)) return projectDistCandidate;
2992
+ return distCandidate;
2993
+ }
2994
+ function startDaemonProcessBackground(token, port) {
2995
+ const cliEntry = resolveCliEntry();
2996
+ if (!fs5.existsSync(DAEMON_DIR)) {
2997
+ fs5.mkdirSync(DAEMON_DIR, { mode: 448, recursive: true });
2998
+ }
2999
+ const child = spawn3(process.execPath, [cliEntry, "--mode", "wxt", "daemon", "--port", String(port)], {
3000
+ detached: true,
3001
+ stdio: "ignore",
3002
+ windowsHide: true,
3003
+ env: {
3004
+ ...process.env,
3005
+ ROBOT_WXT_BRIDGE_TOKEN: token
3006
+ }
3007
+ });
3008
+ child.unref();
3009
+ }
3010
+ async function runDaemonProcess(args) {
3011
+ let port = WS_PORT2;
3012
+ let token;
3013
+ const portIdx = args.indexOf("--port");
3014
+ if (portIdx !== -1 && args[portIdx + 1]) {
3015
+ port = parseInt(args[portIdx + 1], 10);
3016
+ }
3017
+ const tokenIdx = args.indexOf("--token");
3018
+ if (tokenIdx !== -1 && args[tokenIdx + 1]) {
3019
+ token = args[tokenIdx + 1];
3020
+ } else if (process.env.ROBOT_WXT_BRIDGE_TOKEN) {
3021
+ token = process.env.ROBOT_WXT_BRIDGE_TOKEN;
3022
+ }
3023
+ const client = new ExtensionBridgeClient(port, token);
3024
+ client.on("error", (err) => {
3025
+ if (err && (err.code === "EADDRINUSE" || err.message?.includes("EADDRINUSE"))) {
3026
+ process.exit(1);
3027
+ }
3028
+ });
3029
+ const pidFile = getDaemonPidFile(port);
3030
+ client.on("listening", () => {
3031
+ try {
3032
+ if (!fs5.existsSync(DAEMON_DIR)) {
3033
+ fs5.mkdirSync(DAEMON_DIR, { mode: 448, recursive: true });
3034
+ }
3035
+ fs5.writeFileSync(pidFile, String(process.pid), { mode: 384, encoding: "utf8" });
3036
+ } catch {
3037
+ }
3038
+ });
3039
+ client.connect();
3040
+ const shutdown = () => {
3041
+ try {
3042
+ if (fs5.existsSync(pidFile)) {
3043
+ const recordedPid = fs5.readFileSync(pidFile, "utf8").trim();
3044
+ if (recordedPid === String(process.pid)) {
3045
+ fs5.unlinkSync(pidFile);
3046
+ }
3047
+ }
3048
+ } catch {
3049
+ }
3050
+ client.destroy();
3051
+ process.exit(0);
3052
+ };
3053
+ process.on("SIGINT", shutdown);
3054
+ process.on("SIGTERM", shutdown);
3055
+ process.on("exit", shutdown);
3056
+ setInterval(() => {
3057
+ }, 6e4);
3058
+ }
3059
+ async function isBridgeDaemonProcess(pid) {
3060
+ if (!pid || pid <= 0 || !isProcessAlive(pid)) return false;
3061
+ try {
3062
+ let cmd = "";
3063
+ if (process.platform === "win32") {
3064
+ const { stdout } = await execAsync(
3065
+ `powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter \\"ProcessId = ${pid}\\").CommandLine"`
3066
+ );
3067
+ cmd = stdout.trim();
3068
+ } else {
3069
+ const { stdout } = await execAsync(`ps -p ${pid} -o command=`);
3070
+ cmd = stdout.trim();
3071
+ }
3072
+ if (!cmd) return false;
3073
+ return (cmd.includes("webmcp-cli") || cmd.includes("bin.js") || cmd.includes("daemon.js")) && cmd.includes("daemon");
3074
+ } catch {
3075
+ return false;
3076
+ }
3077
+ }
3078
+ async function stopBridgeDaemon(port = WS_PORT2, options = {}) {
3079
+ const onlyVerified = options.onlyVerified ?? false;
3080
+ let killedAny = false;
3081
+ const pidFile = getDaemonPidFile(port);
3082
+ let daemonPid = null;
3083
+ if (fs5.existsSync(pidFile)) {
3084
+ try {
3085
+ const pidStr = fs5.readFileSync(pidFile, "utf8").trim();
3086
+ const p = parseInt(pidStr, 10);
3087
+ if (p && isProcessAlive(p)) {
3088
+ daemonPid = p;
3089
+ }
3090
+ } catch {
3091
+ }
3092
+ }
3093
+ if (onlyVerified) {
3094
+ if (!daemonPid) {
3095
+ return false;
3096
+ }
3097
+ const isVerified = await isBridgeDaemonProcess(daemonPid);
3098
+ if (!isVerified) {
3099
+ return false;
3100
+ }
3101
+ const portPid = await findPidByPort(port, process.pid);
3102
+ if (portPid && portPid !== daemonPid) {
3103
+ return false;
3104
+ }
3105
+ const killed = await killProcessTree(daemonPid);
3106
+ if (killed) {
3107
+ killedAny = true;
3108
+ try {
3109
+ if (fs5.existsSync(pidFile)) fs5.unlinkSync(pidFile);
3110
+ } catch {
3111
+ }
3112
+ }
3113
+ } else {
3114
+ if (daemonPid) {
3115
+ try {
3116
+ const killed = await killProcessTree(daemonPid);
3117
+ if (killed) {
3118
+ killedAny = true;
3119
+ try {
3120
+ if (fs5.existsSync(pidFile)) fs5.unlinkSync(pidFile);
3121
+ } catch {
3122
+ }
3123
+ }
3124
+ } catch {
3125
+ }
3126
+ }
3127
+ const portPid = await findPidByPort(port, process.pid);
3128
+ if (portPid) {
3129
+ const killedByPort = await killProcessOnPort(port);
3130
+ if (killedByPort) {
3131
+ killedAny = true;
3132
+ }
3133
+ }
3134
+ }
3135
+ let portReleased = false;
3136
+ for (let i = 0; i < 10; i++) {
3137
+ const remainingPid = await findPidByPort(port, process.pid);
3138
+ if (!remainingPid) {
3139
+ portReleased = true;
3140
+ break;
3141
+ }
3142
+ await new Promise((r) => setTimeout(r, 200));
3143
+ }
3144
+ if (!portReleased) {
3145
+ return false;
3146
+ }
3147
+ return killedAny;
3148
+ }
3149
+ var execAsync, WS_PORT2, DAEMON_DIR, PID_FILE;
3150
+ var init_daemon = __esm({
3151
+ "src/bridge/daemon.ts"() {
3152
+ "use strict";
3153
+ init_bridge_client();
3154
+ execAsync = promisify(exec);
3155
+ WS_PORT2 = 18999;
3156
+ DAEMON_DIR = path6.join(os4.homedir(), ".robot-wxt");
3157
+ PID_FILE = getDaemonPidFile(WS_PORT2);
3158
+ }
3159
+ });
3160
+
3161
+ // src/mcp/server.ts
3162
+ var server_exports = {};
3163
+ __export(server_exports, {
3164
+ startMcpServer: () => startMcpServer
3165
+ });
3166
+ import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
3167
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3168
+ async function startMcpServer(options = {}) {
3169
+ const mode = options.mode ?? "cdp";
3170
+ const agentMode = options.agentMode ?? "tools";
3171
+ const isAgentMode = agentMode === "agent";
3172
+ const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION });
3173
+ if (mode === "cdp") {
3174
+ if (isAgentMode) {
3175
+ 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");
3176
+ }
3177
+ await startCdpMcpServer(server, isAgentMode);
3178
+ } else {
3179
+ await startWxtMcpServer(server, isAgentMode, options);
3180
+ }
3181
+ const transport = new StdioServerTransport();
3182
+ await server.connect(transport);
3183
+ process.stderr.write(
3184
+ `[webmcp-cli] MCP Server \u5DF2\u542F\u52A8\uFF08${SERVER_NAME} v${SERVER_VERSION}\uFF0C\u6A21\u5F0F: ${mode}${isAgentMode ? "/agent" : "/tools"}\uFF09
3185
+ `
3186
+ );
3187
+ }
3188
+ async function startCdpMcpServer(server, isAgentMode) {
3189
+ const { CdpBrowserAdapter: CdpBrowserAdapter2 } = await Promise.resolve().then(() => (init_cdp_adapter(), cdp_adapter_exports));
3190
+ const adapter = new CdpBrowserAdapter2();
3191
+ registerCommonTools(server, adapter, isAgentMode);
3192
+ process.on("SIGINT", async () => {
3193
+ await adapter.dispose();
3194
+ process.exit(0);
3195
+ });
3196
+ process.on("SIGTERM", async () => {
3197
+ await adapter.dispose();
3198
+ process.exit(0);
3199
+ });
3200
+ }
3201
+ async function startWxtMcpServer(server, isAgentMode, options) {
3202
+ const { WxtBrowserAdapter: WxtBrowserAdapter2 } = await Promise.resolve().then(() => (init_wxt_adapter(), wxt_adapter_exports));
3203
+ const { ensureBridgeDaemon: ensureBridgeDaemon2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
3204
+ const daemonResult = await ensureBridgeDaemon2({
3205
+ token: options.token,
3206
+ port: options.wsPort,
3207
+ silent: true
3208
+ });
3209
+ const adapter = new WxtBrowserAdapter2(options.token, options.wsPort);
3210
+ await adapter.ensureConnected();
3211
+ if (daemonResult.newlyStarted) {
3212
+ 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");
3213
+ }
3214
+ const client = adapter.bridgeClient;
3215
+ registerCommonTools(server, adapter, isAgentMode);
3216
+ registerWxtTools(server, adapter, isAgentMode, server);
3217
+ registerSkillsResources(server, adapter);
3218
+ client.on("connected", () => {
3219
+ process.stderr.write("[webmcp-cli] \u5DF2\u8FDE\u63A5\u5230 Chrome \u6269\u5C55\n");
3220
+ try {
3221
+ server.server.notification({ method: "notifications/resources/list_changed" });
3222
+ } catch {
3223
+ }
3224
+ });
3225
+ client.on("disconnected", () => {
3226
+ process.stderr.write("[webmcp-cli] \u4E0E Chrome \u6269\u5C55\u7684\u8FDE\u63A5\u5DF2\u65AD\u5F00\n");
3227
+ });
3228
+ process.on("SIGINT", async () => {
3229
+ await adapter.dispose();
3230
+ process.exit(0);
3231
+ });
3232
+ process.on("SIGTERM", async () => {
3233
+ await adapter.dispose();
3234
+ process.exit(0);
3235
+ });
3236
+ const tokenFingerprint = options.token ? `${options.token.slice(0, 6)}...` : "(auto)";
3237
+ process.stderr.write(`[webmcp-cli] \u{1F511} Token \u6307\u7EB9: ${tokenFingerprint} (\u5B8C\u6574\u51ED\u636E\u89C1 ~/.robot-wxt/bridge-token)
3238
+ `);
3239
+ }
3240
+ function registerCommonTools(server, adapter, isAgentMode) {
3241
+ server.registerTool(
3242
+ "browser_state",
3243
+ {
3244
+ 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",
3245
+ inputSchema: BrowserStateInput.shape
3246
+ },
3247
+ async (args) => {
3248
+ const result = await adapter.getState(args.tabId);
3249
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
3250
+ }
3251
+ );
3252
+ if (!isAgentMode) {
3253
+ server.registerTool(
3254
+ "browser_tool_call",
3255
+ {
3256
+ 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",
3257
+ inputSchema: BrowserToolCallInput.shape
3258
+ },
3259
+ async (args) => {
3260
+ const result = await adapter.callTool(args.toolName, args.toolArgs ?? {}, args.tabId);
3261
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
3262
+ }
3263
+ );
3264
+ server.registerTool(
3265
+ "browser_tabs_open",
3266
+ { 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 },
3267
+ async (args) => {
3268
+ const result = await adapter.tabs("open", { url: args.url });
3269
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
3270
+ }
3271
+ );
3272
+ server.registerTool(
3273
+ "browser_tabs_close",
3274
+ { 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 },
3275
+ async (args) => {
3276
+ const result = await adapter.tabs("close", { tabId: args.tabId });
3277
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
3278
+ }
3279
+ );
3280
+ server.registerTool(
3281
+ "browser_tabs_switch",
3282
+ {
3283
+ 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",
3284
+ inputSchema: BrowserTabsSwitchInput.shape
3285
+ },
3286
+ async (args) => {
3287
+ const result = await adapter.tabs("switch", { tabId: args.tabId, activateVisible: args.activateVisible });
3288
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
3289
+ }
3290
+ );
3291
+ server.registerTool(
3292
+ "browser_tabs_back",
3293
+ { 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 },
3294
+ async (args) => {
3295
+ const result = await adapter.tabs("back", { tabId: args.tabId });
3296
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
3297
+ }
3298
+ );
3299
+ server.registerTool(
3300
+ "browser_tabs_forward",
3301
+ { 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 },
3302
+ async (args) => {
3303
+ const result = await adapter.tabs("forward", { tabId: args.tabId });
3304
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
3305
+ }
3306
+ );
3307
+ }
3308
+ }
3309
+ function registerWxtTools(server, adapter, isAgentMode, mcpServer) {
3310
+ server.registerTool(
3311
+ "browser_sub_agent_run",
3312
+ {
3313
+ 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",
3314
+ inputSchema: BrowserSubAgentRunInput.shape
3315
+ },
3316
+ async (args, extra) => {
3317
+ const progressToken = extra?._meta?.progressToken;
3318
+ const onProgress = progressToken != null ? (params) => {
3319
+ if (params?.progressToken && params.progressToken !== progressToken) return;
3320
+ try {
3321
+ mcpServer.server.notification({
3322
+ method: "notifications/progress",
3323
+ params: { progressToken, progress: params?.step ?? 0, total: params?.total ?? args.maxSteps ?? 8, message: params?.message ?? "" }
3324
+ });
3325
+ } catch {
3326
+ }
3327
+ } : void 0;
3328
+ if (onProgress) adapter.bridgeClient.on("progress", onProgress);
3329
+ try {
3330
+ const result = await adapter.runSubAgent(args.instruction, {
3331
+ tabId: args.tabId,
3332
+ maxSteps: args.maxSteps,
3333
+ progressToken
3334
+ });
3335
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
3336
+ } finally {
3337
+ if (onProgress) adapter.bridgeClient.off("progress", onProgress);
3338
+ }
3339
+ }
3340
+ );
3341
+ if (!isAgentMode) {
3342
+ server.registerTool(
3343
+ "browser_skills_list",
3344
+ {
3345
+ 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",
3346
+ inputSchema: BrowserSkillsListInput.shape
3347
+ },
3348
+ async () => {
3349
+ const result = await adapter.listSkills();
3350
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
3351
+ }
3352
+ );
3353
+ server.registerTool(
3354
+ "browser_skills_read",
3355
+ {
3356
+ 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",
3357
+ inputSchema: BrowserSkillsReadInput.shape
3358
+ },
3359
+ async (args) => {
3360
+ const result = await adapter.getSkill(args.name);
3361
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
3362
+ }
3363
+ );
3364
+ }
3365
+ }
3366
+ function registerSkillsResources(server, adapter) {
3367
+ server.registerResource(
3368
+ "skills_index",
3369
+ "skills://index",
3370
+ { 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" },
3371
+ async () => {
3372
+ try {
3373
+ const skills = await adapter.listSkills();
3374
+ return { contents: [{ uri: "skills://index", text: JSON.stringify(skills, null, 2), mimeType: "application/json" }] };
3375
+ } catch (err) {
3376
+ return { contents: [{ uri: "skills://index", text: JSON.stringify({ error: err instanceof Error ? err.message : String(err) }), mimeType: "application/json" }] };
3377
+ }
3378
+ }
3379
+ );
3380
+ const skillDetailTemplate = new ResourceTemplate("skills://{skillName}/detail", { list: void 0 });
3381
+ server.registerResource(
3382
+ "skill_detail",
3383
+ skillDetailTemplate,
3384
+ { 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" },
3385
+ async (uri, params) => {
3386
+ const { skillName } = params;
3387
+ try {
3388
+ const detail = await adapter.getSkill(skillName);
3389
+ return { contents: [{ uri: uri.href, text: JSON.stringify(detail, null, 2), mimeType: "application/json" }] };
3390
+ } catch (err) {
3391
+ return { contents: [{ uri: uri.href, text: JSON.stringify({ error: err instanceof Error ? err.message : String(err) }), mimeType: "application/json" }] };
3392
+ }
3393
+ }
3394
+ );
3395
+ const skillResourceTemplate = new ResourceTemplate("skills://{skillName}/{resourcePath}", { list: void 0 });
3396
+ server.registerResource(
3397
+ "skill_resource",
3398
+ skillResourceTemplate,
3399
+ { 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" },
3400
+ async (uri, params) => {
3401
+ const { skillName, resourcePath } = params;
3402
+ try {
3403
+ const text = await adapter.readSkillResource(skillName, resourcePath);
3404
+ return { contents: [{ uri: uri.href, text: String(text), mimeType: "text/plain" }] };
3405
+ } catch (err) {
3406
+ return { contents: [{ uri: uri.href, text: `\u8BFB\u53D6\u8D44\u6E90\u5931\u8D25: ${err instanceof Error ? err.message : String(err)}`, mimeType: "text/plain" }] };
3407
+ }
3408
+ }
3409
+ );
3410
+ }
3411
+ var SERVER_NAME, SERVER_VERSION;
3412
+ var init_server = __esm({
3413
+ "src/mcp/server.ts"() {
3414
+ "use strict";
3415
+ init_package();
3416
+ init_tools();
3417
+ SERVER_NAME = "webmcp-cli";
3418
+ SERVER_VERSION = package_default.version || "0.0.9";
3419
+ }
3420
+ });
3421
+
3422
+ // src/commands/agent.ts
3423
+ var agent_exports = {};
3424
+ __export(agent_exports, {
3425
+ handleAgentCommand: () => handleAgentCommand
3426
+ });
3427
+ async function handleAgentCommand(adapter, args) {
3428
+ const subCommand = args[0];
3429
+ const restArgs = args.slice(1);
3430
+ if (!subCommand || subCommand === "--help" || subCommand === "-h") {
3431
+ printAgentHelp();
3432
+ return;
3433
+ }
3434
+ if (subCommand === "run") {
3435
+ await handleAgentRun(adapter, restArgs);
3436
+ return;
3437
+ }
3438
+ console.error(`[\u9519\u8BEF] \u672A\u77E5\u5B50\u547D\u4EE4: agent ${subCommand}`);
3439
+ console.error("\u8FD0\u884C webmcp-cli --mode wxt agent --help \u67E5\u770B\u652F\u6301\u7684\u547D\u4EE4");
3440
+ process.exit(1);
3441
+ }
3442
+ async function handleAgentRun(adapter, args) {
3443
+ let instruction = "";
3444
+ let maxSteps;
3445
+ let tabId;
3446
+ const isJson = args.includes("--json");
3447
+ for (let i = 0; i < args.length; i++) {
3448
+ const arg = args[i];
3449
+ if (arg === "--max-steps" && args[i + 1]) {
3450
+ maxSteps = parseInt(args[++i], 10);
3451
+ } else if (arg === "--tab" && args[i + 1]) {
3452
+ tabId = parseInt(args[++i], 10);
3453
+ } else if (!arg.startsWith("-")) {
3454
+ instruction = arg;
3455
+ }
3456
+ }
3457
+ if (!instruction) {
3458
+ 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"');
3459
+ process.exit(1);
3460
+ }
3461
+ if (!isJson) {
3462
+ console.log(`\u{1F916} \u6B63\u5728\u59D4\u6258 Tiny Robot \u5B50\u4EE3\u7406\u6267\u884C\u4EFB\u52A1\uFF1A\u300C${instruction}\u300D`);
3463
+ if (maxSteps) console.log(` \u6700\u5927\u6B65\u6570\uFF1A${maxSteps}`);
3464
+ }
3465
+ try {
3466
+ const result = await adapter.runSubAgent(instruction, { tabId, maxSteps });
3467
+ if (isJson) {
3468
+ console.log(JSON.stringify(result, null, 2));
3469
+ } else {
3470
+ console.log("\n\u2705 \u5B50\u4EE3\u7406\u6267\u884C\u5B8C\u6210\uFF1A");
3471
+ console.log(JSON.stringify(result, null, 2));
3472
+ }
3473
+ } catch (err) {
3474
+ const msg = err instanceof Error ? err.message : String(err);
3475
+ if (isJson) {
3476
+ console.log(JSON.stringify({ success: false, error: msg }));
3477
+ } else {
3478
+ console.error(`\u274C \u6267\u884C\u5931\u8D25\uFF1A${msg}`);
3479
+ }
3480
+ process.exit(1);
3481
+ }
3482
+ }
3483
+ function printAgentHelp() {
3484
+ console.log(`
3485
+ webmcp-cli --mode wxt agent - \u59D4\u6258 Chrome \u6269\u5C55\u5185 Tiny Robot \u5B50\u4EE3\u7406\u6267\u884C\u9AD8\u5C42\u4EFB\u52A1
3486
+
3487
+ \u7528\u6CD5\uFF1A
3488
+ webmcp-cli --mode wxt agent run "<\u6307\u4EE4>" \u59D4\u6258\u5B50\u4EE3\u7406\u81EA\u4E3B\u6267\u884C\u81EA\u7136\u8BED\u8A00\u4EFB\u52A1
3489
+
3490
+ \u9009\u9879\uFF1A
3491
+ --max-steps <n> \u6700\u5927\u6267\u884C\u6B65\u6570\uFF08\u9ED8\u8BA4 8\uFF0C\u6700\u5927 20\uFF09
3492
+ --tab <tabId> \u6307\u5B9A\u76EE\u6807\u6807\u7B7E\u9875 ID
3493
+ --json \u8F93\u51FA JSON \u683C\u5F0F\u7ED3\u679C
3494
+
3495
+ \u793A\u4F8B\uFF1A
3496
+ webmcp-cli --mode wxt agent run "\u5E2E\u6211\u628A\u5F53\u524D\u5546\u54C1\u52A0\u5165\u8D2D\u7269\u8F66"
3497
+ webmcp-cli --mode wxt agent run "\u641C\u7D22\u5E76\u6536\u85CF\u524D3\u7BC7\u6587\u7AE0" --max-steps 10
3498
+ `.trim());
3499
+ }
3500
+ var init_agent = __esm({
3501
+ "src/commands/agent.ts"() {
3502
+ "use strict";
3503
+ }
3504
+ });
3505
+
3506
+ // src/commands/skills.ts
3507
+ var skills_exports = {};
3508
+ __export(skills_exports, {
3509
+ handleSkillsCommand: () => handleSkillsCommand
3510
+ });
3511
+ async function handleSkillsCommand(adapter, args) {
3512
+ const subCommand = args[0];
3513
+ const restArgs = args.slice(1);
3514
+ const isJson = args.includes("--json");
3515
+ if (!subCommand || subCommand === "--help" || subCommand === "-h") {
3516
+ printSkillsHelp();
3517
+ return;
3518
+ }
3519
+ if (subCommand === "list") {
3520
+ await handleSkillsList(adapter, isJson);
3521
+ return;
3522
+ }
3523
+ if (subCommand === "get") {
3524
+ const skillName = restArgs.find((a) => !a.startsWith("-"));
3525
+ if (!skillName) {
3526
+ console.error("[\u9519\u8BEF] \u8BF7\u63D0\u4F9B\u6280\u80FD\u540D\u79F0\u3002\u793A\u4F8B\uFF1Awebmcp-cli --mode wxt skills get <skillName>");
3527
+ process.exit(1);
3528
+ }
3529
+ await handleSkillsGet(adapter, skillName, isJson);
3530
+ return;
3531
+ }
3532
+ console.error(`[\u9519\u8BEF] \u672A\u77E5\u5B50\u547D\u4EE4: skills ${subCommand}`);
3533
+ printSkillsHelp();
3534
+ process.exit(1);
3535
+ }
3536
+ async function handleSkillsList(adapter, isJson) {
3537
+ try {
3538
+ const result = await adapter.listSkills();
3539
+ if (isJson) {
3540
+ console.log(JSON.stringify(result, null, 2));
3541
+ } else {
3542
+ const skills = result;
3543
+ if (!skills || skills.length === 0) {
3544
+ console.log("\uFF08\u5F53\u524D\u6269\u5C55\u672A\u6CE8\u518C\u4EFB\u4F55\u6280\u80FD\uFF09");
3545
+ return;
3546
+ }
3547
+ console.log(`
3548
+ \u{1F4DA} \u5DF2\u6CE8\u518C Skills\uFF08\u5171 ${skills.length} \u4E2A\uFF09\uFF1A
3549
+ `);
3550
+ for (const skill of skills) {
3551
+ console.log(` \u2022 ${skill.name}`);
3552
+ if (skill.description) {
3553
+ console.log(` ${skill.description.slice(0, 100)}${skill.description.length > 100 ? "..." : ""}`);
3554
+ }
3555
+ }
3556
+ console.log(`
3557
+ \u63D0\u793A\uFF1A\u4F7F\u7528 "webmcp-cli --mode wxt skills get <name>" \u67E5\u770B\u6280\u80FD\u8BE6\u60C5`);
3558
+ }
3559
+ } catch (err) {
3560
+ const msg = err instanceof Error ? err.message : String(err);
3561
+ if (isJson) {
3562
+ console.log(JSON.stringify({ error: msg }));
3563
+ } else {
3564
+ console.error(`\u274C \u83B7\u53D6\u6280\u80FD\u5217\u8868\u5931\u8D25\uFF1A${msg}`);
3565
+ }
3566
+ process.exit(1);
3567
+ }
3568
+ }
3569
+ async function handleSkillsGet(adapter, name, isJson) {
3570
+ try {
3571
+ const result = await adapter.getSkill(name);
3572
+ if (isJson) {
3573
+ console.log(JSON.stringify(result, null, 2));
3574
+ } else {
3575
+ const skill = result;
3576
+ console.log(`
3577
+ \u{1F4D6} \u6280\u80FD\uFF1A${skill.name}`);
3578
+ if (skill.description) console.log(`\u63CF\u8FF0\uFF1A${skill.description}`);
3579
+ if (skill.instructions) {
3580
+ console.log("\n--- \u6307\u4EE4 ---");
3581
+ console.log(skill.instructions);
3582
+ }
3583
+ }
3584
+ } catch (err) {
3585
+ const msg = err instanceof Error ? err.message : String(err);
3586
+ if (isJson) {
3587
+ console.log(JSON.stringify({ error: msg }));
3588
+ } else {
3589
+ console.error(`\u274C \u83B7\u53D6\u6280\u80FD\u8BE6\u60C5\u5931\u8D25\uFF1A${msg}`);
3590
+ }
3591
+ process.exit(1);
3592
+ }
3593
+ }
3594
+ function printSkillsHelp() {
3595
+ console.log(`
3596
+ webmcp-cli --mode wxt skills - \u67E5\u8BE2\u4E0E\u8BFB\u53D6\u6D4F\u89C8\u5668\u6269\u5C55\u4E2D\u6CE8\u518C\u7684 Skills \u6280\u80FD
3597
+
3598
+ \u7528\u6CD5\uFF1A
3599
+ webmcp-cli --mode wxt skills list \u5217\u51FA\u6240\u6709\u5DF2\u6CE8\u518C\u7684\u6280\u80FD
3600
+ webmcp-cli --mode wxt skills get <name> \u8BFB\u53D6\u6307\u5B9A\u6280\u80FD\u7684\u8BE6\u7EC6\u6267\u884C\u6307\u4EE4
3601
+
3602
+ \u9009\u9879\uFF1A
3603
+ --json \u8F93\u51FA JSON \u683C\u5F0F\u7ED3\u679C
3604
+
3605
+ \u793A\u4F8B\uFF1A
3606
+ webmcp-cli --mode wxt skills list
3607
+ webmcp-cli --mode wxt skills get order-management
3608
+ `.trim());
3609
+ }
3610
+ var init_skills = __esm({
3611
+ "src/commands/skills.ts"() {
3612
+ "use strict";
3613
+ }
3614
+ });
3615
+
3616
+ // src/bin.ts
3617
+ import fs6 from "fs";
3618
+ import path7 from "path";
3619
+ import os5 from "os";
3620
+ import { Command } from "commander";
3621
+ import pc2 from "picocolors";
3622
+ import { readFileSync as readFileSync2 } from "fs";
3623
+ import { resolve as resolve2 } from "path";
3624
+
3625
+ // src/expand-file-refs.ts
3626
+ import { readFileSync } from "fs";
3627
+ import { dirname, isAbsolute, normalize, resolve } from "path";
3628
+ import { fileURLToPath } from "url";
3629
+ var JSON_STRING_LITERAL = /"(?:[^"\\]|\\.)*"/g;
3630
+ var UNQUOTED_FILE_REF = /(?<![\\"])@(base64)?file:([^\s"',}\]]+)/g;
3631
+ var FILE_REF_PREFIX = /^@(base64)?file:(.+)$/s;
3632
+ function resolveFilePath(filePath, baseDir = process.cwd()) {
3633
+ let normalizedPath = filePath.trim();
3634
+ if (normalizedPath.startsWith('"') && normalizedPath.endsWith('"') || normalizedPath.startsWith("'") && normalizedPath.endsWith("'")) {
3635
+ normalizedPath = normalizedPath.slice(1, -1).trim();
3636
+ }
3637
+ if (normalizedPath.startsWith("file://")) {
3638
+ normalizedPath = fileURLToPath(normalizedPath);
3639
+ }
3640
+ if (isAbsolute(normalizedPath)) {
3641
+ return normalize(normalizedPath);
3642
+ }
3643
+ return resolve(baseDir, normalizedPath);
3644
+ }
3645
+ function decodeFilePath(rawPath) {
3646
+ return rawPath.replace(/\\\\/g, "\\");
3647
+ }
3648
+ function readFileRefContent(filePath, baseDir, base64) {
3649
+ const absPath = resolveFilePath(filePath, baseDir);
3650
+ let content;
3651
+ try {
3652
+ content = readFileSync(absPath, "utf-8");
3653
+ } catch (e) {
3654
+ throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6\u5F15\u7528 "${filePath}" (${absPath}): ${e.message}`);
3655
+ }
3656
+ return base64 ? Buffer.from(content, "utf-8").toString("base64") : content;
3657
+ }
3658
+ function expandFileRefValue(rawInner, baseDir) {
3659
+ const match = rawInner.match(FILE_REF_PREFIX);
3660
+ if (!match) {
3661
+ return null;
3662
+ }
3663
+ const [, base64Flag, rawPath] = match;
3664
+ const filePath = decodeFilePath(rawPath);
3665
+ const value = readFileRefContent(filePath, baseDir, Boolean(base64Flag));
3666
+ return JSON.stringify(value);
3667
+ }
3668
+ function expandQuotedFileRefs(argsJson, baseDir) {
3669
+ return argsJson.replace(JSON_STRING_LITERAL, (jsonStringLiteral) => {
3670
+ const rawInner = jsonStringLiteral.slice(1, -1);
3671
+ const replacement = expandFileRefValue(rawInner, baseDir);
3672
+ return replacement ?? jsonStringLiteral;
3673
+ });
3674
+ }
3675
+ function expandUnquotedFileRefs(argsJson, baseDir) {
3676
+ return argsJson.replace(UNQUOTED_FILE_REF, (match, base64Flag, filePath) => {
3677
+ const value = readFileRefContent(filePath, baseDir, Boolean(base64Flag));
3678
+ return JSON.stringify(value);
3679
+ });
3680
+ }
3681
+ function expandFileRefs(argsJson, baseDir = process.cwd()) {
3682
+ const withQuotedExpanded = expandQuotedFileRefs(argsJson, baseDir);
3683
+ return expandUnquotedFileRefs(withQuotedExpanded, baseDir);
3684
+ }
3685
+ function getFileBaseDir(fileOption) {
3686
+ if (!fileOption) {
3687
+ return process.cwd();
3688
+ }
3689
+ return dirname(resolve(process.cwd(), fileOption));
3690
+ }
3691
+
3692
+ // src/parse-run-args.ts
3693
+ import JSON5 from "json5";
3694
+ function cleanJsonString(str) {
3695
+ let cleaned = str.trim();
3696
+ if (cleaned.startsWith("'") && cleaned.endsWith("'")) {
3697
+ cleaned = cleaned.slice(1, -1).trim();
3698
+ }
3699
+ return cleaned;
3700
+ }
3701
+ function looksLikeObjectBody(raw) {
3702
+ return /^("?[\w-]+"?\s*:)/.test(raw);
3703
+ }
3704
+ function joinShellArgs(args) {
3705
+ const cleaned = args.map(cleanJsonString);
3706
+ const first = cleaned[0] ?? "";
3707
+ if (first.startsWith("{")) {
3708
+ return cleaned.join(" ");
531
3709
  }
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.`);
3710
+ if (looksLikeObjectBody(first)) {
3711
+ let joined = cleaned.join(" ");
3712
+ if (!joined.startsWith("{")) {
3713
+ joined = `{${joined}}`;
537
3714
  }
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
- }
3715
+ if (!joined.endsWith("}")) {
3716
+ joined = `${joined}}`;
546
3717
  }
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 {
3718
+ return joined;
3719
+ }
3720
+ return cleaned.join(" ");
3721
+ }
3722
+ function insertMissingCommas(raw) {
3723
+ return raw.replace(/"(\s+)("?[\w-]+"?\s*:)/g, '",$2');
3724
+ }
3725
+ function quoteUnquotedStringValues(raw) {
3726
+ return raw.replace(
3727
+ /([{,]\s*(?:"([^"]+)"|([\w-]+))\s*:\s*)(?!"@(?:base64)?file:|"|true|false|null|-?\d|\{|\[)([^",}\]]+?)(?=\s*[,}])/g,
3728
+ (_match, prefix, _quotedKey, _unquotedKey, value) => {
3729
+ const trimmed = value.trim();
3730
+ if (/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(trimmed)) {
3731
+ return prefix + trimmed;
576
3732
  }
3733
+ return prefix + JSON.stringify(trimmed);
577
3734
  }
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;
3735
+ );
588
3736
  }
589
- async function injectIntoPage(page) {
590
- await injectWebMCPPolyfillAndTools(page);
3737
+ function normalizeShellDamagedJson(raw) {
3738
+ let normalized = raw.trim();
3739
+ normalized = insertMissingCommas(normalized);
3740
+ normalized = quoteUnquotedStringValues(normalized);
3741
+ return normalized;
591
3742
  }
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.`);
3743
+ function buildArgsFromKeyValuePairs(args) {
3744
+ const obj = {};
3745
+ for (const pair of args) {
3746
+ const index = pair.indexOf("=");
3747
+ if (index === -1) {
3748
+ throw new Error(`\u65E0\u6548\u7684\u53C2\u6570\u683C\u5F0F "${pair}"\u3002\u8BF7\u4F7F\u7528 key=value\uFF0C\u6216 JSON / -f \u6587\u4EF6\u3002`);
601
3749
  }
602
- const scriptContent = fs.readFileSync(injectScriptPath, "utf-8");
3750
+ const key = pair.substring(0, index).trim();
3751
+ let val = cleanJsonString(pair.substring(index + 1).trim());
603
3752
  try {
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);
3753
+ obj[key] = JSON.parse(val);
3754
+ } catch {
3755
+ obj[key] = val;
608
3756
  }
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
- });
615
3757
  }
616
- await injectDomainTools(page);
3758
+ return JSON.stringify(obj);
617
3759
  }
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 = [];
3760
+ function parseArgsJson(raw) {
3761
+ const trimmed = cleanJsonString(raw);
625
3762
  try {
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`;
3763
+ return JSON.stringify(JSON5.parse(trimmed));
3764
+ } catch (firstError) {
3765
+ const repaired = normalizeShellDamagedJson(trimmed);
3766
+ try {
3767
+ return JSON.stringify(JSON5.parse(repaired));
3768
+ } catch {
3769
+ 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`;
3770
+ const message = firstError instanceof Error ? firstError.message : String(firstError);
3771
+ throw new Error(`\u53C2\u6570\u4E0D\u662F\u6709\u6548\u7684 JSON \u6216 JS \u5BF9\u8C61: ${message}
3772
+ ${hint}`);
637
3773
  }
638
3774
  }
639
- return null;
640
3775
  }
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;
648
- }
649
- const bundleName = getToolsBundleName(hostname);
650
- if (!bundleName) {
651
- return;
3776
+ function prepareRunArgsJson(args, fileContent, baseDir) {
3777
+ if (fileContent !== void 0) {
3778
+ const trimmed = fileContent.trim();
3779
+ if (!trimmed) {
3780
+ throw new Error("\u901A\u8FC7 -f/--file \u6307\u5B9A\u7684\u53C2\u6570\u6587\u4EF6\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A");
3781
+ }
3782
+ const expanded2 = expandFileRefs(trimmed, baseDir);
3783
+ return parseArgsJson(expanded2);
652
3784
  }
653
- const toolBundlePath = path.resolve(__dirname, bundleName);
654
- if (!fs.existsSync(toolBundlePath)) {
655
- return;
3785
+ if (args.length === 0) {
3786
+ return "{}";
656
3787
  }
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;
3788
+ const joined = joinShellArgs(args);
3789
+ let raw = "";
3790
+ if (joined.startsWith("{") || looksLikeObjectBody(joined)) {
3791
+ raw = joined;
3792
+ } else if (args.every((arg) => arg.includes("="))) {
3793
+ raw = buildArgsFromKeyValuePairs(args);
3794
+ } else {
3795
+ raw = joined;
662
3796
  }
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}`));
3797
+ if (!raw.trim()) {
3798
+ throw new Error("\u672A\u63D0\u4F9B\u6709\u6548\u53C2\u6570");
671
3799
  }
3800
+ const expanded = expandFileRefs(raw, baseDir);
3801
+ return parseArgsJson(expanded);
672
3802
  }
673
3803
 
674
3804
  // src/commands/state.ts
3805
+ init_browser();
675
3806
  async function stateCommand({ tabid }) {
676
3807
  const browser = await connectBrowser();
677
3808
  try {
@@ -725,6 +3856,7 @@ async function stateCommand({ tabid }) {
725
3856
  }
726
3857
 
727
3858
  // src/commands/run.ts
3859
+ init_browser();
728
3860
  async function runCommand({
729
3861
  toolName,
730
3862
  argsJson,
@@ -799,6 +3931,7 @@ async function setClipboard(content) {
799
3931
  }
800
3932
 
801
3933
  // src/commands/tabs.ts
3934
+ init_browser();
802
3935
  function normalizeUrl(url) {
803
3936
  if (!url.startsWith("http://") && !url.startsWith("https://")) {
804
3937
  return "https://" + url;
@@ -920,75 +4053,26 @@ async function tabsForwardCommand(tabid) {
920
4053
  }
921
4054
  }
922
4055
 
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"
988
- }
989
- };
990
-
991
4056
  // src/bin.ts
4057
+ init_package();
4058
+ function extractMode(argv) {
4059
+ let mode = process.env.WEBMCP_MODE === "wxt" ? "wxt" : "cdp";
4060
+ const filteredArgv = [];
4061
+ for (let i = 0; i < argv.length; i++) {
4062
+ if (argv[i] === "--mode" && argv[i + 1]) {
4063
+ const val = argv[i + 1].toLowerCase();
4064
+ if (val === "wxt" || val === "cdp") mode = val;
4065
+ i++;
4066
+ } else if (argv[i].startsWith("--mode=")) {
4067
+ const val = argv[i].split("=")[1]?.toLowerCase();
4068
+ if (val === "wxt" || val === "cdp") mode = val;
4069
+ } else {
4070
+ filteredArgv.push(argv[i]);
4071
+ }
4072
+ }
4073
+ return { mode, filteredArgv };
4074
+ }
4075
+ var { mode: CLI_MODE, filteredArgv: FILTERED_ARGV } = extractMode(process.argv);
992
4076
  var program = new Command();
993
4077
  function parseTabId(id) {
994
4078
  if (!id) return void 0;
@@ -1020,26 +4104,26 @@ function tryParseBrowserStateText(text) {
1020
4104
  }
1021
4105
  function cleanOldLogs(baseDir, logDir) {
1022
4106
  try {
1023
- const oldLogFile = path2.join(baseDir, "webmcp-cli.log");
1024
- if (fs2.existsSync(oldLogFile)) {
4107
+ const oldLogFile = path7.join(baseDir, "webmcp-cli.log");
4108
+ if (fs6.existsSync(oldLogFile)) {
1025
4109
  try {
1026
- fs2.unlinkSync(oldLogFile);
4110
+ fs6.unlinkSync(oldLogFile);
1027
4111
  } catch {
1028
4112
  }
1029
4113
  }
1030
- if (fs2.existsSync(baseDir)) {
1031
- const baseFiles = fs2.readdirSync(baseDir);
4114
+ if (fs6.existsSync(baseDir)) {
4115
+ const baseFiles = fs6.readdirSync(baseDir);
1032
4116
  for (const file of baseFiles) {
1033
4117
  if (/^webmcp-cli-\d{4}-\d{2}-\d{2}\.log$/.test(file)) {
1034
4118
  try {
1035
- fs2.unlinkSync(path2.join(baseDir, file));
4119
+ fs6.unlinkSync(path7.join(baseDir, file));
1036
4120
  } catch {
1037
4121
  }
1038
4122
  }
1039
4123
  }
1040
4124
  }
1041
- if (!fs2.existsSync(logDir)) return;
1042
- const files = fs2.readdirSync(logDir);
4125
+ if (!fs6.existsSync(logDir)) return;
4126
+ const files = fs6.readdirSync(logDir);
1043
4127
  const logFilePattern = /^webmcp-cli-(\d{4}-\d{2}-\d{2})\.log$/;
1044
4128
  const now = Date.now();
1045
4129
  const maxAgeMs = 7 * 24 * 60 * 60 * 1e3;
@@ -1051,7 +4135,7 @@ function cleanOldLogs(baseDir, logDir) {
1051
4135
  if (isNaN(fileDate)) continue;
1052
4136
  if (now - fileDate > maxAgeMs) {
1053
4137
  try {
1054
- fs2.unlinkSync(path2.join(logDir, file));
4138
+ fs6.unlinkSync(path7.join(logDir, file));
1055
4139
  } catch {
1056
4140
  }
1057
4141
  }
@@ -1107,13 +4191,13 @@ ${searchResultStr}`;
1107
4191
  }
1108
4192
  function writeLog(commandName, args, result, error) {
1109
4193
  try {
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 });
4194
+ const baseDir = process.env.WEBMCP_WORKSPACE || path7.join(os5.homedir(), ".webmcp_chrome_profile");
4195
+ const logDir = path7.join(baseDir, "logs");
4196
+ if (!fs6.existsSync(logDir)) {
4197
+ fs6.mkdirSync(logDir, { recursive: true });
1114
4198
  }
1115
4199
  const todayStr = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
1116
- const logFile = path2.join(logDir, `webmcp-cli-${todayStr}.log`);
4200
+ const logFile = path7.join(logDir, `webmcp-cli-${todayStr}.log`);
1117
4201
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
1118
4202
  let logText = `========================================
1119
4203
  `;
@@ -1139,7 +4223,7 @@ ${error instanceof Error ? error.stack : String(error)}
1139
4223
  logText += `========================================
1140
4224
 
1141
4225
  `;
1142
- fs2.appendFileSync(logFile, logText, "utf-8");
4226
+ fs6.appendFileSync(logFile, logText, "utf-8");
1143
4227
  cleanOldLogs(baseDir, logDir);
1144
4228
  } catch (e) {
1145
4229
  }
@@ -1150,11 +4234,22 @@ function handleCommandError(error, commandName, args) {
1150
4234
  console.error(pc2.red(`Error executing ${commandName} command: ${msg}`));
1151
4235
  process.exit(1);
1152
4236
  }
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) => {
4237
+ program.name("webmcp-cli").description(
4238
+ "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"
4239
+ ).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(
4240
+ "--ignore-certificate-errors",
4241
+ "\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"
4242
+ ).hook("preAction", (thisCommand) => {
1154
4243
  const opts = thisCommand.opts();
1155
4244
  if (opts.workspace) {
1156
4245
  process.env.WEBMCP_WORKSPACE = opts.workspace;
1157
4246
  }
4247
+ if (opts.ignoreCertificateErrors) {
4248
+ process.env.WEBMCP_IGNORE_CERTIFICATE_ERRORS = "1";
4249
+ }
4250
+ if (process.env.WEBMCP_IGNORE_CERTIFICATE_ERRORS === "1") {
4251
+ console.error(pc2.yellow("\u5F53\u524D\u53D7\u63A7\u6D4F\u89C8\u5668\u5DF2\u5173\u95ED TLS \u8BC1\u4E66\u6821\u9A8C\u3002"));
4252
+ }
1158
4253
  });
1159
4254
  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) => {
1160
4255
  const args = { tabid: parseTabId(options.tabid) };
@@ -1262,5 +4357,174 @@ tabs.command("forward [tabid]").description("\u5C06\u5F53\u524D\u6216\u6307\u5B9
1262
4357
  handleCommandError(error, "tabs forward", args);
1263
4358
  }
1264
4359
  });
1265
- program.parse(process.argv);
4360
+ 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) => {
4361
+ try {
4362
+ const { startMcpServer: startMcpServer2 } = await Promise.resolve().then(() => (init_server(), server_exports));
4363
+ await startMcpServer2({ mode: "cdp", agentMode: opts.agent ? "agent" : "tools" });
4364
+ } catch (error) {
4365
+ handleCommandError(error, "mcp", {});
4366
+ }
4367
+ });
4368
+ if (CLI_MODE === "wxt") {
4369
+ void handleWxtMode(FILTERED_ARGV.slice(2)).catch((error) => {
4370
+ handleCommandError(error, `wxt:${FILTERED_ARGV[2] ?? "help"}`, {});
4371
+ });
4372
+ } else {
4373
+ program.parse(FILTERED_ARGV);
4374
+ }
4375
+ async function handleWxtMode(args) {
4376
+ const command = args[0];
4377
+ if (command === "daemon" || command === "server") {
4378
+ const { runDaemonProcess: runDaemonProcess2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
4379
+ await runDaemonProcess2(args.slice(1));
4380
+ return;
4381
+ }
4382
+ if (command === "stop") {
4383
+ const { stopBridgeDaemon: stopBridgeDaemon2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
4384
+ const stopped = await stopBridgeDaemon2();
4385
+ 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");
4386
+ return;
4387
+ }
4388
+ if (command === "token") {
4389
+ const subArgs = args.slice(1);
4390
+ let wsPort2;
4391
+ const cleanArgs = [];
4392
+ for (let i = 0; i < subArgs.length; i++) {
4393
+ if ((subArgs[i] === "--ws-port" || subArgs[i] === "--port") && subArgs[i + 1]) {
4394
+ wsPort2 = parseInt(subArgs[++i], 10) || void 0;
4395
+ } else {
4396
+ cleanArgs.push(subArgs[i]);
4397
+ }
4398
+ }
4399
+ const action = cleanArgs[0];
4400
+ let tokenToSet;
4401
+ if (action === "set" && cleanArgs[1]) {
4402
+ tokenToSet = cleanArgs[1].trim();
4403
+ } else if (action && action !== "get" && !action.startsWith("-")) {
4404
+ tokenToSet = action.trim();
4405
+ }
4406
+ const { resolveOrCreateAuthToken: resolveOrCreateAuthToken2 } = await Promise.resolve().then(() => (init_bridge_client(), bridge_client_exports));
4407
+ if (tokenToSet) {
4408
+ resolveOrCreateAuthToken2(tokenToSet);
4409
+ console.log("\u2705 Token \u5DF2\u6210\u529F\u4FDD\u5B58\u81F3 ~/.robot-wxt/bridge-token");
4410
+ const { stopBridgeDaemon: stopBridgeDaemon2, ensureBridgeDaemon: ensureBridgeDaemon3 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
4411
+ await stopBridgeDaemon2(wsPort2);
4412
+ await ensureBridgeDaemon3({ token: tokenToSet, port: wsPort2 });
4413
+ 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");
4414
+ return;
4415
+ }
4416
+ console.log(resolveOrCreateAuthToken2());
4417
+ return;
4418
+ }
4419
+ if (command === "mcp") {
4420
+ const { startMcpServer: startMcpServer2 } = await Promise.resolve().then(() => (init_server(), server_exports));
4421
+ const isAgent = args.includes("--agent") || args.includes("--mode=agent");
4422
+ const tokenIdx = args.indexOf("--token");
4423
+ const token2 = tokenIdx !== -1 ? args[tokenIdx + 1] : void 0;
4424
+ const wsPortIdx = args.indexOf("--ws-port");
4425
+ const wsPort2 = wsPortIdx !== -1 ? parseInt(args[wsPortIdx + 1], 10) || void 0 : void 0;
4426
+ await startMcpServer2({ mode: "wxt", agentMode: isAgent ? "agent" : "tools", token: token2, wsPort: wsPort2 });
4427
+ return;
4428
+ }
4429
+ if (!command || command === "--help" || command === "-h") {
4430
+ printWxtHelp();
4431
+ return;
4432
+ }
4433
+ let token;
4434
+ let wsPort;
4435
+ const commandArgs = [];
4436
+ for (let i = 1; i < args.length; i++) {
4437
+ if (args[i] === "--token" && args[i + 1]) {
4438
+ token = args[++i];
4439
+ } else if (args[i] === "--ws-port" && args[i + 1]) {
4440
+ wsPort = parseInt(args[++i], 10) || void 0;
4441
+ } else {
4442
+ commandArgs.push(args[i]);
4443
+ }
4444
+ }
4445
+ const { ensureBridgeDaemon: ensureBridgeDaemon2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
4446
+ const isJson = commandArgs.includes("--json");
4447
+ await ensureBridgeDaemon2({ token, port: wsPort, silent: isJson });
4448
+ const { WxtBrowserAdapter: WxtBrowserAdapter2 } = await Promise.resolve().then(() => (init_wxt_adapter(), wxt_adapter_exports));
4449
+ const adapter = new WxtBrowserAdapter2(token, wsPort);
4450
+ await adapter.ensureConnected();
4451
+ try {
4452
+ switch (command) {
4453
+ case "state": {
4454
+ const tabIdx = commandArgs.indexOf("--tab");
4455
+ const tabId = tabIdx !== -1 ? commandArgs[tabIdx + 1] : void 0;
4456
+ const result = await adapter.getState(tabId ? parseInt(tabId, 10) : void 0);
4457
+ console.log(JSON.stringify(result, null, 2));
4458
+ break;
4459
+ }
4460
+ case "run": {
4461
+ const toolName = commandArgs.find((a) => !a.startsWith("-"));
4462
+ const argsStr = commandArgs.slice(commandArgs.indexOf(toolName) + 1).find((a) => !a.startsWith("-"));
4463
+ if (!toolName) {
4464
+ console.error("[\u9519\u8BEF] \u8BF7\u63D0\u4F9B\u5DE5\u5177\u540D\u79F0");
4465
+ process.exit(1);
4466
+ }
4467
+ const toolArgs = argsStr ? JSON.parse(argsStr) : {};
4468
+ const result = await adapter.callTool(toolName, toolArgs);
4469
+ console.log(JSON.stringify(result, null, 2));
4470
+ break;
4471
+ }
4472
+ case "tabs": {
4473
+ const tabAction = commandArgs[0];
4474
+ const tabArgs = commandArgs.slice(1);
4475
+ const url = tabArgs.find((a) => a.startsWith("http"));
4476
+ const tabIdVal = tabArgs.find((a) => !a.startsWith("-") && !a.startsWith("http"));
4477
+ const result = await adapter.tabs(tabAction, {
4478
+ url,
4479
+ tabId: tabIdVal ? parseInt(tabIdVal, 10) : void 0
4480
+ });
4481
+ console.log(JSON.stringify(result, null, 2));
4482
+ break;
4483
+ }
4484
+ case "agent": {
4485
+ const { handleAgentCommand: handleAgentCommand2 } = await Promise.resolve().then(() => (init_agent(), agent_exports));
4486
+ await handleAgentCommand2(adapter, commandArgs);
4487
+ break;
4488
+ }
4489
+ case "skills":
4490
+ case "skill": {
4491
+ const { handleSkillsCommand: handleSkillsCommand2 } = await Promise.resolve().then(() => (init_skills(), skills_exports));
4492
+ await handleSkillsCommand2(adapter, commandArgs);
4493
+ break;
4494
+ }
4495
+ default:
4496
+ console.error(`[\u9519\u8BEF] WXT \u6A21\u5F0F\u4E0B\u672A\u77E5\u547D\u4EE4: ${command}`);
4497
+ printWxtHelp();
4498
+ process.exit(1);
4499
+ }
4500
+ } finally {
4501
+ await adapter.dispose();
4502
+ }
4503
+ }
4504
+ function printWxtHelp() {
4505
+ console.log(`
4506
+ 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
4507
+
4508
+ \u547D\u4EE4\uFF1A
4509
+ state \u83B7\u53D6\u5F53\u524D\u6D3B\u8DC3 tab \u4FE1\u606F\u4E0E\u9875\u9762\u5DE5\u5177\u5217\u8868
4510
+ run <tool> [args] \u8C03\u7528\u9875\u9762 WebMCP \u5DE5\u5177
4511
+ tabs <action> [...] \u7BA1\u7406\u6807\u7B7E\u9875\uFF08open/close/switch/back/forward\uFF09
4512
+ agent run "<\u6307\u4EE4>" \u59D4\u6258 Tiny Robot \u5B50\u4EE3\u7406\u81EA\u4E3B\u6267\u884C\u9AD8\u5C42\u4EFB\u52A1
4513
+ skills list \u5217\u51FA\u5DF2\u6CE8\u518C\u7684 Skills \u6280\u80FD
4514
+ skills get <name> \u8BFB\u53D6\u6307\u5B9A\u6280\u80FD\u7684\u8BE6\u7EC6\u6307\u4EE4
4515
+ token [get|set <t>] \u67E5\u770B\u6216\u4FDD\u5B58\u8BA4\u8BC1 Token
4516
+ stop \u505C\u6B62\u540E\u53F0 WebSocket \u6865\u63A5\u670D\u52A1
4517
+ mcp \u4EE5 MCP Server \u6A21\u5F0F\u542F\u52A8
4518
+
4519
+ \u9009\u9879\uFF1A
4520
+ --token <token> \u8BA4\u8BC1 Token\uFF08\u4F18\u5148\u4E8E ~/.robot-wxt/bridge-token\uFF09
4521
+ --ws-port <port> WS \u6865\u63A5\u7AEF\u53E3\uFF08\u9ED8\u8BA4 18999\uFF09
4522
+ --json \u8F93\u51FA JSON \u683C\u5F0F
4523
+
4524
+ \u793A\u4F8B\uFF1A
4525
+ webmcp-cli --mode wxt state
4526
+ webmcp-cli --mode wxt agent run "\u5E2E\u6211\u628A\u5546\u54C1\u52A0\u5165\u8D2D\u7269\u8F66"
4527
+ webmcp-cli --mode wxt mcp --agent
4528
+ `.trim());
4529
+ }
1266
4530
  //# sourceMappingURL=bin.js.map