Skip to content

AI-native design editor. Open-source Figma alternative.

Add CLI-to-app RPC bridge for live document access

Danila Poyarkove7e5f53b5710
diff --git a/packages/cli/src/app-client.ts b/packages/cli/src/app-client.ts
new file mode 100644
index 000000000..f45145918
--- /dev/null
+++ b/packages/cli/src/app-client.ts
@@ -0,0 +1,50 @@
+const AUTOMATION_PORT = 7600
+const HEALTH_URL = `http://127.0.0.1:${AUTOMATION_PORT}/health`
+const RPC_URL = `http://127.0.0.1:${AUTOMATION_PORT}/rpc`
+
+let cachedToken: string | null = null
+
+export async function getAppToken(): Promise<string> {
+ if (cachedToken) return cachedToken
+ const res = await fetch(HEALTH_URL).catch(() => null)
+ if (!res || !res.ok) {
+ throw new Error(
+ 'Could not connect to OpenPencil app on localhost:7600.\n' +
+ 'Is the app running? Start it with: bun run tauri dev'
+ )
+ }
+ const data = (await res.json()) as { status: string; token?: string }
+ if (data.status !== 'ok' || !data.token) {
+ throw new Error(
+ 'OpenPencil app is running but no document is open.\n' +
+ 'Open a document in the app, or provide a .fig file path.'
+ )
+ }
+ cachedToken = data.token
+ return cachedToken
+}
+
+export async function rpc<T = unknown>(command: string, args: unknown = {}): Promise<T> {
+ const token = await getAppToken()
+ const res = await fetch(RPC_URL, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${token}`
+ },
+ body: JSON.stringify({ command, args })
+ })
+
+ if (!res.ok) {
+ const body = (await res.json().catch(() => ({ error: `HTTP ${res.status}` }))) as { error?: string; ok?: boolean }
+ throw new Error(body.error ?? `RPC failed: HTTP ${res.status}`)
+ }
+
+ const body = (await res.json()) as { ok?: boolean; result?: T; error?: string }
+ if (body.ok === false) throw new Error(body.error ?? 'RPC failed')
+ return body.result as T
+}
+
+export function isAppMode(file?: string): boolean {
+ return !file
+}
diff --git a/packages/cli/src/commands/analyze/clusters.ts b/packages/cli/src/commands/analyze/clusters.ts
index 530bb67f0..60833ded4 100644
--- a/packages/cli/src/commands/analyze/clusters.ts
+++ b/packages/cli/src/commands/analyze/clusters.ts
@@ -1,41 +1,13 @@
import { defineCommand } from 'citty'
import { loadDocument } from '../../headless'
+import { isAppMode, rpc } from '../../app-client'
import { bold, fmtList, fmtSummary } from '../../format'
-import type { SceneNode, SceneGraph } from '@open-pencil/core'
-
-interface ClusterNode {
- id: string
- name: string
- type: string
- width: number
- height: number
- childCount: number
-}
-
-interface Cluster {
- signature: string
- nodes: ClusterNode[]
-}
+import { executeRpcCommand } from '@open-pencil/core'
-function buildSignature(graph: SceneGraph, node: SceneNode): string {
- const childTypes = new Map<string, number>()
- for (const childId of node.childIds) {
- const child = graph.getNode(childId)
- if (!child) continue
- childTypes.set(child.type, (childTypes.get(child.type) ?? 0) + 1)
- }
- const childPart = [...childTypes.entries()]
- .sort((a, b) => a[0].localeCompare(b[0]))
- .map(([t, c]) => `${t}:${c}`)
- .join(',')
-
- const w = Math.round(node.width / 10) * 10
- const h = Math.round(node.height / 10) * 10
- return `${node.type}:${w}x${h}|${childPart}`
-}
+import type { AnalyzeClustersResult } from '@open-pencil/core'
-function calcConfidence(nodes: ClusterNode[]): number {
+function calcConfidence(nodes: Array<{ width: number; height: number; childCount: number }>): number {
if (nodes.length < 2) return 100
const base = nodes[0]!
let score = 0
@@ -67,63 +39,31 @@ function formatSignature(sig: string): string {
return `${typeName} > [${childParts.join(', ')}]`
}
-function findClusters(
- graph: SceneGraph,
- minSize: number,
- minCount: number
-): { clusters: Cluster[]; totalNodes: number } {
- const sigMap = new Map<string, ClusterNode[]>()
- let totalNodes = 0
-
- for (const node of graph.getAllNodes()) {
- if (node.type === 'CANVAS') continue
- totalNodes++
- if (node.width < minSize || node.height < minSize) continue
- if (node.childIds.length === 0) continue
-
- const sig = buildSignature(graph, node)
- const arr = sigMap.get(sig) ?? []
- arr.push({
- id: node.id,
- name: node.name,
- type: node.type,
- width: Math.round(node.width),
- height: Math.round(node.height),
- childCount: node.childIds.length
- })
- sigMap.set(sig, arr)
- }
-
- const clusters = [...sigMap.entries()]
- .filter(([, nodes]) => nodes.length >= minCount)
- .map(([signature, nodes]) => ({ signature, nodes }))
- .sort((a, b) => b.nodes.length - a.nodes.length)
-
- return { clusters, totalNodes }
+async function getData(file: string | undefined, args: { limit?: string; 'min-size'?: string; 'min-count'?: string }): Promise<AnalyzeClustersResult> {
+ const rpcArgs = { limit: Number(args.limit ?? 20), minSize: Number(args['min-size'] ?? 30), minCount: Number(args['min-count'] ?? 2) }
+ if (isAppMode(file)) return rpc<AnalyzeClustersResult>('analyze_clusters', rpcArgs)
+ const graph = await loadDocument(file!)
+ return executeRpcCommand(graph, 'analyze_clusters', rpcArgs) as AnalyzeClustersResult
}
export default defineCommand({
meta: { description: 'Find repeated design patterns (potential components)' },
args: {
- file: { type: 'positional', description: '.fig file path', required: true },
+ file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },
limit: { type: 'string', description: 'Max clusters to show', default: '20' },
'min-size': { type: 'string', description: 'Min node size in px', default: '30' },
'min-count': { type: 'string', description: 'Min instances to form cluster', default: '2' },
json: { type: 'boolean', description: 'Output as JSON' }
},
async run({ args }) {
- const graph = await loadDocument(args.file)
- const limit = Number(args.limit)
- const minSize = Number(args['min-size'])
- const minCount = Number(args['min-count'])
- const { clusters, totalNodes } = findClusters(graph, minSize, minCount)
+ const data = await getData(args.file, args)
if (args.json) {
- console.log(JSON.stringify({ clusters: clusters.slice(0, limit), totalNodes }, null, 2))
+ console.log(JSON.stringify(data, null, 2))
return
}
- if (clusters.length === 0) {
+ if (data.clusters.length === 0) {
console.log('No repeated patterns found.')
return
}
@@ -132,7 +72,7 @@ export default defineCommand({
console.log(bold(' Repeated patterns'))
console.log('')
- const items = clusters.slice(0, limit).map((c) => {
+ const items = data.clusters.map((c) => {
const first = c.nodes[0]!
const confidence = calcConfidence(c.nodes)
@@ -160,11 +100,11 @@ export default defineCommand({
console.log(fmtList(items, { numbered: true }))
- const clusteredNodes = clusters.reduce((sum, c) => sum + c.nodes.length, 0)
+ const clusteredNodes = data.clusters.reduce((sum, c) => sum + c.nodes.length, 0)
console.log('')
console.log(
- fmtSummary({ clusters: clusters.length }) +
- ` from ${totalNodes} nodes (${clusteredNodes} clustered)`
+ fmtSummary({ clusters: data.clusters.length }) +
+ ` from ${data.totalNodes} nodes (${clusteredNodes} clustered)`
)
console.log('')
}
diff --git a/packages/cli/src/commands/analyze/colors.ts b/packages/cli/src/commands/analyze/colors.ts
index ecc482892..e4ab811b8 100644
--- a/packages/cli/src/commands/analyze/colors.ts
+++ b/packages/cli/src/commands/analyze/colors.ts
@@ -1,164 +1,43 @@
import { defineCommand } from 'citty'
import { loadDocument } from '../../headless'
+import { isAppMode, rpc } from '../../app-client'
import { bold, fmtHistogram, fmtList, fmtSummary } from '../../format'
-import type { SceneGraph } from '@open-pencil/core'
+import { executeRpcCommand } from '@open-pencil/core'
-interface ColorInfo {
- hex: string
- count: number
- variableName: string | null
-}
-
-function toHex(r: number, g: number, b: number): string {
- return (
- '#' +
- [r, g, b]
- .map((c) =>
- Math.round(c * 255)
- .toString(16)
- .padStart(2, '0')
- )
- .join('')
- )
-}
-
-function hexToRgb(hex: string): [number, number, number] {
- const clean = hex.replace('#', '')
- return [
- parseInt(clean.slice(0, 2), 16),
- parseInt(clean.slice(2, 4), 16),
- parseInt(clean.slice(4, 6), 16)
- ]
-}
-
-function colorDistance(hex1: string, hex2: string): number {
- const [r1, g1, b1] = hexToRgb(hex1)
- const [r2, g2, b2] = hexToRgb(hex2)
- return Math.sqrt((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2)
-}
-
-interface Cluster {
- colors: ColorInfo[]
- suggestedHex: string
- totalCount: number
-}
-
-function clusterColors(colors: ColorInfo[], threshold: number): Cluster[] {
- const clusters: Cluster[] = []
- const used = new Set<string>()
- const sorted = [...colors].sort((a, b) => b.count - a.count)
-
- for (const color of sorted) {
- if (used.has(color.hex)) continue
-
- const cluster: Cluster = {
- colors: [color],
- suggestedHex: color.hex,
- totalCount: color.count
- }
- used.add(color.hex)
-
- for (const other of sorted) {
- if (used.has(other.hex)) continue
- if (colorDistance(color.hex, other.hex) <= threshold) {
- cluster.colors.push(other)
- cluster.totalCount += other.count
- used.add(other.hex)
- }
- }
-
- if (cluster.colors.length > 1) clusters.push(cluster)
- }
+import type { AnalyzeColorsResult } from '@open-pencil/core'
- return clusters.sort((a, b) => b.colors.length - a.colors.length)
-}
-
-function collectColors(graph: SceneGraph): { colors: ColorInfo[]; totalNodes: number } {
- const colorMap = new Map<string, ColorInfo>()
- let totalNodes = 0
-
- const addColor = (hex: string, variableName: string | null) => {
- const existing = colorMap.get(hex)
- if (existing) {
- existing.count++
- if (variableName && !existing.variableName) existing.variableName = variableName
- } else {
- colorMap.set(hex, { hex, count: 1, variableName })
- }
- }
-
- for (const node of graph.getAllNodes()) {
- if (node.type === 'CANVAS') continue
- totalNodes++
-
- for (const fill of node.fills) {
- if (!fill.visible || fill.type !== 'SOLID') continue
- const hex = toHex(fill.color.r, fill.color.g, fill.color.b)
- addColor(hex, null)
- }
-
- for (const stroke of node.strokes) {
- if (!stroke.visible) continue
- const hex = toHex(stroke.color.r, stroke.color.g, stroke.color.b)
- addColor(hex, null)
- }
-
- for (const effect of node.effects) {
- if (!effect.visible) continue
- const hex = toHex(effect.color.r, effect.color.g, effect.color.b)
- addColor(hex, null)
- }
-
- for (const [field, varId] of Object.entries(node.boundVariables)) {
- if (!field.includes('fill') && !field.includes('stroke') && !field.includes('color'))
- continue
- const variable = graph.variables.get(varId)
- if (variable) {
- const resolvedColor = graph.resolveColorVariable(varId)
- if (resolvedColor) {
- const hex = toHex(resolvedColor.r, resolvedColor.g, resolvedColor.b)
- const existing = colorMap.get(hex)
- if (existing) existing.variableName = variable.name
- }
- }
- }
- }
-
- return { colors: [...colorMap.values()], totalNodes }
+async function getData(file: string | undefined, args: { limit?: string; threshold?: string; similar?: boolean }): Promise<AnalyzeColorsResult> {
+ const rpcArgs = { limit: Number(args.limit ?? 30), threshold: Number(args.threshold ?? 15), similar: args.similar }
+ if (isAppMode(file)) return rpc<AnalyzeColorsResult>('analyze_colors', rpcArgs)
+ const graph = await loadDocument(file!)
+ return executeRpcCommand(graph, 'analyze_colors', rpcArgs) as AnalyzeColorsResult
}
export default defineCommand({
meta: { description: 'Analyze color palette usage' },
args: {
- file: { type: 'positional', description: '.fig file path', required: true },
+ file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },
limit: { type: 'string', description: 'Max colors to show', default: '30' },
- threshold: {
- type: 'string',
- description: 'Distance threshold for clustering similar colors (0–50)',
- default: '15'
- },
+ threshold: { type: 'string', description: 'Distance threshold for clustering similar colors (0–50)', default: '15' },
similar: { type: 'boolean', description: 'Show similar color clusters' },
json: { type: 'boolean', description: 'Output as JSON' }
},
async run({ args }) {
- const graph = await loadDocument(args.file)
+ const data = await getData(args.file, args)
const limit = Number(args.limit)
- const threshold = Number(args.threshold)
- const { colors, totalNodes } = collectColors(graph)
if (args.json) {
- const clusters = args.similar ? clusterColors(colors, threshold) : []
- console.log(JSON.stringify({ colors, totalNodes, clusters }, null, 2))
+ console.log(JSON.stringify(data, null, 2))
return
}
- if (colors.length === 0) {
+ if (data.colors.length === 0) {
console.log('No colors found.')
return
}
- const sorted = colors.sort((a, b) => b.count - a.count).slice(0, limit)
+ const sorted = data.colors.slice(0, limit)
console.log('')
console.log(bold(' Colors by usage'))
@@ -173,29 +52,26 @@ export default defineCommand({
)
)
- const hardcoded = colors.filter((c) => !c.variableName)
- const fromVars = colors.filter((c) => c.variableName)
+ const hardcoded = data.colors.filter((c) => !c.variableName)
+ const fromVars = data.colors.filter((c) => c.variableName)
console.log('')
console.log(
- fmtSummary({ 'unique colors': colors.length, 'from variables': fromVars.length, hardcoded: hardcoded.length })
+ fmtSummary({ 'unique colors': data.colors.length, 'from variables': fromVars.length, hardcoded: hardcoded.length })
)
- if (args.similar) {
- const clusters = clusterColors(hardcoded, threshold)
- if (clusters.length > 0) {
- console.log('')
- console.log(bold(' Similar colors (consider merging)'))
- console.log('')
- console.log(
- fmtList(
- clusters.slice(0, 10).map((cluster) => ({
- header: cluster.colors.map((c) => c.hex).join(', '),
- details: { suggest: cluster.suggestedHex, total: `${cluster.totalCount}×` }
- }))
- )
+ if (args.similar && data.clusters.length > 0) {
+ console.log('')
+ console.log(bold(' Similar colors (consider merging)'))
+ console.log('')
+ console.log(
+ fmtList(
+ data.clusters.slice(0, 10).map((cluster) => ({
+ header: cluster.colors.map((c) => c.hex).join(', '),
+ details: { suggest: cluster.suggestedHex, total: `${cluster.totalCount}×` }
+ }))
)
- }
+ )
}
console.log('')
diff --git a/packages/cli/src/commands/analyze/spacing.ts b/packages/cli/src/commands/analyze/spacing.ts
index 3a091b48a..6dee18c9b 100644
--- a/packages/cli/src/commands/analyze/spacing.ts
+++ b/packages/cli/src/commands/analyze/spacing.ts
@@ -1,73 +1,42 @@
import { defineCommand } from 'citty'
import { loadDocument } from '../../headless'
+import { isAppMode, rpc } from '../../app-client'
import { bold, kv, fmtHistogram, fmtSummary } from '../../format'
-import type { SceneGraph } from '@open-pencil/core'
+import { executeRpcCommand } from '@open-pencil/core'
-interface SpacingValue {
- value: number
- count: number
-}
-
-function collectSpacing(graph: SceneGraph): {
- gaps: SpacingValue[]
- paddings: SpacingValue[]
- totalNodes: number
-} {
- const gapMap = new Map<number, number>()
- const paddingMap = new Map<number, number>()
- let totalNodes = 0
-
- for (const node of graph.getAllNodes()) {
- if (node.type === 'CANVAS') continue
- if (node.layoutMode === 'NONE') continue
- totalNodes++
-
- if (node.itemSpacing > 0) {
- gapMap.set(node.itemSpacing, (gapMap.get(node.itemSpacing) ?? 0) + 1)
- }
- if (node.counterAxisSpacing > 0) {
- gapMap.set(node.counterAxisSpacing, (gapMap.get(node.counterAxisSpacing) ?? 0) + 1)
- }
-
- for (const pad of [node.paddingTop, node.paddingRight, node.paddingBottom, node.paddingLeft]) {
- if (pad > 0) paddingMap.set(pad, (paddingMap.get(pad) ?? 0) + 1)
- }
- }
-
- const toValues = (map: Map<number, number>) =>
- [...map.entries()]
- .map(([value, count]) => ({ value, count }))
- .sort((a, b) => b.count - a.count)
+import type { AnalyzeSpacingResult } from '@open-pencil/core'
- return { gaps: toValues(gapMap), paddings: toValues(paddingMap), totalNodes }
+async function getData(file?: string): Promise<AnalyzeSpacingResult> {
+ if (isAppMode(file)) return rpc<AnalyzeSpacingResult>('analyze_spacing')
+ const graph = await loadDocument(file!)
+ return executeRpcCommand(graph, 'analyze_spacing', undefined) as AnalyzeSpacingResult
}
export default defineCommand({
meta: { description: 'Analyze spacing values (gap, padding)' },
args: {
- file: { type: 'positional', description: '.fig file path', required: true },
+ file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },
grid: { type: 'string', description: 'Base grid size to check against', default: '8' },
json: { type: 'boolean', description: 'Output as JSON' }
},
async run({ args }) {
- const graph = await loadDocument(args.file)
+ const data = await getData(args.file)
const gridSize = Number(args.grid)
- const { gaps, paddings, totalNodes } = collectSpacing(graph)
if (args.json) {
- console.log(JSON.stringify({ gaps, paddings, totalNodes }, null, 2))
+ console.log(JSON.stringify(data, null, 2))
return
}
console.log('')
- if (gaps.length > 0) {
+ if (data.gaps.length > 0) {
console.log(bold(' Gap values'))
console.log('')
console.log(
fmtHistogram(
- gaps.slice(0, 15).map((g) => ({
+ data.gaps.slice(0, 15).map((g) => ({
label: `${String(g.value).padStart(4)}px`,
value: g.count,
suffix: g.value % gridSize !== 0 ? '⚠' : undefined
@@ -77,12 +46,12 @@ export default defineCommand({
console.log('')
}
- if (paddings.length > 0) {
+ if (data.paddings.length > 0) {
console.log(bold(' Padding values'))
console.log('')
console.log(
fmtHistogram(
- paddings.slice(0, 15).map((p) => ({
+ data.paddings.slice(0, 15).map((p) => ({
label: `${String(p.value).padStart(4)}px`,
value: p.count,
suffix: p.value % gridSize !== 0 ? '⚠' : undefined
@@ -92,16 +61,16 @@ export default defineCommand({
console.log('')
}
- if (gaps.length === 0 && paddings.length === 0) {
+ if (data.gaps.length === 0 && data.paddings.length === 0) {
console.log('No auto-layout nodes with spacing found.')
console.log('')
return
}
- console.log(fmtSummary({ 'gap values': gaps.length, 'padding values': paddings.length }))
+ console.log(fmtSummary({ 'gap values': data.gaps.length, 'padding values': data.paddings.length }))
- const offGridGaps = gaps.filter((g) => g.value % gridSize !== 0)
- const offGridPaddings = paddings.filter((p) => p.value % gridSize !== 0)
+ const offGridGaps = data.gaps.filter((g) => g.value % gridSize !== 0)
+ const offGridPaddings = data.paddings.filter((p) => p.value % gridSize !== 0)
if (offGridGaps.length > 0 || offGridPaddings.length > 0) {
console.log('')
diff --git a/packages/cli/src/commands/analyze/typography.ts b/packages/cli/src/commands/analyze/typography.ts
index 113599fd2..61a2cc8bc 100644
--- a/packages/cli/src/commands/analyze/typography.ts
+++ b/packages/cli/src/commands/analyze/typography.ts
@@ -1,44 +1,11 @@
import { defineCommand } from 'citty'
import { loadDocument } from '../../headless'
+import { isAppMode, rpc } from '../../app-client'
import { bold, fmtHistogram, fmtSummary } from '../../format'
-import type { SceneGraph } from '@open-pencil/core'
+import { executeRpcCommand } from '@open-pencil/core'
-interface TypographyStyle {
- family: string
- size: number
- weight: number
- lineHeight: string
- count: number
-}
-
-function collectTypography(graph: SceneGraph): { styles: TypographyStyle[]; totalTextNodes: number } {
- const styleMap = new Map<string, TypographyStyle>()
- let totalTextNodes = 0
-
- for (const node of graph.getAllNodes()) {
- if (node.type !== 'TEXT') continue
- totalTextNodes++
-
- const lh = node.lineHeight === null ? 'auto' : `${node.lineHeight}px`
- const key = `${node.fontFamily}|${node.fontSize}|${node.fontWeight}|${lh}`
-
- const existing = styleMap.get(key)
- if (existing) {
- existing.count++
- } else {
- styleMap.set(key, {
- family: node.fontFamily,
- size: node.fontSize,
- weight: node.fontWeight,
- lineHeight: lh,
- count: 1
- })
- }
- }
-
- return { styles: [...styleMap.values()], totalTextNodes }
-}
+import type { AnalyzeTypographyResult } from '@open-pencil/core'
function weightName(w: number): string {
if (w <= 100) return 'Thin'
@@ -52,88 +19,80 @@ function weightName(w: number): string {
return 'Black'
}
+async function getData(file: string | undefined, groupBy?: string): Promise<AnalyzeTypographyResult> {
+ const rpcArgs = { groupBy }
+ if (isAppMode(file)) return rpc<AnalyzeTypographyResult>('analyze_typography', rpcArgs)
+ const graph = await loadDocument(file!)
+ return executeRpcCommand(graph, 'analyze_typography', rpcArgs) as AnalyzeTypographyResult
+}
+
export default defineCommand({
meta: { description: 'Analyze typography usage' },
args: {
- file: { type: 'positional', description: '.fig file path', required: true },
- 'group-by': {
- type: 'string',
- description: 'Group by: family, size, weight (default: show all styles)'
- },
+ file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },
+ 'group-by': { type: 'string', description: 'Group by: family, size, weight (default: show all styles)' },
limit: { type: 'string', description: 'Max styles to show', default: '30' },
json: { type: 'boolean', description: 'Output as JSON' }
},
async run({ args }) {
- const graph = await loadDocument(args.file)
+ const data = await getData(args.file, args['group-by'])
const limit = Number(args.limit)
const groupBy = args['group-by']
- const { styles, totalTextNodes } = collectTypography(graph)
if (args.json) {
- console.log(JSON.stringify({ styles, totalTextNodes }, null, 2))
+ console.log(JSON.stringify(data, null, 2))
return
}
- if (styles.length === 0) {
+ if (data.styles.length === 0) {
console.log('No text nodes found.')
return
}
- const sorted = styles.sort((a, b) => b.count - a.count)
-
console.log('')
if (groupBy === 'family') {
const byFamily = new Map<string, number>()
- for (const s of sorted) byFamily.set(s.family, (byFamily.get(s.family) ?? 0) + s.count)
+ for (const s of data.styles) byFamily.set(s.family, (byFamily.get(s.family) ?? 0) + s.count)
console.log(bold(' Font families'))
console.log('')
console.log(
fmtHistogram(
- [...byFamily.entries()]
- .sort((a, b) => b[1] - a[1])
- .map(([family, count]) => ({ label: family, value: count }))
+ [...byFamily.entries()].sort((a, b) => b[1] - a[1]).map(([family, count]) => ({ label: family, value: count }))
)
)
} else if (groupBy === 'size') {
const bySize = new Map<number, number>()
- for (const s of sorted) bySize.set(s.size, (bySize.get(s.size) ?? 0) + s.count)
+ for (const s of data.styles) bySize.set(s.size, (bySize.get(s.size) ?? 0) + s.count)
console.log(bold(' Font sizes'))
console.log('')
console.log(
fmtHistogram(
- [...bySize.entries()]
- .sort((a, b) => a[0] - b[0])
- .map(([size, count]) => ({ label: `${size}px`, value: count }))
+ [...bySize.entries()].sort((a, b) => a[0] - b[0]).map(([size, count]) => ({ label: `${size}px`, value: count }))
)
)
} else if (groupBy === 'weight') {
const byWeight = new Map<number, number>()
- for (const s of sorted) byWeight.set(s.weight, (byWeight.get(s.weight) ?? 0) + s.count)
+ for (const s of data.styles) byWeight.set(s.weight, (byWeight.get(s.weight) ?? 0) + s.count)
console.log(bold(' Font weights'))
console.log('')
console.log(
fmtHistogram(
- [...byWeight.entries()]
- .sort((a, b) => b[1] - a[1])
- .map(([weight, count]) => ({ label: `${weight} ${weightName(weight)}`, value: count }))
+ [...byWeight.entries()].sort((a, b) => b[1] - a[1]).map(([weight, count]) => ({ label: `${weight} ${weightName(weight)}`, value: count }))
)
)
} else {
console.log(bold(' Typography styles'))
console.log('')
- const items = sorted.slice(0, limit).map((s) => {
+ const items = data.styles.slice(0, limit).map((s) => {
const lh = s.lineHeight !== 'auto' ? ` / ${s.lineHeight}` : ''
- return {
- label: `${s.family} ${s.size}px ${weightName(s.weight)}${lh}`,
- value: s.count
- }
+ return { label: `${s.family} ${s.size}px ${weightName(s.weight)}${lh}`, value: s.count }
})
console.log(fmtHistogram(items))
}
console.log('')
- console.log(fmtSummary({ 'unique styles': styles.length }) + ` from ${totalTextNodes} text nodes`)
+ console.log(fmtSummary({ 'unique styles': data.styles.length }) + ` from ${data.totalTextNodes} text nodes`)
console.log('')
}
})
diff --git a/packages/cli/src/commands/eval.ts b/packages/cli/src/commands/eval.ts
index 4207cefb6..ea4d8fc55 100644
--- a/packages/cli/src/commands/eval.ts
+++ b/packages/cli/src/commands/eval.ts
@@ -3,6 +3,7 @@ import { defineCommand } from 'citty'
import { FigmaAPI } from '@open-pencil/core'
import { loadDocument } from '../headless'
+import { isAppMode, rpc } from '../app-client'
import { printError } from '../format'
function serializeResult(value: unknown): unknown {
@@ -17,7 +18,7 @@ function serializeResult(value: unknown): unknown {
export default defineCommand({
meta: { description: 'Execute JavaScript with Figma plugin API' },
args: {
- file: { type: 'positional', description: '.fig file path', required: true },
+ file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },
code: { type: 'string', alias: 'c', description: 'JavaScript code to execute' },
stdin: { type: 'boolean', description: 'Read code from stdin' },
write: { type: 'boolean', alias: 'w', description: 'Write changes back to the input file' },
@@ -39,7 +40,19 @@ export default defineCommand({
process.exit(1)
}
- const graph = await loadDocument(args.file)
+ if (isAppMode(args.file)) {
+ const response = await rpc<{ ok: boolean; result?: unknown; error?: string }>('eval', { code })
+ if (!args.quiet && response.result !== undefined) {
+ if (args.json || !process.stdout.isTTY) {
+ console.log(JSON.stringify(response.result, null, 2))
+ } else {
+ console.log(response.result)
+ }
+ }
+ return
+ }
+
+ const graph = await loadDocument(args.file!)
const figma = new FigmaAPI(graph)
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor
@@ -67,9 +80,9 @@ export default defineCommand({
if (args.write || args.output) {
const { exportFigFile } = await import('@open-pencil/core')
- const outPath = args.output ?? args.file
- const data = exportFigFile(graph)
- await Bun.write(outPath, data)
+ const outPath = args.output ?? args.file!
+ const data = await exportFigFile(graph)
+ await Bun.write(outPath, new Uint8Array(data))
if (!args.quiet) {
console.error(`Written to ${outPath}`)
}
diff --git a/packages/cli/src/commands/export.ts b/packages/cli/src/commands/export.ts
index 1eba501df..5dc6dc57d 100644
--- a/packages/cli/src/commands/export.ts
+++ b/packages/cli/src/commands/export.ts
@@ -4,6 +4,7 @@ import { basename, extname, resolve } from 'node:path'
import { renderNodesToSVG, sceneNodeToJSX, selectionToJSX } from '@open-pencil/core'
import { loadDocument, loadFonts, exportNodes, exportThumbnail } from '../headless'
+import { isAppMode, rpc } from '../app-client'
import { ok, printError } from '../format'
import type { ExportFormat, JSXFormat } from '@open-pencil/core'
@@ -14,7 +15,7 @@ const JSX_STYLES = ['openpencil', 'tailwind']
export default defineCommand({
meta: { description: 'Export a .fig file to PNG, JPG, WEBP, SVG, or JSX' },
args: {
- file: { type: 'positional', description: '.fig file path', required: true },
+ file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },
output: { type: 'string', alias: 'o', description: 'Output file path (default: <name>.<format>)' },
format: { type: 'string', alias: 'f', description: 'Export format: png, jpg, webp, svg, jsx (default: png)', default: 'png' },
scale: { type: 'string', alias: 's', description: 'Export scale (default: 1)', default: '1' },
@@ -38,7 +39,39 @@ export default defineCommand({
process.exit(1)
}
- const graph = await loadDocument(args.file)
+ if (isAppMode(args.file)) {
+ if (format === 'JSX' || format === 'SVG') {
+ const toolName = format === 'SVG' ? 'export_svg' : 'eval'
+ const toolArgs = format === 'SVG'
+ ? { ids: args.node ? [args.node] : undefined }
+ : { code: `return selectionToJSX([${args.node ? `"${args.node}"` : '...figma.currentPage.children.map(n => n.id)'}], figma.graph, "${args.style}")` }
+
+ const result = await rpc<{ svg?: string; result?: string }>('tool', { name: toolName, args: toolArgs })
+ const content = format === 'SVG' ? (result as { svg: string }).svg : (result as { result: string }).result
+ if (!content) {
+ printError('Nothing to export.')
+ process.exit(1)
+ }
+ const output = resolve(args.output ?? `export.${format.toLowerCase()}`)
+ await Bun.write(output, content)
+ console.log(ok(`Exported ${output} (${(content.length / 1024).toFixed(1)} KB)`))
+ return
+ }
+
+ const result = await rpc<{ base64: string }>('export', {
+ nodeIds: args.node ? [args.node] : undefined,
+ scale: Number(args.scale),
+ format: format.toLowerCase()
+ })
+ const data = Uint8Array.from(atob(result.base64), (c) => c.charCodeAt(0))
+ const ext = format.toLowerCase() === 'jpg' ? 'jpg' : format.toLowerCase()
+ const output = resolve(args.output ?? `export.${ext}`)
+ await Bun.write(output, data)
+ console.log(ok(`Exported ${output} (${(data.length / 1024).toFixed(1)} KB)`))
+ return
+ }
+
+ const graph = await loadDocument(args.file!)
await loadFonts(graph)
const pages = graph.getPages()
@@ -51,7 +84,7 @@ export default defineCommand({
process.exit(1)
}
- const defaultName = basename(args.file, extname(args.file))
+ const defaultName = basename(args.file!, extname(args.file!))
if (format === 'JSX') {
const jsxFormat = args.style as JSXFormat
diff --git a/packages/cli/src/commands/find.ts b/packages/cli/src/commands/find.ts
index d2823cd61..c2325994f 100644
--- a/packages/cli/src/commands/find.ts
+++ b/packages/cli/src/commands/find.ts
@@ -1,13 +1,23 @@
import { defineCommand } from 'citty'
import { loadDocument } from '../headless'
-import { fmtList, nodeToListItem, printError, bold } from '../format'
-import type { SceneNode } from '@open-pencil/core'
+import { isAppMode, rpc } from '../app-client'
+import { fmtList, printError, bold, entity, formatType } from '../format'
+import { executeRpcCommand } from '@open-pencil/core'
+
+import type { FindNodeResult } from '@open-pencil/core'
+
+async function getData(file: string | undefined, args: { name?: string; type?: string; page?: string; limit?: string }): Promise<FindNodeResult[]> {
+ const rpcArgs = { name: args.name, type: args.type, page: args.page, limit: args.limit ? Number(args.limit) : undefined }
+ if (isAppMode(file)) return rpc<FindNodeResult[]>('find', rpcArgs)
+ const graph = await loadDocument(file!)
+ return executeRpcCommand(graph, 'find', rpcArgs) as FindNodeResult[]
+}
export default defineCommand({
meta: { description: 'Find nodes by name or type' },
args: {
- file: { type: 'positional', description: '.fig file path', required: true },
+ file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },
name: { type: 'string', description: 'Node name (partial match, case-insensitive)' },
type: { type: 'string', description: 'Node type: FRAME, TEXT, RECTANGLE, INSTANCE, etc.' },
page: { type: 'string', description: 'Page name (default: all pages)' },
@@ -15,43 +25,10 @@ export default defineCommand({
json: { type: 'boolean', description: 'Output as JSON' }
},
async run({ args }) {
- const graph = await loadDocument(args.file)
- const pages = graph.getPages()
- const max = Number(args.limit)
- const namePattern = args.name?.toLowerCase()
- const typeFilter = args.type?.toUpperCase()
-
- const results: SceneNode[] = []
-
- const searchPage = (pageNode: SceneNode) => {
- const walk = (id: string) => {
- if (results.length >= max) return
- const node = graph.getNode(id)
- if (!node) return
- const matchesName = !namePattern || node.name.toLowerCase().includes(namePattern)
- const matchesType = !typeFilter || node.type === typeFilter
- if (matchesName && matchesType) results.push(node)
- for (const childId of node.childIds) walk(childId)
- }
- for (const childId of pageNode.childIds) walk(childId)
- }
-
- if (args.page) {
- const page = pages.find((p) => p.name === args.page)
- if (!page) {
- printError(`Page "${args.page}" not found.`)
- process.exit(1)
- }
- searchPage(page)
- } else {
- for (const page of pages) searchPage(page)
- }
+ const results = await getData(args.file, args)
if (args.json) {
- console.log(JSON.stringify(results.map((n) => ({
- id: n.id, name: n.name, type: n.type,
- width: Math.round(n.width), height: Math.round(n.height)
- })), null, 2))
+ console.log(JSON.stringify(results, null, 2))
return
}
@@ -63,7 +40,13 @@ export default defineCommand({
console.log('')
console.log(bold(` Found ${results.length} node${results.length > 1 ? 's' : ''}`))
console.log('')
- console.log(fmtList(results.map(nodeToListItem)))
+ console.log(
+ fmtList(
+ results.map((n) => ({
+ header: entity(formatType(n.type), n.name, n.id)
+ }))
+ )
+ )
console.log('')
}
})
diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.ts
index 808380822..47ca295d9 100644
--- a/packages/cli/src/commands/info.ts
+++ b/packages/cli/src/commands/info.ts
@@ -1,57 +1,45 @@
import { defineCommand } from 'citty'
import { loadDocument } from '../headless'
+import { isAppMode, rpc } from '../app-client'
import { bold, fmtHistogram, fmtSummary, kv } from '../format'
-import type { SceneNode } from '@open-pencil/core'
+
+import type { InfoResult } from '@open-pencil/core'
+import { executeRpcCommand } from '@open-pencil/core'
+
+async function getData(file?: string): Promise<InfoResult> {
+ if (isAppMode(file)) return rpc<InfoResult>('info')
+ const graph = await loadDocument(file!)
+ return executeRpcCommand(graph, 'info', undefined) as InfoResult
+}
export default defineCommand({
meta: { description: 'Show document info (pages, node counts, fonts)' },
args: {
- file: { type: 'positional', description: '.fig file path', required: true },
+ file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },
json: { type: 'boolean', description: 'Output as JSON' }
},
async run({ args }) {
- const graph = await loadDocument(args.file)
- const pages = graph.getPages()
-
- let totalNodes = 0
- const types: Record<string, number> = {}
- const fonts = new Set<string>()
- const pageCounts: Record<string, number> = {}
-
- for (const page of pages) {
- let pageCount = 0
- const walk = (id: string) => {
- const node = graph.getNode(id) as SceneNode | undefined
- if (!node) return
- totalNodes++
- pageCount++
- types[node.type] = (types[node.type] ?? 0) + 1
- if (node.fontFamily) fonts.add(node.fontFamily)
- for (const childId of node.childIds) walk(childId)
- }
- for (const childId of page.childIds) walk(childId)
- pageCounts[page.name] = pageCount
- }
+ const data = await getData(args.file)
if (args.json) {
- console.log(JSON.stringify({ pages: pages.length, totalNodes, types, fonts: [...fonts].sort(), pageCounts }, null, 2))
+ console.log(JSON.stringify(data, null, 2))
return
}
console.log('')
- console.log(bold(` ${pages.length} pages, ${totalNodes} nodes`))
+ console.log(bold(` ${data.pages} pages, ${data.totalNodes} nodes`))
console.log('')
- const pageItems = Object.entries(pageCounts).map(([label, value]) => ({ label, value }))
+ const pageItems = Object.entries(data.pageCounts).map(([label, value]) => ({ label, value }))
console.log(fmtHistogram(pageItems, { unit: 'nodes' }))
console.log('')
- console.log(fmtSummary(types))
+ console.log(fmtSummary(data.types))
- if (fonts.size > 0) {
+ if (data.fonts.length > 0) {
console.log('')
- console.log(kv('Fonts', [...fonts].sort().join(', ')))
+ console.log(kv('Fonts', data.fonts.join(', ')))
}
console.log('')
}
diff --git a/packages/cli/src/commands/node.ts b/packages/cli/src/commands/node.ts
index 18fe247a6..f585b1536 100644
--- a/packages/cli/src/commands/node.ts
+++ b/packages/cli/src/commands/node.ts
@@ -1,83 +1,74 @@
import { defineCommand } from 'citty'
import { loadDocument } from '../headless'
-import { fmtNode, fmtList, nodeToData, nodeDetails, formatType, printError } from '../format'
-import type { SceneNode, SceneGraph } from '@open-pencil/core'
+import { isAppMode, rpc } from '../app-client'
+import { fmtNode, fmtList, nodeToData, printError, formatType } from '../format'
+import { executeRpcCommand } from '@open-pencil/core'
-function fullNodeDetails(graph: SceneGraph, node: SceneNode): Record<string, unknown> {
- const details = nodeDetails(node)
+import type { NodeResult } from '@open-pencil/core'
- const parent = node.parentId ? graph.getNode(node.parentId) : undefined
- if (parent) details.parent = `${parent.name} (${parent.id})`
-
- if (node.text) {
- details.text = node.text.length > 80 ? node.text.slice(0, 80) + '…' : node.text
- }
-
- if (node.childIds.length > 0) details.children = node.childIds.length
-
- for (const [field, varId] of Object.entries(node.boundVariables)) {
- const variable = graph.variables.get(varId)
- details[`var:${field}`] = variable?.name ?? varId
- }
-
- return details
+async function getData(file: string | undefined, id: string): Promise<NodeResult | { error: string }> {
+ if (isAppMode(file)) return rpc<NodeResult>('node', { id })
+ const graph = await loadDocument(file!)
+ return executeRpcCommand(graph, 'node', { id }) as NodeResult | { error: string }
}
export default defineCommand({
meta: { description: 'Show detailed node properties by ID' },
args: {
- file: { type: 'positional', description: '.fig file path', required: true },
+ file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },
id: { type: 'string', description: 'Node ID', required: true },
json: { type: 'boolean', description: 'Output as JSON' }
},
async run({ args }) {
- const graph = await loadDocument(args.file)
- const node = graph.getNode(args.id)
+ const data = await getData(args.file, args.id)
- if (!node) {
- printError(`Node "${args.id}" not found.`)
+ if ('error' in data) {
+ printError(data.error)
process.exit(1)
}
if (args.json) {
- const { childIds, parentId, ...rest } = node
- const children = childIds.length
- const parent = parentId ? graph.getNode(parentId) : undefined
- console.log(
- JSON.stringify(
- {
- ...rest,
- parent: parent ? { id: parent.id, name: parent.name, type: parent.type } : null,
- children
- },
- null,
- 2
- )
- )
+ console.log(JSON.stringify(data, null, 2))
return
}
- console.log('')
- console.log(fmtNode(nodeToData(node), fullNodeDetails(graph, node)))
-
- if (node.childIds.length > 0) {
- const children = node.childIds
- .map((id) => graph.getNode(id))
- .filter((n): n is SceneNode => n !== undefined)
- .slice(0, 10)
- .map((child) => ({
- header: `[${formatType(child.type)}] "${child.name}" (${child.id})`
- }))
+ const nodeData = {
+ type: formatType(data.type),
+ name: data.name,
+ id: data.id,
+ width: data.width,
+ height: data.height,
+ x: data.x,
+ y: data.y
+ }
- if (node.childIds.length > 10) {
- children.push({ header: `… and ${node.childIds.length - 10} more` })
+ const details: Record<string, unknown> = {}
+ if (data.parent) details.parent = `${data.parent.name} (${data.parent.id})`
+ if (data.text) details.text = data.text
+ if (data.fills.length > 0) {
+ const solid = (data.fills as Array<{ type: string; visible: boolean; color: { r: number; g: number; b: number }; opacity: number }>)
+ .find((f) => f.type === 'SOLID' && f.visible)
+ if (solid) {
+ const { r, g, b } = solid.color
+ const hex = '#' + [r, g, b].map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('')
+ details.fill = solid.opacity < 1 ? `${hex} ${Math.round(solid.opacity * 100)}%` : hex
}
-
- console.log('')
- console.log(fmtList(children, { compact: true }))
+ }
+ if (data.cornerRadius) details.radius = `${data.cornerRadius}px`
+ if (data.rotation) details.rotate = `${Math.round(data.rotation)}°`
+ if (data.opacity < 1) details.opacity = data.opacity
+ if (!data.visible) details.visible = false
+ if (data.locked) details.locked = true
+ if (data.fontFamily) details.font = `${data.fontSize}px ${data.fontFamily}`
+ if (data.layoutMode !== 'NONE') details.layout = data.layoutMode.toLowerCase()
+ if (data.children > 0) details.children = data.children
+ for (const [field, name] of Object.entries(data.boundVariables)) {
+ details[`var:${field}`] = name
}
console.log('')
+ console.log(fmtNode(nodeData, details))
+ console.log('')
}
})
diff --git a/packages/cli/src/commands/pages.ts b/packages/cli/src/commands/pages.ts
index 102b3a678..cb5b837ef 100644
--- a/packages/cli/src/commands/pages.ts
+++ b/packages/cli/src/commands/pages.ts
@@ -1,38 +1,29 @@
import { defineCommand } from 'citty'
import { loadDocument } from '../headless'
+import { isAppMode, rpc } from '../app-client'
import { bold, fmtList, entity, formatType } from '../format'
+import type { PageItem } from '@open-pencil/core'
+import { executeRpcCommand } from '@open-pencil/core'
+
+async function getData(file?: string): Promise<PageItem[]> {
+ if (isAppMode(file)) return rpc<PageItem[]>('pages')
+ const graph = await loadDocument(file!)
+ return executeRpcCommand(graph, 'pages', undefined) as PageItem[]
+}
+
export default defineCommand({
meta: { description: 'List pages in a .fig file' },
args: {
- file: { type: 'positional', description: '.fig file path', required: true },
+ file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },
json: { type: 'boolean', description: 'Output as JSON' }
},
async run({ args }) {
- const graph = await loadDocument(args.file)
- const pages = graph.getPages()
-
- const countNodes = (pageId: string): number => {
- let count = 0
- const walk = (id: string) => {
- count++
- const n = graph.getNode(id)
- if (n) for (const cid of n.childIds) walk(cid)
- }
- const page = graph.getNode(pageId)
- if (page) for (const cid of page.childIds) walk(cid)
- return count
- }
+ const pages = await getData(args.file)
if (args.json) {
- console.log(
- JSON.stringify(
- pages.map((p) => ({ id: p.id, name: p.name, nodes: countNodes(p.id) })),
- null,
- 2
- )
- )
+ console.log(JSON.stringify(pages, null, 2))
return
}
@@ -42,8 +33,8 @@ export default defineCommand({
console.log(
fmtList(
pages.map((page) => ({
- header: entity(formatType(page.type), page.name, page.id),
- details: { nodes: countNodes(page.id) }
+ header: entity('page', page.name, page.id),
+ details: { nodes: page.nodes }
})),
{ compact: true }
)
diff --git a/packages/cli/src/commands/tree.ts b/packages/cli/src/commands/tree.ts
index 7ef634878..bf69d0931 100644
--- a/packages/cli/src/commands/tree.ts
+++ b/packages/cli/src/commands/tree.ts
@@ -1,59 +1,55 @@
import { defineCommand } from 'citty'
import { loadDocument } from '../headless'
-import { fmtTree, nodeToTreeNode, printError, entity, formatType } from '../format'
-import type { SceneNode } from '@open-pencil/core'
+import { isAppMode, rpc } from '../app-client'
+import { fmtTree, printError, entity, formatType } from '../format'
+import { executeRpcCommand } from '@open-pencil/core'
+
+import type { TreeResult, TreeNodeResult } from '@open-pencil/core'
+import type { TreeNode } from 'agentfmt'
+
+function toAgentfmtTree(node: TreeNodeResult, maxDepth: number, depth = 0): TreeNode {
+ const treeNode: TreeNode = {
+ header: entity(formatType(node.type), node.name, node.id)
+ }
+ if (node.children && depth < maxDepth) {
+ treeNode.children = node.children.map((c) => toAgentfmtTree(c, maxDepth, depth + 1))
+ }
+ return treeNode
+}
+
+async function getData(file: string | undefined, args: { page?: string; depth?: string }): Promise<TreeResult | { error: string }> {
+ const rpcArgs = { page: args.page, depth: args.depth ? Number(args.depth) : undefined }
+ if (isAppMode(file)) return rpc<TreeResult>('tree', rpcArgs)
+ const graph = await loadDocument(file!)
+ return executeRpcCommand(graph, 'tree', rpcArgs) as TreeResult | { error: string }
+}
export default defineCommand({
meta: { description: 'Print the node tree' },
args: {
- file: { type: 'positional', description: '.fig file path', required: true },
+ file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },
page: { type: 'string', description: 'Page name (default: first page)' },
depth: { type: 'string', description: 'Max depth (default: unlimited)' },
json: { type: 'boolean', description: 'Output as JSON' }
},
async run({ args }) {
- const graph = await loadDocument(args.file)
- const pages = graph.getPages()
+ const data = await getData(args.file, args)
const maxDepth = args.depth ? Number(args.depth) : Infinity
- const page = args.page
- ? pages.find((p) => p.name === args.page)
- : pages[0]
-
- if (!page) {
- printError(`Page "${args.page}" not found. Available: ${pages.map((p) => p.name).join(', ')}`)
+ if ('error' in data) {
+ printError(data.error)
process.exit(1)
}
if (args.json) {
- const buildJson = (id: string, depth: number): unknown => {
- const node = graph.getNode(id)
- if (!node) return null
- const result: Record<string, unknown> = {
- id: node.id,
- name: node.name,
- type: node.type,
- x: Math.round(node.x),
- y: Math.round(node.y),
- width: Math.round(node.width),
- height: Math.round(node.height)
- }
- if (node.childIds.length > 0 && depth < maxDepth) {
- result.children = node.childIds.map((cid) => buildJson(cid, depth + 1)).filter(Boolean)
- }
- return result
- }
- console.log(JSON.stringify(page.childIds.map((id) => buildJson(id, 0)), null, 2))
+ console.log(JSON.stringify(data.children, null, 2))
return
}
const root = {
- header: entity(formatType(page.type), page.name, page.id),
- children: page.childIds
- .map((id) => graph.getNode(id))
- .filter((n): n is SceneNode => n !== undefined)
- .map((child) => nodeToTreeNode(graph, child, maxDepth))
+ header: entity(formatType(data.page.type), data.page.name, data.page.id),
+ children: data.children.map((c) => toAgentfmtTree(c, maxDepth))
}
console.log('')
diff --git a/packages/cli/src/commands/variables.ts b/packages/cli/src/commands/variables.ts
index 4bb292cba..9dbb2b622 100644
--- a/packages/cli/src/commands/variables.ts
+++ b/packages/cli/src/commands/variables.ts
@@ -1,82 +1,50 @@
import { defineCommand } from 'citty'
import { loadDocument } from '../headless'
+import { isAppMode, rpc } from '../app-client'
import { bold, fmtList, fmtSummary } from '../format'
-import type { SceneGraph, Variable } from '@open-pencil/core'
+import { executeRpcCommand } from '@open-pencil/core'
-function formatValue(variable: Variable, graph: SceneGraph): string {
- const modeId = graph.getActiveModeId(variable.collectionId)
- const raw = variable.valuesByMode[modeId]
- if (raw === undefined) return '–'
+import type { VariablesResult } from '@open-pencil/core'
- if (typeof raw === 'object' && raw !== null && 'aliasId' in raw) {
- const alias = graph.variables.get(raw.aliasId)
- return alias ? `→ ${alias.name}` : `→ ${raw.aliasId}`
- }
-
- if (typeof raw === 'object' && 'r' in raw) {
- const { r, g, b } = raw as { r: number; g: number; b: number }
- return (
- '#' +
- [r, g, b]
- .map((c) =>
- Math.round(c * 255)
- .toString(16)
- .padStart(2, '0')
- )
- .join('')
- )
- }
-
- return String(raw)
+async function getData(file: string | undefined, args: { collection?: string; type?: string }): Promise<VariablesResult> {
+ const rpcArgs = { collection: args.collection, type: args.type }
+ if (isAppMode(file)) return rpc<VariablesResult>('variables', rpcArgs)
+ const graph = await loadDocument(file!)
+ return executeRpcCommand(graph, 'variables', rpcArgs) as VariablesResult
}
export default defineCommand({
meta: { description: 'List design variables and collections' },
args: {
- file: { type: 'positional', description: '.fig file path', required: true },
+ file: { type: 'positional', description: '.fig file path (omit to connect to running app)', required: false },
collection: { type: 'string', description: 'Filter by collection name' },
type: { type: 'string', description: 'Filter by type: COLOR, FLOAT, STRING, BOOLEAN' },
json: { type: 'boolean', description: 'Output as JSON' }
},
async run({ args }) {
- const graph = await loadDocument(args.file)
+ const data = await getData(args.file, args)
- const collections = [...graph.variableCollections.values()]
- const variables = [...graph.variables.values()]
-
- if (variables.length === 0) {
+ if (data.totalVariables === 0) {
console.log('No variables found.')
return
}
if (args.json) {
- console.log(JSON.stringify({ collections, variables }, null, 2))
+ console.log(JSON.stringify(data, null, 2))
return
}
- const typeFilter = args.type?.toUpperCase()
- const collFilter = args.collection?.toLowerCase()
-
console.log('')
- for (const coll of collections) {
- if (collFilter && !coll.name.toLowerCase().includes(collFilter)) continue
-
- const collVars = graph
- .getVariablesForCollection(coll.id)
- .filter((v) => !typeFilter || v.type === typeFilter)
-
- if (collVars.length === 0) continue
-
- const modes = coll.modes.map((m) => m.name).join(', ')
- console.log(bold(` ${coll.name}`) + ` (${modes})`)
+ for (const coll of data.collections) {
+ console.log(bold(` ${coll.name}`) + ` (${coll.modes.join(', ')})`)
console.log('')
console.log(
fmtList(
- collVars.map((v) => ({
+ coll.variables.map((v) => ({
header: v.name,
- details: { value: formatValue(v, graph), type: v.type.toLowerCase() }
+ details: { value: v.value, type: v.type.toLowerCase() }
})),
{ compact: true }
)
@@ -86,8 +54,8 @@ export default defineCommand({
console.log(
fmtSummary({
- variables: variables.length,
- collections: collections.length
+ variables: data.totalVariables,
+ collections: data.totalCollections
})
)
console.log('')
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 74cae7e6a..f9037dd85 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -48,6 +48,16 @@ export {
export { FigmaAPI, FigmaNodeProxy, type FigmaFontName } from './figma-api'
export { ALL_TOOLS, defineTool, toolsToAI } from './tools'
export type { ToolDef, ParamDef, ParamType } from './tools'
+export { executeRpcCommand, ALL_RPC_COMMANDS } from './rpc'
+export type {
+ InfoResult, PageItem, TreeArgs, TreeResult, TreeNodeResult,
+ FindArgs, FindNodeResult, NodeArgs, NodeResult,
+ VariablesArgs, VariablesResult,
+ AnalyzeColorsArgs, AnalyzeColorsResult,
+ AnalyzeTypographyArgs, AnalyzeTypographyResult,
+ AnalyzeSpacingResult, SpacingValue,
+ AnalyzeClustersArgs, AnalyzeClustersResult, TypographyStyle
+} from './rpc'
export { SkiaRenderer, type RenderOverlays } from './renderer'
export { RenderProfiler } from './profiler'
export type { FrameCapture, NodeProfile } from './profiler'
diff --git a/packages/core/src/rpc/commands.ts b/packages/core/src/rpc/commands.ts
new file mode 100644
index 000000000..e64f2cb96
--- /dev/null
+++ b/packages/core/src/rpc/commands.ts
@@ -0,0 +1,633 @@
+import type { SceneGraph, SceneNode, Variable } from '../scene-graph'
+
+export interface RpcCommand<A = unknown, R = unknown> {
+ name: string
+ execute: (graph: SceneGraph, args: A) => R
+}
+
+function walkNodes(graph: SceneGraph, rootId: string, fn: (node: SceneNode) => void) {
+ const node = graph.getNode(rootId)
+ if (!node) return
+ fn(node)
+ for (const childId of node.childIds) walkNodes(graph, childId, fn)
+}
+
+function countNodes(graph: SceneGraph, pageId: string): number {
+ let count = 0
+ const page = graph.getNode(pageId)
+ if (page) for (const cid of page.childIds) walkNodes(graph, cid, () => count++)
+ return count
+}
+
+// ── info ──
+
+export interface InfoResult {
+ pages: number
+ totalNodes: number
+ types: Record<string, number>
+ fonts: string[]
+ pageCounts: Record<string, number>
+}
+
+export const infoCommand: RpcCommand<void, InfoResult> = {
+ name: 'info',
+ execute: (graph) => {
+ const pages = graph.getPages()
+ let totalNodes = 0
+ const types: Record<string, number> = {}
+ const fonts = new Set<string>()
+ const pageCounts: Record<string, number> = {}
+
+ for (const page of pages) {
+ let pageCount = 0
+ for (const cid of page.childIds) {
+ walkNodes(graph, cid, (node) => {
+ totalNodes++
+ pageCount++
+ types[node.type] = (types[node.type] ?? 0) + 1
+ if (node.fontFamily) fonts.add(node.fontFamily)
+ })
+ }
+ pageCounts[page.name] = pageCount
+ }
+
+ return { pages: pages.length, totalNodes, types, fonts: [...fonts].sort(), pageCounts }
+ }
+}
+
+// ── pages ──
+
+export interface PageItem {
+ id: string
+ name: string
+ nodes: number
+}
+
+export const pagesCommand: RpcCommand<void, PageItem[]> = {
+ name: 'pages',
+ execute: (graph) => {
+ return graph.getPages().map((p) => ({ id: p.id, name: p.name, nodes: countNodes(graph, p.id) }))
+ }
+}
+
+// ── tree ──
+
+export interface TreeArgs {
+ page?: string
+ depth?: number
+}
+
+export interface TreeNodeResult {
+ id: string
+ name: string
+ type: string
+ x: number
+ y: number
+ width: number
+ height: number
+ children?: TreeNodeResult[]
+}
+
+function buildTreeNode(graph: SceneGraph, id: string, depth: number, maxDepth: number): TreeNodeResult | null {
+ const node = graph.getNode(id)
+ if (!node) return null
+ const result: TreeNodeResult = {
+ id: node.id,
+ name: node.name,
+ type: node.type,
+ x: Math.round(node.x),
+ y: Math.round(node.y),
+ width: Math.round(node.width),
+ height: Math.round(node.height)
+ }
+ if (node.childIds.length > 0 && depth < maxDepth) {
+ result.children = node.childIds
+ .map((cid) => buildTreeNode(graph, cid, depth + 1, maxDepth))
+ .filter((n): n is TreeNodeResult => n !== null)
+ }
+ return result
+}
+
+export interface TreeResult {
+ page: { id: string; name: string; type: string }
+ children: TreeNodeResult[]
+}
+
+export const treeCommand: RpcCommand<TreeArgs, TreeResult | { error: string }> = {
+ name: 'tree',
+ execute: (graph, args) => {
+ const pages = graph.getPages()
+ const maxDepth = args.depth ?? Infinity
+ const page = args.page ? pages.find((p) => p.name === args.page) : pages[0]
+ if (!page) return { error: `Page "${args.page}" not found. Available: ${pages.map((p) => p.name).join(', ')}` }
+
+ return {
+ page: { id: page.id, name: page.name, type: page.type },
+ children: page.childIds
+ .map((cid) => buildTreeNode(graph, cid, 0, maxDepth))
+ .filter((n): n is TreeNodeResult => n !== null)
+ }
+ }
+}
+
+// ── find ──
+
+export interface FindArgs {
+ name?: string
+ type?: string
+ page?: string
+ limit?: number
+}
+
+export interface FindNodeResult {
+ id: string
+ name: string
+ type: string
+ width: number
+ height: number
+}
+
+export const findCommand: RpcCommand<FindArgs, FindNodeResult[]> = {
+ name: 'find',
+ execute: (graph, args) => {
+ const pages = graph.getPages()
+ const max = args.limit ?? 100
+ const namePattern = args.name?.toLowerCase()
+ const typeFilter = args.type?.toUpperCase()
+ const results: FindNodeResult[] = []
+
+ const searchPage = (page: SceneNode) => {
+ for (const cid of page.childIds) {
+ walkNodes(graph, cid, (node) => {
+ if (results.length >= max) return
+ const matchesName = !namePattern || node.name.toLowerCase().includes(namePattern)
+ const matchesType = !typeFilter || node.type === typeFilter
+ if (matchesName && matchesType) {
+ results.push({
+ id: node.id, name: node.name, type: node.type,
+ width: Math.round(node.width), height: Math.round(node.height)
+ })
+ }
+ })
+ }
+ }
+
+ if (args.page) {
+ const page = pages.find((p) => p.name === args.page)
+ if (page) searchPage(page)
+ } else {
+ for (const page of pages) searchPage(page)
+ }
+
+ return results
+ }
+}
+
+// ── node ──
+
+export interface NodeArgs {
+ id: string
+}
+
+export interface NodeResult {
+ id: string
+ name: string
+ type: string
+ x: number
+ y: number
+ width: number
+ height: number
+ visible: boolean
+ locked: boolean
+ opacity: number
+ rotation: number
+ fills: unknown[]
+ strokes: unknown[]
+ effects: unknown[]
+ cornerRadius: number
+ blendMode: string
+ layoutMode: string
+ fontFamily: string
+ fontSize: number
+ fontWeight: number
+ text: string | null
+ parent: { id: string; name: string; type: string } | null
+ children: number
+ boundVariables: Record<string, string>
+}
+
+export const nodeCommand: RpcCommand<NodeArgs, NodeResult | { error: string }> = {
+ name: 'node',
+ execute: (graph, args) => {
+ const node = graph.getNode(args.id)
+ if (!node) return { error: `Node "${args.id}" not found` }
+
+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined
+ const boundVars: Record<string, string> = {}
+ for (const [field, varId] of Object.entries(node.boundVariables)) {
+ const variable = graph.variables.get(varId)
+ boundVars[field] = variable?.name ?? varId
+ }
+
+ return {
+ id: node.id,
+ name: node.name,
+ type: node.type,
+ x: Math.round(node.x),
+ y: Math.round(node.y),
+ width: Math.round(node.width),
+ height: Math.round(node.height),
+ visible: node.visible,
+ locked: node.locked,
+ opacity: node.opacity,
+ rotation: node.rotation,
+ fills: node.fills,
+ strokes: node.strokes,
+ effects: node.effects,
+ cornerRadius: node.cornerRadius,
+ blendMode: node.blendMode,
+ layoutMode: node.layoutMode,
+ fontFamily: node.fontFamily,
+ fontSize: node.fontSize,
+ fontWeight: node.fontWeight,
+ text: node.text?.length ? (node.text.length > 200 ? node.text.slice(0, 200) + '…' : node.text) : null,
+ parent: parent ? { id: parent.id, name: parent.name, type: parent.type } : null,
+ children: node.childIds.length,
+ boundVariables: boundVars
+ }
+ }
+}
+
+// ── variables ──
+
+export interface VariablesArgs {
+ collection?: string
+ type?: string
+}
+
+function formatVariableValue(variable: Variable, graph: SceneGraph): string {
+ const modeId = graph.getActiveModeId(variable.collectionId)
+ const raw = variable.valuesByMode[modeId]
+ if (raw === undefined) return '–'
+
+ if (typeof raw === 'object' && raw !== null && 'aliasId' in raw) {
+ const alias = graph.variables.get((raw as { aliasId: string }).aliasId)
+ return alias ? `→ ${alias.name}` : `→ ${(raw as { aliasId: string }).aliasId}`
+ }
+
+ if (typeof raw === 'object' && raw !== null && 'r' in raw) {
+ const { r, g, b } = raw as { r: number; g: number; b: number }
+ return '#' + [r, g, b].map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('')
+ }
+
+ return String(raw)
+}
+
+export interface VariablesResult {
+ collections: Array<{
+ id: string
+ name: string
+ modes: string[]
+ variables: Array<{
+ id: string
+ name: string
+ type: string
+ value: string
+ }>
+ }>
+ totalVariables: number
+ totalCollections: number
+}
+
+export const variablesCommand: RpcCommand<VariablesArgs, VariablesResult> = {
+ name: 'variables',
+ execute: (graph, args) => {
+ const typeFilter = args.type?.toUpperCase()
+ const collFilter = args.collection?.toLowerCase()
+
+ const result: VariablesResult = {
+ collections: [],
+ totalVariables: graph.variables.size,
+ totalCollections: graph.variableCollections.size
+ }
+
+ for (const coll of graph.variableCollections.values()) {
+ if (collFilter && !coll.name.toLowerCase().includes(collFilter)) continue
+
+ const collVars = graph.getVariablesForCollection(coll.id)
+ .filter((v) => !typeFilter || v.type === typeFilter)
+
+ if (collVars.length === 0) continue
+
+ result.collections.push({
+ id: coll.id,
+ name: coll.name,
+ modes: coll.modes.map((m) => m.name),
+ variables: collVars.map((v) => ({
+ id: v.id,
+ name: v.name,
+ type: v.type,
+ value: formatVariableValue(v, graph)
+ }))
+ })
+ }
+
+ return result
+ }
+}
+
+// ── analyze colors ──
+
+export interface AnalyzeColorsArgs {
+ limit?: number
+ threshold?: number
+ similar?: boolean
+}
+
+interface ColorInfo {
+ hex: string
+ count: number
+ variableName: string | null
+}
+
+interface ColorCluster {
+ colors: ColorInfo[]
+ suggestedHex: string
+ totalCount: number
+}
+
+function hexToRgb(hex: string): [number, number, number] {
+ const clean = hex.replace('#', '')
+ return [parseInt(clean.slice(0, 2), 16), parseInt(clean.slice(2, 4), 16), parseInt(clean.slice(4, 6), 16)]
+}
+
+function colorDistance(hex1: string, hex2: string): number {
+ const [r1, g1, b1] = hexToRgb(hex1)
+ const [r2, g2, b2] = hexToRgb(hex2)
+ return Math.sqrt((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2)
+}
+
+function clusterColors(colors: ColorInfo[], threshold: number): ColorCluster[] {
+ const clusters: ColorCluster[] = []
+ const used = new Set<string>()
+ const sorted = [...colors].sort((a, b) => b.count - a.count)
+
+ for (const color of sorted) {
+ if (used.has(color.hex)) continue
+ const cluster: ColorCluster = { colors: [color], suggestedHex: color.hex, totalCount: color.count }
+ used.add(color.hex)
+
+ for (const other of sorted) {
+ if (used.has(other.hex)) continue
+ if (colorDistance(color.hex, other.hex) <= threshold) {
+ cluster.colors.push(other)
+ cluster.totalCount += other.count
+ used.add(other.hex)
+ }
+ }
+
+ if (cluster.colors.length > 1) clusters.push(cluster)
+ }
+
+ return clusters.sort((a, b) => b.colors.length - a.colors.length)
+}
+
+function toHex(r: number, g: number, b: number): string {
+ return '#' + [r, g, b].map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('')
+}
+
+function collectColors(graph: SceneGraph): { colors: ColorInfo[]; totalNodes: number } {
+ const colorMap = new Map<string, ColorInfo>()
+ let totalNodes = 0
+
+ const addColor = (hex: string, variableName: string | null) => {
+ const existing = colorMap.get(hex)
+ if (existing) {
+ existing.count++
+ if (variableName && !existing.variableName) existing.variableName = variableName
+ } else {
+ colorMap.set(hex, { hex, count: 1, variableName })
+ }
+ }
+
+ for (const node of graph.getAllNodes()) {
+ if (node.type === 'CANVAS') continue
+ totalNodes++
+
+ for (const fill of node.fills) {
+ if (!fill.visible || fill.type !== 'SOLID') continue
+ addColor(toHex(fill.color.r, fill.color.g, fill.color.b), null)
+ }
+ for (const stroke of node.strokes) {
+ if (!stroke.visible) continue
+ addColor(toHex(stroke.color.r, stroke.color.g, stroke.color.b), null)
+ }
+ for (const effect of node.effects) {
+ if (!effect.visible) continue
+ addColor(toHex(effect.color.r, effect.color.g, effect.color.b), null)
+ }
+
+ for (const [field, varId] of Object.entries(node.boundVariables)) {
+ if (!field.includes('fill') && !field.includes('stroke') && !field.includes('color')) continue
+ const variable = graph.variables.get(varId)
+ if (variable) {
+ const resolvedColor = graph.resolveColorVariable(varId)
+ if (resolvedColor) {
+ const hex = toHex(resolvedColor.r, resolvedColor.g, resolvedColor.b)
+ const existing = colorMap.get(hex)
+ if (existing) existing.variableName = variable.name
+ }
+ }
+ }
+ }
+
+ return { colors: [...colorMap.values()], totalNodes }
+}
+
+export interface AnalyzeColorsResult {
+ colors: ColorInfo[]
+ totalNodes: number
+ clusters: ColorCluster[]
+}
+
+export const analyzeColorsCommand: RpcCommand<AnalyzeColorsArgs, AnalyzeColorsResult> = {
+ name: 'analyze_colors',
+ execute: (graph, args) => {
+ const { colors, totalNodes } = collectColors(graph)
+ const clusters = args.similar ? clusterColors(colors.filter((c) => !c.variableName), args.threshold ?? 15) : []
+ return { colors: colors.sort((a, b) => b.count - a.count), totalNodes, clusters }
+ }
+}
+
+// ── analyze typography ──
+
+export interface AnalyzeTypographyArgs {
+ groupBy?: string
+}
+
+export interface TypographyStyle {
+ family: string
+ size: number
+ weight: number
+ lineHeight: string
+ count: number
+}
+
+export interface AnalyzeTypographyResult {
+ styles: TypographyStyle[]
+ totalTextNodes: number
+}
+
+export const analyzeTypographyCommand: RpcCommand<AnalyzeTypographyArgs, AnalyzeTypographyResult> = {
+ name: 'analyze_typography',
+ execute: (graph) => {
+ const styleMap = new Map<string, TypographyStyle>()
+ let totalTextNodes = 0
+
+ for (const node of graph.getAllNodes()) {
+ if (node.type !== 'TEXT') continue
+ totalTextNodes++
+
+ const lh = node.lineHeight === null ? 'auto' : `${node.lineHeight}px`
+ const key = `${node.fontFamily}|${node.fontSize}|${node.fontWeight}|${lh}`
+ const existing = styleMap.get(key)
+ if (existing) { existing.count++ } else {
+ styleMap.set(key, { family: node.fontFamily, size: node.fontSize, weight: node.fontWeight, lineHeight: lh, count: 1 })
+ }
+ }
+
+ return { styles: [...styleMap.values()].sort((a, b) => b.count - a.count), totalTextNodes }
+ }
+}
+
+// ── analyze spacing ──
+
+export interface SpacingValue {
+ value: number
+ count: number
+}
+
+export interface AnalyzeSpacingResult {
+ gaps: SpacingValue[]
+ paddings: SpacingValue[]
+ totalNodes: number
+}
+
+export const analyzeSpacingCommand: RpcCommand<void, AnalyzeSpacingResult> = {
+ name: 'analyze_spacing',
+ execute: (graph) => {
+ const gapMap = new Map<number, number>()
+ const paddingMap = new Map<number, number>()
+ let totalNodes = 0
+
+ for (const node of graph.getAllNodes()) {
+ if (node.type === 'CANVAS' || node.layoutMode === 'NONE') continue
+ totalNodes++
+
+ if (node.itemSpacing > 0) gapMap.set(node.itemSpacing, (gapMap.get(node.itemSpacing) ?? 0) + 1)
+ if (node.counterAxisSpacing > 0) gapMap.set(node.counterAxisSpacing, (gapMap.get(node.counterAxisSpacing) ?? 0) + 1)
+
+ for (const pad of [node.paddingTop, node.paddingRight, node.paddingBottom, node.paddingLeft]) {
+ if (pad > 0) paddingMap.set(pad, (paddingMap.get(pad) ?? 0) + 1)
+ }
+ }
+
+ const toValues = (map: Map<number, number>) =>
+ [...map.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count)
+
+ return { gaps: toValues(gapMap), paddings: toValues(paddingMap), totalNodes }
+ }
+}
+
+// ── analyze clusters ──
+
+export interface AnalyzeClustersArgs {
+ limit?: number
+ minSize?: number
+ minCount?: number
+}
+
+interface ClusterNode {
+ id: string
+ name: string
+ type: string
+ width: number
+ height: number
+ childCount: number
+}
+
+export interface AnalyzeClustersResult {
+ clusters: Array<{
+ signature: string
+ nodes: ClusterNode[]
+ }>
+ totalNodes: number
+}
+
+function buildSignature(graph: SceneGraph, node: SceneNode): string {
+ const childTypes = new Map<string, number>()
+ for (const childId of node.childIds) {
+ const child = graph.getNode(childId)
+ if (!child) continue
+ childTypes.set(child.type, (childTypes.get(child.type) ?? 0) + 1)
+ }
+ const childPart = [...childTypes.entries()].sort((a, b) => a[0].localeCompare(b[0])).map(([t, c]) => `${t}:${c}`).join(',')
+ const w = Math.round(node.width / 10) * 10
+ const h = Math.round(node.height / 10) * 10
+ return `${node.type}:${w}x${h}|${childPart}`
+}
+
+export const analyzeClustersCommand: RpcCommand<AnalyzeClustersArgs, AnalyzeClustersResult> = {
+ name: 'analyze_clusters',
+ execute: (graph, args) => {
+ const minSize = args.minSize ?? 30
+ const minCount = args.minCount ?? 2
+ const limit = args.limit ?? 20
+ const sigMap = new Map<string, ClusterNode[]>()
+ let totalNodes = 0
+
+ for (const node of graph.getAllNodes()) {
+ if (node.type === 'CANVAS') continue
+ totalNodes++
+ if (node.width < minSize || node.height < minSize) continue
+ if (node.childIds.length === 0) continue
+
+ const sig = buildSignature(graph, node)
+ const arr = sigMap.get(sig) ?? []
+ arr.push({
+ id: node.id, name: node.name, type: node.type,
+ width: Math.round(node.width), height: Math.round(node.height), childCount: node.childIds.length
+ })
+ sigMap.set(sig, arr)
+ }
+
+ const clusters = [...sigMap.entries()]
+ .filter(([, nodes]) => nodes.length >= minCount)
+ .map(([signature, nodes]) => ({ signature, nodes }))
+ .sort((a, b) => b.nodes.length - a.nodes.length)
+ .slice(0, limit)
+
+ return { clusters, totalNodes }
+ }
+}
+
+// ── registry ──
+
+export const ALL_RPC_COMMANDS = [
+ infoCommand,
+ pagesCommand,
+ treeCommand,
+ findCommand,
+ nodeCommand,
+ variablesCommand,
+ analyzeColorsCommand,
+ analyzeTypographyCommand,
+ analyzeSpacingCommand,
+ analyzeClustersCommand
+] as RpcCommand[]
+
+export function executeRpcCommand(graph: SceneGraph, name: string, args: unknown): unknown {
+ const cmd = ALL_RPC_COMMANDS.find((c) => c.name === name)
+ if (!cmd) throw new Error(`Unknown command: ${name}`)
+ return cmd.execute(graph, args as never)
+}
diff --git a/packages/core/src/rpc/index.ts b/packages/core/src/rpc/index.ts
new file mode 100644
index 000000000..03fd823fe
--- /dev/null
+++ b/packages/core/src/rpc/index.ts
@@ -0,0 +1,23 @@
+export { executeRpcCommand, ALL_RPC_COMMANDS } from './commands'
+export type {
+ InfoResult,
+ PageItem,
+ TreeArgs,
+ TreeResult,
+ TreeNodeResult,
+ FindArgs,
+ FindNodeResult,
+ NodeArgs,
+ NodeResult,
+ VariablesArgs,
+ VariablesResult,
+ AnalyzeColorsArgs,
+ AnalyzeColorsResult,
+ AnalyzeTypographyArgs,
+ AnalyzeTypographyResult,
+ AnalyzeSpacingResult,
+ SpacingValue,
+ AnalyzeClustersArgs,
+ AnalyzeClustersResult,
+ TypographyStyle
+} from './commands'
diff --git a/src/automation/bridge.ts b/src/automation/bridge.ts
new file mode 100644
index 000000000..a7379fdfc
--- /dev/null
+++ b/src/automation/bridge.ts
@@ -0,0 +1,165 @@
+/**
+ * Automation bridge — runs in the Vite/Bun process (NOT in the browser).
+ *
+ * The browser page connects via WebSocket and registers itself
+ * as the RPC executor. CLI/MCP clients connect via HTTP.
+ *
+ * Flow: CLI → HTTP POST /rpc → bridge → WebSocket → browser → execute → response
+ */
+
+const AUTOMATION_PORT = 7600
+const AUTOMATION_WS_PORT = 7601
+const RPC_TIMEOUT = 30_000
+
+interface PendingRequest {
+ resolve: (value: unknown) => void
+ reject: (error: Error) => void
+ timer: ReturnType<typeof setTimeout>
+}
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Bun WebSocket type not available in browser tsconfig
+type BunWebSocket = any
+
+const pending = new Map<string, PendingRequest>()
+let browserWs: BunWebSocket | null = null
+let authToken: string | null = null
+
+function sendToBrowser(body: Record<string, unknown>): Promise<unknown> {
+ return new Promise((resolve, reject) => {
+ if (!browserWs) {
+ reject(new Error('OpenPencil app is not connected'))
+ return
+ }
+ const id = crypto.randomUUID()
+ const timer = setTimeout(() => {
+ pending.delete(id)
+ reject(new Error('RPC timeout (30s)'))
+ }, RPC_TIMEOUT)
+ pending.set(id, { resolve, reject, timer })
+ browserWs.send(JSON.stringify({ type: 'request', id, ...body }))
+ })
+}
+
+function handleBrowserMessage(data: string) {
+ try {
+ const msg = JSON.parse(data) as {
+ type: string
+ id?: string
+ token?: string
+ result?: unknown
+ error?: string
+ ok?: boolean
+ }
+ if (msg.type === 'register' && msg.token) {
+ authToken = msg.token
+ return
+ }
+ if (msg.type === 'response' && msg.id) {
+ const req = pending.get(msg.id)
+ if (!req) return
+ pending.delete(msg.id)
+ clearTimeout(req.timer)
+ if (msg.ok === false) req.reject(new Error(msg.error ?? 'RPC failed'))
+ else req.resolve(msg.result)
+ }
+ } catch {
+ // ignore
+ }
+}
+
+export function startAutomationBridge() {
+ // @ts-expect-error -- Bun global not in browser tsconfig, but this file runs in Vite/Bun
+ const BunGlobal = globalThis.Bun
+ if (!BunGlobal) {
+ console.warn('[automation] Bun runtime not available, skipping bridge')
+ return
+ }
+
+ BunGlobal.serve({
+ port: AUTOMATION_WS_PORT,
+ hostname: '127.0.0.1',
+ fetch(req: Request, server: { upgrade: (req: Request) => boolean }) {
+ if (server.upgrade(req)) return undefined
+ return new Response('WebSocket only', { status: 400 })
+ },
+ websocket: {
+ open(ws: BunWebSocket) {
+ browserWs = ws
+ },
+ message(_ws: BunWebSocket, message: string | ArrayBuffer) {
+ handleBrowserMessage(
+ typeof message === 'string' ? message : new TextDecoder().decode(message as ArrayBuffer)
+ )
+ },
+ close(ws: BunWebSocket) {
+ if (browserWs === ws) {
+ browserWs = null
+ authToken = null
+ for (const [id, req] of pending) {
+ clearTimeout(req.timer)
+ req.reject(new Error('Browser disconnected'))
+ pending.delete(id)
+ }
+ }
+ }
+ }
+ })
+
+ BunGlobal.serve({
+ port: AUTOMATION_PORT,
+ hostname: '127.0.0.1',
+ async fetch(req: Request) {
+ const url = new URL(req.url)
+ const headers = {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Headers': 'Authorization, Content-Type'
+ }
+
+ if (req.method === 'OPTIONS') {
+ return new Response(null, { status: 204, headers })
+ }
+
+ if (url.pathname === '/health') {
+ return Response.json(
+ {
+ status: browserWs ? 'ok' : 'no_app',
+ ...(browserWs && authToken ? { token: authToken } : {})
+ },
+ { headers }
+ )
+ }
+
+ if (!browserWs || !authToken) {
+ return Response.json(
+ { error: 'OpenPencil app is not connected. Is a document open?' },
+ { status: 503, headers }
+ )
+ }
+
+ const auth = req.headers.get('authorization')
+ const provided = auth?.startsWith('Bearer ') ? auth.slice(7) : null
+ if (provided !== authToken) {
+ return Response.json({ error: 'Unauthorized' }, { status: 401, headers })
+ }
+
+ if (url.pathname === '/rpc' && req.method === 'POST') {
+ const body = await req.json().catch(() => null)
+ if (!body || typeof body !== 'object') {
+ return Response.json({ error: 'Invalid request body' }, { status: 400, headers })
+ }
+ try {
+ const result = await sendToBrowser(body as Record<string, unknown>)
+ return Response.json({ ok: true, result }, { headers })
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e)
+ return Response.json({ ok: false, error: msg }, { status: 502, headers })
+ }
+ }
+
+ return Response.json({ error: 'Not found' }, { status: 404, headers })
+ }
+ })
+
+ console.log(`[automation] HTTP http://127.0.0.1:${AUTOMATION_PORT}`)
+ console.log(`[automation] WS ws://127.0.0.1:${AUTOMATION_WS_PORT}`)
+}
diff --git a/src/automation/server.ts b/src/automation/server.ts
new file mode 100644
index 000000000..b63048d83
--- /dev/null
+++ b/src/automation/server.ts
@@ -0,0 +1,176 @@
+/**
+ * Browser-side automation handler.
+ *
+ * Connects to the bridge via WebSocket, receives RPC requests,
+ * executes them against the live EditorStore, and sends results back.
+ */
+import { ALL_TOOLS, FigmaAPI, executeRpcCommand } from '@open-pencil/core'
+const AUTOMATION_WS_PORT = 7601
+
+import type { EditorStore } from '@/stores/editor'
+import type { ExportFormat } from '@open-pencil/core'
+
+const TOKEN_LENGTH = 32
+
+function generateToken(): string {
+ const bytes = new Uint8Array(TOKEN_LENGTH)
+ crypto.getRandomValues(bytes)
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
+}
+
+export function connectAutomation(getStore: () => EditorStore) {
+ const token = generateToken()
+ let ws: WebSocket | null = null
+ let reconnectTimer: ReturnType<typeof setTimeout> | undefined
+
+ function makeFigma(): FigmaAPI {
+ const store = getStore()
+ const api = new FigmaAPI(store.graph)
+ api.currentPage = api.wrapNode(store.state.currentPageId)
+ api.currentPage.selection = [...store.state.selectedIds]
+ .map((id) => api.getNodeById(id))
+ .filter((n): n is NonNullable<typeof n> => n !== null)
+ api.viewport = {
+ center: {
+ x: (-store.state.panX + window.innerWidth / 2) / store.state.zoom,
+ y: (-store.state.panY + window.innerHeight / 2) / store.state.zoom
+ },
+ zoom: store.state.zoom
+ }
+ api.exportImage = (nodeIds, opts) =>
+ store.renderExportImage(nodeIds, opts.scale ?? 1, (opts.format ?? 'PNG') as ExportFormat)
+ return api
+ }
+
+ async function handleRequest(_id: string, command: string, args: unknown): Promise<unknown> {
+ const store = getStore()
+
+ if (command === 'eval') {
+ const code = (args as { code?: string })?.code
+ if (!code) throw new Error('Missing "code" in args')
+ const figma = makeFigma()
+ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor
+ const wrappedCode = code.trim().startsWith('return')
+ ? code
+ : `return (async () => { ${code} })()`
+ const fn = new AsyncFunction('figma', wrappedCode)
+ const result = await fn(figma)
+ store.requestRender()
+ return { ok: true, result: result ?? null }
+ }
+
+ if (command === 'tool') {
+ const toolName = (args as { name?: string })?.name
+ const toolArgs = (args as { args?: Record<string, unknown> })?.args ?? {}
+ if (!toolName) throw new Error('Missing "name" in args')
+ const def = ALL_TOOLS.find((t) => t.name === toolName)
+ if (!def) throw new Error(`Unknown tool: ${toolName}`)
+ const figma = makeFigma()
+ const result = await def.execute(figma, toolArgs)
+ if (def.mutates) {
+ store.requestRender()
+ store.flashNodes(extractNodeIds(result))
+ }
+ return { ok: true, result }
+ }
+
+ if (command === 'export') {
+ const exportArgs = args as { nodeIds?: string[]; scale?: number; format?: string } | undefined
+ const nodeIds = exportArgs?.nodeIds ?? [...store.state.selectedIds]
+ if (nodeIds.length === 0) throw new Error('No nodes to export')
+ const data = await store.renderExportImage(
+ nodeIds,
+ exportArgs?.scale ?? 1,
+ (exportArgs?.format ?? 'PNG') as ExportFormat
+ )
+ if (!data) throw new Error('Export failed')
+ const base64 = btoa(String.fromCharCode(...data))
+ return { ok: true, base64, mimeType: `image/${(exportArgs?.format ?? 'png').toLowerCase()}` }
+ }
+
+ const result = executeRpcCommand(store.graph, command, args ?? {})
+ return { ok: true, result }
+ }
+
+ function connect() {
+ try {
+ ws = new WebSocket(`ws://127.0.0.1:${AUTOMATION_WS_PORT}`)
+ } catch {
+ scheduleReconnect()
+ return
+ }
+
+ ws.onopen = () => {
+ ws?.send(JSON.stringify({ type: 'register', token }))
+ }
+
+ ws.onmessage = async (event) => {
+ try {
+ const msg = JSON.parse(event.data) as {
+ type: string
+ id: string
+ command: string
+ args?: unknown
+ }
+ if (msg.type !== 'request' || !msg.id) return
+ try {
+ const result = await handleRequest(msg.id, msg.command, msg.args)
+ ws?.send(JSON.stringify({ type: 'response', id: msg.id, ...(result as object) }))
+ } catch (e) {
+ ws?.send(
+ JSON.stringify({
+ type: 'response',
+ id: msg.id,
+ ok: false,
+ error: e instanceof Error ? e.message : String(e)
+ })
+ )
+ }
+ } catch {
+ // ignore parse errors
+ }
+ }
+
+ ws.onclose = () => {
+ ws = null
+ scheduleReconnect()
+ }
+
+ ws.onerror = () => {
+ ws?.close()
+ }
+ }
+
+ function scheduleReconnect() {
+ clearTimeout(reconnectTimer)
+ reconnectTimer = setTimeout(connect, 2000)
+ }
+
+ function disconnect() {
+ clearTimeout(reconnectTimer)
+ ws?.close()
+ ws = null
+ }
+
+ connect()
+ return { disconnect, token }
+}
+
+function extractNodeIds(result: unknown): string[] {
+ if (!result || typeof result !== 'object') return []
+ const obj = result as Record<string, unknown>
+ if (typeof obj.deleted === 'string') return []
+ const ids: string[] = []
+ if (typeof obj.id === 'string') ids.push(obj.id)
+ if (Array.isArray(obj.results)) {
+ for (const item of obj.results) {
+ if (
+ item &&
+ typeof item === 'object' &&
+ typeof (item as Record<string, unknown>).id === 'string'
+ )
+ ids.push((item as Record<string, unknown>).id as string)
+ }
+ }
+ return ids
+}
diff --git a/src/automation/vite-plugin.ts b/src/automation/vite-plugin.ts
new file mode 100644
index 000000000..86638564c
--- /dev/null
+++ b/src/automation/vite-plugin.ts
@@ -0,0 +1,12 @@
+import type { Plugin } from 'vite'
+
+export function automationPlugin(): Plugin {
+ return {
+ name: 'open-pencil-automation',
+ configureServer() {
+ import('./bridge').then(({ startAutomationBridge }) => {
+ startAutomationBridge()
+ })
+ }
+ }
+}
diff --git a/src/views/EditorView.vue b/src/views/EditorView.vue
index 3c2bf1520..852953dff 100644
--- a/src/views/EditorView.vue
+++ b/src/views/EditorView.vue
@@ -8,9 +8,10 @@ import { SplitterGroup, SplitterPanel, SplitterResizeHandle } from 'reka-ui'
import { useKeyboard } from '@/composables/use-keyboard'
import { useMenu } from '@/composables/use-menu'
import { useCollab, COLLAB_KEY } from '@/composables/use-collab'
+import { connectAutomation } from '@/automation/server'
import { createDemoShapes } from '@/demo'
import { useEditorStore } from '@/stores/editor'
-import { createTab, activeTab } from '@/stores/tabs'
+import { createTab, activeTab, getActiveStore } from '@/stores/tabs'
import CollabPanel from '@/components/CollabPanel.vue'
import EditorCanvas from '@/components/EditorCanvas.vue'
@@ -29,6 +30,7 @@ const breakpoints = useBreakpoints({ mobile: 768 })
const isMobile = breakpoints.smaller('mobile')
useKeyboard()
useMenu()
+connectAutomation(getActiveStore)
const collab = useCollab(firstTab.store)
provide(COLLAB_KEY, collab)
diff --git a/vite.config.ts b/vite.config.ts
index 57ac14f9c..552b92ea9 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -9,6 +9,8 @@ import Components from 'unplugin-vue-components/vite'
import { VitePWA } from 'vite-plugin-pwa'
import { copyFileSync, existsSync, mkdirSync } from 'fs'
+import { automationPlugin } from './src/automation/vite-plugin'
+
// @ts-expect-error process is a nodejs global
const host = process.env.TAURI_DEV_HOST
@@ -48,6 +50,7 @@ export default defineConfig(async () => ({
tailwindcss(),
Icons({ compiler: 'vue3' }),
Components({ resolvers: [IconsResolver({ prefix: 'icon' })] }),
+ automationPlugin(),
vue(),
VitePWA({
registerType: 'autoUpdate',