This commit is contained in:
2026-04-12 01:06:31 +07:00
commit 10d660cbcb
1066 changed files with 228596 additions and 0 deletions

View File

@@ -0,0 +1,128 @@
# Design-to-Code Pipeline Patterns
Orchestration workflows chaining Stitch design generation with ClaudeKit implementation skills.
## Basic Pipeline
```
Prompt -> Stitch Generate -> Export HTML -> Claude Implements Components
```
### Steps
1. User describes desired UI in natural language
2. Run `stitch-generate.ts` with the prompt
3. Show preview image to user for approval
4. Run `stitch-export.ts --format all` to get HTML + DESIGN.md
5. Hand DESIGN.md to implementation skill
6. Implementation skill reads DESIGN.md and codes components
### Example
```bash
# 1. Generate
npx tsx stitch-generate.ts "E-commerce product page with image gallery, price, reviews, add-to-cart button"
# 2. Export
npx tsx stitch-export.ts <screen-id> --format all --output ./stitch-exports/
# 3. Implementation skill reads ./stitch-exports/DESIGN.md
# 4. Activate ck:frontend-design to implement React components from the spec
```
## Advanced Pipeline (with Variants)
```
Prompt -> Generate -> Variants -> User Picks -> Export -> Implement
```
### Steps
1. Generate base design
2. Generate 2-3 variants with different aspects (color, layout)
3. Show all variants to user
4. User selects preferred variant
5. Export selected variant
6. Hand off to implementation
### Example
```bash
# Generate with variants
npx tsx stitch-generate.ts "SaaS pricing page" --variants 3
# User reviews images, picks variant 2
npx tsx stitch-export.ts <variant-2-screen-id> --format all
```
## DESIGN.md Specification
DESIGN.md is an agent-readable markdown file containing extracted design tokens.
### Structure
```markdown
# Design System
## Colors
- `bg-blue-600` (primary background)
- `text-gray-900` (body text)
- `border-gray-200` (dividers)
## Typography
- `text-2xl font-bold` (headings)
- `text-base font-normal` (body)
## Spacing
- `p-4` (card padding)
- `gap-6` (grid gaps)
## Components
- `<nav>` (top navigation)
- `<section>` (content sections)
- `<form>` (user inputs)
- `<button>` (actions)
## Notes
- Generated by Google Stitch AI
- Tailwind CSS utility classes
```
### How Implementation Skills Consume It
1. Skill checks for `DESIGN.md` in project root or plan directory
2. If found: reads tokens and uses them as constraints for implementation
3. If not found: falls back to text-based design (existing behavior)
4. DESIGN.md takes precedence over verbal design descriptions
## Skill Routing
| Design Need | Skill | What It Does |
|-------------|-------|-------------|
| React/Vue/Svelte components | `ck:frontend-design` | Converts Tailwind HTML to framework components |
| Full page with style guide | `ck:ui-ux-pro-max` | Builds complete layouts with design system |
| Design token extraction | `ck:ui-styling` | Extracts shadcn/Tailwind tokens from DESIGN.md |
## Handoff Protocol
1. `ck:stitch` exports artifacts to `./stitch-exports/` (or plan directory)
2. Copy `DESIGN.md` to project root if implementation skill expects it there
3. Activate target skill with instruction: "Implement from DESIGN.md in project root"
4. Target skill reads DESIGN.md, applies tokens, generates code
5. No modifications needed to existing skills — they read DESIGN.md opportunistically
## Quota-Aware Pipeline
Always check quota before generating:
```bash
# Pre-check
npx tsx stitch-quota.ts check
# If exhausted (exit code 2):
# -> Skip Stitch, use ck:ui-ux-pro-max for text-based design instead
# If available:
npx tsx stitch-generate.ts "<prompt>"
npx tsx stitch-quota.ts increment
```

View File

@@ -0,0 +1,64 @@
# Quota Management
Google Stitch free tier quota tracking and conservation strategies.
## Limits
| Pool | Credits/Day | Reset |
|------|-------------|-------|
| Daily Credits (generate, variants) | 400 | Midnight UTC |
| Redesign Credits (edit_screens) | 15 | Midnight UTC |
Each generation = 1 credit. Each variant = 1 credit. Each edit = 1 redesign credit (separate pool).
## Local Tracking
Stitch SDK has no programmatic quota check endpoint. ClaudeKit tracks locally:
**File:** `~/.claudekit/.stitch-quota.json`
```json
{
"date": "2026-03-23",
"count": 42,
"limit": 400
}
```
**Auto-reset:** When `date` != today (UTC), count resets to 0.
**Override limit:** `export STITCH_QUOTA_LIMIT="300"` (if Google increases limits).
## Warning Thresholds
| Remaining | Action |
|-----------|--------|
| > 20% | Normal operation |
| < 20% | `[!] Low quota` warning printed |
| 0 | `[X] Exhausted` exit code 2, suggest fallback |
## Conservation Tips
1. **Use variants instead of regenerating** 3 variants = 3 credits vs regenerating 3 times = 3 credits, but variants are more purposeful
2. **Use `screen.edit()` to refine** Editing costs 1 credit but preserves context
3. **Export early** Don't regenerate just to see the design again; export HTML/image once
4. **Batch planning** Plan all designs for the day, generate in one session
5. **Review prompts** Better prompts = fewer regenerations
## Fallback Workflow
When quota is exhausted:
1. `stitch-quota.ts check` returns exit code 2
2. Skill prints: "Daily quota exhausted. Use ck:ui-ux-pro-max as fallback."
3. Activate `ck:ui-ux-pro-max` with the same design prompt
4. `ui-ux-pro-max` generates text-based design spec (no external API needed)
5. Proceed with implementation using text-based spec
## Drift Warning
Local tracking can drift if user generates designs outside ClaudeKit (via Stitch web UI or other tools). If you hit `RATE_LIMITED` error despite local tracker showing credits available:
1. Run `npx tsx stitch-quota.ts reset`
2. Set count to match actual usage (or leave at 0 if unknown)
3. Stitch API itself enforces the real limit local tracker is advisory only

View File

@@ -0,0 +1,95 @@
# Stitch MCP Server Setup
Three options for connecting Google Stitch as an MCP server with Claude Code.
## Option A: API Key (Recommended for Most Users)
Simplest setup. No Google Cloud dependency.
### 1. Get API Key
1. Sign in at https://stitch.withgoogle.com
2. Go to Settings -> API Keys
3. Click "Generate New Key"
4. Copy `sk_...` key
### 2. Add to `.opencode/.mcp.json`
```json
{
"mcpServers": {
"stitch": {
"command": "npx",
"args": ["@_davideast/stitch-mcp", "proxy"],
"env": {
"STITCH_API_KEY": "sk_your_key_here"
}
}
}
}
```
### 3. Verify
Restart Claude Code. You should see Stitch tools available:
- `create_project` — Create new design project
- `generate_screen` — Generate UI from prompt
- `export_html` — Export as HTML/Tailwind
- `export_image` — Export screenshot
## Option B: Google Cloud (For GCP Users)
Uses gcloud credentials. Zero API key management.
### 1. Setup gcloud
```bash
gcloud auth login
gcloud config set project YOUR_PROJECT_ID
gcloud beta services mcp enable stitch.googleapis.com
```
### 2. Add to `.opencode/.mcp.json`
```json
{
"mcpServers": {
"stitch": {
"command": "npx",
"args": ["-y", "stitch-mcp"],
"env": {
"GOOGLE_CLOUD_PROJECT": "your-gcp-project-id"
}
}
}
}
```
## Option C: Auto-Installer (Interactive)
Guided wizard, auto-detects environment.
```bash
npx stitch-mcp-auto
# Opens browser at http://localhost:8086
# Follow wizard to configure
```
## Troubleshooting
| Symptom | Fix |
|---------|-----|
| "AUTH_FAILED" on startup | Verify API key or re-run `gcloud auth login` |
| Tools not appearing | Restart Claude Code after config change |
| Timeout on generation | Stitch is processing; wait 10-30s for complex designs |
| "RATE_LIMITED" errors | Daily quota exceeded; wait until midnight UTC |
## MCP Config Location
| OS | Path |
|----|------|
| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| Windows | `%AppData%\Claude\claude_desktop_config.json` |
| Linux | `~/.config/Claude/claude_desktop_config.json` |
For Claude Code CLI: use `.opencode/.mcp.json` in project root (preferred for ClaudeKit).

View File

@@ -0,0 +1,136 @@
# Stitch SDK API Reference
Condensed reference for `@google/stitch-sdk`. Agent-optimized — covers common operations only.
## Installation
```bash
npm install @google/stitch-sdk
# Optional: Vercel AI SDK integration
npm install @google/stitch-sdk ai
```
## Authentication
```bash
export STITCH_API_KEY="sk_..." # From https://stitch.withgoogle.com/settings/api
```
SDK auto-reads `STITCH_API_KEY` from environment. No explicit config needed.
## Core API
### Stitch (root singleton)
```typescript
import { stitch } from "@google/stitch-sdk";
const projects = await stitch.projects(); // List all projects
const project = stitch.project("my-id"); // Get project handle (sync)
```
### Project
```typescript
const project = stitch.project("project-123"); // sync — returns handle
// Generate screen from prompt (positional params, uppercase device types)
const screen = await project.generate(
"Login page with email/password",
"MOBILE" // optional: "MOBILE" | "DESKTOP" | "TABLET" | "AGNOSTIC"
);
const screens = await project.screens(); // List all screens
const screen = await project.getScreen(screenId); // Get specific screen
```
### Screen
```typescript
// Export
const htmlUrl = await screen.getHtml(); // Returns download URL (HTML + Tailwind)
const imageUrl = await screen.getImage(); // Returns download URL (PNG screenshot)
// Edit/refine (positional: prompt, deviceType?, modelId?)
const edited = await screen.edit("Make colors darker, add search bar");
// Generate variants (positional: prompt, variantOptions, deviceType?, modelId?)
const variants = await screen.variants("Different color schemes", {
variantCount: 3, // 1-5 variants
creativeRange: "medium", // "low" | "medium" | "high"
aspects: ["COLOR_SCHEME"] // "COLOR_SCHEME" | "LAYOUT" | etc.
});
```
### StitchToolClient (low-level MCP access)
```typescript
import { StitchToolClient } from "@google/stitch-sdk";
const client = new StitchToolClient({ apiKey: "sk_..." });
const tools = await client.listTools();
const result = await client.callTool("create_project", { title: "My App" });
```
### Vercel AI SDK Integration
```typescript
import { stitchTools } from "@google/stitch-sdk/ai";
import { generateText } from "ai";
const { text } = await generateText({
model: yourModel,
tools: stitchTools(),
prompt: "Create a modern dashboard"
});
```
## Type Definitions
```typescript
type DeviceType = "DEVICE_TYPE_UNSPECIFIED" | "MOBILE" | "DESKTOP" | "TABLET" | "AGNOSTIC";
type ModelId = "MODEL_ID_UNSPECIFIED" | "GEMINI_3_PRO" | "GEMINI_3_FLASH";
interface Stitch {
projects(): Promise<Project[]>;
createProject(title?: string): Promise<Project>;
project(id: string): Project; // sync — returns handle, no API call
}
interface Project {
id: string;
generate(prompt: string, deviceType?: DeviceType, modelId?: ModelId): Promise<Screen>;
screens(): Promise<Screen[]>;
getScreen(screenId: string): Promise<Screen>;
}
interface Screen {
id: string;
getHtml(): Promise<string>; // Download URL
getImage(): Promise<string>; // Download URL
edit(prompt: string, deviceType?: DeviceType, modelId?: ModelId): Promise<Screen>;
variants(prompt: string, variantOptions: any, deviceType?: DeviceType, modelId?: ModelId): Promise<Screen[]>;
}
class StitchError extends Error {
code: "AUTH_FAILED" | "NOT_FOUND" | "RATE_LIMITED" | string;
}
```
## Error Handling
| Code | Meaning | Action |
|------|---------|--------|
| `AUTH_FAILED` | Bad/missing API key | Check `STITCH_API_KEY` env var |
| `NOT_FOUND` | Screen/project doesn't exist | Verify ID |
| `RATE_LIMITED` | Daily quota exceeded | Wait until midnight UTC or use fallback |
```typescript
try {
const screen = await project.generate(prompt);
} catch (error) {
if (error.code === "RATE_LIMITED") {
console.error("Quota exceeded — use ck:ui-ux-pro-max fallback");
}
}
```