@pairdraw/mcp 0.21.1 → 0.22.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.
package/dist/connect.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import "./rolldown-runtime-ClRpJifh.mjs";
3
- import { a as resolveCORSOrigins, f as pairingFingerprint, i as DEFAULT_CONNECT_APP_URL, n as startServer, t as MCP_VERSION } from "./server-C2X4PLPJ.mjs";
3
+ import { a as resolveCORSOrigins, f as pairingFingerprint, i as DEFAULT_CONNECT_APP_URL, n as startServer, t as MCP_VERSION } from "./server-BHPENxBB.mjs";
4
4
  import { n as getCompanionDir } from "./paths-BpcXnrbP.mjs";
5
5
  import { t as resolveMCPRoot } from "./root-BzmoiT2g.mjs";
6
6
  import { i as readToolPolicyFromEnv } from "./policy-CVfvvMB7.mjs";
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import "./rolldown-runtime-ClRpJifh.mjs";
3
- import { a as resolveCORSOrigins, d as devAgentBridgeFromEnv, n as startServer, t as MCP_VERSION } from "./server-C2X4PLPJ.mjs";
3
+ import { a as resolveCORSOrigins, d as devAgentBridgeFromEnv, n as startServer, t as MCP_VERSION } from "./server-BHPENxBB.mjs";
4
4
  import { t as resolveMCPRoot } from "./root-BzmoiT2g.mjs";
5
5
  import { i as readToolPolicyFromEnv } from "./policy-CVfvvMB7.mjs";
6
6
  //#region src/index.ts
@@ -1537,6 +1537,17 @@ function ok(data, toolName) {
1537
1537
  text
1538
1538
  }] };
1539
1539
  }
1540
+ /** A picture a client can see, with the text a client that ignores images assigns to it. */
1541
+ function imageResult(data, mimeType, summary) {
1542
+ return { content: [{
1543
+ type: "text",
1544
+ text: summary
1545
+ }, {
1546
+ type: "image",
1547
+ data,
1548
+ mimeType
1549
+ }] };
1550
+ }
1540
1551
  function fail(e) {
1541
1552
  const msg = e instanceof Error ? e.message : String(e);
1542
1553
  return {
@@ -1547,6 +1558,13 @@ function fail(e) {
1547
1558
  isError: true
1548
1559
  };
1549
1560
  }
1561
+ /** The bytes a Base64 string decodes to, from its own length, without decoding it. */
1562
+ function decodedBase64Bytes(base64) {
1563
+ let padding = 0;
1564
+ if (base64.endsWith("==")) padding = 2;
1565
+ else if (base64.endsWith("=")) padding = 1;
1566
+ return Math.max(0, Math.floor(base64.length * 3 / 4) - padding);
1567
+ }
1550
1568
  //#endregion
1551
1569
  //#region src/tool/output.ts
1552
1570
  /** Returns true for filesystem errors that indicate a missing or unresolvable path (ENOENT, ENOTDIR, ELOOP). */
@@ -1881,7 +1899,7 @@ function sessionNotFound() {
1881
1899
  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: [...] }`. A gradient effect takes `stops` as `{ color, position }` pairs, and an effect that draws on a shape takes `shape` as JSON such as `'{\"type\":\"sphere3D\",\"radius\":0.35}'`. The app's gallery starts one from 21 complete presets, including `liquidChrome`, `flutedGlass`, `paperStock`, `godRays`, `thermal`, `voronoiCells`, `deepWater`, `smokePlume`, `neonPulse`, `grainWash`, `obsidian`, and `marbleInk`. The canvas shows the shader's first frame, preview plays the shaders on screen, 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` (`underline` or `strikethrough`), and `textCase` (`original`, `upper`, `lower`, `title`). Decoration details 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- A name that more than one component or component set has joins the component set when the props select one of its variants, and otherwise the first one; the warning lists each candidate’s ID and naming one by its ID always picks it.\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 `Tabs.Root` in a component set can name the set's variant property in `modelValue`, so a trigger chooses that variant; the property's options must be the trigger words, and every variant draws the same triggers. 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`, `noise`, `texture`, `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`.";
1882
1900
  //#endregion
1883
1901
  //#region ../../skills/pairdraw/SKILL.md?raw
1884
- 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\npairdraw tokens design.fig --check src/app.css # list tokens that differ from code; exits 1 on drift\npairdraw tokens design.fig --sync src/app.css --write # bring code-only changes in; canvas edits are kept\n```\n\n### Check a pull request\n\n```bash\npairdraw check designs/home.pen designs/settings.fig --out pairdraw-report # renders, token drift, design-memory findings\npairdraw check designs/home.pen --base .pairdraw-base --fail-on error # only findings this change introduced fail\n```\n\nThe repository's `.github/actions/pairdraw-check` action wraps it for a pull request: one comment, updated in place.\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 flow.fig -f gif --start \"Hero 1\" -o hero.gif # record the prototype's After delay chain\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\nA document can keep a design memory: the colors, fonts, font sizes, spacing and corner radii its designs may use (its own variables and styles plus values the person allowed), decisions written down about them, and frames pinned as examples. Read it before you design in the document. Through Pairdraw's agent surfaces (MCP, the app's chat and coding agents, `pairdraw agent`), an edit that brings in a color or font the memory does not allow is undone, and the error names the nearest allowed values; new sizes, spacing and radii off its scale go through with a warning in the result. A color you write is judged even when the document already uses it elsewhere; values kept on layers you duplicate, group, flatten or convert are not refused, and Pairdraw's defaults for new layers only warn, so give layers allowed colors rather than leaving the defaults. A variable or style you create, change or rescope is judged on every value it would let in, and the memory itself can only gain decisions and examples, so propose a new value with `record_design_decision` and let the person allow it:\n\n```bash\npairdraw design-memory design.fig\npairdraw eval design.fig -c 'pairdraw.checkDesignValues({ colors: [\"#FF00AA\"], spacing: [13] })'\npairdraw tool call record_design_decision design.fig --args '{\"text\": \"Cards use 16 px padding.\"}' --write\n```\n\nOver MCP the same is `get_design_memory`, `check_design_values`, and `record_design_decision`. CLI commands such as `pairdraw tool call` and `pairdraw eval` count as the person running them: they only warn about values outside the memory, unless `pairdraw tool call --enforce-design-memory` asks to refuse.\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_css`, `get_jsx`, `diff_jsx`, `diff_create`, `diff_visual`, `describe`, `check_responsive`, `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`, `export_video`, 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- **`get_css`** — a node subtree as compact CSS-like lines: `Name#id W×H {flex:row;gap:12px;padding:16px 24px;bg:var(--color/brand, #4F46E5);radius:8px}`, with `font:600 14px/20px Inter` for text, lengths in px, and `max_bytes` to stop at what the task needs. Use it to read geometry and style; the setters take the same shorthand (`padding: \"16px 24px\"`, `gap: \"12px 4px\"`, `radius: \"12px 0 12px 0\"`, `set_fill { color: \"var(--color/brand)\" }` binds the token). `describe` answers roles and design issues instead.\n- **`describe`** — semantic analysis of role, visual style, layout, and design issues.\n- **`batch_update`** — apply multiple node updates efficiently.\n- **`set_reactions` / `get_reactions`** — prototype interactions in Figma's plugin shape: triggers `ON_CLICK`, `ON_HOVER`, `ON_PRESS`, `MOUSE_ENTER` / `MOUSE_LEAVE` (with `delay`), and `AFTER_TIMEOUT` (with `timeout`, seconds); actions `NODE` with `navigation` `NAVIGATE` / `OVERLAY` / `CHANGE_TO` / `SCROLL_TO` and a `transition` (`INSTANT`, `DISSOLVE`, or `SMART_ANIMATE` with `duration` and `easing`), plus `BACK` and `CLOSE`. For interactive components, set `{ trigger: { type: \"ON_HOVER\" }, actions: [{ type: \"NODE\", navigation: \"CHANGE_TO\", destinationId: \"<Hover variant id>\" }] }` once on the Default variant and every instance plays it; `SCROLL_TO` points at a layer in the same screen, and `update_node { overflow_direction: \"VERTICAL\" }` (or `HORIZONTAL` / `BOTH`) makes a clipping frame scroll in play. `ON_HOVER` and `ON_PRESS` undo their action when the pointer leaves or lifts, and Smart animate moves layers that share a name and place between the two frames or variants.\n- **`list_fonts` / `replace_fonts`** — `list_fonts { scope: \"document\" }` reports every face used anywhere with `missing` and `layerCount`, missing first; swap faces with `replace_fonts { replacements: [{ from: { family, style }, to: { family, style } }] }`, which changes text layers, character runs, and text styles in one undo step.\n- **`token_drift` / `sync_tokens`** — compare or import CSS custom properties, a Tailwind v4 `@theme`, shadcn/ui stylesheets, or W3C design token files; `token_drift { include_layers: true }` also lists layers with raw token values, and `sync_tokens { conflicts: \"skip\" | \"code\" | \"canvas\" }` decides what a token changed on both sides takes.\n- **`export_image` / `export_svg` / `export_pdf`** — visual verification and deliverables; `export_image` takes `quality` (1–100) for JPG and WEBP.\n- **`export_video`** — records the prototype from a start frame, following After delays with their Dissolve and Smart animate transitions (and scripted `clicks`) on a virtual clock, as MP4 (default), GIF, or WebM; check the returned `steps`, and pass `path` for the file. It is long-running: cancelling the request stops the recording and returns no file. MP4 and WebM need the app's WebCodecs or, headless, `ffmpeg` on the path; otherwise ask for a GIF.\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- **`create_variations` / `list_variations` / `pick_variation`** — versions of a layer to compare; the person keeps one with Use this, which replaces the original in place (same id, name, and spot). When asked for several versions of a layer:\n 1. Call `create_variations` once with the layer's id, a count from 1 to 8, and one short label per version naming the idea it tries.\n 2. Change each version in its own direction by editing the layers inside it: `batch_update`, `set_*`, or `render` with `parent_id` or `replace_id` inside the version.\n 3. Keep each version's root layer: a version whose root becomes another kind of layer (a frame where an instance was) cannot replace the original.\n 4. Check them together with one `export_image` of the set.\n 5. Leave the choice to the person; call `pick_variation` only when they ask you to pick or discard.\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- Use `check_responsive { id, widths }` to lay out a copy of a frame at phone, tablet, and desktop widths: it returns one render per width and the text overflow, layers outside the frame, and overlapping siblings found there, without touching the document.\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 on the current page (MCP `analyze_colors` uses the same scope).\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";
1902
+ 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\npairdraw tokens design.fig --check src/app.css # list tokens that differ from code; exits 1 on drift\npairdraw tokens design.fig --sync src/app.css --write # bring code-only changes in; canvas edits are kept\n```\n\n### Check a pull request\n\n```bash\npairdraw check designs/home.pen designs/settings.fig --out pairdraw-report # renders, token drift, design-memory findings\npairdraw check designs/home.pen --base .pairdraw-base --fail-on error # only findings this change introduced fail\n```\n\nThe repository's `.github/actions/pairdraw-check` action wraps it for a pull request: one comment, updated in place.\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 flow.fig -f gif --start \"Hero 1\" -o hero.gif # record the prototype's After delay chain\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\nA document can keep a design memory: the colors, fonts, font sizes, spacing and corner radii its designs may use (its own variables and styles plus values the person allowed), decisions written down about them, and frames pinned as examples. Read it before you design in the document. Through Pairdraw's agent surfaces (MCP, the app's chat and coding agents, `pairdraw agent`), an edit that brings in a color or font the memory does not allow is undone, and the error names the nearest allowed values; new sizes, spacing and radii off its scale go through with a warning in the result. A color you write is judged even when the document already uses it elsewhere; values kept on layers you duplicate, group, flatten or convert are not refused, and Pairdraw's defaults for new layers only warn, so give layers allowed colors rather than leaving the defaults. A variable or style you create, change or rescope is judged on every value it would let in, and the memory itself can only gain decisions and examples, so propose a new value with `record_design_decision` and let the person allow it:\n\n```bash\npairdraw design-memory design.fig\npairdraw eval design.fig -c 'pairdraw.checkDesignValues({ colors: [\"#FF00AA\"], spacing: [13] })'\npairdraw tool call record_design_decision design.fig --args '{\"text\": \"Cards use 16 px padding.\"}' --write\n```\n\nOver MCP the same is `get_design_memory`, `check_design_values`, and `record_design_decision`. CLI commands such as `pairdraw tool call` and `pairdraw eval` count as the person running them: they only warn about values outside the memory, unless `pairdraw tool call --enforce-design-memory` asks to refuse.\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_css`, `get_jsx`, `diff_jsx`, `diff_create`, `diff_visual`, `describe`, `check_responsive`, `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`, `export_video`, 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- **`get_css`** — a node subtree as compact CSS-like lines: `Name#id W×H {flex:row;gap:12px;padding:16px 24px;bg:var(--color/brand, #4F46E5);radius:8px}`, with `font:600 14px/20px Inter` for text, lengths in px, and `max_bytes` to stop at what the task needs. Use it to read geometry and style; the setters take the same shorthand (`padding: \"16px 24px\"`, `gap: \"12px 4px\"`, `radius: \"12px 0 12px 0\"`, `set_fill { color: \"var(--color/brand)\" }` binds the token). `describe` answers roles and design issues instead.\n- **`describe`** — semantic analysis of role, visual style, layout, and design issues.\n- **`batch_update`** — apply multiple node updates efficiently.\n- **`set_reactions` / `get_reactions`** — prototype interactions in Figma's plugin shape: triggers `ON_CLICK`, `ON_HOVER`, `ON_PRESS`, `MOUSE_ENTER` / `MOUSE_LEAVE` (with `delay`), and `AFTER_TIMEOUT` (with `timeout`, seconds); actions `NODE` with `navigation` `NAVIGATE` / `OVERLAY` / `CHANGE_TO` / `SCROLL_TO` and a `transition` (`INSTANT`, `DISSOLVE`, or `SMART_ANIMATE` with `duration` and `easing`), plus `BACK` and `CLOSE`. For interactive components, set `{ trigger: { type: \"ON_HOVER\" }, actions: [{ type: \"NODE\", navigation: \"CHANGE_TO\", destinationId: \"<Hover variant id>\" }] }` once on the Default variant and every instance plays it; `SCROLL_TO` points at a layer in the same screen, and `update_node { overflow_direction: \"VERTICAL\" }` (or `HORIZONTAL` / `BOTH`) makes a clipping frame scroll in play. `ON_HOVER` and `ON_PRESS` undo their action when the pointer leaves or lifts, and Smart animate moves layers that share a name and place between the two frames or variants.\n- **`list_fonts` / `replace_fonts`** — `list_fonts { scope: \"document\" }` reports every face used anywhere with `missing` and `layerCount`, missing first; swap faces with `replace_fonts { replacements: [{ from: { family, style }, to: { family, style } }] }`, which changes text layers, character runs, and text styles in one undo step.\n- **`token_drift` / `sync_tokens`** — compare or import CSS custom properties, a Tailwind v4 `@theme`, shadcn/ui stylesheets, or W3C design token files; `token_drift { include_layers: true }` also lists layers with raw token values, and `sync_tokens { conflicts: \"skip\" | \"code\" | \"canvas\" }` decides what a token changed on both sides takes.\n- **`export_image` / `export_svg` / `export_pdf`** — visual verification and deliverables; `export_image` takes `quality` (1–100) for JPG and WEBP.\n- **`export_video`** — records the prototype from a start frame, following After delays with their Dissolve and Smart animate transitions (and scripted `clicks`) on a virtual clock, as MP4 (default), GIF, or WebM; check the returned `steps`, and pass `path` for the file. It is long-running: cancelling the request stops the recording and returns no file. MP4 and WebM need the app's WebCodecs or, headless, `ffmpeg` on the path; otherwise ask for a GIF.\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- **`import_code`** — React or JSX source with Tailwind classes or inline styles, or HTML with CSS, as editable layers. Nothing in the source runs: components it does not define become named frames, expressions that need their caller become placeholder text, and the returned `report` counts both.\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- **`create_variations` / `list_variations` / `pick_variation`** — versions of a layer to compare; the person keeps one with Use this, which replaces the original in place (same id, name, and spot). When asked for several versions of a layer:\n 1. Call `create_variations` once with the layer's id, a count from 1 to 8, and one short label per version naming the idea it tries.\n 2. Change each version in its own direction by editing the layers inside it: `batch_update`, `set_*`, or `render` with `parent_id` or `replace_id` inside the version.\n 3. Keep each version's root layer: a version whose root becomes another kind of layer (a frame where an instance was) cannot replace the original.\n 4. Check them together with one `export_image` of the set.\n 5. Leave the choice to the person; call `pick_variation` only when they ask you to pick or discard.\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_range_style`** — line height, letter spacing, letter case, or decoration for a character range; `start`/`end` are UTF-16 code units, as the editor's text ranges are.\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- Use `check_responsive { id, widths }` to lay out a copy of a frame at phone, tablet, and desktop widths: it returns one render per width and the text overflow, layers outside the frame, and overlapping siblings found there, without touching the document.\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 on the current page (MCP `analyze_colors` uses the same scope).\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";
1885
1903
  //#endregion
1886
1904
  //#region src/skill/content.ts
1887
1905
  /** The skill's name, as its frontmatter and `npx skills add` know it. */
@@ -1975,7 +1993,7 @@ function registerBrowserTools(register, sendRPC) {
1975
1993
  });
1976
1994
  register("browser_screenshot", { inputSchema: v.strictObject({ kind: browserShotKind }) }, async (args) => {
1977
1995
  try {
1978
- return pngResult((await sendCommand(sendRPC, "browser_screenshot", { kind: args.kind })).result);
1996
+ return pngResult((await sendCommand(sendRPC, "browser_screenshot", { kind: args.kind })).result, args.kind);
1979
1997
  } catch (e) {
1980
1998
  return fail(e);
1981
1999
  }
@@ -2037,15 +2055,11 @@ function snapshotLayer(result) {
2037
2055
  return typeof result.id === "string" && result.id !== "" ? { id: result.id } : {};
2038
2056
  }
2039
2057
  /** A browser screenshot is an image. Anything else is the same failure the window reports. */
2040
- function pngResult(result) {
2058
+ function pngResult(result, kind) {
2041
2059
  if (!isPNGResult(result)) return fail(/* @__PURE__ */ new Error("The page returned no picture"));
2042
2060
  const bytes = Buffer$1.byteLength(result.base64, "utf8");
2043
2061
  if (bytes > 9e5) return fail(new Error(resultTooLargeMessage("Image from \"browser_screenshot\"", bytes, "Screenshot the view, or one element, instead of the whole page.")));
2044
- return { content: [{
2045
- type: "image",
2046
- data: result.base64,
2047
- mimeType: "image/png"
2048
- }] };
2062
+ return imageResult(result.base64, "image/png", `Screenshot of the ${kind} page from "browser_screenshot" (${Math.ceil(decodedBase64Bytes(result.base64) / 1024)} KB, image/png).`);
2049
2063
  }
2050
2064
  function isPNGResult(result) {
2051
2065
  if (!result || typeof result !== "object") return false;
@@ -2192,11 +2206,8 @@ function registerTools(mcpServer, options) {
2192
2206
  const base64 = String(r.base64);
2193
2207
  const bytes = Buffer$1.byteLength(base64, "utf8");
2194
2208
  if (bytes > 9e5) return fail(new Error(resultTooLargeMessage(`Image from "${def.name}"`, bytes, "Export a smaller region or lower the scale/resolution.")));
2195
- return { content: [{
2196
- type: "image",
2197
- data: base64,
2198
- mimeType: r.mimeType
2199
- }] };
2209
+ const facts = Object.fromEntries(Object.entries(r).filter(([key]) => key !== "base64"));
2210
+ return imageResult(base64, r.mimeType, `Image from "${def.name}": ${JSON.stringify(facts)}`);
2200
2211
  }
2201
2212
  return ok(r, def.name);
2202
2213
  } catch (e) {
@@ -2265,6 +2276,7 @@ function registerTools(mcpServer, options) {
2265
2276
  if (res.ok === false) return fail(new Error(res.error));
2266
2277
  const response = { opened: true };
2267
2278
  if (res.target) response.target = res.target;
2279
+ if (res.result?.diagnostics !== void 0) response.diagnostics = res.result.diagnostics;
2268
2280
  return ok(response);
2269
2281
  } catch (e) {
2270
2282
  return fail(e);
@@ -2878,7 +2890,7 @@ function createServerInstructions({ policy, filesystemEnabled, agentKind }) {
2878
2890
  }
2879
2891
  //#endregion
2880
2892
  //#region package.json
2881
- var version = "0.21.1";
2893
+ var version = "0.22.0";
2882
2894
  //#endregion
2883
2895
  //#region src/server/connections.ts
2884
2896
  const HEARTBEAT_INTERVAL_MS = 5e3;
@@ -3414,4 +3426,4 @@ function armAppAttachWatchdog(timeoutMs, browserRPC, handle, onTimeout, hasClien
3414
3426
  //#endregion
3415
3427
  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 };
3416
3428
 
3417
- //# sourceMappingURL=server-C2X4PLPJ.mjs.map
3429
+ //# sourceMappingURL=server-BHPENxBB.mjs.map