# install-aisdkagents-pattern > Use this skill when the user wants to install AI SDK patterns from aisdkagents.com into the playground. - Author: CrazySwami - Repository: mirror-factory/hustle-together-ai - Version: 20260126113327 - Stars: 0 - Forks: 0 - Last Updated: 2026-02-06 - Source: https://github.com/mirror-factory/hustle-together-ai - Web: https://mule.run/skillshub/@@mirror-factory/hustle-together-ai~install-aisdkagents-pattern:20260126113327 --- # Install aisdkagents.com Pattern Skill Use this skill when the user wants to install AI SDK patterns from aisdkagents.com into the playground. ## Purpose This skill covers two installation approaches: ### 🎨 **Pattern Preview System** (Recommended - NEW!) A visual UI for browsing, previewing, and installing patterns: 1. Browse available patterns at `/patterns` 2. Preview file tree and code before installing 3. One-click installation with progress tracking 4. Automatic staging and installation tracking ### 🛠️ **Manual Installation** (Advanced) For complex patterns requiring custom adaptation: 1. Fetching patterns from aisdkagents.com via proxy registry 2. Extracting files to staging directory 3. Reviewing and adapting code to our playground structure 4. Testing integration with Layers gateway 5. Adding to our registry ## When to Use - User provides an aisdkagents.com CLI command - User says "install X pattern from aisdkagents.com" - User asks to add patterns from their registry - User wants to preview patterns before installing ## Prerequisites ✅ **Proxy registry is set up** at `/app/api/registry/proxy/[...slug]/route.ts` ✅ **AISDKAGENTS_TOKEN** is in `.env.local` ✅ **Extraction script** exists at `scripts/extract-pattern.mjs` ✅ **Staging directory** exists at `.patterns-staging/` ✅ **Pattern Preview System** is available at `/patterns` (new!) --- ## 🎨 Pattern Preview System Workflow (Recommended) **Use this for:** Quick pattern installation with visual preview and verification. ### Step 1: Navigate to Pattern Library Direct user to: `http://localhost:3000/patterns` (or use the "📚 Pattern Library" link in the header) ### Step 2: Browse Available Patterns The Pattern Library shows: - All available patterns from aisdkagents.com - Grouped by category (Tools, Structured Output, Agents, etc.) - Metadata: complexity, setup time, features - Installation status (installed/not installed) ### Step 3: Preview Pattern Click "Preview" on any pattern to see: - **File Tree**: Interactive file explorer showing all files - **Code Viewer**: Syntax-highlighted code for each file - **Metadata**: Dependencies, type, file count - **Installation Guide**: Instructions and notes ### Step 4: Review Files **CRITICAL**: Before clicking "Install Pattern", review ALL files: - [ ] Check file tree for all components (not just main demo) - [ ] Review each file's code for: - Import paths - Provider usage - Custom UI components - Layers compatibility - [ ] Note any missing dependencies - [ ] Document files that may need manual adaptation ### Step 5: Install Pattern Click "Install Pattern" button: 1. **Downloading**: Fetches pattern from proxy 2. **Extracting**: Saves to `.patterns-staging/PATTERN-NAME/` 3. **Adapting**: Prepares files for playground 4. **Tracking**: Updates installation record **Monitor the progress dialog** for any errors or warnings. ### Step 6: Post-Installation Verification After installation completes: #### 6.1 Review Staging Directory ```bash ls -la .patterns-staging/PATTERN-NAME/ ``` Check for: - [ ] `EXTRACTION_SUMMARY.md` - Lists all extracted files - [ ] All expected component files present - [ ] No binary or sensitive files #### 6.2 Adapt Files (if needed) **Note**: The UI installs files to staging only. You still need to manually adapt them. For each file in staging: 1. Read the file and understand its purpose 2. Adapt imports: `@/components/...` instead of `../components/...` 3. Adapt providers: Use `getProvider(model, useLayers)` instead of direct imports 4. Adapt UI: Use our shared components (DemoContainer, ModelSelector, etc.) 5. Copy adapted file to appropriate location **File mapping guide:** - `app/api/X/route.ts` → `app/api/playground/CATEGORY/PATTERN/route.ts` - `components/X-demo.tsx` → `components/playground/patterns/CATEGORY/PATTERN-demo.tsx` - `tools/X.ts` → `lib/tools/X.ts` - `lib/X.ts` → `lib/X.ts` #### 6.3 Continue with Manual Workflow After adapting files, continue with: - Step 9: Add to pattern config - Step 10: Add test configuration - Step 11-20: Testing and verification ### Pattern Preview System Benefits ✅ **Visual verification** before installation ✅ **File tree preview** shows all components ✅ **Code viewer** with syntax highlighting ✅ **Installation tracking** prevents duplicates ✅ **Progress monitoring** with detailed logs ✅ **Update detection** (file count comparison) ### When to Use Manual Workflow Instead Use the manual workflow (steps below) when: - Pattern requires complex custom adaptation - Need to modify files before installation - Pattern has conflicting dependencies - Want more granular control over the process --- --- ## 🛠️ Manual Installation Workflow (Advanced) **Use this for:** Complex patterns requiring custom adaptation or when you need granular control over the installation process. ## ⚠️ CRITICAL WARNINGS - Read Before Starting ### 🔴 CodeBlock Errors Will Recur If Steps Are Skipped **THE PROBLEM**: The `code.split() is not a function` error is a SYSTEMIC issue that WILL happen again with every new pattern if you skip steps. **ROOT CAUSES**: 1. Pattern code not generated → `getPatternCode()` returns `undefined` 2. CodeBlock receives object/undefined instead of string 3. `JSON.stringify(undefined)` returns `undefined`, not a string **PREVENTION CHECKLIST** (MANDATORY for every pattern): - [ ] **Step 14**: Run `pnpm generate:code` IMMEDIATELY after creating API route - [ ] **Step 18**: Verify pattern added to `scripts/generate-pattern-code.mjs` PATTERN_ROUTES - [ ] **Always**: Use `patternCode?.fullRoute` not `patternCode` in CodeBlock - [ ] **Always**: Use `JSON.stringify(value || {})` not `JSON.stringify(value)` - [ ] **Step 15**: Test code tabs in browser BEFORE marking complete **IF YOU SKIP THESE**: The pattern will compile but crash in the browser with confusing errors. ### 🔴 Incomplete UI Extraction **THE PROBLEM**: Original aisdkagents.com patterns may have multiple UI components (gauges, displays, visualizations) that need to be extracted. Missing these means the pattern works functionally but lacks the visual polish of the original. **PREVENTION**: - [ ] **Step 3**: Count ALL component files in staging directory (not just the main one) - [ ] **Step 4**: Review EACH component's purpose before adapting - [ ] **Step 6**: Adapt ALL components, not just the main demo - [ ] **Step 15**: Compare browser UI side-by-side with original pattern demo/screenshots - [ ] **Document**: List which UI components were included vs. excluded (and why) **EXAMPLE**: A temperature converter might have: - `dynamic-tool-demo.tsx` - Main demo component ✅ - `temperature-gauge.tsx` - Visual temperature display ❓ - `conversion-history.tsx` - History of conversions ❓ - `unit-selector.tsx` - Custom unit picker component ❓ Don't assume the main component is the only one! **Check the staging directory for ALL `.tsx` files.** ### 🔴 Missing Pattern Code = Silent Failure **THE PROBLEM**: If `pnpm generate:code` isn't run, code tabs show "Loading..." but NO errors appear in terminal. The pattern seems to work until someone clicks the "API Route" tab. **DETECTION**: ```bash # After Step 14, ALWAYS run this verification: grep "CATEGORY/PATTERN" lib/patterns/generated-code.ts # If output is empty → pattern NOT generated → STOP and fix ``` **FIX**: 1. Add to `scripts/generate-pattern-code.mjs` PATTERN_ROUTES 2. Run `pnpm generate:code` again 3. Verify entry exists 4. Test code tabs in browser ## Installation Workflow ### Step 0: Create Todo List **CRITICAL**: Before starting, create a comprehensive todo list using TodoWrite to track all installation steps. ``` TodoWrite: 1. Extract pattern name from CLI command 2. Fetch pattern via proxy 3. Review extracted files 4. Read and understand the code 5. Map to our structure 6. Create adapted API route 7. Create adapted component 8. Create adapted lib/tools files 9. Add to pattern config 10. Add test configuration 11. Test API route 12. Test in playground UI 13. Test with Layers 14. Regenerate pattern code (pnpm generate:code) 15. Update generator script if needed 16. Frontend UI verification 17. Automated testing setup (optional) 18. Layers compatibility verification 19. Update CLI registry (pnpm build:registry) 20. Clean up staging directory ``` **Mark each task as completed as you go** to maintain accurate progress tracking. ### Step 1: Extract Pattern Name From user's CLI command: ```bash npx shadcn add 'https://www.aisdkagents.com/pro-registry/PATTERN-NAME?token=XXX' ``` Extract: `PATTERN-NAME` ### Step 2: Fetch via Proxy ```bash node scripts/extract-pattern.mjs PATTERN-NAME ``` **What this does:** - Fetches from our proxy (automatically uses token from .env.local) - Proxy strips leading slashes from unsafe paths - Saves all files to `.patterns-staging/PATTERN-NAME/` - Creates `_metadata.json` with pattern info **Expected output:** ``` ✅ Registry fetched 📂 Files: 7 🔧 Paths fixed: 7 ✅ app/page.tsx ✅ app/layout.tsx ✅ app/api/dynamic-tool/route.ts ... 🎉 Pattern extracted to: .patterns-staging/PATTERN-NAME ``` ### Step 3: Review Extracted Files ```bash ls -laR .patterns-staging/PATTERN-NAME/ # Count component files specifically find .patterns-staging/PATTERN-NAME/ -name "*.tsx" -type f ``` **Document ALL files extracted** - This prevents missing UI components later: ``` EXTRACTED FILES INVENTORY: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 📄 app/page.tsx → DELETE (standalone page) 📄 app/layout.tsx → DELETE (global layout exists) 📄 app/api/dynamic-tool/route.ts → ADAPT (API route) 📄 components/dynamic-tool-demo.tsx → ADAPT (main component) ✅ 📄 components/temperature-gauge.tsx → ADAPT (visual display) ⚠️ 📄 components/unit-selector.tsx → ADAPT (UI widget) ⚠️ ↑ DON'T MISS THESE! Multiple components = richer UI 📄 lib/dynamic-tool-executor.ts → ADAPT (business logic) 📄 lib/conversion-utils.ts → ADAPT (utilities) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Total: X files | Components: Y | API routes: Z ``` **Critical Check**: - [ ] Count matches extraction script output (e.g., "Files: 7" = 7 files found) - [ ] ALL `.tsx` components identified and categorized - [ ] Each component's purpose understood (not just copied blindly) - [ ] Decision made on each: ADAPT, DELETE, or SKIP (with reason) **Common mistake**: Only adapting the main `*-demo.tsx` file and missing supporting UI components like gauges, selectors, displays, or configuration panels. --- ## 🚨 CASE STUDY: Dynamic Tool Pattern - 40% of UI Components Missed **What Happened**: During the initial dynamic-tool installation, we extracted and adapted **3 out of 5** files, missing **2 substantial UI components**: **Files We Adapted** (60%): 1. ✅ `app/api/dynamic-tool/route.ts` (2,060 bytes) → API route 2. ✅ `components/dynamic-tool-demo.tsx` (11,957 bytes) → Main demo component 3. ✅ `tools/dynamic-tool-executor.ts` (7,117 bytes) → Business logic **Files We MISSED** (40%): 4. ❌ `components/converter-config-form.tsx` (7,158 bytes!) - React Hook Form + Zod validation - Dynamic schema preview (shows what tool schema will be generated) - Educational UI explaining the "dynamic tool" concept - Rich descriptions for each conversion type 5. ❌ `tools/dynamic-tool-ui.tsx` (6,112 bytes!) - Visual conversion card ("FROM 100 fahrenheit → TO 37.78 celsius") - Professional, polished result presentation - Copy JSON button, formatted numbers **Impact**: - ✅ Pattern worked functionally (API calls succeeded) - ❌ Pattern looked unpolished (raw JSON instead of beautiful cards) - ❌ Missing educational value (no schema preview) - ❌ Missing visual appeal (no conversion card display) - ⚠️ User thought pattern was incomplete/broken **Root Cause**: We cherry-picked files during extraction instead of extracting ALL files first for comprehensive review. **Lesson Learned**: Large component files (7KB+) are NOT optional polish - they're core parts of the pattern's value proposition. --- ### Step 4: Read and Understand the Code Read key files to understand the pattern: ```bash # Read API route cat .patterns-staging/PATTERN-NAME/app/api/*/route.ts # Read main component cat .patterns-staging/PATTERN-NAME/components/*.tsx # Read tools/lib files cat .patterns-staging/PATTERN-NAME/tools/*.ts # or cat .patterns-staging/PATTERN-NAME/lib/*.ts ``` **Look for:** - What AI SDK features are used (generateText, streamText, tools, Output.object, etc.) - What model providers they import - What dependencies are needed - What the pattern demonstrates ### Step 5: Map to Our Structure Plan file placement: ``` THEIR STRUCTURE: OUR STRUCTURE: ───────────────────────────────────────────────────────────────────────── app/page.tsx → DELETE (not needed) app/layout.tsx → DELETE (not needed) app/api/PATTERN/route.ts → app/api/playground/CATEGORY/PATTERN/route.ts components/PATTERN-demo.tsx → components/playground/patterns/CATEGORY/PATTERN-demo.tsx components/PATTERN-form.tsx → components/playground/patterns/CATEGORY/PATTERN-form.tsx tools/PATTERN-executor.ts → lib/tools/PATTERN-executor.ts lib/PATTERN-helper.ts → lib/CATEGORY/PATTERN-helper.ts ``` **Determine category:** - Tools/tool-calling → `tools` - Agents/orchestration → `agents` - Structured output → `structured` - Multi-modal → `multimodal` - Human-in-loop → `human-loop` ### Step 6: Create Adapted Files For each file, create the adapted version: #### A. API Route Adaptation ```typescript // Original (their code): import { openai } from '@ai-sdk/openai'; const model = openai('gpt-4o-mini'); // Adapted (our code): import { getProvider } from '@/lib/models/get-provider'; const model = getProvider(modelId, useLayers); ``` Key adaptations: - Replace direct provider imports with `getProvider()` - Add `useLayers` parameter to POST handler - Add Layers-compatible error handling - Ensure tool calls use `tc.input` (not `tc.args`) - Add comprehensive logging #### B. Component Adaptation ```typescript // Add our shared components: import { DemoContainer } from '@/components/playground/shared/demo-container'; import { ModelSelector } from '@/components/playground/shared/model-selector'; import { Explainer } from '@/components/playground/shared/explainer'; import { CodeBlock } from '@/components/playground/shared/code-block'; import { ModelBadge } from '@/components/playground/shared/model-badge'; import { useLayersContext } from '@/lib/contexts/layers-context'; // Use our patterns: const { useLayers } = useLayersContext(); {/* Rest of component */} ``` #### C. Lib/Tools Adaptation - Update imports to use `@/` aliases - Ensure type safety with Zod schemas - Add error handling - Make Layers-compatible ### Step 7: Create Files in Playground ```bash # Create directories mkdir -p app/api/playground/CATEGORY/PATTERN mkdir -p components/playground/patterns/CATEGORY mkdir -p lib/CATEGORY # if needed # Copy and adapt files # (use adapted code from Step 6) ``` ### Step 8: Add to Pattern Config Edit `lib/patterns/config.ts`: ```typescript export const PATTERN_CATEGORIES: PatternCategory[] = [ // ... existing categories { id: 'CATEGORY', label: 'Category Label', icon: IconName, description: 'Description', patterns: [ // ... existing patterns { id: 'PATTERN-NAME', label: 'Pattern Display Name', capability: 'tools', // or 'json', 'vision', etc. testId: 'PATTERN-NAME' } ] } ]; ``` ### Step 9: Add Test Configuration Edit `lib/testing/pattern-routes.ts`: ```typescript export const PATTERN_TEST_CONFIG = { // ... existing patterns 'PATTERN-NAME': { route: '/api/playground/CATEGORY/PATTERN-NAME', requiredCapabilities: ['tools'], // or ['json'], ['vision'], etc. testPayload: { prompt: 'Test prompt for this pattern', model: 'openai/gpt-4o-mini' } } }; ``` ### Step 10: Test API Route ```bash curl -X POST http://localhost:3000/api/playground/CATEGORY/PATTERN-NAME \ -H "Content-Type: application/json" \ -d '{ "prompt": "Test input", "model": "openai/gpt-4o-mini" }' ``` **Verify:** - ✅ Response received (not 500 error) - ✅ Expected output format - ✅ Tool calls work (if applicable) - ✅ No errors in console ### Step 11: Test in Playground UI ```bash pnpm dev open http://localhost:3000/playground ``` 1. Navigate to Category > Pattern 2. Enter test input 3. Execute 4. Verify results display correctly ### Step 12: Test with Layers Ensure `AI_GATEWAY_API_KEY` is set, then retest: ```bash # API test (Layers is default) curl -X POST http://localhost:3000/api/playground/CATEGORY/PATTERN-NAME \ -H "Content-Type: application/json" \ -d '{"prompt": "Test", "model": "openai/gpt-4o-mini"}' ``` **Verify:** - ✅ Tool arguments populated (uses `tc.input`) - ✅ Token counts accurate - ✅ No provider metadata stripped - ✅ Sources/citations preserved (if applicable) ### Step 13: Regenerate Registry ```bash pnpm build:registry ``` This creates: - `registry/CATEGORY-PATTERN-NAME.json` - Includes Layers compatibility notes - Includes test configuration - Can be installed via CLI from our registry ### Step 14: Regenerate Pattern Code **CRITICAL**: Generate pattern code for CodeBlock components to display. ```bash pnpm generate:code ``` **What this does:** - Reads all API route files from `scripts/generate-pattern-code.mjs` configuration - Generates `lib/patterns/generated-code.ts` with route code as strings - Enables code tabs in pattern UI components **Verification:** ```bash # Check that pattern was added grep -A 3 '"CATEGORY/PATTERN-NAME"' lib/patterns/generated-code.ts ``` **If pattern NOT found:** 1. Check that pattern is in `scripts/generate-pattern-code.mjs` PATTERN_ROUTES 2. Add entry if missing: ```javascript 'CATEGORY/PATTERN-NAME': { routePath: 'app/api/playground/CATEGORY/PATTERN-NAME/route.ts', extract: [], // or ['toolDefinition'], ['schema'], etc. }, ``` 3. Run `pnpm generate:code` again **Common CodeBlock errors fixed by this step:** - "Cannot read properties of undefined (reading 'split')" - Missing pattern code - "Loading..." in code tabs - Pattern not in generated code registry ### Step 15: Frontend UI Verification **Manual browser testing checklist** (cannot be automated by Claude): ```bash # Ensure dev server is running pnpm dev # Open browser at http://localhost:3000 ``` **Visual Inspection:** 1. Navigate to Category > Pattern Name 2. ✅ Page loads without errors 3. ✅ Layout renders correctly 4. ✅ All components visible (Explainer, ModelSelector, DemoContainer, CodeBlock tabs) 5. ✅ No visual glitches or broken styling **Interaction Testing:** 6. ✅ Select different models from ModelSelector 7. ✅ Enter test input in form fields 8. ✅ Click execute button 9. ✅ Results display correctly 10. ✅ Tool calls shown (if applicable) 11. ✅ Error states work (try invalid input) **Code Tabs Testing:** 12. ✅ Click "API Route" tab - shows actual route code (not "Loading...") 13. ✅ Click other code tabs - all display correctly 14. ✅ Copy-to-clipboard works on code blocks **Browser Console:** 15. ✅ Open DevTools console (F12) 16. ✅ No errors or warnings 17. ✅ Network tab shows successful API calls **Responsive Design:** 18. ✅ Resize browser window 19. ✅ Test mobile viewport 20. ✅ Components adapt correctly **Comparison with Original** (CRITICAL - Don't skip!): 21. ✅ Open original pattern demo (if available) - aisdkagents.com pattern page - Demo video or screenshots - Example from their documentation 22. ✅ Side-by-side comparison: - Do we have ALL the same UI elements? - Are visual components (gauges, charts, displays) present? - Are interactive widgets (sliders, pickers, toggles) present? - Is the overall UX similar? 23. ✅ Document missing components: ``` MISSING UI COMPONENTS: ❌ Temperature gauge visual display ❌ Conversion history panel ✅ Basic conversion form (present) ✅ Results display (present) DECISION: Skip gauge (not essential) | Add history later ``` 24. ✅ If critical UI missing: - Go back to staging (if not cleaned) - Or re-extract pattern to check for missed files - Or document as "simplified version" **Document any issues found** and fix before proceeding. ### Step 16: Automated Testing Setup (Optional) **Note**: This project does not currently have frontend testing infrastructure (Vitest, Playwright, Storybook). This step documents how to add tests when infrastructure is available. **Component Tests (Vitest):** ```typescript // tests/components/patterns/CATEGORY/PATTERN-demo.test.tsx import { render, screen, fireEvent } from '@testing-library/react'; import { PatternDemo } from '@/components/playground/patterns/CATEGORY/PATTERN-demo'; describe('PatternDemo', () => { it('renders without crashing', () => { render(); expect(screen.getByText('Pattern Title')).toBeInTheDocument(); }); it('displays code tabs', () => { render(); expect(screen.getByText('API Route')).toBeInTheDocument(); }); }); ``` **E2E Tests (Playwright):** ```typescript // e2e/patterns/CATEGORY/PATTERN.spec.ts import { test, expect } from '@playwright/test'; test('pattern executes correctly', async ({ page }) => { await page.goto('http://localhost:3000'); await page.click('text=Category Name'); await page.click('text=Pattern Name'); await page.fill('input[placeholder*="test"]', 'test input'); await page.click('button:has-text("Execute")'); await expect(page.locator('text=/result/i')).toBeVisible(); }); ``` **Skip this step** if tests are not required for this pattern. ### Step 17: Layers Compatibility Verification **Comprehensive Layers testing** to ensure pattern works with AI Gateway's Layers feature. **A. Verify Environment:** ```bash # Check AI_GATEWAY_API_KEY is set grep AI_GATEWAY_API_KEY .env.local ``` **B. Test with Layers (API):** ```bash curl -X POST http://localhost:3000/api/playground/CATEGORY/PATTERN \ -H "Content-Type: application/json" \ -d '{ "prompt": "test input", "model": "openai/gpt-4o-mini", "useLayers": true }' ``` **C. Verify Layers Response:** - ✅ Tool arguments populated correctly (if using tools) - ✅ Token counts accurate and non-zero - ✅ Usage data included in response - ✅ No errors in console logs - ✅ Provider metadata preserved (if applicable) **D. Test with Layers (UI):** 1. Open pattern in browser 2. Toggle "Use Layers Gateway" checkbox (if visible) 3. Execute same test 4. Verify results identical to non-Layers test **E. Common Layers Issues:** **Issue**: Tool arguments are empty or undefined **Fix**: Ensure API route uses `tc.input ?? tc.args` not just `tc.args` ```typescript // ✅ Layers-compatible: const toolArgs = tc.input ?? tc.args; // ❌ Might fail with Layers: const toolArgs = tc.args; ``` **Issue**: Token counts are 0 or missing **Fix**: Verify `AI_GATEWAY_API_KEY` is set and valid **Issue**: Provider metadata stripped **Fix**: Check that response includes all provider-specific fields **F. Document Layers Compatibility:** Add to `lib/testing/pattern-routes.ts`: ```typescript 'PATTERN-NAME': { // ... existing config layersCompatible: true, // or false if issues found layersNotes: 'Fully compatible, no known issues', // or document issues } ``` ### Step 18: Update Generator Script (If Needed) **Only required if Step 14 failed** to find pattern in generated code. Edit `scripts/generate-pattern-code.mjs`: ```javascript const PATTERN_ROUTES = { // ... existing patterns 'CATEGORY/PATTERN-NAME': { routePath: 'app/api/playground/CATEGORY/PATTERN-NAME/route.ts', extract: [], // or ['toolDefinition'], ['schema'], ['providerOptions'], ['agentConfig'], ['cacheOptions'], ['mcpTools'] }, }; ``` **Extract options guide:** - `toolDefinition` - Include if pattern uses `tool()` definitions - `schema` - Include if pattern uses Zod schemas with `Output.object()` - `providerOptions` - Include for reasoning/thinking patterns - `agentConfig` - Include for multi-agent orchestration - `cacheOptions` - Include for prompt caching patterns - `mcpTools` - Include for MCP integration patterns - `[]` - Empty array for simple patterns with just the route After updating, run: ```bash pnpm generate:code ``` ### Step 19: Clean Up Staging ```bash rm -rf .patterns-staging/PATTERN-NAME ``` Or keep for reference/comparison. ## Example: Dynamic Tool Pattern User provides: ``` npx shadcn add 'https://www.aisdkagents.com/pro-registry/tool-api-dynamic-tool?token=XXX' ``` Steps: ```bash # 1. Extract node scripts/extract-pattern.mjs tool-api-dynamic-tool # 2. Review ls -la .patterns-staging/tool-api-dynamic-tool/ cat .patterns-staging/tool-api-dynamic-tool/app/api/dynamic-tool/route.ts # 3. Determine: This is a "tools" pattern # 4. Create adapted files # app/api/playground/tools/dynamic-tool/route.ts # components/playground/patterns/tools/dynamic-tool-demo.tsx # lib/tools/dynamic-tool-executor.ts # 5. Add to config (tools category) # Edit lib/patterns/config.ts # 6. Add test config # Edit lib/testing/pattern-routes.ts # 7. Test curl -X POST http://localhost:3000/api/playground/tools/dynamic-tool \ -H "Content-Type: application/json" \ -d '{"prompt": "Convert 100F to Celsius", "model": "openai/gpt-4o-mini"}' # 8. Test UI pnpm dev # Navigate to Tools > Dynamic Tool # 9. Regenerate registry pnpm build:registry # 10. Clean up rm -rf .patterns-staging/tool-api-dynamic-tool ``` ## Common Adaptations ### Provider Changes ```typescript // ❌ Their code: import { openai } from '@ai-sdk/openai'; import { anthropic } from '@ai-sdk/anthropic'; const model = openai('gpt-4o'); // ✅ Our code: import { getProvider } from '@/lib/models/get-provider'; const model = getProvider(modelId, useLayers); ``` ### Tool Call Arguments (Layers Fix) ```typescript // ❌ Might not work with Layers: const toolArgs = tc.args; // ✅ Layers-compatible: const toolArgs = tc.input ?? tc.args; ``` ### Import Paths ```typescript // ❌ Their imports: import { Button } from '../components/ui/button'; import { helper } from './lib/helper'; // ✅ Our imports: import { Button } from '@/components/ui/button'; import { helper } from '@/lib/helper'; ``` ### Component Structure ```typescript // ✅ Always wrap in DemoContainer: export function PatternDemo() { const { useLayers } = useLayersContext(); return (
{/* Pattern UI */} {/* Code examples */}
); } ``` ## Common Errors (New Patterns) ### Error 1: CodeBlock "code.split() is not a function" **Full Error:** ``` TypeError: Cannot read properties of undefined (reading 'split') at CodeBlock (components/playground/shared/code-block.tsx:28:22) ``` **Root Causes:** 1. **Pattern code not generated** - `getPatternCode('CATEGORY/PATTERN')` returns `undefined` 2. **CodeBlock receives object instead of string** - Using `patternCode` instead of `patternCode?.fullRoute` 3. **JSON.stringify returns undefined** - Passing `undefined` to JSON.stringify **Fixes:** **Fix 1**: Regenerate pattern code ```bash pnpm generate:code # Check pattern was added: grep "CATEGORY/PATTERN" lib/patterns/generated-code.ts ``` **Fix 2**: Use safe property access for pattern code ```typescript // ❌ WRONG: // ✅ CORRECT: ``` **Fix 3**: Ensure JSON.stringify always has a value ```typescript // ❌ WRONG (undefined fails): // ✅ CORRECT (fallback to empty object): ``` **Prevention:** - Always run `pnpm generate:code` after creating new API routes - Always use optional chaining (`?.`) when accessing pattern code properties - Always provide fallback values for JSON.stringify inputs ### Error 2: "Loading..." in Code Tabs **Symptom:** Code tabs show "Loading..." text instead of actual code **Root Cause:** Pattern entry missing from `lib/patterns/generated-code.ts` **Fix:** 1. Check if pattern is in generator script: ```bash grep "CATEGORY/PATTERN" scripts/generate-pattern-code.mjs ``` 2. If missing, add to PATTERN_ROUTES configuration: ```javascript 'CATEGORY/PATTERN': { routePath: 'app/api/playground/CATEGORY/PATTERN/route.ts', extract: [], }, ``` 3. Regenerate: ```bash pnpm generate:code ``` 4. Verify: ```bash grep "CATEGORY/PATTERN" lib/patterns/generated-code.ts ``` **Prevention:** - Add pattern to generator script during Step 6 (create files) - Run `pnpm generate:code` immediately after creating API route - Verify code tabs display correctly during Step 15 (frontend testing) ### Error 3: Pattern Not in Model Tester **Symptom:** Pattern doesn't appear in Model Tester capability tests **Root Cause:** Missing test configuration in `lib/testing/pattern-routes.ts` **Fix:** ```typescript // Add to lib/testing/pattern-routes.ts: export const PATTERN_TEST_CONFIG = { 'PATTERN-NAME': { route: '/api/playground/CATEGORY/PATTERN-NAME', method: 'POST', buildPayload: (modelId: string, options: Record = {}) => ({ prompt: 'test input', model: modelId, ...options, }), validateResponse: (data: any) => ({ success: !!data.text && !data.error, response: data, }), }, }; ``` **Prevention:** - Add test config during Step 9 - Test immediately in Model Tester UI - Verify pattern appears under correct capability filter ### Error 4: Pattern Not in CLI Registry **Symptom:** `npx shadcn add` cannot find pattern **Root Cause:** Registry not regenerated after adding pattern **Fix:** ```bash pnpm build:registry # Verify file created: ls -la registry/CATEGORY-PATTERN-NAME.json ``` **Prevention:** - Always run `pnpm build:registry` after pattern integration (Step 13) - Verify registry file created before marking pattern complete - Test CLI installation to confirm registry works ### Error 5: Tool Calls Empty with Layers **Symptom:** Tool arguments are `{}` or `undefined` when using Layers **Root Cause:** Using `tc.args` instead of `tc.input` (Layers compatibility issue) **Fix:** ```typescript // ❌ WRONG (fails with Layers): const toolArgs = tc.args; // ✅ CORRECT (Layers-compatible): const toolArgs = tc.input ?? tc.args; ``` **Applies to:** - Tool result formatting in API routes - Component display of tool calls - Any code that accesses tool arguments **Prevention:** - Always use `tc.input ?? tc.args` when accessing tool arguments - Test pattern with both `useLayers: true` and `useLayers: false` - Verify tool arguments populate correctly in both modes ### Error 6: Imports Not Resolving **Symptom:** TypeScript errors: "Cannot find module '@/components/...'" **Root Cause:** Using relative imports instead of `@/` aliases **Fix:** ```typescript // ❌ WRONG: import { Button } from '../../../components/ui/button'; import { helper } from './lib/helper'; // ✅ CORRECT: import { Button } from '@/components/ui/button'; import { helper } from '@/lib/helper'; ``` **Prevention:** - During Step 6 (adapt code), replace all relative imports with `@/` aliases - Check `components.json` for configured path aliases - Restart TypeScript server in IDE after creating new files ## Troubleshooting ### Issue 1: Proxy Returns 500 **Symptom:** `curl http://localhost:3000/api/registry/proxy/PATTERN` returns error **Solutions:** 1. Check dev server is running 2. Verify `AISDKAGENTS_TOKEN` in `.env.local` 3. Check server logs: `tail -f /tmp/nextjs-dev.log` 4. Restart server: `pkill -f "next dev" && pnpm dev` ### Issue 2: Pattern Files Not Extracted **Symptom:** `scripts/extract-pattern.mjs` fails or creates empty directory **Solutions:** 1. Verify proxy is working: `curl http://localhost:3000/api/registry/proxy/PATTERN` 2. Check pattern name is correct 3. Ensure `.patterns-staging/` directory exists ### Issue 3: Imports Not Resolving **Symptom:** TypeScript errors after creating adapted files **Solutions:** 1. Update imports to use `@/` aliases 2. Check file is in correct directory 3. Restart TypeScript server in IDE ### Issue 4: API Test Returns Error **Symptom:** `curl` test returns 500 or unexpected response **Solutions:** 1. Check server logs for errors 2. Verify model provider is correct 3. Test with simpler prompt 4. Check tool definitions are valid ### Issue 5: Layers Not Working **Symptom:** Tool calls have empty arguments, token counts are 0 **Solutions:** 1. Verify using `tc.input` not `tc.args` 2. Check `AI_GATEWAY_API_KEY` is set 3. Test without Layers first (`useLayers: false`) 4. Review Layers fixes documentation ## Best Practices 1. **Create todo list FIRST** - Use TodoWrite at Step 0 to track all 20 steps 2. **Update todo list frequently** - Mark each step completed as you go 3. **Always extract to staging first** - Never install directly to playground 4. **Read before adapting** - Understand what the pattern does 5. **Test incrementally** - API → UI → Layers → Registry 6. **Regenerate pattern code immediately** - Run `pnpm generate:code` after creating API route 7. **Verify code tabs work** - Check during frontend testing (Step 15) 8. **Test with Layers explicitly** - Don't assume it works, verify with Step 17 9. **Update registry every time** - Run `pnpm build:registry` before marking complete 10. **Keep staging for reference** - Don't delete until fully working and tested 11. **Document adaptations** - Add comments explaining changes 12. **Follow our patterns** - Use existing playground code as template 13. **Test with multiple models** - Not just openai/gpt-4o-mini 14. **Use safe property access** - Always use `?.` for optional properties 15. **Provide fallbacks** - Never pass `undefined` to components expecting strings ## Files Reference **Proxy Registry:** - `app/api/registry/proxy/[...slug]/route.ts` - Proxy endpoint - `.env.local` - Contains `AISDKAGENTS_TOKEN` **Extraction:** - `scripts/extract-pattern.mjs` - Extraction script - `.patterns-staging/` - Staging directory - `.patterns-staging/PATTERN/_metadata.json` - Pattern metadata **Playground Structure:** - `app/api/playground/CATEGORY/PATTERN/route.ts` - API routes - `components/playground/patterns/CATEGORY/` - UI components - `lib/CATEGORY/` - Reusable library code **Configuration:** - `lib/patterns/config.ts` - Pattern definitions - `lib/testing/pattern-routes.ts` - Test configuration - `registry/CATEGORY-PATTERN.json` - Generated registry entry ## Quick Reference ```bash # 0. Create todo list (use TodoWrite with all 20 steps) # 1-2. Extract pattern node scripts/extract-pattern.mjs PATTERN-NAME # 3. Review files ls -laR .patterns-staging/PATTERN-NAME/ cat .patterns-staging/PATTERN-NAME/_metadata.json # Test proxy (troubleshooting) curl http://localhost:3000/api/registry/proxy/PATTERN-NAME | jq # 10. Test API route curl -X POST http://localhost:3000/api/playground/CATEGORY/PATTERN \ -H "Content-Type: application/json" \ -d '{"prompt": "test", "model": "openai/gpt-4o-mini"}' # 12. Test API with Layers curl -X POST http://localhost:3000/api/playground/CATEGORY/PATTERN \ -H "Content-Type": "application/json" \ -d '{"prompt": "test", "model": "openai/gpt-4o-mini", "useLayers": true}' # 13. Build CLI registry pnpm build:registry ls -la registry/CATEGORY-PATTERN-NAME.json # 14. Generate pattern code pnpm generate:code grep "CATEGORY/PATTERN" lib/patterns/generated-code.ts # 15. Test in browser pnpm dev open http://localhost:3000 # 18. Update generator script (if needed) # Edit scripts/generate-pattern-code.mjs # Add to PATTERN_ROUTES, then run: pnpm generate:code # 19. Clean staging rm -rf .patterns-staging/PATTERN-NAME ``` ## Success Criteria ### Setup & Extraction - [ ] Todo list created with all 20 steps (Step 0) - [ ] Pattern name extracted from CLI command (Step 1) - [ ] Pattern extracted to staging directory (Step 2) - [ ] Files reviewed and understood (Steps 3-4) - [ ] File mapping planned (Step 5) ### Code Adaptation - [ ] Code adapted to our structure (Step 6) - [ ] Files created in correct playground locations (Step 7) - [ ] Imports use `@/` aliases (Step 6) - [ ] Provider uses `getProvider()` not direct imports (Step 6) - [ ] Tool calls use `tc.input ?? tc.args` (Step 6) ### Configuration - [ ] Added to pattern config (Step 8) - [ ] Added to test config (Step 9) - [ ] Pattern code generator updated (Step 18, if needed) ### Testing - [ ] API test passes (Step 10) - [ ] UI test passes in browser (Step 11) - [ ] Frontend verification complete (Step 15) - [ ] Layers test passes (Step 12) - [ ] Layers compatibility verified (Step 17) - [ ] All CodeBlock components display correctly (Step 15) - [ ] No browser console errors (Step 15) ### Code Generation & Registry - [ ] Pattern code generated successfully (Step 14) - [ ] Pattern appears in lib/patterns/generated-code.ts (Step 14) - [ ] Code tabs display actual code, not "Loading..." (Step 14) - [ ] CLI registry entry generated (Step 13) - [ ] Registry file created: registry/CATEGORY-PATTERN-NAME.json (Step 13) - [ ] Pattern installable via CLI (Step 13) ### Cleanup - [ ] Staging directory cleaned (Step 19) - [ ] All todo list items marked completed (Step 0) - [ ] Pattern fully documented in skill notes (if needed) ## Pattern Preview System Infrastructure ### Overview The Pattern Preview System consists of: - **Pattern Browser** (`/patterns`) - Browse all available patterns - **Pattern Preview** (`/patterns/[patternName]`) - Preview individual patterns - **Pattern Installation** - One-click installation with progress tracking - **Pattern Management** - Track installed patterns and detect updates ### File Structure ``` app/ ├── patterns/ │ ├── page.tsx # Pattern browser │ └── [patternName]/ │ └── page.tsx # Pattern preview └── api/ ├── patterns/ │ ├── install/route.ts # Installation handler │ ├── installed/route.ts # Installation tracking │ ├── status/[patternName]/route.ts # Pattern status │ └── check-updates/route.ts # Update detection └── registry/ └── proxy/[...slug]/route.ts # Proxy to aisdkagents.com components/patterns/ ├── pattern-browser.tsx # Pattern grid with search ├── pattern-preview.tsx # Pattern detail view ├── file-tree.tsx # Interactive file explorer ├── code-viewer.tsx # Syntax-highlighted code viewer └── install-button.tsx # Installation with progress lib/patterns/ ├── fetch-pattern.ts # Pattern fetching utilities └── installed-patterns.json # Installation tracking database ``` ### Key Components #### 1. Pattern Browser ([/patterns/page.tsx](app/patterns/page.tsx)) - Lists all available patterns from aisdkagents.com - Grouped by category - Search functionality - Shows installation status #### 2. Pattern Preview ([/patterns/[patternName]/page.tsx](app/patterns/[patternName]/page.tsx)) - File tree viewer - Code viewer with syntax highlighting - Installation guide - Dependency information #### 3. Install Button ([components/patterns/install-button.tsx](components/patterns/install-button.tsx)) - Progress dialog with 4 stages: 1. Downloading 2. Extracting 3. Adapting 4. Tracking - Installation logs - Error handling #### 4. Pattern Fetching ([lib/patterns/fetch-pattern.ts](lib/patterns/fetch-pattern.ts)) - Fetches patterns via proxy - Lists available patterns - Checks installation status - Detects updates (file count comparison) ### Adding New Patterns to the Library To add a pattern to the browsable library, edit [lib/patterns/fetch-pattern.ts](lib/patterns/fetch-pattern.ts): ```typescript export async function fetchPatternList(): Promise { return [ // ... existing patterns { name: 'new-pattern-name', description: 'Pattern description', complexity: 'Intermediate', // Beginner | Intermediate | Advanced setupTime: '~5 minutes', features: ['feature1', 'feature2'], category: 'Category Name' // Groups patterns in browser } ]; } ``` ### Installation Tracking Patterns are tracked in [lib/patterns/installed-patterns.json](lib/patterns/installed-patterns.json): ```json { "patterns": [ { "name": "tool-api-dynamic-tool", "installedAt": "2026-01-24T10:30:00.000Z", "version": "1.0.0", "fileCount": 7 } ], "lastUpdated": "2026-01-24T10:30:00.000Z" } ``` **File count** is used for simple update detection - if upstream has different file count, updates may be available. ### Update Detection The system can check for pattern updates: ```typescript // GET /api/patterns/check-updates { "patterns": [ { "name": "tool-api-dynamic-tool", "installedAt": "2026-01-24T10:30:00.000Z", "hasUpdates": false, "upstreamFileCount": 7, "localFileCount": 7 } ] } ``` **Current limitation**: Only compares file counts. Future improvements could: - Compare file checksums - Use version numbers from pattern metadata - Show diff viewer for changed files ### Extending the System Future enhancements: - [ ] **Diff Viewer** - Visual comparison of local vs upstream files - [ ] **One-click Updates** - Update button to fetch latest version - [ ] **Version History** - Track version numbers and changelog - [ ] **Dependency Installation** - Auto-install npm dependencies - [ ] **Automated Testing** - Run pattern tests after installation - [ ] **Pattern Screenshots** - Visual previews in browser - [ ] **Pattern Search** - Advanced search with filters - [ ] **Pattern Collections** - Curated pattern bundles ## Next Patterns High-value patterns to install next: - `structured-output-array` - Output.array - `structured-output-choice` - Output.choice - `agent-routing-pattern` - Routing Pattern - `ai-human-in-the-loop-inquire-multiple-choice` - Inquire Pattern These fill gaps identified in our pattern analysis.