@pairdraw/mcp 0.16.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/connect.mjs +2 -2
- package/dist/connect.mjs.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{server--T-KD99G.mjs → server-BdiJUhSs.mjs} +3 -3
- package/dist/server-BdiJUhSs.mjs.map +1 -0
- package/dist/server.mjs +1 -1
- package/dist/stdio.mjs +1 -1
- package/package.json +16 -2
- package/src/connect.ts +1 -1
- package/dist/server--T-KD99G.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -13,8 +13,8 @@ On macOS and Linux, local clients prefer a private Unix domain socket; Windows a
|
|
|
13
13
|
|
|
14
14
|
Streamable HTTP clients initialize with a POST, then open GET/SSE with the returned `Mcp-Session-Id`; DELETE ends the session. The server keeps at most 10 sessions and closes those idle for 15 minutes (`PAIRDRAW_MCP_SESSION_IDLE_TIMEOUT_MS`, `0` disables). Running requests keep a session alive, an open SSE stream alone does not, and an expired session ID returns 404.
|
|
15
15
|
|
|
16
|
-
- Setup and client configuration: https://github.com/BadryansahBangsawan/pairdraw/blob/
|
|
17
|
-
- Coding agents in the browser (`pairdraw-connect`): https://github.com/BadryansahBangsawan/pairdraw/blob/
|
|
16
|
+
- Setup and client configuration: https://github.com/BadryansahBangsawan/pairdraw/blob/main/packages/docs/programmable/mcp-server.md
|
|
17
|
+
- Coding agents in the browser (`pairdraw-connect`): https://github.com/BadryansahBangsawan/pairdraw/blob/main/packages/docs/programmable/browser-agents.md
|
|
18
18
|
- Source and issues: https://github.com/BadryansahBangsawan/pairdraw
|
|
19
19
|
|
|
20
20
|
MIT License.
|
package/dist/connect.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import "./rolldown-runtime-ClRpJifh.mjs";
|
|
3
|
-
import { f as pairingFingerprint, i as resolveCORSOrigins, n as startServer, r as DEFAULT_CONNECT_APP_URL, t as MCP_VERSION } from "./server
|
|
3
|
+
import { f as pairingFingerprint, i as resolveCORSOrigins, n as startServer, r as DEFAULT_CONNECT_APP_URL, t as MCP_VERSION } from "./server-BdiJUhSs.mjs";
|
|
4
4
|
import { n as getCompanionDir } from "./paths-BpcXnrbP.mjs";
|
|
5
5
|
import { t as resolveMCPRoot } from "./root-BzmoiT2g.mjs";
|
|
6
6
|
import { i as readToolPolicyFromEnv } from "./policy-B8Ka4WRH.mjs";
|
|
@@ -83,7 +83,7 @@ if (process.argv.includes("--help") || process.argv.includes("-h")) {
|
|
|
83
83
|
process.stdout.write(`pairdraw-connect
|
|
84
84
|
|
|
85
85
|
Connect Pairdraw in the browser to this computer, so its chat can run
|
|
86
|
-
Claude Code, Codex,
|
|
86
|
+
Claude Code, Codex, Gemini CLI, or omp here and use Pairdraw's tools.
|
|
87
87
|
|
|
88
88
|
Starts Pairdraw's MCP server with an agent bridge and opens a one-time link
|
|
89
89
|
that pairs the browser tab. Keep it running while you use agents.
|
package/dist/connect.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.mjs","names":[],"sources":["../src/agents/link.ts","../src/connect.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport { rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nimport { uniq } from 'es-toolkit'\n\nimport { DEFAULT_CONNECT_APP_URL, resolveCORSOrigins } from '#mcp/transport/origins'\n\n/** Hosts a development server may run the app on with plain HTTP. */\nfunction isLocalHost(hostname: string): boolean {\n return (\n hostname === 'localhost' ||\n hostname.endsWith('.localhost') ||\n hostname === '127.0.0.1' ||\n hostname === '[::1]'\n )\n}\n\n/**\n * The web app the companion pairs with: the editor on this computer, or one the operator names,\n * such as a Cloud server's. Plain HTTP is accepted only on this machine. Returns null for anything\n * else.\n */\nexport function resolveConnectAppURL(raw: string | undefined): URL | null {\n const text = raw?.trim() || DEFAULT_CONNECT_APP_URL\n let url: URL\n try {\n url = new URL(text)\n } catch {\n return null\n }\n if (url.username || url.password) return null\n if (url.protocol === 'https:') return url\n return url.protocol === 'http:' && isLocalHost(url.hostname) ? url : null\n}\n\n/**\n * The link that pairs a tab: the app with `#connect=<code>` in its fragment, which browsers never\n * send to a server, and the port when it is not the default one.\n */\nexport function connectLink(appURL: URL, code: string, port: number, defaultPort: number): string {\n const link = new URL(appURL)\n const params = new URLSearchParams({ connect: code })\n if (port !== defaultPort) params.set('port', String(port))\n link.hash = params.toString()\n return link.toString()\n}\n\n/**\n * The origins the companion lets call it: the configured ones and the app it pairs with. `*`\n * would let any site drive the agent bridge, so it is dropped here, whatever was configured.\n */\nexport function connectCORSOrigins(raw: string | undefined, appURL: URL): string[] {\n const configured = resolveCORSOrigins(raw).filter((origin) => origin !== '*')\n return uniq([...configured, appURL.origin])\n}\n\nfunction escapeAttribute(value: string): string {\n return value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<')\n}\n\n/**\n * Writes a page that forwards to the link, readable only by this user, so the browser is opened\n * with the page's path rather than the link: a command line, which other users of the computer\n * can list, then never holds the pairing code. Returns the path and a function that deletes it.\n */\nexport async function writeConnectPage(\n dir: string,\n link: string\n): Promise<{ path: string; remove: () => Promise<void> }> {\n const path = join(dir, `connect-${randomBytes(8).toString('hex')}.html`)\n const href = escapeAttribute(link)\n const html =\n `<!doctype html><meta charset=\"utf-8\"><meta name=\"referrer\" content=\"no-referrer\">` +\n `<meta http-equiv=\"refresh\" content=\"0;url=${href}\"><title>Pairdraw</title>` +\n `<a href=\"${href}\">Open Pairdraw</a>\\n`\n await writeFile(path, html, { mode: 0o600, flag: 'wx' })\n return { path, remove: () => rm(path, { force: true }) }\n}\n","#!/usr/bin/env node\nimport { spawn } from 'node:child_process'\nimport { platform } from 'node:os'\n\nimport {\n connectCORSOrigins,\n connectLink,\n resolveConnectAppURL,\n writeConnectPage\n} from '#mcp/agents/link'\nimport { pairingFingerprint } from '#mcp/agents/pairing'\nimport { resolveMCPRoot } from '#mcp/root'\nimport { MCP_VERSION, startServer } from '#mcp/server'\nimport { readToolPolicyFromEnv } from '#mcp/tool/policy'\nimport { DEFAULT_CONNECT_APP_URL } from '#mcp/transport/origins'\nimport { getCompanionDir } from '#mcp/transport/paths'\n\nconst DEFAULT_PORT = 7600\n\nif (process.argv.includes('--version')) {\n process.stdout.write(`${MCP_VERSION}\\n`)\n process.exit(0)\n}\n\nif (process.argv.includes('--help') || process.argv.includes('-h')) {\n process.stdout.write(\n `pairdraw-connect\\n\\n` +\n `Connect Pairdraw in the browser to this computer, so its chat can run\\n` +\n `Claude Code, Codex, or Gemini CLI here and use Pairdraw's tools.\\n\\n` +\n `Starts Pairdraw's MCP server with an agent bridge and opens a one-time link\\n` +\n `that pairs the browser tab. Keep it running while you use agents.\\n\\n` +\n `Options:\\n` +\n ` --help, -h Show this help message\\n` +\n ` --version Print the version\\n` +\n ` --no-open Print the link without opening the browser\\n\\n` +\n `Environment variables:\\n` +\n ` PORT TCP port (default: ${DEFAULT_PORT})\\n` +\n ` PAIRDRAW_CONNECT_APP_URL The Pairdraw web app to pair with (default:\\n` +\n ` ${DEFAULT_CONNECT_APP_URL}, the editor \\`bun run dev\\` serves).\\n` +\n ` Its origin may call this server.\\n` +\n ` PAIRDRAW_MCP_CORS_ORIGIN Further origins allowed to call this server, comma-separated.\\n` +\n ` PAIRDRAW_MCP_ROOT Allowed directory for file-scoped tools (default: home\\n` +\n ` directory on Windows, current working directory elsewhere)\\n` +\n ` PAIRDRAW_MCP_SOCKET Override the Unix socket path\\n` +\n ` PAIRDRAW_MCP_DISABLED_TOOLS Comma-separated tool names to omit\\n` +\n ` PAIRDRAW_MCP_SCOPE \"selection\" to let clients read only the selected layers\\n\\n` +\n `The eval tool is always off here, and authentication cannot be disabled.\\n`\n )\n process.exit(0)\n}\n\nfunction fail(message: string): never {\n process.stderr.write(`Error: ${message}\\n`)\n process.exit(1)\n}\n\nconst portText = (process.env.PORT ?? String(DEFAULT_PORT)).trim()\nif (!/^\\d+$/.test(portText)) fail(`PORT must be an integer in 1–65535, got \"${portText}\"`)\nconst port = Number.parseInt(portText, 10)\nif (port < 1 || port > 65535) fail(`PORT must be an integer in 1–65535, got \"${portText}\"`)\n\nconst appURL = resolveConnectAppURL(process.env.PAIRDRAW_CONNECT_APP_URL)\nif (!appURL) {\n fail('PAIRDRAW_CONNECT_APP_URL must be an https URL, or http on localhost')\n}\n\nconst explicitToken = process.env.PAIRDRAW_MCP_AUTH_TOKEN?.trim()\nconst toolPolicy = readToolPolicyFromEnv()\n\nlet handle: Awaited<ReturnType<typeof startServer>>\ntry {\n handle = await startServer({\n httpPort: port,\n withTcp: true,\n socketPath: process.env.PAIRDRAW_MCP_SOCKET?.trim() || null,\n // The browser runs agents that can edit files; eval would let a page run code here too.\n enableEval: false,\n disabledTools: toolPolicy.disabledTools,\n scope: toolPolicy.scope,\n mcpRoot: resolveMCPRoot(process.env.PAIRDRAW_MCP_ROOT),\n // Auth always stays on: a paired tab and local MCP clients each bring their own token.\n authToken: explicitToken || undefined,\n corsOrigin: connectCORSOrigins(process.env.PAIRDRAW_MCP_CORS_ORIGIN, appURL),\n agents: {\n onPaired: () =>\n process.stdout.write(\n 'A browser tab connected. If you did not open the link, press Ctrl+C to stop.\\n'\n )\n }\n })\n} catch (error) {\n const code = error instanceof Error && 'code' in error ? error.code : null\n if (code === 'EADDRINUSE') {\n fail(\n `port ${port} or the MCP socket is already in use. Quit the Pairdraw desktop app or ` +\n `another MCP server, or start this one with PORT=${port + 1}.`\n )\n }\n fail(error instanceof Error ? error.message : String(error))\n}\n\nconst issueCode = handle.issuePairingCode\nif (!issueCode) fail('The agent bridge did not start.')\n\n/** Opens a file or link in the default browser, without a shell. */\nfunction openBrowser(url: string): void {\n const os = platform()\n let command = 'xdg-open'\n let args = [url]\n if (os === 'darwin') command = 'open'\n if (os === 'win32') {\n command = 'rundll32'\n args = ['url.dll,FileProtocolHandler', url]\n }\n try {\n const child = spawn(command, args, { stdio: 'ignore', detached: true })\n child.on('error', () => undefined)\n child.unref()\n } catch {\n process.stdout.write('Could not open the browser; open the link above yourself.\\n')\n }\n}\n\nconst shouldOpen = !process.argv.includes('--no-open')\n/** How long the page that forwards to a link stays on disk; the browser reads it at once. */\nconst PAGE_LIFETIME_MS = 30_000\n\n/**\n * Opens the link through a private page, so no command line holds the code, and deletes the\n * page soon after.\n */\nasync function openLink(link: string): Promise<void> {\n try {\n const page = await writeConnectPage(await getCompanionDir(), link)\n openBrowser(page.path)\n setTimeout(() => void page.remove(), PAGE_LIFETIME_MS).unref()\n } catch {\n process.stdout.write('Could not open the browser; open the link above yourself.\\n')\n }\n}\n\nfunction announceLink(open: boolean) {\n const code = issueCode()\n const link = connectLink(appURL, code, handle.httpPort, DEFAULT_PORT)\n process.stdout.write(\n `\\nOpen this link to connect Pairdraw to this computer (works once, for 2 minutes):\\n` +\n ` ${link}\\n` +\n `The tab asks you to confirm; check that it shows ${pairingFingerprint(code)}.\\n\\n` +\n `Press Enter for a new link. Press Ctrl+C to stop.\\n`\n )\n if (open) void openLink(link)\n}\n\nprocess.stdout.write(`Pairdraw companion ${MCP_VERSION}\\n`)\nprocess.stdout.write(` HTTP: http://127.0.0.1:${handle.httpPort}\\n`)\nif (handle.socketPath) process.stdout.write(` Socket: ${handle.socketPath}\\n`)\nannounceLink(shouldOpen)\n\nprocess.stdin.on('data', () => announceLink(false))\nprocess.stdin.on('error', () => undefined)\nprocess.stdin.resume()\n\nconst shutdown = async () => {\n process.stdout.write('\\nStopping the Pairdraw companion...\\n')\n await handle.close()\n process.exit(0)\n}\n\nprocess.on('SIGINT', () => void shutdown().catch(() => process.exit(1)))\nprocess.on('SIGTERM', () => void shutdown().catch(() => process.exit(1)))\n"],"mappings":";;;;;;;;;;;;;;AASA,SAAS,YAAY,UAA2B;CAC9C,OACE,aAAa,eACb,SAAS,SAAS,YAAY,KAC9B,aAAa,eACb,aAAa;AAEjB;;;;;;AAOA,SAAgB,qBAAqB,KAAqC;CAC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;AAC9E,aAAa,UAAU;AAEvB,QAAQ,MAAM,GAAG,cAAc,aAAa,KAAK,CAAC;AAClD,QAAQ,MAAM,GAAG,eAAe,MAAS;AACzC,QAAQ,MAAM,OAAO;AAErB,MAAM,WAAW,YAAY;CAC3B,QAAQ,OAAO,MAAM,wCAAwC;CAC7D,MAAM,OAAO,MAAM;CACnB,QAAQ,KAAK,CAAC;AAChB;AAEA,QAAQ,GAAG,gBAAgB,KAAK,SAAS,CAAC,CAAC,YAAY,QAAQ,KAAK,CAAC,CAAC,CAAC;AACvE,QAAQ,GAAG,iBAAiB,KAAK,SAAS,CAAC,CAAC,YAAY,QAAQ,KAAK,CAAC,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"connect.mjs","names":[],"sources":["../src/agents/link.ts","../src/connect.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport { rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nimport { uniq } from 'es-toolkit'\n\nimport { DEFAULT_CONNECT_APP_URL, resolveCORSOrigins } from '#mcp/transport/origins'\n\n/** Hosts a development server may run the app on with plain HTTP. */\nfunction isLocalHost(hostname: string): boolean {\n return (\n hostname === 'localhost' ||\n hostname.endsWith('.localhost') ||\n hostname === '127.0.0.1' ||\n hostname === '[::1]'\n )\n}\n\n/**\n * The web app the companion pairs with: the editor on this computer, or one the operator names,\n * such as a Cloud server's. Plain HTTP is accepted only on this machine. Returns null for anything\n * else.\n */\nexport function resolveConnectAppURL(raw: string | undefined): URL | null {\n const text = raw?.trim() || DEFAULT_CONNECT_APP_URL\n let url: URL\n try {\n url = new URL(text)\n } catch {\n return null\n }\n if (url.username || url.password) return null\n if (url.protocol === 'https:') return url\n return url.protocol === 'http:' && isLocalHost(url.hostname) ? url : null\n}\n\n/**\n * The link that pairs a tab: the app with `#connect=<code>` in its fragment, which browsers never\n * send to a server, and the port when it is not the default one.\n */\nexport function connectLink(appURL: URL, code: string, port: number, defaultPort: number): string {\n const link = new URL(appURL)\n const params = new URLSearchParams({ connect: code })\n if (port !== defaultPort) params.set('port', String(port))\n link.hash = params.toString()\n return link.toString()\n}\n\n/**\n * The origins the companion lets call it: the configured ones and the app it pairs with. `*`\n * would let any site drive the agent bridge, so it is dropped here, whatever was configured.\n */\nexport function connectCORSOrigins(raw: string | undefined, appURL: URL): string[] {\n const configured = resolveCORSOrigins(raw).filter((origin) => origin !== '*')\n return uniq([...configured, appURL.origin])\n}\n\nfunction escapeAttribute(value: string): string {\n return value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<')\n}\n\n/**\n * Writes a page that forwards to the link, readable only by this user, so the browser is opened\n * with the page's path rather than the link: a command line, which other users of the computer\n * can list, then never holds the pairing code. Returns the path and a function that deletes it.\n */\nexport async function writeConnectPage(\n dir: string,\n link: string\n): Promise<{ path: string; remove: () => Promise<void> }> {\n const path = join(dir, `connect-${randomBytes(8).toString('hex')}.html`)\n const href = escapeAttribute(link)\n const html =\n `<!doctype html><meta charset=\"utf-8\"><meta name=\"referrer\" content=\"no-referrer\">` +\n `<meta http-equiv=\"refresh\" content=\"0;url=${href}\"><title>Pairdraw</title>` +\n `<a href=\"${href}\">Open Pairdraw</a>\\n`\n await writeFile(path, html, { mode: 0o600, flag: 'wx' })\n return { path, remove: () => rm(path, { force: true }) }\n}\n","#!/usr/bin/env node\nimport { spawn } from 'node:child_process'\nimport { platform } from 'node:os'\n\nimport {\n connectCORSOrigins,\n connectLink,\n resolveConnectAppURL,\n writeConnectPage\n} from '#mcp/agents/link'\nimport { pairingFingerprint } from '#mcp/agents/pairing'\nimport { resolveMCPRoot } from '#mcp/root'\nimport { MCP_VERSION, startServer } from '#mcp/server'\nimport { readToolPolicyFromEnv } from '#mcp/tool/policy'\nimport { DEFAULT_CONNECT_APP_URL } from '#mcp/transport/origins'\nimport { getCompanionDir } from '#mcp/transport/paths'\n\nconst DEFAULT_PORT = 7600\n\nif (process.argv.includes('--version')) {\n process.stdout.write(`${MCP_VERSION}\\n`)\n process.exit(0)\n}\n\nif (process.argv.includes('--help') || process.argv.includes('-h')) {\n process.stdout.write(\n `pairdraw-connect\\n\\n` +\n `Connect Pairdraw in the browser to this computer, so its chat can run\\n` +\n `Claude Code, Codex, Gemini CLI, or omp here and use Pairdraw's tools.\\n\\n` +\n `Starts Pairdraw's MCP server with an agent bridge and opens a one-time link\\n` +\n `that pairs the browser tab. Keep it running while you use agents.\\n\\n` +\n `Options:\\n` +\n ` --help, -h Show this help message\\n` +\n ` --version Print the version\\n` +\n ` --no-open Print the link without opening the browser\\n\\n` +\n `Environment variables:\\n` +\n ` PORT TCP port (default: ${DEFAULT_PORT})\\n` +\n ` PAIRDRAW_CONNECT_APP_URL The Pairdraw web app to pair with (default:\\n` +\n ` ${DEFAULT_CONNECT_APP_URL}, the editor \\`bun run dev\\` serves).\\n` +\n ` Its origin may call this server.\\n` +\n ` PAIRDRAW_MCP_CORS_ORIGIN Further origins allowed to call this server, comma-separated.\\n` +\n ` PAIRDRAW_MCP_ROOT Allowed directory for file-scoped tools (default: home\\n` +\n ` directory on Windows, current working directory elsewhere)\\n` +\n ` PAIRDRAW_MCP_SOCKET Override the Unix socket path\\n` +\n ` PAIRDRAW_MCP_DISABLED_TOOLS Comma-separated tool names to omit\\n` +\n ` PAIRDRAW_MCP_SCOPE \"selection\" to let clients read only the selected layers\\n\\n` +\n `The eval tool is always off here, and authentication cannot be disabled.\\n`\n )\n process.exit(0)\n}\n\nfunction fail(message: string): never {\n process.stderr.write(`Error: ${message}\\n`)\n process.exit(1)\n}\n\nconst portText = (process.env.PORT ?? String(DEFAULT_PORT)).trim()\nif (!/^\\d+$/.test(portText)) fail(`PORT must be an integer in 1–65535, got \"${portText}\"`)\nconst port = Number.parseInt(portText, 10)\nif (port < 1 || port > 65535) fail(`PORT must be an integer in 1–65535, got \"${portText}\"`)\n\nconst appURL = resolveConnectAppURL(process.env.PAIRDRAW_CONNECT_APP_URL)\nif (!appURL) {\n fail('PAIRDRAW_CONNECT_APP_URL must be an https URL, or http on localhost')\n}\n\nconst explicitToken = process.env.PAIRDRAW_MCP_AUTH_TOKEN?.trim()\nconst toolPolicy = readToolPolicyFromEnv()\n\nlet handle: Awaited<ReturnType<typeof startServer>>\ntry {\n handle = await startServer({\n httpPort: port,\n withTcp: true,\n socketPath: process.env.PAIRDRAW_MCP_SOCKET?.trim() || null,\n // The browser runs agents that can edit files; eval would let a page run code here too.\n enableEval: false,\n disabledTools: toolPolicy.disabledTools,\n scope: toolPolicy.scope,\n mcpRoot: resolveMCPRoot(process.env.PAIRDRAW_MCP_ROOT),\n // Auth always stays on: a paired tab and local MCP clients each bring their own token.\n authToken: explicitToken || undefined,\n corsOrigin: connectCORSOrigins(process.env.PAIRDRAW_MCP_CORS_ORIGIN, appURL),\n agents: {\n onPaired: () =>\n process.stdout.write(\n 'A browser tab connected. If you did not open the link, press Ctrl+C to stop.\\n'\n )\n }\n })\n} catch (error) {\n const code = error instanceof Error && 'code' in error ? error.code : null\n if (code === 'EADDRINUSE') {\n fail(\n `port ${port} or the MCP socket is already in use. Quit the Pairdraw desktop app or ` +\n `another MCP server, or start this one with PORT=${port + 1}.`\n )\n }\n fail(error instanceof Error ? error.message : String(error))\n}\n\nconst issueCode = handle.issuePairingCode\nif (!issueCode) fail('The agent bridge did not start.')\n\n/** Opens a file or link in the default browser, without a shell. */\nfunction openBrowser(url: string): void {\n const os = platform()\n let command = 'xdg-open'\n let args = [url]\n if (os === 'darwin') command = 'open'\n if (os === 'win32') {\n command = 'rundll32'\n args = ['url.dll,FileProtocolHandler', url]\n }\n try {\n const child = spawn(command, args, { stdio: 'ignore', detached: true })\n child.on('error', () => undefined)\n child.unref()\n } catch {\n process.stdout.write('Could not open the browser; open the link above yourself.\\n')\n }\n}\n\nconst shouldOpen = !process.argv.includes('--no-open')\n/** How long the page that forwards to a link stays on disk; the browser reads it at once. */\nconst PAGE_LIFETIME_MS = 30_000\n\n/**\n * Opens the link through a private page, so no command line holds the code, and deletes the\n * page soon after.\n */\nasync function openLink(link: string): Promise<void> {\n try {\n const page = await writeConnectPage(await getCompanionDir(), link)\n openBrowser(page.path)\n setTimeout(() => void page.remove(), PAGE_LIFETIME_MS).unref()\n } catch {\n process.stdout.write('Could not open the browser; open the link above yourself.\\n')\n }\n}\n\nfunction announceLink(open: boolean) {\n const code = issueCode()\n const link = connectLink(appURL, code, handle.httpPort, DEFAULT_PORT)\n process.stdout.write(\n `\\nOpen this link to connect Pairdraw to this computer (works once, for 2 minutes):\\n` +\n ` ${link}\\n` +\n `The tab asks you to confirm; check that it shows ${pairingFingerprint(code)}.\\n\\n` +\n `Press Enter for a new link. Press Ctrl+C to stop.\\n`\n )\n if (open) void openLink(link)\n}\n\nprocess.stdout.write(`Pairdraw companion ${MCP_VERSION}\\n`)\nprocess.stdout.write(` HTTP: http://127.0.0.1:${handle.httpPort}\\n`)\nif (handle.socketPath) process.stdout.write(` Socket: ${handle.socketPath}\\n`)\nannounceLink(shouldOpen)\n\nprocess.stdin.on('data', () => announceLink(false))\nprocess.stdin.on('error', () => undefined)\nprocess.stdin.resume()\n\nconst shutdown = async () => {\n process.stdout.write('\\nStopping the Pairdraw companion...\\n')\n await handle.close()\n process.exit(0)\n}\n\nprocess.on('SIGINT', () => void shutdown().catch(() => process.exit(1)))\nprocess.on('SIGTERM', () => void shutdown().catch(() => process.exit(1)))\n"],"mappings":";;;;;;;;;;;;;;AASA,SAAS,YAAY,UAA2B;CAC9C,OACE,aAAa,eACb,SAAS,SAAS,YAAY,KAC9B,aAAa,eACb,aAAa;AAEjB;;;;;;AAOA,SAAgB,qBAAqB,KAAqC;CACxE,MAAM,OAAO,KAAK,KAAK,KAAA;CACvB,IAAI;CACJ,IAAI;EACF,MAAM,IAAI,IAAI,IAAI;CACpB,QAAQ;EACN,OAAO;CACT;CACA,IAAI,IAAI,YAAY,IAAI,UAAU,OAAO;CACzC,IAAI,IAAI,aAAa,UAAU,OAAO;CACtC,OAAO,IAAI,aAAa,WAAW,YAAY,IAAI,QAAQ,IAAI,MAAM;A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QAAQ,GAAG,gBAAgB,KAAK,SAAS,CAAC,CAAC,YAAY,QAAQ,KAAK,CAAC,CAAC,CAAC;AACvE,QAAQ,GAAG,iBAAiB,KAAK,SAAS,CAAC,CAAC,YAAY,QAAQ,KAAK,CAAC,CAAC,CAAC"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import "./rolldown-runtime-ClRpJifh.mjs";
|
|
3
|
-
import { d as devAgentBridgeFromEnv, i as resolveCORSOrigins, n as startServer, t as MCP_VERSION } from "./server
|
|
3
|
+
import { d as devAgentBridgeFromEnv, i as resolveCORSOrigins, n as startServer, t as MCP_VERSION } from "./server-BdiJUhSs.mjs";
|
|
4
4
|
import { t as resolveMCPRoot } from "./root-BzmoiT2g.mjs";
|
|
5
5
|
import { i as readToolPolicyFromEnv } from "./policy-B8Ka4WRH.mjs";
|
|
6
6
|
//#region src/index.ts
|
|
@@ -1812,7 +1812,7 @@ function sessionNotFound() {
|
|
|
1812
1812
|
var design_authoring_default = "<!-- Generated from design-jsx reference and renderer metadata. Do not edit; run bun run generate:authoring-reference. -->\n\n# Pairdraw design authoring\n\nThis reference describes scene creation, not React DOM output. Use the `render` tool for JSX strings, or import `Frame`, `Text`, and other authoring exports from `@pairdraw/design-jsx` and render them with `renderTree` from `@pairdraw/core/design-jsx` in library code. Library exports are not automatically globals in agent `eval`; use only the bindings exposed by that execution environment.\n\n## Composition and layout\n\n- `flex=\"row\"` / `flex=\"col\"` enables auto-layout. Use it for content; reserve explicit `x`/`y` or `position=\"absolute\"` for intentional overlays and artwork. Without layout, children share the origin unless positioned.\n- `w` / `h` accept pixels, `\"hug\"` (content-sized), or `\"fill\"` (available space in a supported layout parent). Use Hug for notes, cards, and long pages instead of guessing heights. Fixed viewport sizes and artwork geometry are intentional exceptions.\n- `gap` controls spacing. `p`, `px`, `py`, and `pt`/`pr`/`pb`/`pl` control padding; longhands override shorthands. There is no margin shorthand.\n- `justify=\"start\"|\"end\"|\"center\"|\"between\"|\"around\"` controls the primary axis; `items=\"start\"|\"end\"|\"center\"|\"stretch\"|\"baseline\"` controls the cross axis. `around` gives each child an equal share of the free space, half on each side, on top of `gap`. Distribution needs available space: `between` and `around` cannot create extra room in a Hug container.\n- `grow` distributes available space. Avoid circular Hug/Fill dependencies and redundant fixed widths on growing children. Keep Fill sizing through intermediate containers that should stretch.\n- For wrapping text in a column, prefer `w=\"fill\"`; fixed-width text can use `textAutoResize=\"height\"`. `maxLines` / `truncate` are intentional truncation, not fixes for accidental overflow.\n- `wrap` and `rowGap` enable wrapped flex rows. `grid`, `columns`, and `rows` enable grid (for example `columns=\"1fr 200px 1fr\"` or `columns=\"repeat(7, 1fr)\"`); tracks are `fr`, pixel lengths, `auto`, `repeat()`, and `minmax()`, which grows like its maximum. Grid children use `colStart`, `rowStart`, `colSpan`, and `rowSpan`. The current grid `gap` shorthand takes precedence over `columnGap` and `rowGap`.\n- `flow=\"auto\"|\"ltr\"|\"rtl\"` controls container flow; text `dir` controls writing direction. Preserve these separately.\n- Outside auto-layout, and for `position=\"absolute\"` children, `constraints={{ horizontal, vertical }}` sets how a layer follows its parent's resizing, with Figma's values in lowercase: `\"min\"`, `\"center\"`, `\"max\"`, `\"stretch\"`, or `\"scale\"`. `minW`, `maxW`, `minH`, and `maxH` bound a layer's size. `visible={false}` hides a layer and `locked` locks it.\n- Use measured node bounds and the existing `arrange` tool for independent artboards: `pack` for a page of screens, `spread` when generated layers overlap. Prefer layout constraints to calculating child coordinates; ordinary JavaScript arithmetic is appropriate when real geometry calculations are needed.\n\n## Paint, text, and artwork\n\n- `bg` / `fill`, `stroke`, and text `color` accept colors and supported variable references. Set colors explicitly for predictable contrast. `fills` accepts structured paints; gradient helpers include `linearGradient`, `radialGradient`, `angularGradient`, and `diamondGradient`, each taking an array of stops and optional `{ opacity, transform }`: `fills={[linearGradient([['#3b82f6', 0], ['#8b5cf6', 1]])]}`. Without a `transform` a linear gradient runs left to right and the others are centred; `transform` is Figma's `gradientTransform`, mapping the layer's unit square onto gradient space. Write it as the plugin API's rows, as export does: `linearGradient(stops, { transform: [[0, 1, 0], [-1, 0, 1]] })` runs top to bottom. A paint written as an object takes its `gradientTransform` and `imageTransform` as rows too; the matrix fields `{ m00, m01, m02, m10, m11, m12 }` are accepted as well.\n- `shader(effects, { opacity, visible, blendMode })` fills a layer with a shader from the [`shaders`](https://shaders.com) library: an array of effects such as `bg={shader([{ type: 'Aurora', props: { speed: 2 } }])}`, or a preset as shaders.com exports it, `{ components: [...] }`. The canvas shows the shader's first frame, preview plays it, and files and other formats keep that frame as an image.\n- `shaderSource(code, { uniforms, opacity, visible, blendMode })` fills a layer with shader code written here rather than a preset; `uniforms` gives the values its `@directive` inputs start with, such as `bg={shaderSource(code, { uniforms: { u_color: '#ff0000' } })}`.\n- `stroke` describes one stroke, refined by `strokeWidth`, `strokeAlign` (`\"inside\"`, `\"center\"`, `\"outside\"`), `strokeDash`, `strokeCap`, and `strokeJoin`. `strokes` takes several, as objects with `color`, `weight`, `align`, `dash`, `cap`, `join`, and `visible`; `strokeWeights={{ top, right, bottom, left }}` sets per-side widths. `dashPattern` sets the node's own dash pattern, separate from the per-stroke `strokeDash`.\n- `rounded` and `roundedTL`/`roundedTR`/`roundedBL`/`roundedBR` control corners. `strokeWidth`, `opacity`, `rotate`, and `blendMode` control appearance. `overflow=\"hidden\"` clips content; do not hide accidental text overflow to make a broken layout appear correct.\n- `rotate` turns a layer by degrees, and `flipX` and `flipY` reflect it across its centre before it turns, as the canvas places it. `Star` takes `points` and `innerRadius` (0–1, how deep its points go); `Polygon` takes `points`. `Ellipse` draws an arc or a donut with `startAngle` and `endAngle` in degrees, clockwise from three o'clock (0 to 360 by default), and `innerRadius` (0–1, the hole): `<Ellipse w={80} h={80} startAngle={0} endAngle={270} innerRadius={0.6} />`.\n- `effects` accepts structured effects such as `dropShadow`, `innerShadow`, and `layerBlur`. `shadow` takes a CSS `box-shadow` list, such as `shadow=\"0 4 8 #0002, inset 0 1 0 #fff\"`, and `blur` a layer blur radius; both are convenient shorthands. Effect helpers take `radius`, as Figma's effects do; when a JSX string is rendered, an option a paint or effect helper does not support is reported as a warning.\n- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `fontFeatures` turns OpenType features on or off by tag (`fontFeatures={{ tnum: true, liga: false }}`), `fontVariations` sets variable-font axes by tag (`fontVariations={{ wght: 650 }}`), and `lang` names the text's language (`lang=\"de\"`) for shaping and font fallback. A variable font's optical size follows the font size unless `fontOpticalSizing=\"none\"`, as in CSS; only then does an `opsz` in `fontVariations` apply. `lineHeight=\"auto\"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.\n- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, `fontFeatures`, `fontVariations`, `lang`, and `textCase`; a span's `fontFeatures` and `fontVariations` replace the text's rather than adding to them, and `fontOpticalSizing` is set on the `Text` for all of it. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list=\"ordered\"` or `list=\"unordered\"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.\n- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.\n- Pick artwork by where it comes from. A known icon is an `Icon` by its Iconify name. A shape you draw yourself is a `Vector` with its path in SVG syntax, `<Vector d=\"M11 2L4 11h5l-1 7 7-9h-5z\" bg={designVar(…)} />`: one layer, styled with the same props as any other, so its fills can use variables, stack, and take `strokeAlign` and `effects`. `fillRule=\"evenodd\"` cuts holes. An open path with a `stroke` stays open, a line; with only a `bg` it fills as if closed. Given `w` and `h`, the path is drawn in that box as written, as an icon is in its view box; without them the layer fits the path. `paths` takes several paths as export writes them, each `{ windingRule, data }` with `NONZERO`, `EVENODD`, or `NONE` for an open path: `paths={[{ windingRule: \"EVENODD\", data: \"M0 0L10 0L10 10Z\" }]}`. Inline `<svg>` is for artwork copied from elsewhere: it draws the SVG's shapes, a frame with a layer per shape in the SVG's own colours, and leaves out its text, so do not use it for a shape you will style or bind, nor for text.\n- `Sticky` makes a FigJam sticky note whose text is its body: `<Sticky color=\"yellow\" author=\"Ada\">Ship it</Sticky>`. `color` takes a FigJam palette name (`white`, `gray`, `red`, `orange`, `yellow`, `green`, `teal`, `blue`, `violet`, `pink`) or any colour, `author` signs it (`authorVisible={false}` hides the line), `wide` makes it 416 wide instead of 240, `textSize` is `small`, `medium`, `large`, `extraLarge`, or `huge`, `typeface` is `simple`, `bookish`, `technical`, or `scribbled`, and `scale` scales the whole note. A note sizes itself; it takes no `w`, `h`, fills, or layout props.\n- `Shape` makes a FigJam shape with text whose text is its label: `<Shape kind=\"diamond\" bg=\"#FFC943\">Valid?</Shape>`. `kind` is `square` (default), `ellipse`, `diamond`, `rounded_rectangle`, `parallelogram_right`, `eng_database`, or another FigJam shape, written in lowercase. `w` and `h` are the size it is given (176 by default); it grows taller to fit its label, never wider, so a word too long for it breaks. `truncate` keeps its height and cuts the label off with \"…\" instead, as FigJam does once a shape's height is set. `bg`, `stroke`, `strokeWidth`, `rounded` (6 by default), and `rotate` style it as any layer; the label is centred in the shape and takes the same `textSize` and `typeface` as `Sticky`.\n- `Connector` draws a FigJam connector that follows the layers it joins: `<Connector from=\"Start\" to=\"Done\">Next</Connector>`. `from` and `to` name layers of the same JSX, take a `ref()` a layer is marked with (`const card = ref()`, then `<Frame ref={card}>` and `from={card}`), or give `{ x, y }` points in the connector's parent; `fromSide`/`toSide` (`top`, `right`, `bottom`, `left`) fix the side it attaches by, `line` is `elbowed` (default), `straight`, or `curved`, and `startCap`/`endCap` take the same caps as `strokeCap`: `none`, `round`, `square`, `arrow_lines`, `arrow_equilateral`, `triangle_filled`, `diamond_filled`, or `circle_filled` (it starts with none and ends with `arrow_lines`). Its text is the label; `stroke`, `strokeWidth`, and `dashPattern` style the line. When layers share a name, join them by `ref()`; a name more than one layer has joins the first, with a warning.\n- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.\n\n## Variables and components\n\n- `defineVars('Theme', { Page: '#FFFFFF', Radius: 12 }, { mode: 'Light' })` defines a collection in the file's variables table and returns its variables by name, such as `theme.Page`. Each value is the variable's value in the first mode, named by `mode` (`Mode 1` without one): strings are colors, numbers FLOAT, booleans BOOLEAN, and another collection's variable makes an alias, such as `palette['Gray/900']`. `defineMode(theme, 'Dark', { Page: '#111111' })` adds a mode with the values that differ; the rest keep the first mode's. A render that binds any of the variables creates the collection with all its modes, or updates the one with that name, so running the JSX again changes values instead of adding collections.\n- `designVar('name-or-id')` refers to a variable the document already has; a missing one is an error. When more than one collection has a variable of that name, name the collection too, as `designMode` does: `designVar('Theme', 'Line')`.\n- COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings; the one exception is `lineHeight` and `letterSpacing`, which also take a percent of the font size such as `\"150%\"` that follows the size when it changes.\n- `mode={dark}` shows a layer and its children in a mode, as the Appearance panel's variable mode control does; a list pins several collections, and `designMode('Theme', 'Dark')` names a mode of a collection the document already has, by the collection's ID when several share its name. Without `mode`, a layer inherits its parent's.\n- Variables bind real graph fields, not copied values. Layout resolves scalar variables in the mode the layer is created in, its own or inherited; it does not lay content out again after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.\n- `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.\n- Build repeated or computed content with JavaScript inside `{}` rather than writing each item out: `{days.map((day) => <Text>{day}</Text>)}`, `{Array.from({ length: 35 }, (_, i) => <Frame>…</Frame>)}`, and conditionals. Statements such as `const weeks = …` may come first and then end with `return` and the JSX, as a component's body does: `const weeks = 5` on one line, `return <Frame>…</Frame>` on the next.\n- A reusable JavaScript function shares source code, not component identity. Use `Component`, `ComponentSet`, and `Instance` for editable main components and linked instances.\n- `Instance` resolves an existing component through `of`, `component`, or `componentId`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set.\n- `property(name, defaultValue)` binds a field of a component's layer to a component property, created on first use: `text={property('Message', 'Hi')}` on a `Text` makes a TEXT property, `visible={property('Pinned', true)}` a BOOLEAN one, and `of={property('Icon', 'Star')}` on an `Instance` an INSTANCE_SWAP one whose default is the component `of` names. The property belongs to the nearest `Component`, or to its `ComponentSet` for a variant, so the same name in each variant binds one property; one name with two types or two defaults is an error.\n- An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of=\"Note\" State=\"Done\" Message=\"Updated review\" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Only instances accept `properties`.\n- `exposed` on an `Instance` in a component shows that instance's own properties on the component's instances, as Figma's \"Expose properties from nested instances\" does; the instance's component needs properties to expose. An outer instance gives an exposed instance its variant and properties as an object under the exposed layer's name: `<Instance of=\"Card\" Title=\"Welcome\" Action={{ Variant: 'Secondary', Label: 'Save' }} />`, or `properties={{ Action: { … } }}`.\n- Instance assignments take `true` / `false` or the native `'true'` / `'false'` for BOOLEAN properties, and a component's name or ID for swaps, as `of` does, whether set as a prop or in `properties`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.\n- Reuse existing local or library components before recreating them. Keep meaningful text, visibility, and swap properties exposed rather than hand-editing cloned child nodes.\n- Explicit instance `w` / `h` replace the inherited sizing mode on that axis; omitted dimensions retain the main component's sizing. Authored overrides survive component synchronization. Distinguish those placement constraints from the main component's default size, and verify actual bounds in narrower parents. Do not compensate for a sizing mismatch with guessed heights, clipping, or manually positioned siblings.\n\n## Controls\n\n- A main component can behave as a Reka UI control in preview and code. Write it with Reka's names: `Switch.Root` is the component (a component set when its children are `Component` variants), and each Reka part is the slot that draws it, such as `Switch.Thumb`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Track`, `Progress.Indicator`, `Tabs.List`, `Collapsible.Trigger`, or `NumberField.Increment`. Parts in different variants share one slot.\n- The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, and, for text fields, `filled`, as a variant or boolean property name, or `{ property, on, off }` when the variant values are not named like On and Off. `states` names the variant property that draws default, hover, pressed, focus, and disabled; a slider, progress bar, or number field takes `min`, `max`, `step`, and `defaultValue`.\n- `TextField.Input`, `Textarea.Input`, and `NumberField.Input` are the text layers whose text becomes the field's text property. `Tabs.Trigger` goes in `Tabs.List`; `Tabs.Content` panels may sit directly under `Tabs.Root`, the first showing. A part with children and no `flex`, `display`, `w`, or `h` of its own stacks them in a column that hugs them.\n- A group's item component is written on its own (`RadioGroup.Item`, `ToggleGroup.Item`, `Accordion.Item` with its `Accordion.Trigger` and `Accordion.Content`); the group's root then lists items as `<RadioGroup.Item of={radioId} />`.\n\n```tsx\n<Switch.Root name=\"Switch\" modelValue=\"State\" states=\"Interaction\">\n <Component name=\"State=Off, Interaction=Default\" w={44} h={24} rounded={12} bg=\"#D0D4DA\">\n <Switch.Thumb x={2} y={2} w={20} h={20} rounded={10} bg=\"#FFFFFF\" />\n </Component>\n <Component name=\"State=On, Interaction=Default\" w={44} h={24} rounded={12} bg=\"#3B6CF6\">\n <Switch.Thumb x={22} y={2} w={20} h={20} rounded={10} bg=\"#FFFFFF\" />\n </Component>\n</Switch.Root>\n```\n\n## Verification\n\nInspect structure and actual rendered output. Node counts and `describe` diagnostics do not establish visual fidelity. Check wrapping with longer content, narrower containers, component edits, and relevant modes. Resolve overflow and contrast problems at their source. Reuse IDs returned by creation tools rather than repeatedly searching for the same nodes.\n\nThe examples below are executed by the authoring-reference tests. Create the named variables before running a variable-bound example.\n\n## Content-sized review note\n\n```jsx\n<Frame name=\"Review note\" w={280} h=\"hug\" flex=\"col\" gap={8} p={16} bg=\"#FFFFFF\">\n<Text name=\"Author\" size={12} weight=\"medium\" color=\"#252A31\">June Lee</Text>\n<Text name=\"Message\" w=\"fill\" size={12} color=\"#6B7079\">Give the date a little more room at the bottom.</Text>\n</Frame>\n```\n\n## Variable-bound spacing and typography\n\n```jsx\n<Frame name=\"Bound note\" w={280} h=\"hug\" flex=\"col\" gap={designVar('Space/small')} p={designVar('Space/medium')} bg=\"#FFFFFF\">\n<Text name=\"Message\" w=\"fill\" size={designVar('Type/body')} lineHeight={designVar('Type/body-leading')} letterSpacing={designVar('Type/body-tracking')} color=\"#252A31\">A note that grows with its content.</Text>\n</Frame>\n```\n\n## A theme with two modes\n\n```jsx\nconst theme = defineVars('Theme', { Surface: '#FFFFFF', Ink: '#252A31', Radius: 12 }, { mode: 'Light' })\nconst dark = defineMode(theme, 'Dark', { Surface: '#1A1A20', Ink: '#F5F5F7' })\nreturn <Frame name=\"Dark note\" mode={dark} w={280} h=\"hug\" flex=\"col\" gap={8} p={16} bg={theme.Surface} rounded={theme.Radius}>\n<Text name=\"Message\" w=\"fill\" size={12} color={theme.Ink}>Shown in the Dark mode of the Theme collection.</Text>\n</Frame>\n```\n\n## Component with text and visibility properties\n\n```jsx\n<Component name=\"Comment\" w={280} h=\"hug\" flex=\"col\" gap={8} p={16} bg=\"#FFFFFF\">\n<Text name=\"Author\" size={12} weight=\"medium\" color=\"#252A31\" text={property('Author', 'June Lee')} />\n<Text name=\"Message\" w=\"fill\" size={12} color=\"#6B7079\" text={property('Message', 'Give the date more room.')} visible={property('Show message', true)} />\n</Component>\n```\n\n## Rich text with spans and lists\n\n```jsx\n<Frame name=\"Release notes\" w={280} h=\"hug\" flex=\"col\" gap={8} p={16} bg=\"#FFFFFF\">\n<Text name=\"Notes\" w=\"fill\" size={12} color=\"#252A31\" paragraphSpacing={4}>\n <Paragraph spacing={8}>Version 2 is <Span weight=\"bold\" color=\"#3B6CF6\" textDecoration=\"underline\" textDecorationStyle=\"wavy\" textUnderlineOffset={2}>out now</Span>.</Paragraph>\n <Paragraph list=\"unordered\">Faster export</Paragraph>\n <Paragraph list=\"unordered\" level={2}>PDF and SVG</Paragraph>\n <Paragraph list=\"ordered\">Fewer clicks</Paragraph>\n</Text>\n</Frame>\n```\n\n## Supported syntax inventory\n\nGenerated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.\n\n**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Sticky`, `Shape`, `Connector`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.\n\n**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `shaderSource`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `defineVars`, `defineMode`, `designVar`, `designMode`, `property`, `ref`.\n\n**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `flipX`, `flipY`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `fontFeatures`, `fontVariations`, `lang`, `fontOpticalSizing`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `startAngle`, `endAngle`, `d`, `fillRule`, `paths`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `mode`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.";
|
|
1813
1813
|
//#endregion
|
|
1814
1814
|
//#region ../../skills/pairdraw/SKILL.md?raw
|
|
1815
|
-
var SKILL_default = "---\nname: pairdraw\ndescription: Work with Figma .fig design files and the running Pairdraw editor — inspect structure, query nodes, analyze design tokens, export PNG/SVG/PDF/JSX, and modify designs programmatically. Use when asked to open, inspect, export, analyze, or edit .fig files, or to control the running Pairdraw app.\n---\n\n# Pairdraw\n\nPairdraw provides a CLI and MCP server for `.fig` design files and the running Pairdraw editor.\n\nUse two modes:\n\n- **App mode** — connect to the running Pairdraw editor by omitting the file argument.\n- **Headless mode** — work with `.fig` files directly by passing a file path.\n\n```bash\n# App mode — operates on the document open in the editor\npairdraw tree\n\n# Headless mode — operates on a .fig file\npairdraw tree design.fig\n```\n\nUse `pairdraw --help`, per-command help, and the connected MCP server’s tool schemas to check the installed version’s capabilities. See the [CLI reference](https://github.com/BadryansahBangsawan/pairdraw/blob/master/packages/docs/reference/cli.md) and [MCP guide](https://github.com/BadryansahBangsawan/pairdraw/blob/master/packages/docs/programmable/mcp-server.md) for current documentation.\n\n## Variable formulas\n\nInside `eval`, use `pairdraw.setVariableFormula('Spacing', 'large', '{base} * 2')` for numeric formulas or `pairdraw.setVariableFormula('State', 'visible', '{viewport} > 1024 and not {loading}')` for Boolean formulas, which use `and`, `or`, `not` and number comparisons. Collections and variables must already exist. An optional fourth argument selects a mode by name; otherwise the default mode is edited. The call validates before mutation and returns the resolved value. Length formulas use stored pixels. The CSS stylesheet writes number formulas as `calc()`; design-token files hold the result with the formula in `$extensions`.\n\nVariables follow Figma's plugin API: `figma.variables.getLocalVariables()`, `createVariable(name, collection, type)`, `variable.setValueForMode(modeId, value)`, and `node.setBoundVariable(field, variable)` with Figma's field names (`characters`, `width`, `paddingLeft`) and types; paint colours bind through `figma.variables.setBoundVariableForPaint`. To bind as the layer panel does, use `pairdraw.bindVariable(node, field, variable)` and `pairdraw.unbindVariable(node, field)` with Pairdraw names (`text`, `visible`, `opacity`, `fills/0/color`): text content takes a text or number variable, shown as text; visibility a boolean or text one. `pairdraw` also sets layout and text direction (`setLayoutDirection`, `setTextDirection`), OkHCL paint colors (`setFillOkHCL`, `setStrokeOkHCL`), exposes instance swaps (`exposeInstanceSwap`), and reports font availability (`getFontStatus()`); booleans and flattening are Figma's `figma.union`, `subtract`, `intersect`, `exclude` and `figma.flatten`.\n\n## Requirements\n\n```bash\n# CLI\nbun add -g @pairdraw/cli\n\n# MCP server used by the desktop app and external MCP clients\nbun add -g @pairdraw/mcp\n```\n\nThe desktop app starts `pairdraw-mcp-http` automatically in production Tauri builds when `@pairdraw/mcp` is installed globally and exposes automation on:\n\n- HTTP/RPC: `http://127.0.0.1:7600`\n- WebSocket bridge: `ws://127.0.0.1:7601`\n- MCP Streamable HTTP: `http://127.0.0.1:7600/mcp`\n\n## CLI Commands\n\n```bash\npairdraw --help\n```\n\nCommon commands:\n\n- `info` — document overview: pages, node counts, fonts\n- `tree` — print hierarchy with types and sizes\n- `pages` — list pages\n- `node` — detailed node properties by ID\n- `selection` — current selection from the running app\n- `find` — find nodes by name/type\n- `query` — XPath selectors for node search\n- `variables` — list variables and collections\n- `tokens` — variables as a CSS custom-property stylesheet, a Tailwind v4 theme, or W3C design token files (`--format dtcg --out <folder>`)\n- `export` — export PNG/JPG/WEBP/SVG/PDF/JSX/.fig\n- `convert` — convert between supported document formats\n- `analyze` — colors, typography, spacing, repeated clusters\n- `lint` — consistency, structure, and accessibility checks\n- `formats` — supported document/export formats\n- `eval` — execute JavaScript with the Figma Plugin API\n- `tool` — list, describe, and call any MCP tool from the shell, in app or headless mode\n- `documents` — list, open, create, save, close, and activate documents in the running app\n- `undo` / `redo` — step back through your own (automation) changes in the running app\n- `settings` — read and change editor settings in the running app\n\n### Inspect\n\n```bash\npairdraw info design.fig\npairdraw tree design.fig\npairdraw tree --page \"Components\" --depth 3 # app mode\npairdraw pages design.fig\npairdraw node design.fig --id 1:23\npairdraw node --id 1:23 # app mode\npairdraw selection --json\npairdraw variables design.fig\npairdraw variables --collection \"Colors\" --type COLOR\npairdraw tokens design.fig --format tailwind > theme.css\npairdraw tokens design.fig --format dtcg --out tokens # W3C design tokens; import_design_tokens reads them back\n```\n\n### Search and XPath query\n\n```bash\npairdraw find design.fig --name \"Button\"\npairdraw find --type FRAME # app mode\npairdraw find design.fig --type TEXT --page \"Home\"\npairdraw find design.fig --name \"Card\" --type COMPONENT --limit 50\n\npairdraw query design.fig \"//FRAME\"\npairdraw query design.fig \"//FRAME[@width < 300]\"\npairdraw query design.fig \"//TEXT[contains(@name, 'Button')]\"\npairdraw query design.fig \"//COMPONENT[@stackMode]\"\npairdraw query design.fig \"//COMPONENT//FRAME//TEXT\"\npairdraw query \"//FRAME[@width > 1000]\" # app mode\n```\n\nCommon node types: `FRAME`, `TEXT`, `RECTANGLE`, `ELLIPSE`, `VECTOR`, `GROUP`, `COMPONENT`, `COMPONENT_SET`, `INSTANCE`, `SECTION`, `LINE`, `STAR`, `POLYGON`, `SLICE`, `BOOLEAN_OPERATION`.\n\n### Export and convert\n\n```bash\npairdraw export design.fig -o hero.png\npairdraw export -o hero.png # app mode\npairdraw export design.fig --node 1:23 -s 2 -o button@2x.png\npairdraw export design.fig -f jpg -q 85 -o preview.jpg\npairdraw export design.fig -f svg --node 1:23 -o icon.svg\npairdraw export design.fig -f pdf -o page.pdf\npairdraw export design.fig -f fig -o roundtrip.fig\npairdraw export design.fig -f jsx -o component.jsx\npairdraw export design.fig -f jsx --style tailwind -o component.tsx\npairdraw export design.pen -f storybook -o src/stories --watch # stories + design images per component, re-exported on save\npairdraw export 'src/**/*.pen' -f storybook --beside # stories next to each design file\npairdraw export design.fig --thumbnail --width 1920 --height 1080\npairdraw export --page \"Components\" -o components.png\n\npairdraw convert design.fig -o design.pen\npairdraw formats\n```\n\n### Analyze and lint\n\n```bash\npairdraw analyze colors design.fig\npairdraw analyze colors --similar --threshold 10 # app mode\npairdraw analyze typography design.fig --group-by size\npairdraw analyze spacing design.fig --grid 8\npairdraw analyze clusters design.fig --min-count 3\npairdraw lint design.fig\npairdraw lint design.fig --json\npairdraw lint design.fig --fix -o fixed.fig # bind matching color variables, round to whole pixels\n```\n\nIn MCP and AI chat, `lint` lists findings with their `fix` and `suggestions`; `lint_fix` applies the safe fixes, and the first suggestion of each finding with `suggestions: true`.\n\n### Eval (Figma Plugin API)\n\nExecute JavaScript against the document using a Figma Plugin API-compatible runtime:\n\n```bash\npairdraw eval design.fig -c 'figma.currentPage.findAll(n => n.type === \"TEXT\").length'\n\n# App mode — modifies the live document in the editor\npairdraw eval -c '\n const buttons = figma.currentPage.findAll(n => n.name === \"Button\");\n buttons.forEach(b => { b.cornerRadius = 8 });\n buttons.length + \" buttons updated\"\n'\n\n# Modify and save to the same file; text edits need the text's fonts loaded first, as in Figma\npairdraw eval design.fig -w -c '\n const texts = figma.currentPage.findAll(n => n.type === \"TEXT\" && n.characters.length > 0);\n const fonts = texts.flatMap(t => t.getRangeAllFontNames(0, t.characters.length));\n await Promise.all(fonts.map(font => figma.loadFontAsync(font)));\n texts.forEach(t => { t.fontSize = 16 });\n'\n\n# Save to a different file\npairdraw eval design.fig -o modified.fig -c '...'\n\n# Read code from stdin\necho 'figma.currentPage.children.map(n => n.name)' | pairdraw eval design.fig --stdin\n\n# Style part of a text, and read how it is styled\npairdraw eval design.fig -w -c '\n const title = figma.currentPage.findOne(n => n.type === \"TEXT\" && n.name === \"Title\");\n const fonts = [...title.getRangeAllFontNames(0, title.characters.length), { family: \"Inter\", style: \"Bold\" }];\n await Promise.all(fonts.map(font => figma.loadFontAsync(font)));\n title.setRangeFontName(0, 5, { family: \"Inter\", style: \"Bold\" });\n title.setRangeFills(0, 5, [{ type: \"SOLID\", color: { r: 0.9, g: 0.1, b: 0.1 } }]);\n title.getStyledTextSegments([\"fontName\", \"fills\"]).map(s => [s.characters, s.fontName.style])\n'\n```\n\nText edits follow Figma's font rule: anything that lays text out again (`characters`, `fontSize`, `fontName`, spacing, case, alignment, auto-resize, and the matching `setRange…` methods) throws `Cannot write to node with unloaded font` until `figma.loadFontAsync` has loaded every font the text uses, and a new font has to be loaded before it is set. A font that is not available rejects `loadFontAsync`; replace it with `fontName = { family, style }` in a loaded font. The built-in text tools load fonts themselves.\n\nText styles follow Figma's per-character model: `getStyledTextSegments(fields)` reads runs, `getRange…`/`setRange…` read and set font, size, fills, letter spacing, line height, decorations, text case, hyperlinks, text and fill style IDs, and bound variables for `[start, end)`, and a text's `fontSize`, `fontName`, `fills`, and similar read `figma.mixed` while characters differ. Check for it before using the value. Paints everywhere take Figma's shape: a solid `color` is `{ r, g, b }` with the alpha in `opacity`, and an image is `{ type: \"IMAGE\", imageHash, scaleMode: \"FILL\" | \"FIT\" | \"CROP\" | \"TILE\" }` with optional `rotation` and `scalingFactor`.\n\nNext to `figma`, scripts get `pairdraw`: what Pairdraw adds to the Figma API, in its style. A main component can behave as a Reka UI control, by its own property and slot names:\n\n```bash\npairdraw eval design.fig -w -c '\n const set = figma.currentPage.findOne(n => n.type === \"COMPONENT_SET\" && n.name === \"Switch\");\n const thumb = set.findOne(n => n.name === \"Thumb\");\n const behaviour = pairdraw.setBehaviour(set, \"switch\")\n .bindValue(\"value\", \"State\") // On/Off guessed from the variant values\n .bindPart(\"thumb\", thumb); // the frame becomes a slot\n behaviour.states = \"Interaction\";\n behaviour.missing // [] when the control is complete\n'\n```\n\n`pairdraw.behaviourKinds` lists every kind with its values and parts; `pairdraw.getBehaviour(node)` reads one (a variant reads its set's); `pairdraw.createSlot(frame)` makes a frame a slot. The `set_behaviour`, `get_behaviour`, and `create_slot` tools do the same over MCP, and design JSX writes controls with Reka's element names (`Switch.Root`, `Switch.Thumb`).\n\nComments people leave on the canvas are review feedback you can act on. Read the open ones, change the design, then answer and resolve each, naming yourself as the author:\n\n```bash\npairdraw eval design.fig -w -c '\n pairdraw.getComments({ resolved: false }).map(c => ({ id: c.id, text: c.text, layer: c.node?.name }))\n'\n# after the change:\npairdraw eval design.fig -w -c 'pairdraw.getComment(\"c_…\").reply(\"Title is 24px now\", { author: \"Claude\" }).resolve()'\n```\n\n`pairdraw.addComment(text, { node, page, x, y, author })` leaves a new one. Over MCP the same is `get_comments`, `add_comment`, `reply_to_comment`, and `resolve_comment`. Comment text is Markdown.\n\nStatuses say where a section, frame, component, or instance stands, from the document's own list. Read the list, find what is ready, and move a layer on once your work on it is done:\n\n```bash\npairdraw eval design.fig -c 'pairdraw.statuses.map(s => s.name)'\npairdraw eval design.fig -w -c 'pairdraw.setStatus(figma.currentPage.findOne(n => n.name === \"Checkout\"), \"In review\")'\n```\n\n`pairdraw.getStatus(node)` reads one. Over MCP the same is `get_statuses` and `set_status`.\n\n### Diff\n\nCompare nodes and documents, and apply patches:\n\n```bash\npairdraw diff create design.fig --from 1:23 --to 1:87 # JSX attribute patch\npairdraw diff jsx design.fig --from 1:23 --to 1:87 # JSX structure\npairdraw diff show 1:24 design.fig --attributes 'rounded={8}' > fix.diff\npairdraw diff apply fix.diff design.fig --dry-run # fails on stale values\npairdraw diff apply fix.diff design.fig --write\npairdraw diff visual design.fig --from 1:23 --to 1:87 -o diff.png\npairdraw diff files before.fig after.fig # exit 1 when different\n```\n\n### Control the running app\n\n```bash\npairdraw documents list --json # tab IDs, paths, pages\npairdraw documents open designs/landing.fig # new tab; --json returns target.documentId\npairdraw documents new --path designs/draft.fig\npairdraw documents activate tab-123 --page-id 0:4 # bring a tab to the front\npairdraw documents save --document-id tab-123\npairdraw documents close --document-id tab-123 --save # or --discard; fails on unsaved changes otherwise\npairdraw undo --document-id tab-123 # also: redo\npairdraw settings get --json\npairdraw settings set editing.snapping.pixelGrid false\n```\n\n`tool` exposes every MCP tool, so the CLI is never limited to its dedicated commands:\n\n```bash\npairdraw tool list\npairdraw tool describe set_fill # JSON Schema for the arguments\npairdraw tool call set_fill --document-id tab-123 --args '{\"id\":\"0:5\",\"color\":\"#2563eb\"}'\npairdraw tool call create_page design.fig --args '{\"name\":\"Icons\"}' --write # headless\npairdraw tool call create_shape design.fig --args '{\"type\":\"FRAME\",\"x\":0,\"y\":0,\"width\":320,\"height\":200}' -w --preview-output preview.png\nprintf '%s\\n' 'create_page {\"name\":\"Icons\"}' 'save()' | pairdraw shell design.fig # one load, many tool lines\npairdraw models --json # AI providers and their models\n```\n\nEvery command that reports structured data supports `--json` when appropriate.\n\n## MCP Server\n\n### Stdio MCP clients\n\nUse Bun by default:\n\n```json\n{\n \"mcpServers\": {\n \"pairdraw\": {\n \"command\": \"bunx\",\n \"args\": [\"pairdraw-mcp\"]\n }\n }\n}\n```\n\nIf `@pairdraw/mcp` is installed globally, direct binaries also work:\n\n```json\n{\n \"mcpServers\": {\n \"pairdraw\": {\n \"command\": \"pairdraw-mcp\"\n }\n }\n}\n```\n\n### HTTP / Streamable HTTP\n\n```bash\nexport PORT=7600\nexport PAIRDRAW_MCP_ROOT=/path/to/files # explicitly limit filesystem access\n\npairdraw-mcp-http\n# or: bunx pairdraw-mcp-http\n```\n\nAuthentication is enabled by default with an automatically generated token. `PAIRDRAW_MCP_AUTH_TOKEN` can supply an explicit non-empty token; an empty value disables authentication. If browser access needs CORS, set `PAIRDRAW_MCP_CORS_ORIGIN` to a trusted origin. Never combine wildcard CORS (`*`) with disabled authentication.\n\nThe CLI defaults the filesystem root to the home directory on Windows and the current working directory elsewhere. Set `PAIRDRAW_MCP_ROOT` to an explicit narrow directory rather than relying on that default.\n\n### MCP workflow\n\n1. **Find or open a document** — `list_documents` for open tabs and their IDs; `open_file { path }` within the effective filesystem root (`list_recent_files` lists recently opened files there), or `new_document {}`. Pass `document_id` and `page_id` explicitly instead of relying on the active tab; `activate_document { document_id }` brings a tab to the front when the user should see it.\n2. **Query** — `get_page_tree`, `find_nodes`, `query_nodes`, `get_node`, `list_pages`, `get_current_page`.\n3. **Inspect** — `get_jsx`, `diff_jsx`, `diff_create`, `diff_visual`, `describe`, `export_image`, `export_svg`, `export_pdf`.\n4. **Modify** — `render`, `batch_update`, `update_node`, `set_fill`, `set_layout`, `create_shape`, `import_svg`, etc. For a flowchart, write it as Mermaid and call `import_mermaid { mermaid }`: it lays out FigJam shapes, sections, and connectors without overlaps and returns each node's layer id, instead of placing shapes and connectors by hand. When layers you created overlap, call `arrange { ids }`: it spreads them apart and keeps each near where it was. `arrange` also packs screens (`mode: \"pack\"`) and lays shapes out along the connectors joining them (`mode: \"flow\"` for flows, `\"tree\"` for hierarchies, `\"radial\"` for mind maps, `\"network\"` for relationship maps).\n5. **Save/export** — `save_file`, `export_image`, `export_svg`, `export_pdf`, or CLI `export`.\n6. **Close** — `close_file { document_id, unsaved }` closes a document tab after the workflow. With unsaved changes it fails unless `unsaved` is `\"save\"` or `\"discard\"`; automation never prompts in the app.\n\nUse `undo` / `redo { document_id }` to step back your own changes. They refuse when the newest step was made by the user in the editor; never work around that. `get_settings` and `update_settings { settings }` read and change editor preferences such as theme, language, and snapping; they never expose credentials, models, or tool access.\n\n### Browser-native WebMCP (experimental)\n\nWebMCP is off by default. In **Settings → MCP → WebMCP**, choose **Inspect** for read-only tools or **Edit** for scoped changes. These controls are independent of local MCP settings. Supporting browsers expose inspection and undoable existing-layer/property and variable edits directly from the Pairdraw workspace through `document.modelContext`, without an MCP server connection. Discover this browser surface separately: it excludes structural creation/deletion, arbitrary JS/JSX execution, external assets, filesystem operations, and credentials.\n\nCalls capture the active document/page. Cancellation prevents an edit from starting but does not reverse an already committed edit; use editor undo instead. Atomic edits require at most 10,000 nodes and variables combined, including when these same tools run through app AI/MCP. See the [WebMCP guide](https://github.com/BadryansahBangsawan/pairdraw/blob/master/packages/docs/programmable/mcp-server.md#browser-native-webmcp-experimental-webmcp) for scope and browser requirements.\n\n## Tool discovery\n\nUsers configure local server tools in **Settings → Tool access** → **Local MCP**, independently from **Built-in AI** tool preferences. Local MCP changes require a server restart and stdio client reconnection; built-in AI changes apply to the next message. ACP and Pi agents use the MCP surface, not the direct-model AI tool selection. Tool switches are not a sandbox: enabled scripting tools can still perform operations whose dedicated tools are disabled.\n\nDiscover available tools and their arguments from the connected server or browser; availability varies by version and mode. Each tool's schema and execution/exposure metadata are authoritative. Numeric inputs accept numbers or numeric strings consistently, but reject non-finite values. Do not rely on a fixed tool count or a copied inventory.\n\n> Tool availability can depend on server mode. `open_file`, `save_file`, and disk-writing export paths are scoped to the effective filesystem root; set it explicitly with `PAIRDRAW_MCP_ROOT`.\n\n## Key tools for agents\n\n- **`query_nodes`** — XPath selectors to find specific nodes without fetching the full tree.\n- **`get_jsx`** — inspect any node as JSX in the same format accepted by `render`.\n- **`diff_jsx` / `diff_create`** — compare two nodes as a JSX line diff or as an appliable patch of JSX attributes; `diff_show` previews setting attributes and `diff_apply` applies a patch only if the nodes still match it.\n- **`diff_visual`** — pixel diff between two rendered nodes; use it to confirm an edit changed only the intended region.\n- **`describe`** — semantic analysis of role, visual style, layout, and design issues.\n- **`batch_update`** — apply multiple node updates efficiently.\n- **`export_image` / `export_svg` / `export_pdf`** — visual verification and deliverables; `export_image` takes `quality` (1–100) for JPG and WEBP.\n- **`export_html` / `import_html`** — layers to HTML with CSS or Tailwind (fragment or standalone, `layer_ids` to map markup back to layers), and HTML/CSS back into editable layers in the open document.\n- **`diff_changes`** — outside AI chat, call it with `mark: true`, then later without it to see what you or the designer changed since.\n- **`find_empty_space`** — a free spot of a given size beside existing content, before placing new frames.\n- **`replace_matching_properties`** — swap a fill, text, or stroke color, stroke weight, radius, font family, style, or size everywhere on a page or selection; layers of read-only library components come back in `read_only`.\n- **`get_style`** — curated style directions for a design with no look yet, or when asked for a style or mood: call it with a `query` describing the request to list matches, then with an `id` for that direction's palette by role, font pairing, type scale, radii, spacing, elevation, and written guidance. Adapt it; do not copy it verbatim.\n- **`rescale`** — scale layers with their text sizes, stroke weights, radii, effects, and spacing, as the Scale tool (K) does, around an `anchor` of their joint bounds; locked layers and layers inside instances come back in `skipped`; `node_resize` changes only the box.\n- **`set_text_properties` / `set_font_range` `hyperlink`** — link a whole text or a range to an http, https, or mailto address (`example.com` becomes `https://example.com`); `null` or `\"\"` removes it. Links are not underlined automatically.\n- **`generate_image` / `remove_background` / `replace_background` / `generate_svg`** — image AI on the user's own image service keys (Settings → Image services); they work only through the running app, take a while, cost the user money, and report a missing key for the user to add. Call them only when asked; `generate_svg` imports editable vector layers.\n- **`vectorize_image`** — turn a layer's image fill into editable vector paths in a new frame beside the image, with the user's own vectorize service; it works only through the running app, takes up to a few minutes, and reports a missing key for the user to add in Settings → Image services.\n- **`viewport_zoom_to_fit` / `viewport_set` / `viewport_get`** — move the user's view only when they ask to be shown something.\n- **`get_codegen_prompt`** — retrieve Pairdraw's current JSX/codegen guidance.\n- **`read_skill`** — read this skill (`SKILL.md`) or `references/design-authoring.md` from the connected server, for clients that cannot install skills; the same files are the `pairdraw://skills/pairdraw/` resources and the `design` prompt.\n- **`undo` / `redo`** — revert or reapply your newest change; they refuse to touch the user's edits.\n- **`list_documents` / `activate_document`** — discover open tabs and show the one you worked on.\n\n## JSX Rendering\n\nRead [Design authoring](references/design-authoring.md) before creating or modifying JSX designs. This bundled reference is generated from Core's authoring guidance, tested examples, and renderer metadata—the same reference used by chat and codegen prompts.\n\nUse the `render` tool for JSX strings. Use only the APIs exposed by the installed `eval` environment; native library exports are not automatically scripting globals. The connected server's `get_codegen_prompt` provides its version's codegen and authoring guidance.\n\n## Tips\n\n- Omit the file path to work with the document open in the running Pairdraw editor.\n- Start with `info` or `get_page_tree` to understand the document.\n- Use `tree --depth 2` or `query_nodes` to avoid overwhelming output on large files.\n- Export specific nodes with `--node` for faster visual checks.\n- Use `export_image` after changes to verify visual quality.\n- The running editor shows each MCP session as an agent at the layers its tools touch, and follows it while it works when the user has Follow agents on. Leave the user's selection and view alone unless they ask to be shown something.\n- Use `analyze colors --similar` to find near-duplicate colors.\n- Use `pairdraw tool call` for MCP tools without a dedicated CLI command, and `eval` for Figma Plugin API operations not covered by any tool.\n- Use `--json` when piping CLI output to scripts.\n- In app mode, `eval` and MCP modifications are reflected live in the editor.\n";
|
|
1815
|
+
var SKILL_default = "---\nname: pairdraw\ndescription: Work with Figma .fig design files and the running Pairdraw editor — inspect structure, query nodes, analyze design tokens, export PNG/SVG/PDF/JSX, and modify designs programmatically. Use when asked to open, inspect, export, analyze, or edit .fig files, or to control the running Pairdraw app.\n---\n\n# Pairdraw\n\nPairdraw provides a CLI and MCP server for `.fig` design files and the running Pairdraw editor.\n\nUse two modes:\n\n- **App mode** — connect to the running Pairdraw editor by omitting the file argument.\n- **Headless mode** — work with `.fig` files directly by passing a file path.\n\n```bash\n# App mode — operates on the document open in the editor\npairdraw tree\n\n# Headless mode — operates on a .fig file\npairdraw tree design.fig\n```\n\nUse `pairdraw --help`, per-command help, and the connected MCP server’s tool schemas to check the installed version’s capabilities. See the [CLI reference](https://github.com/BadryansahBangsawan/pairdraw/blob/main/packages/docs/reference/cli.md) and [MCP guide](https://github.com/BadryansahBangsawan/pairdraw/blob/main/packages/docs/programmable/mcp-server.md) for current documentation.\n\n## Variable formulas\n\nInside `eval`, use `pairdraw.setVariableFormula('Spacing', 'large', '{base} * 2')` for numeric formulas or `pairdraw.setVariableFormula('State', 'visible', '{viewport} > 1024 and not {loading}')` for Boolean formulas, which use `and`, `or`, `not` and number comparisons. Collections and variables must already exist. An optional fourth argument selects a mode by name; otherwise the default mode is edited. The call validates before mutation and returns the resolved value. Length formulas use stored pixels. The CSS stylesheet writes number formulas as `calc()`; design-token files hold the result with the formula in `$extensions`.\n\nVariables follow Figma's plugin API: `figma.variables.getLocalVariables()`, `createVariable(name, collection, type)`, `variable.setValueForMode(modeId, value)`, and `node.setBoundVariable(field, variable)` with Figma's field names (`characters`, `width`, `paddingLeft`) and types; paint colours bind through `figma.variables.setBoundVariableForPaint`. To bind as the layer panel does, use `pairdraw.bindVariable(node, field, variable)` and `pairdraw.unbindVariable(node, field)` with Pairdraw names (`text`, `visible`, `opacity`, `fills/0/color`): text content takes a text or number variable, shown as text; visibility a boolean or text one. `pairdraw` also sets layout and text direction (`setLayoutDirection`, `setTextDirection`), OkHCL paint colors (`setFillOkHCL`, `setStrokeOkHCL`), exposes instance swaps (`exposeInstanceSwap`), and reports font availability (`getFontStatus()`); booleans and flattening are Figma's `figma.union`, `subtract`, `intersect`, `exclude` and `figma.flatten`.\n\n## Requirements\n\n```bash\n# CLI\nbun add -g @pairdraw/cli\n\n# MCP server used by the desktop app and external MCP clients\nbun add -g @pairdraw/mcp\n```\n\nThe desktop app starts `pairdraw-mcp-http` automatically in production Tauri builds when `@pairdraw/mcp` is installed globally and exposes automation on:\n\n- HTTP/RPC: `http://127.0.0.1:7600`\n- WebSocket bridge: `ws://127.0.0.1:7601`\n- MCP Streamable HTTP: `http://127.0.0.1:7600/mcp`\n\n## CLI Commands\n\n```bash\npairdraw --help\n```\n\nCommon commands:\n\n- `info` — document overview: pages, node counts, fonts\n- `tree` — print hierarchy with types and sizes\n- `pages` — list pages\n- `node` — detailed node properties by ID\n- `selection` — current selection from the running app\n- `find` — find nodes by name/type\n- `query` — XPath selectors for node search\n- `variables` — list variables and collections\n- `tokens` — variables as a CSS custom-property stylesheet, a Tailwind v4 theme, or W3C design token files (`--format dtcg --out <folder>`)\n- `export` — export PNG/JPG/WEBP/SVG/PDF/JSX/.fig\n- `convert` — convert between supported document formats\n- `analyze` — colors, typography, spacing, repeated clusters\n- `lint` — consistency, structure, and accessibility checks\n- `formats` — supported document/export formats\n- `eval` — execute JavaScript with the Figma Plugin API\n- `tool` — list, describe, and call any MCP tool from the shell, in app or headless mode\n- `documents` — list, open, create, save, close, and activate documents in the running app\n- `undo` / `redo` — step back through your own (automation) changes in the running app\n- `settings` — read and change editor settings in the running app\n\n### Inspect\n\n```bash\npairdraw info design.fig\npairdraw tree design.fig\npairdraw tree --page \"Components\" --depth 3 # app mode\npairdraw pages design.fig\npairdraw node design.fig --id 1:23\npairdraw node --id 1:23 # app mode\npairdraw selection --json\npairdraw variables design.fig\npairdraw variables --collection \"Colors\" --type COLOR\npairdraw tokens design.fig --format tailwind > theme.css\npairdraw tokens design.fig --format dtcg --out tokens # W3C design tokens; import_design_tokens reads them back\n```\n\n### Search and XPath query\n\n```bash\npairdraw find design.fig --name \"Button\"\npairdraw find --type FRAME # app mode\npairdraw find design.fig --type TEXT --page \"Home\"\npairdraw find design.fig --name \"Card\" --type COMPONENT --limit 50\n\npairdraw query design.fig \"//FRAME\"\npairdraw query design.fig \"//FRAME[@width < 300]\"\npairdraw query design.fig \"//TEXT[contains(@name, 'Button')]\"\npairdraw query design.fig \"//COMPONENT[@stackMode]\"\npairdraw query design.fig \"//COMPONENT//FRAME//TEXT\"\npairdraw query \"//FRAME[@width > 1000]\" # app mode\n```\n\nCommon node types: `FRAME`, `TEXT`, `RECTANGLE`, `ELLIPSE`, `VECTOR`, `GROUP`, `COMPONENT`, `COMPONENT_SET`, `INSTANCE`, `SECTION`, `LINE`, `STAR`, `POLYGON`, `SLICE`, `BOOLEAN_OPERATION`.\n\n### Export and convert\n\n```bash\npairdraw export design.fig -o hero.png\npairdraw export -o hero.png # app mode\npairdraw export design.fig --node 1:23 -s 2 -o button@2x.png\npairdraw export design.fig -f jpg -q 85 -o preview.jpg\npairdraw export design.fig -f svg --node 1:23 -o icon.svg\npairdraw export design.fig -f pdf -o page.pdf\npairdraw export design.fig -f fig -o roundtrip.fig\npairdraw export design.fig -f jsx -o component.jsx\npairdraw export design.fig -f jsx --style tailwind -o component.tsx\npairdraw export design.pen -f storybook -o src/stories --watch # stories + design images per component, re-exported on save\npairdraw export 'src/**/*.pen' -f storybook --beside # stories next to each design file\npairdraw export design.fig --thumbnail --width 1920 --height 1080\npairdraw export --page \"Components\" -o components.png\n\npairdraw convert design.fig -o design.pen\npairdraw formats\n```\n\n### Analyze and lint\n\n```bash\npairdraw analyze colors design.fig\npairdraw analyze colors --similar --threshold 10 # app mode\npairdraw analyze typography design.fig --group-by size\npairdraw analyze spacing design.fig --grid 8\npairdraw analyze clusters design.fig --min-count 3\npairdraw lint design.fig\npairdraw lint design.fig --json\npairdraw lint design.fig --fix -o fixed.fig # bind matching color variables, round to whole pixels\n```\n\nIn MCP and AI chat, `lint` lists findings with their `fix` and `suggestions`; `lint_fix` applies the safe fixes, and the first suggestion of each finding with `suggestions: true`.\n\n### Eval (Figma Plugin API)\n\nExecute JavaScript against the document using a Figma Plugin API-compatible runtime:\n\n```bash\npairdraw eval design.fig -c 'figma.currentPage.findAll(n => n.type === \"TEXT\").length'\n\n# App mode — modifies the live document in the editor\npairdraw eval -c '\n const buttons = figma.currentPage.findAll(n => n.name === \"Button\");\n buttons.forEach(b => { b.cornerRadius = 8 });\n buttons.length + \" buttons updated\"\n'\n\n# Modify and save to the same file; text edits need the text's fonts loaded first, as in Figma\npairdraw eval design.fig -w -c '\n const texts = figma.currentPage.findAll(n => n.type === \"TEXT\" && n.characters.length > 0);\n const fonts = texts.flatMap(t => t.getRangeAllFontNames(0, t.characters.length));\n await Promise.all(fonts.map(font => figma.loadFontAsync(font)));\n texts.forEach(t => { t.fontSize = 16 });\n'\n\n# Save to a different file\npairdraw eval design.fig -o modified.fig -c '...'\n\n# Read code from stdin\necho 'figma.currentPage.children.map(n => n.name)' | pairdraw eval design.fig --stdin\n\n# Style part of a text, and read how it is styled\npairdraw eval design.fig -w -c '\n const title = figma.currentPage.findOne(n => n.type === \"TEXT\" && n.name === \"Title\");\n const fonts = [...title.getRangeAllFontNames(0, title.characters.length), { family: \"Inter\", style: \"Bold\" }];\n await Promise.all(fonts.map(font => figma.loadFontAsync(font)));\n title.setRangeFontName(0, 5, { family: \"Inter\", style: \"Bold\" });\n title.setRangeFills(0, 5, [{ type: \"SOLID\", color: { r: 0.9, g: 0.1, b: 0.1 } }]);\n title.getStyledTextSegments([\"fontName\", \"fills\"]).map(s => [s.characters, s.fontName.style])\n'\n```\n\nText edits follow Figma's font rule: anything that lays text out again (`characters`, `fontSize`, `fontName`, spacing, case, alignment, auto-resize, and the matching `setRange…` methods) throws `Cannot write to node with unloaded font` until `figma.loadFontAsync` has loaded every font the text uses, and a new font has to be loaded before it is set. A font that is not available rejects `loadFontAsync`; replace it with `fontName = { family, style }` in a loaded font. The built-in text tools load fonts themselves.\n\nText styles follow Figma's per-character model: `getStyledTextSegments(fields)` reads runs, `getRange…`/`setRange…` read and set font, size, fills, letter spacing, line height, decorations, text case, hyperlinks, text and fill style IDs, and bound variables for `[start, end)`, and a text's `fontSize`, `fontName`, `fills`, and similar read `figma.mixed` while characters differ. Check for it before using the value. Paints everywhere take Figma's shape: a solid `color` is `{ r, g, b }` with the alpha in `opacity`, and an image is `{ type: \"IMAGE\", imageHash, scaleMode: \"FILL\" | \"FIT\" | \"CROP\" | \"TILE\" }` with optional `rotation` and `scalingFactor`.\n\nNext to `figma`, scripts get `pairdraw`: what Pairdraw adds to the Figma API, in its style. A main component can behave as a Reka UI control, by its own property and slot names:\n\n```bash\npairdraw eval design.fig -w -c '\n const set = figma.currentPage.findOne(n => n.type === \"COMPONENT_SET\" && n.name === \"Switch\");\n const thumb = set.findOne(n => n.name === \"Thumb\");\n const behaviour = pairdraw.setBehaviour(set, \"switch\")\n .bindValue(\"value\", \"State\") // On/Off guessed from the variant values\n .bindPart(\"thumb\", thumb); // the frame becomes a slot\n behaviour.states = \"Interaction\";\n behaviour.missing // [] when the control is complete\n'\n```\n\n`pairdraw.behaviourKinds` lists every kind with its values and parts; `pairdraw.getBehaviour(node)` reads one (a variant reads its set's); `pairdraw.createSlot(frame)` makes a frame a slot. The `set_behaviour`, `get_behaviour`, and `create_slot` tools do the same over MCP, and design JSX writes controls with Reka's element names (`Switch.Root`, `Switch.Thumb`).\n\nComments people leave on the canvas are review feedback you can act on. Read the open ones, change the design, then answer and resolve each, naming yourself as the author:\n\n```bash\npairdraw eval design.fig -w -c '\n pairdraw.getComments({ resolved: false }).map(c => ({ id: c.id, text: c.text, layer: c.node?.name }))\n'\n# after the change:\npairdraw eval design.fig -w -c 'pairdraw.getComment(\"c_…\").reply(\"Title is 24px now\", { author: \"Claude\" }).resolve()'\n```\n\n`pairdraw.addComment(text, { node, page, x, y, author })` leaves a new one. Over MCP the same is `get_comments`, `add_comment`, `reply_to_comment`, and `resolve_comment`. Comment text is Markdown.\n\nStatuses say where a section, frame, component, or instance stands, from the document's own list. Read the list, find what is ready, and move a layer on once your work on it is done:\n\n```bash\npairdraw eval design.fig -c 'pairdraw.statuses.map(s => s.name)'\npairdraw eval design.fig -w -c 'pairdraw.setStatus(figma.currentPage.findOne(n => n.name === \"Checkout\"), \"In review\")'\n```\n\n`pairdraw.getStatus(node)` reads one. Over MCP the same is `get_statuses` and `set_status`.\n\n### Diff\n\nCompare nodes and documents, and apply patches:\n\n```bash\npairdraw diff create design.fig --from 1:23 --to 1:87 # JSX attribute patch\npairdraw diff jsx design.fig --from 1:23 --to 1:87 # JSX structure\npairdraw diff show 1:24 design.fig --attributes 'rounded={8}' > fix.diff\npairdraw diff apply fix.diff design.fig --dry-run # fails on stale values\npairdraw diff apply fix.diff design.fig --write\npairdraw diff visual design.fig --from 1:23 --to 1:87 -o diff.png\npairdraw diff files before.fig after.fig # exit 1 when different\n```\n\n### Control the running app\n\n```bash\npairdraw documents list --json # tab IDs, paths, pages\npairdraw documents open designs/landing.fig # new tab; --json returns target.documentId\npairdraw documents new --path designs/draft.fig\npairdraw documents activate tab-123 --page-id 0:4 # bring a tab to the front\npairdraw documents save --document-id tab-123\npairdraw documents close --document-id tab-123 --save # or --discard; fails on unsaved changes otherwise\npairdraw undo --document-id tab-123 # also: redo\npairdraw settings get --json\npairdraw settings set editing.snapping.pixelGrid false\n```\n\n`tool` exposes every MCP tool, so the CLI is never limited to its dedicated commands:\n\n```bash\npairdraw tool list\npairdraw tool describe set_fill # JSON Schema for the arguments\npairdraw tool call set_fill --document-id tab-123 --args '{\"id\":\"0:5\",\"color\":\"#2563eb\"}'\npairdraw tool call create_page design.fig --args '{\"name\":\"Icons\"}' --write # headless\npairdraw tool call create_shape design.fig --args '{\"type\":\"FRAME\",\"x\":0,\"y\":0,\"width\":320,\"height\":200}' -w --preview-output preview.png\nprintf '%s\\n' 'create_page {\"name\":\"Icons\"}' 'save()' | pairdraw shell design.fig # one load, many tool lines\npairdraw models --json # AI providers and their models\n```\n\nEvery command that reports structured data supports `--json` when appropriate.\n\n## MCP Server\n\n### Stdio MCP clients\n\nUse Bun by default:\n\n```json\n{\n \"mcpServers\": {\n \"pairdraw\": {\n \"command\": \"bunx\",\n \"args\": [\"pairdraw-mcp\"]\n }\n }\n}\n```\n\nIf `@pairdraw/mcp` is installed globally, direct binaries also work:\n\n```json\n{\n \"mcpServers\": {\n \"pairdraw\": {\n \"command\": \"pairdraw-mcp\"\n }\n }\n}\n```\n\n### HTTP / Streamable HTTP\n\n```bash\nexport PORT=7600\nexport PAIRDRAW_MCP_ROOT=/path/to/files # explicitly limit filesystem access\n\npairdraw-mcp-http\n# or: bunx pairdraw-mcp-http\n```\n\nAuthentication is enabled by default with an automatically generated token. `PAIRDRAW_MCP_AUTH_TOKEN` can supply an explicit non-empty token; an empty value disables authentication. If browser access needs CORS, set `PAIRDRAW_MCP_CORS_ORIGIN` to a trusted origin. Never combine wildcard CORS (`*`) with disabled authentication.\n\nThe CLI defaults the filesystem root to the home directory on Windows and the current working directory elsewhere. Set `PAIRDRAW_MCP_ROOT` to an explicit narrow directory rather than relying on that default.\n\n### MCP workflow\n\n1. **Find or open a document** — `list_documents` for open tabs and their IDs; `open_file { path }` within the effective filesystem root (`list_recent_files` lists recently opened files there), or `new_document {}`. Pass `document_id` and `page_id` explicitly instead of relying on the active tab; `activate_document { document_id }` brings a tab to the front when the user should see it.\n2. **Query** — `get_page_tree`, `find_nodes`, `query_nodes`, `get_node`, `list_pages`, `get_current_page`.\n3. **Inspect** — `get_jsx`, `diff_jsx`, `diff_create`, `diff_visual`, `describe`, `export_image`, `export_svg`, `export_pdf`.\n4. **Modify** — `render`, `batch_update`, `update_node`, `set_fill`, `set_layout`, `create_shape`, `import_svg`, etc. For a flowchart, write it as Mermaid and call `import_mermaid { mermaid }`: it lays out FigJam shapes, sections, and connectors without overlaps and returns each node's layer id, instead of placing shapes and connectors by hand. When layers you created overlap, call `arrange { ids }`: it spreads them apart and keeps each near where it was. `arrange` also packs screens (`mode: \"pack\"`) and lays shapes out along the connectors joining them (`mode: \"flow\"` for flows, `\"tree\"` for hierarchies, `\"radial\"` for mind maps, `\"network\"` for relationship maps).\n5. **Save/export** — `save_file`, `export_image`, `export_svg`, `export_pdf`, or CLI `export`.\n6. **Close** — `close_file { document_id, unsaved }` closes a document tab after the workflow. With unsaved changes it fails unless `unsaved` is `\"save\"` or `\"discard\"`; automation never prompts in the app.\n\nUse `undo` / `redo { document_id }` to step back your own changes. They refuse when the newest step was made by the user in the editor; never work around that. `get_settings` and `update_settings { settings }` read and change editor preferences such as theme, language, and snapping; they never expose credentials, models, or tool access.\n\n### Browser-native WebMCP (experimental)\n\nWebMCP is off by default. In **Settings → MCP → WebMCP**, choose **Inspect** for read-only tools or **Edit** for scoped changes. These controls are independent of local MCP settings. Supporting browsers expose inspection and undoable existing-layer/property and variable edits directly from the Pairdraw workspace through `document.modelContext`, without an MCP server connection. Discover this browser surface separately: it excludes structural creation/deletion, arbitrary JS/JSX execution, external assets, filesystem operations, and credentials.\n\nCalls capture the active document/page. Cancellation prevents an edit from starting but does not reverse an already committed edit; use editor undo instead. Atomic edits require at most 10,000 nodes and variables combined, including when these same tools run through app AI/MCP. See the [WebMCP guide](https://github.com/BadryansahBangsawan/pairdraw/blob/main/packages/docs/programmable/mcp-server.md#browser-native-webmcp-experimental-webmcp) for scope and browser requirements.\n\n## Tool discovery\n\nUsers configure local server tools in **Settings → Tool access** → **Local MCP**, independently from **Built-in AI** tool preferences. Local MCP changes require a server restart and stdio client reconnection; built-in AI changes apply to the next message. ACP and Pi agents use the MCP surface, not the direct-model AI tool selection. Tool switches are not a sandbox: enabled scripting tools can still perform operations whose dedicated tools are disabled.\n\nDiscover available tools and their arguments from the connected server or browser; availability varies by version and mode. Each tool's schema and execution/exposure metadata are authoritative. Numeric inputs accept numbers or numeric strings consistently, but reject non-finite values. Do not rely on a fixed tool count or a copied inventory.\n\n> Tool availability can depend on server mode. `open_file`, `save_file`, and disk-writing export paths are scoped to the effective filesystem root; set it explicitly with `PAIRDRAW_MCP_ROOT`.\n\n## Key tools for agents\n\n- **`query_nodes`** — XPath selectors to find specific nodes without fetching the full tree.\n- **`get_jsx`** — inspect any node as JSX in the same format accepted by `render`.\n- **`diff_jsx` / `diff_create`** — compare two nodes as a JSX line diff or as an appliable patch of JSX attributes; `diff_show` previews setting attributes and `diff_apply` applies a patch only if the nodes still match it.\n- **`diff_visual`** — pixel diff between two rendered nodes; use it to confirm an edit changed only the intended region.\n- **`describe`** — semantic analysis of role, visual style, layout, and design issues.\n- **`batch_update`** — apply multiple node updates efficiently.\n- **`export_image` / `export_svg` / `export_pdf`** — visual verification and deliverables; `export_image` takes `quality` (1–100) for JPG and WEBP.\n- **`export_html` / `import_html`** — layers to HTML with CSS or Tailwind (fragment or standalone, `layer_ids` to map markup back to layers), and HTML/CSS back into editable layers in the open document.\n- **`diff_changes`** — outside AI chat, call it with `mark: true`, then later without it to see what you or the designer changed since.\n- **`find_empty_space`** — a free spot of a given size beside existing content, before placing new frames.\n- **`replace_matching_properties`** — swap a fill, text, or stroke color, stroke weight, radius, font family, style, or size everywhere on a page or selection; layers of read-only library components come back in `read_only`.\n- **`get_style`** — curated style directions for a design with no look yet, or when asked for a style or mood: call it with a `query` describing the request to list matches, then with an `id` for that direction's palette by role, font pairing, type scale, radii, spacing, elevation, and written guidance. Adapt it; do not copy it verbatim.\n- **`rescale`** — scale layers with their text sizes, stroke weights, radii, effects, and spacing, as the Scale tool (K) does, around an `anchor` of their joint bounds; locked layers and layers inside instances come back in `skipped`; `node_resize` changes only the box.\n- **`set_text_properties` / `set_font_range` `hyperlink`** — link a whole text or a range to an http, https, or mailto address (`example.com` becomes `https://example.com`); `null` or `\"\"` removes it. Links are not underlined automatically.\n- **`generate_image` / `remove_background` / `replace_background` / `generate_svg`** — image AI on the user's own image service keys (Settings → Image services); they work only through the running app, take a while, cost the user money, and report a missing key for the user to add. Call them only when asked; `generate_svg` imports editable vector layers.\n- **`vectorize_image`** — turn a layer's image fill into editable vector paths in a new frame beside the image, with the user's own vectorize service; it works only through the running app, takes up to a few minutes, and reports a missing key for the user to add in Settings → Image services.\n- **`viewport_zoom_to_fit` / `viewport_set` / `viewport_get`** — move the user's view only when they ask to be shown something.\n- **`get_codegen_prompt`** — retrieve Pairdraw's current JSX/codegen guidance.\n- **`read_skill`** — read this skill (`SKILL.md`) or `references/design-authoring.md` from the connected server, for clients that cannot install skills; the same files are the `pairdraw://skills/pairdraw/` resources and the `design` prompt.\n- **`undo` / `redo`** — revert or reapply your newest change; they refuse to touch the user's edits.\n- **`list_documents` / `activate_document`** — discover open tabs and show the one you worked on.\n\n## JSX Rendering\n\nRead [Design authoring](references/design-authoring.md) before creating or modifying JSX designs. This bundled reference is generated from Core's authoring guidance, tested examples, and renderer metadata—the same reference used by chat and codegen prompts.\n\nUse the `render` tool for JSX strings. Use only the APIs exposed by the installed `eval` environment; native library exports are not automatically scripting globals. The connected server's `get_codegen_prompt` provides its version's codegen and authoring guidance.\n\n## Tips\n\n- Omit the file path to work with the document open in the running Pairdraw editor.\n- Start with `info` or `get_page_tree` to understand the document.\n- Use `tree --depth 2` or `query_nodes` to avoid overwhelming output on large files.\n- Export specific nodes with `--node` for faster visual checks.\n- Use `export_image` after changes to verify visual quality.\n- The running editor shows each MCP session as an agent at the layers its tools touch, and follows it while it works when the user has Follow agents on. Leave the user's selection and view alone unless they ask to be shown something.\n- Use `analyze colors --similar` to find near-duplicate colors.\n- Use `pairdraw tool call` for MCP tools without a dedicated CLI command, and `eval` for Figma Plugin API operations not covered by any tool.\n- Use `--json` when piping CLI output to scripts.\n- In app mode, `eval` and MCP modifications are reflected live in the editor.\n";
|
|
1816
1816
|
//#endregion
|
|
1817
1817
|
//#region src/skill/content.ts
|
|
1818
1818
|
/** The skill's name, as its frontmatter and `npx skills add` know it. */
|
|
@@ -2612,7 +2612,7 @@ function isLoopbackHost(host) {
|
|
|
2612
2612
|
}
|
|
2613
2613
|
//#endregion
|
|
2614
2614
|
//#region package.json
|
|
2615
|
-
var version = "0.16.
|
|
2615
|
+
var version = "0.16.1";
|
|
2616
2616
|
//#endregion
|
|
2617
2617
|
//#region src/server/connections.ts
|
|
2618
2618
|
const HEARTBEAT_INTERVAL_MS = 5e3;
|
|
@@ -3258,4 +3258,4 @@ function armAppAttachWatchdog(timeoutMs, browserRPC, handle) {
|
|
|
3258
3258
|
//#endregion
|
|
3259
3259
|
export { createServerInstructions as a, registerSkill as c, devAgentBridgeFromEnv as d, pairingFingerprint as f, resolveCORSOrigins as i, fail as l, startServer as n, MCP_AGENT_KINDS as o, DEFAULT_CONNECT_APP_URL as r, registerTools as s, MCP_VERSION as t, ok as u };
|
|
3260
3260
|
|
|
3261
|
-
//# sourceMappingURL=server
|
|
3261
|
+
//# sourceMappingURL=server-BdiJUhSs.mjs.map
|