From f4db8378a83156f08288ff152685d8f63c912ff8 Mon Sep 17 00:00:00 2001 From: abose Date: Mon, 16 Feb 2026 10:51:57 +0530 Subject: [PATCH 1/4] feat: phoenix builder mcp for phoenix to build itself --- .gitignore | 3 + .mcp.json | 11 + package-lock.json | 5 +- package.json | 1 + phoenix-builder-mcp/index.js | 39 + phoenix-builder-mcp/log-buffer.js | 32 + phoenix-builder-mcp/mcp-tools.js | 228 ++++ phoenix-builder-mcp/package-lock.json | 1164 +++++++++++++++++ phoenix-builder-mcp/package.json | 12 + phoenix-builder-mcp/process-manager.js | 123 ++ phoenix-builder-mcp/ws-control-server.js | 291 +++++ src/brackets.js | 1 + src/extensions/default/DebugCommands/main.js | 1 + src/nls/root/strings.js | 1 + .../builder-connect-dialog.html | 54 + src/phoenix-builder/main.js | 95 ++ src/phoenix-builder/phoenix-builder-client.js | 370 ++++++ 17 files changed, 2429 insertions(+), 2 deletions(-) create mode 100644 .mcp.json create mode 100644 phoenix-builder-mcp/index.js create mode 100644 phoenix-builder-mcp/log-buffer.js create mode 100644 phoenix-builder-mcp/mcp-tools.js create mode 100644 phoenix-builder-mcp/package-lock.json create mode 100644 phoenix-builder-mcp/package.json create mode 100644 phoenix-builder-mcp/process-manager.js create mode 100644 phoenix-builder-mcp/ws-control-server.js create mode 100644 src/phoenix-builder/builder-connect-dialog.html create mode 100644 src/phoenix-builder/main.js create mode 100644 src/phoenix-builder/phoenix-builder-client.js diff --git a/.gitignore b/.gitignore index da9257abfa..23215dc3c2 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,9 @@ Thumbs.db /test/pro-test-suite.js /src/extensionsIntegrated/phoenix-pro +# ignore node_modules inside phoenix-builder-mcp +/phoenix-builder-mcp/node_modules + # ignore node_modules inside src /src/node_modules /src-node/node_modules diff --git a/.mcp.json b/.mcp.json new file mode 100644 index 0000000000..a2dc6bede8 --- /dev/null +++ b/.mcp.json @@ -0,0 +1,11 @@ +{ + "mcpServers": { + "phoenix-builder": { + "command": "node", + "args": ["phoenix-builder-mcp/index.js"], + "env": { + "PHOENIX_DESKTOP_PATH": "../phoenix-desktop" + } + } + } +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index ae112e8ece..2d1ac373ed 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,13 @@ { "name": "phoenix", - "version": "5.1.1-0", + "version": "5.1.4-0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "phoenix", - "version": "5.1.1-0", + "version": "5.1.4-0", + "hasInstallScript": true, "dependencies": { "@bugsnag/js": "^7.18.0", "@floating-ui/dom": "^0.5.4", diff --git a/package.json b/package.json index 4548962a78..e93657da42 100644 --- a/package.json +++ b/package.json @@ -42,6 +42,7 @@ "lmdb": "^3.5.1" }, "scripts": { + "postinstall": "npm install --prefix phoenix-builder-mcp", "lint": "eslint --quiet src test", "lint:fix": "eslint --quiet --fix src test", "prepare": "husky install", diff --git a/phoenix-builder-mcp/index.js b/phoenix-builder-mcp/index.js new file mode 100644 index 0000000000..5b7230ec54 --- /dev/null +++ b/phoenix-builder-mcp/index.js @@ -0,0 +1,39 @@ +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createWSControlServer } from "./ws-control-server.js"; +import { createProcessManager } from "./process-manager.js"; +import { registerTools } from "./mcp-tools.js"; +import { fileURLToPath } from "url"; +import path from "path"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +const wsPort = parseInt(process.env.PHOENIX_MCP_WS_PORT || "38571", 10); +const phoenixDesktopPath = process.env.PHOENIX_DESKTOP_PATH + || path.resolve(__dirname, "../../phoenix-desktop"); + +const wsControlServer = createWSControlServer(wsPort); +const processManager = createProcessManager(); + +const server = new McpServer({ + name: "phoenix-builder", + version: "1.0.0" +}); + +registerTools(server, processManager, wsControlServer, phoenixDesktopPath); + +const transport = new StdioServerTransport(); +await server.connect(transport); + +process.on("SIGINT", async () => { + await processManager.stop(); + wsControlServer.close(); + process.exit(0); +}); + +process.on("SIGTERM", async () => { + await processManager.stop(); + wsControlServer.close(); + process.exit(0); +}); diff --git a/phoenix-builder-mcp/log-buffer.js b/phoenix-builder-mcp/log-buffer.js new file mode 100644 index 0000000000..3c60d6b10b --- /dev/null +++ b/phoenix-builder-mcp/log-buffer.js @@ -0,0 +1,32 @@ +const MAX_ENTRIES = 10000; + +export class LogBuffer { + constructor() { + this._entries = []; + this._readIndex = 0; + } + + push(entry) { + this._entries.push(entry); + if (this._entries.length > MAX_ENTRIES) { + const overflow = this._entries.length - MAX_ENTRIES; + this._entries.splice(0, overflow); + this._readIndex = Math.max(0, this._readIndex - overflow); + } + } + + getAll() { + return this._entries.slice(); + } + + getSinceLastRead() { + const newEntries = this._entries.slice(this._readIndex); + this._readIndex = this._entries.length; + return newEntries; + } + + clear() { + this._entries = []; + this._readIndex = 0; + } +} diff --git a/phoenix-builder-mcp/mcp-tools.js b/phoenix-builder-mcp/mcp-tools.js new file mode 100644 index 0000000000..1c13ba8b49 --- /dev/null +++ b/phoenix-builder-mcp/mcp-tools.js @@ -0,0 +1,228 @@ +import { z } from "zod"; + +export function registerTools(server, processManager, wsControlServer, phoenixDesktopPath) { + server.tool( + "start_phoenix", + "Start the Phoenix Code desktop app (Electron). Launches npm run serve:electron in the phoenix-desktop directory.", + {}, + async () => { + try { + if (processManager.isRunning()) { + return { + content: [{ + type: "text", + text: JSON.stringify({ + success: false, + error: "Phoenix is already running", + pid: processManager.getPid() + }) + }] + }; + } + const result = await processManager.start(phoenixDesktopPath); + return { + content: [{ + type: "text", + text: JSON.stringify({ + success: true, + pid: result.pid, + wsPort: wsControlServer.getPort() + }) + }] + }; + } catch (err) { + return { + content: [{ + type: "text", + text: JSON.stringify({ success: false, error: err.message }) + }] + }; + } + } + ); + + server.tool( + "stop_phoenix", + "Stop the running Phoenix Code desktop app.", + {}, + async () => { + try { + const result = await processManager.stop(); + return { + content: [{ + type: "text", + text: JSON.stringify(result) + }] + }; + } catch (err) { + return { + content: [{ + type: "text", + text: JSON.stringify({ success: false, error: err.message }) + }] + }; + } + } + ); + + server.tool( + "get_terminal_logs", + "Get stdout/stderr output from the Electron process. By default returns new logs since last call; set clear=true to get all logs and clear the buffer.", + { clear: z.boolean().default(false).describe("If true, return all logs and clear the buffer. If false, return only new logs since last read.") }, + async ({ clear }) => { + let logs; + if (clear) { + logs = processManager.getTerminalLogs(false); + processManager.clearTerminalLogs(); + } else { + logs = processManager.getTerminalLogs(true); + } + const text = logs.map(e => `[${e.stream}] ${e.text}`).join(""); + return { + content: [{ + type: "text", + text: text || "(no terminal logs)" + }] + }; + } + ); + + server.tool( + "get_browser_console_logs", + "Get console logs forwarded from the Phoenix browser runtime via WebSocket. By default returns new logs since last call; set clear=true to get all logs and clear the buffer.", + { + clear: z.boolean().default(false).describe("If true, return all logs and clear the buffer. If false, return only new logs since last read."), + instance: z.string().optional().describe("Target a specific Phoenix instance by name (e.g. 'Phoenix-a3f2'). Required when multiple instances are connected.") + }, + async ({ clear, instance }) => { + let logs; + if (clear) { + logs = wsControlServer.getBrowserLogs(false, instance); + if (logs && logs.error) { + return { + content: [{ type: "text", text: JSON.stringify(logs) }] + }; + } + const clearResult = wsControlServer.clearBrowserLogs(instance); + if (clearResult && clearResult.error) { + return { + content: [{ type: "text", text: JSON.stringify(clearResult) }] + }; + } + } else { + logs = wsControlServer.getBrowserLogs(true, instance); + if (logs && logs.error) { + return { + content: [{ type: "text", text: JSON.stringify(logs) }] + }; + } + } + return { + content: [{ + type: "text", + text: JSON.stringify(logs.length > 0 ? logs : "(no browser logs)") + }] + }; + } + ); + + server.tool( + "take_screenshot", + "Take a screenshot of the Phoenix Code app window. Returns a PNG image.", + { + selector: z.string().optional().describe("Optional CSS selector to capture a specific element"), + instance: z.string().optional().describe("Target a specific Phoenix instance by name (e.g. 'Phoenix-a3f2'). Required when multiple instances are connected.") + }, + async ({ selector, instance }) => { + try { + const base64Data = await wsControlServer.requestScreenshot(selector, instance); + return { + content: [{ + type: "image", + data: base64Data, + mimeType: "image/png" + }] + }; + } catch (err) { + return { + content: [{ + type: "text", + text: JSON.stringify({ error: err.message }) + }] + }; + } + } + ); + + server.tool( + "reload_phoenix", + "Reload the Phoenix Code app. Closes all open files (prompting to save unsaved changes) then reloads the app.", + { + instance: z.string().optional().describe("Target a specific Phoenix instance by name (e.g. 'Phoenix-a3f2'). Required when multiple instances are connected.") + }, + async ({ instance }) => { + try { + const result = await wsControlServer.requestReload(false, instance); + return { + content: [{ + type: "text", + text: JSON.stringify({ success: true, message: "Phoenix is reloading" }) + }] + }; + } catch (err) { + return { + content: [{ + type: "text", + text: JSON.stringify({ error: err.message }) + }] + }; + } + } + ); + + server.tool( + "force_reload_phoenix", + "Force reload the Phoenix Code app without saving. Closes all open files without saving unsaved changes, then reloads the app.", + { + instance: z.string().optional().describe("Target a specific Phoenix instance by name (e.g. 'Phoenix-a3f2'). Required when multiple instances are connected.") + }, + async ({ instance }) => { + try { + const result = await wsControlServer.requestReload(true, instance); + return { + content: [{ + type: "text", + text: JSON.stringify({ success: true, message: "Phoenix is force reloading (unsaved changes discarded)" }) + }] + }; + } catch (err) { + return { + content: [{ + type: "text", + text: JSON.stringify({ error: err.message }) + }] + }; + } + } + ); + + server.tool( + "get_phoenix_status", + "Check the status of the Phoenix process and WebSocket connection.", + {}, + async () => { + return { + content: [{ + type: "text", + text: JSON.stringify({ + processRunning: processManager.isRunning(), + pid: processManager.getPid(), + wsConnected: wsControlServer.isClientConnected(), + connectedInstances: wsControlServer.getConnectedInstances(), + wsPort: wsControlServer.getPort() + }) + }] + }; + } + ); +} diff --git a/phoenix-builder-mcp/package-lock.json b/phoenix-builder-mcp/package-lock.json new file mode 100644 index 0000000000..64359b6072 --- /dev/null +++ b/phoenix-builder-mcp/package-lock.json @@ -0,0 +1,1164 @@ +{ + "name": "phoenix-builder-mcp", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "phoenix-builder-mcp", + "version": "1.0.0", + "dependencies": { + "@modelcontextprotocol/sdk": "latest", + "ws": "^8.0.0", + "zod": "^3.25.0" + } + }, + "node_modules/@hono/node-server": { + "version": "1.19.9", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.9.tgz", + "integrity": "sha512-vHL6w3ecZsky+8P5MD+eFfaGTyCeOHUIFYMGpQGbrBTSmNNoxv0if69rEZ5giu36weC5saFuznL411gRX7bJDw==", + "license": "MIT", + "engines": { + "node": ">=18.14.1" + }, + "peerDependencies": { + "hono": "^4" + } + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.26.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.26.0.tgz", + "integrity": "sha512-Y5RmPncpiDtTXDbLKswIJzTqu2hyBKxTNsgKqKclDbhIgg1wgtf1fRuvxgTnRfcnxtvvgbIEcqUOzZrJ6iSReg==", + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/body-parser": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz", + "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.1", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz", + "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "peer": true, + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.2.1.tgz", + "integrity": "sha512-PCZEIEIxqwhzw4KF0n7QF4QqruVTcF73O5kFKUnGOyjbCCgizBBiFaYpd/fnBLUMPw/BWw9OsiN7GgrNYr7j6g==", + "license": "MIT", + "dependencies": { + "ip-address": "10.0.1" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hono": { + "version": "4.11.9", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.11.9.tgz", + "integrity": "sha512-Eaw2YTGM6WOxA6CXbckaEvslr2Ne4NFsKrvc0v97JD5awbmeBLO5w9Ho9L9kmKonrwF9RJlW6BxT1PVv/agBHQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ip-address": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.0.1.tgz", + "integrity": "sha512-NWv9YLW4PoW2B7xtzaS3NCot75m6nK7Icdv0o3lfMceJVRfSoQwqD4wEH5rLwoKJwUiZ/rfpiVBhnaF0FK4HoA==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.1.3.tgz", + "integrity": "sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz", + "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.0.tgz", + "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.1", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.1.tgz", + "integrity": "sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25 || ^4" + } + } + } +} diff --git a/phoenix-builder-mcp/package.json b/phoenix-builder-mcp/package.json new file mode 100644 index 0000000000..48c700d3e3 --- /dev/null +++ b/phoenix-builder-mcp/package.json @@ -0,0 +1,12 @@ +{ + "name": "phoenix-builder-mcp", + "version": "1.0.0", + "private": true, + "type": "module", + "main": "index.js", + "dependencies": { + "@modelcontextprotocol/sdk": "latest", + "ws": "^8.0.0", + "zod": "^3.25.0" + } +} diff --git a/phoenix-builder-mcp/process-manager.js b/phoenix-builder-mcp/process-manager.js new file mode 100644 index 0000000000..d49a4a91d2 --- /dev/null +++ b/phoenix-builder-mcp/process-manager.js @@ -0,0 +1,123 @@ +import { spawn } from "child_process"; +import { LogBuffer } from "./log-buffer.js"; + +export function createProcessManager() { + let childProcess = null; + const terminalLogs = new LogBuffer(); + + function start(phoenixDesktopPath) { + if (childProcess) { + throw new Error("Phoenix is already running. Stop it first."); + } + + return new Promise((resolve, reject) => { + const child = spawn("npm", ["run", "serve:electron"], { + cwd: phoenixDesktopPath, + shell: true, + stdio: ["ignore", "pipe", "pipe"], + env: { ...process.env } + }); + + childProcess = child; + + child.stdout.on("data", (data) => { + const text = data.toString(); + terminalLogs.push({ + stream: "stdout", + text, + timestamp: new Date().toISOString() + }); + }); + + child.stderr.on("data", (data) => { + const text = data.toString(); + terminalLogs.push({ + stream: "stderr", + text, + timestamp: new Date().toISOString() + }); + }); + + child.on("error", (err) => { + terminalLogs.push({ + stream: "stderr", + text: `Process error: ${err.message}`, + timestamp: new Date().toISOString() + }); + childProcess = null; + reject(err); + }); + + child.on("exit", (code, signal) => { + terminalLogs.push({ + stream: "stderr", + text: `Process exited with code=${code} signal=${signal}`, + timestamp: new Date().toISOString() + }); + childProcess = null; + }); + + // Give the process a moment to start or fail + setTimeout(() => { + if (childProcess) { + resolve({ pid: child.pid }); + } + }, 500); + }); + } + + function stop() { + return new Promise((resolve) => { + if (!childProcess) { + resolve({ success: true, message: "No process running" }); + return; + } + + const child = childProcess; + let killed = false; + + const forceKillTimeout = setTimeout(() => { + if (childProcess === child) { + child.kill("SIGKILL"); + killed = true; + } + }, 5000); + + child.on("exit", () => { + clearTimeout(forceKillTimeout); + childProcess = null; + resolve({ success: true, forced: killed }); + }); + + child.kill("SIGTERM"); + }); + } + + function isRunning() { + return childProcess !== null; + } + + function getPid() { + return childProcess ? childProcess.pid : null; + } + + function getTerminalLogs(sinceLast) { + if (sinceLast) { + return terminalLogs.getSinceLastRead(); + } + return terminalLogs.getAll(); + } + + function clearTerminalLogs() { + terminalLogs.clear(); + } + + return { + start, + stop, + isRunning, + getPid, + getTerminalLogs, + clearTerminalLogs + }; +} diff --git a/phoenix-builder-mcp/ws-control-server.js b/phoenix-builder-mcp/ws-control-server.js new file mode 100644 index 0000000000..8e22e19050 --- /dev/null +++ b/phoenix-builder-mcp/ws-control-server.js @@ -0,0 +1,291 @@ +import { WebSocketServer } from "ws"; +import { LogBuffer } from "./log-buffer.js"; + +export function createWSControlServer(port) { + const wss = new WebSocketServer({ port }); + const clients = new Map(); // name -> { ws, logs, isAlive } + let unknownCounter = 0; + let requestIdCounter = 0; + const pendingRequests = new Map(); + let heartbeatInterval = null; + + wss.on("connection", (ws) => { + // Name is assigned when the client sends a "hello" message. + // Track the ws temporarily so we can map it back on close/error. + let clientName = null; + + ws.on("message", (data) => { + let msg; + try { + msg = JSON.parse(data.toString()); + } catch { + return; + } + + switch (msg.type) { + case "hello": { + clientName = msg.name || ("Unknown-" + (++unknownCounter)); + + // If same name reconnects (e.g. tab reload), close old connection + const existing = clients.get(clientName); + if (existing) { + try { + existing.ws.close(1000, "Replaced by new connection"); + } catch { + // ignore + } + } + + clients.set(clientName, { + ws: ws, + logs: new LogBuffer(), + isAlive: true + }); + break; + } + + case "console_log": { + const client = clientName && clients.get(clientName); + if (client && Array.isArray(msg.entries)) { + for (const entry of msg.entries) { + client.logs.push(entry); + } + } + break; + } + + case "screenshot_response": { + const pending = pendingRequests.get(msg.id); + if (pending) { + pendingRequests.delete(msg.id); + pending.resolve(msg.data); + } + break; + } + + case "reload_response": { + const pending3 = pendingRequests.get(msg.id); + if (pending3) { + pendingRequests.delete(msg.id); + if (msg.success) { + pending3.resolve({ success: true }); + } else { + pending3.reject(new Error(msg.message || "Reload failed")); + } + } + break; + } + + case "error": { + const pending2 = pendingRequests.get(msg.id); + if (pending2) { + pendingRequests.delete(msg.id); + pending2.reject(new Error(msg.message || "Unknown error from Phoenix")); + } + break; + } + + case "pong": { + const client = clientName && clients.get(clientName); + if (client) { + client.isAlive = true; + } + break; + } + } + }); + + ws.on("close", () => { + if (clientName && clients.get(clientName)?.ws === ws) { + clients.delete(clientName); + } + }); + + ws.on("error", () => { + if (clientName && clients.get(clientName)?.ws === ws) { + clients.delete(clientName); + } + }); + }); + + // Heartbeat + heartbeatInterval = setInterval(() => { + for (const [name, client] of clients) { + if (!client.isAlive) { + client.ws.terminate(); + clients.delete(name); + continue; + } + client.isAlive = false; + try { + client.ws.send(JSON.stringify({ type: "ping" })); + } catch { + // ignore send errors + } + } + }, 15000); + + function _resolveClient(instanceName) { + if (clients.size === 0) { + return { error: "No Phoenix client connected" }; + } + + if (!instanceName) { + if (clients.size === 1) { + const [name, client] = [...clients.entries()][0]; + return { name, client }; + } + const names = [...clients.keys()]; + return { + error: "Multiple Phoenix instances connected. Specify an instance name: " + + names.join(", ") + }; + } + + const client = clients.get(instanceName); + if (!client) { + const names = [...clients.keys()]; + return { + error: "Instance \"" + instanceName + "\" not found. Available: " + + names.join(", ") + }; + } + + return { name: instanceName, client }; + } + + function requestScreenshot(selector, instanceName) { + return new Promise((resolve, reject) => { + const resolved = _resolveClient(instanceName); + if (resolved.error) { + reject(new Error(resolved.error)); + return; + } + + const { client } = resolved; + if (client.ws.readyState !== 1) { + reject(new Error("Phoenix client \"" + resolved.name + "\" is not connected")); + return; + } + + const id = ++requestIdCounter; + const timeout = setTimeout(() => { + pendingRequests.delete(id); + reject(new Error("Screenshot request timed out (30s)")); + }, 30000); + + pendingRequests.set(id, { + resolve: (data) => { + clearTimeout(timeout); + resolve(data); + }, + reject: (err) => { + clearTimeout(timeout); + reject(err); + } + }); + + const msg = { type: "screenshot_request", id }; + if (selector) { + msg.selector = selector; + } + client.ws.send(JSON.stringify(msg)); + }); + } + + function requestReload(forceClose, instanceName) { + return new Promise((resolve, reject) => { + const resolved = _resolveClient(instanceName); + if (resolved.error) { + reject(new Error(resolved.error)); + return; + } + + const { client } = resolved; + if (client.ws.readyState !== 1) { + reject(new Error("Phoenix client \"" + resolved.name + "\" is not connected")); + return; + } + + const id = ++requestIdCounter; + const timeout = setTimeout(() => { + pendingRequests.delete(id); + reject(new Error("Reload request timed out (30s)")); + }, 30000); + + pendingRequests.set(id, { + resolve: (data) => { + clearTimeout(timeout); + resolve(data); + }, + reject: (err) => { + clearTimeout(timeout); + reject(err); + } + }); + + client.ws.send(JSON.stringify({ + type: "reload_request", + id, + forceClose: !!forceClose + })); + }); + } + + function getBrowserLogs(sinceLast, instanceName) { + const resolved = _resolveClient(instanceName); + if (resolved.error) { + return { error: resolved.error }; + } + + const { client } = resolved; + if (sinceLast) { + return client.logs.getSinceLastRead(); + } + return client.logs.getAll(); + } + + function clearBrowserLogs(instanceName) { + const resolved = _resolveClient(instanceName); + if (resolved.error) { + return { error: resolved.error }; + } + resolved.client.logs.clear(); + } + + function isClientConnected() { + return clients.size > 0; + } + + function getConnectedInstances() { + return [...clients.keys()]; + } + + function close() { + clearInterval(heartbeatInterval); + for (const [id, pending] of pendingRequests) { + pending.reject(new Error("Server shutting down")); + } + pendingRequests.clear(); + for (const [name, client] of clients) { + try { + client.ws.close(1000, "Server shutting down"); + } catch { + // ignore + } + } + clients.clear(); + wss.close(); + } + + return { + requestScreenshot, + requestReload, + getBrowserLogs, + clearBrowserLogs, + isClientConnected, + getConnectedInstances, + close, + getPort: () => port + }; +} diff --git a/src/brackets.js b/src/brackets.js index 79428dbc72..128070ca94 100644 --- a/src/brackets.js +++ b/src/brackets.js @@ -141,6 +141,7 @@ define(function (require, exports, module) { require("widgets/InlineMenu"); require("thirdparty/tinycolor"); require("utils/LocalizationUtils"); + require("phoenix-builder/main"); // DEPRECATED: In future we want to remove the global CodeMirror, but for now we // expose our required CodeMirror globally so as to avoid breaking extensions in the diff --git a/src/extensions/default/DebugCommands/main.js b/src/extensions/default/DebugCommands/main.js index e2a5b97824..5dce4cb5d4 100644 --- a/src/extensions/default/DebugCommands/main.js +++ b/src/extensions/default/DebugCommands/main.js @@ -828,6 +828,7 @@ define(function (require, exports, module) { diagnosticsSubmenu.addMenuItem(DEBUG_RUN_UNIT_TESTS); CommandManager.register(Strings.CMD_BUILD_TESTS, DEBUG_BUILD_TESTS, TestBuilder.toggleTestBuilder); diagnosticsSubmenu.addMenuItem(DEBUG_BUILD_TESTS); + diagnosticsSubmenu.addMenuItem("debug.phoenixBuilderConnect"); diagnosticsSubmenu.addMenuDivider(); diagnosticsSubmenu.addMenuItem(DEBUG_ENABLE_LOGGING); diagnosticsSubmenu.addMenuItem(DEBUG_ENABLE_PHNODE_INSPECTOR, undefined, undefined, undefined, { diff --git a/src/nls/root/strings.js b/src/nls/root/strings.js index 7e0fc632fd..cde5aeabfb 100644 --- a/src/nls/root/strings.js +++ b/src/nls/root/strings.js @@ -947,6 +947,7 @@ define({ "CMD_SWITCH_LANGUAGE": "Switch Language\u2026", "CMD_RUN_UNIT_TESTS": "Run {APP_NAME} Tests", "CMD_BUILD_TESTS": "Build Editor Tests", + "CMD_PHOENIX_BUILDER_CONNECT": "Phoenix Builder MCP\u2026", "CMD_SHOW_PERF_DATA": "Show Performance Data", "CMD_ENABLE_LOGGING": "Enable Detailed Logs", "CMD_ENABLE_PHNODE_INSPECTOR": "Enable PhNode Inspector", diff --git a/src/phoenix-builder/builder-connect-dialog.html b/src/phoenix-builder/builder-connect-dialog.html new file mode 100644 index 0000000000..4426236262 --- /dev/null +++ b/src/phoenix-builder/builder-connect-dialog.html @@ -0,0 +1,54 @@ + diff --git a/src/phoenix-builder/main.js b/src/phoenix-builder/main.js new file mode 100644 index 0000000000..5e1ade812b --- /dev/null +++ b/src/phoenix-builder/main.js @@ -0,0 +1,95 @@ +/* + * GNU AGPL-3.0 License + * + * Copyright (c) 2021 - present core.ai . All rights reserved. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License + * for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see https://opensource.org/licenses/AGPL-3.0. + * + */ + +define(function (require, exports, module) { + + const AppInit = require("utils/AppInit"), + CommandManager = require("command/CommandManager"), + Dialogs = require("widgets/Dialogs"), + Strings = require("strings"), + PreferencesManager = require("preferences/PreferencesManager"), + Mustache = require("thirdparty/mustache/mustache"), + PhoenixBuilderClient = require("./phoenix-builder-client"), + BuilderConnectTemplate = require("text!./builder-connect-dialog.html"); + + const COMMAND_ID = "debug.phoenixBuilderConnect"; + + const builderPrefs = PreferencesManager.getExtensionPrefs("phoenixBuilder"); + builderPrefs.definePreference("enabled", "boolean", false, { + description: "Enable Phoenix Builder MCP connection" + }); + builderPrefs.definePreference("wsUrl", "string", "ws://localhost:38571", { + description: "Phoenix Builder MCP WebSocket URL" + }); + + function _handlePhoenixBuilderConnect() { + var url = builderPrefs.get("wsUrl"), + enabled = builderPrefs.get("enabled"); + + var templateVars = { + url: url, + enabled: enabled, + connected: PhoenixBuilderClient.isConnected(), + instanceName: PhoenixBuilderClient.getInstanceName() + }; + + var template = Mustache.render(BuilderConnectTemplate, templateVars); + Dialogs.showModalDialogUsingTemplate(template).done(function (id) { + if (id === Dialogs.DIALOG_BTN_OK) { + builderPrefs.set("wsUrl", url); + builderPrefs.set("enabled", enabled); + + if (enabled) { + PhoenixBuilderClient.connect(url); + } else { + PhoenixBuilderClient.disconnect(); + } + } + }); + + var $dialog = $(".phoenix-builder-connect.instance"); + $dialog.find(".builder-url").on("input", function () { + url = $(this).val(); + }); + $dialog.find(".builder-enable").on("change", function () { + enabled = $(this).is(":checked"); + }); + $dialog.find(".builder-config-code").on("click", function () { + Phoenix.app.copyToClipboard($(this).text()); + var $pre = $(this); + var $copied = $('Copied!'); + $pre.css("position", "relative").append($copied); + setTimeout(function () { $copied.remove(); }, 1000); + }); + } + + CommandManager.register(Strings.CMD_PHOENIX_BUILDER_CONNECT, COMMAND_ID, _handlePhoenixBuilderConnect); + + AppInit.appReady(function () { + if (builderPrefs.get("enabled")) { + PhoenixBuilderClient.connect(builderPrefs.get("wsUrl")); + } + }); + + exports.COMMAND_ID = COMMAND_ID; +}); diff --git a/src/phoenix-builder/phoenix-builder-client.js b/src/phoenix-builder/phoenix-builder-client.js new file mode 100644 index 0000000000..08f9fe7166 --- /dev/null +++ b/src/phoenix-builder/phoenix-builder-client.js @@ -0,0 +1,370 @@ +/* + * GNU AGPL-3.0 License + * + * Copyright (c) 2021 - present core.ai . All rights reserved. + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License + * for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see https://opensource.org/licenses/AGPL-3.0. + * + */ + +/*globals Phoenix*/ + +define(function (require, exports, module) { + + const CommandManager = require("command/CommandManager"); + const Commands = require("command/Commands"); + + const LOG_TO_CONSOLE_KEY = "logToConsole"; + const INSTANCE_NAME_KEY = "phoenixBuilderInstanceName"; + const FLUSH_INTERVAL = 500; + const FLUSH_THRESHOLD = 50; + const MAX_MESSAGE_LENGTH = 2000; + const RECONNECT_BASE_MS = 500; + const RECONNECT_MAX_MS = 5000; + + let ws = null; + let logBuffer = []; + let flushTimer = null; + let reconnectTimer = null; + let reconnectDelay = RECONNECT_BASE_MS; + let currentUrl = null; + let autoReconnect = true; + let originalConsoleLog, originalConsoleInfo, originalConsoleWarn, originalConsoleError; + let consoleHooked = false; + let errorListenerAdded = false; + + function _getPlatformTag() { + if (window.__TAURI__) { + return "tauri"; + } + if (window.__ELECTRON__) { + return "electron"; + } + var desktop = Phoenix.browser && Phoenix.browser.desktop; + if (desktop) { + if (desktop.isFirefox) { return "firefox"; } + if (desktop.isEdgeChromium) { return "edge"; } + if (desktop.isOperaChromium || desktop.isOpera) { return "opera"; } + if (desktop.isChrome) { return "chrome"; } + if (desktop.isSafari) { return "safari"; } + if (desktop.isChromeBased) { return "chromium"; } + } + return "browser"; + } + + function _getOrCreateInstanceName() { + var name = sessionStorage.getItem(INSTANCE_NAME_KEY); + if (!name) { + var hex = Math.floor(Math.random() * 0x10000).toString(16).padStart(4, "0"); + name = "phoenix-" + _getPlatformTag() + "-" + hex; + sessionStorage.setItem(INSTANCE_NAME_KEY, name); + } + return name; + } + + function _serializeArg(arg) { + if (arg === null) { return "null"; } + if (arg === undefined) { return "undefined"; } + if (typeof arg === "string") { + return arg.length > MAX_MESSAGE_LENGTH ? arg.substring(0, MAX_MESSAGE_LENGTH) + "..." : arg; + } + if (typeof arg === "number" || typeof arg === "boolean") { + return String(arg); + } + if (arg instanceof Error) { + return arg.stack || arg.message || String(arg); + } + try { + const seen = new Set(); + const json = JSON.stringify(arg, (key, value) => { + if (typeof value === "object" && value !== null) { + if (seen.has(value)) { return "[Circular]"; } + seen.add(value); + } + return value; + }); + return json.length > MAX_MESSAGE_LENGTH ? json.substring(0, MAX_MESSAGE_LENGTH) + "..." : json; + } catch (e) { + return String(arg); + } + } + + function _pushLogEntry(level, args) { + const message = Array.from(args).map(_serializeArg).join(" "); + logBuffer.push({ + level: level, + message: message, + timestamp: new Date().toISOString() + }); + if (logBuffer.length >= FLUSH_THRESHOLD) { + _flushLogs(); + } + } + + function _flushLogs() { + if (!ws || ws.readyState !== WebSocket.OPEN || logBuffer.length === 0) { + return; + } + const entries = logBuffer; + logBuffer = []; + try { + ws.send(JSON.stringify({ + type: "console_log", + entries: entries + })); + } catch (e) { + // Put them back if send failed + logBuffer = entries.concat(logBuffer); + } + } + + function _hookConsole() { + if (consoleHooked) { return; } + + originalConsoleLog = console.log; + originalConsoleInfo = console.info; + originalConsoleWarn = console.warn; + originalConsoleError = console.error; + + console.log = function () { + _pushLogEntry("log", arguments); + originalConsoleLog.apply(console, arguments); + }; + console.info = function () { + _pushLogEntry("info", arguments); + originalConsoleInfo.apply(console, arguments); + }; + console.warn = function () { + _pushLogEntry("warn", arguments); + originalConsoleWarn.apply(console, arguments); + }; + console.error = function () { + _pushLogEntry("error", arguments); + originalConsoleError.apply(console, arguments); + }; + + consoleHooked = true; + } + + function _unhookConsole() { + if (!consoleHooked) { return; } + + console.log = originalConsoleLog; + console.info = originalConsoleInfo; + console.warn = originalConsoleWarn; + console.error = originalConsoleError; + + consoleHooked = false; + } + + function _addErrorListeners() { + if (errorListenerAdded) { return; } + + window.addEventListener("error", function (event) { + _pushLogEntry("error", ["[Uncaught Error] " + (event.message || "") + + (event.filename ? " at " + event.filename + ":" + event.lineno : "")]); + }); + + window.addEventListener("unhandledrejection", function (event) { + const reason = event.reason; + const msg = reason instanceof Error ? (reason.stack || reason.message) : String(reason); + _pushLogEntry("error", ["[Unhandled Promise Rejection] " + msg]); + }); + + errorListenerAdded = true; + } + + function _enableDebugLogging() { + localStorage.setItem(LOG_TO_CONSOLE_KEY, "true"); + if (window.setupLogging) { + window.setupLogging(); + } + } + + function _handleScreenshotRequest(msg) { + if (!Phoenix || !Phoenix.app || !Phoenix.app.screenShotBinary) { + _sendMessage({ + type: "error", + id: msg.id, + message: "Screenshot API not available" + }); + return; + } + + Phoenix.app.screenShotBinary(msg.selector || undefined) + .then(function (bytes) { + // Convert Uint8Array to base64 in chunks to avoid call stack limits + let binary = ""; + const chunkSize = 8192; + for (let i = 0; i < bytes.length; i += chunkSize) { + const chunk = bytes.subarray(i, Math.min(i + chunkSize, bytes.length)); + binary += String.fromCharCode.apply(null, chunk); + } + const base64 = btoa(binary); + _sendMessage({ + type: "screenshot_response", + id: msg.id, + data: base64 + }); + }) + .catch(function (err) { + _sendMessage({ + type: "error", + id: msg.id, + message: err.message || "Screenshot failed" + }); + }); + } + + function _handleReloadRequest(msg) { + var closeArgs = msg.forceClose ? { _forceClose: true } : undefined; + CommandManager.execute(Commands.FILE_CLOSE_ALL, closeArgs) + .done(function () { + _sendMessage({ + type: "reload_response", + id: msg.id, + success: true + }); + // Give the response a moment to send before reloading + setTimeout(function () { + location.reload(); + }, 100); + }) + .fail(function (err) { + _sendMessage({ + type: "reload_response", + id: msg.id, + success: false, + message: (err && err.message) || "Close cancelled by user" + }); + }); + } + + function _sendMessage(msg) { + if (ws && ws.readyState === WebSocket.OPEN) { + try { + ws.send(JSON.stringify(msg)); + } catch (e) { + // ignore + } + } + } + + function _scheduleReconnect() { + if (!autoReconnect || !currentUrl || reconnectTimer) { return; } + reconnectTimer = setTimeout(function () { + reconnectTimer = null; + if (!ws && currentUrl && autoReconnect) { + connect(currentUrl); + } + }, reconnectDelay); + reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS); + } + + function connect(url) { + if (ws) { + disconnect(); + } + + currentUrl = url; + autoReconnect = true; + + try { + ws = new WebSocket(url); + } catch (e) { + ws = null; + _scheduleReconnect(); + return; + } + + ws.onopen = function () { + reconnectDelay = RECONNECT_BASE_MS; + _sendMessage({ type: "hello", version: "1.0.0", name: _getOrCreateInstanceName() }); + + _enableDebugLogging(); + _hookConsole(); + _addErrorListeners(); + + flushTimer = setInterval(_flushLogs, FLUSH_INTERVAL); + }; + + ws.onmessage = function (event) { + let msg; + try { + msg = JSON.parse(event.data); + } catch (e) { + return; + } + + switch (msg.type) { + case "screenshot_request": + _handleScreenshotRequest(msg); + break; + case "reload_request": + _handleReloadRequest(msg); + break; + case "ping": + _sendMessage({ type: "pong" }); + break; + } + }; + + ws.onclose = function () { + _cleanup(); + _scheduleReconnect(); + }; + + ws.onerror = function () { + // onclose will be called after this + }; + } + + function _cleanup() { + if (flushTimer) { + clearInterval(flushTimer); + flushTimer = null; + } + _unhookConsole(); + ws = null; + } + + function disconnect() { + autoReconnect = false; + if (reconnectTimer) { + clearTimeout(reconnectTimer); + reconnectTimer = null; + } + if (ws) { + try { + ws.close(1000, "Disconnecting"); + } catch (e) { + // ignore + } + _cleanup(); + } + } + + function isConnected() { + return ws !== null && ws.readyState === WebSocket.OPEN; + } + + function getInstanceName() { + return _getOrCreateInstanceName(); + } + + exports.connect = connect; + exports.disconnect = disconnect; + exports.isConnected = isConnected; + exports.getInstanceName = getInstanceName; +}); From 1f3719839212cab8420b58ce9ac45d45c01d5880 Mon Sep 17 00:00:00 2001 From: abose Date: Mon, 16 Feb 2026 13:20:13 +0530 Subject: [PATCH 2/4] feat: chrome extenstion for phoenix builder to take screenshots --- .gitignore | 7 + phoenix-builder-mcp/README.md | 128 ++++++++++++++++++ .../chrome_extension/background.js | 13 ++ phoenix-builder-mcp/chrome_extension/build.sh | 26 ++++ .../chrome_extension/content-script.js | 27 ++++ .../chrome_extension/manifest.json | 36 +++++ .../chrome_extension/page-script.js | 3 + phoenix-builder-mcp/index.js | 34 +++++ src/phoenix/shell.js | 88 +++++++++++- 9 files changed, 359 insertions(+), 3 deletions(-) create mode 100644 phoenix-builder-mcp/README.md create mode 100644 phoenix-builder-mcp/chrome_extension/background.js create mode 100755 phoenix-builder-mcp/chrome_extension/build.sh create mode 100644 phoenix-builder-mcp/chrome_extension/content-script.js create mode 100644 phoenix-builder-mcp/chrome_extension/manifest.json create mode 100644 phoenix-builder-mcp/chrome_extension/page-script.js diff --git a/.gitignore b/.gitignore index 23215dc3c2..09a8da1989 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,13 @@ Thumbs.db # ignore node_modules inside phoenix-builder-mcp /phoenix-builder-mcp/node_modules +# ignore MCP server runtime files +/phoenix-builder-mcp/.mcp-server.pid + +# ignore chrome extension build artifacts +/phoenix-builder-mcp/chrome_extension/build/ +/phoenix-builder-mcp/chrome_extension/*.zip + # ignore node_modules inside src /src/node_modules /src-node/node_modules diff --git a/phoenix-builder-mcp/README.md b/phoenix-builder-mcp/README.md new file mode 100644 index 0000000000..9d088b8535 --- /dev/null +++ b/phoenix-builder-mcp/README.md @@ -0,0 +1,128 @@ +# Phoenix Builder MCP + +An MCP (Model Context Protocol) server that lets Claude Code launch, control, and inspect a running Phoenix Code instance. It also includes a Chrome extension that enables screenshot capture when Phoenix runs in a browser. + +## Prerequisites + +- Node.js +- The [phoenix-desktop](https://github.com/nicedoc/phoenix-desktop) repo cloned alongside this repo (i.e. `../phoenix-desktop`) + +## Setup + +### 1. Install dependencies + +```bash +cd phoenix-builder-mcp +npm install +``` + +### 2. Claude Code MCP configuration + +The project root already contains `.mcp.json` which registers the server automatically: + +```json +{ + "mcpServers": { + "phoenix-builder": { + "command": "node", + "args": ["phoenix-builder-mcp/index.js"], + "env": { + "PHOENIX_DESKTOP_PATH": "../phoenix-desktop" + } + } + } +} +``` + +Set `PHOENIX_DESKTOP_PATH` to the path of your phoenix-desktop checkout if it is not at `../phoenix-desktop`. + +You can also set `PHOENIX_MCP_WS_PORT` (default `38571`) to change the WebSocket port used for communication between the MCP server and the Phoenix browser runtime. + +### 3. Chrome extension (for browser screenshots) + +Screenshots work out of the box in the Electron/Tauri desktop app. If you are running Phoenix in a browser (e.g. `localhost` or `phcode.dev`), you need to install the Chrome extension: + +#### Loading as an unpacked extension (development) + +1. Open `chrome://extensions` in Chrome. +2. Enable **Developer mode** (toggle in the top-right corner). +3. Click **Load unpacked**. +4. Select the `phoenix-builder-mcp/chrome_extension/` directory. +5. The extension will appear as "Phoenix Code Screenshot". + +Once loaded, any Phoenix page on `localhost` or `phcode.dev` will have `window._phoenixScreenshotExtensionAvailable` set to `true`, and the `take_screenshot` MCP tool and `Phoenix.app.screenShotBinary()` API will work in the browser. + +#### Building a .zip for distribution + +```bash +cd phoenix-builder-mcp/chrome_extension +./build.sh +``` + +This produces `chrome_extension/build/phoenix-screenshot-extension.zip`. + +To build a signed `.crx` you need the Chrome binary and a private key: + +```bash +chrome --pack-extension=./phoenix-builder-mcp/chrome_extension --pack-extension-key=key.pem +``` + +## MCP Tools + +Once the MCP server is running, the following tools are available in Claude Code: + +### `start_phoenix` +Launches the Phoenix Code Electron app by running `npm run serve:electron` in the phoenix-desktop directory. Returns the process PID and WebSocket port. + +### `stop_phoenix` +Stops the running Phoenix Code process (SIGTERM, then SIGKILL after 5s). + +### `get_phoenix_status` +Returns process status, PID, WebSocket connection state, connected instance names, and the WS port. + +### `get_terminal_logs` +Returns stdout/stderr from the Electron process. By default returns only new logs since the last call. Pass `clear: true` to get all logs and clear the buffer. + +### `get_browser_console_logs` +Returns `console.log`/`warn`/`error` output forwarded from the Phoenix browser runtime over WebSocket. Supports the same `clear` flag. When multiple Phoenix instances are connected, pass `instance` to target a specific one (e.g. `"Phoenix-a3f2"`). + +### `take_screenshot` +Captures a PNG screenshot of the Phoenix window. Optionally pass a `selector` (CSS selector string) to capture a specific element. Returns the image directly as `image/png`. + +In Electron/Tauri this uses the native capture API. In the browser it requires the Chrome extension (see above). + +### `reload_phoenix` +Reloads the Phoenix app. Prompts to save unsaved files before reloading. + +### `force_reload_phoenix` +Force-reloads the Phoenix app without saving unsaved changes. + +## Typical Claude Code workflow + +``` +> start_phoenix # launches the app +> take_screenshot # see what the UI looks like +> get_browser_console_logs # check for errors +> reload_phoenix # pick up code changes +> take_screenshot # verify the fix +> stop_phoenix # done +``` + +## Architecture + +``` +Claude Code <--stdio--> MCP Server (index.js) + | + +-- process-manager.js (spawns/kills Electron) + +-- ws-control-server.js (WebSocket on port 38571) + | + Phoenix browser runtime + (connects back over WS for logs, screenshots, reload) +``` + +For browser-mode screenshots the flow is: + +``` +MCP Server --WS--> Phoenix runtime --postMessage--> Content Script --chrome.runtime--> Background SW + (captureVisibleTab) +``` diff --git a/phoenix-builder-mcp/chrome_extension/background.js b/phoenix-builder-mcp/chrome_extension/background.js new file mode 100644 index 0000000000..aa83f8959f --- /dev/null +++ b/phoenix-builder-mcp/chrome_extension/background.js @@ -0,0 +1,13 @@ +chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + if (message.type !== "phoenix_screenshot_capture") { + return false; + } + chrome.tabs.captureVisibleTab(null, { format: "png" }) + .then(dataUrl => { + sendResponse({ success: true, dataUrl }); + }) + .catch(err => { + sendResponse({ success: false, error: err.message || String(err) }); + }); + return true; // keep channel open for async sendResponse +}); diff --git a/phoenix-builder-mcp/chrome_extension/build.sh b/phoenix-builder-mcp/chrome_extension/build.sh new file mode 100755 index 0000000000..45fcd1e96e --- /dev/null +++ b/phoenix-builder-mcp/chrome_extension/build.sh @@ -0,0 +1,26 @@ +#!/bin/bash +# Builds a .zip of the Chrome extension for distribution or local install. +# Usage: ./build.sh +# +# To load as an unpacked extension during development: +# 1. Open chrome://extensions +# 2. Enable "Developer mode" +# 3. Click "Load unpacked" and select this directory +# +# To build a .crx (signed package) you need the Chrome binary and a private key: +# chrome --pack-extension=./phoenix-builder-mcp/chrome_extension --pack-extension-key=key.pem + +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +BUILD_DIR="$SCRIPT_DIR/build" + +rm -rf "$BUILD_DIR" +mkdir -p "$BUILD_DIR" + +zip -j "$BUILD_DIR/phoenix-screenshot-extension.zip" \ + "$SCRIPT_DIR/manifest.json" \ + "$SCRIPT_DIR/background.js" \ + "$SCRIPT_DIR/content-script.js" \ + "$SCRIPT_DIR/page-script.js" + +echo "Built: $BUILD_DIR/phoenix-screenshot-extension.zip" diff --git a/phoenix-builder-mcp/chrome_extension/content-script.js b/phoenix-builder-mcp/chrome_extension/content-script.js new file mode 100644 index 0000000000..a6993556fb --- /dev/null +++ b/phoenix-builder-mcp/chrome_extension/content-script.js @@ -0,0 +1,27 @@ +// Relay screenshot requests from the page to the background service worker. +// The availability flag (window._phoenixScreenshotExtensionAvailable) is set by +// page-script.js which runs in the MAIN world via the manifest. +window.addEventListener("message", (event) => { + if (event.source !== window || !event.data || event.data.type !== "phoenix_screenshot_request") { + return; + } + const requestId = event.data.id; + chrome.runtime.sendMessage({ type: "phoenix_screenshot_capture" }, (response) => { + if (chrome.runtime.lastError) { + window.postMessage({ + type: "phoenix_screenshot_response", + id: requestId, + success: false, + error: chrome.runtime.lastError.message || "Extension communication error" + }, "*"); + return; + } + window.postMessage({ + type: "phoenix_screenshot_response", + id: requestId, + success: response.success, + dataUrl: response.dataUrl, + error: response.error + }, "*"); + }); +}); diff --git a/phoenix-builder-mcp/chrome_extension/manifest.json b/phoenix-builder-mcp/chrome_extension/manifest.json new file mode 100644 index 0000000000..33e83db6ff --- /dev/null +++ b/phoenix-builder-mcp/chrome_extension/manifest.json @@ -0,0 +1,36 @@ +{ + "manifest_version": 3, + "name": "Phoenix Code Screenshot", + "version": "1.0.0", + "description": "Enables screenshot capture in Phoenix Code when running in the browser.", + "permissions": [], + "host_permissions": [ + "" + ], + "background": { + "service_worker": "background.js" + }, + "content_scripts": [ + { + "matches": [ + "http://localhost/*", + "https://phcode.dev/*", + "https://*.phcode.dev/*" + ], + "js": ["page-script.js"], + "run_at": "document_start", + "all_frames": false, + "world": "MAIN" + }, + { + "matches": [ + "http://localhost/*", + "https://phcode.dev/*", + "https://*.phcode.dev/*" + ], + "js": ["content-script.js"], + "run_at": "document_start", + "all_frames": false + } + ] +} diff --git a/phoenix-builder-mcp/chrome_extension/page-script.js b/phoenix-builder-mcp/chrome_extension/page-script.js new file mode 100644 index 0000000000..9b76622271 --- /dev/null +++ b/phoenix-builder-mcp/chrome_extension/page-script.js @@ -0,0 +1,3 @@ +// Runs in the MAIN world (the page's own JS context) at document_start, +// so it executes before deferred modules like shell.js. +window._phoenixScreenshotExtensionAvailable = true; diff --git a/phoenix-builder-mcp/index.js b/phoenix-builder-mcp/index.js index 5b7230ec54..4b8f7f282e 100644 --- a/phoenix-builder-mcp/index.js +++ b/phoenix-builder-mcp/index.js @@ -5,10 +5,42 @@ import { createProcessManager } from "./process-manager.js"; import { registerTools } from "./mcp-tools.js"; import { fileURLToPath } from "url"; import path from "path"; +import fs from "fs"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); +const PID_FILE = path.join(__dirname, ".mcp-server.pid"); + +// Kill any previous MCP server instance that wasn't cleaned up (e.g. parent crashed). +try { + const oldPid = parseInt(fs.readFileSync(PID_FILE, "utf8").trim(), 10); + if (oldPid && oldPid !== process.pid) { + try { + process.kill(oldPid, "SIGTERM"); + // Wait up to 3 seconds for it to exit + const deadline = Date.now() + 3000; + while (Date.now() < deadline) { + try { + process.kill(oldPid, 0); // throws if process is gone + await new Promise(r => setTimeout(r, 100)); + } catch { + break; + } + } + } catch { + // Process already dead — nothing to do + } + } +} catch { + // No PID file or unreadable — first run +} +fs.writeFileSync(PID_FILE, String(process.pid)); + +function removePidFile() { + try { fs.unlinkSync(PID_FILE); } catch { /* ignore */ } +} + const wsPort = parseInt(process.env.PHOENIX_MCP_WS_PORT || "38571", 10); const phoenixDesktopPath = process.env.PHOENIX_DESKTOP_PATH || path.resolve(__dirname, "../../phoenix-desktop"); @@ -29,11 +61,13 @@ await server.connect(transport); process.on("SIGINT", async () => { await processManager.stop(); wsControlServer.close(); + removePidFile(); process.exit(0); }); process.on("SIGTERM", async () => { await processManager.stop(); wsControlServer.close(); + removePidFile(); process.exit(0); }); diff --git a/src/phoenix/shell.js b/src/phoenix/shell.js index 8564370819..0daf4fef9b 100644 --- a/src/phoenix/shell.js +++ b/src/phoenix/shell.js @@ -188,10 +188,85 @@ function _resolveRect(rectOrNodeOrSelector) { }; } -async function _capturePageBinary(rectOrNodeOrSelector) { - if (!Phoenix.isNativeApp) { - throw new Error("Screenshot capture is not supported in browsers"); +function _dataUrlToUint8Array(dataUrl) { + const base64 = dataUrl.split(",")[1]; + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); } + return bytes; +} + +function _cropDataUrlToRect(dataUrl, rect) { + return new Promise((resolve, reject) => { + const img = new Image(); + img.onload = function () { + try { + const dpr = window.devicePixelRatio || 1; + const canvas = document.createElement("canvas"); + const sx = Math.round(rect.x * dpr); + const sy = Math.round(rect.y * dpr); + const sw = Math.round(rect.width * dpr); + const sh = Math.round(rect.height * dpr); + canvas.width = sw; + canvas.height = sh; + const ctx = canvas.getContext("2d"); + ctx.drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh); + canvas.toBlob(function (blob) { + if (!blob) { + reject(new Error("Failed to crop screenshot to blob")); + return; + } + const reader = new FileReader(); + reader.onloadend = function () { + resolve(new Uint8Array(reader.result)); + }; + reader.onerror = function () { + reject(new Error("Failed to read cropped screenshot blob")); + }; + reader.readAsArrayBuffer(blob); + }, "image/png"); + } catch (e) { + reject(e); + } + }; + img.onerror = function () { + reject(new Error("Failed to load screenshot image for cropping")); + }; + img.src = dataUrl; + }); +} + +let _screenshotRequestId = 0; +function _requestExtensionScreenshot() { + return new Promise((resolve, reject) => { + const id = ++_screenshotRequestId; + const TIMEOUT_MS = 30000; + let timeoutHandle; + function onMessage(event) { + if (event.source !== window || !event.data || + event.data.type !== "phoenix_screenshot_response" || event.data.id !== id) { + return; + } + window.removeEventListener("message", onMessage); + clearTimeout(timeoutHandle); + if (event.data.success) { + resolve(event.data.dataUrl); + } else { + reject(new Error(event.data.error || "Screenshot capture failed")); + } + } + window.addEventListener("message", onMessage); + timeoutHandle = setTimeout(() => { + window.removeEventListener("message", onMessage); + reject(new Error("Screenshot capture timed out after 30 seconds")); + }, TIMEOUT_MS); + window.postMessage({ type: "phoenix_screenshot_request", id }, "*"); + }); +} + +async function _capturePageBinary(rectOrNodeOrSelector) { const rect = _resolveRect(rectOrNodeOrSelector); if (rect !== undefined) { if (rect.x === undefined || rect.y === undefined || @@ -225,6 +300,13 @@ async function _capturePageBinary(rectOrNodeOrSelector) { if (window.__ELECTRON__) { return window.electronAPI.capturePage(rect); } + if (window._phoenixScreenshotExtensionAvailable) { + const dataUrl = await _requestExtensionScreenshot(); + return rect ? _cropDataUrlToRect(dataUrl, rect) : _dataUrlToUint8Array(dataUrl); + } + throw new Error("Screenshot capture is not supported in browsers. Install the Phoenix Code" + + " Screenshot extension for Chrome: load it as an unpacked extension from" + + " phoenix-builder-mcp/chrome_extension/ in chrome://extensions with Developer mode enabled."); } Phoenix.app = { From 17bd15db85a1ed41850997b54e4b88bb4b2b9224 Mon Sep 17 00:00:00 2001 From: abose Date: Mon, 16 Feb 2026 15:52:36 +0530 Subject: [PATCH 3/4] feat: phoenix builder mcp to get browser console logs --- CLAUDE.md | 1 + phoenix-builder-mcp/mcp-tools.js | 47 +-- phoenix-builder-mcp/ws-control-server.js | 63 +++- src/extensions/default/DebugCommands/main.js | 6 +- src/index.html | 1 + .../builder-connect-dialog.html | 83 +++-- src/phoenix-builder/main.js | 101 +++-- src/phoenix-builder/phoenix-builder-boot.js | 346 ++++++++++++++++++ src/phoenix-builder/phoenix-builder-client.js | 308 +--------------- 9 files changed, 571 insertions(+), 385 deletions(-) create mode 100644 src/phoenix-builder/phoenix-builder-boot.js diff --git a/CLAUDE.md b/CLAUDE.md index e21e6386b0..cf905ef066 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,3 +11,4 @@ - Brace style: (`if (x) {`), single-line blocks allowed. - Always use curly braces for `if`/`else`/`for`/`while`. - No trailing whitespace. +- Use `const` and `let` instead of `var`. diff --git a/phoenix-builder-mcp/mcp-tools.js b/phoenix-builder-mcp/mcp-tools.js index 1c13ba8b49..2b525dcbdd 100644 --- a/phoenix-builder-mcp/mcp-tools.js +++ b/phoenix-builder-mcp/mcp-tools.js @@ -89,40 +89,27 @@ export function registerTools(server, processManager, wsControlServer, phoenixDe server.tool( "get_browser_console_logs", - "Get console logs forwarded from the Phoenix browser runtime via WebSocket. By default returns new logs since last call; set clear=true to get all logs and clear the buffer.", + "Get console logs captured from the Phoenix browser runtime from boot time. Fetches the full retained log buffer directly from the browser instance.", { - clear: z.boolean().default(false).describe("If true, return all logs and clear the buffer. If false, return only new logs since last read."), instance: z.string().optional().describe("Target a specific Phoenix instance by name (e.g. 'Phoenix-a3f2'). Required when multiple instances are connected.") }, - async ({ clear, instance }) => { - let logs; - if (clear) { - logs = wsControlServer.getBrowserLogs(false, instance); - if (logs && logs.error) { - return { - content: [{ type: "text", text: JSON.stringify(logs) }] - }; - } - const clearResult = wsControlServer.clearBrowserLogs(instance); - if (clearResult && clearResult.error) { - return { - content: [{ type: "text", text: JSON.stringify(clearResult) }] - }; - } - } else { - logs = wsControlServer.getBrowserLogs(true, instance); - if (logs && logs.error) { - return { - content: [{ type: "text", text: JSON.stringify(logs) }] - }; - } + async ({ instance }) => { + try { + const logs = await wsControlServer.requestLogs(instance); + return { + content: [{ + type: "text", + text: JSON.stringify(logs.length > 0 ? logs : "(no browser logs)") + }] + }; + } catch (err) { + return { + content: [{ + type: "text", + text: JSON.stringify({ error: err.message }) + }] + }; } - return { - content: [{ - type: "text", - text: JSON.stringify(logs.length > 0 ? logs : "(no browser logs)") - }] - }; } ); diff --git a/phoenix-builder-mcp/ws-control-server.js b/phoenix-builder-mcp/ws-control-server.js index 8e22e19050..5250b37f86 100644 --- a/phoenix-builder-mcp/ws-control-server.js +++ b/phoenix-builder-mcp/ws-control-server.js @@ -27,6 +27,7 @@ export function createWSControlServer(port) { clientName = msg.name || ("Unknown-" + (++unknownCounter)); // If same name reconnects (e.g. tab reload), close old connection + // but preserve the existing log buffer so logs survive across reloads const existing = clients.get(clientName); if (existing) { try { @@ -34,13 +35,18 @@ export function createWSControlServer(port) { } catch { // ignore } + clients.set(clientName, { + ws: ws, + logs: existing.logs, + isAlive: true + }); + } else { + clients.set(clientName, { + ws: ws, + logs: new LogBuffer(), + isAlive: true + }); } - - clients.set(clientName, { - ws: ws, - logs: new LogBuffer(), - isAlive: true - }); break; } @@ -63,6 +69,15 @@ export function createWSControlServer(port) { break; } + case "get_logs_response": { + const pending4 = pendingRequests.get(msg.id); + if (pending4) { + pendingRequests.delete(msg.id); + pending4.resolve(msg.entries || []); + } + break; + } + case "reload_response": { const pending3 = pendingRequests.get(msg.id); if (pending3) { @@ -232,6 +247,41 @@ export function createWSControlServer(port) { }); } + function requestLogs(instanceName) { + return new Promise((resolve, reject) => { + const resolved = _resolveClient(instanceName); + if (resolved.error) { + reject(new Error(resolved.error)); + return; + } + + const { client } = resolved; + if (client.ws.readyState !== 1) { + reject(new Error("Phoenix client \"" + resolved.name + "\" is not connected")); + return; + } + + const id = ++requestIdCounter; + const timeout = setTimeout(() => { + pendingRequests.delete(id); + reject(new Error("Log request timed out (10s)")); + }, 10000); + + pendingRequests.set(id, { + resolve: (data) => { + clearTimeout(timeout); + resolve(data); + }, + reject: (err) => { + clearTimeout(timeout); + reject(err); + } + }); + + client.ws.send(JSON.stringify({ type: "get_logs_request", id })); + }); + } + function getBrowserLogs(sinceLast, instanceName) { const resolved = _resolveClient(instanceName); if (resolved.error) { @@ -281,6 +331,7 @@ export function createWSControlServer(port) { return { requestScreenshot, requestReload, + requestLogs, getBrowserLogs, clearBrowserLogs, isClientConnected, diff --git a/src/extensions/default/DebugCommands/main.js b/src/extensions/default/DebugCommands/main.js index 5dce4cb5d4..58d792abd8 100644 --- a/src/extensions/default/DebugCommands/main.js +++ b/src/extensions/default/DebugCommands/main.js @@ -19,7 +19,7 @@ * */ -/*globals path, logger, Phoenix*/ +/*globals path, logger, Phoenix, AppConfig*/ /*jslint regexp: true */ define(function (require, exports, module) { @@ -828,7 +828,9 @@ define(function (require, exports, module) { diagnosticsSubmenu.addMenuItem(DEBUG_RUN_UNIT_TESTS); CommandManager.register(Strings.CMD_BUILD_TESTS, DEBUG_BUILD_TESTS, TestBuilder.toggleTestBuilder); diagnosticsSubmenu.addMenuItem(DEBUG_BUILD_TESTS); - diagnosticsSubmenu.addMenuItem("debug.phoenixBuilderConnect"); + if (AppConfig.config.environment === "dev") { + diagnosticsSubmenu.addMenuItem("debug.phoenixBuilderConnect"); + } diagnosticsSubmenu.addMenuDivider(); diagnosticsSubmenu.addMenuItem(DEBUG_ENABLE_LOGGING); diagnosticsSubmenu.addMenuItem(DEBUG_ENABLE_PHNODE_INSPECTOR, undefined, undefined, undefined, { diff --git a/src/index.html b/src/index.html index 5c7e665e00..0c20244df5 100644 --- a/src/index.html +++ b/src/index.html @@ -481,6 +481,7 @@ +