vite-plugin-opencode-assistant 1.1.24 → 1.1.25

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.
@@ -0,0 +1,21 @@
1
+ export interface McpProxyOptions {
2
+ args?: string[];
3
+ idleTimeout?: number;
4
+ }
5
+ export declare class McpProxy {
6
+ #private;
7
+ readonly sessionId: string;
8
+ readonly accessToken: string;
9
+ constructor(options?: McpProxyOptions);
10
+ get isRunning(): boolean;
11
+ start(): Promise<void>;
12
+ /** 转发原始 JSON-RPC 请求,保留客户端 ID */
13
+ forward(rawRequest: string): Promise<string>;
14
+ /** 调用 MCP 工具 */
15
+ call(method: string, params?: Record<string, unknown>): Promise<unknown>;
16
+ /** 直接调用 chrome-devtools-mcp 底层工具(内部使用) */
17
+ callChromeDevTool(name: string, args?: Record<string, unknown>): Promise<unknown>;
18
+ /** 验证 MCP 是否可用 + 预热 CDP 连接 */
19
+ verify(): Promise<boolean>;
20
+ stop(): void;
21
+ }
@@ -0,0 +1,254 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __typeError = (msg) => {
3
+ throw TypeError(msg);
4
+ };
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
8
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
9
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
10
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
11
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
12
+ var __privateWrapper = (obj, member, setter, getter) => ({
13
+ set _(value) {
14
+ __privateSet(obj, member, value, setter);
15
+ },
16
+ get _() {
17
+ return __privateGet(obj, member, getter);
18
+ }
19
+ });
20
+ var __async = (__this, __arguments, generator) => {
21
+ return new Promise((resolve, reject) => {
22
+ var fulfilled = (value) => {
23
+ try {
24
+ step(generator.next(value));
25
+ } catch (e) {
26
+ reject(e);
27
+ }
28
+ };
29
+ var rejected = (value) => {
30
+ try {
31
+ step(generator.throw(value));
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ };
36
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
+ step((generator = generator.apply(__this, __arguments)).next());
38
+ });
39
+ };
40
+ const import_meta = {};
41
+ var _proc, _rl, _messageId, _internalIdBase, _pending, _args, _startPromise, _idleTimer, _idleTimeout, _McpProxy_instances, doStart_fn, resetIdleTimer_fn;
42
+ import { spawn } from "node:child_process";
43
+ import { createInterface } from "node:readline";
44
+ import crypto from "node:crypto";
45
+ import { createRequire } from "node:module";
46
+ import path from "node:path";
47
+ import { createLogger } from "@vite-plugin-opencode-assistant/shared/node";
48
+ const log = createLogger("McpProxy");
49
+ function resolveChromeDevToolsMcpBin() {
50
+ const require2 = createRequire(import_meta.url);
51
+ const pkgJsonPath = require2.resolve("chrome-devtools-mcp/package.json");
52
+ const pkgDir = path.dirname(pkgJsonPath);
53
+ const { bin } = require2(pkgJsonPath);
54
+ const binEntry = typeof bin === "string" ? bin : Object.values(bin)[0];
55
+ return path.resolve(pkgDir, binEntry);
56
+ }
57
+ class McpProxy {
58
+ constructor(options = {}) {
59
+ __privateAdd(this, _McpProxy_instances);
60
+ __privateAdd(this, _proc, null);
61
+ __privateAdd(this, _rl, null);
62
+ __privateAdd(this, _messageId, 0);
63
+ /** 内部调用使用的高位 ID 起始值,避免与客户端 ID 冲突 */
64
+ __privateAdd(this, _internalIdBase, 1e6);
65
+ __privateAdd(this, _pending, /* @__PURE__ */ new Map());
66
+ __privateAdd(this, _args);
67
+ __privateAdd(this, _startPromise, null);
68
+ __privateAdd(this, _idleTimer, null);
69
+ __privateAdd(this, _idleTimeout);
70
+ __publicField(this, "sessionId");
71
+ __publicField(this, "accessToken");
72
+ var _a, _b;
73
+ __privateSet(this, _args, (_a = options.args) != null ? _a : ["--auto-connect", "--no-usage-statistics"]);
74
+ __privateSet(this, _idleTimeout, (_b = options.idleTimeout) != null ? _b : 0);
75
+ this.sessionId = crypto.randomUUID();
76
+ this.accessToken = crypto.randomBytes(32).toString("hex");
77
+ }
78
+ get isRunning() {
79
+ return __privateGet(this, _proc) !== null && !__privateGet(this, _proc).killed;
80
+ }
81
+ start() {
82
+ return __async(this, null, function* () {
83
+ if (this.isRunning) return;
84
+ if (__privateGet(this, _startPromise)) return __privateGet(this, _startPromise);
85
+ __privateSet(this, _startPromise, __privateMethod(this, _McpProxy_instances, doStart_fn).call(this));
86
+ return __privateGet(this, _startPromise);
87
+ });
88
+ }
89
+ /** 转发原始 JSON-RPC 请求,保留客户端 ID */
90
+ forward(rawRequest) {
91
+ return __async(this, null, function* () {
92
+ yield this.start();
93
+ if (!__privateGet(this, _proc) || !__privateGet(this, _proc).stdin) {
94
+ throw new Error("MCP process not available");
95
+ }
96
+ __privateMethod(this, _McpProxy_instances, resetIdleTimer_fn).call(this);
97
+ let msg;
98
+ try {
99
+ msg = JSON.parse(rawRequest);
100
+ } catch (e) {
101
+ throw new Error("Invalid JSON-RPC request");
102
+ }
103
+ return new Promise((resolve, reject) => {
104
+ const id = msg.id;
105
+ if (id !== void 0) {
106
+ __privateGet(this, _pending).set(id, (raw) => resolve(JSON.stringify(raw)));
107
+ } else {
108
+ __privateGet(this, _proc).stdin.write(rawRequest + "\n");
109
+ resolve("");
110
+ return;
111
+ }
112
+ __privateGet(this, _proc).stdin.write(rawRequest + "\n");
113
+ setTimeout(() => {
114
+ if (__privateGet(this, _pending).has(id)) {
115
+ __privateGet(this, _pending).delete(id);
116
+ reject(new Error("MCP forward timeout"));
117
+ }
118
+ }, 3e4);
119
+ });
120
+ });
121
+ }
122
+ /** 调用 MCP 工具 */
123
+ call(_0) {
124
+ return __async(this, arguments, function* (method, params = {}) {
125
+ yield this.start();
126
+ if (!__privateGet(this, _proc) || !__privateGet(this, _proc).stdin) {
127
+ throw new Error("MCP process not available");
128
+ }
129
+ __privateMethod(this, _McpProxy_instances, resetIdleTimer_fn).call(this);
130
+ const id = __privateGet(this, _internalIdBase) + ++__privateWrapper(this, _messageId)._;
131
+ return new Promise((resolve, reject) => {
132
+ __privateGet(this, _pending).set(id, resolve);
133
+ const request = JSON.stringify({ jsonrpc: "2.0", id, method, params });
134
+ __privateGet(this, _proc).stdin.write(request + "\n");
135
+ setTimeout(() => {
136
+ if (__privateGet(this, _pending).has(id)) {
137
+ __privateGet(this, _pending).delete(id);
138
+ reject(new Error(`MCP call timeout: ${method}`));
139
+ }
140
+ }, 3e4);
141
+ });
142
+ });
143
+ }
144
+ /** 直接调用 chrome-devtools-mcp 底层工具(内部使用) */
145
+ callChromeDevTool(_0) {
146
+ return __async(this, arguments, function* (name, args = {}) {
147
+ return this.call("tools/call", { name, arguments: args });
148
+ });
149
+ }
150
+ /** 验证 MCP 是否可用 + 预热 CDP 连接 */
151
+ verify() {
152
+ return __async(this, null, function* () {
153
+ try {
154
+ yield this.callChromeDevTool("list_pages", {});
155
+ return true;
156
+ } catch (e) {
157
+ return false;
158
+ }
159
+ });
160
+ }
161
+ stop() {
162
+ if (__privateGet(this, _idleTimer)) clearTimeout(__privateGet(this, _idleTimer));
163
+ const err = new Error("MCP server shutting down");
164
+ for (const resolve of __privateGet(this, _pending).values()) {
165
+ resolve({ error: { code: -32e3, message: err.message } });
166
+ }
167
+ __privateGet(this, _pending).clear();
168
+ if (__privateGet(this, _rl)) {
169
+ __privateGet(this, _rl).close();
170
+ __privateSet(this, _rl, null);
171
+ }
172
+ if (__privateGet(this, _proc) && !__privateGet(this, _proc).killed) {
173
+ __privateGet(this, _proc).kill();
174
+ __privateSet(this, _proc, null);
175
+ }
176
+ __privateSet(this, _startPromise, null);
177
+ }
178
+ }
179
+ _proc = new WeakMap();
180
+ _rl = new WeakMap();
181
+ _messageId = new WeakMap();
182
+ _internalIdBase = new WeakMap();
183
+ _pending = new WeakMap();
184
+ _args = new WeakMap();
185
+ _startPromise = new WeakMap();
186
+ _idleTimer = new WeakMap();
187
+ _idleTimeout = new WeakMap();
188
+ _McpProxy_instances = new WeakSet();
189
+ doStart_fn = function() {
190
+ return __async(this, null, function* () {
191
+ var _a;
192
+ log.debug("Starting MCP process", { args: __privateGet(this, _args) });
193
+ try {
194
+ const binPath = resolveChromeDevToolsMcpBin();
195
+ __privateSet(this, _proc, spawn(binPath, __privateGet(this, _args), { stdio: ["pipe", "pipe", "pipe"] }));
196
+ log.debug("Using local chrome-devtools-mcp");
197
+ } catch (e) {
198
+ __privateSet(this, _proc, spawn("npx", ["-y", "chrome-devtools-mcp@latest", ...__privateGet(this, _args)], {
199
+ stdio: ["pipe", "pipe", "pipe"]
200
+ }));
201
+ }
202
+ __privateSet(this, _rl, createInterface({ input: __privateGet(this, _proc).stdout }));
203
+ __privateGet(this, _rl).on("line", (line) => {
204
+ try {
205
+ const msg = JSON.parse(line);
206
+ log.debug("MCP stdout", {
207
+ id: msg.id,
208
+ method: msg.method,
209
+ hasResult: !!msg.result,
210
+ hasError: !!msg.error
211
+ });
212
+ if (msg.id !== void 0 && __privateGet(this, _pending).has(msg.id)) {
213
+ const resolve = __privateGet(this, _pending).get(msg.id);
214
+ __privateGet(this, _pending).delete(msg.id);
215
+ log.debug("MCP pending resolved", { id: msg.id });
216
+ resolve(msg);
217
+ }
218
+ } catch (e) {
219
+ }
220
+ });
221
+ (_a = __privateGet(this, _proc).stderr) == null ? void 0 : _a.on("data", (d) => {
222
+ const text = d.toString().trim();
223
+ if (text) log.debug("[MCP stderr]", { text: text.substring(0, 200) });
224
+ });
225
+ __privateGet(this, _proc).on("close", (code) => {
226
+ log.debug("MCP process closed", { code });
227
+ for (const resolve of __privateGet(this, _pending).values()) {
228
+ resolve({ error: { code: -32e3, message: `MCP process exited with code ${code}` } });
229
+ }
230
+ __privateGet(this, _pending).clear();
231
+ __privateSet(this, _proc, null);
232
+ __privateSet(this, _rl, null);
233
+ __privateSet(this, _startPromise, null);
234
+ });
235
+ yield this.call("initialize", {
236
+ protocolVersion: "2024-11-05",
237
+ capabilities: {},
238
+ clientInfo: { name: "vite-plugin-opencode", version: "1.0.0" }
239
+ });
240
+ log.debug("MCP proxy ready");
241
+ __privateSet(this, _startPromise, null);
242
+ });
243
+ };
244
+ resetIdleTimer_fn = function() {
245
+ if (__privateGet(this, _idleTimeout) <= 0) return;
246
+ if (__privateGet(this, _idleTimer)) clearTimeout(__privateGet(this, _idleTimer));
247
+ __privateSet(this, _idleTimer, setTimeout(() => {
248
+ log.debug("MCP process idle timeout, stopping");
249
+ this.stop();
250
+ }, __privateGet(this, _idleTimeout)));
251
+ };
252
+ export {
253
+ McpProxy
254
+ };
@@ -1,4 +1,4 @@
1
1
  import type { ResultPromise } from "execa";
2
2
  import type { WebOptions } from "@vite-plugin-opencode-assistant/shared";
3
- export declare function prepareOpenCodeRuntime(cwd: string): string;
3
+ export declare function prepareOpenCodeRuntime(cwd: string, vitePort: number, mcpToken: string): string;
4
4
  export declare function startOpenCodeWeb(options: WebOptions): ResultPromise;
@@ -22,11 +22,12 @@ import fs from "fs";
22
22
  import { createRequire } from "module";
23
23
  import path from "path";
24
24
  import { pathToFileURL } from "url";
25
+ import { MCP_API_PATH } from "@vite-plugin-opencode-assistant/shared";
25
26
  import { createLogger, getProcessLogBuffer } from "@vite-plugin-opencode-assistant/shared/node";
26
27
  const require2 = createRequire(path.join(process.cwd(), "package.json"));
27
28
  const packageDir = resolvePackageDir();
28
29
  const log = createLogger("OpenCodeWeb");
29
- function prepareOpenCodeRuntime(cwd) {
30
+ function prepareOpenCodeRuntime(cwd, vitePort, mcpToken) {
30
31
  const cacheDir = path.join(cwd, "node_modules", ".cache", "opencode");
31
32
  log.debug("Setting up OpenCode runtime", { cacheDir });
32
33
  if (!fs.existsSync(cacheDir)) {
@@ -42,9 +43,8 @@ function prepareOpenCodeRuntime(cwd) {
42
43
  plugin: plugins,
43
44
  mcp: {
44
45
  "chrome-devtools": {
45
- type: "local",
46
- command: ["npx", "-y", "chrome-devtools-mcp@latest", "--autoConnect"],
47
- enabled: true
46
+ type: "remote",
47
+ url: `http://localhost:${vitePort}${MCP_API_PATH}?token=${mcpToken}`
48
48
  }
49
49
  }
50
50
  },
@@ -4,6 +4,7 @@ import type { ModelInfo } from "@vite-plugin-opencode-assistant/shared";
4
4
  import type { OpenCodeOptions, ServiceStartupTask } from "@vite-plugin-opencode-assistant/shared";
5
5
  import { ChromeMcpWarmupErrorType } from "@vite-plugin-opencode-assistant/shared";
6
6
  import type { OpenCodeAPI } from "./api";
7
+ import type { McpProxy } from "./mcp-proxy";
7
8
  export declare class OpenCodeService {
8
9
  private config;
9
10
  private api;
@@ -26,7 +27,7 @@ export declare class OpenCodeService {
26
27
  workspaceRoot: string | null;
27
28
  constructor(config: Required<OpenCodeOptions>, api: OpenCodeAPI, sseClients: Set<http.ServerResponse>, onPortAllocated: (port: number) => void, onProxyPortAllocated: (port: number) => void);
28
29
  private sendTaskUpdate;
29
- start(corsOrigins?: string[], contextApiUrl?: string, logsApiUrl?: string, viteOrigin?: string): Promise<void>;
30
+ start(mcpToken: string, vitePort: number, corsOrigins: string[], contextApiUrl: string, logsApiUrl: string, viteOrigin: string, mcp: McpProxy): Promise<void>;
30
31
  getAvailableModels(): Promise<ModelInfo[]>;
31
32
  retryWarmupChromeMcp(viteOrigin?: string, selectedModel?: {
32
33
  providerID: string;
@@ -87,7 +87,7 @@ class OpenCodeService {
87
87
  }
88
88
  });
89
89
  }
90
- start(corsOrigins, contextApiUrl, logsApiUrl, viteOrigin) {
90
+ start(mcpToken, vitePort, corsOrigins, contextApiUrl, logsApiUrl, viteOrigin, mcp) {
91
91
  return __async(this, null, function* () {
92
92
  if (this.isStarted && this.webProcess) {
93
93
  log.debug("Services already started, skipping");
@@ -148,7 +148,7 @@ Please install OpenCode first:
148
148
  this.workspaceRoot = findGitRoot(process.cwd());
149
149
  log.debug(`Using workspace root: ${this.workspaceRoot}`);
150
150
  this.sendTaskUpdate("preparing_runtime");
151
- const configDir = prepareOpenCodeRuntime(this.workspaceRoot);
151
+ const configDir = prepareOpenCodeRuntime(this.workspaceRoot, vitePort, mcpToken);
152
152
  timer.checkpoint("Plugin setup complete");
153
153
  this.sendTaskUpdate("starting_web");
154
154
  log.debug("Starting OpenCode Web process...", {
@@ -238,7 +238,8 @@ Please install OpenCode first:
238
238
  this.sendTaskUpdate("warming_up_chrome");
239
239
  let warmupFailed = false;
240
240
  try {
241
- yield this.api.warmupChromeMcp(this.workspaceRoot, viteOrigin);
241
+ const ok = yield mcp.verify();
242
+ if (!ok) throw new Error("MCP tools list returned empty");
242
243
  timer.checkpoint("Chrome MCP warmup complete");
243
244
  } catch (e) {
244
245
  log.warn("Chrome MCP warmup failed", { error: e });
@@ -1,3 +1,38 @@
1
1
  import type { ViteDevServer } from "vite";
2
+ import type { McpProxy } from "../core/mcp-proxy";
2
3
  import type { EndpointContext } from "./types";
4
+ /** 从页面 URL 提取项目 origin(protocol + host + port) */
5
+ export declare function getProjectOrigin(pageUrl: string): string | null;
6
+ export interface PageInfo {
7
+ pageId: number;
8
+ url: string;
9
+ title: string;
10
+ /** Chrome DevTools 当前选中的页面 */
11
+ selected: boolean;
12
+ }
13
+ /** 解析 list_pages 返回的文本。格式:"56: Title (URL) [selected]" */
14
+ export declare function parseListPages(text: string): PageInfo[];
15
+ /** 从 evaluate_script 返回的格式化文本中提取 JSON 值 */
16
+ export declare function extractEvalValue(text: string | undefined): string | undefined;
17
+ type PageIdResult = {
18
+ ok: true;
19
+ pageId: number;
20
+ } | {
21
+ ok: false;
22
+ error: string;
23
+ };
24
+ /**
25
+ * 通过 MCP 解析当前页面对应的 Chrome DevTools pageId
26
+ *
27
+ * 策略:
28
+ * 1. list_pages → 解析每行的 "pageId: title (URL)" 格式
29
+ * 2. 优先用 sessionId 匹配(跨导航可靠,遍历所有页面 evaluate_script)
30
+ * 3. 无 sessionId 时降级为 URL 精确匹配
31
+ *
32
+ * 失败时返回具体原因,由调用方透传给 Agent。
33
+ */
34
+ export declare function resolveChromePageId(mcp: McpProxy | undefined, url: string, title: string, sessionId?: string, pages?: PageInfo[],
35
+ /** Chrome 当前选中的 pageId(调用方传入,避免过滤后丢失非项目页面信息) */
36
+ chromeSelectedPageId?: number): Promise<PageIdResult>;
3
37
  export declare function setupContextEndpoint(server: ViteDevServer, ctx: EndpointContext): void;
38
+ export {};
@@ -21,6 +21,121 @@ var __async = (__this, __arguments, generator) => {
21
21
  import { CONTEXT_API_PATH } from "@vite-plugin-opencode-assistant/shared";
22
22
  import { RequestContext, createLogger } from "@vite-plugin-opencode-assistant/shared/node";
23
23
  const log = createLogger("Endpoints:Context");
24
+ function getProjectOrigin(pageUrl) {
25
+ try {
26
+ return new URL(pageUrl).origin;
27
+ } catch (e) {
28
+ return null;
29
+ }
30
+ }
31
+ function parseListPages(text) {
32
+ const pages = [];
33
+ for (const line of text.split("\n")) {
34
+ const match = line.match(/^(\d+):\s*(.+?)\s*\((\S+)\)/);
35
+ if (match) {
36
+ pages.push({
37
+ pageId: parseInt(match[1], 10),
38
+ title: match[2].replace(/\s*\.{3}$/, "").trim(),
39
+ url: match[3],
40
+ selected: /\[selected\]/i.test(line)
41
+ });
42
+ }
43
+ }
44
+ return pages;
45
+ }
46
+ function extractEvalValue(text) {
47
+ if (!text) return void 0;
48
+ const marker = "```json\n";
49
+ const startIdx = text.indexOf(marker);
50
+ if (startIdx < 0) return text.trim();
51
+ const contentStart = startIdx + marker.length;
52
+ const endIdx = text.indexOf("\n```", contentStart);
53
+ const jsonStr = endIdx < 0 ? text.substring(contentStart) : text.substring(contentStart, endIdx);
54
+ try {
55
+ return JSON.parse(jsonStr.trim());
56
+ } catch (e) {
57
+ return jsonStr.trim();
58
+ }
59
+ }
60
+ function resolveChromePageId(mcp, url, title, sessionId, pages, chromeSelectedPageId) {
61
+ return __async(this, null, function* () {
62
+ var _a, _b, _c, _d, _e, _f, _g;
63
+ if (!mcp || !mcp.isRunning) {
64
+ const reason = !mcp ? "MCP \u6A21\u5757\u672A\u521D\u59CB\u5316" : "Chrome DevTools MCP \u8FDB\u7A0B\u672A\u542F\u52A8";
65
+ log.debug(`resolveChromePageId: ${reason}`);
66
+ return { ok: false, error: reason };
67
+ }
68
+ if (!url) {
69
+ return { ok: false, error: "\u9875\u9762 URL \u4E3A\u7A7A\uFF0C\u5C1A\u672A\u6536\u5230\u4E0A\u4E0B\u6587\u4FE1\u606F" };
70
+ }
71
+ try {
72
+ if (!pages) {
73
+ const listResult = yield mcp.callChromeDevTool("list_pages", {});
74
+ const text = (_c = (_b = (_a = listResult == null ? void 0 : listResult.result) == null ? void 0 : _a.content) == null ? void 0 : _b[0]) == null ? void 0 : _c.text;
75
+ if (!text) {
76
+ return { ok: false, error: "\u65E0\u6CD5\u83B7\u53D6 Chrome \u9875\u9762\u5217\u8868\uFF0C\u8BF7\u786E\u8BA4\u5DF2\u6253\u5F00\u76EE\u6807\u9875\u9762" };
77
+ }
78
+ const allPages = parseListPages(text);
79
+ chromeSelectedPageId = (_d = allPages.find((p) => p.selected)) == null ? void 0 : _d.pageId;
80
+ const projectOrigin = getProjectOrigin(url);
81
+ pages = projectOrigin ? allPages.filter((p) => p.url.startsWith(projectOrigin)) : allPages;
82
+ }
83
+ log.debug("resolveChromePageId: list_pages result", {
84
+ pages: pages.map((p) => ({ id: p.pageId, url: p.url, title: p.title.substring(0, 40) })),
85
+ target: { url, title }
86
+ });
87
+ const normalizeUrl = (u) => u.replace(/\/$/, "");
88
+ const targetUrl = normalizeUrl(url);
89
+ if (sessionId) {
90
+ let matchedPageId = null;
91
+ for (const page of pages) {
92
+ yield mcp.callChromeDevTool("select_page", { pageId: page.pageId, bringToFront: false });
93
+ const evalResult = yield mcp.callChromeDevTool("evaluate_script", {
94
+ function: "() => sessionStorage.getItem('_opencode_pk')"
95
+ });
96
+ const rawText = (_g = (_f = (_e = evalResult == null ? void 0 : evalResult.result) == null ? void 0 : _e.content) == null ? void 0 : _f[0]) == null ? void 0 : _g.text;
97
+ const extracted = extractEvalValue(rawText);
98
+ if (extracted === sessionId) {
99
+ matchedPageId = page.pageId;
100
+ break;
101
+ }
102
+ }
103
+ if (chromeSelectedPageId != null && chromeSelectedPageId !== matchedPageId) {
104
+ yield mcp.callChromeDevTool("select_page", {
105
+ pageId: chromeSelectedPageId,
106
+ bringToFront: false
107
+ });
108
+ }
109
+ if (matchedPageId != null) {
110
+ return { ok: true, pageId: matchedPageId };
111
+ }
112
+ return {
113
+ ok: false,
114
+ error: `\u672A\u80FD\u901A\u8FC7\u4F1A\u8BDD\u6807\u8BC6\u627E\u5230\u76EE\u6807\u9875\u9762\uFF0C\u8BF7\u786E\u8BA4\u76EE\u6807\u9875\u9762\u5DF2\u6253\u5F00`
115
+ };
116
+ }
117
+ const matches = pages.filter((p) => normalizeUrl(p.url) === targetUrl);
118
+ if (matches.length === 0) {
119
+ return {
120
+ ok: false,
121
+ error: `Chrome \u4E2D\u672A\u627E\u5230\u5339\u914D\u7684\u9875\u9762 (${targetUrl})\uFF0C\u8BF7\u786E\u8BA4\u672C\u5730\u5F00\u53D1\u9875\u9762\u5DF2\u5728 Chrome DevTools \u4E2D\u6253\u5F00`
122
+ };
123
+ }
124
+ if (matches.length === 1) {
125
+ log.debug("resolveChromePageId: URL matched", { pageId: matches[0].pageId });
126
+ return { ok: true, pageId: matches[0].pageId };
127
+ }
128
+ return {
129
+ ok: false,
130
+ error: `\u5B58\u5728 ${matches.length} \u4E2A\u540C URL \u7684\u9875\u9762\uFF0C\u7F3A\u5C11\u9875\u9762\u6807\u8BC6\u65E0\u6CD5\u533A\u5206\uFF0C\u8BF7\u5237\u65B0\u9875\u9762\u540E\u91CD\u8BD5`
131
+ };
132
+ } catch (err) {
133
+ const msg = `MCP \u8C03\u7528\u5931\u8D25: ${err.message}`;
134
+ log.debug("Failed to resolve pageId via MCP", { error: err.message });
135
+ return { ok: false, error: msg };
136
+ }
137
+ });
138
+ }
24
139
  function setupContextEndpoint(server, ctx) {
25
140
  server.middlewares.use(CONTEXT_API_PATH, (req, res) => __async(null, null, function* () {
26
141
  const reqCtx = new RequestContext(req.method || "GET", CONTEXT_API_PATH);
@@ -36,7 +151,6 @@ function setupContextEndpoint(server, ctx) {
36
151
  }
37
152
  if (req.method === "GET") {
38
153
  const pc = ctx.getPageContext();
39
- log.debug(`[Context] GET \u2192 url=${pc.url} title=${pc.title} tabId=${pc.tabId}`);
40
154
  res.writeHead(200);
41
155
  res.end(JSON.stringify(pc));
42
156
  reqCtx.end(200);
@@ -67,7 +181,11 @@ function setupContextEndpoint(server, ctx) {
67
181
  }
68
182
  if (req.method === "POST") {
69
183
  let body = "";
70
- req.on("data", (chunk) => body += chunk);
184
+ req.on("data", (chunk) => body += chunk.toString());
185
+ req.on("error", () => {
186
+ res.writeHead(400);
187
+ res.end(JSON.stringify({ error: "Request error" }));
188
+ });
71
189
  req.on("end", () => {
72
190
  var _a, _b, _c;
73
191
  try {
@@ -77,6 +195,7 @@ function setupContextEndpoint(server, ctx) {
77
195
  const newCtx = {
78
196
  url: data.url || "",
79
197
  title: data.title || "",
198
+ sessionId: data.sessionId,
80
199
  tabId: (_a = data.tabId) != null ? _a : existing.tabId,
81
200
  tabIndex: (_b = data.tabIndex) != null ? _b : existing.tabIndex,
82
201
  selectedElements: data.selectedElements || []
@@ -89,6 +208,7 @@ function setupContextEndpoint(server, ctx) {
89
208
  tabId,
90
209
  url: newCtx.url,
91
210
  title: newCtx.title,
211
+ sessionId: newCtx.sessionId,
92
212
  selectedElementsCount: ((_c = newCtx.selectedElements) == null ? void 0 : _c.length) || 0
93
213
  });
94
214
  if (newCtx.selectedElements && newCtx.selectedElements.length > 0) {
@@ -121,5 +241,9 @@ function setupContextEndpoint(server, ctx) {
121
241
  }));
122
242
  }
123
243
  export {
244
+ extractEvalValue,
245
+ getProjectOrigin,
246
+ parseListPages,
247
+ resolveChromePageId,
124
248
  setupContextEndpoint
125
249
  };
@@ -1,6 +1,8 @@
1
1
  import type { ViteDevServer } from "vite";
2
2
  import type { EndpointContext } from "./types";
3
+ import { MCP_API_PATH } from "./mcp";
4
+ import type { McpProxy } from "../core/mcp-proxy";
3
5
  import { LOGS_API_PATH } from "@vite-plugin-opencode-assistant/shared";
4
6
  export * from "./types";
5
- export { LOGS_API_PATH };
6
- export declare function setupMiddlewares(server: ViteDevServer, ctx: EndpointContext): void;
7
+ export { LOGS_API_PATH, MCP_API_PATH };
8
+ export declare function setupMiddlewares(server: ViteDevServer, ctx: EndpointContext, mcp?: McpProxy): void;
@@ -5,9 +5,10 @@ import { setupSseEndpoint } from "./sse.mjs";
5
5
  import { setupSessionsEndpoint } from "./sessions.mjs";
6
6
  import { setupWarmupEndpoint } from "./warmup.mjs";
7
7
  import { setupLogsEndpoint } from "./logs.mjs";
8
+ import { setupMcpEndpoint, MCP_API_PATH } from "./mcp.mjs";
8
9
  import { LOGS_API_PATH } from "@vite-plugin-opencode-assistant/shared";
9
10
  export * from "./types.mjs";
10
- function setupMiddlewares(server, ctx) {
11
+ function setupMiddlewares(server, ctx, mcp) {
11
12
  setupWidgetEndpoints(server, ctx);
12
13
  setupContextEndpoint(server, ctx);
13
14
  setupStartEndpoint(server, ctx);
@@ -15,8 +16,10 @@ function setupMiddlewares(server, ctx) {
15
16
  setupSessionsEndpoint(server, ctx);
16
17
  setupWarmupEndpoint(server, ctx);
17
18
  setupLogsEndpoint(server);
19
+ if (mcp) setupMcpEndpoint(server, mcp, () => ctx.getPageContext());
18
20
  }
19
21
  export {
20
22
  LOGS_API_PATH,
23
+ MCP_API_PATH,
21
24
  setupMiddlewares
22
25
  };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * 自定义 DevTools 工具定义
3
+ * 所有工具自动映射到 chrome-devtools-mcp 底层工具
4
+ */
5
+ export interface CustomTool {
6
+ name: string;
7
+ description: string;
8
+ inputSchema: {
9
+ type: "object";
10
+ properties: Record<string, unknown>;
11
+ required?: string[];
12
+ };
13
+ }
14
+ export declare const CUSTOM_TOOLS: CustomTool[];
15
+ /** 工具名映射(自定义 → chrome-devtools-mcp) */
16
+ export declare const TOOL_MAP: Record<string, string>;