Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
feat(skills): Major updates from Jan 2026 documentation audits
Jez3672333e1e62
diff --git a/skills/ai-sdk-core/README.md b/skills/ai-sdk-core/README.mdindex d713e3c7..03b26eae 100644--- a/skills/ai-sdk-core/README.md+++ b/skills/ai-sdk-core/README.md@@ -1,26 +1,46 @@# AI SDK Core-Backend AI with Vercel AI SDK v5 - text generation, structured output, tools, and agents.+Backend AI with Vercel AI SDK v5/v6 - text generation, structured output, multi-modal (speech, transcription, image gen), embeddings, tools, and agents.## Auto-Trigger KeywordsThis skill should be discovered when working with:### Primary Keywords (High Priority)-- ai sdk core, vercel ai sdk, ai sdk v5+- ai sdk core, vercel ai sdk, ai sdk v5, ai sdk v6- generateText, streamText, generate text ai-- generateObject, streamObject, structured ai output+- Output.object, Output.array, Output.choice (v6)- ai sdk node, ai sdk server, ai sdk backend- zod ai schema, zod ai validation- ai tools calling, ai agent class, agent with tools- openai sdk, anthropic sdk, google gemini sdk- multi-provider ai, ai provider switching+### v6 Output API Keywords (CRITICAL)+- Output API, Output.object, Output.array, Output.choice+- generateObject deprecated, streamObject deprecated+- ai sdk v6 migration, v6 breaking changes+- structured output v6, ai sdk structured data++### Multi-Modal Keywords+- ai sdk speech, generateSpeech, text to speech ai+- ai sdk transcription, transcribe audio, speech to text ai+- ai sdk image generation, generateImage, dall-e api+- ai sdk embeddings, embed, embedMany, cosineSimilarity+- multi-modal prompts, pdf ai, image ai, file ai++### Advanced Features Keywords+- ai sdk reranking, rerank documents, rag relevance+- ai sdk middleware, wrapLanguageModel, extractReasoningMiddleware+- ai sdk telemetry, opentelemetry ai, ai tracing+- ai sdk mcp, model context protocol, mcp tools+- tool approval, human in the loop ai, needsApproval+### Secondary Keywords (Medium Priority)- ai streaming backend, stream ai responses- ai server actions, nextjs ai server- cloudflare workers ai sdk, workers-ai-provider-- ai sdk migration, v4 to v5 migration+- ai sdk migration, v4 to v5 migration, v5 to v6 migration- ai chat completion, llm text generation- ai sdk typescript, typed ai responses- stopWhen ai sdk, multi-step ai execution@@ -33,6 +53,8 @@ This skill should be discovered when working with:- AI_InvalidArgumentError, invalid argument ai- AI_TypeValidationError, zod validation failed- AI_RetryError, ai retry failed+- AI_NoSpeechGeneratedError, speech generation failed+- AI_NoTranscriptGeneratedError, transcription failed- streamText fails silently, stream error swallowed- worker startup limit ai sdk, 270ms startup- ai rate limit, rate limiting ai@@ -47,25 +69,30 @@ This skill should be discovered when working with:- vercel ai deployment, serverless ai### Provider Keywords-- openai integration, gpt-4 api, chatgpt api-- anthropic claude, claude api integration-- google gemini api, gemini integration+- openai integration, gpt-5 api, gpt-5.2 api, chatgpt api+- anthropic claude, claude api integration, claude 4 api+- google gemini api, gemini 2.5 integration- cloudflare llama, workers ai llm+- elevenlabs ai sdk, deepgram ai sdk## What This Skill Provides-- **4 Core Functions**: generateText, streamText, generateObject, streamObject-- **Top 4 Providers**: OpenAI, Anthropic, Google, Cloudflare Workers AI-- **Tool Calling & Agents**: Multi-step execution with tools+- **v6 Output API**: Output.object/array/choice replaces deprecated generateObject/streamObject+- **Multi-Modal**: Speech synthesis, transcription, image generation, embeddings+- **Core Functions**: generateText, streamText with structured output+- **MCP Integration**: Model Context Protocol tools+- **Middleware**: Language model middleware patterns+- **Telemetry**: OpenTelemetry integration+- **Top Providers**: OpenAI, Anthropic, Google, Cloudflare, ElevenLabs, 60+ more- **v4→v5 Migration**: Complete breaking changes guide- **Top 12 Errors**: Common issues with solutions-- **13 Templates**: Copy-paste examples-- **5 Reference Docs**: Detailed guides- **Production Patterns**: Best practices for deployment## Quick Links- **Official Docs**: https://ai-sdk.dev/docs+- **Output API**: https://ai-sdk.dev/docs/ai-sdk-core/generating-structured-data+- **Multi-Modal**: https://ai-sdk.dev/docs/ai-sdk-core/speech- **Migration Guide**: https://ai-sdk.dev/docs/migration-guides/migration-guide-5-0- **Error Reference**: https://ai-sdk.dev/docs/reference/ai-sdk-errors- **GitHub**: https://github.com/vercel/ai@@ -82,25 +109,26 @@ See `SKILL.md` for comprehensive documentation and examples.## Version-- **Skill Version**: 1.1.1-- **AI SDK Version**: 5.0.95+-- **Last Updated**: 2025-11-19+- **Skill Version**: 2.0.0+- **AI SDK Version**: 6.1.0+- **Last Updated**: 2026-01-03-## Recent Updates (v1.1.1 - 2025-11-19)+## Recent Updates (v2.0.0 - 2026-01-03)-- **Updated Package Versions**: AI SDK 5.0.95, @ai-sdk/anthropic 2.0.45, @ai-sdk/openai 2.0.68, @ai-sdk/google 2.0.38-- **Updated Template Models**: anthropic-setup.ts and openai-setup.ts now use latest model IDs- - Claude: Sonnet 4.5, Opus 4.0, Haiku 4.5 (deprecated Claude 3.x models as commented examples)- - OpenAI: GPT-5.1, GPT-5-Pro, GPT-4.1, o3 reasoning model (previous gen as comments)-- **Added Metadata**: YAML frontmatter now includes version tracking and last_verified date-- **Zod 3.x for Compatibility**: Templates use Zod 3.23.8 for maximum compatibility (AI SDK supports both 3.x and 4.x)+- **BREAKING: Output API**: Added v6 Output.object/array/choice documentation (generateObject/streamObject deprecated)+- **Multi-Modal**: Added speech synthesis, transcription, image generation sections+- **Embeddings**: Added embed(), embedMany(), cosineSimilarity() with full examples+- **MCP Tools**: Added Model Context Protocol integration+- **Middleware**: Added wrapLanguageModel and extractReasoningMiddleware patterns+- **Telemetry**: Added OpenTelemetry integration+- **Models**: Added GPT-5.2, o3, o3-mini, o4-mini model references+- **Providers**: Updated to 69+ providers (was ~25)+- **Errors**: Updated to 31 error types (was 12 documented)-## Previous Updates (v1.1.0 - 2025-10-29)+## Previous Updates (v1.2.0 - 2025-11-22)-- **Updated Model Names**: Claude 4.x (Sonnet 4.5, Opus 4), GPT-5, Gemini 2.5 models now GA-- **Zod 4 Support Documented**: AI SDK 5 supports both Zod 3.x and 4.x (4.1.12 latest)-- **Issue #4726 Resolved**: streamText now has onError callback (fixed in v4.1.22)-- **Deprecated Claude 3.x**: Anthropic deprecated Claude 3.x models in favor of Claude 4.x family+- **v6 Beta**: Added AI SDK 6 beta features (Agent abstraction, tool approval, reranking)+- **Updated Models**: GPT-5.1, Claude Sonnet 4.5, Gemini 2.5 models## Licensediff --git a/skills/ai-sdk-core/SKILL.md b/skills/ai-sdk-core/SKILL.mdindex 93652149..d09b449f 100644--- a/skills/ai-sdk-core/SKILL.md+++ b/skills/ai-sdk-core/SKILL.md@@ -1,32 +1,104 @@---name: ai-sdk-coredescription: |- Build backend AI with Vercel AI SDK v5/v6. Covers v6 beta (Agent abstraction, tool approval, reranking),- v4→v5 migration (breaking changes), latest models (GPT-5/5.1, Claude 4.x, Gemini 2.5), Workers startup- fix, and 12 error solutions (AI_APICallError, AI_NoObjectGeneratedError, streamText silent errors).+ Build backend AI with Vercel AI SDK v5/v6. v6 stable introduces Output API (Output.object/array/choice+ replace deprecated generateObject/streamObject), plus speech synthesis, transcription, image generation,+ embeddings, reranking, MCP tools, and middleware. Covers v4→v5 migration, latest models (GPT-5.2,+ Claude 4.x, Gemini 2.5), Workers startup fix, and 12 error solutions.- Use when: implementing AI SDK v5/v6, migrating v4→v5, troubleshooting errors, fixing Workers startup- issues, or updating to latest models.+ Use when: implementing AI SDK v5/v6, using Output API, speech/transcription/image features, embeddings,+ MCP tools, migrating v4→v5, troubleshooting errors, or fixing Workers startup issues.---# AI SDK Core-Backend AI with Vercel AI SDK v5 and v6 Beta.+Backend AI with Vercel AI SDK v5 and v6.**Installation:**```bashnpm install ai @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google zod-# Beta: npm install ai@beta @ai-sdk/openai@beta```----## AI SDK 6 Beta (November 2025)+## AI SDK 6 (Stable - January 2026)-**Status:** Beta (stable release planned end of 2025)-**Latest:** [email protected] (Nov 22, 2025)+**Status:** Stable+**Latest:** [email protected] (Jan 2026)-### New Features+### BREAKING: Output API Replaces generateObject/streamObject++⚠️ **CRITICAL**: `generateObject()` and `streamObject()` are **DEPRECATED** and will be removed in a future version. Use the new Output API instead.++**Before (v5 - DEPRECATED):**+```typescript+// ❌ DEPRECATED - will be removed+import { generateObject } from 'ai';++const result = await generateObject({+ model: openai('gpt-5'),+ schema: z.object({ name: z.string(), age: z.number() }),+ prompt: 'Generate a person',+});+```++**After (v6 - USE THIS):**+```typescript+// ✅ NEW OUTPUT API+import { generateText, Output } from 'ai';++const result = await generateText({+ model: openai('gpt-5'),+ output: Output.object({ schema: z.object({ name: z.string(), age: z.number() }) }),+ prompt: 'Generate a person',+});++// Access the typed object+console.log(result.object); // { name: "Alice", age: 30 }+```++### Output Types++```typescript+import { generateText, Output } from 'ai';++// Object with Zod schema+output: Output.object({ schema: myZodSchema })++// Array of typed objects+output: Output.array({ schema: personSchema })++// Enum/choice from options+output: Output.choice({ choices: ['positive', 'negative', 'neutral'] })++// Plain text (explicit)+output: Output.text()++// Unstructured JSON (no schema validation)+output: Output.json()+```++### Streaming with Output API++```typescript+import { streamText, Output } from 'ai';++const result = streamText({+ model: openai('gpt-5'),+ output: Output.object({ schema: personSchema }),+ prompt: 'Generate a person',+});++// Stream partial objects+for await (const partialObject of result.objectStream) {+ console.log(partialObject); // { name: "Ali..." } -> { name: "Alice", age: ... }+}++// Get final object+const finalObject = await result.object;+```++### v6 New Features**1. Agent Abstraction**Unified interface for building agents with `ToolLoopAgent` class:@@ -34,63 +106,106 @@ Unified interface for building agents with `ToolLoopAgent` class:- Replaces manual tool calling orchestration**2. Tool Execution Approval (Human-in-the-Loop)**-Request user confirmation before executing tools:-- Static approval: Always ask for specific tools-- Dynamic approval: Conditional based on tool inputs-- Native human-in-the-loop pattern--**3. Reranking Support**-Improve search relevance by reordering documents:-- Supported providers: Cohere, Amazon Bedrock, Together.ai-- Specialized reranking models for RAG workflows--**4. Structured Output (Stable)**-Combine multi-step tool calling with structured data generation:-- Multiple output strategies: objects, arrays, choices, text formats-- Now stable and production-ready in v6--**5. Call Options**-Dynamic runtime configuration:-- Type-safe parameter passing-- RAG integration, model selection, tool customization-- Provider-specific settings adjustments--**6. Image Editing (Coming Soon)**-Native support for image transformation workflows.--### Migration from v5--**Unlike v4→v5, v6 has minimal breaking changes:**-- Powered by v3 Language Model Specification-- Most users require no code changes-- Agent abstraction is additive (opt-in)--**Install Beta:**-```bash-npm install ai@beta @ai-sdk/openai@beta @ai-sdk/react@beta+```typescript+tools: {+ payment: tool({+ needsApproval: true, // Always ask+ // OR dynamic:+ needsApproval: async ({ amount }) => amount > 1000,+ inputSchema: z.object({ amount: z.number() }),+ execute: async ({ amount }) => { /* process payment */ },+ }),+}+```++**3. Reranking for RAG**+```typescript+import { rerank } from 'ai';++const result = await rerank({+ model: cohere.reranker('rerank-v3.5'),+ query: 'user question',+ documents: searchResults,+ topK: 5,+});+```++**4. MCP Tools (Model Context Protocol)**+```typescript+import { experimental_createMCPClient } from 'ai';++const mcpClient = await experimental_createMCPClient({+ transport: { type: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem'] },+});++const tools = await mcpClient.tools();++const result = await generateText({+ model: openai('gpt-5'),+ tools,+ prompt: 'List files in the current directory',+});+```++**5. Language Model Middleware**+```typescript+import { wrapLanguageModel, extractReasoningMiddleware } from 'ai';++const wrappedModel = wrapLanguageModel({+ model: anthropic('claude-sonnet-4-5-20250929'),+ middleware: extractReasoningMiddleware({ tagName: 'think' }),+});++// Reasoning extracted automatically from <think>...</think> tags```-**Official Docs:** https://ai-sdk.dev/docs/announcing-ai-sdk-6-beta+**6. Telemetry (OpenTelemetry)**+```typescript+const result = await generateText({+ model: openai('gpt-5'),+ prompt: 'Hello',+ experimental_telemetry: {+ isEnabled: true,+ functionId: 'my-chat-function',+ metadata: { userId: '123' },+ recordInputs: true,+ recordOutputs: true,+ },+});+```++**Official Docs:** https://ai-sdk.dev/docs----## Latest AI Models (2025)+## Latest AI Models (2025-2026)### OpenAI-**GPT-5** (Aug 7, 2025):-- 45% less hallucination than GPT-4o-- State-of-the-art in math, coding, visual perception, health-- Available in ChatGPT, API, GitHub Models, Microsoft Copilot+**GPT-5.2** (Dec 2025):+- 400k context window, 128k output tokens+- Enhanced reasoning capabilities+- Available in API platform-**GPT-5.1** (Nov 13, 2025):+**GPT-5.1** (Nov 2025):- Improved speed and efficiency over GPT-5-- Available in API platform+- "Warmer" and more intelligent responses++**GPT-5** (Aug 2025):+- 45% less hallucination than GPT-4o+- State-of-the-art in math, coding, visual perception++**o3 Reasoning Models** (Dec 2025):+- o3, o3-pro, o3-mini - Advanced reasoning+- o4-mini - Fast reasoning```typescriptimport { openai } from '@ai-sdk/openai';-const gpt5 = openai('gpt-5');+const gpt52 = openai('gpt-5.2');const gpt51 = openai('gpt-5.1');+const gpt5 = openai('gpt-5');+const o3 = openai('o3');+const o3mini = openai('o3-mini');```### Anthropic@@ -126,14 +241,151 @@ const lite = google('gemini-2.5-flash-lite');----## v5 Core Functions (Basics)+## Core Functions++### Text Generation**generateText()** - Text completion with tools**streamText()** - Real-time streaming-**generateObject()** - Structured output (Zod schemas)-**streamObject()** - Streaming structured data-See official docs for usage: https://ai-sdk.dev/docs/ai-sdk-core+### Structured Output (v6 Output API)++**Output.object()** - Typed objects with Zod schema (replaces generateObject)+**Output.array()** - Typed arrays+**Output.choice()** - Enum selection+**Output.json()** - Unstructured JSON++See "AI SDK 6" section above for usage examples.++### Multi-Modal Capabilities++#### Speech Synthesis (Text-to-Speech)++```typescript+import { experimental_generateSpeech as generateSpeech } from 'ai';+import { openai } from '@ai-sdk/openai';++const result = await generateSpeech({+ model: openai.speech('tts-1-hd'),+ voice: 'alloy',+ text: 'Hello, how can I help you today?',+});++// result.audio is an ArrayBuffer containing the audio+const audioBuffer = result.audio;+```++**Supported Providers:**+- OpenAI: tts-1, tts-1-hd, gpt-4o-mini-tts+- ElevenLabs: eleven_multilingual_v2, eleven_turbo_v2+- LMNT, Hume++#### Transcription (Speech-to-Text)++```typescript+import { experimental_transcribe as transcribe } from 'ai';+import { openai } from '@ai-sdk/openai';++const result = await transcribe({+ model: openai.transcription('whisper-1'),+ audio: audioFile, // File, Blob, ArrayBuffer, or URL+});++console.log(result.text); // Transcribed text+console.log(result.segments); // Timestamped segments+```++**Supported Providers:**+- OpenAI: whisper-1+- ElevenLabs, Deepgram, AssemblyAI, Groq, Rev.ai++#### Image Generation++```typescript+import { generateImage } from 'ai';+import { openai } from '@ai-sdk/openai';++const result = await generateImage({+ model: openai.image('dall-e-3'),+ prompt: 'A futuristic city at sunset',+ size: '1024x1024',+ n: 1,+});++// result.images is an array of generated images+const imageUrl = result.images[0].url;+const imageBase64 = result.images[0].base64;+```++**Supported Providers:**+- OpenAI: dall-e-2, dall-e-3+- Google: imagen-3.0+- Fal AI, Black Forest Labs (Flux), Luma AI, Replicate++#### Embeddings++```typescript+import { embed, embedMany, cosineSimilarity } from 'ai';+import { openai } from '@ai-sdk/openai';++// Single embedding+const result = await embed({+ model: openai.embedding('text-embedding-3-small'),+ value: 'Hello world',+});+console.log(result.embedding); // number[]++// Multiple embeddings (parallel processing)+const results = await embedMany({+ model: openai.embedding('text-embedding-3-small'),+ values: ['Hello', 'World', 'AI'],+ maxParallelCalls: 5, // Parallel processing+});++// Compare similarity+const similarity = cosineSimilarity(+ results.embeddings[0],+ results.embeddings[1]+);+console.log(`Similarity: ${similarity}`); // 0.0 to 1.0+```++**Supported Providers:**+- OpenAI: text-embedding-3-small, text-embedding-3-large+- Google: text-embedding-004+- Cohere, Voyage AI, Mistral, Amazon Bedrock++#### Multi-Modal Prompts (Files, Images, PDFs)++```typescript+import { generateText } from 'ai';+import { google } from '@ai-sdk/google';++const result = await generateText({+ model: google('gemini-2.5-pro'),+ messages: [{+ role: 'user',+ content: [+ { type: 'text', text: 'Summarize this document' },+ { type: 'file', data: pdfBuffer, mimeType: 'application/pdf' },+ ],+ }],+});++// Or with images+const result = await generateText({+ model: openai('gpt-5'),+ messages: [{+ role: 'user',+ content: [+ { type: 'text', text: 'What is in this image?' },+ { type: 'image', image: imageBuffer },+ ],+ }],+});+```++See official docs for full API: https://ai-sdk.dev/docs/ai-sdk-core---@@ -813,19 +1065,19 @@ try {## Versions**AI SDK:**-- Stable: [email protected] (Nov 20, 2025)-- Beta: [email protected] (Nov 22, 2025)-- Zod 3.x/4.x both supported (3.23.8 recommended)+- Stable: [email protected] (Jan 2026)+- Legacy v5: [email protected] (Nov 2025)+- Zod 3.x/4.x both supported-**Latest Models (2025):**-- OpenAI: GPT-5.1, GPT-5, o3+**Latest Models (2026):**+- OpenAI: GPT-5.2, GPT-5.1, GPT-5, o3, o3-mini, o4-mini- Anthropic: Claude Sonnet 4.5, Opus 4.1, Haiku 4.5- Google: Gemini 2.5 Pro/Flash/Lite**Check Latest:**```bashnpm view ai version-npm view ai dist-tags # See beta versions+npm view ai dist-tags```---@@ -833,11 +1085,18 @@ npm view ai dist-tags # See beta versions## Official Docs**Core:**-- AI SDK 6 Beta: https://ai-sdk.dev/docs/announcing-ai-sdk-6-beta+- AI SDK v6: https://ai-sdk.dev/docs- AI SDK Core: https://ai-sdk.dev/docs/ai-sdk-core/overview+- Output API: https://ai-sdk.dev/docs/ai-sdk-core/generating-structured-data- v4→v5 Migration: https://ai-sdk.dev/docs/migration-guides/migration-guide-5-0-- All Errors (28): https://ai-sdk.dev/docs/reference/ai-sdk-errors-- Providers (25+): https://ai-sdk.dev/providers/overview+- All Errors (31): https://ai-sdk.dev/docs/reference/ai-sdk-errors+- Providers (69+): https://ai-sdk.dev/providers/overview++**Multi-Modal:**+- Speech: https://ai-sdk.dev/docs/ai-sdk-core/speech+- Transcription: https://ai-sdk.dev/docs/ai-sdk-core/transcription+- Image Generation: https://ai-sdk.dev/docs/ai-sdk-core/image-generation+- Embeddings: https://ai-sdk.dev/docs/ai-sdk-core/embeddings**GitHub:**- Repository: https://github.com/vercel/ai@@ -845,6 +1104,6 @@ npm view ai dist-tags # See beta versions----**Last Updated:** 2025-11-22-**Skill Version:** 1.2.0-**AI SDK:** 5.0.98 stable / 6.0.0-beta.107+**Last Updated:** 2026-01-03+**Skill Version:** 2.0.0+**AI SDK:** 6.1.0 stablediff --git a/skills/clerk-auth/SKILL.md b/skills/clerk-auth/SKILL.mdindex 3bb8f1a8..db06f4fc 100644--- a/skills/clerk-auth/SKILL.md+++ b/skills/clerk-auth/SKILL.md@@ -1,18 +1,115 @@---name: clerk-authdescription: |- Clerk auth with API version 2025-11-10 breaking changes (billing endpoints, payment_source→payment_method), Next.js v6 async auth(), PKCE for custom OAuth, credential stuffing defense. Use when: troubleshooting "Missing Clerk Secret Key", JWKS errors, authorizedParties CSRF, JWT size limits (1.2KB), 431 header errors (Vite dev mode), or testing with 424242 OTP.+ Clerk auth with API Keys beta (Dec 2025), Next.js 16 proxy.ts, API version 2025-11-10 breaking changes, clerkMiddleware() options, webhooks, and component reference. Use when: API keys for users/orgs, Next.js 16 middleware filename, troubleshooting JWKS/CSRF/JWT errors, webhook verification, or testing with 424242 OTP.---# Clerk Auth - Breaking Changes & Error Prevention Guide**Package Versions**: @clerk/[email protected], @clerk/[email protected], @clerk/[email protected], @clerk/[email protected]**Breaking Changes**: Nov 2025 - API version 2025-11-10, Oct 2024 - Next.js v6 async auth()-**Last Updated**: 2025-11-22+**Last Updated**: 2026-01-03----## What's New in v6.35.x & API 2025-11-10 (Nov 2025)+## What's New (Dec 2025 - Jan 2026)++### 1. API Keys Beta (Dec 11, 2025) - NEW ✨++User-scoped and organization-scoped API keys for your application. Zero-code UI component.++```typescript+// 1. Add the component for self-service API key management+import { APIKeys } from '@clerk/nextjs'++export default function SettingsPage() {+ return (+ <div>+ <h2>API Keys</h2>+ <APIKeys /> {/* Full CRUD UI for user's API keys */}+ </div>+ )+}+```++**Backend Verification:**+```typescript+import { verifyToken } from '@clerk/backend'++// API keys are verified like session tokens+const { data, error } = await verifyToken(apiKey, {+ secretKey: process.env.CLERK_SECRET_KEY,+ authorizedParties: ['https://yourdomain.com'],+})++// Check token type+if (data?.tokenType === 'api_key') {+ // Handle API key auth+}+```++**clerkMiddleware Token Types:**+```typescript+// v6.36.0+: Middleware can distinguish token types+clerkMiddleware((auth, req) => {+ const { userId, tokenType } = auth()++ if (tokenType === 'api_key') {+ // API key auth - programmatic access+ } else if (tokenType === 'session_token') {+ // Regular session - web UI access+ }+})+```++**Pricing (Beta = Free):**+- Creation: $0.001/key+- Verification: $0.0001/verification++### 2. Next.js 16: proxy.ts Middleware Filename (Dec 2025)++**⚠️ BREAKING**: Next.js 16 changed middleware filename:++```+Next.js 15 and earlier: middleware.ts+Next.js 16+: proxy.ts+```++**Correct Setup for Next.js 16:**+```typescript+// src/proxy.ts (NOT middleware.ts!)+import { clerkMiddleware } from '@clerk/nextjs/server'++export default clerkMiddleware()++export const config = {+ matcher: [+ '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',+ '/(api|trpc)(.*)',+ ],+}+```++### 3. Force Password Reset (Dec 19, 2025)++Administrators can mark passwords as compromised and force reset:++```typescript+import { clerkClient } from '@clerk/backend'++// Force password reset for a user+await clerkClient.users.updateUser(userId, {+ passwordDigest: 'compromised', // Triggers reset on next sign-in+})+```++### 4. Organization Reports & Filters (Dec 15-17, 2025)++Dashboard now includes org creation metrics and filtering by name/slug/date.++---++## API Version 2025-11-10 Breaking Changes### 1. API Version 2025-11-10 (Nov 10, 2025) - BREAKING CHANGES ⚠️@@ -135,6 +232,145 @@ const { data, error } = await verifyToken(token, {---+## clerkMiddleware() Configuration++### Route Protection Patterns++```typescript+import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'++// Define protected routes+const isProtectedRoute = createRouteMatcher([+ '/dashboard(.*)',+ '/api/private(.*)',+])++const isAdminRoute = createRouteMatcher(['/admin(.*)'])++export default clerkMiddleware(async (auth, req) => {+ // Protect routes+ if (isProtectedRoute(req)) {+ await auth.protect() // Redirects unauthenticated users+ }++ // Require specific permissions+ if (isAdminRoute(req)) {+ await auth.protect({+ role: 'org:admin', // Requires organization admin role+ })+ }+})+```++### All Middleware Options++| Option | Type | Description |+|--------|------|-------------|+| `debug` | `boolean` | Enable debug logging |+| `jwtKey` | `string` | JWKS public key for networkless verification |+| `clockSkewInMs` | `number` | Token time variance (default: 5000ms) |+| `organizationSyncOptions` | `object` | URL-based org activation |+| `signInUrl` | `string` | Custom sign-in URL |+| `signUpUrl` | `string` | Custom sign-up URL |++### Organization Sync (URL-based Org Activation)++```typescript+clerkMiddleware({+ organizationSyncOptions: {+ organizationPatterns: ['/orgs/:slug', '/orgs/:slug/(.*)'],+ personalAccountPatterns: ['/personal', '/personal/(.*)'],+ },+})+```++---++## Webhooks++### Webhook Verification++```typescript+import { Webhook } from 'svix'++export async function POST(req: Request) {+ const payload = await req.text()+ const headers = {+ 'svix-id': req.headers.get('svix-id')!,+ 'svix-timestamp': req.headers.get('svix-timestamp')!,+ 'svix-signature': req.headers.get('svix-signature')!,+ }++ const wh = new Webhook(process.env.CLERK_WEBHOOK_SIGNING_SECRET!)++ try {+ const event = wh.verify(payload, headers)+ // Process event+ return Response.json({ success: true })+ } catch (err) {+ return Response.json({ error: 'Invalid signature' }, { status: 400 })+ }+}+```++### Common Event Types++| Event | Trigger |+|-------|---------|+| `user.created` | New user signs up |+| `user.updated` | User profile changes |+| `user.deleted` | User account deleted |+| `session.created` | New sign-in |+| `session.ended` | Sign-out |+| `organization.created` | New org created |+| `organization.membership.created` | User joins org |++**⚠️ Important:** Webhook routes must be PUBLIC (no auth). Add to middleware exclude list:++```typescript+const isPublicRoute = createRouteMatcher([+ '/api/webhooks/clerk(.*)', // Clerk webhooks are public+])++clerkMiddleware((auth, req) => {+ if (!isPublicRoute(req)) {+ auth.protect()+ }+})+```++---++## UI Components Quick Reference++| Component | Purpose |+|-----------|---------|+| `<SignIn />` | Full sign-in flow |+| `<SignUp />` | Full sign-up flow |+| `<SignInButton />` | Trigger sign-in modal |+| `<SignUpButton />` | Trigger sign-up modal |+| `<SignedIn>` | Render only when authenticated |+| `<SignedOut>` | Render only when unauthenticated |+| `<UserButton />` | User menu with sign-out |+| `<UserProfile />` | Full profile management |+| `<OrganizationSwitcher />` | Switch between orgs |+| `<OrganizationProfile />` | Org settings |+| `<CreateOrganization />` | Create new org |+| `<APIKeys />` | API key management (NEW) |++### React Hooks++| Hook | Returns |+|------|---------|+| `useAuth()` | `{ userId, sessionId, isLoaded, isSignedIn, getToken }` |+| `useUser()` | `{ user, isLoaded, isSignedIn }` |+| `useClerk()` | Clerk instance with methods |+| `useSession()` | Current session object |+| `useOrganization()` | Current org context |+| `useOrganizationList()` | All user's orgs |++---+## JWT Templates - Size Limits & Shortcodes### JWT Size Limitation: 1.2KB for Custom Claims ⚠️@@ -368,13 +604,13 @@ Add to `package.json`:---**Token Efficiency**:-- **Without skill**: ~5,200 tokens (setup tutorials, JWT templates, testing setup)-- **With skill**: ~2,500 tokens (breaking changes + critical patterns + error prevention)-- **Savings**: ~52% (~2,700 tokens)+- **Without skill**: ~6,000 tokens (setup tutorials, JWT templates, testing setup, webhooks)+- **With skill**: ~2,800 tokens (breaking changes + critical patterns + error prevention)+- **Savings**: ~53% (~3,200 tokens)**Errors prevented**: 11 documented issues with exact solutions-**Key value**: API 2025-11-10 breaking changes, Next.js v6 async auth(), PKCE for custom OAuth, credential stuffing defense, JWT size limits, 431 header error workaround+**Key value**: API Keys beta, Next.js 16 proxy.ts, clerkMiddleware() options, webhooks, component reference, API 2025-11-10 breaking changes, JWT size limits----**Last verified**: 2025-11-22 | **Skill version**: 2.0.0 | **Changes**: Added API version 2025-11-10 breaking changes (billing endpoints), PKCE support, Client Trust defense, Next.js 16 support. Removed tutorials (~480 lines). Updated SDK versions. Focused on breaking changes + error prevention + critical patterns.+**Last verified**: 2026-01-03 | **Skill version**: 3.0.0 | **Changes**: Added API Keys beta (Dec 2025), Next.js 16 proxy.ts filename, clerkMiddleware() configuration options, webhooks verification patterns, UI components + React hooks reference tables, organization sync patterns.diff --git a/skills/drizzle-orm-d1/SKILL.md b/skills/drizzle-orm-d1/SKILL.mdindex cf85e4f4..a7368ba5 100644--- a/skills/drizzle-orm-d1/SKILL.md+++ b/skills/drizzle-orm-d1/SKILL.md@@ -24,7 +24,7 @@ description: |# Drizzle ORM for Cloudflare D1**Status**: Production Ready ✅-**Last Updated**: 2025-11-25+**Last Updated**: 2026-01-03**Dependencies**: cloudflare-d1, cloudflare-worker-base@@ -97,6 +97,124 @@ const allUsers = await db.select().from(users).all();---+## Drizzle Kit Tools++### Drizzle Studio (Visual Database Browser)++```bash+npx drizzle-kit studio+# Opens http://local.drizzle.studio++# For remote D1 database+npx drizzle-kit studio --port 3001+```++**Features:**+- Browse tables and data visually+- Edit records inline+- Run custom SQL queries+- View schema relationships++### Migration Commands++| Command | Purpose |+|---------|---------|+| `drizzle-kit generate` | Generate SQL migrations from schema changes |+| `drizzle-kit push` | Push schema directly (dev only, not for production) |+| `drizzle-kit pull` | Introspect existing database → Drizzle schema |+| `drizzle-kit check` | Validate migration integrity (race conditions) |+| `drizzle-kit up` | Upgrade migration snapshots to latest format |++```bash+# Introspect existing D1 database+npx drizzle-kit pull++# Validate migrations haven't collided+npx drizzle-kit check+```++---++## Advanced Query Patterns++### Dynamic Query Building++Build queries conditionally with `.$dynamic()`:++```typescript+import { eq, and, or, like, sql } from 'drizzle-orm';++// Base query+function getUsers(filters: { name?: string; email?: string; active?: boolean }) {+ let query = db.select().from(users).$dynamic();++ if (filters.name) {+ query = query.where(like(users.name, `%${filters.name}%`));+ }+ if (filters.email) {+ query = query.where(eq(users.email, filters.email));+ }+ if (filters.active !== undefined) {+ query = query.where(eq(users.active, filters.active));+ }++ return query;+}++// Usage+const results = await getUsers({ name: 'John', active: true });+```++### Upsert (Insert or Update on Conflict)++```typescript+import { users } from './schema';++// Insert or ignore if exists+await db.insert(users)+ .values({ id: 1, email: '[email protected]', name: 'Test' })+ .onConflictDoNothing();++// Insert or update specific fields on conflict+await db.insert(users)+ .values({ id: 1, email: '[email protected]', name: 'Test' })+ .onConflictDoUpdate({+ target: users.email, // Conflict on unique email+ set: {+ name: sql`excluded.name`, // Use value from INSERT+ updatedAt: new Date(),+ },+ });+```++**⚠️ D1 Upsert Caveat:** Target must be a unique column or primary key.++### Debugging with Logging++```typescript+import { drizzle } from 'drizzle-orm/d1';++// Enable query logging+const db = drizzle(env.DB, { logger: true });++// Custom logger+const db = drizzle(env.DB, {+ logger: {+ logQuery(query, params) {+ console.log('SQL:', query);+ console.log('Params:', params);+ },+ },+});++// Get SQL without executing (for debugging)+const query = db.select().from(users).where(eq(users.id, 1));+const sql = query.toSQL();+console.log(sql.sql, sql.params);+```++---+## Known Issues PreventionThis skill prevents **12** documented issues:diff --git a/skills/hono-routing/SKILL.md b/skills/hono-routing/SKILL.mdindex d9a601cc..ea0278f3 100644--- a/skills/hono-routing/SKILL.md+++ b/skills/hono-routing/SKILL.md@@ -1,16 +1,16 @@---name: hono-routingdescription: |- Build type-safe APIs with Hono - fast, lightweight routing for Cloudflare Workers, Deno, Bun, and Node.js. Set up routing patterns, middleware composition, request validation (Zod/Valibot/Typia/ArkType), RPC client/server with full type inference, and error handling with HTTPException.+ Build type-safe APIs with Hono - fast, lightweight routing for Cloudflare Workers, Deno, Bun, and Node.js. Covers routing, middleware, validation (Zod/Valibot), RPC client/server, streaming (SSE, streamText), WebSocket, security middleware (secureHeaders, CSRF), and combine middleware.- Use when: building APIs with Hono, setting up request validation with schema libraries, creating type-safe RPC client/server communication, implementing custom middleware chains, handling errors with HTTPException, extending context with custom variables, or troubleshooting middleware type inference issues, validation hook confusion, RPC performance problems, or middleware response typing errors.+ Use when: building APIs with Hono, streaming responses (SSE, AI), WebSocket connections, security middleware (CSRF, secureHeaders), request validation, RPC communication, or troubleshooting validation hooks, RPC types, middleware chains.---# Hono Routing & Middleware**Status**: Production Ready ✅-**Last Updated**: 2025-11-26+**Last Updated**: 2026-01-03**Dependencies**: None (framework-agnostic)**Latest Versions**: [email protected], [email protected], [email protected], @hono/[email protected], @hono/[email protected]@@ -208,6 +208,153 @@ app.use(**Built-in Middleware Reference**: See `references/middleware-catalog.md`+#### Streaming Helpers (SSE, AI Responses)++```typescript+import { Hono } from 'hono'+import { stream, streamText, streamSSE } from 'hono/streaming'++const app = new Hono()++// Binary streaming+app.get('/download', (c) => {+ return stream(c, async (stream) => {+ await stream.write(new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]))+ await stream.pipe(readableStream)+ })+})++// Text streaming (AI responses)+app.get('/ai', (c) => {+ return streamText(c, async (stream) => {+ for await (const chunk of aiResponse) {+ await stream.write(chunk)+ await stream.sleep(50) // Rate limit if needed+ }+ })+})++// Server-Sent Events (real-time updates)+app.get('/sse', (c) => {+ return streamSSE(c, async (stream) => {+ let id = 0+ while (true) {+ await stream.writeSSE({+ data: JSON.stringify({ time: Date.now() }),+ event: 'update',+ id: String(id++),+ })+ await stream.sleep(1000)+ }+ })+})+```++**Use Cases:**+- `stream()` - Binary files, video, audio+- `streamText()` - AI chat responses, typewriter effects+- `streamSSE()` - Real-time notifications, live feeds++#### WebSocket Helper++```typescript+import { Hono } from 'hono'+import { upgradeWebSocket } from 'hono/cloudflare-workers' // Platform-specific!++const app = new Hono()++app.get('/ws', upgradeWebSocket((c) => ({+ onMessage(event, ws) {+ console.log(`Message: ${event.data}`)+ ws.send(`Echo: ${event.data}`)+ },+ onClose: () => console.log('Closed'),+ onError: (event) => console.error('Error:', event),+ // onOpen is NOT supported on Cloudflare Workers!+})))++export default app+```++**⚠️ Cloudflare Workers WebSocket Caveats:**+- Import from `hono/cloudflare-workers` (not `hono/ws`)+- `onOpen` callback is **NOT supported** (Cloudflare limitation)+- CORS/header-modifying middleware conflicts with WebSocket routes+- Use route grouping to exclude WebSocket routes from CORS:++```typescript+const api = new Hono()+api.use('*', cors()) // CORS for API only+app.route('/api', api)+app.get('/ws', upgradeWebSocket(...)) // No CORS on WebSocket+```++#### Security Middleware++```typescript+import { Hono } from 'hono'+import { secureHeaders } from 'hono/secure-headers'+import { csrf } from 'hono/csrf'++const app = new Hono()++// Security headers (X-Frame-Options, CSP, HSTS, etc.)+app.use('*', secureHeaders({+ xFrameOptions: 'DENY',+ xXssProtection: '1; mode=block',+ contentSecurityPolicy: {+ defaultSrc: ["'self'"],+ scriptSrc: ["'self'", "'unsafe-inline'"],+ },+}))++// CSRF protection (validates Origin header)+app.use('/api/*', csrf({+ origin: ['https://example.com', 'https://admin.example.com'],+}))+```++**Security Middleware Options:**++| Middleware | Purpose |+|------------|---------|+| `secureHeaders` | X-Frame-Options, CSP, HSTS, XSS protection |+| `csrf` | CSRF via Origin/Sec-Fetch-Site validation |+| `bearerAuth` | Bearer token authentication |+| `basicAuth` | HTTP Basic authentication |+| `ipRestriction` | IP allowlist/blocklist |++#### Combine Middleware++Compose middleware with conditional logic:++```typescript+import { Hono } from 'hono'+import { some, every, except } from 'hono/combine'+import { bearerAuth } from 'hono/bearer-auth'+import { ipRestriction } from 'hono/ip-restriction'++const app = new Hono()++// some: ANY middleware must pass (OR logic)+app.use('/admin/*', some(+ bearerAuth({ token: 'admin-token' }),+ ipRestriction({ allowList: ['10.0.0.0/8'] }),+))++// every: ALL middleware must pass (AND logic)+app.use('/secure/*', every(+ bearerAuth({ token: 'secret' }),+ ipRestriction({ allowList: ['192.168.1.0/24'] }),+))++// except: Skip middleware for certain paths+app.use('*', except(+ ['/health', '/metrics'],+ logger(),+))+```+---### Part 3: Type-Safe Context Extensiondiff --git a/skills/openai-api/SKILL.md b/skills/openai-api/SKILL.mdindex e0ad20c5..4e5d8964 100644--- a/skills/openai-api/SKILL.md+++ b/skills/openai-api/SKILL.md@@ -1,16 +1,16 @@---name: openai-apidescription: |- Build with OpenAI's stateless APIs - Chat Completions (GPT-5, GPT-4o), Embeddings, Images (DALL-E 3), Audio (Whisper + TTS), and Moderation. Includes Node.js SDK and fetch-based approaches for Cloudflare Workers.+ Build with OpenAI's stateless APIs - Chat Completions (GPT-5.2, GPT-5.1, o3, o4-mini), Realtime API (voice), Batch API (50% savings), Embeddings, Images (DALL-E 3), Audio (Whisper + TTS), and Moderation. Node.js SDK and fetch for Cloudflare Workers.- Use when: implementing chat completions with GPT-5/GPT-4o, streaming responses with SSE, using function calling/tools, creating structured outputs with JSON schemas, generating embeddings for RAG (text-embedding-3-small/large), generating images with DALL-E 3, editing images with GPT-Image-1, transcribing audio with Whisper, synthesizing speech with TTS (11 voices), moderating content (11 safety categories), or troubleshooting rate limits (429), invalid API keys (401), function calling failures, streaming parse errors, embeddings dimension mismatches, or token limit exceeded.+ Use when: implementing chat with GPT-5.2/5.1/o3/o4-mini, Realtime voice API (WebSocket), Batch API for cost savings, xhigh reasoning (GPT-5.2), streaming responses, function calling/tools, structured outputs, embeddings for RAG, DALL-E 3 images, Whisper transcription, TTS (13 voices), or troubleshooting rate limits (429), API keys (401), streaming errors.---# OpenAI API - Complete Guide**Version**: Production Ready ✅-**Package**: [email protected]-**Last Updated**: 2025-11-26+**Package**: [email protected]+**Last Updated**: 2026-01-03---@@ -181,45 +181,68 @@ Three roles: **system** (behavior), **user** (input), **assistant** (model respo## GPT-5 Series Models-GPT-5 models (released August 2025) introduce reasoning and verbosity controls:+GPT-5 models (released August 2025) introduce reasoning and verbosity controls.++### GPT-5.2 (Released December 11, 2025)++**Latest flagship model**:+- **gpt-5.2**: 400k context window, 128k output tokens+- **xhigh reasoning_effort**: New level beyond "high" for complex problems+- **Compaction**: Extends context for long workflows (via API endpoint)+- **Pricing**: $1.75/$14 per million tokens (1.4x of GPT-5.1)++```typescript+// GPT-5.2 with maximum reasoning+const completion = await openai.chat.completions.create({+ model: 'gpt-5.2',+ messages: [{ role: 'user', content: 'Solve this extremely complex problem...' }],+ reasoning_effort: 'xhigh', // NEW: Beyond "high"+});+```### GPT-5.1 (Released November 13, 2025)-**Latest model with major improvements**:+**Warmer, more intelligent model**:- **gpt-5.1**: Adaptive reasoning that varies thinking time dynamically- **24-hour extended prompt caching**: Faster follow-up queries at lower cost- **New developer tools**: apply_patch (code editing), shell (command execution)-**BREAKING CHANGE**: GPT-5.1 defaults to `reasoning_effort: 'none'` (vs GPT-5 defaulting to `'medium'`). Update your code when migrating!+**BREAKING CHANGE**: GPT-5.1/5.2 default to `reasoning_effort: 'none'` (vs GPT-5 defaulting to `'medium'`).-### reasoning_effort Parameter+### O-Series Reasoning Models-Controls thinking depth (available on GPT-5 and GPT-5.1):-- **"none"**: No reasoning (fastest, lowest latency) - GPT-5.1 default-- **"minimal"**: Quick responses, minimal thinking-- **"low"**: Basic reasoning-- **"medium"**: Balanced reasoning - GPT-5 default-- **"high"**: Deep reasoning for complex problems+Dedicated reasoning models (separate from GPT-5):-```typescript-// GPT-5.1 with no reasoning (fast)-const completion = await openai.chat.completions.create({- model: 'gpt-5.1',- messages: [{ role: 'user', content: 'Simple query' }],- // reasoning_effort: 'none' is implicit default for GPT-5.1-});+| Model | Released | Purpose |+|-------|----------|---------|+| **o3** | Apr 16, 2025 | Successor to o1, advanced reasoning |+| **o3-pro** | Jun 10, 2025 | Extended compute version of o3 |+| **o3-mini** | Jan 31, 2025 | Smaller, faster o3 variant |+| **o4-mini** | Apr 16, 2025 | Fast, cost-efficient reasoning |-// GPT-5.1 with high reasoning (complex tasks)+```typescript+// O-series modelsconst completion = await openai.chat.completions.create({- model: 'gpt-5.1',- messages: [{ role: 'user', content: 'Solve this complex math problem...' }],- reasoning_effort: 'high',+ model: 'o3', // or 'o3-mini', 'o4-mini'+ messages: [{ role: 'user', content: 'Complex reasoning task...' }],});```+**Note**: O-series may be deprecated in favor of GPT-5 with `reasoning_effort` parameter.++### reasoning_effort Parameter++Controls thinking depth (GPT-5/5.1/5.2):+- **"none"**: No reasoning (fastest) - GPT-5.1/5.2 default+- **"minimal"**: Quick responses+- **"low"**: Basic reasoning+- **"medium"**: Balanced - GPT-5 default+- **"high"**: Deep reasoning+- **"xhigh"**: Maximum reasoning (GPT-5.2 only)+### verbosity Parameter-Controls output detail (GPT-5/GPT-5.1):+Controls output detail (GPT-5 series):- **"low"**: Concise- **"medium"**: Balanced (default)- **"high"**: Verbose@@ -711,6 +734,124 @@ const moderation = await openai.moderations.create({---+## Realtime API (Voice/Audio)++Low-latency voice and audio interactions via WebSocket/WebRTC. GA August 28, 2025.++### WebSocket Connection++```typescript+const ws = new WebSocket('wss://api.openai.com/v1/realtime', {+ headers: {+ Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,+ 'OpenAI-Beta': 'realtime=v1',+ },+});++ws.onopen = () => {+ ws.send(JSON.stringify({+ type: 'session.update',+ session: {+ voice: 'alloy', // or: echo, fable, onyx, nova, shimmer, marin, cedar+ instructions: 'You are a helpful assistant',+ input_audio_transcription: { model: 'whisper-1' },+ },+ }));+};++ws.onmessage = (event) => {+ const data = JSON.parse(event.data);+ switch (data.type) {+ case 'response.audio.delta':+ // Handle audio chunk (base64 encoded)+ playAudioChunk(data.delta);+ break;+ case 'response.text.delta':+ // Handle text transcript+ console.log(data.delta);+ break;+ }+};++// Send user audio+ws.send(JSON.stringify({+ type: 'input_audio_buffer.append',+ audio: base64AudioData,+}));+```++### Model++- **gpt-realtime**: Production model ($32/1M input, $64/1M output)+- **gpt-realtime-mini**: Smaller, faster variant++### Features++- Voice activity detection+- Interruption handling+- Function calling while speaking+- 13 voices (including new: marin, cedar)+- WebRTC, WebSocket, SIP connections++---++## Batch API (50% Cost Savings)++Process large volumes with 24-hour turnaround at 50% lower cost.++### Create Batch++```typescript+// 1. Create JSONL file with requests+const requests = [+ { custom_id: 'req-1', method: 'POST', url: '/v1/chat/completions',+ body: { model: 'gpt-5.1', messages: [{ role: 'user', content: 'Hello 1' }] } },+ { custom_id: 'req-2', method: 'POST', url: '/v1/chat/completions',+ body: { model: 'gpt-5.1', messages: [{ role: 'user', content: 'Hello 2' }] } },+];++// 2. Upload file+const file = await openai.files.create({+ file: new File([requests.map(r => JSON.stringify(r)).join('\n')], 'batch.jsonl'),+ purpose: 'batch',+});++// 3. Create batch+const batch = await openai.batches.create({+ input_file_id: file.id,+ endpoint: '/v1/chat/completions',+ completion_window: '24h',+});++console.log(batch.id); // batch_abc123+```++### Check Status++```typescript+const batch = await openai.batches.retrieve('batch_abc123');++console.log(batch.status); // validating, in_progress, completed, failed+console.log(batch.request_counts); // { total, completed, failed }++if (batch.status === 'completed') {+ const results = await openai.files.content(batch.output_file_id);+ // Parse JSONL results+}+```++### When to Use Batch API++| Use Case | Batch API? |+|----------|------------|+| Content moderation at scale | ✅ |+| Document processing (embeddings) | ✅ |+| Bulk summarization | ✅ |+| Real-time chat | ❌ Use Chat API |+| Streaming responses | ❌ Use Chat API |++---+## Error Handling & Rate Limits### Common Errorsdiff --git a/skills/tanstack-query/SKILL.md b/skills/tanstack-query/SKILL.mdindex 623c8d2b..49b1ce61 100644--- a/skills/tanstack-query/SKILL.md+++ b/skills/tanstack-query/SKILL.md@@ -1,19 +1,207 @@---name: tanstack-querydescription: |- Manage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery.+ Manage server state in React with TanStack Query v5. Covers useMutationState (cross-component mutations), simplified optimistic updates, throwOnError for error boundaries, network mode (offline/PWA), useQueries combine, infiniteQueryOptions, and maxPages for memory optimization.- Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.+ Use when: setting up data fetching, useMutationState, optimistic updates with variables, throwOnError error boundaries, offline/PWA network mode, or fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData).---# TanStack Query (React Query) v5-**Last Updated**: 2025-11-28+**Last Updated**: 2026-01-03**Versions**: @tanstack/[email protected], @tanstack/[email protected]**Requires**: React 18.0+ (useSyncExternalStore), TypeScript 4.7+ (recommended)---+## v5 New Features++### useMutationState - Cross-Component Mutation Tracking++Access mutation state from anywhere without prop drilling:++```tsx+import { useMutationState } from '@tanstack/react-query'++function GlobalLoadingIndicator() {+ // Get all pending mutations+ const pendingMutations = useMutationState({+ filters: { status: 'pending' },+ select: (mutation) => mutation.state.variables,+ })++ if (pendingMutations.length === 0) return null+ return <div>Saving {pendingMutations.length} items...</div>+}++// Filter by mutation key+const todoMutations = useMutationState({+ filters: { mutationKey: ['addTodo'] },+})+```++### Simplified Optimistic Updates++New pattern using `variables` - no cache manipulation, no rollback needed:++```tsx+function TodoList() {+ const { data: todos } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos })++ const addTodo = useMutation({+ mutationKey: ['addTodo'],+ mutationFn: (newTodo) => api.addTodo(newTodo),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['todos'] })+ },+ })++ // Show optimistic UI using variables from pending mutations+ const pendingTodos = useMutationState({+ filters: { mutationKey: ['addTodo'], status: 'pending' },+ select: (mutation) => mutation.state.variables,+ })++ return (+ <ul>+ {todos?.map(todo => <li key={todo.id}>{todo.title}</li>)}+ {/* Show pending items with visual indicator */}+ {pendingTodos.map((todo, i) => (+ <li key={`pending-${i}`} style={{ opacity: 0.5 }}>{todo.title}</li>+ ))}+ </ul>+ )+}+```++### throwOnError - Error Boundaries++Renamed from `useErrorBoundary` (breaking change):++```tsx+import { QueryErrorResetBoundary } from '@tanstack/react-query'+import { ErrorBoundary } from 'react-error-boundary'++function App() {+ return (+ <QueryErrorResetBoundary>+ {({ reset }) => (+ <ErrorBoundary onReset={reset} fallbackRender={({ resetErrorBoundary }) => (+ <div>+ Error! <button onClick={resetErrorBoundary}>Retry</button>+ </div>+ )}>+ <Todos />+ </ErrorBoundary>+ )}+ </QueryErrorResetBoundary>+ )+}++function Todos() {+ const { data } = useQuery({+ queryKey: ['todos'],+ queryFn: fetchTodos,+ throwOnError: true, // ✅ v5 (was useErrorBoundary in v4)+ })+ return <div>{data.map(...)}</div>+}+```++### Network Mode (Offline/PWA Support)++Control behavior when offline:++```tsx+const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ networkMode: 'offlineFirst', // Use cache when offline+ },+ },+})++// Per-query override+useQuery({+ queryKey: ['todos'],+ queryFn: fetchTodos,+ networkMode: 'always', // Always try, even offline (for local APIs)+})+```++| Mode | Behavior |+|------|----------|+| `online` (default) | Only fetch when online |+| `always` | Always try (useful for local/service worker APIs) |+| `offlineFirst` | Use cache first, fetch when online |++**Detecting paused state:**+```tsx+const { isPending, fetchStatus } = useQuery(...)+// isPending + fetchStatus === 'paused' = offline, waiting for network+```++### useQueries with Combine++Combine results from parallel queries:++```tsx+const results = useQueries({+ queries: userIds.map(id => ({+ queryKey: ['user', id],+ queryFn: () => fetchUser(id),+ })),+ combine: (results) => ({+ data: results.map(r => r.data),+ pending: results.some(r => r.isPending),+ error: results.find(r => r.error)?.error,+ }),+})++// Access combined result+if (results.pending) return <Loading />+console.log(results.data) // [user1, user2, user3]+```++### infiniteQueryOptions Helper++Type-safe factory for infinite queries (parallel to `queryOptions`):++```tsx+import { infiniteQueryOptions, useInfiniteQuery, prefetchInfiniteQuery } from '@tanstack/react-query'++const todosInfiniteOptions = infiniteQueryOptions({+ queryKey: ['todos', 'infinite'],+ queryFn: ({ pageParam }) => fetchTodosPage(pageParam),+ initialPageParam: 0,+ getNextPageParam: (lastPage) => lastPage.nextCursor,+})++// Reuse across hooks+useInfiniteQuery(todosInfiniteOptions)+useSuspenseInfiniteQuery(todosInfiniteOptions)+prefetchInfiniteQuery(queryClient, todosInfiniteOptions)+```++### maxPages - Memory Optimization++Limit pages stored in cache for infinite queries:++```tsx+useInfiniteQuery({+ queryKey: ['posts'],+ queryFn: ({ pageParam }) => fetchPosts(pageParam),+ initialPageParam: 0,+ getNextPageParam: (lastPage) => lastPage.nextCursor,+ getPreviousPageParam: (firstPage) => firstPage.prevCursor, // Required with maxPages+ maxPages: 3, // Only keep 3 pages in memory+})+```++**Note:** `maxPages` requires bi-directional pagination (`getNextPageParam` AND `getPreviousPageParam`).++---+## Quick Setup```bash