@pairdraw/mcp 0.16.2 → 0.18.0

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.
@@ -1,8 +1,8 @@
1
1
  import "./rolldown-runtime-ClRpJifh.mjs";
2
2
  import { a as getSocketPath, i as getSocketDir, o as platformHasUnixSockets, r as getDiscoveryPath, t as getAgentWorkspacePath } from "./paths-BpcXnrbP.mjs";
3
- import { n as isToolEnabled, o as createToolDescriptors, s as getMCPToolDefinitions, t as applyToolPolicy } from "./policy-B8Ka4WRH.mjs";
3
+ import { n as isToolEnabled, o as createToolDescriptors, s as getMCPToolDefinitions, t as applyToolPolicy } from "./policy-3SjGqzs8.mjs";
4
4
  import { n as SELECTION_SCOPE_FILE_OUTPUT_ERROR, s as scopeRPC } from "./scope-D2LTTsDw.mjs";
5
- import { a as writeDiscoveryFile, i as removeStaleSocket, r as removeDiscoveryFile, t as parseDiscoveryInfo } from "./discovery-CB2Bv5WA.mjs";
5
+ import { a as writeDiscoveryFile, i as removeStaleSocket, r as removeDiscoveryFile, t as parseDiscoveryInfo } from "./discovery-EZhmHKtk.mjs";
6
6
  import { bodyLimit } from "hono/body-limit";
7
7
  import * as v from "valibot";
8
8
  import { WebSocketServer } from "ws";
@@ -17,12 +17,13 @@ import { Hono } from "hono";
17
17
  import { cors } from "hono/cors";
18
18
  import { compact } from "es-toolkit/array";
19
19
  import { toUint8Array } from "js-base64";
20
+ import { writeFileAtomic } from "@pairdraw/core/node/fs";
20
21
  import { Buffer as Buffer$1 } from "node:buffer";
21
22
  import { McpServer, WebStandardStreamableHTTPServerTransport, isJSONRPCResultResponse } from "@modelcontextprotocol/server";
23
+ import { isPlainObject, minBy, uniq as uniq$1 } from "es-toolkit";
22
24
  import { withTimeout } from "es-toolkit/promise";
23
25
  import { toStandardJsonSchema } from "@valibot/to-json-schema";
24
- import { CODEGEN_PROMPT } from "@pairdraw/core/tools";
25
- import { uniq as uniq$1 } from "es-toolkit";
26
+ import { CODEGEN_PROMPT, parseToolArgs } from "@pairdraw/core/tools";
26
27
  import { resolveCommand } from "package-manager-detector/commands";
27
28
  import { detect, getUserAgent } from "package-manager-detector/detect";
28
29
  import { createServer } from "node:http";
@@ -1463,24 +1464,6 @@ function createBrowserRPCBridge({ authToken, authorize = (token) => isAuthorized
1463
1464
  };
1464
1465
  }
1465
1466
  //#endregion
1466
- //#region src/http-options.ts
1467
- const MCP_CORS_METHODS = [
1468
- "GET",
1469
- "POST",
1470
- "PUT",
1471
- "DELETE",
1472
- "OPTIONS"
1473
- ];
1474
- const MCP_CORS_HEADERS = [
1475
- "Content-Type",
1476
- "Authorization",
1477
- "x-mcp-token",
1478
- "mcp-session-id",
1479
- "Last-Event-ID",
1480
- "mcp-protocol-version"
1481
- ];
1482
- const MCP_EXPOSED_HEADERS = ["mcp-session-id", "mcp-protocol-version"];
1483
- //#endregion
1484
1467
  //#region src/result.ts
1485
1468
  const MAX_RESULT_BYTES = 9e5;
1486
1469
  function resultTooLargeMessage(kind, bytes, hint) {
@@ -1663,7 +1646,7 @@ async function writeInsideRoot(filePath, root, content) {
1663
1646
  const parentDir = dirname(realPath);
1664
1647
  await mkdir(parentDir, { recursive: true });
1665
1648
  await resolveSafePath(parentDir, root);
1666
- await writeFile(realPath, content);
1649
+ await writeFileAtomic(realPath, content);
1667
1650
  await resolveSafePath(realPath, root);
1668
1651
  return {
1669
1652
  written: resolved,
@@ -1714,6 +1697,32 @@ async function writeToolOutput(toolName, result, filePath, root) {
1714
1697
  return ok(await writeInsideRoot(filePath, root, content));
1715
1698
  }
1716
1699
  //#endregion
1700
+ //#region src/http-options.ts
1701
+ const MCP_CORS_METHODS = [
1702
+ "GET",
1703
+ "POST",
1704
+ "PUT",
1705
+ "DELETE",
1706
+ "OPTIONS"
1707
+ ];
1708
+ /**
1709
+ * Refuses a larger body, counted as it streams in, so one without Content-Length is bounded too.
1710
+ * Routes check the token before it, so a caller without one never makes the server buffer.
1711
+ */
1712
+ const limitBody = bodyLimit({
1713
+ maxSize: 2 * MAX_FILE_TRANSFER_BYTES,
1714
+ onError: (c) => c.json({ error: "Request is too large" }, 413)
1715
+ });
1716
+ const MCP_CORS_HEADERS = [
1717
+ "Content-Type",
1718
+ "Authorization",
1719
+ "x-mcp-token",
1720
+ "mcp-session-id",
1721
+ "Last-Event-ID",
1722
+ "mcp-protocol-version"
1723
+ ];
1724
+ const MCP_EXPOSED_HEADERS = ["mcp-session-id", "mcp-protocol-version"];
1725
+ //#endregion
1717
1726
  //#region src/server/files.ts
1718
1727
  /**
1719
1728
  * The path after `/files/`, one encoded segment per folder, so the URL ends in the file's name.
@@ -1809,10 +1818,10 @@ function sessionNotFound() {
1809
1818
  }
1810
1819
  //#endregion
1811
1820
  //#region ../../skills/pairdraw/references/design-authoring.md?raw
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`.";
1821
+ 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. A raw shadow needs an effect type, a numeric radius, and a color. A raw blur needs an effect type and a numeric radius, and a missing color is transparent. A shader needs `source`. Anything else is an error that names the prop.\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
1822
  //#endregion
1814
1823
  //#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/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";
1824
+ 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 # the document this session is targeting, or the one in front\npairdraw documents save --document-id tab-123\npairdraw documents close --document-id tab-123 --save # or --discard; fails on unsaved changes otherwise\n# close without --document-id only closes a document this CLI session opened\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. Commands share one `cli` session. Set `PAIRDRAW_SESSION` to run a second CLI agent beside it:\n\n```bash\nPAIRDRAW_SESSION=agent-a pairdraw tool call create_shape --args '{\"type\":\"RECTANGLE\",\"x\":0,\"y\":0,\"width\":40,\"height\":40}'\n```\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\nEach session keeps the document it edits, including after the person switches tabs. Home and a New file tab are not documents: an edit with none chosen yet opens a document tab and leaves the current tab in front. `open_file` owns a document only when that call opened it. `close_file` without `document_id` closes only a document this session opened. `save_file` without `document_id` saves the document this session is targeting, or the document in front. When that document has been closed, call `list_documents` and pass `document_id`, or call `new_document` or `open_file`. A new HTTP session starts with no document. An idle timeout of 15 minutes ends the previous session, and the next edit opens its own tab. Set `PAIRDRAW_SESSION` to run two CLI agents at once; otherwise CLI commands share one `cli` session.\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
1825
  //#endregion
1817
1826
  //#region src/skill/content.ts
1818
1827
  /** The skill's name, as its frontmatter and `npx skills add` know it. */
@@ -2058,20 +2067,35 @@ function registerTools(mcpServer, options) {
2058
2067
  call: agentCallId(meta)
2059
2068
  };
2060
2069
  };
2070
+ const sendToApp = (body) => {
2071
+ const args = body.args;
2072
+ if (!agentSession || !isPlainObject(args) || args.agent) return sendRPC(body);
2073
+ return sendRPC({
2074
+ ...body,
2075
+ args: {
2076
+ ...args,
2077
+ agent: agent(void 0)
2078
+ }
2079
+ });
2080
+ };
2061
2081
  const resolvedRoot = options.mcpRoot ? resolve(options.mcpRoot) : null;
2062
2082
  const descriptors = descriptorByName(createToolDescriptors(resolvedRoot !== null));
2063
2083
  const register = (name, toolOptions, handler) => {
2064
2084
  const descriptor = descriptors.get(name);
2065
2085
  if (!descriptor) throw new Error(`Missing MCP tool descriptor for "${name}"`);
2066
2086
  if (!isToolEnabled(descriptor, policy)) return;
2087
+ const inputSchema = { "~standard": {
2088
+ ...toStandardJsonSchema(toolOptions.inputSchema)["~standard"],
2089
+ validate: (value) => ({ value })
2090
+ } };
2067
2091
  mcpServer.registerTool(name, {
2068
2092
  description: toolOptions.description ?? descriptor.description,
2069
- inputSchema: toStandardJsonSchema(toolOptions.inputSchema),
2093
+ inputSchema,
2070
2094
  annotations: toolAnnotations(descriptor.effect),
2071
2095
  _meta: { "pairdraw/capabilities": descriptor.capabilities }
2072
2096
  }, async (args, context) => {
2073
2097
  try {
2074
- return await handler(args, context);
2098
+ return await handler(parseToolArgs(name, toolOptions.inputSchema, args), context);
2075
2099
  } finally {
2076
2100
  await options.onToolSettled?.(context);
2077
2101
  }
@@ -2088,7 +2112,7 @@ function registerTools(mcpServer, options) {
2088
2112
  const { target, args: toolArgs } = splitAutomationTarget(args);
2089
2113
  const filePath = writesFileOutput(def.name) && typeof toolArgs.path === "string" ? toolArgs.path : null;
2090
2114
  if (policy.scope === "selection" && filePath !== null) return fail(new Error(SELECTION_SCOPE_FILE_OUTPUT_ERROR));
2091
- const res = await sendRPC({
2115
+ const res = await sendToApp({
2092
2116
  command: "tool",
2093
2117
  args: {
2094
2118
  ...target,
@@ -2124,7 +2148,7 @@ function registerTools(mcpServer, options) {
2124
2148
  inputSchema: v.strictObject({})
2125
2149
  }, async () => {
2126
2150
  try {
2127
- const res = await sendRPC({
2151
+ const res = await sendToApp({
2128
2152
  command: "list_documents",
2129
2153
  args: {}
2130
2154
  });
@@ -2144,7 +2168,7 @@ function registerTools(mcpServer, options) {
2144
2168
  try {
2145
2169
  const safePath = args.path !== void 0 && resolvedRoot ? await resolveSafePath(args.path, resolvedRoot) : void 0;
2146
2170
  const { target } = splitAutomationTarget(args);
2147
- const res = await sendRPC({
2171
+ const res = await sendToApp({
2148
2172
  command: "save_file",
2149
2173
  args: {
2150
2174
  ...target,
@@ -2171,7 +2195,7 @@ function registerTools(mcpServer, options) {
2171
2195
  try {
2172
2196
  const safe = await resolveSafePath(args.path, resolvedRoot);
2173
2197
  const { target } = splitAutomationTarget(args);
2174
- const res = await sendRPC({
2198
+ const res = await sendToApp({
2175
2199
  command: "open_file",
2176
2200
  args: {
2177
2201
  ...target,
@@ -2188,7 +2212,7 @@ function registerTools(mcpServer, options) {
2188
2212
  });
2189
2213
  register("list_recent_files", { inputSchema: v.strictObject({}) }, async () => {
2190
2214
  try {
2191
- const res = await sendCommand(sendRPC, "list_recent_files", {});
2215
+ const res = await sendCommand(sendToApp, "list_recent_files", {});
2192
2216
  const { files } = v.parse(recentFilesResultSchema, res.result);
2193
2217
  const insideRoot = await Promise.all(files.map((file) => resolveSafePath(file.path, resolvedRoot).then(() => true, () => false)));
2194
2218
  return ok({ files: files.filter((_, index) => insideRoot[index]) });
@@ -2206,7 +2230,7 @@ function registerTools(mcpServer, options) {
2206
2230
  try {
2207
2231
  const safePath = args.path !== void 0 ? await resolveSafePath(args.path, resolvedRoot) : void 0;
2208
2232
  const { target } = splitAutomationTarget(args);
2209
- const res = await sendRPC({
2233
+ const res = await sendToApp({
2210
2234
  command: "new_document",
2211
2235
  args: {
2212
2236
  ...target,
@@ -2240,7 +2264,7 @@ function registerTools(mcpServer, options) {
2240
2264
  const rpcArgs = { ...target };
2241
2265
  if (args.unsaved) rpcArgs.unsaved = args.unsaved;
2242
2266
  if (safePath) rpcArgs.path = safePath.realPath;
2243
- const res = await sendCommand(sendRPC, "close_file", rpcArgs);
2267
+ const res = await sendCommand(sendToApp, "close_file", rpcArgs);
2244
2268
  return ok(withTarget({ closed: res.result?.closed === true }, res));
2245
2269
  } catch (e) {
2246
2270
  return fail(e);
@@ -2252,7 +2276,7 @@ function registerTools(mcpServer, options) {
2252
2276
  }) }, async (args) => {
2253
2277
  try {
2254
2278
  const { target } = splitAutomationTarget(args);
2255
- return ok(withTarget({ activated: true }, await sendCommand(sendRPC, "activate_document", target)));
2279
+ return ok(withTarget({ activated: true }, await sendCommand(sendToApp, "activate_document", target)));
2256
2280
  } catch (e) {
2257
2281
  return fail(e);
2258
2282
  }
@@ -2260,7 +2284,7 @@ function registerTools(mcpServer, options) {
2260
2284
  for (const command of ["undo", "redo"]) register(command, { inputSchema: v.strictObject({ ...automationTargetSchema }) }, async (args) => {
2261
2285
  try {
2262
2286
  const { target } = splitAutomationTarget(args);
2263
- const res = await sendCommand(sendRPC, command, target);
2287
+ const res = await sendCommand(sendToApp, command, target);
2264
2288
  return ok(withTarget({ ...res.result }, res));
2265
2289
  } catch (e) {
2266
2290
  return fail(e);
@@ -2268,14 +2292,14 @@ function registerTools(mcpServer, options) {
2268
2292
  });
2269
2293
  register("get_settings", { inputSchema: v.strictObject({}) }, async () => {
2270
2294
  try {
2271
- return ok((await sendCommand(sendRPC, "get_settings", {})).result ?? {});
2295
+ return ok((await sendCommand(sendToApp, "get_settings", {})).result ?? {});
2272
2296
  } catch (e) {
2273
2297
  return fail(e);
2274
2298
  }
2275
2299
  });
2276
2300
  register("update_settings", { inputSchema: v.strictObject({ settings: v.pipe(v.record(v.string(), v.unknown()), v.description("Partial settings, e.g. {\"appearance\":{\"theme\":\"light\"},\"editing\":{\"snapping\":{\"pixelGrid\":false}}}. Unknown keys and invalid values are rejected.")) }) }, async (args) => {
2277
2301
  try {
2278
- await sendCommand(sendRPC, "update_settings", { settings: args.settings });
2302
+ await sendCommand(sendToApp, "update_settings", { settings: args.settings });
2279
2303
  return ok({ updated: args.settings });
2280
2304
  } catch (e) {
2281
2305
  return fail(e);
@@ -2289,11 +2313,10 @@ function registerTools(mcpServer, options) {
2289
2313
  type: "text",
2290
2314
  text: SKILL_FILES[args.path ?? "SKILL.md"].text
2291
2315
  }] }));
2292
- registerBrowserTools(register, sendRPC);
2316
+ registerBrowserTools(register, sendToApp);
2293
2317
  }
2294
- //#endregion
2295
- //#region src/server/sessions.ts
2296
- const MAX_MCP_SESSIONS = 10;
2318
+ /** How long a session must sit idle before a newcomer may take its slot. */
2319
+ const MCP_SESSION_EVICT_IDLE_MS = 12e4;
2297
2320
  /** App chat ids are random hex; anything else is ignored rather than forwarded. */
2298
2321
  const CHAT_ID = /^[0-9a-f]{16,64}$/;
2299
2322
  /** The opener a session's first request names through the app's agent and chat headers. */
@@ -2330,7 +2353,7 @@ async function isInitializeResult(response, id) {
2330
2353
  const message = await response.clone().json().catch(() => void 0);
2331
2354
  return isJSONRPCResultResponse(message);
2332
2355
  }
2333
- function createMCPSessionManager({ serverVersion, registerTools, instructions, onSessionOpened, onSessionClosed, sessionIdleTimeoutMs = MCP_SESSION_IDLE_TIMEOUT_MS }) {
2356
+ function createMCPSessionManager({ serverVersion, registerTools, instructions, onSessionOpened, onSessionClosed, sessionIdleTimeoutMs = MCP_SESSION_IDLE_TIMEOUT_MS, evictIdleMs = MCP_SESSION_EVICT_IDLE_MS }) {
2334
2357
  const sessions = /* @__PURE__ */ new Map();
2335
2358
  const closing = /* @__PURE__ */ new Map();
2336
2359
  function scheduleClose(session, id) {
@@ -2368,6 +2391,26 @@ function createMCPSessionManager({ serverVersion, registerTools, instructions, o
2368
2391
  const sweep = sessionIdleTimeoutMs > 0 ? setInterval(cleanupExpired, Math.min(sessionIdleTimeoutMs, MAX_SWEEP_INTERVAL_MS)).unref() : void 0;
2369
2392
  const creating = /* @__PURE__ */ new Map();
2370
2393
  let closed = false;
2394
+ /**
2395
+ * A session whose slot a newcomer may take. A client may replace its own idle session, and any
2396
+ * client may take the slot of one left idle long enough that nobody is using it. A session
2397
+ * another client may still be working in is never taken, so no client can push another out;
2398
+ * when live sessions are below the cap, the slots are held by ones still closing, and the
2399
+ * caller waits for them.
2400
+ */
2401
+ function evictionCandidate(opener) {
2402
+ if (sessions.size + creating.size < 10) return void 0;
2403
+ const idle = [...sessions].map(([id, session]) => ({
2404
+ id,
2405
+ session
2406
+ })).filter((entry) => entry.session.activeRequests === 0);
2407
+ if (idle.length === 0) return void 0;
2408
+ const own = opener.chat ? idle.filter((entry) => entry.session.agent.chat === opener.chat) : [];
2409
+ const now = Date.now();
2410
+ const pool = own.length > 0 ? own : idle.filter((entry) => now - entry.session.lastSeen >= evictIdleMs);
2411
+ if (pool.length === 0) return void 0;
2412
+ return minBy(pool, (entry) => entry.session.lastSeen);
2413
+ }
2371
2414
  async function createSession(id, opener) {
2372
2415
  if (closed) throw new Error("Session manager is closed");
2373
2416
  const inFlight = creating.get(id);
@@ -2467,7 +2510,12 @@ function createMCPSessionManager({ serverVersion, registerTools, instructions, o
2467
2510
  throw e;
2468
2511
  });
2469
2512
  }
2470
- if (sessions.size + creating.size + closing.size >= MAX_MCP_SESSIONS) return Promise.resolve({ error: "too_many" });
2513
+ if (sessions.size + creating.size + closing.size >= 10) {
2514
+ const victim = evictionCandidate(opener);
2515
+ if (!victim) return Promise.resolve({ error: "too_many" });
2516
+ sessions.delete(victim.id);
2517
+ scheduleClose(victim.session, victim.id);
2518
+ }
2471
2519
  return createSession(sessionId ?? randomUUID(), opener).catch((e) => {
2472
2520
  if (closed) return { error: "closed" };
2473
2521
  throw e;
@@ -2513,39 +2561,23 @@ function createMCPSessionManager({ serverVersion, registerTools, instructions, o
2513
2561
  };
2514
2562
  }
2515
2563
  //#endregion
2516
- //#region src/skill/instructions.ts
2517
- const SKILL_FILE_URI = skillResourceURI("SKILL.md");
2518
- const REFERENCE_PATH = "references/design-authoring.md";
2519
- const REFERENCE_URI = skillResourceURI(REFERENCE_PATH);
2520
- function skillParagraph(enabled) {
2521
- const designs = enabled("render");
2522
- const lead = designs ? "Before you design" : "Before you use these tools";
2523
- if (!enabled("read_skill")) return `${lead}, read the ${SKILL_NAME} skill from the resources ${SKILL_FILE_URI} and ${REFERENCE_URI}.`;
2524
- return `${lead}, read the ${SKILL_NAME} skill: call read_skill for SKILL.md, then read_skill with path "${REFERENCE_PATH}"${designs ? " before you use render" : ""}. Clients without that tool can read the same files as the resources ${SKILL_FILE_URI} and ${REFERENCE_URI}.`;
2525
- }
2526
- function usageParagraph(enabled, policy) {
2527
- const undo = enabled("undo");
2528
- return compact([
2529
- enabled("list_documents") && "When several documents may be open, call list_documents first and pass its document_id and page_id to later calls.",
2530
- policy.scope === "document" && enabled("export_image") && "Check visual changes with export_image.",
2531
- undo && `${enabled("redo") ? "undo and redo step" : "undo steps"} back only your own changes.`,
2532
- enabled("get_codegen_prompt") && "Call get_codegen_prompt before turning a design into frontend code."
2533
- ]).join(" ");
2564
+ //#region src/server/install-command.ts
2565
+ let installCommandPromise = null;
2566
+ async function resolveMCPInstallCommand(version) {
2567
+ const agent = getUserAgent() ?? (await detect({ strategies: [
2568
+ "install-metadata",
2569
+ "lockfile",
2570
+ "packageManager-field",
2571
+ "devEngines-field"
2572
+ ] }))?.agent ?? "npm";
2573
+ const resolved = resolveCommand(agent, "global", [`@pairdraw/mcp@${version}`]);
2574
+ if (!resolved) return `npm install -g @pairdraw/mcp@${version}`;
2575
+ return [resolved.command, ...resolved.args].join(" ");
2534
2576
  }
2535
- /**
2536
- * What the server tells a client when it connects, naming only the tools its policy and scope
2537
- * expose. Clients such as Codex show only the start of it, so the first paragraphs stand on their
2538
- * own and stay under 512 characters. App chats get no skill paragraph: their system prompt already
2539
- * carries the design authoring reference.
2540
- */
2541
- function createServerInstructions({ policy, filesystemEnabled, agentKind }) {
2542
- const exposed = new Set(createToolDescriptors(filesystemEnabled).filter((descriptor) => isToolEnabled(descriptor, policy)).map((descriptor) => descriptor.name));
2543
- const enabled = (name) => exposed.has(name);
2544
- return compact([
2545
- policy.scope === "selection" ? "Pairdraw is a design editor. These tools read only the layers selected in its running app and cannot change the document." : "Pairdraw is a design editor. These tools read and edit the documents open in its running app.",
2546
- agentKind === "mcp" && skillParagraph(enabled),
2547
- usageParagraph(enabled, policy)
2548
- ]).join("\n\n");
2577
+ /** How to install this server version globally with the package manager that runs it. */
2578
+ function mcpInstallCommand(version) {
2579
+ installCommandPromise ??= resolveMCPInstallCommand(version);
2580
+ return installCommandPromise;
2549
2581
  }
2550
2582
  //#endregion
2551
2583
  //#region src/transport/origins.ts
@@ -2611,8 +2643,179 @@ function isLoopbackHost(host) {
2611
2643
  return hostname === "127.0.0.1" || hostname === "localhost" || hostname === "[::1]" || hostname.endsWith(".localhost");
2612
2644
  }
2613
2645
  //#endregion
2646
+ //#region src/server/origin.ts
2647
+ /**
2648
+ * Refuses requests from pages of other sites, and requests addressed to a name other than this
2649
+ * machine's, as a page that rebound its DNS name to 127.0.0.1 sends. CORS only hides answers from
2650
+ * other sites; refusing the request also stops them from acting, such as spending pairing
2651
+ * attempts.
2652
+ */
2653
+ function originGuard(origins) {
2654
+ return async (c, next) => {
2655
+ if (!isLoopbackHost(c.req.header("host"))) return c.json({ error: "Host not allowed" }, 403);
2656
+ if (!isAllowedOrigin(c.req.header("origin"), origins)) return c.json({ error: "Origin not allowed" }, 403);
2657
+ await next();
2658
+ if (c.req.method === "OPTIONS" && c.req.header("access-control-request-private-network")) c.res.headers.set("Access-Control-Allow-Private-Network", "true");
2659
+ };
2660
+ }
2661
+ /**
2662
+ * Routes WebSocket upgrades: agent sockets to the agent bridge, everything else to the app's
2663
+ * automation bridge. Browsers always send `Origin` on an upgrade, so a page from another site is
2664
+ * refused before either sees it.
2665
+ */
2666
+ function createUpgradeHandler(origins, wss, agentBridge) {
2667
+ return (request, socket, head) => {
2668
+ if (!isLoopbackHost(request.headers.host) || !isAllowedOrigin(request.headers.origin, origins)) {
2669
+ socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
2670
+ return;
2671
+ }
2672
+ if (agentBridge?.handleUpgrade(request, socket, head)) return;
2673
+ wss.handleUpgrade(request, socket, head, (ws) => {
2674
+ wss.emit("connection", ws, request);
2675
+ });
2676
+ };
2677
+ }
2678
+ //#endregion
2679
+ //#region src/server/http-app.ts
2680
+ const MCP_METHODS = [
2681
+ "GET",
2682
+ "POST",
2683
+ "DELETE"
2684
+ ];
2685
+ /** Set up Hono routes: /health, /rpc, /files, /mcp */
2686
+ function createHonoApp(options) {
2687
+ const { authToken, corsOrigin, corsAllowed, fileRoot, browserRPC, mcpSessions, sendToBrowser } = options;
2688
+ const { toolDescriptors, verifyToken, verifyMCPToken, origins, agentBridge } = options;
2689
+ const app = new Hono();
2690
+ app.use("*", originGuard(origins));
2691
+ if (corsOrigin) {
2692
+ const corsOrigins = corsAllowed ?? (typeof corsOrigin === "string" ? [corsOrigin] : [...corsOrigin]);
2693
+ app.use("*", cors({
2694
+ origin: [...corsOrigins],
2695
+ allowMethods: MCP_CORS_METHODS,
2696
+ allowHeaders: MCP_CORS_HEADERS,
2697
+ exposeHeaders: MCP_EXPOSED_HEADERS
2698
+ }));
2699
+ }
2700
+ app.get("/health", async (c) => {
2701
+ const provided = bearerToken(c.req.header("authorization"));
2702
+ const canInspectConfiguration = verifyMCPToken(provided);
2703
+ return c.json({
2704
+ status: browserRPC.isConnected() ? "ok" : "no_app",
2705
+ version: options.version,
2706
+ installCommand: await mcpInstallCommand(options.version),
2707
+ authRequired: authToken !== null,
2708
+ agentSessionEvents: true,
2709
+ ...canInspectConfiguration ? { tools: toolDescriptors } : {}
2710
+ });
2711
+ });
2712
+ const requireToken = async (c, next) => {
2713
+ if (!verifyToken(bearerToken(c.req.header("authorization")))) return c.json({ error: "Unauthorized" }, 401);
2714
+ return next();
2715
+ };
2716
+ app.use("/rpc", requireToken);
2717
+ if (fileRoot !== null) {
2718
+ app.use("/files/*", requireToken);
2719
+ registerFileRoutes(app, fileRoot);
2720
+ }
2721
+ app.post("/rpc", limitBody, async (c) => {
2722
+ const body = await c.req.json().catch(() => null);
2723
+ if (!body || typeof body !== "object" || Array.isArray(body)) return c.json({ error: "Invalid request body" }, 400);
2724
+ try {
2725
+ const result = await sendToBrowser(body);
2726
+ return c.json(result);
2727
+ } catch (e) {
2728
+ const msg = e instanceof Error ? e.message : String(e);
2729
+ return c.json({
2730
+ ok: false,
2731
+ error: msg
2732
+ }, 502);
2733
+ }
2734
+ });
2735
+ const requireMCPToken = async (c, next) => {
2736
+ const token = mcpRequestToken(c.req.header("authorization"), c.req.header("x-mcp-token"));
2737
+ return verifyMCPToken(token) ? next() : c.json({ error: "Unauthorized" }, 401);
2738
+ };
2739
+ app.all("/mcp", requireMCPToken, limitBody, async (c) => {
2740
+ if (!MCP_METHODS.includes(c.req.method)) return c.json({ error: "Method not allowed" }, {
2741
+ status: 405,
2742
+ headers: { Allow: MCP_METHODS.join(", ") }
2743
+ });
2744
+ const sessionId = c.req.header("mcp-session-id") ?? void 0;
2745
+ if (sessionId) {
2746
+ const existing = mcpSessions.getExistingTransport(sessionId);
2747
+ if ("error" in existing) {
2748
+ if (existing.error === "closed") return c.json({ error: "MCP server is shutting down" }, 503);
2749
+ return c.json({ error: "MCP session not found" }, 404);
2750
+ }
2751
+ if (c.req.method !== "DELETE") return existing.handleRequest(c.req.raw);
2752
+ try {
2753
+ return await existing.handleRequest(c.req.raw);
2754
+ } finally {
2755
+ await mcpSessions.deleteSession(sessionId);
2756
+ }
2757
+ }
2758
+ if (c.req.method !== "POST") return c.json({ error: "Missing MCP session id" }, 400);
2759
+ const transport = await mcpSessions.resolveTransport(void 0, sessionOpener(c.req.header(MCP_AGENT_HEADER), c.req.header(MCP_CHAT_HEADER)));
2760
+ if ("error" in transport) {
2761
+ if (transport.error === "closed") return c.json({ error: "MCP server is shutting down" }, 503);
2762
+ return c.json({
2763
+ error: `The server holds 10 MCP sessions at once; close one with DELETE, or wait for one left idle for ${MCP_SESSION_EVICT_IDLE_MS / 1e3} seconds to be released.`,
2764
+ limit: 10,
2765
+ retryAfterSeconds: 5
2766
+ }, {
2767
+ status: 503,
2768
+ headers: { "Retry-After": "5" }
2769
+ });
2770
+ }
2771
+ return transport.handleRequest(c.req.raw);
2772
+ });
2773
+ agentBridge?.routes(app);
2774
+ return app;
2775
+ }
2776
+ //#endregion
2777
+ //#region src/skill/instructions.ts
2778
+ const SKILL_FILE_URI = skillResourceURI("SKILL.md");
2779
+ const REFERENCE_PATH = "references/design-authoring.md";
2780
+ const REFERENCE_URI = skillResourceURI(REFERENCE_PATH);
2781
+ function skillParagraph(enabled) {
2782
+ const designs = enabled("render");
2783
+ const lead = designs ? "Before you design" : "Before you use these tools";
2784
+ if (!enabled("read_skill")) return `${lead}, read the ${SKILL_NAME} skill from the resources ${SKILL_FILE_URI} and ${REFERENCE_URI}.`;
2785
+ return `${lead}, read the ${SKILL_NAME} skill: call read_skill for SKILL.md, then read_skill with path "${REFERENCE_PATH}"${designs ? " before you use render" : ""}. Clients without that tool can read the same files as the resources ${SKILL_FILE_URI} and ${REFERENCE_URI}.`;
2786
+ }
2787
+ function closedRecovery(enabled) {
2788
+ const actions = compact([enabled("new_document") && "new_document", enabled("open_file") && "open_file"]);
2789
+ if (actions.length === 0) return "";
2790
+ return ` After that document is closed, pass document_id from list_documents, or call ${actions.join(" or ")}.`;
2791
+ }
2792
+ function usageParagraph(enabled, policy) {
2793
+ const undo = enabled("undo");
2794
+ return compact([
2795
+ enabled("list_documents") && `When several documents may be open, call list_documents first and pass its document_id and page_id to later calls. Each session keeps the document it edits. Home is not a document. Closing without document_id only closes a document this session opened.${closedRecovery(enabled)}`,
2796
+ policy.scope === "document" && enabled("export_image") && "Check visual changes with export_image.",
2797
+ undo && `${enabled("redo") ? "undo and redo step" : "undo steps"} back only your own changes.`,
2798
+ enabled("get_codegen_prompt") && "Call get_codegen_prompt before turning a design into frontend code."
2799
+ ]).join(" ");
2800
+ }
2801
+ /**
2802
+ * What the server tells a client when it connects, naming only the tools its policy and scope
2803
+ * expose. Clients such as Codex show only the start of it, so the first paragraphs stand on their
2804
+ * own and stay under 512 characters. App chats get no skill paragraph: their system prompt already
2805
+ * carries the design authoring reference.
2806
+ */
2807
+ function createServerInstructions({ policy, filesystemEnabled, agentKind }) {
2808
+ const exposed = new Set(createToolDescriptors(filesystemEnabled).filter((descriptor) => isToolEnabled(descriptor, policy)).map((descriptor) => descriptor.name));
2809
+ const enabled = (name) => exposed.has(name);
2810
+ return compact([
2811
+ policy.scope === "selection" ? "Pairdraw is a design editor. These tools read only the layers selected in its running app and cannot change the document." : "Pairdraw is a design editor. These tools read and edit the documents open in its running app.",
2812
+ agentKind === "mcp" && skillParagraph(enabled),
2813
+ usageParagraph(enabled, policy)
2814
+ ]).join("\n\n");
2815
+ }
2816
+ //#endregion
2614
2817
  //#region package.json
2615
- var version = "0.16.2";
2818
+ var version = "0.18.0";
2616
2819
  //#endregion
2617
2820
  //#region src/server/connections.ts
2618
2821
  const HEARTBEAT_INTERVAL_MS = 5e3;
@@ -2661,25 +2864,6 @@ function wireConnectionHandling(wss, browserRPC) {
2661
2864
  wss.on("close", () => clearInterval(heartbeat));
2662
2865
  }
2663
2866
  //#endregion
2664
- //#region src/server/install-command.ts
2665
- let installCommandPromise = null;
2666
- async function resolveMCPInstallCommand(version) {
2667
- const agent = getUserAgent() ?? (await detect({ strategies: [
2668
- "install-metadata",
2669
- "lockfile",
2670
- "packageManager-field",
2671
- "devEngines-field"
2672
- ] }))?.agent ?? "npm";
2673
- const resolved = resolveCommand(agent, "global", [`@pairdraw/mcp@${version}`]);
2674
- if (!resolved) return `npm install -g @pairdraw/mcp@${version}`;
2675
- return [resolved.command, ...resolved.args].join(" ");
2676
- }
2677
- /** How to install this server version globally with the package manager that runs it. */
2678
- function mcpInstallCommand(version) {
2679
- installCommandPromise ??= resolveMCPInstallCommand(version);
2680
- return installCommandPromise;
2681
- }
2682
- //#endregion
2683
2867
  //#region src/server/lifecycle.ts
2684
2868
  const trackedConnections = Symbol("pairdraw-mcp-connections");
2685
2869
  /** Create an HTTP server bound to the Hono app. Each server can listen on one address. */
@@ -2896,131 +3080,8 @@ async function tryWriteDiscovery(resolvedSocketPath, actualHttpPort, authToken,
2896
3080
  }
2897
3081
  }
2898
3082
  //#endregion
2899
- //#region src/server/origin.ts
2900
- /**
2901
- * Refuses requests from pages of other sites, and requests addressed to a name other than this
2902
- * machine's, as a page that rebound its DNS name to 127.0.0.1 sends. CORS only hides answers from
2903
- * other sites; refusing the request also stops them from acting, such as spending pairing
2904
- * attempts.
2905
- */
2906
- function originGuard(origins) {
2907
- return async (c, next) => {
2908
- if (!isLoopbackHost(c.req.header("host"))) return c.json({ error: "Host not allowed" }, 403);
2909
- if (!isAllowedOrigin(c.req.header("origin"), origins)) return c.json({ error: "Origin not allowed" }, 403);
2910
- await next();
2911
- if (c.req.method === "OPTIONS" && c.req.header("access-control-request-private-network")) c.res.headers.set("Access-Control-Allow-Private-Network", "true");
2912
- };
2913
- }
2914
- /**
2915
- * Routes WebSocket upgrades: agent sockets to the agent bridge, everything else to the app's
2916
- * automation bridge. Browsers always send `Origin` on an upgrade, so a page from another site is
2917
- * refused before either sees it.
2918
- */
2919
- function createUpgradeHandler(origins, wss, agentBridge) {
2920
- return (request, socket, head) => {
2921
- if (!isLoopbackHost(request.headers.host) || !isAllowedOrigin(request.headers.origin, origins)) {
2922
- socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
2923
- return;
2924
- }
2925
- if (agentBridge?.handleUpgrade(request, socket, head)) return;
2926
- wss.handleUpgrade(request, socket, head, (ws) => {
2927
- wss.emit("connection", ws, request);
2928
- });
2929
- };
2930
- }
2931
- //#endregion
2932
3083
  //#region src/server.ts
2933
3084
  const MCP_VERSION = version;
2934
- const MCP_METHODS = [
2935
- "GET",
2936
- "POST",
2937
- "DELETE"
2938
- ];
2939
- /** Set up Hono routes: /health, /rpc, /files, /mcp */
2940
- function createHonoApp(options) {
2941
- const { authToken, corsOrigin, corsAllowed, fileRoot, browserRPC, mcpSessions, sendToBrowser } = options;
2942
- const { toolDescriptors, verifyToken, verifyMCPToken, origins, agentBridge } = options;
2943
- const app = new Hono();
2944
- app.use("*", originGuard(origins));
2945
- if (corsOrigin) {
2946
- const corsOrigins = corsAllowed ?? (typeof corsOrigin === "string" ? [corsOrigin] : [...corsOrigin]);
2947
- app.use("*", cors({
2948
- origin: [...corsOrigins],
2949
- allowMethods: MCP_CORS_METHODS,
2950
- allowHeaders: MCP_CORS_HEADERS,
2951
- exposeHeaders: MCP_EXPOSED_HEADERS
2952
- }));
2953
- }
2954
- app.get("/health", async (c) => {
2955
- const provided = bearerToken(c.req.header("authorization"));
2956
- const canInspectConfiguration = verifyMCPToken(provided);
2957
- return c.json({
2958
- status: browserRPC.isConnected() ? "ok" : "no_app",
2959
- version: MCP_VERSION,
2960
- installCommand: await mcpInstallCommand(MCP_VERSION),
2961
- authRequired: authToken !== null,
2962
- agentSessionEvents: true,
2963
- ...canInspectConfiguration ? { tools: toolDescriptors } : {}
2964
- });
2965
- });
2966
- const requireToken = async (c, next) => {
2967
- if (!verifyToken(bearerToken(c.req.header("authorization")))) return c.json({ error: "Unauthorized" }, 401);
2968
- return next();
2969
- };
2970
- app.use("/rpc", requireToken);
2971
- if (fileRoot !== null) {
2972
- app.use("/files/*", requireToken);
2973
- registerFileRoutes(app, fileRoot);
2974
- }
2975
- app.post("/rpc", async (c) => {
2976
- const body = await c.req.json().catch(() => null);
2977
- if (!body || typeof body !== "object" || Array.isArray(body)) return c.json({ error: "Invalid request body" }, 400);
2978
- try {
2979
- const result = await sendToBrowser(body);
2980
- return c.json(result);
2981
- } catch (e) {
2982
- const msg = e instanceof Error ? e.message : String(e);
2983
- return c.json({
2984
- ok: false,
2985
- error: msg
2986
- }, 502);
2987
- }
2988
- });
2989
- app.all("/mcp", async (c) => {
2990
- const token = mcpRequestToken(c.req.header("authorization"), c.req.header("x-mcp-token"));
2991
- if (!verifyMCPToken(token)) return c.json({ error: "Unauthorized" }, 401);
2992
- if (!MCP_METHODS.includes(c.req.method)) return c.json({ error: "Method not allowed" }, {
2993
- status: 405,
2994
- headers: { Allow: MCP_METHODS.join(", ") }
2995
- });
2996
- const sessionId = c.req.header("mcp-session-id") ?? void 0;
2997
- if (sessionId) {
2998
- const existing = mcpSessions.getExistingTransport(sessionId);
2999
- if ("error" in existing) {
3000
- if (existing.error === "closed") return c.json({ error: "MCP server is shutting down" }, 503);
3001
- return c.json({ error: "MCP session not found" }, 404);
3002
- }
3003
- if (c.req.method !== "DELETE") return existing.handleRequest(c.req.raw);
3004
- try {
3005
- return await existing.handleRequest(c.req.raw);
3006
- } finally {
3007
- await mcpSessions.deleteSession(sessionId);
3008
- }
3009
- }
3010
- if (c.req.method !== "POST") return c.json({ error: "Missing MCP session id" }, 400);
3011
- const transport = await mcpSessions.resolveTransport(void 0, sessionOpener(c.req.header(MCP_AGENT_HEADER), c.req.header(MCP_CHAT_HEADER)));
3012
- if ("error" in transport) {
3013
- if (transport.error === "closed") return c.json({ error: "MCP server is shutting down" }, 503);
3014
- return c.json({ error: "Too many active MCP sessions" }, {
3015
- status: 503,
3016
- headers: { "Retry-After": "5" }
3017
- });
3018
- }
3019
- return transport.handleRequest(c.req.raw);
3020
- });
3021
- agentBridge?.routes(app);
3022
- return app;
3023
- }
3024
3085
  function buildServerContext(options) {
3025
3086
  const httpPort = options.httpPort ?? 7600;
3026
3087
  if (options.agents !== void 0 && (options.enableEval ?? false)) process.stderr.write("Warning: enableEval is ignored while the agent bridge is on; eval stays off.\n");
@@ -3101,7 +3162,8 @@ function buildServerContext(options) {
3101
3162
  browserRPC,
3102
3163
  mcpSessions,
3103
3164
  sendToBrowser,
3104
- toolDescriptors
3165
+ toolDescriptors,
3166
+ version: MCP_VERSION
3105
3167
  });
3106
3168
  const wss = new WebSocketServer({ noServer: true });
3107
3169
  return {
@@ -3213,7 +3275,7 @@ async function startServer(options = {}) {
3213
3275
  const resolvedSocketPath = state.socketResult?.resolvedPath ?? null;
3214
3276
  const actualHttpPort = state.tcpResult?.port ?? 0;
3215
3277
  const handle = buildHandle(ctx.app, ctx.wss, ctx.agentBridge, ctx.browserRPC, ctx.mcpSessions, state, resolvedSocketPath, actualHttpPort, ctx.authToken, startedAt);
3216
- armAppAttachWatchdog(options.appAttachTimeoutMs, ctx.browserRPC, handle);
3278
+ armAppAttachWatchdog(options.appAttachTimeoutMs, ctx.browserRPC, handle, options.onAppAttachTimeout);
3217
3279
  return handle;
3218
3280
  }
3219
3281
  const MAX_TIMER_MS = 2147483647;
@@ -3228,7 +3290,7 @@ function validateTimeoutOption(name, timeoutMs) {
3228
3290
  * starts a fresh grace period so renderer reloads can reconnect without
3229
3291
  * leaving a permanently orphaned process behind.
3230
3292
  */
3231
- function armAppAttachWatchdog(timeoutMs, browserRPC, handle) {
3293
+ function armAppAttachWatchdog(timeoutMs, browserRPC, handle, onTimeout) {
3232
3294
  if (timeoutMs === void 0 || timeoutMs === 0) return;
3233
3295
  let timer = null;
3234
3296
  let closing = false;
@@ -3244,7 +3306,8 @@ function armAppAttachWatchdog(timeoutMs, browserRPC, handle) {
3244
3306
  if (browserRPC.isConnected() || closing) return;
3245
3307
  closing = true;
3246
3308
  unsubscribe();
3247
- handle.close().catch((e) => {
3309
+ process.stderr.write(`[MCP] No app attached for ${timeoutMs} ms; closing the server.\n`);
3310
+ handle.close().then(() => onTimeout?.()).catch((e) => {
3248
3311
  console.error("[MCP] Watchdog: failed to close orphaned (no_app) server:", e);
3249
3312
  });
3250
3313
  }, timeoutMs);
@@ -3256,6 +3319,6 @@ function armAppAttachWatchdog(timeoutMs, browserRPC, handle) {
3256
3319
  });
3257
3320
  }
3258
3321
  //#endregion
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 };
3322
+ export { resolveCORSOrigins as a, registerSkill as c, devAgentBridgeFromEnv as d, pairingFingerprint as f, DEFAULT_CONNECT_APP_URL as i, fail as l, startServer as n, MCP_AGENT_KINDS as o, createServerInstructions as r, registerTools as s, MCP_VERSION as t, ok as u };
3260
3323
 
3261
- //# sourceMappingURL=server-Byl3Tcf4.mjs.map
3324
+ //# sourceMappingURL=server-DfBiXAjt.mjs.map