Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
feat(claude-agent-sdk): Major update to v3.0.0 with SDK 0.2.12
Jeremy Dawes2036bf02c561
diff --git a/skills/claude-agent-sdk/README.md b/skills/claude-agent-sdk/README.mdindex 6b7821ba..3f420998 100644--- a/skills/claude-agent-sdk/README.md+++ b/skills/claude-agent-sdk/README.md@@ -135,11 +135,16 @@ This skill automatically activates when you mention:## What This Skill Does- ✅ Complete Agent SDK API reference (query, tools, MCP, subagents)+- ✅ V2 Session APIs (preview) for simpler multi-turn conversations+- ✅ Sandbox Settings for secure bash execution+- ✅ File Checkpointing for rollback capability- ✅ Tool integration patterns (built-in tools + custom MCP servers)-- ✅ Subagent orchestration (specialized agents working together)+- ✅ Subagent orchestration with skills and maxTurns support (v0.2.10+)- ✅ Session management (start, resume, fork sessions)- ✅ Permission control (fine-grained safety controls)- ✅ Filesystem settings (user, project, local configurations)+- ✅ Query object methods (setModel, supportedCommands, etc.)+- ✅ Complete hooks system (all 12 hook events)- ✅ Streaming message handling (all message types)- ✅ Error handling and recovery patterns- ✅ 11 production-ready TypeScript templates@@ -427,13 +432,14 @@ See: `templates/session-management.ts`## Package Versions-**Last Verified**: 2025-10-25+**Last Verified**: 2026-01-20```json{"dependencies": {- "@anthropic-ai/claude-agent-sdk": "^0.1.0",- "zod": "^3.23.0"+ "@anthropic-ai/claude-agent-sdk": "^0.2.12",+ "zod": "^3.24.0 || ^4.0.0",+ "zod-to-json-schema": "^3.24.0"},"devDependencies": {"@types/node": "^20.0.0",@@ -446,11 +452,12 @@ See: `templates/session-management.ts`## Official Documentation-- **Agent SDK Overview**: https://docs.claude.com/en/api/agent-sdk/overview-- **TypeScript API**: https://docs.claude.com/en/api/agent-sdk/typescript-- **Python API**: https://docs.claude.com/en/api/agent-sdk/python+- **Agent SDK Overview**: https://platform.claude.com/docs/en/api/agent-sdk/overview+- **TypeScript API**: https://platform.claude.com/docs/en/api/agent-sdk/typescript+- **TypeScript V2 Preview**: https://platform.claude.com/docs/en/agent-sdk/typescript-v2-preview+- **Structured Outputs**: https://platform.claude.com/docs/en/agent-sdk/structured-outputs- **GitHub**: https://github.com/anthropics/claude-agent-sdk-typescript-- **Context7**: /anthropics/claude-agent-sdk-typescript+- **CHANGELOG**: https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md---diff --git a/skills/claude-agent-sdk/SKILL.md b/skills/claude-agent-sdk/SKILL.mdindex 3b55ad40..01ff9199 100644--- a/skills/claude-agent-sdk/SKILL.md+++ b/skills/claude-agent-sdk/SKILL.md@@ -9,7 +9,7 @@ user-invocable: true# Claude Agent SDK - Structured Outputs & Error Prevention Guide-**Package**: @anthropic-ai/[email protected]+**Package**: @anthropic-ai/[email protected]**Breaking Changes**: v0.1.45 - Structured outputs (Nov 2025), v0.1.0 - No default system prompt, settingSources required---@@ -29,6 +29,7 @@ user-invocable: true```typescriptimport { query } from "@anthropic-ai/claude-agent-sdk";import { z } from "zod";+import { zodToJsonSchema } from "zod-to-json-schema";const schema = z.object({summary: z.string(),@@ -60,13 +61,48 @@ for await (const message of response) {}```+**Zod Compatibility (v0.1.71+):** SDK supports both Zod v3.24.1+ and Zod v4.0.0+ as peer dependencies. Import remains `import { z } from "zod"` for either version.+### 2. Plugins System (v0.1.27)- **`plugins` array** - Load local plugin paths- **Custom plugin support** - Extend agent capabilities### 3. Hooks System (v0.1.0+)-- **Event-driven callbacks** - PreToolUse, PostToolUse, Notification, UserPromptSubmit-- **Session event hooks** - Monitor and control agent behavior++**All 12 Hook Events:**++| Hook | When Fired | Use Case |+|------|------------|----------|+| `PreToolUse` | Before tool execution | Validate, modify, or block tool calls |+| `PostToolUse` | After tool execution | Log results, trigger side effects |+| `Notification` | Agent notifications | Display status updates |+| `UserPromptSubmit` | User prompt received | Pre-process or validate input |+| `SubagentStart` | Subagent spawned | Track delegation, log context |+| `SubagentStop` | Subagent completed | Aggregate results, cleanup |+| `PreCompact` | Before context compaction | Save state before truncation |+| `PermissionRequest` | Permission needed | Custom approval workflows |+| `Stop` | Agent stopping | Cleanup, final logging |+| `SessionStart` | Session begins | Initialize state |+| `SessionEnd` | Session ends | Persist state, cleanup |+| `Error` | Error occurred | Custom error handling |++**Hook Configuration:**+```typescript+const response = query({+ prompt: "...",+ options: {+ hooks: {+ PreToolUse: async (input) => {+ console.log(`Tool: ${input.toolName}`);+ return { allow: true }; // or { allow: false, message: "..." }+ },+ PostToolUse: async (input) => {+ await logToolUsage(input.toolName, input.result);+ }+ }+ }+});+```### 4. Additional Options- **`fallbackModel`** - Automatic model fallback on failures@@ -89,10 +125,13 @@ for await (const message of response) {4. [Subagent Orchestration](#subagent-orchestration)5. [Session Management](#session-management)6. [Permission Control](#permission-control)-7. [Filesystem Settings](#filesystem-settings)-8. [Message Types & Streaming](#message-types--streaming)-9. [Error Handling](#error-handling)-10. [Known Issues](#known-issues-prevention)+7. [Sandbox Settings](#sandbox-settings-security-critical)+8. [File Checkpointing](#file-checkpointing)+9. [Filesystem Settings](#filesystem-settings)+10. [Query Object Methods](#query-object-methods)+11. [Message Types & Streaming](#message-types--streaming)+12. [Error Handling](#error-handling)+13. [Known Issues](#known-issues-prevention)---@@ -111,6 +150,42 @@ query(prompt: string | AsyncIterable<SDKUserMessage>, options?: Options)- `agents` - Programmatic subagent definitions- `mcpServers` - MCP server configuration- `permissionMode` - 'default'|'acceptEdits'|'bypassPermissions'|'plan'+- `betas` - Enable beta features (e.g., 1M context window)+- `sandbox` - Sandbox settings for secure execution+- `enableFileCheckpointing` - Enable file state snapshots+- `systemPrompt` - System prompt (string or preset object)++### Extended Context (1M Tokens)++Enable 1 million token context window:++```typescript+const response = query({+ prompt: "Analyze this large codebase",+ options: {+ betas: ['context-1m-2025-08-07'], // Enable 1M context+ model: "claude-sonnet-4-5"+ }+});+```++### System Prompt Configuration++Two forms of systemPrompt:++```typescript+// 1. Simple string+systemPrompt: "You are a helpful coding assistant."++// 2. Preset with optional append (preserves Claude Code defaults)+systemPrompt: {+ type: 'preset',+ preset: 'claude_code',+ append: "\n\nAdditional context: Focus on security."+}+```++**Use preset form** when you want Claude Code's default behaviors plus custom additions.---@@ -121,7 +196,45 @@ query(prompt: string | AsyncIterable<SDKUserMessage>, options?: Options)- `disallowedTools` - Blacklist- `canUseTool` - Custom permission callback (see Permission Control section)-**Built-in Tools:** Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch, Task, NotebookEdit, BashOutput, KillBash, ListMcpResources, ReadMcpResource+**Built-in Tools:** Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch, Task, NotebookEdit, BashOutput, KillBash, ListMcpResources, ReadMcpResource, AskUserQuestion++### AskUserQuestion Tool (v0.1.71+)++Enable user interaction during agent execution:++```typescript+const response = query({+ prompt: "Review and refactor the codebase",+ options: {+ allowedTools: ["Read", "Write", "Edit", "AskUserQuestion"]+ }+});++// Agent can now ask clarifying questions+// Questions appear in message stream as tool_call with name "AskUserQuestion"+```++**Use cases:**+- Clarify ambiguous requirements mid-task+- Get user approval before destructive operations+- Present options and get selection++### Tools Configuration (v0.1.57+)++**Three forms of tool configuration:**++```typescript+// 1. Exact allowlist (string array)+tools: ["Read", "Write", "Grep"]++// 2. Disable all tools (empty array)+tools: []++// 3. Preset with defaults (object form)+tools: { type: 'preset', preset: 'claude_code' }+```++**Note:** `allowedTools` and `disallowedTools` still work but `tools` provides more flexibility.---@@ -218,6 +331,8 @@ type AgentDefinition = {prompt: string; // System prompt for agenttools?: string[]; // Allowed tools (optional)model?: 'sonnet' | 'opus' | 'haiku' | 'inherit'; // Model (optional)+ skills?: string[]; // Skills to load (v0.2.10+)+ maxTurns?: number; // Maximum turns before stopping (v0.2.10+)}```@@ -227,6 +342,8 @@ type AgentDefinition = {- **prompt**: System prompt (defines role, inherits main context)- **tools**: Allowed tools (if omitted, inherits from main agent)- **model**: Model override (`haiku`/`sonnet`/`opus`/`inherit`)+- **skills**: Skills to load for agent (v0.2.10+)+- **maxTurns**: Limit agent to N turns before returning control (v0.2.10+)**Usage:**```typescript@@ -235,7 +352,9 @@ agents: {description: "Security audits and vulnerability scanning",prompt: "You check security. Scan for secrets, verify OWASP compliance.",tools: ["Read", "Grep", "Bash"],- model: "sonnet"+ model: "sonnet",+ skills: ["security-best-practices"], // Load specific skills+ maxTurns: 10 // Limit to 10 turns}}```@@ -271,6 +390,42 @@ for await (const message of response) {}```+### V2 Session APIs (Preview - v0.1.54+)++**Simpler multi-turn conversation pattern:**++```typescript+import {+ unstable_v2_createSession,+ unstable_v2_resumeSession,+ unstable_v2_prompt+} from "@anthropic-ai/claude-agent-sdk";++// Create a new session+const session = await unstable_v2_createSession({+ model: "claude-sonnet-4-5",+ workingDirectory: process.cwd(),+ allowedTools: ["Read", "Grep", "Glob"]+});++// Send prompts and stream responses+const stream = unstable_v2_prompt(session, "Analyze the codebase structure");+for await (const message of stream) {+ console.log(message);+}++// Continue conversation in same session+const stream2 = unstable_v2_prompt(session, "Now suggest improvements");+for await (const message of stream2) {+ console.log(message);+}++// Resume a previous session+const resumedSession = await unstable_v2_resumeSession(session.sessionId);+```++**Note:** V2 APIs are in preview (`unstable_` prefix). The `.receive()` method was renamed to `.stream()` in v0.1.72.+---## Permission Control@@ -372,6 +527,84 @@ canUseTool: async (toolName, input) => {---+## Sandbox Settings (Security-Critical)++**Enable sandboxed execution for Bash commands:**++```typescript+const response = query({+ prompt: "Run system diagnostics",+ options: {+ sandbox: {+ enabled: true,+ autoAllowBashIfSandboxed: true, // Auto-approve bash in sandbox+ excludedCommands: ["rm", "dd", "mkfs"], // Never auto-approve these+ allowUnsandboxedCommands: false // Deny unsandboxable commands+ }+ }+});+```++### SandboxSettings Type++```typescript+type SandboxSettings = {+ enabled: boolean;+ autoAllowBashIfSandboxed?: boolean; // Default: false+ excludedCommands?: string[];+ allowUnsandboxedCommands?: boolean; // Default: false+ network?: NetworkSandboxSettings;+ ignoreViolations?: SandboxIgnoreViolations;+};++type NetworkSandboxSettings = {+ enabled: boolean;+ proxyUrl?: string; // HTTP proxy for network requests+};+```++**Key Options:**+- `enabled` - Activate sandbox isolation+- `autoAllowBashIfSandboxed` - Skip permission prompts for safe bash commands+- `excludedCommands` - Commands that always require permission+- `allowUnsandboxedCommands` - Allow commands that can't be sandboxed (risky)+- `network.proxyUrl` - Route network through proxy for monitoring++**Best Practice:** Always use sandbox in production agents handling untrusted input.++---++## File Checkpointing++**Enable file state snapshots for rollback capability:**++```typescript+const response = query({+ prompt: "Refactor the authentication module",+ options: {+ enableFileCheckpointing: true // Enable file snapshots+ }+});++// Later: rewind file changes to a specific point+for await (const message of response) {+ if (message.type === 'user' && message.uuid) {+ // Can rewind to this point later+ const userMessageUuid = message.uuid;++ // To rewind (call on Query object)+ await response.rewindFiles(userMessageUuid);+ }+}+```++**Use cases:**+- Undo failed refactoring attempts+- A/B test code changes+- Safe exploration of alternatives++---+## Filesystem Settings**Setting Sources:**@@ -422,6 +655,40 @@ const response = query({---+## Query Object Methods++The `query()` function returns a `Query` object with these methods:++```typescript+const q = query({ prompt: "..." });++// Async iteration (primary usage)+for await (const message of q) { ... }++// Runtime model control+await q.setModel("claude-opus-4-5"); // Change model mid-session+await q.setMaxThinkingTokens(4096); // Set thinking budget++// Introspection+const models = await q.supportedModels(); // List available models+const commands = await q.supportedCommands(); // List available commands+const account = await q.accountInfo(); // Get account details++// MCP status+const status = await q.mcpServerStatus(); // Check MCP server status+// Returns: { [serverName]: { status: 'connected' | 'failed', error?: string } }++// File operations (requires enableFileCheckpointing)+await q.rewindFiles(userMessageUuid); // Rewind to checkpoint+```++**Use cases:**+- Dynamic model switching based on task complexity+- Monitoring MCP server health+- Adjusting thinking budget for reasoning tasks++---+## Message Types & Streaming**Message Types:**@@ -553,13 +820,13 @@ This skill prevents **12** documented issues:---**Token Efficiency**:-- **Without skill**: ~12,000 tokens (MCP setup, permission patterns, session forking, structured outputs, error handling)-- **With skill**: ~3,600 tokens (focused on v0.1.45+ features + error prevention + advanced patterns)-- **Savings**: ~70% (~8,400 tokens)+- **Without skill**: ~15,000 tokens (MCP setup, permission patterns, session APIs, sandbox config, hooks, structured outputs, error handling)+- **With skill**: ~4,500 tokens (comprehensive v0.2.12 coverage + error prevention + advanced patterns)+- **Savings**: ~70% (~10,500 tokens)**Errors prevented**: 12 documented issues with exact solutions-**Key value**: Structured outputs (v0.1.45+), session forking, canUseTool patterns, settingSources priority, MCP naming, error codes+**Key value**: V2 Session APIs, Sandbox Settings, File Checkpointing, Query methods, AskUserQuestion tool, structured outputs (v0.1.45+), session forking, canUseTool patterns, complete hooks system (12 events), Zod v4 support----**Last verified**: 2026-01-09 | **Skill version**: 2.0.1 | **Changes**: Updated SDK version to 0.2.1+**Last verified**: 2026-01-20 | **Skill version**: 3.0.0 | **Changes**: Updated SDK to 0.2.12, added V2 Session APIs, Sandbox Settings, File Checkpointing, Query methods, AskUserQuestion tool, tools preset config, betas option, systemPrompt preset, complete hooks system (12 events), Zod v4 supportdiff --git a/skills/claude-agent-sdk/templates/package.json b/skills/claude-agent-sdk/templates/package.jsonindex 9945c620..fa45f047 100644--- a/skills/claude-agent-sdk/templates/package.json+++ b/skills/claude-agent-sdk/templates/package.json@@ -15,8 +15,9 @@"workflow": "tsx templates/multi-agent-workflow.ts"},"dependencies": {- "@anthropic-ai/claude-agent-sdk": "^0.1.0",- "zod": "^3.23.0"+ "@anthropic-ai/claude-agent-sdk": "^0.2.12",+ "zod": "^3.24.0 || ^4.0.0",+ "zod-to-json-schema": "^3.24.0"},"devDependencies": {"@types/node": "^20.0.0",