@tdsoft-tech/aikit 0.1.2

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../node_modules/tsup/assets/esm_shims.js","../src/utils/paths.ts","../src/utils/logger.ts","../src/core/tools/figma-mcp.ts","../src/core/tools/figma-screen-developer.ts","../src/core/memory.ts","../src/mcp-server.ts","../src/core/config.ts","../src/core/skills.ts","../src/core/agents.ts","../src/core/commands.ts","../src/core/tools.ts","../src/core/tool-config.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","import { homedir } from 'os';\nimport { join } from 'path';\nimport { existsSync } from 'fs';\n\n/**\n * Path utilities for AIKit configuration and data directories\n */\nexport const paths = {\n /**\n * Get the global AIKit configuration directory\n * ~/.config/aikit/ on Unix, %APPDATA%/aikit/ on Windows\n */\n globalConfig(): string {\n const base = process.platform === 'win32'\n ? process.env.APPDATA || join(homedir(), 'AppData', 'Roaming')\n : join(homedir(), '.config');\n return join(base, 'aikit');\n },\n\n /**\n * Get the project-level AIKit configuration directory\n */\n projectConfig(projectPath?: string): string {\n const base = projectPath || process.cwd();\n return join(base, '.aikit');\n },\n\n /**\n * Get the OpenCode configuration directory\n */\n opencodeConfig(): string {\n const base = process.platform === 'win32'\n ? process.env.APPDATA || join(homedir(), 'AppData', 'Roaming')\n : join(homedir(), '.config');\n return join(base, 'opencode');\n },\n\n /**\n * Get the Beads directory for the current project\n */\n beadsDir(projectPath?: string): string {\n const base = projectPath || process.cwd();\n return join(base, '.beads');\n },\n\n /**\n * Check if a project has AIKit initialized\n */\n hasProjectConfig(projectPath?: string): boolean {\n return existsSync(this.projectConfig(projectPath));\n },\n\n /**\n * Check if global AIKit is initialized\n */\n hasGlobalConfig(): boolean {\n return existsSync(this.globalConfig());\n },\n\n /**\n * Get effective config path (project takes precedence over global)\n */\n effectiveConfig(projectPath?: string): string | null {\n if (this.hasProjectConfig(projectPath)) {\n return this.projectConfig(projectPath);\n }\n if (this.hasGlobalConfig()) {\n return this.globalConfig();\n }\n return null;\n },\n\n /**\n * Get skills directory\n */\n skills(configPath: string): string {\n return join(configPath, 'skills');\n },\n\n /**\n * Get agents directory\n */\n agents(configPath: string): string {\n return join(configPath, 'agents');\n },\n\n /**\n * Get commands directory\n */\n commands(configPath: string): string {\n return join(configPath, 'commands');\n },\n\n /**\n * Get tools directory\n */\n tools(configPath: string): string {\n return join(configPath, 'tools');\n },\n\n /**\n * Get plugins directory\n */\n plugins(configPath: string): string {\n return join(configPath, 'plugins');\n },\n\n /**\n * Get memory directory\n */\n memory(configPath: string): string {\n return join(configPath, 'memory');\n },\n};\n","import chalk from 'chalk';\n\n/**\n * Simple logger with colored output\n */\nexport const logger = {\n info(...args: unknown[]): void {\n console.log(chalk.blue('ℹ'), ...args);\n },\n\n success(...args: unknown[]): void {\n console.log(chalk.green('✓'), ...args);\n },\n\n warn(...args: unknown[]): void {\n console.log(chalk.yellow('⚠'), ...args);\n },\n\n error(...args: unknown[]): void {\n console.error(chalk.red('✖'), ...args);\n },\n\n debug(...args: unknown[]): void {\n if (process.env.DEBUG || process.env.AIKIT_DEBUG) {\n console.log(chalk.gray('⋯'), ...args);\n }\n },\n\n step(step: number, total: number, message: string): void {\n console.log(chalk.cyan(`[${step}/${total}]`), message);\n },\n\n header(message: string): void {\n console.log(chalk.bold.underline(`\\n${message}\\n`));\n },\n\n list(items: string[], prefix = '•'): void {\n for (const item of items) {\n console.log(` ${prefix} ${item}`);\n }\n },\n};\n","import { ToolConfigManager } from '../tool-config.js';\nimport { logger } from '../../utils/logger.js';\nimport { writeFile, mkdir } from 'fs/promises';\nimport { join, dirname } from 'path';\nimport { existsSync } from 'fs';\n\n/**\n * Figma API response types\n */\nexport interface FigmaFile {\n document: FigmaNode;\n components: Record<string, FigmaComponent>;\n styles: Record<string, FigmaStyle>;\n}\n\nexport interface FigmaNode {\n id: string;\n name: string;\n type: string;\n children?: FigmaNode[];\n fills?: FigmaFill[];\n strokes?: FigmaFill[];\n effects?: FigmaEffect[];\n absoluteBoundingBox?: {\n x: number;\n y: number;\n width: number;\n height: number;\n };\n style?: {\n fontFamily?: string;\n fontSize?: number;\n fontWeight?: number;\n lineHeightPx?: number;\n letterSpacing?: number;\n };\n characters?: string;\n layoutMode?: 'HORIZONTAL' | 'VERTICAL';\n paddingLeft?: number;\n paddingRight?: number;\n paddingTop?: number;\n paddingBottom?: number;\n itemSpacing?: number;\n}\n\nexport interface FigmaFill {\n type: string;\n color?: {\n r: number;\n g: number;\n b: number;\n a: number;\n };\n imageRef?: string;\n}\n\nexport interface FigmaEffect {\n type: string;\n visible: boolean;\n radius?: number;\n color?: {\n r: number;\n g: number;\n b: number;\n a: number;\n };\n}\n\nexport interface FigmaComponent {\n key: string;\n name: string;\n description: string;\n}\n\nexport interface FigmaStyle {\n key: string;\n name: string;\n styleType: 'FILL' | 'TEXT' | 'EFFECT' | 'GRID';\n}\n\n/**\n * Extracted design tokens\n */\nexport interface DesignTokens {\n colors: Array<{\n name: string;\n hex: string;\n rgba: string;\n }>;\n typography: Array<{\n name: string;\n fontFamily: string;\n fontSize: number;\n fontWeight: number;\n lineHeight: number;\n letterSpacing?: number;\n }>;\n spacing: {\n unit: number;\n scale: number[];\n };\n components: Array<{\n name: string;\n type: string;\n description?: string;\n }>;\n screens: Array<{\n id: string;\n name: string;\n width: number;\n height: number;\n type: string;\n description?: string;\n childrenCount?: number;\n }>;\n breakpoints: number[];\n structure?: {\n nodes: Array<{\n id: string;\n name: string;\n type: string;\n content?: string;\n position?: { x: number; y: number; width: number; height: number };\n styles?: {\n backgroundColor?: string;\n fontSize?: number;\n fontFamily?: string;\n fontWeight?: number;\n color?: string;\n padding?: { top: number; right: number; bottom: number; left: number };\n margin?: { top: number; right: number; bottom: number; left: number };\n layout?: 'HORIZONTAL' | 'VERTICAL' | 'NONE';\n gap?: number;\n };\n children?: string[]; // IDs of child nodes\n }>;\n hierarchy: string; // Tree structure representation\n };\n assets?: Array<{\n nodeId: string;\n nodeName: string;\n nodeType: string;\n format: 'png' | 'svg' | 'jpg';\n path: string;\n url: string;\n width?: number;\n height?: number;\n }>;\n}\n\n/**\n * Figma MCP Client\n * \n * Wrapper for figma-developer-mcp to extract design data\n */\nexport class FigmaMcpClient {\n private apiKey: string;\n private configManager: ToolConfigManager;\n\n constructor(apiKey: string, configManager: ToolConfigManager) {\n this.apiKey = apiKey;\n this.configManager = configManager;\n }\n\n /**\n * Fetch helper with simple retry/backoff for 429/5xx\n */\n private async fetchWithRetry(\n url: string,\n options: RequestInit,\n label: string,\n retries: number = 3,\n backoffMs: number = 1500\n ): Promise<Response> {\n let attempt = 0;\n let lastError: any;\n\n while (attempt <= retries) {\n try {\n const res = await fetch(url, options);\n if (res.ok) return res;\n\n // Retry on throttling or server errors\n if (res.status === 429 || res.status >= 500) {\n const retryAfter = Number(res.headers.get('retry-after')) || 0;\n const delay = retryAfter > 0 ? retryAfter * 1000 : backoffMs * (attempt + 1);\n logger.warn(`${label} failed (status ${res.status}), retrying in ${Math.round(delay / 1000)}s...`);\n await new Promise((r) => setTimeout(r, delay));\n attempt += 1;\n continue;\n }\n\n const text = await res.text();\n throw new Error(`${label} error: ${res.status} ${res.statusText}\\n${text}`);\n } catch (err) {\n lastError = err;\n // Retry network errors\n logger.warn(`${label} network error, attempt ${attempt + 1}/${retries + 1}: ${err instanceof Error ? err.message : String(err)}`);\n if (attempt >= retries) break;\n await new Promise((r) => setTimeout(r, backoffMs * (attempt + 1)));\n attempt += 1;\n }\n }\n\n throw lastError instanceof Error\n ? lastError\n : new Error(`${label} failed after retries`);\n }\n\n /**\n * Extract file key from Figma URL\n */\n private extractFileKey(url: string): string | null {\n // URL format: https://www.figma.com/design/{fileKey}/...\n const match = url.match(/figma\\.com\\/design\\/([a-zA-Z0-9]+)/);\n return match ? match[1] : null;\n }\n\n /**\n * Extract node ID from Figma URL\n */\n private extractNodeId(url: string): string | null {\n // URL format: ...?node-id={nodeId} or ...&node-id={nodeId}\n // Node ID can be in format: 0-1, 1-2, etc. (page-frame format)\n const match = url.match(/[?&]node-id=([^&]+)/);\n if (!match) return null;\n \n // Decode and handle different formats\n let nodeId = decodeURIComponent(match[1]);\n \n // If it's in format \"0-1\", convert to \"0:1\" for API\n // Figma API uses colon separator, not dash\n if (nodeId.includes('-') && !nodeId.includes(':')) {\n nodeId = nodeId.replace(/-/g, ':');\n }\n \n return nodeId;\n }\n\n /**\n * Get Figma file data using API\n */\n async getFileData(url: string): Promise<FigmaFile> {\n const fileKey = this.extractFileKey(url);\n if (!fileKey) {\n throw new Error(`Invalid Figma URL: ${url}`);\n }\n\n const nodeId = this.extractNodeId(url);\n const apiUrl = nodeId\n ? `https://api.figma.com/v1/files/${fileKey}/nodes?ids=${encodeURIComponent(nodeId)}`\n : `https://api.figma.com/v1/files/${fileKey}`;\n\n const response = await this.fetchWithRetry(apiUrl, {\n headers: {\n 'X-Figma-Token': this.apiKey,\n },\n }, 'Figma file fetch');\n\n const data = await response.json();\n \n if (nodeId) {\n // Return specific node data\n const nodes = data.nodes as Record<string, { document: FigmaNode }>;\n const nodeData = Object.values(nodes)[0];\n if (!nodeData) {\n throw new Error(`Node not found: ${nodeId}`);\n }\n return {\n document: nodeData.document,\n components: {},\n styles: {},\n };\n }\n\n return data as FigmaFile;\n }\n\n /**\n * Extract design tokens from Figma file\n */\n async extractDesignTokens(url: string, downloadAssets: boolean = true, assetsDir?: string): Promise<DesignTokens> {\n const fileData = await this.getFileData(url);\n const fileKey = this.extractFileKey(url);\n if (!fileKey) {\n throw new Error(`Invalid Figma URL: ${url}`);\n }\n\n const tokens: DesignTokens = {\n colors: [],\n typography: [],\n spacing: {\n unit: 8, // Default 8px grid\n scale: [],\n },\n components: [],\n screens: [],\n breakpoints: [375, 768, 1024, 1280, 1920], // Common breakpoints\n };\n\n // Extract colors\n const colorMap = new Map<string, string>();\n this.extractColors(fileData.document, colorMap);\n tokens.colors = Array.from(colorMap.entries()).map(([name, hex]) => ({\n name,\n hex,\n rgba: hex, // Simplified\n }));\n\n // Extract typography\n const typographyMap = new Map<string, any>();\n this.extractTypography(fileData.document, typographyMap);\n tokens.typography = Array.from(typographyMap.values());\n\n // Extract components\n Object.values(fileData.components).forEach(component => {\n tokens.components.push({\n name: component.name,\n type: 'component',\n description: component.description,\n });\n });\n\n // Extract screens/frames\n this.extractScreens(fileData.document, tokens.screens);\n\n // Extract structure and content\n tokens.structure = this.extractStructure(fileData.document);\n\n // Download assets if requested\n if (downloadAssets && tokens.structure) {\n try {\n tokens.assets = await this.downloadAssets(\n fileKey,\n fileData.document,\n assetsDir || './assets/images'\n );\n } catch (error) {\n logger.warn(`Failed to download assets: ${error instanceof Error ? error.message : String(error)}`);\n // Continue without assets\n }\n }\n\n return tokens;\n }\n\n /**\n * Recursively extract colors from nodes\n */\n private extractColors(node: FigmaNode, colorMap: Map<string, string>): void {\n // Extract fills\n if (node.fills && Array.isArray(node.fills)) {\n node.fills.forEach(fill => {\n if (fill.type === 'SOLID' && fill.color) {\n const { r, g, b, a } = fill.color;\n const hex = this.rgbaToHex(r, g, b, a);\n const name = node.name || 'Color';\n if (!colorMap.has(hex)) {\n colorMap.set(hex, hex);\n }\n }\n });\n }\n\n // Extract strokes\n if (node.strokes && Array.isArray(node.strokes)) {\n node.strokes.forEach(stroke => {\n if (stroke.type === 'SOLID' && stroke.color) {\n const { r, g, b, a } = stroke.color;\n const hex = this.rgbaToHex(r, g, b, a);\n if (!colorMap.has(hex)) {\n colorMap.set(hex, hex);\n }\n }\n });\n }\n\n // Recurse children\n if (node.children) {\n node.children.forEach(child => this.extractColors(child, colorMap));\n }\n }\n\n /**\n * Recursively extract typography from nodes\n */\n private extractTypography(node: FigmaNode, typographyMap: Map<string, any>): void {\n if (node.type === 'TEXT' && node.style) {\n const key = `${node.style.fontFamily}-${node.style.fontSize}-${node.style.fontWeight}`;\n if (!typographyMap.has(key)) {\n typographyMap.set(key, {\n name: `${node.style.fontSize}px ${node.style.fontFamily}`,\n fontFamily: node.style.fontFamily || 'Inter',\n fontSize: node.style.fontSize || 16,\n fontWeight: node.style.fontWeight || 400,\n lineHeight: node.style.lineHeightPx || node.style.fontSize || 16,\n letterSpacing: node.style.letterSpacing,\n });\n }\n }\n\n if (node.children) {\n node.children.forEach(child => this.extractTypography(child, typographyMap));\n }\n }\n\n /**\n * Extract screens/frames with detailed information\n */\n private extractScreens(\n node: FigmaNode, \n screens: Array<{\n id: string;\n name: string;\n width: number;\n height: number;\n type: string;\n description?: string;\n childrenCount?: number;\n }>\n ): void {\n if (node.type === 'FRAME' || node.type === 'COMPONENT') {\n if (node.absoluteBoundingBox) {\n // Only include main screens (skip nested frames that are too small or decorative)\n const isMainScreen = node.absoluteBoundingBox.width >= 800 && \n node.absoluteBoundingBox.height >= 400;\n \n if (isMainScreen) {\n screens.push({\n id: node.id,\n name: node.name,\n width: node.absoluteBoundingBox.width,\n height: node.absoluteBoundingBox.height,\n type: node.type,\n childrenCount: node.children?.length || 0,\n });\n }\n }\n }\n\n if (node.children) {\n node.children.forEach(child => this.extractScreens(child, screens));\n }\n }\n\n /**\n * Extract structure, content, and layout from nodes\n */\n private extractStructure(node: FigmaNode, depth: number = 0): {\n nodes: Array<{\n id: string;\n name: string;\n type: string;\n content?: string;\n position?: { x: number; y: number; width: number; height: number };\n styles?: {\n backgroundColor?: string;\n fontSize?: number;\n fontFamily?: string;\n fontWeight?: number;\n color?: string;\n padding?: { top: number; right: number; bottom: number; left: number };\n margin?: { top: number; right: number; bottom: number; left: number };\n layout?: 'HORIZONTAL' | 'VERTICAL' | 'NONE';\n gap?: number;\n };\n children?: string[];\n }>;\n hierarchy: string;\n } {\n const nodes: Array<{\n id: string;\n name: string;\n type: string;\n content?: string;\n position?: { x: number; y: number; width: number; height: number };\n styles?: any;\n children?: string[];\n }> = [];\n const hierarchyLines: string[] = [];\n\n const processNode = (n: FigmaNode, level: number = 0): string[] => {\n const indent = ' '.repeat(level);\n const childIds: string[] = [];\n\n // Extract node data\n const nodeData: any = {\n id: n.id,\n name: n.name || 'Unnamed',\n type: n.type,\n };\n\n // Extract position\n if (n.absoluteBoundingBox) {\n nodeData.position = {\n x: n.absoluteBoundingBox.x,\n y: n.absoluteBoundingBox.y,\n width: n.absoluteBoundingBox.width,\n height: n.absoluteBoundingBox.height,\n };\n }\n\n // Extract text content\n if (n.type === 'TEXT' && n.characters) {\n nodeData.content = n.characters;\n }\n\n // Extract styles\n const styles: any = {};\n \n // Background color\n if (n.fills && Array.isArray(n.fills)) {\n const solidFill = n.fills.find(f => f.type === 'SOLID' && f.color);\n if (solidFill && solidFill.color) {\n const { r, g, b, a } = solidFill.color;\n styles.backgroundColor = this.rgbaToHex(r, g, b, a);\n }\n }\n\n // Text styles\n if (n.style) {\n if (n.style.fontFamily) styles.fontFamily = n.style.fontFamily;\n if (n.style.fontSize) styles.fontSize = n.style.fontSize;\n if (n.style.fontWeight) styles.fontWeight = n.style.fontWeight;\n if (n.style.lineHeightPx) styles.lineHeight = n.style.lineHeightPx;\n \n // Text color from fills\n if (n.fills && Array.isArray(n.fills)) {\n const textFill = n.fills.find(f => f.type === 'SOLID' && f.color);\n if (textFill && textFill.color) {\n const { r, g, b, a } = textFill.color;\n styles.color = this.rgbaToHex(r, g, b, a);\n }\n }\n }\n\n // Layout properties\n if (n.layoutMode) {\n styles.layout = n.layoutMode;\n }\n if (n.itemSpacing !== undefined) {\n styles.gap = n.itemSpacing;\n }\n\n // Padding\n if (n.paddingLeft || n.paddingRight || n.paddingTop || n.paddingBottom) {\n styles.padding = {\n top: n.paddingTop || 0,\n right: n.paddingRight || 0,\n bottom: n.paddingBottom || 0,\n left: n.paddingLeft || 0,\n };\n }\n\n if (Object.keys(styles).length > 0) {\n nodeData.styles = styles;\n }\n\n // Process children\n if (n.children && n.children.length > 0) {\n n.children.forEach(child => {\n const childNodeIds = processNode(child, level + 1);\n childIds.push(child.id);\n childIds.push(...childNodeIds);\n });\n nodeData.children = n.children.map(c => c.id);\n }\n\n nodes.push(nodeData);\n\n // Build hierarchy string\n const typeLabel = n.type.toLowerCase();\n const nameLabel = n.name || 'Unnamed';\n const contentPreview = n.type === 'TEXT' && n.characters \n ? `: \"${n.characters.substring(0, 50)}${n.characters.length > 50 ? '...' : ''}\"`\n : '';\n const sizeLabel = n.absoluteBoundingBox\n ? ` [${Math.round(n.absoluteBoundingBox.width)}×${Math.round(n.absoluteBoundingBox.height)}]`\n : '';\n \n hierarchyLines.push(`${indent}${typeLabel} \"${nameLabel}\"${contentPreview}${sizeLabel}`);\n\n return [n.id, ...childIds];\n };\n\n processNode(node, depth);\n\n return {\n nodes,\n hierarchy: hierarchyLines.join('\\n'),\n };\n }\n\n /**\n * Find all nodes that can be exported as images (optionally filtered by screen)\n */\n private findImageNodes(\n node: FigmaNode, \n imageNodes: Array<{ id: string; name: string; type: string; width?: number; height?: number }> = [],\n screenId?: string,\n isWithinScreen: boolean = false\n ): void {\n // Check if we're within the target screen\n const currentIsScreen = node.id === screenId;\n const nowWithinScreen = isWithinScreen || currentIsScreen;\n \n // If screenId is specified and we're not within that screen, skip\n if (screenId && !nowWithinScreen && node.type !== 'PAGE') {\n // Continue searching children\n if (node.children) {\n node.children.forEach(child => this.findImageNodes(child, imageNodes, screenId, false));\n }\n return;\n }\n // Exportable node types\n const exportableTypes = ['VECTOR', 'COMPONENT', 'INSTANCE', 'FRAME', 'GROUP', 'RECTANGLE', 'ELLIPSE'];\n \n // Check if node has image fills or is exportable\n const hasImageFill = node.fills?.some(fill => fill.type === 'IMAGE' || fill.imageRef);\n const isExportable = exportableTypes.includes(node.type) || hasImageFill;\n\n if (isExportable && node.absoluteBoundingBox) {\n // Skip very small nodes (likely decorative)\n const minSize = 16;\n if (node.absoluteBoundingBox.width >= minSize && node.absoluteBoundingBox.height >= minSize) {\n imageNodes.push({\n id: node.id,\n name: node.name || 'Unnamed',\n type: node.type,\n width: node.absoluteBoundingBox.width,\n height: node.absoluteBoundingBox.height,\n });\n }\n }\n\n // Recurse children\n if (node.children) {\n node.children.forEach(child => this.findImageNodes(child, imageNodes, screenId, nowWithinScreen));\n }\n }\n\n /**\n * Download images/assets from Figma (optionally filtered by screen)\n */\n async downloadAssets(\n fileKey: string,\n rootNode: FigmaNode,\n assetsDir: string,\n screenId?: string // Optional: only download assets for specific screen\n ): Promise<Array<{\n nodeId: string;\n nodeName: string;\n nodeType: string;\n format: 'png' | 'svg' | 'jpg';\n path: string;\n url: string;\n width?: number;\n height?: number;\n }>> {\n // Find all image nodes (optionally filtered by screen)\n const imageNodes: Array<{ id: string; name: string; type: string; width?: number; height?: number }> = [];\n this.findImageNodes(rootNode, imageNodes, screenId);\n\n if (imageNodes.length === 0) {\n logger.info('No image nodes found to download');\n return [];\n }\n\n logger.info(`Found ${imageNodes.length} image nodes to download`);\n\n // Limit to first 50 nodes to avoid API limits\n const nodesToDownload = imageNodes.slice(0, 50);\n const nodeIds = nodesToDownload.map(n => n.id).join(',');\n\n // Request image URLs from Figma API\n // Use PNG format by default, SVG for vectors\n const imageUrl = `https://api.figma.com/v1/images/${fileKey}?ids=${encodeURIComponent(nodeIds)}&format=png&scale=2`;\n \n const response = await this.fetchWithRetry(imageUrl, {\n headers: {\n 'X-Figma-Token': this.apiKey,\n },\n }, 'Figma images listing');\n\n const imageData = await response.json();\n const images = imageData.images as Record<string, string>;\n\n // Ensure assets directory exists\n const fullAssetsDir = assetsDir.startsWith('/') ? assetsDir : join(process.cwd(), assetsDir);\n if (!existsSync(fullAssetsDir)) {\n await mkdir(fullAssetsDir, { recursive: true });\n }\n\n // Download each image\n const downloadedAssets: Array<{\n nodeId: string;\n nodeName: string;\n nodeType: string;\n format: 'png' | 'svg' | 'jpg';\n path: string;\n url: string;\n width?: number;\n height?: number;\n }> = [];\n\n for (const node of nodesToDownload) {\n const imageUrl = images[node.id];\n if (!imageUrl) {\n logger.warn(`No image URL returned for node ${node.id} (${node.name})`);\n continue;\n }\n\n try {\n // Download image\n const imageResponse = await this.fetchWithRetry(\n imageUrl,\n {},\n `Download image ${node.id}`\n );\n\n const imageBuffer = await imageResponse.arrayBuffer();\n \n // Generate safe filename\n const safeName = node.name\n .replace(/[^a-z0-9]/gi, '_')\n .toLowerCase()\n .substring(0, 50);\n const extension = 'png'; // PNG format\n const filename = `${safeName}_${node.id.substring(0, 8)}.${extension}`;\n const filePath = join(fullAssetsDir, filename);\n\n // Write file\n await writeFile(filePath, Buffer.from(imageBuffer));\n\n downloadedAssets.push({\n nodeId: node.id,\n nodeName: node.name,\n nodeType: node.type,\n format: extension as 'png',\n path: filePath,\n url: imageUrl,\n width: node.width,\n height: node.height,\n });\n\n logger.info(`Downloaded: ${filename} (${node.name})`);\n } catch (error) {\n logger.warn(`Error downloading image for node ${node.id}: ${error instanceof Error ? error.message : String(error)}`);\n // Continue with other images\n }\n }\n\n logger.info(`Downloaded ${downloadedAssets.length} assets to ${fullAssetsDir}`);\n return downloadedAssets;\n }\n\n /**\n * Convert RGBA to hex\n */\n private rgbaToHex(r: number, g: number, b: number, a: number = 1): string {\n const toHex = (n: number) => {\n const hex = Math.round(n * 255).toString(16);\n return hex.length === 1 ? '0' + hex : hex;\n };\n return `#${toHex(r)}${toHex(g)}${toHex(b)}${a < 1 ? toHex(a) : ''}`;\n }\n}\n\n","import { logger } from '../../utils/logger.js';\nimport { readFile, readdir } from 'fs/promises';\nimport { join } from 'path';\nimport { existsSync } from 'fs';\n\n/**\n * Check current source code status\n */\nexport async function checkCurrentCodeStatus(projectPath: string = process.cwd()): Promise<{\n hasHTML: boolean;\n htmlFile?: string;\n hasCSS: boolean;\n cssFiles: string[];\n hasAssets: boolean;\n assetCount: number;\n sections: string[];\n}> {\n const status = {\n hasHTML: false,\n htmlFile: undefined as string | undefined,\n hasCSS: false,\n cssFiles: [] as string[],\n hasAssets: false,\n assetCount: 0,\n sections: [] as string[],\n };\n\n try {\n // Check for HTML files\n const htmlFiles = ['index.html', 'index.htm', 'main.html'].filter(file => \n existsSync(join(projectPath, file))\n );\n if (htmlFiles.length > 0) {\n status.hasHTML = true;\n status.htmlFile = htmlFiles[0];\n \n // Try to read HTML to extract sections\n try {\n const htmlContent = await readFile(join(projectPath, htmlFiles[0]), 'utf-8');\n // Extract section IDs and classes\n const sectionMatches = htmlContent.match(/<(section|div|header|footer|main|article|aside)[^>]*(?:id|class)=[\"']([^\"']+)[\"']/gi);\n if (sectionMatches) {\n status.sections = sectionMatches.map(match => {\n const idMatch = match.match(/id=[\"']([^\"']+)[\"']/i);\n const classMatch = match.match(/class=[\"']([^\"']+)[\"']/i);\n return idMatch ? idMatch[1] : (classMatch ? classMatch[1].split(' ')[0] : '');\n }).filter(Boolean);\n }\n } catch (e) {\n // Ignore read errors\n }\n }\n\n // Check for CSS files\n const stylesDir = join(projectPath, 'styles');\n if (existsSync(stylesDir)) {\n try {\n const files = await readdir(stylesDir);\n const cssFiles = files.filter(f => f.endsWith('.css'));\n if (cssFiles.length > 0) {\n status.hasCSS = true;\n status.cssFiles = cssFiles.map(f => join(stylesDir, f));\n }\n } catch (e) {\n // Ignore read errors\n }\n }\n\n // Check for assets\n const assetsDir = join(projectPath, 'assets', 'images');\n if (existsSync(assetsDir)) {\n try {\n const files = await readdir(assetsDir);\n const imageFiles = files.filter(f => /\\.(png|jpg|jpeg|svg|webp)$/i.test(f));\n if (imageFiles.length > 0) {\n status.hasAssets = true;\n status.assetCount = imageFiles.length;\n }\n } catch (e) {\n // Ignore read errors\n }\n }\n } catch (error) {\n logger.warn(`Error checking code status: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n return status;\n}\n\n/**\n * Compare current code with Figma design to identify what needs to be implemented\n */\nexport async function compareCodeWithFigma(\n figmaTokens: any,\n selectedScreenId: string,\n projectPath: string = process.cwd()\n): Promise<{\n missingSections: string[];\n missingAssets: string[];\n needsUpdate: boolean;\n recommendations: string[];\n}> {\n const codeStatus = await checkCurrentCodeStatus(projectPath);\n const result = {\n missingSections: [] as string[],\n missingAssets: [] as string[],\n needsUpdate: false,\n recommendations: [] as string[],\n };\n\n // Find selected screen\n const selectedScreen = figmaTokens.screens?.find((s: any) => s.id === selectedScreenId);\n if (!selectedScreen) {\n result.recommendations.push('Selected screen not found in Figma design');\n return result;\n }\n\n // Extract sections from Figma structure\n const figmaSections: string[] = [];\n if (figmaTokens.structure?.nodes) {\n const screenNode = figmaTokens.structure.nodes.find((n: any) => n.id === selectedScreenId);\n if (screenNode?.children) {\n // Extract main sections from children\n screenNode.children.forEach((childId: string) => {\n const childNode = figmaTokens.structure.nodes.find((n: any) => n.id === childId);\n if (childNode && (childNode.type === 'FRAME' || childNode.type === 'COMPONENT')) {\n const sectionName = childNode.name.toLowerCase()\n .replace(/[^a-z0-9]/g, '-')\n .replace(/-+/g, '-');\n figmaSections.push(sectionName);\n }\n });\n }\n }\n\n // Compare sections\n const existingSections = codeStatus.sections.map(s => s.toLowerCase());\n result.missingSections = figmaSections.filter(s => \n !existingSections.some(existing => existing.includes(s) || s.includes(existing))\n );\n\n // Check assets\n if (codeStatus.assetCount === 0) {\n result.missingAssets.push('All assets need to be downloaded');\n result.needsUpdate = true;\n }\n\n // Generate recommendations\n if (!codeStatus.hasHTML) {\n result.recommendations.push('Create index.html with HTML5 structure');\n }\n if (!codeStatus.hasCSS) {\n result.recommendations.push('Create CSS files (variables.css, base.css, components.css)');\n }\n if (result.missingSections.length > 0) {\n result.recommendations.push(`Implement missing sections: ${result.missingSections.join(', ')}`);\n }\n if (result.missingAssets.length > 0) {\n result.recommendations.push('Download required assets from Figma');\n }\n\n return result;\n}\n\n\n\n\n","import { readFile, writeFile, mkdir, access, constants } from 'fs/promises';\nimport { join } from 'path';\nimport { Config } from './config.js';\nimport { paths } from '../utils/paths.js';\n\n/**\n * Memory entry structure\n */\nexport interface Memory {\n key: string;\n content: string;\n summary: string;\n createdAt: Date;\n updatedAt: Date;\n type: 'observation' | 'handoff' | 'research' | 'template' | 'custom';\n}\n\n/**\n * Memory Manager - Persistent context across sessions\n */\nexport class MemoryManager {\n private config: Config;\n\n constructor(config: Config) {\n this.config = config;\n }\n\n /**\n * List all memory entries\n */\n async list(): Promise<Memory[]> {\n const memories: Memory[] = [];\n const memoryPath = paths.memory(this.config.configPath);\n \n const subDirs = ['observations', 'handoffs', 'research'];\n \n for (const subDir of subDirs) {\n const dirPath = join(memoryPath, subDir);\n try {\n const { readdir } = await import('fs/promises');\n const files = await readdir(dirPath);\n \n for (const file of files) {\n if (!file.endsWith('.md')) continue;\n \n const content = await readFile(join(dirPath, file), 'utf-8');\n const summary = this.extractSummary(content);\n \n memories.push({\n key: `${subDir}/${file.replace('.md', '')}`,\n content,\n summary,\n createdAt: new Date(), // Would get from file stats\n updatedAt: new Date(),\n type: subDir as Memory['type'],\n });\n }\n } catch {\n // Directory doesn't exist\n }\n }\n \n return memories;\n }\n\n /**\n * Read a memory entry\n */\n async read(key: string): Promise<string | null> {\n const memoryPath = paths.memory(this.config.configPath);\n \n // Check if key includes subdirectory\n let filePath: string;\n if (key.includes('/')) {\n filePath = join(memoryPath, `${key}.md`);\n } else {\n // Search in all subdirectories\n const subDirs = ['observations', 'handoffs', 'research', '_templates'];\n for (const subDir of subDirs) {\n const testPath = join(memoryPath, subDir, `${key}.md`);\n try {\n await access(testPath, constants.R_OK);\n filePath = testPath;\n break;\n } catch {\n continue;\n }\n }\n filePath = filePath! || join(memoryPath, `${key}.md`);\n }\n \n try {\n return await readFile(filePath, 'utf-8');\n } catch {\n return null;\n }\n }\n\n /**\n * Update a memory entry\n */\n async update(key: string, content: string, options?: {\n append?: boolean;\n type?: Memory['type'];\n }): Promise<void> {\n const memoryPath = paths.memory(this.config.configPath);\n const type = options?.type || 'custom';\n \n // Determine file path based on type\n let filePath: string;\n if (key.includes('/')) {\n filePath = join(memoryPath, `${key}.md`);\n } else {\n const subDir = type === 'observation' ? 'observations' \n : type === 'handoff' ? 'handoffs'\n : type === 'research' ? 'research'\n : '';\n filePath = join(memoryPath, subDir, `${key}.md`);\n }\n \n // Ensure directory exists\n const { dirname } = await import('path');\n await mkdir(dirname(filePath), { recursive: true });\n \n // Handle append mode\n if (options?.append) {\n try {\n const existing = await readFile(filePath, 'utf-8');\n const timestamp = new Date().toISOString();\n content = `${existing}\\n\\n---\\n_Updated: ${timestamp}_\\n\\n${content}`;\n } catch {\n // File doesn't exist, create new\n }\n }\n \n await writeFile(filePath, content);\n }\n\n /**\n * Create a handoff bundle\n */\n async createHandoff(summary: {\n completed: string[];\n inProgress: string[];\n remaining: string[];\n context: string;\n nextSteps: string[];\n }): Promise<string> {\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n const key = `handoffs/${timestamp}`;\n \n const content = `# Handoff: ${new Date().toLocaleString()}\n\n## Completed\n${summary.completed.map(item => `- [x] ${item}`).join('\\n') || '- None'}\n\n## In Progress\n${summary.inProgress.map(item => `- [ ] ${item}`).join('\\n') || '- None'}\n\n## Remaining\n${summary.remaining.map(item => `- [ ] ${item}`).join('\\n') || '- None'}\n\n## Context\n${summary.context || 'No additional context.'}\n\n## Next Steps\n${summary.nextSteps.map((step, i) => `${i + 1}. ${step}`).join('\\n') || '- Continue from where left off'}\n`;\n \n await this.update(key, content, { type: 'handoff' });\n return key;\n }\n\n /**\n * Get the latest handoff\n */\n async getLatestHandoff(): Promise<Memory | null> {\n const memories = await this.list();\n const handoffs = memories.filter(m => m.type === 'handoff');\n \n if (handoffs.length === 0) return null;\n \n // Sort by key (which includes timestamp)\n handoffs.sort((a, b) => b.key.localeCompare(a.key));\n return handoffs[0];\n }\n\n /**\n * Create an observation\n */\n async createObservation(title: string, observation: {\n what: string;\n why: string;\n impact: string;\n tags?: string[];\n }): Promise<string> {\n const slug = title.toLowerCase().replace(/\\s+/g, '-').replace(/[^a-z0-9-]/g, '');\n const key = `observations/${slug}`;\n \n const content = `# ${title}\n\n## What\n${observation.what}\n\n## Why\n${observation.why}\n\n## Impact\n${observation.impact}\n\n${observation.tags?.length ? `## Tags\\n${observation.tags.map(t => `- ${t}`).join('\\n')}` : ''}\n\n---\n_Created: ${new Date().toISOString()}_\n`;\n \n await this.update(key, content, { type: 'observation' });\n return key;\n }\n\n /**\n * Save research findings\n */\n async saveResearch(topic: string, findings: {\n summary: string;\n sources: string[];\n recommendations: string[];\n codeExamples?: string;\n }): Promise<string> {\n const slug = topic.toLowerCase().replace(/\\s+/g, '-').replace(/[^a-z0-9-]/g, '');\n const key = `research/${slug}`;\n \n const content = `# Research: ${topic}\n\n## Summary\n${findings.summary}\n\n## Sources\n${findings.sources.map(s => `- ${s}`).join('\\n')}\n\n## Recommendations\n${findings.recommendations.map((r, i) => `${i + 1}. ${r}`).join('\\n')}\n\n${findings.codeExamples ? `## Code Examples\\n\\`\\`\\`\\n${findings.codeExamples}\\n\\`\\`\\`` : ''}\n\n---\n_Researched: ${new Date().toISOString()}_\n`;\n \n await this.update(key, content, { type: 'research' });\n return key;\n }\n\n /**\n * Extract a summary from content (first paragraph or heading)\n */\n private extractSummary(content: string): string {\n const lines = content.split('\\n').filter(l => l.trim());\n \n // Find first non-heading line\n for (const line of lines) {\n if (!line.startsWith('#') && line.trim().length > 0) {\n return line.slice(0, 100) + (line.length > 100 ? '...' : '');\n }\n }\n \n // Fall back to first heading\n if (lines[0]?.startsWith('#')) {\n return lines[0].replace(/^#+\\s*/, '');\n }\n \n return 'No summary available';\n }\n}\n","/**\n * AIKit MCP Server for OpenCode\n * \n * Exposes AIKit skills, agents, and commands as MCP tools\n * that OpenCode can discover and use via the Model Context Protocol\n */\n\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n Tool,\n} from '@modelcontextprotocol/sdk/types.js';\nimport type { ServerCapabilities } from '@modelcontextprotocol/sdk/types.js';\nimport { loadConfig } from './core/config.js';\nimport { SkillEngine } from './core/skills.js';\nimport { AgentManager } from './core/agents.js';\nimport { CommandRunner } from './core/commands.js';\nimport { ToolRegistry } from './core/tools.js';\nimport { ToolConfigManager } from './core/tool-config.js';\nimport { logger } from './utils/logger.js';\n\nclass AiKitMcpServer {\n private server: Server;\n private skillEngine!: SkillEngine;\n private agentManager!: AgentManager;\n private commandRunner!: CommandRunner;\n private toolRegistry!: ToolRegistry;\n private toolConfigManager!: ToolConfigManager;\n\n constructor() {\n // Define server capabilities - must declare tools support\n const capabilities: ServerCapabilities = {\n tools: {},\n };\n\n this.server = new Server(\n {\n name: 'aikit',\n version: '0.1.0',\n },\n {\n capabilities,\n }\n );\n\n this.setupHandlers();\n }\n\n private setupHandlers(): void {\n this.server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: await this.getAvailableTools(),\n };\n });\n\n this.server.setRequestHandler(CallToolRequestSchema, async (request) => {\n return await this.handleToolCall(request);\n });\n }\n\n private async getAvailableTools(): Promise<Tool[]> {\n const tools: Tool[] = [];\n\n try {\n // Add skill tools\n const skills = await this.skillEngine.listSkills();\n for (const skill of skills) {\n tools.push({\n name: `skill_${skill.name.replace(/\\s+/g, '_')}`,\n description: `Execute the \"${skill.name}\" skill: ${skill.description}`,\n inputSchema: {\n type: 'object',\n properties: {\n context: {\n type: 'string',\n description: 'Additional context for the skill',\n },\n },\n required: [],\n },\n });\n }\n\n // Add agent delegation tools\n const agents = this.agentManager.listAgents();\n for (const agent of agents) {\n tools.push({\n name: `agent_${agent.name}`,\n description: `Delegate to the ${agent.name} agent: ${agent.description}`,\n inputSchema: {\n type: 'object',\n properties: {\n task: {\n type: 'string',\n description: 'Task for the agent to handle',\n },\n context: {\n type: 'string',\n description: 'Optional context',\n },\n },\n required: ['task'],\n },\n });\n }\n\n // Add command tools\n const commands = await this.commandRunner.listCommands();\n for (const cmd of commands) {\n tools.push({\n name: `cmd_${cmd.name.replace(/\\//g, '_').slice(1)}`,\n description: `Run command: ${cmd.description}`,\n inputSchema: {\n type: 'object',\n properties: {\n args: {\n type: 'string',\n description: 'Arguments for the command',\n },\n },\n required: [],\n },\n });\n }\n\n // Add built-in tools from ToolRegistry\n const aikitTools = await this.toolRegistry.listTools();\n for (const tool of aikitTools) {\n // Convert Tool to MCP Tool format\n const properties: Record<string, { type: string; description: string }> = {};\n const required: string[] = [];\n \n for (const [argName, argDef] of Object.entries(tool.args)) {\n properties[argName] = {\n type: argDef.type,\n description: argDef.description,\n };\n if (argDef.required) {\n required.push(argName);\n }\n }\n\n tools.push({\n name: `tool_${tool.name.replace(/\\s+/g, '_')}`,\n description: tool.description,\n inputSchema: {\n type: 'object',\n properties,\n required,\n },\n });\n }\n } catch (error) {\n logger.error(`Failed to list tools: ${error}`);\n }\n\n return tools;\n }\n\n private async handleToolCall(request: {\n params: {\n name: string;\n arguments?: Record<string, unknown>;\n };\n }): Promise<{ content: Array<{ type: string; text: string }> }> {\n const { name, arguments: args } = request.params;\n\n try {\n let result = '';\n\n if (name.startsWith('skill_')) {\n const skillName = name.replace('skill_', '').replace(/_/g, '-');\n const skill = await this.skillEngine.getSkill(skillName);\n\n if (skill) {\n const formatted = this.skillEngine.formatForAgent(skill);\n result = formatted;\n } else {\n result = `Skill not found: ${skillName}`;\n }\n } else if (name.startsWith('agent_')) {\n const task = (args?.task as string) || 'Execute task';\n const context = (args?.context as string) || '';\n\n const decision = this.agentManager.decideAgent(task, context);\n result = `Delegated to agent: ${decision.agent}\\n\\nReasoning: ${decision.reason}`;\n } else if (name.startsWith('cmd_')) {\n const cmdName = '/' + name.replace('cmd_', '').replace(/_/g, '/');\n const cmdArgs = (args?.args as string) || '';\n\n result = `Execute: ${cmdName} ${cmdArgs}`;\n } else if (name.startsWith('tool_')) {\n // Remove 'tool_' prefix and keep underscores (tool names use underscores, not dashes)\n const toolName = name.replace('tool_', '');\n try {\n // Verify toolConfigManager is available\n if (!this.toolConfigManager) {\n result = `Error: Tool configuration manager not initialized. MCP server may not be properly started.`;\n } else {\n // Pass toolConfigManager context for tools that need it\n const context = { toolConfigManager: this.toolConfigManager };\n result = await this.toolRegistry.executeTool(toolName, args || {}, context);\n }\n } catch (error) {\n result = `Error executing tool ${toolName}: ${error instanceof Error ? error.message : String(error)}`;\n }\n } else {\n result = `Unknown tool: ${name}`;\n }\n\n return {\n content: [\n {\n type: 'text',\n text: result,\n },\n ],\n };\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n return {\n content: [\n {\n type: 'text',\n text: `Error executing tool: ${errorMsg}`,\n },\n ],\n };\n }\n }\n\n async initialize(): Promise<void> {\n try {\n const config = await loadConfig();\n this.skillEngine = new SkillEngine(config);\n this.agentManager = new AgentManager(config);\n this.commandRunner = new CommandRunner(config);\n this.toolRegistry = new ToolRegistry(config);\n this.toolConfigManager = new ToolConfigManager(config);\n this.toolRegistry.setToolConfigManager(this.toolConfigManager);\n \n // Verify tool config is loaded\n const figmaReady = await this.toolConfigManager.isToolReady('figma-analysis');\n if (figmaReady) {\n logger.info('Figma tool configured and ready');\n } else {\n logger.warn('Figma tool not configured - tools requiring config may not work');\n }\n } catch (error) {\n logger.error(`Failed to initialize: ${error}`);\n process.exit(1);\n }\n }\n\n async start(): Promise<void> {\n const transport = new StdioServerTransport();\n await this.server.connect(transport);\n logger.info('AIKit MCP Server started');\n }\n}\n\nasync function main(): Promise<void> {\n const server = new AiKitMcpServer();\n await server.initialize();\n await server.start();\n}\n\nmain().catch((error) => {\n logger.error(`Fatal error: ${error}`);\n process.exit(1);\n});\n","import { readFile, access, constants } from 'fs/promises';\nimport { join } from 'path';\nimport { z } from 'zod';\nimport { paths } from '../utils/paths.js';\n\n/**\n * AIKit Configuration Schema\n */\nconst ConfigSchema = z.object({\n version: z.string(),\n skills: z.object({\n enabled: z.boolean().default(true),\n directory: z.string().optional(),\n }).default({}),\n agents: z.object({\n enabled: z.boolean().default(true),\n default: z.string().default('build'),\n }).default({}),\n commands: z.object({\n enabled: z.boolean().default(true),\n }).default({}),\n tools: z.object({\n enabled: z.boolean().default(true),\n }).default({}),\n plugins: z.object({\n enabled: z.boolean().default(true),\n autoload: z.array(z.string()).optional(),\n }).default({}),\n memory: z.object({\n enabled: z.boolean().default(true),\n maxSize: z.number().optional(),\n }).default({}),\n beads: z.object({\n enabled: z.boolean().default(true),\n autoInit: z.boolean().default(false),\n }).default({}),\n antiHallucination: z.object({\n enabled: z.boolean().default(true),\n specFile: z.string().default('spec.md'),\n reviewFile: z.string().default('review.md'),\n }).default({}),\n mcp: z.object({\n context7: z.boolean().default(false),\n githubGrep: z.boolean().default(false),\n gkg: z.boolean().default(false),\n }).optional(),\n});\n\nexport type AIKitConfig = z.infer<typeof ConfigSchema> & {\n configPath: string;\n projectPath: string;\n};\n\n/**\n * Configuration manager for AIKit\n */\nexport class Config {\n private config: AIKitConfig;\n\n constructor(config: AIKitConfig) {\n this.config = config;\n }\n\n get(): AIKitConfig {\n return this.config;\n }\n\n get skills() {\n return this.config.skills;\n }\n\n get agents() {\n return this.config.agents;\n }\n\n get commands() {\n return this.config.commands;\n }\n\n get tools() {\n return this.config.tools;\n }\n\n get plugins() {\n return this.config.plugins;\n }\n\n get memory() {\n return this.config.memory;\n }\n\n get beads() {\n return this.config.beads;\n }\n\n get antiHallucination() {\n return this.config.antiHallucination;\n }\n\n get configPath(): string {\n return this.config.configPath;\n }\n\n get projectPath(): string {\n return this.config.projectPath;\n }\n\n /**\n * Get path to a specific resource\n */\n getPath(resource: 'skills' | 'agents' | 'commands' | 'tools' | 'plugins' | 'memory'): string {\n return paths[resource](this.configPath);\n }\n}\n\n/**\n * Load AIKit configuration\n * Merges project-level config with global config (project takes precedence)\n */\nexport async function loadConfig(projectPath?: string): Promise<Config> {\n const project = projectPath || process.cwd();\n \n // Try project config first, then global\n const projectConfigPath = paths.projectConfig(project);\n const globalConfigPath = paths.globalConfig();\n \n let configPath: string;\n let configData: Record<string, unknown> = {};\n \n // Load global config first (as base)\n try {\n await access(join(globalConfigPath, 'aikit.json'), constants.R_OK);\n const globalContent = await readFile(join(globalConfigPath, 'aikit.json'), 'utf-8');\n configData = JSON.parse(globalContent);\n configPath = globalConfigPath;\n } catch {\n // No global config\n configPath = projectConfigPath;\n }\n \n // Merge project config on top\n try {\n await access(join(projectConfigPath, 'aikit.json'), constants.R_OK);\n const projectContent = await readFile(join(projectConfigPath, 'aikit.json'), 'utf-8');\n const projectData = JSON.parse(projectContent);\n configData = deepMerge(configData, projectData);\n configPath = projectConfigPath;\n } catch {\n // No project config, use global or defaults\n }\n \n // Add default version if not present\n if (!configData.version) {\n configData.version = '0.1.0';\n }\n\n // Parse and validate config\n const parsed = ConfigSchema.parse(configData);\n\n return new Config({\n ...parsed,\n configPath,\n projectPath: project,\n });\n}\n\n/**\n * Deep merge two objects\n */\nfunction deepMerge<T extends Record<string, unknown>>(base: T, override: Partial<T>): T {\n const result = { ...base };\n \n for (const key in override) {\n const baseValue = base[key];\n const overrideValue = override[key];\n \n if (\n typeof baseValue === 'object' &&\n baseValue !== null &&\n typeof overrideValue === 'object' &&\n overrideValue !== null &&\n !Array.isArray(baseValue) &&\n !Array.isArray(overrideValue)\n ) {\n result[key] = deepMerge(\n baseValue as Record<string, unknown>,\n overrideValue as Record<string, unknown>\n ) as T[Extract<keyof T, string>];\n } else if (overrideValue !== undefined) {\n result[key] = overrideValue as T[Extract<keyof T, string>];\n }\n }\n \n return result;\n}\n","import { readFile, readdir, writeFile, mkdir } from 'fs/promises';\nimport { join, basename, extname } from 'path';\nimport matter from 'gray-matter';\nimport { Config } from './config.js';\nimport { paths } from '../utils/paths.js';\n\n/**\n * Skill definition\n */\nexport interface Skill {\n name: string;\n description: string;\n useWhen: string;\n category: string;\n tags: string[];\n content: string;\n filePath: string;\n}\n\n/**\n * Skill frontmatter schema\n */\ninterface SkillFrontmatter {\n name?: string;\n description?: string;\n useWhen?: string;\n category?: string;\n tags?: string[];\n}\n\n/**\n * Skill Engine - Manages workflow skills for AI agents\n * \n * Skills are mandatory workflow instructions that agents must follow.\n * They enforce structured processes like TDD, systematic debugging, etc.\n */\nexport class SkillEngine {\n private config: Config;\n private skillsCache: Map<string, Skill> = new Map();\n\n constructor(config: Config) {\n this.config = config;\n }\n\n /**\n * List all available skills\n */\n async listSkills(): Promise<Skill[]> {\n const skills: Skill[] = [];\n \n // Load from global config\n const globalSkillsPath = paths.skills(paths.globalConfig());\n try {\n const globalSkills = await this.loadSkillsFromDir(globalSkillsPath);\n skills.push(...globalSkills);\n } catch {\n // No global skills\n }\n \n // Load from project config (override global)\n const projectSkillsPath = paths.skills(this.config.configPath);\n if (projectSkillsPath !== globalSkillsPath) {\n try {\n const projectSkills = await this.loadSkillsFromDir(projectSkillsPath);\n // Override global skills with project skills\n for (const skill of projectSkills) {\n const existingIndex = skills.findIndex(s => s.name === skill.name);\n if (existingIndex >= 0) {\n skills[existingIndex] = skill;\n } else {\n skills.push(skill);\n }\n }\n } catch {\n // No project skills\n }\n }\n \n return skills.sort((a, b) => a.name.localeCompare(b.name));\n }\n\n /**\n * Get a specific skill by name\n */\n async getSkill(name: string): Promise<Skill | null> {\n // Check cache first\n if (this.skillsCache.has(name)) {\n return this.skillsCache.get(name)!;\n }\n \n const skills = await this.listSkills();\n const skill = skills.find(s => s.name === name);\n \n if (skill) {\n this.skillsCache.set(name, skill);\n }\n \n return skill || null;\n }\n\n /**\n * Find skills matching a query\n */\n async findSkills(query?: string): Promise<Skill[]> {\n const skills = await this.listSkills();\n \n if (!query) {\n return skills;\n }\n \n const lowerQuery = query.toLowerCase();\n return skills.filter(skill =>\n skill.name.toLowerCase().includes(lowerQuery) ||\n skill.description.toLowerCase().includes(lowerQuery) ||\n skill.tags.some(tag => tag.toLowerCase().includes(lowerQuery)) ||\n skill.category.toLowerCase().includes(lowerQuery)\n );\n }\n\n /**\n * Create a new skill\n */\n async createSkill(name: string, options?: {\n description?: string;\n useWhen?: string;\n category?: string;\n tags?: string[];\n content?: string;\n global?: boolean;\n }): Promise<Skill> {\n const configPath = options?.global ? paths.globalConfig() : this.config.configPath;\n const skillsDir = paths.skills(configPath);\n \n await mkdir(skillsDir, { recursive: true });\n \n const fileName = `${name.replace(/\\s+/g, '-').toLowerCase()}.md`;\n const filePath = join(skillsDir, fileName);\n \n const frontmatter: SkillFrontmatter = {\n name,\n description: options?.description || `Use when you need to ${name}`,\n useWhen: options?.useWhen || `The user asks you to ${name}`,\n category: options?.category || 'custom',\n tags: options?.tags || ['custom'],\n };\n \n const content = options?.content || `## ${name}\n\n### Overview\nDescribe what this skill does.\n\n### Workflow\n\n#### Step 1: Understand the Task\n- Gather context\n- Clarify requirements\n\n#### Step 2: Plan the Approach\n- Break down into sub-tasks\n- Identify dependencies\n\n#### Step 3: Execute\n- Follow TDD principles\n- Write tests first\n\n#### Step 4: Verify\n- Run all tests\n- Check for regressions\n\n### Checklist\n- [ ] Requirements understood\n- [ ] Tests written\n- [ ] Implementation complete\n- [ ] All tests passing\n- [ ] Code reviewed\n`;\n\n const fileContent = matter.stringify(content, frontmatter);\n await writeFile(filePath, fileContent);\n \n const skill: Skill = {\n name,\n description: frontmatter.description!,\n useWhen: frontmatter.useWhen!,\n category: frontmatter.category!,\n tags: frontmatter.tags!,\n content,\n filePath,\n };\n \n this.skillsCache.set(name, skill);\n \n return skill;\n }\n\n /**\n * Sync global skills to project directory\n */\n async syncSkillsToProject(): Promise<{ count: number; synced: string[] }> {\n const globalSkillsPath = paths.skills(paths.globalConfig());\n const projectSkillsPath = paths.skills(this.config.configPath);\n \n if (globalSkillsPath === projectSkillsPath) {\n return { count: 0, synced: [] };\n }\n \n const globalSkills = await this.loadSkillsFromDir(globalSkillsPath);\n await mkdir(projectSkillsPath, { recursive: true });\n \n const synced: string[] = [];\n \n for (const skill of globalSkills) {\n const fileName = `${skill.name.replace(/\\s+/g, '-').toLowerCase()}.md`;\n const destPath = join(projectSkillsPath, fileName);\n const srcContent = await readFile(skill.filePath, 'utf-8');\n await writeFile(destPath, srcContent);\n synced.push(skill.name);\n }\n \n return { count: synced.length, synced };\n }\n\n /**\n * Format skill for agent consumption\n */\n formatForAgent(skill: Skill): string {\n return `# Skill: ${skill.name}\n\n## When to Use\n${skill.useWhen}\n\n## Description\n${skill.description}\n\n## Workflow\n${skill.content}\n\n---\n**IMPORTANT**: Follow this workflow step by step. Do not skip steps.\n`;\n }\n\n /**\n * Load skills from a directory\n */\n private async loadSkillsFromDir(dir: string): Promise<Skill[]> {\n const files = await readdir(dir);\n const skills: Skill[] = [];\n \n for (const file of files) {\n if (extname(file) !== '.md') continue;\n \n const filePath = join(dir, file);\n const content = await readFile(filePath, 'utf-8');\n const { data, content: body } = matter(content);\n \n const frontmatter = data as SkillFrontmatter;\n const name = frontmatter.name || basename(file, '.md');\n \n skills.push({\n name,\n description: frontmatter.description || '',\n useWhen: frontmatter.useWhen || '',\n category: frontmatter.category || 'general',\n tags: frontmatter.tags || [],\n content: body.trim(),\n filePath,\n });\n }\n \n return skills;\n }\n}\n","import { Config } from './config.js';\n\n/**\n * Agent types available in AIKit\n */\nexport type AgentType = 'planner' | 'build' | 'rush' | 'review' | 'scout' | 'explore' | 'vision';\n\n/**\n * Agent definition\n */\nexport interface Agent {\n name: AgentType;\n displayName: string;\n description: string;\n useWhen: string;\n capabilities: string[];\n systemPrompt: string;\n delegatesTo: AgentType[];\n}\n\n/**\n * Default agent definitions\n */\nconst DEFAULT_AGENTS: Agent[] = [\n {\n name: 'planner',\n displayName: '@planner',\n description: 'Strategic planning and multi-agent coordination',\n useWhen: 'Complex tasks requiring architecture decisions, multi-step planning, or coordination between specialists',\n capabilities: [\n 'Break down complex tasks into sub-tasks',\n 'Coordinate between specialist agents',\n 'Make architecture decisions',\n 'Create implementation plans',\n ],\n systemPrompt: `You are a strategic planner agent. Your role is to:\n\n1. ANALYZE the task and understand the full scope\n2. BREAK DOWN complex tasks into smaller, manageable sub-tasks\n3. DELEGATE to appropriate specialist agents\n4. COORDINATE the overall workflow\n5. VERIFY completion of the overall goal\n\nWhen delegating:\n- Use @build for implementation tasks\n- Use @scout for external research\n- Use @review for code review and security audits\n- Use @explore for codebase navigation\n- Use @vision for visual analysis\n\nAlways create a clear plan before delegating. Track progress and ensure all sub-tasks complete successfully.`,\n delegatesTo: ['build', 'scout', 'review', 'explore', 'vision'],\n },\n {\n name: 'build',\n displayName: '@build',\n description: 'Primary execution agent for implementing features',\n useWhen: 'Implementing features, writing code, making changes to the codebase',\n capabilities: [\n 'Write production code',\n 'Write tests',\n 'Refactor code',\n 'Fix bugs',\n 'Implement features',\n ],\n systemPrompt: `You are the build agent. Your role is to implement code changes.\n\nFollow these principles:\n1. TEST-DRIVEN DEVELOPMENT: Write tests before implementation\n2. INCREMENTAL CHANGES: Make small, focused commits\n3. VERIFY: Run tests and type checks after each change\n4. DOCUMENT: Add comments for complex logic\n\nBefore starting:\n- Understand the requirements fully\n- Check existing patterns in the codebase\n- Plan the implementation approach\n\nAfter completing:\n- Ensure all tests pass\n- Run linting and type checks\n- Create a clear commit message`,\n delegatesTo: ['review', 'explore'],\n },\n {\n name: 'rush',\n displayName: '@rush',\n description: 'Fast execution with minimal planning',\n useWhen: 'Quick fixes, hotfixes, simple edits that need minimal planning',\n capabilities: [\n 'Quick bug fixes',\n 'Simple refactoring',\n 'Minor changes',\n 'Hotfixes',\n ],\n systemPrompt: `You are the rush agent. Your role is to make quick, focused changes.\n\nGuidelines:\n1. ACT FAST: Minimal planning, direct execution\n2. FOCUS: One change at a time\n3. VERIFY: Quick sanity check after change\n4. MINIMAL SCOPE: Don't expand beyond the immediate task\n\nUse for:\n- Typo fixes\n- Simple bug fixes\n- Minor adjustments\n- Urgent hotfixes`,\n delegatesTo: [],\n },\n {\n name: 'review',\n displayName: '@review',\n description: 'Code review, debugging, and security audits',\n useWhen: 'Reviewing code quality, finding bugs, security review, debugging issues',\n capabilities: [\n 'Code review',\n 'Security audit',\n 'Performance analysis',\n 'Bug finding',\n 'Best practices enforcement',\n ],\n systemPrompt: `You are the review agent. Your role is to review and improve code quality.\n\nReview checklist:\n1. CORRECTNESS: Does the code do what it's supposed to?\n2. SECURITY: Are there any security vulnerabilities?\n3. PERFORMANCE: Are there performance issues?\n4. MAINTAINABILITY: Is the code clean and readable?\n5. TESTS: Are there adequate tests?\n6. PATTERNS: Does it follow project conventions?\n\nWhen reviewing:\n- Be specific about issues\n- Suggest fixes, not just problems\n- Prioritize by severity\n- Check for edge cases`,\n delegatesTo: [],\n },\n {\n name: 'scout',\n displayName: '@scout',\n description: 'External research - library docs, GitHub patterns, frameworks',\n useWhen: 'Researching external libraries, finding code patterns on GitHub, learning about frameworks',\n capabilities: [\n 'Web research',\n 'GitHub code search',\n 'Documentation lookup',\n 'Framework exploration',\n 'Best practices research',\n ],\n systemPrompt: `You are the scout agent. Your role is to research external resources.\n\nResearch strategy:\n1. UNDERSTAND what information is needed\n2. SEARCH appropriate sources (docs, GitHub, web)\n3. EVALUATE quality and relevance of findings\n4. SUMMARIZE key findings concisely\n5. PROVIDE actionable recommendations\n\nSources to use:\n- Official documentation\n- GitHub code examples\n- Stack Overflow (verified answers)\n- Framework guides\n- Community best practices\n\nAlways cite your sources and verify information accuracy.`,\n delegatesTo: [],\n },\n {\n name: 'explore',\n displayName: '@explore',\n description: 'Fast codebase navigation and pattern search',\n useWhen: 'Finding files, understanding codebase structure, searching for patterns in code',\n capabilities: [\n 'File discovery',\n 'Pattern search',\n 'Codebase navigation',\n 'Structure analysis',\n 'Dependency mapping',\n ],\n systemPrompt: `You are the explore agent. Your role is to navigate and understand the codebase.\n\nExploration techniques:\n1. FILE STRUCTURE: Understand project organization\n2. GREP SEARCH: Find specific patterns or usages\n3. DEPENDENCY ANALYSIS: Map relationships between modules\n4. PATTERN DISCOVERY: Find existing patterns to follow\n5. QUICK CONTEXT: Gather just enough context for the task\n\nFocus on speed and accuracy. Provide concise summaries of findings.`,\n delegatesTo: [],\n },\n {\n name: 'vision',\n displayName: '@vision',\n description: 'Multimodal analysis - mockups, PDFs, diagrams',\n useWhen: 'Analyzing images, mockups, screenshots, PDFs, or diagrams',\n capabilities: [\n 'Image analysis',\n 'Mockup interpretation',\n 'PDF extraction',\n 'Diagram understanding',\n 'UI/UX analysis',\n ],\n systemPrompt: `You are the vision agent. Your role is to analyze visual content.\n\nAnalysis approach:\n1. OBSERVE: Carefully examine the visual content\n2. EXTRACT: Identify key information, text, structure\n3. INTERPRET: Understand the intent and requirements\n4. TRANSLATE: Convert visual specs to actionable tasks\n5. VALIDATE: Ensure accurate interpretation\n\nFor mockups:\n- Identify components and layout\n- Note colors, spacing, typography\n- Extract interaction patterns\n\nFor diagrams:\n- Understand relationships\n- Map to code structure\n- Note data flow`,\n delegatesTo: [],\n },\n];\n\n/**\n * Agent delegation result\n */\nexport interface DelegationDecision {\n agent: Agent;\n reason: string;\n shouldDelegate: boolean;\n subTasks?: string[];\n}\n\n/**\n * Agent Manager - Handles agent selection and delegation\n */\nexport class AgentManager {\n private config: Config;\n private agents: Map<AgentType, Agent>;\n\n constructor(config: Config) {\n this.config = config;\n this.agents = new Map();\n \n // Initialize default agents\n for (const agent of DEFAULT_AGENTS) {\n this.agents.set(agent.name, agent);\n }\n }\n\n /**\n * List all available agents\n */\n listAgents(): Agent[] {\n return Array.from(this.agents.values());\n }\n\n /**\n * Get a specific agent\n */\n getAgent(name: AgentType): Agent | undefined {\n return this.agents.get(name);\n }\n\n /**\n * Get the default agent\n */\n getDefaultAgent(): Agent {\n const defaultName = this.config.agents.default as AgentType;\n return this.agents.get(defaultName) || this.agents.get('build')!;\n }\n\n /**\n * Decide which agent should handle a task\n */\n decideAgent(task: string, _context?: string): DelegationDecision {\n const lowerTask = task.toLowerCase();\n \n // Check for explicit agent mentions\n for (const [name, agent] of this.agents) {\n if (lowerTask.includes(`@${name}`)) {\n return {\n agent,\n reason: `Explicitly requested @${name}`,\n shouldDelegate: false,\n };\n }\n }\n \n // Keyword-based delegation\n if (this.matchesKeywords(lowerTask, ['plan', 'architect', 'design', 'coordinate', 'complex'])) {\n return {\n agent: this.agents.get('planner')!,\n reason: 'Task requires planning and coordination',\n shouldDelegate: true,\n };\n }\n \n if (this.matchesKeywords(lowerTask, ['research', 'docs', 'documentation', 'library', 'framework', 'how to'])) {\n return {\n agent: this.agents.get('scout')!,\n reason: 'Task requires external research',\n shouldDelegate: false,\n };\n }\n \n if (this.matchesKeywords(lowerTask, ['review', 'audit', 'security', 'check', 'debug'])) {\n return {\n agent: this.agents.get('review')!,\n reason: 'Task requires code review or debugging',\n shouldDelegate: false,\n };\n }\n \n if (this.matchesKeywords(lowerTask, ['find', 'search', 'where', 'locate', 'explore'])) {\n return {\n agent: this.agents.get('explore')!,\n reason: 'Task requires codebase exploration',\n shouldDelegate: false,\n };\n }\n \n if (this.matchesKeywords(lowerTask, ['image', 'mockup', 'screenshot', 'pdf', 'diagram', 'visual'])) {\n return {\n agent: this.agents.get('vision')!,\n reason: 'Task requires visual analysis',\n shouldDelegate: false,\n };\n }\n \n if (this.matchesKeywords(lowerTask, ['fix quickly', 'hotfix', 'urgent', 'quick fix', 'typo'])) {\n return {\n agent: this.agents.get('rush')!,\n reason: 'Task is a quick fix',\n shouldDelegate: false,\n };\n }\n \n // Default to build agent\n return {\n agent: this.agents.get('build')!,\n reason: 'Default to build agent for implementation',\n shouldDelegate: false,\n };\n }\n\n /**\n * Format agent instructions for prompt\n */\n formatAgentPrompt(agent: Agent): string {\n return `# Agent: ${agent.displayName}\n\n${agent.systemPrompt}\n\n## Capabilities\n${agent.capabilities.map(c => `- ${c}`).join('\\n')}\n\n${agent.delegatesTo.length > 0 ? `## Can Delegate To\n${agent.delegatesTo.map(a => `- @${a}`).join('\\n')}` : ''}\n`;\n }\n\n private matchesKeywords(text: string, keywords: string[]): boolean {\n return keywords.some(kw => text.includes(kw));\n }\n}\n","import { readFile, readdir, writeFile, mkdir } from 'fs/promises';\nimport { join, basename, extname } from 'path';\nimport matter from 'gray-matter';\nimport { Config } from './config.js';\nimport { paths } from '../utils/paths.js';\n\n/**\n * Command definition\n */\nexport interface Command {\n name: string;\n description: string;\n category: string;\n usage: string;\n examples: string[];\n content: string;\n filePath: string;\n}\n\n/**\n * Command frontmatter schema\n */\ninterface CommandFrontmatter {\n name?: string;\n description?: string;\n category?: string;\n usage?: string;\n examples?: string[];\n}\n\n/**\n * Command categories\n */\nexport const COMMAND_CATEGORIES = {\n core: 'Core Workflow',\n quick: 'Quick Actions',\n research: 'Research & Analysis',\n design: 'Design & Planning',\n git: 'Git & Version Control',\n utility: 'Utilities',\n} as const;\n\n/**\n * Default commands\n */\nconst DEFAULT_COMMANDS: Omit<Command, 'filePath'>[] = [\n // Core Workflow Commands (Beads integration)\n {\n name: 'create',\n description: 'Create a new Beads task for tracking',\n category: 'core',\n usage: '/create <task description>',\n examples: ['/create Add user authentication', '/create Fix navigation bug'],\n content: `Create a new task in the Beads system (.beads/ directory).\n\n## Workflow\n1. Create a new bead file with unique ID\n2. Add task description, status, and notes\n3. Set status to \"in-progress\"\n4. Initialize working notes section\n\n## Required Output\n- Task ID for reference\n- Confirmation of task creation\n- Next steps`,\n },\n {\n name: 'plan',\n description: 'Create a detailed implementation plan',\n category: 'core',\n usage: '/plan <feature or task>',\n examples: ['/plan user authentication system', '/plan refactor database layer'],\n content: `Create a comprehensive plan before implementation.\n\n## Workflow\n1. UNDERSTAND: Clarify requirements through Socratic questioning\n2. RESEARCH: Check existing patterns and dependencies\n3. BREAK DOWN: Create 2-5 minute sub-tasks with:\n - Exact file paths\n - Expected changes\n - Verification steps\n4. DOCUMENT: Write plan to memory/plans/\n\n## Output Format\n\\`\\`\\`markdown\n# Plan: [Feature Name]\n\n## Overview\nBrief description of the goal.\n\n## Tasks\n1. [ ] Task 1 - file.ts\n2. [ ] Task 2 - component.tsx\n...\n\n## Dependencies\n- List dependencies\n\n## Risks\n- Potential issues\n\n## Verification\n- How to verify completion\n\\`\\`\\``,\n },\n {\n name: 'implement',\n description: 'Implement a planned task with TDD',\n category: 'core',\n usage: '/implement <task reference>',\n examples: ['/implement task-001', '/implement \"add login form\"'],\n content: `Implement a task following TDD principles.\n\n## Workflow\n1. LOAD: Get task details from .beads/ or plan\n2. TEST: Write failing tests first (RED)\n3. IMPLEMENT: Write minimal code to pass (GREEN)\n4. REFACTOR: Clean up while keeping tests green\n5. VERIFY: Run full test suite\n\n## Hard Gates\nBefore marking complete:\n- [ ] All new tests pass\n- [ ] No regressions\n- [ ] Type check passes\n- [ ] Linting passes`,\n },\n {\n name: 'finish',\n description: 'Complete a task with quality gates',\n category: 'core',\n usage: '/finish [task-id]',\n examples: ['/finish', '/finish task-001'],\n content: `Complete the current task with mandatory quality checks.\n\n## Hard Gates (Must ALL Pass)\n1. \\`npm run typecheck\\` - No type errors\n2. \\`npm run test\\` - All tests pass\n3. \\`npm run lint\\` - No linting errors\n4. \\`npm run build\\` - Build succeeds\n\n## Workflow\n1. Run all quality gates\n2. If any fail, report issues and stop\n3. If all pass, update task status to \"completed\"\n4. Create summary of changes\n5. Suggest commit message`,\n },\n {\n name: 'handoff',\n description: 'Create handoff bundle for session continuity',\n category: 'core',\n usage: '/handoff',\n examples: ['/handoff'],\n content: `Create a handoff bundle for context transfer to next session.\n\n## Workflow\n1. Summarize current progress\n2. Document:\n - What was completed\n - What remains\n - Current blockers\n - Key decisions made\n3. Save to memory/handoffs/[timestamp].md\n\n## Output Format\n\\`\\`\\`markdown\n# Handoff: [Date/Time]\n\n## Completed\n- List of completed items\n\n## In Progress\n- Current work state\n\n## Remaining\n- What still needs to be done\n\n## Context\n- Important context for next session\n\n## Next Steps\n- Recommended actions\n\\`\\`\\``,\n },\n {\n name: 'resume',\n description: 'Resume from last handoff',\n category: 'core',\n usage: '/resume',\n examples: ['/resume'],\n content: `Resume work from the most recent handoff.\n\n## Workflow\n1. Load latest handoff from memory/handoffs/\n2. Display summary to user\n3. Propose next actions\n4. Continue from where left off`,\n },\n\n // Quick Actions\n {\n name: 'fix',\n description: 'Quick fix for an issue',\n category: 'quick',\n usage: '/fix <issue description>',\n examples: ['/fix button not clickable', '/fix type error in auth.ts'],\n content: `Quick fix with minimal ceremony.\n\n## Workflow\n1. Identify the issue\n2. Make minimal change to fix\n3. Verify fix works\n4. Run affected tests`,\n },\n {\n name: 'fix-types',\n description: 'Fix TypeScript type errors',\n category: 'quick',\n usage: '/fix-types [file]',\n examples: ['/fix-types', '/fix-types src/auth.ts'],\n content: `Fix TypeScript type errors systematically.\n\n## Workflow\n1. Run \\`npm run typecheck\\`\n2. Parse error output\n3. Fix each error in dependency order\n4. Verify all types pass`,\n },\n {\n name: 'fix-ci',\n description: 'Fix CI/CD pipeline failures',\n category: 'quick',\n usage: '/fix-ci',\n examples: ['/fix-ci'],\n content: `Diagnose and fix CI failures.\n\n## Workflow\n1. Check CI logs for errors\n2. Reproduce locally if possible\n3. Fix issues in order:\n - Type errors\n - Test failures\n - Lint errors\n - Build errors\n4. Verify full CI pipeline locally`,\n },\n {\n name: 'commit',\n description: 'Create a well-formatted commit',\n category: 'quick',\n usage: '/commit [message]',\n examples: ['/commit', '/commit \"feat: add login\"'],\n content: `Create a conventional commit.\n\n## Workflow\n1. Stage changes: \\`git add -A\\`\n2. Generate commit message following conventional commits:\n - feat: New feature\n - fix: Bug fix\n - docs: Documentation\n - refactor: Code refactoring\n - test: Adding tests\n - chore: Maintenance\n3. Commit with message`,\n },\n {\n name: 'pr',\n description: 'Create a pull request',\n category: 'quick',\n usage: '/pr [title]',\n examples: ['/pr', '/pr \"Add user authentication\"'],\n content: `Create a pull request with proper description.\n\n## Workflow\n1. Push current branch\n2. Generate PR description:\n - Summary of changes\n - Related issues\n - Testing done\n - Screenshots if UI changes\n3. Create PR via GitHub CLI or provide URL`,\n },\n\n // Research & Analysis\n {\n name: 'research',\n description: 'Deep research on a topic',\n category: 'research',\n usage: '/research <topic>',\n examples: ['/research React Server Components', '/research OAuth 2.0 best practices'],\n content: `Conduct thorough research and document findings.\n\n## Workflow\n1. Search documentation and resources\n2. Find code examples and patterns\n3. Evaluate options and trade-offs\n4. Document findings in memory/research/\n\n## Output\n- Summary of findings\n- Recommended approach\n- Code examples\n- Links to resources`,\n },\n {\n name: 'analyze-project',\n description: 'Analyze project structure and patterns',\n category: 'research',\n usage: '/analyze-project',\n examples: ['/analyze-project'],\n content: `Comprehensive project analysis.\n\n## Workflow\n1. Scan directory structure\n2. Identify:\n - Tech stack\n - Architecture patterns\n - Key dependencies\n - Coding conventions\n3. Document findings in AGENTS.md`,\n },\n {\n name: 'review-codebase',\n description: 'Review codebase quality',\n category: 'research',\n usage: '/review-codebase [path]',\n examples: ['/review-codebase', '/review-codebase src/'],\n content: `Review codebase for quality issues.\n\n## Workflow\n1. Check code quality metrics\n2. Identify:\n - Code smells\n - Security issues\n - Performance concerns\n - Test coverage gaps\n3. Prioritize findings\n4. Suggest improvements`,\n },\n\n // Design & Planning\n {\n name: 'design',\n description: 'Design a feature or system',\n category: 'design',\n usage: '/design <feature>',\n examples: ['/design notification system', '/design API gateway'],\n content: `Design a feature with thorough planning.\n\n## Workflow\n1. Requirements gathering (Socratic questioning)\n2. Research existing solutions\n3. Design options with trade-offs\n4. Choose approach\n5. Document design in memory/\n\n## Output\n- Design document\n- Architecture diagrams (described)\n- API contracts\n- Data models`,\n },\n {\n name: 'brainstorm',\n description: 'Brainstorm ideas for a problem',\n category: 'design',\n usage: '/brainstorm <problem>',\n examples: ['/brainstorm user retention', '/brainstorm performance optimization'],\n content: `Collaborative brainstorming session.\n\n## Workflow\n1. Define the problem clearly\n2. Generate diverse ideas (no judgement)\n3. Group related ideas\n4. Evaluate feasibility\n5. Select top candidates`,\n },\n\n // Git & Version Control\n {\n name: 'branch',\n description: 'Create a new feature branch',\n category: 'git',\n usage: '/branch <name>',\n examples: ['/branch feat/auth', '/branch fix/navigation-bug'],\n content: `Create and switch to a new branch.\n\n## Workflow\n1. Ensure clean working directory\n2. Pull latest main/master\n3. Create branch with naming convention:\n - feat/* for features\n - fix/* for bug fixes\n - refactor/* for refactoring\n - docs/* for documentation\n4. Switch to new branch`,\n },\n {\n name: 'merge',\n description: 'Merge current branch to target',\n category: 'git',\n usage: '/merge [target]',\n examples: ['/merge', '/merge main'],\n content: `Merge current branch to target.\n\n## Workflow\n1. Run quality gates first\n2. Commit any pending changes\n3. Switch to target branch\n4. Pull latest\n5. Merge feature branch\n6. Resolve conflicts if any\n7. Push`,\n },\n\n // Utilities\n {\n name: 'status',\n description: 'Show current status overview',\n category: 'utility',\n usage: '/status',\n examples: ['/status'],\n content: `Display comprehensive status.\n\n## Shows\n- Current task (from Beads)\n- Git status\n- Active branch\n- Pending changes\n- Test status\n- Recent activity`,\n },\n {\n name: 'help',\n description: 'Show available commands',\n category: 'utility',\n usage: '/help [command]',\n examples: ['/help', '/help plan'],\n content: `Display help information.\n\nIf no command specified, list all available commands.\nIf command specified, show detailed help for that command.`,\n },\n {\n name: 'analyze-figma',\n description: 'Analyze Figma design and extract design tokens using Figma API',\n category: 'design',\n usage: '/analyze-figma <figma-url>',\n examples: [\n '/analyze-figma https://www.figma.com/design/...',\n '/analyze-figma [figma-url]',\n ],\n content: `Analyze a Figma design and extract all design tokens automatically using Figma API.\n\n## Workflow\n\n**Step 1: Extract URL from User Input**\n\nThe Figma URL is provided in the SAME message as the command. Extract it:\n- Check the full user input message\n- Look for URL pattern: \\`https://www.figma.com/design/...\\` or \\`http://www.figma.com/design/...\\`\n- Extract the ENTIRE URL including all query parameters\n- If URL not found in current message, check previous messages\n\n**Step 2: Check Tool Configuration**\n\nBefore calling the tool, verify that Figma tool is configured:\n- If not configured, inform user to run: \\`aikit skills figma-analysis config\\`\n- The tool requires a Figma Personal Access Token\n\n**Step 3: Call MCP Tool**\n\n**CRITICAL**: You MUST use the MCP tool \\`tool_read_figma_design\\`, NOT web fetch!\n\n**The correct tool name is**: \\`tool_read_figma_design\\` (exposed via MCP)\n\n**DO NOT use**:\n- ❌ \\`read_figma_design\\` (wrong - missing \"tool_\" prefix)\n- ❌ \\`figma-analysis/read_figma_design\\` (wrong format)\n- ❌ Web fetch (file requires authentication)\n\n**DO use**:\n- ✅ \\`tool_read_figma_design\\` (correct MCP tool name)\n\nUse the MCP tool:\n\\`\\`\\`\nUse MCP tool: tool_read_figma_design\nArguments: { \"url\": \"[extracted URL]\" }\n\\`\\`\\`\n\nThe tool has the Figma API token configured and will authenticate automatically.\n\nThis tool will:\n1. Validate the Figma URL format\n2. Check if Figma tool is configured\n3. Call Figma API to fetch design data\n4. Extract design tokens:\n - Colors (from fills and strokes)\n - Typography (font families, sizes, weights, line heights)\n - Spacing system (8px grid detection)\n - Components (from Figma components)\n - Screens/Frames (dimensions and names)\n - Breakpoints (common responsive breakpoints)\n5. Return formatted markdown with all extracted tokens\n\n**Step 4: Format and Save**\n\nFormat extracted tokens as structured markdown:\n\\`\\`\\`markdown\n# Figma Design Analysis\n\n**Source**: [Figma URL]\n**Analyzed**: [Date]\n\n## Screens/Pages\n- [List all screens]\n\n## Color Palette\n### Primary Colors\n- Color Name: #hexcode\n[Continue for all colors]\n\n## Typography\n### Font Families\n- Primary: Font Name\n[Continue]\n\n### Font Sizes\n- Heading 1: 48px\n[Continue for all sizes]\n\n## Spacing System\n- Base unit: 8px\n- Values used: [list]\n\n## Component Structure\n- Header: [description]\n[Continue for all components]\n\n## Layout Grid\n- Container max-width: [value]\n- Columns: [value]\n\n## Responsive Breakpoints\n- Mobile: [range]\n- Tablet: [range]\n- Desktop: [range]\n\n## Assets Needed\n### Images\n- [List]\n\n### Icons\n- [List]\n\n### Fonts\n- [List]\n\\`\\`\\`\n\nSave to memory using memory-update tool:\n\\`\\`\\`\nUse tool: memory-update\nArguments: {\n \"key\": \"research/figma-analysis\",\n \"content\": \"[formatted markdown]\"\n}\n\\`\\`\\`\n\n**Step 5: Report Results**\n\nSummarize what was extracted:\n- Number of colors found\n- Number of typography styles\n- Number of components\n- Number of screens/frames\n- Confirm save location: \\`memory/research/figma-analysis.md\\`\n\n## Important Notes\n\n- **DO NOT** ask user to provide URL again - extract it from input\n- **DO NOT** wait - start immediately after extracting URL\n- The URL is in the SAME message as the command\n- The tool uses Figma API, so the file must be accessible with your API token\n- If the tool returns an error about configuration, guide user to run: \\`aikit skills figma-analysis config\\`\n- If the tool returns an error about access, verify the file is accessible with your token\n\nThe analysis will be saved automatically for later reference.`,\n },\n {\n name: 'refactor',\n description: 'Refactor code to improve structure without changing behavior',\n category: 'quick',\n usage: '/refactor [file or pattern]',\n examples: ['/refactor src/utils.ts', '/refactor duplicate code'],\n content: `Refactor code following best practices.\n\n## Workflow\n1. Ensure tests are in place\n2. Identify refactoring opportunities\n3. Apply refactoring incrementally\n4. Run tests after each change\n5. Verify no behavior changes`,\n },\n {\n name: 'test',\n description: 'Run tests and show results',\n category: 'utility',\n usage: '/test [pattern]',\n examples: ['/test', '/test auth', '/test --watch'],\n content: `Run test suite and display results.\n\n## Workflow\n1. Run test command: \\`npm run test\\`\n2. Parse and display results\n3. Show coverage if available\n4. Highlight failures\n5. Suggest fixes for failures`,\n },\n {\n name: 'lint',\n description: 'Run linter and fix issues',\n category: 'quick',\n usage: '/lint [--fix]',\n examples: ['/lint', '/lint --fix'],\n content: `Run linter and optionally fix issues.\n\n## Workflow\n1. Run linter: \\`npm run lint\\`\n2. Parse errors and warnings\n3. If --fix flag, run auto-fix\n4. Report remaining issues\n5. Suggest manual fixes if needed`,\n },\n {\n name: 'deploy',\n description: 'Deploy application to production',\n category: 'utility',\n usage: '/deploy [environment]',\n examples: ['/deploy', '/deploy staging', '/deploy production'],\n content: `Deploy application with quality checks.\n\n## Workflow\n1. Run quality gates (test, lint, build)\n2. Check for uncommitted changes\n3. Build production bundle\n4. Deploy to target environment\n5. Verify deployment success`,\n },\n {\n name: 'rollback',\n description: 'Rollback to previous deployment',\n category: 'utility',\n usage: '/rollback [version]',\n examples: ['/rollback', '/rollback v1.2.3'],\n content: `Rollback to previous version.\n\n## Workflow\n1. Identify current version\n2. List available versions\n3. Confirm rollback target\n4. Execute rollback\n5. Verify rollback success`,\n },\n {\n name: 'logs',\n description: 'View application logs',\n category: 'utility',\n usage: '/logs [--tail] [--follow]',\n examples: ['/logs', '/logs --tail 100', '/logs --follow'],\n content: `View and filter application logs.\n\n## Workflow\n1. Determine log location\n2. Apply filters if specified\n3. Display logs\n4. If --follow, stream updates\n5. Format for readability`,\n },\n];\n\n/**\n * Command Runner - Manages and executes slash commands\n */\nexport class CommandRunner {\n private config: Config;\n private commandsCache: Map<string, Command> = new Map();\n\n constructor(config: Config) {\n this.config = config;\n }\n\n /**\n * List all available commands\n */\n async listCommands(): Promise<Command[]> {\n const commands: Command[] = [];\n \n // Add default commands\n for (const cmd of DEFAULT_COMMANDS) {\n commands.push({\n ...cmd,\n filePath: 'built-in',\n });\n }\n \n // Load custom commands from global config\n const globalCommandsPath = paths.commands(paths.globalConfig());\n try {\n const globalCommands = await this.loadCommandsFromDir(globalCommandsPath);\n commands.push(...globalCommands);\n } catch {\n // No global commands\n }\n \n // Load custom commands from project config\n const projectCommandsPath = paths.commands(this.config.configPath);\n if (projectCommandsPath !== globalCommandsPath) {\n try {\n const projectCommands = await this.loadCommandsFromDir(projectCommandsPath);\n // Override with project commands\n for (const cmd of projectCommands) {\n const existingIndex = commands.findIndex(c => c.name === cmd.name);\n if (existingIndex >= 0) {\n commands[existingIndex] = cmd;\n } else {\n commands.push(cmd);\n }\n }\n } catch {\n // No project commands\n }\n }\n \n return commands.sort((a, b) => a.name.localeCompare(b.name));\n }\n\n /**\n * Get a specific command\n */\n async getCommand(name: string): Promise<Command | null> {\n if (this.commandsCache.has(name)) {\n return this.commandsCache.get(name)!;\n }\n \n const commands = await this.listCommands();\n const command = commands.find(c => c.name === name);\n \n if (command) {\n this.commandsCache.set(name, command);\n }\n \n return command || null;\n }\n\n /**\n * Create a custom command\n */\n async createCommand(name: string, options?: {\n description?: string;\n category?: string;\n usage?: string;\n examples?: string[];\n content?: string;\n global?: boolean;\n }): Promise<Command> {\n const configPath = options?.global ? paths.globalConfig() : this.config.configPath;\n const category = options?.category || 'utility';\n const commandsDir = join(paths.commands(configPath), category);\n \n await mkdir(commandsDir, { recursive: true });\n \n const fileName = `${name}.md`;\n const filePath = join(commandsDir, fileName);\n \n const frontmatter: CommandFrontmatter = {\n name,\n description: options?.description || `Custom command: ${name}`,\n category,\n usage: options?.usage || `/${name}`,\n examples: options?.examples || [`/${name}`],\n };\n \n const content = options?.content || `## /${name}\n\nDescribe what this command does.\n\n## Workflow\n1. Step 1\n2. Step 2\n3. Step 3\n`;\n\n const fileContent = matter.stringify(content, frontmatter);\n await writeFile(filePath, fileContent);\n \n const command: Command = {\n name,\n description: frontmatter.description!,\n category,\n usage: frontmatter.usage!,\n examples: frontmatter.examples!,\n content,\n filePath,\n };\n \n this.commandsCache.set(name, command);\n \n return command;\n }\n\n /**\n * Format command for agent consumption\n */\n formatForAgent(command: Command): string {\n return `# Command: /${command.name}\n\n## Usage\n\\`${command.usage}\\`\n\n## Description\n${command.description}\n\n## Examples\n${command.examples.map(e => `- \\`${e}\\``).join('\\n')}\n\n## Workflow\n${command.content}\n`;\n }\n\n /**\n * Load commands from directory (recursively)\n */\n private async loadCommandsFromDir(dir: string): Promise<Command[]> {\n const commands: Command[] = [];\n \n const processDir = async (currentDir: string, category: string) => {\n try {\n const entries = await readdir(currentDir, { withFileTypes: true });\n \n for (const entry of entries) {\n const fullPath = join(currentDir, entry.name);\n \n if (entry.isDirectory()) {\n await processDir(fullPath, entry.name);\n } else if (extname(entry.name) === '.md') {\n const content = await readFile(fullPath, 'utf-8');\n const { data, content: body } = matter(content);\n const frontmatter = data as CommandFrontmatter;\n const name = frontmatter.name || basename(entry.name, '.md');\n \n commands.push({\n name,\n description: frontmatter.description || '',\n category: frontmatter.category || category,\n usage: frontmatter.usage || `/${name}`,\n examples: frontmatter.examples || [],\n content: body.trim(),\n filePath: fullPath,\n });\n }\n }\n } catch {\n // Directory doesn't exist or can't be read\n return;\n }\n };\n \n await processDir(dir, 'custom');\n return commands;\n }\n}\n","import { readdir, writeFile, mkdir } from 'fs/promises';\nimport { join, extname } from 'path';\nimport { z } from 'zod';\nimport { Config } from './config.js';\nimport { paths } from '../utils/paths.js';\nimport { logger } from '../utils/logger.js';\n\n/**\n * Tool argument schema\n */\nexport const ToolArgSchema = z.object({\n type: z.enum(['string', 'number', 'boolean', 'array', 'object']),\n description: z.string(),\n required: z.boolean().optional().default(true),\n default: z.any().optional(),\n});\n\nexport type ToolArg = z.infer<typeof ToolArgSchema>;\n\n/**\n * Tool definition\n */\nexport interface Tool {\n name: string;\n description: string;\n args: Record<string, ToolArg>;\n execute: (args: Record<string, unknown>) => Promise<string>;\n filePath?: string;\n}\n\n/**\n * Tool definition helper for type safety\n */\nexport function defineTool(config: {\n name: string;\n description: string;\n args: Record<string, ToolArg>;\n execute: (args: Record<string, unknown>) => Promise<string>;\n}): Tool {\n return config;\n}\n\n/**\n * Built-in tools\n */\nconst BUILT_IN_TOOLS: Tool[] = [\n {\n name: 'websearch',\n description: 'Search the web for documentation, articles, and current information',\n args: {\n query: {\n type: 'string',\n description: 'The search query',\n required: true,\n },\n numResults: {\n type: 'number',\n description: 'Number of results to return (default: 5)',\n required: false,\n default: 5,\n },\n },\n async execute({ query }) {\n // This would integrate with a search API (Exa, Tavily, etc.)\n // For now, return placeholder\n return `Web search results for: \"${query}\"\\n\\nNote: Configure a search provider in AIKit settings for actual results.`;\n },\n },\n {\n name: 'codesearch',\n description: 'Search GitHub for code patterns and examples across millions of repositories',\n args: {\n query: {\n type: 'string',\n description: 'The code pattern or search query',\n required: true,\n },\n language: {\n type: 'string',\n description: 'Programming language to filter by',\n required: false,\n },\n },\n async execute({ query, language }) {\n // This would integrate with GitHub code search\n const langFilter = language ? ` in ${language}` : '';\n return `GitHub code search for: \"${query}\"${langFilter}\\n\\nNote: Configure GitHub integration in AIKit settings for actual results.`;\n },\n },\n {\n name: 'memory-read',\n description: 'Read from persistent memory (project or global)',\n args: {\n key: {\n type: 'string',\n description: 'The memory key to read',\n required: true,\n },\n },\n async execute({ key }) {\n // Implemented by MemoryManager\n return `Memory read: ${key}`;\n },\n },\n {\n name: 'memory-update',\n description: 'Update persistent memory with new information',\n args: {\n key: {\n type: 'string',\n description: 'The memory key to update',\n required: true,\n },\n content: {\n type: 'string',\n description: 'The content to write',\n required: true,\n },\n append: {\n type: 'boolean',\n description: 'Whether to append to existing content (default: true)',\n required: false,\n default: true,\n },\n },\n async execute({ key, append = true }) {\n // Implemented by MemoryManager\n return `Memory updated: ${key} (append: ${append})`;\n },\n },\n {\n name: 'find_skills',\n description: 'Find available workflow skills',\n args: {\n query: {\n type: 'string',\n description: 'Optional search query to filter skills',\n required: false,\n },\n },\n async execute({ query }) {\n // Implemented by SkillEngine integration\n return `Skills matching: ${query || 'all'}`;\n },\n },\n {\n name: 'use_skill',\n description: 'Load and use a specific skill workflow',\n args: {\n name: {\n type: 'string',\n description: 'Name of the skill to use',\n required: true,\n },\n },\n async execute({ name }) {\n // Implemented by SkillEngine integration\n return `Loading skill: ${name}`;\n },\n },\n {\n name: 'read_figma_design',\n description: 'Read and analyze a Figma design using Figma API. Extracts design tokens including colors, typography, spacing, components, and layout.',\n args: {\n url: {\n type: 'string',\n description: 'Figma design URL to analyze (must start with https://www.figma.com/design/)',\n required: true,\n },\n },\n async execute({ url }, context?: { toolConfigManager?: import('./tool-config.js').ToolConfigManager }) {\n // Validate Figma URL\n if (!url || typeof url !== 'string') {\n return 'Error: Invalid URL provided';\n }\n \n if (!url.startsWith('https://www.figma.com/design/') && !url.startsWith('http://www.figma.com/design/')) {\n return `Error: Invalid Figma URL format. URL must start with https://www.figma.com/design/\\n\\nProvided URL: ${url}`;\n }\n\n // Check if Figma tool is configured\n const configManager = context?.toolConfigManager;\n if (!configManager) {\n return `Error: Tool configuration manager not available. This usually means the MCP server isn't properly initialized. Please restart OpenCode.\\n\\nIf the issue persists, configure Figma tool manually: aikit skills figma-analysis config`;\n }\n\n const isReady = await configManager.isToolReady('figma-analysis');\n if (!isReady) {\n // Provide more helpful error message\n const toolConfig = await configManager.getToolConfig('figma-analysis');\n if (toolConfig?.status === 'error') {\n return `Error: Figma tool configuration error: ${toolConfig.errorMessage || 'Unknown error'}\\n\\nPlease reconfigure: aikit skills figma-analysis config`;\n }\n return `Error: Figma tool is not configured. Please run: aikit skills figma-analysis config\\n\\nThis will guide you through setting up your Figma Personal Access Token.`;\n }\n\n const apiKey = await configManager.getApiKey('figma-analysis');\n if (!apiKey) {\n return `Error: Figma API key not found. Please run: aikit skills figma-analysis config`;\n }\n\n try {\n // Use Figma MCP client to extract design tokens\n const { FigmaMcpClient } = await import('./tools/figma-mcp.js');\n const client = new FigmaMcpClient(apiKey, configManager);\n \n // Determine assets directory (use project root or current working directory)\n const assetsDir = './assets/images';\n \n // Extract design tokens (without downloading assets yet - will do after screen selection)\n const tokens = await client.extractDesignTokens(url, false, assetsDir);\n\n // Format results\n let result = `# Figma Design Analysis\\n\\n`;\n result += `**URL**: ${url}\\n\\n`;\n \n result += `## Design Structure & Content\\n\\n`;\n \n // Structure hierarchy\n if (tokens.structure) {\n result += `### Node Hierarchy (${tokens.structure.nodes.length} nodes)\\n\\n`;\n result += `\\`\\`\\`\\n${tokens.structure.hierarchy}\\n\\`\\`\\`\\n\\n`;\n \n // Key elements with content\n const textNodes = tokens.structure.nodes.filter(n => n.type === 'TEXT' && n.content);\n if (textNodes.length > 0) {\n result += `### Text Content (${textNodes.length} text elements)\\n\\n`;\n textNodes.slice(0, 20).forEach(node => {\n const preview = node.content && node.content.length > 100 \n ? node.content.substring(0, 100) + '...' \n : node.content;\n result += `- **${node.name}**: \"${preview}\"\\n`;\n if (node.styles) {\n result += ` - Style: ${node.styles.fontFamily || 'N/A'} ${node.styles.fontSize || 'N/A'}px, weight ${node.styles.fontWeight || 'N/A'}\\n`;\n }\n });\n if (textNodes.length > 20) {\n result += `\\n... and ${textNodes.length - 20} more text elements\\n`;\n }\n result += `\\n`;\n }\n\n // Layout structure\n const frameNodes = tokens.structure.nodes.filter(n => n.type === 'FRAME' || n.type === 'COMPONENT');\n if (frameNodes.length > 0) {\n result += `### Layout Structure (${frameNodes.length} frames/components)\\n\\n`;\n frameNodes.slice(0, 15).forEach(node => {\n result += `- **${node.name}** (${node.type})\\n`;\n if (node.position) {\n result += ` - Position: x=${Math.round(node.position.x)}, y=${Math.round(node.position.y)}\\n`;\n result += ` - Size: ${Math.round(node.position.width)}×${Math.round(node.position.height)}px\\n`;\n }\n if (node.styles?.layout) {\n result += ` - Layout: ${node.styles.layout}${node.styles.gap ? `, gap: ${node.styles.gap}px` : ''}\\n`;\n }\n if (node.children && node.children.length > 0) {\n result += ` - Children: ${node.children.length}\\n`;\n }\n });\n if (frameNodes.length > 15) {\n result += `\\n... and ${frameNodes.length - 15} more frames/components\\n`;\n }\n result += `\\n`;\n }\n }\n \n result += `## Design Tokens\\n\\n`;\n \n // Colors\n if (tokens.colors.length > 0) {\n result += `### Colors (${tokens.colors.length} found)\\n\\n`;\n tokens.colors.slice(0, 30).forEach(color => {\n result += `- \\`${color.hex}\\`\\n`;\n });\n if (tokens.colors.length > 30) {\n result += `\\n... and ${tokens.colors.length - 30} more colors\\n`;\n }\n result += `\\n`;\n }\n\n // Typography\n if (tokens.typography.length > 0) {\n result += `### Typography (${tokens.typography.length} styles)\\n\\n`;\n tokens.typography.forEach(typography => {\n result += `- **${typography.name}**: ${typography.fontFamily}, ${typography.fontSize}px, weight ${typography.fontWeight}, line-height ${typography.lineHeight}px\\n`;\n });\n result += `\\n`;\n }\n\n // Spacing\n result += `### Spacing System\\n\\n`;\n result += `- Base unit: ${tokens.spacing.unit}px\\n`;\n result += `- Scale: ${tokens.spacing.scale.length > 0 ? tokens.spacing.scale.join(', ') : 'Not detected'}\\n\\n`;\n\n // Components\n if (tokens.components.length > 0) {\n result += `### Components (${tokens.components.length} found)\\n\\n`;\n tokens.components.forEach(component => {\n result += `- **${component.name}**: ${component.type}${component.description ? ` - ${component.description}` : ''}\\n`;\n });\n result += `\\n`;\n }\n\n // Screens - Show with selection prompt\n if (tokens.screens.length > 0) {\n result += `## Available Screens/Frames (${tokens.screens.length} found)\\n\\n`;\n result += `**Please confirm which screen(s) you want to develop:**\\n\\n`;\n tokens.screens.forEach((screen, index) => {\n result += `${index + 1}. **${screen.name}**\\n`;\n result += ` - Size: ${screen.width}×${screen.height}px\\n`;\n result += ` - Type: ${screen.type}\\n`;\n if (screen.childrenCount) {\n result += ` - Components: ${screen.childrenCount}\\n`;\n }\n result += ` - ID: \\`${screen.id}\\`\\n\\n`;\n });\n result += `\\n**To proceed, simply reply with the screen number(s) or name(s) you want to develop.**\\n`;\n result += `Example: \"1\" or \"Main Page\" or \"1, 2, 3\"\\n\\n`;\n }\n\n // Breakpoints\n result += `### Responsive Breakpoints\\n\\n`;\n result += `- ${tokens.breakpoints.join('px, ')}px\\n\\n`;\n\n // Assets\n if (tokens.assets && tokens.assets.length > 0) {\n result += `## Downloaded Assets (${tokens.assets.length} files)\\n\\n`;\n result += `All assets have been downloaded to: \\`${tokens.assets[0].path.split('/').slice(0, -1).join('/')}\\`\\n\\n`;\n result += `### Image Files\\n\\n`;\n tokens.assets.forEach(asset => {\n const relativePath = asset.path.replace(process.cwd() + '/', '');\n result += `- **${asset.nodeName}** (${asset.nodeType})\\n`;\n result += ` - File: \\`${relativePath}\\`\\n`;\n if (asset.width && asset.height) {\n result += ` - Size: ${Math.round(asset.width)}×${Math.round(asset.height)}px\\n`;\n }\n result += ` - Format: ${asset.format.toUpperCase()}\\n`;\n result += ` - Usage: \\`<img src=\"${relativePath}\" alt=\"${asset.nodeName}\" />\\`\\n\\n`;\n });\n }\n\n result += `## Implementation Guide\\n\\n`;\n result += `### Structure Analysis\\n`;\n result += `The design contains ${tokens.structure?.nodes.length || 0} nodes organized in a hierarchical structure.\\n`;\n result += `Use the node hierarchy above to understand:\\n`;\n result += `1. **Component structure** - How elements are organized\\n`;\n result += `2. **Text content** - All text content from TEXT nodes\\n`;\n result += `3. **Layout properties** - Flex direction, gaps, padding\\n`;\n result += `4. **Positioning** - Exact x, y, width, height values\\n\\n`;\n result += `### Next Steps\\n\\n`;\n result += `1. Review the structure hierarchy to understand component organization\\n`;\n result += `2. Extract text content from TEXT nodes for HTML content\\n`;\n result += `3. Use position and size data for pixel-perfect CSS\\n`;\n result += `4. Use layout properties (HORIZONTAL/VERTICAL) for flexbox/grid\\n`;\n result += `5. Use extracted design tokens (colors, typography) for styling\\n`;\n result += `6. Save this analysis: \\`memory-update(\"research/figma-analysis\", \"[this analysis]\")\\`\\n`;\n\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return `Error analyzing Figma design: ${errorMessage}\\n\\nPlease check:\\n1. The Figma URL is correct and accessible\\n2. Your Figma API token has proper permissions\\n3. The design file is shared with your account`;\n }\n },\n },\n {\n name: 'analyze_figma',\n description: 'Analyze a Figma design URL and extract all design tokens automatically. The URL should be provided in the user input after the command.',\n args: {\n url: {\n type: 'string',\n description: 'Figma design URL to analyze',\n required: true,\n },\n },\n async execute({ url }) {\n // This tool will be used by agents to analyze Figma\n // The actual analysis will be done by @vision agent\n return `Figma analysis tool called for: ${url}\\n\\nNext steps:\\n1. Use @vision agent to analyze the design\\n2. Extract all design tokens\\n3. Save to memory/research/figma-analysis.md`;\n },\n },\n {\n name: 'develop_figma_screen',\n description: 'Smart workflow to develop a specific Figma screen: check current code, pull needed assets, plan, and develop. User just needs to confirm the screen number/name.',\n args: {\n figmaUrl: {\n type: 'string',\n description: 'Figma design URL',\n required: true,\n },\n screenId: {\n type: 'string',\n description: 'Screen ID or name to develop (from read_figma_design output)',\n required: true,\n },\n },\n async execute({ figmaUrl, screenId }, context?: { toolConfigManager?: import('./tool-config.js').ToolConfigManager }) {\n const configManager = context?.toolConfigManager;\n if (!configManager) {\n return 'Error: Tool configuration manager not available.';\n }\n\n const isReady = await configManager.isToolReady('figma-analysis');\n if (!isReady) {\n return 'Error: Figma tool is not configured. Please run: aikit skills figma-analysis config';\n }\n\n const apiKey = await configManager.getApiKey('figma-analysis');\n if (!apiKey) {\n return 'Error: Figma API key not found.';\n }\n\n try {\n const { FigmaMcpClient } = await import('./tools/figma-mcp.js');\n const { checkCurrentCodeStatus, compareCodeWithFigma } = await import('./tools/figma-screen-developer.js');\n \n const client = new FigmaMcpClient(apiKey, configManager);\n \n // Step 1: Extract design tokens\n const tokens = await client.extractDesignTokens(figmaUrl as string, false, './assets/images');\n \n // Step 2: Find selected screen\n const screenIdStr = String(screenId);\n const selectedScreen = tokens.screens?.find((s: any) => \n s.id === screenIdStr || s.name.toLowerCase() === screenIdStr.toLowerCase()\n );\n \n if (!selectedScreen) {\n return `Error: Screen \"${screenId}\" not found. Available screens:\\n${tokens.screens?.map((s: any, i: number) => `${i + 1}. ${s.name} (ID: ${s.id})`).join('\\n') || 'None'}`;\n }\n\n // Step 3: Check current code status\n const codeStatus = await checkCurrentCodeStatus();\n \n // Step 4: Compare with Figma\n const comparison = await compareCodeWithFigma(tokens, selectedScreen.id);\n \n // Step 5: Download assets for this screen only\n let downloadedAssets: any[] = [];\n const fileKey = (client as any).extractFileKey(figmaUrl as string);\n if (fileKey) {\n try {\n const fileData = await (client as any).getFileData(figmaUrl as string);\n // Use absolute path for assets directory\n const projectPath = process.cwd();\n const assetsDir = join(projectPath, 'assets', 'images');\n const assets = await (client as any).downloadAssets(fileKey, fileData.document, assetsDir, selectedScreen.id);\n downloadedAssets = assets || [];\n logger.info(`Downloaded ${downloadedAssets.length} assets for screen ${selectedScreen.name}`);\n } catch (error) {\n logger.warn(`Failed to download assets: ${error instanceof Error ? error.message : String(error)}`);\n downloadedAssets = [];\n }\n }\n\n // Step 6: Generate detailed plan\n let result = `# Development Plan for Screen: ${selectedScreen.name}\\n\\n`;\n result += `## Current Code Status\\n\\n`;\n result += `- HTML: ${codeStatus.hasHTML ? `✅ ${codeStatus.htmlFile}` : '❌ Not found'}\\n`;\n result += `- CSS: ${codeStatus.hasCSS ? `✅ ${codeStatus.cssFiles.length} files` : '❌ Not found'}\\n`;\n result += `- Assets: ${codeStatus.hasAssets ? `✅ ${codeStatus.assetCount} files` : '❌ Not found'}\\n`;\n result += `- Existing Sections: ${codeStatus.sections.length > 0 ? codeStatus.sections.join(', ') : 'None'}\\n\\n`;\n \n result += `## Comparison with Figma Design\\n\\n`;\n result += `- Missing Sections: ${comparison.missingSections.length > 0 ? comparison.missingSections.join(', ') : 'None'}\\n`;\n result += `- Missing Assets: ${comparison.missingAssets.length > 0 ? comparison.missingAssets.join(', ') : 'None'}\\n`;\n result += `- Needs Update: ${comparison.needsUpdate ? 'Yes' : 'No'}\\n\\n`;\n \n result += `## Recommendations\\n\\n`;\n comparison.recommendations.forEach((rec, i) => {\n result += `${i + 1}. ${rec}\\n`;\n });\n result += `\\n`;\n \n result += `## Downloaded Assets (${downloadedAssets.length})\\n\\n`;\n if (downloadedAssets.length > 0) {\n downloadedAssets.forEach((asset: any) => {\n const relativePath = asset.path.replace(process.cwd() + '/', '');\n result += `- **${asset.nodeName}** (${asset.nodeType})\\n`;\n result += ` - File: \\`${relativePath}\\`\\n`;\n if (asset.width && asset.height) {\n result += ` - Size: ${Math.round(asset.width)}×${Math.round(asset.height)}px\\n`;\n }\n result += ` - Usage: \\`<img src=\"${relativePath}\" alt=\"${asset.nodeName}\" />\\`\\n\\n`;\n });\n \n // Add critical instruction to use downloaded assets\n result += `\\n**⚠️ IMPORTANT: Use downloaded assets above instead of placeholder images!**\\n`;\n result += `Replace all Unsplash/placeholder image URLs with the downloaded asset paths.\\n\\n`;\n } else {\n result += `**No assets downloaded.** This may indicate:\\n`;\n result += `1. The screen doesn't contain exportable image nodes\\n`;\n result += `2. Assets download failed (check logs)\\n`;\n result += `3. Figma API permissions issue\\n\\n`;\n }\n \n result += `\\n## Next Steps\\n\\n`;\n result += `1. Review the plan above\\n`;\n result += `2. Use @build agent to implement missing sections\\n`;\n result += `3. Use extracted design tokens for CSS variables\\n`;\n result += `4. Use downloaded assets in HTML\\n`;\n result += `5. Verify pixel-perfect match with Figma design\\n`;\n\n return result;\n } catch (error) {\n return `Error: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n },\n {\n name: 'list_session',\n description: 'List previous sessions to discover what happened and when. Use this before read_session to find the right context.',\n args: {\n limit: {\n type: 'number',\n description: 'Maximum number of sessions to return (default: 10)',\n required: false,\n default: 10,\n },\n },\n async execute({ limit = 10 }, context?: { config?: Config }) {\n const config = context?.config;\n if (!config) {\n return 'Error: Configuration not available';\n }\n \n // Ensure limit is a number\n const limitNum = typeof limit === 'number' ? limit : 10;\n \n try {\n const { MemoryManager } = await import('./memory.js');\n const memory = new MemoryManager(config);\n const memories = await memory.list();\n \n // Filter handoffs (sessions)\n const handoffs = memories\n .filter(m => m.type === 'handoff')\n .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())\n .slice(0, limitNum);\n \n if (handoffs.length === 0) {\n return 'No previous sessions found. Use /handoff to create a session handoff.';\n }\n \n let result = `# Previous Sessions (${handoffs.length})\\n\\n`;\n handoffs.forEach((handoff, index) => {\n const sessionId = handoff.key.replace('handoffs/', '');\n result += `${index + 1}. **${sessionId}**\\n`;\n result += ` - Updated: ${handoff.updatedAt.toLocaleString()}\\n`;\n result += ` - Summary: ${handoff.summary}\\n\\n`;\n });\n \n result += `\\nUse \\`read_session\\` with a session ID to load full context.`;\n return result;\n } catch (error) {\n return `Error listing sessions: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n },\n {\n name: 'read_session',\n description: 'Load context from a previous session. Returns session summary, user tasks, and file changes.',\n args: {\n sessionId: {\n type: 'string',\n description: 'Session ID from list_session (e.g., \"2024-01-15T10-30-00\")',\n required: true,\n },\n },\n async execute({ sessionId }, context?: { config?: Config }) {\n const config = context?.config;\n if (!config) {\n return 'Error: Configuration not available';\n }\n \n try {\n const { MemoryManager } = await import('./memory.js');\n const memory = new MemoryManager(config);\n const content = await memory.read(`handoffs/${sessionId}`);\n \n if (!content) {\n return `Session not found: ${sessionId}\\n\\nUse \\`list_session\\` to see available sessions.`;\n }\n \n return `# Session Context: ${sessionId}\\n\\n${content}\\n\\n---\\n\\nThis context has been loaded. Use /resume to continue from this point.`;\n } catch (error) {\n return `Error reading session: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n },\n];\n\n/**\n * Tool Registry - Manages custom tools for AI agents\n */\nexport class ToolRegistry {\n private config: Config;\n private tools: Map<string, Tool> = new Map();\n private toolConfigManager?: import('./tool-config.js').ToolConfigManager;\n\n constructor(config: Config) {\n this.config = config;\n \n // Register built-in tools\n for (const tool of BUILT_IN_TOOLS) {\n this.tools.set(tool.name, tool);\n }\n }\n\n /**\n * Set tool config manager (for tools that need configuration)\n */\n setToolConfigManager(manager: import('./tool-config.js').ToolConfigManager): void {\n this.toolConfigManager = manager;\n }\n\n /**\n * List all available tools\n */\n async listTools(): Promise<Tool[]> {\n // Load custom tools\n await this.loadCustomTools();\n return Array.from(this.tools.values());\n }\n\n /**\n * Get a specific tool\n */\n getTool(name: string): Tool | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Register a new tool\n */\n registerTool(tool: Tool): void {\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Execute a tool\n */\n async executeTool(name: string, args: Record<string, unknown>, context?: { toolConfigManager?: import('./tool-config.js').ToolConfigManager }): Promise<string> {\n const tool = this.tools.get(name);\n if (!tool) {\n throw new Error(`Tool not found: ${name}`);\n }\n \n // Validate required arguments\n for (const [argName, argDef] of Object.entries(tool.args)) {\n if (argDef.required && args[argName] === undefined) {\n throw new Error(`Missing required argument: ${argName}`);\n }\n }\n\n // Merge context with toolConfigManager from registry\n const mergedContext = {\n ...context,\n toolConfigManager: context?.toolConfigManager || this.toolConfigManager,\n };\n \n // Check if tool.execute accepts context parameter\n if (tool.execute.length === 2) {\n return await (tool.execute as (args: Record<string, unknown>, context?: any) => Promise<string>)(args, mergedContext);\n }\n \n return await tool.execute(args);\n }\n\n /**\n * Create a custom tool\n */\n async createTool(name: string, options: {\n description: string;\n args: Record<string, ToolArg>;\n code: string;\n global?: boolean;\n }): Promise<void> {\n const configPath = options.global ? paths.globalConfig() : this.config.configPath;\n const toolsDir = paths.tools(configPath);\n \n await mkdir(toolsDir, { recursive: true });\n \n const fileName = `${name}.ts`;\n const filePath = join(toolsDir, fileName);\n \n const argsSchema = Object.entries(options.args)\n .map(([argName, arg]) => ` ${argName}: {\n type: '${arg.type}',\n description: '${arg.description}',\n required: ${arg.required ?? true},\n }`)\n .join(',\\n');\n \n const content = `import { defineTool } from 'aikit';\n\nexport default defineTool({\n name: '${name}',\n description: '${options.description}',\n args: {\n${argsSchema}\n },\n async execute(args) {\n${options.code}\n }\n});\n`;\n \n await writeFile(filePath, content);\n }\n\n /**\n * Format tool for agent consumption\n */\n formatForAgent(tool: Tool): string {\n const argsDesc = Object.entries(tool.args)\n .map(([name, arg]) => ` - ${name} (${arg.type}${arg.required ? ', required' : ''}): ${arg.description}`)\n .join('\\n');\n \n return `## Tool: ${tool.name}\n\n${tool.description}\n\n### Arguments\n${argsDesc}\n`;\n }\n\n /**\n * Load custom tools from disk\n */\n private async loadCustomTools(): Promise<void> {\n // Load from global config\n const globalToolsPath = paths.tools(paths.globalConfig());\n await this.loadToolsFromDir(globalToolsPath);\n \n // Load from project config (override global)\n const projectToolsPath = paths.tools(this.config.configPath);\n if (projectToolsPath !== globalToolsPath) {\n await this.loadToolsFromDir(projectToolsPath);\n }\n }\n\n private async loadToolsFromDir(dir: string): Promise<void> {\n let files: string[];\n try {\n files = await readdir(dir);\n } catch {\n return; // Directory doesn't exist\n }\n \n for (const file of files) {\n if (extname(file) !== '.ts' && extname(file) !== '.js') continue;\n \n const filePath = join(dir, file);\n \n try {\n // Dynamic import of custom tool\n const toolModule = await import(`file://${filePath}`);\n const tool = toolModule.default as Tool;\n \n if (tool?.name && typeof tool.execute === 'function') {\n tool.filePath = filePath;\n this.tools.set(tool.name, tool);\n }\n } catch (error) {\n // Failed to load tool, skip\n logger.warn(`Failed to load tool from ${filePath}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n}\n","import { readFile, writeFile, mkdir, access, constants } from 'fs/promises';\nimport { join } from 'path';\nimport { z } from 'zod';\nimport { Config } from './config.js';\n\n/**\n * Tool configuration status\n */\nexport type ToolStatus = 'ready' | 'needs_config' | 'error';\n\n/**\n * Configuration method\n */\nexport type ConfigMethod = 'oauth' | 'manual' | 'none';\n\n/**\n * Tool configuration schema\n */\nconst ToolConfigSchema = z.object({\n name: z.string(),\n status: z.enum(['ready', 'needs_config', 'error']),\n description: z.string(),\n configMethod: z.enum(['oauth', 'manual', 'none']),\n config: z.record(z.unknown()).optional(),\n errorMessage: z.string().optional(),\n});\n\nexport type ToolConfig = z.infer<typeof ToolConfigSchema>;\n\n/**\n * Tools registry with configuration\n */\nconst REGISTERED_TOOLS: Omit<ToolConfig, 'status' | 'config' | 'errorMessage'>[] = [\n {\n name: 'figma-analysis',\n description: 'Analyze Figma designs and extract design tokens using Figma API',\n configMethod: 'oauth',\n },\n // Add more tools here as needed\n];\n\n/**\n * Tool Configuration Manager\n */\nexport class ToolConfigManager {\n private config: Config;\n private toolsConfigPath: string;\n\n constructor(config: Config) {\n this.config = config;\n this.toolsConfigPath = join(this.config.configPath, 'config', 'tools.json');\n }\n\n /**\n * Get all registered tools with their current status\n */\n async listTools(): Promise<ToolConfig[]> {\n const savedConfigs = await this.loadConfigs();\n const tools: ToolConfig[] = [];\n\n for (const tool of REGISTERED_TOOLS) {\n const saved = savedConfigs[tool.name];\n const toolConfig: ToolConfig = {\n ...tool,\n status: this.determineStatus(tool, saved),\n config: saved?.config,\n errorMessage: saved?.errorMessage,\n };\n tools.push(toolConfig);\n }\n\n return tools;\n }\n\n /**\n * Get configuration for a specific tool\n */\n async getToolConfig(toolName: string): Promise<ToolConfig | null> {\n const tools = await this.listTools();\n return tools.find(t => t.name === toolName) || null;\n }\n\n /**\n * Update tool configuration\n */\n async updateToolConfig(toolName: string, updates: {\n config?: Record<string, unknown>;\n status?: ToolStatus;\n errorMessage?: string;\n }): Promise<void> {\n const savedConfigs = await this.loadConfigs();\n const tool = REGISTERED_TOOLS.find(t => t.name === toolName);\n\n if (!tool) {\n throw new Error(`Tool not found: ${toolName}`);\n }\n\n const existing = savedConfigs[toolName] || {};\n savedConfigs[toolName] = {\n ...existing,\n ...updates,\n };\n\n await this.saveConfigs(savedConfigs);\n }\n\n /**\n * Check if a tool is ready to use\n */\n async isToolReady(toolName: string): Promise<boolean> {\n const toolConfig = await this.getToolConfig(toolName);\n return toolConfig?.status === 'ready';\n }\n\n /**\n * Get API key for a tool (if configured)\n */\n async getApiKey(toolName: string): Promise<string | null> {\n const toolConfig = await this.getToolConfig(toolName);\n if (toolConfig?.config?.apiKey && typeof toolConfig.config.apiKey === 'string') {\n return toolConfig.config.apiKey;\n }\n return null;\n }\n\n /**\n * Determine tool status based on configuration\n */\n private determineStatus(\n tool: Omit<ToolConfig, 'status' | 'config' | 'errorMessage'>,\n saved?: { config?: Record<string, unknown>; errorMessage?: string }\n ): ToolStatus {\n if (tool.configMethod === 'none') {\n return 'ready';\n }\n\n if (saved?.errorMessage) {\n return 'error';\n }\n\n if (tool.configMethod === 'oauth' || tool.configMethod === 'manual') {\n // Check if API key is configured\n if (saved?.config?.apiKey && typeof saved.config.apiKey === 'string' && saved.config.apiKey.length > 0) {\n return 'ready';\n }\n return 'needs_config';\n }\n\n return 'needs_config';\n }\n\n /**\n * Load saved configurations\n */\n private async loadConfigs(): Promise<Record<string, { config?: Record<string, unknown>; errorMessage?: string }>> {\n try {\n await access(this.toolsConfigPath, constants.R_OK);\n const content = await readFile(this.toolsConfigPath, 'utf-8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n }\n\n /**\n * Save configurations\n */\n private async saveConfigs(configs: Record<string, unknown>): Promise<void> {\n const configDir = join(this.config.configPath, 'config');\n await mkdir(configDir, { recursive: true });\n await writeFile(this.toolsConfigPath, JSON.stringify(configs, null, 2));\n }\n}\n\n"],"mappings":";;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;;;ACAA,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,kBAAkB;AAF3B,IAOa;AAPb;AAAA;AAAA;AAAA;AAOO,IAAM,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA,MAK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,YACE,MAAM;AAAA,YACN,MAAM,yBAAyB,QAAQ;AAAA,UACzC;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,aAA4B;AAChC,QAAI;AACF,YAAM,SAAS,MAAM,WAAW;AAChC,WAAK,cAAc,IAAI,YAAY,MAAM;AACzC,WAAK,eAAe,IAAI,aAAa,MAAM;AAC3C,WAAK,gBAAgB,IAAI,cAAc,MAAM;AAC7C,WAAK,eAAe,IAAI,aAAa,MAAM;AAC3C,WAAK,oBAAoB,IAAI,kBAAkB,MAAM;AACrD,WAAK,aAAa,qBAAqB,KAAK,iBAAiB;AAG7D,YAAM,aAAa,MAAM,KAAK,kBAAkB,YAAY,gBAAgB;AAC5E,UAAI,YAAY;AACd,eAAO,KAAK,iCAAiC;AAAA,MAC/C,OAAO;AACL,eAAO,KAAK,iEAAiE;AAAA,MAC/E;AAAA,IACF,SAAS,OAAO;AACd,aAAO,MAAM,yBAAyB,KAAK,EAAE;AAC7C,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AAAA,EAEA,MAAM,QAAuB;AAC3B,UAAM,YAAY,IAAI,qBAAqB;AAC3C,UAAM,KAAK,OAAO,QAAQ,SAAS;AACnC,WAAO,KAAK,0BAA0B;AAAA,EACxC;AACF;AAEA,eAAe,OAAsB;AACnC,QAAM,SAAS,IAAI,eAAe;AAClC,QAAM,OAAO,WAAW;AACxB,QAAM,OAAO,MAAM;AACrB;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,SAAO,MAAM,gBAAgB,KAAK,EAAE;AACpC,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["writeFile","mkdir","join","existsSync","imageUrl","readFile","readdir","join","existsSync","readFile","writeFile","mkdir","access","constants","join","readdir","dirname","join","readFile","join","readFile","readdir","writeFile","mkdir","join","basename","extname","matter","join","mkdir","matter","writeFile","readdir","extname","readFile","basename","readdir","writeFile","mkdir","join","extname","z","FigmaMcpClient","checkCurrentCodeStatus","compareCodeWithFigma","join","MemoryManager","mkdir","writeFile","readdir","extname","readFile","writeFile","mkdir","access","constants","join","z"]}
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@tdsoft-tech/aikit",
3
+ "version": "0.1.2",
4
+ "description": "Open-source AI coding agent toolkit for OpenCode - skills, agents, commands, tools, and plugins",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "bin": {
9
+ "aikit": "./dist/cli.js",
10
+ "aikit-mcp": "./dist/mcp-server.js"
11
+ },
12
+ "files": [
13
+ "dist/",
14
+ "CHANGELOG.md",
15
+ "README.md"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsup",
19
+ "dev": "tsup --watch",
20
+ "start": "node dist/cli.js",
21
+ "lint": "eslint src --ext .ts",
22
+ "typecheck": "tsc --noEmit",
23
+ "test": "vitest run",
24
+ "test:watch": "vitest",
25
+ "prepare": "node scripts/postinstall.js"
26
+ },
27
+ "keywords": [
28
+ "opencode",
29
+ "ai",
30
+ "coding",
31
+ "agent",
32
+ "skills",
33
+ "cli",
34
+ "beads"
35
+ ],
36
+ "author": "",
37
+ "license": "MIT",
38
+ "dependencies": {
39
+ "@modelcontextprotocol/sdk": "^1.0.0",
40
+ "chalk": "^5.3.0",
41
+ "commander": "^12.1.0",
42
+ "figma-developer-mcp": "^0.6.4",
43
+ "glob": "^10.3.10",
44
+ "gray-matter": "^4.0.3",
45
+ "inquirer": "^9.2.12",
46
+ "js-yaml": "^4.1.0",
47
+ "open": "^10.1.0",
48
+ "zod": "^3.22.4"
49
+ },
50
+ "devDependencies": {
51
+ "@types/inquirer": "^9.0.7",
52
+ "@types/js-yaml": "^4.0.9",
53
+ "@types/node": "^20.10.0",
54
+ "eslint": "^8.55.0",
55
+ "tsup": "^8.0.1",
56
+ "typescript": "^5.3.0",
57
+ "vitest": "^1.0.0"
58
+ },
59
+ "engines": {
60
+ "node": ">=18.0.0"
61
+ }
62
+ }